@tdacorp/hyle-sdk 0.3.0 → 0.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/README.md +135 -5
  2. package/bin/hyle-sdk-check-routes.mjs +3 -0
  3. package/dist/check-routes-bin.js +537 -0
  4. package/dist/chunk-67IOIAVW.js +35 -0
  5. package/dist/chunk-BUJFMR3M.js +38 -0
  6. package/dist/chunk-EBNIKRQH.js +536 -0
  7. package/dist/{chunk-EARQBSMF.js → chunk-LGW2KP4X.js} +109 -5
  8. package/dist/{chunk-7VCMJUPC.js → chunk-N4QYPO7S.js} +1 -1
  9. package/dist/diagram-viewer-DYX6R63Y.js +1132 -0
  10. package/dist/index.cjs +279 -23
  11. package/dist/index.d.cts +147 -3
  12. package/dist/index.d.ts +147 -3
  13. package/dist/index.js +18 -1
  14. package/dist/mermaid-diagram.cjs +1267 -16
  15. package/dist/mermaid-diagram.d.cts +39 -1
  16. package/dist/mermaid-diagram.d.ts +39 -1
  17. package/dist/mermaid-diagram.js +35 -5
  18. package/dist/next.cjs +385 -30
  19. package/dist/next.d.cts +93 -5
  20. package/dist/next.d.ts +93 -5
  21. package/dist/next.js +210 -5
  22. package/dist/react.cjs +118 -5
  23. package/dist/react.d.cts +44 -4
  24. package/dist/react.d.ts +44 -4
  25. package/dist/react.js +2 -1
  26. package/dist/{resolve-fMx2W8RR.d.ts → resolve-1rQntRBh.d.ts} +1 -1
  27. package/dist/{resolve-B_p0p4Zn.d.cts → resolve-36-Ng1H0.d.cts} +1 -1
  28. package/dist/styles.css +76 -0
  29. package/dist/{types-CBvLhUPr.d.ts → types-BoyBWF2F.d.ts} +1 -1
  30. package/dist/{types-DjXf6iPo.d.cts → types-CwBCPh6K.d.cts} +20 -1
  31. package/dist/{types-DjXf6iPo.d.ts → types-CwBCPh6K.d.ts} +20 -1
  32. package/dist/{types-D0qoLh4E.d.cts → types-DnPzhrFx.d.cts} +1 -1
  33. package/dist/use-cache.cjs +55 -23
  34. package/dist/use-cache.d.cts +2 -2
  35. package/dist/use-cache.d.ts +2 -2
  36. package/dist/use-cache.js +3 -2
  37. package/package.json +5 -1
  38. package/dist/chunk-HFUJRNFP.js +0 -290
package/README.md CHANGED
@@ -43,15 +43,22 @@ import { createRevalidateRoute } from "@tdacorp/hyle-sdk/next";
43
43
  export const { POST } = createRevalidateRoute({ workspaceId: process.env.HYLE_WORKSPACE_ID, secrets: [process.env.HYLE_WEBHOOK_SECRET] });
44
44
  ```
45
45
 
46
- Register that URL as the workspace's webhook endpoint in hyle. Set `metadataBase` in your root layout so canonical and hreflang URLs are absolute.
46
+ `app/api/hyle/assets/[file]/route.ts` (images, video and audio in hyle content; see "Media"):
47
+
48
+ ```ts
49
+ import { createAssetRoute } from "@tdacorp/hyle-sdk/next";
50
+ export const { GET, HEAD } = createAssetRoute({ baseUrl: process.env.HYLE_TARGET_BASE_URL, token: process.env.HYLE_TARGET_TOKEN });
51
+ ```
52
+
53
+ Register the revalidate URL as the workspace's webhook endpoint in hyle. Set `metadataBase` in your root layout so canonical and hreflang URLs are absolute.
47
54
 
48
55
  ## Entry points
49
56
 
50
57
  | Import | Contents | Needs |
51
58
  |---|---|---|
52
- | `@tdacorp/hyle-sdk` | `createHyleClient` (typed `resolve`), `listPublicationPaths`, `Cp1ClientError`, `verifyHyleSignature`, `parseSignatureHeader`, `isValidCacheTag`, `DeliveryDedupe`, `createRevalidationCallbackRoute`, the result types | nothing (no framework) |
59
+ | `@tdacorp/hyle-sdk` | `createHyleClient` (typed `resolve`, `mounts` and `asset`), `listPublicationPaths`, `checkRoutes` and the other route-check functions, `Cp1ClientError`, `verifyHyleSignature`, `parseSignatureHeader`, `isValidCacheTag`, `DeliveryDedupe`, `createRevalidationCallbackRoute`, the result types | nothing (no framework) |
53
60
  | `@tdacorp/hyle-sdk/react` | `ArticlePage`, `ListPage`, `DocsPage`, `NotFound`, `Redirecting`, `Unavailable`, `HastContent`, `TrustedServerHtml`, `sanitizeHast` | react >= 19 |
54
- | `@tdacorp/hyle-sdk/next` | `hylePage`, `hyleMetadata`, `hyleSitemap`, `createRevalidateRoute`, `fetchResolver`, `workspaceTags` | next >= 16 |
61
+ | `@tdacorp/hyle-sdk/next` | `hylePage`, `hyleMetadata`, `hyleSitemap`, `hyleRootPage`, `hyleRootMetadata`, `hyleRootSitemap`, `createRevalidateRoute`, `createAssetRoute`, `fetchResolver`, `workspaceTags` | next >= 16 |
55
62
  | `@tdacorp/hyle-sdk/next/use-cache` | `cachedResolver` | next >= 16 with `cacheComponents: true` |
56
63
  | `@tdacorp/hyle-sdk/styles.css` | the stylesheet | |
57
64
 
@@ -121,6 +128,88 @@ export default async function sitemap() {
121
128
 
122
129
  `origin` must be a bare https origin (anything else throws). URLs are percent-encoded and use `localePrefix`; the locale is `options.locale` when it is a string, and a function of the route params is never called (the sitemap is for the default locale). `lastModified` is `published_at` (omitted if it is not an ISO date): the list carries no `updated_at`. Only the default section and the `sections` you list are covered (a section's index resolves at `basePath/<slug>`), at most 2000 pages per index. `onIncomplete` decides what a hyle failure (or a listing cut off by the page limit) does: `"partial"` returns what was collected, `"throw"` throws so a build during an outage fails; the default throws only when nothing was collected. The core `listPublicationPaths({ client, basePath, sections?, locale?, maxPages? })` never throws and returns `{ paths: { path, publishedAt }[], complete }`, where `complete: false` means `paths` is partial.
123
130
 
131
+ ## Root catch-all
132
+
133
+ `hylePage` serves one mount you name (`/learn`). `hyleRootPage` instead hands hyle EVERY URL the host did not match, and asks hyle where it publishes (`GET /cp1/read/mounts`), so the host config no longer lists prefixes. It is the replacement for a site's `notFound()` catch-all.
134
+
135
+ ```tsx
136
+ // app/(site)/[...hyle]/page.tsx (a REQUIRED catch-all: [...hyle], not [[...hyle]])
137
+ import { hyleRootMetadata, hyleRootPage } from "@tdacorp/hyle-sdk/next";
138
+
139
+ const config = { baseUrl: process.env.HYLE_BASE_URL!, token: process.env.HYLE_TARGET_TOKEN!, workspaceId: process.env.HYLE_WORKSPACE_ID!,
140
+ locale: (p) => String(p.locale), localePrefix: (l) => (l === "en" ? "" : `/${l}`) };
141
+ export default hyleRootPage(config); // or hyleRootPage([configA, configB]) for several workspaces
142
+ export const generateMetadata = hyleRootMetadata(config);
143
+ // app/sitemap.ts: [...hostEntries, ...(await hyleRootSitemap(config, { origin: "https://tdacorp.in" }))]
144
+ ```
145
+
146
+ Options are those of `hylePage` without `basePath` (it comes from the mount) and `resolver`; `baseUrl`, `token` and `workspaceId` are required because the mounts are read through Next's fetch cache (tag `hyle:1:ws:<id>`, `revalidate` default 300). An array serves several workspaces from one site; the longest matching prefix wins across them and the first config wins a tie. All configs must use the same `param` (default `hyle`).
147
+
148
+ Why a REQUIRED catch-all: an optional catch-all at the app root (`[[...hyle]]`) also matches `/`, so it conflicts with the sibling `page.tsx` that every site has for its home page (verified: `next build` fails with "You cannot define a route with the same specificity as an optional catch-all route (\"/\" and \"/[[...hyle]]\")"). `[...hyle]` needs one or more segments, so the home page stays yours.
149
+
150
+ ### How it works, and why it does not interfere with the host
151
+
152
+ 1. Next matches specific routes before a catch-all. `/about`, `/api/x`, `/sitemap.xml` and every other page or route handler of the host never reach `hyleRootPage`; it only receives URLs nothing else matched. The host's matcher keeps `_next`, `api` and files with an extension out of any middleware or proxy exactly as before.
153
+ 2. For such a URL the page decodes the path once and refuses anything odd (encoded slash, `.` or `..`, empty segment, bad encoding, control characters, non-NFC) with a 404. It then compares it with the mounts: segment-boundary and case-sensitive (`/learn` matches `/learn` and `/learn/x`, never `/learnx` or `/Learn`; a root mount `/` matches the rest), longest prefix wins.
154
+ 3. No mount matches, or the path is reserved: `notFound()` at once. A workspace whose `reserved` list covers the path takes no part in the choice, so another workspace's mount (for example a root mount) can still serve it; the path is a 404 only when no remaining mount matches. hyle gets ZERO resolve calls, so junk URLs and bot probes cost one cached mounts lookup at most (the mounts are fetched once per workspace per revalidate window, not per URL).
155
+ 4. Otherwise the request is served by `hylePage` with `basePath` = the matched prefix: same locale handling, redirects, list and article pages, same failure rules.
156
+ 5. The app always wins a collision: a host page at a path hyle also publishes is served, hyle is not asked, and the hyle page is simply never shown. The three guards against that silent loss are hyle's Reserved paths (hyle refuses to publish onto them), the build-time checker below, and this precedence (so a collision can never break a host page).
157
+
158
+ ### Failure modes
159
+
160
+ | Situation | Result |
161
+ |---|---|
162
+ | Mounts answer 401 or 403 (revoked token, deprovisioned workspace) | the last good copy is dropped and the error is rethrown (Next keeps the last good ISR page; a first render is an uncached 500) |
163
+ | Mounts answer with a 4xx, or the read surface is switched off (`kind: "disabled"`) | nothing is served: 404. The last good copy is dropped, so the kill switch is not undone by a later outage |
164
+ | Mounts fail transiently (network, timeout, 5xx, 429, malformed body) and a copy read within the last 15 minutes exists | that copy decides: unmatched URLs stay a plain 404, mounted pages go on to `hylePage` (which keeps its own last-good-page rule) |
165
+ | Mounts fail transiently and there is no usable copy (a cold server, or a copy older than `MOUNTS_MAX_STALE_MS`, 15 minutes) | the error is rethrown: Next keeps the last good ISR page, a first render is an uncached 500. It is not guessed to be a 404, because the URL might be a mounted page |
166
+ | Root mount (`/`) and no usable copy | every unmatched URL errors until hyle is back (the root mount could own any of them) |
167
+ | hyle is down | the host's own pages are unaffected: they never call hyle |
168
+
169
+ The last good copy is in process memory, keyed by hyle origin plus workspace id (never the token). Next's fetch cache serves a stale mounts response while a refresh fails, so in practice the in-memory copy is a second layer.
170
+
171
+ ### Adopting it on a Next 16 + next-intl site
172
+
173
+ 1. Add the reserved-paths sync to your production build (see "Syncing reserved paths" below); nothing is pasted into hyle by hand. `--print-reserved` still prints what would be sent.
174
+ 2. Replace `app/[locale]/[...rest]/page.tsx` (the `notFound()` catch-all) with `app/[locale]/(site)/[...hyle]/page.tsx`, put it under the layout group that carries the site chrome, and keep your `not-found.tsx` in that group: a 404 from the catch-all then renders inside the chrome. Pass `locale: (p) => String(p.locale)` and `localePrefix` as for `hylePage`.
175
+ 3. Keep `dynamicParams` true (see Host requirements). Keep the proxy matcher as is.
176
+ 4. Add `hyleRootSitemap` to `app/sitemap.ts`, run the checker (below), deploy.
177
+
178
+ ### Collision checker
179
+
180
+ `hyle-sdk-check-routes` (bin of this package) reads `.next/routes-manifest.json` and `.next/server/app-paths-manifest.json` of a finished `next build`, and hyle's `mounts` plus the published pages of each mount (read-only; `HYLE_TARGET_BASE_URL` or `--base-url`, and `HYLE_TARGET_TOKEN` from the environment only). It reports (a) hyle pages shadowed by a host static route, (b) host dynamic routes that match hyle URLs, with a verdict from route specificity (`[x]` before `[...x]` before `[[...x]]`; the hyle catch-all itself is fine), (c) mounts whose prefix is a host static route. Exit 1 on (a) or (c), 0 otherwise, 2 when it cannot run (no build, no credentials, hyle unreachable or the listing incomplete). `--json` prints the report; `--print-reserved` prints the host's routes in hyle's Reserved paths format (see "Syncing reserved paths" for the derivation). `--locales`, `--default-locale` and `--locale-prefix as-needed|always|never` expand a leading `[locale]` segment (next-intl). `--sections a,b` lists extra sections; `--hyle-param` names the catch-all param. A root mount over the host's home page is a note, not a failure. In CI, run it after `next build` as a required step. The same functions are exported from `@tdacorp/hyle-sdk` (`hostRoutesFromManifests`, `checkRoutes`, `reservedFor`, `formatReport`).
181
+
182
+ ### Syncing reserved paths
183
+
184
+ Reserved paths are the URLs your app owns, which hyle refuses to publish onto. They are derived from your build and sent to hyle, so nobody maintains them in hyle's UI:
185
+
186
+ ```
187
+ hyle-sdk-check-routes --sync --no-check --locales en,fr,es --default-locale en --locale-prefix as-needed
188
+ ```
189
+
190
+ Run it as the last step of the PRODUCTION build (a `postbuild` script, or the build command after `next build`). It needs, from the environment only:
191
+
192
+ | Variable | What |
193
+ |---|---|
194
+ | `HYLE_TARGET_BASE_URL`, `HYLE_TARGET_TOKEN` | already set for the site: finds the workspace through `mounts` (the read token only reads) |
195
+ | `HYLE_CONTROL_TOKEN` | NEW: a control credential (`hyle_tc_...`) whose principal holds `hyle.workspace.manage` on that workspace. The read token cannot write and is refused before any request. Mint it in hyle under Workspace > Agents (a name like `site-sync`); while hyle authorizes through identity, also link that agent's principal to an identity service principal bound to `hyle.workspace.manage` only (`scripts/link-principal-identity.mjs`, as the Agents screen says), otherwise the write answers 404. Store it as a secret in the Production scope of the host only |
196
+ | `HYLE_HOST_ID` | optional name for the audit trail; defaults to `VERCEL_PROJECT_PRODUCTION_URL`, or pass `--host` |
197
+
198
+ What is sent: `PUT /cp1/control/workspace/host-reserved-paths` with `{ paths, host, build_id }` (the build id is `.next/BUILD_ID`). The list: static routes exact; a segment with two or more routes becomes `/x/*`; a dynamic route becomes the wildcard on its static prefix (`/shop/[id]` is `/shop/*`, `/docs/[...slug]` is `/docs/*`); skipped are your hyle catch-all (`--hyle-param`), a route with no static prefix, anything on a mount's segment (the checker reports those as (b)), per-build hashed metadata routes (`/opengraph-image-1ycygp`), and `/` when hyle is mounted at the root. At most 512 entries. hyle stores it as a separate set (the workspace's own Reserved paths are never touched), enforces the union when publishing, renaming and re-prefixing, and shows it read-only in the workspace settings with the host, build and time.
199
+
200
+ - **Never fails your deploy.** A failed sync (hyle down, wrong token, not granted) prints a `sync:` warning and exits 0. Add `--strict` to exit 3 instead. Without `--no-check` the collision check also runs and keeps its own exit codes (1 collision, 2 cannot run).
201
+ - **Production only.** When `VERCEL_ENV` is set and is not `production` the sync is skipped, so a preview cannot replace production's list (`--allow-non-production` overrides). Elsewhere, only run it in production builds.
202
+ - **Idempotent.** The same list changes nothing in hyle (`unchanged`). An empty list is refused (`--allow-empty` overrides) so a broken manifest read cannot erase the reservations.
203
+ - **Conflicts.** If a path you now own already has a published hyle page, hyle unpublishes nothing: the result lists those URLs (CLI output and the settings page). Your own route wins in Next, so the hyle page is simply not shown; move or unpublish it in hyle.
204
+ - `--json` adds a `sync` object. The programmatic form is `syncHostReserved({ baseUrl, token, workspaceId, paths, host, buildId })`.
205
+
206
+ ### Limits
207
+
208
+ - A junk URL still renders a 404 page in your site chrome; whether and how long Next keeps that render is Next's own ISR behaviour (not measured here). It never reaches hyle either way.
209
+ - The checker sees the published default-locale pages of each mount (at most 10,000 per mount) and host routes known to the build; routes that only a proxy rewrite creates, or translated pathnames, are invisible to it, so list those in the workspace's own Reserved paths by hand (that list is separate from the synced one and is never overwritten by a sync).
210
+ - Matching uses the mounts of the last successful read: a new mount is served after the mounts revalidate window (default 300 s) or a workspace-tag purge.
211
+ - A reserved or mounted URL can only be reached if no host route matches it first; that is the intended precedence.
212
+
124
213
  ## Building blocks
125
214
 
126
215
  `fetchResolver(options)` is the default fetch-cache resolver, and `workspaceTags(workspaceId, sections?)` builds its tags (`hyle:1:ws:<id>`, `hyle:1:sec:<ws>:<section>`). Wrap `fetchResolver` to adjust a result (pass the wrapper as `resolver`) instead of copying it.
@@ -135,6 +224,16 @@ Verify after `next build`: `.next/prerender-manifest.json` must not show `"fallb
135
224
 
136
225
  Locale-prefixed hosts: you may keep `generateStaticParams` for the locales, but validate the locale in the layout (call `notFound()` for an unknown one) and set `dynamicParams = true` there, so unknown locales are still rejected.
137
226
 
227
+ ## Media
228
+
229
+ hyle stores an image, video or audio reference as `/assets/<uuid>.<ext>`, a path that exists only on hyle's own (authenticated) origin. On a host site it would 404, so the SDK rewrites it while rendering (`HastContent`, so every page component, and the `format: "html"` escape hatch) to `/api/hyle/assets/<uuid>.<ext>` on the host's own origin. That path is answered by the one route file in the quickstart, `app/api/hyle/assets/[file]/route.ts`; nothing else is needed per site, and a strict CSP such as `img-src 'self' data:` (and `media-src` left at `default-src 'self'`) works unchanged. The `Image` slot receives the rewritten `src`, so a `next/image` slot also works; the default is a plain `<img loading="lazy">`.
230
+
231
+ How it works: `createAssetRoute` asks hyle for exactly that file (`GET /cp1/read/assets/<file>`, ADR 0015) with the target credential and streams the bytes back. hyle answers only for an asset that a currently published, non-trashed page of this workspace references, so a draft, unpublished or other workspace's asset is a 404 on your site too. Responses carry `Cache-Control: public, max-age=3600, s-maxage=86400, stale-while-revalidate=86400`, hyle's strong `ETag` (revalidation is a 304) and `Accept-Ranges`; `Range` is forwarded, so video and audio seek. After an unpublish a cached copy can still be served for up to the cache window (about a day on a CDN).
232
+
233
+ Safety: the only input is the `file` segment and it must match `<lowercase uuid>[.png|jpg|gif|webp|svg|pdf|mp4|webm|mp3|ogg]` before anything is sent, so the route is not an open proxy. Only `Range`, `If-Range` and `If-None-Match` are forwarded (never the visitor's cookies or `Authorization`); the token goes to hyle only. Response headers are built by the SDK, the content type must be on the asset allowlist (an HTML or script answer is refused), the body is capped at 16 MiB (`maxBytes`) and the upstream call times out after 30 s (`timeoutMs`). Failures are empty responses: 404 for an unknown or unpublished asset, a bad name, a missing configuration or `HYLE_CONTENT_ENABLED=0`, 502 for any upstream error, so hyle's state and your token never leak. SVG is served as `image/svg+xml` with `Content-Security-Policy: default-src 'none'; style-src 'unsafe-inline'; sandbox` and `nosniff` (an `<img>` never runs SVG script; navigating to the URL runs none either).
234
+
235
+ The route sits under `/api/hyle/*`, which hyle's Reserved paths must cover (`hyle-sdk-check-routes --print-reserved` always lists `/api/hyle/*`, and so does `--sync`), and the checker prints a note when the build has no `/api/hyle/assets/...` route. If your proxy or middleware matcher intercepts `/api`, exclude `/api/hyle/assets`. Nothing renders `/assets/...` for you outside the SDK's components: a custom renderer of the `hast` tree should map `src` the same way (`/assets/<id>.<ext>` to `/api/hyle/assets/<id>.<ext>`).
236
+
138
237
  ## Mermaid diagrams
139
238
 
140
239
  Zero setup. A Mermaid fence arrives from hyle as a sandboxed `<iframe srcdoc>` that loads a script from cdnjs, and a `srcdoc` frame inherits the host page's CSP, so a host with `script-src 'self'` would show a blank box. The SDK therefore reads the diagram text out of that document (only after it matched hyle's exact template) and renders it in your page with the Mermaid library it bundles as a dependency (`mermaid` `~11.9.0`, MIT). No cdnjs, no extra package, no config.
@@ -146,6 +245,36 @@ Zero setup. A Mermaid fence arrives from hyle as a sandboxed `<iframe srcdoc>` t
146
245
  - Host CSP: `script-src 'self'` is enough (plus `'unsafe-inline'` or nonces for Next's own inline scripts, as for any Next app); `style-src 'unsafe-inline'` is required because Mermaid's SVG carries inline styles; `img-src` decides whether images that a diagram label references load. Checked under `default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data:` in headless Chromium on Next 16.2.7, 16.3.4 and 16.4.2 (`node scripts/e2e-next-build.mjs --browser`).
147
246
  - Override: `components.Mermaid` still replaces all of this. It receives `{ srcDoc, source, title }`; `source` is the diagram text, or `undefined` when it could not be extracted. `MermaidDiagram` (`{ source, title, errorText }`) is exported from `./react` if you want to wrap it. It is the SDK's only client component and takes nothing but those strings: no token or client ever crosses the boundary.
148
247
 
248
+ ## Diagram viewer
249
+
250
+ Every Mermaid diagram is a button. Click it, press Enter or Space on it, or tap it, and it opens in a dialog you can zoom, pan, trace and search. Nothing to install or configure: it ships in the package, has no extra dependency, uses no host UI library, and works under the same strict CSP as the inline diagram.
251
+
252
+ - Lazy: the viewer is its own chunk, fetched by the first click and never before. A page whose diagrams are never opened pays only for the trigger: about 2.2 KB raw (1 KB gzipped) more than 0.3.0, the button markup in `MermaidDiagram` and the English strings; the viewer itself is about 48 KB raw (14 KB gzipped) fetched on the first click. It shows the SVG the page already rendered (ids and `#id` CSS scoping rewritten to a unique id), so Mermaid does not lay the diagram out a second time; after a theme change the dialog swaps in the re-rendered SVG and keeps your zoom and your pinned node.
253
+ - Dialog: a native `<dialog>` opened with `showModal()`: the page behind is inert and focus cannot leave, `Esc` or a click on the backdrop closes it, focus returns to the trigger, page scroll is locked (a class on `<html>`), the open animation and the flowing dashes switch off under `prefers-reduced-motion`, and on a phone it fills the screen with 44 px touch targets.
254
+ - Zoom and pan: the wheel (or a trackpad pinch) zooms around the cursor from 0.2x to 10x; drag pans with pointer events (mouse, touch, pen) and glides on release; two fingers pinch and pan; double-click or double-tap zooms 2x (on a node: to that node); a readout shows the percentage; it opens fitted to the dialog.
255
+ - Flowchart, state, class and ER diagrams (anything Mermaid draws as `g.node` elements): hover or keyboard-focus a node and it, its direct neighbours and the edges between them stay lit while everything else dims. Click or press Enter and the node is pinned and traced: every upstream path in one tone, every downstream path in another (colours in the legend), with dashes flowing along the traced edges. Click the background to clear. `F` or a double-click zooms to the node and its neighbours with an eased transition. A minimap with a draggable viewport rectangle appears from 12 nodes. The graph is read from the rendered SVG (node ids, edge ids, or where each edge path starts and ends), never from the Mermaid source.
256
+ - Find: `/` or Ctrl+F opens a find box; matching nodes light up and the rest dim, `Enter` and `Shift+Enter` step through the matches and bring each into view. Diagrams without nodes search every SVG text element.
257
+ - Export: `MMD` copies the Mermaid source, `SVG` and `PNG` download (PNG at 1x, 2x or 4x, scaled down past canvas limits), `IMG` copies the PNG to the clipboard where the browser allows it. Clipboard calls run only inside the click that asked for them; downloads are `blob:` URLs created on click and revoked afterwards; the PNG is drawn from a `data:` SVG image, so a host CSP must allow `img-src data:` or the button reports "Not available here".
258
+ - Fullscreen: a button when `document.fullscreenEnabled` (the Fullscreen API refuses `<dialog>` elements, so it fullscreens the content wrapper inside the dialog).
259
+ - Links: a node with a Mermaid `click A "https://..."` link keeps working: a click on it follows the link (inline and in the dialog), a drag that starts on it only pans, and Enter or the trace keys still pin it. Large diagrams (over 150 nodes) skip the fade between highlight states, and a trace of more than 120 edges is drawn without the flowing dashes, to keep it instant (a 500-node trace paints in about 40 ms).
260
+ - Other diagram types: sequence, gantt, pie, journey, mindmap and the rest have no node and edge structure to trace, so they get everything except tracing and keyboard traversal: zoom, pan, fit, fullscreen, find by text and export. A node whose edges cannot be matched is simply left out of the trace; extraction never throws (an unreadable SVG is a plain pan and zoom view).
261
+
262
+ | Key | Does |
263
+ |---|---|
264
+ | `+` `=` / `-` | Zoom in / out around the centre |
265
+ | `0` or `Home` / `1` | Fit to the dialog / 100% |
266
+ | Arrow keys | With a node focused: move to the neighbouring node in that direction (a direct neighbour first, then the nearest node that way). Otherwise pan (Shift: 4x) |
267
+ | `Enter` or `Space` on a node | Pin or unpin its trace |
268
+ | `F` | Zoom to the focused, pinned or hovered node and its neighbours |
269
+ | `/` or Ctrl+F | Find; `Enter` next match, `Shift+Enter` previous, `Esc` closes the find box only |
270
+ | `Esc` | Close the dialog |
271
+
272
+ Tab moves through the toolbar, then to the diagram (one tab stop; arrow keys move between nodes). Each node is a `role="button"` named from its text and outgoing edges ("Ok?, 2 outgoing: yes, no") with `aria-pressed` for the pin, a status line announces the trace summary, and the dialog is named "Diagram viewer: <title>".
273
+
274
+ CSS variables, all optional, set anywhere above the mount: `--hyle-viewer-bg` (default `--hyle-surface`), `--hyle-viewer-accent` (selection, matches and the minimap rectangle; default `--hyle-accent`), `--hyle-viewer-up` and `--hyle-viewer-down` (the two trace tones; default `--hyle-warn` and `--hyle-ok`), `--hyle-viewer-dim` (opacity of dimmed parts, default `.16`), `--hyle-viewer-backdrop`. The dialog also reads the usual `--hyle-border`, `--hyle-text`, `--hyle-text-muted`, `--hyle-radius-lg` and `--hyle-shadow`, each with a neutral fallback. The styles live in `styles.css`; there is no inline style attribute and nothing else to load.
275
+
276
+ Limits: PNG export of a diagram with HTML labels depends on the browser drawing SVG `foreignObject` into a canvas (Chromium does); the minimap and tracing are for node diagrams only; `components.Mermaid` replaces the viewer together with the diagram; the CommonJS build (`dist/mermaid-diagram.cjs`) inlines the viewer instead of splitting it, which only matters to a CJS bundler.
277
+
149
278
  ## Styling
150
279
 
151
280
  Import `@tdacorp/hyle-sdk/styles.css`. It is the design kit's stylesheet: every value comes from a public `--hyle-*` custom property with a SIGNAL fallback (`--sig-*` from `@tdacorp/signal-tokens`, so dark and light acts flip with no extra code). Set variables on `:root`, `body` or any wrapper above the mount; the SDK never declares them:
@@ -170,13 +299,14 @@ Chrome strings exist for en, fr and es (fr and es are unreviewed drafts). The pa
170
299
 
171
300
  - The token is sent only as an `Authorization` header from the server. It is never placed in a URL, logged or put in an error message. Keep it out of client components. The client requires an https `baseUrl` (http only for localhost, or with `allowInsecureHttp`), refuses redirects, aborts after `timeoutMs` (default 10 s) and refuses responses over `maxResponseBytes` (default 5 MiB).
172
301
  - The path is sent as a query parameter (encoded once); catch-all segments are decoded and refused if they contain `/`, `\`, control characters, `.` or `..`.
173
- - The `hast` tree is rendered through an allowlist (`sanitizeHast`) even though hyle sanitizes server-side: only known tags and properties with accepted value shapes survive; no `on*` attributes, `style` only inside KaTeX output and only for the properties KaTeX emits with small values (no `position:absolute`, `z-index`, `left` or large sizes), ids and in-page fragments scoped with the server's `user-content-` prefix (so heading ids, footnote links and TOC links still resolve), `href` and `src` limited to site-relative paths and `http(s)` (and `mailto` for links), unknown tags are unwrapped, `script` and `style` are dropped, and an `iframe` is kept only with `sandbox="allow-scripts"` and a `srcdoc` that is exactly the document hyle's renderer builds for a Mermaid fence (pinned script URL, at most 64 KiB); the SDK adds `referrerpolicy="no-referrer"` and a `csp` that allows only that script (checked in headless Chromium: the diagram still renders). A tree over 20,000 nodes or 512 KiB of text fails closed with `HastLimitError` and a safe notice. `dangerouslySetInnerHTML` is used in exactly two places: the Mermaid SVG sink (below) and `TrustedServerHtml`, the escape hatch for `content.format === "html"`: it renders HTML as is, so pass it only HTML that came straight from hyle's resolve endpoint, never user input.
302
+ - The `hast` tree is rendered through an allowlist (`sanitizeHast`) even though hyle sanitizes server-side: only known tags and properties with accepted value shapes survive; no `on*` attributes, `style` only inside KaTeX output and only for the properties KaTeX emits with small values (no `position:absolute`, `z-index`, `left` or large sizes), ids and in-page fragments scoped with the server's `user-content-` prefix (so heading ids, footnote links and TOC links still resolve), `href` and `src` limited to site-relative paths and `http(s)` (and `mailto` for links), unknown tags are unwrapped, `script` and `style` are dropped, and an `iframe` is kept only with `sandbox="allow-scripts"` and a `srcdoc` that is exactly the document hyle's renderer builds for a Mermaid fence (pinned script URL, at most 64 KiB); the SDK adds `referrerpolicy="no-referrer"` and a `csp` that allows only that script (checked in headless Chromium: the diagram still renders). A tree over 20,000 nodes or 512 KiB of text fails closed with `HastLimitError` and a safe notice. `dangerouslySetInnerHTML` is used in exactly three places: the Mermaid SVG sink (below), the same SVG with rewritten ids in the diagram viewer's stage (below), and `TrustedServerHtml`, the escape hatch for `content.format === "html"`: it renders HTML as is, so pass it only HTML that came straight from hyle's resolve endpoint, never user input.
174
303
  - Mermaid renders into your page, so: the source comes only from hyle content, passes the exact-template check and a 20,000 character cap, and is rendered with `securityLevel: "strict"` (Mermaid's own DOMPurify pass, no raw HTML labels) and `maxTextSize` set to the cap. The SDK strips every `%%{ ... }%%` directive (multi-line, unterminated and `init`, `initialize`, `config`, `wrap` forms) and a leading YAML frontmatter block from the source before rendering, and keeps plain `%% comment` lines. Reason: Mermaid's `themeCSS` (set by a directive or by frontmatter `config:`) is injected into the page as CSS and its sanitizer only checks brace balance, so a diagram could make the page fetch a URL or overlay the host UI; verified against Mermaid 11.9.0 with a loopback canary server, which received requests when the stripping was disabled and none with it. Consequence: authors cannot configure a diagram per diagram; a diagram that carries an init directive renders with the SDK's defaults. As a second guard `.hyle-mermaid-svg` uses `contain: paint` and the SVG is `position: static !important`, so diagram CSS cannot place anything over the host page. Flowchart `style` and `classDef` lines cannot carry `url(...)` (they fail to parse). What remains: Mermaid keeps an `<img>` inside a label (event handlers are stripped), so an author can make the page request an image, and your CSP `img-src` governs that exactly as for Markdown images (the e2e proves a strict `img-src 'self' data:` stops it); a `click A "https://..."` line makes a clickable link, a phishing-link capability inside author-controlled content, so treat hyle authors as trusted to link. Nothing is executed: the SDK ignores Mermaid's `bindFunctions`, and the hostile `click ... call`, `<img onerror>` and `securityLevel: "loose"` payloads did nothing in the browser check. The host CSP needs `style-src 'unsafe-inline'`.
304
+ - The diagram viewer adds no network request, no `eval`, no storage and no new way to write HTML: its stage receives the very string the inline diagram holds (Mermaid's strict-mode DOMPurify output) after one rewrite of the SDK-generated render id (`hyle-mermaid-N`) to another SDK-generated token (`hyle-viewer-N`), applied only inside tags and `<style>` bodies and only for `[\w-]+` tokens, so it cannot add a quote, a tag or a script; the node and edge decoration only sets classes, `tabindex`, `role` and `aria-*` on elements that already exist. Export builds `blob:` and `data:` URLs from that same string on click, and the clipboard is only touched inside the click that asked for it. A unit test pins these properties by reading the viewer's source (no `fetch`, `eval`, `innerHTML =`, storage or `document.write`, exactly one `dangerouslySetInnerHTML`).
175
305
  - Webhooks are verified with HMAC-SHA256 over the raw body (read with a running 64 KiB cap), a 300 s timestamp tolerance and constant-time comparison, with dual-secret rotation (empty secrets are never candidates), a payload shape check (400, not 500), tag validation, and delivery-id dedupe that records an id only after every purge succeeded, so a failed delivery can be retried.
176
306
 
177
307
  ## Not included
178
308
 
179
- Docs versions, reading time, scroll-spy, "closest matches" on the 404 page and a copy-code button: hyle does not provide that data or the page would need client JavaScript. Image URLs in content such as `/assets/<id>` are passed through unchanged; map them with the `Image` slot if they live on hyle's origin.
309
+ Docs versions, reading time, scroll-spy, "closest matches" on the 404 page and a copy-code button: hyle does not provide that data or the page would need client JavaScript. Image URLs in content such as `/assets/<id>` are no longer passed through unchanged: see "Media".
180
310
 
181
311
  ## Contract
182
312
 
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+ // Stable bin entry for package-manager links: the real CLI is built to dist/, which does not exist at install time.
3
+ await import('../dist/check-routes-bin.js')