diff --git a/.env.example b/.env.example index d9313fb..624153c 100644 --- a/.env.example +++ b/.env.example @@ -11,3 +11,7 @@ AZURE_CUSTOM_DOMAIN_VALIDATION_METHOD=CNAME # MockAPI Dashboard credentials. Leave blank if keeping it publicly accessible AZURE_DASHBOARD_USERNAME= AZURE_DASHBOARD_PASSWORD= + +# Optional initial X-MockAPI-Key: 32-256 ASCII letters, digits, hyphens, or underscores. +# Existing persisted security settings take precedence. +AZURE_MOCKAPI_KEY= diff --git a/.github/agents/refactoring.agent.md b/.github/agents/refactoring.agent.md index 0868467..79ea510 100644 --- a/.github/agents/refactoring.agent.md +++ b/.github/agents/refactoring.agent.md @@ -37,7 +37,7 @@ Only recommend work supported by concrete evidence such as: - missing or ambiguous public contract metadata that prevents generated documentation, static tooling, or focused contract tests from describing supported behavior; - measured startup, throughput, memory, image-size, or interaction latency regressions. -Do not treat line count, small bounded `O(n)` loops, ordinary collection allocation, or stylistic preference as sufficient evidence. MockAPI supports at most 25 endpoint definitions, so optimize endpoint scans only when large payloads, repeated passes, duplicated policy, or measurements justify the change. Do not introduce pooling, caching, indexing, frameworks, or dependencies without demonstrating a net benefit under repository limits. +Do not treat line count, small bounded `O(n)` loops, ordinary collection allocation, or stylistic preference as sufficient evidence. MockAPI has no endpoint-count cap, but configurations remain bounded by the 4 MiB UTF-8 document-size limit. Evaluate endpoint scans with representative large configurations and optimize only when repeated passes, duplicated policy, or measurements justify the change. Do not introduce pooling, caching, indexing, frameworks, or dependencies without demonstrating a net benefit under repository limits. ## Invariants diff --git a/.github/instructions/configuration.instructions.md b/.github/instructions/configuration.instructions.md index 73dbbc2..423bf25 100644 --- a/.github/instructions/configuration.instructions.md +++ b/.github/instructions/configuration.instructions.md @@ -10,6 +10,9 @@ applyTo: "{config,schemas}/**/*.json" - Reject unknown properties unless a versioned compatibility decision deliberately permits them. - Keep endpoint IDs stable UUIDs and method arrays non-empty and unique. - Keep endpoint descriptions optional freeform text bounded to 4,000 characters and preserve their whitespace through round trips. +- For Trailhead sample endpoints, use two labeled plain-text sections in the existing `description`: + `Description:` first and `Technical implementation:` second, separated by a blank line. + Explain the business scenario before the mock's HTTP behavior and limitations; do not require this format for custom endpoints. - Keep optional `apiDescriptions` keyed by case-sensitive first-segment paths, independent of endpoint membership. Bound metadata to 25 groups and 4,000 characters per description; preserve whitespace and ordinal key ordering. Endpoint deletion never removes metadata. Built-in merges add missing descriptions atomically but preserve @@ -22,12 +25,23 @@ applyTo: "{config,schemas}/**/*.json" - Keep rolling-window rate limits optional, restricted to terminal `429` responses, and configured with a `2xx` pre-limit response. - Reject control characters and server-controlled or hop-by-hop headers. - Keep response bodies as raw strings; do not normalize JSON-shaped payload text. -- Apply practical, tested limits to documents, endpoints, methods, headers, and bodies. +- Apply practical, tested size limits to documents and endpoint fields, methods, headers, and bodies. + Do not impose an endpoint-count limit on configuration documents, merges, or bulk selections. - Keep schema validation and semantic validation distinct. The semantic layer owns cross-record method/path conflicts and reserved-route checks. - Keep serialization deterministic and verify generated configuration against the checked-in schema. -- Keep the built-in example document as a checked-in, schema-valid embedded resource. Expose it read-only and activate it only through the normal validated, ETag-protected merge path. -- Keep the built-in example cohesive under `/ctp` (Contoso Theme Parks), with fictional park, attraction, - reservation, and wait-time fixtures and clearly labeled `/ctp/demo-faults/` routes. Explain static behavior - and make advertised links resolvable. Preserve the original seven example IDs when changing their routes - so previously loaded examples require the normal reviewed conflict/force merge instead of duplication. +- Copy all three Trailhead sample files (AOAI, inventory, and shipping) into the container build stage + and embed them unchanged in the application. Keep development-container path filters and packaging + tests aligned with the sample catalog. Embedding a sample must not activate it or seed persisted data. +- Compose the built-in example from all three checked-in, schema-valid `trailhead-aoai.json`, + `trailhead-inventory.json`, and `trailhead-shipping.json` embedded resources (41 endpoints). + Keep those files as the single source of definitions. + Expose the combined example read-only and activate it only through the validated, ETag-protected merge path. +- Keep the Trailhead Supply examples cohesive under `/aoai`, `/inventory`, and `/shipping`, with assistant, stock, reservation, + shipment, tracking, and clearly labeled demo-faults fixtures. Explain static behavior, preserve stable IDs, + and reserve sample HEAD support for one HEAD-only `//health` endpoint per API, returning an empty 200. + Inspection endpoints use GET only; sample health routes retain mock API-key protection + and do not replace the public application health probes. + Make advertised links resolvable. Never automatically delete or rewrite existing saved endpoints. + Apply the document-size limit and all semantic validation to the complete merge, including unrelated endpoints. + Keep the independent API-description limit at 25 groups. - Any contract change must update the schema, models, source-generated JSON metadata, examples, management API/dashboard behavior, documentation, and tests together. Use the `mock-endpoint-change` skill. diff --git a/.github/instructions/dotnet.instructions.md b/.github/instructions/dotnet.instructions.md index 260a681..d5b827e 100644 --- a/.github/instructions/dotnet.instructions.md +++ b/.github/instructions/dotnet.instructions.md @@ -26,6 +26,10 @@ applyTo: "**/*.{cs,csproj,sln,props,targets}" Apply configured administrator credentials to Security Settings, but permit setup when administration is anonymous. Keep security persistence separate from endpoint configuration, activate only after a successful save, and require the independent current strong security ETag for writes. Never export a key or its hash. +- Accept an optional deployment key through `MockApi__ApiKey` (32-256 ASCII letters, digits, hyphens, or + underscores). Seed only a missing security document, persist its SHA-256 hash before activation, and enable + protection. Existing settings, rotations, and explicit opt-outs take precedence over the deployment value. + Invalid keys, unreadable settings, or failed persistence fail startup without exposing secrets. - Use cancellation tokens for asynchronous I/O and propagate them through application boundaries. - Use UTC timestamps through `TimeProvider` where behavior depends on time. - Use source-generated `System.Text.Json` contexts for application-owned request, response, and persistence types. diff --git a/.github/instructions/frontend.instructions.md b/.github/instructions/frontend.instructions.md index ccfff08..188ff7c 100644 --- a/.github/instructions/frontend.instructions.md +++ b/.github/instructions/frontend.instructions.md @@ -11,6 +11,11 @@ applyTo: "src/MockAPI/wwwroot/**/*.{js,html,css},tests/{frontend,browser}/**/*.j - Keep endpoint table selection/filter/group-local sort state in `dashboard-endpoint-table.js`, draft and captured-revision state in `dashboard-editor-dialog.js`, test-request batches and focus restoration in `dashboard-test-blade.js`, and statistics/request-log scope and rendering in `dashboard-statistics.js`. Keep management commands and confirmations in the entrypoint. - Show all filtered endpoints without pagination in a vertically scrollable table with sticky headers. Keep API groups alphabetical regardless of operation sort; default operations to ascending path order. + Provide a page-local collapse/expand-all group control for the current filtered result. Preserve + hidden groups' state and endpoint selection, keep individual toggles, and start new groups expanded. + Disable the bulk group control when no groups match; mixed state offers collapse-all. + Keep per-API selection checkboxes scoped to filtered endpoints, including collapsed groups; show + partial selection and synchronize with row and table-wide selection without clearing hidden selections. Display group-relative paths before the information button and operation name; retain complete paths for configuration, filtering, and requests. - Keep API description drafts and captured revisions in `dashboard-api-description.js`; the endpoint table owns @@ -18,7 +23,11 @@ applyTo: "src/MockAPI/wwwroot/**/*.{js,html,css},tests/{frontend,browser}/**/*.j information-button/popover styles for endpoint descriptions and test-blade help, with hover/focus previews and caller-owned Escape dismissal and close cleanup. Close previews when the pointer leaves the information button, including when it moves onto the preview. + Keep the shared CSS and placement height caps aligned at 400px and 60% of the viewport, further + bounded by available space above or below the trigger. Preserve description casing and whitespace; use text nodes, never evaluate or inject configured content as HTML. + Render standalone `Description:` and `Technical implementation:` lines as bold text in information previews, + without interpreting other text as HTML or Markdown. Endpoint information buttons open the existing endpoint editor. Group identity remains the case-sensitive first path segment, and live updates must not replace an open draft's revision. - Keep security Settings and the memory-only mock key in `dashboard-api-security.js`; rely on the management @@ -27,7 +36,8 @@ applyTo: "src/MockAPI/wwwroot/**/*.{js,html,css},tests/{frontend,browser}/**/*.j failed status checks show unknown protection rather than assuming protection is off. Never persist that key in browser storage or attach it to management calls, exports, or redirect targets. Exported requests reference caller-supplied variables; endpoint tests attach the key only after same-origin validation. -- Prefill editable illustrative JSON bodies and JSON request content types for POST, PUT, and PATCH in the test blade; use a reservation-specific sample for the built-in reservation routes. Samples are not schemas and do not imply business-field validation. Preserve deliberate edits and cleared fields across method changes. Never block malformed or missing bodies locally: display the backend's actual validation response. Keep request samples transient, not in endpoint configuration or browser storage. + Accept both generated and deployment-supplied keys: 32-256 ASCII letters, digits, hyphens, or underscores. +- Prefill editable illustrative JSON bodies and JSON request content types for POST, PUT, and PATCH in the test blade; use Trailhead inventory reservation and shipping samples for their respective built-in routes, aligned with portable exports. Samples are not schemas and do not imply business-field validation. Preserve deliberate edits and cleared fields across method changes. Never block malformed or missing bodies locally: display the backend's actual validation response. Keep request samples transient, not in endpoint configuration or browser storage. - Give feature controllers explicit inputs, callbacks, and disposal. Use `dashboard-dom.js` event scopes for controller-owned listeners and separate scopes for replaceable rows/charts; delegate header-row removal rather than retaining removed rows. Invalidate asynchronous completions when an editor or blade closes, reopens, or is disposed. - Prefer descriptive state and handler names, early returns, and named intermediate values. Avoid nested ternaries, implicit coercion tricks, dense expression chains, and large anonymous callbacks when explicit steps make the behavior easier to teach and review. - Keep event, timer, request, and subscription lifecycles visible. Co-locate setup with cleanup where practical, and explain ordering or stale-update protections when they are not apparent from the control flow. diff --git a/.github/skills/mock-endpoint-change/SKILL.md b/.github/skills/mock-endpoint-change/SKILL.md index c4fdd73..f6315e7 100644 --- a/.github/skills/mock-endpoint-change/SKILL.md +++ b/.github/skills/mock-endpoint-change/SKILL.md @@ -31,8 +31,12 @@ Use this skill when a change affects what an endpoint definition means or how it ## Required Evidence - Checked-in examples validate against the schema. -- The `/ctp` Contoso Theme Parks examples retain stable IDs, resolve advertised lookup and redirect - links, document static reservation behavior, and migrate older examples only after explicit conflict review. +- The Trailhead Supply AOAI, inventory, and shipping examples retain stable IDs, resolve advertised resource + links, and document static business behavior. Their combined built-in example preserves unrelated + endpoints and metadata, includes all 41 sample endpoints without an endpoint-count cap, enforces document-size limits atomically, + and changes conflicts only after explicit review. +- Each sample API has one HEAD-only `//health` mock returning an empty 200; inspection calls are GET-only. + Sample health mocks retain instance API-key protection and are separate from public application health probes. - Application-generated configuration validates against the schema and round-trips deterministically. - Semantic conflicts produce actionable errors and leave the active snapshot unchanged. - A runtime-created or edited endpoint is invocable immediately without process restart. diff --git a/.github/workflows/devcontainer.yml b/.github/workflows/devcontainer.yml index ecb5c39..daf2133 100644 --- a/.github/workflows/devcontainer.yml +++ b/.github/workflows/devcontainer.yml @@ -15,7 +15,9 @@ on: - "MockAPI.slnx" - "src/**" - "tests/MockAPI.Tests/**" - - "config/mockapi.json" + - "config/trailhead-aoai.json" + - "config/trailhead-inventory.json" + - "config/trailhead-shipping.json" - "scripts/install-git-hooks.cjs" - "scripts/lib/pnpm-lock-registry.cjs" - "start.sh" @@ -51,7 +53,7 @@ jobs: docker exec --user vscode mockapi-devcontainer bash .devcontainer/setup.sh docker exec --user vscode mockapi-devcontainer bash -lc 'node --version; pnpm --version; pwsh --version; dotnet --version' docker exec --detach --user vscode mockapi-devcontainer bash -lc './start.sh --action run > /tmp/mockapi.log 2>&1' - curl --retry 60 --retry-connrefused --retry-delay 1 --fail http://127.0.0.1:5080/health/ready + curl --retry 60 --retry-all-errors --retry-delay 1 --retry-max-time 120 --max-time 5 --fail http://127.0.0.1:5080/health/ready curl --fail http://127.0.0.1:5080/__mockapi/ > /dev/null - name: Capture startup diagnostics if: failure() diff --git a/Dockerfile b/Dockerfile index 145b08d..33a2669 100644 --- a/Dockerfile +++ b/Dockerfile @@ -14,7 +14,7 @@ COPY src/MockAPI/MockAPI.csproj src/MockAPI/ RUN dotnet restore src/MockAPI/MockAPI.csproj --source "$NUGET_SOURCE" -p:PublishAot=true COPY src/MockAPI/ src/MockAPI/ -COPY config/mockapi.json config/ +COPY config/trailhead-aoai.json config/trailhead-inventory.json config/trailhead-shipping.json config/ RUN dotnet publish src/MockAPI/MockAPI.csproj --configuration Release --no-restore --output /app/publish -p:PublishAot=true -p:TreatWarningsAsErrors=true # --------------------------------------------------------------------- diff --git a/README.md b/README.md index 759a042..cfc8e99 100644 --- a/README.md +++ b/README.md @@ -47,9 +47,8 @@ Local runs default to `http://localhost:5080`. Set `ASPNETCORE_URLS` only to ove 1. Open **[the dashboard](http://localhost:5080/__mockapi/)** and select **Load examples**. 2. Configure [dashboard administrator credentials](docs/OPERATIONS.md#mock-api-keys), then open **Settings > Mock API security** and generate a key. Mock calls fail with `401` until a key is generated. -3. Select **Test** on `/ctp/parks`. CTP stands for **Contoso Theme Parks**; the examples follow a - fictional park visit, from discovering attractions to reserving a ride. Dashboard tests use the - generated key automatically. +3. Select **Test** on `/inventory/items`. The **Trailhead Supply** examples cover stock, reservations, + shipping quotes, and shipment tracking. Dashboard tests use the generated key automatically. External callers must send it in `X-MockAPI-Key`; opening a mock URL without that header returns `401`. 4. Edit its response in the dashboard and repeat the test. No restart needed. 5. Changes are saved automatically to your [writable file or volume](#22-run-directly-with-net). Use **Retry save** if saving fails. @@ -67,7 +66,7 @@ Keep administrative access on localhost or a protected network unless you config > MockAPI is pre-1.0. The published `v1.0.0-alpha.1` image is an older preview, not the current beta source. > Use the source quick start for current features. A version in the project does not mean that image has been published. -![Annotated MockAPI dashboard showing nine Contoso Theme Parks endpoints under /ctp, configuration commands, live request metrics, the last-60-minutes activity graph, and recent request outcomes.](docs/images/01-dashboard-overview.png) +![MockAPI dashboard showing Trailhead Supply inventory and shipping examples, configuration commands, live request metrics, the last-60-minutes activity graph, and recent request outcomes.](docs/images/01-dashboard-overview.png) The browser dashboard is the operations console: load or import a configuration, watch live request metrics, and manage every mock endpoint in one place. @@ -123,7 +122,7 @@ MockAPI replaces that dependency with a small HTTP server whose behavior is conf > [!NOTE] > The team can keep moving before a dependency is ready, replay the same scenario on demand, and safely exercise failures that would be impractical to trigger against a real service. -![Annotated request lifecycle panel describing how MockAPI defines a response, matches each request by method and normalized path, responds and records statistics, activates valid edits atomically without a restart, and persists saved changes to disk.](docs/images/06-how-it-works.png) +![Request lifecycle panel describing how MockAPI defines a response, matches each request by method and normalized path, responds and records statistics, activates valid edits atomically without a restart, and persists saved changes.](docs/images/06-how-it-works.png) Every request follows the same lifecycle: define a response, match it by method and exact path, then respond and record process-local statistics. Valid edits activate atomically with no restart. @@ -184,11 +183,11 @@ MockAPI is intentionally narrower than a general-purpose API virtualization plat credentials protect security Settings, while anonymous local administration can perform initial setup. - **Hardened portable runtime:** Run as a trimmed, non-root Linux container on `amd64` and `arm64`, including with a read-only root filesystem. -![Annotated endpoint registry table listing the example endpoints with their methods, exact paths, configured responses, request counts, last-request times, and enabled state, plus per-row test, edit, duplicate, and delete actions.](docs/images/02-endpoints.png) +![Endpoint registry table listing Trailhead Supply examples with their methods, group-relative paths, configured responses, attempt counts, and enabled state, plus per-row test, edit, duplicate, and delete actions.](docs/images/02-endpoints.png) -The endpoint registry lists every mock with its method, exact path, configured response, and live request count, and offers per-row test, edit, duplicate, and delete actions. +The endpoint registry lists every mock with its method, exact path, configured response, and live request count, and offers per-row test, edit, duplicate, and delete actions. Use the checkbox beside an API heading to select or clear all of that API's endpoints matching the current filters, even while its group is collapsed. Partial selections show a mixed checkbox state; selections in other APIs and endpoints hidden by filters are preserved. Selected endpoints can be enabled, disabled, or deleted together. -![Annotated per-endpoint statistics table showing request counts, request rate per minute, last observed status, total response bytes, and a plain-language explanation of each configured response.](docs/images/05-statistics.png) +![Per-endpoint statistics table showing request counts, request rate per minute, last observed status, total response bytes, and a plain-language explanation of each configured response.](docs/images/05-statistics.png) Process-local statistics report aggregate and per-endpoint activity — request counts, rate, last status, and response bytes — with a plain-language note explaining each configured response. The dashboard also shows the 100 most recent request outcomes newest first. It retains only timestamp, method, normalized path, endpoint identity, outcome, status, and response byte count; never request or response content, headers, cookies, or query values. @@ -268,7 +267,7 @@ Use this path for the shortest local development loop. Start MockAPI in one term # Terminal 2: verify readiness, then call the first mock endpoint Invoke-WebRequest http://localhost:5080/health/ready -Invoke-RestMethod http://localhost:5080/ctp/parks -Headers @{ 'X-MockAPI-Key' = $env:MOCKAPI_KEY } +Invoke-RestMethod http://localhost:5080/inventory/items -Headers @{ 'X-MockAPI-Key' = $env:MOCKAPI_KEY } ``` @@ -282,7 +281,7 @@ Invoke-RestMethod http://localhost:5080/ctp/parks -Headers @{ 'X-MockAPI-Key' = # Terminal 2: verify readiness, then call the first mock endpoint curl -fsS http://localhost:5080/health/ready -curl -fsS -H "X-MockAPI-Key: $MOCKAPI_KEY" http://localhost:5080/ctp/parks +curl -fsS -H "X-MockAPI-Key: $MOCKAPI_KEY" http://localhost:5080/inventory/items ``` @@ -294,7 +293,7 @@ Direct development starts with an empty configuration unless a configuration pat ```powershell New-Item -ItemType Directory -Force artifacts/local-data | Out-Null -Copy-Item config/mockapi.json artifacts/local-data/mockapi.json +Copy-Item config/trailhead-inventory.json artifacts/local-data/mockapi.json $env:MockApi__ConfigurationPath = (Resolve-Path artifacts/local-data/mockapi.json).Path $env:MockApi__AllowEmptyConfiguration = 'false' .\start.ps1 -Action run @@ -307,7 +306,7 @@ $env:MockApi__AllowEmptyConfiguration = 'false' ```bash mkdir -p artifacts/local-data -cp config/mockapi.json artifacts/local-data/mockapi.json +cp config/trailhead-inventory.json artifacts/local-data/mockapi.json export MockApi__ConfigurationPath="$(realpath artifacts/local-data/mockapi.json)" export MockApi__AllowEmptyConfiguration='false' ./start.sh --action run @@ -400,7 +399,7 @@ Open `http://localhost:8080/`, select **Load examples**, and verify the first re PowerShell 7 ```powershell -Invoke-RestMethod http://localhost:8080/ctp/parks -Headers @{ 'X-MockAPI-Key' = $env:MOCKAPI_KEY } +Invoke-RestMethod http://localhost:8080/inventory/items -Headers @{ 'X-MockAPI-Key' = $env:MOCKAPI_KEY } ``` @@ -409,7 +408,7 @@ Invoke-RestMethod http://localhost:8080/ctp/parks -Headers @{ 'X-MockAPI-Key' = Bash ```bash -curl -fsS -H "X-MockAPI-Key: $MOCKAPI_KEY" http://localhost:8080/ctp/parks +curl -fsS -H "X-MockAPI-Key: $MOCKAPI_KEY" http://localhost:8080/inventory/items ``` @@ -491,6 +490,12 @@ docker compose up --detach The repository includes `azd` infrastructure for Azure Container Apps, Azure Container Registry, private managed-identity Blob persistence, and minimal Log Analytics retention. +For automatic mock authorization, optionally set `AZURE_MOCKAPI_KEY` in the ignored environment file. +It becomes the container's secret-backed `MockApi__ApiKey` setting, so callers can send the same value in +`X-MockAPI-Key` without generating a key through the dashboard. Direct IaC consumers can use the secure +`mockApiKey` Bicep parameter. The key seeds only missing security settings; existing saved keys and protection +choices take precedence. See [deployment key setup and constraints](docs/OPERATIONS.md#mock-api-keys). + Set up the Azure tools, create the ignored environment file, validate the deployment, and deploy:
@@ -599,9 +604,9 @@ The image runs as the non-root `app` user. `/data` is the only required writable The same workflow applies to every execution model: 1. Open the dashboard at the application root. -2. Select **Load examples** to add the built-in Contoso Theme Parks (`/ctp/*`) endpoints. +2. Select **Load examples** to merge the built-in Trailhead Supply AI assistant, inventory, and shipping endpoints. 3. With administrator credentials configured, generate a key in **Settings > Mock API security**. - Copy it before reloading; the server stores only its hash. Select **Test** on an endpoint, or call `/ctp/parks` + Copy it before reloading; the server stores only its hash. Select **Test** on an endpoint, or call `/inventory/items` with the key in `X-MockAPI-Key`. Set `MOCKAPI_KEY` in the calling terminal for the request examples above. 4. Edit, duplicate, enable, disable, or create an endpoint. Valid changes become active immediately. 5. Changes are saved automatically to the selected persistence target. If saving fails, changes stay active @@ -610,11 +615,11 @@ The same workflow applies to every execution model: The built-in example merge adds missing endpoints, skips identical ones, preserves unrelated configuration, and requires explicit confirmation before replacing a conflicting example. -![Annotated endpoint editor for /ctp/parks showing its description, GET and HEAD methods, exact path, response behavior, status code, headers, raw body, enabled toggle, and the apply-endpoint action.](docs/images/03-endpoint-editor.png) +![Endpoint editor for /inventory/items/SKU-1001 showing its description, GET and HEAD methods, exact path, response behavior, status code, headers, body, enabled toggle, and the apply-endpoint action.](docs/images/03-endpoint-editor.png) The endpoint editor defines everything a response returns: methods, exact path, status code, reason phrase, headers, content type, and body. Valid changes apply immediately. -![Annotated endpoint test drawer for /ctp/parks showing the request controls and a local HTTP 200 response with headers, timing, effective URL, and the static park discovery body.](docs/images/04-endpoint-test.png) +![Endpoint test drawer for /inventory/items showing the request controls and a local HTTP 200 response with headers, timing, effective URL, and the static inventory body.](docs/images/04-endpoint-test.png) The built-in test drawer sends a real request to any endpoint and shows the live response — status, elapsed time, effective URL, and headers — without leaving the dashboard. @@ -634,8 +639,8 @@ Each request generates the document from one current active configuration snapsh 2. In APIM, choose **APIs > Add API > OpenAPI** and supply the deployed export URL, or upload a freshly downloaded file if the export requires authentication or is private. 3. Set APIM's **Web service URL** to the deployed MockAPI HTTPS base URL. The export's `servers` value is a local-development placeholder, not deployment discovery. 4. Configure the backend call to supply `X-MockAPI-Key`, using a secret value rather than embedding the key in - the export. Choose an API URL suffix, such as `mockapi`. An enabled `/ctp/parks` route is then called through - `https:///mockapi/ctp/parks`. + the export. Choose an API URL suffix, such as `mockapi`. An enabled `/inventory/items` route is then called through + `https:///mockapi/inventory/items`. 5. Test through APIM with its required subscription key or other caller credentials. MockAPI still serves the response; importing the document does not reproduce its behavior inside APIM. **Runtime generation is not APIM synchronization.** APIM imports a snapshot and does not watch the source URL. Re-import into the same APIM API when its operations or documented responses need updating. Existing imported routes forward to the current MockAPI behavior immediately, subject to APIM policies and caching. @@ -648,11 +653,28 @@ See [Live mock OpenAPI and APIM import](docs/MANAGEMENT_API.md#live-mock-openapi ### 3.1) Configuration -MockAPI accepts complete JSON documents conforming to [schemas/mockapi.schema.json](schemas/mockapi.schema.json). [config/mockapi.json](config/mockapi.json) contains examples for normal and delayed responses, repeated headers, non-success status codes, empty bodies, and an intentional connection abort. +MockAPI accepts complete JSON documents conforming to [schemas/mockapi.schema.json](schemas/mockapi.schema.json). The Trailhead Supply samples cover normal and delayed responses, repeated headers, non-success status codes, empty bodies, and an intentional connection abort. + +The repository includes these native sample configurations: + +| File | Scenarios | +| ----------------------------------------------------------- | ------------------------------------------------------------------------------ | +| [trailhead-aoai.json](config/trailhead-aoai.json) | Trailhead AI assistant completion, capacity exhaustion, and backend failures | +| [trailhead-inventory.json](config/trailhead-inventory.json) | Stock snapshots, reservations, insufficient stock, and warehouse outages | +| [trailhead-shipping.json](config/trailhead-shipping.json) | Quotes, shipments, tracking, label downloads, throttling, and carrier failures | + +Import a sample through the dashboard, or use it as the source of the writable startup copy shown +in [Run Directly with .NET](#22-run-directly-with-net). Samples return static data, not live business services. +The dashboard's **Load examples** action merges all three Trailhead files as one 41-endpoint example. +Each API provides a HEAD-only health mock (`/aoai/health`, `/inventory/health`, `/shipping/health`) +returning an empty `200 OK`; inspection endpoints use GET only. These mock health routes require +the instance API key when protection is enabled, unlike the public application health probes. +Existing saved configurations are not replaced automatically. There is no endpoint-count limit; +the complete merged configuration must still fit the 4 MiB UTF-8 document-size limit and pass validation. The primary runtime switches control persistence and independently expose the dashboard, management API, OpenAPI document, and Swagger UI. Detailed settings, limits, endpoint fields, and persistence behavior are documented in the [configuration reference](docs/CONFIGURATION.md). -![Annotated configuration commands showing example loading, JSON import, export, and Retry save, with a guide listing all eight export formats and explaining automatic persistence.](docs/images/07-export-formats.png) +![Configuration commands showing example loading, JSON import, export-format selection, export, and Retry save.](docs/images/07-export-formats.png) Export the active configuration as MockAPI JSON or as a ready-to-use Postman, Insomnia, cURL, JMeter, OpenAPI, k6, or HTTP-file collection, import a saved configuration, and save valid changes to the selected persistence target. @@ -762,7 +784,14 @@ To review the GitHub Pages documentation locally, run `.\start.ps1 -Action site- The documentation site's **Toggle color theme** sun-icon button matches the dashboard. On first load, the theme follows the operating system unless a Light or Dark choice was saved. Clicking toggles between Light and Dark and saves the choice independently of dashboard preferences. -The documentation gallery shows a populated dashboard overview, all 16 Contoso Theme Parks (`/ctp`) example endpoints, and an expanded log of 16 sample requests. Use the left/right arrow buttons, the named view buttons, or the left/right arrow keys within the gallery to switch screenshots. Images open at full size in a new tab. The carousel does not advance automatically; without JavaScript, all three screenshots remain visible. Captures use only the checked-in example configuration and generated local requests, not a running deployment's data. +The documentation gallery captures the 23-endpoint inventory and shipping subset of Trailhead Supply, +with a populated dashboard overview and recent entries from 25 sample requests. **Load examples** +loads all 41 endpoints, including the 15 AI assistant scenarios and three HEAD-only API health mocks +not shown in these captures. Use the left/right arrow +buttons, the named view buttons, or the left/right arrow keys within the gallery to switch screenshots. +Images open at full size in a new tab. The carousel does not advance automatically; without JavaScript, +all three screenshots remain visible. Captures use only the checked-in example configuration and +generated local requests, not a running deployment's data. Gallery screenshots use lossless WebP at their original dimensions, with a combined 160 KiB transfer budget checked by tests. A PNG overview is retained for social previews. Documentation images are published only with the static site, not with the application container. diff --git a/config/aoai.json b/config/aoai.json deleted file mode 100644 index 63dd412..0000000 --- a/config/aoai.json +++ /dev/null @@ -1,261 +0,0 @@ -{ - "$schema": "../schemas/mockapi.schema.json", - "schemaVersion": "1.0", - "endpoints": [ - { - "id": "2dd0ad99-53ed-4d37-a9a3-c94c531d8520", - "name": "Inference backend - success", - "description": "Returns a healthy Azure OpenAI-style chat completion. APIM should return this response without retrying or tripping the backend circuit breaker.", - "enabled": true, - "methods": ["POST"], - "path": "/aoai/200/chat/completions", - "response": { - "statusCode": 200, - "reasonPhrase": "OK", - "headers": { - "X-Mock-Backend-Scenario": ["success"] - }, - "contentType": "application/json; charset=utf-8", - "body": "{\"id\":\"chatcmpl-mock-success\",\"object\":\"chat.completion\",\"created\":0,\"model\":\"mock-inference-model\",\"choices\":[{\"index\":0,\"message\":{\"role\":\"assistant\",\"content\":\"Mock inference completed successfully.\"},\"finish_reason\":\"stop\"}],\"usage\":{\"prompt_tokens\":8,\"completion_tokens\":6,\"total_tokens\":14}}" - } - }, - { - "id": "99c2c757-5f85-4ee0-83f9-b26e8364946f", - "name": "Inference backend - invalid request", - "description": "Returns a client error for an invalid inference request. APIM should pass it through unchanged without retrying or tripping the circuit breaker.", - "enabled": true, - "methods": ["POST"], - "path": "/aoai/400/chat/completions", - "response": { - "statusCode": 400, - "reasonPhrase": "Bad Request", - "headers": { - "X-Mock-Backend-Scenario": ["client-error"] - }, - "contentType": "application/json; charset=utf-8", - "body": "{\"error\":{\"code\":\"invalid_request_error\",\"message\":\"The request payload is invalid.\",\"type\":\"invalid_request_error\"}}" - } - }, - { - "id": "d88b6d82-81d4-49e9-8cf1-d0262231750b", - "name": "Inference backend - authentication failed", - "description": "Returns a backend authentication failure. APIM should pass it through unchanged; operators should correct the backend credential or managed identity configuration.", - "enabled": true, - "methods": ["POST"], - "path": "/aoai/401/chat/completions", - "response": { - "statusCode": 401, - "reasonPhrase": "Unauthorized", - "headers": { - "X-Mock-Backend-Scenario": ["authentication-error"] - }, - "contentType": "application/json; charset=utf-8", - "body": "{\"error\":{\"code\":\"Unauthorized\",\"message\":\"Backend authentication failed.\"}}" - } - }, - { - "id": "1b62446b-eedb-4c9b-a5c7-817fdcad5250", - "name": "Inference backend - authorization failed", - "description": "Returns a backend authorization failure. APIM should pass it through unchanged; operators should correct the backend role assignment or authorization policy.", - "enabled": true, - "methods": ["POST"], - "path": "/aoai/403/chat/completions", - "response": { - "statusCode": 403, - "reasonPhrase": "Forbidden", - "headers": { - "X-Mock-Backend-Scenario": ["authorization-error"] - }, - "contentType": "application/json; charset=utf-8", - "body": "{\"error\":{\"code\":\"Forbidden\",\"message\":\"The backend identity is not authorized to invoke this deployment.\"}}" - } - }, - { - "id": "e51ab3dd-91a3-4104-a315-16fd40b826d7", - "name": "Inference backend - deployment not found", - "description": "Returns a missing model deployment error. APIM should pass it through unchanged; operators should correct the backend URL or deployment name.", - "enabled": true, - "methods": ["POST"], - "path": "/aoai/404/chat/completions", - "response": { - "statusCode": 404, - "reasonPhrase": "Not Found", - "headers": { - "X-Mock-Backend-Scenario": ["configuration-error"] - }, - "contentType": "application/json; charset=utf-8", - "body": "{\"error\":{\"code\":\"DeploymentNotFound\",\"message\":\"The requested model deployment does not exist.\"}}" - } - }, - { - "id": "a405ed96-53ea-423c-931f-e688a6bb3667", - "name": "Inference backend - request timeout", - "description": "Returns an explicit HTTP 408. APIM should trip the responding backend circuit and retry another eligible backend, retaining 408 if the fallback chain is exhausted.", - "enabled": true, - "methods": ["POST"], - "path": "/aoai/408/chat/completions", - "response": { - "statusCode": 408, - "reasonPhrase": "Request Timeout", - "headers": { - "X-Mock-Backend-Scenario": ["timeout"] - }, - "contentType": "application/json; charset=utf-8", - "body": "{\"error\":{\"code\":\"RequestTimeout\",\"message\":\"The backend timed out while processing the inference request.\"}}" - } - }, - { - "id": "a11f58f0-e0da-4a3e-b8fc-418e42dbf2ee", - "name": "Inference backend - non-transient conflict", - "description": "Returns HTTP 409 without Retry-After. APIM should treat the conflict as non-transient and return it after one backend attempt.", - "enabled": true, - "methods": ["POST"], - "path": "/aoai/409/chat/completions", - "response": { - "statusCode": 409, - "reasonPhrase": "Conflict", - "headers": { - "X-Mock-Backend-Scenario": ["non-transient-conflict"] - }, - "contentType": "application/json; charset=utf-8", - "body": "{\"error\":{\"code\":\"Conflict\",\"message\":\"A non-transient backend conflict occurred.\"}}" - } - }, - { - "id": "f8ab06f1-a428-429e-a71e-2f69cc334d5e", - "name": "Inference backend - transient conflict", - "description": "Returns HTTP 409 with Retry-After: 1. APIM should retry another backend but should not open the responding backend circuit for this conditional conflict.", - "enabled": true, - "methods": ["POST"], - "path": "/aoai/409-retry-after/chat/completions", - "response": { - "statusCode": 409, - "reasonPhrase": "Conflict", - "headers": { - "Retry-After": ["1"], - "X-Mock-Backend-Scenario": ["transient-conflict"] - }, - "contentType": "application/json; charset=utf-8", - "body": "{\"error\":{\"code\":\"Conflict\",\"message\":\"A transient backend conflict occurred; retry after one second.\"}}" - } - }, - { - "id": "7713e516-ac68-4d51-87ed-0fc8caf12387", - "name": "Inference backend - capacity exhausted", - "description": "Returns HTTP 429 with Retry-After: 10 to model exhausted inference capacity. APIM should trip the backend circuit and retry another eligible backend.", - "enabled": true, - "methods": ["POST"], - "path": "/aoai/429/chat/completions", - "response": { - "statusCode": 429, - "reasonPhrase": "Too Many Requests", - "headers": { - "Retry-After": ["10"], - "X-Mock-Backend-Scenario": ["capacity-exhausted"] - }, - "contentType": "application/json; charset=utf-8", - "body": "{\"error\":{\"code\":\"RateLimitReached\",\"message\":\"The backend deployment has exhausted its available capacity.\",\"type\":\"tokens\"}}" - } - }, - { - "id": "c8226f69-d647-4d32-8323-c196c4a52fa7", - "name": "Inference backend - transformed PTU exhaustion", - "description": "Returns custom HTTP 499 to represent PTU exhaustion transformed from a backend 408. APIM should trip the backend circuit and fail over.", - "enabled": true, - "methods": ["POST"], - "path": "/aoai/499/chat/completions", - "response": { - "statusCode": 499, - "reasonPhrase": "PTU Capacity Exhausted", - "headers": { - "X-Mock-Backend-Scenario": ["transformed-ptu-exhaustion"] - }, - "contentType": "application/json; charset=utf-8", - "body": "{\"error\":{\"code\":\"PtuCapacityExhausted\",\"message\":\"PTU exhaustion was transformed to the custom 499 response.\"}}" - } - }, - { - "id": "e7116d72-9a7e-481c-a41c-678a6dd5c9e8", - "name": "Inference backend - internal server error", - "description": "Returns HTTP 500. APIM should trip the backend circuit, retry another eligible backend, and normalize an exhausted fallback chain to HTTP 503.", - "enabled": true, - "methods": ["POST"], - "path": "/aoai/500/chat/completions", - "response": { - "statusCode": 500, - "reasonPhrase": "Internal Server Error", - "headers": { - "X-Mock-Backend-Scenario": ["infrastructure-error"] - }, - "contentType": "application/json; charset=utf-8", - "body": "{\"error\":{\"code\":\"InternalServerError\",\"message\":\"The inference backend encountered an internal error.\"}}" - } - }, - { - "id": "8db83525-ac49-4208-a921-c3af70a98c31", - "name": "Inference backend - bad gateway", - "description": "Returns HTTP 502. APIM should trip the backend circuit, retry another eligible backend, and normalize an exhausted fallback chain to HTTP 503.", - "enabled": true, - "methods": ["POST"], - "path": "/aoai/502/chat/completions", - "response": { - "statusCode": 502, - "reasonPhrase": "Bad Gateway", - "headers": { - "X-Mock-Backend-Scenario": ["gateway-error"] - }, - "contentType": "application/json; charset=utf-8", - "body": "{\"error\":{\"code\":\"BadGateway\",\"message\":\"The backend received an invalid response from an upstream dependency.\"}}" - } - }, - { - "id": "1bd86f8e-e798-4f4b-b809-c67e42cb714b", - "name": "Inference backend - unavailable", - "description": "Returns HTTP 503 with Retry-After: 5. APIM should trip the backend circuit, fail over immediately, and return a generic 503 if every fallback is exhausted.", - "enabled": true, - "methods": ["POST"], - "path": "/aoai/503/chat/completions", - "response": { - "statusCode": 503, - "reasonPhrase": "Service Unavailable", - "headers": { - "Retry-After": ["5"], - "X-Mock-Backend-Scenario": ["service-unavailable"] - }, - "contentType": "application/json; charset=utf-8", - "body": "{\"error\":{\"code\":\"ServiceUnavailable\",\"message\":\"The inference backend is temporarily unavailable.\"}}" - } - }, - { - "id": "9a641750-c727-4e65-991f-a7b45fd84740", - "name": "Inference backend - gateway timeout", - "description": "Returns explicit HTTP 504. APIM should trip the backend circuit, retry another eligible backend, and normalize an exhausted fallback chain to HTTP 503.", - "enabled": true, - "methods": ["POST"], - "path": "/aoai/504/chat/completions", - "response": { - "statusCode": 504, - "reasonPhrase": "Gateway Timeout", - "headers": { - "X-Mock-Backend-Scenario": ["gateway-timeout"] - }, - "contentType": "application/json; charset=utf-8", - "body": "{\"error\":{\"code\":\"GatewayTimeout\",\"message\":\"The backend did not receive a timely response from an upstream dependency.\"}}" - } - }, - { - "id": "4b408fc0-2eda-4adf-83d4-3d74c308ca41", - "name": "Inference backend - transport failure", - "description": "Accepts the request and aborts the connection before sending HTTP headers. This approximates a backend transport failure that APIM should retry and normalize to 503 when exhausted.", - "enabled": true, - "methods": ["POST"], - "path": "/aoai/transport-failure/chat/completions", - "response": { - "behavior": "abortConnection", - "headers": {}, - "contentType": null, - "body": "" - } - } - ] -} diff --git a/config/mockapi.json b/config/mockapi.json deleted file mode 100644 index 88743f8..0000000 --- a/config/mockapi.json +++ /dev/null @@ -1,304 +0,0 @@ -{ - "$schema": "../schemas/mockapi.schema.json", - "schemaVersion": "1.0", - "apiDescriptions": { - "/ctp": "CTP stands for Contoso Theme Parks, a fictional theme park company where a little wonder awaits every visitor. Discover Starlight Gardens and its Cloud Cruiser ride, check sample wait times, and explore a ride reservation from creation to cancellation. These static MockAPI examples do not store reservations or provide live availability. POST, PUT, and PATCH request bodies are optional; supplied non-empty JSON payloads are syntax-checked, but body fields and query strings do not select responses. Clearly labeled demo-faults routes demonstrate HTTP and connection failures." - }, - "endpoints": [ - { - "id": "4cb6e141-5f4f-4a30-9715-ec2c68554ad0", - "name": "Discover the parks", - "description": "Welcome to Contoso Theme Parks! Discover the fictional Starlight Gardens park and its Cloud Cruiser attraction through a static 200 OK JSON response with an X-Mock-Source header. This endpoint supports GET only; use HEAD /ctp/health for the sample health check.", - "enabled": true, - "methods": ["GET"], - "path": "/ctp/parks", - "response": { - "statusCode": 200, - "reasonPhrase": "OK", - "headers": { - "X-Mock-Source": ["MockAPI"] - }, - "contentType": "application/json; charset=utf-8", - "body": "{\"parks\":[{\"id\":\"starlight-gardens\",\"name\":\"Starlight Gardens\",\"tagline\":\"A little wonder in every visit.\",\"attractionIds\":[\"cloud-cruiser\"]}]}" - } - }, - { - "id": "29050644-b1cb-4c28-845a-7aa48ae6b165", - "name": "Check the park API health", - "description": "Static HEAD-only health-check demo: always returns 200 OK with an X-Mock-Source header, no content type, and no body. No park services or dependencies are checked. GET on this path and HEAD /ctp/parks return 404. This is a mock endpoint subject to instance API-key protection, not MockAPI's public /health/live or /health/ready probes.", - "enabled": true, - "methods": ["HEAD"], - "path": "/ctp/health", - "response": { - "statusCode": 200, - "reasonPhrase": "OK", - "headers": { - "X-Mock-Source": ["MockAPI"] - }, - "contentType": null, - "body": "" - } - }, - { - "id": "e4d94382-7645-4e3b-9ee3-d7da24e3879b", - "name": "Explore Cloud Cruiser", - "description": "Discover Cloud Cruiser in Starlight Gardens' Skyward Summit land. Returns static ride details with 200 OK, including its park ID, operating status, minimum height, and a link to sample wait times. No live ride, weather, or maintenance data is queried.", - "enabled": true, - "methods": ["GET"], - "path": "/ctp/attractions/cloud-cruiser", - "response": { - "statusCode": 200, - "reasonPhrase": "OK", - "headers": { - "X-Mock-Source": ["MockAPI"] - }, - "contentType": "application/json; charset=utf-8", - "body": "{\"id\":\"cloud-cruiser\",\"parkId\":\"starlight-gardens\",\"name\":\"Cloud Cruiser\",\"type\":\"roller-coaster\",\"land\":\"Skyward Summit\",\"status\":\"open\",\"minimumHeightCm\":110,\"waitTimesUrl\":\"/ctp/attractions/cloud-cruiser/wait-times\"}" - } - }, - { - "id": "17a50c14-e67f-4770-9bf6-afb4a80e4609", - "name": "Reserve a ride", - "description": "Make room for a little adventure! After syntax-checking any supplied non-empty JSON payload, simulates a Cloud Cruiser reservation for two visitors with 201 Created, a confirmation payload, and Location: /ctp/reservations/42. Body field values are ignored; nothing is stored or changed.", - "enabled": true, - "methods": ["POST"], - "path": "/ctp/reservations", - "response": { - "statusCode": 201, - "reasonPhrase": "Created", - "headers": { - "Location": ["/ctp/reservations/42"], - "X-Mock-Source": ["MockAPI"] - }, - "contentType": "application/json; charset=utf-8", - "body": "{\"id\":42,\"parkId\":\"starlight-gardens\",\"attractionId\":\"cloud-cruiser\",\"partySize\":2,\"status\":\"reserved\",\"confirmationCode\":\"CTP-0042\",\"message\":\"Your Cloud Cruiser reservation is confirmed.\"}" - } - }, - { - "id": "f902cd75-7fa4-41bc-a167-7019e3c96f8e", - "name": "View your ride reservation", - "description": "Returns sample reservation 42 for Cloud Cruiser with 200 OK. This is the destination of the creation response's Location header. The fixture is always available, even before creation or after cancellation; it is not a stored reservation.", - "enabled": true, - "methods": ["GET"], - "path": "/ctp/reservations/42", - "response": { - "statusCode": 200, - "reasonPhrase": "OK", - "headers": { - "X-Mock-Source": ["MockAPI"] - }, - "contentType": "application/json; charset=utf-8", - "body": "{\"id\":42,\"parkId\":\"starlight-gardens\",\"attractionId\":\"cloud-cruiser\",\"partySize\":2,\"status\":\"reserved\",\"confirmationCode\":\"CTP-0042\",\"message\":\"Your Cloud Cruiser reservation is confirmed.\"}" - } - }, - { - "id": "7b2d425d-75f1-4ded-a74e-503374a7e99e", - "name": "Check Cloud Cruiser wait times", - "description": "Check a sample 15-minute wait for Cloud Cruiser. Up to four requests in a rolling 10-second window return 200 OK; additional requests return 429 Too Many Requests with a themed JSON error and Retry-After: 10. The wait time is static, not live. The dashboard preselects five requests to demonstrate the limit, and both responses include repeated X-Mock-Source header values.", - "enabled": true, - "methods": ["GET"], - "path": "/ctp/attractions/cloud-cruiser/wait-times", - "requestCount": 5, - "response": { - "statusCode": 429, - "reasonPhrase": "Too Many Requests", - "headers": { - "Retry-After": ["10"], - "X-Mock-Source": ["MockAPI", "checked-in-example"] - }, - "contentType": "application/json; charset=utf-8", - "body": "{\"error\":\"wait_times_rate_limited\",\"message\":\"Take a little breather! Check back in 10 seconds.\"}", - "rateLimit": { - "requestLimit": 4, - "windowSeconds": 10, - "successResponse": { - "statusCode": 200, - "reasonPhrase": "OK", - "headers": { - "X-Mock-Source": ["MockAPI", "checked-in-example"] - }, - "contentType": "application/json; charset=utf-8", - "body": "{\"attractionId\":\"cloud-cruiser\",\"waitMinutes\":15,\"status\":\"open\"}" - } - } - } - }, - { - "id": "b53545e8-fd25-44cb-940b-0ce175547483", - "name": "Cancel your ride reservation", - "description": "Plans change, and more adventures await. Simulates cancellation of reservation 42 with 204 No Content and an empty body. Nothing is deleted; repeated cancellations return the same response and GET /ctp/reservations/42 still returns the sample reservation.", - "enabled": true, - "methods": ["DELETE"], - "path": "/ctp/reservations/42", - "response": { - "statusCode": 204, - "reasonPhrase": "No Content", - "headers": { - "X-Mock-Source": ["MockAPI"] - }, - "contentType": null, - "body": "" - } - }, - { - "id": "ec8d45cb-a095-4d7e-9540-c7d9d81fe426", - "name": "Find the featured attraction", - "description": "Follow today's spotlight to Cloud Cruiser. Returns 302 Found with Location: /ctp/attractions/cloud-cruiser and an empty body. Clients that follow redirects receive the ride's static 200 OK JSON details.", - "enabled": true, - "methods": ["GET"], - "path": "/ctp/attractions/featured", - "response": { - "statusCode": 302, - "reasonPhrase": "Found", - "headers": { - "Location": ["/ctp/attractions/cloud-cruiser"], - "X-Mock-Source": ["MockAPI"] - }, - "contentType": null, - "body": "" - } - }, - { - "id": "a276b184-ecf6-4377-bf45-5ef1dc8f7433", - "name": "Parade schedule timeout demo", - "description": "Intentional slow HTTP failure demo: the fictional parade schedule service waits 3 seconds before returning 500 Internal Server Error with a themed JSON error. Use it to test client timeout and error handling; it does not cause a real application error or represent live park operations.", - "enabled": true, - "methods": ["GET"], - "path": "/ctp/demo-faults/parade-schedule", - "response": { - "delaySeconds": 3, - "statusCode": 500, - "reasonPhrase": "Internal Server Error", - "headers": { - "X-Mock-Source": ["MockAPI"] - }, - "contentType": "application/json; charset=utf-8", - "body": "{\"error\":\"parade_schedule_unavailable\",\"message\":\"The parade schedule hit a little hiccup. Please try again later.\"}" - } - }, - { - "id": "5f8c908d-42e1-4af9-952a-35c77c408a26", - "name": "Ride sensor connection fault demo", - "description": "Intentional transport failure demo: the fictional Cloud Cruiser sensor connection is immediately aborted without an HTTP status, headers, or body. Test network-failure handling separately from HTTP errors. No real ride sensors or safety systems are involved.", - "enabled": true, - "methods": ["GET"], - "path": "/ctp/demo-faults/ride-sensor", - "response": { - "behavior": "abortConnection", - "headers": {}, - "contentType": null, - "body": "" - } - }, - { - "id": "b7629894-c849-4a62-91cb-85271b6bd988", - "name": "Reservation validation fault demo", - "description": "Intentional business-validation failure demo: after syntax-checking any supplied non-empty JSON payload, returns 422 Unprocessable Entity with application/problem+json and a sample partySize field error. Body field values are ignored; no reservation is created and no business validation is performed. Malformed JSON payloads instead return 400.", - "enabled": true, - "methods": ["POST"], - "path": "/ctp/demo-faults/reservation-validation", - "response": { - "statusCode": 422, - "reasonPhrase": "Unprocessable Entity", - "headers": { - "X-Mock-Source": ["MockAPI"] - }, - "contentType": "application/problem+json; charset=utf-8", - "body": "{\"type\":\"about:blank\",\"title\":\"Unprocessable Entity\",\"status\":422,\"detail\":\"The sample reservation contains an invalid party size.\",\"errors\":{\"partySize\":[\"Party size must be between 1 and 6 visitors.\"]}}" - } - }, - { - "id": "9f3144f7-9775-4e08-a38e-2d3c982d8912", - "name": "Reservation conflict fault demo", - "description": "Intentional business conflict demo: after syntax-checking any supplied non-empty JSON payload, returns 409 Conflict because the sample Cloud Cruiser ride slot is full. Body field values are ignored; no live availability is checked and no reservation is stored. Malformed JSON payloads instead return 400.", - "enabled": true, - "methods": ["POST"], - "path": "/ctp/demo-faults/reservation-conflict", - "response": { - "statusCode": 409, - "reasonPhrase": "Conflict", - "headers": { - "X-Mock-Source": ["MockAPI"] - }, - "contentType": "application/problem+json; charset=utf-8", - "body": "{\"type\":\"about:blank\",\"title\":\"Conflict\",\"status\":409,\"detail\":\"The sample Cloud Cruiser ride slot is full. Choose another time for your adventure.\",\"attractionId\":\"cloud-cruiser\"}" - } - }, - { - "id": "fb839ed6-4556-40a9-ade9-18c6635e3dda", - "name": "Ticket service maintenance fault demo", - "description": "Intentional temporary unavailability demo: always returns 503 Service Unavailable with Retry-After: 30 and a static maintenance message. Use it to test maintenance messaging and retry handling separately from rate limiting. No real ticket service is contacted; waiting 30 seconds does not change the response.", - "enabled": true, - "methods": ["GET"], - "path": "/ctp/demo-faults/ticket-service", - "response": { - "statusCode": 503, - "reasonPhrase": "Service Unavailable", - "headers": { - "Retry-After": ["30"], - "X-Mock-Source": ["MockAPI"] - }, - "contentType": "application/problem+json; charset=utf-8", - "body": "{\"type\":\"about:blank\",\"title\":\"Service Unavailable\",\"status\":503,\"detail\":\"The sample ticket service is taking a maintenance break. Please try again later.\"}" - } - }, - { - "id": "1fd531ba-e58e-4201-b459-7f9a87ea9681", - "name": "Download the park schedule", - "description": "Take a little wonder with you! Returns a static Starlight Gardens schedule with 200 OK, text/csv, and Content-Disposition: attachment. Use it to test non-JSON responses and download headers. The sample times are fictional, not a live schedule; query strings do not select a different park or date.", - "enabled": true, - "methods": ["GET"], - "path": "/ctp/parks/starlight-gardens/schedule.csv", - "response": { - "statusCode": 200, - "reasonPhrase": "OK", - "headers": { - "Content-Disposition": ["attachment; filename=\"starlight-gardens-schedule.csv\""], - "X-Mock-Source": ["MockAPI"] - }, - "contentType": "text/csv; charset=utf-8", - "body": "parkId,event,startTime\r\nstarlight-gardens,Park opening,09:00\r\nstarlight-gardens,Starlight parade,15:00\r\nstarlight-gardens,Park closing,21:00\r\n" - } - }, - { - "id": "daf10ac8-5a0c-46ab-bfa0-8556d65eac18", - "name": "Update your ride reservation", - "description": "Bring more friends along! After syntax-checking any supplied non-empty JSON payload, simulates updating reservation 42 with 200 OK and a fixed party size of four. Body field values are ignored and nothing is stored; GET /ctp/reservations/42 still returns the original two-visitor fixture. Includes fixed CORS headers for a non-credentialed cross-origin PATCH demo with the companion OPTIONS endpoint. Browser preflight requires instance API-key protection to be disabled.", - "enabled": true, - "methods": ["PATCH"], - "path": "/ctp/reservations/42", - "response": { - "statusCode": 200, - "reasonPhrase": "OK", - "headers": { - "Access-Control-Allow-Origin": ["*"], - "Access-Control-Expose-Headers": ["X-Mock-Source"], - "X-Mock-Source": ["MockAPI"] - }, - "contentType": "application/json; charset=utf-8", - "body": "{\"id\":42,\"parkId\":\"starlight-gardens\",\"attractionId\":\"cloud-cruiser\",\"partySize\":4,\"status\":\"reserved\"}" - } - }, - { - "id": "28b473da-d0d6-4fe5-9a6c-cdb2d998cb98", - "name": "Check reservation preflight", - "description": "Explicit OPTIONS demo for reservation 42: returns 204 No Content, Allow: GET, PATCH, DELETE, OPTIONS, and fixed CORS headers permitting a non-credentialed PATCH with Content-Type and X-MockAPI-Key. Origin and requested method/header values are ignored; this is not dynamic CORS validation. Only the PATCH response includes matching CORS headers. Browser preflights do not carry the API key, so this cross-origin demo requires instance API-key protection to be disabled; this endpoint does not bypass protection.", - "enabled": true, - "methods": ["OPTIONS"], - "path": "/ctp/reservations/42", - "response": { - "statusCode": 204, - "reasonPhrase": "No Content", - "headers": { - "Allow": ["GET, PATCH, DELETE, OPTIONS"], - "Access-Control-Allow-Origin": ["*"], - "Access-Control-Allow-Methods": ["PATCH, OPTIONS"], - "Access-Control-Allow-Headers": ["Content-Type, X-MockAPI-Key"], - "X-Mock-Source": ["MockAPI"] - }, - "contentType": null, - "body": "" - } - } - ] -} diff --git a/config/trailhead-aoai.json b/config/trailhead-aoai.json new file mode 100644 index 0000000..aa9c6aa --- /dev/null +++ b/config/trailhead-aoai.json @@ -0,0 +1,281 @@ +{ + "$schema": "../schemas/mockapi.schema.json", + "schemaVersion": "1.0", + "apiDescriptions": { + "/aoai": "A fictional Azure OpenAI-style backend for the Trailhead Supply assistant. The success route returns a fixed answer about the sample Trail flask stock and shipment tracking. These static examples do not run a model, read the inventory or shipping APIs, store conversations, or contact Azure. POST bodies are optional; supplied non-empty JSON is syntax-checked, but prompts, headers, and query strings never select responses. Choose an explicit scenario path to test success, client errors, capacity exhaustion, infrastructure failures, or a connection abort. Retry and circuit-breaker behavior belongs to the caller or its APIM policy, not MockAPI. Usage counts are illustrative, not measured." + }, + "endpoints": [ + { + "id": "0c524b8e-d3c7-4fa4-94d5-76656d912dae", + "name": "Trailhead assistant - health", + "description": "Description:\nLet an API consumer check that the Trailhead Supply assistant mock is reachable without starting a conversation.\n\nTechnical implementation:\nHEAD returns a fixed 200 OK with sample headers and no response body. This is a mock endpoint subject to instance API-key protection, not a live model or dependency check. GET is not configured.", + "enabled": true, + "methods": ["HEAD"], + "path": "/aoai/health", + "response": { + "statusCode": 200, + "reasonPhrase": "OK", + "headers": { + "X-Mock-Source": ["MockAPI", "aoai-sample"] + }, + "contentType": null, + "body": "" + } + }, + { + "id": "2dd0ad99-53ed-4d37-a9a3-c94c531d8520", + "name": "Trailhead assistant - success", + "description": "Description:\nDemonstrate a successful Trailhead Supply assistant conversation that helps a shopper check Trail flask availability and understand the status of a sample shipment.\n\nTechnical implementation:\nReturns a fixed Azure OpenAI-style assistant answer about Trailhead Supply's sample stock and shipment, regardless of the prompt. No model or business API is called. APIM should return this response without retrying or tripping the backend circuit breaker.", + "enabled": true, + "methods": ["POST"], + "path": "/aoai/200/chat/completions", + "response": { + "statusCode": 200, + "reasonPhrase": "OK", + "headers": { + "X-Mock-Backend-Scenario": ["success"] + }, + "contentType": "application/json; charset=utf-8", + "body": "{\"id\":\"chatcmpl-trailhead-demo\",\"object\":\"chat.completion\",\"created\":0,\"model\":\"trailhead-assistant-mock\",\"choices\":[{\"index\":0,\"message\":{\"role\":\"assistant\",\"content\":\"Trailhead Supply demo: SKU-1001 (Trail flask) has 24 units available at WH-DEMO-01. Shipment shp-demo-001 is label_created; its tracking ID is TRACK-DEMO-001. These are fixed sample snapshots, not live inventory or carrier updates.\"},\"finish_reason\":\"stop\"}],\"usage\":{\"prompt_tokens\":8,\"completion_tokens\":6,\"total_tokens\":14}}" + } + }, + { + "id": "99c2c757-5f85-4ee0-83f9-b26e8364946f", + "name": "Trailhead assistant - invalid request", + "description": "Description:\nExercise the assistant experience when a submitted conversation request is invalid, so the application can explain that it needs correction rather than repeatedly resubmitting it.\n\nTechnical implementation:\nReturns a fixed client error for a Trailhead Supply assistant request; it does not inspect prompt or message fields. APIM should pass it through unchanged without retrying or tripping the circuit breaker.", + "enabled": true, + "methods": ["POST"], + "path": "/aoai/400/chat/completions", + "response": { + "statusCode": 400, + "reasonPhrase": "Bad Request", + "headers": { + "X-Mock-Backend-Scenario": ["client-error"] + }, + "contentType": "application/json; charset=utf-8", + "body": "{\"error\":{\"code\":\"invalid_request_error\",\"message\":\"The request payload is invalid.\",\"type\":\"invalid_request_error\"}}" + } + }, + { + "id": "d88b6d82-81d4-49e9-8cf1-d0262231750b", + "name": "Trailhead assistant - authentication failed", + "description": "Description:\nDemonstrate the assistant being unable to sign in to its AI service, helping the support team distinguish an integration credential problem from an issue with a shopper's question.\n\nTechnical implementation:\nSimulates a backend authentication failure for the Trailhead Supply assistant, not MockAPI's own API-key check. APIM should pass it through unchanged; operators should correct the backend credential or managed identity configuration.", + "enabled": true, + "methods": ["POST"], + "path": "/aoai/401/chat/completions", + "response": { + "statusCode": 401, + "reasonPhrase": "Unauthorized", + "headers": { + "X-Mock-Backend-Scenario": ["authentication-error"] + }, + "contentType": "application/json; charset=utf-8", + "body": "{\"error\":{\"code\":\"Unauthorized\",\"message\":\"Backend authentication failed.\"}}" + } + }, + { + "id": "1b62446b-eedb-4c9b-a5c7-817fdcad5250", + "name": "Trailhead assistant - authorization failed", + "description": "Description:\nExercise the case where the assistant's service identity lacks permission to use the AI deployment, so the issue can be routed to the team responsible for access rather than treated as temporary demand.\n\nTechnical implementation:\nSimulates a backend authorization failure for the Trailhead Supply assistant. APIM should pass it through unchanged; operators should correct the backend role assignment or authorization policy.", + "enabled": true, + "methods": ["POST"], + "path": "/aoai/403/chat/completions", + "response": { + "statusCode": 403, + "reasonPhrase": "Forbidden", + "headers": { + "X-Mock-Backend-Scenario": ["authorization-error"] + }, + "contentType": "application/json; charset=utf-8", + "body": "{\"error\":{\"code\":\"Forbidden\",\"message\":\"The backend identity is not authorized to invoke this deployment.\"}}" + } + }, + { + "id": "e51ab3dd-91a3-4104-a315-16fd40b826d7", + "name": "Trailhead assistant - deployment not found", + "description": "Description:\nDemonstrate the assistant being configured to use an AI deployment that is no longer available, so operators can identify a setup problem before restoring shopper assistance.\n\nTechnical implementation:\nSimulates a missing model deployment for the Trailhead Supply assistant. APIM should pass it through unchanged; operators should correct the backend URL or deployment name.", + "enabled": true, + "methods": ["POST"], + "path": "/aoai/404/chat/completions", + "response": { + "statusCode": 404, + "reasonPhrase": "Not Found", + "headers": { + "X-Mock-Backend-Scenario": ["configuration-error"] + }, + "contentType": "application/json; charset=utf-8", + "body": "{\"error\":{\"code\":\"DeploymentNotFound\",\"message\":\"The requested model deployment does not exist.\"}}" + } + }, + { + "id": "a405ed96-53ea-423c-931f-e688a6bb3667", + "name": "Trailhead assistant - request timeout", + "description": "Description:\nExercise an assistant request that cannot finish in time, testing whether the service can use another available AI backend rather than leave a shopper waiting indefinitely.\n\nTechnical implementation:\nReturns an explicit HTTP 408 for the Trailhead Supply assistant without a real timeout or delay. APIM should trip the responding backend circuit and retry another eligible backend, retaining 408 if the fallback chain is exhausted.", + "enabled": true, + "methods": ["POST"], + "path": "/aoai/408/chat/completions", + "response": { + "statusCode": 408, + "reasonPhrase": "Request Timeout", + "headers": { + "X-Mock-Backend-Scenario": ["timeout"] + }, + "contentType": "application/json; charset=utf-8", + "body": "{\"error\":{\"code\":\"RequestTimeout\",\"message\":\"The backend timed out while processing the inference request.\"}}" + } + }, + { + "id": "a11f58f0-e0da-4a3e-b8fc-418e42dbf2ee", + "name": "Trailhead assistant - non-transient conflict", + "description": "Description:\nDemonstrate an assistant request blocked by a conflict that needs intervention rather than another automatic attempt, so the application can present a clear failure instead of looping.\n\nTechnical implementation:\nReturns HTTP 409 without Retry-After for the Trailhead Supply assistant. APIM should treat the conflict as non-transient and return it after one backend attempt.", + "enabled": true, + "methods": ["POST"], + "path": "/aoai/409/chat/completions", + "response": { + "statusCode": 409, + "reasonPhrase": "Conflict", + "headers": { + "X-Mock-Backend-Scenario": ["non-transient-conflict"] + }, + "contentType": "application/json; charset=utf-8", + "body": "{\"error\":{\"code\":\"Conflict\",\"message\":\"A non-transient backend conflict occurred.\"}}" + } + }, + { + "id": "f8ab06f1-a428-429e-a71e-2f69cc334d5e", + "name": "Trailhead assistant - transient conflict", + "description": "Description:\nExercise a temporary conflict while serving an assistant conversation, allowing the integration to try another AI backend without treating the original service as generally unavailable.\n\nTechnical implementation:\nReturns HTTP 409 with Retry-After: 1 for the Trailhead Supply assistant. APIM should retry another backend but should not open the responding backend circuit for this conditional conflict.", + "enabled": true, + "methods": ["POST"], + "path": "/aoai/409-retry-after/chat/completions", + "response": { + "statusCode": 409, + "reasonPhrase": "Conflict", + "headers": { + "Retry-After": ["1"], + "X-Mock-Backend-Scenario": ["transient-conflict"] + }, + "contentType": "application/json; charset=utf-8", + "body": "{\"error\":{\"code\":\"Conflict\",\"message\":\"A transient backend conflict occurred; retry after one second.\"}}" + } + }, + { + "id": "7713e516-ac68-4d51-87ed-0fc8caf12387", + "name": "Trailhead assistant - capacity exhausted", + "description": "Description:\nDemonstrate a surge in shopper questions that exhausts an AI deployment's capacity, testing whether the assistant can continue through spare capacity or explain that it is busy.\n\nTechnical implementation:\nReturns HTTP 429 with Retry-After: 10 to model exhausted Trailhead Supply assistant capacity. This route always fails; no rolling-window counter is configured. APIM should trip the backend circuit and retry another eligible backend.", + "enabled": true, + "methods": ["POST"], + "path": "/aoai/429/chat/completions", + "response": { + "statusCode": 429, + "reasonPhrase": "Too Many Requests", + "headers": { + "Retry-After": ["10"], + "X-Mock-Backend-Scenario": ["capacity-exhausted"] + }, + "contentType": "application/json; charset=utf-8", + "body": "{\"error\":{\"code\":\"RateLimitReached\",\"message\":\"The backend deployment has exhausted its available capacity.\",\"type\":\"tokens\"}}" + } + }, + { + "id": "c8226f69-d647-4d32-8323-c196c4a52fa7", + "name": "Trailhead assistant - transformed PTU exhaustion", + "description": "Description:\nExercise the assistant's fallback journey when its reserved AI processing capacity is exhausted, so shopper conversations can be redirected to another eligible deployment.\n\nTechnical implementation:\nReturns custom HTTP 499 to represent Trailhead Supply assistant PTU exhaustion already transformed from a backend 408. This is a synthetic policy outcome, not a standard Azure OpenAI status or a caller disconnect. APIM should trip the backend circuit and fail over.", + "enabled": true, + "methods": ["POST"], + "path": "/aoai/499/chat/completions", + "response": { + "statusCode": 499, + "reasonPhrase": "PTU Capacity Exhausted", + "headers": { + "X-Mock-Backend-Scenario": ["transformed-ptu-exhaustion"] + }, + "contentType": "application/json; charset=utf-8", + "body": "{\"error\":{\"code\":\"PtuCapacityExhausted\",\"message\":\"PTU exhaustion was transformed to the custom 499 response.\"}}" + } + }, + { + "id": "e7116d72-9a7e-481c-a41c-678a6dd5c9e8", + "name": "Trailhead assistant - internal server error", + "description": "Description:\nDemonstrate an unexpected AI service failure during a shopper conversation, testing whether the assistant can recover through another backend or clearly report a temporary loss of service.\n\nTechnical implementation:\nReturns HTTP 500 for the Trailhead Supply assistant. APIM should trip the backend circuit, retry another eligible backend, and normalize an exhausted fallback chain to HTTP 503.", + "enabled": true, + "methods": ["POST"], + "path": "/aoai/500/chat/completions", + "response": { + "statusCode": 500, + "reasonPhrase": "Internal Server Error", + "headers": { + "X-Mock-Backend-Scenario": ["infrastructure-error"] + }, + "contentType": "application/json; charset=utf-8", + "body": "{\"error\":{\"code\":\"InternalServerError\",\"message\":\"The inference backend encountered an internal error.\"}}" + } + }, + { + "id": "8db83525-ac49-4208-a921-c3af70a98c31", + "name": "Trailhead assistant - bad gateway", + "description": "Description:\nExercise a failure in a dependency behind the AI service, ensuring the assistant handles the interruption without presenting a broken response as a useful answer to the shopper.\n\nTechnical implementation:\nReturns HTTP 502 for the Trailhead Supply assistant. APIM should trip the backend circuit, retry another eligible backend, and normalize an exhausted fallback chain to HTTP 503.", + "enabled": true, + "methods": ["POST"], + "path": "/aoai/502/chat/completions", + "response": { + "statusCode": 502, + "reasonPhrase": "Bad Gateway", + "headers": { + "X-Mock-Backend-Scenario": ["gateway-error"] + }, + "contentType": "application/json; charset=utf-8", + "body": "{\"error\":{\"code\":\"BadGateway\",\"message\":\"The backend received an invalid response from an upstream dependency.\"}}" + } + }, + { + "id": "1bd86f8e-e798-4f4b-b809-c67e42cb714b", + "name": "Trailhead assistant - unavailable", + "description": "Description:\nDemonstrate the assistant's primary AI service being temporarily unavailable, testing continuity through a fallback and an honest unavailable message when no service can help the shopper.\n\nTechnical implementation:\nReturns HTTP 503 with Retry-After: 5 for the Trailhead Supply assistant. APIM should trip the backend circuit, fail over immediately, and return a generic 503 if every fallback is exhausted.", + "enabled": true, + "methods": ["POST"], + "path": "/aoai/503/chat/completions", + "response": { + "statusCode": 503, + "reasonPhrase": "Service Unavailable", + "headers": { + "Retry-After": ["5"], + "X-Mock-Backend-Scenario": ["service-unavailable"] + }, + "contentType": "application/json; charset=utf-8", + "body": "{\"error\":{\"code\":\"ServiceUnavailable\",\"message\":\"The inference backend is temporarily unavailable.\"}}" + } + }, + { + "id": "9a641750-c727-4e65-991f-a7b45fd84740", + "name": "Trailhead assistant - gateway timeout", + "description": "Description:\nExercise an AI service waiting too long for one of its dependencies, so a shopper's conversation can be retried elsewhere or ended with a clear temporary-unavailability message.\n\nTechnical implementation:\nReturns explicit HTTP 504 for the Trailhead Supply assistant without a real timeout or delay. APIM should trip the backend circuit, retry another eligible backend, and normalize an exhausted fallback chain to HTTP 503.", + "enabled": true, + "methods": ["POST"], + "path": "/aoai/504/chat/completions", + "response": { + "statusCode": 504, + "reasonPhrase": "Gateway Timeout", + "headers": { + "X-Mock-Backend-Scenario": ["gateway-timeout"] + }, + "contentType": "application/json; charset=utf-8", + "body": "{\"error\":{\"code\":\"GatewayTimeout\",\"message\":\"The backend did not receive a timely response from an upstream dependency.\"}}" + } + }, + { + "id": "4b408fc0-2eda-4adf-83d4-3d74c308ca41", + "name": "Trailhead assistant - transport failure", + "description": "Description:\nDemonstrate an interrupted connection to the assistant's AI service, testing that the shopper receives a recoverable service message or a fallback answer rather than an unexplained broken conversation.\n\nTechnical implementation:\nAccepts the Trailhead Supply assistant request and aborts the connection before sending HTTP headers. This approximates a backend transport failure that APIM should retry and normalize to 503 when exhausted; it does not reproduce DNS or TLS failures.", + "enabled": true, + "methods": ["POST"], + "path": "/aoai/transport-failure/chat/completions", + "response": { + "behavior": "abortConnection", + "headers": {}, + "contentType": null, + "body": "" + } + } + ] +} diff --git a/config/trailhead-inventory.json b/config/trailhead-inventory.json new file mode 100644 index 0000000..b09eed3 --- /dev/null +++ b/config/trailhead-inventory.json @@ -0,0 +1,198 @@ +{ + "$schema": "../schemas/mockapi.schema.json", + "schemaVersion": "1.0", + "apiDescriptions": { + "/inventory": "A fictional inventory API for Trailhead Supply. Browse two products, inspect in-stock and out-of-stock snapshots, and try reservation success, cancellation, and failure scenarios. These static examples do not change stock or store reservations. POST bodies are optional; supplied non-empty JSON is syntax-checked, but field values and query strings never select responses. Use the explicit demo-faults routes to exercise business errors and warehouse outages." + }, + "endpoints": [ + { + "id": "7519b5a8-6a09-4859-9722-171a9df01ff0", + "name": "Inventory API health", + "description": "Description:\nLet a storefront or fulfillment agent check that the Trailhead Supply inventory mock is reachable without inspecting stock or reserving products.\n\nTechnical implementation:\nHEAD returns a fixed 200 OK with sample headers and no response body. This is a mock endpoint subject to instance API-key protection, not a live warehouse or dependency check. GET is not configured.", + "enabled": true, + "methods": ["HEAD"], + "path": "/inventory/health", + "response": { + "statusCode": 200, + "reasonPhrase": "OK", + "headers": { + "X-Mock-Source": ["MockAPI", "inventory-sample"] + }, + "contentType": null, + "body": "" + } + }, + { + "id": "4dd49c88-4a3c-4910-b878-d98ff8089214", + "name": "Browse inventory", + "description": "Description:\nHelp a Trailhead Supply shopper browse the catalog and see which products are available before choosing an item.\n\nTechnical implementation:\nReturns two fictional products with fixed available quantities and links to their detail endpoints. Query strings do not filter or paginate this static list.", + "enabled": true, + "methods": ["GET"], + "path": "/inventory/items", + "response": { + "statusCode": 200, + "reasonPhrase": "OK", + "headers": { + "X-Mock-Source": ["MockAPI", "inventory-sample"] + }, + "contentType": "application/json; charset=utf-8", + "body": "{\"items\":[{\"sku\":\"SKU-1001\",\"name\":\"Trail flask\",\"quantityAvailable\":24,\"url\":\"/inventory/items/SKU-1001\"},{\"sku\":\"SKU-1002\",\"name\":\"Day pack\",\"quantityAvailable\":0,\"url\":\"/inventory/items/SKU-1002\"}]}" + } + }, + { + "id": "88797a9d-6b11-4c7b-a652-cc40915030bd", + "name": "Inspect an in-stock product", + "description": "Description:\nLet a shopper or fulfillment agent check how many Trail flasks can be ordered, including the quantities already reserved at the warehouse.\n\nTechnical implementation:\nGET returns a fixed JSON stock snapshot for SKU-1001 in warehouse WH-DEMO-01. Reservation and cancellation calls never change these quantities.", + "enabled": true, + "methods": ["GET"], + "path": "/inventory/items/SKU-1001", + "response": { + "statusCode": 200, + "reasonPhrase": "OK", + "headers": { + "X-Mock-Source": ["MockAPI", "inventory-sample"] + }, + "contentType": "application/json; charset=utf-8", + "body": "{\"sku\":\"SKU-1001\",\"name\":\"Trail flask\",\"warehouseId\":\"WH-DEMO-01\",\"quantityOnHand\":30,\"quantityReserved\":6,\"quantityAvailable\":24,\"status\":\"in_stock\"}" + } + }, + { + "id": "86bb5fbd-3d01-40a3-9094-38001dfa9a35", + "name": "Inspect an out-of-stock product", + "description": "Description:\nShow a shopper that the Day pack is a recognized product but currently unavailable, so the storefront can display an out-of-stock message rather than a missing-product page.\n\nTechnical implementation:\nReturns 200 OK for an existing product with zero available stock. Distinguish an unavailable product from a missing SKU; no live warehouse is queried.", + "enabled": true, + "methods": ["GET"], + "path": "/inventory/items/SKU-1002", + "response": { + "statusCode": 200, + "reasonPhrase": "OK", + "headers": { + "X-Mock-Source": ["MockAPI", "inventory-sample"] + }, + "contentType": "application/json; charset=utf-8", + "body": "{\"sku\":\"SKU-1002\",\"name\":\"Day pack\",\"warehouseId\":\"WH-DEMO-01\",\"quantityOnHand\":0,\"quantityReserved\":0,\"quantityAvailable\":0,\"status\":\"out_of_stock\"}" + } + }, + { + "id": "d0ed024a-f10d-4b81-a975-5d03a2669116", + "name": "Look up a missing product", + "description": "Description:\nHelp a storefront or support agent handle a product code that Trailhead Supply does not recognize and guide the shopper back to the catalog.\n\nTechnical implementation:\nThe literal unknown SKU route always returns a configured 404 problem response. This is not a route template; other unconfigured SKU paths receive MockAPI's ordinary unmatched response.", + "enabled": true, + "methods": ["GET"], + "path": "/inventory/items/unknown", + "response": { + "statusCode": 404, + "reasonPhrase": "Not Found", + "headers": { + "X-Mock-Source": ["MockAPI", "inventory-sample"] + }, + "contentType": "application/problem+json; charset=utf-8", + "body": "{\"type\":\"about:blank\",\"title\":\"Not Found\",\"status\":404,\"detail\":\"The sample SKU does not exist.\",\"sku\":\"unknown\"}" + } + }, + { + "id": "1134c585-5ad6-4403-b18b-386b276d5345", + "name": "Reserve inventory", + "description": "Description:\nDemonstrate holding two Trail flasks for a shopper during checkout so the order journey can show an inventory reservation confirmation.\n\nTechnical implementation:\nSimulates a reservation of two trail flasks with 201 Created and a resolvable Location header. Body fields are ignored; no stock is reduced and the lookup exists before this call.", + "enabled": true, + "methods": ["POST"], + "path": "/inventory/reservations", + "response": { + "statusCode": 201, + "reasonPhrase": "Created", + "headers": { + "Location": ["/inventory/reservations/res-demo-001"], + "X-Mock-Source": ["MockAPI", "inventory-sample"] + }, + "contentType": "application/json; charset=utf-8", + "body": "{\"id\":\"res-demo-001\",\"sku\":\"SKU-1001\",\"quantity\":2,\"status\":\"reserved\",\"itemUrl\":\"/inventory/items/SKU-1001\"}" + } + }, + { + "id": "761e5d33-1dd8-4bc4-8ba2-dc91daec7301", + "name": "Inspect the sample reservation", + "description": "Description:\nLet a checkout application or support agent review the products and quantities held for a sample order before fulfillment.\n\nTechnical implementation:\nAlways returns the same sample reservation, including before creation and after cancellation. It is a static lookup, not persisted reservation state.", + "enabled": true, + "methods": ["GET"], + "path": "/inventory/reservations/res-demo-001", + "response": { + "statusCode": 200, + "reasonPhrase": "OK", + "headers": { + "X-Mock-Source": ["MockAPI", "inventory-sample"] + }, + "contentType": "application/json; charset=utf-8", + "body": "{\"id\":\"res-demo-001\",\"sku\":\"SKU-1001\",\"quantity\":2,\"status\":\"reserved\",\"itemUrl\":\"/inventory/items/SKU-1001\"}" + } + }, + { + "id": "1a9e0efb-af51-4115-a0c1-6fc584edbe4a", + "name": "Cancel the sample reservation", + "description": "Description:\nDemonstrate releasing a shopper's inventory hold when checkout is abandoned or an order is canceled.\n\nTechnical implementation:\nSimulates cancellation with 204 No Content. Nothing is deleted or released; repeated calls succeed and the reservation lookup and stock snapshots remain unchanged.", + "enabled": true, + "methods": ["DELETE"], + "path": "/inventory/reservations/res-demo-001", + "response": { + "statusCode": 204, + "reasonPhrase": "No Content", + "headers": { + "X-Mock-Source": ["MockAPI", "inventory-sample"] + }, + "contentType": null, + "body": "" + } + }, + { + "id": "7279a980-1475-4c8d-9a5f-4b339cc96c83", + "name": "Insufficient stock fault demo", + "description": "Description:\nExercise the checkout message shown when a shopper requests more Day packs than are available, allowing the shopper to reduce the quantity or choose another product.\n\nTechnical implementation:\nAlways returns 409 Conflict for a fictional request for three day packs when none are available. Request field values do not select this outcome and no stock check is performed.", + "enabled": true, + "methods": ["POST"], + "path": "/inventory/demo-faults/insufficient-stock", + "response": { + "statusCode": 409, + "reasonPhrase": "Conflict", + "headers": { + "X-Mock-Source": ["MockAPI", "inventory-sample"] + }, + "contentType": "application/problem+json; charset=utf-8", + "body": "{\"type\":\"about:blank\",\"title\":\"Conflict\",\"status\":409,\"detail\":\"There is not enough sample stock to reserve this item.\",\"sku\":\"SKU-1002\",\"quantityRequested\":3,\"quantityAvailable\":0}" + } + }, + { + "id": "88baaad2-4b21-4f55-8de9-838bb6bba1cc", + "name": "Reservation validation fault demo", + "description": "Description:\nDemonstrate asking a shopper to correct an invalid reservation quantity before the checkout journey can continue.\n\nTechnical implementation:\nAlways returns a static 422 quantity error after global JSON syntax checks. This route does not inspect quantity or validate business fields; malformed JSON instead receives the runtime's 400 response.", + "enabled": true, + "methods": ["POST"], + "path": "/inventory/demo-faults/invalid-reservation", + "response": { + "statusCode": 422, + "reasonPhrase": "Unprocessable Entity", + "headers": { + "X-Mock-Source": ["MockAPI", "inventory-sample"] + }, + "contentType": "application/problem+json; charset=utf-8", + "body": "{\"type\":\"about:blank\",\"title\":\"Unprocessable Entity\",\"status\":422,\"detail\":\"The sample reservation quantity is invalid.\",\"errors\":{\"quantity\":[\"Quantity must be a positive whole number.\"]}}" + } + }, + { + "id": "25675691-3056-45bd-b5da-271e0184b5e9", + "name": "Warehouse outage fault demo", + "description": "Description:\nExercise a temporary warehouse outage so the storefront can explain that stock information is unavailable instead of incorrectly reporting products as sold out.\n\nTechnical implementation:\nAlways returns 503 Service Unavailable with Retry-After: 30. Use it for outage and retry handling; waiting does not restore the fictional warehouse.", + "enabled": true, + "methods": ["GET"], + "path": "/inventory/demo-faults/warehouse-unavailable", + "response": { + "statusCode": 503, + "reasonPhrase": "Service Unavailable", + "headers": { + "Retry-After": ["30"], + "X-Mock-Source": ["MockAPI", "inventory-sample"] + }, + "contentType": "application/problem+json; charset=utf-8", + "body": "{\"type\":\"about:blank\",\"title\":\"Service Unavailable\",\"status\":503,\"detail\":\"The sample warehouse service is unavailable. Retry later.\"}" + } + } + ] +} diff --git a/config/trailhead-shipping.json b/config/trailhead-shipping.json new file mode 100644 index 0000000..ae47db8 --- /dev/null +++ b/config/trailhead-shipping.json @@ -0,0 +1,263 @@ +{ + "$schema": "../schemas/mockapi.schema.json", + "schemaVersion": "1.0", + "apiDescriptions": { + "/shipping": "A fictional shipping API for Trailhead Supply. Explore fixed shipping quotes, shipment creation and cancellation, tracking snapshots, and a text-only demonstration label. These static examples do not buy postage, move parcels, store shipments, or contact carriers. POST bodies are optional; supplied non-empty JSON is syntax-checked, but field values and query strings never select responses. Explicit demo-faults routes cover invalid parcels, carrier outages, rate limiting, a delayed HTTP 504, and connection failure." + }, + "endpoints": [ + { + "id": "b596a0d7-a814-4b09-8f3e-fc717e3df218", + "name": "Shipping API health", + "description": "Description:\nLet a fulfillment dashboard or support agent check that the Trailhead Supply shipping mock is reachable without inspecting shipments or requesting rates.\n\nTechnical implementation:\nHEAD returns a fixed 200 OK with sample headers and no response body. This is a mock endpoint subject to instance API-key protection, not a live carrier or dependency check. GET is not configured.", + "enabled": true, + "methods": ["HEAD"], + "path": "/shipping/health", + "response": { + "statusCode": 200, + "reasonPhrase": "OK", + "headers": { + "X-Mock-Source": ["MockAPI", "shipping-sample"] + }, + "contentType": null, + "body": "" + } + }, + { + "id": "1d4badd0-f004-4401-95ed-3a28477bd75c", + "name": "Compare shipping rates", + "description": "Description:\nHelp a Trailhead Supply shopper compare delivery cost and estimated arrival time when choosing between standard and express shipping at checkout.\n\nTechnical implementation:\nReturns fixed standard and express quotes in USD for a fictional 1.2 kg parcel. Query strings do not change the destination, weight, currency, or prices.", + "enabled": true, + "methods": ["GET"], + "path": "/shipping/rates", + "response": { + "statusCode": 200, + "reasonPhrase": "OK", + "headers": { + "X-Mock-Source": ["MockAPI", "shipping-sample"] + }, + "contentType": "application/json; charset=utf-8", + "body": "{\"parcelWeightKg\":1.2,\"currency\":\"USD\",\"quotes\":[{\"service\":\"standard\",\"amount\":7.5,\"estimatedBusinessDays\":5},{\"service\":\"express\",\"amount\":18.0,\"estimatedBusinessDays\":2}]}" + } + }, + { + "id": "88e58963-dff5-4f76-ae2a-c64da1f589ba", + "name": "Create a sample shipment", + "description": "Description:\nDemonstrate preparing a paid order for dispatch by giving warehouse staff a shipment reference, tracking number, and label link.\n\nTechnical implementation:\nSimulates shipment creation with 201 Created and a resolvable Location header. Returns fixed tracking and label links regardless of body fields; no shipment, postage, or carrier booking is created.", + "enabled": true, + "methods": ["POST"], + "path": "/shipping/shipments", + "response": { + "statusCode": 201, + "reasonPhrase": "Created", + "headers": { + "Location": ["/shipping/shipments/shp-demo-001"], + "X-Mock-Source": ["MockAPI", "shipping-sample"] + }, + "contentType": "application/json; charset=utf-8", + "body": "{\"id\":\"shp-demo-001\",\"status\":\"label_created\",\"service\":\"standard\",\"trackingId\":\"TRACK-DEMO-001\",\"trackingUrl\":\"/shipping/tracking/TRACK-DEMO-001\",\"labelUrl\":\"/shipping/shipments/shp-demo-001/label.txt\"}" + } + }, + { + "id": "c49ea950-c300-440b-89ec-546a7b1e8797", + "name": "Inspect the sample shipment", + "description": "Description:\nLet a fulfillment dashboard or support agent review the selected delivery service and find the tracking and label details for a sample order.\n\nTechnical implementation:\nGET returns the fixed shipment. The lookup exists before creation and remains unchanged after cancellation.", + "enabled": true, + "methods": ["GET"], + "path": "/shipping/shipments/shp-demo-001", + "response": { + "statusCode": 200, + "reasonPhrase": "OK", + "headers": { + "X-Mock-Source": ["MockAPI", "shipping-sample"] + }, + "contentType": "application/json; charset=utf-8", + "body": "{\"id\":\"shp-demo-001\",\"status\":\"label_created\",\"service\":\"standard\",\"trackingId\":\"TRACK-DEMO-001\",\"trackingUrl\":\"/shipping/tracking/TRACK-DEMO-001\",\"labelUrl\":\"/shipping/shipments/shp-demo-001/label.txt\"}" + } + }, + { + "id": "658cc6c8-2cfe-4394-9243-3b0bd19a1b68", + "name": "Track the sample shipment", + "description": "Description:\nShow a shopper that their order has a shipping label but has not yet progressed through delivery, setting expectations on the order-tracking page.\n\nTechnical implementation:\nReturns a fixed label-created tracking snapshot with a fictional timestamp. Polling does not advance the shipment; the delivered route is a separate, explicitly selected fixture.", + "enabled": true, + "methods": ["GET"], + "path": "/shipping/tracking/TRACK-DEMO-001", + "response": { + "statusCode": 200, + "reasonPhrase": "OK", + "headers": { + "X-Mock-Source": ["MockAPI", "shipping-sample"] + }, + "contentType": "application/json; charset=utf-8", + "body": "{\"trackingId\":\"TRACK-DEMO-001\",\"status\":\"label_created\",\"events\":[{\"status\":\"label_created\",\"timestamp\":\"2026-01-05T12:00:00Z\",\"description\":\"A demonstration shipping label was created.\"}]}" + } + }, + { + "id": "4bc1a983-7a31-4e91-bfa0-928da84a4927", + "name": "Inspect a delivered tracking scenario", + "description": "Description:\nDemonstrate the completed-delivery view a shopper or support agent sees after a parcel reaches its destination, including a short journey history.\n\nTechnical implementation:\nAlways returns a separate fictional delivered tracking history. It does not represent a state change to TRACK-DEMO-001 and contains no customer address or signature.", + "enabled": true, + "methods": ["GET"], + "path": "/shipping/tracking/TRACK-DEMO-DELIVERED", + "response": { + "statusCode": 200, + "reasonPhrase": "OK", + "headers": { + "X-Mock-Source": ["MockAPI", "shipping-sample"] + }, + "contentType": "application/json; charset=utf-8", + "body": "{\"trackingId\":\"TRACK-DEMO-DELIVERED\",\"status\":\"delivered\",\"events\":[{\"status\":\"in_transit\",\"timestamp\":\"2026-01-05T15:00:00Z\",\"description\":\"The demonstration parcel left the sample depot.\"},{\"status\":\"delivered\",\"timestamp\":\"2026-01-07T10:00:00Z\",\"description\":\"The demonstration parcel was delivered.\"}]}" + } + }, + { + "id": "254b43ef-0669-42f7-b6f9-c1ba734f93e2", + "name": "Download a demonstration label", + "description": "Description:\nDemonstrate the warehouse workflow for downloading a parcel label before packing and dispatch, using a clearly marked demonstration document.\n\nTechnical implementation:\nReturns a text-only attachment to test non-JSON download handling. This is not a PDF, barcode, postage purchase, or valid shipping label.", + "enabled": true, + "methods": ["GET"], + "path": "/shipping/shipments/shp-demo-001/label.txt", + "response": { + "statusCode": 200, + "reasonPhrase": "OK", + "headers": { + "Content-Disposition": ["attachment; filename=shipping-label-demo-001.txt"], + "X-Mock-Source": ["MockAPI", "shipping-sample"] + }, + "contentType": "text/plain; charset=utf-8", + "body": "MOCK SHIPPING LABEL\nShipment: shp-demo-001\nTracking: TRACK-DEMO-001\nService: standard\nNot valid for shipment.\n" + } + }, + { + "id": "ee5a6440-ef48-4488-badb-fc3b5f3dd50c", + "name": "Cancel the sample shipment", + "description": "Description:\nDemonstrate withdrawing a shipment request when an order is canceled or its delivery arrangements need to be changed before dispatch.\n\nTechnical implementation:\nSimulates cancellation with 204 No Content. Nothing is canceled or deleted; repeated calls succeed and shipment, tracking, and label lookups remain unchanged.", + "enabled": true, + "methods": ["DELETE"], + "path": "/shipping/shipments/shp-demo-001", + "response": { + "statusCode": 204, + "reasonPhrase": "No Content", + "headers": { + "X-Mock-Source": ["MockAPI", "shipping-sample"] + }, + "contentType": null, + "body": "" + } + }, + { + "id": "f3ba3696-53a9-4660-826a-6c00086a7e42", + "name": "Shipment validation fault demo", + "description": "Description:\nHelp warehouse staff recognize and correct an invalid parcel weight before they can complete a shipping booking.\n\nTechnical implementation:\nAlways returns a static 422 parcel-weight error after global JSON syntax checks. No parcel or address fields are inspected; malformed JSON instead receives the runtime's 400 response.", + "enabled": true, + "methods": ["POST"], + "path": "/shipping/demo-faults/invalid-shipment", + "response": { + "statusCode": 422, + "reasonPhrase": "Unprocessable Entity", + "headers": { + "X-Mock-Source": ["MockAPI", "shipping-sample"] + }, + "contentType": "application/problem+json; charset=utf-8", + "body": "{\"type\":\"about:blank\",\"title\":\"Unprocessable Entity\",\"status\":422,\"detail\":\"The sample parcel weight is invalid.\",\"errors\":{\"parcelWeightKg\":[\"Parcel weight must be greater than zero.\"]}}" + } + }, + { + "id": "705fab3d-7b4b-41bb-bb8d-9ef9bdceb77a", + "name": "Carrier outage fault demo", + "description": "Description:\nExercise the fulfillment experience when a carrier cannot accept bookings, so staff see a temporary service problem rather than a successful dispatch confirmation.\n\nTechnical implementation:\nAlways returns 503 Service Unavailable with Retry-After: 15. No carrier is contacted and waiting does not change this configured failure.", + "enabled": true, + "methods": ["POST"], + "path": "/shipping/demo-faults/service-unavailable", + "response": { + "statusCode": 503, + "reasonPhrase": "Service Unavailable", + "headers": { + "Retry-After": ["15"], + "X-Mock-Source": ["MockAPI", "shipping-sample"] + }, + "contentType": "application/problem+json; charset=utf-8", + "body": "{\"type\":\"about:blank\",\"title\":\"Service Unavailable\",\"status\":503,\"detail\":\"The sample carrier booking service is unavailable. Retry later.\"}" + } + }, + { + "id": "ef802d0d-28b6-4575-8e63-3743fe645e34", + "name": "Look up a missing tracking number", + "description": "Description:\nDemonstrate helping a shopper who enters an unrecognized tracking number, prompting them to check the reference from their order confirmation.\n\nTechnical implementation:\nThe literal unknown tracking route always returns a configured 404 problem response. Other unconfigured tracking numbers receive MockAPI's ordinary unmatched response; no tracking service is queried.", + "enabled": true, + "methods": ["GET"], + "path": "/shipping/tracking/unknown", + "response": { + "statusCode": 404, + "reasonPhrase": "Not Found", + "headers": { + "X-Mock-Source": ["MockAPI", "shipping-sample"] + }, + "contentType": "application/problem+json; charset=utf-8", + "body": "{\"type\":\"about:blank\",\"title\":\"Not Found\",\"status\":404,\"detail\":\"The sample tracking number does not exist.\",\"trackingId\":\"unknown\"}" + } + }, + { + "id": "e7e08d5e-76a2-4f80-9a64-4e772ff6d907", + "name": "Tracking rate-limit fault demo", + "description": "Description:\nExercise a tracking page that is refreshed too frequently, so the shopper is asked to wait briefly instead of repeatedly contacting the delivery service.\n\nTechnical implementation:\nThe first two requests in a rolling 10-second window return a fixed label-created snapshot. Further requests return 429 with Retry-After: 10. The dashboard preselects three calls; counters are process-local and tracking state never changes.", + "enabled": true, + "methods": ["GET"], + "path": "/shipping/demo-faults/tracking-rate-limit", + "requestCount": 3, + "response": { + "statusCode": 429, + "reasonPhrase": "Too Many Requests", + "headers": { + "Retry-After": ["10"], + "X-Mock-Source": ["MockAPI", "shipping-sample"] + }, + "contentType": "application/problem+json; charset=utf-8", + "body": "{\"type\":\"about:blank\",\"title\":\"Too Many Requests\",\"status\":429,\"detail\":\"The sample tracking request limit was exceeded. Retry in 10 seconds.\"}", + "rateLimit": { + "requestLimit": 2, + "windowSeconds": 10, + "successResponse": { + "statusCode": 200, + "reasonPhrase": "OK", + "headers": { + "X-Mock-Source": ["MockAPI", "shipping-sample"] + }, + "contentType": "application/json; charset=utf-8", + "body": "{\"trackingId\":\"TRACK-DEMO-001\",\"status\":\"label_created\"}" + } + } + } + }, + { + "id": "a8840357-f738-48c6-b64c-7ba36b9b4648", + "name": "Carrier timeout fault demo", + "description": "Description:\nDemonstrate the experience when a carrier takes too long to provide an update, allowing the tracking page to explain the delay and offer a later retry.\n\nTechnical implementation:\nWaits one second, then sends an explicit HTTP 504 problem response. This is a delayed server response, not a client-side timeout, DNS failure, or actual carrier request.", + "enabled": true, + "methods": ["GET"], + "path": "/shipping/demo-faults/carrier-timeout", + "response": { + "delaySeconds": 1, + "statusCode": 504, + "reasonPhrase": "Gateway Timeout", + "headers": { + "X-Mock-Source": ["MockAPI", "shipping-sample"] + }, + "contentType": "application/problem+json; charset=utf-8", + "body": "{\"type\":\"about:blank\",\"title\":\"Gateway Timeout\",\"status\":504,\"detail\":\"The sample carrier did not respond before the fictional gateway deadline.\"}" + } + }, + { + "id": "878ec4d4-b623-4dae-abf0-5691a798d102", + "name": "Carrier connection fault demo", + "description": "Description:\nExercise an interrupted connection to the delivery service so the shopper sees a recoverable connection problem instead of an incorrect shipment status.\n\nTechnical implementation:\nImmediately aborts the accepted connection without sending an HTTP response. It approximates a transport failure but does not reproduce DNS or TLS failures and never contacts a carrier.", + "enabled": true, + "methods": ["GET"], + "path": "/shipping/demo-faults/connection-failure", + "response": { + "behavior": "abortConnection", + "headers": {}, + "contentType": null, + "body": "" + } + } + ] +} diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index 5a49082..90a397e 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -26,14 +26,14 @@ Optional `apiDescriptions` supplies API/group metadata separately from each endp { "schemaVersion": "1.0", "apiDescriptions": { - "/ctp": "CTP stands for Contoso Theme Parks. Discover a fictional park, explore its attractions, and try static ride reservations and wait times." + "/inventory": "Trailhead Supply inventory: inspect static stock snapshots, reserve sample items, and exercise warehouse failures." }, "endpoints": [] } ``` -Groups retain the dashboard's existing first-path-segment identity: `/ctp`, `/ctp/parks`, and -`/ctp/reservations/42` belong to `/ctp`; `/CTP` is a different group. Keys are `/` or one absolute segment +Groups retain the dashboard's existing first-path-segment identity: `/inventory`, `/inventory/items`, and +`/inventory/reservations/res-demo-001` belong to `/inventory`; `/INVENTORY` is a different group. Keys are `/` or one absolute segment of at most 2,048 characters, without whitespace, control characters, backslashes, query strings, or fragments. Management and health names are reserved. Metadata never creates a mock route. At most 25 descriptions may be stored, each containing at most 4,000 characters of plain text. @@ -49,10 +49,20 @@ Each endpoint also has an information button beside its name instead of an inlin Hover or focus to preview; activate it to open the endpoint editor. Both kinds of preview preserve original casing and line breaks. The endpoint edit dialog shows its stable Operation ID as a read-only field; new and duplicate endpoints receive a new ID when applied. +Information previews can grow to 400 pixels tall or 60% of the viewport height, limited by the space +above or below the information button. Activate the button to read longer descriptions in the editor. Descriptions and dashboard response previews are rendered as text: HTML markup and JavaScript such as `eval(...)` are not interpreted or executed. This does not strip configured mock response bodies, which must remain faithful to the responses being tested. +Every Trailhead sample endpoint organizes its existing `description` into two labeled plain-text +sections: **Description:** first, then **Technical implementation:**, separated by a blank line. +The first explains the shopper, support, or fulfillment scenario; the second explains the mock's +HTTP behavior, fixed data, and limitations. Both headings appear in bold in the information preview; +the content remains plain text and editable +in the single Description field. This is a sample-writing convention, not a required format for custom +endpoints, a new configuration property, or automatic business behavior. + Descriptions survive deletion of the group's last endpoint and reappear if endpoints return to that group. Moving an endpoint does not move API metadata. An empty string deliberately clears the displayed description and prevents built-in loading from restoring it. Native configuration import replaces @@ -99,12 +109,13 @@ methods remain unchanged. These are global runtime rules, not new endpoint confi remains independent and unchanged. Validation responses are counted against the matched endpoint without retaining the request content. -The test blade and all portable request exports provide optional illustrative JSON samples for `POST`, `PUT`, and -`PATCH`. The built-in `/ctp/reservations` and `/ctp/reservations/42` routes use a sample reservation for two -visitors to Starlight Gardens' Cloud Cruiser ride. Other routes use a general sample item with a name, status, -quantity, and metadata. These are request examples, not schemas: the backend checks only supplied payload size -and non-empty JSON syntax, not field names or business values. You can edit or clear the sample in the blade to test -actual server errors; the blade does not block malformed payloads. +The test blade and all portable request exports provide optional illustrative JSON samples for +`POST`, `PUT`, and `PATCH`. Trailhead inventory reservation routes use a SKU, quantity, and warehouse; +shipping creation routes use a service, parcel weight, and line items. Other routes use a general +sample item with a name, status, quantity, and metadata. These are examples, not schemas: the backend +checks supplied payload size and non-empty JSON syntax, not field names or business values. +You can edit or clear the sample in the blade to test actual server errors; the blade does not +block malformed payloads. The dashboard shows `ID` followed by the first eight characters of the endpoint UUID beneath each endpoint name. This is a shortened stable identifier, not a hash. Hover over it to see the complete UUID. The ID remains unchanged across edits so statistics and built-in merge comparisons continue to refer to the same endpoint. @@ -160,7 +171,8 @@ Set `response.behavior` to `abortConnection` to close the connection before any ## Limits and Reserved Values -- Configuration document: 4 MiB and 25 endpoints. +- Configuration document: 4 MiB when UTF-8 encoded, with no endpoint-count limit. +- API descriptions: 25 groups, independently of endpoint count. - Response headers per endpoint: 64. - Individual UTF-8 header value: 8 KiB. - Combined UTF-8 header names and values per endpoint: 32 KiB. @@ -189,94 +201,96 @@ The dashboard checks response bodies whose content type is `application/json` or Uploaded imports replace the entire active document after validation and ETag verification. The built-in example action is different: it merges by stable endpoint ID, adds missing entries, skips identical entries, preserves unrelated endpoints, and requires a conflict preview plus explicit forced update before applying divergent examples. -## Contoso Theme Parks Example - -The checked-in [example](../config/mockapi.json) contains sixteen endpoints in one cohesive API. -**CTP stands for Contoso Theme Parks**, a fictional company where a little wonder awaits every visitor. -Discover Starlight Gardens, explore its Cloud Cruiser roller coaster, and try a sample reservation. -The fixtures are newly invented for MockAPI, inspired by the cohesive learning approach of the -[Contoso Theme Parks project](https://github.com/contoso-theme-parks); they do not reproduce its original -service contracts or require its Azure infrastructure. - -| Method | Route | Behavior | -| --------- | ------------------------------------------- | ---------------------------------------------------------------- | -| `GET` | `/ctp/parks` | Park discovery, `200`; GET-only | -| `HEAD` | `/ctp/health` | Static health fixture, `200`, with no body or content type | -| `GET` | `/ctp/attractions/cloud-cruiser` | Ride details and a wait-times link, `200` | -| `POST` | `/ctp/reservations` | Sample reservation, `201`, with `Location: /ctp/reservations/42` | -| `GET` | `/ctp/reservations/42` | Retrieve the same sample reservation, `200` | -| `DELETE` | `/ctp/reservations/42` | Simulate cancellation, `204`, with no body | -| `GET` | `/ctp/attractions/featured` | Redirect to Cloud Cruiser, `302` | -| `GET` | `/ctp/attractions/cloud-cruiser/wait-times` | Static wait time, `200`; excessive polling returns `429` | -| `GET` | `/ctp/demo-faults/parade-schedule` | Wait 3 seconds, then return an intentional HTTP failure, `500` | -| `GET` | `/ctp/demo-faults/ride-sensor` | Intentional connection abort; no HTTP response | -| `POST` | `/ctp/demo-faults/reservation-validation` | Structured field-level validation failure, `422`, problem JSON | -| `POST` | `/ctp/demo-faults/reservation-conflict` | Full sample ride slot, `409`, problem JSON | -| `GET` | `/ctp/demo-faults/ticket-service` | Maintenance failure, `503`, with `Retry-After: 30` | -| `GET` | `/ctp/parks/starlight-gardens/schedule.csv` | Static CSV schedule, `200`, with an attachment filename | -| `PATCH` | `/ctp/reservations/42` | Fixed four-visitor reservation, `200`; no stored update | -| `OPTIONS` | `/ctp/reservations/42` | Explicit preflight, `204`, with `Allow` and fixed CORS headers | - -The HEAD-only `/ctp/health` fixture returns `200 OK` and `X-Mock-Source: MockAPI` without checking -dependencies. GET `/ctp/health` and HEAD `/ctp/parks` return `404`. This mock route requires the -instance API key when protection is enabled; it is separate from MockAPI's public `/health/live` -and `/health/ready` probes. - -All park information and wait times are static. After the global format checks for any supplied payload, reservation creation ignores the request body's values and -stores nothing; cancellation changes nothing, and the sample reservation remains retrievable before -creation and after cancellation. PATCH ignores the request body's values and returns a fixed four-visitor -reservation; subsequent GET requests still return the original two-visitor fixture. -Query strings do not select different responses. All paths are exact -literals, not route templates. The featured-attraction redirect and reservation `Location` resolve to -configured `GET` endpoints. - -Wait-time polling permits four requests in a rolling 10-second window. Further requests return -`429 Too Many Requests`, `Retry-After: 10`, and -`{"error":"wait_times_rate_limited","message":"Take a little breather! Check back in 10 seconds."}`. -Both outcomes demonstrate repeated `X-Mock-Source` header values. The dashboard preselects five requests. -The parade-schedule fault waits three seconds before returning its configured `500`, making it suitable -for client timeout experiments. Fault routes are deliberately separated under `/ctp/demo-faults/`; no real park operations or safety -systems are involved. Each endpoint's dashboard information button explains its behavior. - -For well-formed payloads or no payload, the validation and conflict demos always return their configured failures. -They do not perform business validation, check ride capacity, or create reservations. Malformed JSON payloads -instead receive the global `400` response. Both configured failures return `application/problem+json`: -the validation response includes an `errors.partySize` array, and the conflict response describes a -full Cloud Cruiser slot. The ticket-service demo uses the same problem media type and always returns -`503`; its `Retry-After: 30` header is a client retry hint, not a timer that restores the service. -The schedule download returns fictional events as UTF-8 `text/csv` with CRLF line endings and -`Content-Disposition: attachment; filename="starlight-gardens-schedule.csv"`. - -The explicit OPTIONS example targets the PATCH path and has no body or content type. Its `Allow` -header lists the configured `GET`, `PATCH`, `DELETE`, and `OPTIONS` methods on that path. Fixed CORS -headers permit a non-credentialed cross-origin PATCH with `Content-Type` and `X-MockAPI-Key`; -the PATCH response supplies matching `Access-Control-Allow-Origin: *` and exposes `X-Mock-Source`. -The OPTIONS fixture ignores `Origin`, `Access-Control-Request-Method`, and -`Access-Control-Request-Headers`; it is not a dynamic CORS policy, and other paths do not acquire -automatic OPTIONS behavior. GET and DELETE on this path do not include matching CORS headers. -API-key protection still applies to OPTIONS. Because browsers do not send the API key on preflight, -the cross-origin browser demonstration requires explicitly disabling instance API-key protection -in a controlled test environment. It does not work with credentialed browser requests or enable -CORS on the dashboard or management API. - -The seven earlier `/ex` example IDs are retained so existing statistics attribution and built-in merge -identity remain stable. On an instance with those examples already loaded, **Load examples** previews -conflicts rather than silently moving routes. After reviewing, **Force update** replaces those seven -definitions and adds the missing examples without deleting unrelated endpoints. -Instances using the earlier nine-, thirteen-, or fifteen-endpoint `/ctp` example also receive a -conflict preview for the stable parks endpoint ID: its HEAD method has moved to the new `/ctp/health` -endpoint. No missing endpoints are added until the conflict is reviewed. **Force update** makes -`/ctp/parks` GET-only and adds `/ctp/health` along with any other missing examples; repeated loading -is then a no-op. API descriptions -remain independent: old `/ex` metadata is retained, and an existing custom or empty `/ctp` description -is preserved. - -## Azure OpenAI Sample - -[`config/aoai.json`](../config/aoai.json) provides controlled Azure OpenAI backend outcomes for the APIM inference-failover response-handling matrix. Every route accepts `POST` with an optional request body. Supplied non-empty JSON requests must pass the global syntax checks above; request field values and ordinary headers do not select responses because matching uses only the HTTP method and exact path. +## Loading Sample Files + +The repository supplies native configuration documents for +[Trailhead Azure OpenAI-style assistant](../config/trailhead-aoai.json), +[Trailhead inventory](../config/trailhead-inventory.json), and +[Trailhead shipping](../config/trailhead-shipping.json). + +All three files are copied into the container build stage and embedded unchanged in the application. +They are not installed as loose runtime configuration files, and embedding does not activate them +or initialize persisted data. + +Import a selected file through the dashboard to replace the complete active configuration, or +copy it to a writable instance-data directory and set `MockApi__ConfigurationPath` to that copy +before startup. Set `MockApi__AllowEmptyConfiguration=false` to fail startup if the copy is missing. +Container deployments can supply the copy through their configuration volume. Follow the +[local startup instructions](../README.md#22-run-directly-with-net), replacing the source sample +filename as needed. API-key protection remains enabled by default and is configured separately. + +The dashboard's **Load examples** action combines all three files as one validated 41-endpoint example. +Individual files can still be imported independently. Native import replaces rather than merges +configuration; none of these files automatically seeds a fresh instance merely by filename. + +## Trailhead Supply Examples + +Trailhead Supply is a fictional company with three cohesive API samples: +[AI assistant](../config/trailhead-aoai.json), +[inventory](../config/trailhead-inventory.json) and +[shipping](../config/trailhead-shipping.json). Their 41 endpoint definitions are the single source +for **Load examples**, which composes all three embedded documents without duplicating their content +or changing endpoint IDs. Individual files remain useful for smaller, focused fixtures. + +The examples contain fixed assistant completions, stock snapshots, reservations, shipping quotes, shipment and tracking lookups, +a demonstration label, and clearly labeled HTTP and transport faults. All business data is static: +creation and cancellation do not store records, adjust stock, book carriers, or move parcels. +Advertised resource links resolve to configured GET endpoints. See the route tables below. + +Each API has one HEAD-only health endpoint: `/aoai/health`, `/inventory/health`, and `/shipping/health`. +They return a fixed `200 OK` with sample headers, no content type, and no body; GET is not configured. +Inspection endpoints use GET only; HEAD on those paths returns `404`. +These are mock routes subject to instance API-key protection, not live dependency checks or substitutes +for the public application probes under `/health/`. + +Built-in loading remains an explicit, revision-protected merge. It adds missing endpoints and API +descriptions, preserves custom or deliberately empty descriptions, and requires conflict review +before a forced update. Repeated loading is a no-op. Existing saved endpoints are never automatically +removed or rewritten when the application is upgraded. + +There is no endpoint-count limit, so the 41 Trailhead endpoints can coexist with unrelated endpoints. +The complete candidate must still fit the 4 MiB UTF-8 document-size limit and pass all other validation. +An invalid or oversized candidate is rejected without changing the active configuration or discarding +unrelated endpoints. Sample filenames are independent of the persisted instance +filename, which remains `mockapi.json` by default. + +## Trailhead Azure OpenAI Sample + +[`config/trailhead-aoai.json`](../config/trailhead-aoai.json) models the fictional Trailhead Supply +AI assistant and preserves the Azure OpenAI-style backend outcomes used by the APIM inference-failover +response-handling matrix. Its success response describes the Trail flask stock and sample shipment +from the inventory and shipping fixtures. These are fixed snapshots: no model runs, no business APIs +are queried, and no conversation is stored. The model name, completion ID, and token usage are +illustrative, not a real deployment or measured usage. + +The filename, names, and descriptions are Trailhead-specific; existing `/aoai/*` routes, endpoint IDs, +status codes, error envelopes, and scenario headers remain stable. This is a separate 16-endpoint +configuration when imported alone: 15 inference scenarios and one HEAD-only health mock. +**Load examples** merges these 16 endpoints with inventory and shipping for 41 total. + +Every inference route accepts `POST` with an optional request body. Supplied non-empty JSON requests must pass +the global syntax checks above; prompt text, request field values, query strings, and ordinary headers +do not select responses because matching uses only the HTTP method and exact path. For example, +send this body to `/aoai/200/chat/completions`: + +```json +{ + "messages": [ + { + "role": "user", + "content": "How many Trail flasks are available, and what is the status of shipment shp-demo-001?" + } + ] +} +``` + +Changing the prompt does not change the configured answer. The timeout routes return explicit HTTP +statuses without waiting; the 429 route always returns capacity exhaustion rather than counting requests. +Custom 499 represents an already-transformed PTU policy outcome, not a standard Azure OpenAI response. | Route | Backend outcome | | ------------------------------------------ | ---------------------------------------- | +| `/aoai/health` | HEAD-only health mock; empty `200 OK` | | `/aoai/200/chat/completions` | Successful chat-completions response | | `/aoai/400/chat/completions` | Invalid request | | `/aoai/401/chat/completions` | Backend authentication failure | @@ -296,3 +310,61 @@ is preserved. For a recovery test, configure one APIM pool member to use a fault route and a later member to use the `200` route. For an exhausted-chain test, configure every eligible member to use the fault under test. MockAPI returns the selected backend outcome; APIM owns retry counts, circuit breaking, backend selection, caller-visible normalization, and response headers such as `X-Backend-Retry`. The transport-failure route approximates a backend connection failure by accepting the request and then aborting the connection. It does not reproduce DNS resolution failure, TLS certificate failure, a forwarding timeout caused by a delayed origin, or a caller disconnect. Those cases require the network-level fault origins described by the inference-failover sample. + +## Inventory Sample + +[`config/trailhead-inventory.json`](../config/trailhead-inventory.json) contains eleven endpoint definitions for the +fictional Trailhead Supply inventory API. SKU-1001 is a trail flask with 30 units on hand, six +reserved, and 24 available; SKU-1002 is an existing day pack with zero stock. The sample +distinguishes an out-of-stock `200` response from an explicitly configured missing-SKU `404`. + +| Method | Route | Behavior | +| ------ | ---------------------------------------------- | ------------------------------------------------------- | +| HEAD | `/inventory/health` | Fixed `200 OK`, no body | +| GET | `/inventory/items` | Two products with available quantities and detail links | +| GET | `/inventory/items/SKU-1001` | In-stock snapshot | +| GET | `/inventory/items/SKU-1002` | Out-of-stock snapshot | +| GET | `/inventory/items/unknown` | `404` problem response for this literal path | +| POST | `/inventory/reservations` | `201`, fixed reservation, and resolvable `Location` | +| GET | `/inventory/reservations/res-demo-001` | Fixed reservation lookup | +| DELETE | `/inventory/reservations/res-demo-001` | `204`, no body | +| POST | `/inventory/demo-faults/insufficient-stock` | `409` problem response | +| POST | `/inventory/demo-faults/invalid-reservation` | `422` problem response with a quantity error | +| GET | `/inventory/demo-faults/warehouse-unavailable` | `503` problem response, `Retry-After: 30` | + +Reservation creation and cancellation do not change stock or lookup responses. The lookup +exists before creation and remains available after cancellation. Request bodies are optional; +supplied non-empty JSON is syntax-checked, but fields do not select a SKU, quantity, or outcome. +Use the explicit fault paths to test business errors. The warehouse outage does not recover +automatically after its suggested retry interval. + +## Shipping Sample + +[`config/trailhead-shipping.json`](../config/trailhead-shipping.json) contains fourteen endpoint definitions for a +fictional Trailhead Supply shipping API. It provides fixed standard and express quotes, a +label-created shipment, a separate delivered tracking scenario, and a text-only demonstration +label without customer addresses or valid postage. + +| Method | Route | Behavior | +| ------ | -------------------------------------------- | ------------------------------------------------------------------------------ | +| HEAD | `/shipping/health` | Fixed `200 OK`, no body | +| GET | `/shipping/rates` | Fixed standard and express quotes in USD | +| POST | `/shipping/shipments` | `201`, shipment details, and resolvable `Location` | +| GET | `/shipping/shipments/shp-demo-001` | Fixed shipment | +| GET | `/shipping/tracking/TRACK-DEMO-001` | Fixed label-created tracking history | +| GET | `/shipping/tracking/TRACK-DEMO-DELIVERED` | Separate fixed delivered tracking history | +| GET | `/shipping/shipments/shp-demo-001/label.txt` | Text attachment marked not valid for shipment | +| DELETE | `/shipping/shipments/shp-demo-001` | `204`, no body | +| POST | `/shipping/demo-faults/invalid-shipment` | `422` problem response with a parcel-weight error | +| POST | `/shipping/demo-faults/service-unavailable` | `503` problem response, `Retry-After: 15` | +| GET | `/shipping/tracking/unknown` | `404` problem response for this literal path | +| GET | `/shipping/demo-faults/tracking-rate-limit` | Two `200` responses per rolling ten seconds, then `429` with `Retry-After: 10` | +| GET | `/shipping/demo-faults/carrier-timeout` | One-second delay, then an explicit HTTP `504` problem response | +| GET | `/shipping/demo-faults/connection-failure` | Accepted connection aborted without an HTTP response | + +Creation and cancellation do not store or modify shipments, tracking history, or labels. +Request bodies are optional; supplied non-empty JSON is syntax-checked without inspecting +parcel or address fields. Query strings never select a service, rate, or tracking number. +The dashboard preselects three requests for the rate-limit scenario. Its counters are +process-local; the tracking snapshot is static. The delayed `504` is an HTTP response, not +a client-side timeout. The connection fault does not reproduce DNS or TLS failures. diff --git a/docs/DEVELOPMENT.md b/docs/DEVELOPMENT.md index 5dec65f..e1f62ca 100644 --- a/docs/DEVELOPMENT.md +++ b/docs/DEVELOPMENT.md @@ -28,7 +28,7 @@ forwarding and notification; GitHub's private default and your visibility settin Do not change it to Public without intentionally configuring application authentication and HTTPS. Select **Load examples**, configure administrator credentials, and generate a key in **Settings > Mock API -security** before testing `/ctp/parks`. Dashboard tests attach the memory-only key automatically; external +security** before testing `/inventory/items`. Dashboard tests attach the memory-only key automatically; external requests require `X-MockAPI-Key`. Edit a response; changes are saved automatically. Use **Retry save** if persistence fails. See [Mock API keys](OPERATIONS.md#mock-api-keys) for bootstrap and persistence. @@ -68,8 +68,10 @@ Scanner execution failures and invalid reports still fail validation. This policy does not remediate vulnerabilities or change container-image scanning. The [development-container workflow](../.github/workflows/devcontainer.yml) exercises the exact image, -non-root setup, tooling, and application readiness. A real Codespaces launch still needs account-level -validation. No production credentials, Docker socket, or Azure login is needed for ordinary development. +non-root setup, tooling, and application readiness. The readiness probe retries transient connection +resets and unavailable responses during startup, with a five-second per-attempt timeout and a +two-minute retry window. A real Codespaces launch still needs account-level validation. +No production credentials, Docker socket, or Azure login is needed for ordinary development. ## Maintenance and boundaries @@ -79,6 +81,8 @@ validation. No production credentials, Docker socket, or Azure login is needed f - The image supports Linux AMD64 and ARM64. Its SDK follows `global.json`; no extra SDK pin is introduced. - Setup uses `pnpm install --frozen-lockfile` and the CLI's `restore` action rather than the full `setup` action, which also checks for a local container engine. +- Keep `start.sh` tracked with Git mode `100755` (executable). Post-create setup and the smoke + workflow invoke it directly; mode `100644` causes `Permission denied` in Linux checkouts. - A local Dev Containers forwarded port binds locally; Codespaces is private by default. Neither replaces the application's authentication requirements for a shared deployment. - Container release builds remain on matching native CI runners. This workspace does not prove diff --git a/docs/MANAGEMENT_API.md b/docs/MANAGEMENT_API.md index d69171b..41b8112 100644 --- a/docs/MANAGEMENT_API.md +++ b/docs/MANAGEMENT_API.md @@ -78,7 +78,7 @@ Both export routes accept repeated `endpointId` query parameters containing stab artifact to those endpoints. The dashboard applies the same rule: Export includes every endpoint when the selection is empty and only the selected endpoints otherwise. -API description edits accept `{"path":"/ctp","description":"Contoso Theme Parks overview"}` and require the +API description edits accept `{"path":"/inventory","description":"Trailhead Supply inventory overview"}` and require the editor's captured strong `If-Match` ETag. Both properties are required strings; an empty description clears its displayed text. Success returns `200` with the complete configuration status, including `apiDescriptions`. Invalid metadata returns `422` without changing any endpoints or descriptions. @@ -129,6 +129,13 @@ proxies must not cache authenticated dashboard assets. Statistics-only updates preserve endpoint row controls and focus unless the selected sort changes row order. Collapsed panels and inactive statistics views are rendered when shown. +The Endpoints table offers **Collapse all groups**, switching to **Expand all groups** when all API +groups in the current filtered result are collapsed. With a mixture of expanded and collapsed groups, +the action collapses them all. Groups hidden by filters retain their state; new API groups start +expanded. The control is disabled when there are no matching groups. Individual group controls remain +available, and endpoint selection, sorting, configuration, and persistence are unchanged. +Group collapse state lasts for the current page, independently of the saved whole-panel collapse preference. + The request log offers **Collapse all buckets**, switching to **Expand all buckets** when all current buckets are collapsed. New minute buckets start expanded; additional requests in an existing bucket retain its state. Table columns use stable widths and reserved scrollbar space, @@ -200,6 +207,15 @@ MOCKAPI_CONFIGURATION_READ_DIAGNOSTICS=1 DOTNET_TieredCompilation=0 \ ## Built-In Merge Results +The example combines [Trailhead AOAI](../config/trailhead-aoai.json), +[Trailhead inventory](../config/trailhead-inventory.json), and +[Trailhead shipping](../config/trailhead-shipping.json): 41 definitions across three API groups. +It does not automatically replace saved configurations. There is no endpoint-count limit for +configuration or bulk selections. The complete candidate must still fit the 4 MiB UTF-8 document-size +limit; an oversized merge returns `422` without changing the active configuration, even when forced. +Bulk selections must be non-empty, unique, and reference existing endpoints; management request bodies +remain limited to 4 MiB. + A successful merge reports `added`, `updated`, `skipped`, the resulting revision, and whether a change was applied. Repeating the same merge is an idempotent `200` response with no revision increment. Missing API descriptions are added atomically with the endpoints. Existing custom or empty descriptions @@ -257,7 +273,7 @@ In the Azure portal: 3. For authenticated or private deployments, download the document from a trusted machine with access and upload the file instead. Keep Basic credentials out of URLs, source control, and command history; do not disable administrative authentication for import. 4. Set **Web service URL** to `https://`, without the export route or APIM API suffix. The generated document currently uses `http://localhost:8080` in `servers`; APIM requires the actual backend URL to be supplied explicitly. 5. Choose an API URL suffix such as `mockapi`, create the API, and verify its operations and backend setting. -6. Call an imported operation through the gateway, for example `https:///mockapi/ctp/parks`. Supply a subscription key if required by APIM. The gateway must have network access to the MockAPI backend independently of how the specification was imported. +6. Call an imported operation through the gateway, for example `https:///mockapi/inventory/items`. Supply a subscription key if required by APIM. The gateway must have network access to the MockAPI backend independently of how the specification was imported. For a protected export, these examples prompt for credentials rather than putting the password in the command. Replace the host placeholder and keep the downloaded artifact outside source control. diff --git a/docs/OPERATIONS.md b/docs/OPERATIONS.md index 5bf649a..4d2ffd5 100644 --- a/docs/OPERATIONS.md +++ b/docs/OPERATIONS.md @@ -25,6 +25,27 @@ connection aborts, rate limiting, or mock statistics. Administrative credentials 4. Supply `X-MockAPI-Key` on external mock calls. Dashboard tests automatically use the key held in memory. After a reload, enter the existing key in Settings or generate a replacement. +For fully automatic deployment, supply `MockApi__ApiKey` through a container secret instead of generating a +key in the dashboard. Use a cryptographically random value containing 32-256 ASCII letters, digits, hyphens, +or underscores (for example, 32 random bytes encoded as unpadded Base64url). Keys are case-sensitive. +Invalid non-empty values fail startup without including the value in the error. + +On first startup, if the security file or blob does not exist, MockAPI persists the supplied key's SHA-256 +hash and enables protection before accepting requests, even when `MockApi__RequireApiKey=false`. +Persistence failure fails startup; the key is never activated without a successful save. +Existing security settings always take precedence: changing the container value does not replace a saved +key, undo rotation, or re-enable disabled protection. Malformed or inaccessible security settings fail startup +rather than being replaced. An absent or empty deployment key preserves the existing dashboard setup flow. +If the security document is lost while the deployment key remains configured, the next startup seeds it again. +Retain the security document and coordinate any later rotation with callers. + +The [Bicep entry point](../infra/main.bicep) accepts the optional secure `mockApiKey` parameter. +The [Container Apps module](../infra/resources.bicep) stores it as a Container Apps secret and references that +secret from `MockApi__ApiKey`; it never emits the value in deployment outputs. An external IaC deployment, +such as APIM Samples, can pass its shared secret into this parameter and configure its caller to send the same +value in `X-MockAPI-Key`. This requires no dashboard interaction. APIM policy and Named Value provisioning +remain the responsibility of the calling deployment. + Settings separates instance-wide **Request protection** from the memory-only **Dashboard test key**. Changing the **Require X-MockAPI-Key on mock requests** checkbox automatically saves the protection setting on the server for all callers, including after a restart. Disabling protection still requires confirmation; @@ -75,7 +96,8 @@ the test blade open when it dismisses a visible popover. Tapping an icon also op The hash and enforcement setting are saved in `.security.json`, or in a sibling `.security.json` when Blob persistence is configured. Retain this document with the configuration volume or private Blob container. Endpoint import/export/save never changes it. Losing this -document restores the fail-closed default; generate a replacement key as an administrator. +document restores the fail-closed default unless a deployment key seeds it again; otherwise generate a +replacement key as an administrator. For a deliberately unauthenticated local fixture, set `MockApi__RequireApiKey=false` before the first security document is saved. Persisted security settings take precedence over this bootstrap setting. Operators can also @@ -116,7 +138,7 @@ text in light and dark themes. `DROP` uses a neutral badge for connection aborts uses system highlight colors. The displayed code remains readable without relying on color alone. Path appears immediately after the selection checkbox, before the information button and operation -name. It omits the API group prefix: `/ctp/parks` appears as `/parks` under `ctp/`, and `/ctp` appears +name. It omits the API group prefix: `/inventory/items` appears as `/items` under `inventory/`, and `/inventory` appears as `/`. Hovering the path shows its full configured value. Editing, filtering, exports, and endpoint tests continue to use the full path; the shorter display does not change routing. @@ -160,10 +182,18 @@ AZURE_CUSTOM_DOMAIN= AZURE_CUSTOM_DOMAIN_VALIDATION_METHOD=CNAME AZURE_DASHBOARD_USERNAME= AZURE_DASHBOARD_PASSWORD= +AZURE_MOCKAPI_KEY= ``` Set both dashboard values to enable Basic authentication, or leave both empty to deploy the dashboard and management API without authentication. The password must contain at least 8 characters. `start.ps1` derives the PBKDF2-SHA256 password hash locally and sends only the username and hash to azd; plaintext is confined to the ignored `.env` or process environment. Partial credentials fail preflight. +Optionally set `AZURE_MOCKAPI_KEY` in the ignored `.env` or process environment to seed mock authorization +automatically. Both developer CLIs validate and synchronize it to azd, which passes it to the secure +`mockApiKey` Bicep parameter. The deployment key is retained in local azd environment state and as a Container +Apps secret, while MockAPI's separate security document contains only its hash. Protect `.env` and `.azure` +as secret-bearing local state. Leaving the value blank does not disable protection or erase a saved key. +See [Mock API keys](#mock-api-keys) for the initial-setup-only precedence and rotation behavior. + Run `./start.ps1 -Action azure-setup -InstallMissing` to install or verify Azure Developer CLI 1.27.1 or newer and Azure CLI through WinGet. This action does not authenticate or configure an environment. Then run `./start.ps1 -Action azure-check`; it verifies the cached login status, starts interactive login when needed, synchronizes the named azd environment, parses the Docker service, and builds Bicep locally. The local `check` and `setup` actions remain independent of Azure tooling. Azure preflight prints the environment, subscription, location, and resource group before deployment. The resource group is `rg--`, matching the infrastructure parameters and using the effective settings after process-environment overrides. Both `./start.ps1 -Action azure-check` and `./start.sh --action azure-check`, as well as the deployment actions that run preflight, show this target. diff --git a/docs/PLAN.md b/docs/PLAN.md index c2c30d8..b9d5f57 100644 --- a/docs/PLAN.md +++ b/docs/PLAN.md @@ -115,7 +115,17 @@ Avoid a separate Node.js runtime or frontend server. A small static dashboard ke ## 6. Configuration Contract -The future configuration asset should be `config/mockapi.json`, with its JSON Schema in `schemas/mockapi.schema.json`. The schema should use JSON Schema Draft 2020-12 and the configuration should reference it through `$schema`. +The checked-in Trailhead Supply samples are `config/trailhead-aoai.json`, +`config/trailhead-inventory.json`, and `config/trailhead-shipping.json`, with their JSON Schema in +`schemas/mockapi.schema.json`. Copy all three into the container build stage and embed them unchanged +in the application. Compose the built-in **Load examples** configuration from all three documents, +without duplicating definitions: 41 endpoints across `/aoai`, `/inventory`, and `/shipping`. Each sample API +has one HEAD-only `//health` mock returning an empty 200; inspection calls use GET only. +These static health mocks retain instance API-key protection and do not replace public `/health/` probes. +Embedding a sample does +not activate it or seed persisted configuration. Sample filenames are independent of the persisted +instance filename, which remains `mockapi.json` by default. The schema should use JSON Schema Draft +2020-12 and the configuration should reference it through `$schema`. ### Document shape @@ -125,7 +135,7 @@ The future configuration asset should be `config/mockapi.json`, with its JSON Sc "schemaVersion": "1.0", "endpoints": [ { - "id": "7b2d425d-75f1-4ded-a74e-503374a7e99e", + "id": "e7e08d5e-76a2-4f80-9a64-4e772ff6d907", "name": "Rate limited response", "enabled": true, "methods": ["GET"], @@ -149,7 +159,7 @@ The future configuration asset should be `config/mockapi.json`, with its JSON Sc ### Schema constraints - `schemaVersion` and `endpoints` are required. -- - Optional `apiDescriptions` maps case-sensitive first-segment paths (for example, `/ctp`) to +- - Optional `apiDescriptions` maps case-sensitive first-segment paths (for example, `/inventory`) to freeform descriptions of at most 4,000 characters. Limit metadata to 25 groups and keys to 2,048 characters; keys use `/` or one absolute segment without whitespace, controls, query/fragment delimiters, or backslashes. Reserved management and health group names are rejected. @@ -161,6 +171,10 @@ The future configuration asset should be `config/mockapi.json`, with its JSON Sc - `id` is a UUID and remains stable across edits/import/export. - `name` is non-empty and limited to 200 characters. - `description` is optional freeform text limited to 4,000 characters. +- Trailhead sample descriptions use two labeled plain-text sections in that existing field: + `Description:` followed by `Technical implementation:`, separated by a blank line. + Render those standalone heading lines in bold in information previews, without interpreting HTML or Markdown. + Keep the business scenario above the mock behavior and limitations; custom descriptions remain freeform. - `methods` is a non-empty unique array of at most 8 valid HTTP method tokens. - `path` is limited to 2,048 characters, starts with `/`, and cannot target a reserved route. - `requestCount` is optional, defaults to 1 in the dashboard test blade, and accepts integers from 1 through 5. @@ -172,7 +186,7 @@ The future configuration asset should be `config/mockapi.json`, with its JSON Sc - Reject controlled or hop-by-hop headers, including `Connection`, `Content-Length`, `Date`, `Host`, `Server`, `Transfer-Encoding`, and `Upgrade`. The server owns protocol framing and default headers. - `contentType` is optional but required by validation when a non-empty body is present unless a documented default is applied. - `body` is a raw string limited to 1 MiB when UTF-8 encoded. JSON payloads are stored as JSON text so exact response bytes and invalid-JSON test cases remain possible. -- Limit a configuration document to 4 MiB when UTF-8 encoded and 25 endpoint definitions. +- Limit a configuration document to 4 MiB when UTF-8 encoded, without an endpoint-count limit. - Limit each endpoint to 64 configured response headers, each individual header value to 8 KiB when UTF-8 encoded, and all configured header names and values for an endpoint to 32 KiB when UTF-8 encoded. - Reject oversized management requests before parsing where possible, and enforce the same limits during startup loading, validation, import, runtime editing, export, and save so no path can activate an invalid document. @@ -298,11 +312,11 @@ at 220px and align the collapse control with the first filter row when filters w opens on hover and keyboard focus, closes when the pointer leaves the button (including for the preview itself), and dismisses with Escape. Activating the button opens a keyboard-accessible editor with the captured revision; stale writes cannot overwrite live edits. -- The built-in `/ctp` API description spells out **Contoso Theme Parks** and introduces a cohesive - fictional park visit with static attraction, reservation, and wait-time fixtures. Clearly labeled - `/ctp/demo-faults/` routes preserve HTTP and transport-failure demonstrations. Retain the original - seven example IDs and add resolvable attraction and reservation lookups; existing configurations - migrate through the normal conflict-preview and explicit-force merge, not a silent rewrite. +- The built-in Trailhead Supply example composes the `/aoai`, `/inventory`, and `/shipping` APIs from their + checked-in native documents. Descriptions explain static assistant answers, stock, reservations, shipping, and tracking; + clearly labeled demo-faults routes cover HTTP and transport failures. Preserve stable endpoint IDs + and resolvable resource links. Merge changes only after normal revision and conflict checks, never + rewrite or delete existing saved endpoints automatically. - Keep description drafts independent of live updates, restore focus after editing, and cover save/reload, native import/export, metadata preservation, merge defaults, stale writes, and accessible editing. - Dense endpoint table with name, methods, path, status, enabled state, request count, and actions. @@ -311,6 +325,10 @@ at 220px and align the collapse control with the first filter row when filters w - Show every filtered endpoint without paging in a vertically scrollable table with sticky headers. Keep API groups alphabetical and default operations to ascending path order within each group. Header clicks sort operations within expanded groups, never reorder API groups. +- Offer **Collapse all groups** above the endpoint table, switching to **Expand all groups** when all + filtered API groups are collapsed. Apply it only to the current filtered groups, preserving hidden + groups' state and endpoint selection. Keep individual toggles, start new groups expanded, and disable + the bulk group control when no groups match. Collapse state is page-local and never changes configuration. - Display each supported HTTP method in its own bordered badge to keep adjacent method names visually distinct. - Show endpoint descriptions behind the same information button before each endpoint name, not inline. Preserve original casing and whitespace in both previews; treat all preview content as inert text. @@ -324,6 +342,9 @@ at 220px and align the collapse control with the first filter row when filters w - Create/edit form with a response/connection-abort behavior selector, optional delay, header rows, status code, reason phrase caveat, content type, and a payload editor. - Enable/disable toggle, edit action, delete confirmation, and endpoint duplication. - Stable-ID row selection with select-all for the current filtered result set and bulk enable, disable, and confirmed delete actions. +- Provide a select-all checkbox in each API group header for that API's filtered endpoints, including + when collapsed. Show a mixed state for partial selection, preserve selections in other APIs and + endpoints hidden by filters, and keep group, row, and table-wide selection states synchronized. - Filters for name, method, path, status, and enabled state. - Immediate validation with server-authoritative errors. The dashboard prevents applying a non-empty malformed response body when its content type identifies JSON, while direct configuration retains raw-body semantics. @@ -415,6 +436,13 @@ The initial ARM64 experiment measured 26.83 MB for Alpine CoreCLR and 27.11 MB f - Generate 32-byte random keys, compare SHA-256 hashes in constant time, and keep only the hash in a separate security document beside the configuration file or blob. Persist before atomic activation; use an independent strong ETag for security writes. Rotation enables protection and immediately revokes the previous key. +- Support fully automatic initial key setup through the optional secret-backed `MockApi__ApiKey` setting + and secure `mockApiKey` Bicep parameter (`AZURE_MOCKAPI_KEY` in both developer CLIs). Accept 32-256 ASCII + letters, digits, hyphens, or underscores. If no security document exists, persist only the supplied key's + SHA-256 hash and enable protection before serving requests. Existing security settings always win, + including rotations and disabled enforcement; never overwrite malformed or inaccessible settings. + Invalid keys or failed persistence fail startup without exposing the secret. Empty values preserve + the existing setup flow. Do not provision external APIM policies or Named Values as part of this contract. - Keep dashboard keys in memory only and send them only to same-origin mock tests, rejecting redirects. Request exports include header variables or OpenAPI security requirements, never the secret or hash. Endpoint configuration import/export/save never reads or changes security settings. @@ -518,7 +546,7 @@ The initial ARM64 experiment measured 26.83 MB for Alpine CoreCLR and 27.11 MB f ### Developer CLI example showcase -- Add a dedicated developer CLI action and interactive-menu entry that exercises the running built-in example at `/ctp/attractions/cloud-cruiser/wait-times`; keep the existing container smoke test fast and separate. +- Add a dedicated developer CLI action and interactive-menu entry that exercises the running built-in example at `/shipping/demo-faults/tracking-rate-limit`; keep the existing container smoke test fast and separate. - Do not silently import or replace the active configuration. Detect when the example endpoint is unavailable and explain how to load the built-in example from the dashboard before rerunning the showcase. - Treat the expected HTTP `429` response as a successful assertion rather than a native-command failure. - Verify the HTTP/1.1 reason phrase, `Retry-After: 10`, both `X-Mock-Source` values, JSON content type, and exact `{"error":"wait_times_rate_limited","message":"Take a little breather! Check back in 10 seconds."}` response body. @@ -638,7 +666,7 @@ The initial ARM64 experiment measured 26.83 MB for Alpine CoreCLR and 27.11 MB f - [x] One multi-platform image index provides functionally equivalent `linux/amd64` and `linux/arm64` images. - [x] The application passes local native container checks with a `0.5` CPU and `256 MiB` limit; deployment examples start with a `0.25` CPU and `128 MiB` request. - [x] The root filesystem can be read-only with `/data` as the sole writable application mount. -- [x] The developer CLI can non-destructively showcase the loaded `/ctp/attractions/cloud-cruiser/wait-times` example by verifying its status, reason phrase, repeated headers, content type, exact body, query-insensitive matching, negative `404` cases, and statistics deltas with clear pass/fail output. +- [x] The developer CLI can non-destructively showcase the loaded `/shipping/demo-faults/tracking-rate-limit` example by verifying its status, reason phrase, repeated headers, content type, exact body, query-insensitive matching, negative `404` cases, and statistics deltas with clear pass/fail output. - [x] Dependabot covers NuGet, Docker, and GitHub Actions, with an eight-day cooldown applied to every update ecosystem. - [x] Local and CI dependency validation enforces an eight-day minimum release age for NuGet, Docker, GitHub Actions, and frontend/Playwright packages, with only explicit version-scoped, expiring emergency exceptions. - [x] GitHub pull-request automation builds and tests containers without registry credentials. @@ -663,7 +691,7 @@ The initial ARM64 experiment measured 26.83 MB for Alpine CoreCLR and 27.11 MB f - Ship both `linux/amd64` and `linux/arm64` images under one multi-platform image index. - Use WSLC as the local container CLI; perform unsupported cross-platform, image-index, read-only-root, SBOM, and vulnerability checks in CI. - Start deployment guidance at a `0.25` CPU and `128 MiB` memory request with a `0.5` CPU and `256 MiB` memory limit, then tune only from measured runtime evidence. -- Limit configuration documents to 4 MiB and 25 endpoints; each endpoint permits a 200-character name, at most 8 methods, a 2,048-character path, a 1 MiB UTF-8 response body, 64 response headers, 8 KiB per UTF-8 header value, and 32 KiB of combined UTF-8 header names and values. +- Limit configuration documents to 4 MiB with no endpoint-count limit; each endpoint permits a 200-character name, at most 8 methods, a 2,048-character path, a 1 MiB UTF-8 response body, 64 response headers, 8 KiB per UTF-8 header value, and 32 KiB of combined UTF-8 header names and values. - Retain recent-rate statistics in 60 one-minute buckets for a 60-minute rolling window. - Assign workflow-created or workflow-reused issues to `simonkurtz-MSFT`; do not use the personal `simonua` handle for this repository. - Require every newly selected dependency version to be at least seven complete days old in local and CI workflows; exceptions must be security- or build-blocker-specific, reviewed, version-scoped, and temporary. diff --git a/docs/RELEASING.md b/docs/RELEASING.md index 023bdf9..9fadd73 100644 --- a/docs/RELEASING.md +++ b/docs/RELEASING.md @@ -117,7 +117,8 @@ IDs and configuration documents remain compatible; no migration is required. The release date was **2026-10-13**, with the immutable tag **`1.4.3`**. The [1.4.3 changelog entry](../CHANGELOG.md#143---2026-10-13) supplies the GitHub release notes. -- The Contoso Theme Parks example configuration has additional endpoints and clearer descriptions. +- The built-in example configuration gained additional endpoints and clearer descriptions. + That sample has since been replaced by Trailhead Supply. - Dashboard layout and endpoint testing interactions are refined. ### Compatibility and upgrade behavior diff --git a/docs/TROUBLESHOOTING.md b/docs/TROUBLESHOOTING.md index 627c780..7fc9ec1 100644 --- a/docs/TROUBLESHOOTING.md +++ b/docs/TROUBLESHOOTING.md @@ -19,6 +19,12 @@ not undo the change, so do not repeat the original mutation. Containers must mou An identical example is skipped, so repeated loading may correctly report no changes. A changed stable ID or method/path collision returns a conflict preview and makes no changes. Review the named endpoints and choose **Force update** only when the checked-in built-in version should win. Unrelated endpoints are preserved. +The Trailhead AOAI, inventory, and shipping example contains 41 endpoint definitions. There is no +endpoint-count limit, but a merged configuration that exceeds 4 MiB when UTF-8 encoded returns `422`; +force does not bypass size or other validation. Review the returned errors and export a backup before +reducing oversized response bodies or importing a selected sample file. +The rejected merge leaves the complete active configuration unchanged. + ## Endpoint Returns 404 Check that the endpoint is enabled and that the HTTP method and path match exactly. Paths are case-sensitive; query strings do not affect matching. Runtime-defined routes cannot use `/`, `/__mockapi`, `/health`, or application-owned descendants. @@ -37,8 +43,8 @@ HTTP reason phrases are transmitted only by HTTP/1.1. HTTP/2 and HTTP/3 omit the The local container is recreated when the `mockapi:dev` image ID changes. The named data volume is retained. WSLC `2.9.3.0` may warn that swap cannot be limited separately; the configured memory limit remains active. -The example showcase tests `/ctp/attractions/cloud-cruiser/wait-times`. If older examples or local edits -conflict with the built-in Contoso Theme Parks configuration, review **Load examples** in the dashboard, +The example showcase tests `/shipping/demo-faults/tracking-rate-limit`. If older examples or local edits +conflict with the built-in Trailhead Supply configuration, review **Load examples** in the dashboard, confirm the desired updates, and rerun: ```powershell diff --git a/docs/images/01-dashboard-overview.png b/docs/images/01-dashboard-overview.png index 9e7d9f2..fa7d6a4 100644 Binary files a/docs/images/01-dashboard-overview.png and b/docs/images/01-dashboard-overview.png differ diff --git a/docs/images/02-endpoints.png b/docs/images/02-endpoints.png index a2184e5..cdbf22b 100644 Binary files a/docs/images/02-endpoints.png and b/docs/images/02-endpoints.png differ diff --git a/docs/images/03-endpoint-editor.png b/docs/images/03-endpoint-editor.png index 2eccfc3..6d73013 100644 Binary files a/docs/images/03-endpoint-editor.png and b/docs/images/03-endpoint-editor.png differ diff --git a/docs/images/04-endpoint-test.png b/docs/images/04-endpoint-test.png index d816c5e..1f8e492 100644 Binary files a/docs/images/04-endpoint-test.png and b/docs/images/04-endpoint-test.png differ diff --git a/docs/images/05-statistics.png b/docs/images/05-statistics.png index 7122bd9..3b016ff 100644 Binary files a/docs/images/05-statistics.png and b/docs/images/05-statistics.png differ diff --git a/docs/images/06-how-it-works.png b/docs/images/06-how-it-works.png index 07442d6..8d505fe 100644 Binary files a/docs/images/06-how-it-works.png and b/docs/images/06-how-it-works.png differ diff --git a/docs/images/07-export-formats.png b/docs/images/07-export-formats.png index ff3e7ee..3d64ae8 100644 Binary files a/docs/images/07-export-formats.png and b/docs/images/07-export-formats.png differ diff --git a/docs/images/site-dashboard-endpoints.webp b/docs/images/site-dashboard-endpoints.webp index 2574b02..18ed9cc 100644 Binary files a/docs/images/site-dashboard-endpoints.webp and b/docs/images/site-dashboard-endpoints.webp differ diff --git a/docs/images/site-dashboard-overview.png b/docs/images/site-dashboard-overview.png index c491411..fa7d6a4 100644 Binary files a/docs/images/site-dashboard-overview.png and b/docs/images/site-dashboard-overview.png differ diff --git a/docs/images/site-dashboard-overview.webp b/docs/images/site-dashboard-overview.webp index f7660d6..9fd466a 100644 Binary files a/docs/images/site-dashboard-overview.webp and b/docs/images/site-dashboard-overview.webp differ diff --git a/docs/images/site-dashboard-request-log.webp b/docs/images/site-dashboard-request-log.webp index 40f7ed2..9025991 100644 Binary files a/docs/images/site-dashboard-request-log.webp and b/docs/images/site-dashboard-request-log.webp differ diff --git a/infra/main.bicep b/infra/main.bicep index 851dd6a..97ea2d3 100644 --- a/infra/main.bicep +++ b/infra/main.bicep @@ -23,6 +23,11 @@ param dashboardUsername string = '' @description('Optional locally derived dashboard password hash. Leave empty with dashboardUsername to disable authentication.') param dashboardPasswordHash string = '' +@secure() +@maxLength(256) +@description('Optional initial mock API key (32-256 ASCII letters, digits, hyphens, or underscores). Used only when no persisted security settings exist.') +param mockApiKey string = '' + @description('Existing ingress domain bindings preserved by the developer CLI before reprovisioning. New managed certificates are bound after deployment and DNS validation.') param customDomains array = [] @@ -48,6 +53,7 @@ module resources 'resources.bicep' = { location: location dashboardUsername: dashboardUsername dashboardPasswordHash: dashboardPasswordHash + mockApiKey: mockApiKey customDomains: customDomains } } diff --git a/infra/main.parameters.json b/infra/main.parameters.json index 6baa72d..f80e143 100644 --- a/infra/main.parameters.json +++ b/infra/main.parameters.json @@ -17,6 +17,9 @@ "dashboardPasswordHash": { "value": "${AZURE_DASHBOARD_PASSWORD_HASH}" }, + "mockApiKey": { + "value": "${AZURE_MOCKAPI_KEY=}" + }, "customDomains": { "value": "${AZURE_CUSTOM_DOMAINS=[]}" } diff --git a/infra/resources.bicep b/infra/resources.bicep index c25096c..8649894 100644 --- a/infra/resources.bicep +++ b/infra/resources.bicep @@ -17,6 +17,11 @@ param dashboardUsername string = '' @description('Optional locally derived dashboard password hash. Leave empty with dashboardUsername to disable authentication.') param dashboardPasswordHash string = '' +@secure() +@maxLength(256) +@description('Optional initial mock API key (32-256 ASCII letters, digits, hyphens, or underscores). Existing persisted security settings take precedence.') +param mockApiKey string = '' + @description('Existing ingress domain bindings preserved before reprovisioning.') param customDomains array = [] @@ -69,6 +74,9 @@ var dashboardAuthenticationEnabled = !empty(dashboardUsername) && !empty(dashboa @description('Name of the Container Apps secret containing the dashboard password hash.') var dashboardPasswordSecretName = 'dashboard-password-hash' +@description('Name of the Container Apps secret containing the initial mock API key.') +var mockApiKeySecretName = 'mock-api-key' + @description('Subscription-scoped resource ID for the built-in AcrPull role.') var acrPullRoleDefinitionId = subscriptionResourceId( 'Microsoft.Authorization/roleDefinitions', @@ -314,12 +322,20 @@ resource containerApp 'Microsoft.App/containerApps@2024-03-01' = { environmentId: managedEnvironment.id configuration: { activeRevisionsMode: 'Single' - secrets: dashboardAuthenticationEnabled ? [ - { - name: dashboardPasswordSecretName - value: dashboardPasswordHash - } - ] : [] + secrets: [ + ...dashboardAuthenticationEnabled ? [ + { + name: dashboardPasswordSecretName + value: dashboardPasswordHash + } + ] : [] + ...!empty(mockApiKey) ? [ + { + name: mockApiKeySecretName + value: mockApiKey + } + ] : [] + ] ingress: { allowInsecure: false customDomains: customDomains @@ -389,6 +405,12 @@ resource containerApp 'Microsoft.App/containerApps@2024-03-01' = { secretRef: dashboardPasswordSecretName } ] : [] + ...!empty(mockApiKey) ? [ + { + name: 'MockApi__ApiKey' + secretRef: mockApiKeySecretName + } + ] : [] ] probes: [ { diff --git a/package.json b/package.json index 17c6646..7f2e927 100644 --- a/package.json +++ b/package.json @@ -23,15 +23,15 @@ }, "engines": { "node": ">=26", - "pnpm": "12.10.1" + "pnpm": "12.13.0" }, - "packageManager": "pnpm@12.10.1", + "packageManager": "pnpm@12.13.0", "devDependencies": { "@axe-core/playwright": "4.13.0", "@playwright/test": "1.61.1", - "@vitest/coverage-v8": "5.0.3", + "@vitest/coverage-v8": "5.0.4", "markdownlint-cli2": "0.23.3", - "prettier": "3.9.9", - "vitest": "5.0.3" + "prettier": "3.9.10", + "vitest": "5.0.4" } } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 8587f76..9e4799d 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -7,153 +7,153 @@ importers: configDependencies: {} packageManagerDependencies: pnpm: - specifier: 12.10.1 - version: 12.10.1 + specifier: 12.13.0 + version: 12.13.0 packages: - '@pnpm/exe.android-arm64@12.10.1': - resolution: {integrity: sha512-CVTlHPwNvadQCJD9bGSMzWIhFX8QpjtqC2c27dhdnn/9iKzEjZ3qL62o3gHpKbIuo6qn4WxTKRoaokgNdReBig==} + '@pnpm/exe.android-arm64@12.13.0': + resolution: {integrity: sha512-BI++xXYAk3lTLQ1695b3pAAaLwzUTQqKyT5UukVd1NU5qv7h/rUfVCiV5hrLksdbgPMWcic8gf9uXMiqTlerzg==} cpu: [arm64] os: [android] - '@pnpm/exe.android-x64@12.10.1': - resolution: {integrity: sha512-NFiYLIaodY7da0XIebwcU3JoP7IK/lzF7zgKSSP+9H+QcFnQ1GDfBkuBKCYJzZ+Xu0WH54neIPLBBCaOjaaauA==} + '@pnpm/exe.android-x64@12.13.0': + resolution: {integrity: sha512-bFq6cnbSB3fezJ0siOtuoRqLiR3VXFCZvUUFa0wlZ4a3EaJYsnnDli4ZTe8/bDfX1UhNMFxAAiSAKg7xITu+Zw==} cpu: [x64] os: [android] - '@pnpm/exe.darwin-arm64@12.10.1': - resolution: {integrity: sha512-0O8tdQ8ijlPJudXspLMTcitMkdBEz6uUflazL5uQE0WMs85oQIp0U+5hfEktMFB64QqEhjqlvvujTwbzdr9oMg==} + '@pnpm/exe.darwin-arm64@12.13.0': + resolution: {integrity: sha512-9rRpaMGxxrv5YbptsRTIeG+q2IzQyrkRKXkD30pb7weCC6Xz6vQzfkItzrUZsb2bXyYd7fSsq+luTsreXBQYyQ==} cpu: [arm64] os: [darwin] - '@pnpm/exe.darwin-x64@12.10.1': - resolution: {integrity: sha512-ud+1/uZOKEo8P/AsPynOJc/LNwfI0j6WwCElibj71rU9l4nIBnsSn+wWTIPZPkZ4BBSH5+82azSnAARMyJ1lNA==} + '@pnpm/exe.darwin-x64@12.13.0': + resolution: {integrity: sha512-A+VFQakozmXIo8kxtcP9sZCKIi94f9uB5jLXRvwnNSA5G6/G6Iq/8E17+fIPf4bm7xvR+qeM794Nz98Q52lutQ==} cpu: [x64] os: [darwin] - '@pnpm/exe.freebsd-x64@12.10.1': - resolution: {integrity: sha512-mj9PE5rf8uAfQQ2K66HSATMSut+lNiB4eSqFd5+azFVCMnxNSy/32xpZQJT21PhnN3Y4qbK+iKHe5nWAxSuRhw==} + '@pnpm/exe.freebsd-x64@12.13.0': + resolution: {integrity: sha512-HqT2ppLDxmpO8jTgl44BLdrBQoQXE73HHBElYRKvxL47d4maQ0sfk+fI+bfeDpRTqKzc5JZfj85yjRo7anqioA==} cpu: [x64] os: [freebsd] - '@pnpm/exe.linux-arm64-musl@12.10.1': - resolution: {integrity: sha512-xba+00wZJ8Um6rBJJjWl88uJj0tydB8dtomvjlCLvi0uL32vpa9CRP8Vv26FIXvbiZ1bo2RCzYt/eChxJVV52w==} + '@pnpm/exe.linux-arm64-musl@12.13.0': + resolution: {integrity: sha512-yZfm/7h1Kdd1XTNf9+F2Gt5R4WuQKMRbkMIpbzCtxpzniPEKGo/2kymNxdHq3jIcfnzHnP+KBR/YONZ+4Icq+g==} cpu: [arm64] os: [linux] libc: [musl] - '@pnpm/exe.linux-arm64@12.10.1': - resolution: {integrity: sha512-oBdMp69ScC9UnniG4qZAQVr2fBDSXjm4yk/72vkEVyrlwS23yMxcRQl7Qdo3sgXPAygY6TWnPRKm4rXzjoyW7w==} + '@pnpm/exe.linux-arm64@12.13.0': + resolution: {integrity: sha512-jp29ia+fTNhheXzt4FRUw5CwFW9caPNEdLRuy7/Dlbv3sj+iHldfJXfCojkPE4g71NPVwMpY5Eoc7nkfWexqrA==} cpu: [arm64] os: [linux] libc: [glibc] - '@pnpm/exe.linux-ppc64@12.10.1': - resolution: {integrity: sha512-Yyb3wu09h3c7mLme270uHFiVaAIUHC411Ru9LIU2BKUIstrGlXa9OqqVWoXaRgYRdFdOFknkwG7GNn6ygwLbnw==} + '@pnpm/exe.linux-ppc64@12.13.0': + resolution: {integrity: sha512-BO8Nz70baL6KV0G9p+Lx8l6BQYFE11KDEOTTjSNZdiUMMyN1byeDlls10ZgCIaIq5ELlLJ0F/LKieNjubOC7BA==} cpu: [ppc64] os: [linux] libc: [glibc] - '@pnpm/exe.linux-riscv64@12.10.1': - resolution: {integrity: sha512-PdkeUFFkybknnGkWP0H22eMpIiS4OZXL5BcQzF4lh+vmrW3IaC2HOkbANKgot/PKO0Kl77pzA/6PKFxgbgfXIQ==} + '@pnpm/exe.linux-riscv64@12.13.0': + resolution: {integrity: sha512-LrGM+VzpNghXuHK1XSMNEsochaLscAYkllSPLF3Y4CQpaOFYmiZoX+G3TN+T3pYRxdgvwWJCqbbdwRJZFykrig==} cpu: [riscv64] os: [linux] libc: [glibc] - '@pnpm/exe.linux-s390x@12.10.1': - resolution: {integrity: sha512-1okKuHKJwJPAbofDxfhZWAUxEWtee4ZSf7Pah8kcvocaJkf2WxFJ5KVTiNIvDml5GLidDQsgf7Pcf/WHbCak7Q==} + '@pnpm/exe.linux-s390x@12.13.0': + resolution: {integrity: sha512-0Xetcb9OJpXYmJ7rMDh3oFszIvbQl0F8UNh7oJnbLJY1K5PtDgYVkjqwb1JpjU0mkr0b4HKkFdZhlYh7XEGTvw==} cpu: [s390x] os: [linux] libc: [glibc] - '@pnpm/exe.linux-x64-musl@12.10.1': - resolution: {integrity: sha512-e6IqzVNkPa7srFKJKnY23uWJ+qz0LaRWiTUo/sHfFXRRMRzB5uNOr6qWWip/jqhdGwU91n9J7LrEYZ6e0tRczw==} + '@pnpm/exe.linux-x64-musl@12.13.0': + resolution: {integrity: sha512-LSD/snRsouEGA52HrTfEbGrCGdkkr5gXfQym26Ogu3I7sc5dJHUHyp8GnA7ewXrFOSRCJXH25mnmQ6Jpit572Q==} cpu: [x64] os: [linux] libc: [musl] - '@pnpm/exe.linux-x64@12.10.1': - resolution: {integrity: sha512-ZByV0DRgWzGaDSjT5ddRBASdwz+r/qPMYh7o6RGmPQjtRGNFbSl94xY2DcAM8mqCOZJUUDtAXQ+wpBXcdpKlkg==} + '@pnpm/exe.linux-x64@12.13.0': + resolution: {integrity: sha512-t4EYUFG4SPYaJJVQToWIPq/lLBquCPCxMtt9vV//HirSDl332dnxDnwgvdW29sqLg3Ob2x7zFQ69HZLyoCyfpQ==} cpu: [x64] os: [linux] libc: [glibc] - '@pnpm/exe.win32-arm64@12.10.1': - resolution: {integrity: sha512-I7QZHcjioG7orFeCRUFUHByJ1G0zFPnAlaGGyrUvb6MGkv5oeNwNPl7t+Gp+7zHfnMcgLGJ1a+Wfim0IDw3lOw==} + '@pnpm/exe.win32-arm64@12.13.0': + resolution: {integrity: sha512-aDzzll9stgP+p6KKYHNzuShZhBCaxabv481xK5BjfvSnyFbjzu7ksKUIVlsiAw4xAXnrIqvEj0lQarsbBRcIQA==} cpu: [arm64] os: [win32] - '@pnpm/exe.win32-x64@12.10.1': - resolution: {integrity: sha512-4WJFdp58EKlCj0zLobrXU0vpszSZIr4X/3y/uNbAQqGW0zE+VdruZB0gFc3L2kzsUzVwTYbaCn+XEhnCYSAlTg==} + '@pnpm/exe.win32-x64@12.13.0': + resolution: {integrity: sha512-Nkw4hDJTcmuO6zDjkTo4Dz7pG2ojEifSBGC4QbFJFIfBoRbN88GIMu/Lm1woxd7ONhJFlfJ+dJeiDyuP0NKtSA==} cpu: [x64] os: [win32] - pnpm@12.10.1: - resolution: {integrity: sha512-ukCjfrGjcNYP6oxM8dNkwTvMzvUY6YrSvO6VT1OdONo3RY5YJho/pV4GUjRQ6g//+fSXsTW+QfLBXBZCusrObA==} + pnpm@12.13.0: + resolution: {integrity: sha512-HlVxm/JugJ3OXFCE/euqZO+z2pA4rl1oqfimgxHxpFhByMO3ajcpjDtm9rzIBAmpt/M8eKcWij6Q+2Wl2CNa5A==} engines: {node: '>=18.*'} hasBin: true snapshots: - '@pnpm/exe.android-arm64@12.10.1': + '@pnpm/exe.android-arm64@12.13.0': optional: true - '@pnpm/exe.android-x64@12.10.1': + '@pnpm/exe.android-x64@12.13.0': optional: true - '@pnpm/exe.darwin-arm64@12.10.1': + '@pnpm/exe.darwin-arm64@12.13.0': optional: true - '@pnpm/exe.darwin-x64@12.10.1': + '@pnpm/exe.darwin-x64@12.13.0': optional: true - '@pnpm/exe.freebsd-x64@12.10.1': + '@pnpm/exe.freebsd-x64@12.13.0': optional: true - '@pnpm/exe.linux-arm64-musl@12.10.1': + '@pnpm/exe.linux-arm64-musl@12.13.0': optional: true - '@pnpm/exe.linux-arm64@12.10.1': + '@pnpm/exe.linux-arm64@12.13.0': optional: true - '@pnpm/exe.linux-ppc64@12.10.1': + '@pnpm/exe.linux-ppc64@12.13.0': optional: true - '@pnpm/exe.linux-riscv64@12.10.1': + '@pnpm/exe.linux-riscv64@12.13.0': optional: true - '@pnpm/exe.linux-s390x@12.10.1': + '@pnpm/exe.linux-s390x@12.13.0': optional: true - '@pnpm/exe.linux-x64-musl@12.10.1': + '@pnpm/exe.linux-x64-musl@12.13.0': optional: true - '@pnpm/exe.linux-x64@12.10.1': + '@pnpm/exe.linux-x64@12.13.0': optional: true - '@pnpm/exe.win32-arm64@12.10.1': + '@pnpm/exe.win32-arm64@12.13.0': optional: true - '@pnpm/exe.win32-x64@12.10.1': + '@pnpm/exe.win32-x64@12.13.0': optional: true - pnpm@12.10.1: + pnpm@12.13.0: optionalDependencies: - '@pnpm/exe.android-arm64': 12.10.1 - '@pnpm/exe.android-x64': 12.10.1 - '@pnpm/exe.darwin-arm64': 12.10.1 - '@pnpm/exe.darwin-x64': 12.10.1 - '@pnpm/exe.freebsd-x64': 12.10.1 - '@pnpm/exe.linux-arm64': 12.10.1 - '@pnpm/exe.linux-arm64-musl': 12.10.1 - '@pnpm/exe.linux-ppc64': 12.10.1 - '@pnpm/exe.linux-riscv64': 12.10.1 - '@pnpm/exe.linux-s390x': 12.10.1 - '@pnpm/exe.linux-x64': 12.10.1 - '@pnpm/exe.linux-x64-musl': 12.10.1 - '@pnpm/exe.win32-arm64': 12.10.1 - '@pnpm/exe.win32-x64': 12.10.1 + '@pnpm/exe.android-arm64': 12.13.0 + '@pnpm/exe.android-x64': 12.13.0 + '@pnpm/exe.darwin-arm64': 12.13.0 + '@pnpm/exe.darwin-x64': 12.13.0 + '@pnpm/exe.freebsd-x64': 12.13.0 + '@pnpm/exe.linux-arm64': 12.13.0 + '@pnpm/exe.linux-arm64-musl': 12.13.0 + '@pnpm/exe.linux-ppc64': 12.13.0 + '@pnpm/exe.linux-riscv64': 12.13.0 + '@pnpm/exe.linux-s390x': 12.13.0 + '@pnpm/exe.linux-x64': 12.13.0 + '@pnpm/exe.linux-x64-musl': 12.13.0 + '@pnpm/exe.win32-arm64': 12.13.0 + '@pnpm/exe.win32-x64': 12.13.0 --- lockfileVersion: '9.0' @@ -180,17 +180,17 @@ importers: specifier: 1.61.1 version: 1.61.1 '@vitest/coverage-v8': - specifier: 5.0.3 - version: 5.0.3(vitest@5.0.3) + specifier: 5.0.4 + version: 5.0.4(vitest@5.0.4) markdownlint-cli2: specifier: 0.23.3 version: 0.23.3 prettier: - specifier: 3.9.9 - version: 3.9.9 + specifier: 3.9.10 + version: 3.9.10 vitest: - specifier: 5.0.3 - version: 5.0.3(@vitest/coverage-v8@5.0.3)(vite@8.3.3) + specifier: 5.0.4 + version: 5.0.4(@vitest/coverage-v8@5.0.4)(vite@8.3.4) packages: @@ -242,106 +242,106 @@ packages: resolution: {integrity: sha1-6Vc36LtnRt3t9pxVaVNJTxlv5po=} engines: {node: '>= 8'} - '@oxc-project/types@0.152.0': - resolution: {integrity: sha512-oM/5rLBm2tPkg0iBgkH/FOeR3PCDpY19GTgAZjMFM8h9WI9VW7cLgzp6nwtarYKmovavIQZ+Fe/RKX/8C8O/Rw==} + '@oxc-project/types@0.153.0': + resolution: {integrity: sha512-jSNrRIyvPVLL5E1z/tS5zLAprosGz/FuI1PWwEOz59j3E4TTTzSpqKb/RDGqJhhW0QHYISGXxq582wGx6T11Tw==} '@playwright/test@1.61.1': resolution: {integrity: sha1-SFaNwir3gZ5V+l6OO8ebfmo+ZnU=} engines: {node: '>=18'} hasBin: true - '@rolldown/binding-android-arm-eabi@1.2.12': - resolution: {integrity: sha512-dB/a1214qKfHMXCpgqR4OZT+jS4kTyEXbQGJPqzobt5EwH5rX080pxE37alt3RzvR1bf1Yz/yGqRfrYAxuPw0A==} + '@rolldown/binding-android-arm-eabi@1.2.13': + resolution: {integrity: sha512-Vu/NICrgdRvUOeaJZIyB2FP63s6fO/4ud5l8dXmxDx9yDyn+mN0y+gsvsVviSli+T361Aqo0h46EuMoobrwawA==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm] os: [android] - '@rolldown/binding-android-arm64@1.2.12': - resolution: {integrity: sha512-7KHFgQ5VJxIHcLlrwrc3Xbds7oTNQT7Pgi9gQCJKrd2VGab/UksIOYp6VD8MzCstGxOKMgNamPwUCfxPdP1OHg==} + '@rolldown/binding-android-arm64@1.2.13': + resolution: {integrity: sha512-6LEoIrGy5vvCd2boNnv2soPSUZj/PRvhp8R/t9KlX+mIZxThIE/ZqxrGXxmuNX0FuvQFvLdZr7S4HrYpYBVhEQ==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm64] os: [android] - '@rolldown/binding-darwin-arm64@1.2.12': - resolution: {integrity: sha512-3YIhqHD96nA5SaYNRBR16HnGv4oavZvXfD/ayHM+oYZ0WD/8lBAtf6zQua4kEyAvpqrluKXl0lnOBoiNby7x9w==} + '@rolldown/binding-darwin-arm64@1.2.13': + resolution: {integrity: sha512-CaJSRzlQ6Q+zkDMVA9OkVxBjVoPRCDEE3v0FSJ9kIQBgRjFApA3Si4ijhbNVUji7ZJt+PfO0e46qy4nPInHUPA==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm64] os: [darwin] - '@rolldown/binding-darwin-x64@1.2.12': - resolution: {integrity: sha512-UuuJ35MFw4gmFOrE9pEqIV+K3syIKveph+Qc1/ljHZVdoDW4pz/JHR/eMVom+TZGl/5OOvGJOWaOCVt3ZfqhxA==} + '@rolldown/binding-darwin-x64@1.2.13': + resolution: {integrity: sha512-e4r340I5hxSzJkD3YJBxgzq/rJ3wwxwdLLb2FPt1Zpyem20nrQPT11DDEEkazwxaHumH8wpglsp/Ozgj/wT6mw==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [x64] os: [darwin] - '@rolldown/binding-freebsd-x64@1.2.12': - resolution: {integrity: sha512-uMvssit0a4W+/7D8CbHUvG719mH3R2jwXAlh/XcPvuHTE0g++LymF88DCGNX0HM2rBOn0xrzgXktIB6fLSJBTQ==} + '@rolldown/binding-freebsd-x64@1.2.13': + resolution: {integrity: sha512-hoBWDZ4/K/mJKVMbsgUd1jfpA2DiOrJ54mpegObU9TBHBBrtX4FLIXJJQRDPZ/2Dn91GvPob+Z2hwKJzf4E5SQ==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [x64] os: [freebsd] - '@rolldown/binding-linux-arm-gnueabihf@1.2.12': - resolution: {integrity: sha512-XcFu0R0xWnwzSf4IQgFH1rJIckPN1pLy2R+4r9IDB7Yfu/ys9cVqfa4pBrMHj7a3gl8mIR4nRNPg0e5IvEVs6g==} + '@rolldown/binding-linux-arm-gnueabihf@1.2.13': + resolution: {integrity: sha512-oF9fZu3vTWnTiVAkDFxU9PJLt1nh20K9RRpuHsR7ZnE2L7XookBbDBVLojCVSLGbvtSlxeUNnjAj6DbNsKyzbg==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm] os: [linux] - '@rolldown/binding-linux-arm64-gnu@1.2.12': - resolution: {integrity: sha512-260UrKgn8tz39ak+SMDOirKzr7V04M9dWPw5llW00SwBivCZoWcRBKV1d8cXnRkUmSZA3BdiUmBHWk7734Ulpw==} + '@rolldown/binding-linux-arm64-gnu@1.2.13': + resolution: {integrity: sha512-DTpb/+jMiqWMPgphn4ksW1zW+XLJ6dJJ9FMvnIk9I291LhCctMPhMYJrP5t9p6C9qa3KXadDdUEZHBaPh3kNxQ==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm64] os: [linux] libc: [glibc] - '@rolldown/binding-linux-arm64-musl@1.2.12': - resolution: {integrity: sha512-5YK1I9SqDkbPgc1IA8BgDl34suqUS2q0KWnBrirm0E51YjOs6eo6dV6jbQfNE/argHRSvd0QUGgtpIoYx+WWpw==} + '@rolldown/binding-linux-arm64-musl@1.2.13': + resolution: {integrity: sha512-xU+Kvv9N2A3SY35zFh1FWWNjxbadE/BKeqnkXe7vScU4GZsw757BlVmDLITZEq8DPpk6m7uoDYkK7P+x/uU5Ow==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm64] os: [linux] libc: [musl] - '@rolldown/binding-linux-ppc64-gnu@1.2.12': - resolution: {integrity: sha512-Rkcrmp7eFRg74yL5fXEU91JEWbdEPLevWwGtXpmhbjlD1StScbWTmO94Bhly+Mo+ketKYkdmM1vNUKeWSlx8cQ==} + '@rolldown/binding-linux-ppc64-gnu@1.2.13': + resolution: {integrity: sha512-XMk/hnhh25oQ756Lclb1Q11h4ll0xC0Esa5w4Vzp+mAE2S3AGJgeM0SonrIgY8fHhjarb6hcoTuwoFG0VVP2ig==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [ppc64] os: [linux] libc: [glibc] - '@rolldown/binding-linux-s390x-gnu@1.2.12': - resolution: {integrity: sha512-qvK4DuAsQc2BSjlx+Xr+IzOIvvxbGZqxFwdWfG6F518Erj0GGISyQbJ6pIappnOxlNPzNHvo/L0BwB30GZ+zVw==} + '@rolldown/binding-linux-s390x-gnu@1.2.13': + resolution: {integrity: sha512-U1BoTHYmlywE2n3HUWjzZ+8EQsKr+OwpxYuDWaubx42tUL8QSL7nOqRz/NVHanibbFP3M1Rxuprz/wNcbMKjqw==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [s390x] os: [linux] libc: [glibc] - '@rolldown/binding-linux-x64-gnu@1.2.12': - resolution: {integrity: sha512-Q9uLBO53Xd4QIq1WOycVQyPP1O4HhraEV2qqb3uTrnVw6QZih9duY4vNXOivL1xoUS1/z+W8eF4NMfl2a8Sdjw==} + '@rolldown/binding-linux-x64-gnu@1.2.13': + resolution: {integrity: sha512-J4cm80Pc6wEwV5AZ42o62sIQgDk+Y7R2s646jIwuvO+4V46QB58N4vVuMPWCBaNgursXLpmUWJV//WQAkPvHBQ==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [x64] os: [linux] libc: [glibc] - '@rolldown/binding-linux-x64-musl@1.2.12': - resolution: {integrity: sha512-3IBxWFMjbOZskDPKv8Lf9BCnahlKuHthWkYnyIxOH/QcJrFcS4EmcenthApkwr/5+nEqZlLzeYbxeMaX7A5u4g==} + '@rolldown/binding-linux-x64-musl@1.2.13': + resolution: {integrity: sha512-W0euZS40U4V6JkmEnVCIX9mcsL6cbXQ4X8c2w+MMOIjFg68TXUW+u3RT+2e1t1pv9mg/EP3pDtK3POXdQ7Rxyw==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [x64] os: [linux] libc: [musl] - '@rolldown/binding-openharmony-arm64@1.2.12': - resolution: {integrity: sha512-xtX61xg4LKPkPWilZU1ynKClz5Gj4bf74LML4r3eVLWumKnGjoEr1OSHQhMdbBDoYTi+yjrujvpZe2pUnqCrrA==} + '@rolldown/binding-openharmony-arm64@1.2.13': + resolution: {integrity: sha512-do/AF/4n9MRshia3a5aXoy8xM2c6mgfT6D7H/dY6my5z+hfCIR4ab7mk4IRj++nsEQpKy39kd0DQnDq+r692tw==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm64] os: [openharmony] - '@rolldown/binding-win32-arm64-msvc@1.2.12': - resolution: {integrity: sha512-At7fPB6PCaIjzgIhEZFxuT+BBFqiQibJDT4d3PhiR3f4E7bbMZF4aKblbFfEM3sETRDd1YiQx/+U/g/B/ou5Ew==} + '@rolldown/binding-win32-arm64-msvc@1.2.13': + resolution: {integrity: sha512-6FtUf2cJZobutJdxnGYX8z0vtbgqU0b2v8vfBhkXb9wp2MppMFtkunE+IaOntyi01rkIQoPW2GHABtfzsC0BRQ==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm64] os: [win32] - '@rolldown/binding-win32-x64-msvc@1.2.12': - resolution: {integrity: sha512-WIw2haVKwjuYdXkHaoC0mF8Le71TuCBxjrdKqLbJGctbBABj+ClfmNvtbOnzpq3RokNo5+V1qhtSzJyXorsklQ==} + '@rolldown/binding-win32-x64-msvc@1.2.13': + resolution: {integrity: sha512-UKhFaZTeTcbKrb3iU82m17jVcPEAoqDkCN5MBqgPyZSwp/cQmib21crTS0DdH7T1B7wZRWEI89YQAOJMet5yhg==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [x64] os: [win32] @@ -374,11 +374,11 @@ packages: '@types/unist@2.0.11': resolution: {integrity: sha1-Ea9XsSfjJId3SEH3pOVOqxZtA8Q=} - '@vitest/coverage-v8@5.0.3': - resolution: {integrity: sha512-+klsyz7BvT1vCU28Zkfzms1Ia78XD0V41U3FUtRaa3S+vOr/EXvK1O6BvVD7l1RzEjm6SONR2aybOvDDf9u0mQ==} + '@vitest/coverage-v8@5.0.4': + resolution: {integrity: sha512-P5YcQY8Y6RmoE9xRXI38rT8pssbcubEzqtYTM2XQoxOXMDn04nRaTI1SM8qCl9/NfW3ag9GlzdSXu7IwO5Ft8A==} peerDependencies: - '@vitest/browser': 5.0.3 - vitest: 5.0.3 + '@vitest/browser': 5.0.4 + vitest: 5.0.4 peerDependenciesMeta: '@vitest/browser': optional: true @@ -391,10 +391,10 @@ packages: resolution: {integrity: sha512-gUsfXZJbzPamoIY5TvHFiMMoXESBrUMo+xqaj+rYrWI69+EnvRlYBlP96ZnHPY4vX8kyUpgAnFUCg5wZG/HkDQ==} engines: {node: '>=22'} - '@vitest/mocker@5.0.3': - resolution: {integrity: sha512-T8sWAIbkSyAjkwTcaEc3Iu0o9A27X1/kdXrizhZkGuSKScRQtRzclfAMpOTcGdXCsqxeWlpGy3XjqaW8CpLORg==} + '@vitest/mocker@5.0.4': + resolution: {integrity: sha512-tqAlrYWce4iUxhr3ncNohejtCTOcHeE8XWrSNZY3OhPoDn01yeGv+gnaBy64ATp7o6pb03eIbBAjzmibpc9vIQ==} peerDependencies: - msw: ^2.4.9 + msw: ^2.4.9 || ^3.0.0 vite: ^6.0.0 || ^7.0.0 || ^8.0.0 peerDependenciesMeta: msw: @@ -402,8 +402,8 @@ packages: vite: optional: true - '@vitest/spy@5.0.3': - resolution: {integrity: sha512-XhFysQTB8AZ+P4gMi+Lpo99vg2AZi0qKpaB9yXQl37+CaMEAPO3iH/wGVnSyL5MPERiLezpqTVtrR6UZH5GCXg==} + '@vitest/spy@5.0.4': + resolution: {integrity: sha512-MZKk/gSkm2q+ICobMxCpH1mA+cCAWm8WV7UhxlqGjq/sJ3AGc1BqFOs5CRVXxH78wQtme9q/NAAgBquj4AcyMw==} ansi-regex@6.4.0: resolution: {integrity: sha512-KzTVk2tCWAHtYrvvvaP8bJKJq2pVinhLcGEQdtLIYPbmNGNyYe8QwNaTUYQp2J7/vIsUKt5QCqAfUkYyG9DkOw==} @@ -771,8 +771,8 @@ packages: engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1} hasBin: true - obug@2.2.1: - resolution: {integrity: sha1-nEU+/u2oIgUOuXdCQulpx4TWTXg=} + obug@3.0.0: + resolution: {integrity: sha512-5vvB5+W7ePv+p3uqxi+RcW1XAzLW0/hxt3/4X4Lc4qHudzOhmBiBwOY6DRob4WnanAEGvNcLjF+KNOufrUoEQw==} engines: {node: '>=12.20.0'} parse-entities@4.0.2: @@ -803,8 +803,8 @@ packages: resolution: {integrity: sha1-NJNVARb0eEhymDAdLC6NxaVuZZQ=} engines: {node: ^10 || ^12 || >=14} - prettier@3.9.9: - resolution: {integrity: sha512-Z/CJHIkdujO/OtN7nXUii0Rf3VT5SRuhjBA82Xvu2XhBUgX3nhP67T0LHceBdQLex7OOFGTox+Q5Yg8Jk2Qivg==} + prettier@3.9.10: + resolution: {integrity: sha512-skGHTH1Yb9QvaTC4hWnRTzEYtCpApF0UMBPz+t/0ZPzP8ihefo/btKd+QA7pUE0fEwA1SbS/NmhyEcstdXOIdA==} engines: {node: '>=14'} hasBin: true @@ -819,8 +819,8 @@ packages: resolution: {integrity: sha1-D+E7lSLhRz9RtVjueW4I8R+bSJ8=} engines: {iojs: '>=1.0.0', node: '>=0.10.0'} - rolldown@1.2.12: - resolution: {integrity: sha512-8wafseiaG80xmXSfqidUNqZcylTlhmPZZt+za2m+js2sFZ8dTNlhIOV2WcbIPx2hgwPBJpEUGFAMZ9bgBBLTSQ==} + rolldown@1.2.13: + resolution: {integrity: sha512-/5apOkwWxtACcQtZ5WlrAsKS4JwXVThQPJZ3RqIruRY9UG9M8e0VlXN068xum/JRKA4aIUoJ13ghe/kGCvidiQ==} engines: {node: ^20.19.0 || >=22.12.0} hasBin: true @@ -850,8 +850,8 @@ packages: resolution: {integrity: sha1-0iomlSKDamJ6+NBLXD/Sx/o+MuM=} engines: {node: '>=12'} - tinybench@6.2.1: - resolution: {integrity: sha512-IAbQaPJIIdhVxi0mqy9lez1wEwje0UQf9F1vwtbelEG5Nbgn0nPOxCvU+mNeNS9gyJTAhrHp74CbUaSynQpZcQ==} + tinybench@6.2.2: + resolution: {integrity: sha512-nIZ2N2dFpjBsg2hgitKu7mA+FvsIJuGJOwysRngmVRRmWgR/UyPjwJj8c/fT/dhm8EkHnF5EOogRf+0Z2qrimA==} engines: {node: '>=20.0.0'} tinyexec@1.3.1: @@ -877,8 +877,8 @@ packages: resolution: {integrity: sha512-lzlXPoVB0Uy/FvTaUgX39RbixYiSKoc3JSoSf01+0c2B6FR3qdYIPN7Qjo/AV7n6sqLCk0509cT3LRj1oSZ1+A==} engines: {node: '>=20'} - vite@8.3.3: - resolution: {integrity: sha512-cTAldKPImjg6c+gk48U19POPn3GCBzZwpdsN8ZMEEcbpes+6/wvfqUd0C2y3qYY4wsj8PwgFwrZ/1jBPVttMSg==} + vite@8.3.4: + resolution: {integrity: sha512-IftLE8phJhdNRIGNEV4JCCvfNScoZQVfcXaN8TQropWGJtOHcu+iAB9pHcuGvmEb/kddw0LBe/jS8ztdC6xdiQ==} engines: {node: ^20.19.0 || >=22.12.0} hasBin: true peerDependencies: @@ -920,20 +920,20 @@ packages: yaml: optional: true - vitest@5.0.3: - resolution: {integrity: sha512-xMw97S3rjdtj5dkVat7jCsqWBpvchs3RlpQctUqwJD0KkERk40vz2fJ77lDwW/Vzh/pk18eItYAzkodhSes3jQ==} + vitest@5.0.4: + resolution: {integrity: sha512-z0WxZRV2Sg48wF0FSgMq3TFG8JS38/Qr96vZVZdX6+Em9raQTvnXQvdTFJe2m3rfyJnEHeHQ/snceIdi8D1pVg==} engines: {node: ^22.12.0 || ^24.0.0 || >=26.0.0} hasBin: true peerDependencies: '@edge-runtime/vm': '*' '@opentelemetry/api': ^1.9.0 '@types/node': ^22.0.0 || >=24.0.0 - '@vitest/browser-playwright': 5.0.3 - '@vitest/browser-preview': 5.0.3 + '@vitest/browser-playwright': 5.0.4 + '@vitest/browser-preview': 5.0.4 '@vitest/browser-webdriverio': ^5.0.0-beta.5 || >=5.0.0 - '@vitest/coverage-istanbul': 5.0.3 - '@vitest/coverage-v8': 5.0.3 - '@vitest/ui': 5.0.3 + '@vitest/coverage-istanbul': 5.0.4 + '@vitest/coverage-v8': 5.0.4 + '@vitest/ui': 5.0.4 happy-dom: '*' jsdom: '*' vite: ^6.4.0 || ^7.0.0 || ^8.0.0 @@ -1009,55 +1009,55 @@ snapshots: '@nodelib/fs.scandir': 2.1.5 fastq: 1.20.3 - '@oxc-project/types@0.152.0': {} + '@oxc-project/types@0.153.0': {} '@playwright/test@1.61.1': dependencies: playwright: 1.61.1 - '@rolldown/binding-android-arm-eabi@1.2.12': + '@rolldown/binding-android-arm-eabi@1.2.13': optional: true - '@rolldown/binding-android-arm64@1.2.12': + '@rolldown/binding-android-arm64@1.2.13': optional: true - '@rolldown/binding-darwin-arm64@1.2.12': + '@rolldown/binding-darwin-arm64@1.2.13': optional: true - '@rolldown/binding-darwin-x64@1.2.12': + '@rolldown/binding-darwin-x64@1.2.13': optional: true - '@rolldown/binding-freebsd-x64@1.2.12': + '@rolldown/binding-freebsd-x64@1.2.13': optional: true - '@rolldown/binding-linux-arm-gnueabihf@1.2.12': + '@rolldown/binding-linux-arm-gnueabihf@1.2.13': optional: true - '@rolldown/binding-linux-arm64-gnu@1.2.12': + '@rolldown/binding-linux-arm64-gnu@1.2.13': optional: true - '@rolldown/binding-linux-arm64-musl@1.2.12': + '@rolldown/binding-linux-arm64-musl@1.2.13': optional: true - '@rolldown/binding-linux-ppc64-gnu@1.2.12': + '@rolldown/binding-linux-ppc64-gnu@1.2.13': optional: true - '@rolldown/binding-linux-s390x-gnu@1.2.12': + '@rolldown/binding-linux-s390x-gnu@1.2.13': optional: true - '@rolldown/binding-linux-x64-gnu@1.2.12': + '@rolldown/binding-linux-x64-gnu@1.2.13': optional: true - '@rolldown/binding-linux-x64-musl@1.2.12': + '@rolldown/binding-linux-x64-musl@1.2.13': optional: true - '@rolldown/binding-openharmony-arm64@1.2.12': + '@rolldown/binding-openharmony-arm64@1.2.13': optional: true - '@rolldown/binding-win32-arm64-msvc@1.2.12': + '@rolldown/binding-win32-arm64-msvc@1.2.13': optional: true - '@rolldown/binding-win32-x64-msvc@1.2.12': + '@rolldown/binding-win32-x64-msvc@1.2.13': optional: true '@rolldown/pluginutils@1.0.1': {} @@ -1083,17 +1083,17 @@ snapshots: '@types/unist@2.0.11': {} - '@vitest/coverage-v8@5.0.3(vitest@5.0.3)': + '@vitest/coverage-v8@5.0.4(vitest@5.0.4)': dependencies: '@bcoe/v8-coverage': 1.0.2 '@vitest/istanbul-lib-coverage': 1.0.2 '@vitest/istanbul-lib-report': 1.0.2 ast-v8-to-istanbul: 1.0.7 magicast: 0.5.5 - obug: 2.2.1 + obug: 3.0.0 std-env: 4.3.0 tinyrainbow: 3.2.0 - vitest: 5.0.3(@vitest/coverage-v8@5.0.3)(vite@8.3.3) + vitest: 5.0.4(@vitest/coverage-v8@5.0.4)(vite@8.3.4) '@vitest/istanbul-lib-coverage@1.0.2': {} @@ -1101,16 +1101,16 @@ snapshots: dependencies: '@vitest/istanbul-lib-coverage': 1.0.2 - '@vitest/mocker@5.0.3(vite@8.3.3)': + '@vitest/mocker@5.0.4(vite@8.3.4)': dependencies: '@jridgewell/trace-mapping': 0.3.31 - '@vitest/spy': 5.0.3 + '@vitest/spy': 5.0.4 estree-walker: 3.0.3 magic-string: 1.4.3 optionalDependencies: - vite: 8.3.3 + vite: 8.3.4 - '@vitest/spy@5.0.3': {} + '@vitest/spy@5.0.4': {} ansi-regex@6.4.0: {} @@ -1536,7 +1536,7 @@ snapshots: nanoid@3.3.18: {} - obug@2.2.1: {} + obug@3.0.0: {} parse-entities@4.0.2: dependencies: @@ -1568,7 +1568,7 @@ snapshots: picocolors: 1.1.1 source-map-js: 1.2.2 - prettier@3.9.9: {} + prettier@3.9.10: {} punycode.js@2.3.1: {} @@ -1576,26 +1576,26 @@ snapshots: reusify@1.1.0: {} - rolldown@1.2.12: + rolldown@1.2.13: dependencies: - '@oxc-project/types': 0.152.0 + '@oxc-project/types': 0.153.0 '@rolldown/pluginutils': 1.0.1 optionalDependencies: - '@rolldown/binding-android-arm-eabi': 1.2.12 - '@rolldown/binding-android-arm64': 1.2.12 - '@rolldown/binding-darwin-arm64': 1.2.12 - '@rolldown/binding-darwin-x64': 1.2.12 - '@rolldown/binding-freebsd-x64': 1.2.12 - '@rolldown/binding-linux-arm-gnueabihf': 1.2.12 - '@rolldown/binding-linux-arm64-gnu': 1.2.12 - '@rolldown/binding-linux-arm64-musl': 1.2.12 - '@rolldown/binding-linux-ppc64-gnu': 1.2.12 - '@rolldown/binding-linux-s390x-gnu': 1.2.12 - '@rolldown/binding-linux-x64-gnu': 1.2.12 - '@rolldown/binding-linux-x64-musl': 1.2.12 - '@rolldown/binding-openharmony-arm64': 1.2.12 - '@rolldown/binding-win32-arm64-msvc': 1.2.12 - '@rolldown/binding-win32-x64-msvc': 1.2.12 + '@rolldown/binding-android-arm-eabi': 1.2.13 + '@rolldown/binding-android-arm64': 1.2.13 + '@rolldown/binding-darwin-arm64': 1.2.13 + '@rolldown/binding-darwin-x64': 1.2.13 + '@rolldown/binding-freebsd-x64': 1.2.13 + '@rolldown/binding-linux-arm-gnueabihf': 1.2.13 + '@rolldown/binding-linux-arm64-gnu': 1.2.13 + '@rolldown/binding-linux-arm64-musl': 1.2.13 + '@rolldown/binding-linux-ppc64-gnu': 1.2.13 + '@rolldown/binding-linux-s390x-gnu': 1.2.13 + '@rolldown/binding-linux-x64-gnu': 1.2.13 + '@rolldown/binding-linux-x64-musl': 1.2.13 + '@rolldown/binding-openharmony-arm64': 1.2.13 + '@rolldown/binding-win32-arm64-msvc': 1.2.13 + '@rolldown/binding-win32-x64-msvc': 1.2.13 run-parallel@1.2.0: dependencies: @@ -1618,7 +1618,7 @@ snapshots: dependencies: ansi-regex: 6.4.0 - tinybench@6.2.1: {} + tinybench@6.2.2: {} tinyexec@1.3.1: {} @@ -1637,34 +1637,34 @@ snapshots: unicorn-magic@0.4.1: {} - vite@8.3.3: + vite@8.3.4: dependencies: lightningcss: 1.33.0 picomatch: 4.0.7 postcss: 8.5.23 - rolldown: 1.2.12 + rolldown: 1.2.13 tinyglobby: 0.2.17 optionalDependencies: fsevents: 2.3.3 - vitest@5.0.3(@vitest/coverage-v8@5.0.3)(vite@8.3.3): + vitest@5.0.4(@vitest/coverage-v8@5.0.4)(vite@8.3.4): dependencies: '@types/chai': 5.2.3 - '@vitest/mocker': 5.0.3(vite@8.3.3) + '@vitest/mocker': 5.0.4(vite@8.3.4) chai: 6.3.0 es-module-lexer: 2.3.2 expect-type: 1.4.0 magic-string: 1.4.3 - obug: 2.2.1 + obug: 3.0.0 picomatch: 4.0.7 std-env: 4.3.0 - tinybench: 6.2.1 + tinybench: 6.2.2 tinyexec: 1.3.1 tinyglobby: 0.2.17 - vite: 8.3.3 + vite: 8.3.4 why-is-node-running: 3.2.1 optionalDependencies: - '@vitest/coverage-v8': 5.0.3(vitest@5.0.3) + '@vitest/coverage-v8': 5.0.4(vitest@5.0.4) transitivePeerDependencies: - msw diff --git a/schemas/mockapi.schema.json b/schemas/mockapi.schema.json index 78d55bf..56b5fb5 100644 --- a/schemas/mockapi.schema.json +++ b/schemas/mockapi.schema.json @@ -28,7 +28,6 @@ }, "endpoints": { "type": "array", - "maxItems": 25, "items": { "$ref": "#/$defs/endpoint" } diff --git a/site/index.html b/site/index.html index a647462..7a70a8b 100644 --- a/site/index.html +++ b/site/index.html @@ -76,7 +76,7 @@ @@ -87,7 +87,7 @@ `; + const payload = `Description:\nMixed Case \n\nTechnical implementation:\n`; endpoint.name = "Untrusted "; endpoint.description = payload; endpoint.response.contentType = "text/html"; endpoint.response.body = payload; endpoint.response.headers = { "X-Untrusted-Text": [""] }; - await importDocument(request, { ...example, endpoints: [endpoint], apiDescriptions: { "/ctp": payload } }); + await importDocument(request, { ...example, endpoints: [endpoint], apiDescriptions: { "/inventory": payload } }); await page.reload(); const row = page.locator(".endpoint-row"); @@ -183,7 +252,8 @@ test("endpoint information is keyboard accessible and untrusted descriptions and await expect(tooltip).toBeHidden(); await info.hover(); await expect(tooltip.locator("p")).toHaveText(payload); - await expect(tooltip.locator("strong")).toHaveText(endpoint.name); + await expect(tooltip.locator(":scope > strong")).toHaveText(endpoint.name); + await expect(tooltip.locator("p > strong")).toHaveText(["Description:", "Technical implementation:"]); await expect(tooltip.locator("p")).toHaveCSS("margin-top", "8px"); await expect(tooltip.locator("small").last()).toHaveText("Click the information button to edit."); await expect(tooltip).toHaveCSS("text-transform", "none"); @@ -219,7 +289,7 @@ test("endpoint information is keyboard accessible and untrusted descriptions and await expect(info).toBeFocused(); await page.keyboard.press("Escape"); - const groupInfo = page.getByRole("button", { name: "Edit API description for /ctp", exact: true }); + const groupInfo = page.getByRole("button", { name: "Edit API description for /inventory", exact: true }); await groupInfo.click(); await expect(page.locator("#api-description-text")).toHaveValue(payload); await page.locator("#api-description-text").fill(edited); @@ -227,7 +297,7 @@ test("endpoint information is keyboard accessible and untrusted descriptions and await expect(page.locator(".endpoint-group-row .api-description-tooltip p")).toHaveText(edited); await page.keyboard.press("Escape"); const exported = await (await request.get("/__mockapi/api/configuration/export")).json(); - expect(exported.apiDescriptions["/ctp"]).toBe(edited); + expect(exported.apiDescriptions["/inventory"]).toBe(edited); expect(exported.endpoints[0].description).toBe(edited); await page.reload(); await info.focus(); @@ -270,6 +340,7 @@ test("endpoints without descriptions still offer information and filter by hidde await expect(filter).toBeFocused(); await expect(page.locator(".endpoint-row")).toHaveCount(1); await expect(page.locator(".endpoint-row .api-description-tooltip")).toBeHidden(); + await expect(page.locator(".endpoint-row .api-description-tooltip p > strong")).toHaveCount(0); await filter.fill("Description that does not match"); await expect(page.locator(".endpoint-row")).toHaveCount(0); }); diff --git a/tests/browser/dashboard-api-security.spec.js b/tests/browser/dashboard-api-security.spec.js index ea62da9..484011d 100644 --- a/tests/browser/dashboard-api-security.spec.js +++ b/tests/browser/dashboard-api-security.spec.js @@ -242,19 +242,23 @@ for (const theme of ["light", "dark"]) { expect(dimensions.labelHeight).toBeGreaterThanOrEqual(44); const keyInput = page.getByLabel("API key for dashboard tests"); - await expect(keyInput).toHaveAttribute("maxlength", "43"); + await expect(keyInput).toHaveAttribute("maxlength", "256"); await page.keyboard.press("Tab"); await expect(page.locator("#settings-api-security-enabled")).toBeFocused(); await page.keyboard.press("Tab"); await expect(keyInput).toBeFocused(); await keyInput.fill("invalid"); await expect(keyInput).toHaveAttribute("aria-invalid", "true"); - await expect(page.locator("#settings-api-key-error")).toHaveText("Enter a generated 43-character MockAPI key."); + await expect(page.locator("#settings-api-key-error")).toHaveText( + "Enter a 32-256 character MockAPI key using ASCII letters, digits, hyphens, or underscores." + ); await expect(page.getByRole("button", { name: "Copy key", exact: true })).toBeDisabled(); - await keyInput.fill("a".repeat(43)); + await keyInput.fill("a".repeat(32)); + await expect(keyInput).toHaveAttribute("aria-invalid", "false"); + await keyInput.fill("a".repeat(256)); await keyInput.press("End"); await keyInput.pressSequentially("b"); - await expect(keyInput).toHaveValue("a".repeat(43)); + await expect(keyInput).toHaveValue("a".repeat(256)); await expect(keyInput).toHaveAttribute("aria-invalid", "false"); await expect(page.locator("#settings-api-key-error")).toBeHidden(); await expect(page.getByRole("button", { name: "Copy key", exact: true })).toBeEnabled(); diff --git a/tests/browser/dashboard-controllers.spec.js b/tests/browser/dashboard-controllers.spec.js index b1b4670..80d359b 100644 --- a/tests/browser/dashboard-controllers.spec.js +++ b/tests/browser/dashboard-controllers.spec.js @@ -69,6 +69,15 @@ test("API security controller generates once, uses captured revisions, and ignor await expect(frame.locator("#settings-api-key-generate")).toHaveText("Generate key"); await frame.locator("#settings-api-key").fill("invalid"); await expect(frame.locator("#settings-api-key-error")).toBeVisible(); + for (const length of [32, 36, 43, 256]) { + const suppliedKey = "deployment_key-" + "a".repeat(length - 15); + await frame.locator("#settings-api-key").fill(suppliedKey); + await expect(frame.locator("#settings-api-key-error")).toBeHidden(); + expect(await frame.evaluate(() => window.security.getKey())).toBe(suppliedKey); + } + await frame.locator("#settings-api-key").fill("a".repeat(31)); + await expect(frame.locator("#settings-api-key-error")).toBeVisible(); + expect(await frame.evaluate(() => window.security.getKey())).toBe(""); await frame.locator("#settings-api-key-generate").click(); await expect(frame.locator("#settings-api-key-generate")).toBeDisabled(); expect(await frame.evaluate(() => window.securityCalls[1].options.etag)).toBe('"0"'); @@ -593,13 +602,17 @@ test("endpoint table owns selection snapshots and releases controls and obsolete /^9 attempts\. Last attempt: (?!Never$).+/ ); await expect(frame.locator("#selection-count")).toHaveText("1"); + await expect(frame.locator(".endpoint-group-selection")).toBeChecked(); expect(await frame.evaluate(() => document.querySelector(".endpoint-row") === window.originalRow)).toBe(true); await frame.evaluate((definition) => { window.oldEdit = document.querySelector('.endpoint-row button[title="Edit"]'); + window.oldGroupSelection = document.querySelector(".endpoint-group-selection"); window.table.updateEndpoints([{ ...definition, name: "Refreshed endpoint" }]); window.oldEdit.click(); + window.oldGroupSelection.click(); }, endpoint); expect(await frame.evaluate(() => window.actions.length)).toBe(1); + await expect(frame.locator(".endpoint-group-selection")).toBeChecked(); await expect(frame.getByRole("checkbox", { name: "Select Refreshed endpoint", exact: true })).toBeChecked(); await frame.locator(".switch input").focus(); await frame.evaluate(() => window.table.setPending(true)); @@ -609,7 +622,39 @@ test("endpoint table owns selection snapshots and releases controls and obsolete await frame.getByRole("button", { name: "Edit", exact: true }).click(); expect(await frame.evaluate(() => window.actions.length)).toBe(2); + const groupControl = frame.locator("#endpoint-toggle-groups"); + await groupControl.click(); + await expect(frame.locator(".endpoint-row")).toHaveCount(0); + await expect(groupControl).toHaveText("Expand all groups"); + await frame.evaluate((definition) => { + window.table.updateEndpoints([ + { ...definition, name: "Refreshed endpoint" }, + { ...definition, id: "cb11041d-1ba5-4c93-86a4-6570adfc282e", name: "New group", path: "/new-group/route" }, + ]); + }, endpoint); + await expect(frame.locator(".endpoint-row")).toHaveCount(1); + await expect(frame.locator(".endpoint-row")).toContainText("New group"); + await expect(groupControl).toHaveText("Collapse all groups"); + await groupControl.click(); + await expect(frame.locator(".endpoint-row")).toHaveCount(0); + await frame.evaluate(() => window.table.updateStatistics({ endpoints: [] })); + await expect(frame.locator(".endpoint-row")).toHaveCount(0); + await expect(groupControl).toHaveText("Expand all groups"); + await groupControl.click(); + await expect(frame.locator(".endpoint-row")).toHaveCount(2); + await expect(frame.getByRole("checkbox", { name: "Select Refreshed endpoint", exact: true })).toBeChecked(); + await frame.evaluate( + (definition) => window.table.updateEndpoints([{ ...definition, name: "Refreshed endpoint" }]), + endpoint + ); + await expect(frame.locator(".endpoint-row")).toHaveCount(1); + await expect(groupControl).toHaveText("Collapse all groups"); + await frame.evaluate(() => window.table.dispose()); + await frame.locator(".endpoint-group-selection").click(); + expect(await frame.evaluate(() => window.table.getSelectedEndpointIds())).toEqual([endpoint.id]); + await groupControl.click(); + await expect(frame.locator(".endpoint-row")).toHaveCount(1); await frame.getByRole("button", { name: "Edit", exact: true }).click(); await frame.locator("#bulk-enable").click(); await frame.locator("#filter-text").fill("does not match"); diff --git a/tests/browser/dashboard-endpoints.spec.js b/tests/browser/dashboard-endpoints.spec.js index abb0ddb..e859068 100644 --- a/tests/browser/dashboard-endpoints.spec.js +++ b/tests/browser/dashboard-endpoints.spec.js @@ -153,66 +153,270 @@ test("shows all operations with relative paths and sorts within alphabetical API expect(Math.abs(regionBounds.y - headerBounds.y)).toBeLessThanOrEqual(1); }); +test("@smoke selects and clears one API without changing other API selections", async ({ page, request }) => { + const endpoints = ["alpha", "zeta"].flatMap((api, groupIndex) => + ["GET", "POST"].map((method, index) => ({ + id: `00000000-0000-4000-8000-${String(groupIndex * 2 + index + 1).padStart(12, "0")}`, + name: `${api} ${method}`, + enabled: true, + methods: [method], + path: `/${api}/operation`, + response: { statusCode: 200, headers: {}, contentType: "text/plain", body: "ok" }, + })) + ); + await importDocument(request, { ...emptyDocument, endpoints }); + const alpha = page.getByRole("checkbox", { name: "Select all matching endpoints in alpha", exact: true }); + const zeta = page.getByRole("checkbox", { name: "Select all matching endpoints in zeta", exact: true }); + const selectAll = page.locator("#select-all-endpoints"); + const count = page.locator("#selection-count"); + const configuration = await request.get("/__mockapi/api/configuration"); + + await expect(alpha).not.toBeChecked(); + await expect(zeta).not.toBeChecked(); + await page.getByRole("checkbox", { name: "Select zeta GET", exact: true }).check(); + await alpha.focus(); + await page.keyboard.press("Space"); + await expect(alpha).toBeChecked(); + await expect(alpha).toBeFocused(); + await expect(zeta).toBeChecked({ indeterminate: true }); + await expect(selectAll).toBeChecked({ indeterminate: true }); + await expect(count).toHaveText("3"); + + await page.getByRole("checkbox", { name: "Select alpha GET", exact: true }).uncheck(); + await expect(alpha).toBeChecked({ indeterminate: true }); + await alpha.focus(); + await page.keyboard.press("Space"); + await expect(alpha).toBeChecked(); + await page.keyboard.press("Space"); + await expect(alpha).not.toBeChecked(); + await expect(count).toHaveText("1"); + await expect(page.getByRole("checkbox", { name: "Select zeta GET", exact: true })).toBeChecked(); + + await page.getByRole("button", { name: "Collapse alpha", exact: true }).click(); + await alpha.check(); + await expect(page.locator(".endpoint-row")).toHaveCount(2); + await expect(page.getByRole("button", { name: "Expand alpha", exact: true })).toBeVisible(); + await expect(count).toHaveText("3"); + await selectAll.check(); + await expect(alpha).toBeChecked(); + await expect(zeta).toBeChecked(); + await expect(count).toHaveText("4"); + await selectAll.uncheck(); + await expect(alpha).not.toBeChecked(); + await expect(zeta).not.toBeChecked(); + await expect(count).toHaveText("0"); + + await zeta.check(); + await expect(count).toHaveText("2"); + const afterSelection = await request.get("/__mockapi/api/configuration"); + expect(await afterSelection.json()).toEqual(await configuration.json()); + await expectNoUnreviewedAccessibilityViolations(page, ".workspace"); + await page.locator("#bulk-disable").click(); + await expect(page.getByText("Disabled 2 endpoints", { exact: true })).toBeVisible(); + const stored = await (await request.get("/__mockapi/api/endpoints")).json(); + expect(stored.filter((endpoint) => endpoint.enabled).map((endpoint) => endpoint.id)).toEqual( + endpoints.filter((endpoint) => endpoint.path.startsWith("/alpha/")).map((endpoint) => endpoint.id) + ); +}); + +test("per-API selection respects filters and preserves hidden selections", async ({ page, request }) => { + const endpoints = ["alpha", "zeta"].flatMap((api, groupIndex) => + ["GET", "POST"].map((method, index) => ({ + id: `00000000-0000-4000-8000-${String(groupIndex * 2 + index + 1).padStart(12, "0")}`, + name: `${api} ${method}`, + enabled: true, + methods: [method], + path: `/${api}/operation`, + response: { statusCode: 200, headers: {}, contentType: "text/plain", body: "ok" }, + })) + ); + await importDocument(request, { ...emptyDocument, endpoints }); + const alpha = page.getByRole("checkbox", { name: "Select all matching endpoints in alpha", exact: true }); + const zeta = page.getByRole("checkbox", { name: "Select all matching endpoints in zeta", exact: true }); + const count = page.locator("#selection-count"); + await page.getByRole("checkbox", { name: "Select alpha POST", exact: true }).check(); + await page.getByRole("checkbox", { name: "Select zeta POST", exact: true }).check(); + await page.locator("#filter-method").selectOption("GET"); + await expect(alpha).not.toBeChecked(); + await expect(zeta).not.toBeChecked(); + await alpha.check(); + await expect(count).toHaveText("3"); + await expect(page.getByRole("checkbox", { name: "Select alpha GET", exact: true })).toBeChecked(); + await expect(page.getByRole("checkbox", { name: "Select zeta GET", exact: true })).not.toBeChecked(); + await alpha.uncheck(); + await expect(count).toHaveText("2"); + await page.locator("#filter-method").selectOption(""); + await expect(alpha).toBeChecked({ indeterminate: true }); + await expect(zeta).toBeChecked({ indeterminate: true }); + await expect(page.getByRole("checkbox", { name: "Select alpha POST", exact: true })).toBeChecked(); + await expect(page.getByRole("checkbox", { name: "Select zeta POST", exact: true })).toBeChecked(); + + await page.locator("#filter-text").fill("/alpha"); + await alpha.check(); + await expect(count).toHaveText("3"); + await page.locator("#filter-text").fill("no matches"); + await expect(page.locator(".endpoint-group-selection")).toHaveCount(0); + await expect(page.locator("#select-all-endpoints")).toBeDisabled(); + await expect(count).toHaveText("3"); + await page.locator("#filter-text").fill(""); + await expect(alpha).toBeChecked(); + await expect(zeta).toBeChecked({ indeterminate: true }); + await expect(count).toHaveText("3"); +}); + +test("@smoke collapses and expands all API groups without changing endpoint configuration or selection", async ({ + page, + request, +}) => { + const control = page.locator("#endpoint-toggle-groups"); + await expect(control).toHaveText("Collapse all groups"); + await expect(control).toBeDisabled(); + await page.getByRole("button", { name: "Load examples" }).first().click(); + const rows = page.locator("#endpoint-rows .endpoint-row"); + const groups = page.locator(".endpoint-group-toggle"); + await expect(rows).toHaveCount(41); + await expect(control).toBeEnabled(); + await rows.first().locator(".selection-checkbox").check(); + const configuration = await request.get("/__mockapi/api/configuration"); + + await control.focus(); + await page.keyboard.press("Enter"); + await expect(control).toHaveText("Expand all groups"); + await expect(control).toBeFocused(); + await expect(rows).toHaveCount(0); + await expect(groups).toHaveCount(3); + await expect(page.locator('.endpoint-group-toggle[aria-expanded="false"]')).toHaveCount(3); + await expect(page.locator("#endpoint-count")).toHaveText("41"); + await expect(page.locator("#selection-count")).toHaveText("1"); + await expectNoUnreviewedAccessibilityViolations(page, ".workspace"); + + await page.keyboard.press("Space"); + await expect(rows).toHaveCount(41); + await expect(control).toHaveText("Collapse all groups"); + await expect(control).toBeFocused(); + await expect(rows.locator(".selection-checkbox:checked")).toHaveCount(1); + await page.getByRole("button", { name: "Collapse inventory", exact: true }).click(); + await expect(control).toHaveText("Collapse all groups"); + await expect(rows).toHaveCount(30); + await control.click(); + await expect(rows).toHaveCount(0); + await expect(control).toHaveText("Expand all groups"); + await page.getByRole("button", { name: "Expand aoai", exact: true }).click(); + await expect(rows).toHaveCount(16); + await expect(control).toHaveText("Collapse all groups"); + await control.click(); + await expect(rows).toHaveCount(0); + await page.getByRole("button", { name: "Collapse endpoints", exact: true }).click(); + await expect(control).toBeHidden(); + await page.getByRole("button", { name: "Expand endpoints", exact: true }).click(); + await expect(control).toHaveText("Expand all groups"); + await control.click(); + await expect(rows).toHaveCount(41); + await expect(rows.locator(".selection-checkbox:checked")).toHaveCount(1); + + const current = await request.get("/__mockapi/api/configuration"); + expect(current.headers().etag).toBe(configuration.headers().etag); + await expectNoUnreviewedAccessibilityViolations(page, ".workspace"); +}); + +test("bulk API group collapse applies to filtered groups and preserves hidden group state", async ({ page }) => { + await page.getByRole("button", { name: "Load examples" }).first().click(); + const control = page.locator("#endpoint-toggle-groups"); + const filter = page.locator("#filter-text"); + const rows = page.locator("#endpoint-rows .endpoint-row"); + await expect(rows).toHaveCount(41); + await filter.fill("/inventory/"); + await expect(rows).toHaveCount(11); + await control.click(); + await expect(rows).toHaveCount(0); + await expect(control).toHaveText("Expand all groups"); + await filter.fill(""); + await expect(rows).toHaveCount(30); + await expect(control).toHaveText("Collapse all groups"); + await expect(page.getByRole("button", { name: "Expand inventory", exact: true })).toBeVisible(); + await filter.fill("no matching API group"); + await expect(page.locator(".endpoint-group-toggle")).toHaveCount(0); + await expect(control).toBeDisabled(); + await filter.fill("/shipping/"); + await expect(rows).toHaveCount(14); + await expect(control).toBeEnabled(); + await control.click(); + await expect(rows).toHaveCount(0); + await filter.fill(""); + await expect(rows).toHaveCount(16); + await expect(page.getByRole("button", { name: "Expand inventory", exact: true })).toBeVisible(); + await expect(page.getByRole("button", { name: "Expand shipping", exact: true })).toBeVisible(); + await control.click(); + await expect(rows).toHaveCount(0); + await control.click(); + await expect(rows).toHaveCount(41); +}); + test("@smoke loads examples idempotently and filters by status", async ({ page, request }) => { await page.getByRole("button", { name: "Load examples" }).first().click(); - await expect(page.locator("#endpoint-rows .endpoint-row")).toHaveCount(16); + await expect(page.locator("#endpoint-rows .endpoint-row")).toHaveCount(41); + await expect(page.locator(".endpoint-group-row")).toHaveCount(3); + await expect(page.getByRole("button", { name: "Collapse aoai", exact: true })).toContainText("16"); await expect(page.getByRole("navigation", { name: "Endpoint pages" })).toHaveCount(0); const responseHeader = page.getByRole("columnheader", { name: "Response" }); await responseHeader.getByRole("button").click(); await responseHeader.getByRole("button").click(); await expect(responseHeader).toHaveAttribute("aria-sort", "descending"); await expect(page.locator("#endpoint-rows .endpoint-row").first().locator(".status-badge")).toHaveText("DROP"); + await expect(page.locator("#endpoint-rows .endpoint-row").nth(16).locator(".status-badge")).toHaveText("503"); + await expect(page.locator("#endpoint-rows .endpoint-row").nth(27).locator(".status-badge")).toHaveText("DROP"); await page.getByRole("columnheader", { name: "Endpoint" }).getByRole("button").click(); - const exampleGroup = page.getByRole("button", { name: "Collapse ctp" }); - await expect(exampleGroup).toContainText("16"); + const exampleGroup = page.getByRole("button", { name: "Collapse inventory" }); + await expect(exampleGroup).toContainText("11"); await page.locator("#endpoint-rows .endpoint-row").first().locator(".selection-checkbox").check(); await expect(page.locator("#selection-count")).toHaveText("1"); await exampleGroup.click(); - await expect(page.locator("#endpoint-rows .endpoint-row")).toHaveCount(0); + await expect(page.locator("#endpoint-rows .endpoint-row")).toHaveCount(30); await expect(page.locator("#selection-count")).toHaveText("1"); await page.locator("#select-all-endpoints").check(); - await expect(page.locator("#selection-count")).toHaveText("16"); - await page.getByRole("button", { name: "Expand ctp" }).click(); - await expect(page.locator("#endpoint-rows .selection-checkbox:checked")).toHaveCount(16); + await expect(page.locator("#selection-count")).toHaveText("41"); + await page.getByRole("button", { name: "Expand inventory" }).click(); + await expect(page.locator("#endpoint-rows .selection-checkbox:checked")).toHaveCount(41); await page.locator("#select-all-endpoints").uncheck(); await page.getByRole("button", { name: "Load examples" }).first().click(); await expect(page.getByText("No example changes were needed")).toBeVisible(); - await expect(page.locator("#endpoint-rows .endpoint-row")).toHaveCount(16); + await expect(page.locator("#endpoint-rows .endpoint-row")).toHaveCount(41); + const completion = await request.post("/aoai/200/chat/completions", { + data: { messages: [{ role: "user", content: "How many Trail flasks are available?" }] }, + }); + expect(completion.status()).toBe(200); + expect((await completion.json()).choices[0].message.content).toContain("Trailhead Supply"); await page.locator("#filter-status").selectOption("3"); - await expect(page.locator("#endpoint-rows .endpoint-row")).toHaveCount(1); - await expect(page.getByRole("row", { name: /Find the featured attraction/ }).locator(".status-badge")).toHaveText( - "302" - ); - const redirect = await request.get("/ctp/attractions/featured", { maxRedirects: 0 }); - expect(redirect.status()).toBe(302); - expect(redirect.headers().location).toBe("/ctp/attractions/cloud-cruiser"); + await expect(page.locator("#endpoint-rows .endpoint-row")).toHaveCount(0); await page.locator("#filter-status").selectOption("5"); - await expect(page.locator("#endpoint-rows .endpoint-row")).toHaveCount(2); - await expect( - page.getByRole("row", { name: /Ticket service maintenance fault demo/ }).locator(".status-badge") - ).toHaveText("503"); - await expect(page.getByRole("row", { name: /Parade schedule timeout demo/ }).locator(".status-badge")).toHaveText( - "500" + await expect(page.locator("#endpoint-rows .endpoint-row")).toHaveCount(7); + await expect(page.getByRole("row", { name: /Warehouse outage fault demo/ }).locator(".status-badge")).toHaveText( + "503" ); - const serverError = await request.get("/ctp/demo-faults/parade-schedule"); - expect(serverError.status()).toBe(500); + await expect(page.getByRole("row", { name: /Carrier timeout fault demo/ }).locator(".status-badge")).toHaveText( + "504" + ); + const serverError = await request.get("/shipping/demo-faults/carrier-timeout"); + expect(serverError.status()).toBe(504); expect(await serverError.json()).toEqual({ - error: "parade_schedule_unavailable", - message: "The parade schedule hit a little hiccup. Please try again later.", + type: "about:blank", + title: "Gateway Timeout", + status: 504, + detail: "The sample carrier did not respond before the fictional gateway deadline.", }); await page.locator("#filter-status").selectOption("4"); - await expect(page.locator("#endpoint-rows .endpoint-row")).toHaveCount(3); + await expect(page.locator("#endpoint-rows .endpoint-row")).toHaveCount(15); await expect( page.getByRole("row", { name: /Reservation validation fault demo/ }).locator(".status-badge") ).toHaveText("422"); - await expect(page.getByRole("row", { name: /Reservation conflict fault demo/ }).locator(".status-badge")).toHaveText( + await expect(page.getByRole("row", { name: /Insufficient stock fault demo/ }).locator(".status-badge")).toHaveText( "409" ); - const rateLimitedRow = page.locator("#endpoint-rows").getByRole("row", { name: /Check Cloud Cruiser wait times/ }); - await expect(rateLimitedRow.locator(".endpoint-name-heading > strong")).toHaveText("Check Cloud Cruiser wait times"); + const rateLimitedRow = page.locator("#endpoint-rows").getByRole("row", { name: /Tracking rate-limit fault demo/ }); + await expect(rateLimitedRow.locator(".endpoint-name-heading > strong")).toHaveText("Tracking rate-limit fault demo"); const responseCode = rateLimitedRow.locator(".status-badge"); await responseCode.hover(); await expect(responseCode).toHaveAttribute("title", "Too Many Requests"); @@ -276,7 +480,7 @@ test("keeps column geometry stable through group collapse and sorting, with cent }) => { const example = await (await request.get("/__mockapi/api/configuration/example")).json(); await importDocument(request, example); - await expect(page.locator(".endpoint-row")).toHaveCount(16); + await expect(page.locator(".endpoint-row")).toHaveCount(41); for (const width of [1200, 1920]) { await page.setViewportSize({ width, height: 1000 }); await expect(page.locator("html")).toHaveAttribute("data-dashboard-layout", width === 1200 ? "stacked" : "columns"); @@ -298,8 +502,12 @@ test("keeps column geometry stable through group collapse and sorting, with cent }; }); const groupCaret = await page.locator(".endpoint-group-chevron").first().boundingBox(); + const groupSelection = await page.locator(".endpoint-group-selection-control").first().boundingBox(); expect(groupCell.paddingInlineStart).toBe("0px"); - expect(groupCaret.x - groupCell.x).toBeLessThanOrEqual(14); + expect(groupSelection.x).toBe(groupCell.x); + expect(groupSelection.width).toBe(34); + expect(groupCaret.x).toBeGreaterThanOrEqual(groupSelection.x + groupSelection.width); + expect(groupCaret.x - (groupSelection.x + groupSelection.width)).toBeLessThanOrEqual(14); for (const [column, maximumWidth] of [ [4, 80], [5, 80], @@ -323,14 +531,14 @@ test("keeps column geometry stable through group collapse and sorting, with cent expect(buttons[0].x).toBeGreaterThanOrEqual(actionBounds.x); expect(buttons.at(-1).x + buttons.at(-1).width).toBeLessThanOrEqual(actionBounds.x + actionBounds.width); for (const button of buttons) expect(button.width).toBe(32); - await page.getByRole("button", { name: "Collapse ctp", exact: true }).click(); - await expect(page.locator(".endpoint-row")).toHaveCount(0); + await page.getByRole("button", { name: "Collapse inventory", exact: true }).click(); + await expect(page.locator(".endpoint-row")).toHaveCount(30); const collapsed = await headers.evaluateAll((cells) => cells.map((cell) => ({ x: cell.getBoundingClientRect().x, width: cell.getBoundingClientRect().width })) ); expect(collapsed).toEqual(original); - await page.getByRole("button", { name: "Expand ctp", exact: true }).click(); - await expect(page.locator(".endpoint-row")).toHaveCount(16); + await page.getByRole("button", { name: "Expand inventory", exact: true }).click(); + await expect(page.locator(".endpoint-row")).toHaveCount(41); const expanded = await headers.evaluateAll((cells) => cells.map((cell) => ({ x: cell.getBoundingClientRect().x, width: cell.getBoundingClientRect().width })) ); @@ -377,10 +585,20 @@ test("duplicate drafts do not display or reuse the source operation ID", async ( ); }); -test("selects multiple or all endpoints for bulk actions", async ({ page }) => { +test("selects multiple or all endpoints beyond former count limits for bulk actions", async ({ page, request }) => { + const endpoints = Array.from({ length: 13 }, (_, index) => ({ + id: `00000000-0000-4000-8000-${String(index + 1).padStart(12, "0")}`, + name: `Custom bulk endpoint ${index + 1}`, + enabled: true, + methods: ["GET"], + path: `/custom-bulk/${index + 1}`, + response: { statusCode: 200, headers: {}, contentType: "text/plain", body: "ok" }, + })); + await importDocument(request, { ...emptyDocument, endpoints }); + await expect(page.locator("#endpoint-rows .endpoint-row")).toHaveCount(13); await page.getByRole("button", { name: "Load examples" }).first().click(); const rows = page.locator("#endpoint-rows .endpoint-row"); - await expect(rows).toHaveCount(16); + await expect(rows).toHaveCount(54); await rows.nth(0).locator(".selection-checkbox").check(); await rows.nth(1).locator(".selection-checkbox").check(); @@ -392,16 +610,16 @@ test("selects multiple or all endpoints for bulk actions", async ({ page }) => { await expect(rows.nth(1).getByRole("checkbox", { name: /^Enable |^Disable / })).not.toBeChecked(); await page.locator("#select-all-endpoints").check(); - await expect(page.locator("#selection-count")).toHaveText("16"); + await expect(page.locator("#selection-count")).toHaveText("54"); await page.getByRole("button", { name: "Enable", exact: true }).click(); - await expect(page.getByText("Enabled 16 endpoints", { exact: true })).toBeVisible(); - await expect(rows.getByRole("checkbox", { name: /^Disable / })).toHaveCount(16); + await expect(page.getByText("Enabled 54 endpoints", { exact: true })).toBeVisible(); + await expect(rows.getByRole("checkbox", { name: /^Disable / })).toHaveCount(54); await page.locator("#select-all-endpoints").check(); await page.locator("#bulk-delete").click(); - await expect(page.getByRole("dialog", { name: "Delete 16 selected endpoints" })).toBeVisible(); + await expect(page.getByRole("dialog", { name: "Delete 54 selected endpoints" })).toBeVisible(); await page - .getByRole("dialog", { name: "Delete 16 selected endpoints" }) + .getByRole("dialog", { name: "Delete 54 selected endpoints" }) .getByRole("button", { name: "Delete", exact: true }) .click(); await expect(rows).toHaveCount(0); @@ -594,7 +812,7 @@ test("reports denied clipboard access when copying an endpoint URL", async ({ pa test("@smoke collapses endpoints and restores the preference", async ({ page }) => { await page.getByRole("button", { name: "Load examples" }).first().click(); - await expect(page.locator("#endpoint-rows .endpoint-row")).toHaveCount(16); + await expect(page.locator("#endpoint-rows .endpoint-row")).toHaveCount(41); await page.getByRole("button", { name: "Collapse endpoints" }).click(); await expect(page.locator("#endpoint-body")).toBeHidden(); @@ -607,7 +825,7 @@ test("@smoke collapses endpoints and restores the preference", async ({ page }) const expand = page.getByRole("button", { name: "Expand endpoints" }); await expect(expand).toHaveAttribute("aria-expanded", "false"); await expand.click(); - await expect(page.locator("#endpoint-rows .endpoint-row")).toHaveCount(16); + await expect(page.locator("#endpoint-rows .endpoint-row")).toHaveCount(41); await expect(page.locator("#endpoint-controls")).toBeVisible(); await expect(page.locator("#endpoint-toggle")).toBeFocused(); }); diff --git a/tests/browser/dashboard-layout.spec.js b/tests/browser/dashboard-layout.spec.js index dbfb87d..4674e9a 100644 --- a/tests/browser/dashboard-layout.spec.js +++ b/tests/browser/dashboard-layout.spec.js @@ -294,7 +294,7 @@ test("uses spare viewport height for Endpoints and Request log without growing S test("fits populated endpoint rows within the wide-screen endpoint column", async ({ page }) => { await page.setViewportSize({ width: 1760, height: 900 }); await page.getByRole("button", { name: "Load examples" }).first().click(); - await expect(page.locator(".endpoint-row")).toHaveCount(16); + await expect(page.locator(".endpoint-row")).toHaveCount(41); await expect(page.locator("html")).toHaveAttribute("data-dashboard-layout", "columns"); const dimensions = await page.locator(".table-wrap").evaluate((element) => ({ @@ -385,7 +385,7 @@ test("keeps expanded endpoint and request log heights stable with keyboard-scrol expect(emptyLog.height).toBeGreaterThanOrEqual(400); expect(Math.abs(emptyEndpoints.y + emptyEndpoints.height - emptyLog.y - emptyLog.height)).toBeLessThanOrEqual(1); - const endpoints = Array.from({ length: 25 }, (_, index) => ({ + const endpoints = Array.from({ length: 50 }, (_, index) => ({ id: `00000000-0000-4000-8000-${String(index + 1).padStart(12, "0")}`, name: `Scroll endpoint ${String(index + 1).padStart(2, "0")}`, enabled: true, @@ -394,12 +394,12 @@ test("keeps expanded endpoint and request log heights stable with keyboard-scrol response: { statusCode: 200, headers: {}, contentType: "text/plain", body: "ok" }, })); await importDocument(request, { ...emptyDocument, endpoints }); - await expect(page.locator("#endpoint-count")).toHaveText("25"); - await expect(page.locator("#endpoint-rows .endpoint-row")).toHaveCount(25); + await expect(page.locator("#endpoint-count")).toHaveText("50"); + await expect(page.locator("#endpoint-rows .endpoint-row")).toHaveCount(50); for (const endpoint of endpoints) { expect((await request.get(endpoint.path)).status()).toBe(200); } - await expect(page.locator("#request-log-count")).toHaveText("25"); + await expect(page.locator("#request-log-count")).toHaveText("50"); expect((await endpointsPanel.boundingBox()).height).toBe(emptyEndpoints.height); expect((await logPanel.boundingBox()).height).toBe(emptyLog.height); for (const [panel, selector] of [ @@ -552,6 +552,16 @@ test("reflows without page overflow", async ({ page }) => { await expect .poll(() => page.evaluate(() => document.documentElement.scrollWidth <= document.documentElement.clientWidth)) .toBe(true); + const groupControl = page.locator("#endpoint-toggle-groups"); + const panelBounds = await page.locator(".workspace").boundingBox(); + const controlBounds = await groupControl.boundingBox(); + expect(controlBounds.x).toBeGreaterThanOrEqual(panelBounds.x); + expect(controlBounds.x + controlBounds.width).toBeLessThanOrEqual(panelBounds.x + panelBounds.width); + await groupControl.click(); + await expect(groupControl).toHaveText("Expand all groups"); + expect((await groupControl.boundingBox()).width).toBe(controlBounds.width); + await groupControl.click(); + await expect(groupControl).toHaveText("Collapse all groups"); await page.getByRole("button", { name: "Test" }).first().click(); const bladeWidth = await page.locator("#test-blade").evaluate((element) => element.getBoundingClientRect().width); const viewportWidth = await page.evaluate(() => document.documentElement.clientWidth); diff --git a/tests/browser/dashboard-management.spec.js b/tests/browser/dashboard-management.spec.js index aae18bf..0eba074 100644 --- a/tests/browser/dashboard-management.spec.js +++ b/tests/browser/dashboard-management.spec.js @@ -320,17 +320,17 @@ test.describe("revision-bound management commands", () => { test("rejects a stale force-merge preview rather than applying unreviewed conflicts", async ({ page, request }) => { const example = await (await request.get("/__mockapi/api/configuration/example")).json(); - const parks = example.endpoints.find((candidate) => candidate.path === "/ctp/parks"); - const locallyChanged = { ...parks, response: { ...parks.response, body: "local change" } }; + const items = example.endpoints.find((candidate) => candidate.path === "/inventory/items"); + const locallyChanged = { ...items, response: { ...items.response, body: "local change" } }; await importDocument(request, { ...emptyDocument, endpoints: [locallyChanged] }); - await expect(page.locator(`.endpoint-row[data-endpoint-id="${parks.id}"]`)).toBeVisible(); + await expect(page.locator(`.endpoint-row[data-endpoint-id="${items.id}"]`)).toBeVisible(); const { etag } = await (await request.get("/__mockapi/api/configuration")).json(); await page.locator("#load-example-button").click(); await expect(page.getByRole("heading", { name: "Built-in configuration conflicts" })).toBeVisible(); await expect(page.locator("#confirm-accept")).toBeEnabled(); const newer = { ...locallyChanged, name: "Newer conflict" }; await importDocument(request, { ...emptyDocument, endpoints: [newer] }); - await expect(page.locator(`.endpoint-row[data-endpoint-id="${parks.id}"]`)).toContainText(newer.name); + await expect(page.locator(`.endpoint-row[data-endpoint-id="${items.id}"]`)).toContainText(newer.name); const rejected = page.waitForResponse((response) => response.url().endsWith("/configuration/example/merge?force=true") @@ -402,10 +402,10 @@ test.describe("revision-bound management commands", () => { test("previews a built-in conflict and force-updates only reviewed endpoints", async ({ page, request }) => { const exampleResponse = await request.get("/__mockapi/api/configuration/example"); const example = await exampleResponse.json(); - const parks = example.endpoints.find((endpoint) => endpoint.path === "/ctp/parks"); - const changedParks = structuredClone(parks); - changedParks.response.body = "changed locally"; - await importDocument(request, { ...emptyDocument, endpoints: [changedParks] }); + const items = example.endpoints.find((endpoint) => endpoint.path === "/inventory/items"); + const changedInventory = structuredClone(items); + changedInventory.response.body = "changed locally"; + await importDocument(request, { ...emptyDocument, endpoints: [changedInventory] }); await page.reload(); await page.getByRole("button", { name: "Load examples" }).first().click(); @@ -416,10 +416,10 @@ test("previews a built-in conflict and force-updates only reviewed endpoints", a await expect(conflictList).toContainText("Different definition (same endpoint ID)"); await expect(conflictList).toContainText("Built-in"); await expect(conflictList).toContainText("Current configuration"); - await expect(conflictList).toContainText("GET /ctp/parks"); + await expect(conflictList).toContainText("GET /inventory/items"); await expectNoUnreviewedAccessibilityViolations(page); await page.getByRole("button", { name: "Force update" }).click(); - await expect(page.locator("#endpoint-rows .endpoint-row")).toHaveCount(16); - const response = await request.get("/ctp/parks"); - expect(await response.text()).toBe(parks.response.body); + await expect(page.locator("#endpoint-rows .endpoint-row")).toHaveCount(41); + const response = await request.get("/inventory/items"); + expect(await response.text()).toBe(items.response.body); }); diff --git a/tests/browser/dashboard-orchestration.spec.js b/tests/browser/dashboard-orchestration.spec.js index 30be4a6..0f792f3 100644 --- a/tests/browser/dashboard-orchestration.spec.js +++ b/tests/browser/dashboard-orchestration.spec.js @@ -277,13 +277,13 @@ test("keeps the viewport fixed when live status updates rerender a focused endpo }) => { await request.post("/__mockapi/api/statistics/reset"); await page.getByRole("button", { name: "Load examples" }).first().click(); - const row = page.locator("#endpoint-rows").getByRole("row", { name: /Discover the parks/ }); + const row = page.locator("#endpoint-rows").getByRole("row", { name: /Browse inventory/ }); const testButton = row.getByRole("button", { name: "Test" }); await page.evaluate(() => window.scrollTo(0, 0)); await testButton.evaluate((button) => button.focus({ preventScroll: true })); expect(await page.evaluate(() => window.scrollY)).toBe(0); - await request.get("/ctp/parks"); + await request.get("/inventory/items"); await expect(row.locator("td").nth(5)).toHaveText("1"); await expect(testButton).toBeFocused(); expect(await page.evaluate(() => window.scrollY)).toBe(0); diff --git a/tests/browser/dashboard-shell.spec.js b/tests/browser/dashboard-shell.spec.js index 3bbdbff..b43bd61 100644 --- a/tests/browser/dashboard-shell.spec.js +++ b/tests/browser/dashboard-shell.spec.js @@ -187,7 +187,7 @@ test("shows keyboard focus on endpoint toggles across color modes", async ({ pag for (const theme of ["light", "dark"]) { await page.goto(`/?scoutTheme=${theme}`); - const toggle = page.getByRole("checkbox", { name: "Disable Check Cloud Cruiser wait times" }); + const toggle = page.getByRole("checkbox", { name: "Disable Tracking rate-limit fault demo" }); await toggle.focus(); await expect(toggle).toBeFocused(); const visibleSwitch = toggle.locator("+ span"); @@ -218,7 +218,7 @@ test("shows keyboard focus on endpoint toggles across color modes", async ({ pag await page.emulateMedia({ forcedColors: "active" }); await page.goto("/?scoutTheme=light"); - const toggle = page.getByRole("checkbox", { name: "Disable Check Cloud Cruiser wait times" }); + const toggle = page.getByRole("checkbox", { name: "Disable Tracking rate-limit fault demo" }); await toggle.focus(); await expect(toggle).toBeFocused(); await expect(toggle.locator("+ span")).toHaveCSS("outline-style", "solid"); diff --git a/tests/browser/dashboard-statistics.spec.js b/tests/browser/dashboard-statistics.spec.js index 89b3b2a..6ce2ef6 100644 --- a/tests/browser/dashboard-statistics.spec.js +++ b/tests/browser/dashboard-statistics.spec.js @@ -58,8 +58,8 @@ test("uses the consolidated Statistics reset control for overall and endpoint sc await page.getByRole("button", { name: "Load examples" }).first().click(); await page .getByLabel("Endpoint statistics") - .selectOption({ label: "Check Cloud Cruiser wait times · /ctp/attractions/cloud-cruiser/wait-times" }); - expect((await request.get("/ctp/attractions/cloud-cruiser/wait-times")).status()).toBe(200); + .selectOption({ label: "Tracking rate-limit fault demo · /shipping/demo-faults/tracking-rate-limit" }); + expect((await request.get("/shipping/demo-faults/tracking-rate-limit")).status()).toBe(200); await expect(page.locator("#metric-total")).toHaveText("1"); const endpointId = await page.getByLabel("Endpoint statistics").inputValue(); await page.getByRole("button", { name: "Reset endpoint", exact: true }).click(); @@ -88,10 +88,10 @@ test("uses the consolidated Statistics reset control for overall and endpoint sc test("shows only configured endpoint requests without retaining query values", async ({ page, request }) => { await page.getByRole("button", { name: "Load examples" }).first().click(); - await expect(page.locator("#endpoint-rows .endpoint-row")).toHaveCount(16); + await expect(page.locator("#endpoint-rows .endpoint-row")).toHaveCount(41); await request.post("/__mockapi/api/statistics/reset"); - const matchedResponse = await request.get("/ctp/parks?token=private-value"); + const matchedResponse = await request.get("/inventory/items?token=private-value"); expect(matchedResponse.status()).toBe(200); const unmatchedResponse = await request.get("/missing-latest?token=private-value"); expect(unmatchedResponse.status()).toBe(404); @@ -118,7 +118,7 @@ test("shows only configured endpoint requests without retaining query values", a await expect(rows.nth(0)).toBeHidden(); await bucketToggle.click(); await expect(rows.nth(0)).toBeVisible(); - await expect(rows.nth(0)).toContainText("/ctp/parks"); + await expect(rows.nth(0)).toContainText("/inventory/items"); await expect(rows.nth(0).locator(".request-log-result")).toHaveClass(/status-2xx/); await expect(rows.nth(0).locator(".request-log-result")).toHaveCSS("text-align", "center"); await expect(page.locator("#metric-unmatched")).toHaveText("1"); @@ -137,8 +137,8 @@ test.describe("request log time zone", () => { }) => { await expect(page.locator(".request-log-empty")).toHaveAttribute("colspan", "6"); await page.getByRole("button", { name: "Load examples" }).first().click(); - await expect(page.locator("#endpoint-rows .endpoint-row")).toHaveCount(16); - expect((await request.get("/ctp/parks")).status()).toBe(200); + await expect(page.locator("#endpoint-rows .endpoint-row")).toHaveCount(41); + expect((await request.get("/inventory/items")).status()).toBe(200); const entryTime = page.locator(".request-log-entry time").first(); const bucketTime = page.locator(".request-log-bucket time").first(); await expect(entryTime).toHaveCount(1); @@ -201,7 +201,7 @@ test.describe("request log time zone", () => { await setting.selectOption("local"); await expectNoUnreviewedAccessibilityViolations(page, "#settings-dialog"); await page.getByRole("button", { name: "Close settings", exact: true }).click(); - expect((await request.get("/ctp/parks")).status()).toBe(200); + expect((await request.get("/inventory/items")).status()).toBe(200); await expect(page.locator(".request-log-entry")).toHaveCount(2); const times = await page.locator(".request-log-entry time").evaluateAll((elements) => { const formatter = new Intl.DateTimeFormat(undefined, { dateStyle: "short", timeStyle: "short" }); @@ -218,9 +218,9 @@ test.describe("request log time zone", () => { test("collapses request log buckets and opens them from statistics columns", async ({ page, request }) => { await page.getByRole("button", { name: "Load examples" }).first().click(); - await expect(page.locator("#endpoint-rows .endpoint-row")).toHaveCount(16); + await expect(page.locator("#endpoint-rows .endpoint-row")).toHaveCount(41); await request.post("/__mockapi/api/statistics/reset"); - const response = await request.get("/ctp/parks"); + const response = await request.get("/inventory/items"); expect(response.status()).toBe(200); const bucketToggle = page.locator(".request-log-bucket-toggle"); @@ -360,24 +360,24 @@ test("bulk bucket controls preserve column widths through collapse, expansion, a test("shows grounded endpoint statistics as a graph and table", async ({ page, request }) => { await page.getByRole("button", { name: "Load examples" }).first().click(); await expect( - page.locator("#endpoint-rows").getByRole("row", { name: /Check Cloud Cruiser wait times/ }) + page.locator("#endpoint-rows").getByRole("row", { name: /Tracking rate-limit fault demo/ }) ).toBeVisible(); await request.post("/__mockapi/api/statistics/reset"); - for (let attempt = 0; attempt < 4; attempt += 1) { - const response = await request.get("/ctp/attractions/cloud-cruiser/wait-times"); + for (let attempt = 0; attempt < 2; attempt += 1) { + const response = await request.get("/shipping/demo-faults/tracking-rate-limit"); expect(response.status()).toBe(200); } - const limitedResponse = await request.get("/ctp/attractions/cloud-cruiser/wait-times"); + const limitedResponse = await request.get("/shipping/demo-faults/tracking-rate-limit"); expect(limitedResponse.status()).toBe(429); await page.getByRole("button", { name: "By endpoint" }).click(); await page .getByLabel("Endpoint statistics") - .selectOption({ label: "Check Cloud Cruiser wait times · /ctp/attractions/cloud-cruiser/wait-times" }); - await expect(page.locator("#statistics-chart-title")).toHaveText("Check Cloud Cruiser wait times attempt activity"); + .selectOption({ label: "Tracking rate-limit fault demo · /shipping/demo-faults/tracking-rate-limit" }); + await expect(page.locator("#statistics-chart-title")).toHaveText("Tracking rate-limit fault demo attempt activity"); await expect(page.locator("#statistics-chart")).toHaveAttribute( "aria-label", - /The first 4 requests within 10 seconds return HTTP 200; later requests return HTTP 429\./ + /The first 2 requests within 10 seconds return HTTP 200; later requests return HTTP 429\./ ); const chartScroll = page.getByRole("region", { name: /Attempt activity timeline/ }); const chartViewport = await chartScroll.evaluate((element) => ({ @@ -395,15 +395,15 @@ test("shows grounded endpoint statistics as a graph and table", async ({ page, r .evaluateAll((items) => new Set(items.map((item) => item.offsetTop)).size); expect(responseStatusLegendRowCount).toBe(1); const activeColumn = page.locator("#statistics-chart .chart-column.active").last(); - await expect(activeColumn.locator(".status-2xx")).toHaveCSS("flex-grow", "4"); + await expect(activeColumn.locator(".status-2xx")).toHaveCSS("flex-grow", "2"); await expect(activeColumn.locator(".status-4xx")).toHaveCSS("flex-grow", "1"); await expect(activeColumn.locator(".status-2xx")).toHaveCSS("background-color", /rgb\((22, 114, 58|114, 214, 154)\)/); await expect(activeColumn.locator(".status-4xx")).toHaveCSS("background-color", /rgb\((189, 30, 44|255, 138, 150)\)/); await activeColumn.hover(); const tooltip = page.locator(".chart-tooltip"); await expect(tooltip).toBeVisible(); - await expect(tooltip.locator(".chart-tooltip-heading")).toContainText("5 attempts"); - await expect(tooltip.locator(".chart-tooltip-row")).toHaveText(["1xx0", "2xx4", "3xx0", "4xx1", "5xx0", "Other0"]); + await expect(tooltip.locator(".chart-tooltip-heading")).toContainText("3 attempts"); + await expect(tooltip.locator(".chart-tooltip-row")).toHaveText(["1xx0", "2xx2", "3xx0", "4xx1", "5xx0", "Other0"]); await expect(tooltip.locator(".status-2xx")).toHaveCSS("background-color", /rgb\((22, 114, 58|114, 214, 154)\)/); await expect(tooltip.locator(".status-4xx")).toHaveCSS("background-color", /rgb\((189, 30, 44|255, 138, 150)\)/); @@ -423,12 +423,12 @@ test("shows grounded endpoint statistics as a graph and table", async ({ page, r await expect(statisticsTable.getByRole("columnheader", { name: "Attempts" })).toBeVisible(); const statisticsRow = page .locator("#statistics-table-view tbody tr") - .filter({ hasText: "Check Cloud Cruiser wait times" }); - await expect(statisticsRow).toContainText("5"); + .filter({ hasText: "Tracking rate-limit fault demo" }); + await expect(statisticsRow).toContainText("3"); await expect(statisticsRow).toContainText("attempts/min"); await page .locator(".request-log-entry") - .filter({ hasText: "/ctp/attractions/cloud-cruiser/wait-times" }) + .filter({ hasText: "/shipping/demo-faults/tracking-rate-limit" }) .filter({ has: page.locator(".status-4xx") }) .hover(); await expectNoUnreviewedAccessibilityViolations(page); diff --git a/tests/browser/dashboard-test-blade.spec.js b/tests/browser/dashboard-test-blade.spec.js index 92c2f99..d7730a8 100644 --- a/tests/browser/dashboard-test-blade.spec.js +++ b/tests/browser/dashboard-test-blade.spec.js @@ -55,21 +55,21 @@ test("tests a configured non-2xx response and restores focus", async ({ page, re const exampleResponse = await request.get("/__mockapi/api/configuration/example"); const example = await exampleResponse.json(); expect( - example.endpoints.find((endpoint) => endpoint.path === "/ctp/attractions/cloud-cruiser/wait-times").requestCount - ).toBe(5); + example.endpoints.find((endpoint) => endpoint.path === "/shipping/demo-faults/tracking-rate-limit").requestCount + ).toBe(3); await page.getByRole("button", { name: "Load examples" }).first().click(); - const row = page.getByRole("row", { name: /Check Cloud Cruiser wait times/ }); + const row = page.getByRole("row", { name: /Tracking rate-limit fault demo/ }); const trigger = row.getByRole("button", { name: "Test" }); await trigger.click(); - await page.getByLabel("Path and query").fill("/ctp/attractions/cloud-cruiser/wait-times?browser=1"); + await page.getByLabel("Path and query").fill("/shipping/demo-faults/tracking-rate-limit?browser=1"); const requestCount = page.getByLabel("Number of requests"); - await expect(requestCount).toHaveValue("5"); + await expect(requestCount).toHaveValue("3"); await expect(requestCount).toHaveAttribute("min", "1"); await expect(requestCount).toHaveAttribute("max", "5"); await page.getByRole("button", { name: "Send request" }).click(); - await expect(page.locator("#test-status")).toHaveText("5 requests completed; final response HTTP 429."); + await expect(page.locator("#test-status")).toHaveText("3 requests completed; final response HTTP 429."); await expect(page.locator("#test-response-body")).toHaveText( - '{"error":"wait_times_rate_limited","message":"Take a little breather! Check back in 10 seconds."}' + '{"type":"about:blank","title":"Too Many Requests","status":429,"detail":"The sample tracking request limit was exceeded. Retry in 10 seconds."}' ); await expect(page.locator("#test-response-headers")).toContainText("x-mock-source"); const colonColumns = await page.locator("#test-response-headers").evaluate((element) => @@ -87,7 +87,7 @@ test("tests a configured non-2xx response and restores focus", async ({ page, re test("aligns request information icons and shares hover and focus tooltip behavior", async ({ page }) => { await page.getByRole("button", { name: "Load examples" }).first().click(); await page - .getByRole("row", { name: /Reserve a ride/ }) + .getByRole("row", { name: /Reserve inventory/ }) .getByRole("button", { name: "Test" }) .click(); @@ -175,7 +175,7 @@ test("aligns request information icons and shares hover and focus tooltip behavi await page.locator("#test-blade-close").click(); await expect(page.locator("#test-request-body-hint")).toBeHidden(); await page - .getByRole("row", { name: /Reserve a ride/ }) + .getByRole("row", { name: /Reserve inventory/ }) .getByRole("button", { name: "Test" }) .click(); await expect(guidance).toBeHidden(); @@ -191,19 +191,16 @@ test("aligns request information icons and shares hover and focus tooltip behavi test("prefills an editable sample and displays real backend payload errors", async ({ page, request }) => { await request.post("/__mockapi/api/statistics/reset"); await page.getByRole("button", { name: "Load examples" }).first().click(); - const createRow = page.getByRole("row", { name: /Reserve a ride/ }); + const createRow = page.getByRole("row", { name: /Reserve inventory/ }); await createRow.getByRole("button", { name: "Test" }).click(); const headers = page.locator("#test-request-headers"); const body = page.locator("#test-request-body"); await expect(headers).toHaveValue("Content-Type: application/json; charset=utf-8"); expect(JSON.parse(await body.inputValue())).toEqual({ - parkId: "starlight-gardens", - attractionId: "cloud-cruiser", - reservationDate: "2030-06-15", - reservationTime: "10:30", - partySize: 2, - guest: { name: "Alex Morgan", email: "alex@example.com" }, + sku: "SKU-1001", + quantity: 2, + warehouseId: "WH-DEMO-01", }); await page.getByRole("button", { name: "Request header information" }).click(); await expect(page.getByText("The browser requires valid header syntax", { exact: false })).toBeVisible(); @@ -220,7 +217,8 @@ test("prefills an editable sample and displays real backend payload errors", asy ]) { await body.fill(payload); const responsePromise = page.waitForResponse( - (response) => new URL(response.url()).pathname === "/ctp/reservations" && response.request().method() === "POST" + (response) => + new URL(response.url()).pathname === "/inventory/reservations" && response.request().method() === "POST" ); await page.getByRole("button", { name: "Send request" }).click(); const response = await responsePromise; @@ -232,7 +230,7 @@ test("prefills an editable sample and displays real backend payload errors", asy await expect(page.locator("#test-response-body")).toContainText('"status":400'); } else { await expect(page.locator("#test-status")).toHaveText("Request completed with HTTP 201."); - await expect(page.locator("#test-response-body")).toContainText('"confirmationCode":"CTP-0042"'); + await expect(page.locator("#test-response-body")).toContainText('"id":"res-demo-001"'); } } @@ -286,32 +284,29 @@ test("prefills POST PUT and PATCH without replacing deliberate request edits", a await expect(body).toHaveValue("{deliberately-malformed"); }); -test("tests body-bearing and empty-response endpoints", async ({ page }) => { +test("tests body-bearing and empty-response endpoints", async ({ page, request }) => { + const example = await (await request.get("/__mockapi/api/configuration/example")).json(); + const reservationBody = example.endpoints.find((endpoint) => endpoint.path === "/inventory/reservations").response + .body; await page.getByRole("button", { name: "Load examples" }).first().click(); - const createRow = page.getByRole("row", { name: /Reserve a ride/ }); + const createRow = page.getByRole("row", { name: /Reserve inventory/ }); await createRow.getByRole("button", { name: "Test" }).click(); await page.getByLabel("Request headers", { exact: true }).fill("Content-Type: application/json; charset=utf-8"); - await page.getByLabel("Request body", { exact: true }).fill('{"attractionId":"cloud-cruiser","partySize":2}'); + await page.getByLabel("Request body", { exact: true }).fill('{"sku":"SKU-1001","quantity":2}'); await page.getByRole("button", { name: "Send request" }).click(); await expect(page.locator("#test-status")).toHaveText("Request completed with HTTP 201."); - await expect(page.locator("#test-response-body")).toHaveText( - '{"id":42,"parkId":"starlight-gardens","attractionId":"cloud-cruiser","partySize":2,"status":"reserved","confirmationCode":"CTP-0042","message":"Your Cloud Cruiser reservation is confirmed."}' - ); + await expect(page.locator("#test-response-body")).toHaveText(reservationBody); const prettyPrint = page.getByRole("button", { name: "Pretty print" }); await expect(prettyPrint).toBeVisible(); await prettyPrint.click(); await expect(page.locator("#test-response-body-label")).toHaveText("Pretty response body"); - await expect(page.locator("#test-response-body")).toHaveText( - '{\n "id": 42,\n "parkId": "starlight-gardens",\n "attractionId": "cloud-cruiser",\n "partySize": 2,\n "status": "reserved",\n "confirmationCode": "CTP-0042",\n "message": "Your Cloud Cruiser reservation is confirmed."\n}' - ); + await expect(page.locator("#test-response-body")).toHaveText(JSON.stringify(JSON.parse(reservationBody), null, 2)); await page.getByRole("button", { name: "Show raw" }).click(); await expect(page.locator("#test-response-body-label")).toHaveText("Raw response body"); - await expect(page.locator("#test-response-body")).toHaveText( - '{"id":42,"parkId":"starlight-gardens","attractionId":"cloud-cruiser","partySize":2,"status":"reserved","confirmationCode":"CTP-0042","message":"Your Cloud Cruiser reservation is confirmed."}' - ); + await expect(page.locator("#test-response-body")).toHaveText(reservationBody); await page.keyboard.press("Escape"); - const deleteRow = page.getByRole("row", { name: /Cancel your ride reservation/ }); + const deleteRow = page.getByRole("row", { name: /Cancel the sample reservation/ }); await deleteRow.getByRole("button", { name: "Test" }).click(); await page.getByRole("button", { name: "Send request" }).click(); await expect(page.locator("#test-status")).toHaveText("Request completed with HTTP 204."); @@ -328,11 +323,11 @@ test("prefers and persists pretty endpoint test responses when available", async await responseBodyDisplay.selectOption("pretty"); await settings.getByRole("button", { name: "Done" }).click(); - const row = page.getByRole("row", { name: /Reserve a ride/ }); + const row = page.getByRole("row", { name: /Reserve inventory/ }); await row.getByRole("button", { name: "Test" }).click(); await page.getByRole("button", { name: "Send request" }).click(); await expect(page.locator("#test-response-body-label")).toHaveText("Pretty response body"); - await expect(page.locator("#test-response-body")).toContainText('\n "id": 42,'); + await expect(page.locator("#test-response-body")).toContainText('\n "id": "res-demo-001",'); await expect(page.getByRole("button", { name: "Show raw" })).toBeVisible(); await page.getByRole("button", { name: "Close endpoint test" }).last().click(); @@ -347,7 +342,7 @@ test("prefers and persists pretty endpoint test responses when available", async test("keeps request and response sections compact and closes from the backdrop", async ({ page }) => { await page.getByRole("button", { name: "Load examples" }).first().click(); - const trigger = page.getByRole("row", { name: /Discover the parks/ }).getByRole("button", { name: "Test" }); + const trigger = page.getByRole("row", { name: /Browse inventory/ }).getByRole("button", { name: "Test" }); await trigger.click(); const requestActions = await page.locator(".test-actions").boundingBox(); @@ -363,48 +358,81 @@ test("keeps request and response sections compact and closes from the backdrop", await expect(trigger).toBeFocused(); }); -for (const { name, path, status, contentType } of [ +for (const { name, path, status, contentType, method } of [ + { + name: "Trailhead assistant - success", + path: "/aoai/200/chat/completions", + status: 200, + contentType: "application/json; charset=utf-8", + }, { name: "Reservation validation fault demo", - path: "/ctp/demo-faults/reservation-validation", + path: "/inventory/demo-faults/invalid-reservation", status: 422, contentType: "application/problem+json; charset=utf-8", }, { - name: "Reservation conflict fault demo", - path: "/ctp/demo-faults/reservation-conflict", + name: "Insufficient stock fault demo", + path: "/inventory/demo-faults/insufficient-stock", status: 409, contentType: "application/problem+json; charset=utf-8", }, { - name: "Ticket service maintenance fault demo", - path: "/ctp/demo-faults/ticket-service", + name: "Warehouse outage fault demo", + path: "/inventory/demo-faults/warehouse-unavailable", status: 503, contentType: "application/problem+json; charset=utf-8", }, { - name: "Download the park schedule", - path: "/ctp/parks/starlight-gardens/schedule.csv", + name: "Download a demonstration label", + path: "/shipping/shipments/shp-demo-001/label.txt", status: 200, - contentType: "text/csv; charset=utf-8", + contentType: "text/plain; charset=utf-8", }, { - name: "Update your ride reservation", - path: "/ctp/reservations/42", - status: 200, + name: "Create a sample shipment", + path: "/shipping/shipments", + status: 201, contentType: "application/json; charset=utf-8", }, { - name: "Check reservation preflight", - path: "/ctp/reservations/42", + name: "Cancel the sample reservation", + path: "/inventory/reservations/res-demo-001", status: 204, contentType: null, }, { - name: "Check the park API health", - path: "/ctp/health", + name: "Inspect an in-stock product", + path: "/inventory/items/SKU-1001", + status: 200, + contentType: "application/json; charset=utf-8", + }, + { + name: "Inspect the sample shipment", + path: "/shipping/shipments/shp-demo-001", + status: 200, + contentType: "application/json; charset=utf-8", + }, + { + name: "Trailhead assistant - health", + path: "/aoai/health", + status: 200, + contentType: null, + method: "HEAD", + }, + { + name: "Inventory API health", + path: "/inventory/health", + status: 200, + contentType: null, + method: "HEAD", + }, + { + name: "Shipping API health", + path: "/shipping/health", status: 200, contentType: null, + method: "HEAD", }, ]) { test(`previews and tests the built-in ${name} example`, async ({ page, request }) => { @@ -419,61 +447,93 @@ for (const { name, path, status, contentType } of [ await row.getByRole("button", { name: "Test", exact: true }).click(); await expect(page.getByLabel("Path and query")).toHaveValue(path); await expect(page.locator("#test-method")).toHaveValue(endpoint.methods[0]); + if (method) await page.locator("#test-method").selectOption(method); if (endpoint.methods.includes("POST") || endpoint.methods.includes("PATCH")) { - await page.getByLabel("Request body", { exact: true }).fill('{"partySize":2}'); + await page.getByLabel("Request body", { exact: true }).fill('{"quantity":2}'); } await page.getByRole("button", { name: "Send request" }).click(); await expect(page.locator("#test-status")).toHaveText(`Request completed with HTTP ${status}.`); - await expect(page.locator("#test-response-body")).toHaveText(endpoint.response.body || "Empty response body."); + await expect(page.locator("#test-response-body")).toHaveText( + method === "HEAD" ? "Empty response body." : endpoint.response.body || "Empty response body." + ); if (contentType) { await expect(page.locator("#test-response-headers")).toContainText(contentType); } if (status === 503) { await expect(page.locator("#test-response-headers")).toContainText(/retry-after\s*: 30/); } - if (contentType?.startsWith("text/csv")) { + if (contentType?.startsWith("text/plain")) { await expect(page.locator("#test-response-headers")).toContainText( - 'attachment; filename="starlight-gardens-schedule.csv"' + "attachment; filename=shipping-label-demo-001.txt" ); } - if (endpoint.methods.includes("PATCH")) { - expect((await (await request.get(path)).json()).partySize).toBe(2); - } - if (endpoint.methods.includes("OPTIONS")) { - await expect(page.locator("#test-response-headers")).toContainText(/allow\s*: GET, PATCH, DELETE, OPTIONS/); - await expect(page.locator("#test-response-headers")).toContainText( - /access-control-allow-methods\s*: PATCH, OPTIONS/ - ); - await expect(page.locator("#test-response-headers")).not.toContainText(/(?:^|\n)content-type\s*:/); - } if (endpoint.methods.includes("HEAD")) { await expect(page.locator("#test-response-headers")).toContainText(/x-mock-source\s*: MockAPI/); - await expect(page.locator("#test-response-headers")).not.toContainText(/(?:^|\n)content-type\s*:/); expect((await request.get(path)).status()).toBe(404); - expect((await request.head("/ctp/parks")).status()).toBe(404); - await expect(page.getByRole("row", { name: /Discover the parks/ }).locator(".method-badge")).toHaveText(["GET"]); + } else if (name.startsWith("Inspect")) { + expect((await request.head(path)).status()).toBe(404); + await expect(row.locator(".method-badge")).toHaveText(["GET"]); } }); } test("performs a cross-origin PATCH preflight with API-key protection disabled", async ({ page, request, baseURL }) => { - const example = await (await request.get("/__mockapi/api/configuration/example")).json(); - await page.getByRole("button", { name: "Load examples" }).first().click(); - await expect(page.locator("#endpoint-rows .endpoint-row")).toHaveCount(example.endpoints.length); + const corsHeaders = { + "Access-Control-Allow-Origin": ["*"], + "Access-Control-Allow-Methods": ["PATCH, OPTIONS"], + "Access-Control-Allow-Headers": ["Content-Type, X-MockAPI-Key"], + "Access-Control-Expose-Headers": ["X-Mock-Source"], + "X-Mock-Source": ["MockAPI"], + }; + const preflight = { + id: "c4880e93-664a-4c8f-8915-bdd01f629311", + name: "CORS preflight", + enabled: true, + methods: ["OPTIONS"], + path: "/cors/item", + response: { statusCode: 204, headers: corsHeaders, body: "" }, + }; + await importDocument(request, { + schemaVersion: "1.0", + endpoints: [ + preflight, + { + id: "9ebf089a-cc5a-46c6-9e8e-3a953204f9ab", + name: "CORS update", + enabled: true, + methods: ["PATCH"], + path: "/cors/item", + response: { + statusCode: 200, + headers: corsHeaders, + contentType: "application/json", + body: '{"status":"updated"}', + }, + }, + { + id: "46cfac48-20c3-40d9-99cc-c27e2bc020f0", + name: "CORS lookup", + enabled: true, + methods: ["GET"], + path: "/cors/item", + response: { statusCode: 200, headers: {}, contentType: "application/json", body: '{"status":"original"}' }, + }, + ], + }); const clientUrl = new URL(baseURL); clientUrl.hostname = "localhost"; await page.goto(clientUrl.href); await expect(page.locator("#connection-status")).toHaveText("Live"); const result = await page.evaluate(async (url) => { - const response = await fetch(`${url}/ctp/reservations/42`, { + const response = await fetch(`${url}/cors/item`, { method: "PATCH", credentials: "omit", headers: { "Content-Type": "application/json", "X-MockAPI-Key": "sample-key-for-cors-demo", }, - body: '{"partySize":6}', + body: '{"status":"requested"}', }); return { status: response.status, @@ -483,13 +543,12 @@ test("performs a cross-origin PATCH preflight with API-key protection disabled", }, baseURL); expect(result.status).toBe(200); expect(result.source).toBe("MockAPI"); - expect(result.body.partySize).toBe(4); - expect((await (await request.get("/ctp/reservations/42")).json()).partySize).toBe(2); - const options = example.endpoints.find((endpoint) => endpoint.methods.includes("OPTIONS")); + expect(result.body).toEqual({ status: "updated" }); + expect(await (await request.get("/cors/item")).json()).toEqual({ status: "original" }); await expect .poll(async () => { const statistics = await (await request.get("/__mockapi/api/statistics")).json(); - return statistics.endpoints.find((endpoint) => endpoint.endpointId === options.id)?.totalRequests; + return statistics.endpoints.find((endpoint) => endpoint.endpointId === preflight.id)?.totalRequests; }) .toBe(1); }); @@ -497,13 +556,15 @@ test("performs a cross-origin PATCH preflight with API-key protection disabled", test("reports endpoint-test network errors", async ({ page, request }) => { await request.post("/__mockapi/api/statistics/reset"); await page.getByRole("button", { name: "Load examples" }).first().click(); - const row = page.locator("#endpoint-rows").getByRole("row", { name: /Ride sensor connection fault demo/ }); + const row = page.locator("#endpoint-rows").getByRole("row", { name: /Carrier connection fault demo/ }); await expect(row).toContainText("DROP"); await row.getByRole("button", { name: "Test" }).click(); await page.getByRole("button", { name: "Send request" }).click(); await expect(page.locator("#test-status")).toContainText("Network error:"); const requestLog = page.getByRole("region", { name: "Recent request log" }); - const loggedRow = requestLog.locator(".request-log-entry").filter({ hasText: "/ctp/demo-faults/ride-sensor" }); + const loggedRow = requestLog + .locator(".request-log-entry") + .filter({ hasText: "/shipping/demo-faults/connection-failure" }); await expect(loggedRow).toHaveCount(1); await expect .poll(async () => Number(await loggedRow.locator(".request-log-attempts").textContent())) @@ -523,11 +584,11 @@ test("reports endpoint-test network errors", async ({ page, request }) => { test("cancels an active endpoint test", async ({ page }) => { await page.getByRole("button", { name: "Load examples" }).first().click(); - await page.route("**/ctp/parks", async (route) => { + await page.route("**/inventory/items", async (route) => { await new Promise((resolve) => setTimeout(resolve, 2_000)); await route.abort(); }); - const row = page.getByRole("row", { name: /Discover the parks/ }); + const row = page.getByRole("row", { name: /Browse inventory/ }); await row.getByRole("button", { name: "Test" }).click(); await page.getByRole("button", { name: "Send request" }).click(); await page.getByRole("button", { name: "Cancel", exact: true }).click(); diff --git a/tests/frontend/dashboard-core.test.js b/tests/frontend/dashboard-core.test.js index 41a8e59..52d773c 100644 --- a/tests/frontend/dashboard-core.test.js +++ b/tests/frontend/dashboard-core.test.js @@ -148,10 +148,10 @@ describe("sortEndpoints", () => { describe("getEndpointDisplayPath", () => { it.each([ - ["/ctp/parks", "/parks"], - ["/ctp/attractions/ctp", "/attractions/ctp"], - ["/ctp", "/"], - ["/ctp/", "/"], + ["/inventory/items", "/items"], + ["/inventory/attractions/inventory", "/attractions/inventory"], + ["/inventory", "/"], + ["/inventory/", "/"], ["/", "/"], ])("displays %s as %s without its group prefix", (path, expected) => { expect(getEndpointDisplayPath(path)).toBe(expected); diff --git a/tests/frontend/dashboard-dom.test.js b/tests/frontend/dashboard-dom.test.js index 98e32a0..93024b4 100644 --- a/tests/frontend/dashboard-dom.test.js +++ b/tests/frontend/dashboard-dom.test.js @@ -7,9 +7,17 @@ import { } from "../../src/MockAPI/wwwroot/dashboard-dom.js"; describe("shared information tooltips", () => { - function createTooltipFixture({ top = 100, bottom = 126, right = 200, height = 120, width = 360, onActivate } = {}) { + function createTooltipFixture({ + top = 100, + bottom = 126, + right = 200, + height = 120, + width = 360, + viewportHeight = 800, + onActivate, + } = {}) { const trigger = Object.assign(new EventTarget(), { - ownerDocument: { defaultView: { innerHeight: 800, innerWidth: 1000 } }, + ownerDocument: { defaultView: { innerHeight: viewportHeight, innerWidth: 1000 } }, getBoundingClientRect: () => ({ top, bottom, right }), matches: vi.fn(() => false), }); @@ -28,7 +36,7 @@ describe("shared information tooltips", () => { const { trigger, tooltip, preview } = createTooltipFixture(); trigger.dispatchEvent(new Event("mouseenter")); expect(tooltip.showPopover).toHaveBeenCalledTimes(1); - expect(tooltip.style).toEqual({ top: "126px", left: "8px", maxHeight: "320px" }); + expect(tooltip.style).toEqual({ top: "126px", left: "8px", maxHeight: "400px" }); trigger.dispatchEvent(new Event("mouseleave")); expect(tooltip.hidePopover).toHaveBeenCalledTimes(1); trigger.dispatchEvent(new Event("focus")); @@ -47,13 +55,30 @@ describe("shared information tooltips", () => { it("places tall previews above their trigger and keeps them within the right viewport edge", () => { const { trigger, tooltip } = createTooltipFixture({ top: 700, bottom: 726, right: 1100, height: 200 }); trigger.dispatchEvent(new Event("mouseenter")); - expect(tooltip.style).toEqual({ top: "500px", left: "632px", maxHeight: "320px" }); + expect(tooltip.style).toEqual({ top: "500px", left: "632px", maxHeight: "400px" }); }); it("uses the larger space below for an oversized preview and limits its height", () => { const { trigger, tooltip } = createTooltipFixture({ top: 300, bottom: 326, right: 600, height: 700 }); trigger.dispatchEvent(new Event("focus")); - expect(tooltip.style).toEqual({ top: "326px", left: "240px", maxHeight: "320px" }); + expect(tooltip.style).toEqual({ top: "326px", left: "240px", maxHeight: "400px" }); + }); + + it("limits previews to sixty percent of a short viewport", () => { + const { trigger, tooltip } = createTooltipFixture({ viewportHeight: 500 }); + trigger.dispatchEvent(new Event("focus")); + expect(tooltip.style.maxHeight).toBe("300px"); + }); + + it("limits previews to the available space beside the trigger", () => { + const { trigger, tooltip } = createTooltipFixture({ + top: 280, + bottom: 306, + viewportHeight: 600, + height: 500, + }); + trigger.dispatchEvent(new Event("focus")); + expect(tooltip.style).toEqual({ top: "306px", left: "8px", maxHeight: "286px" }); }); it("activates the editor without reopening help when focus is restored", () => { diff --git a/tests/frontend/dashboard-test-request.test.js b/tests/frontend/dashboard-test-request.test.js index 1e52a23..d7201fe 100644 --- a/tests/frontend/dashboard-test-request.test.js +++ b/tests/frontend/dashboard-test-request.test.js @@ -68,16 +68,23 @@ describe("createDefaultTestRequest", () => { }); }); - it("provides a reservation-specific sample for the built-in reservation routes", () => { - for (const path of ["/ctp/reservations", "/ctp/reservations/42?include=guest"]) { + it("provides an inventory-specific sample for the built-in reservation routes", () => { + for (const path of ["/inventory/reservations", "/inventory/reservations/res-demo-001?include=guest"]) { const defaults = createDefaultTestRequest("POST", path); expect(JSON.parse(defaults.body)).toEqual({ - parkId: "starlight-gardens", - attractionId: "cloud-cruiser", - reservationDate: "2030-06-15", - reservationTime: "10:30", - partySize: 2, - guest: { name: "Alex Morgan", email: "alex@example.com" }, + sku: "SKU-1001", + quantity: 2, + warehouseId: "WH-DEMO-01", + }); + } + }); + + it("provides a shipping-specific sample for the built-in shipment routes", () => { + for (const path of ["/shipping/shipments", "/shipping/shipments/shp-demo-001?include=tracking"]) { + expect(JSON.parse(createDefaultTestRequest("POST", path).body)).toEqual({ + service: "standard", + parcelWeightKg: 1.2, + items: [{ sku: "SKU-1001", quantity: 2 }], }); } }); diff --git a/tests/frontend/onboarding.test.js b/tests/frontend/onboarding.test.js index 07b5476..5c43336 100644 --- a/tests/frontend/onboarding.test.js +++ b/tests/frontend/onboarding.test.js @@ -1,6 +1,10 @@ import fs from "node:fs"; import path from "node:path"; +import { execFile, execFileSync } from "node:child_process"; +import { once } from "node:events"; +import { createServer } from "node:http"; import { createRequire } from "node:module"; +import { promisify } from "node:util"; import { describe, expect, it } from "vitest"; const require = createRequire(import.meta.url); @@ -31,6 +35,9 @@ describe("public onboarding boundaries", () => { expect(fs.readFileSync(path.join(output, "site.css"), "utf8")).toBe(renderSiteStyles()); const index = fs.readFileSync(path.join(output, "index.html"), "utf8"); expect(index).toContain(`Version ${readApplicationVersion()}`); + expect(index).toContain("https://github.com/simonkurtz-MSFT/MockAPI/blob/main/config/trailhead-inventory.json"); + expect(index).toContain("https://github.com/simonkurtz-MSFT/MockAPI/blob/main/config/trailhead-shipping.json"); + expect(index).toContain("https://github.com/simonkurtz-MSFT/MockAPI/blob/main/config/trailhead-aoai.json"); expect(index).toContain(''); expect(index).not.toMatch(/\{\{(?:VERSION|BUILD_DATE_(?:ISO|DISPLAY))\}\}/); const unexpected = path.join(output, "unexpected-test-fixture.txt"); @@ -55,6 +62,49 @@ describe("public onboarding boundaries", () => { expect(totalBytes).toBeLessThanOrEqual(160 * 1024); }); + it("tracks the Bash entry point as executable for Linux checkouts", () => { + const entry = execFileSync("git", ["ls-files", "--stage", "--", "start.sh"], { + cwd: root, + encoding: "utf8", + }); + expect(entry).toMatch(/^100755 /); + }); + + it( + "retries connection resets and unavailable responses until the development app is ready", + { timeout: 15_000 }, + async () => { + const readinessLine = read(".github/workflows/devcontainer.yml") + .split("\n") + .find((line) => /^\s*curl /.test(line) && line.includes("/health/ready")); + expect(readinessLine).toBeDefined(); + const [command, ...arguments_] = readinessLine.trim().split(/\s+/); + let attempts = 0; + const server = createServer((request, response) => { + attempts++; + if (attempts === 1) { + request.socket.resetAndDestroy(); + return; + } + response.statusCode = attempts === 2 ? 503 : 200; + response.end(attempts === 2 ? "starting" : "ready"); + }); + server.listen(0, "127.0.0.1"); + await once(server, "listening"); + try { + const address = server.address(); + arguments_[arguments_.length - 1] = `http://127.0.0.1:${address.port}/health/ready`; + const { stdout } = await promisify(execFile)(command, arguments_, { timeout: 10_000 }); + expect(stdout).toBe("ready"); + expect(attempts).toBe(3); + } finally { + server.closeAllConnections(); + server.close(); + await once(server, "close"); + } + } + ); + it("keeps the development workspace non-root without privileged features or automatic public exposure", () => { const config = JSON.parse(read(".devcontainer/devcontainer.json")); expect(config.image).toMatch(/^mcr\.microsoft\.com\/devcontainers\/dotnet:[^@]+@sha256:[a-f0-9]{64}$/); @@ -66,7 +116,7 @@ describe("public onboarding boundaries", () => { expect(config.privileged).toBeUndefined(); expect(config.features).toBeUndefined(); expect(config.containerEnv.MOCKAPI_NODE_VERSION).toMatch(/^\d+\.\d+\.\d+$/); - expect(read(".devcontainer/setup.sh")).not.toContain("cp config/mockapi.json"); + expect(read(".devcontainer/setup.sh")).not.toContain("cp config/trailhead-inventory.json"); expect(read(".devcontainer/setup.sh")).toContain('source "$NVM_DIR/nvm.sh" --no-use'); expect(read(".devcontainer/setup.sh")).not.toContain("\r"); expect(read(".dockerignore")).toMatch(/^\.devcontainer$/m); diff --git a/tests/site/landing.spec.js b/tests/site/landing.spec.js index 87fd439..7244d60 100644 --- a/tests/site/landing.spec.js +++ b/tests/site/landing.spec.js @@ -132,6 +132,20 @@ test("quick starts, assets and accessibility work under the Pages repository pre await expect(page).toHaveURL(/#start$/); await expect(page.locator("body")).not.toContainText("Codespaces"); await expect(page.locator('a[href*="codespaces"]')).toHaveCount(0); + for (const [name, filename] of [ + ["Explore inventory examples", "trailhead-inventory.json"], + ["Explore shipping examples", "trailhead-shipping.json"], + ["Explore AI assistant examples", "trailhead-aoai.json"], + ]) { + const sample = page.getByRole("link", { name, exact: true }); + await expect(sample).toHaveAttribute( + "href", + `https://github.com/simonkurtz-MSFT/MockAPI/blob/main/config/${filename}` + ); + const size = await sample.boundingBox(); + expect(size.width).toBeGreaterThanOrEqual(24); + expect(size.height).toBeGreaterThanOrEqual(24); + } expect( await page.locator("img").evaluateAll((images) => images.every((image) => image.complete && image.naturalWidth > 0)) ).toBe(true); @@ -529,8 +543,8 @@ test("dashboard gallery supports named views, wrapping controls, keyboard naviga .evaluateAll((images) => images.map((image) => [image.naturalWidth, image.naturalHeight])) ).toEqual([ [1905, 1500], - [915, 1235], - [915, 811], + [915, 1833], + [915, 807], ]); expect( await gallery