@tdacorp/hyle-sdk 0.2.1 → 0.5.0
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.
- package/README.md +105 -4
- package/bin/hyle-sdk-check-routes.mjs +3 -0
- package/dist/check-routes-bin.js +389 -0
- package/dist/chunk-4OB77ZOD.js +455 -0
- package/dist/chunk-BUJFMR3M.js +38 -0
- package/dist/{chunk-7VCMJUPC.js → chunk-OW6S7IZX.js} +1 -1
- package/dist/{chunk-MHVWHSKC.js → chunk-SO6H2UGL.js} +124 -6
- package/dist/diagram-viewer-DYX6R63Y.js +1132 -0
- package/dist/index.cjs +191 -20
- package/dist/index.d.cts +95 -3
- package/dist/index.d.ts +95 -3
- package/dist/index.js +13 -1
- package/dist/mermaid-diagram.cjs +1395 -0
- package/dist/mermaid-diagram.d.cts +55 -0
- package/dist/mermaid-diagram.d.ts +55 -0
- package/dist/mermaid-diagram.js +140 -0
- package/dist/next.cjs +286 -27
- package/dist/next.d.cts +51 -5
- package/dist/next.d.ts +51 -5
- package/dist/next.js +131 -5
- package/dist/react.cjs +124 -5
- package/dist/react.d.cts +60 -4
- package/dist/react.d.ts +60 -4
- package/dist/react.js +3 -1
- package/dist/{resolve-fMx2W8RR.d.ts → resolve-1rQntRBh.d.ts} +1 -1
- package/dist/{resolve-B_p0p4Zn.d.cts → resolve-36-Ng1H0.d.cts} +1 -1
- package/dist/styles.css +82 -1
- package/dist/{types-BNaGecO7.d.ts → types-BoyBWF2F.d.ts} +3 -1
- package/dist/{types-DjXf6iPo.d.cts → types-CwBCPh6K.d.cts} +20 -1
- package/dist/{types-DjXf6iPo.d.ts → types-CwBCPh6K.d.ts} +20 -1
- package/dist/{types-DLWvqanV.d.cts → types-DnPzhrFx.d.cts} +3 -1
- package/dist/use-cache.cjs +34 -20
- package/dist/use-cache.d.cts +2 -2
- package/dist/use-cache.d.ts +2 -2
- package/dist/use-cache.js +2 -2
- package/package.json +8 -3
- package/dist/chunk-HFUJRNFP.js +0 -290
package/README.md
CHANGED
|
@@ -49,9 +49,9 @@ Register that URL as the workspace's webhook endpoint in hyle. Set `metadataBase
|
|
|
49
49
|
|
|
50
50
|
| Import | Contents | Needs |
|
|
51
51
|
|---|---|---|
|
|
52
|
-
| `@tdacorp/hyle-sdk` | `createHyleClient` (typed `resolve`), `listPublicationPaths`, `Cp1ClientError`, `verifyHyleSignature`, `parseSignatureHeader`, `isValidCacheTag`, `DeliveryDedupe`, `createRevalidationCallbackRoute`, the result types | nothing (no framework) |
|
|
52
|
+
| `@tdacorp/hyle-sdk` | `createHyleClient` (typed `resolve` and `mounts`), `listPublicationPaths`, `checkRoutes` and the other route-check functions, `Cp1ClientError`, `verifyHyleSignature`, `parseSignatureHeader`, `isValidCacheTag`, `DeliveryDedupe`, `createRevalidationCallbackRoute`, the result types | nothing (no framework) |
|
|
53
53
|
| `@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 |
|
|
54
|
+
| `@tdacorp/hyle-sdk/next` | `hylePage`, `hyleMetadata`, `hyleSitemap`, `hyleRootPage`, `hyleRootMetadata`, `hyleRootSitemap`, `createRevalidateRoute`, `fetchResolver`, `workspaceTags` | next >= 16 |
|
|
55
55
|
| `@tdacorp/hyle-sdk/next/use-cache` | `cachedResolver` | next >= 16 with `cacheComponents: true` |
|
|
56
56
|
| `@tdacorp/hyle-sdk/styles.css` | the stylesheet | |
|
|
57
57
|
|
|
@@ -121,6 +121,64 @@ export default async function sitemap() {
|
|
|
121
121
|
|
|
122
122
|
`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
123
|
|
|
124
|
+
## Root catch-all
|
|
125
|
+
|
|
126
|
+
`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.
|
|
127
|
+
|
|
128
|
+
```tsx
|
|
129
|
+
// app/(site)/[...hyle]/page.tsx (a REQUIRED catch-all: [...hyle], not [[...hyle]])
|
|
130
|
+
import { hyleRootMetadata, hyleRootPage } from "@tdacorp/hyle-sdk/next";
|
|
131
|
+
|
|
132
|
+
const config = { baseUrl: process.env.HYLE_BASE_URL!, token: process.env.HYLE_TARGET_TOKEN!, workspaceId: process.env.HYLE_WORKSPACE_ID!,
|
|
133
|
+
locale: (p) => String(p.locale), localePrefix: (l) => (l === "en" ? "" : `/${l}`) };
|
|
134
|
+
export default hyleRootPage(config); // or hyleRootPage([configA, configB]) for several workspaces
|
|
135
|
+
export const generateMetadata = hyleRootMetadata(config);
|
|
136
|
+
// app/sitemap.ts: [...hostEntries, ...(await hyleRootSitemap(config, { origin: "https://tdacorp.in" }))]
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
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`).
|
|
140
|
+
|
|
141
|
+
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.
|
|
142
|
+
|
|
143
|
+
### How it works, and why it does not interfere with the host
|
|
144
|
+
|
|
145
|
+
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.
|
|
146
|
+
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.
|
|
147
|
+
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).
|
|
148
|
+
4. Otherwise the request is served by `hylePage` with `basePath` = the matched prefix: same locale handling, redirects, list and article pages, same failure rules.
|
|
149
|
+
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).
|
|
150
|
+
|
|
151
|
+
### Failure modes
|
|
152
|
+
|
|
153
|
+
| Situation | Result |
|
|
154
|
+
|---|---|
|
|
155
|
+
| 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) |
|
|
156
|
+
| 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 |
|
|
157
|
+
| 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) |
|
|
158
|
+
| 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 |
|
|
159
|
+
| Root mount (`/`) and no usable copy | every unmatched URL errors until hyle is back (the root mount could own any of them) |
|
|
160
|
+
| hyle is down | the host's own pages are unaffected: they never call hyle |
|
|
161
|
+
|
|
162
|
+
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.
|
|
163
|
+
|
|
164
|
+
### Adopting it on a Next 16 + next-intl site
|
|
165
|
+
|
|
166
|
+
1. Run `HYLE_TARGET_BASE_URL=... HYLE_TARGET_TOKEN=... npx hyle-sdk-check-routes --next-dir .next --locales en,fr,es --default-locale en --locale-prefix as-needed --print-reserved` after a build and paste the output into the workspace's Reserved paths setting in hyle, then publish your mounts.
|
|
167
|
+
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`.
|
|
168
|
+
3. Keep `dynamicParams` true (see Host requirements). Keep the proxy matcher as is.
|
|
169
|
+
4. Add `hyleRootSitemap` to `app/sitemap.ts`, run the checker (below), deploy.
|
|
170
|
+
|
|
171
|
+
### Collision checker
|
|
172
|
+
|
|
173
|
+
`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 static routes in hyle's Reserved paths format (exact paths, and `/x/*` for a segment with several routes, unless a mount lives on that segment). `--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`).
|
|
174
|
+
|
|
175
|
+
### Limits
|
|
176
|
+
|
|
177
|
+
- 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.
|
|
178
|
+
- 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 Reserved paths by hand.
|
|
179
|
+
- 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.
|
|
180
|
+
- A reserved or mounted URL can only be reached if no host route matches it first; that is the intended precedence.
|
|
181
|
+
|
|
124
182
|
## Building blocks
|
|
125
183
|
|
|
126
184
|
`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 +193,47 @@ Verify after `next build`: `.next/prerender-manifest.json` must not show `"fallb
|
|
|
135
193
|
|
|
136
194
|
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
195
|
|
|
196
|
+
## Mermaid diagrams
|
|
197
|
+
|
|
198
|
+
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.
|
|
199
|
+
|
|
200
|
+
- What loads when: the server renders a no-JavaScript fallback, a `<figure class="hyle-mermaid">` holding the source as a `language-mermaid` code block. On a page with a diagram, the browser then imports `mermaid` (a dynamic import, so your bundler emits it as lazy chunks served from your own origin) and swaps in the SVG. Pages without a diagram never load it: the client component is not even in their JavaScript. In the e2e app (Next 16.2.7, Turbopack) the lazy chunks total about 2.8 MB raw, 0.8 MB gzipped across every diagram type; a page loads only the ones its diagram type needs. `mermaid` itself is 64 MB on disk in `node_modules` (it is not shipped to browsers).
|
|
201
|
+
- Rendering: a diagram renders when it is within 200 px of the viewport, one at a time, each limited to 10 s (a slower one falls back to the code block and the note). Per-diagram configuration (`%%{init}%%` directives and frontmatter) is stripped, see Security model. A re-render (theme change) keeps the previous SVG on screen until the new one is ready, and keeps it if the new one fails.
|
|
202
|
+
- Themes: dark or default is chosen from the figure's computed background (falling back to `prefers-color-scheme`), and the diagram re-renders when `data-act`, `data-theme` or `class` change on `<html>` or the OS scheme changes.
|
|
203
|
+
- Fallback: if the source cannot be extracted (over 20,000 characters, or not the renderer's template) the old sandboxed frame is used, which needs cdnjs in your CSP. If Mermaid cannot render the source (a syntax error), the code block stays and a short "diagram could not be rendered" note appears.
|
|
204
|
+
- 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`).
|
|
205
|
+
- 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.
|
|
206
|
+
|
|
207
|
+
## Diagram viewer
|
|
208
|
+
|
|
209
|
+
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.
|
|
210
|
+
|
|
211
|
+
- 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.
|
|
212
|
+
- 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.
|
|
213
|
+
- 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.
|
|
214
|
+
- 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.
|
|
215
|
+
- 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.
|
|
216
|
+
- 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".
|
|
217
|
+
- Fullscreen: a button when `document.fullscreenEnabled` (the Fullscreen API refuses `<dialog>` elements, so it fullscreens the content wrapper inside the dialog).
|
|
218
|
+
- 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).
|
|
219
|
+
- 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).
|
|
220
|
+
|
|
221
|
+
| Key | Does |
|
|
222
|
+
|---|---|
|
|
223
|
+
| `+` `=` / `-` | Zoom in / out around the centre |
|
|
224
|
+
| `0` or `Home` / `1` | Fit to the dialog / 100% |
|
|
225
|
+
| 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) |
|
|
226
|
+
| `Enter` or `Space` on a node | Pin or unpin its trace |
|
|
227
|
+
| `F` | Zoom to the focused, pinned or hovered node and its neighbours |
|
|
228
|
+
| `/` or Ctrl+F | Find; `Enter` next match, `Shift+Enter` previous, `Esc` closes the find box only |
|
|
229
|
+
| `Esc` | Close the dialog |
|
|
230
|
+
|
|
231
|
+
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>".
|
|
232
|
+
|
|
233
|
+
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.
|
|
234
|
+
|
|
235
|
+
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.
|
|
236
|
+
|
|
138
237
|
## Styling
|
|
139
238
|
|
|
140
239
|
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:
|
|
@@ -149,7 +248,7 @@ The 52 variables are listed in the token block at the top of `styles.css`. Layou
|
|
|
149
248
|
|
|
150
249
|
`components` replaces how a part is drawn, `slots` fills named places. Both are props of the pages and options of `hylePage`.
|
|
151
250
|
|
|
152
|
-
- Component slots: `Link` (every internal link, breadcrumb and in-page link: pass your router's Link), `Image`, `CodeBlock` (receives `code`, `language`, and the default `children`; the stock block has no copy button because that needs client JavaScript), `Mermaid` (receives hyle's sandboxed `srcDoc`), `Callout` (GFM alerts such as `> [!NOTE]`). The raw element overrides `a`, `img`, `code`, `pre`, `table`, `blockquote` and `h1` to `h6` also work.
|
|
251
|
+
- Component slots: `Link` (every internal link, breadcrumb and in-page link: pass your router's Link), `Image`, `CodeBlock` (receives `code`, `language`, and the default `children`; the stock block has no copy button because that needs client JavaScript), `Mermaid` (receives hyle's sandboxed `srcDoc` and the extracted `source`; the default renders the diagram in the page, see "Mermaid diagrams"), `Callout` (GFM alerts such as `> [!NOTE]`). The raw element overrides `a`, `img`, `code`, `pre`, `table`, `blockquote` and `h1` to `h6` also work.
|
|
153
252
|
- Visual slots: `article.before`, `article.meta`, `article.aside`, `article.after`, `list.header`, `list.item` (a component that receives the item), `list.empty`, `docs.sidebar-header`, `docs.version`, `docs.sidebar-footer`, `docs.after`, `notfound.body`, `notfound.actions`, `redirecting.body`. An unfilled slot renders nothing.
|
|
154
253
|
- Layout: `layout: "docs"` renders articles as `DocsPage` (tree navigation from `ancestors`, `children` and `breadcrumbs`).
|
|
155
254
|
|
|
@@ -159,7 +258,9 @@ Chrome strings exist for en, fr and es (fr and es are unreviewed drafts). The pa
|
|
|
159
258
|
|
|
160
259
|
- 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).
|
|
161
260
|
- The path is sent as a query parameter (encoded once); catch-all segments are decoded and refused if they contain `/`, `\`, control characters, `.` or `..`.
|
|
162
|
-
- 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
|
|
261
|
+
- 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.
|
|
262
|
+
- 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'`.
|
|
263
|
+
- 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`).
|
|
163
264
|
- 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.
|
|
164
265
|
|
|
165
266
|
## Not included
|
|
@@ -0,0 +1,389 @@
|
|
|
1
|
+
// src/check-routes-cli.ts
|
|
2
|
+
import { readFileSync } from "fs";
|
|
3
|
+
import { join } from "path";
|
|
4
|
+
|
|
5
|
+
// src/errors.ts
|
|
6
|
+
var Cp1ClientError = class extends Error {
|
|
7
|
+
code;
|
|
8
|
+
status;
|
|
9
|
+
requestId;
|
|
10
|
+
details;
|
|
11
|
+
constructor(code, message, status, requestId, details) {
|
|
12
|
+
super(message);
|
|
13
|
+
this.name = "Cp1ClientError";
|
|
14
|
+
this.code = code;
|
|
15
|
+
this.status = status;
|
|
16
|
+
this.requestId = requestId;
|
|
17
|
+
this.details = details;
|
|
18
|
+
}
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
// src/client.ts
|
|
22
|
+
var DEFAULT_TIMEOUT_MS = 1e4;
|
|
23
|
+
var DEFAULT_MAX_RESPONSE_BYTES = 5 * 1024 * 1024;
|
|
24
|
+
var LOOPBACK = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "[::1]"]);
|
|
25
|
+
async function readCapped(res, max) {
|
|
26
|
+
const tooLarge = () => new Cp1ClientError("RESPONSE_TOO_LARGE", `hyle response exceeds ${max} bytes`, res.status, "");
|
|
27
|
+
if (Number(res.headers.get("content-length")) > max) throw tooLarge();
|
|
28
|
+
if (!res.body) return "";
|
|
29
|
+
const reader = res.body.getReader();
|
|
30
|
+
const chunks = [];
|
|
31
|
+
let total = 0;
|
|
32
|
+
for (; ; ) {
|
|
33
|
+
const { done, value } = await reader.read();
|
|
34
|
+
if (done) break;
|
|
35
|
+
total += value.byteLength;
|
|
36
|
+
if (total > max) {
|
|
37
|
+
await reader.cancel();
|
|
38
|
+
throw tooLarge();
|
|
39
|
+
}
|
|
40
|
+
chunks.push(value);
|
|
41
|
+
}
|
|
42
|
+
return Buffer.concat(chunks).toString("utf8");
|
|
43
|
+
}
|
|
44
|
+
var KINDS = /* @__PURE__ */ new Set(["article", "list", "redirect", "notfound", "disabled"]);
|
|
45
|
+
var isStrings = (value) => Array.isArray(value) && value.every((v) => typeof v === "string");
|
|
46
|
+
function isMounts(data) {
|
|
47
|
+
const mounts = data.mounts;
|
|
48
|
+
return typeof data.workspace_id === "string" && isStrings(data.reserved) && isStrings(data.supported_locales) && Array.isArray(mounts) && mounts.every((m) => typeof m?.prefix === "string" && typeof m.default_section === "string");
|
|
49
|
+
}
|
|
50
|
+
function createHyleClient(options) {
|
|
51
|
+
let origin;
|
|
52
|
+
try {
|
|
53
|
+
origin = new URL(options.baseUrl);
|
|
54
|
+
} catch {
|
|
55
|
+
throw new TypeError("baseUrl must be an https origin");
|
|
56
|
+
}
|
|
57
|
+
if (origin.protocol !== "https:" && !(origin.protocol === "http:" && (options.allowInsecureHttp || LOOPBACK.has(origin.hostname)))) {
|
|
58
|
+
throw new TypeError("baseUrl must be https (http is allowed only for localhost, or with allowInsecureHttp)");
|
|
59
|
+
}
|
|
60
|
+
if (!options.token) throw new TypeError("token is required");
|
|
61
|
+
const base = options.baseUrl.replace(/\/+$/, "");
|
|
62
|
+
const fetchImpl = options.fetch ?? fetch;
|
|
63
|
+
async function get(pathname, query, init) {
|
|
64
|
+
const url = new URL(`${base}${pathname}`);
|
|
65
|
+
url.search = query.toString();
|
|
66
|
+
const headers = new Headers(init?.headers);
|
|
67
|
+
headers.set("authorization", `Bearer ${options.token}`);
|
|
68
|
+
const timeout = AbortSignal.timeout(options.timeoutMs ?? DEFAULT_TIMEOUT_MS);
|
|
69
|
+
const signal = init?.signal ? AbortSignal.any([init.signal, timeout]) : timeout;
|
|
70
|
+
const res = await fetchImpl(url.toString(), { ...init, method: "GET", headers, redirect: "error", signal });
|
|
71
|
+
const text = await readCapped(res, options.maxResponseBytes ?? DEFAULT_MAX_RESPONSE_BYTES);
|
|
72
|
+
let parsed;
|
|
73
|
+
try {
|
|
74
|
+
parsed = JSON.parse(text);
|
|
75
|
+
} catch {
|
|
76
|
+
parsed = void 0;
|
|
77
|
+
}
|
|
78
|
+
return { parsed, status: res.status };
|
|
79
|
+
}
|
|
80
|
+
const failure = ({ parsed, status }) => {
|
|
81
|
+
const err = parsed?.error;
|
|
82
|
+
return new Cp1ClientError(err?.code ?? "INVALID_RESPONSE", err?.message ?? `Unexpected response from hyle (HTTP ${status})`, status, err?.request_id ?? "", err?.details);
|
|
83
|
+
};
|
|
84
|
+
async function resolve(opts) {
|
|
85
|
+
const query = new URLSearchParams({ path: opts.path });
|
|
86
|
+
if (opts.locale !== void 0) query.set("locale", opts.locale);
|
|
87
|
+
if (opts.format !== void 0) query.set("format", opts.format);
|
|
88
|
+
if (opts.cursor !== void 0) query.set("cursor", opts.cursor);
|
|
89
|
+
if (opts.limit !== void 0) query.set("limit", String(opts.limit));
|
|
90
|
+
const reply = await get("/cp1/read/resolve", query, opts.init);
|
|
91
|
+
const data = reply.parsed?.data;
|
|
92
|
+
if (data && data.cp === 1 && typeof data.kind === "string" && KINDS.has(data.kind)) return data;
|
|
93
|
+
throw failure(reply);
|
|
94
|
+
}
|
|
95
|
+
async function mounts(opts = {}) {
|
|
96
|
+
const reply = await get("/cp1/read/mounts", new URLSearchParams(), opts.init);
|
|
97
|
+
const data = reply.parsed?.data;
|
|
98
|
+
if (data?.cp === 1 && data.kind === "disabled") return data;
|
|
99
|
+
if (data?.cp === 1 && data.kind === "mounts" && isMounts(data)) return data;
|
|
100
|
+
throw failure(reply);
|
|
101
|
+
}
|
|
102
|
+
return { resolve, mounts };
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
// src/next/paths.ts
|
|
106
|
+
function normalizeBasePath(basePath) {
|
|
107
|
+
const raw = basePath ?? "";
|
|
108
|
+
const value = raw === "/" ? "" : raw.replace(/\/$/, "");
|
|
109
|
+
if (value === "") return "";
|
|
110
|
+
if (!/^\/[^\s?#\\]+$/.test(value) || raw.includes("//")) throw new TypeError(`basePath must look like "/learn", got "${basePath}"`);
|
|
111
|
+
return value;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
// src/route-check.ts
|
|
115
|
+
var NOT_ROUTES = /* @__PURE__ */ new Set(["/_not-found", "/_global-error", "/_app", "/_error", "/_document", "/404", "/500"]);
|
|
116
|
+
var LOCALE_PARAM = "locale";
|
|
117
|
+
function normalizeRoute(key) {
|
|
118
|
+
const segments = key.replace(/\/(page|route)$/, "").split("/").filter((s) => s !== "");
|
|
119
|
+
if (segments.some((s) => s.startsWith("@") || /^\(\.{1,3}\)/.test(s))) return void 0;
|
|
120
|
+
const route = `/${segments.filter((s) => !/^\(.*\)$/.test(s)).join("/")}`;
|
|
121
|
+
return NOT_ROUTES.has(route) ? void 0 : route;
|
|
122
|
+
}
|
|
123
|
+
function hostRoutesFromManifests({ routesManifest, appPaths }) {
|
|
124
|
+
const keys = [...(routesManifest?.staticRoutes ?? []).map((r) => r.page), ...(routesManifest?.dynamicRoutes ?? []).map((r) => r.page), ...Object.keys(appPaths ?? {})];
|
|
125
|
+
return [...new Set(keys.map(normalizeRoute).filter((r) => r !== void 0))].sort();
|
|
126
|
+
}
|
|
127
|
+
var segmentsOf = (path) => path.split("/").filter((s) => s !== "");
|
|
128
|
+
function parse(route) {
|
|
129
|
+
return segmentsOf(route).map((value) => {
|
|
130
|
+
const optional = /^\[\[\.\.\.([^\]]+)\]\]$/.exec(value);
|
|
131
|
+
if (optional) return { kind: "optional-catch-all", name: optional[1] };
|
|
132
|
+
const rest = /^\[\.\.\.([^\]]+)\]$/.exec(value);
|
|
133
|
+
if (rest) return { kind: "catch-all", name: rest[1] };
|
|
134
|
+
const one = /^\[([^\]]+)\]$/.exec(value);
|
|
135
|
+
return one ? { kind: "dynamic", name: one[1] } : { kind: "static", value };
|
|
136
|
+
});
|
|
137
|
+
}
|
|
138
|
+
var isDynamic = (route) => parse(route).some((s) => s.kind !== "static");
|
|
139
|
+
function routeMatches(route, path) {
|
|
140
|
+
const pattern = parse(route);
|
|
141
|
+
const parts = segmentsOf(path);
|
|
142
|
+
for (const [i, seg] of pattern.entries()) {
|
|
143
|
+
if (seg.kind === "optional-catch-all") return i === pattern.length - 1;
|
|
144
|
+
if (seg.kind === "catch-all") return i === pattern.length - 1 && parts.length > i;
|
|
145
|
+
if (i >= parts.length || seg.kind === "static" && seg.value !== parts[i]) return false;
|
|
146
|
+
}
|
|
147
|
+
return parts.length === pattern.length;
|
|
148
|
+
}
|
|
149
|
+
var RANK = { static: 0, dynamic: 1, "catch-all": 2, "optional-catch-all": 3 };
|
|
150
|
+
function compareSpecificity(a, b) {
|
|
151
|
+
const [pa, pb] = [parse(a), parse(b)];
|
|
152
|
+
for (let i = 0; i < Math.min(pa.length, pb.length); i++) {
|
|
153
|
+
const d = RANK[pa[i].kind] - RANK[pb[i].kind];
|
|
154
|
+
if (d !== 0) return d;
|
|
155
|
+
}
|
|
156
|
+
return pa.length - pb.length;
|
|
157
|
+
}
|
|
158
|
+
function withLocale(path, locale) {
|
|
159
|
+
if (!locale) return [path];
|
|
160
|
+
const prefixed = (l) => path === "/" ? `/${l}` : `/${l}${path}`;
|
|
161
|
+
if (locale.prefix === "never") return [path];
|
|
162
|
+
return locale.locales.map((l) => locale.prefix === "as-needed" && l === locale.defaultLocale ? path : prefixed(l));
|
|
163
|
+
}
|
|
164
|
+
function expandLocale(route, locale) {
|
|
165
|
+
const [first, ...rest] = segmentsOf(route);
|
|
166
|
+
if (!locale || first !== `[${LOCALE_PARAM}]`) return [route];
|
|
167
|
+
return [...new Set(withLocale(`/${rest.join("/")}`, locale))];
|
|
168
|
+
}
|
|
169
|
+
var MAX_EXAMPLES = 5;
|
|
170
|
+
function checkRoutes(input) {
|
|
171
|
+
const { locale } = input;
|
|
172
|
+
const hyleParam = input.hyleParam ?? "hyle";
|
|
173
|
+
const routes = [...new Set(input.hostRoutes.flatMap((r) => expandLocale(r, locale)))];
|
|
174
|
+
const staticRoutes = new Set(routes.filter((r) => !isDynamic(r)));
|
|
175
|
+
const dynamicRoutes = routes.filter(isDynamic);
|
|
176
|
+
const catchAlls = dynamicRoutes.filter((r) => {
|
|
177
|
+
const last = parse(r).at(-1);
|
|
178
|
+
return (last?.kind === "catch-all" || last?.kind === "optional-catch-all") && last.name === hyleParam;
|
|
179
|
+
});
|
|
180
|
+
const notes = [];
|
|
181
|
+
const shadowedHylePaths = input.hylePaths.flatMap(
|
|
182
|
+
(path) => withLocale(path, locale).filter((url) => staticRoutes.has(url)).map((url) => ({ path, url, route: url }))
|
|
183
|
+
);
|
|
184
|
+
const mountCollisions = [];
|
|
185
|
+
for (const prefix of input.mounts) {
|
|
186
|
+
if (prefix === "/") {
|
|
187
|
+
if (staticRoutes.has("/")) notes.push(`root mount: the host's own home page owns "/", so hyle's index page is not served there (pages below it are)`);
|
|
188
|
+
continue;
|
|
189
|
+
}
|
|
190
|
+
for (const url of withLocale(prefix, locale)) if (staticRoutes.has(url)) mountCollisions.push({ prefix, url, route: url });
|
|
191
|
+
}
|
|
192
|
+
const urls = [...new Set([...input.hylePaths, ...input.mounts.filter((m) => m !== "/")].flatMap((p) => withLocale(p, locale)))];
|
|
193
|
+
const dynamicOverlaps = [];
|
|
194
|
+
for (const route of dynamicRoutes) {
|
|
195
|
+
const matched = urls.filter((u) => routeMatches(route, u));
|
|
196
|
+
if (catchAlls.includes(route)) {
|
|
197
|
+
dynamicOverlaps.push({ route, verdict: "hyle-catch-all", matches: matched.length, examples: matched.slice(0, MAX_EXAMPLES) });
|
|
198
|
+
continue;
|
|
199
|
+
}
|
|
200
|
+
const hostWins = matched.filter((u) => {
|
|
201
|
+
const best = catchAlls.filter((c) => routeMatches(c, u)).sort(compareSpecificity)[0];
|
|
202
|
+
return best === void 0 || compareSpecificity(route, best) <= 0;
|
|
203
|
+
});
|
|
204
|
+
if (matched.length === 0) continue;
|
|
205
|
+
const shown = hostWins.length > 0 ? hostWins : matched;
|
|
206
|
+
dynamicOverlaps.push({ route, verdict: hostWins.length > 0 ? "host-wins" : "hyle-wins", matches: shown.length, examples: shown.slice(0, MAX_EXAMPLES) });
|
|
207
|
+
}
|
|
208
|
+
if (catchAlls.length === 0) notes.push(`no hyle catch-all route (a "[...${hyleParam}]" or "[[...${hyleParam}]]" page) was found in the host routes`);
|
|
209
|
+
return { shadowedHylePaths, mountCollisions, dynamicOverlaps, notes, ok: shadowedHylePaths.length === 0 && mountCollisions.length === 0 };
|
|
210
|
+
}
|
|
211
|
+
function reservedFor(hostRoutes, options = {}) {
|
|
212
|
+
const dropLocale = (route) => {
|
|
213
|
+
const [first, ...rest] = segmentsOf(route);
|
|
214
|
+
return options.locale && first === `[${LOCALE_PARAM}]` ? `/${rest.join("/")}` : route;
|
|
215
|
+
};
|
|
216
|
+
const exact = new Set(hostRoutes.map(dropLocale).filter((r) => !isDynamic(r)));
|
|
217
|
+
const mounts = options.mounts?.filter((m) => m !== "/");
|
|
218
|
+
const groups = /* @__PURE__ */ new Map();
|
|
219
|
+
for (const route of exact) {
|
|
220
|
+
const [first, ...rest] = segmentsOf(route);
|
|
221
|
+
if (first !== void 0 && rest.length > 0) groups.set(first, [...groups.get(first) ?? [], route]);
|
|
222
|
+
}
|
|
223
|
+
for (const [first, members] of groups) {
|
|
224
|
+
const onMount = mounts?.some((m) => m === `/${first}` || m.startsWith(`/${first}/`)) ?? true;
|
|
225
|
+
if (members.length < 2 || onMount) continue;
|
|
226
|
+
for (const m of members) exact.delete(m);
|
|
227
|
+
exact.delete(`/${first}`);
|
|
228
|
+
exact.add(`/${first}/*`);
|
|
229
|
+
}
|
|
230
|
+
return [...exact].sort();
|
|
231
|
+
}
|
|
232
|
+
function formatReport(report) {
|
|
233
|
+
const lines = [];
|
|
234
|
+
const section = (title, rows, empty) => lines.push(`${title}`, ...rows.length ? rows.map((r) => ` ${printable(r)}`) : [` ${empty}`], "");
|
|
235
|
+
section(
|
|
236
|
+
"(a) hyle paths shadowed by host static routes (the hyle page is never served):",
|
|
237
|
+
report.shadowedHylePaths.map((s) => `${s.url} (hyle path ${s.path})`),
|
|
238
|
+
"none"
|
|
239
|
+
);
|
|
240
|
+
section("(c) mounts whose prefix is a host static route (the mount's index page is never served):", report.mountCollisions.map((m) => `${m.url} (mount ${m.prefix})`), "none");
|
|
241
|
+
section(
|
|
242
|
+
"(b) host dynamic routes matching hyle URLs:",
|
|
243
|
+
report.dynamicOverlaps.map((d) => {
|
|
244
|
+
const label = { "hyle-catch-all": "OK: this is hyle's catch-all", "hyle-wins": "OK: hyle's catch-all is more specific", "host-wins": "WARN: the host route is served, hyle content is hidden" }[d.verdict];
|
|
245
|
+
return `${d.route} ${label} (${d.matches} URLs, e.g. ${d.examples.join(", ") || "-"})`;
|
|
246
|
+
}),
|
|
247
|
+
"none"
|
|
248
|
+
);
|
|
249
|
+
if (report.notes.length) section("notes:", report.notes, "");
|
|
250
|
+
lines.push(report.ok ? "RESULT: no collisions" : "RESULT: collisions found");
|
|
251
|
+
return lines.join("\n");
|
|
252
|
+
}
|
|
253
|
+
var MAX_PRINTED = 200;
|
|
254
|
+
var printable = (text) => {
|
|
255
|
+
const clean = text.replace(/\u001b(?:\[[0-?]*[ -/]*[@-~]|\][^\u0007\u001b]*(?:\u0007|\u001b\\)?|.)?/g, "").replace(/[\u0000-\u001f\u007f-\u009f]/g, "");
|
|
256
|
+
return clean.length > MAX_PRINTED ? `${clean.slice(0, MAX_PRINTED)}...` : clean;
|
|
257
|
+
};
|
|
258
|
+
|
|
259
|
+
// src/sitemap.ts
|
|
260
|
+
var PAGE_LIMIT = 100;
|
|
261
|
+
var DEFAULT_MAX_PAGES = 20;
|
|
262
|
+
var SECTION_SLUG = /^[A-Za-z0-9][A-Za-z0-9_-]*$/;
|
|
263
|
+
var UNSAFE_PATH = /[\\?#<>&"'\u0000- \u007f]/;
|
|
264
|
+
async function listPublicationPaths(options) {
|
|
265
|
+
const maxPages = options.maxPages ?? DEFAULT_MAX_PAGES;
|
|
266
|
+
const prefix = `${options.basePath}/`;
|
|
267
|
+
const indexes = [options.basePath || "/"];
|
|
268
|
+
for (const slug of options.sections ?? []) if (slug !== "posts" && SECTION_SLUG.test(slug)) indexes.push(`${options.basePath}/${slug}`);
|
|
269
|
+
const found = /* @__PURE__ */ new Map();
|
|
270
|
+
let complete = true;
|
|
271
|
+
try {
|
|
272
|
+
for (const index of new Set(indexes)) {
|
|
273
|
+
let cursor;
|
|
274
|
+
for (let page = 0; page < maxPages; page++) {
|
|
275
|
+
const result = await options.client.resolve({
|
|
276
|
+
path: index,
|
|
277
|
+
limit: PAGE_LIMIT,
|
|
278
|
+
...options.locale !== void 0 ? { locale: options.locale } : {},
|
|
279
|
+
...cursor !== void 0 ? { cursor } : {}
|
|
280
|
+
});
|
|
281
|
+
if (result.kind !== "list") {
|
|
282
|
+
complete = false;
|
|
283
|
+
break;
|
|
284
|
+
}
|
|
285
|
+
for (const item of result.items) {
|
|
286
|
+
if (item.canonical_path.startsWith(prefix) && !UNSAFE_PATH.test(item.canonical_path)) found.set(item.canonical_path, item.published_at);
|
|
287
|
+
}
|
|
288
|
+
if (!result.next_cursor) break;
|
|
289
|
+
if (page === maxPages - 1) complete = false;
|
|
290
|
+
cursor = result.next_cursor;
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
} catch {
|
|
294
|
+
complete = false;
|
|
295
|
+
}
|
|
296
|
+
return { paths: [...found].map(([path, publishedAt]) => ({ path, publishedAt })), complete };
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
// src/check-routes-cli.ts
|
|
300
|
+
var USAGE = `hyle-sdk-check-routes [--next-dir .next] [--base-url URL] [--json] [--print-reserved]
|
|
301
|
+
[--locales en,fr,es --default-locale en --locale-prefix as-needed|always|never] [--sections a,b] [--hyle-param hyle]
|
|
302
|
+
|
|
303
|
+
Run after \`next build\`. Reads the build's route manifests and hyle's read-only endpoints (mounts, and the published pages of each mount).
|
|
304
|
+
Credentials: HYLE_TARGET_BASE_URL (or --base-url) and HYLE_TARGET_TOKEN. The token is read from the environment only, never a flag.
|
|
305
|
+
(a) hyle pages a host static route shadows, (b) host dynamic routes that match hyle URLs, (c) mounts that are host static routes.
|
|
306
|
+
--print-reserved print the host's static routes in hyle's "Reserved paths" format and exit.
|
|
307
|
+
Exit: 0 no collision, 1 collision (a) or (c), 2 cannot run.`;
|
|
308
|
+
var FLAGS = /* @__PURE__ */ new Set(["--next-dir", "--base-url", "--locales", "--default-locale", "--locale-prefix", "--sections", "--hyle-param"]);
|
|
309
|
+
var BOOLEAN = /* @__PURE__ */ new Set(["--json", "--print-reserved", "--help"]);
|
|
310
|
+
var CANNOT_RUN = 2;
|
|
311
|
+
function parseArgs(argv) {
|
|
312
|
+
const args = /* @__PURE__ */ new Map();
|
|
313
|
+
for (let i = 0; i < argv.length; i++) {
|
|
314
|
+
const flag = argv[i];
|
|
315
|
+
if (BOOLEAN.has(flag)) args.set(flag, "true");
|
|
316
|
+
else if (FLAGS.has(flag) && argv[i + 1] !== void 0) args.set(flag, argv[++i]);
|
|
317
|
+
else throw new Error(`unknown or incomplete option ${flag}`);
|
|
318
|
+
}
|
|
319
|
+
return args;
|
|
320
|
+
}
|
|
321
|
+
var readJson = (file) => JSON.parse(readFileSync(file, "utf8"));
|
|
322
|
+
async function runCli(argv, io) {
|
|
323
|
+
try {
|
|
324
|
+
const args = parseArgs(argv);
|
|
325
|
+
if (args.has("--help")) return io.out(USAGE), 0;
|
|
326
|
+
const nextDir = args.get("--next-dir") ?? ".next";
|
|
327
|
+
const hyleParam = args.get("--hyle-param") ?? "hyle";
|
|
328
|
+
let locale;
|
|
329
|
+
if (args.has("--locales")) {
|
|
330
|
+
const prefix = args.get("--locale-prefix") ?? "as-needed";
|
|
331
|
+
const locales = args.get("--locales").split(",").filter(Boolean);
|
|
332
|
+
const defaultLocale = args.get("--default-locale") ?? locales[0];
|
|
333
|
+
if (!["as-needed", "always", "never"].includes(prefix) || !defaultLocale || !locales.includes(defaultLocale)) throw new Error("--locales needs --default-locale among them and --locale-prefix as-needed|always|never");
|
|
334
|
+
locale = { locales, defaultLocale, prefix };
|
|
335
|
+
}
|
|
336
|
+
let hostRoutes;
|
|
337
|
+
try {
|
|
338
|
+
const appPaths = (() => {
|
|
339
|
+
try {
|
|
340
|
+
return readJson(join(nextDir, "server", "app-paths-manifest.json"));
|
|
341
|
+
} catch {
|
|
342
|
+
return void 0;
|
|
343
|
+
}
|
|
344
|
+
})();
|
|
345
|
+
hostRoutes = hostRoutesFromManifests({ routesManifest: readJson(join(nextDir, "routes-manifest.json")), ...appPaths ? { appPaths } : {} });
|
|
346
|
+
} catch {
|
|
347
|
+
io.err(`CANNOT RUN: no readable ${join(nextDir, "routes-manifest.json")} (run \`next build\` first, or pass --next-dir)`);
|
|
348
|
+
return CANNOT_RUN;
|
|
349
|
+
}
|
|
350
|
+
const baseUrl = args.get("--base-url") ?? io.env.HYLE_TARGET_BASE_URL;
|
|
351
|
+
const token = io.env.HYLE_TARGET_TOKEN;
|
|
352
|
+
const client = baseUrl && token ? createHyleClient({ baseUrl, token, ...io.fetch ? { fetch: io.fetch } : {} }) : void 0;
|
|
353
|
+
const mounts = client ? await client.mounts() : void 0;
|
|
354
|
+
if (mounts?.kind === "disabled") {
|
|
355
|
+
io.err("CANNOT RUN: hyle's read surface is switched off (kind: disabled)");
|
|
356
|
+
return CANNOT_RUN;
|
|
357
|
+
}
|
|
358
|
+
const prefixes = mounts?.mounts.map((m) => m.prefix);
|
|
359
|
+
if (args.has("--print-reserved")) {
|
|
360
|
+
const reserved = reservedFor(hostRoutes, { ...locale ? { locale } : {}, ...prefixes ? { mounts: prefixes } : {} });
|
|
361
|
+
if (!prefixes) io.err("note: hyle was not reachable (set HYLE_TARGET_BASE_URL and HYLE_TARGET_TOKEN), so route groups are listed exactly, not collapsed to /x/*");
|
|
362
|
+
io.out(args.has("--json") ? JSON.stringify(reserved) : reserved.join("\n"));
|
|
363
|
+
return 0;
|
|
364
|
+
}
|
|
365
|
+
if (!client || !mounts || mounts.kind !== "mounts") {
|
|
366
|
+
io.err("CANNOT RUN: set HYLE_TARGET_BASE_URL (or --base-url) and HYLE_TARGET_TOKEN");
|
|
367
|
+
return CANNOT_RUN;
|
|
368
|
+
}
|
|
369
|
+
const sections = args.get("--sections")?.split(",").filter(Boolean);
|
|
370
|
+
const hylePaths = [];
|
|
371
|
+
for (const { prefix } of mounts.mounts) {
|
|
372
|
+
const listing = await listPublicationPaths({ client, basePath: normalizeBasePath(prefix), maxPages: 100, ...sections ? { sections } : {} });
|
|
373
|
+
if (!listing.complete) {
|
|
374
|
+
io.err(`CANNOT RUN: hyle's pages under ${printable(prefix)} could not be listed completely, so a collision could be missed`);
|
|
375
|
+
return CANNOT_RUN;
|
|
376
|
+
}
|
|
377
|
+
hylePaths.push(...listing.paths.map((p) => p.path));
|
|
378
|
+
}
|
|
379
|
+
const report = checkRoutes({ hostRoutes, mounts: mounts.mounts.map((m) => m.prefix), hylePaths, hyleParam, ...locale ? { locale } : {} });
|
|
380
|
+
io.out(args.has("--json") ? JSON.stringify(report, null, 2) : formatReport(report));
|
|
381
|
+
return report.ok ? 0 : 1;
|
|
382
|
+
} catch (error) {
|
|
383
|
+
io.err(`CANNOT RUN: ${error instanceof Error ? printable(`${error.name}: ${error.message}`) : "unknown error"}`);
|
|
384
|
+
return CANNOT_RUN;
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
// src/check-routes-bin.ts
|
|
389
|
+
process.exitCode = await runCli(process.argv.slice(2), { env: process.env, out: (l) => console.log(l), err: (l) => console.error(l) });
|