diff --git a/.claude/skills/write-feature-docs/references/docusaurus-conventions.md b/.claude/skills/write-feature-docs/references/docusaurus-conventions.md index 375f8983..c773f0eb 100644 --- a/.claude/skills/write-feature-docs/references/docusaurus-conventions.md +++ b/.claude/skills/write-feature-docs/references/docusaurus-conventions.md @@ -72,8 +72,8 @@ Match the neighbors' usage — `:::tip` for guidance, `:::note` for caveats, `:: ## Internal links and anchors -- **Cross-page:** relative path without extension — `[Get Started](./get-started)` or `[Modes](./modes)`. -- **Anchor on another page:** `./get-started#step-4-configure-exposures-import-hybrid-only`. +- **Cross-page:** a file link — the target's source file, with its extension, relative to the file the link is in: `[Get Started](./get-started.mdx)`, `[Create](../create.mdx)`, or `./index.mdx` for a category's index page. Percent-encode spaces (`./SAML%20Role%20Mapping.mdx`). Docusaurus turns it into the page URL, and the build fails (`markdown.hooks.onBrokenMarkdownLinks: "throw"`) when it doesn't resolve. A file link without `./` (`get-started.mdx`) also resolves from the same folder. Don't write URL links (`./get-started`, `/docs/...`): the build doesn't resolve them against files, and `./get-started` silently changes target under `trailingSlash: true`. +- **Anchor on another page:** `./get-started.mdx#step-4-configure-exposures-import-hybrid-only`. - **Same-page anchor:** `#the-default-data-source`. - The anchor **slug is the kebab-cased heading text** (lowercased, spaces→hyphens, punctuation dropped, `_italics_` markers dropped). So `## Step 4: Configure exposures import _(Hybrid only)_` → `step-4-configure-exposures-import-hybrid-only`. - **If you rename a heading, update every link that targets its old slug.** Validation (Phase 5) catches broken anchors, but grep for the old slug proactively: diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 303a937b..e75d1eb9 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -11,6 +11,9 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v7 + with: + # Full history: "Last updated" dates and sitemap lastmod come from git log. + fetch-depth: 0 - name: Set Node.js uses: actions/setup-node@v7 @@ -28,3 +31,15 @@ jobs: - name: Build production bundle run: yarn build + + # Unit tests plus checks on the built site (plugins/build-checks.test.js). + - name: Plugin and build-output tests + run: yarn test + + - name: Set up Deno + uses: denoland/setup-deno@v2 + with: + deno-version: v2.x + + - name: Edge function tests + run: deno test --no-check --allow-read netlify/edge-functions-tests/ diff --git a/AGENTS.md b/AGENTS.md index 0ec78319..5b222abb 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -52,6 +52,14 @@ yarn gen:api - `@signalwire/docusaurus-plugin-llms-txt` converts every built page to Markdown at `.md` (e.g. `/docs/glossary/` -> `/docs/glossary.md`) and writes `/llms.txt` and `/llms-full.txt`. +- It is wrapped by `plugins/llms-markdown/llms-txt-wrapper.js`, whose `postBuild` then runs + `postprocess-llms.js` (options: `postProcess` in `docusaurus.config.js`): adds the "Start here" + block, moves Web Console API endpoints to per-resource lists behind + `/docs/APIs-and-SDKs/Web-Console-API/llms.txt`, + describes API entries from the OpenAPI spec, percent-encodes link URLs, and drops Web Console + endpoint pages and the per-page pointer lines from `/llms-full.txt`. Other entries keep the + inner plugin's description (front-matter `description`, else the first source line of the first + paragraph), so every page needs a one-sentence `description:`. - `plugins/llms-markdown/rehype-docusaurus-cleanup.js` rewrites tabs, code blocks, admonitions and `
` into plain HTML first so they survive the conversion. - `netlify/edge-functions/markdown-negotiation.js` serves the `.md` at the normal page URL when the @@ -63,8 +71,75 @@ yarn gen:api - Discovery: every docs page has `` in its `` (`src/theme/DocItem/Metadata/index.js`, a swizzle wrapper), and the `/llms.txt` header explains the `.md` suffix and `Accept: text/markdown` options. -- API reference pages render schemas client-side, so their Markdown has only the endpoint and - description; the raw specs are published at `/openapi/*.yaml` and linked from `/llms.txt`. +- API reference Markdown is generated from the OpenAPI specs, not from the client-rendered pages. + In its `postBuild` (Docusaurus runs postBuilds concurrently), `llms-txt-wrapper.js` builds the + operation index with `buildOperationIndex` (`api/spec-index.js`: dereferenced specs, generated + page URLs, titles from the spec summaries), then runs the inner plugin with `rehype-api-markdown.js` added + first to `beforeDefaultRehypePlugins` and given that index, and passes the same index to + `postprocess-llms.js`. `rehype-api-markdown.js` replaces an endpoint page's content with + Markdown from `api/render-operation.js` and `api/render-schema.js`. Auth lines are hand-written + there (from `APIs-and-SDKs/overview.mdx`), never derived from `securitySchemes`. The raw specs + are also published at `/openapi/*.yaml` (`publish-openapi-specs.js`) and linked from `/llms.txt`. +- API page titles, sidebar labels, breadcrumbs and llms.txt entry titles are the operation + `summary` values from the specs (api-mocks uses readable, unique "{Resource} {action}" summaries, + e.g. "Goal archive"); the docs don't rewrite them. When an operationId changes, the generated page + slug changes too: add a 301 for the old page URL and its `.md` to `static/_redirects`. +- `pointer.js` holds the pointer line at the top of every `.md` (and of every rendered page): "For AI + agents: this page is available as Markdown at `.md`. The full documentation index is at + https://docs.absmartly.com/llms.txt." Its `encodeUrlPath` percent-encodes page URLs (some SSO + permalinks contain spaces). `remark-tight-lists.js` keeps list items tight in the converted + Markdown. +- `llms-txt-wrapper.js` fails the build when fewer endpoint pages were replaced by + `rehype-api-markdown.js` than there are operations (e.g. after a theme markup change), so API + pages never ship as sparse Markdown. `/search` is excluded via `excludeRoutes` (both `/search` + and `/search/`, as routes carry trailing slashes). +- llms.txt structure: a "Start here" block, with the Web Console endpoints split out in two levels. + `/docs/APIs-and-SDKs/Web-Console-API/llms.txt` is the API index: the auth and `ok: false` notes, + the overview and examples pages, and one entry per resource. Each resource (the endpoint path's + first segment, e.g. `/goals/...` -> `goals`) has its own list of endpoints at + `/docs/APIs-and-SDKs/Web-Console-API/llms/.txt`, sorted by title, with descriptions + written by `postprocess-llms.js`. `netlify.toml` serves those lists as UTF-8 plain text with open + CORS. `/llms-full.txt` excludes Web Console endpoint pages and pointer lines. Every `.md` must + stay under 50,000 characters. `/llms.txt`, the API index and each resource list must also stay + under 50,000 characters when every URL uses the longest deploy-preview origin. The resource lists + together must contain every Web Console endpoint page exactly once. All of these limits are + enforced by `plugins/build-checks.test.js`. +- Pointer line and copy menu on rendered pages: `src/theme/DocItem/Content/index.js` is an ejected + copy of the upstream component, so re-diff it against `@docusaurus/theme-classic` when upgrading + Docusaurus. It uses `src/components/AgentPointer`, `src/components/PageAiActions` (copy-page + menu, copying via `src/utils/copyMarkdown.js`) and `src/utils/markdownUrl.js`. +- The edge function also sets a canonical `Link` header on `.md` responses (for negotiated + Markdown, from the final URL when the `.md` fetch was redirected), and `netlify.toml` sets + `X-Robots-Tag: noindex` on `/llms-full.txt`. +- Known limits: the inner plugin's `docusaurus llms-txt` CLI command is not registered (the wrapper + drops its `extendCli`, as the API index is not loaded there; use `yarn build`). `yarn clean:api` also deletes the tracked + `_category_.json` files in both API dirs; restore them with `git checkout` and never commit the + deletion. + +## SEO + +- `trailingSlash: true`. Write internal links as file links: the target's source file, with its + extension, relative to the file the link is in (`./get-started.mdx`, `../create.mdx#anchor`, + `./index.mdx` for a category's index page, `%20` for spaces). Docusaurus turns them into the page + URL, and `markdown.hooks.onBrokenMarkdownLinks: "throw"` fails the build when one doesn't + resolve. A file link without `./` (`get-started.mdx`) also resolves from the same folder. Don't write URL links (`./foo`, `/docs/...`): the build doesn't resolve them against + files, and `./foo` silently changes target under trailing slashes. +- `static/robots.txt` allows all crawlers (AI training crawlers included) everywhere except + `/search`, and points to the sitemap and `/llms.txt`. + The sitemap ignores `/search` and `/blog`. +- Last-updated dates come from git history, so they need a full clone: a shallow checkout disables + them with a warning (CI uses `fetch-depth: 0`). The custom `experimental_vcs` in + `docusaurus.config.js` gives generated API pages no date. + +## Tests + +- `yarn test` runs `node --test` over `plugins/**/*.test.js` and the React component tests in + `src/**/*.test.js` (JSX loaded through `test-support/register.mjs`, which compiles it with swc + and stubs the Docusaurus modules). Run `yarn gen:api` first (tests + that need the generated `.api.mdx` pages skip without them) and `yarn build` for + `plugins/build-checks.test.js`, which inspects `build/` and is skipped when it is absent. +- Edge function: `yarn build && deno test --no-check --allow-read netlify/edge-functions-tests/`. +- CI (`.github/workflows/build.yml`) runs both suites after `yarn clean:api && yarn gen:api && yarn build`. ## Social previews @@ -74,5 +149,6 @@ yarn gen:api ## Notes -- The Web Console API spec uses placeholder metadata (`sandbox.example.com/v1`, `api@example.com`) from the api-mocks package; this is intentional. +- The site URL comes from `plugins/site-url.js` (client code: `siteConfig.url`): Netlify deploy previews and branch deploys use their own `DEPLOY_PRIME_URL`, so their llms.txt, `.md` pages, pointer lines, copy menu and canonical headers link to the preview; every other build uses `https://docs.absmartly.com`. Don't hard-code the production URL elsewhere (a test checks `plugins/` and `src/`); `static/robots.txt` is the exception. +- The Web Console API spec's server (`https://{subdomain}.absmartly.com/v1`) and auth header (`Authorization: Api-Key `) are real; only `info.contact` (`api@example.com`) and `license.url` are still placeholders from the api-mocks package. - `yarn build` may emit a pre-existing broken-anchor warning on `SDK-Documentation/getting-started` (`#using-a-custom-event-logger`) — unrelated to the API docs work. diff --git a/docs/APIs-and-SDKs/CLI-Documentation/authentication.mdx b/docs/APIs-and-SDKs/CLI-Documentation/authentication.mdx index 861c140f..08d0959b 100644 --- a/docs/APIs-and-SDKs/CLI-Documentation/authentication.mdx +++ b/docs/APIs-and-SDKs/CLI-Documentation/authentication.mdx @@ -1,8 +1,10 @@ --- +title: "CLI Authentication" +sidebar_label: "Authentication" sidebar_position: 2 --- -# Authentication +# CLI Authentication The CLI stores credentials in your OS keychain (via keytar) and configuration in `~/.config/absmartly/config.yaml`. On headless systems without a keychain service, credentials fall back to a local `~/.config/absmartly/credentials.json` file. diff --git a/docs/APIs-and-SDKs/CLI-Documentation/configuration.mdx b/docs/APIs-and-SDKs/CLI-Documentation/configuration.mdx index 75a81858..167ee071 100644 --- a/docs/APIs-and-SDKs/CLI-Documentation/configuration.mdx +++ b/docs/APIs-and-SDKs/CLI-Documentation/configuration.mdx @@ -45,7 +45,7 @@ abs experiments update 123 --field "Hypothesis=Updated hypothesis" --show-reques `--curl` output redacts the `Authorization` header and known sensitive body fields by default. That makes it safer to share, but other headers, query parameters, paths or body fields can still contain credentials or user data, so check the output before sharing it. Redacted output won't authenticate if you paste it into a shell. Add `--show-secrets` to get a replayable, authenticated command; this prints your API key in plain text, so don't paste that output into tickets, chat or logs. `--headers-only` strips request bodies, so combining it with `--curl` won't give a complete, replayable command for requests that send a body (`POST`, `PUT`, `PATCH`). -`--show-request` is the fastest way to see the exact payload shape the CLI sends for a given command — useful when integrating directly against the REST API and you want to confirm a field's wire format, such as [custom field values](./experiments-and-feature-flags#custom-field-options). +`--show-request` is the fastest way to see the exact payload shape the CLI sends for a given command — useful when integrating directly against the REST API and you want to confirm a field's wire format, such as [custom field values](./experiments-and-feature-flags.mdx#custom-field-options). ## Configuration file @@ -95,7 +95,7 @@ profiles: | `ABSMARTLY_API_KEY` | API key (overrides keychain and credentials file) | | `ABSMARTLY_API_ENDPOINT` | API endpoint URL (overrides profile config) | -See [Authentication](./authentication) for the full credential resolution order and OAuth/API key login flows. +See [Authentication](./authentication.mdx) for the full credential resolution order and OAuth/API key login flows. ## Date formats diff --git a/docs/APIs-and-SDKs/CLI-Documentation/experiment-templates.mdx b/docs/APIs-and-SDKs/CLI-Documentation/experiment-templates.mdx index 1e9501f3..b14c9fb2 100644 --- a/docs/APIs-and-SDKs/CLI-Documentation/experiment-templates.mdx +++ b/docs/APIs-and-SDKs/CLI-Documentation/experiment-templates.mdx @@ -1,8 +1,10 @@ --- +title: "CLI Experiment Templates" +sidebar_label: "Experiment Templates" sidebar_position: 6 --- -# Experiment Templates +# CLI Experiment Templates The CLI uses Markdown templates with YAML frontmatter for experiment round-trips. All names (metrics, owners, teams, tags, applications) are resolved by name — no IDs needed. diff --git a/docs/APIs-and-SDKs/CLI-Documentation/experiments-and-feature-flags.mdx b/docs/APIs-and-SDKs/CLI-Documentation/experiments-and-feature-flags.mdx index 5ed53bb5..5795fcdf 100644 --- a/docs/APIs-and-SDKs/CLI-Documentation/experiments-and-feature-flags.mdx +++ b/docs/APIs-and-SDKs/CLI-Documentation/experiments-and-feature-flags.mdx @@ -71,7 +71,7 @@ abs experiments search "onboarding" | `--show ` | Add extra columns | | `--exclude ` | Hide columns | -All `--from`, `--to`, `--created-after`, and other date options accept the shared [date formats](./configuration#date-formats). +All `--from`, `--to`, `--created-after`, and other date options accept the shared [date formats](./configuration.mdx#date-formats). ## Getting details @@ -128,7 +128,7 @@ abs experiments restart 123 --hypothesis "New iteration" abs experiments create --name test --field "Hypothesis=We believe X" ``` -Custom field values are sent to the API as an object keyed by each field's numeric id (not an array) — the CLI builds this automatically. If you're integrating directly against the REST API and want to see the exact request the CLI sends for a given custom field update, use the global [`--show-request`](./configuration#debugging-api-traffic) flag: +Custom field values are sent to the API as an object keyed by each field's numeric id (not an array) — the CLI builds this automatically. If you're integrating directly against the REST API and want to see the exact request the CLI sends for a given custom field update, use the global [`--show-request`](./configuration.mdx#debugging-api-traffic) flag: ```bash abs experiments update 123 --field "Hypothesis=Updated hypothesis" --show-request @@ -207,7 +207,7 @@ abs experiments archive 123 --unarchive ## Metric results -`--from`/`--to` accept all [date formats](./configuration#date-formats). +`--from`/`--to` accept all [date formats](./configuration.mdx#date-formats). ```bash abs experiments metrics list 123 # list assigned metrics @@ -410,4 +410,4 @@ abs experiments estimate-participants --unit-type user_id --from 90d abs experiments estimate-participants --unit-type user_id -o json ``` -See [Experiment Templates](./experiment-templates) for the markdown+YAML round-trip format used by `--from-file` and `-o template`. +See [Experiment Templates](./experiment-templates.mdx) for the markdown+YAML round-trip format used by `--from-file` and `-o template`. diff --git a/docs/APIs-and-SDKs/CLI-Documentation/other-entities.mdx b/docs/APIs-and-SDKs/CLI-Documentation/other-entities.mdx index ed3c82e6..bf10616d 100644 --- a/docs/APIs-and-SDKs/CLI-Documentation/other-entities.mdx +++ b/docs/APIs-and-SDKs/CLI-Documentation/other-entities.mdx @@ -8,7 +8,7 @@ Command reference for every CLI entity outside of experiments and feature flags ## Activity feed -Global activity feed across all experiments. Scans recent experiments and aggregates their activity notes. `--since` accepts all [date formats](./configuration#date-formats). +Global activity feed across all experiments. Scans recent experiments and aggregates their activity notes. `--since` accepts all [date formats](./configuration.mdx#date-formats). Aliases: `activity-feed` @@ -35,7 +35,7 @@ abs experiments activity list checkout_redesign --notes --show-images abs experiments activity create checkout_redesign --note "Deployed to staging" ``` -See [Experiments & Feature Flags](./experiments-and-feature-flags#activity-log) for the full per-experiment activity command reference (edit, reply, etc.). +See [Experiments & Feature Flags](./experiments-and-feature-flags.mdx#activity-log) for the full per-experiment activity command reference (edit, reply, etc.). ## Goals @@ -335,7 +335,7 @@ abs custom-sections reorder --sections "1:0,2:1,3:2" ## Events -View and manage event tracking data. `--from`/`--to` accept all [date formats](./configuration#date-formats). +View and manage event tracking data. `--from`/`--to` accept all [date formats](./configuration.mdx#date-formats). Aliases: `events`, `event` @@ -356,7 +356,7 @@ abs events json-layouts --source unit_attribute --phase after_enrichment ## Insights -View experiment velocity and decision analytics. `--from`/`--to` accept ISO dates (see [date formats](./configuration#date-formats)). +View experiment velocity and decision analytics. `--from`/`--to` accept ISO dates (see [date formats](./configuration.mdx#date-formats)). Aliases: `insights`, `insight` @@ -407,7 +407,7 @@ abs action-dialog-fields update 1 --config '{"required": true}' ## Platform configuration -Manage server-side platform settings (not local CLI config — see [Configuration](./configuration) for local config). +Manage server-side platform settings (not local CLI config — see [Configuration](./configuration.mdx) for local config). Aliases: `platform-config`, `platformconfig`, `platform-configs` diff --git a/docs/APIs-and-SDKs/Federated-Authentication/federated-oidc-tokens.mdx b/docs/APIs-and-SDKs/Federated-Authentication/federated-oidc-tokens.mdx index 3f4f2b9b..a1cdfbc8 100644 --- a/docs/APIs-and-SDKs/Federated-Authentication/federated-oidc-tokens.mdx +++ b/docs/APIs-and-SDKs/Federated-Authentication/federated-oidc-tokens.mdx @@ -27,7 +27,7 @@ Federated tokens can be enabled for two endpoints: This page describes what works with any identity provider. For the step-by-step setup of a specific provider, see its guide: -- [Microsoft Entra ID](./microsoft-entra-id) +- [Microsoft Entra ID](./microsoft-entra-id.mdx) :::info Enabled on request Federated tokens are off by default. ABsmartly support turns them on for your @@ -137,7 +137,7 @@ providers often issue different identifiers to different applications, and some put a changeable login or email in `sub`. Configure a SAML assertion attribute that contains exactly the value your access tokens carry in the subject claim, and tell ABsmartly support its name. For Entra ID, see -[the SAML attribute setup](./microsoft-entra-id#link-users-through-saml-sso). +[the SAML attribute setup](./microsoft-entra-id.mdx#link-users-through-saml-sso). When a user signs in through that SAML provider, ABsmartly records the link, and the tenant from the assertion if it carries one. Every user must sign in @@ -229,7 +229,7 @@ opaque access tokens, so use a custom authorization server. How your backend gets the token depends on your identity provider: - **Microsoft Entra ID** uses the On-Behalf-Of flow. See - [Request a token with the On-Behalf-Of flow](./microsoft-entra-id#request-a-token-with-the-on-behalf-of-flow). + [Request a token with the On-Behalf-Of flow](./microsoft-entra-id.mdx#request-a-token-with-the-on-behalf-of-flow). - **Providers that support OAuth 2.0 Token Exchange** ([RFC 8693](https://www.rfc-editor.org/rfc/rfc8693)) exchange the user's token at the token endpoint with @@ -498,11 +498,11 @@ with the [token requirements](#token-requirements). | An MCP tool call that runs for more than five minutes fails partway with `401` | The internal credential the MCP server uses for each request is valid for five minutes | Split the work into shorter tool calls | For provider-specific problems, see the provider guide, for example -[Microsoft Entra ID troubleshooting](./microsoft-entra-id#troubleshooting). +[Microsoft Entra ID troubleshooting](./microsoft-entra-id.mdx#troubleshooting). ## Related -- [Microsoft Entra ID](./microsoft-entra-id) — step-by-step setup for Entra ID +- [Microsoft Entra ID](./microsoft-entra-id.mdx) — step-by-step setup for Entra ID - [Platform API](/docs/APIs-and-SDKs/Web-Console-API/absmartly-web-console-api) — the REST API reference - [MCP Server authentication](/docs/APIs-and-SDKs/MCP-Server/authentication) diff --git a/docs/APIs-and-SDKs/Federated-Authentication/microsoft-entra-id.mdx b/docs/APIs-and-SDKs/Federated-Authentication/microsoft-entra-id.mdx index 13346a5f..1d48c586 100644 --- a/docs/APIs-and-SDKs/Federated-Authentication/microsoft-entra-id.mdx +++ b/docs/APIs-and-SDKs/Federated-Authentication/microsoft-entra-id.mdx @@ -6,7 +6,7 @@ description: Set up Microsoft Entra ID so your backend can call the ABsmartly RE # Microsoft Entra ID -This guide sets up [federated OIDC access tokens](./federated-oidc-tokens) +This guide sets up [federated OIDC access tokens](./federated-oidc-tokens.mdx) with Microsoft Entra ID. Your backend uses the Entra [On-Behalf-Of (OBO) flow](https://learn.microsoft.com/en-us/entra/identity-platform/v2-oauth2-on-behalf-of-flow) to exchange a signed-in user's token for an access token issued for ABsmartly, @@ -14,7 +14,7 @@ and calls the ABsmartly REST API (`/v1`) or your instance's `/mcp` endpoint with it. Each call acts as the matching ABsmartly user, with exactly that user's permissions. -Read [Federated OIDC access tokens](./federated-oidc-tokens) first for how the +Read [Federated OIDC access tokens](./federated-oidc-tokens.mdx) first for how the feature works, how to call `/v1` and `/mcp`, the errors and the security model. This page covers only the Entra ID setup. @@ -75,7 +75,7 @@ is separate from the enterprise application you created for SAML SSO. Click **Add scope**. `mcp.access` grants access to `/mcp` and `api.access` grants access to `/v1`. -See [REST API and MCP access](./federated-oidc-tokens#rest-api-and-mcp-access). +See [REST API and MCP access](./federated-oidc-tokens.mdx#rest-api-and-mcp-access). These are the scope names we use by convention. ABsmartly configures the scopes for your instance, so if you need different names, agree them with ABsmartly support and use them everywhere this page says `mcp.access` or @@ -141,9 +141,9 @@ even if they already have an account or browser session. There is no bulk import. The first sign-in decides the link, so check that every user's email in Entra ID maps to the right ABsmartly user before you enable it. Links are never reassigned automatically; see -[Link users through SAML SSO](./federated-oidc-tokens#link-users-through-saml-sso) +[Link users through SAML SSO](./federated-oidc-tokens.mdx#link-users-through-saml-sso) for details and for how to -[fix a wrong link](./federated-oidc-tokens#fix-a-wrong-or-stuck-link). +[fix a wrong link](./federated-oidc-tokens.mdx#fix-a-wrong-or-stuck-link). ## Step 2: Give your backend app permission to call ABsmartly @@ -270,15 +270,15 @@ Send the `access_token` from the OBO response as `Authorization: Bearer ` on every request to `https://your-instance.absmartly.com/v1/...` or `https://your-instance.absmartly.com/mcp`. See -[Call the REST API with the token](./federated-oidc-tokens#call-the-rest-api-with-the-token) +[Call the REST API with the token](./federated-oidc-tokens.mdx#call-the-rest-api-with-the-token) and -[Call the MCP server with the token](./federated-oidc-tokens#call-the-mcp-server-with-the-token) +[Call the MCP server with the token](./federated-oidc-tokens.mdx#call-the-mcp-server-with-the-token) for full examples. ## What ABsmartly checks in Entra ID tokens ABsmartly applies all the -[token requirements](./federated-oidc-tokens#token-requirements). For Entra ID +[token requirements](./federated-oidc-tokens.mdx#token-requirements). For Entra ID they mean: | Check | Token claim | Must be | @@ -303,7 +303,7 @@ archived. ## Troubleshooting Rejected tokens come back with an `error_description` that says why. See -[Error reasons](./federated-oidc-tokens#error-reasons) for the full list. These +[Error reasons](./federated-oidc-tokens.mdx#error-reasons) for the full list. These problems are specific to Entra ID: | Symptom | Likely cause | Fix | @@ -316,14 +316,14 @@ problems are specific to Entra ID: | `required scope missing` (`403`) | `scp` doesn't contain the scope named in the `WWW-Authenticate` header (`mcp.access` on `/mcp`, `api.access` on `/v1`): the scope wasn't requested, or consent wasn't granted | Request `api:///` and [grant admin consent](#step-2-give-your-backend-app-permission-to-call-absmartly) | | `federated tokens are not accepted on this endpoint` on `/v1` | REST API access isn't enabled for your instance | Ask ABsmartly support to enable it with your API scope, or call `/mcp` | | `token subject claim missing` | The token has no `oid` | Send a delegated access token issued for the ABsmartly app | -| `no active ABsmartly user for this identity` | The user hasn't signed in with SAML since federated tokens were enabled, the SAML assertion lacks the [object ID attribute](#link-users-through-saml-sso), the linked user is archived, or the token is from a different tenant than the one recorded at SAML sign-in (or has no `tid`) | Have the user sign in with SAML SSO once, and request the token from the same tenant the user signs in to ABsmartly with. If the link is wrong, [fix it](./federated-oidc-tokens#fix-a-wrong-or-stuck-link). | +| `no active ABsmartly user for this identity` | The user hasn't signed in with SAML since federated tokens were enabled, the SAML assertion lacks the [object ID attribute](#link-users-through-saml-sso), the linked user is archived, or the token is from a different tenant than the one recorded at SAML sign-in (or has no `tid`) | Have the user sign in with SAML SSO once, and request the token from the same tenant the user signs in to ABsmartly with. If the link is wrong, [fix it](./federated-oidc-tokens.mdx#fix-a-wrong-or-stuck-link). | | `app-only tokens are not accepted` | The token comes from the client credentials flow, not OBO | Use the [OBO flow](#request-a-token-with-the-on-behalf-of-flow) with a signed-in user's token | | The OBO request fails with `AADSTS65001` | Admin consent wasn't granted to your backend app | Grant admin consent in **API permissions** | | The OBO request fails with `AADSTS50013` or `AADSTS50027` | The `assertion` isn't a valid access token for your backend app | Pass the user's access token for your backend app, not an ID token | ## Related -- [Federated OIDC access tokens](./federated-oidc-tokens) — how the feature +- [Federated OIDC access tokens](./federated-oidc-tokens.mdx) — how the feature works, calling `/v1` and `/mcp`, errors and security - [SAML SSO - Azure](/docs/Third-party-integrations/SSO/Azure%20SAML%20Setup) — set up Entra ID sign-in to the Web Console diff --git a/docs/APIs-and-SDKs/MCP-Server/authentication.mdx b/docs/APIs-and-SDKs/MCP-Server/authentication.mdx index 08b3885d..6c36a9a2 100644 --- a/docs/APIs-and-SDKs/MCP-Server/authentication.mdx +++ b/docs/APIs-and-SDKs/MCP-Server/authentication.mdx @@ -1,9 +1,10 @@ --- -title: Authentication +title: "MCP Server Authentication" +sidebar_label: "Authentication" sidebar_position: 4 --- -# Authentication +# MCP Server Authentication The ABsmartly MCP server supports two authentication methods. Both are configured per client — there are no server-side secrets, so credentials are @@ -32,7 +33,7 @@ Depending on the client, the API key is supplied as either: - A query string parameter on the connection URL (`?api_key=YOUR_API_KEY&absmartly-endpoint=https://your-instance.absmartly.com`). -See the [Setup](./setup) guide for the exact configuration per client. +See the [Setup](./setup.mdx) guide for the exact configuration per client. ### Authorization header formats @@ -81,7 +82,7 @@ There are two OAuth-enabled MCP URLs: Every OAuth connection uses the authorization code flow with PKCE (`S256`). For the full sequence, the endpoints involved and the ways an MCP client can be -registered, see [OAuth & Client Registration](./oauth-clients). +registered, see [OAuth & Client Registration](./oauth-clients.mdx). ### Specifying the instance URL @@ -100,7 +101,7 @@ instance is implied by the URL. Most MCP clients are accepted automatically, either through a trusted client metadata document or through dynamic client registration with an allowlisted redirect URI. If your client is rejected, use an API key instead, or see -[Your client isn't on the list?](./oauth-clients#your-client-isnt-on-the-list). +[Your client isn't on the list?](./oauth-clients.mdx#your-client-isnt-on-the-list). ## Federated OIDC tokens (e.g. Microsoft Entra ID) @@ -135,12 +136,12 @@ profile with `--profile=` (for example, `--profile=production`). authentication-method confusion. - **Restricted OAuth clients** — only trusted clients and allowlisted redirect URIs can receive OAuth access, and every new client is shown on a consent - page first (see [OAuth & Client Registration](./oauth-clients)). + page first (see [OAuth & Client Registration](./oauth-clients.mdx)). - **PKCE required** — OAuth requests must use PKCE with `S256`. - **Destructive action confirmation** — destructive operations such as `start`, `stop`, `archive` and `delete` ask you to confirm before they run, on every transport (see the - [Tools Reference](./tools-reference#execute_command)). + [Tools Reference](./tools-reference.mdx#execute_command)). - **API error surfacing** — validation errors from the API are returned with full detail so the assistant can correct them. diff --git a/docs/APIs-and-SDKs/MCP-Server/oauth-clients.mdx b/docs/APIs-and-SDKs/MCP-Server/oauth-clients.mdx index 3a2ba972..5fdac55c 100644 --- a/docs/APIs-and-SDKs/MCP-Server/oauth-clients.mdx +++ b/docs/APIs-and-SDKs/MCP-Server/oauth-clients.mdx @@ -10,7 +10,7 @@ This page explains what happens when an MCP client signs in to ABsmartly with OAuth: which endpoints it calls, how it gets registered, and why some clients are accepted while others are rejected. You don't need any of this to connect a supported client, because the client does it all for you. It is useful when you -connect a client that isn't listed in [Setup](./setup), or when you need to +connect a client that isn't listed in [Setup](./setup.mdx), or when you need to debug a failed connection. ## Two ways to connect with OAuth @@ -217,7 +217,7 @@ with that URL, then update the connection with the new `client_id` and ### API key If your client can't use OAuth at all, or isn't on the allowlist, connect with -an [API key](./authentication#api-key) instead. API key connections skip OAuth +an [API key](./authentication.mdx#api-key) instead. API key connections skip OAuth entirely, so no registration is needed. This works with any client that can send an HTTP header or connect to a URL with a query string. @@ -257,7 +257,7 @@ receive the access. The consent page shows a warning for these hosts. Only approve when you have just started the connection yourself. These platforms connect from their own cloud. Connect them to the hosted -server URL, as shown in [Setup](./setup#cloud-agent-platforms). +server URL, as shown in [Setup](./setup.mdx#cloud-agent-platforms). ::: ### Your client isn't on the list? @@ -265,7 +265,7 @@ server URL, as shown in [Setup](./setup#cloud-agent-platforms). If your MCP client is rejected and isn't covered above: 1. **Use an API key.** It works with any client and needs no registration. See - [Authentication](./authentication#api-key). + [Authentication](./authentication.mdx#api-key). 2. **Ask for the client to be added.** Contact ABsmartly support with the client's name and its redirect URI or metadata-document URL. You can also open an issue on @@ -297,8 +297,8 @@ MCP client. ## Related -- [Authentication](./authentication) — API keys, header formats and the +- [Authentication](./authentication.mdx) — API keys, header formats and the security model -- [Setup](./setup) — per-client configuration -- [Troubleshooting](./troubleshooting#oauth-errors) — what each OAuth error +- [Setup](./setup.mdx) — per-client configuration +- [Troubleshooting](./troubleshooting.mdx#oauth-errors) — what each OAuth error means diff --git a/docs/APIs-and-SDKs/MCP-Server/overview.mdx b/docs/APIs-and-SDKs/MCP-Server/overview.mdx index 7226284d..6d09935b 100644 --- a/docs/APIs-and-SDKs/MCP-Server/overview.mdx +++ b/docs/APIs-and-SDKs/MCP-Server/overview.mdx @@ -1,9 +1,10 @@ --- -title: Overview +title: "MCP Server Overview" +sidebar_label: "Overview" sidebar_position: 1 --- -# ABsmartly MCP Server +# MCP Server Overview The ABsmartly [Model Context Protocol](https://modelcontextprotocol.io/) (MCP) server lets AI assistants — Claude, Cursor, VS Code, Windsurf, Gemini, ChatGPT @@ -73,7 +74,7 @@ always ask you to confirm before they run — through an in-client prompt on the hosted server and local stdio server where the client supports it, or in the chat. Experiment creation from templates returns a preview first. -See the [Tools Reference](./tools-reference) for the full surface. +See the [Tools Reference](./tools-reference.mdx) for the full surface. ## Authentication at a glance @@ -83,8 +84,8 @@ See the [Tools Reference](./tools-reference) for the full surface. | **API Key** | Programmatic access, CI/CD, headless, or clients that can't use OAuth | Pass the key in HTTP headers or via the URL | | **Federated OIDC token** | Your own backend agent acting for users signed in to your identity provider (e.g. Microsoft Entra ID) | Send an access token from your identity provider to your instance's `/mcp` (enabled on request) | -All methods are documented in detail in [Authentication](./authentication). -[OAuth & Client Registration](./oauth-clients) explains the OAuth flow, the +All methods are documented in detail in [Authentication](./authentication.mdx). +[OAuth & Client Registration](./oauth-clients.mdx) explains the OAuth flow, the endpoints involved and which clients are accepted. [Federated OIDC access tokens](/docs/APIs-and-SDKs/Federated-Authentication/federated-oidc-tokens) explains federated tokens, which also work on the REST API, with a step-by-step guide for @@ -101,18 +102,18 @@ tokens, which also work on the REST API, with a step-by-step guide for ## What's next -- **[Quick Start](./quick-start)** — connect Claude Desktop with OAuth and run +- **[Quick Start](./quick-start.mdx)** — connect Claude Desktop with OAuth and run your first command in under five minutes -- **[Setup](./setup)** — per-client setup for every supported MCP client -- **[Authentication](./authentication)** — API key formats, OAuth, +- **[Setup](./setup.mdx)** — per-client setup for every supported MCP client +- **[Authentication](./authentication.mdx)** — API key formats, OAuth, security model -- **[OAuth & Client Registration](./oauth-clients)** — the OAuth flow with +- **[OAuth & Client Registration](./oauth-clients.mdx)** — the OAuth flow with diagrams, endpoints, and how MCP clients are registered and accepted -- **[Usage Examples](./usage-examples)** — natural-language prompts that work +- **[Usage Examples](./usage-examples.mdx)** — natural-language prompts that work today -- **[Tools Reference](./tools-reference)** — full list of tools, command groups, +- **[Tools Reference](./tools-reference.mdx)** — full list of tools, command groups, resources and prompts -- **[Troubleshooting](./troubleshooting)** — common errors and how to fix them +- **[Troubleshooting](./troubleshooting.mdx)** — common errors and how to fix them ## Source code diff --git a/docs/APIs-and-SDKs/MCP-Server/quick-start.mdx b/docs/APIs-and-SDKs/MCP-Server/quick-start.mdx index 9764a3e2..2d0e50c3 100644 --- a/docs/APIs-and-SDKs/MCP-Server/quick-start.mdx +++ b/docs/APIs-and-SDKs/MCP-Server/quick-start.mdx @@ -9,7 +9,7 @@ This guide gets you from zero to running your first ABsmartly command via the MCP server in under five minutes. We'll use **Claude Desktop** with **OAuth** — the fastest path with no API keys to manage. -For other clients or API key setups, jump straight to [Setup](./setup). +For other clients or API key setups, jump straight to [Setup](./setup.mdx). ## Prerequisites @@ -48,7 +48,7 @@ shows that Claude is asking for access to your ABsmartly account, and click your org uses it). When the browser confirms success, the connector is live. Your approval is remembered in that browser, so reconnecting later skips the -consent page. See [OAuth & Client Registration](./oauth-clients) for what +consent page. See [OAuth & Client Registration](./oauth-clients.mdx) for what happens behind the scenes. :::tip @@ -106,11 +106,11 @@ and show a preview / confirmation step — destructive actions like `start`, ## Where to go next -- **[Usage Examples](./usage-examples)** — more natural-language prompts that +- **[Usage Examples](./usage-examples.mdx)** — more natural-language prompts that work today -- **[Tools Reference](./tools-reference)** — the full set of commands, including +- **[Tools Reference](./tools-reference.mdx)** — the full set of commands, including experiment creation from markdown templates -- **[Authentication](./authentication)** — switch to API key auth (for CI or +- **[Authentication](./authentication.mdx)** — switch to API key auth (for CI or headless use), or learn about the security model -- **[Troubleshooting](./troubleshooting)** — if the connection isn't working, +- **[Troubleshooting](./troubleshooting.mdx)** — if the connection isn't working, start here diff --git a/docs/APIs-and-SDKs/MCP-Server/setup.mdx b/docs/APIs-and-SDKs/MCP-Server/setup.mdx index d27da7b0..7c9629bd 100644 --- a/docs/APIs-and-SDKs/MCP-Server/setup.mdx +++ b/docs/APIs-and-SDKs/MCP-Server/setup.mdx @@ -34,8 +34,8 @@ covers Claude Desktop, Claude Code, Cursor, Windsurf, VS Code (Copilot), Gemini agent platforms and the DXT extension. For details on API keys and supported `Authorization` header formats, see -[Authentication](./authentication). For how OAuth clients are registered and -which ones are accepted, see [OAuth & Client Registration](./oauth-clients). +[Authentication](./authentication.mdx). For how OAuth clients are registered and +which ones are accepted, see [OAuth & Client Registration](./oauth-clients.mdx). ## Transports @@ -62,7 +62,7 @@ login, or an API key sent as `Authorization: Api-Key YOUR_API_KEY`. Because the URL already identifies your instance, no `absmartly-endpoint` parameter or `x-absmartly-endpoint` header is needed. Use this URL in place of `https://mcp.absmartly.com/mcp` in any of the Streamable HTTP examples below. -See [OAuth & Client Registration](./oauth-clients#two-ways-to-connect-with-oauth) +See [OAuth & Client Registration](./oauth-clients.mdx#two-ways-to-connect-with-oauth) for how the two differ. :::info Availability @@ -574,11 +574,11 @@ Streamable HTTP transport — use the `/mcp` endpoint: 3. **Server URL:** `https://mcp.absmartly.com/mcp?absmartly-endpoint=https://your-instance.absmartly.com` 4. **Authentication:** OAuth. The connector form asks for an existing OAuth - client. First [register a client manually](./oauth-clients#manual-registration) + client. First [register a client manually](./oauth-clients.mdx#manual-registration) with the redirect URI `https://vertexaisearch.cloud.google.com/oauth-redirect`, then enter its `client_id` and `client_secret`, the authorization and token URLs from the - [endpoint table](./oauth-clients#endpoints), and the `mcp:access` scope. + [endpoint table](./oauth-clients.mdx#endpoints), and the `mcp:access` scope. Select **Enable PKCE Support**: ABsmartly requires PKCE with `S256`. Keep **Use HTTP Basic Authentication** selected, to match the `client_secret_basic` method in the registration example. @@ -680,12 +680,12 @@ https://mcp.absmartly.com/mcp?absmartly-endpoint=https://your-instance.absmartly [Gemini Enterprise](#gemini-enterprise-google-cloud-console) is covered above. Other platforms whose callbacks are on the -[allowlist](./oauth-clients#allowed-redirect-uris) may work, but we haven't +[allowlist](./oauth-clients.mdx#allowed-redirect-uris) may work, but we haven't tested them yet, so they have no setup guide here. ABsmartly requires the authorization-code flow with PKCE (`S256`). If a platform asks you for a client ID and secret instead of registering itself, see -[Manual registration](./oauth-clients#manual-registration). If it can't connect, -use an [API key](./authentication#api-key). +[Manual registration](./oauth-clients.mdx#manual-registration). If it can't connect, +use an [API key](./authentication.mdx#api-key). These platforms use callback URLs shared by all their customers, so the consent page shows an extra warning. @@ -696,12 +696,12 @@ page shows an extra warning. Any MCP client that supports OAuth with dynamic client registration or a trusted client metadata document, and uses an -[allowed redirect URI](./oauth-clients#allowed-redirect-uris), works with the +[allowed redirect URI](./oauth-clients.mdx#allowed-redirect-uris), works with the same URL as above. Local clients that sign in through a `localhost` callback, such as Zed, Kiro, OpenCode or MCP Inspector, are accepted automatically. If your client is rejected, connect with an API key instead, or see -[Your client isn't on the list?](./oauth-clients#your-client-isnt-on-the-list). +[Your client isn't on the list?](./oauth-clients.mdx#your-client-isnt-on-the-list). --- diff --git a/docs/APIs-and-SDKs/MCP-Server/troubleshooting.mdx b/docs/APIs-and-SDKs/MCP-Server/troubleshooting.mdx index 00164873..ab149c9f 100644 --- a/docs/APIs-and-SDKs/MCP-Server/troubleshooting.mdx +++ b/docs/APIs-and-SDKs/MCP-Server/troubleshooting.mdx @@ -49,16 +49,16 @@ instance's own `/mcp` endpoint. Where they differ, both are listed. | Error | Cause | Fix | | --- | --- | --- | -| `invalid_client` — *"This MCP client is not supported by this server"* (hosted server) or *"Unknown client"* (your instance) | The client identifies itself with a metadata-document URL that isn't on the trusted list. | Use an API key, or [ask for the client to be added](./oauth-clients#your-client-isnt-on-the-list). | -| `invalid_redirect_uri` — *"One or more redirect_uris are not allowed"* | The client tried to register with a redirect URI that isn't on the [allowlist](./oauth-clients#allowed-redirect-uris). | Use an API key, or ask for the client to be added. | -| `invalid_client` for a client that used to work | The client's registration expired. On the hosted server, registrations expire 90 days after they are created. On your instance, they expire after 90 days without use. | Remove the connector and add it again so it registers again. If you registered the client manually, [register it again](./oauth-clients#manual-registration) and enter the new `client_id` and `client_secret` in the connector. | +| `invalid_client` — *"This MCP client is not supported by this server"* (hosted server) or *"Unknown client"* (your instance) | The client identifies itself with a metadata-document URL that isn't on the trusted list. | Use an API key, or [ask for the client to be added](./oauth-clients.mdx#your-client-isnt-on-the-list). | +| `invalid_redirect_uri` — *"One or more redirect_uris are not allowed"* | The client tried to register with a redirect URI that isn't on the [allowlist](./oauth-clients.mdx#allowed-redirect-uris). | Use an API key, or ask for the client to be added. | +| `invalid_client` for a client that used to work | The client's registration expired. On the hosted server, registrations expire 90 days after they are created. On your instance, they expire after 90 days without use. | Remove the connector and add it again so it registers again. If you registered the client manually, [register it again](./oauth-clients.mdx#manual-registration) and enter the new `client_id` and `client_secret` in the connector. | | *"PKCE with code_challenge_method=S256 is required"* (hosted server) or `invalid_request` — *"PKCE is required. Supported code_challenge_method: S256"* (your instance) | The client sent no PKCE challenge, or used `plain`. | Update the client. If it can't use `S256`, use an API key. | | *"Authorization request expired or invalid, please restart the connection from your MCP client"* | The consent page was left open for more than 10 minutes, or was approved in a different browser from the one that started it. On the hosted server, it also appears if the page was submitted twice. | Start the connection again from the MCP client, and complete it in one browser. | | *"This login was started in a different browser…"* (hosted server only) | The sign-in to your instance finished in a different browser from the one that approved the consent page. | Copy the authorization link into the browser where you're signed in to ABsmartly, or restart the connection. | | `invalid_grant` — *"The ABsmartly session has ended, please sign in again"* (hosted server) or *"The session that approved this request has ended"* (your instance) | You signed out of ABsmartly, or your session expired. | Reconnect the client and sign in again. | | `access_denied` | You clicked **Deny** on the consent page. | Reconnect and click **Approve**. | -See [OAuth & Client Registration](./oauth-clients) for how clients are +See [OAuth & Client Registration](./oauth-clients.mdx) for how clients are accepted. ### Errors with a federated OIDC token (e.g. Microsoft Entra ID) diff --git a/docs/APIs-and-SDKs/MCP-Server/usage-examples.mdx b/docs/APIs-and-SDKs/MCP-Server/usage-examples.mdx index 67909bf4..cf64d822 100644 --- a/docs/APIs-and-SDKs/MCP-Server/usage-examples.mdx +++ b/docs/APIs-and-SDKs/MCP-Server/usage-examples.mdx @@ -5,9 +5,9 @@ sidebar_position: 6 # Usage Examples -Once the MCP server is connected in your AI assistant (see [Setup](./setup)), +Once the MCP server is connected in your AI assistant (see [Setup](./setup.mdx)), you can drive ABsmartly with plain language. Here are prompts that map cleanly -to the underlying [tools](./tools-reference). +to the underlying [tools](./tools-reference.mdx). ## Discover what's available diff --git a/docs/APIs-and-SDKs/SDK-Documentation/_create-context-basic.mdx b/docs/APIs-and-SDKs/SDK-Documentation/_create-context-basic.mdx index 268c7f57..b19514e8 100644 --- a/docs/APIs-and-SDKs/SDK-Documentation/_create-context-basic.mdx +++ b/docs/APIs-and-SDKs/SDK-Documentation/_create-context-basic.mdx @@ -205,5 +205,5 @@ The `user_id` above is just an example. You can use any unit type that you've co in your Web Console under Settings > Units (e.g. `session_id`, `device_id`, `email`). Pass all the units you have available for the current user. If you're not sure which ones to use, check Settings > Units in the Web Console. You'll see how these connect -to experiments on the [next page](./running-your-first-experiment). +to experiments on the [next page](./running-your-first-experiment.mdx). ::: diff --git a/docs/APIs-and-SDKs/SDK-Documentation/_initialize-basic.mdx b/docs/APIs-and-SDKs/SDK-Documentation/_initialize-basic.mdx index 6b1e961b..5d735c1f 100644 --- a/docs/APIs-and-SDKs/SDK-Documentation/_initialize-basic.mdx +++ b/docs/APIs-and-SDKs/SDK-Documentation/_initialize-basic.mdx @@ -151,7 +151,7 @@ Vue.use(absmartly.ABSmartlyVue, { Using pre-fetched context data If you have already fetched context data on the server (see -[Pre-Fetching Context Data](./pre-fetching-context-data)), you can pass it directly +[Pre-Fetching Context Data](./pre-fetching-context-data.mdx)), you can pass it directly to avoid an extra network request: ```js @@ -236,7 +236,7 @@ app.use(absmartly.ABSmartlyVue, { Using pre-fetched context data If you have already fetched context data on the server (see -[Pre-Fetching Context Data](./pre-fetching-context-data)), you can pass it directly +[Pre-Fetching Context Data](./pre-fetching-context-data.mdx)), you can pass it directly to avoid an extra network request: ```js diff --git a/docs/APIs-and-SDKs/SDK-Documentation/config-api.mdx b/docs/APIs-and-SDKs/SDK-Documentation/config-api.mdx index 6691efcb..d7d15953 100644 --- a/docs/APIs-and-SDKs/SDK-Documentation/config-api.mdx +++ b/docs/APIs-and-SDKs/SDK-Documentation/config-api.mdx @@ -72,5 +72,5 @@ exposures are tracked without you having to think about it. You've reached the end of the SDK Guide. For per-SDK API details beyond what's covered here, check the README in each SDK's GitHub repository (linked on the -[SDK Guide overview](./)). If you have questions, reach out to our team through +[SDK Guide overview](./index.mdx)). If you have questions, reach out to our team through the Web Console. diff --git a/docs/APIs-and-SDKs/SDK-Documentation/feature-support.mdx b/docs/APIs-and-SDKs/SDK-Documentation/feature-support.mdx index a39084db..dcbacbee 100644 --- a/docs/APIs-and-SDKs/SDK-Documentation/feature-support.mdx +++ b/docs/APIs-and-SDKs/SDK-Documentation/feature-support.mdx @@ -1,5 +1,6 @@ --- sidebar_position: 11 +description: "Minimum SDK versions for switchbacks, override rules, split traffic rules and semver comparison, for every ABsmartly SDK, with upgrade notes for React and Swift." --- # SDK Feature Support diff --git a/docs/APIs-and-SDKs/SDK-Documentation/getting-started.mdx b/docs/APIs-and-SDKs/SDK-Documentation/getting-started.mdx index bdde7b3b..074bea22 100644 --- a/docs/APIs-and-SDKs/SDK-Documentation/getting-started.mdx +++ b/docs/APIs-and-SDKs/SDK-Documentation/getting-started.mdx @@ -12,7 +12,7 @@ import CustomEventLogger from "./_shared/custom-event-logger/_custom-event-logge This page walks you through connecting your application to ABsmartly. By the end, you'll have the SDK installed, initialised, and a context ready to use for experiments. -Once you've finished here, the [next page](./running-your-first-experiment) walks through +Once you've finished here, the [next page](./running-your-first-experiment.mdx) walks through a complete experiment: assigning variants, reading variables, and tracking goals. Together, these two pages give you everything you need to run your first test. @@ -56,5 +56,5 @@ before you can check treatments or track goals. ## Next steps Your SDK is installed, initialised, and you have a context ready to go. Head over to -[Running Your First Experiment](./running-your-first-experiment) to learn how to +[Running Your First Experiment](./running-your-first-experiment.mdx) to learn how to assign variants, use variables, and track goals. diff --git a/docs/APIs-and-SDKs/SDK-Documentation/pre-fetching-context-data.mdx b/docs/APIs-and-SDKs/SDK-Documentation/pre-fetching-context-data.mdx index 05bdb7a2..4a645cd6 100644 --- a/docs/APIs-and-SDKs/SDK-Documentation/pre-fetching-context-data.mdx +++ b/docs/APIs-and-SDKs/SDK-Documentation/pre-fetching-context-data.mdx @@ -345,7 +345,7 @@ user sees the correct variant on the very first paint. ## Related topics -- [Targeting Users and Controlling Assignments](./targeting-and-audiences) shows how +- [Targeting Users and Controlling Assignments](./targeting-and-audiences.mdx) shows how to pass user attributes, use custom assignments, and override variants during QA. -- [Using Custom Fields](./using-custom-fields) covers adding per-experiment metadata +- [Using Custom Fields](./using-custom-fields.mdx) covers adding per-experiment metadata for advanced use cases. diff --git a/docs/APIs-and-SDKs/SDK-Documentation/running-your-first-experiment.mdx b/docs/APIs-and-SDKs/SDK-Documentation/running-your-first-experiment.mdx index 3abec480..8ea46dec 100644 --- a/docs/APIs-and-SDKs/SDK-Documentation/running-your-first-experiment.mdx +++ b/docs/APIs-and-SDKs/SDK-Documentation/running-your-first-experiment.mdx @@ -119,11 +119,11 @@ creation, treatment checking, variable usage, goal tracking, and cleanup. You now have everything you need to run a basic experiment. When you're ready to go deeper: -- [Managing the Context Lifecycle](./managing-the-context-lifecycle) covers when to +- [Managing the Context Lifecycle](./managing-the-context-lifecycle.mdx) covers when to close contexts, refresh experiment data, and flush events. -- [Pre-Fetching Context Data](./pre-fetching-context-data) shows how to fetch +- [Pre-Fetching Context Data](./pre-fetching-context-data.mdx) shows how to fetch experiment data on the server and pass it to the client to avoid flickering. -- [Targeting Users and Controlling Assignments](./targeting-and-audiences) shows how +- [Targeting Users and Controlling Assignments](./targeting-and-audiences.mdx) shows how to pass user attributes, use custom assignments, and override variants during QA. -- [Checking Variants Without Triggering Exposures](./checking-variants-without-exposures) +- [Checking Variants Without Triggering Exposures](./checking-variants-without-exposures.mdx) explains peeking, which is useful for pre-loading assets or debugging. diff --git a/docs/APIs-and-SDKs/SDK-Documentation/using-custom-fields.mdx b/docs/APIs-and-SDKs/SDK-Documentation/using-custom-fields.mdx index 9328ba23..32964d22 100644 --- a/docs/APIs-and-SDKs/SDK-Documentation/using-custom-fields.mdx +++ b/docs/APIs-and-SDKs/SDK-Documentation/using-custom-fields.mdx @@ -180,12 +180,12 @@ edited on the Web Console to change the variant that developers see. :::caution Overriding an experiment allocation will not count the user towards the experiment data. -To learn more about overrides, have a look at the [overrides documentation](./targeting-and-audiences#overriding-variants-for-development-and-qa). +To learn more about overrides, have a look at the [overrides documentation](./targeting-and-audiences.mdx#overriding-variants-for-development-and-qa). ::: ## Next steps -- [Targeting Users and Controlling Assignments](./targeting-and-audiences) covers +- [Targeting Users and Controlling Assignments](./targeting-and-audiences.mdx) covers overrides and custom assignments in more detail. -- [Config API](./config-api) shows another way to use experiment data without +- [Config API](./config-api.mdx) shows another way to use experiment data without branching logic in your code. diff --git a/docs/APIs-and-SDKs/SDK-Documentation/using-variables-as-code.mdx b/docs/APIs-and-SDKs/SDK-Documentation/using-variables-as-code.mdx index 92557cc0..35f8ca16 100644 --- a/docs/APIs-and-SDKs/SDK-Documentation/using-variables-as-code.mdx +++ b/docs/APIs-and-SDKs/SDK-Documentation/using-variables-as-code.mdx @@ -6,7 +6,7 @@ import Image from "@theme/IdealImage"; # Using Variables as Code -[Treatment variables](./running-your-first-experiment#step-2-use-variables-for-flexible-experiments) +[Treatment variables](./running-your-first-experiment.mdx#step-2-use-variables-for-flexible-experiments) are great for setting values like colours, copy, or feature flags. But sometimes you want the Web Console to control actual behaviour: injecting HTML elements, running functions, or applying CSS styles. @@ -18,7 +18,7 @@ a function directly from the Web Console. ## Starting Point For these examples, we're using a basic Vite app with the SDK already initialised and a -context ready (see [Getting Started](./getting-started) if you need to set that up). +context ready (see [Getting Started](./getting-started.mdx) if you need to set that up). The page starts with a simple heading:
diff --git a/docs/APIs-and-SDKs/overview.mdx b/docs/APIs-and-SDKs/overview.mdx index bd229beb..6723188c 100644 --- a/docs/APIs-and-SDKs/overview.mdx +++ b/docs/APIs-and-SDKs/overview.mdx @@ -1,8 +1,10 @@ --- +title: "Developer Tools Overview" +sidebar_label: "Overview" sidebar_position: 0 --- -# Overview +# Developer Tools Overview The **Developer Tools** section is the technical home of ABsmartly. It covers every way you can integrate, automate, extend or operate the platform from diff --git a/docs/Third-party-integrations/SSO/Azure SAML Setup.mdx b/docs/Third-party-integrations/SSO/Azure SAML Setup.mdx index 91579254..bf783248 100644 --- a/docs/Third-party-integrations/SSO/Azure SAML Setup.mdx +++ b/docs/Third-party-integrations/SSO/Azure SAML Setup.mdx @@ -93,7 +93,7 @@ Feel free to add [the ABsmartly logo](/img/logo.png) to the application in **Pro | `lastName` | `Attribute` | `user.surname` | | `department` | `Attribute` | `user.department` | -To assign ABsmartly roles from Azure, also add a `roles` claim, see [Assigning Roles](./SAML%20Role%20Mapping). +To assign ABsmartly roles from Azure, also add a `roles` claim, see [Assigning Roles](./SAML%20Role%20Mapping.mdx). firstName - Last Name -> lastName - To assign ABsmartly roles from Google Workspace, also map a `roles` attribute, see [Assigning Roles](./SAML%20Role%20Mapping). + To assign ABsmartly roles from Google Workspace, also map a `roles` attribute, see [Assigning Roles](./SAML%20Role%20Mapping.mdx). -Check the [Exposure events](exposure-events) and [Goal events](goal-events) pages for more details on those events +Check the [Exposure events](exposure-events.mdx) and [Goal events](goal-events.mdx) pages for more details on those events ## Events Filters @@ -94,4 +94,4 @@ this box and only your own events will appear in the list. ## Downloading Events -See the [downloading events page](downloading-events) for a complete guide to downloading raw events. \ No newline at end of file +See the [downloading events page](downloading-events.mdx) for a complete guide to downloading raw events. \ No newline at end of file diff --git a/docs/web-console-docs/events/visitors-identity.mdx b/docs/web-console-docs/events/visitors-identity.mdx index eb9f446a..a5a22d78 100644 --- a/docs/web-console-docs/events/visitors-identity.mdx +++ b/docs/web-console-docs/events/visitors-identity.mdx @@ -18,7 +18,7 @@ Those identifiers are used to uniquely identify visitors in experiments through to link them to the goals events they are triggering as they use your products. What identifiers exist depends on where the experiment is running and what you know about the visitor at that moment. -Those tracking identifiers (also know as Units) need to be pre-registered on the ABsmartly platform, see [Units](../configuration/units) for more details. +Those tracking identifiers (also know as Units) need to be pre-registered on the ABsmartly platform, see [Units](../configuration/units.mdx) for more details. Below is an example on how the ABsmartly context can be initialised with 3 different unit types. diff --git a/docs/web-console-docs/experiments/aborting-experiments.mdx b/docs/web-console-docs/experiments/aborting-experiments.mdx index ff248767..a45f8892 100644 --- a/docs/web-console-docs/experiments/aborting-experiments.mdx +++ b/docs/web-console-docs/experiments/aborting-experiments.mdx @@ -47,7 +47,7 @@ If the treatment introduces a **bug** or **technical failure** that disrupts cor A bug in the checkout flow prevents users from completing transactions, making it imperative to abort the experiment immediately. ### Experiment Health Checks alert -[Health Checks](experiment-health-checks) are quality checks run in the background to ensure the experiment and data are reliable. Most health checks alerts would require to abort the experiment and investigate the reason for the alert. +[Health Checks](experiment-health-checks.mdx) are quality checks run in the background to ensure the experiment and data are reliable. Most health checks alerts would require to abort the experiment and investigate the reason for the alert. **Example**: The health checks show an assignment conflicts was detected meaning that some visitors have been exposed to more than one variant. This might require the experiment to be stopped and the issue investigated. diff --git a/docs/web-console-docs/experiments/creating-an-experiment.mdx b/docs/web-console-docs/experiments/creating-an-experiment.mdx index 854fa8aa..5dbb4a3c 100644 --- a/docs/web-console-docs/experiments/creating-an-experiment.mdx +++ b/docs/web-console-docs/experiments/creating-an-experiment.mdx @@ -13,7 +13,7 @@ To get started with creating a new experiment, you can click **Experiments** on :::info Instead of creating an experiment from scratch you can also decide to use a pre-existing template. -To find out more about creating and using templates check our [template documentation](templates). +To find out more about creating and using templates check our [template documentation](templates.mdx). ::: ## Basics @@ -80,7 +80,7 @@ Screenshots are useful to quickly understand what an experiment is changing. The audiences’ step is where you will control where the experiment will run and who will be exposed to it. :::info Redesigned experiment form -In the redesigned experiment form, this step is split into the **Tracking** and **Unit assignments** sections, the targeting audience is called **eligibility rules**, and exclusion rules are called **override rules**. See [Unit Assignment](./unit-assignment) for details. +In the redesigned experiment form, this step is split into the **Tracking** and **Unit assignments** sections, the targeting audience is called **eligibility rules**, and exclusion rules are called **override rules**. See [Unit Assignment](./unit-assignment.mdx) for details. ::: Defining the audience @@ -240,7 +240,7 @@ It is good practice to have a set of guardrail metrics agreed upon and shared by To improve their usefulness, it is possible to define on the metric’s page, a threshold at which an alert would be triggered so you don’t miss it. Depending on the severity of the issues they signal, **Guardrail Metrics** can be used both for early stopping of experiments and to assess their impact at decision time. -For more information on early stopping of experiments using ABsmartly you can read our [**early stopping guide**](aborting-experiments). +For more information on early stopping of experiments using ABsmartly you can read our [**early stopping guide**](aborting-experiments.mdx). ### The Exploratory Metrics @@ -272,12 +272,12 @@ Cannot find your metric in the list? Make sure it is `active` as `draft` metrics ## Analysis In this step, you can choose and set up the analysis type you want to use. -To choose between a Group Sequential or Fixed Horizon analysis check our [analysis type article](overview#analysis-methods). +To choose between a Group Sequential or Fixed Horizon analysis check our [analysis type article](overview.mdx#analysis-methods). To continue to properly set up your experiment refer to the relevant setup guide -- [**Group Sequential setup guide**](setting-up-a-gst-experiment) -- [**Fixed Horizon setup guide**](setting-up-a-fixed-horizon-experiment) +- [**Group Sequential setup guide**](setting-up-a-gst-experiment.mdx) +- [**Fixed Horizon setup guide**](setting-up-a-fixed-horizon-experiment.mdx) ## Metadata diff --git a/docs/web-console-docs/experiments/experiment-health-checks.mdx b/docs/web-console-docs/experiments/experiment-health-checks.mdx index 20634c51..e74539cd 100644 --- a/docs/web-console-docs/experiments/experiment-health-checks.mdx +++ b/docs/web-console-docs/experiments/experiment-health-checks.mdx @@ -90,7 +90,7 @@ Assess the risk of the interaction and abort one or both of the experiments to e ### Variables Conflicting **What is it?** -Checks for conflicting variables used across 2 or more experiments. This check is performed when [Experiment Variables](creating-an-experiment#variant-variables) are used in the experiment setup. +Checks for conflicting variables used across 2 or more experiments. This check is performed when [Experiment Variables](creating-an-experiment.mdx#variant-variables) are used in the experiment setup. :::caution Variable keys that are prefixed with a double underscore (`__`) are ignored during this health check. diff --git a/docs/web-console-docs/experiments/experiment-reports.mdx b/docs/web-console-docs/experiments/experiment-reports.mdx index 81031f39..77003e3b 100644 --- a/docs/web-console-docs/experiments/experiment-reports.mdx +++ b/docs/web-console-docs/experiments/experiment-reports.mdx @@ -89,8 +89,8 @@ Even if an experiment was running only for a few seconds it would appear on the Experiments completed report This report highlights the number of experiment which were successfully completed in the reporting period. -In the case of a [Fixed Horizon Experiment](overview#analysis-methods), it is deemed completed once it reaches its expected sample size or planned duration. -For a [Group Sequential Test](overview#analysis-methods), an experiment is completed once it crosses one of the test boundaries (efficiency or futility). +In the case of a [Fixed Horizon Experiment](overview.mdx#analysis-methods), it is deemed completed once it reaches its expected sample size or planned duration. +For a [Group Sequential Test](overview.mdx#analysis-methods), an experiment is completed once it crosses one of the test boundaries (efficiency or futility). The report also visualises the outcome of the statistical test on the primary metric at the moment the experiment was completed. The experiment will be shown in `green` if its **primary metric was significant in the expected direction** at the time the experiment was completed. @@ -112,7 +112,7 @@ Knowing that something does not have the expected impact on customer behaviour c In the case of **early stopped experiments** (also known as aborted experiments), the decisions to abort can happen because of bugs in the implementation, early worrying negative signals, strategic reasons or for any other reason. Depending on the reason for early stopping, aborted experiments are typically restarted once the underlying issue is fixed. -Read our [When to abort an experiment?](aborting-experiments) guide to understand more about aborting experiments. +Read our [When to abort an experiment?](aborting-experiments.mdx) guide to understand more about aborting experiments. While aborting experiments is common and part of the process, **early Full on**, should be rare as they indicate that changes were pushed without supporting evidence. This can sometimes happen for strategic or legal reasons but because the experiment did not complete, it does not provide the reliable evidence needed to support or discard the underlying hypothesis. @@ -156,7 +156,7 @@ It is nonetheless possible for `Full on` decisions to not be fully supported by Currently a `Full on` decision is shown as supported by evidence **if and only if the experiment was completed and the primary metric is significant in the expected direction**. :::caution -The supported by evidence validation does not currently include checks on the secondary and guardrail metrics nor on the experiment [health checks](experiment-health-checks). +The supported by evidence validation does not currently include checks on the secondary and guardrail metrics nor on the experiment [health checks](experiment-health-checks.mdx). ::: @@ -176,7 +176,7 @@ This typically happens when the evidence does not support the hypothesis. This widget provides a view on how many `Abort` decisions were made in the reporting period. Aborting means stopping an experiment before it is completed. Aborting can happen when a bug is found or when early negative signals indicate a possible degradation in certain key metrics but it could also be a strategic choice to stop early. -Read our [When to abort an experiment?](aborting-experiments) guide to understand more about aborting experiments. +Read our [When to abort an experiment?](aborting-experiments.mdx) guide to understand more about aborting experiments. Like with `Keep current` decisions, `Abort` decisons means that the current experience remains but unlike `Keep current` decisions it does not say anything about the hypothesis being tested or not. ### Decisions history diff --git a/docs/web-console-docs/experiments/interpreting-metrics-in-experiment-results.mdx b/docs/web-console-docs/experiments/interpreting-metrics-in-experiment-results.mdx index 65dfbec9..d40aa40d 100644 --- a/docs/web-console-docs/experiments/interpreting-metrics-in-experiment-results.mdx +++ b/docs/web-console-docs/experiments/interpreting-metrics-in-experiment-results.mdx @@ -22,7 +22,7 @@ The metrics table provides the following key data points for each variant: - **Participants**: The number of individuals assigned to each variant, expressed as a count and percentage of the total participants. - **Value**: The total count or sum associated with the metric (e.g., number of "buyers") for each variant. -- **Mean**: The average performance of the metric for each variant, calculated as: `Mean = Value / Participants`. If the metric uses [CUPED](../goals-and-metrics/metrics/variance-reduction-cuped), Value and Mean are CUPED-adjusted. For [Ratio](../goals-and-metrics/metrics/metric-types/ratio) metrics, Value and Mean both show the ratio. +- **Mean**: The average performance of the metric for each variant, calculated as: `Mean = Value / Participants`. If the metric uses [CUPED](../goals-and-metrics/metrics/variance-reduction-cuped.mdx), Value and Mean are CUPED-adjusted. For [Ratio](../goals-and-metrics/metrics/metric-types/ratio.mdx) metrics, Value and Mean both show the ratio. - **Confidence**: The statistical confidence that the observed difference between variants is real, not due to random chance. diff --git a/docs/web-console-docs/experiments/overview.mdx b/docs/web-console-docs/experiments/overview.mdx index 67fc2095..a491d9e3 100644 --- a/docs/web-console-docs/experiments/overview.mdx +++ b/docs/web-console-docs/experiments/overview.mdx @@ -1,10 +1,12 @@ --- +title: "Experiments Overview" +sidebar_label: "Overview" sidebar_position: 1 --- import Image from "../../../src/components/Image"; -# Overview +# Experiments Overview ## What is an experiment @@ -39,7 +41,7 @@ When a user reaches an experiment, ABsmartly assigns them to a variant using a d - consistent behaviour during the entire experiment - predictable control of traffic allocation -[Exposure events](../events/exposure-events) are sent automatically by the SDK, and these events define when users become part of the analysis dataset. +[Exposure events](../events/exposure-events.mdx) are sent automatically by the SDK, and these events define when users become part of the analysis dataset. ### Variants @@ -55,7 +57,7 @@ Variants determine what users see, while the metrics determine how those differe ### Goals and metrics -Experiments are measured using [goals](../goals-and-metrics/goals/overview) and the [metrics](../goals-and-metrics/metrics/overview) derived from them. +Experiments are measured using [goals](../goals-and-metrics/goals/overview.mdx) and the [metrics](../goals-and-metrics/metrics/overview.mdx) derived from them. Examples of goals: @@ -65,7 +67,7 @@ context.track("add_to_cart", { product_id: "ABC123" }); context.track("view_item", { item_id: "XYZ987" }); ``` -Metrics take your [goal events](../events/goal-events) and turn them into meaningful measurements of user behaviour. +Metrics take your [goal events](../events/goal-events.mdx) and turn them into meaningful measurements of user behaviour. They let you answer questions like: - how many times something happened @@ -77,16 +79,16 @@ ABsmartly handles all the computation and presents the results in a clear, compa ### Guardrails and monitoring -Before experiment results can be trusted, ABsmartly performs several [health checks](experiment-health-checks) automatically: +Before experiment results can be trusted, ABsmartly performs several [health checks](experiment-health-checks.mdx) automatically: - Sample Ratio Mismatch at the experiment level - assignment and exposure conflicts - guardrail metric thresholds - unexpected behaviour in exposure or goal events - data quality anomalies -Guardrails help detect harmful side effects and make it possible to [abort experiments](aborting-experiments) if needed. +Guardrails help detect harmful side effects and make it possible to [abort experiments](aborting-experiments.mdx) if needed. -You can also configure guardrail metrics with [thresholds](../goals-and-metrics/metrics/create#metric-threshold-alert) that alert you when impact crosses meaningful limits, +You can also configure guardrail metrics with [thresholds](../goals-and-metrics/metrics/create.mdx#metric-threshold-alert) that alert you when impact crosses meaningful limits, for example when a performance metric becomes slower or when a business KPI shows a potential drop. ### Analysing results @@ -100,7 +102,7 @@ For each metric you will see: - confidence interval - impact per day -You can use our guide on [interpreting metrics results](interpreting-metrics-in-experiment-results) to help with the analysis step. +You can use our guide on [interpreting metrics results](interpreting-metrics-in-experiment-results.mdx) to help with the analysis step. ### Decisions @@ -221,7 +223,7 @@ The frontend calls `context.track`. The SDK returns the assigned variant, and th - Very fast iteration - No backend deployment needed - Ideal for design and UX teams -- Non-engineers can create visually in the [Visual Editor](../launchpad-browser-extension/getting-started) +- Non-engineers can create visually in the [Visual Editor](../launchpad-browser-extension/getting-started.mdx) **Things to consider** - Must be implemented correctly to avoid flicker @@ -360,7 +362,7 @@ The following permissions exist when managing and working with `experiments`. #### Global access -Permission to create and manage `experiments` can be granted to the relevant users through their [role](../configuration/settings#roles) at the platform level. +Permission to create and manage `experiments` can be granted to the relevant users through their [role](../configuration/settings.mdx#roles) at the platform level. :::info It is not recommended to provide access to `metrics` to non platform admin users at the platform level. diff --git a/docs/web-console-docs/experiments/setting-up-a-fixed-horizon-experiment.mdx b/docs/web-console-docs/experiments/setting-up-a-fixed-horizon-experiment.mdx index dec0282d..8976e9bb 100644 --- a/docs/web-console-docs/experiments/setting-up-a-fixed-horizon-experiment.mdx +++ b/docs/web-console-docs/experiments/setting-up-a-fixed-horizon-experiment.mdx @@ -11,7 +11,7 @@ A step by step guide to set up and configure a Fixed Horizon experiment. ## Type of Analysis A Fixed Horizon test can be configured on the Analysis step (Step 5) of the experimentation setup. -To understand the differences between Group Sequential and Fixed Horizon experiment check our [analysis type article](overview#analysis-methods). +To understand the differences between Group Sequential and Fixed Horizon experiment check our [analysis type article](overview.mdx#analysis-methods). Choosing an analysis type diff --git a/docs/web-console-docs/experiments/setting-up-a-gst-experiment.mdx b/docs/web-console-docs/experiments/setting-up-a-gst-experiment.mdx index 83a01f41..fc734ab1 100644 --- a/docs/web-console-docs/experiments/setting-up-a-gst-experiment.mdx +++ b/docs/web-console-docs/experiments/setting-up-a-gst-experiment.mdx @@ -11,7 +11,7 @@ A step by step guide to set up and configure a Group Sequential experiment. ## Type of Analysis A Group Sequential test can be configured on the Analysis step (Step 5) of the experimentation setup. -To understand the differences between Group Sequential and Fixed Horizon experiment check our [analysis type article](overview#analysis-methods). +To understand the differences between Group Sequential and Fixed Horizon experiment check our [analysis type article](overview.mdx#analysis-methods). Choosing an analysis type diff --git a/docs/web-console-docs/experiments/templates.mdx b/docs/web-console-docs/experiments/templates.mdx index 4c5a37d2..23b5a568 100644 --- a/docs/web-console-docs/experiments/templates.mdx +++ b/docs/web-console-docs/experiments/templates.mdx @@ -1,10 +1,12 @@ --- +title: "Experiment Templates in the Web Console" +sidebar_label: "Experiment Templates" sidebar_position: 8 --- import Image from "../../../src/components/Image"; -# Experiment Templates +# Experiment Templates in the Web Console ## Overview **Templates** are designed to streamline the process of creating experiments and feature flags. By using templates, you can quickly set up experiments with pre-configured settings, avoiding the need to start from scratch each time. This not only speeds up the process but also ensures consistency and quality across all experiments and feature flags. diff --git a/docs/web-console-docs/experiments/unit-assignment.mdx b/docs/web-console-docs/experiments/unit-assignment.mdx index b3d59a83..0e56bffa 100644 --- a/docs/web-console-docs/experiments/unit-assignment.mdx +++ b/docs/web-console-docs/experiments/unit-assignment.mdx @@ -15,7 +15,7 @@ In the redesigned experiment form, the **Unit assignments** section decides whic - [Override rules](#override-rules): units forced into a variant, or into their own traffic split, and excluded from the analysis - [Assignment summary](#assignment-summary): a live view of how every unit will be assigned -The tracking unit and the applications are set in the **Tracking** section, just above. See [Create an experiment](./creating-an-experiment#tracking-unit) for more details on choosing them. +The tracking unit and the applications are set in the **Tracking** section, just above. See [Create an experiment](./creating-an-experiment.mdx#tracking-unit) for more details on choosing them. ## Eligibility rules @@ -28,7 +28,7 @@ The rules are shown in the **Experiment rules** card, under **Eligibility**. Eac The **Audience enforced** switch decides what happens to units which don't match the eligibility rules: - **Audience enforced**: only units matching the eligibility rules take part in the experiment. Other units are shown the control variant, but their data is not tracked. -- **Audience not enforced**: every unit takes part, and it is up to you to make sure only eligible units are shown the experiment in your code. ABsmartly shows an [audience mismatch](./experiment-health-checks#audience-mismatch) warning when units not matching the rules are exposed. +- **Audience not enforced**: every unit takes part, and it is up to you to make sure only eligible units are shown the experiment in your code. ABsmartly shows an [audience mismatch](./experiment-health-checks.mdx#audience-mismatch) warning when units not matching the rules are exposed. ## Traffic allocation and variant split diff --git a/docs/web-console-docs/goals-and-metrics/goals/composite-goals.mdx b/docs/web-console-docs/goals-and-metrics/goals/composite-goals.mdx index 1b5e8c04..b8d7c5f7 100644 --- a/docs/web-console-docs/goals-and-metrics/goals/composite-goals.mdx +++ b/docs/web-console-docs/goals-and-metrics/goals/composite-goals.mdx @@ -14,11 +14,11 @@ Composite goals are useful when the same outcome is tracked under different goal - A sign-up event was renamed from `signup` to `registration` and older code still sends the old name - Several micro-conversions such as `add_to_wishlist`, `share_product` and `save_for_later` together describe engagement -Instead of building a separate metric for each goal, you create one composite goal and build your [metrics](../metrics/overview) on top of it, exactly as you would with any other goal. +Instead of building a separate metric for each goal, you create one composite goal and build your [metrics](../metrics/overview.mdx) on top of it, exactly as you would with any other goal. ## Creating a composite goal -Composite goals are created from `Settings` > `Goals`, in the same way as any other [goal](./create). +Composite goals are created from `Settings` > `Goals`, in the same way as any other [goal](./create.mdx). 1. Enter a **Goal name** and a **Description** 2. Set **Goal type** to `Composite Goal` @@ -61,7 +61,7 @@ Component goals don't always use the same names for the same data. For example, | `revenue` | `total` | `amount` | | `currency` | `currency` | `currency_code` | -The mapped properties can then be used in metrics built on the composite goal, both as the metric's [property](../metrics/create#property) and in [property filters](../metrics/create#property-filters). +The mapped properties can then be used in metrics built on the composite goal, both as the metric's [property](../metrics/create.mdx#property) and in [property filters](../metrics/create.mdx#property-filters). ## Using composite goals in metrics @@ -73,9 +73,9 @@ For example, with a composite goal `purchase` combining `payment_web` and `payme - A **goal property** metric on `revenue` sums `total` from `payment_web` and `amount` from `payment_app` :::info -Composite goals cannot currently be used as the foreign goal of a [goal relation](../metrics/create#goal-relations), such as a cancellation or a refund. +Composite goals cannot currently be used as the foreign goal of a [goal relation](../metrics/create.mdx#goal-relations), such as a cancellation or a refund. ::: ## Tracking composite goals -Nothing changes in your code. Composite goals are built from the goals you already track with the SDK's `track` method, so you don't send events for the composite goal itself. See [Goal Events](../../events/goal-events) for more details on tracking goals. +Nothing changes in your code. Composite goals are built from the goals you already track with the SDK's `track` method, so you don't send events for the composite goal itself. See [Goal Events](../../events/goal-events.mdx) for more details on tracking goals. diff --git a/docs/web-console-docs/goals-and-metrics/goals/create.mdx b/docs/web-console-docs/goals-and-metrics/goals/create.mdx index 41489316..da9fb1b3 100644 --- a/docs/web-console-docs/goals-and-metrics/goals/create.mdx +++ b/docs/web-console-docs/goals-and-metrics/goals/create.mdx @@ -20,7 +20,7 @@ Goals can be created in the ABsmartly's console by navigating to `Settings` and | Field | Description | |-------|--------------| | **Goal Name** | The unique goal name. This is the name which needs to be used in when calling `track` | -| **Goal type** | `Simple Goal` for a goal tracked with the SDK, or `Composite Goal` to combine several existing goals. See [Composite Goals](./composite-goals). | +| **Goal type** | `Simple Goal` for a goal tracked with the SDK, or `Composite Goal` to combine several existing goals. See [Composite Goals](./composite-goals.mdx). | | **Description**| Describes what this goal tracks. | | **Owners**| The list of goal owners. Owners can be Teams or individuals. | | **Tags**| Tags used to better describe the goal and improve discoverability. | diff --git a/docs/web-console-docs/goals-and-metrics/goals/overview.mdx b/docs/web-console-docs/goals-and-metrics/goals/overview.mdx index 22ef516f..a7a1c3cf 100644 --- a/docs/web-console-docs/goals-and-metrics/goals/overview.mdx +++ b/docs/web-console-docs/goals-and-metrics/goals/overview.mdx @@ -1,8 +1,10 @@ --- +title: "Goals Overview" +sidebar_label: "Overview" sidebar_position: 1 --- -# Overview +# Goals Overview ## Goals @@ -10,7 +12,7 @@ sidebar_position: 1 They represent actions that are meaningful to the product or business — such as viewing a page, clicking a button, adding an item to a cart, or completing a purchase. Each goal is defined by a name and any associated contextual data (for example, `product ID`, `price`, or `category`). Goals are the building blocks of measurement: they define what to observe in the experiment. -Goals are the raw data used to compute [Metrics](../metrics/overview). +Goals are the raw data used to compute [Metrics](../metrics/overview.mdx). ## Goal Events @@ -28,7 +30,7 @@ context.track("purchase", { ``` In the example above, a `goal` with the name **purchase** was triggered. This goal has additional property information which can be used to compute the metric. -To learn more about `events` you can read the dedicated [Goal Events page](../../events/goal-events) in the knowledge base. +To learn more about `events` you can read the dedicated [Goal Events page](../../events/goal-events.mdx) in the knowledge base. ## Ownership & permissions @@ -69,7 +71,7 @@ The following permissions exist when managing and working with `goals`. #### Global access -Permission to create and manage `goals` can be granted to the relevant users through their [role](../../configuration/settings#roles) at the platform level. +Permission to create and manage `goals` can be granted to the relevant users through their [role](../../configuration/settings.mdx#roles) at the platform level. :::info It is not recommended to provide access to `goals` to non platform admin at the platform level. diff --git a/docs/web-console-docs/goals-and-metrics/metrics/create.mdx b/docs/web-console-docs/goals-and-metrics/metrics/create.mdx index fec44c7e..b5c03442 100644 --- a/docs/web-console-docs/goals-and-metrics/metrics/create.mdx +++ b/docs/web-console-docs/goals-and-metrics/metrics/create.mdx @@ -30,15 +30,15 @@ This information is version-specific and, as such, can differ between different |-------|--------------| | **Description** | Providing a good description is important as it helps experiments choose the right metric.| | **Impact**| Directionality of the metric. `positive` means that increasing this metric is good. `negative` means that decreasing the metric is good. Use `unknown` if the metric has no preferred direction.| -| **Metric type**| Describes how the metric is implemented. Choose between [`Goal Unique Count`](metric-types/goal-unique-count), [`Goal Count`](metric-types/goal-count), [`Goal Time To Achievement`](metric-types/time-to-achievement), [`Goal Property`](metric-types/property), [`Goal Property Unique Count`](metric-types/unique-property-count), [`Goal Retention`](metric-types/retention), [`Goal Activity Period Count`](metric-types/activity-per-period) and [`Ratio`](metric-types/ratio). `Custom SQL` is also available when [warehouse-native](../../warehouse-native/overview) is enabled. | +| **Metric type**| Describes how the metric is implemented. Choose between [`Goal Unique Count`](metric-types/goal-unique-count.mdx), [`Goal Count`](metric-types/goal-count.mdx), [`Goal Time To Achievement`](metric-types/time-to-achievement.mdx), [`Goal Property`](metric-types/property.mdx), [`Goal Property Unique Count`](metric-types/unique-property-count.mdx), [`Goal Retention`](metric-types/retention.mdx), [`Goal Activity Period Count`](metric-types/activity-per-period.mdx) and [`Ratio`](metric-types/ratio.mdx). `Custom SQL` is also available when [warehouse-native](../../warehouse-native/overview.mdx) is enabled. | | **Tags** (optional)| Makes the metric more discoverable by providing relevant [tags](/docs/web-console-docs/configuration/settings#tags).| -| **Category** (optional)| The [category](categories) the metric belongs to (`conversion`, `performance`, etc). While optional, selecting a category makes it easier for experimenters to find relevant metrics. | -| **Applications** (optional)| Select the [applications](../../configuration/applications) where this metric makes sense. Only experiments running on these applications should track this metric. While optional, setting the correct `Application(s)` helps experimenters find relevant metrics for their experiments. | -| **Units** (optional)| Select the [tracking units](../../configuration/units) for which this metric is computed. The tracking unit of the metric should match the tracking unit of the experiments where it is tracked. While optional, setting the correct `Tracking Unit(s)` will help experimenters track relevant metrics in their experiments. | +| **Category** (optional)| The [category](categories.mdx) the metric belongs to (`conversion`, `performance`, etc). While optional, selecting a category makes it easier for experimenters to find relevant metrics. | +| **Applications** (optional)| Select the [applications](../../configuration/applications.mdx) where this metric makes sense. Only experiments running on these applications should track this metric. While optional, setting the correct `Application(s)` helps experimenters find relevant metrics for their experiments. | +| **Units** (optional)| Select the [tracking units](../../configuration/units.mdx) for which this metric is computed. The tracking unit of the metric should match the tracking unit of the experiments where it is tracked. While optional, setting the correct `Tracking Unit(s)` will help experimenters track relevant metrics in their experiments. | ## Goal -In this section, you can select and configure the [goal](../goals/overview) which provides the raw data for this metric. +In this section, you can select and configure the [goal](../goals/overview.mdx) which provides the raw data for this metric. :::info This part of a metric’s setup is version-controlled. @@ -58,7 +58,7 @@ context.track("purchase", { ### Goal -Select the [goal](../goals/overview) to use as a source for this metric. +Select the [goal](../goals/overview.mdx) to use as a source for this metric. In the example above, the name of the goal is `purchase`. If you don't see a goal in the list, make sure it exists and make sure you have the correct permissions to view and use it. @@ -69,7 +69,7 @@ Auto-created goals do not have an owner when created. For governance reasons, ma ### Property -In the case of [`Goal Property`](metric-types/property) or [`Goal Property Unique Count`](metric-types/unique-property-count) metrics, +In the case of [`Goal Property`](metric-types/property.mdx) or [`Goal Property Unique Count`](metric-types/unique-property-count.mdx) metrics, you also need to choose which property of the metric to use. For example, a `revenue` metric built using the goal event above, would use the event property **price**. @@ -91,7 +91,7 @@ A time filter lets you include only the goal events that happen within a defined This ensures your metric measures behavior in a controlled, meaningful period (for example, `purchases within the first hour` or `engagement in the first 7 days`). :::caution -If your metric uses [CUPED](variance-reduction-cuped) and has an `At least` or `Between` time filter, the lookback period must be longer than the start of the time filter. +If your metric uses [CUPED](variance-reduction-cuped.mdx) and has an `At least` or `Between` time filter, the lookback period must be longer than the start of the time filter. For example, if your metric measures `conversions achieved at least 2 weeks after exposure`, the CUPED lookback period must be 3 or 4 weeks. ::: @@ -219,7 +219,7 @@ Goal relations define how one goal (the current one) is linked to another goal ( This identifier is provided through a property in both events (for example **order_number**, **purchase_id**, or **transaction_id**). Each relation type has its own behaviour and additional fields. -Refund and replacement relations are only available for [`Goal Property`](metric-types/property#refunds-and-replacements) metrics, including a Goal Property numerator or denominator in a Ratio. +Refund and replacement relations are only available for [`Goal Property`](metric-types/property.mdx#refunds-and-replacements) metrics, including a Goal Property numerator or denominator in a Ratio. #### Cancellation @@ -348,8 +348,8 @@ Replacement relations allow the metric to reflect up-to-date values when items a ## Variance reduction -If applicable, you can enable [CUPED](variance-reduction-cuped) for this metric to help reduce variance. -Enable [CUPED](variance-reduction-cuped) for this metric by checking the checkbox and choose a lookback period which matches the user behaviour. +If applicable, you can enable [CUPED](variance-reduction-cuped.mdx) for this metric to help reduce variance. +Enable [CUPED](variance-reduction-cuped.mdx) for this metric by checking the checkbox and choose a lookback period which matches the user behaviour. ## Format, scale and precisions @@ -378,7 +378,7 @@ These settings allow you to present the metric in a readable and meaningful way ### Value The Value column in the results table displays the total summed value of your metric for each variant. -For [ratio metrics](metric-types/ratio), Value and Mean both show the ratio, so set both formats to suit the ratio. +For [ratio metrics](metric-types/ratio.mdx), Value and Mean both show the ratio, so set both formats to suit the ratio. You can control how this number appears using: #### Format diff --git a/docs/web-console-docs/goals-and-metrics/metrics/metric-types/activity-per-period.mdx b/docs/web-console-docs/goals-and-metrics/metrics/metric-types/activity-per-period.mdx index b702f1a2..83b46e98 100644 --- a/docs/web-console-docs/goals-and-metrics/metrics/metric-types/activity-per-period.mdx +++ b/docs/web-console-docs/goals-and-metrics/metrics/metric-types/activity-per-period.mdx @@ -30,11 +30,11 @@ Three users are exposed to the experiment: In the experiment results, this group would show a **Value** of 3 (2 + 1 + 0 active days in total) and a **Mean** of 3 / 3 = **1.0** active day per participant. -Compare that with a [`Goal Count`](./goal-count) on the same goal, which counts every event: Ana 3, Ben 12 and Cara 0, so a **Value** of 15 and a **Mean** of 5. Ben's burst of activity dominates the count, while the activity period count shows that Ana came back on more days. +Compare that with a [`Goal Count`](./goal-count.mdx) on the same goal, which counts every event: Ana 3, Ben 12 and Cara 0, so a **Value** of 15 and a **Mean** of 5. Ben's burst of activity dominates the count, while the activity period count shows that Ana came back on more days. ## Creating the metric -When [creating a metric](../create), choose `Goal Activity Period Count` as the metric type, then: +When [creating a metric](../create.mdx), choose `Goal Activity Period Count` as the metric type, then: 1. Select the goal you want to measure, for example `app_open`. 2. Set the **Activity interval**: a number and a unit (`Hours`, `Days` or `Weeks`). @@ -50,7 +50,7 @@ Because the slots don't start at the user's exposure, a user's first period can ## Reading the results -In the [metric results table](../../../experiments/interpreting-metrics-in-experiment-results), **Value** is the total number of active periods across all participants in the variant, and **Mean** is that total divided by the number of participants. The impact is calculated on the Mean, as with other continuous metrics such as `Goal Count`. +In the [metric results table](../../../experiments/interpreting-metrics-in-experiment-results.mdx), **Value** is the total number of active periods across all participants in the variant, and **Mean** is that total divided by the number of participants. The impact is calculated on the Mean, as with other continuous metrics such as `Goal Count`. If CUPED is active for the metric, both Value and Mean are CUPED-adjusted, so they won't match the raw count of active periods and can be fractional. Configuring CUPED isn't always enough: if the pre-exposure covariate doesn't correlate well enough with the metric, or the adjustment wouldn't reduce variance, ABsmartly falls back to the unadjusted values. @@ -61,7 +61,7 @@ Because the value counts periods rather than dividing by them, it grows the long - `Active days`: goal `app_open`, interval `1 day`. How many different days users opened the app. - `Active weeks with a purchase`: goal `purchase`, interval `1 week`. How many different weeks users bought something. - `Active hours watching`: goal `video_play`, interval `1 hour`. How many different hours users started a video. -- `Purchases per active day`: a [Ratio](./ratio) metric with a `Goal Count` of `purchase` as the numerator and a `Goal Activity Period Count` of `app_open` (1 day) as the denominator. +- `Purchases per active day`: a [Ratio](./ratio.mdx) metric with a `Goal Count` of `purchase` as the numerator and a `Goal Activity Period Count` of `app_open` (1 day) as the denominator. ## Good to know @@ -69,5 +69,5 @@ Because the value counts periods rather than dividing by them, it grows the long - Less sensitive to bursts than `Goal Count`, because repeat events in the same period add nothing. - Filters on the goal apply before periods are counted, so `Active days with a purchase in category ZYZ123` only counts days with a matching purchase. - If you cancel goal events, a period stops counting only when every event in it has been cancelled. -- If you use [CUPED](../variance-reduction-cuped), the pre-exposure covariate is the same count of active periods, measured over the lookback window before exposure. +- If you use [CUPED](../variance-reduction-cuped.mdx), the pre-exposure covariate is the same count of active periods, measured over the lookback window before exposure. - Changing the activity interval changes what the metric means and requires a new metric version. diff --git a/docs/web-console-docs/goals-and-metrics/metrics/metric-types/goal-count.mdx b/docs/web-console-docs/goals-and-metrics/metrics/metric-types/goal-count.mdx index 727a4c52..803ac7dc 100644 --- a/docs/web-console-docs/goals-and-metrics/metrics/metric-types/goal-count.mdx +++ b/docs/web-console-docs/goals-and-metrics/metrics/metric-types/goal-count.mdx @@ -28,23 +28,23 @@ Three users in the same variant are exposed to the experiment: In the experiment results, this variant would show a **Value** of 11 (2 + 9 + 0 purchases in total) and a **Mean** of 11 / 3 = **3.6667** purchases per participant. -Compare that with a [`Goal Unique Count`](./goal-unique-count) on the same goal, which only asks whether each user purchased: Ana 1, Ben 1 and Cara 0, so a **Value** of 2 and a **Mean** of **66.67%**. The unique count says two out of three users bought something. The goal count says how much buying happened, and most of it came from Ben. +Compare that with a [`Goal Unique Count`](./goal-unique-count.mdx) on the same goal, which only asks whether each user purchased: Ana 1, Ben 1 and Cara 0, so a **Value** of 2 and a **Mean** of **66.67%**. The unique count says two out of three users bought something. The goal count says how much buying happened, and most of it came from Ben. ## Creating the metric -When [creating a metric](../create), choose `Goal Count` as the **Metric type**, then: +When [creating a metric](../create.mdx), choose `Goal Count` as the **Metric type**, then: 1. Select the **Goal** you want to count, for example `purchase`. 2. Optionally set an **Outliers limit method** to cap heavy users (see below). 3. Optionally add **Metric property filters** to count only matching events, for example purchases where `category_id` is `ZYZ123`. 4. Optionally use **Add time filters** to count only events within a time range relative to exposure. -5. Optionally use **Add cancellation** under **Goal relations** so that cancelled events stop counting. The goal and the cancellation event need a shared key property, such as an order number. See [Cancellation](../create#cancellation). +5. Optionally use **Add cancellation** under **Goal relations** so that cancelled events stop counting. The goal and the cancellation event need a shared key property, such as an order number. See [Cancellation](../create.mdx#cancellation). The goal is the only required field. `Add refund` and `Add replacement` are not available for this metric type. ## Capping heavy users -A few very active users can dominate a count and make the results noisy. [Outlier limits](../create#outliers) cap each user's total count, not individual events. +A few very active users can dominate a count and make the results noisy. [Outlier limits](../create.mdx#outliers) cap each user's total count, not individual events. In the example above, with the `Fixed` method, a **Lower limit value** of 0 and an **Upper limit value** of 5: @@ -60,7 +60,7 @@ Users with no events are never raised to the lower limit. They stay at 0. ## Reading the results -In the [metric results table](../../../experiments/interpreting-metrics-in-experiment-results), **Value** is the total number of events across all participants in the variant, and **Mean** is that total divided by the number of participants. The impact is calculated on the Mean, as a continuous metric. If the metric uses CUPED, both Value and Mean are CUPED-adjusted. Value is still shown rounded to a whole number. +In the [metric results table](../../../experiments/interpreting-metrics-in-experiment-results.mdx), **Value** is the total number of events across all participants in the variant, and **Mean** is that total divided by the number of participants. The impact is calculated on the Mean, as a continuous metric. If the metric uses CUPED, both Value and Mean are CUPED-adjusted. Value is still shown rounded to a whole number. A change in the Mean can come from more users doing the action, or from the same users doing it more often. To tell those apart, look at a `Goal Unique Count` on the same goal next to it. @@ -69,7 +69,7 @@ A change in the Mean can come from more users doing the action, or from the same - `Total purchases`: goal `purchase`. How many orders users placed. - `Purchases in category ZYZ123`: goal `purchase` with a property filter on `category_id`. How many orders in one category. - `Searches`: goal `search`. How often users searched. -- `Purchases per visit`: a [Ratio](./ratio) metric with a `Goal Count` of `purchase` as the numerator and a `Goal Count` of `session_start` as the denominator. +- `Purchases per visit`: a [Ratio](./ratio.mdx) metric with a `Goal Count` of `purchase` as the numerator and a `Goal Count` of `session_start` as the denominator. ## Good to know diff --git a/docs/web-console-docs/goals-and-metrics/metrics/metric-types/goal-unique-count.mdx b/docs/web-console-docs/goals-and-metrics/metrics/metric-types/goal-unique-count.mdx index 27abc66a..6ee64c92 100644 --- a/docs/web-console-docs/goals-and-metrics/metrics/metric-types/goal-unique-count.mdx +++ b/docs/web-console-docs/goals-and-metrics/metrics/metric-types/goal-unique-count.mdx @@ -29,11 +29,11 @@ Four users are exposed to the experiment: In the experiment results, this group would show a **Value** of 2 (two users purchased) and a **Mean** of 2 / 4 = **50.00%**, the conversion rate. -Compare that with a [`Goal Count`](./goal-count) on the same goal, which counts every event: Ana 3, Ben 1, Cara 0 and Dan 0, so a **Value** of 4 and a **Mean** of 1.0000 purchases per participant. The goal count tells you how much people bought. The unique count tells you how many people bought at all. +Compare that with a [`Goal Count`](./goal-count.mdx) on the same goal, which counts every event: Ana 3, Ben 1, Cara 0 and Dan 0, so a **Value** of 4 and a **Mean** of 1.0000 purchases per participant. The goal count tells you how much people bought. The unique count tells you how many people bought at all. ## Creating the metric -When [creating a metric](../create), choose `Goal Unique Count` as the **Metric type**, then: +When [creating a metric](../create.mdx), choose `Goal Unique Count` as the **Metric type**, then: 1. Select the **Goal** you want to measure, for example `purchase`. 2. Optionally add **Metric property filters**, for example on `category_id`. A user then converts only if at least one of their events matches. @@ -42,7 +42,7 @@ The **Outliers limit method** can't be changed for this metric type, since each ## Reading the results -In the [metric results table](../../../experiments/interpreting-metrics-in-experiment-results), **Value** is the number of participants in the variant who triggered the goal at least once, and **Mean** is that number divided by the number of participants: the conversion rate. When CUPED is applied in an analysis, both columns show CUPED-adjusted values, so **Value** is no longer an exact count of converters. +In the [metric results table](../../../experiments/interpreting-metrics-in-experiment-results.mdx), **Value** is the number of participants in the variant who triggered the goal at least once, and **Mean** is that number divided by the number of participants: the conversion rate. When CUPED is applied in an analysis, both columns show CUPED-adjusted values, so **Value** is no longer an exact count of converters. By default the Mean is shown as a percentage with two decimals, for example `50.00%`. You can change this with the **Format**, **Scale** and **Precision** fields under **Mean**. @@ -51,11 +51,11 @@ By default the Mean is shown as a percentage with two decimals, for example `50. - `Purchasers`: goal `purchase`. The share of users who bought something. - `Sign-up conversion`: goal `sign_up`. The share of users who created an account. - `Purchasers in category ZYZ123`: goal `purchase`, with a property filter on `category_id`. The share of users who bought from that category. -- `Purchases per purchaser`: a [Ratio](./ratio) metric with `Goal Count` of `purchase` as the **Numerator type** and `Goal Unique Count` of `purchase` as the **Denominator type**. +- `Purchases per purchaser`: a [Ratio](./ratio.mdx) metric with `Goal Count` of `purchase` as the **Numerator type** and `Goal Unique Count` of `purchase` as the **Denominator type**. ## Good to know - A few very active users can't skew the result, because each user counts at most once. That's also why outlier limits don't apply. -- It doesn't show how often users do something. Use a [`Goal Count`](./goal-count) for volume, or a [`Goal Activity Period Count`](./activity-per-period) for how regularly they come back. +- It doesn't show how often users do something. Use a [`Goal Count`](./goal-count.mdx) for volume, or a [`Goal Activity Period Count`](./activity-per-period.mdx) for how regularly they come back. - If you add a cancellation under **Goal relations**, a user stops counting as converted only when every event that counted for them has been cancelled. Cancelling one of Ana's three purchases leaves her at 1. -- If you use [CUPED](../variance-reduction-cuped), the pre-exposure covariate is whether the user triggered the same goal before they were exposed. When CUPED is applied in an analysis, the adjusted values are no longer just 0 or 1, so the metric is analysed as a continuous metric instead of a binomial one. +- If you use [CUPED](../variance-reduction-cuped.mdx), the pre-exposure covariate is whether the user triggered the same goal before they were exposed. When CUPED is applied in an analysis, the adjusted values are no longer just 0 or 1, so the metric is analysed as a continuous metric instead of a binomial one. diff --git a/docs/web-console-docs/goals-and-metrics/metrics/metric-types/property.mdx b/docs/web-console-docs/goals-and-metrics/metrics/metric-types/property.mdx index b7ff2ba5..1b3bbe32 100644 --- a/docs/web-console-docs/goals-and-metrics/metrics/metric-types/property.mdx +++ b/docs/web-console-docs/goals-and-metrics/metrics/metric-types/property.mdx @@ -10,7 +10,7 @@ A `Goal Property` metric answers the question: **how much of this did each user You pick a goal and one of its numeric properties, such as `price`, `quantity` or `duration`. For each user, ABsmartly adds up that property across all of their goal events. Two orders of 40 and 25 give that user a value of 65. -This is the metric type behind revenue, items sold, time watched and any other amount carried in the event. It's also the only type that supports [refunds and replacements](#refunds-and-replacements), including when it's used as the numerator or denominator of a [Ratio](./ratio). That lets you measure net revenue rather than gross. +This is the metric type behind revenue, items sold, time watched and any other amount carried in the event. It's also the only type that supports [refunds and replacements](#refunds-and-replacements), including when it's used as the numerator or denominator of a [Ratio](./ratio.mdx). That lets you measure net revenue rather than gross. ## How it's calculated @@ -33,13 +33,13 @@ Three users are exposed to the experiment: In the experiment results, this group would show a **Value** of 180 (65 + 115 + 0) and a **Mean** of 180 / 3 = **60** per participant. -Compare that with a [`Goal Count`](./goal-count) on the same goal, which counts orders instead of adding up their price: Ana 2, Ben 1 and Cara 0, so a **Value** of 3 and a **Mean** of 1. Ana places more orders, but Ben spends more. A change that gets people to buy more often and a change that gets them to spend more per order can look very different on these two metrics. +Compare that with a [`Goal Count`](./goal-count.mdx) on the same goal, which counts orders instead of adding up their price: Ana 2, Ben 1 and Cara 0, so a **Value** of 3 and a **Mean** of 1. Ana places more orders, but Ben spends more. A change that gets people to buy more often and a change that gets them to spend more per order can look very different on these two metrics. If the property is missing on an event, or isn't a number, that event adds 0. Numbers sent as strings, such as `"12.50"`, are converted and counted. ## Creating the metric -When [creating a metric](../create), choose `Goal Property` as the metric type, then: +When [creating a metric](../create.mdx), choose `Goal Property` as the metric type, then: 1. Select the goal you want to measure, for example `purchase`. 2. In **Property**, enter the name of the numeric property, for example `price`. The field suggests properties as you type. For a nested property, separate the levels with `/`, for example `cart/total`. @@ -48,7 +48,7 @@ When [creating a metric](../create), choose `Goal Property` as the metric type, The property is required and can be up to 256 characters long. -To show amounts as money, set the **Format** fields in the [Format, Scale & Precision](../create#format-scale-and-precisions) section, for example `€{}` or `${}`. The Value and the Mean each have their own Format. +To show amounts as money, set the **Format** fields in the [Format, Scale & Precision](../create.mdx#format-scale-and-precisions) section, for example `€{}` or `${}`. The Value and the Mean each have their own Format. ## Refunds and replacements @@ -101,9 +101,9 @@ You can combine a refund or replacement with a cancellation. If an order is canc ## Reading the results -In the [metric results table](../../../experiments/interpreting-metrics-in-experiment-results), **Value** is the total of the property across all participants in the variant, after any refunds, replacements and cancellations. **Mean** is that total divided by the number of participants. The impact is calculated on the Mean. If CUPED is applied to the metric, the Value and Mean shown are CUPED-adjusted. +In the [metric results table](../../../experiments/interpreting-metrics-in-experiment-results.mdx), **Value** is the total of the property across all participants in the variant, after any refunds, replacements and cancellations. **Mean** is that total divided by the number of participants. The impact is calculated on the Mean. If CUPED is applied to the metric, the Value and Mean shown are CUPED-adjusted. -Because every participant counts in the Mean, including those who never bought anything, a revenue metric's Mean is revenue per participant, not revenue per order. To measure average order value, use a [Ratio](./ratio) metric instead. +Because every participant counts in the Mean, including those who never bought anything, a revenue metric's Mean is revenue per participant, not revenue per order. To measure average order value, use a [Ratio](./ratio.mdx) metric instead. ## More examples @@ -112,7 +112,7 @@ Because every participant counts in the Mean, including those who never bought a - `Items sold`: goal `purchase`, property `quantity`. - `Shipping revenue`: goal `purchase`, property `cart/shipping`. - `Time watched`: goal `video_progress`, property `seconds_watched`. -- `Average order value`: a [Ratio](./ratio) metric with a `Goal Property` of `price` as the numerator and a `Goal Count` of `purchase` as the denominator. +- `Average order value`: a [Ratio](./ratio.mdx) metric with a `Goal Property` of `price` as the numerator and a `Goal Count` of `purchase` as the denominator. ## Good to know diff --git a/docs/web-console-docs/goals-and-metrics/metrics/metric-types/ratio.mdx b/docs/web-console-docs/goals-and-metrics/metrics/metric-types/ratio.mdx index f9c59616..df0f30d1 100644 --- a/docs/web-console-docs/goals-and-metrics/metrics/metric-types/ratio.mdx +++ b/docs/web-console-docs/goals-and-metrics/metrics/metric-types/ratio.mdx @@ -34,11 +34,11 @@ The totals are 4 clicks and 10 page views, so the ratio is 4 / 10 = **0.4** clic This is a ratio of totals, not an average of each user's own ratio. Averaging Ana (0.5), Ben (1) and Cara (0) would give 0.5, and Dan would have no ratio at all. With a ratio of totals, users with more page views carry more weight, and every participant can be included. -Compare that with a [`Goal Count`](./goal-count) of `click` on the same data: a **Value** of 4 clicks and a **Mean** of 4 / 4 = 1 click per participant. The `Goal Count` tells you how much users clicked. The ratio tells you how often a page view led to a click. +Compare that with a [`Goal Count`](./goal-count.mdx) of `click` on the same data: a **Value** of 4 clicks and a **Mean** of 4 / 4 = 1 click per participant. The `Goal Count` tells you how much users clicked. The ratio tells you how often a page view led to a click. ## Creating the metric -When [creating a metric](../create), choose `Ratio` as the metric type, then: +When [creating a metric](../create.mdx), choose `Ratio` as the metric type, then: 1. In **Numerator Configuration**, pick a **Numerator type** and set it up as you would that metric type: the **Goal**, plus the **Property**, **Activity interval** or **Retention period** if the type needs one, **Metric property filters** and, where the type allows it, **Outliers limit method**. 2. In **Denominator Configuration**, do the same with a **Denominator type**. The denominator goal must share a datasource with the numerator goal. @@ -59,7 +59,7 @@ With `Require denominator` set, a participant's numerator only counts if their d ## Reading the results -In the [metric results table](../../../experiments/interpreting-metrics-in-experiment-results), **Value** and **Mean** both show the ratio for the variant, and the **Metric total** row shows the total numerator divided by the total denominator across all variants. Unless the **GST** switch is on, you can hover over a variant's Value to see its numerator and denominator totals, and over its Mean to see their averages per participant. +In the [metric results table](../../../experiments/interpreting-metrics-in-experiment-results.mdx), **Value** and **Mean** both show the ratio for the variant, and the **Metric total** row shows the total numerator divided by the total denominator across all variants. Unless the **GST** switch is on, you can hover over a variant's Value to see its numerator and denominator totals, and over its Mean to see their averages per participant. The **Relative impact** compares the ratio between variants, as a continuous metric. The **Impact per day** column shows `--` for ratio metrics. @@ -72,11 +72,11 @@ A ratio can move because either side moved. If the ratio changes, check the Valu - `Click-through rate`: `Goal Count` of `click` divided by `Goal Count` of `page_view`. - `Average order value`: `Goal Property` of `purchase` (`revenue`) divided by `Goal Count` of `purchase`. - `Items per order`: `Goal Property` of `purchase` (`items`) divided by `Goal Count` of `purchase`. -- `Purchases per active day`: `Goal Count` of `purchase` divided by [`Goal Activity Period Count`](./activity-per-period) of `app_open` (1 day). +- `Purchases per active day`: `Goal Count` of `purchase` divided by [`Goal Activity Period Count`](./activity-per-period.mdx) of `app_open` (1 day). - `Payments per checkout`: `Goal Unique Count` of `payment` divided by `Goal Unique Count` of `checkout`, with `Require denominator`. ## Good to know - **Metric property filters**, **Outliers limit method**, **Time filter** and **Goal relations** are set separately for the numerator and the denominator, and each side uses its own settings. -- If you use [CUPED](../variance-reduction-cuped), the numerator and denominator are each adjusted using their own pre-exposure value over the same lookback period. The Numerator and Denominator shown in the tooltips are the adjusted values. +- If you use [CUPED](../variance-reduction-cuped.mdx), the numerator and denominator are each adjusted using their own pre-exposure value over the same lookback period. The Numerator and Denominator shown in the tooltips are the adjusted values. - If the denominator total for a variant is 0, the ratio shows 0. diff --git a/docs/web-console-docs/goals-and-metrics/metrics/metric-types/retention.mdx b/docs/web-console-docs/goals-and-metrics/metrics/metric-types/retention.mdx index 57c24987..514adfd8 100644 --- a/docs/web-console-docs/goals-and-metrics/metrics/metric-types/retention.mdx +++ b/docs/web-console-docs/goals-and-metrics/metrics/metric-types/retention.mdx @@ -32,11 +32,11 @@ With **First exposure**, this group would show a **Value** of 2 (Ana and Cara) a With **First achievement**, the **Value** is 1 (Ana only) and the **Mean** is 1 / 3, about **33%**. Here the question becomes "did they buy again at least 7 days after their first purchase?". -Compare that with a [`Goal Unique Count`](./goal-unique-count) on the same goal, which counts anyone who purchased at all: a **Value** of 3 and a **Mean** of **100%**. Retention leaves out Ben, who bought twice but only in the first week. +Compare that with a [`Goal Unique Count`](./goal-unique-count.mdx) on the same goal, which counts anyone who purchased at all: a **Value** of 3 and a **Mean** of **100%**. Retention leaves out Ben, who bought twice but only in the first week. ## Creating the metric -When [creating a metric](../create), choose `Goal Retention` as the metric type, then: +When [creating a metric](../create.mdx), choose `Goal Retention` as the metric type, then: 1. Select the goal you want to measure, for example `purchase`. 2. Set the **Retention period**: a number from 1 to 30 and a unit (`Seconds`, `Minutes`, `Hours`, `Days`, `Weeks` or `Months`). A month is 30 days. The default is 1 day. @@ -54,7 +54,7 @@ If you add property filters, only matching events count, both for the first achi ## Reading the results -In the [metric results table](../../../experiments/interpreting-metrics-in-experiment-results), **Value** is the number of retained participants in the variant, and **Mean** is that number divided by the number of participants, shown as a percentage. It's analysed as a binomial metric, like `Goal Unique Count`. If the metric uses CUPED, Value and Mean are CUPED-adjusted, so Value is no longer a whole number of users. +In the [metric results table](../../../experiments/interpreting-metrics-in-experiment-results.mdx), **Value** is the number of retained participants in the variant, and **Mean** is that number divided by the number of participants, shown as a percentage. It's analysed as a binomial metric, like `Goal Unique Count`. If the metric uses CUPED, Value and Mean are CUPED-adjusted, so Value is no longer a whole number of users. Users exposed less than one retention period ago haven't had the chance to be retained yet, but they still count as participants with a value of 0. So the Mean starts low and tends to rise as the experiment runs, and it reads lower than the true retention rate while recent users are still in their retention period. Random assignment gives both variants a similar mix of exposure times, so the comparison stays fair, but read the raw percentage with that in mind. The longer the retention period, the stronger the effect. @@ -63,9 +63,9 @@ Users exposed less than one retention period ago haven't had the chance to be re - `Purchase retention (7 days)`: goal `purchase`, `7 Days` after `First exposure`. The share of users who bought something a week or more after seeing the experiment. - `Repeat purchase (30 days)`: goal `purchase`, `30 Days` after `First achievement`. The share of users who bought again at least 30 days after their first purchase. - `App return (1 day)`: goal `app_open`, `1` `Days` after `First exposure`. The share of users who opened the app at any point from 24 hours after exposure, whether that's day 2 or day 30. -- `Returned in week 2`: goal `app_open`, `7 Days` after `First exposure`, with a [time filter](../create#time-filters) of `At most` 14 days. Adding the time filter caps the window, so only returns between day 7 and day 14 count. +- `Returned in week 2`: goal `app_open`, `7 Days` after `First exposure`, with a [time filter](../create.mdx#time-filters) of `At most` 14 days. Adding the time filter caps the window, so only returns between day 7 and day 14 count. ## Good to know -- With `First exposure`, you can count only returns within a window by adding an `At most` [time filter](../create#time-filters), as in `Returned in week 2` above. -- If you use [CUPED](../variance-reduction-cuped), the lookback window must be longer than the retention period, not equal to it. A 7-day retention period needs a lookback of at least 2 weeks, and since the longest lookback is 4 weeks, retention periods of 4 weeks or more can't use CUPED. +- With `First exposure`, you can count only returns within a window by adding an `At most` [time filter](../create.mdx#time-filters), as in `Returned in week 2` above. +- If you use [CUPED](../variance-reduction-cuped.mdx), the lookback window must be longer than the retention period, not equal to it. A 7-day retention period needs a lookback of at least 2 weeks, and since the longest lookback is 4 weeks, retention periods of 4 weeks or more can't use CUPED. diff --git a/docs/web-console-docs/goals-and-metrics/metrics/metric-types/time-to-achievement.mdx b/docs/web-console-docs/goals-and-metrics/metrics/metric-types/time-to-achievement.mdx index fa93e98e..482f7c5e 100644 --- a/docs/web-console-docs/goals-and-metrics/metrics/metric-types/time-to-achievement.mdx +++ b/docs/web-console-docs/goals-and-metrics/metrics/metric-types/time-to-achievement.mdx @@ -32,11 +32,11 @@ In the experiment results, this group would show a **Value** of `3 days, 2 hrs` Ana's second purchase on Wednesday adds nothing, and Cara pulls the Mean down even though she never bought anything. -Compare that with a [`Goal Unique Count`](./goal-unique-count) on the same goal, which counts whether each user purchased at all: Ana 1, Ben 1 and Cara 0, so a **Value** of 2 and a **Mean** of 66.67%. The unique count tells you how many users got there. The time to achievement adds how long they took, mixed with how many got there. +Compare that with a [`Goal Unique Count`](./goal-unique-count.mdx) on the same goal, which counts whether each user purchased at all: Ana 1, Ben 1 and Cara 0, so a **Value** of 2 and a **Mean** of 66.67%. The unique count tells you how many users got there. The time to achievement adds how long they took, mixed with how many got there. ## Creating the metric -When [creating a metric](../create), choose `Goal Time To Achievement` as the metric type, then: +When [creating a metric](../create.mdx), choose `Goal Time To Achievement` as the metric type, then: 1. Choose the **Impact**. It defaults to `Positive`. See [Choosing the impact](#choosing-the-impact) below. 2. Select the **Goal** you want to measure, for example `purchase`. @@ -48,7 +48,7 @@ Values and means are shown as durations, such as `1 day, 40 mins`, using the two ## Reading the results -In the [metric results table](../../../experiments/interpreting-metrics-in-experiment-results), **Value** is the total time to first achievement across all participants in the variant, and **Mean** is that total divided by the number of participants, including those who never reached the goal. The impact is calculated on the Mean, as with other continuous metrics. If the metric uses CUPED, both Value and Mean are CUPED-adjusted. +In the [metric results table](../../../experiments/interpreting-metrics-in-experiment-results.mdx), **Value** is the total time to first achievement across all participants in the variant, and **Mean** is that total divided by the number of participants, including those who never reached the goal. The impact is calculated on the Mean, as with other continuous metrics. If the metric uses CUPED, both Value and Mean are CUPED-adjusted. Because users who never reach the goal count as 0, the Mean goes **up** when more users reach the goal, even if nobody got there any faster. In the example above, if Cara had also bought on Friday at 09:00 (4 days after exposure), the Value would rise to `1 wk, 2 hrs` and the Mean to `2 days, 8 hrs`. The variant converted more users, but its Mean looks slower. @@ -61,7 +61,7 @@ Always read it next to a `Goal Unique Count` on the same goal. If the unique cou ### Average time for users who reached the goal -To measure the average wait only for users who reached the goal, create a [Ratio](./ratio) metric with: +To measure the average wait only for users who reached the goal, create a [Ratio](./ratio.mdx) metric with: - a `Goal Time To Achievement` numerator on your goal, and - a `Goal Unique Count` denominator on the same goal, with the same property filters, time filters and cancellation. @@ -81,7 +81,7 @@ Ratio metrics don't format their values as durations, so the result is a number - `Time to first purchase`: goal `purchase`. How long users take to buy after entering the experiment. - `Time to first search`: goal `search`. How quickly users find and use search. - `Time to activation`: goal `onboarding_completed`. How long users take to finish onboarding. -- `Average time to first purchase for buyers`: a [Ratio](./ratio) with a `Goal Time To Achievement` numerator and a `Goal Unique Count` denominator, both on `purchase`. +- `Average time to first purchase for buyers`: a [Ratio](./ratio.mdx) with a `Goal Time To Achievement` numerator and a `Goal Unique Count` denominator, both on `purchase`. ## Good to know @@ -89,4 +89,4 @@ Ratio metrics don't format their values as durations, so the result is a number - Property filters and time filters decide which events can count as the first one, but the time is still measured from exposure. With a time filter of `Goal is achieved At least 4 days after first exposure`, a user who buys on day 3 and on day 6 has a value of 6 days. - If you add a cancellation (**Add cancellation** under **Goal relations**), a cancelled event no longer counts. The value becomes the time to the earliest event that hasn't been cancelled, so it can increase. If all of a user's events are cancelled, they go back to 0. Refunds and replacements aren't available for this metric type. - The values can have a very long tail, with a few users who took weeks. To limit their influence, set the **Outliers limit method**, for example to `Fixed` with a **Lower limit value** of `0` and an **Upper limit value** of `604800` (7 days, in seconds). Outlier limits only apply to users who reached the goal, so users who never did stay at 0. -- If you use [CUPED](../variance-reduction-cuped), the pre-exposure covariate is the time from the start of the lookback window (the experiment start minus the lookback period) to the user's first goal event before exposure, or 0 if there was none. +- If you use [CUPED](../variance-reduction-cuped.mdx), the pre-exposure covariate is the time from the start of the lookback window (the experiment start minus the lookback period) to the user's first goal event before exposure, or 0 if there was none. diff --git a/docs/web-console-docs/goals-and-metrics/metrics/metric-types/unique-property-count.mdx b/docs/web-console-docs/goals-and-metrics/metrics/metric-types/unique-property-count.mdx index 360ae2f9..0704f8d7 100644 --- a/docs/web-console-docs/goals-and-metrics/metrics/metric-types/unique-property-count.mdx +++ b/docs/web-console-docs/goals-and-metrics/metrics/metric-types/unique-property-count.mdx @@ -32,11 +32,11 @@ In the experiment results, this group would show a **Value** of 4 (3 + 1 + 0) an Values are distinct per user, not across the whole experiment. Ana and Ben both viewed P1, so it counts once for each of them. The group viewed only three different products, but the Value is 4. -Compare that with a [`Goal Count`](./goal-count) on the same goal, which counts every event: Ana 4, Ben 5 and Cara 0, so a **Value** of 9 and a **Mean** of 3.0000. Ben's repeat views make him look like the more active user, while the unique count shows that Ana looked at more products. +Compare that with a [`Goal Count`](./goal-count.mdx) on the same goal, which counts every event: Ana 4, Ben 5 and Cara 0, so a **Value** of 9 and a **Mean** of 3.0000. Ben's repeat views make him look like the more active user, while the unique count shows that Ana looked at more products. ## Creating the metric -When [creating a metric](../create), choose `Goal Property Unique Count` as the metric type, then: +When [creating a metric](../create.mdx), choose `Goal Property Unique Count` as the metric type, then: 1. Select the **Goal** you want to measure, for example `product_view`. 2. In **Property**, type the event property whose distinct values you want to count, for example `product_id`. This field is required. @@ -52,7 +52,7 @@ Under **Goal relations**, you can **Add cancellation**. Unlike `Goal Property`, ## Reading the results -In the [metric results table](../../../experiments/interpreting-metrics-in-experiment-results), **Value** is the sum of every participant's distinct count in the variant, and **Mean** is that total divided by the number of participants. The impact is calculated on the Mean, as with other continuous metrics such as `Goal Count`. +In the [metric results table](../../../experiments/interpreting-metrics-in-experiment-results.mdx), **Value** is the sum of every participant's distinct count in the variant, and **Mean** is that total divided by the number of participants. The impact is calculated on the Mean, as with other continuous metrics such as `Goal Count`. Because each user's values are counted separately, Value is not the number of different values seen in the variant. If every user viewed the same single product, the Value would equal the number of users who viewed it. @@ -61,7 +61,7 @@ Because each user's values are counted separately, Value is not the number of di - `Products viewed`: goal `product_view`, property `product_id`. How many different products users looked at. - `Categories purchased from`: goal `purchase`, property `category_id`. How many different categories users bought from. - `Articles read`: goal `article_read`, property `article_id`. How many different articles users opened. -- `Products per purchaser`: a [Ratio](./ratio) metric with a `Goal Property Unique Count` of `purchase` on `product_id` as the numerator and a [`Goal Unique Count`](./goal-unique-count) of `purchase` as the denominator. How many different products buyers bought, on average. +- `Products per purchaser`: a [Ratio](./ratio.mdx) metric with a `Goal Property Unique Count` of `purchase` on `product_id` as the numerator and a [`Goal Unique Count`](./goal-unique-count.mdx) of `purchase` as the denominator. How many different products buyers bought, on average. ## Good to know diff --git a/docs/web-console-docs/goals-and-metrics/metrics/overview.mdx b/docs/web-console-docs/goals-and-metrics/metrics/overview.mdx index 7d0e1fea..48353b17 100644 --- a/docs/web-console-docs/goals-and-metrics/metrics/overview.mdx +++ b/docs/web-console-docs/goals-and-metrics/metrics/overview.mdx @@ -1,18 +1,20 @@ --- +title: "Metrics Overview" +sidebar_label: "Overview" sidebar_position: 1 --- -# Overview +# Metrics Overview ## Experimentation Metrics -Metrics are aggregations or computations derived from [goals](../goals/overview). +Metrics are aggregations or computations derived from [goals](../goals/overview.mdx). They transform raw event data into interpretable measures that quantify the effect of an experiment. Metrics summarize performance over a group of experiment visitors — for example, `conversion rate`, `Average revenue per visitor`, or `click-through rate`. Metrics can represent direct business outcomes, engagement signals, or technical performance indicators, -and are often grouped into [categories](categories) such as `conversion`, `engagement`, `retention`, or `revenue`. +and are often grouped into [categories](categories.mdx) such as `conversion`, `engagement`, `retention`, or `revenue`. ## Understanding Experimentation Metrics @@ -263,7 +265,7 @@ The following permissions exist when managing and working with `metrics`. #### Global access -Permission to create and manage `metrics` can be granted to the relevant users through their [role](../../configuration/settings#roles) at the platform level. +Permission to create and manage `metrics` can be granted to the relevant users through their [role](../../configuration/settings.mdx#roles) at the platform level. :::info It is not recommended to provide access to `metrics` to non platform admin users at the platform level. diff --git a/docs/web-console-docs/launchpad-browser-extension/getting-started.mdx b/docs/web-console-docs/launchpad-browser-extension/getting-started.mdx index 6fb69baa..36af6410 100644 --- a/docs/web-console-docs/launchpad-browser-extension/getting-started.mdx +++ b/docs/web-console-docs/launchpad-browser-extension/getting-started.mdx @@ -36,7 +36,7 @@ First you need to download and install the LaunchPad as a Chrome extension. This 4. Select **JWT from Browser Cookie** to use the ABsmartly cookie. 5. Click **Authenticate in ABsmartly** to connect to your ABsmartly's instance. 6. You are now ready to use the ABsmartly's LaunchPad to create new experiments. -7. Check our [how-to guide](creating-an-experiment-with-the-launchpad) to create your first experiment. +7. Check our [how-to guide](creating-an-experiment-with-the-launchpad.mdx) to create your first experiment. ### How It Works diff --git a/docs/web-console-docs/overview.mdx b/docs/web-console-docs/overview.mdx index 1889e747..91a09539 100644 --- a/docs/web-console-docs/overview.mdx +++ b/docs/web-console-docs/overview.mdx @@ -1,8 +1,10 @@ --- +title: "Product Documentation Overview" +sidebar_label: "Overview" sidebar_position: 0 --- -# Overview +# Product Documentation Overview The Product Documentation section explains how to use the ABsmartly Web Console. If you run experiments, manage feature flags or work with goals and metrics, this is where you will find everything you need. diff --git a/docs/web-console-docs/users-teams-permissions/ownership-and-permissions.mdx b/docs/web-console-docs/users-teams-permissions/ownership-and-permissions.mdx index 455e1934..2053c6eb 100644 --- a/docs/web-console-docs/users-teams-permissions/ownership-and-permissions.mdx +++ b/docs/web-console-docs/users-teams-permissions/ownership-and-permissions.mdx @@ -11,7 +11,7 @@ In this document we will discuss those changes and how you can start making use Experiment Assets in scope: **Experiments**, **Features**, **Templates**, **Metrics** & **Goals**. -All other configuration settings are managed using global roles. For more details see our [Roles](./roles) page. +All other configuration settings are managed using global roles. For more details see our [Roles](./roles.mdx) page. --- diff --git a/docs/web-console-docs/users-teams-permissions/roles.mdx b/docs/web-console-docs/users-teams-permissions/roles.mdx index 9d162dbc..ffec34f4 100644 --- a/docs/web-console-docs/users-teams-permissions/roles.mdx +++ b/docs/web-console-docs/users-teams-permissions/roles.mdx @@ -57,8 +57,8 @@ This role should only be granted to the person(s) managing the platform. While the 2 roles mentioned above cover most usecases, your organisation might have specific needs. In this case custom roles can be created and assigned to certain users as needed. -For example, custom roles could be created for allowing some users to create and manage [Units](../configuration/units), -[Applications](../configuration/applications), API Keys, etc which otherwise can only be managed by the `FullAdmin`. +For example, custom roles could be created for allowing some users to create and manage [Units](../configuration/units.mdx), +[Applications](../configuration/applications.mdx), API Keys, etc which otherwise can only be managed by the `FullAdmin`. ### Assigning Global Roles @@ -119,6 +119,6 @@ Global `FullAdmin` or users with `Team Admin` on that team, can invite users to ## Ownership and Permissions model for Experiment Assets -Read our [The Ownership Model](./ownership-and-permissions) for a more detailed explanation on how to manage ownership and permissions for Experiment Assets. +Read our [The Ownership Model](./ownership-and-permissions.mdx) for a more detailed explanation on how to manage ownership and permissions for Experiment Assets. diff --git a/docs/web-console-docs/warehouse-native/connect/bigquery.mdx b/docs/web-console-docs/warehouse-native/connect/bigquery.mdx index e7ccda7d..37e5cf49 100644 --- a/docs/web-console-docs/warehouse-native/connect/bigquery.mdx +++ b/docs/web-console-docs/warehouse-native/connect/bigquery.mdx @@ -148,8 +148,8 @@ The staging dataset holds only objects ABsmartly owns: the `json_layouts` table The staging dataset requirements depend on the feature: -- **JSON layouts** (auto-complete for JSON properties in the metric editor) require a staging dataset under **Trust relationship**. They stay turned off until you set a **Staging dataset**. With **Service account key (JSON)**, a staging dataset is optional for JSON layouts: without one, they use the ABsmartly dataset. See [JSON layouts table](../get-started#json-layouts-table). -- **Exposures import** _(Hybrid only)_ requires a staging dataset with either **Service account key (JSON)** or **Trust relationship** authentication. The import creates a temporary external table, so it needs a staging dataset to create it in. ABsmartly won't save a data source with an exposures import, or run **Test exposures import**, until you set a **Staging dataset**. A data source saved earlier without a staging dataset keeps failing Hybrid metric queries until you add one, and its next save requires it. See [Exposures import](../get-started#step-4-configure-exposures-import-hybrid-only). +- **JSON layouts** (auto-complete for JSON properties in the metric editor) require a staging dataset under **Trust relationship**. They stay turned off until you set a **Staging dataset**. With **Service account key (JSON)**, a staging dataset is optional for JSON layouts: without one, they use the ABsmartly dataset. See [JSON layouts table](../get-started.mdx#json-layouts-table). +- **Exposures import** _(Hybrid only)_ requires a staging dataset with either **Service account key (JSON)** or **Trust relationship** authentication. The import creates a temporary external table, so it needs a staging dataset to create it in. ABsmartly won't save a data source with an exposures import, or run **Test exposures import**, until you set a **Staging dataset**. A data source saved earlier without a staging dataset keeps failing Hybrid metric queries until you add one, and its next save requires it. See [Exposures import](../get-started.mdx#step-4-configure-exposures-import-hybrid-only). We recommend a staging dataset for every BigQuery data source, including Warehouse Native deployments without exposures import. It is where ABsmartly creates and maintains the tables it owns, so it keeps them out of your ABsmartly dataset and lets JSON layouts work under either authentication method. @@ -172,7 +172,7 @@ bq update --source ds.json : ### 5. Grant access to the exposures staging bucket _(Hybrid only)_ -Skip this step unless you use [Exposures import](../get-started#step-4-configure-exposures-import-hybrid-only). With a **Trust relationship** data source, BigQuery reads the staged files as ABsmartly's service account, so grant this role even if the **Exposures staging** section uses **Access key (HMAC)**. If **Exposures staging** also uses **Trust relationship**, the same role lets ABsmartly write the files. +Skip this step unless you use [Exposures import](../get-started.mdx#step-4-configure-exposures-import-hybrid-only). With a **Trust relationship** data source, BigQuery reads the staged files as ABsmartly's service account, so grant this role even if the **Exposures staging** section uses **Access key (HMAC)**. If **Exposures staging** also uses **Trust relationship**, the same role lets ABsmartly write the files. Put the bucket in the same location as your staging and source datasets. If those datasets are in the `US` or `EU` multi-region, the bucket can also be in a single region inside it (for example `europe-west1` for `EU`). BigQuery reads the staged files through an external table, which can't read a bucket outside the dataset's location. @@ -225,4 +225,4 @@ If the test fails, double-check your credentials and make sure ABsmartly's IP ad With **Trust relationship**, a failed test shows the missing role and resource (for example "Missing BigQuery Job User on ``") with a **See permissions** link. **Test connection** doesn't exercise inserts, so a missing **Service Usage Consumer** grant on a separate job project shows up later as failed writes, not as a failed test. ::: -Once connected, save the data source and proceed to [map your tables](../get-started#step-2-map-your-tables). +Once connected, save the data source and proceed to [map your tables](../get-started.mdx#step-2-map-your-tables). diff --git a/docs/web-console-docs/warehouse-native/connect/clickhouse.mdx b/docs/web-console-docs/warehouse-native/connect/clickhouse.mdx index fa9c2d1c..a0ca1e6f 100644 --- a/docs/web-console-docs/warehouse-native/connect/clickhouse.mdx +++ b/docs/web-console-docs/warehouse-native/connect/clickhouse.mdx @@ -30,4 +30,4 @@ Click **Test connection** at the bottom of the form. If everything is configured If the test fails, double-check your credentials and make sure ABsmartly's IP addresses are allowed through your ClickHouse firewall or network policies. ::: -Once connected, save the data source and proceed to [map your tables](../get-started#step-2-map-your-tables). +Once connected, save the data source and proceed to [map your tables](../get-started.mdx#step-2-map-your-tables). diff --git a/docs/web-console-docs/warehouse-native/connect/databricks.mdx b/docs/web-console-docs/warehouse-native/connect/databricks.mdx index ba906127..e8e89144 100644 --- a/docs/web-console-docs/warehouse-native/connect/databricks.mdx +++ b/docs/web-console-docs/warehouse-native/connect/databricks.mdx @@ -31,4 +31,4 @@ Click **Test connection** at the bottom of the form. If everything is configured If the test fails, double-check your credentials and make sure ABsmartly's IP addresses are allowed through your Databricks workspace network settings. ::: -Once connected, save the data source and proceed to [map your tables](../get-started#step-2-map-your-tables). +Once connected, save the data source and proceed to [map your tables](../get-started.mdx#step-2-map-your-tables). diff --git a/docs/web-console-docs/warehouse-native/connect/redshift.mdx b/docs/web-console-docs/warehouse-native/connect/redshift.mdx index 0bcf16e6..022c57c1 100644 --- a/docs/web-console-docs/warehouse-native/connect/redshift.mdx +++ b/docs/web-console-docs/warehouse-native/connect/redshift.mdx @@ -31,4 +31,4 @@ Click **Test connection** at the bottom of the form. If everything is configured If the test fails, double-check your credentials and make sure ABsmartly's IP addresses are allowed through your Redshift cluster's security groups and VPC settings. ::: -Once connected, save the data source and proceed to [map your tables](../get-started#step-2-map-your-tables). +Once connected, save the data source and proceed to [map your tables](../get-started.mdx#step-2-map-your-tables). diff --git a/docs/web-console-docs/warehouse-native/connect/snowflake.mdx b/docs/web-console-docs/warehouse-native/connect/snowflake.mdx index 295229c0..eeef9337 100644 --- a/docs/web-console-docs/warehouse-native/connect/snowflake.mdx +++ b/docs/web-console-docs/warehouse-native/connect/snowflake.mdx @@ -31,4 +31,4 @@ Click **Test connection** at the bottom of the form. If everything is configured If the test fails, double-check your credentials and make sure ABsmartly's IP addresses are allowed through your Snowflake network policies. ::: -Once connected, save the data source and proceed to [map your tables](../get-started#step-2-map-your-tables). +Once connected, save the data source and proceed to [map your tables](../get-started.mdx#step-2-map-your-tables). diff --git a/docs/web-console-docs/warehouse-native/get-started.mdx b/docs/web-console-docs/warehouse-native/get-started.mdx index e6596a63..e355dd7e 100644 --- a/docs/web-console-docs/warehouse-native/get-started.mdx +++ b/docs/web-console-docs/warehouse-native/get-started.mdx @@ -11,7 +11,7 @@ import Image from "../../../src/components/Image"; Warehouse Native lets you run experiments directly on data that lives in your own data warehouse. Instead of sending events to ABsmartly's collectors, you point ABsmartly at your existing tables — exposures, goals, and attributes — and it takes care of the rest. :::tip New to Warehouse Native? -This guide covers connecting and configuring a data source. If you're deciding between **Hybrid** and **Fully** Warehouse Native first, read [Warehouse Native Modes](./modes). +This guide covers connecting and configuring a data source. If you're deciding between **Hybrid** and **Fully** Warehouse Native first, read [Warehouse Native Modes](./modes.mdx). ::: Getting started takes three steps: @@ -27,7 +27,7 @@ Getting started takes three steps: To begin, navigate to **Settings → Data Sources** and click **Add data source**. :::note The default data source -Every installation ships with a built-in **default** data source, managed by ABsmartly. In [Hybrid mode](./modes#hybrid-warehouse-native) you keep this default and add external data sources for your goals. In [Fully mode](./modes#fully-warehouse-native) your own warehouse becomes the default. Exposure events always come from the default data source, so which one is the default determines your mode. +Every installation ships with a built-in **default** data source, managed by ABsmartly. In [Hybrid mode](./modes.mdx#hybrid-warehouse-native) you keep this default and add external data sources for your goals. In [Fully mode](./modes.mdx#fully-warehouse-native) your own warehouse becomes the default. Exposure events always come from the default data source, so which one is the default determines your mode. ::: You'll see a form with two sections: general information about the data source, and the connection credentials specific to your warehouse type. @@ -40,11 +40,11 @@ Start by giving your data source a **name** and an optional **description**. The Select your warehouse from the **Database type** dropdown. ABsmartly supports five warehouse types — follow the guide for yours: -- **[BigQuery](./connect/bigquery)** -- **[Snowflake](./connect/snowflake)** -- **[ClickHouse](./connect/clickhouse)** -- **[Redshift](./connect/redshift)** -- **[Databricks](./connect/databricks)** +- **[BigQuery](./connect/bigquery.mdx)** +- **[Snowflake](./connect/snowflake.mdx)** +- **[ClickHouse](./connect/clickhouse.mdx)** +- **[Redshift](./connect/redshift.mdx)** +- **[Databricks](./connect/databricks.mdx)** Each guide walks you through the specific credentials needed and how to test the connection. @@ -59,7 +59,7 @@ With your warehouse connected, the next step is to tell ABsmartly where your exp For each table, you can either use the **Column mapping** tab to select columns from a dropdown, or switch to the **SQL query** tab to write a custom query. :::note Which tables apply to your data source -Exposures always come from the **[default data source](./modes#the-default-data-source)**, so the exposure mapping below matters most on whichever data source is your default. On an **external** (non-default) data source used in [Hybrid mode](./modes#hybrid-warehouse-native), you'll typically map only the **goals** table — exposures are brought in automatically through the [Exposures import](#step-4-configure-exposures-import-hybrid-only) setup rather than mapped here. +Exposures always come from the **[default data source](./modes.mdx#the-default-data-source)**, so the exposure mapping below matters most on whichever data source is your default. On an **external** (non-default) data source used in [Hybrid mode](./modes.mdx#hybrid-warehouse-native), you'll typically map only the **goals** table — exposures are brought in automatically through the [Exposures import](#step-4-configure-exposures-import-hybrid-only) setup rather than mapped here. ::: ### Exposure table @@ -151,7 +151,7 @@ Without this table, experiments will still work — but JSON-property auto-compl ::: :::note -On BigQuery with a **Staging dataset** set, the `json_layouts` table lives in the staging dataset instead. With **Trust relationship** authentication, JSON layouts are turned off until you set one. With **Service account key (JSON)** and no staging dataset, JSON layouts use the ABsmartly dataset. See [Create the staging dataset](./connect/bigquery#4-create-the-staging-dataset). +On BigQuery with a **Staging dataset** set, the `json_layouts` table lives in the staging dataset instead. With **Trust relationship** authentication, JSON layouts are turned off until you set one. With **Service account key (JSON)** and no staging dataset, JSON layouts use the ABsmartly dataset. See [Create the staging dataset](./connect/bigquery.mdx#4-create-the-staging-dataset). ::: --- @@ -181,13 +181,13 @@ ABsmartly will show a preview of the computed schedule in both UTC and your loca Match the frequency to your actual ETL schedule. If your data lands once a day at 8 AM UTC, use **Daily at specific time** with a 480-minute offset. Querying more often than data arrives just adds unnecessary load to your warehouse. ::: -Save the data source. If you're setting up [Fully Warehouse Native](./modes#fully-warehouse-native) and this warehouse is your **default** data source, you're done - ABsmartly will start querying your warehouse on the configured schedule and your experiment data will flow through automatically. The built-in ABsmartly-managed default data source needs no such configuration, since it isn't a warehouse of yours. If you're connecting an **external** data source for [Hybrid mode](./modes#hybrid-warehouse-native), continue to Step 4. +Save the data source. If you're setting up [Fully Warehouse Native](./modes.mdx#fully-warehouse-native) and this warehouse is your **default** data source, you're done - ABsmartly will start querying your warehouse on the configured schedule and your experiment data will flow through automatically. The built-in ABsmartly-managed default data source needs no such configuration, since it isn't a warehouse of yours. If you're connecting an **external** data source for [Hybrid mode](./modes.mdx#hybrid-warehouse-native), continue to Step 4. --- ## Step 4: Configure exposures import _(Hybrid only)_ -This step only applies to **external** (non-default) data sources — the setup used in [Hybrid Warehouse Native](./modes#hybrid-warehouse-native). If your warehouse is the default data source, you can skip it. +This step only applies to **external** (non-default) data sources — the setup used in [Hybrid Warehouse Native](./modes.mdx#hybrid-warehouse-native). If your warehouse is the default data source, you can skip it. In Hybrid mode, a goal can live in an external warehouse, but exposures come from the default data source (managed by ABsmartly). To compute metrics for such a goal, ABsmartly needs to make those exposures available to your external warehouse. It does this through an object store that you provide - you point ABsmartly at a storage location it can use, and your warehouse reads the exposures from there. @@ -198,11 +198,11 @@ The **Exposures staging** section configures that storage location: | **Object store URL** | The bucket/prefix ABsmartly uses to stage exposures for your warehouse. The accepted scheme depends on your warehouse (for example, `gs://` for BigQuery, `s3://` for Redshift, and `s3://`, `gs://`, or `azure://` for Snowflake). | | **Credentials** | The access needed to read and write that location — an access key/secret for ClickHouse, a stage name for Snowflake, an IAM role ARN for Redshift. Databricks needs no extra credentials. For BigQuery, pick the method in the section's own **Authentication** dropdown: **Access key (HMAC)** (the default, an access key/secret) or **Trust relationship**. | -With **Trust relationship** on BigQuery, the access key and secret fields are replaced by ABsmartly's service account email: grant that service account **Storage Object User** (`roles/storage.objectUser`) on the staging bucket. The dropdown is independent of the data source's own **Authentication** setting, but BigQuery always reads the staged files with the data source's credentials. That service account needs access to the bucket too: **Storage Object User** for ABsmartly's service account under Trust relationship (see [Grant access to the exposures staging bucket](./connect/bigquery#5-grant-access-to-the-exposures-staging-bucket-hybrid-only)), or **Storage Object Viewer** (`roles/storage.objectViewer`) for your own service account under Service account key (JSON). +With **Trust relationship** on BigQuery, the access key and secret fields are replaced by ABsmartly's service account email: grant that service account **Storage Object User** (`roles/storage.objectUser`) on the staging bucket. The dropdown is independent of the data source's own **Authentication** setting, but BigQuery always reads the staged files with the data source's credentials. That service account needs access to the bucket too: **Storage Object User** for ABsmartly's service account under Trust relationship (see [Grant access to the exposures staging bucket](./connect/bigquery.mdx#5-grant-access-to-the-exposures-staging-bucket-hybrid-only)), or **Storage Object Viewer** (`roles/storage.objectViewer`) for your own service account under Service account key (JSON). With **Access key (HMAC)**, the `storage.restrictAuthTypes` organization policy on the bucket's project must allow HMAC authentication. -On BigQuery, Hybrid exposures import requires a [staging dataset](./connect/bigquery#4-create-the-staging-dataset) with either **Service account key (JSON)** or **Trust relationship** as the data source's authentication, regardless of the exposures staging **Authentication** choice. The import creates its temporary external table there. ABsmartly won't save a data source with an exposures import, or run **Test exposures import**, until you set a **Staging dataset**. A data source saved earlier without a staging dataset keeps failing Hybrid metric queries until you add one, and its next save requires it. Put the bucket in the same location as the staging and source datasets, or, for a `US` or `EU` multi-region dataset, in a single region inside that multi-region (for example `europe-west1` for `EU`). +On BigQuery, Hybrid exposures import requires a [staging dataset](./connect/bigquery.mdx#4-create-the-staging-dataset) with either **Service account key (JSON)** or **Trust relationship** as the data source's authentication, regardless of the exposures staging **Authentication** choice. The import creates its temporary external table there. ABsmartly won't save a data source with an exposures import, or run **Test exposures import**, until you set a **Staging dataset**. A data source saved earlier without a staging dataset keeps failing Hybrid metric queries until you add one, and its next save requires it. Put the bucket in the same location as the staging and source datasets, or, for a `US` or `EU` multi-region dataset, in a single region inside that multi-region (for example `europe-west1` for `EU`). :::note Staged files are cached and reused for a short window, then cleaned up automatically — no manual cleanup is required. For defense in depth, you can also add a bucket lifecycle rule (e.g. "delete objects older than 1 day") as a backstop. @@ -210,4 +210,4 @@ Staged files are cached and reused for a short window, then cleaned up automatic Save the data source once the exposures import is configured. ABsmartly will then query your warehouse on the configured schedule, evaluating your externally-sourced goals against the exposures automatically. -In [Fully Warehouse Native](./modes#fully-warehouse-native), your warehouse is the default and already holds the exposures, so this step doesn't apply. +In [Fully Warehouse Native](./modes.mdx#fully-warehouse-native), your warehouse is the default and already holds the exposures, so this step doesn't apply. diff --git a/docs/web-console-docs/warehouse-native/modes.mdx b/docs/web-console-docs/warehouse-native/modes.mdx index 0011dd20..fe794d95 100644 --- a/docs/web-console-docs/warehouse-native/modes.mdx +++ b/docs/web-console-docs/warehouse-native/modes.mdx @@ -11,7 +11,7 @@ ABsmartly supports two ways of running Warehouse Native, depending on how much o - **Hybrid Warehouse Native** - ABsmartly handles assignment and exposures, while your **goals and metrics** can be computed against your own warehouse. This is set per goal, so you can mix goals that stay with ABsmartly with goals sourced from your warehouse. - **Fully Warehouse Native** - your warehouse holds **everything** - exposures, goals, and attributes - and nothing user-level ever leaves your infrastructure. -Both modes are built on the same foundation: **[data sources](./get-started)**. The mode you're in is determined by which data source is your **default**. +Both modes are built on the same foundation: **[data sources](./get-started.mdx)**. The mode you're in is determined by which data source is your **default**. ## The default data source @@ -30,7 +30,7 @@ In Hybrid mode, you keep the ABsmartly-managed data source as your default and a - **Assignment and exposures** are handled by ABsmartly. - **Goals and metrics** are assigned a data source per goal. A goal can be sourced from an external warehouse - where your business data already lives, so results line up with what your BI and finance teams report - or it can stay managed by ABsmartly. You can mix both. -- When a goal is sourced from an external warehouse, ABsmartly makes the default source's exposures available to that warehouse so the two can be evaluated together. You enable this by pointing ABsmartly at an object store through the **[Exposures import](./get-started#step-4-configure-exposures-import-hybrid-only)** section on each external data source. +- When a goal is sourced from an external warehouse, ABsmartly makes the default source's exposures available to that warehouse so the two can be evaluated together. You enable this by pointing ABsmartly at an object store through the **[Exposures import](./get-started.mdx#step-4-configure-exposures-import-hybrid-only)** section on each external data source. - Because that import lands the exposures inside your warehouse, **goals sourced from your warehouse can filter and enrich those exposures** the same way Fully mode does - strip out bots and internal traffic, or join in your own attributes table. **Goals that stay managed by ABsmartly don't get this**, since their exposures never leave ABsmartly's default data source. ![Hybrid Warehouse Native architecture: the ABsmartly SDK sends exposures into ABsmartly's default source, which handles unfiltered managed goals directly and also imports exposures into the customer's external warehouse, where imported exposures, goals, and attributes are filtered and enriched before ABsmartly Cloud runs a scheduled query and returns only aggregate results. ABsmartly Cloud retains user-level data for exposures and any goals kept on the managed default source.](/img/warehouse-native/hybrid-architecture.svg) @@ -72,5 +72,5 @@ Exposure-side filtering (bots, scrapers, internal traffic) and attribute enrichm Whichever mode you're targeting, the setup starts the same way — by connecting a data source: -- **[Get Started with Warehouse Native](./get-started)** — connect your warehouse, map your tables, and configure data freshness. -- **[Connect your warehouse](./get-started#step-1-connect-to-your-data-warehouse)** — step-by-step guides for BigQuery, Snowflake, ClickHouse, Redshift, and Databricks. +- **[Get Started with Warehouse Native](./get-started.mdx)** — connect your warehouse, map your tables, and configure data freshness. +- **[Connect your warehouse](./get-started.mdx#step-1-connect-to-your-data-warehouse)** — step-by-step guides for BigQuery, Snowflake, ClickHouse, Redshift, and Databricks. diff --git a/docs/web-console-docs/warehouse-native/overview.mdx b/docs/web-console-docs/warehouse-native/overview.mdx index 72ad11a7..f63585f2 100644 --- a/docs/web-console-docs/warehouse-native/overview.mdx +++ b/docs/web-console-docs/warehouse-native/overview.mdx @@ -31,7 +31,7 @@ Warehouse Native comes in two flavors, depending on how much of your data you wa - **Hybrid Warehouse Native** - ABsmartly manages assignment and exposures, while your **goals and metrics** can be computed against your own warehouse. It's set per goal, so you can mix goals managed by ABsmartly with goals sourced from your warehouse. Goals sourced from your warehouse can also be filtered and enriched with your own attributes. - **Fully Warehouse Native** - **everything** lives in your warehouse: exposures, goals, and attributes. No user-level data ever leaves your infrastructure, and you can filter or enrich exposures for every goal. -Which mode you're in is determined by which data source is your **default**. See **[Warehouse Native Modes](./modes)** for a full comparison and guidance on choosing. +Which mode you're in is determined by which data source is your **default**. See **[Warehouse Native Modes](./modes.mdx)** for a full comparison and guidance on choosing. ### Supported warehouses @@ -56,4 +56,4 @@ Which mode you're in is determined by which data source is your **default**. See ## Next steps -New to Warehouse Native? Start by understanding the [two modes](./modes) — Hybrid and Fully — and which one fits your needs. When you're ready to set it up, head to the [Get Started guide](./get-started) to connect your warehouse, map your tables, and configure data freshness. +New to Warehouse Native? Start by understanding the [two modes](./modes.mdx) — Hybrid and Fully — and which one fits your needs. When you're ready to set it up, head to the [Get Started guide](./get-started.mdx) to connect your warehouse, map your tables, and configure data freshness. diff --git a/docusaurus.config.js b/docusaurus.config.js index 4a9e28d5..e02b18c3 100644 --- a/docusaurus.config.js +++ b/docusaurus.config.js @@ -4,20 +4,60 @@ const { themes } = require("prism-react-renderer"); const lightCodeTheme = themes.github; const darkCodeTheme = themes.dracula; +const path = require("path"); +const { execFileSync } = require("child_process"); +const { getVcsPreset } = require("@docusaurus/utils"); +const { SPECS } = require("./plugins/llms-markdown/api/spec-index"); +const { siteUrl } = require("./plugins/site-url"); + +const SITE_URL = siteUrl(); + +const apiOutputDirs = SPECS.map((s) => path.join(__dirname, s.docsDir)); + +function hasFullGitHistory() { + try { + const out = execFileSync("git", ["rev-parse", "--is-shallow-repository"], { + cwd: __dirname, + stdio: ["ignore", "pipe", "ignore"], + }); + return out.toString().trim() === "false"; + } catch { + return false; + } +} +const gitDates = hasFullGitHistory(); +if (!gitDates) { + console.warn( + "[docs] Git history is shallow or unavailable: 'Last updated' dates and sitemap lastmod are disabled " + + "(they would all show the checkout date). Use a full clone (git fetch --unshallow) to enable them." + ); +} + +const defaultVcs = getVcsPreset("default-v1"); +const isGeneratedApiPage = (filePath) => + /\.(api|info)\.mdx$/.test(filePath) && apiOutputDirs.some((d) => filePath.startsWith(d + path.sep)); +const vcs = { + initialize: (params) => defaultVcs.initialize(params), + getFileCreationInfo: (filePath) => defaultVcs.getFileCreationInfo(filePath), + getFileLastUpdateInfo: (filePath) => + isGeneratedApiPage(filePath) ? Promise.resolve(null) : defaultVcs.getFileLastUpdateInfo(filePath), +}; /** @type {import('@docusaurus/types').Config} */ const config = { title: "The ABsmartly Docs", tagline: "Booking.com experimentation culture without the big investment.", - url: "https://docs.absmartly.com", + url: SITE_URL, baseUrl: "/", + trailingSlash: true, + future: { experimental_vcs: vcs }, onBrokenLinks: "throw", - onBrokenMarkdownLinks: "warn", favicon: "img/favicon.ico", markdown: { mermaid: true, + hooks: { onBrokenMarkdownLinks: "throw" }, }, // Speeding up the build with swc - was 2m34s on M1 Macbook, now 1m29s @@ -68,6 +108,7 @@ const config = { sidebarPath: require.resolve("./sidebars.js"), editUrl: "https://github.com/absmartly/docs/edit/master", docItemComponent: "@theme/ApiItem", + showLastUpdateTime: gitDates, }, theme: { customCss: require.resolve("./src/scss/custom.scss"), @@ -76,6 +117,8 @@ const config = { changefreq: "weekly", priority: 0.5, filename: "sitemap.xml", + ignorePatterns: ["/search/**", "/search", "/blog/**", "/blog"], + lastmod: gitDates ? "date" : null, }, }), ], @@ -84,29 +127,92 @@ const config = { plugins: [ "docusaurus-plugin-sass", [ - // .md per page + /llms.txt; see netlify/edge-functions/markdown-negotiation.js. - "@signalwire/docusaurus-plugin-llms-txt", + require.resolve("./plugins/llms-markdown/llms-txt-wrapper"), { siteDescription: "ABsmartly product documentation: experimentation platform, SDKs and APIs.\n\n" + "Every page is available as Markdown: append `.md` to the page URL " + - "(e.g. https://docs.absmartly.com/docs/glossary.md), or request the normal URL " + - "with `Accept: text/markdown`. /llms-full.txt contains all pages in one file.", + `(e.g. ${SITE_URL}/docs/glossary.md), or request the normal URL ` + + "with `Accept: text/markdown`. /llms-full.txt has the guides and the Collector API " + + "pages in one file; the Web Console API endpoints have their own index at " + + "/docs/APIs-and-SDKs/Web-Console-API/llms.txt.", depth: 2, - // A page that fails to convert would still advertise a .md that 404s. + postProcess: { + startHere: [ + { + title: "SDK getting started", + url: `${SITE_URL}/docs/APIs-and-SDKs/SDK-Documentation/getting-started.md`, + description: "Install an ABsmartly SDK, create a context and run your first experiment.", + }, + { + title: "SDK guide", + url: `${SITE_URL}/docs/APIs-and-SDKs/SDK-Documentation.md`, + description: "How the SDKs assign variants, track exposures and goals, and handle feature flags.", + }, + { + title: "Web Console API endpoint index", + url: `${SITE_URL}/docs/APIs-and-SDKs/Web-Console-API/llms.txt`, + description: "Web Console API resources (experiments, metrics, goals, teams, settings…), each linking to its REST endpoints.", + }, + { + title: "Web Console API OpenAPI spec", + url: `${SITE_URL}/openapi/web-console-api.yaml`, + description: "Full request/response schemas for the Web Console API.", + }, + { + title: "Collector API", + url: `${SITE_URL}/docs/APIs-and-SDKs/SDK-API/absmartly-collector-api.md`, + description: "The API the SDKs use to fetch assignments and publish events, for languages without an SDK.", + }, + { + title: "Collector API OpenAPI spec", + url: `${SITE_URL}/openapi/collector-api.yaml`, + description: "Full request/response schemas for the Collector API.", + }, + { + title: "MCP server", + url: `${SITE_URL}/docs/APIs-and-SDKs/MCP-Server/overview.md`, + description: "Connect AI assistants to ABsmartly through the Model Context Protocol.", + }, + { + title: "CLI", + url: `${SITE_URL}/docs/APIs-and-SDKs/CLI-Documentation.md`, + description: "Manage experiments and feature flags from a terminal or script.", + }, + { + title: "Glossary", + url: `${SITE_URL}/docs/glossary.md`, + description: "Key experimentation and ABsmartly concepts.", + }, + ], + apiIndexHeader: + "# ABsmartly Web Console API\n\n" + + "> REST API for managing experiments, feature flags, metrics, goals, teams and settings in ABsmartly. " + + "Authenticate with `Authorization: Api-Key ` (API key from Settings → API Keys) or a federated OIDC access token. " + + `Full request/response schemas: ${SITE_URL}/openapi/web-console-api.yaml\n\n` + + "Some endpoints return HTTP 200 with `ok: false` on failure; always check `ok`.\n\n" + + `Each resource below links to a list of its endpoints; every endpoint page is Markdown. ` + + "Sub-resources such as experiment custom sections and action dialog fields have their own lists. " + + `The main documentation index is at ${SITE_URL}/llms.txt.\n`, + fullNote: + "This file has the guides and the Collector API pages. Web Console API endpoint pages are not " + + `included: see the endpoint index at ${SITE_URL}/docs/APIs-and-SDKs/Web-Console-API/llms.txt ` + + `and the OpenAPI specs at ${SITE_URL}/openapi/web-console-api.yaml and ` + + `${SITE_URL}/openapi/collector-api.yaml.`, + }, onRouteError: "throw", optionalLinks: [ { title: "Web Console API OpenAPI spec", - url: "https://docs.absmartly.com/openapi/web-console-api.yaml", + url: `${SITE_URL}/openapi/web-console-api.yaml`, description: - "Full request/response schemas for the Web Console API reference pages", + "Full request/response schemas for the Web Console API reference pages.", }, { title: "Collector API OpenAPI spec", - url: "https://docs.absmartly.com/openapi/collector-api.yaml", + url: `${SITE_URL}/openapi/collector-api.yaml`, description: - "Full request/response schemas for the SDK Collector API reference pages", + "Full request/response schemas for the SDK Collector API reference pages.", }, ], content: { @@ -115,11 +221,12 @@ const config = { relativePaths: false, includeBlog: false, includePages: false, - excludeRoutes: ["/search"], - remarkPlugins: [require("./plugins/llms-markdown/remark-fix-md-links")], - beforeDefaultRehypePlugins: [ - require("./plugins/llms-markdown/rehype-docusaurus-cleanup"), + excludeRoutes: ["/search", "/search/", "/search/**"], + remarkPlugins: [ + require("./plugins/llms-markdown/remark-fix-md-links"), + require("./plugins/llms-markdown/remark-tight-lists"), ], + beforeDefaultRehypePlugins: [require("./plugins/llms-markdown/rehype-docusaurus-cleanup")], }, }, ], diff --git a/netlify.toml b/netlify.toml index e7b587cb..1c628580 100644 --- a/netlify.toml +++ b/netlify.toml @@ -13,6 +13,26 @@ Content-Type = "text/plain; charset=utf-8" Access-Control-Allow-Origin = "*" +# The Web Console API endpoint index (linked from /llms.txt). +[[headers]] + for = "/docs/APIs-and-SDKs/Web-Console-API/llms.txt" + [headers.values] + Content-Type = "text/plain; charset=utf-8" + Access-Control-Allow-Origin = "*" + +# The per-resource Web Console API endpoint lists (linked from the endpoint index). +[[headers]] + for = "/docs/APIs-and-SDKs/Web-Console-API/llms/*" + [headers.values] + Content-Type = "text/plain; charset=utf-8" + Access-Control-Allow-Origin = "*" + +# The full dump duplicates every page; keep it out of search results. +[[headers]] + for = "/llms-full.txt" + [headers.values] + X-Robots-Tag = "noindex" + # Page URLs return HTML or Markdown depending on the Accept header. Netlify # rewrites a Vary header set by the edge function on 200 responses, so declare # it here as well so downstream caches keep the two variants apart. diff --git a/netlify/edge-functions-tests/markdown-negotiation.test.js b/netlify/edge-functions-tests/markdown-negotiation.test.js index 4f48758d..7d994b20 100644 --- a/netlify/edge-functions-tests/markdown-negotiation.test.js +++ b/netlify/edge-functions-tests/markdown-negotiation.test.js @@ -3,8 +3,10 @@ import handler, { appendVary, canonicalMarkdownPath, + htmlPathForMarkdown, markdownPathFor, prefersMarkdown, + siteOrigin, } from "../edge-functions/markdown-negotiation.js"; const BUILD = new URL("../../build", import.meta.url).pathname; @@ -45,6 +47,42 @@ const eq = (a, b) => { if (a !== b) throw new Error(`expected ${JSON.stringify(b)}, got ${JSON.stringify(a)}`); }; +Deno.test("siteOrigin: production without the Netlify global or outside previews", () => { + eq(typeof globalThis.Netlify, "undefined"); + eq(siteOrigin(), "https://docs.absmartly.com"); + const env = (vars) => ({ env: { get: (k) => vars[k] } }); + const prime = "https://deploy-preview-9--x.netlify.app/"; + try { + globalThis.Netlify = env({ CONTEXT: "deploy-preview", DEPLOY_PRIME_URL: prime }); + eq(siteOrigin(), "https://deploy-preview-9--x.netlify.app"); + globalThis.Netlify = env({ CONTEXT: "branch-deploy", DEPLOY_PRIME_URL: prime }); + eq(siteOrigin(), "https://deploy-preview-9--x.netlify.app"); + globalThis.Netlify = env({ CONTEXT: "production", DEPLOY_PRIME_URL: prime }); + eq(siteOrigin(), "https://docs.absmartly.com"); + globalThis.Netlify = env({ CONTEXT: "deploy-preview" }); + eq(siteOrigin(), "https://docs.absmartly.com"); + } finally { + delete globalThis.Netlify; + } +}); + +Deno.test("siteOrigin: falls back to the edge context's deploy context and the request origin", () => { + const origin = "https://deploy-preview-9--x.netlify.app"; + eq(siteOrigin({ deploy: { context: "deploy-preview" } }, origin), origin); + eq(siteOrigin({ deploy: { context: "branch-deploy" } }, origin), origin); + eq(siteOrigin({ deploy: { context: "production" } }, origin), "https://docs.absmartly.com"); + eq(siteOrigin({}, origin), "https://docs.absmartly.com"); + eq(siteOrigin(undefined, origin), "https://docs.absmartly.com"); +}); + +Deno.test("canonical Link uses the preview origin on a deploy preview", async () => { + const r = await handler(new Request("https://preview.example/docs/glossary.md"), { + next: () => serve("/docs/glossary.md"), + deploy: { context: "deploy-preview" }, + }); + eq(r.headers.get("link"), `; rel="canonical"`); +}); + Deno.test("Accept parsing", () => { eq(prefersMarkdown("text/html,application/xhtml+xml,*/*;q=0.8"), false); eq(prefersMarkdown("*/*"), false); @@ -65,6 +103,8 @@ Deno.test("path mapping", () => { eq(canonicalMarkdownPath("/docs/foo/.md"), "/docs/foo.md"); eq(canonicalMarkdownPath("/docs/foo.md/"), "/docs/foo.md"); eq(canonicalMarkdownPath("/docs/foo"), null); + eq(htmlPathForMarkdown("/docs/foo.md"), "/docs/foo/"); + eq(htmlPathForMarkdown("/docs/a/b.md"), "/docs/a/b/"); }); Deno.test("appendVary matches whole tokens", () => { @@ -81,12 +121,17 @@ Deno.test("appendVary matches whole tokens", () => { }); const PAGE = "/docs/APIs-and-SDKs/SDK-Documentation/getting-started/"; +const SITE = "https://docs.absmartly.com"; +const canonicalLink = (path) => `<${SITE}${path}>; rel="canonical"`; +// Markdown starts with the agent pointer line, then the page heading. +const MD_START = /^> For AI agents.*\n\n# Getting Started/; Deno.test("negotiation: agent gets Markdown, browser gets HTML", async () => { let r = await call(PAGE, "text/markdown"); eq(r.headers.get("content-type").startsWith("text/markdown"), true); - eq((await r.text()).startsWith("# Getting Started"), true); + eq(MD_START.test(await r.text()), true); eq(r.headers.get("vary"), "Accept"); + eq(r.headers.get("link"), canonicalLink(PAGE)); r = await call(PAGE, "text/html,*/*;q=0.8"); eq((await r.text()).startsWith(""), true); @@ -97,6 +142,13 @@ Deno.test("negotiation: agent gets Markdown, browser gets HTML", async () => { eq(r.status, 404); }); +Deno.test("negotiation on the no-slash URL gives the trailing-slash canonical", async () => { + const r = await call("/docs/glossary", "text/markdown"); + eq(r.status, 200); + eq(r.headers.get("content-type").startsWith("text/markdown"), true); + eq(r.headers.get("link"), canonicalLink("/docs/glossary/")); +}); + Deno.test("negotiation adds Accept to an upstream Vary: Accept-Encoding", async () => { const withVary = async (p) => { const r = await serve(p); @@ -129,7 +181,7 @@ Deno.test("negotiated Markdown drops upstream encoding/length headers", async () const r = await call(PAGE, "text/markdown"); eq(r.headers.get("content-encoding"), null); eq(r.headers.get("content-length"), null); - eq((await r.text()).startsWith("# Getting Started"), true); + eq(MD_START.test(await r.text()), true); } finally { globalThis.fetch = (u) => serve(new URL(u).pathname); } @@ -149,6 +201,10 @@ Deno.test("negotiation falls back to HTML when the Markdown fetch throws", async Deno.test(".md URLs", async () => { let r = await call("/docs/glossary.md"); eq(r.status, 200); + eq(r.headers.get("link"), canonicalLink("/docs/glossary/")); + r = await call(PAGE.replace(/\/$/, ".md")); + eq(r.status, 200); + eq(r.headers.get("link"), canonicalLink(PAGE)); r = await call(PAGE + "index.md"); eq(r.status, 301); eq(loc(r), PAGE.replace(/\/$/, ".md")); @@ -156,6 +212,7 @@ Deno.test(".md URLs", async () => { eq(loc(r), "/docs/glossary.md"); r = await call("/docs/does-not-exist.md"); eq(r.status, 404); + eq(r.headers.get("link"), null); r = await call("/index.md"); eq(loc(r), "/llms.txt"); }); @@ -170,6 +227,69 @@ Deno.test(".md URLs of redirected pages follow the page's redirect", async () => eq(loc(r), "/docs/APIs-and-SDKs/Web-Console-API/api-key-get.md"); }); +Deno.test("negotiation after a redirect: canonical and Content-Location name the final page", async () => { + const finalMd = PAGE.replace(/\/$/, ".md"); + globalThis.fetch = async () => { + const r = await serve(finalMd); + Object.defineProperties(r, { + redirected: { value: true }, + url: { value: `https://x${finalMd}` }, + }); + return r; + }; + try { + const r = await handler(new Request("https://x/docs/getting-started", { headers: { accept: "text/markdown" } }), { + next: () => serve("/docs/getting-started"), + }); + eq(r.status, 200); + eq(r.headers.get("link"), canonicalLink(PAGE)); + eq(r.headers.get("content-location"), finalMd); + eq(MD_START.test(await r.text()), true); + } finally { + globalThis.fetch = (u) => serve(new URL(u).pathname); + } +}); + +Deno.test("negotiation serves HTML when the Markdown fetch was redirected to another origin", async () => { + globalThis.fetch = async () => { + const r = await serve(PAGE.replace(/\/$/, ".md")); + Object.defineProperties(r, { + redirected: { value: true }, + url: { value: "https://elsewhere.example/docs/other.md" }, + }); + return r; + }; + try { + const r = await call(PAGE, "text/markdown"); + eq(r.status, 200); + eq((await r.text()).startsWith(""), true); + } finally { + globalThis.fetch = (u) => serve(new URL(u).pathname); + } +}); + +Deno.test("negotiated Markdown has one canonical Link when the .md fetch already carries one", async () => { + globalThis.fetch = (u) => handler(new Request(u), { next: () => serve(new URL(u).pathname) }); + try { + const r = await call(PAGE, "text/markdown"); + eq(r.headers.get("link"), canonicalLink(PAGE)); + } finally { + globalThis.fetch = (u) => serve(new URL(u).pathname); + } +}); + +Deno.test(".md responses keep an upstream Link header next to the canonical one", async () => { + const r = await handler(new Request("https://x/docs/glossary.md"), { + next: async () => { + const served = await serve("/docs/glossary.md"); + const h = new Headers(served.headers); + h.set("link", `; rel="preload"`); + return new Response(served.body, { status: 200, headers: h }); + }, + }); + eq(r.headers.get("link"), `; rel="preload", ${canonicalLink("/docs/glossary/")}`); +}); + Deno.test(".md redirect probing survives fetch failures", async () => { globalThis.fetch = () => Promise.reject(new TypeError("network")); try { diff --git a/netlify/edge-functions/markdown-negotiation.js b/netlify/edge-functions/markdown-negotiation.js index a2d86738..5302c940 100644 --- a/netlify/edge-functions/markdown-negotiation.js +++ b/netlify/edge-functions/markdown-negotiation.js @@ -1,5 +1,19 @@ -// Serves the build-time `.md` at the page URL when the Accept header -// prefers text/markdown (browsers never send it), and handles `.md` URLs. +// Serves `.md` at the page URL when the Accept header prefers text/markdown, and handles `.md` URLs. + +const PRODUCTION_URL = "https://docs.absmartly.com"; +const PREVIEW_CONTEXTS = ["deploy-preview", "branch-deploy"]; + +// Netlify does not always expose CONTEXT/DEPLOY_PRIME_URL to edge functions, hence the deploy-context fallback. +export function siteOrigin(context, requestOrigin) { + if (typeof Netlify !== "undefined") { + const prime = Netlify.env.get("DEPLOY_PRIME_URL"); + if (PREVIEW_CONTEXTS.includes(Netlify.env.get("CONTEXT")) && prime) { + return prime.replace(/\/+$/, ""); + } + } + if (requestOrigin && PREVIEW_CONTEXTS.includes(context?.deploy?.context)) return requestOrigin; + return PRODUCTION_URL; +} export function parseAccept(header) { return (header || "") @@ -15,8 +29,6 @@ export function parseAccept(header) { .filter((entry) => entry.type); } -// True when text/markdown is explicitly accepted and preferred at least as much -// as text/html. Wildcards alone never select Markdown. export function prefersMarkdown(acceptHeader) { const entries = parseAccept(acceptHeader); const qFor = (type) => { @@ -47,9 +59,6 @@ export function appendVary(headers) { } } -// Canonical Markdown path for a URL that already asks for Markdown by -// extension: "/docs/foo/index.md", "/docs/foo/.md", "/docs/foo.md/" all map -// to "/docs/foo.md". Returns null when the path is not a .md request. export function canonicalMarkdownPath(pathname) { const m = pathname.match(/^(.*?)(?:\/index)?\/?\.md\/?$/); if (!m) return null; @@ -57,9 +66,24 @@ export function canonicalMarkdownPath(pathname) { return base ? `${base}.md` : null; } -// Handles explicit `.md` URLs. The static file is served directly when it -// exists; otherwise normalise odd spellings and follow page redirects (e.g. -// renamed sections in _redirects) to the Markdown of the target page. +export function htmlPathForMarkdown(mdPath) { + return mdPath.replace(/\.md$/, "/"); +} + +function setCanonicalLink(headers, mdPath, origin) { + headers.append("Link", `<${origin}${htmlPathForMarkdown(mdPath)}>; rel="canonical"`); +} + +function withHeaders(response, edit) { + const headers = new Headers(response.headers); + edit(headers); + return new Response(response.body, { + status: response.status, + statusText: response.statusText, + headers, + }); +} + async function handleMarkdownUrl(request, context, url) { const canonical = canonicalMarkdownPath(url.pathname); if (!canonical) { @@ -71,10 +95,10 @@ async function handleMarkdownUrl(request, context, url) { } const response = await context.next(); - if (response.ok) return response; + if (response.ok) { + return withHeaders(response, (h) => setCanonicalLink(h, canonical, siteOrigin(context, url.origin))); + } - // A splat in _redirects can match the .md URL before a page-specific rule, - // so follow the redirect of the HTML page URL instead. const pagePath = canonical.replace(/\.md$/, ""); for (const candidate of [pagePath, `${pagePath}/`]) { let probe; @@ -96,12 +120,13 @@ async function handleMarkdownUrl(request, context, url) { return response; } -// Returns null on any failure so the caller falls back to HTML. async function fetchMarkdown(mdPath, origin) { try { const res = await fetch(new URL(mdPath, origin), { headers: { accept: "text/markdown" } }); - if (res.ok) return res; - console.warn(`markdown-negotiation: ${mdPath} returned ${res.status}; serving HTML`); + const finalUrl = res.redirected ? new URL(res.url) : new URL(mdPath, origin); + const path = finalUrl.pathname; + if (res.ok && finalUrl.origin === origin && path.endsWith(".md")) return { response: res, path }; + console.warn(`markdown-negotiation: ${mdPath} returned ${res.status} from ${finalUrl}; serving HTML`); } catch (err) { console.warn(`markdown-negotiation: fetching ${mdPath} failed: ${err}; serving HTML`); } @@ -116,17 +141,17 @@ export default async function handler(request, context) { const mdPath = markdownPathFor(url.pathname); if (mdPath && prefersMarkdown(request.headers.get("accept"))) { - const mdResponse = await fetchMarkdown(mdPath, url.origin); - if (mdResponse) { - const headers = new Headers(mdResponse.headers); - // fetch() hands back a decoded body; the upstream encoding/length no - // longer describe it. + const markdown = await fetchMarkdown(mdPath, url.origin); + if (markdown) { + const headers = new Headers(markdown.response.headers); headers.delete("Content-Encoding"); headers.delete("Content-Length"); headers.set("Content-Type", "text/markdown; charset=utf-8"); - headers.set("Content-Location", mdPath); + headers.set("Content-Location", markdown.path); + headers.delete("Link"); + setCanonicalLink(headers, markdown.path, siteOrigin(context, url.origin)); appendVary(headers); - return new Response(mdResponse.body, { status: 200, headers }); + return new Response(markdown.response.body, { status: 200, headers }); } // No Markdown version (e.g. landing page): fall through to HTML. } @@ -134,15 +159,11 @@ export default async function handler(request, context) { const response = await context.next(); const contentType = response.headers.get("content-type") || ""; if (mdPath && contentType.includes("text/html")) { - const headers = new Headers(response.headers); - appendVary(headers); - if (response.ok) { - headers.append("Link", `<${mdPath}>; rel="alternate"; type="text/markdown"`); - } - return new Response(response.body, { - status: response.status, - statusText: response.statusText, - headers, + return withHeaders(response, (headers) => { + appendVary(headers); + if (response.ok) { + headers.append("Link", `<${mdPath}>; rel="alternate"; type="text/markdown"`); + } }); } return response; diff --git a/package.json b/package.json index 652cf673..b634a7af 100644 --- a/package.json +++ b/package.json @@ -13,20 +13,28 @@ "write-translations": "docusaurus write-translations", "write-heading-ids": "docusaurus write-heading-ids", "typecheck": "tsc", + "test": "node --import ./test-support/register.mjs --test \"plugins/**/*.test.js\" \"src/**/*.test.js\"", "gen:api": "docusaurus gen-api-docs all", "clean:api": "docusaurus clean-api-docs all" }, "dependencies": { + "@apidevtools/json-schema-ref-parser": "^15.2.2", "@docusaurus/core": "^3.10.2", "@docusaurus/plugin-ideal-image": "^3.10.2", "@docusaurus/preset-classic": "^3.10.2", "@docusaurus/theme-mermaid": "^3.10.2", + "@docusaurus/utils": "^3.10.2", "@mdx-js/react": "^3.1.1", "@signalwire/docusaurus-plugin-llms-txt": "1.2.2", "clsx": "^2.1.0", "docusaurus-plugin-openapi-docs": "^5.1.3", "docusaurus-plugin-sass": "^0.2.5", "docusaurus-theme-openapi-docs": "^5.1.3", + "js-yaml": "^4.1.1", + "mdast-util-from-markdown": "^2.0.0", + "mdast-util-gfm": "^3.0.0", + "mdast-util-to-hast": "^13.0.0", + "micromark-extension-gfm": "^3.0.0", "prism-react-renderer": "^2.4.1", "raw-loader": "^4.0.2", "react": "^18.2.0", @@ -34,10 +42,14 @@ "sass": "^1.75.0" }, "devDependencies": { - "@absmartly/api-mocks": "1.0.11", + "@absmartly/api-mocks": "1.0.12", "@docusaurus/module-type-aliases": "^3.10.2", "@swc/core": "^1.4.13", + "@testing-library/dom": "^10.4.2", + "@testing-library/react": "^16.3.3", + "@testing-library/user-event": "^14.6.13", "@tsconfig/docusaurus": "^2.0.3", + "jsdom": "^29.1.1", "swc-loader": "^0.2.6", "typescript": "^5.4.3" }, @@ -54,6 +66,6 @@ ] }, "engines": { - "node": ">=20.0" + "node": ">=22.13" } } diff --git a/plugins/build-checks.test.js b/plugins/build-checks.test.js new file mode 100644 index 00000000..9208dd49 --- /dev/null +++ b/plugins/build-checks.test.js @@ -0,0 +1,319 @@ +// Checks on the built site (yarn build). Each check is skipped when build/ is absent. +const test = require("node:test"); +const assert = require("node:assert"); +const fs = require("fs"); +const path = require("path"); + +const buildDir = path.resolve(__dirname, "../build"); +const read = (rel) => fs.readFileSync(path.join(buildDir, rel), "utf8"); +const API_INDEX = "docs/APIs-and-SDKs/Web-Console-API/llms.txt"; +const RESOURCE_DIR = "docs/APIs-and-SDKs/Web-Console-API/llms/"; +const WC_URL = "https://docs.absmartly.com/docs/APIs-and-SDKs/Web-Console-API/"; +const PRODUCTION_URL = "https://docs.absmartly.com"; +const LONGEST_PREVIEW_URL = "https://deploy-preview-99999--absmartly-docs.netlify.app"; + +const resourceFiles = () => + fs.readdirSync(path.join(buildDir, RESOURCE_DIR)).map((f) => `${RESOURCE_DIR}${f}`); + +// Agent link lists: build-relative path -> text. +const agentIndexes = () => + Object.fromEntries(["llms.txt", API_INDEX, ...resourceFiles()].map((rel) => [rel, read(rel)])); + +const linkLines = (text) => text.split("\n").filter((l) => l.startsWith("- [")); + +function buildTest(name, fn) { + test(name, (t) => { + if (!fs.existsSync(path.join(buildDir, "llms.txt"))) return t.skip("build/ absent"); + return fn(t); + }); +} + +buildTest("main llms.txt is under 50,000 characters and has no Web Console endpoints", () => { + const main = read("llms.txt"); + assert.ok(main.length < 50000, `llms.txt is ${main.length} chars`); + assert.match(main, /\n## Start here\n/); + assert.ok(main.includes(`(${WC_URL}llms.txt)`)); + const wcEntries = main.split("\n").filter((l) => l.startsWith("- [") && l.includes(`](${WC_URL}`) && !l.includes("llms.txt)")); + assert.deepStrictEqual(wcEntries, []); +}); + +buildTest("API endpoint descriptions in the resource files are not Markdown-formatted", () => { + for (const rel of resourceFiles()) { + for (const line of linkLines(read(rel))) assert.ok(!line.includes("**") && !line.includes(":::"), `${rel}: ${line}`); + } +}); + +buildTest("link URLs in the agent indexes contain no raw spaces", () => { + const linkLists = { + ...agentIndexes(), + "llms-full.txt": read("llms-full.txt").split("\n# Full Documentation Content\n")[0], + }; + for (const [file, text] of Object.entries(linkLists)) { + const raw = text.split("\n").filter((l) => /\]\(]* [^>]*>\)|\]\(https?:[^)]* [^)]*\.md\)/.test(l)); + assert.deepStrictEqual(raw, [], `${file}: raw spaces in link URLs`); + } +}); + +buildTest("the search page stays out of the agent files", () => { + for (const file of ["llms.txt", "llms-full.txt"]) { + assert.ok(!read(file).includes("/search.md"), `${file} links the search page`); + assert.ok(!read(file).includes("# Search the documentation"), `${file} has the search page`); + } + assert.ok(!fs.existsSync(path.join(buildDir, "search.md")), "build/search.md published"); +}); + +buildTest("every API endpoint .md has the spec-derived reference and no admonition markers", () => { + const api = path.join(buildDir, "docs/APIs-and-SDKs"); + let endpoints = 0; + for (const dir of ["Web-Console-API", "SDK-API"]) { + for (const f of fs.readdirSync(path.join(api, dir), { recursive: true }).map(String)) { + if (!f.endsWith(".md")) continue; + const md = fs.readFileSync(path.join(api, dir, f), "utf8"); + assert.ok(!md.includes(":::"), `${dir}/${f}: contains :::`); + if (dir === "Web-Console-API") assert.ok(!md.includes("absmartly.io/v1"), `${dir}/${f}: Collector base URL`); + if (f.endsWith("-api.md") || f.startsWith("examples")) continue; + assert.match(md, /^Source: \(operationId `/m, `${dir}/${f}: not rendered from the spec`); + const glued = md.match(/^( *)[*-] [^\n]*One of:\n\1[*-] Option /m); + assert.ok(!glued, `${dir}/${f}: options run on from a field: ${glued && glued[0]}`); + endpoints++; + } + } + assert.ok(endpoints >= 255, `only ${endpoints} endpoint pages`); +}); + +buildTest("the Web Console API index links each resource file once", () => { + const index = read(API_INDEX); + assert.match(index, /^# ABsmartly Web Console API\n/); + assert.ok(index.includes("Some endpoints return HTTP 200 with `ok: false` on failure; always check `ok`.")); + const linked = linkLines(index.split("\n## Resources\n")[1]).map((l) => l.match(/\]\(([^)]*)\)/)[1]); + assert.deepStrictEqual(linked, [...new Set(linked)]); + assert.deepStrictEqual(linked.sort(), resourceFiles().map((rel) => `${PRODUCTION_URL}/${rel}`).sort()); + for (const line of linkLines(index.split("\n## Resources\n")[1])) { + assert.match(line, /\): \d+ endpoints?: \S/); + assert.ok(line.length <= 300, `${line.length} chars: ${line}`); + } +}); + +buildTest("the resource files list every Web Console endpoint page exactly once", () => { + const dir = path.join(buildDir, "docs/APIs-and-SDKs/Web-Console-API"); + const pages = fs + .readdirSync(dir) + .filter((f) => f.endsWith(".md") && /^Source: <[^>]*web-console-api\.yaml>/m.test(fs.readFileSync(path.join(dir, f), "utf8"))) + .map((f) => `${WC_URL}${f}`); + const listed = resourceFiles().flatMap((rel) => { + const text = read(rel); + assert.match(text, /^# ABsmartly Web Console API: .+\n\n> .*\n\n## Endpoints\n\n/, rel); + return linkLines(text).map((l) => { + assert.match(l, /\): (GET|PUT|POST|DELETE|PATCH|HEAD|OPTIONS) \//, `${rel}: ${l}`); + return l.match(/\]\(([^)]*)\)/)[1]; + }); + }); + assert.ok(pages.length >= 270, `${pages.length} endpoint pages`); + assert.strictEqual(listed.length, new Set(listed).size, "an endpoint is listed twice"); + assert.deepStrictEqual(listed.sort(), pages.sort()); +}); + +buildTest("the resource files cannot collide with a page route", () => { + for (const f of ["index.html", "../llms.md", "../llms/index.html"]) { + assert.ok(!fs.existsSync(path.join(buildDir, RESOURCE_DIR, f)), `${RESOURCE_DIR}${f} exists`); + } +}); + +buildTest("every agent index stays under 50,000 characters on the longest preview origin", () => { + for (const [rel, text] of Object.entries(agentIndexes())) { + const urls = text.split(PRODUCTION_URL).length - 1; + const size = text.length + urls * (LONGEST_PREVIEW_URL.length - PRODUCTION_URL.length); + assert.ok(size < 50000, `${rel} would be ${size} chars (${text.length} in production)`); + } +}); + +buildTest("llms-full.txt excludes Web Console endpoint pages but keeps Collector ones", () => { + const full = read("llms-full.txt"); + const sources = [...full.matchAll(/^Source: <([^>]*)> \(operationId `/gm)].map((m) => m[1]); + assert.deepStrictEqual(sources.filter((u) => u.includes("web-console")), [], "Web Console endpoint pages left in llms-full.txt"); + assert.ok(sources.some((u) => u.includes("collector")), "Collector endpoint pages missing"); + assert.ok(full.includes("# Check Service Health")); + const withoutPointer = (md) => md.replace(/^> For AI agents:.*\n\n/, ""); + const overview = withoutPointer(read("docs/APIs-and-SDKs/Web-Console-API/absmartly-web-console-api.md")); + const collectorOverview = withoutPointer(read("docs/APIs-and-SDKs/SDK-API/absmartly-collector-api.md")); + assert.ok(full.includes(`${overview}\n\n---\n\n`), "Web Console API overview page missing"); + assert.ok(full.includes(`${collectorOverview}\n\n---\n\n`), "Collector API overview page missing"); + assert.ok(full.includes(`${WC_URL}llms.txt`), "note pointing to the API index"); +}); + +buildTest("llms-full.txt has at most one agent pointer line", () => { + const pointers = read("llms-full.txt").split("For AI agents:").length - 1; + assert.ok(pointers <= 1, `${pointers} pointer lines`); +}); + +buildTest("every generated .md page is under 50,000 characters", () => { + const walk = (dir) => + fs.readdirSync(dir, { withFileTypes: true }).flatMap((e) => { + const p = path.join(dir, e.name); + return e.isDirectory() ? walk(p) : e.name.endsWith(".md") ? [p] : []; + }); + for (const file of walk(path.join(buildDir, "docs"))) { + const size = fs.readFileSync(file, "utf8").length; + assert.ok(size < 50000, `${path.relative(buildDir, file)} is ${size} chars`); + } +}); + +const { pointerLine } = require("./llms-markdown/pointer"); +const SITE = "https://docs.absmartly.com"; + +buildTest("page Markdown starts with the agent pointer line (before the H1) and the HTML carries it", () => { + const md = read("docs/glossary.md"); + const lines = md.split("\n"); + assert.match(lines[2], /^# /); + // Markdown conversion renders bare URLs as autolinks. + const autolinked = pointerLine(`${SITE}/docs/glossary`, SITE).replace(/https:[^ ]*?(\.md|\.txt)/g, "<$&>"); + assert.strictEqual(lines[0], autolinked); + assert.strictEqual(md.split("For AI agents:").length - 1, 1); + const html = read("docs/glossary/index.html"); + assert.ok(html.includes("For AI agents: this page is available as Markdown at")); + assert.ok(html.includes(`${SITE}/docs/glossary.md`) && html.includes(`${SITE}/llms.txt`)); + assert.ok(!/]*>For AI agents/.test(html), "pointer must not be a

(Algolia)"); + assert.match(html, /]*class="agent-pointer[^"]*"[^>]*aria-hidden="true"|]*aria-hidden="true"[^>]*class="agent-pointer/, "pointer must be aria-hidden"); +}); + +buildTest("the SSO page's Markdown URLs are percent-encoded and match the llms.txt entry", () => { + const rel = "docs/Third-party-integrations/SSO/Okta SAML Setup"; + const listed = read("llms.txt").match(/\[SAML SSO - Okta\]\((https:[^)]*)\)/); + assert.ok(listed, "Okta page listed in llms.txt"); + const encoded = `${SITE}/${rel.replace(/ /g, "%20")}.md`; + assert.strictEqual(listed[1], encoded); + assert.ok(fs.existsSync(path.join(buildDir, decodeURI(new URL(encoded).pathname))), "encoded .md URL does not resolve"); + const pointer = read(`${rel}.md`).split("\n")[0]; + assert.ok(pointer.includes(`<${encoded}>`), pointer); + assert.ok(!/\.absmartly\.com\/[^ >)]* /.test(pointer), `raw space in pointer URL: ${pointer}`); + const html = read(`${rel}/index.html`); + assert.ok(html.includes(`type="text/markdown" href="${encoded}"`), "alternate link not encoded"); + // (The "Edit this page" link to the .mdx source on GitHub is Docusaurus's own.) + assert.ok(!/SAML Setup\.md(?!x)/.test(html), "raw-space .md URL in the HTML"); +}); + +buildTest("an API endpoint .md has exactly one pointer line", () => { + const md = read("docs/APIs-and-SDKs/SDK-API/collector-health-check.md"); + assert.strictEqual(md.split("For AI agents:").length - 1, 1); +}); + +buildTest("llms.txt descriptions never start with the pointer", () => { + for (const [rel, text] of Object.entries(agentIndexes())) assert.ok(!/: For AI agents/.test(text), rel); +}); + +buildTest("doc and API pages render the Copy page menu; it stays out of the Markdown", () => { + for (const rel of ["docs/glossary/index.html", "docs/APIs-and-SDKs/SDK-API/collector-health-check/index.html"]) { + const html = read(rel); + assert.ok(html.includes("page-ai-actions"), `${rel}: menu wrapper`); + assert.ok(/]*aria-haspopup="menu"[^>]*aria-expanded="false"/.test(html), `${rel}: trigger`); + assert.ok(html.includes("Copy page"), `${rel}: label`); + assert.ok(!/]*>[^<]*Copy page/.test(html), `${rel}: must not be an li (Algolia)`); + } + for (const rel of ["docs/glossary.md", "docs/APIs-and-SDKs/SDK-API/collector-health-check.md"]) { + const md = read(rel); + assert.ok(!md.includes("Copy page") && !md.includes("Open in Claude"), `${rel}: menu leaked into Markdown`); + } +}); + +buildTest("canonical URLs and sitemap entries use the trailing-slash form", () => { + const html = read("docs/glossary/index.html"); + assert.match(html, /]*rel="canonical"[^>]*href="https:\/\/docs\.absmartly\.com\/docs\/glossary\/"/); + const locs = [...read("sitemap.xml").matchAll(/([^<]*)<\/loc>/g)].map((m) => m[1]); + const docs = locs.filter((u) => u.startsWith("https://docs.absmartly.com/docs/")); + assert.ok(docs.length > 100, `only ${docs.length} docs URLs in sitemap`); + assert.deepStrictEqual(docs.filter((u) => !u.endsWith("/")), []); +}); + +buildTest("config-api's SDK Guide overview link points at the SDK docs index, not itself", () => { + const html = read("docs/APIs-and-SDKs/SDK-Documentation/config-api/index.html"); + assert.match(html, /]*href="\/docs\/APIs-and-SDKs\/SDK-Documentation\/">SDK Guide overview<\/a>/); + const md = read("docs/APIs-and-SDKs/SDK-Documentation/config-api.md"); + assert.ok(md.includes("[SDK Guide overview](https://docs.absmartly.com/docs/APIs-and-SDKs/SDK-Documentation.md)")); +}); + +buildTest("Markdown copies stay at .md and link to .md", () => { + assert.ok(fs.existsSync(path.join(buildDir, "docs/glossary.md"))); + assert.ok(!fs.existsSync(path.join(buildDir, "docs/glossary/.md"))); + assert.ok(!fs.existsSync(path.join(buildDir, "docs/glossary/index.md"))); + const md = read("docs/APIs-and-SDKs/SDK-Documentation/getting-started.md"); + assert.ok(!/\/\.md(?=[)?#\s])/.test(md), "found a /.md link"); + assert.match(md, /\(https:\/\/docs\.absmartly\.com\/docs\/[^)\s]*\.md(?:#[^)\s]*)?\)/); +}); + +buildTest("robots.txt allows crawling, blocks /search and points at the sitemap", () => { + const robots = read("robots.txt"); + assert.match(robots, /^User-agent: \*$/m); + assert.match(robots, /^Disallow: \/search$/m); + assert.match(robots, /^Allow: \/$/m); + assert.ok(robots.includes("Sitemap: https://docs.absmartly.com/sitemap.xml")); + assert.ok(robots.includes("https://docs.absmartly.com/llms.txt")); +}); + +buildTest("sitemap has no /search or /blog URLs", () => { + const locs = [...read("sitemap.xml").matchAll(/([^<]+)<\/loc>/g)].map((m) => new URL(m[1]).pathname); + assert.deepStrictEqual(locs.filter((p) => /^\/(search|blog)(\/|$)/.test(p)), []); +}); + +buildTest("hand-written docs have lastmod and generated API pages do not (full history only)", (t) => { + const { execSync } = require("child_process"); + let shallow; + try { + shallow = execSync("git rev-parse --is-shallow-repository", { cwd: buildDir, stdio: ["ignore", "pipe", "ignore"] }).toString().trim(); + } catch { + return t.skip("no git"); + } + if (shallow !== "false") return t.skip("shallow clone: dates disabled by config"); + const entries = [...read("sitemap.xml").matchAll(/([\s\S]*?)<\/url>/g)].map((m) => m[1]); + const hasLastmod = (e) => //.test(e); + const loc = (e) => e.match(/([^<]+)/)[1]; + const glossary = entries.find((e) => loc(e).endsWith("/docs/glossary/")); + assert.ok(glossary && hasLastmod(glossary), "glossary has no lastmod"); + const api = entries.filter((e) => /\/APIs-and-SDKs\/(Web-Console-API|SDK-API)\/[^/]+\/$/.test(loc(e))); + assert.ok(api.length > 50, `${api.length} API entries`); + assert.deepStrictEqual(api.filter(hasLastmod).map(loc), []); + const html = read("docs/APIs-and-SDKs/Web-Console-API/0100-000-list-experiments/index.html"); + assert.ok(!html.includes("Last updated")); + assert.ok(read("docs/glossary/index.html").includes("Last updated")); +}); + +buildTest("hand-written page titles are unique", () => { + const seen = new Map(); + for (const f of fs.readdirSync(path.join(buildDir, "docs"), { recursive: true })) { + if (!String(f).endsWith("index.html")) continue; + const m = read(path.join("docs", String(f))).match(/]*>([^<]*)/); + if (!m) continue; + seen.set(m[1], [...(seen.get(m[1]) || []), String(f)]); + } + assert.deepStrictEqual([...seen].filter(([, v]) => v.length > 1), []); +}); + +buildTest("Web Console API page titles are the readable spec summaries, unique", () => { + const dir = path.join(buildDir, "docs/APIs-and-SDKs/Web-Console-API"); + const titles = fs.readdirSync(dir, { withFileTypes: true }) + .filter((d) => d.isDirectory() && fs.existsSync(path.join(dir, d.name, "index.html"))) + .map((d) => fs.readFileSync(path.join(dir, d.name, "index.html"), "utf8").match(/]*>([^<]*)/)[1]); + assert.ok(titles.length >= 270, `${titles.length} pages`); + assert.deepStrictEqual(titles.filter((t) => t.includes("[")), []); + assert.deepStrictEqual(titles.filter((t, i) => titles.indexOf(t) !== i), []); +}); + +buildTest("redirects of renamed API pages point from a missing page to a built one", () => { + const rules = read("_redirects").split("\n") + .map((l) => l.trim().split(/\s+/)) + .filter(([from]) => from && from.startsWith("/docs/APIs-and-SDKs/Web-Console-API/0")); + assert.ok(rules.length >= 2, "no API rename redirects"); + const built = (p) => fs.existsSync(path.join(buildDir, p.endsWith("/") ? `${p}index.html` : p)); + for (const [from, to] of rules) { + assert.ok(!built(from) && !built(`${from}/`), `${from} still exists`); + assert.ok(built(to), `${to} missing`); + } +}); + +buildTest("no hand-written page's H1 is a bare generic heading", () => { + const generic = new Set(["# Overview", "# Authentication", "# Experiment Templates"]); + const apiDir = /^APIs-and-SDKs\/(Web-Console-API|SDK-API)\//; + const bare = fs.readdirSync(path.join(buildDir, "docs"), { recursive: true }).map(String) + .filter((f) => f.endsWith(".md") && !apiDir.test(f)) + .filter((f) => generic.has(read(path.join("docs", f)).split("\n").find((l) => l.startsWith("# ")))); + assert.deepStrictEqual(bare, []); +}); diff --git a/plugins/copy-markdown.test.js b/plugins/copy-markdown.test.js new file mode 100644 index 00000000..d3024386 --- /dev/null +++ b/plugins/copy-markdown.test.js @@ -0,0 +1,67 @@ +// Unit tests for src/utils/copyMarkdown.js (the "Copy page as Markdown" action). +const test = require("node:test"); +const assert = require("node:assert"); +const path = require("path"); +const { pathToFileURL } = require("url"); + +const load = () => import(pathToFileURL(path.resolve(__dirname, "../src/utils/copyMarkdown.js")).href); +const okFetch = (text) => async () => ({ ok: true, status: 200, text: async () => text }); + +test("uses clipboard.write with a promised ClipboardItem when available (keeps Safari's gesture)", async () => { + const { copyMarkdown } = await load(); + const calls = []; + class FakeItem { + constructor(items) { + this.items = items; + } + } + const clipboard = { + // The item must be handed over synchronously, before the fetch resolves. + write: async (items) => { + calls.push("write"); + assert.ok(items[0] instanceof FakeItem); + const blob = await items[0].items["text/plain"]; + calls.push(await blob.text()); + }, + writeText: async () => calls.push("writeText"), + }; + await copyMarkdown("/docs/x.md", { fetch: okFetch("# X"), clipboard, ClipboardItem: FakeItem }); + assert.deepStrictEqual(calls, ["write", "# X"]); +}); + +test("falls back to writeText without ClipboardItem", async () => { + const { copyMarkdown } = await load(); + const written = []; + const clipboard = { writeText: async (t) => written.push(t) }; + await copyMarkdown("/docs/x.md", { fetch: okFetch("# X"), clipboard, ClipboardItem: undefined }); + assert.deepStrictEqual(written, ["# X"]); +}); + +test("falls back to writeText when clipboard.write rejects", async () => { + const { copyMarkdown } = await load(); + const written = []; + const clipboard = { + write: async () => { + throw new Error("NotAllowedError"); + }, + writeText: async (t) => written.push(t), + }; + await copyMarkdown("/docs/x.md", { fetch: okFetch("# X"), clipboard, ClipboardItem: class {} }); + assert.deepStrictEqual(written, ["# X"]); +}); + +test("rejects on an HTTP error, whichever path is used", async () => { + const { copyMarkdown } = await load(); + const fetch = async () => ({ ok: false, status: 404, text: async () => "nope" }); + const writeText = async () => assert.fail("must not write"); + const write = async (items) => { + await items[0].items["text/plain"]; + }; + class Item { + constructor(items) { + this.items = items; + } + } + await assert.rejects(copyMarkdown("/x.md", { fetch, clipboard: { writeText }, ClipboardItem: undefined }), /HTTP 404/); + await assert.rejects(copyMarkdown("/x.md", { fetch, clipboard: { write, writeText }, ClipboardItem: Item }), /HTTP 404/); +}); diff --git a/plugins/llms-markdown/api/render-operation.js b/plugins/llms-markdown/api/render-operation.js new file mode 100644 index 00000000..2ad667ef --- /dev/null +++ b/plugins/llms-markdown/api/render-operation.js @@ -0,0 +1,245 @@ +const { renderSchemaFields, canReturnNotOk, admonitionLabel } = require("./render-schema"); +const { pointerLine } = require("../pointer"); +const { sampleRequestFromSchema } = require("docusaurus-plugin-openapi-docs/lib/openapi/createRequestExample"); +const { sampleResponseFromSchema } = require("docusaurus-plugin-openapi-docs/lib/openapi/createResponseExample"); + +const MAX_CHARS = 50000; +const HTML_ROUND_TRIP_MARGIN = 5000; +const SIZE_BUDGET = MAX_CHARS - HTML_ROUND_TRIP_MARGIN; +const MAX_DEPTH = 6; +const ALL_EXAMPLES = "all"; +const ONE_EXAMPLE_EACH = "one-each"; +const REQUEST_EXAMPLE_ONLY = "request-only"; +const BASE_URLS = { + webConsole: "https://.absmartly.com/v1", + collector: "https://.absmartly.io/v1", +}; +const NOT_OK_LINE = "This endpoint can return HTTP 200 with `ok: false` on failure; always check `ok`."; +const authLines = (siteUrl) => ({ + webConsole: + "**Authentication:** send `Authorization: Api-Key `, with an API key from **Settings → API Keys**, " + + `or a federated OIDC access token. See [Platform API authentication](${siteUrl}/docs/APIs-and-SDKs/overview.md#platform-api) ` + + `and [Federated Authentication](${siteUrl}/docs/APIs-and-SDKs/Federated-Authentication/federated-oidc-tokens.md).`, + collector: "**Authentication:** send `X-API-Key: `.", +}); +const NO_AUTH_LINE = "**Authentication:** none required."; + +function isObj(v) { + return v && typeof v === "object" && !Array.isArray(v); +} + +function stripAdmonitions(text) { + return String(text || "") + .split("\n") + .filter((l) => !/^\s*:::/.test(l)) + .join("\n") + .trim(); +} + +function admonitionQuote(type, lines) { + const body = lines.map((l) => l.trim()); + while (body.length && !body[0]) body.shift(); + while (body.length && !body[body.length - 1]) body.pop(); + return body.map((l, i) => (i === 0 ? `> ${admonitionLabel(type)} ${l}` : l ? `> ${l}` : ">")).join("\n"); +} + +function quoteAdmonitions(text) { + const out = []; + let open = null; + for (const line of String(text || "").split("\n")) { + const start = !open && line.match(/^\s*:::(\w+)/); + if (start) open = { type: start[1], lines: [] }; + else if (open && /^\s*:::\s*$/.test(line)) { + out.push(admonitionQuote(open.type, open.lines)); + open = null; + } else (open ? open.lines : out).push(line); + } + if (open) out.push(admonitionQuote(open.type, open.lines)); + return out + .join("\n") + .replace(/[ \t]+$/gm, "") + .trim(); +} + +function flatten(text) { + return stripAdmonitions(text).replace(/\s*\n\s*/g, " "); +} + +function oneLine(text) { + return flatten(text).replace(/\|/g, "\\|"); +} + +function paramType(schema) { + if (!isObj(schema)) return ""; + let t = Array.isArray(schema.type) ? schema.type.join(" or ") : schema.type || ""; + if (t === "array" && isObj(schema.items)) t = `array of ${paramType(schema.items) || "any"}`; + if (schema.format) t += ` (${schema.format})`; + return t; +} + +// Path-item parameters apply to every operation; operation-level ones win on name+in. +function mergeParams(pathParams, opParams) { + const own = Array.isArray(opParams) ? opParams : []; + const inherited = (Array.isArray(pathParams) ? pathParams : []).filter( + (p) => !own.some((o) => o.name === p.name && o.in === p.in), + ); + return [...inherited, ...own]; +} + +function paramTable(params, where, title) { + const rows = params.filter((p) => p.in === where); + if (!rows.length) return ""; + const lines = [`## ${title}`, "", "| Name | Type | Required | Description |", "| --- | --- | --- | --- |"]; + for (const p of rows) { + let desc = oneLine(p.description || (p.schema && p.schema.description)); + const en = p.schema && Array.isArray(p.schema.enum) ? p.schema.enum : null; + if (desc && en && !/[.!?:]$/.test(desc)) desc += "."; + if (en) desc += `${desc ? " " : ""}One of: ${en.map((v) => `\`${String(v).replace(/\|/g, "\\|")}\``).join(", ")}.`; + lines.push(`| \`${p.name}\` | ${paramType(p.schema)} | ${p.required || where === "path" ? "yes" : "no"} | ${desc} |`); + } + return lines.join("\n"); +} + +function pickContent(content) { + if (!isObj(content)) return null; + const types = Object.keys(content); + if (!types.length) return null; + const type = types.find((t) => /json/.test(t)) || types[0]; + return { type, media: content[type] || {} }; +} + +function ownExamples(media) { + if (media.example !== undefined) return [{ label: null, value: media.example }]; + if (!isObj(media.examples)) return []; + const named = Object.entries(media.examples); + return named.map(([key, ex]) => ({ + label: isObj(ex) && ex.summary ? flatten(ex.summary) : named.length > 1 ? `\`${key}\`` : null, + value: isObj(ex) && "value" in ex ? ex.value : ex, + })); +} + +function sample(fn, schema) { + try { + const v = fn(schema); + return v === undefined || v === null ? undefined : v; + } catch (e) { + return undefined; + } +} + +function jsonBlock(value) { + const text = typeof value === "string" ? value : JSON.stringify(value, null, 2); + return "```json\n" + text + "\n```"; +} + +function isNotOk(value) { + return isObj(value) && value.ok === false; +} + +function examplesFor(media, sampler, schema, examples) { + const own = ownExamples(media); + if (own.length) { + if (examples === ALL_EXAMPLES) return own; + return [own.find((ex) => !isNotOk(ex.value)) || own[0]]; + } + const gen = sample(sampler, schema); + if (gen === undefined || (isObj(gen) && !Object.keys(gen).length)) return []; + return [{ label: null, value: gen, generated: true }]; +} + +function exampleCaption(ex) { + if (ex.generated) return "Example (generated from the schema):"; + return ex.label ? `Example: ${ex.label}` : "Example:"; +} + +function fieldList(schema, maxDepth) { + if (!isObj(schema)) return ""; + return stripAdmonitions(renderSchemaFields(schema, { maxDepth })); +} + +function build(entry, pageUrl, { requestDepth, responseDepth, examples, siteUrl }) { + const op = entry.op || {}; + const params = mergeParams(entry.pathParameters, op.parameters); + const sections = []; + const push = (s) => s && sections.push(s); + + push(pointerLine(pageUrl, siteUrl)); + push(`# ${entry.title || entry.summary || entry.operationId}`); + push(`\`${entry.method} ${entry.path}\``); + push(`Base URL: your ABsmartly instance's API endpoint, e.g. \`${BASE_URLS[entry.specKey]}\``); + push(Array.isArray(op.security) && op.security.length === 0 ? NO_AUTH_LINE : authLines(siteUrl)[entry.specKey]); + push(quoteAdmonitions(op.description || entry.description)); + push(paramTable(params, "path", "Path parameters")); + push(paramTable(params, "query", "Query parameters")); + push(paramTable(params, "header", "Header parameters")); + + const body = op.requestBody && pickContent(op.requestBody.content); + if (body) { + const fields = fieldList(body.media.schema, requestDepth); + const exs = examplesFor(body.media, sampleRequestFromSchema, body.media.schema, examples); + const note = fields || exs.length ? fields : "No schema is defined for this body."; + push(`## Request body (\`${body.type}\`)` + (note ? `\n\n${note}` : "")); + for (const ex of exs) { + const label = ex.label === "Example request" ? null : ex.label; + const suffix = ex.generated ? " (generated from the schema)" : label ? `: ${label}` : ""; + push(`### Example request body${suffix}\n\n${jsonBlock(ex.value)}`); + } + } + + const responses = isObj(op.responses) ? op.responses : {}; + const codes = Object.keys(responses); + const ok = codes.filter((c) => /^2/.test(c)); + const errors = codes.filter((c) => !/^2/.test(c)); + if (ok.length) { + push("## Responses"); + for (const code of ok) { + const r = responses[code] || {}; + const parts = [`### ${code} ${oneLine(r.description)}`.trim()]; + const content = pickContent(r.content); + if (content) { + const schemaNotOk = isObj(content.media.schema) && canReturnNotOk(content.media.schema); + if (schemaNotOk || ownExamples(content.media).some((ex) => isNotOk(ex.value))) parts.push(NOT_OK_LINE); + const fields = fieldList(content.media.schema, responseDepth); + if (fields) parts.push(fields); + if (examples !== REQUEST_EXAMPLE_ONLY) { + const exs = examplesFor(content.media, sampleResponseFromSchema, content.media.schema, examples); + for (const ex of exs) parts.push(`${exampleCaption(ex)}\n\n${jsonBlock(ex.value)}`); + } + } + if (parts.length === 1) parts.push("No response body."); + push(parts.join("\n\n")); + } + } + if (errors.length) { + const head = ok.length ? "### Errors" : "## Responses\n\n### Errors"; + push( + `${head}\n\n` + + errors.map((c) => `- \`${c}\` ${oneLine((responses[c] || {}).description)}`.trimEnd()).join("\n"), + ); + } + push(`Source: ${entry.publishedUrl} (operationId \`${entry.operationId}\`)`); + return sections.join("\n\n") + "\n"; +} + +// Size guard: drop extra examples, then response examples, then reduce response depth, then request depth. +function renderOperationMarkdown(entry, { pageUrl, siteUrl }) { + if (!siteUrl) throw new Error("renderOperationMarkdown: siteUrl is required"); + const attempts = [ + { requestDepth: MAX_DEPTH, responseDepth: MAX_DEPTH, examples: ALL_EXAMPLES }, + { requestDepth: MAX_DEPTH, responseDepth: MAX_DEPTH, examples: ONE_EXAMPLE_EACH }, + { requestDepth: MAX_DEPTH, responseDepth: MAX_DEPTH, examples: REQUEST_EXAMPLE_ONLY }, + ]; + for (let d = MAX_DEPTH - 1; d >= 1; d--) { + attempts.push({ requestDepth: MAX_DEPTH, responseDepth: d, examples: REQUEST_EXAMPLE_ONLY }); + } + for (let d = MAX_DEPTH - 1; d >= 1; d--) attempts.push({ requestDepth: d, responseDepth: 1, examples: REQUEST_EXAMPLE_ONLY }); + let out; + for (const a of attempts) { + out = build(entry, pageUrl, { ...a, siteUrl }); + if (out.length < SIZE_BUDGET) return out; + } + console.warn(`${entry.method} ${entry.path}: ${out.length} chars, still over ${SIZE_BUDGET} after the size guard`); + return out; +} + +module.exports = { renderOperationMarkdown, MAX_CHARS, SIZE_BUDGET, _build: build }; diff --git a/plugins/llms-markdown/api/render-operation.test.js b/plugins/llms-markdown/api/render-operation.test.js new file mode 100644 index 00000000..e64bcd17 --- /dev/null +++ b/plugins/llms-markdown/api/render-operation.test.js @@ -0,0 +1,385 @@ +const test = require("node:test"); +const assert = require("node:assert"); +const path = require("path"); +const si = require("./spec-index"); +const { renderOperationMarkdown, MAX_CHARS, SIZE_BUDGET } = require("./render-operation"); +const { pointerLine } = require("../pointer"); + +const siteDir = path.resolve(__dirname, "../../.."); +let cached; +async function load() { + if (!cached) { + const specs = await si.loadDereferencedSpecs(siteDir); + const pages = new Map(si.listOperations(specs).map((o) => [`${o.method} ${o.path}`, `/docs/test/${o.operationId}`])); + cached = si.buildOperationIndex(specs, pages, "https://docs.absmartly.com"); + } + return cached; +} +const render = (e) => renderOperationMarkdown(e, { pageUrl: e.pageUrl, siteUrl: SITE }); +// An empty section is a heading directly followed by a heading of the same or higher level. +const noEmptySections = (md) => { + const re = /^(#+) .*\n\n(#+) /gm; + let m; + while ((m = re.exec(md))) assert.ok(m[2].length > m[1].length, `empty section: ${m[0]}`); +}; + +const SITE = "https://docs.absmartly.com"; + +test("pointerLine wording", () => { + assert.strictEqual( + pointerLine(`${SITE}/docs/x`, SITE), + "> For AI agents: this page is available as Markdown at https://docs.absmartly.com/docs/x.md. The full documentation index is at https://docs.absmartly.com/llms.txt.", + ); +}); + +test("archive goal page", async () => { + const e = (await load()).get("PUT /goals/{goalId}/archive"); + const md = render(e); + assert.ok(md.startsWith(pointerLine(e.pageUrl, SITE))); + assert.ok(md.includes("# Goal archive")); + assert.ok(md.includes("`PUT /goals/{goalId}/archive`")); + assert.match(md, /## Path parameters[\s\S]*\| `goalId` \|/); + assert.ok(md.includes("Api-Key")); + // Internal links in agent Markdown use the .md form, like every other page. + assert.ok(md.includes("(https://docs.absmartly.com/docs/APIs-and-SDKs/overview.md#platform-api)")); + assert.ok(md.includes("(https://docs.absmartly.com/docs/APIs-and-SDKs/Federated-Authentication/federated-oidc-tokens.md)")); + assert.ok(!/absmartly\.com\/docs\/[^)\s]*\/[#)]/.test(md), "HTML-form docs link in agent Markdown"); + assert.ok(md.includes("operationId `ArchiveGoal`")); + assert.ok(md.includes("Base URL: ")); + noEmptySections(md); +}); + +test("links use the given site URL", async () => { + const site = "https://preview.example"; + const e = { + ...(await load()).get("PUT /goals/{goalId}/archive"), + pageUrl: `${site}/docs/x`, + publishedUrl: `${site}/openapi/web-console-api.yaml`, + }; + const md = renderOperationMarkdown(e, { pageUrl: e.pageUrl, siteUrl: site }); + assert.ok(md.startsWith(pointerLine(e.pageUrl, site))); + assert.ok(md.includes(`(${site}/docs/APIs-and-SDKs/overview.md#platform-api)`)); + assert.ok(md.includes(`(${site}/docs/APIs-and-SDKs/Federated-Authentication/federated-oidc-tokens.md)`)); + assert.ok(!md.includes("docs.absmartly.com"), md.slice(0, 600)); +}); + +test("create experiment page", async () => { + const md = render((await load()).get("POST /experiments")); + assert.ok(md.includes("## Request body")); + assert.ok(md.includes("unit_type_id")); + const m = md.match(/### Example request body[^\n]*\n\n```json\n([\s\S]*?)\n```/); + assert.ok(m); + JSON.parse(m[1]); +}); + +test("collector context create", async () => { + const md = render((await load()).get("POST /context")); + assert.ok(md.includes("X-API-Key")); + assert.ok(md.includes("(generated from the schema)")); +}); + +test("sparse operations have no empty sections", async () => { + const idx = await load(); + for (const k of ["GET /healthy", "DELETE /events/unit_data"]) { + const e = idx.get(k); + assert.ok(e, k); + const md = render(e); + noEmptySections(md); + assert.doesNotMatch(md, /\n## [^\n]*\n*$/); + } +}); + +test("every operation renders under the cap without :::", async () => { + const idx = await load(); + for (const [k, e] of idx) { + const md = render(e); + assert.ok(md.length < SIZE_BUDGET, `${k} is ${md.length}`); + assert.ok(!md.includes(":::"), k); + noEmptySections(md); + } +}); + +test("every {placeholder} in every path has a parameter row", async () => { + const idx = await load(); + for (const [k, e] of idx) { + const md = render(e); + for (const [, name] of e.path.matchAll(/\{([^}]+)\}/g)) { + assert.ok(md.includes(`| \`${name}\` |`), `${k} is missing a row for ${name}`); + } + } +}); + +test("operation-level parameters override path-level ones", () => { + const entry = { + specKey: "webConsole", + method: "GET", + path: "/a/{id}", + operationId: "x", + title: "X", + publishedUrl: "u", + pathParameters: [ + { name: "id", in: "path", required: true, schema: { type: "integer" }, description: "path-level" }, + { name: "q", in: "query", schema: { type: "string" }, description: "inherited" }, + ], + op: { + parameters: [{ name: "id", in: "path", required: true, schema: { type: "string" }, description: "op-level" }], + responses: {}, + }, + }; + const md = renderOperationMarkdown(entry, { pageUrl: "https://x/y", siteUrl: SITE }); + assert.ok(md.includes("op-level")); + assert.ok(!md.includes("path-level")); + assert.ok(md.includes("| `q` |")); +}); + +test("enum values escape pipes", () => { + const entry = { + specKey: "collector", + method: "GET", + path: "/a", + operationId: "x", + title: "X", + publishedUrl: "u", + op: { parameters: [{ name: "q", in: "query", schema: { type: "string", enum: ["a|b"] } }], responses: {} }, + }; + assert.ok(renderOperationMarkdown(entry, { pageUrl: "https://x/y", siteUrl: SITE }).includes("`a\\|b`")); +}); + +test("param descriptions and enum lists are separate sentences", () => { + const entry = { + specKey: "collector", + method: "GET", + path: "/a", + operationId: "x", + title: "X", + publishedUrl: "u", + op: { + parameters: [ + { name: "q", in: "query", description: "Filter by sample ratio mismatch", schema: { type: "integer", enum: [0, 1] } }, + { name: "r", in: "query", description: "Ends in a stop.", schema: { type: "string", enum: ["a"] } }, + { name: "s", in: "query", schema: { type: "string", enum: ["b"] } }, + ], + responses: {}, + }, + }; + const md = renderOperationMarkdown(entry, { pageUrl: "https://x/y", siteUrl: SITE }); + assert.ok(md.includes("| Filter by sample ratio mismatch. One of: `0`, `1`. |"), md); + assert.ok(md.includes("| Ends in a stop. One of: `a`. |")); + assert.ok(md.includes("| One of: `b`. |")); +}); + +const fixture = (specKey, op) => ({ + specKey, + method: "PUT", + path: "/a", + operationId: "x", + title: "X", + publishedUrl: "https://docs.absmartly.com/openapi/x.yaml", + op: { responses: {}, ...op }, +}); + +test("the base URL depends on the spec", () => { + const wc = renderOperationMarkdown(fixture("webConsole", {}), { pageUrl: "https://x/y", siteUrl: SITE }); + const collector = renderOperationMarkdown(fixture("collector", {}), { pageUrl: "https://x/y", siteUrl: SITE }); + assert.ok(wc.includes("`https://.absmartly.com/v1`"), wc); + assert.ok(!wc.includes("absmartly.io")); + assert.ok(collector.includes("`https://.absmartly.io/v1`"), collector); +}); + +const okSchema = { + anyOf: [ + { type: "object", required: ["ok"], properties: { ok: { const: true }, id: { type: "integer" } } }, + { type: "object", required: ["ok"], properties: { ok: { const: false }, errors: { type: "array", items: { type: "string" } } } }, + ], +}; +const okResponses = (examples) => ({ + responses: { 200: { description: "OK", content: { "application/json": { schema: okSchema, examples } } } }, +}); + +test("every named response example is rendered with its summary or key", () => { + const md = renderOperationMarkdown( + fixture( + "webConsole", + okResponses({ + failed: { value: { ok: false, errors: ["Internal Server Error"] } }, + succeeded: { summary: "Success", value: { ok: true, id: 7 } }, + }), + ), + { pageUrl: "https://x/y", siteUrl: SITE }, + ); + assert.ok(md.includes("Example: `failed`"), md); + assert.ok(md.includes("Example: Success"), md); + assert.ok(md.includes('"Internal Server Error"')); + assert.ok(md.includes('"id": 7')); +}); + +const NOT_OK = "This endpoint can return HTTP 200 with `ok: false` on failure; always check `ok`."; + +test("endpoints whose 200 can carry ok: false say so", () => { + const md = renderOperationMarkdown(fixture("webConsole", okResponses(undefined)), { pageUrl: "https://x/y", siteUrl: SITE }); + assert.ok(md.includes("This endpoint can return HTTP 200 with `ok: false` on failure; always check `ok`."), md); + const plain = renderOperationMarkdown( + fixture("webConsole", { + responses: { + 200: { description: "OK", content: { "application/json": { schema: { type: "object", properties: { id: { type: "integer" } } } } } }, + }, + }), + { pageUrl: "https://x/y", siteUrl: SITE }, + ); + assert.ok(!plain.includes("ok: false")); +}); + +test("the size guard drops extra examples before the first one", () => { + const big = { ok: false, errors: ["x".repeat(MAX_CHARS)] }; + const md = renderOperationMarkdown( + fixture("webConsole", okResponses({ first: { value: { ok: true, id: 1 } }, second: { value: big } })), + { pageUrl: "https://x/y", siteUrl: SITE }, + ); + assert.ok(md.includes('"id": 1'), md.slice(0, 2000)); + assert.ok(!md.includes("xxxxxxxxxx")); + assert.ok(md.length < SIZE_BUDGET); +}); + +const plainResponses = (examples) => ({ + responses: { + 200: { + description: "OK", + content: { "application/json": { schema: { type: "object", properties: { ok: { type: "boolean" } } }, examples } }, + }, + }, +}); + +test("an ok: false 200 example triggers the note even when the schema does not model it", () => { + const md = renderOperationMarkdown( + fixture("webConsole", plainResponses({ failed: { value: { ok: false, errors: ["nope"] } } })), + { pageUrl: "https://x/y", siteUrl: SITE }, + ); + assert.ok(md.includes(NOT_OK), md); +}); + +test("the example-driven note survives the size guard dropping every response example", () => { + const huge = "x".repeat(MAX_CHARS); + const md = renderOperationMarkdown( + fixture("webConsole", plainResponses({ failed: { value: { ok: false, errors: [huge] } } })), + { pageUrl: "https://x/y", siteUrl: SITE }, + ); + assert.ok(!md.includes("xxxxxxxxxx")); + assert.ok(md.includes(NOT_OK), md.slice(0, 2000)); +}); + +test("with only one example per response the size guard keeps a success example", () => { + const md = renderOperationMarkdown( + fixture( + "webConsole", + okResponses({ + failed: { value: { ok: false, errors: ["first error"] } }, + succeeded: { value: { ok: true, id: 1 } }, + huge: { value: { ok: false, errors: ["x".repeat(MAX_CHARS)] } }, + }), + ), + { pageUrl: "https://x/y", siteUrl: SITE }, + ); + assert.ok(md.includes('"id": 1'), md.slice(0, 2000)); + assert.ok(!md.includes("first error")); + assert.ok(!md.includes("xxxxxxxxxx")); +}); + +test("example captions keep pipes unescaped", () => { + const md = renderOperationMarkdown( + fixture("webConsole", okResponses({ a: { summary: "on | off", value: { ok: true, id: 1 } } })), + { pageUrl: "https://x/y", siteUrl: SITE }, + ); + assert.ok(md.includes("Example: on | off"), md); +}); + +test("real endpoints that return ok: false in a 200 carry the note", async () => { + const idx = await load(); + for (const k of [ + "PUT /experiment_custom_sections/order", + "POST /experiments/{experimentId}/activity/{commentId}/reply", + "POST /experiments", + ]) { + assert.ok(idx.get(k), k); + assert.ok(render(idx.get(k)).includes(NOT_OK), k); + } +}); + +test("type arrays read 'a or b' in parameter tables", () => { + const md = renderOperationMarkdown( + fixture("collector", { parameters: [{ name: "q", in: "query", schema: { type: ["integer", "string"] } }] }), + { pageUrl: "https://x/y", siteUrl: SITE }, + ); + assert.ok(md.includes("| `q` | integer or string | no |"), md); +}); + +test("the full-on page shows the success example and the ok discriminator", async () => { + const md = render((await load()).get("PUT /experiments/{experimentId}/full_on")); + assert.ok(md.includes("`https://.absmartly.com/v1`")); + assert.ok(md.includes("### Example request body\n"), md); + const labels = md.split("\n").filter((l) => l.startsWith("Example: ")); + assert.strictEqual(labels[0], "Example: Success"); + assert.ok(labels.slice(1).length >= 1 && labels.slice(1).every((l) => l.startsWith("Example: Error: ")), labels.join("\n")); + assert.match(md, /"ok": true/); + assert.match(md, /"ok": false/); + assert.ok(md.includes("Option 1 (`ok: true`)")); + assert.ok(md.includes("Always `false`.")); +}); + +test("admonitions in the description become labelled blockquotes", () => { + const md = renderOperationMarkdown( + fixture("webConsole", { + description: "**Required**: x\n\n:::caution\nFirst line.\n\nSecond line.\n:::\n\n:::note Heads up\nA note.\n:::", + }), + { pageUrl: "https://x/y", siteUrl: SITE }, + ); + assert.ok(md.includes("**Required**: x\n\n> **Caution:** First line.\n>\n> Second line.\n\n> **Note:** A note."), md); + assert.ok(!md.includes(":::")); +}); + +test("the size guard shrinks the response before the request", () => { + const deep = (n) => + n ? { type: "object", properties: { [`level${n}`]: deep(n - 1) } } : { type: "string", description: "deepleaf" }; + const inner = Object.fromEntries( + Array.from({ length: 5 }, (_, i) => [`f${i}`, { type: "string", description: "d".repeat(100) }]), + ); + const wide = { + type: "object", + properties: Object.fromEntries(Array.from({ length: 300 }, (_, i) => [`p${i}`, { type: "object", properties: inner }])), + }; + const md = renderOperationMarkdown( + fixture("webConsole", { + requestBody: { content: { "application/json": { schema: deep(4), example: { level4: {} } } } }, + responses: { 200: { description: "OK", content: { "application/json": { schema: wide } } } }, + }), + { pageUrl: "https://x/y", siteUrl: SITE }, + ); + assert.ok(md.length < SIZE_BUDGET, `${md.length}`); + assert.ok(md.includes("deepleaf"), md.slice(0, 1500)); + assert.ok(md.includes("`p299`")); +}); + +test("real pages: root shapes, maps, cautions, request depth and back-references", async () => { + const idx = await load(); + const summary = render(idx.get("GET /metrics/{metricId}/usage/summary")); + assert.ok(summary.includes("Aggregate usage totals and breakdowns for the metric.\n\nJSON object (free-form)."), summary); + assert.ok(!summary.includes("No response body")); + const alerts = render(idx.get("GET /platform_alerts")); + assert.match(alerts, /Array of:\n\n- `id`[\s\S]*- `message`/); + const goal = render(idx.get("PUT /goals/{goalId}")); + assert.match(goal, /^> \*\*Caution:\*\* Regular fields provided/m); + assert.match(goal, /^> However, if relationship fields .*ALL existing related records will be DELETED/m); + const create = render(idx.get("POST /experiments")); + const request = create.split("\n## Responses\n")[0]; + assert.ok(!request.includes("nested fields omitted"), "request fields dropped on POST /experiments"); + assert.match( + request, + /- `custom_section_field_values` \(map of object, required\)\n {2}- `` \(object\)\. Key pattern: `\^\[0-9\]\+\$`\.\n {4}- `experiment_id`/, + ); + const fullOn = render(idx.get("PUT /experiments/{experimentId}/full_on")); + assert.ok(!fullOn.includes("(option"), "option numbers in back-references"); + assert.match(fullOn, /`seed` \(integer or string\)/); +}); + +test("renderOperationMarkdown requires a site URL", () => { + assert.throws(() => renderOperationMarkdown(fixture("collector", {}), { pageUrl: "https://x/y" }), /siteUrl/); +}); diff --git a/plugins/llms-markdown/api/render-schema.js b/plugins/llms-markdown/api/render-schema.js new file mode 100644 index 00000000..a1a3e8f1 --- /dev/null +++ b/plugins/llms-markdown/api/render-schema.js @@ -0,0 +1,287 @@ +const OMITTED = "(nested fields omitted; see the OpenAPI spec)"; + +function isObj(v) { + return v && typeof v === "object" && !Array.isArray(v); +} + +function constType(value) { + if (Array.isArray(value)) return "array"; + if (Number.isInteger(value)) return "integer"; + return typeof value; +} + +function isNullSchema(s) { + return isObj(s) && (s.type === "null" || (Array.isArray(s.enum) && s.enum.length === 1 && s.enum[0] === null)); +} + +// Flattens allOf (own keys win) and folds `null` oneOf/anyOf alternatives into `nullable`. +function merge(schema, seen = new Set()) { + const m = { + types: [], + properties: new Map(), + required: new Set(), + oneOf: null, + anyOf: null, + nullable: false, + }; + const visit = (s) => { + if (!isObj(s) || seen.has(s)) return; + seen.add(s); + for (const key of ["description", "format", "default", "enum", "const", "title", "items", "additionalProperties", "propertyNames"]) { + if (m[key] === undefined && s[key] !== undefined) m[key] = s[key]; + } + const t = Array.isArray(s.type) ? s.type : s.type ? [s.type] : []; + for (const x of t) { + if (x === "null") m.nullable = true; + else if (!m.types.includes(x)) m.types.push(x); + } + if (s.nullable === true) m.nullable = true; + if (Array.isArray(s.allOf)) s.allOf.forEach(visit); + if (isObj(s.properties)) { + for (const [k, v] of Object.entries(s.properties)) { + const prev = m.properties.get(k); + m.properties.set(k, prev && prev !== v ? { allOf: [v, prev] } : v); + } + } + if (Array.isArray(s.required)) s.required.forEach((r) => m.required.add(r)); + for (const kw of ["oneOf", "anyOf"]) { + if (!Array.isArray(s[kw]) || m[kw]) continue; + const nonNull = s[kw].filter((o) => { + if (!isNullSchema(o)) return true; + m.nullable = true; + return false; + }); + if (nonNull.length === 1) visit(nonNull[0]); + else if (nonNull.length > 1) m[kw] = nonNull; + } + }; + visit(schema); + for (const kw of ["oneOf", "anyOf"]) { + const labels = m[kw] && m[kw].map(scalarLabel); + if (!labels || labels.includes(null)) continue; + for (const label of labels) if (!m.types.includes(label)) m.types.push(label); + m[kw] = null; + } + if (!m.types.length) { + if (m.properties.size) m.types.push("object"); + else if (m.items) m.types.push("array"); + else if (m.const !== undefined && m.const !== null) m.types.push(constType(m.const)); + } + return m; +} + +// Unwraps an allOf of one, or a single non-null alternative, around a referenced schema. +function canon(schema) { + let s = schema; + for (let i = 0; i < 10 && isObj(s); i++) { + if (s.properties || s.items) break; + const present = ["allOf", "oneOf", "anyOf"] + .map((k) => (Array.isArray(s[k]) ? s[k].filter((o) => !isNullSchema(o)) : null)) + .filter(Boolean); + if (present.length === 1 && present[0].length === 1) s = present[0][0]; + else break; + } + return s; +} + +function admonitionLabel(type) { + return `**${type[0].toUpperCase()}${type.slice(1).toLowerCase()}:**`; +} + +function cleanDescription(text) { + return String(text) + .replace(/^\s*:::(\w+)/gm, (_, type) => admonitionLabel(type)) + .replace(/^\s*:::\s*$/gm, "") + .replace(/\s*\n\s*/g, " ") + .replace(/\s{2,}/g, " ") + .trim(); +} + +function endSentence(text) { + return /[.!?:]$/.test(text) ? text : `${text}.`; +} + +function code(v) { + return `\`${typeof v === "string" ? v : JSON.stringify(v)}\``; +} + +function mapValue(m) { + const value = m.additionalProperties; + return isObj(value) && Object.keys(value).length ? value : null; +} + +function hasStructure(m) { + return Boolean(m.properties.size || m.oneOf || m.anyOf || mapValue(m)); +} + +function scalarLabel(option) { + const om = merge(option); + if (hasStructure(om) || om.types.includes("object") || om.enum || om.description) return null; + if (om.items && hasStructure(merge(om.items))) return null; + if (om.const !== undefined) return code(om.const); + return typeLabel(om) || null; +} + +function typeLabel(m) { + const value = mapValue(m); + if (value && !m.properties.size) return `map of ${typeLabel(merge(value)) || "any"}`; + if (m.types.includes("array")) { + if (!m.items) return "array"; + const im = merge(m.items); + const inner = im.types.length ? im.types.join(" or ") : im.oneOf || im.anyOf ? "object" : "any"; + return `array of ${inner}`; + } + return m.types.join(" or "); +} + +function constFields(m) { + return [...m.properties] + .map(([name, prop]) => [name, merge(prop).const]) + .filter(([, value]) => value !== undefined) + .map(([name, value]) => `${name}: ${JSON.stringify(value)}`); +} + +const MAX_LABEL_FIELDS = 3; + +function optionLabels(options) { + const merged = options.map((opt) => merge(opt)); + return options.map((opt, i) => { + const om = merged[i]; + if (om.const !== undefined) return code(om.const); + const consts = constFields(om); + if (consts.length) return consts.map(code).join(", "); + if (opt.title || om.title) return opt.title || om.title; + const names = [...om.properties.keys()]; + if (!names.length && !om.types.length && om.required.size) return `requires ${[...om.required].map(code).join(", ")}`; + if (!names.length) return typeLabel(om) || "any"; + const own = names.filter((n) => !merged.some((other, j) => j !== i && other.properties.has(n))); + return `object with ${(own.length ? own : names).slice(0, MAX_LABEL_FIELDS).map(code).join(", ")}`; + }); +} + +function sharesFieldNames(options) { + const seen = new Set(); + for (const opt of options) { + for (const name of merge(opt).properties.keys()) { + if (seen.has(name)) return true; + seen.add(name); + } + } + return false; +} + +function describe(sentences, hasDescription) { + if (!sentences.length) return ""; + return hasDescription ? `: ${sentences.join(" ")}` : `. ${sentences.join(" ")}`; +} + +function descriptionSentences(m) { + const sentences = []; + if (m.description) sentences.push(endSentence(cleanDescription(m.description))); + const enumVals = Array.isArray(m.enum) ? m.enum : m.items ? merge(m.items).enum : null; + if (Array.isArray(enumVals) && enumVals.length) sentences.push(`One of: ${enumVals.map(code).join(", ")}.`); + return sentences; +} + +function renderFields(schema, ctx, depth, indent, path) { + const m = merge(schema); + const here = path[path.length - 1]; + const lines = []; + const pad = " ".repeat(indent); + for (const [name, prop] of m.properties) { + lines.push(...renderField(name, prop, { required: m.required.has(name) }, ctx, depth, indent, path)); + } + const value = mapValue(m); + if (value) { + const keyPattern = isObj(m.propertyNames) ? m.propertyNames.pattern : undefined; + lines.push(...renderField("", value, { keyPattern }, ctx, depth, indent, path)); + } + const hasFields = lines.length > 0; + for (const kw of ["oneOf", "anyOf"]) { + if (!m[kw]) continue; + lines.push(hasFields ? `${pad}- One of these shapes:` : `${pad}One of:`); + const optionIndent = hasFields ? indent + 1 : indent; + const optionPad = " ".repeat(optionIndent); + const labels = optionLabels(m[kw]); + const disambiguate = sharesFieldNames(m[kw]); + m[kw].forEach((opt, i) => { + const om = merge(opt); + lines.push(`${optionPad}- Option ${i + 1} (${labels[i]})${describe(descriptionSentences(om), Boolean(om.description))}`); + const option = disambiguate ? labels[i].replace(/`/g, "") : here.option; + lines.push(...renderNested(opt, here.name, here.label, ctx, depth, optionIndent + 1, path, option)); + }); + } + return lines; +} + +// Nested lines for `target` (already unwrapped from arrays), or [] if it has no structure. +function renderNested(target, name, label, ctx, depth, indent, path, option) { + if (!hasStructure(merge(target))) return []; + const key = canon(target); + const pad = " ".repeat(indent); + const onPath = path.find((p) => p.key === key); + if (onPath) return [`${pad}- (recursive: same shape as ${code(onPath.name || name || "parent")})`]; + if (ctx.seen.has(key)) { + const first = ctx.seen.get(key); + const under = first.option ? ` under option ${code(first.option)}` : ""; + return [`${pad}- (same shape as ${code(first.label)}${under} above)`]; + } + if (depth >= ctx.maxDepth) return [`${pad}- ${OMITTED}`]; + if (label) ctx.seen.set(key, { label, option }); + return renderFields(target, ctx, depth + 1, indent, [...path, { key, name, label, option }]); +} + +function renderField(name, prop, { required = false, keyPattern }, ctx, depth, indent, path) { + const lines = []; + const m = merge(prop); + const meta = []; + const t = typeLabel(m); + if (t) meta.push(t); + if (required) meta.push("required"); + if (m.nullable) meta.push("nullable"); + let head = `${" ".repeat(indent)}- ${code(name)}`; + if (meta.length) head += ` (${meta.join(", ")})`; + + const sentences = descriptionSentences(m); + if (m.const !== undefined) sentences.push(`Always ${code(m.const)}.`); + if (m.default !== undefined) sentences.push(`Default: ${code(m.default)}.`); + if (m.format) sentences.push(`Format: ${code(m.format)}.`); + if (keyPattern) sentences.push(`Key pattern: ${code(keyPattern)}.`); + + lines.push(head + describe(sentences, Boolean(m.description))); + + const target = m.types.includes("array") && m.items ? m.items : prop; + const { label: parent, option } = path[path.length - 1]; + const label = parent ? `${parent}.${name}` : name; + lines.push(...renderNested(target, name, label, ctx, depth, indent + 1, path, option)); + return lines; +} + +function rootBody(schema, m, ctx) { + if (m.types.includes("array") && !hasStructure(m)) { + const items = m.items ? renderFields(m.items, ctx, 1, 0, [{ key: canon(m.items), name: null, label: "" }]) : []; + return items.length ? `Array of:\n\n${items.join("\n")}` : `${typeLabel(m).replace(/^a/, "A")}.`; + } + const fields = renderFields(schema, ctx, 1, 0, [{ key: canon(schema), name: null, label: "" }]); + if (fields.length) return fields.join("\n"); + if (m.types.includes("object")) return m.additionalProperties === false ? "Empty JSON object." : "JSON object (free-form)."; + return m.types.length ? `Type: ${typeLabel(m)}.` : ""; +} + +function renderSchemaFields(schema, { maxDepth = 6 } = {}) { + if (!isObj(schema)) return ""; + const m = merge(schema); + const description = m.description ? endSentence(cleanDescription(m.description)) : ""; + const body = rootBody(schema, m, { maxDepth, seen: new Map() }); + return [description, body].filter(Boolean).join("\n\n"); +} + +function canReturnNotOk(schema) { + const m = merge(schema); + return [schema, ...(m.oneOf || []), ...(m.anyOf || [])].some((option) => { + const ok = merge(option).properties.get("ok"); + return ok !== undefined && merge(ok).const === false; + }); +} + +module.exports = { renderSchemaFields, canReturnNotOk, admonitionLabel }; diff --git a/plugins/llms-markdown/api/render-schema.test.js b/plugins/llms-markdown/api/render-schema.test.js new file mode 100644 index 00000000..c2f5328c --- /dev/null +++ b/plugins/llms-markdown/api/render-schema.test.js @@ -0,0 +1,362 @@ +const test = require("node:test"); +const assert = require("node:assert"); +const path = require("path"); +const { renderSchemaFields } = require("./render-schema"); +const si = require("./spec-index"); + +const siteDir = path.resolve(__dirname, "../../.."); + +test("allOf merges properties and required markers", () => { + const out = renderSchemaFields({ + allOf: [ + { type: "object", required: ["a"], properties: { a: { type: "string" } } }, + { type: "object", required: ["b"], properties: { b: { type: "integer" } } }, + ], + }); + assert.match(out, /^- `a` \(string, required\)/m); + assert.match(out, /^- `b` \(integer, required\)/m); +}); + +test("enum, default, format, description, nullable", () => { + const out = renderSchemaFields({ + type: "object", + properties: { + kind: { type: "string", enum: ["a", "b"], default: "a", description: "Kind." }, + at: { type: "string", format: "date-time", nullable: true }, + n: { type: ["integer", "null"] }, + }, + }); + assert.match(out, /`kind` \(string\): Kind\. One of: `a`, `b`\. Default: `a`\./); + assert.match(out, /`at` \(string, nullable\)\. Format: `date-time`\./); + assert.match(out, /`n` \(integer, nullable\)/); +}); + +test("array of objects nests item fields", () => { + const out = renderSchemaFields({ + type: "object", + properties: { + owners: { type: "array", items: { type: "object", properties: { id: { type: "integer" } } } }, + tags: { type: "array", items: { type: "string" } }, + }, + }); + assert.match(out, /^- `owners` \(array of object\)/m); + assert.match(out, /^ {2}- `id` \(integer\)/m); + assert.match(out, /`tags` \(array of string\)/); +}); + +test("oneOf renders labelled options", () => { + const out = renderSchemaFields({ + type: "object", + properties: { + v: { + oneOf: [ + { title: "Num", type: "object", properties: { x: { type: "number" } } }, + { type: "string" }, + ], + }, + }, + }); + assert.match(out, /^ {2}One of:/m); + assert.match(out, /^ {2}- Option 1 \(Num\)/m); + assert.match(out, /^ {4}- `x` \(number\)/m); + assert.match(out, /^ {2}- Option 2 \(string\)/m); +}); + +test("self-referencing schema terminates", () => { + const node = { type: "object", properties: {} }; + node.properties.children = { type: "array", items: node }; + const out = renderSchemaFields(node); + assert.match(out, /recursive: same shape as `children`/); +}); + +test("depth cap emits omission note", () => { + const out = renderSchemaFields( + { + type: "object", + properties: { + a: { type: "object", properties: { b: { type: "object", properties: { c: { type: "string" } } } } }, + }, + }, + { maxDepth: 2 } + ); + assert.match(out, /nested fields omitted; see the OpenAPI spec/); + assert.ok(!out.includes("`c`")); +}); + +test("descriptions are cleaned", () => { + const out = renderSchemaFields({ + type: "object", + properties: { x: { type: "string", description: "x\n line two" } }, + }); + assert.ok(!out.includes("\nline")); + assert.match(out, /x line two/); +}); + +test("real ExperimentInput includes unit_type_id and owners", async () => { + const specs = await si.loadDereferencedSpecs(siteDir); + const out = renderSchemaFields(specs.get("webConsole").components.schemas.ExperimentInput); + assert.match(out, /`unit_type_id`/); + assert.match(out, /`owners`/); +}); + +test("schema's own description/default/format/enum beat allOf members", () => { + const out = renderSchemaFields({ + type: "object", + properties: { + f: { + description: "Specific", + default: "own", + format: "own-fmt", + enum: ["own"], + allOf: [{ type: "string", description: "Generic", default: "gen", format: "gen-fmt", enum: ["gen"] }], + }, + }, + }); + assert.match(out, /`f` \(string\): Specific\. One of: `own`\. Default: `own`\. Format: `own-fmt`\./); + assert.ok(!out.includes("Generic") && !out.includes("gen")); +}); + +test("allOf nested inside a property and inside array items", () => { + const out = renderSchemaFields({ + type: "object", + properties: { + p: { allOf: [{ properties: { a: { type: "string" } } }, { properties: { b: { type: "string" } } }] }, + list: { + type: "array", + items: { allOf: [{ properties: { c: { type: "string" } } }, { properties: { d: { type: "string" } } }] }, + }, + }, + }); + assert.match(out, /^ {2}- `a` \(string\)/m); + assert.match(out, /^ {2}- `b` \(string\)/m); + assert.match(out, /^- `list` \(array of object\)/m); + assert.match(out, /^ {2}- `c` \(string\)/m); + assert.match(out, /^ {2}- `d` \(string\)/m); +}); + +test("array whose item is an allOf of scalar + constraints", () => { + const out = renderSchemaFields({ + type: "object", + properties: { ids: { type: "array", items: { allOf: [{ type: "integer" }, { format: "int64" }] } } }, + }); + assert.match(out, /`ids` \(array of integer\)/); +}); + +test("null alternative in anyOf/oneOf folds into nullable", () => { + const out = renderSchemaFields({ + type: "object", + properties: { + one: { anyOf: [{ type: "string" }, { type: "null" }] }, + two: { oneOf: [{ type: "string" }, { type: "integer" }, { type: "null" }] }, + }, + }); + assert.match(out, /^- `one` \(string, nullable\)$/m); + assert.ok(!out.includes("Option 3") && !out.includes("(any)")); + assert.match(out, /^- `two` \(string or integer, nullable\)$/m); + assert.ok(!out.includes("One of:")); +}); + +test("required inside an option is honoured", () => { + const out = renderSchemaFields({ + oneOf: [ + { title: "A", type: "object", required: ["x"], properties: { x: { type: "string" }, y: { type: "string" } } }, + { title: "B", type: "object", properties: { z: { type: "string" } } }, + ], + }); + assert.match(out, /^ {2}- `x` \(string, required\)/m); + assert.match(out, /^ {2}- `y` \(string\)$/m); + assert.match(out, /^- Option 2 \(B\)/m); +}); + +test("same schema object is rendered in full only once", () => { + const user = { type: "object", properties: { id: { type: "integer" }, email: { type: "string" } } }; + const out = renderSchemaFields({ + type: "object", + properties: { + owner: user, + editors: { type: "array", items: user }, + reviewer: { anyOf: [user, { type: "null" }] }, + wrapped: { description: "w", allOf: [user] }, + }, + }); + assert.strictEqual(out.split("`email`").length - 1, 1); + assert.strictEqual(out.split("(same shape as `owner` above)").length - 1, 3); +}); + +test("every schema in both real specs renders without throwing", async () => { + const specs = await si.loadDereferencedSpecs(siteDir); + const sizes = []; + for (const [key, spec] of specs) { + for (const [name, schema] of Object.entries((spec.components && spec.components.schemas) || {})) { + const out = renderSchemaFields(schema); + assert.strictEqual(typeof out, "string"); + sizes.push([`${key}:${name}`, out.length]); + } + } + sizes.sort((a, b) => b[1] - a[1]); + console.log("largest rendered schemas:", JSON.stringify(sizes.slice(0, 5))); + assert.ok(sizes.length > 100); + const input = sizes.find(([n]) => n === "webConsole:ExperimentInput"); + assert.ok(input[1] < 40000, `ExperimentInput is ${input[1]} chars`); +}); + +test("const renders as Always and labels the options it discriminates", () => { + const out = renderSchemaFields({ + oneOf: [ + { type: "object", required: ["ok"], properties: { ok: { const: true }, id: { type: "integer" } } }, + { type: "object", required: ["ok"], properties: { ok: { const: false } } }, + ], + }); + assert.match(out, /^- Option 1 \(`ok: true`\)$/m); + assert.match(out, /^- Option 2 \(`ok: false`\)$/m); + assert.match(out, /^ {2}- `ok` \(boolean, required\)\. Always `true`\.$/m); + assert.match(out, /^ {2}- `ok` \(boolean, required\)\. Always `false`\.$/m); +}); + +test("a root array renders Array of: and the item fields", () => { + const out = renderSchemaFields({ + type: "array", + items: { type: "object", properties: { id: { type: "integer" }, message: { type: "string" } } }, + }); + assert.match(out, /^Array of:\n\n- `id` \(integer\)\n- `message` \(string\)$/); + assert.strictEqual(renderSchemaFields({ type: "array", items: { type: "string" } }), "Array of string."); +}); + +test("a free-form root renders its description and JSON object (free-form)", () => { + assert.strictEqual( + renderSchemaFields({ type: "object", additionalProperties: true, description: "Usage totals" }), + "Usage totals.\n\nJSON object (free-form).", + ); + assert.strictEqual(renderSchemaFields({ type: "object" }), "JSON object (free-form)."); +}); + +test("a root description precedes the fields", () => { + const out = renderSchemaFields({ type: "object", description: "The thing.", properties: { a: { type: "string" } } }); + assert.strictEqual(out, "The thing.\n\n- `a` (string)"); +}); + +test("additionalProperties renders as a map from the key pattern to the value shape", () => { + const out = renderSchemaFields({ + type: "object", + properties: { + values: { + type: "object", + propertyNames: { pattern: "^[0-9]+$" }, + additionalProperties: { type: "object", properties: { v: { type: "string" } } }, + }, + scores: { type: "object", additionalProperties: { type: "number" } }, + }, + }); + assert.match(out, /^- `values` \(map of object\)$/m); + assert.match(out, /^ {2}- `` \(object\)\. Key pattern: `\^\[0-9\]\+\$`\.$/m); + assert.match(out, /^ {4}- `v` \(string\)$/m); + assert.match(out, /^- `scores` \(map of number\)$/m); + assert.match(out, /^ {2}- `` \(number\)$/m); +}); + +test("back-references name fields, not options", () => { + const user = { type: "object", properties: { id: { type: "integer" } } }; + const out = renderSchemaFields({ + oneOf: [ + { type: "object", properties: { experiment: { type: "object", properties: { owner: user } } } }, + { type: "object", properties: { other: user } }, + ], + }); + assert.ok(out.includes("(same shape as `experiment.owner` above)"), out); + assert.ok(!out.includes("(option"), out); +}); + +test("scalar unions render inline", () => { + const out = renderSchemaFields({ + type: "object", + properties: { seed: { description: "Seed.", oneOf: [{ type: "integer" }, { type: "string" }] } }, + }); + assert.strictEqual(out, "- `seed` (integer or string): Seed."); +}); + +test("admonitions in field descriptions keep their label", () => { + const out = renderSchemaFields({ + type: "object", + properties: { x: { type: "string", description: "Values.\n:::caution\nOrder may vary.\n:::" } }, + }); + assert.match(out, /`x` \(string\): Values\. \*\*Caution:\*\* Order may vary\.$/m); +}); + +test("object options are labelled by their distinguishing fields", () => { + const out = renderSchemaFields({ + oneOf: [ + { type: "object", properties: { id: { type: "integer" }, unit_type_id: { type: "integer" } } }, + { type: "object", properties: { id: { type: "integer" }, name: { type: "string" }, display_name: { type: "string" }, extra: { type: "string" } } }, + { type: "object", properties: { id: { type: "integer" } } }, + ], + }); + assert.match(out, /^- Option 1 \(object with `unit_type_id`\)$/m); + assert.match(out, /^- Option 2 \(object with `name`, `display_name`, `extra`\)$/m); + assert.match(out, /^- Option 3 \(object with `id`\)$/m); +}); + +test("back-references name the option when options share a field name", () => { + const e1 = { type: "object", properties: { p: { type: "string" } } }; + const e2 = { type: "object", properties: { q: { type: "string" } } }; + const out = renderSchemaFields({ + type: "object", + properties: { + r: { + oneOf: [ + { type: "object", properties: { experiment: e1, id: { type: "integer" } } }, + { type: "object", properties: { experiment: e2, name: { type: "string" } } }, + ], + }, + again: e2, + }, + }); + assert.ok(out.includes("(same shape as `r.experiment` under option `object with name` above)"), out); +}); + +test("scalar options with an enum or a description stay as options", () => { + const out = renderSchemaFields({ + type: "object", + properties: { v: { oneOf: [{ type: "string", enum: ["a", "b"] }, { type: "integer", description: "Count" }] } }, + }); + assert.match(out, /^ {2}One of:$/m); + assert.match(out, /^ {2}- Option 1 \(string\)\. One of: `a`, `b`\.$/m); + assert.match(out, /^ {2}- Option 2 \(integer\): Count\.$/m); +}); + +test("empty-object and scalar roots", () => { + assert.strictEqual(renderSchemaFields({ type: "object", additionalProperties: false }), "Empty JSON object."); + assert.strictEqual(renderSchemaFields({ type: "string", format: "binary" }), "Type: string."); +}); + +test("a union next to fields is its own list item with nested options", () => { + const out = renderSchemaFields({ + type: "object", + properties: { a: { type: "string" } }, + oneOf: [ + { type: "object", properties: { b: { type: "string" } } }, + { type: "object", properties: { c: { type: "integer" } } }, + ], + }); + assert.strictEqual( + out, + [ + "- `a` (string)", + "- One of these shapes:", + " - Option 1 (object with `b`)", + " - `b` (string)", + " - Option 2 (object with `c`)", + " - `c` (integer)", + ].join("\n"), + ); +}); + +test("options that only list required fields say which fields they require", () => { + const out = renderSchemaFields({ + type: "object", + properties: { items: { type: "array", items: { type: "string" } }, page: { type: "integer" }, id: { type: "integer" } }, + anyOf: [{ required: ["items", "page"] }, { required: ["id"] }], + }); + assert.match(out, /^ {2}- Option 1 \(requires `items`, `page`\)$/m); + assert.match(out, /^ {2}- Option 2 \(requires `id`\)$/m); + assert.ok(!out.includes("(any)"), out); +}); diff --git a/plugins/llms-markdown/api/spec-index.js b/plugins/llms-markdown/api/spec-index.js new file mode 100644 index 00000000..983debd8 --- /dev/null +++ b/plugins/llms-markdown/api/spec-index.js @@ -0,0 +1,126 @@ +const fs = require("fs"); +const path = require("path"); +const yaml = require("js-yaml"); + +const METHODS = ["get", "put", "post", "delete", "patch", "head", "options", "trace"]; + +const SPECS = [ + { + key: "collector", + source: "api-spec.yaml", + publishedPath: "/openapi/collector-api.yaml", + docsDir: "/docs/APIs-and-SDKs/SDK-API", + }, + { + key: "webConsole", + source: "node_modules/@absmartly/api-mocks/openapi/openapi.bundle.yaml", + publishedPath: "/openapi/web-console-api.yaml", + docsDir: "/docs/APIs-and-SDKs/Web-Console-API", + }, +]; + +function readSpec(siteDir, spec) { + return yaml.load(fs.readFileSync(path.resolve(siteDir, spec.source), "utf8")); +} + +function loadRawSpecsSync(siteDir) { + return new Map(SPECS.map((spec) => [spec.key, readSpec(siteDir, spec)])); +} + +function listOperations(rawSpecs) { + const ops = []; + for (const { key } of SPECS) { + const doc = rawSpecs.get(key); + for (const [p, item] of Object.entries((doc && doc.paths) || {})) { + for (const m of METHODS) { + const op = item[m]; + if (!op) continue; + ops.push({ + specKey: key, + method: m.toUpperCase(), + path: p, + operationId: op.operationId, + summary: op.summary, + description: op.description, + op, + pathParameters: Array.isArray(item.parameters) ? item.parameters : [], + }); + } + } + } + return ops; +} + +// The dereferenced result may contain object cycles (circular refs). +async function loadDereferencedSpecs(siteDir) { + const { dereference } = await import("@apidevtools/json-schema-ref-parser"); + const specs = new Map(); + for (const spec of SPECS) { + specs.set( + spec.key, + await dereference(readSpec(siteDir, spec), { dereference: { circular: true } }), + ); + } + return specs; +} + +function normaliseEndpointPath(displayPath) { + return displayPath.replace(/:([A-Za-z_][A-Za-z0-9_]*)/g, "{$1}"); +} + +function readApiPages(siteDir) { + const pages = new Map(); + for (const spec of SPECS) { + const dir = path.join(siteDir, spec.docsDir); + for (const file of fs.readdirSync(dir)) { + if (!file.endsWith(".api.mdx")) continue; + const text = fs.readFileSync(path.join(dir, file), "utf8"); + const id = (text.match(/^id:\s*["']?([^"'\n]+?)["']?\s*$/m) || [])[1]; + const method = (text.match(/method=\{"([a-z]+)"\}/) || [])[1]; + const p = (text.match(/path=\{"([^"]+)"\}/) || [])[1]; + if (!id || !method || !p) continue; + pages.set(`${method.toUpperCase()} ${p}`, `${spec.docsDir}/${id}`); + } + } + return pages; +} + +function buildOperationIndex(specs, pages, siteUrl) { + const index = new Map(); + for (const o of listOperations(specs)) { + const key = `${o.method} ${o.path}`; + if (index.has(key)) throw new Error(`Duplicate operation ${key}`); + const route = pages.get(key); + if (!route) throw new Error(`No generated API page for ${key}`); + if (!o.summary) throw new Error(`No summary for ${key}`); + const spec = SPECS.find((s) => s.key === o.specKey); + index.set(key, { + ...o, + publishedUrl: `${siteUrl}${spec.publishedPath}`, + pageUrl: `${siteUrl}${route}`, + title: o.summary, + }); + } + return index; +} + +function assertAllEndpointsReplaced(index, replacedKeys) { + if (replacedKeys.size >= index.size) return; + const missing = [...index.keys()].filter((k) => !replacedKeys.has(k)); + throw new Error( + `Only ${replacedKeys.size} of ${index.size} API endpoint pages got the spec-derived Markdown ` + + `(is the openapi__method-endpoint markup unchanged?). Missing: ${missing.slice(0, 5).join(", ")}` + + (missing.length > 5 ? ", …" : ""), + ); +} + +module.exports = { + SPECS, + loadRawSpecsSync, + listOperations, + loadDereferencedSpecs, + normaliseEndpointPath, + readApiPages, + buildOperationIndex, + assertAllEndpointsReplaced, +}; diff --git a/plugins/llms-markdown/api/spec-index.test.js b/plugins/llms-markdown/api/spec-index.test.js new file mode 100644 index 00000000..d15d714e --- /dev/null +++ b/plugins/llms-markdown/api/spec-index.test.js @@ -0,0 +1,99 @@ +const test = require("node:test"); +const assert = require("node:assert"); +const fs = require("fs"); +const path = require("path"); +const si = require("./spec-index"); + +const siteDir = path.resolve(__dirname, "../../.."); + +test("listOperations covers both real specs without duplicates", () => { + const ops = si.listOperations(si.loadRawSpecsSync(siteDir)); + const web = ops.filter((o) => o.specKey === "webConsole"); + const collector = ops.filter((o) => o.specKey === "collector"); + // Sanity bounds rather than exact counts, so api-mocks upgrades don't break the test. + assert.ok(web.length >= 250, `${web.length} Web Console operations`); + assert.ok(web.some((o) => o.method === "HEAD" && o.path === "/files/{usage}/{id}/{action}/{filename}")); + assert.ok(collector.length >= 5, `${collector.length} Collector operations`); + const keys = ops.map((o) => `${o.method} ${o.path}`); + assert.strictEqual(new Set(keys).size, keys.length); + for (const o of ops) assert.match(o.method, /^(GET|PUT|POST|DELETE|PATCH|HEAD|OPTIONS|TRACE)$/); +}); + +const keyOf = (o) => `${o.method} ${o.path}`; +const pagesFor = (specs) => + new Map(si.listOperations(specs).map((o) => [keyOf(o), `/docs/test/${o.operationId}`])); +const indexFor = (specs, siteUrl = "https://docs.absmartly.com") => si.buildOperationIndex(specs, pagesFor(specs), siteUrl); + +test("buildOperationIndex builds complete, dereferenced entries", async () => { + const index = indexFor(await si.loadDereferencedSpecs(siteDir)); + const entry = index.get("PUT /goals/{goalId}/archive"); + assert.strictEqual(entry.operationId, "ArchiveGoal"); + assert.strictEqual(entry.specKey, "webConsole"); + assert.strictEqual(entry.publishedUrl, "https://docs.absmartly.com/openapi/web-console-api.yaml"); + assert.strictEqual(entry.pageUrl, "https://docs.absmartly.com/docs/test/ArchiveGoal"); + assert.strictEqual(entry.title, "Goal archive"); + assert.ok(!JSON.stringify(entry.op.parameters || []).includes('"$ref"')); +}); + +test("buildOperationIndex uses the given site URL", async () => { + const entry = indexFor(await si.loadDereferencedSpecs(siteDir), "https://preview.example").get("PUT /goals/{goalId}/archive"); + assert.strictEqual(entry.publishedUrl, "https://preview.example/openapi/web-console-api.yaml"); + assert.strictEqual(entry.pageUrl, "https://preview.example/docs/test/ArchiveGoal"); +}); + +const tinySpecs = (collectorPaths, webConsolePaths) => + new Map([ + ["collector", { paths: collectorPaths }], + ["webConsole", { paths: webConsolePaths }], + ]); +const op = { operationId: "x", summary: "s" }; + +test("duplicate method+path across specs throws", () => { + const specs = tinySpecs({ "/a": { get: op } }, { "/a": { get: op } }); + assert.throws(() => indexFor(specs), /Duplicate operation/); +}); + +test("buildOperationIndex throws for an operation without a page or a summary", () => { + const specs = tinySpecs({}, { "/a": { get: op } }); + assert.throws(() => si.buildOperationIndex(specs, new Map(), "https://x"), /No generated API page for GET \/a/); + assert.throws(() => indexFor(tinySpecs({}, { "/a": { get: { operationId: "x" } } })), /No summary for GET \/a/); +}); + +test("entries carry path-item parameters", async () => { + const index = indexFor(await si.loadDereferencedSpecs(siteDir)); + const entry = index.get("GET /experiments/{experimentId}"); + assert.ok(entry.pathParameters.some((p) => p.name === "experimentId" && p.in === "path")); + assert.deepStrictEqual(index.get("GET /healthy").pathParameters, []); +}); + +test("normaliseEndpointPath converts colon params", () => { + assert.strictEqual( + si.normaliseEndpointPath("/goals/:goalId/archive"), + "/goals/{goalId}/archive", + ); +}); + +test("assertAllEndpointsReplaced names the operations whose pages were not replaced", () => { + const index = new Map([["GET /a", {}], ["GET /b", {}]]); + assert.throws(() => si.assertAllEndpointsReplaced(index, new Set()), /0 of 2/); + assert.throws(() => si.assertAllEndpointsReplaced(index, new Set(["GET /a"])), /1 of 2[\s\S]*GET \/b/); + si.assertAllEndpointsReplaced(index, new Set(["GET /a", "GET /b"])); +}); + +// Generated API pages (docs/…/*.api.mdx) are gitignored; `yarn gen:api` creates them. +function generatedPagesPresent() { + return si.SPECS.every((spec) => { + const dir = path.join(siteDir, spec.docsDir); + return fs.existsSync(dir) && fs.readdirSync(dir).some((f) => f.endsWith(".api.mdx")); + }); +} + +test("readApiPages finds a generated page for every operation", async (t) => { + if (!generatedPagesPresent()) return t.skip("generated API pages absent: run yarn gen:api"); + const pages = si.readApiPages(siteDir); + assert.strictEqual(pages.get("PUT /goals/{goalId}/archive"), "/docs/APIs-and-SDKs/Web-Console-API/archive-goal"); + for (const o of si.listOperations(si.loadRawSpecsSync(siteDir))) { + const docsDir = si.SPECS.find((s) => s.key === o.specKey).docsDir; + assert.ok(pages.get(keyOf(o))?.startsWith(`${docsDir}/`), keyOf(o)); + } +}); diff --git a/plugins/llms-markdown/llms-txt-wrapper.js b/plugins/llms-markdown/llms-txt-wrapper.js new file mode 100644 index 00000000..8266017b --- /dev/null +++ b/plugins/llms-markdown/llms-txt-wrapper.js @@ -0,0 +1,84 @@ +const { createRequire } = require("module"); +const { + loadDereferencedSpecs, + readApiPages, + buildOperationIndex, + assertAllEndpointsReplaced, +} = require("./api/spec-index"); +const rehypeApiMarkdown = require("./rehype-api-markdown"); +const { postProcessLlms } = require("./postprocess-llms"); + +const INNER = "@signalwire/docusaurus-plugin-llms-txt"; + +// Loaded with jiti, as Docusaurus does: the package's ESM build has extensionless imports Node rejects. +let innerModule; +function loadInnerModule() { + if (!innerModule) { + const jiti = createRequire(require.resolve("@docusaurus/utils"))("jiti"); + innerModule = jiti(__filename, { interopDefault: true })(require.resolve(INNER)); + } + return innerModule; +} + +async function loadApiIndex(siteDir, siteUrl) { + return buildOperationIndex(await loadDereferencedSpecs(siteDir), readApiPages(siteDir), siteUrl); +} + +function withApiMarkdown(innerOptions, apiMarkdownOptions) { + const content = innerOptions.content ?? {}; + return { + ...innerOptions, + content: { + ...content, + beforeDefaultRehypePlugins: [ + [rehypeApiMarkdown, apiMarkdownOptions], + ...(content.beforeDefaultRehypePlugins ?? []), + ], + }, + }; +} + +function createLlmsTxtWrapper({ loadInner, loadApiIndex, postProcess }) { + return async function llmsTxtWrapper(context, options) { + const { postProcess: postProcessOptions, ...innerOptions } = options; + const innerFactory = await loadInner(); + // The inner `docusaurus llms-txt` CLI command can't load the API index, so it would write sparse API pages. + const { extendCli, ...inner } = await innerFactory(context, innerOptions); + const siteUrl = context.siteConfig.url; + return { + ...inner, + async postBuild(props) { + const index = await loadApiIndex(props.siteDir || context.siteDir, siteUrl); + const replaced = new Set(); + const converter = await innerFactory( + context, + withApiMarkdown(innerOptions, { index, siteUrl, onReplaced: (key) => replaced.add(key) }), + ); + await converter.postBuild(props); + assertAllEndpointsReplaced(index, replaced); + await postProcess(props.outDir, postProcessOptions, index, siteUrl); + }, + }; + }; +} + +function createValidateOptions(getInnerValidate) { + return function validateOptions({ options, validate }) { + const { postProcess, ...innerOptions } = options; + const validated = getInnerValidate()({ options: innerOptions, validate }); + return { ...validated, postProcess }; + }; +} + +const llmsTxtWrapper = createLlmsTxtWrapper({ + loadInner: async () => { + const inner = loadInnerModule(); + return inner.default ?? inner; + }, + loadApiIndex, + postProcess: postProcessLlms, +}); + +module.exports = llmsTxtWrapper; +module.exports.validateOptions = createValidateOptions(() => loadInnerModule().validateOptions); +module.exports._internal = { createLlmsTxtWrapper, createValidateOptions }; diff --git a/plugins/llms-markdown/llms-txt-wrapper.test.js b/plugins/llms-markdown/llms-txt-wrapper.test.js new file mode 100644 index 00000000..483d07ba --- /dev/null +++ b/plugins/llms-markdown/llms-txt-wrapper.test.js @@ -0,0 +1,112 @@ +const test = require("node:test"); +const assert = require("node:assert"); +const { createLlmsTxtWrapper, createValidateOptions } = require("./llms-txt-wrapper")._internal; + +const rehypeApiMarkdown = require("./rehype-api-markdown"); +const tick = () => new Promise((r) => setTimeout(r, 5)); +const cleanup = () => {}; + +function fakeInner(calls, created, replaceKeys = []) { + return async () => (context, options) => { + created.push(options); + return { + name: "inner", + loadContent: () => "inner-content", + extendCli: () => {}, + async postBuild() { + calls.push("inner:start"); + const [plugin, apiOptions] = options.content.beforeDefaultRehypePlugins[0]; + assert.strictEqual(plugin, rehypeApiMarkdown); + for (const key of replaceKeys) apiOptions.onReplaced(key); + await tick(); + calls.push("inner:end"); + }, + }; + }; +} + +const INDEX = new Map([["GET /a", { pageUrl: "https://x/a" }]]); + +test("postBuild loads the API index, converts pages with it, then post-processes with it", async () => { + const calls = []; + const created = []; + const wrapper = createLlmsTxtWrapper({ + loadInner: fakeInner(calls, created, ["GET /a"]), + loadApiIndex: async (siteDir, siteUrl) => { + await tick(); + calls.push(`index:${siteDir}:${siteUrl}`); + return INDEX; + }, + postProcess: async (outDir, options, index, siteUrl) => { + assert.strictEqual(index, INDEX); + calls.push(`post:${outDir}:${options.marker}:${siteUrl}`); + }, + }); + const options = { + depth: 2, + postProcess: { marker: "m" }, + content: { beforeDefaultRehypePlugins: [cleanup] }, + }; + const plugin = await wrapper({ siteDir: "/site", siteConfig: { url: "https://site" } }, options); + assert.deepStrictEqual(created[0], { depth: 2, content: { beforeDefaultRehypePlugins: [cleanup] } }); + assert.strictEqual(plugin.name, "inner"); + assert.strictEqual(plugin.loadContent(), "inner-content"); + assert.strictEqual(plugin.extendCli, undefined); + await plugin.postBuild({ outDir: "/out" }); + assert.deepStrictEqual(calls, ["index:/site:https://site", "inner:start", "inner:end", "post:/out:m:https://site"]); + const [[plugin0, apiOptions], next] = created[1].content.beforeDefaultRehypePlugins; + assert.strictEqual(plugin0, rehypeApiMarkdown); + assert.strictEqual(apiOptions.index, INDEX); + assert.strictEqual(apiOptions.siteUrl, "https://site"); + assert.strictEqual(next, cleanup); +}); + +test("postBuild fails when API pages were not all replaced", async () => { + let postProcessed = false; + const wrapper = createLlmsTxtWrapper({ + loadInner: fakeInner([], []), + loadApiIndex: async () => INDEX, + postProcess: async () => { + postProcessed = true; + }, + }); + const plugin = await wrapper({ siteDir: "/site", siteConfig: { url: "https://site" } }, {}); + await assert.rejects(plugin.postBuild({ outDir: "/out" }), /Only 0 of 1[\s\S]*GET \/a/); + assert.strictEqual(postProcessed, false); +}); + +test("validateOptions validates without postProcess and keeps it on the result", () => { + let seen; + const validateOptions = createValidateOptions(() => ({ options, validate }) => { + seen = options; + return { ...validate(options), id: "default" }; + }); + const result = validateOptions({ + options: { depth: 2, postProcess: { a: 1 } }, + validate: (o) => ({ ...o, validated: true }), + }); + assert.deepStrictEqual(seen, { depth: 2 }); + assert.deepStrictEqual(result, { depth: 2, validated: true, id: "default", postProcess: { a: 1 } }); +}); + +test("the exported validateOptions runs the real inner validation", () => { + const { validateOptions } = require("./llms-txt-wrapper"); + const { normalizePluginOptions } = require("@docusaurus/utils-validation"); + const result = validateOptions({ + options: { depth: 2, postProcess: { marker: 1 } }, + validate: normalizePluginOptions, + }); + assert.strictEqual(result.depth, 2); + assert.deepStrictEqual(result.postProcess, { marker: 1 }); + assert.throws( + () => validateOptions({ options: { depth: "deep" }, validate: normalizePluginOptions }), + /"depth" must be a number/, + ); +}); + +test("validateOptions passes inner validation errors through", () => { + const validateOptions = createValidateOptions(() => () => { + throw new Error("bad option"); + }); + assert.throws(() => validateOptions({ options: {}, validate: (o) => o }), /bad option/); +}); diff --git a/plugins/llms-markdown/pointer.js b/plugins/llms-markdown/pointer.js new file mode 100644 index 00000000..ea881b57 --- /dev/null +++ b/plugins/llms-markdown/pointer.js @@ -0,0 +1,25 @@ +function encodeUrlPath(url) { + return url.replace(/%(?![0-9A-Fa-f]{2})|[^A-Za-z0-9\-._~!$&'()*+,;=:@/?#%]/gu, (c) => + encodeURIComponent(c), + ); +} + +const POINTER_LEAD = "For AI agents: this page is available as Markdown at "; + +function pointerParts(pageUrl, siteUrl) { + if (!siteUrl) throw new Error("pointerParts: siteUrl is required"); + return { + before: POINTER_LEAD, + markdownUrl: encodeUrlPath(`${pageUrl}.md`), + between: ". The full documentation index is at ", + llmsUrl: `${siteUrl}/llms.txt`, + after: ".", + }; +} + +function pointerLine(pageUrl, siteUrl) { + const p = pointerParts(pageUrl, siteUrl); + return `> ${p.before}${p.markdownUrl}${p.between}${p.llmsUrl}${p.after}`; +} + +module.exports = { pointerLine, pointerParts, encodeUrlPath, POINTER_LEAD }; diff --git a/plugins/llms-markdown/pointer.test.js b/plugins/llms-markdown/pointer.test.js new file mode 100644 index 00000000..826384e9 --- /dev/null +++ b/plugins/llms-markdown/pointer.test.js @@ -0,0 +1,35 @@ +const test = require("node:test"); +const assert = require("node:assert"); +const { encodeUrlPath, pointerParts, pointerLine } = require("./pointer"); + +test("encodeUrlPath percent-encodes spaces and other unsafe characters", () => { + assert.strictEqual( + encodeUrlPath("https://docs.absmartly.com/docs/SSO/Azure SAML Setup"), + "https://docs.absmartly.com/docs/SSO/Azure%20SAML%20Setup", + ); + assert.strictEqual(encodeUrlPath("/docs/a\"bé"), "/docs/a%22b%3Cc%3E%C3%A9"); +}); + +test("encodeUrlPath does not double-encode and keeps URL syntax", () => { + const url = "https://docs.absmartly.com/docs/SSO/Azure%20SAML%20Setup.md#a-b?x=1&y=(2)"; + assert.strictEqual(encodeUrlPath(url), url); + assert.strictEqual(encodeUrlPath("/docs/50%off"), "/docs/50%25off"); + assert.strictEqual(encodeUrlPath(encodeUrlPath("/a b")), "/a%20b"); +}); + +test("the pointer uses the encoded Markdown URL", () => { + const site = "https://docs.absmartly.com"; + const p = pointerParts(`${site}/docs/SSO/Okta SAML Setup`, site); + assert.strictEqual(p.markdownUrl, "https://docs.absmartly.com/docs/SSO/Okta%20SAML%20Setup.md"); + assert.ok(!pointerLine(`${site}/docs/SSO/Okta SAML Setup`, site).includes("Okta SAML")); +}); + +test("the pointer's index URL uses the given site URL", () => { + const site = "https://preview.example"; + assert.strictEqual(pointerParts(`${site}/docs/x`, site).llmsUrl, "https://preview.example/llms.txt"); + assert.strictEqual( + pointerLine(`${site}/docs/x`, site), + "> For AI agents: this page is available as Markdown at https://preview.example/docs/x.md. " + + "The full documentation index is at https://preview.example/llms.txt.", + ); +}); diff --git a/plugins/llms-markdown/postprocess-llms.js b/plugins/llms-markdown/postprocess-llms.js new file mode 100644 index 00000000..df45cb4f --- /dev/null +++ b/plugins/llms-markdown/postprocess-llms.js @@ -0,0 +1,300 @@ +const fs = require("fs"); +const path = require("path"); +const { encodeUrlPath, POINTER_LEAD } = require("./pointer"); + +const WEB_CONSOLE_API_DIR = "/docs/APIs-and-SDKs/Web-Console-API/"; +const API_INDEX_PATH = "docs/APIs-and-SDKs/Web-Console-API/llms.txt"; +const RESOURCE_DIR = "docs/APIs-and-SDKs/Web-Console-API/llms/"; +const ACRONYMS = new Set(["api", "cors"]); +const ACTION_ORDER = ["list", "get", "create", "update", "delete", "archive"]; +const MAX_RESOURCE_LINE = 300; +const MAX_DESCRIPTION = 200; +const SECTION_SEPARATOR = "\n\n---\n\n"; +const FULL_CONTENT_HEADING = "# Full Documentation Content\n\n"; + +const PERMISSIONS = /\*\*Required Permissions\*\*:([^\n]*)/; + +function apiDescriptionFor(operation) { + const endpoint = `${operation.method} ${operation.path}.`; + const prose = (operation.description || "") + .replace(/^:::[^\n]*\n[\s\S]*?^:::[ \t]*$/gm, "") + .replace(PERMISSIONS, "") + .split(/\n\s*\n/) + .map((p) => p.replace(/\[([^\]]*)\]\([^)]*\)/g, "$1").replace(/\*\*/g, "").replace(/\s+/g, " ").trim()) + .find((p) => p && !/^(#|[-*+] |\d+[.)] |\||>|```|:::|!|<)/.test(p)); + if (!prose) return endpoint; + const sentence = firstSentence(prose) ?? `${prose.replace(/[:;,]$/, "")}.`; + return sentence.length <= MAX_DESCRIPTION ? `${endpoint} ${sentence}` : endpoint; +} + +// "etc." is left out: before a capitalised word it ends the sentence. +const ABBREVIATION = /(?:^|\s)(?:e\.g|i\.e|vs|cf)\.$/i; + +function firstSentence(text) { + for (const m of text.matchAll(/[.!?](?=\s|$)/g)) { + const sentence = text.slice(0, m.index + 1); + const next = text.slice(m.index + 1).trimStart(); + if (!ABBREVIATION.test(sentence) && !/^[a-z]/.test(next)) return sentence; + } + return null; +} + +const ENTRY = /^- \[(.*?)\]\((https?:\/\/[^)]*)\)(?:: (.*))?$/; + +function renderLinks(links) { + return links + .map((l) => `- [${l.title}](${encodeUrlPath(l.url)})${l.description ? `: ${l.description}` : ""}`) + .join("\n"); +} + +function resourceOf(apiPath) { + const slug = apiPath.split("/")[1] || ""; + if (!/^[a-z0-9][a-z0-9_-]*$/i.test(slug)) throw new Error(`No resource in API path ${apiPath}`); + const words = slug.split(/[_-]/).map((w) => (ACRONYMS.has(w.toLowerCase()) ? w.toUpperCase() : w)); + const name = words.join(" "); + return { slug, name: name.charAt(0).toUpperCase() + name.slice(1) }; +} + +const byTitle = (a, b) => a.title.localeCompare(b.title); +const plural = (n, word) => `${n} ${word}${n === 1 ? "" : "s"}`; + +function resourceFile(resource, apiIndexUrl) { + const endpoints = [...resource.endpoints].sort(byTitle); + return [ + `# ABsmartly Web Console API: ${resource.name}`, + "", + `> ${plural(endpoints.length, "endpoint")}. Authentication, the \`ok: false\` note and the other resources: ` + + `${apiIndexUrl}. Full schemas: ${resource.specUrl}.`, + "", + "## Endpoints", + "", + renderLinks(endpoints), + "", + ].join("\n"); +} + +// Titles outside the most common first word (e.g. "Team role list" among roles) are kept whole. +function resourceActions(titles) { + const words = titles.map((t) => t.split(" ")); + const firstWordCount = (w) => words.filter((v) => v[0] === w[0]).length; + const lead = words.reduce((best, w) => (firstWordCount(w) > firstWordCount(best) ? w : best))[0]; + const group = words.filter((w) => w[0] === lead); + const shortest = Math.min(...group.map((w) => w.length)); + let common = 0; + while (common < shortest - 1 && group.every((w) => w[common] === group[0][common])) common++; + const actions = [...new Set(words.map((w) => (w[0] === lead ? w.slice(common) : w).join(" ")))]; + const rank = (action) => { + const at = ACTION_ORDER.indexOf(action); + return at < 0 ? ACTION_ORDER.length : at; + }; + return actions.sort((x, y) => rank(x) - rank(y) || x.localeCompare(y)); +} + +function resourceEntry(resource, url) { + const actions = resourceActions(resource.endpoints.map((e) => e.title)); + const entry = (shown) => { + const more = shown < actions.length ? ", …" : ""; + const list = `${actions.slice(0, shown).join(", ")}${more}`; + return { title: resource.name, url, description: `${plural(resource.endpoints.length, "endpoint")}: ${list}` }; + }; + let shown = actions.length; + while (shown > 1 && renderLinks([entry(shown)]).length > MAX_RESOURCE_LINE) shown--; + return entry(shown); +} + +function rewriteLlmsTxt(llmsTxt, { apiOperation, apiIndexUrl, startHere, apiIndexHeader, siteUrl }) { + const webConsoleApiUrl = `${siteUrl}${WEB_CONSOLE_API_DIR}`; + const main = []; + const apiGuides = []; + const resourcesBySlug = new Map(); + let endpointCount = 0; + let apiLinkAt = -1; + let startHereAt = -1; + + for (const line of llmsTxt.split("\n")) { + const m = line.match(ENTRY); + if (!m) { + if (startHereAt < 0 && line.startsWith("## ")) startHereAt = main.length; + main.push(line); + continue; + } + const entry = { title: m[1], url: m[2], description: m[3] || "" }; + const operation = apiOperation(entry.url); + const described = operation ? { ...entry, description: apiDescriptionFor(operation) } : entry; + if (!entry.url.startsWith(webConsoleApiUrl)) { + main.push(renderLinks([described])); + continue; + } + if (operation) { + const { slug, name } = resourceOf(operation.path); + if (!resourcesBySlug.has(slug)) { + resourcesBySlug.set(slug, { name, specUrl: operation.publishedUrl, endpoints: [] }); + } + resourcesBySlug.get(slug).endpoints.push(described); + endpointCount++; + } else { + apiGuides.push(renderLinks([described])); + } + if (apiLinkAt < 0) { + apiLinkAt = main.length; + main.push(null); + } + } + + if (apiLinkAt >= 0) { + main[apiLinkAt] = renderLinks([ + { + title: "Web Console API endpoint index", + url: apiIndexUrl, + description: `Index of the ${endpointCount} Web Console API endpoints, grouped by resource, plus the API overview and examples.`, + }, + ]); + } + if (startHereAt >= 0) { + main.splice(startHereAt, 0, `## Start here\n\n${renderLinks(startHere)}\n`); + } + + const sorted = [...resourcesBySlug].sort(([, a], [, b]) => a.name.localeCompare(b.name)); + const resources = new Map(sorted.map(([slug, r]) => [slug, resourceFile(r, apiIndexUrl)])); + const resourceEntries = sorted.map(([slug, r]) => resourceEntry(r, `${siteUrl}/${RESOURCE_DIR}${slug}.txt`)); + + const apiIndex = [ + apiIndexHeader.trimEnd(), + "", + "## Overview and examples", + "", + ...apiGuides, + "", + "## Resources", + "", + renderLinks(resourceEntries), + "", + ].join("\n"); + + return { main: main.join("\n"), apiIndex, resources }; +} + +function addNote(header, note) { + const lines = header.trimEnd().split("\n"); + let at = lines.findIndex((l) => l.startsWith("> ")); + if (at < 0) at = 0; + while (at + 1 < lines.length && lines[at + 1].startsWith(">")) at++; + lines.splice(at + 1, 0, "", note); + return `${lines.join("\n")}\n`; +} + +function withoutPointer(section) { + const lineEnd = section.indexOf("\n"); + const isPointer = section.startsWith(`> ${POINTER_LEAD}`) && section.startsWith("\n\n", lineEnd); + return isPointer ? section.slice(lineEnd + 2) : section; +} + +// The inner plugin writes each page's .md verbatim plus SECTION_SEPARATOR, and pages may contain "---" themselves. +function rewriteLlmsFull(full, { pages, isApiPage, note, header }) { + const marker = `${SECTION_SEPARATOR}${FULL_CONTENT_HEADING}`; + const at = full.indexOf(marker); + if (at < 0) throw new Error("llms-full.txt: no Full Documentation Content section"); + const body = full.slice(at + marker.length); + + const PREFIX = 32; + const byPrefix = new Map(); + for (const [url, markdown] of pages) { + if (!markdown) continue; + const key = markdown.slice(0, PREFIX); + if (!byPrefix.has(key)) byPrefix.set(key, []); + byPrefix.get(key).push({ url, section: `${markdown}${SECTION_SEPARATOR}` }); + } + for (const list of byPrefix.values()) list.sort((a, b) => b.section.length - a.section.length); + + const kept = []; + let pos = 0; + while (pos < body.length) { + const candidates = [...byPrefix.entries()] + .filter(([key]) => body.startsWith(key, pos)) + .flatMap(([, list]) => list); + const page = candidates.find((c) => body.startsWith(c.section, pos)); + if (!page) { + throw new Error(`llms-full.txt: no known page at offset ${pos}: ${JSON.stringify(body.slice(pos, pos + 80))}`); + } + if (!isApiPage(page.url)) kept.push(withoutPointer(page.section)); + pos += page.section.length; + } + + return `${addNote(header ?? full.slice(0, at), note)}${marker}${kept.join("")}`; +} + +function markdownReader(outDir, siteUrl) { + return (url) => { + if (!url.startsWith(`${siteUrl}/`) || !url.endsWith(".md")) return null; + let relative; + try { + relative = decodeURI(url.slice(siteUrl.length + 1)); + } catch (err) { + if (err instanceof URIError) return null; + throw err; + } + const file = path.join(outDir, relative); + return fs.existsSync(file) ? fs.readFileSync(file, "utf8") : null; + }; +} + +function operationsByMarkdownUrl(index) { + return new Map([...index.values()].map((entry) => [`${entry.pageUrl}.md`, entry])); +} + +function pagesOf(llmsTxt, readMd) { + const pages = new Map(); + for (const line of llmsTxt.split("\n")) { + const m = line.match(ENTRY); + const markdown = m && readMd(m[2]); + if (markdown) pages.set(m[2], markdown); + } + return pages; +} + +async function postProcessLlms(outDir, options, index, siteUrl) { + if (!siteUrl) throw new Error("llms-txt wrapper: postProcessLlms: siteUrl is required"); + if (!options) throw new Error("llms-txt wrapper: missing postProcess options"); + const { startHere, apiIndexHeader, fullNote } = options; + const llmsTxtPath = path.join(outDir, "llms.txt"); + const fullPath = path.join(outDir, "llms-full.txt"); + + const readMd = markdownReader(outDir, siteUrl); + const operations = operationsByMarkdownUrl(index); + const llmsTxt = fs.readFileSync(llmsTxtPath, "utf8"); + const { main, apiIndex, resources } = rewriteLlmsTxt(llmsTxt, { + apiOperation: (url) => operations.get(url) ?? null, + apiIndexUrl: `${siteUrl}/${API_INDEX_PATH}`, + siteUrl, + startHere, + apiIndexHeader, + }); + fs.writeFileSync(llmsTxtPath, main); + fs.mkdirSync(path.dirname(path.join(outDir, API_INDEX_PATH)), { recursive: true }); + fs.writeFileSync(path.join(outDir, API_INDEX_PATH), apiIndex); + fs.rmSync(path.join(outDir, RESOURCE_DIR), { recursive: true, force: true }); + fs.mkdirSync(path.join(outDir, RESOURCE_DIR), { recursive: true }); + for (const [slug, text] of resources) fs.writeFileSync(path.join(outDir, RESOURCE_DIR, `${slug}.txt`), text); + + if (fs.existsSync(fullPath)) { + const full = rewriteLlmsFull(fs.readFileSync(fullPath, "utf8"), { + pages: pagesOf(llmsTxt, readMd), + isApiPage: (url) => operations.get(url)?.specKey === "webConsole", + note: fullNote, + header: main, + }); + fs.writeFileSync(fullPath, full); + } +} + +module.exports = { + apiDescriptionFor, + rewriteLlmsTxt, + resourceOf, + resourceActions, + rewriteLlmsFull, + markdownReader, + postProcessLlms, + API_INDEX_PATH, + RESOURCE_DIR, +}; diff --git a/plugins/llms-markdown/postprocess-llms.test.js b/plugins/llms-markdown/postprocess-llms.test.js new file mode 100644 index 00000000..0e3bbc75 --- /dev/null +++ b/plugins/llms-markdown/postprocess-llms.test.js @@ -0,0 +1,397 @@ +const test = require("node:test"); +const assert = require("node:assert"); +const { + rewriteLlmsTxt, + resourceOf, + resourceActions, + rewriteLlmsFull, + apiDescriptionFor, + markdownReader, + postProcessLlms, +} = require("./postprocess-llms"); + +const SITE = "https://docs.absmartly.com"; +const WC = `${SITE}/docs/APIs-and-SDKs/Web-Console-API`; +const pointer = (url) => + `> For AI agents: this page is available as Markdown at <${url}.md>. The full documentation index is at <${SITE}/llms.txt>.`; + +// --- apiDescriptionFor ---------------------------------------------------------- + +test("apiDescriptionFor is the endpoint and a prose sentence, without permissions", () => { + assert.strictEqual( + apiDescriptionFor({ + method: "PUT", + path: "/experiments/{experimentId}/development", + summary: "Start Experiment in Development [UPDATE]", + description: "**Required Permissions**: `Experiment Development` or `Experiment Admin`", + }), + "PUT /experiments/{experimentId}/development.", + ); + assert.strictEqual( + apiDescriptionFor({ + method: "POST", + path: "/datasources/{datasourceId}/json_layouts/recreate", + description: "Drops and recreates the json_layouts table. Destructive.\n**Required Permissions**: `EventDatasourceConfig Edit`", + }), + "POST /datasources/{datasourceId}/json_layouts/recreate. Drops and recreates the json_layouts table.", + ); +}); + +test("apiDescriptionFor drops admonitions and permission text, keeps unterminated prose", () => { + const d = apiDescriptionFor({ + method: "PUT", + path: "/goals/{goalId}", + description: + "**Required Permissions**: `Goal Edit` or `Goal Admin`\n\n:::caution\nOnly fields provided will be updated.\n:::\n", + }); + assert.strictEqual(d, "PUT /goals/{goalId}."); + assert.ok(!d.includes(":::") && !d.includes("**")); + assert.strictEqual( + apiDescriptionFor({ + method: "POST", + path: "/experiments/import", + description: + "**Required Permissions**: `Experiment Admin` and (`Experiment Create` or `Experiment CreateFromTemplate`). Importing a feature requires more.\n\nImports an experiment.", + }), + "POST /experiments/import. Imports an experiment.", + ); + assert.strictEqual( + apiDescriptionFor({ method: "GET", path: "/notifications/summary", description: "Get user notifications with counts and pagination" }), + "GET /notifications/summary. Get user notifications with counts and pagination.", + ); + assert.strictEqual( + apiDescriptionFor({ method: "GET", path: "/events/quota", description: "Get monthly events quota. **Required Permissions**: `List`" }), + "GET /events/quota. Get monthly events quota.", + ); + assert.strictEqual(apiDescriptionFor({ method: "GET", path: "/x" }), "GET /x."); + assert.strictEqual( + apiDescriptionFor({ method: "HEAD", path: "/files/{id}", description: "**Required Permissions**: Access to the file based on its usage type." }), + "HEAD /files/{id}.", + ); +}); + +test("apiDescriptionFor ends the sentence at \"etc.\" before a capital, not at other abbreviations", () => { + assert.strictEqual( + apiDescriptionFor({ method: "GET", path: "/goals", description: "Use e.g. this endpoint to list goals. Paginated." }), + "GET /goals. Use e.g. this endpoint to list goals.", + ); + assert.strictEqual( + apiDescriptionFor({ method: "GET", path: "/teams", description: "Lists teams, i.e. groups of users. Sorted by name." }), + "GET /teams. Lists teams, i.e. groups of users.", + ); + assert.strictEqual( + apiDescriptionFor({ method: "GET", path: "/units", description: "Returns approx. three units per page. Cached." }), + "GET /units. Returns approx. three units per page.", + ); + assert.strictEqual( + apiDescriptionFor({ method: "GET", path: "/tags", description: "Lists goals, metrics, etc. and their tags. Sorted." }), + "GET /tags. Lists goals, metrics, etc. and their tags.", + ); + assert.strictEqual( + apiDescriptionFor({ method: "GET", path: "/labels", description: "Lists goals, metrics, etc. Paginated." }), + "GET /labels. Lists goals, metrics, etc.", + ); +}); + +test("apiDescriptionFor skips lead images and HTML", () => { + assert.strictEqual( + apiDescriptionFor({ method: "GET", path: "/a", description: "![Diagram](/img/a.png)\n\nLists things. More." }), + "GET /a. Lists things.", + ); + assert.strictEqual( + apiDescriptionFor({ method: "GET", path: "/b", description: "\n\nGets a thing." }), + "GET /b. Gets a thing.", + ); +}); + +// --- rewriteLlmsTxt --------------------------------------------------------------- + +const LLMS_TXT = `# The ABsmartly Docs + +> ABsmartly product documentation. + +Every page is available as Markdown. + + +## docs + + +### APIs-and-SDKs + +- [Authentication](${SITE}/docs/APIs-and-SDKs/MCP-Server/authentication.md): The ABsmartly MCP server supports two authentication methods. Both are +- [Global Options & Configuration](${SITE}/docs/APIs-and-SDKs/CLI-Documentation/configuration.md): Global options +- [Good page](${SITE}/docs/a/good.md): Connect ABsmartly to Snowflake. +- [Experiment development start](${WC}/003-set-experiment-to-development.md): **Required Permissions**: \`Experiment Development\` or \`Experiment Admin\` +- [ABsmartly Web Console API](${WC}/absmartly-web-console-api.md): An OpenAPI Specification that describes the ABsmartly API for working wit +- [Experiment list](${WC}/0100-000-list-experiments.md): **Required Permissions**: \`Experiment List\` or \`Experiment Admin\` +- [Goal list](${WC}/0200-000-list-goals.md): **Required Permissions**: \`Goal List\` +- [Check Service Health](${SITE}/docs/APIs-and-SDKs/SDK-API/collector-health-check.md): A GET request to check that the service is running as expected. + +### glossary + +- [SAML SSO - Okta](${SITE}/docs/SSO/Okta SAML Setup.md): The ABsmartly Web Console supports SAML SSO with Okta. +- [Already encoded](${SITE}/docs/SSO/Azure%20SAML%20Setup.md): Encoded once. + +## Optional +- [Web Console API OpenAPI spec](${SITE}/openapi/web-console-api.yaml): Full schemas +- [Missing page](${SITE}/docs/missing.md): Left as it is +`; + +const WC_SPEC = `${SITE}/openapi/web-console-api.yaml`; +const API = { + [`${WC}/003-set-experiment-to-development.md`]: { + method: "PUT", + path: "/experiments/{experimentId}/development", + description: "**Required Permissions**: `Experiment Development`", + publishedUrl: WC_SPEC, + }, + [`${WC}/0100-000-list-experiments.md`]: { method: "GET", path: "/experiments", publishedUrl: WC_SPEC }, + [`${WC}/0200-000-list-goals.md`]: { method: "GET", path: "/goals", description: "Lists goals.", publishedUrl: WC_SPEC }, + [`${SITE}/docs/APIs-and-SDKs/SDK-API/collector-health-check.md`]: { + method: "GET", + path: "/healthy", + description: "A GET request to check that the service is running as expected.", + publishedUrl: `${SITE}/openapi/collector-api.yaml`, + }, +}; + +const API_INDEX_URL = `${WC}/llms.txt`; +const START_HERE = [ + { title: "Web Console API index", url: API_INDEX_URL, description: "Every endpoint." }, + { title: "Glossary", url: `${SITE}/docs/glossary.md`, description: "Key concepts." }, +]; + +function rewrite() { + return rewriteLlmsTxt(LLMS_TXT, { + apiOperation: (url) => API[url] ?? null, + apiIndexUrl: API_INDEX_URL, + startHere: START_HERE, + apiIndexHeader: "# ABsmartly Web Console API\n\n> Auth line. Spec link.\n", + siteUrl: SITE, + }); +} + +const entryLine = (text, title) => text.split("\n").find((l) => l.startsWith(`- [${title}](`)); + +test("rewriteLlmsTxt keeps the plugin's description for non-API entries", () => { + const { main } = rewrite(); + assert.match(entryLine(main, "Authentication"), /\): The ABsmartly MCP server supports two authentication methods\. Both are$/); + assert.match(entryLine(main, "Global Options & Configuration"), /\): Global options$/); + assert.match(entryLine(main, "Good page"), /\): Connect ABsmartly to Snowflake\.$/); +}); + +test("rewriteLlmsTxt percent-encodes URLs with spaces, without encoding twice", () => { + const { main } = rewrite(); + assert.strictEqual( + entryLine(main, "SAML SSO - Okta"), + `- [SAML SSO - Okta](${SITE}/docs/SSO/Okta%20SAML%20Setup.md): The ABsmartly Web Console supports SAML SSO with Okta.`, + ); + assert.match(entryLine(main, "Already encoded"), /\/Azure%20SAML%20Setup\.md\)/); + for (const line of main.split("\n")) assert.ok(!/\]\([^)]* /.test(line), line); +}); + +test("rewriteLlmsTxt leaves spec links and other entries untouched", () => { + const { main } = rewrite(); + assert.match(entryLine(main, "Web Console API OpenAPI spec"), /\): Full schemas$/); + assert.match(entryLine(main, "Missing page"), /\): Left as it is$/); +}); + +test("rewriteLlmsTxt moves Web Console entries to the API index and links it once", () => { + const { main, apiIndex } = rewrite(); + assert.ok(!main.includes(`${WC}/0`), "endpoint entries left in main"); + assert.ok(!main.includes("absmartly-web-console-api.md")); + assert.ok(!main.includes("**")); + const link = main.split("\n").filter((l) => l.startsWith("- [") && l.includes(`](${API_INDEX_URL})`)); + assert.strictEqual(link.length, 2, "Start here link + section link"); + assert.match(main, /Index of the 3 Web Console API endpoints, grouped by resource/); + assert.match( + entryLine(main, "Check Service Health"), + /\): GET \/healthy\. A GET request to check that the service is running as expected\.$/, + ); + + assert.ok(apiIndex.startsWith("# ABsmartly Web Console API\n\n> Auth line. Spec link.\n")); + assert.match( + entryLine(apiIndex, "ABsmartly Web Console API"), + /\): An OpenAPI Specification that describes the ABsmartly API for working wit$/, + ); + assert.ok(apiIndex.indexOf("## Overview and examples") < apiIndex.indexOf("## Resources")); + assert.ok(!apiIndex.includes("**")); +}); + +test("the API index lists one entry per resource and no endpoint pages", () => { + const { apiIndex } = rewrite(); + assert.ok(!apiIndex.includes("## Endpoints")); + assert.ok(!/\/0\d{2}[^)]*\.md\)/.test(apiIndex), "endpoint page linked from the API index"); + const resources = apiIndex.split("\n## Resources\n\n")[1].trimEnd().split("\n"); + assert.deepStrictEqual(resources, [ + `- [Experiments](${WC}/llms/experiments.txt): 2 endpoints: list, development start`, + `- [Goals](${WC}/llms/goals.txt): 1 endpoint: list`, + ]); +}); + +test("each resource file lists its endpoints sorted by title and points back to the index and spec", () => { + const { resources } = rewrite(); + assert.deepStrictEqual([...resources.keys()], ["experiments", "goals"]); + assert.strictEqual( + resources.get("experiments"), + [ + "# ABsmartly Web Console API: Experiments", + "", + `> 2 endpoints. Authentication, the \`ok: false\` note and the other resources: ${API_INDEX_URL}. Full schemas: ${WC_SPEC}.`, + "", + "## Endpoints", + "", + `- [Experiment development start](${WC}/003-set-experiment-to-development.md): PUT /experiments/{experimentId}/development.`, + `- [Experiment list](${WC}/0100-000-list-experiments.md): GET /experiments.`, + "", + ].join("\n"), + ); + assert.match(resources.get("goals"), /\n- \[Goal list\]\([^)]*\): GET \/goals\. Lists goals\.\n$/); +}); + +test("resourceActions strips the common prefix and orders list, get, create, update, delete, archive first", () => { + assert.deepStrictEqual( + resourceActions(["API key update", "API key delete", "API key list", "API key create", "API key get"]), + ["list", "get", "create", "update", "delete"], + ); + assert.deepStrictEqual( + resourceActions(["Datasource connection test", "Datasource archive", "Datasource list", "Datasource introspect"]), + ["list", "archive", "connection test", "introspect"], + ); + assert.deepStrictEqual(resourceActions(["Permission list"]), ["list"]); + assert.deepStrictEqual(resourceActions(["Config update", "Config bulk update", "Config update"]), ["update", "bulk update"]); + assert.deepStrictEqual( + resourceActions(["Role create", "Role list", "Team role list", "Role get"]), + ["list", "get", "create", "Team role list"], + ); +}); + +test("a resource entry ends in … only when the full action list would pass 300 characters", () => { + const actions = Array.from({ length: 40 }, (_, i) => `step${String(i).padStart(2, "0")} run`); + const lines = actions.map((a, i) => `- [Widget ${a}](${WC}/w-${i}.md): x`).join("\n"); + const ops = Object.fromEntries( + actions.map((a, i) => [`${WC}/w-${i}.md`, { method: "GET", path: `/widgets/${i}`, publishedUrl: WC_SPEC }]), + ); + const { apiIndex } = rewriteLlmsTxt(`# T\n\n## docs\n\n${lines}\n`, { + apiOperation: (url) => ops[url] ?? null, + apiIndexUrl: API_INDEX_URL, + startHere: [], + apiIndexHeader: "# H\n", + siteUrl: SITE, + }); + const line = entryLine(apiIndex, "Widgets"); + assert.ok(line.length <= 300, `${line.length} chars`); + assert.match(line, /\): 40 endpoints: step00 run, step01 run, .*, …$/); + const short = entryLine(rewrite().apiIndex, "Experiments"); + assert.ok(!short.includes("…")); +}); + +test("resourceOf groups by the path's first segment", () => { + assert.deepStrictEqual(resourceOf("/experiments/{experimentId}/start"), { slug: "experiments", name: "Experiments" }); + assert.deepStrictEqual(resourceOf("/experiment_custom_sections/order"), { + slug: "experiment_custom_sections", + name: "Experiment custom sections", + }); + assert.deepStrictEqual(resourceOf("/stop-reasons"), { slug: "stop-reasons", name: "Stop reasons" }); + assert.deepStrictEqual(resourceOf("/api_keys/{id}"), { slug: "api_keys", name: "API keys" }); + assert.deepStrictEqual(resourceOf("/cors"), { slug: "cors", name: "CORS" }); + assert.throws(() => resourceOf("/{id}"), /resource/); + assert.throws(() => resourceOf("/"), /resource/); +}); + +test("rewriteLlmsTxt inserts the Start here block before the first section", () => { + const { main } = rewrite(); + const startHere = main.indexOf("## Start here"); + assert.ok(startHere > main.indexOf("Every page is available as Markdown.")); + assert.ok(startHere < main.indexOf("## docs")); + assert.match(main, /## Start here\n\n- \[Web Console API index\]\(https:\/\/docs\.absmartly\.com\/docs\/APIs-and-SDKs\/Web-Console-API\/llms\.txt\): Every endpoint\.\n- \[Glossary\]/); +}); + +// --- rewriteLlmsFull ---------------------------------------------------------------- + +// The inner plugin writes: llms.txt, then "\n\n---\n\n# Full Documentation Content\n\n", +// then each page's .md content followed by "\n\n---\n\n". +const PAGES = new Map([ + [`${SITE}/docs/cli.md`, "# ABsmartly CLI\n\nCLI body."], + [ + `${SITE}/docs/APIs-and-SDKs/SDK-API/collector-health-check.md`, + `${pointer(`${SITE}/docs/APIs-and-SDKs/SDK-API/collector-health-check`)}\n\n# Check Service Health\n\nCollector body.`, + ], + [ + `${WC}/archive-goal.md`, + `${pointer(`${WC}/archive-goal`)}\n\n# Archive goal\n\nWeb Console body.\n\n---\n\nContinuation of the Web Console page after a horizontal rule.`, + ], + [`${WC}/absmartly-web-console-api.md`, "Version: 1.0.0\n\n# ABsmartly Web Console API\n\nAPI overview body."], + [`${WC}/list-goals.md`, `${pointer(`${WC}/list-goals`)}\n\n# List goals\n\nAnother endpoint body.`], + [`${SITE}/docs/glossary.md`, "# Glossary\n\nGlossary body.\n\n---\n\nGlossary continuation."], +]); +const FULL = + "# The ABsmartly Docs\n\n> Old description.\n\n## docs\n\n- [x](y): z\n" + + "\n\n---\n\n# Full Documentation Content\n\n" + + [...PAGES.values()].map((md) => `${md}\n\n---\n\n`).join(""); +const OPERATION_URLS = new Set([`${WC}/archive-goal.md`, `${WC}/list-goals.md`]); + +function rewriteFull(full = FULL) { + return rewriteLlmsFull(full, { + pages: PAGES, + isApiPage: (url) => OPERATION_URLS.has(url), + note: "Web Console API endpoints are not included here.", + header: "# The ABsmartly Docs\n\n> New description.\n\n## Start here\n\n- [a](b): c\n", + }); +} + +test("rewriteLlmsFull drops Web Console endpoint pages and keeps every other page", () => { + const out = rewriteFull(); + assert.ok(out.includes("Collector body.")); + assert.ok(!out.includes("Web Console body.")); + assert.ok(!out.includes("Continuation of the Web Console page")); + assert.ok(!out.includes("Another endpoint body.")); + assert.ok(out.includes("Glossary body.") && out.includes("Glossary continuation.")); + assert.ok(out.includes("CLI body.")); + assert.ok(out.includes("# Full Documentation Content")); + assert.ok(!out.includes("Old description.")); + assert.ok(out.startsWith("# The ABsmartly Docs\n\n> New description.\n\nWeb Console API endpoints are not included here.\n\n## Start here")); + assert.ok(!out.includes("---\n\n---")); +}); + +test("rewriteLlmsFull strips the agent pointer line from every page", () => { + const out = rewriteFull(); + assert.ok(!out.includes("For AI agents")); + assert.match(out, /# Full Documentation Content\n\n# ABsmartly CLI\n\nCLI body\.\n\n---\n\n# Check Service Health\n\nCollector body\./); +}); + +test("rewriteLlmsFull keeps a page starting with `Version:` that follows an endpoint page", () => { + const out = rewriteFull(); + assert.ok(out.includes("Version: 1.0.0\n\n# ABsmartly Web Console API\n\nAPI overview body.")); + assert.match(out, /Collector body\.\n\n---\n\nVersion: 1\.0\.0/); +}); + +test("rewriteLlmsFull throws on content that matches no known page", () => { + assert.throws( + () => rewriteFull(FULL.replace("Glossary body.", "Changed body.")), + /llms-full\.txt: no known page at .*# Glossary/, + ); +}); + +// --- markdownReader ----------------------------------------------------------------- + +test("markdownReader returns null for a malformed percent-encoded URL", () => { + const read = markdownReader(__dirname, SITE); + assert.strictEqual(read(`${SITE}/docs/bad%E0%A4%A.md`), null); + assert.strictEqual(read(`${SITE}/openapi/web-console-api.yaml`), null); +}); + +test("markdownReader reads URLs under the given site URL", () => { + const fs = require("fs"); + const path = require("path"); + const tmp = fs.mkdtempSync(path.join(require("os").tmpdir(), "mdreader-")); + fs.writeFileSync(path.join(tmp, "page.md"), "# Page"); + const read = markdownReader(tmp, "https://preview.example"); + assert.strictEqual(read("https://preview.example/page.md"), "# Page"); + assert.strictEqual(read(`${SITE}/page.md`), null); + fs.rmSync(tmp, { recursive: true }); +}); + +test("postProcessLlms requires a site URL", async () => { + await assert.rejects(postProcessLlms(__dirname, {}, new Map()), /siteUrl/); +}); diff --git a/plugins/llms-markdown/publish-openapi-specs.js b/plugins/llms-markdown/publish-openapi-specs.js index c182c4ca..673c59fd 100644 --- a/plugins/llms-markdown/publish-openapi-specs.js +++ b/plugins/llms-markdown/publish-openapi-specs.js @@ -1,5 +1,6 @@ -// Publishes the OpenAPI specs at /openapi/*.yaml: API pages render schemas -// client-side, so their Markdown lacks them. +// Publishes the raw OpenAPI specs at /openapi/*.yaml, the machine-readable +// source of the API reference pages and their generated Markdown +// (see rehype-api-markdown.js). const fs = require("fs/promises"); const path = require("path"); diff --git a/plugins/llms-markdown/rehype-api-markdown.js b/plugins/llms-markdown/rehype-api-markdown.js new file mode 100644 index 00000000..cc76315d --- /dev/null +++ b/plugins/llms-markdown/rehype-api-markdown.js @@ -0,0 +1,60 @@ +const { normaliseEndpointPath } = require("./api/spec-index"); +const { renderOperationMarkdown } = require("./api/render-operation"); + +const isEl = (node) => node && node.type === "element"; +const hasClass = (node, name) => { + const c = node.properties && node.properties.className; + return (Array.isArray(c) ? c : typeof c === "string" ? c.split(/\s+/) : []).includes(name); +}; + +function find(node, pred) { + if (pred(node)) return node; + for (const child of node.children || []) { + const hit = find(child, pred); + if (hit) return hit; + } + return null; +} + +function toText(node) { + if (node.type === "text") return node.value; + return (node.children || []).map(toText).join(""); +} + +// ESM-only packages; require() of ESM works on Node >= 22.12. +function markdownToHast(markdown) { + const { fromMarkdown } = require("mdast-util-from-markdown"); + const { gfm } = require("micromark-extension-gfm"); + const { gfmFromMarkdown } = require("mdast-util-gfm"); + const { toHast } = require("mdast-util-to-hast"); + const mdast = fromMarkdown(markdown, { + extensions: [gfm()], + mdastExtensions: [gfmFromMarkdown()], + }); + return toHast(mdast); +} + +function endpointOf(tree) { + const pre = find(tree, (n) => isEl(n) && n.tagName === "pre" && hasClass(n, "openapi__method-endpoint")); + if (!pre) return null; + const badge = find(pre, (n) => isEl(n) && hasClass(n, "badge")); + const pathEl = find(pre, (n) => isEl(n) && hasClass(n, "openapi__method-endpoint-path")); + if (!badge || !pathEl) throw new Error("Malformed openapi__method-endpoint element"); + return { + method: toText(badge).trim().toUpperCase(), + path: normaliseEndpointPath(toText(pathEl).trim()), + }; +} + +module.exports = function rehypeApiMarkdown({ index, onReplaced, siteUrl }) { + return (tree) => { + const endpoint = endpointOf(tree); + if (!endpoint) return; + const key = `${endpoint.method} ${endpoint.path}`; + const entry = index.get(key); + if (!entry) throw new Error(`No OpenAPI operation for ${endpoint.method} ${endpoint.path}`); + const hast = markdownToHast(renderOperationMarkdown(entry, { pageUrl: entry.pageUrl, siteUrl })); + tree.children = hast.type === "root" ? hast.children : [hast]; + onReplaced(key); + }; +}; diff --git a/plugins/llms-markdown/rehype-api-markdown.test.js b/plugins/llms-markdown/rehype-api-markdown.test.js new file mode 100644 index 00000000..438f0bbd --- /dev/null +++ b/plugins/llms-markdown/rehype-api-markdown.test.js @@ -0,0 +1,92 @@ +const test = require("node:test"); +const assert = require("node:assert"); +const fs = require("fs"); +const path = require("path"); +const si = require("./api/spec-index"); +const rehypeApiMarkdown = require("./rehype-api-markdown"); + +const siteDir = path.resolve(__dirname, "../.."); +const builtArchiveGoal = path.join( + siteDir, + "build/docs/APIs-and-SDKs/Web-Console-API/archive-goal/index.html", +); +const PAGE_URL = "https://docs.absmartly.com/docs/APIs-and-SDKs/Web-Console-API/archive-goal"; + +const endpointHtml = (method, displayPath) => + `

`; + +const keyOf = (o) => `${o.method} ${o.path}`; +let fullIndex; +async function loadIndex() { + if (!fullIndex) { + const specs = await si.loadDereferencedSpecs(siteDir); + const ops = si.listOperations(specs); + const pages = new Map(ops.map((o) => [keyOf(o), `/docs/test/${o.operationId}`])); + pages.set("PUT /goals/{goalId}/archive", "/docs/APIs-and-SDKs/Web-Console-API/archive-goal"); + fullIndex = si.buildOperationIndex(specs, pages, "https://docs.absmartly.com"); + } + return fullIndex; +} + +// Mirrors what the llms-txt plugin hands to rehype plugins: a root wrapping +// the first `.theme-doc-markdown` element. +async function contentRoot(html) { + const { fromHtml } = await import("hast-util-from-html"); + const { select } = await import("hast-util-select"); + const doc = fromHtml(html); + const el = select(".theme-doc-markdown", doc); + assert.ok(el, "no .theme-doc-markdown element"); + return { type: "root", children: [el] }; +} + +async function run(tree, onReplaced = () => {}) { + rehypeApiMarkdown({ index: await loadIndex(), onReplaced, siteUrl: "https://docs.absmartly.com" })(tree); + const { toHtml } = await import("hast-util-to-html"); + return toHtml(tree); +} + +test("replaces an API page's content with the spec-derived reference", async () => { + const html = await run(await contentRoot(endpointHtml("PUT", "/goals/:goalId/archive"))); + assert.match(html, /goalId<\/code><\/td>/); + assert.match(html, /

Goal archive<\/h1>/); + assert.match(html, /
[\s\S]*For AI agents/); + assert.ok(html.includes(`${PAGE_URL}.md`)); + assert.ok(!html.includes("client-side stub")); + assert.ok(!html.includes("Old title")); +}); + +test("real built archive-goal page", async (t) => { + if (!fs.existsSync(builtArchiveGoal)) return t.skip("build/ absent"); + const html = await run(await contentRoot(fs.readFileSync(builtArchiveGoal, "utf8"))); + assert.match(html, /goalId<\/code><\/td>/); + assert.match(html, /

Responses<\/h2>/); +}); + +test("JSON code fences keep their language", async () => { + const html = await run(await contentRoot(endpointHtml("POST", "/experiments"))); + assert.match(html, //); +}); + +test("unknown endpoint throws naming method and path", async () => { + const tree = await contentRoot(endpointHtml("GET", "/nope/:id")); + await assert.rejects(run(tree), /No OpenAPI operation for GET \/nope\/\{id\}/); +}); + +test("reports each replaced endpoint", async () => { + const replaced = []; + await run(await contentRoot(endpointHtml("PUT", "/goals/:goalId/archive")), (key) => replaced.push(key)); + assert.deepStrictEqual(replaced, ["PUT /goals/{goalId}/archive"]); +}); + +test("pages without an endpoint pass through untouched", async () => { + const tree = await contentRoot( + `

Web Console API

Intro

`, + ); + const before = JSON.stringify(tree); + const replaced = []; + await run(tree, (key) => replaced.push(key)); + assert.strictEqual(JSON.stringify(tree), before); + assert.deepStrictEqual(replaced, []); +}); diff --git a/plugins/llms-markdown/rehype-docusaurus-cleanup.js b/plugins/llms-markdown/rehype-docusaurus-cleanup.js index 923ba5aa..5395b670 100644 --- a/plugins/llms-markdown/rehype-docusaurus-cleanup.js +++ b/plugins/llms-markdown/rehype-docusaurus-cleanup.js @@ -1,5 +1,4 @@ -// Rewrites Docusaurus theme markup (tabs, code blocks, admonitions, details) -// into plain HTML so the llms-txt HTML -> Markdown conversion keeps its meaning. +// Rewrites Docusaurus theme markup into plain HTML so the HTML -> Markdown conversion keeps its meaning. const el = (tagName, properties, children) => ({ type: "element", @@ -114,7 +113,15 @@ function transform(node) { // Drop heading permalink anchors ("Direct link to ...") and icons. if (hasClass(child, "hash-link") || child.tagName === "svg") continue; + // "Copy page" menu is UI only. + if (hasClass(child, "page-ai-actions")) continue; + let replacement = null; + // Agent pointer -> blockquote line. + if (hasClass(child, "agent-pointer")) { + next.push(el("blockquote", {}, [el("p", {}, child.children)])); + continue; + } if (hasClass(child, "theme-code-block")) replacement = convertCodeBlock(child); else if (hasClass(child, "tabs-container")) replacement = convertTabs(child); else if (hasClass(child, "theme-admonition")) replacement = convertAdmonition(child); diff --git a/plugins/llms-markdown/remark-tight-lists.js b/plugins/llms-markdown/remark-tight-lists.js new file mode 100644 index 00000000..6d86faf5 --- /dev/null +++ b/plugins/llms-markdown/remark-tight-lists.js @@ -0,0 +1,15 @@ +function isCompact(item) { + return (item.children || []).filter((c) => c.type !== "list").length <= 1; +} + +function walk(node) { + for (const child of node.children || []) walk(child); + if (node.type === "list" && node.children.every(isCompact)) { + node.spread = false; + for (const item of node.children) item.spread = false; + } +} + +module.exports = function remarkTightLists() { + return walk; +}; diff --git a/plugins/llms-markdown/remark-tight-lists.test.js b/plugins/llms-markdown/remark-tight-lists.test.js new file mode 100644 index 00000000..067cc9fa --- /dev/null +++ b/plugins/llms-markdown/remark-tight-lists.test.js @@ -0,0 +1,27 @@ +const test = require("node:test"); +const assert = require("node:assert"); +const remarkTightLists = require("./remark-tight-lists"); + +// Same path as the llms-txt plugin: HTML -> hast -> mdast -> Markdown. +function htmlToMarkdown(html) { + const { fromHtml } = require("hast-util-from-html"); + const { toMdast } = require("hast-util-to-mdast"); + const { toMarkdown } = require("mdast-util-to-markdown"); + const mdast = toMdast(fromHtml(html, { fragment: true })); + remarkTightLists()(mdast); + return toMarkdown(mdast); +} + +test("items with a nested list stay tight (hast-util-to-mdast marks them spread)", () => { + const md = htmlToMarkdown( + "
  • a (string)
  • b (object)\n
    • c
    • d
", + ); + assert.strictEqual(md, "* `a` (string)\n* `b` (object)\n * `c`\n * `d`\n"); +}); + +test("items with several paragraphs or a code block stay spread", () => { + const md = htmlToMarkdown("
  • One.

    Two.

  • Three.

"); + assert.strictEqual(md, "* One.\n\n Two.\n\n* Three.\n"); + const code = htmlToMarkdown("
  1. Run:

    abs doctor\n
  2. Done.
"); + assert.match(code, /Run:\n\n {3}```\n {3}abs doctor/); +}); diff --git a/plugins/netlify-headers.test.js b/plugins/netlify-headers.test.js new file mode 100644 index 00000000..b6b978c0 --- /dev/null +++ b/plugins/netlify-headers.test.js @@ -0,0 +1,31 @@ +// Checks the static header rules in netlify.toml for the agent-facing files. +const test = require("node:test"); +const assert = require("node:assert"); +const fs = require("fs"); +const path = require("path"); + +const toml = fs.readFileSync(path.resolve(__dirname, "../netlify.toml"), "utf8"); + +// `for` pattern -> header values, from each [[headers]] block. +function headerRules() { + const rules = new Map(); + for (const block of toml.split("[[headers]]").slice(1)) { + const pattern = block.match(/^\s*for\s*=\s*"([^"]+)"/m)[1]; + const values = {}; + for (const m of block.matchAll(/^\s*([A-Za-z-]+)\s*=\s*"([^"]*)"\s*$/gm)) { + if (m[1] !== "for") values[m[1]] = m[2]; + } + rules.set(pattern, { ...(rules.get(pattern) || {}), ...values }); + } + return rules; +} + +test("every llms.txt index is served as UTF-8 plain text with open CORS", () => { + const rules = headerRules(); + for (const file of ["/llms*.txt", "/docs/APIs-and-SDKs/Web-Console-API/llms.txt", "/docs/APIs-and-SDKs/Web-Console-API/llms/*"]) { + const rule = rules.get(file); + assert.ok(rule, `no [[headers]] rule for ${file}`); + assert.strictEqual(rule["Content-Type"], "text/plain; charset=utf-8", file); + assert.strictEqual(rule["Access-Control-Allow-Origin"], "*", file); + } +}); diff --git a/plugins/site-url.js b/plugins/site-url.js new file mode 100644 index 00000000..43227196 --- /dev/null +++ b/plugins/site-url.js @@ -0,0 +1,13 @@ +// Server-side only: client code takes the URL from siteConfig.url. + +const PRODUCTION_URL = "https://docs.absmartly.com"; +const PREVIEW_CONTEXTS = ["deploy-preview", "branch-deploy"]; + +function siteUrl(env = process.env) { + if (PREVIEW_CONTEXTS.includes(env.CONTEXT) && env.DEPLOY_PRIME_URL) { + return env.DEPLOY_PRIME_URL.replace(/\/+$/, ""); + } + return PRODUCTION_URL; +} + +module.exports = { siteUrl, PRODUCTION_URL }; diff --git a/plugins/site-url.test.js b/plugins/site-url.test.js new file mode 100644 index 00000000..a0f7c348 --- /dev/null +++ b/plugins/site-url.test.js @@ -0,0 +1,39 @@ +const test = require("node:test"); +const assert = require("node:assert"); +const fs = require("fs"); +const path = require("path"); +const { siteUrl, PRODUCTION_URL } = require("./site-url"); + +test("siteUrl defaults to production", () => { + assert.strictEqual(siteUrl({}), "https://docs.absmartly.com"); + assert.strictEqual(PRODUCTION_URL, "https://docs.absmartly.com"); +}); + +test("siteUrl uses DEPLOY_PRIME_URL (no trailing slash) on deploy previews and branch deploys", () => { + const prime = "https://deploy-preview-9--x.netlify.app/"; + const expected = "https://deploy-preview-9--x.netlify.app"; + assert.strictEqual(siteUrl({ CONTEXT: "deploy-preview", DEPLOY_PRIME_URL: prime }), expected); + assert.strictEqual(siteUrl({ CONTEXT: "branch-deploy", DEPLOY_PRIME_URL: prime }), expected); +}); + +test("siteUrl stays production in the production context or without DEPLOY_PRIME_URL", () => { + const prime = "https://main--x.netlify.app"; + assert.strictEqual(siteUrl({ CONTEXT: "production", DEPLOY_PRIME_URL: prime }), PRODUCTION_URL); + assert.strictEqual(siteUrl({ CONTEXT: "dev", DEPLOY_PRIME_URL: prime }), PRODUCTION_URL); + assert.strictEqual(siteUrl({ CONTEXT: "deploy-preview" }), PRODUCTION_URL); +}); + +test("no hard-coded production URL in plugins/ or src/ outside site-url.js and tests", () => { + const root = path.resolve(__dirname, ".."); + const walk = (dir) => + fs.readdirSync(dir, { withFileTypes: true }).flatMap((e) => { + const p = path.join(dir, e.name); + if (e.isDirectory()) return e.name === "node_modules" ? [] : walk(p); + return /\.(js|jsx|mjs|cjs|ts|tsx)$/.test(e.name) ? [p] : []; + }); + const offenders = [...walk(path.join(root, "plugins")), ...walk(path.join(root, "src"))] + .filter((f) => !f.endsWith(".test.js") && f !== path.join(__dirname, "site-url.js")) + .filter((f) => fs.readFileSync(f, "utf8").includes("https://docs.absmartly.com")) + .map((f) => path.relative(root, f)); + assert.deepStrictEqual(offenders, []); +}); diff --git a/src/components/AgentPointer/index.js b/src/components/AgentPointer/index.js new file mode 100644 index 00000000..d328ac9a --- /dev/null +++ b/src/components/AgentPointer/index.js @@ -0,0 +1,21 @@ +import React from "react"; +import useDocusaurusContext from "@docusaurus/useDocusaurusContext"; +import { useDoc } from "@docusaurus/plugin-content-docs/client"; +import { pointerParts } from "../../../plugins/llms-markdown/pointer"; +import { pageUrlFor } from "../../utils/markdownUrl"; +import styles from "./styles.module.css"; + +export default function AgentPointer() { + const { metadata } = useDoc(); + const { siteConfig } = useDocusaurusContext(); + const p = pointerParts(pageUrlFor(metadata.permalink, siteConfig.url), siteConfig.url); + return ( +
+ ); +} diff --git a/src/components/AgentPointer/styles.module.css b/src/components/AgentPointer/styles.module.css new file mode 100644 index 00000000..70389182 --- /dev/null +++ b/src/components/AgentPointer/styles.module.css @@ -0,0 +1,13 @@ +/* Standard visually-hidden pattern: stays in the DOM and accessibility tree, + takes no space and cannot cause layout shift. */ +.srOnly { + position: absolute; + width: 1px; + height: 1px; + margin: -1px; + padding: 0; + overflow: hidden; + clip: rect(0, 0, 0, 0); + white-space: nowrap; + border: 0; +} diff --git a/src/components/PageAiActions/PageAiActions.test.js b/src/components/PageAiActions/PageAiActions.test.js new file mode 100644 index 00000000..efe4eab7 --- /dev/null +++ b/src/components/PageAiActions/PageAiActions.test.js @@ -0,0 +1,187 @@ +import assert from "node:assert/strict"; +import { after, afterEach, beforeEach, describe, test } from "node:test"; +import { JSDOM } from "jsdom"; + +const dom = new JSDOM("", { url: "https://docs.example.com/docs/page" }); +globalThis.window = dom.window; +globalThis.document = dom.window.document; +Object.defineProperty(globalThis, "navigator", { value: dom.window.navigator, configurable: true }); +for (const name of ["HTMLElement", "Node", "MutationObserver", "getComputedStyle"]) { + globalThis[name] = dom.window[name]; +} +globalThis.IS_REACT_ACT_ENVIRONMENT = true; +globalThis.docusaurusMock = { + context: { siteConfig: { url: "https://docs.example.com" } }, + doc: { metadata: { permalink: "/docs/page" }, frontMatter: {} }, +}; + +const { act, cleanup, render, screen } = await import("@testing-library/react"); +const { default: userEvent } = await import("@testing-library/user-event"); +const { default: PageAiActions } = await import("./index.js"); + +function stubCopy({ succeeds }) { + dom.window.fetch = async () => ({ ok: succeeds, status: succeeds ? 200 : 500, text: async () => "# Page" }); + Object.defineProperty(dom.window.navigator, "clipboard", { + value: { writeText: async () => {} }, + configurable: true, + }); +} + +// Runs only the menu's 2 s close timer by hand; every other timer stays real. +function controlCloseTimer() { + const realSetTimeout = globalThis.setTimeout; + const realClearTimeout = globalThis.clearTimeout; + const pending = new Map(); + let nextId = 0; + globalThis.setTimeout = (callback, delay, ...args) => { + if (delay !== 2000) return realSetTimeout(callback, delay, ...args); + pending.set(++nextId, callback); + return nextId; + }; + globalThis.clearTimeout = (id) => { + if (!pending.delete(id)) realClearTimeout(id); + }; + return { + fire: () => act(() => [...pending.values()].forEach((callback) => callback())), + restore: () => { + globalThis.setTimeout = realSetTimeout; + globalThis.clearTimeout = realClearTimeout; + }, + }; +} + +function renderMenu() { + const user = userEvent.setup({ delay: null }); + render( + <> + + + , + ); + const trigger = screen.getByRole("button", { name: /Copy page$/ }); + const items = () => screen.getAllByRole("menuitem"); + return { user, trigger, items }; +} + +describe("PageAiActions", () => { + let closeTimer; + after(() => dom.window.close()); + beforeEach(() => stubCopy({ succeeds: true })); + afterEach(() => { + cleanup(); + closeTimer?.restore(); + closeTimer = undefined; + }); + + test("clicking the trigger opens the menu and clicking again closes it", async () => { + const { user, trigger } = renderMenu(); + assert.equal(trigger.getAttribute("aria-expanded"), "false"); + + await user.click(trigger); + assert.equal(trigger.getAttribute("aria-expanded"), "true"); + + await user.click(trigger); + assert.equal(trigger.getAttribute("aria-expanded"), "false"); + }); + + test("Escape closes the menu and returns focus to the trigger", async () => { + const { user, trigger, items } = renderMenu(); + await user.click(trigger); + items()[0].focus(); + + await user.keyboard("{Escape}"); + + assert.equal(trigger.getAttribute("aria-expanded"), "false"); + assert.equal(document.activeElement, trigger); + }); + + for (const key of ["{ArrowDown}", "{Enter}"]) { + test(`${key} on the trigger opens the menu and focuses the first item`, async () => { + const { user, trigger, items } = renderMenu(); + trigger.focus(); + + await user.keyboard(key); + + assert.equal(trigger.getAttribute("aria-expanded"), "true"); + assert.equal(document.activeElement, items()[0]); + }); + } + + test("tabbing out of the menu closes it", async () => { + const { user, trigger, items } = renderMenu(); + trigger.focus(); + await user.keyboard("{ArrowDown}"); + items().at(-1).focus(); + + await user.tab(); + + assert.equal(document.activeElement, screen.getByRole("button", { name: "Outside" })); + assert.equal(trigger.getAttribute("aria-expanded"), "false"); + }); + + test("a successful copy shows Copied", async () => { + const { user, trigger } = renderMenu(); + await user.click(trigger); + + await user.click(screen.getByRole("menuitem", { name: "Copy page as Markdown" })); + + assert.ok(screen.getByRole("menuitem", { name: "Copied" })); + }); + + test("a failed copy offers the link in a live region outside the menu", async () => { + stubCopy({ succeeds: false }); + const { user, trigger } = renderMenu(); + const note = screen.getByRole("status"); + assert.equal(note.textContent, ""); + assert.equal(note.closest('[role="menu"]'), null); + await user.click(trigger); + + await user.click(screen.getByRole("menuitem", { name: "Copy page as Markdown" })); + + assert.ok(screen.getByRole("menuitem", { name: "Couldn't copy" })); + assert.equal(screen.getByRole("status"), note); + assert.match(note.textContent, /Copy the link instead/); + assert.equal(note.querySelector("a").getAttribute("href"), "https://docs.example.com/docs/page.md"); + + await user.click(trigger); + assert.equal(note.textContent, ""); + }); + + test("the page losing focus closes the menu", async () => { + const { user, trigger } = renderMenu(); + await user.click(trigger); + + act(() => { + window.dispatchEvent(new window.Event("blur")); + }); + + assert.equal(trigger.getAttribute("aria-expanded"), "false"); + }); + + test("reopening within 2 s of a copy keeps the menu open", async () => { + closeTimer = controlCloseTimer(); + const { user, trigger } = renderMenu(); + await user.click(trigger); + await user.click(screen.getByRole("menuitem", { name: "Copy page as Markdown" })); + + await user.click(trigger); + await user.click(trigger); + closeTimer.fire(); + + assert.equal(trigger.getAttribute("aria-expanded"), "true"); + }); + + test("after a keyboard copy the timer closes the menu with focus back on the trigger", async () => { + closeTimer = controlCloseTimer(); + const { user, trigger, items } = renderMenu(); + trigger.focus(); + await user.keyboard("{ArrowDown}"); + assert.equal(document.activeElement, items()[0]); + + await user.keyboard("{Enter}"); + closeTimer.fire(); + + assert.equal(trigger.getAttribute("aria-expanded"), "false"); + assert.equal(document.activeElement, trigger); + }); +}); diff --git a/src/components/PageAiActions/index.js b/src/components/PageAiActions/index.js new file mode 100644 index 00000000..921413b7 --- /dev/null +++ b/src/components/PageAiActions/index.js @@ -0,0 +1,161 @@ +import React, { useEffect, useRef, useState } from "react"; +import clsx from "clsx"; +import useDocusaurusContext from "@docusaurus/useDocusaurusContext"; +import { useDoc } from "@docusaurus/plugin-content-docs/client"; +import { markdownUrlFor } from "../../utils/markdownUrl"; +import { copyMarkdown } from "../../utils/copyMarkdown"; +import styles from "./styles.module.css"; + +const copyLabels = { + idle: "Copy page as Markdown", + copied: "Copied", + failed: "Couldn't copy", +}; + +export default function PageAiActions() { + const { metadata, frontMatter } = useDoc(); + const { siteConfig } = useDocusaurusContext(); + const isInline = Boolean(frontMatter.api); + const mdUrl = markdownUrlFor(metadata.permalink, siteConfig.url); + const prompt = encodeURIComponent(`Read ${mdUrl} and help me with questions about it.`); + const [isOpen, setIsOpen] = useState(false); + const [status, setStatus] = useState("idle"); + const rootRef = useRef(null); + const triggerRef = useRef(null); + const closeTimer = useRef(null); + const shouldFocusFirstItem = useRef(false); + + useEffect( + function closeOnOutsidePointerOrEscape() { + if (!isOpen) return undefined; + const closeOnOutsidePointer = (event) => { + if (rootRef.current && !rootRef.current.contains(event.target)) setIsOpen(false); + }; + const closeOnEscape = (event) => { + if (event.key === "Escape") { + setIsOpen(false); + triggerRef.current?.focus(); + } + }; + const closeOnPageBlur = () => setIsOpen(false); + document.addEventListener("mousedown", closeOnOutsidePointer); + document.addEventListener("touchstart", closeOnOutsidePointer); + document.addEventListener("keydown", closeOnEscape); + window.addEventListener("blur", closeOnPageBlur); + return () => { + window.removeEventListener("blur", closeOnPageBlur); + document.removeEventListener("mousedown", closeOnOutsidePointer); + document.removeEventListener("touchstart", closeOnOutsidePointer); + document.removeEventListener("keydown", closeOnEscape); + }; + }, + [isOpen], + ); + + useEffect(function focusFirstItemAfterKeyboardOpen() { + if (isOpen && shouldFocusFirstItem.current) { + rootRef.current.querySelector('[role="menuitem"]')?.focus(); + } + shouldFocusFirstItem.current = false; + }, [isOpen]); + + useEffect(function clearStatusOnClose() { + if (!isOpen) setStatus("idle"); + }, [isOpen]); + + useEffect(() => () => clearTimeout(closeTimer.current), []); + + const itemClass = clsx("dropdown__link", styles.item); + const externalLink = { target: "_blank", rel: "noopener noreferrer", role: "menuitem", className: itemClass }; + + return ( +
{ + if (event.relatedTarget && !rootRef.current.contains(event.relatedTarget)) setIsOpen(false); + }} + > + +
+
{ + if (event.key !== "ArrowDown" && event.key !== "ArrowUp") return; + event.preventDefault(); + const items = [...rootRef.current.querySelectorAll('[role="menuitem"]')]; + const step = event.key === "ArrowDown" ? 1 : -1; + const current = items.indexOf(document.activeElement); + items[(current + step + items.length) % items.length]?.focus(); + }} + > + + + View as Markdown + + + Open in Claude + + + Open in ChatGPT + +
+
+ {status === "failed" && ( + <> + Copy the link instead: {mdUrl} + + )} +
+
+
+ ); +} diff --git a/src/components/PageAiActions/styles.module.css b/src/components/PageAiActions/styles.module.css new file mode 100644 index 00000000..c4cb2d6f --- /dev/null +++ b/src/components/PageAiActions/styles.module.css @@ -0,0 +1,78 @@ +/* Top-right of the content, beside the title on desktop; own line on mobile. */ +.root { + float: right; + margin: 0 0 0.5rem 1rem; +} + +.trigger { + display: inline-flex; + align-items: center; + gap: 0.4rem; + padding: 0.25rem 0.7rem; + font: inherit; + font-size: 0.875rem; + font-weight: var(--ifm-font-weight-semibold); + color: var(--ifm-font-color-base); + background: transparent; + border: 1px solid var(--ifm-color-emphasis-300); + border-radius: var(--ifm-button-border-radius); + cursor: pointer; +} + +.trigger:hover, +.trigger[aria-expanded="true"] { + background: var(--ifm-color-emphasis-200); +} + +.inline { + float: none; + margin: 0 0 1rem; +} + +.inline .menu { + left: 0; + right: auto; +} + +.caret { + flex: none; +} + +.menu { + right: 0; + left: auto; + min-width: 14rem; +} + +.item { + display: block; + width: 100%; + margin: 0; + background: none; + border: 0; + font: inherit; + text-align: left; + cursor: pointer; +} + +.note { + padding: 0.25rem 0.75rem; + font-size: 0.8rem; + overflow-wrap: anywhere; +} + +.note:empty { + padding: 0; +} + +@media (max-width: 996px) { + .root { + float: none; + margin: 0 0 1rem; + } + + .menu { + left: 0; + right: auto; + } +} diff --git a/src/theme/DocItem/Content/index.js b/src/theme/DocItem/Content/index.js new file mode 100644 index 00000000..29650752 --- /dev/null +++ b/src/theme/DocItem/Content/index.js @@ -0,0 +1,49 @@ +/** + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +import React from 'react'; +import clsx from 'clsx'; +import {ThemeClassNames} from '@docusaurus/theme-common'; +import {useDoc} from '@docusaurus/plugin-content-docs/client'; +import Heading from '@theme/Heading'; +import MDXContent from '@theme/MDXContent'; +// Ejected from @docusaurus/theme-classic: the only changes are and . +import AgentPointer from '@site/src/components/AgentPointer'; +import PageAiActions from '@site/src/components/PageAiActions'; +/** + Title can be declared inside md content or declared through + front matter and added manually. To make both cases consistent, + the added title is added under the same div.markdown block + See https://github.com/facebook/docusaurus/pull/4882#issuecomment-853021120 + + We render a "synthetic title" if: + - user doesn't ask to hide it with front matter + - the markdown content does not already contain a top-level h1 heading +*/ +function useSyntheticTitle() { + const {metadata, frontMatter, contentTitle} = useDoc(); + const shouldRender = + !frontMatter.hide_title && typeof contentTitle === 'undefined'; + if (!shouldRender) { + return null; + } + return metadata.title; +} +export default function DocItemContent({children}) { + const syntheticTitle = useSyntheticTitle(); + return ( +
+ + + {syntheticTitle && ( +
+ {syntheticTitle} +
+ )} + {children} +
+ ); +} diff --git a/src/theme/DocItem/Metadata/index.js b/src/theme/DocItem/Metadata/index.js index 423712b9..6a264e3c 100644 --- a/src/theme/DocItem/Metadata/index.js +++ b/src/theme/DocItem/Metadata/index.js @@ -4,11 +4,14 @@ import React from "react"; import Head from "@docusaurus/Head"; import Metadata from "@theme-original/DocItem/Metadata"; +import useDocusaurusContext from "@docusaurus/useDocusaurusContext"; import { useDoc } from "@docusaurus/plugin-content-docs/client"; +import { markdownUrlFor } from "../../../utils/markdownUrl"; export default function MetadataWrapper(props) { const { metadata } = useDoc(); - const mdHref = `${metadata.permalink.replace(/\/+$/, "")}.md`; + const { siteConfig } = useDocusaurusContext(); + const mdHref = markdownUrlFor(metadata.permalink, siteConfig.url); return ( <> diff --git a/src/utils/copyMarkdown.js b/src/utils/copyMarkdown.js new file mode 100644 index 00000000..764411a8 --- /dev/null +++ b/src/utils/copyMarkdown.js @@ -0,0 +1,25 @@ +// Safari drops the click's user activation after an awaited fetch, so the ClipboardItem write starts first. +export async function copyMarkdown(url, deps = {}) { + const fetchImpl = deps.fetch ?? ((...args) => window.fetch(...args)); + const clipboard = deps.clipboard ?? navigator.clipboard; + const Item = "ClipboardItem" in deps ? deps.ClipboardItem : globalThis.ClipboardItem; + + const text = Promise.resolve() + .then(() => fetchImpl(url)) + .then((res) => { + if (!res.ok) throw new Error(`HTTP ${res.status}`); + return res.text(); + }); + // Awaited below on every path; this only prevents an early unhandled-rejection report. + text.catch(() => {}); + + if (Item && typeof clipboard.write === "function") { + try { + const blob = text.then((t) => new Blob([t], { type: "text/plain" })); + blob.catch(() => {}); + await clipboard.write([new Item({ "text/plain": blob })]); + return; + } catch {} + } + await clipboard.writeText(await text); +} diff --git a/src/utils/markdownUrl.js b/src/utils/markdownUrl.js new file mode 100644 index 00000000..5908d464 --- /dev/null +++ b/src/utils/markdownUrl.js @@ -0,0 +1,9 @@ +import { encodeUrlPath } from "../../plugins/llms-markdown/pointer"; + +export function pageUrlFor(permalink, siteUrl) { + return encodeUrlPath(`${siteUrl}${permalink.replace(/\/+$/, "")}`); +} + +export function markdownUrlFor(permalink, siteUrl) { + return `${pageUrlFor(permalink, siteUrl)}.md`; +} diff --git a/static/_redirects b/static/_redirects index 52cce30e..da6565ec 100644 --- a/static/_redirects +++ b/static/_redirects @@ -109,7 +109,7 @@ # Old overview page was named "backend" (from the previous spec's info.title); # the @absmartly/api-mocks spec titles it "ABsmartly Web Console API". -/docs/APIs-and-SDKs/Web-Console-API/backend /docs/APIs-and-SDKs/Web-Console-API/absmartly-web-console-api 302 +/docs/APIs-and-SDKs/Web-Console-API/backend /docs/APIs-and-SDKs/Web-Console-API/absmartly-web-console-api/ 302 # General splat rule (catches all other paths that don't need transformation) /docs/web-console-api/* /docs/APIs-and-SDKs/Web-Console-API/:splat 302 @@ -186,3 +186,9 @@ # APIs-and-SDKs overview rename # ============================================================================= /docs/APIs-and-SDKs/apis-and-sdks /docs/APIs-and-SDKs/overview/ 302 + +# ============================================================================= +# Web Console API operationId rename (api-mocks 1.0.12: 0100_014addExperimentMetric → 0100_014queryExperimentMetricData) +# ============================================================================= +/docs/APIs-and-SDKs/Web-Console-API/0100-014-add-experiment-metric.md /docs/APIs-and-SDKs/Web-Console-API/0100-014-query-experiment-metric-data.md 301 +/docs/APIs-and-SDKs/Web-Console-API/0100-014-add-experiment-metric /docs/APIs-and-SDKs/Web-Console-API/0100-014-query-experiment-metric-data/ 301 diff --git a/static/robots.txt b/static/robots.txt new file mode 100644 index 00000000..9f77ab59 --- /dev/null +++ b/static/robots.txt @@ -0,0 +1,6 @@ +# Documentation index for AI agents: https://docs.absmartly.com/llms.txt +User-agent: * +Disallow: /search +Allow: / + +Sitemap: https://docs.absmartly.com/sitemap.xml diff --git a/test-support/docusaurus-context-stub.mjs b/test-support/docusaurus-context-stub.mjs new file mode 100644 index 00000000..54ccf90f --- /dev/null +++ b/test-support/docusaurus-context-stub.mjs @@ -0,0 +1,3 @@ +export default function useDocusaurusContext() { + return globalThis.docusaurusMock.context; +} diff --git a/test-support/docusaurus-docs-stub.mjs b/test-support/docusaurus-docs-stub.mjs new file mode 100644 index 00000000..9247e112 --- /dev/null +++ b/test-support/docusaurus-docs-stub.mjs @@ -0,0 +1,3 @@ +export function useDoc() { + return globalThis.docusaurusMock.doc; +} diff --git a/test-support/jsx-loader.mjs b/test-support/jsx-loader.mjs new file mode 100644 index 00000000..8fa95955 --- /dev/null +++ b/test-support/jsx-loader.mjs @@ -0,0 +1,42 @@ +import { readFile } from "node:fs/promises"; +import { fileURLToPath } from "node:url"; +import swc from "@swc/core"; + +const stubs = { + "@docusaurus/useDocusaurusContext": new URL("./docusaurus-context-stub.mjs", import.meta.url).href, + "@docusaurus/plugin-content-docs/client": new URL("./docusaurus-docs-stub.mjs", import.meta.url).href, +}; +const srcDir = new URL("../src/", import.meta.url).href; + +export async function resolve(specifier, context, nextResolve) { + if (stubs[specifier]) return { url: stubs[specifier], shortCircuit: true }; + const isExtensionless = specifier.startsWith(".") && !/\.\w+$/.test(specifier); + if (isExtensionless && context.parentURL?.startsWith(srcDir)) { + return nextResolve(`${specifier}.js`, context); + } + return nextResolve(specifier, context); +} + +export async function load(url, context, nextLoad) { + if (url.endsWith(".css")) { + return { + format: "module", + source: "export default new Proxy({}, { get: (_, name) => String(name) });", + shortCircuit: true, + }; + } + if (url.startsWith(srcDir) && url.endsWith(".js")) { + const filename = fileURLToPath(url); + const { code } = await swc.transform(await readFile(filename, "utf8"), { + filename, + jsc: { + parser: { syntax: "ecmascript", jsx: true }, + transform: { react: { runtime: "automatic" } }, + target: "es2022", + }, + module: { type: "es6" }, + }); + return { format: "module", source: code, shortCircuit: true }; + } + return nextLoad(url, context); +} diff --git a/test-support/register.mjs b/test-support/register.mjs new file mode 100644 index 00000000..94e5cd6a --- /dev/null +++ b/test-support/register.mjs @@ -0,0 +1,3 @@ +import { register } from "node:module"; + +register("./jsx-loader.mjs", import.meta.url); diff --git a/yarn.lock b/yarn.lock index 3e8e641a..f3d6f8df 100644 --- a/yarn.lock +++ b/yarn.lock @@ -12,10 +12,10 @@ section-matter "^1.0.0" strip-bom-string "^1.0.0" -"@absmartly/api-mocks@1.0.11": - version "1.0.11" - resolved "https://registry.yarnpkg.com/@absmartly/api-mocks/-/api-mocks-1.0.11.tgz#a9c4ff0f3c61ca54ddd93eabbab10f5125a00217" - integrity sha512-TadRn2wnTBspGlOFvzZF6uHxPlxO9PM3ffaUKYFPWfPw5k8WlRcJIzac6eVlUS7Sb6k/giZZEucbYIMZy+T2kQ== +"@absmartly/api-mocks@1.0.12": + version "1.0.12" + resolved "https://registry.yarnpkg.com/@absmartly/api-mocks/-/api-mocks-1.0.12.tgz#633e1ae741067a001ba820cfc20554cc6af67616" + integrity sha512-+ocYwO+3QKk0xqtzjrjFpHyLSf1v3VA7pv6BjgpeLlca0fgYMiS1iAgN9aOx0c7NdFuM5y3V5Ei4mD42pJQzqQ== dependencies: "@apidevtools/json-schema-ref-parser" "^15.2.2" "@faker-js/faker" "^10.2.0" @@ -218,6 +218,38 @@ js-yaml "^5.2.2" undici "^6.28.0" +"@asamuzakjp/css-color@^5.1.11": + version "5.1.11" + resolved "https://registry.yarnpkg.com/@asamuzakjp/css-color/-/css-color-5.1.11.tgz#28a0aac8220a4cc19045ac3bd9a813d4060bd375" + integrity sha512-KVw6qIiCTUQhByfTd78h2yD1/00waTmm9uy/R7Ck/ctUyAPj+AEDLkQIdJW0T8+qGgj3j5bpNKK7Q3G+LedJWg== + dependencies: + "@asamuzakjp/generational-cache" "^1.0.1" + "@csstools/css-calc" "^3.2.0" + "@csstools/css-color-parser" "^4.1.0" + "@csstools/css-parser-algorithms" "^4.0.0" + "@csstools/css-tokenizer" "^4.0.0" + +"@asamuzakjp/dom-selector@^7.1.1": + version "7.1.1" + resolved "https://registry.yarnpkg.com/@asamuzakjp/dom-selector/-/dom-selector-7.1.1.tgz#01880086bb2490098f167beb58555da1a6c9adbd" + integrity sha512-67RZDnYRc8H/8MLDgQCDE//zoqVFwajkepHZgmXrbwybzXOEwOWGPYGmALYl9J2DOLfFPPs6kKCqmbzV895hTQ== + dependencies: + "@asamuzakjp/generational-cache" "^1.0.1" + "@asamuzakjp/nwsapi" "^2.3.9" + bidi-js "^1.0.3" + css-tree "^3.2.1" + is-potential-custom-element-name "^1.0.1" + +"@asamuzakjp/generational-cache@^1.0.1": + version "1.0.1" + resolved "https://registry.yarnpkg.com/@asamuzakjp/generational-cache/-/generational-cache-1.0.1.tgz#3d0bf6be4fc059851390a7070720c6007af793ec" + integrity sha512-wajfB8KqzMCN2KGNFdLkReeHncd0AslUSrvHVvvYWuU8ghncRJoA50kT3zP9MVL0+9g4/67H+cdvBskj9THPzg== + +"@asamuzakjp/nwsapi@^2.3.9": + version "2.3.9" + resolved "https://registry.yarnpkg.com/@asamuzakjp/nwsapi/-/nwsapi-2.3.9.tgz#ad5549322dfe9d153d4b4dd6f7ff2ae234b06e24" + integrity sha512-n8GuYSrI9bF7FFZ/SjhwevlHc8xaVlb/7HmHelnc/PZXBD2ZR49NnN9sMMuDdEGPeeRQ5d0hqlSlEpgCX3Wl0Q== + "@babel/code-frame@^7.0.0", "@babel/code-frame@^7.28.6", "@babel/code-frame@^7.29.0": version "7.29.0" resolved "https://registry.yarnpkg.com/@babel/code-frame/-/code-frame-7.29.0.tgz#7cd7a59f15b3cc0dcd803038f7792712a7d0b15c" @@ -227,7 +259,7 @@ js-tokens "^4.0.0" picocolors "^1.1.1" -"@babel/code-frame@^7.29.7": +"@babel/code-frame@^7.10.4", "@babel/code-frame@^7.29.7": version "7.29.7" resolved "https://registry.yarnpkg.com/@babel/code-frame/-/code-frame-7.29.7.tgz#f2fbbfea87c44a21590ec515b778b2c26d8866e7" integrity sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw== @@ -1305,6 +1337,13 @@ resolved "https://registry.yarnpkg.com/@braintree/sanitize-url/-/sanitize-url-7.1.2.tgz#ca2035b0fefe956a8676ff0c69af73e605fcd81f" integrity sha512-jigsZK+sMF/cuiB7sERuo9V7N9jx+dhmHHnQyDSVdpZwVutaBu7WvNYqMDLSgFgfB30n452TP3vjDAvFC973mA== +"@bramus/specificity@^2.4.2": + version "2.4.5" + resolved "https://registry.yarnpkg.com/@bramus/specificity/-/specificity-2.4.5.tgz#214c09c99d6fbca5d60c56338f1f90bfc083a17e" + integrity sha512-TWjoxMCb5z1j19ZAVlGIkRkoq22F9F1+s+sTcJcw3GN+sEj/ZhWD+PPyol0feaRGZyajOA22FTCv95Ow26i6iA== + dependencies: + css-tree "^3.2.1" + "@chevrotain/types@~11.1.2": version "11.1.2" resolved "https://registry.yarnpkg.com/@chevrotain/types/-/types-11.1.2.tgz#e83a1a2704f0c5e49e7592b214031a0f4a34d7e5" @@ -1325,11 +1364,21 @@ resolved "https://registry.yarnpkg.com/@csstools/color-helpers/-/color-helpers-5.1.0.tgz#106c54c808cabfd1ab4c602d8505ee584c2996ef" integrity sha512-S11EXWJyy0Mz5SYvRmY8nJYTFFd1LCNV+7cXyAgQtOOuzb4EsgfqDufL+9esx72/eLhsRdGZwaldu/h+E4t4BA== +"@csstools/color-helpers@^6.1.3": + version "6.1.3" + resolved "https://registry.yarnpkg.com/@csstools/color-helpers/-/color-helpers-6.1.3.tgz#fb5643a6ee828cc10c4a1aa6a6606940f459d780" + integrity sha512-c6CpX5G1pvuOKTXiRFJ54Lzc8zQrZ3qUjp44QC5DJNt1OmA1vmfUxOMCcKdDqsvffVDG0/MHnY63J+Mn0nmdUg== + "@csstools/css-calc@^2.1.4": version "2.1.4" resolved "https://registry.yarnpkg.com/@csstools/css-calc/-/css-calc-2.1.4.tgz#8473f63e2fcd6e459838dd412401d5948f224c65" integrity sha512-3N8oaj+0juUw/1H3YwmDDJXCgTB1gKU6Hc/bB502u9zR0q2vd786XJH9QfrKIEgFlZmhZiq6epXl4rHqhzsIgQ== +"@csstools/css-calc@^3.2.0", "@csstools/css-calc@^3.4.4": + version "3.4.4" + resolved "https://registry.yarnpkg.com/@csstools/css-calc/-/css-calc-3.4.4.tgz#05416934945345f6ff69a354a7822faa9e742dea" + integrity sha512-Jwo1Z8DUsZ8xVOLBdLMfhjJFvWD6pqaUTlBNQZ+qIB2i9g7yG8kd/UBJj2c9J9Twr+u87cjy9BjkmfvMbyOk3Q== + "@csstools/css-color-parser@^3.1.0": version "3.1.0" resolved "https://registry.yarnpkg.com/@csstools/css-color-parser/-/css-color-parser-3.1.0.tgz#4e386af3a99dd36c46fef013cfe4c1c341eed6f0" @@ -1338,16 +1387,39 @@ "@csstools/color-helpers" "^5.1.0" "@csstools/css-calc" "^2.1.4" +"@csstools/css-color-parser@^4.1.0": + version "4.2.8" + resolved "https://registry.yarnpkg.com/@csstools/css-color-parser/-/css-color-parser-4.2.8.tgz#d3e30fcb87de2d74847c9474c21942d4529aa7e2" + integrity sha512-JLsKBee9dmnA3L+H+vYK4lQ6n5CoY3yEnh33zdlMutRfrTxtqt+hFeoZ1maHRt5vLw67huDLpOkDb3rl9A51MQ== + dependencies: + "@csstools/color-helpers" "^6.1.3" + "@csstools/css-calc" "^3.4.4" + "@csstools/css-parser-algorithms@^3.0.5": version "3.0.5" resolved "https://registry.yarnpkg.com/@csstools/css-parser-algorithms/-/css-parser-algorithms-3.0.5.tgz#5755370a9a29abaec5515b43c8b3f2cf9c2e3076" integrity sha512-DaDeUkXZKjdGhgYaHNJTV9pV7Y9B3b644jCLs9Upc3VeNGg6LWARAT6O+Q+/COo+2gg/bM5rhpMAtf70WqfBdQ== +"@csstools/css-parser-algorithms@^4.0.0": + version "4.0.3" + resolved "https://registry.yarnpkg.com/@csstools/css-parser-algorithms/-/css-parser-algorithms-4.0.3.tgz#d3f9a5502b828fca49511a66aa274b279e15157d" + integrity sha512-EpCfUDaJtwohPHC7egoXxPGT/R1/WyyAhw87MKB/7BPPZvZU+IcEqo4er5FpLnby2Gvwt9Lpxy+WNEDyFjoXtA== + +"@csstools/css-syntax-patches-for-csstree@^1.1.3": + version "1.1.17" + resolved "https://registry.yarnpkg.com/@csstools/css-syntax-patches-for-csstree/-/css-syntax-patches-for-csstree-1.1.17.tgz#42b82855d0f0711f134619d9ac4a538617f0e3f3" + integrity sha512-IPx9W33+t0Yt5TVb+Y7oICrThOIry0TY6GuXfSHOatxA0uiHqbzi98Gai905lpBAX1m/LH7iI96e9jcI7Dkvxw== + "@csstools/css-tokenizer@^3.0.4": version "3.0.4" resolved "https://registry.yarnpkg.com/@csstools/css-tokenizer/-/css-tokenizer-3.0.4.tgz#333fedabc3fd1a8e5d0100013731cf19e6a8c5d3" integrity sha512-Vd/9EVDiu6PPJt9yAh6roZP6El1xHrdvIVGjyBsHR0RYwNHgL7FJPyIIW4fANJNG6FtyZfvlRPpFI4ZM/lubvw== +"@csstools/css-tokenizer@^4.0.0": + version "4.0.3" + resolved "https://registry.yarnpkg.com/@csstools/css-tokenizer/-/css-tokenizer-4.0.3.tgz#eeab5057075343851c12b5181bd6efb463b0dd11" + integrity sha512-gdkFe/Z4KU1q8Y5S3GYScXGcOnO56dgWwIs5+97Ij1VIKISItOIUlCXUq4VLbdnRclF+SSQ49sLsn3KeV111AA== + "@csstools/media-query-list-parser@^4.0.3": version "4.0.3" resolved "https://registry.yarnpkg.com/@csstools/media-query-list-parser/-/media-query-list-parser-4.0.3.tgz#7aec77bcb89c2da80ef207e73f474ef9e1b3cdf1" @@ -2223,7 +2295,7 @@ lodash "^4.17.21" tslib "^2.6.0" -"@docusaurus/utils@3.10.2": +"@docusaurus/utils@3.10.2", "@docusaurus/utils@^3.10.2": version "3.10.2" resolved "https://registry.yarnpkg.com/@docusaurus/utils/-/utils-3.10.2.tgz#d99c1ffc5c7961e912344269a8728ce2aad8b3dc" integrity sha512-xx0W3eav2uW1NRIpuHJWNwLTC15xPNjU4Uxi9NSnd3swYC96BE3vFiT93SD8s24kmAAWNwgZwfZ2fghGZ01Lcw== @@ -2250,6 +2322,11 @@ utility-types "^3.10.0" webpack "^5.88.1" +"@exodus/bytes@^1.11.0", "@exodus/bytes@^1.15.0", "@exodus/bytes@^1.6.0": + version "1.16.0" + resolved "https://registry.yarnpkg.com/@exodus/bytes/-/bytes-1.16.0.tgz#954c9d9dd7eec15b966b2e8f2d883c04295b720c" + integrity sha512-IcpW84uEn3N7ETtNZMlxKhfl6Pec8rUNGOTBtWbK1FKhJxIFAptZyVrvVRVBimAJxJCgc3PxepxkdWWG4DVzfA== + "@exodus/schemasafe@^1.0.0-rc.2": version "1.3.0" resolved "https://registry.yarnpkg.com/@exodus/schemasafe/-/schemasafe-1.3.0.tgz#731656abe21e8e769a7f70a4d833e6312fe59b7f" @@ -3160,11 +3237,42 @@ dependencies: defer-to-connect "^2.0.1" +"@testing-library/dom@^10.4.2": + version "10.4.2" + resolved "https://registry.yarnpkg.com/@testing-library/dom/-/dom-10.4.2.tgz#e996827c4e5e1f13589527293b4b3958de2f709f" + integrity sha512-yzr2S9HyAIdhz2/6qHgbs665Q7PKVcDF05vsOlHPxG1mo36gKVesdYVeDLnXgfjJ03CrKRk08knc6+E/9m8v2Q== + dependencies: + "@babel/code-frame" "^7.10.4" + "@babel/runtime" "^7.12.5" + "@types/aria-query" "^5.0.1" + aria-query "5.3.0" + dom-accessibility-api "^0.5.9" + lz-string "^1.5.0" + picocolors "1.1.1" + pretty-format "^27.0.2" + +"@testing-library/react@^16.3.3": + version "16.3.3" + resolved "https://registry.yarnpkg.com/@testing-library/react/-/react-16.3.3.tgz#426907e7716f37038dab8aa69d8f0459f9ec24b2" + integrity sha512-Uo193NgQbPMz6lrrhtRQQFcMC6Re/ELLFbbuVL30WDlZxlpZf9/lMHTAVxPRLw1q1iu9OJmR1c2BLiENRstdBg== + dependencies: + "@babel/runtime" "^7.12.5" + +"@testing-library/user-event@^14.6.13": + version "14.6.13" + resolved "https://registry.yarnpkg.com/@testing-library/user-event/-/user-event-14.6.13.tgz#00a33d2a57730090336f0d7cbd11aa72968c2a5a" + integrity sha512-2LVZGptuB5un1Cu/u31o9adkCwbsUTMp4B4p04xupI7uobvTIpgKidSdShqZiReo/mQmvR9xjgdgTgge4oAbYA== + "@tsconfig/docusaurus@^2.0.3": version "2.0.9" resolved "https://registry.yarnpkg.com/@tsconfig/docusaurus/-/docusaurus-2.0.9.tgz#e530ae78bca4f88917af48fe25a944d6d6bdcdf5" integrity sha512-0jVxZCgy2v7TnJrW9kVNikNwJHeiWb68Zhiiw2vHw4tzBFSP5vS2zn3O5EY2oPEVz5dXZRkK7MnWG3Ay5q0mIg== +"@types/aria-query@^5.0.1": + version "5.0.4" + resolved "https://registry.yarnpkg.com/@types/aria-query/-/aria-query-5.0.4.tgz#1a31c3d378850d2778dabb6374d036dcba4ba708" + integrity sha512-rfT93uj5s0PRL7EzccGMs3brplhcrghnDoV26NqKhCAS1hVo+WdNsPvE/yb6ilfr5hi2MEk6d5EWJTKdxg8jVw== + "@types/body-parser@*": version "1.19.6" resolved "https://registry.yarnpkg.com/@types/body-parser/-/body-parser-1.19.6.tgz#1859bebb8fd7dac9918a45d54c1971ab8b5af474" @@ -4026,6 +4134,11 @@ ansi-styles@^4.0.0, ansi-styles@^4.1.0: dependencies: color-convert "^2.0.1" +ansi-styles@^5.0.0: + version "5.2.0" + resolved "https://registry.yarnpkg.com/ansi-styles/-/ansi-styles-5.2.0.tgz#07449690ad45777d1924ac2abb2fc8895dba836b" + integrity sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA== + ansi-styles@^6.1.0: version "6.2.3" resolved "https://registry.yarnpkg.com/ansi-styles/-/ansi-styles-6.2.3.tgz#c044d5dcc521a076413472597a1acb1f103c4041" @@ -4059,6 +4172,13 @@ argparse@^2.0.1: resolved "https://registry.yarnpkg.com/argparse/-/argparse-2.0.1.tgz#246f50f3ca78a3240f6c997e8a9bd1eac49e4b38" integrity sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q== +aria-query@5.3.0: + version "5.3.0" + resolved "https://registry.yarnpkg.com/aria-query/-/aria-query-5.3.0.tgz#650c569e41ad90b51b3d7df5e5eed1c7549c103e" + integrity sha512-b0P0sZPKtyu8HkeRAfCq0IfURZK+SuwMjY1UXGBU27wpAiTwQAIlq56IbIO+ytk/JjS1fMR14ee5WBBfKi5J6A== + dependencies: + dequal "^2.0.3" + array-flatten@1.1.1: version "1.1.1" resolved "https://registry.yarnpkg.com/array-flatten/-/array-flatten-1.1.1.tgz#9a5f699051b1e7073328f2a008968b64ea2955d2" @@ -4223,6 +4343,13 @@ bcp-47-match@^2.0.0: resolved "https://registry.yarnpkg.com/bcp-47-match/-/bcp-47-match-2.0.3.tgz#603226f6e5d3914a581408be33b28a53144b09d0" integrity sha512-JtTezzbAibu8G0R9op9zb3vcWZd9JF6M0xOYGPn0fNCd7wOpRB1mU2mH9T8gaBGbAAyIIVgB2G7xG0GP98zMAQ== +bidi-js@^1.0.3: + version "1.1.0" + resolved "https://registry.yarnpkg.com/bidi-js/-/bidi-js-1.1.0.tgz#c92efafe3fce3b9fdd30ba67bdddf0dd4d424af7" + integrity sha512-fX1Onk0tdVPC7obPWB5EbJ1z7NVhLq4m2xZLq2YXBkxzMXIGRpNMU88n0EPgWseKl12J7zXs7qrDxPK4sRs2fg== + dependencies: + require-from-string "^2.0.2" + big.js@^5.2.2: version "5.2.2" resolved "https://registry.yarnpkg.com/big.js/-/big.js-5.2.2.tgz#65f0af382f578bcdc742bd9c281e9cb2d7768328" @@ -5003,6 +5130,14 @@ css-tree@^2.3.1: mdn-data "2.0.30" source-map-js "^1.0.1" +css-tree@^3.2.1: + version "3.2.1" + resolved "https://registry.yarnpkg.com/css-tree/-/css-tree-3.2.1.tgz#86cac7011561272b30e6b1e042ba6ce047aa7518" + integrity sha512-X7sjQzceUhu1u7Y/ylrRZFU2FS6LRiFVp6rKLPg23y3x3c3DOKAwuXGDp+PAGjh6CSnCjYeAul8pcT8bAl+lSA== + dependencies: + mdn-data "2.27.1" + source-map-js "^1.2.1" + css-tree@~2.2.0: version "2.2.1" resolved "https://registry.yarnpkg.com/css-tree/-/css-tree-2.2.1.tgz#36115d382d60afd271e377f9c5f67d02bd48c032" @@ -5398,6 +5533,14 @@ dagre-d3-es@7.0.14: d3 "^7.9.0" lodash-es "^4.17.21" +data-urls@^7.0.0: + version "7.0.0" + resolved "https://registry.yarnpkg.com/data-urls/-/data-urls-7.0.0.tgz#6dce8b63226a1ecfdd907ce18a8ccfb1eee506d3" + integrity sha512-23XHcCF+coGYevirZceTVD7NdJOqVn+49IHyxgszm+JIiHLoB2TkmPtsYkNWT1pvRSGkc35L6NHs0yHkN2SumA== + dependencies: + whatwg-mimetype "^5.0.0" + whatwg-url "^16.0.0" + dayjs@^1.11.20: version "1.11.21" resolved "https://registry.yarnpkg.com/dayjs/-/dayjs-1.11.21.tgz#57f87562e62de76f3c704bd2b8d522fc33068eb2" @@ -5422,6 +5565,11 @@ debug@^4.0.0, debug@^4.1.0, debug@^4.3.1, debug@^4.4.3: dependencies: ms "^2.1.3" +decimal.js@^10.6.0: + version "10.6.0" + resolved "https://registry.yarnpkg.com/decimal.js/-/decimal.js-10.6.0.tgz#e649a43e3ab953a72192ff5983865e509f37ed9a" + integrity sha512-YpgQiITW3JXGntzdUmyUR1V812Hn8T1YVXhCu+wO3OpS4eU9l4YdD3qjyiKdV6mvV29zapkMeD390UVEf2lkUg== + decode-named-character-reference@^1.0.0: version "1.3.0" resolved "https://registry.yarnpkg.com/decode-named-character-reference/-/decode-named-character-reference-1.3.0.tgz#3e40603760874c2e5867691b599d73a7da25b53f" @@ -5509,7 +5657,7 @@ depd@~1.1.2: resolved "https://registry.yarnpkg.com/depd/-/depd-1.1.2.tgz#9bcd52e14c097763e749b274c4346ed2e560b5a9" integrity sha512-7emPTl6Dpo6JRXOXjLRxck+FlLRX5847cLKEn00PLAgc3g2hTZZgr+e4c2v6QpSmLeFP3n5yUo7ft6avBK/5jQ== -dequal@^2.0.0: +dequal@^2.0.0, dequal@^2.0.3: version "2.0.3" resolved "https://registry.yarnpkg.com/dequal/-/dequal-2.0.3.tgz#2644214f1997d39ed0ee0ece72335490a7ac67be" integrity sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA== @@ -5631,6 +5779,11 @@ docusaurus-theme-openapi-docs@^5.1.3: url "^0.11.4" xml-formatter "^3.6.6" +dom-accessibility-api@^0.5.9: + version "0.5.16" + resolved "https://registry.yarnpkg.com/dom-accessibility-api/-/dom-accessibility-api-0.5.16.tgz#5a7429e6066eb3664d911e33fb0e45de8eb08453" + integrity sha512-X7BJ2yElsnOJ30pZF4uIIDfBEVgF4XEBxL9Bxhy6dnrm5hkzqmsWHGTiHqRiITNhMyFLyAiWndIJP7Z1NTteDg== + dom-converter@^0.2.0: version "0.2.0" resolved "https://registry.yarnpkg.com/dom-converter/-/dom-converter-0.2.0.tgz#6721a9daee2e293682955b6afe416771627bb768" @@ -5809,6 +5962,11 @@ entities@^6.0.0: resolved "https://registry.yarnpkg.com/entities/-/entities-6.0.1.tgz#c28c34a43379ca7f61d074130b2f5f7020a30694" integrity sha512-aN97NXWF6AWBTahfVOIrB/NShkzi5H7F9r1s9mD3cDj4Ko5f2qhhVoYMibXF7GlLveb/D2ioWay8lxI97Ven3g== +entities@^9.0.0: + version "9.0.0" + resolved "https://registry.yarnpkg.com/entities/-/entities-9.0.0.tgz#c45df3cdbc5ce805474759f4ec4ea7907d9d5477" + integrity sha512-oJFNDJg3kTPwAD1cNn2+WmUq4wFoo09npc3Ydf1D7ED4smRiWrsKnaLxykrTWgyGEcusc87P5dxlAleol9kpkg== + error-ex@^1.3.1: version "1.3.4" resolved "https://registry.yarnpkg.com/error-ex/-/error-ex-1.3.4.tgz#b3a8d8bb6f92eecc1629e3e27d3c8607a8a32414" @@ -6782,6 +6940,13 @@ hpack.js@^2.1.6: readable-stream "^2.0.1" wbuf "^1.1.0" +html-encoding-sniffer@^6.0.0: + version "6.0.0" + resolved "https://registry.yarnpkg.com/html-encoding-sniffer/-/html-encoding-sniffer-6.0.0.tgz#f8d9390b3b348b50d4f61c16dd2ef5c05980a882" + integrity sha512-CV9TW3Y3f8/wT0BRFc1/KAVQ3TUHiXmaAb6VW9vtiMFf7SLoMd1PdAc4W3KFOFETBJUb90KatHqlsZMWV+R9Gg== + dependencies: + "@exodus/bytes" "^1.6.0" + html-escaper@^2.0.2: version "2.0.2" resolved "https://registry.yarnpkg.com/html-escaper/-/html-escaper-2.0.2.tgz#dfd60027da36a36dfcbe236262c00a5822681453" @@ -7229,6 +7394,11 @@ is-plain-object@^2.0.4: dependencies: isobject "^3.0.1" +is-potential-custom-element-name@^1.0.1: + version "1.0.1" + resolved "https://registry.yarnpkg.com/is-potential-custom-element-name/-/is-potential-custom-element-name-1.0.1.tgz#171ed6f19e3ac554394edf78caa05784a45bebb5" + integrity sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ== + is-regexp@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/is-regexp/-/is-regexp-1.0.0.tgz#fd2d883545c46bac5a633e7b9a09e87fa2cb5069" @@ -7368,6 +7538,33 @@ js-yaml@^5.2.2: dependencies: argparse "^2.0.1" +jsdom@^29.1.1: + version "29.1.1" + resolved "https://registry.yarnpkg.com/jsdom/-/jsdom-29.1.1.tgz#5b9704906f3cd510c34aa941ae2f8f7f8179df01" + integrity sha512-ECi4Fi2f7BdJtUKTflYRTiaMxIB0O6zfR1fX0GXpUrf6flp8QIYn1UT20YQqdSOfk2dfkCwS8LAFoJDEppNK5Q== + dependencies: + "@asamuzakjp/css-color" "^5.1.11" + "@asamuzakjp/dom-selector" "^7.1.1" + "@bramus/specificity" "^2.4.2" + "@csstools/css-syntax-patches-for-csstree" "^1.1.3" + "@exodus/bytes" "^1.15.0" + css-tree "^3.2.1" + data-urls "^7.0.0" + decimal.js "^10.6.0" + html-encoding-sniffer "^6.0.0" + is-potential-custom-element-name "^1.0.1" + lru-cache "^11.3.5" + parse5 "^8.0.1" + saxes "^6.0.0" + symbol-tree "^3.2.4" + tough-cookie "^6.0.1" + undici "^7.25.0" + w3c-xmlserializer "^5.0.0" + webidl-conversions "^8.0.1" + whatwg-mimetype "^5.0.0" + whatwg-url "^16.0.1" + xml-name-validator "^5.0.0" + jsesc@^3.0.2, jsesc@~3.1.0: version "3.1.0" resolved "https://registry.yarnpkg.com/jsesc/-/jsesc-3.1.0.tgz#74d335a234f67ed19907fdadfac7ccf9d409825d" @@ -7583,6 +7780,11 @@ lowercase-keys@^3.0.0: resolved "https://registry.yarnpkg.com/lowercase-keys/-/lowercase-keys-3.0.0.tgz#c5e7d442e37ead247ae9db117a9d0a467c89d4f2" integrity sha512-ozCC6gdQ+glXOQsveKD0YsDy8DSQFjDTz4zyzEHNV5+JP5D62LmfDZ6o1cycFx9ouG940M5dE8C8CTewdj2YWQ== +lru-cache@^11.3.5: + version "11.5.4" + resolved "https://registry.yarnpkg.com/lru-cache/-/lru-cache-11.5.4.tgz#6073dda1feb2a438e568f791fd13fffa223be76f" + integrity sha512-B8nJCTi8JuSaDBg0tBdnImV6j5O2CXaqKfdj24ZTCFbyivN8KZ2Z+RL3aHjwJAfLutD9cNnObG4SIgW4gMufiw== + lru-cache@^5.1.1: version "5.1.1" resolved "https://registry.yarnpkg.com/lru-cache/-/lru-cache-5.1.1.tgz#1da27e6710271947695daf6848e847f01d84b920" @@ -7590,6 +7792,11 @@ lru-cache@^5.1.1: dependencies: yallist "^3.0.2" +lz-string@^1.5.0: + version "1.5.0" + resolved "https://registry.yarnpkg.com/lz-string/-/lz-string-1.5.0.tgz#c1ab50f77887b712621201ba9fd4e3a6ed099941" + integrity sha512-h5bgJWpxJNswbU7qCrV0tIKQCaS3blPDrqKWx+QxzuzL1zGUzij9XCWLrSLsJPu5t+eWA/ycetzYAO5IOMcWAQ== + markdown-extensions@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/markdown-extensions/-/markdown-extensions-2.0.0.tgz#34bebc83e9938cae16e0e017e4a9814a8330d3c4" @@ -7838,6 +8045,11 @@ mdn-data@2.0.30: resolved "https://registry.yarnpkg.com/mdn-data/-/mdn-data-2.0.30.tgz#ce4df6f80af6cfbe218ecd5c552ba13c4dfa08cc" integrity sha512-GaqWWShW4kv/G9IEucWScBx9G1/vsFZZJUO+tD26M8J8z3Kw5RDQjaoZe03YAClgeS/SWPOcb4nkFBTEi5DUEA== +mdn-data@2.27.1: + version "2.27.1" + resolved "https://registry.yarnpkg.com/mdn-data/-/mdn-data-2.27.1.tgz#e37b9c50880b75366c4d40ac63d9bbcacdb61f0e" + integrity sha512-9Yubnt3e8A0OKwxYSXyhLymGW4sCufcLG6VdiDdUGVkPhpqLxlvP5vl1983gQjJl3tqbrM731mjaZaP68AgosQ== + media-typer@0.3.0: version "0.3.0" resolved "https://registry.yarnpkg.com/media-typer/-/media-typer-0.3.0.tgz#8710d7af0aa626f8fffa1ce00168545263255748" @@ -8929,6 +9141,13 @@ parse5@^7.0.0: dependencies: entities "^6.0.0" +parse5@^8.0.1: + version "8.1.1" + resolved "https://registry.yarnpkg.com/parse5/-/parse5-8.1.1.tgz#d73eb52282024c921e9c5a19b870f53492e631b2" + integrity sha512-EcR/6WDcU7b2N3vQSxKALCk9lXGtUMQxXio008OEMBE0kavu/7JLfBEeFPzi43nMqVDSbEn3QCK+BMCc9zO//w== + dependencies: + entities "^9.0.0" + parseurl@~1.3.3: version "1.3.3" resolved "https://registry.yarnpkg.com/parseurl/-/parseurl-1.3.3.tgz#9da19e7bee8d12dff0513ed5b76957793bc2e8d4" @@ -8999,7 +9218,7 @@ path-type@^4.0.0: resolved "https://registry.yarnpkg.com/path-type/-/path-type-4.0.0.tgz#84ed01c0a7ba380afe09d90a8c180dcd9d03043b" integrity sha512-gDKb8aZMDeD/tZWs9P6+q0J9Mwkdl6xMV8TjnGP3qJVJ06bdMgkbBlLU8IdfOsIsFz2BW1rNVT3XuNEl8zPAvw== -picocolors@^1.0.0, picocolors@^1.1.1: +picocolors@1.1.1, picocolors@^1.0.0, picocolors@^1.1.1: version "1.1.1" resolved "https://registry.yarnpkg.com/picocolors/-/picocolors-1.1.1.tgz#3d321af3eab939b083c8f929a1d12cda81c26b6b" integrity sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA== @@ -9690,6 +9909,15 @@ pretty-error@^4.0.0: lodash "^4.17.20" renderkid "^3.0.0" +pretty-format@^27.0.2: + version "27.5.1" + resolved "https://registry.yarnpkg.com/pretty-format/-/pretty-format-27.5.1.tgz#2181879fdea51a7a5851fb39d920faa63f01d88e" + integrity sha512-Qb1gy5OrP5+zDf2Bvnzdl3jsTf1qXVMazbvCoKhtKqVs4/YK4ozX4gKQJJVyNe+cajNPn0KoC0MC3FUmaHWEmQ== + dependencies: + ansi-regex "^5.0.1" + ansi-styles "^5.0.0" + react-is "^17.0.1" + pretty-time@^1.1.0: version "1.1.0" resolved "https://registry.yarnpkg.com/pretty-time/-/pretty-time-1.1.0.tgz#ffb7429afabb8535c346a34e41873adf3d74dd0e" @@ -9886,6 +10114,11 @@ react-is@^16.13.1, react-is@^16.6.0, react-is@^16.7.0: resolved "https://registry.yarnpkg.com/react-is/-/react-is-16.13.1.tgz#789729a4dc36de2999dc156dd6c1d9c18cea56a4" integrity sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ== +react-is@^17.0.1: + version "17.0.2" + resolved "https://registry.yarnpkg.com/react-is/-/react-is-17.0.2.tgz#e691d4a8e9c789365655539ab372762b0efb54f0" + integrity sha512-w2GsyukL62IJnlaff/nRegPQR94C/XXamvMWmSHRJ4y7Ts/4ocGRmTHvOs8PSE6pB3dWOrD/nueuU5sduBsQ4w== + react-json-view-lite@^2.3.0: version "2.5.0" resolved "https://registry.yarnpkg.com/react-json-view-lite/-/react-json-view-lite-2.5.0.tgz#c7ff011c7cc80e9900abc7aa4916c6a5c6d6c1c6" @@ -10463,6 +10696,13 @@ sax@^1.2.4, sax@^1.5.0: resolved "https://registry.yarnpkg.com/sax/-/sax-1.6.0.tgz#da59637629307b97e7c4cb28e080a7bc38560d5b" integrity sha512-6R3J5M4AcbtLUdZmRv2SygeVaM7IhrLXu9BmnOGmmACak8fiUtOsYNWUS4uK7upbmHIBbLBeFeI//477BKLBzA== +saxes@^6.0.0: + version "6.0.0" + resolved "https://registry.yarnpkg.com/saxes/-/saxes-6.0.0.tgz#fe5b4a4768df4f14a201b1ba6a65c1f3d9988cc5" + integrity sha512-xAg7SOnEhrm5zI3puOOKyy1OMcMlIJZYNJY7xLBwSze0UjhPLnWfj2GF2EpT0jmzaJKIWKHLsaSSajf35bcYnA== + dependencies: + xmlchars "^2.2.0" + scheduler@^0.23.2: version "0.23.2" resolved "https://registry.yarnpkg.com/scheduler/-/scheduler-0.23.2.tgz#414ba64a3b282892e944cf2108ecc078d115cdc3" @@ -11110,6 +11350,11 @@ swc-loader@^0.2.6: dependencies: "@swc/counter" "^0.1.3" +symbol-tree@^3.2.4: + version "3.2.4" + resolved "https://registry.yarnpkg.com/symbol-tree/-/symbol-tree-3.2.4.tgz#430637d248ba77e078883951fb9aa0eed7c63fa2" + integrity sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw== + tapable@^2.0.0, tapable@^2.2.1, tapable@^2.3.0, tapable@^2.3.3: version "2.3.3" resolved "https://registry.yarnpkg.com/tapable/-/tapable-2.3.3.tgz#5da7c9992c46038221267985ab28421a8879f160" @@ -11253,6 +11498,18 @@ tinypool@^1.0.2: resolved "https://registry.yarnpkg.com/tinypool/-/tinypool-1.1.1.tgz#059f2d042bd37567fbc017d3d426bdd2a2612591" integrity sha512-Zba82s87IFq9A9XmjiX5uZA/ARWDrB03OHlq+Vw1fSdt0I+4/Kutwy8BP4Y/y/aORMo61FQ0vIb5j44vSo5Pkg== +tldts-core@^7.6.4: + version "7.6.4" + resolved "https://registry.yarnpkg.com/tldts-core/-/tldts-core-7.6.4.tgz#ea3d475cf0f09564d54fb5dcd73289d1a74828c5" + integrity sha512-QywQ9lgQyZMuc3NVlqmuxHOhlwirSdvgD/vDLvX8dZYcYgy1cdri5rY/TXDHcF4J3VBSdJLcJNIJI6zGJ7jE+w== + +tldts@^7.0.5: + version "7.6.4" + resolved "https://registry.yarnpkg.com/tldts/-/tldts-7.6.4.tgz#4cf4a818a4309916a634b6de46fa6130375f96e3" + integrity sha512-wp+ZdvQyov404xynNcjbXoJyeGM28W/aCwMmry/rJ+Y0SsObukJYkWwuxWGbNpIjeqMaEbNUtXPNtPPfI5cTFA== + dependencies: + tldts-core "^7.6.4" + to-regex-range@^5.0.1: version "5.0.1" resolved "https://registry.yarnpkg.com/to-regex-range/-/to-regex-range-5.0.1.tgz#1648c44aae7c8d988a326018ed72f5b4dd0392e4" @@ -11270,6 +11527,20 @@ totalist@^3.0.0: resolved "https://registry.yarnpkg.com/totalist/-/totalist-3.0.1.tgz#ba3a3d600c915b1a97872348f79c127475f6acf8" integrity sha512-sf4i37nQ2LBx4m3wB74y+ubopq6W/dIzXg0FDGjsYnZHVa1Da8FH853wlL2gtUhg+xJXjfk3kUZS3BRoQeoQBQ== +tough-cookie@^6.0.1: + version "6.1.0" + resolved "https://registry.yarnpkg.com/tough-cookie/-/tough-cookie-6.1.0.tgz#eafa6e331d2b948cdd73d75ee1190cb5a8f0df0d" + integrity sha512-FTxc8u8Kl2tz0Lat1u8ksvcy8bwHRyEMawwTWybo51JqaC6O7SvfuhAKg+Ld6VqyIe2QRJBzY9HA7y2WyFRT2w== + dependencies: + tldts "^7.0.5" + +tr46@^6.0.0: + version "6.0.0" + resolved "https://registry.yarnpkg.com/tr46/-/tr46-6.0.0.tgz#f5a1ae546a0adb32a277a2278d0d17fa2f9093e6" + integrity sha512-bLVMLPtstlZ4iMQHpFHTR7GAGj2jxi8Dg0s2h2MafAE4uSWF98FC/3MomU51iQAMf8/qDUbKWf5GxuvvVcXEhw== + dependencies: + punycode "^2.3.1" + tr46@~0.0.3: version "0.0.3" resolved "https://registry.yarnpkg.com/tr46/-/tr46-0.0.3.tgz#8184fd347dac9cdc185992f3a6622e14b9d9ab6a" @@ -11374,6 +11645,11 @@ undici@^6.28.0: resolved "https://registry.yarnpkg.com/undici/-/undici-6.28.0.tgz#9f0e385744fef5021d6596c5bccd783f61193c1c" integrity sha512-LIY910g9TI13YS95lrMFrs8Rm/u/irgHeTWoKCoteeJ04CUJ92eEfj0rVn+7VKMPBpUPiUoBKfhNyLI23EE/KA== +undici@^7.25.0: + version "7.30.2" + resolved "https://registry.yarnpkg.com/undici/-/undici-7.30.2.tgz#26c6acb0ffe838f823511f8cb79a8d530652135e" + integrity sha512-mLyPQnHwUxaM/rideoK/+KL8DaAJLRl4aBCfmX444aCSLnIaomqPLtNRe2jdCYcsk5wZzXrDIQC8ZeYNRAYyIA== + unicode-canonical-property-names-ecmascript@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/unicode-canonical-property-names-ecmascript/-/unicode-canonical-property-names-ecmascript-2.0.1.tgz#cb3173fe47ca743e228216e4a3ddc4c84d628cc2" @@ -11658,6 +11934,13 @@ vfile@^6.0.0, vfile@^6.0.1: "@types/unist" "^3.0.0" vfile-message "^4.0.0" +w3c-xmlserializer@^5.0.0: + version "5.0.0" + resolved "https://registry.yarnpkg.com/w3c-xmlserializer/-/w3c-xmlserializer-5.0.0.tgz#f925ba26855158594d907313cedd1476c5967f6c" + integrity sha512-o8qghlI8NZHU1lLPrpi2+Uq7abh4GGPpYANlalzWxyWteJOCsr/P+oPBA49TOLu5FTZO4d3F9MnWJfiMo4BkmA== + dependencies: + xml-name-validator "^5.0.0" + warning@^4.0.3: version "4.0.3" resolved "https://registry.yarnpkg.com/warning/-/warning-4.0.3.tgz#16e9e077eb8a86d6af7d64aa1e05fd85b4678ca3" @@ -11689,6 +11972,11 @@ webidl-conversions@^3.0.0: resolved "https://registry.yarnpkg.com/webidl-conversions/-/webidl-conversions-3.0.1.tgz#24534275e2a7bc6be7bc86611cc16ae0a5654871" integrity sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ== +webidl-conversions@^8.0.1: + version "8.0.1" + resolved "https://registry.yarnpkg.com/webidl-conversions/-/webidl-conversions-8.0.1.tgz#0657e571fe6f06fcb15ca50ed1fdbcb495cd1686" + integrity sha512-BMhLD/Sw+GbJC21C/UgyaZX41nPt8bUTg+jWyDeg7e7YN4xOM05YPSIXceACnXVtqyEw/LMClUQMtMZ+PGGpqQ== + webpack-bundle-analyzer@^4.10.2: version "4.10.2" resolved "https://registry.yarnpkg.com/webpack-bundle-analyzer/-/webpack-bundle-analyzer-4.10.2.tgz#633af2862c213730be3dbdf40456db171b60d5bd" @@ -11826,6 +12114,20 @@ websocket-extensions@>=0.1.1: resolved "https://registry.yarnpkg.com/websocket-extensions/-/websocket-extensions-0.1.4.tgz#7f8473bc839dfd87608adb95d7eb075211578a42" integrity sha512-OqedPIGOfsDlo31UNwYbCFMSaO9m9G/0faIHj5/dZFDMFqPTcx6UwqyOy3COEaEOg/9VsGIpdqn62W5KhoKSpg== +whatwg-mimetype@^5.0.0: + version "5.0.0" + resolved "https://registry.yarnpkg.com/whatwg-mimetype/-/whatwg-mimetype-5.0.0.tgz#d8232895dbd527ceaee74efd4162008fb8a8cf48" + integrity sha512-sXcNcHOC51uPGF0P/D4NVtrkjSU2fNsm9iog4ZvZJsL3rjoDAzXZhkm2MWt1y+PUdggKAYVoMAIYcs78wJ51Cw== + +whatwg-url@^16.0.0, whatwg-url@^16.0.1: + version "16.0.1" + resolved "https://registry.yarnpkg.com/whatwg-url/-/whatwg-url-16.0.1.tgz#047f7f4bd36ef76b7198c172d1b1cebc66f764dd" + integrity sha512-1to4zXBxmXHV3IiSSEInrreIlu02vUOvrhxJJH5vcxYTBDAx51cqZiKdyTxlecdKNSjj8EcxGBxNf6Vg+945gw== + dependencies: + "@exodus/bytes" "^1.11.0" + tr46 "^6.0.0" + webidl-conversions "^8.0.1" + whatwg-url@^5.0.0: version "5.0.0" resolved "https://registry.yarnpkg.com/whatwg-url/-/whatwg-url-5.0.0.tgz#966454e8765462e37644d3626f6742ce8b70965d" @@ -11922,11 +12224,21 @@ xml-js@^1.6.11: dependencies: sax "^1.2.4" +xml-name-validator@^5.0.0: + version "5.0.0" + resolved "https://registry.yarnpkg.com/xml-name-validator/-/xml-name-validator-5.0.0.tgz#82be9b957f7afdacf961e5980f1bf227c0bf7673" + integrity sha512-EvGK8EJ3DhaHfbRlETOWAS5pO9MZITeauHKJyb8wyajUfQUenkIg2MvLDTZ4T/TgIcm3HU0TFBgWWboAZ30UHg== + xml-parser-xo@^4.1.5: version "4.1.6" resolved "https://registry.yarnpkg.com/xml-parser-xo/-/xml-parser-xo-4.1.6.tgz#22bb2d0e1f651f92de04c7b79433a9df6f1490f2" integrity sha512-mXbSNSM+rIwndoxSwmFa83bOdeP8G/cOGr7XvxA67X7ebCzoAuVez9JYDCDub3zRDNBZxIbfjuXLSsamr7NfwQ== +xmlchars@^2.2.0: + version "2.2.0" + resolved "https://registry.yarnpkg.com/xmlchars/-/xmlchars-2.2.0.tgz#060fe1bcb7f9c76fe2a17db86a9bc3ab894210cb" + integrity sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw== + y18n@^5.0.5: version "5.0.8" resolved "https://registry.yarnpkg.com/y18n/-/y18n-5.0.8.tgz#7f4934d0f7ca8c56f95314939ddcd2dd91ce1d55"