@tdacorp/hyle-sdk 0.12.0 → 0.17.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.
Files changed (43) hide show
  1. package/README.md +46 -12
  2. package/dist/check-routes-bin.js +31 -18
  3. package/dist/{chunk-S7PCCEHP.js → chunk-6VOHFFA5.js} +4 -3
  4. package/dist/{chunk-ZQFYH4FX.js → chunk-DMK4XQLU.js} +497 -327
  5. package/dist/{chunk-N7ZQUAGM.js → chunk-MGSUQBDW.js} +19 -7
  6. package/dist/{chunk-R5EMI4HQ.js → chunk-PJMJMP66.js} +3 -1
  7. package/dist/comments.cjs +6 -4
  8. package/dist/comments.js +6 -5
  9. package/dist/{diagram-viewer-DYX6R63Y.js → diagram-viewer-FJPED4SN.js} +46 -26
  10. package/dist/{embed-jCaSI31t.d.cts → embed-BmdwA2G9.d.cts} +51 -5
  11. package/dist/{embed-DL5QIZRJ.d.ts → embed-DNTZ2UXv.d.ts} +51 -5
  12. package/dist/index.cjs +19 -7
  13. package/dist/index.d.cts +15 -8
  14. package/dist/index.d.ts +15 -8
  15. package/dist/index.js +1 -1
  16. package/dist/labels-nmukKYgL.d.cts +37 -0
  17. package/dist/labels-nmukKYgL.d.ts +37 -0
  18. package/dist/mermaid-diagram.cjs +59 -30
  19. package/dist/mermaid-diagram.d.cts +4 -37
  20. package/dist/mermaid-diagram.d.ts +4 -37
  21. package/dist/mermaid-diagram.js +7 -5
  22. package/dist/mermaid-image.cjs +1382 -0
  23. package/dist/mermaid-image.d.cts +29 -0
  24. package/dist/mermaid-image.d.ts +29 -0
  25. package/dist/mermaid-image.js +94 -0
  26. package/dist/next.cjs +1235 -789
  27. package/dist/next.d.cts +149 -24
  28. package/dist/next.d.ts +149 -24
  29. package/dist/next.js +887 -612
  30. package/dist/react.cjs +336 -196
  31. package/dist/react.d.cts +39 -7
  32. package/dist/react.d.ts +39 -7
  33. package/dist/react.js +1 -1
  34. package/dist/{resolve-DvmuBlpO.d.ts → resolve-Ae7UFjsQ.d.ts} +5 -5
  35. package/dist/{resolve-f6IJ6SL9.d.cts → resolve-euZ4-aC9.d.cts} +5 -5
  36. package/dist/styles.css +11 -22
  37. package/dist/{types-5D6ZD0Wi.d.cts → types-Czt887Iv.d.cts} +32 -3
  38. package/dist/{types-5D6ZD0Wi.d.ts → types-Czt887Iv.d.ts} +32 -3
  39. package/dist/use-cache.cjs +1 -1
  40. package/dist/use-cache.d.cts +2 -2
  41. package/dist/use-cache.d.ts +2 -2
  42. package/dist/use-cache.js +2 -2
  43. package/package.json +1 -1
package/README.md CHANGED
@@ -77,7 +77,7 @@ export const GET = () => hyleFeed({ ...options, siteOrigin: "https://tdacorp.in"
77
77
  |---|---|---|
78
78
  | `@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) |
79
79
  | `@tdacorp/hyle-sdk/react` | `ArticlePage`, `Comments`, `ListPage`, `HyleListView`, `HyleArticleView`, `DocsPage`, `NotFound`, `Redirecting`, `Unavailable`, `HastContent`, `TrustedServerHtml`, `sanitizeHast` | react >= 19 |
80
- | `@tdacorp/hyle-sdk/next` | `hylePage`, `hyleMetadata`, `hyleSitemap`, `hyleFeed`, `hyleRootPage`, `hyleRootMetadata`, `hyleRootSitemap`, `createRevalidateRoute`, `createAssetRoute`, `createEngagementRoute`, `HyleList`, `HyleArticle`, `HyleComments`, `HyleCommentsFallback`, `fetchResolver`, `workspaceTags` | next >= 16 |
80
+ | `@tdacorp/hyle-sdk/next` | `hylePage`, `hyleMetadata`, `hyleSitemap`, `hyleFeed`, `hyleRootPage`, `hyleRootMetadata`, `hyleRootSitemap`, `createMarkdownRoute`, `markdownRewritePath`, `createLlmsTxtRoute`, `createRevalidateRoute`, `createAssetRoute`, `createOgImageRoute`, `createEngagementRoute`, `HyleList`, `HyleArticle`, `HyleComments`, `HyleCommentsFallback`, `fetchResolver`, `workspaceTags` | next >= 16 |
81
81
  | `@tdacorp/hyle-sdk/next/use-cache` | `cachedResolver` | next >= 16 with `cacheComponents: true` |
82
82
  | `@tdacorp/hyle-sdk/styles.css` | the stylesheet | |
83
83
 
@@ -102,7 +102,7 @@ A redirect target is followed only if it is a same-origin path: one leading `/`,
102
102
 
103
103
  hyle tags every response with `cache.tags` and, on publish, calls your revalidate route with the tags to purge. Next's fetch cache needs the tags when the request is made, but the response (which carries the tags) does not exist yet. The SDK offers two strategies. Both were run against a real `next build` and `next start` (Next 16.3.4) with a mock hyle: a second request is served from cache, a signed webhook purges, the next request refetches.
104
104
 
105
- 1. **Fetch cache (default, no host configuration).** The fetch is tagged with what is known beforehand, a fixed and small set whatever URLs visitors request: the workspace tag, the default section `posts` and the sections you list (`hyle:1:sec:{workspaceId}:{section}`). Publish, unpublish, rename and edit all purge the section tag (cp1-spec section 5.8), so the page refreshes without knowing its own publication tag. Pass `sections: ["docs"]` for every other section the mount shows. Limits: a page in a section you did not list, and a page that renders a wikilink to a document in another section, refreshes only when `revalidate` (default 300 s) elapses; the per-publication tags in the response are not used. Redirects and 404s return real HTTP 308, 307 and 404.
105
+ 1. **Fetch cache (default, no host configuration).** The fetch is tagged with what is known beforehand, a fixed and small set whatever URLs visitors request: the workspace tag, the sections you list, so pass the mount's own section slug (`hyle:1:sec:{workspaceId}:{section}`). Publish, unpublish, rename and edit all purge the section tag (cp1-spec section 5.8), so the page refreshes without knowing its own publication tag. Through `hyleRootPage` the mount's section is tagged for you. Limits: a page in a section you did not list, and a page that renders a wikilink to a document in another section, refreshes only when `revalidate` (default 300 s) elapses; the per-publication tags in the response are not used. Redirects and 404s return real HTTP 308, 307 and 404.
106
106
  2. **`'use cache'` (exact tags, opt in).** `cachedResolver` fetches inside a `'use cache'` function and tags the entry with the response's own `cache.tags`. The host must set `cacheComponents: true` in `next.config`, and must wrap the page in `<Suspense>` (Next requires it for route params under Cache Components). Because the page then streams, a redirect reaches the browser as a meta refresh and a not found as a noindex page, both with HTTP 200 (observed). Import it only when opting in: Next compiles the directive inside this package, and with `cacheComponents` off even importing the module fails the build ("To use "use cache", please enable the feature flag cacheComponents", observed), which is why it is a separate entry point.
107
107
 
108
108
  ```tsx
@@ -120,7 +120,7 @@ The revalidate route expires tags immediately (`revalidateTag(tag, { expire: 0 }
120
120
 
121
121
  `list: { title, description }` sets the list page's h1, `<title>`, description and Open Graph. Each wins over hyle's section title (which is the slug, "Posts") and falls back separately: no `list.title` keeps the section title, no `list.description` shows none. Articles are unaffected.
122
122
 
123
- List pages show the first page of results (`listLimit`, server default 20, maximum 100). `paginate: "searchParams"` turns on cursor pagination: `?cursor=` is read (it must be 1 to 256 characters of `A-Za-z0-9_-`, otherwise it is ignored; a well-formed cursor hyle rejects is a 404), sent to hyle, and "Older posts" links to `?cursor=<next_cursor>`. It is off by default because reading `searchParams` makes the route dynamic: it can no longer be statically generated or served from ISR (hyle's fetch cache and tags still apply per request). Leave it off when one page is enough. `generateMetadata` does not read the cursor, so page 2 shares page 1's title.
123
+ List pages show the first page of results (`listLimit`, server default 20, maximum 100). `paginate: "searchParams"` turns on cursor pagination: `?cursor=` is read (it must be 1 to 256 characters of `A-Za-z0-9_-`, otherwise it is ignored; a well-formed cursor hyle rejects is a 404), sent to hyle, and "Older posts" links to `?cursor=<next_cursor>`. It is off by default because reading `searchParams` makes the route dynamic: it can no longer be statically generated or served from ISR (hyle's fetch cache and tags still apply per request). Leave it off when one page is enough. `generateMetadata` reads the cursor too (also under `hyleRootMetadata`), so page 2 has its own canonical and an "Older posts" title suffix.
124
124
 
125
125
  ## Errors
126
126
 
@@ -134,6 +134,10 @@ How `hylePage` treats a hyle failure is chosen so a bad moment never replaces a
134
134
 
135
135
  Why rethrow: a rendered "unavailable" page is a normal 200 render, so ISR would cache it and replace the last good article for everyone for the revalidate window. `onError: (error) => ReactElement` is the opt-in for a custom UI anyway; its element IS cached like any render, and the `error` it receives can contain `Cp1ClientError.message` and `requestId`, so never render it (only its name is logged, never the token or message). The `Unavailable` component (en, fr, es; `data-hyle-page="unavailable"`, `role="status"`, no error text) is exported from `./react` for `onError` or your own `error.tsx`. `hyleMetadata` follows the same split: a 4xx rejection gives `{}`, anything else is rethrown, so a transient outage never caches a noindex page.
136
136
 
137
+ ### More in this section
138
+
139
+ `related: { limit?, title? }` (layout "article") adds a "More in this section" list after the pager: one extra request for the article's section path (the first breadcrumb, else `basePath`) with `limit + 1` (default limit 5), the current article left out, rendered with `HyleListView`. An article's own child pages follow under "In this section". The request goes through the page's resolver, so it carries the same cache tags and a purge refreshes both. If it fails, the block is omitted and the page still renders. Backlinks are not read.
140
+
137
141
  ## Sitemap
138
142
 
139
143
  The contract has no "list every page" endpoint, so the helper pages the list result at each section index (100 per page, `next_cursor`, at most 20 pages per index by default). Spread it into your sitemap:
@@ -141,11 +145,11 @@ The contract has no "list every page" endpoint, so the helper pages the list res
141
145
  ```ts
142
146
  import { hyleSitemap } from "@tdacorp/hyle-sdk/next";
143
147
  export default async function sitemap() {
144
- return [...staticEntries, ...(await hyleSitemap({ ...options, origin: "https://tdacorp.in", sections: ["docs"] }))];
148
+ return [...staticEntries, ...(await hyleSitemap({ ...options, origin: "https://tdacorp.in" }))];
145
149
  }
146
150
  ```
147
151
 
148
- `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.
152
+ `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 the later of `published_at` and `updated_at` (omitted if neither is an ISO date). A translated page also gets `alternates.languages` (the list item's `alternates`, via `localePrefix`); `hyleRootSitemap` lists a mount once per locale in `mount.locales`. Only the mount's own section is covered (each section is its own mount; use `hyleRootSitemap` for all of them), at most 2000 pages. `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, locale?, maxPages? })` never throws and returns `{ paths: { path, publishedAt, updatedAt?, alternates?, title, description }[], complete }`, where `complete: false` means `paths` is partial.
149
153
 
150
154
  ## Root catch-all
151
155
 
@@ -196,7 +200,7 @@ The last good copy is in process memory, keyed by hyle origin plus workspace id
196
200
 
197
201
  ### Collision checker
198
202
 
199
- `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`).
203
+ `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). `--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`).
200
204
 
201
205
  ### Syncing reserved paths
202
206
 
@@ -239,8 +243,35 @@ Checklist for a site that mounts hyle at the root (details in the sections named
239
243
 
240
244
  - A REQUIRED catch-all `app/(site)/[...hyle]/page.tsx` (not `[[...hyle]]`), see "Root catch-all". A single mount that you name (`hylePage` at `/learn`) needs only its own route.
241
245
  - `app/api/hyle/assets/[file]/route.ts` exporting `GET` and `HEAD` from `createAssetRoute`, if content has images, video or audio, see "Media".
246
+ - `app/api/hyle/og/[...path]/route.ts` exporting `GET` from `createOgImageRoute(options)` (the same options as `hylePage`), and `ogImageRoute: true` in the page options, if you want the default card (needs `siteOrigin`, no `ogImage`): it draws the 1200x630 card, see "Not included". `/api/hyle/og` is reserved by the SDK.
242
247
  - hyle's reserved paths must cover `/api/hyle/*` and your other routes: run `hyle-sdk-check-routes --sync` after `next build` (needs `HYLE_CONTROL_TOKEN`), see "Syncing reserved paths".
243
248
  - No parent layout or page above the mount may export `dynamicParams = false` (below).
249
+ - Optional, for AI readers: the `.md` twin and `llms.txt` (next section).
250
+
251
+ ### Feed and markdown discovery
252
+
253
+ `feed: { path, title? }` (a path, or `(locale) => path`) adds `<link rel="alternate" type="application/rss+xml">` to article and list metadata, absolute when `siteOrigin` is set, merged with the host's own `alternates.types`. The path is used as given and is not localized (`localePrefix` is not applied): return the locale's own feed path from the function form if feeds are per-locale. On `hyleRootMetadata`, `feed` and `markdownTwin` set on a root config apply to every mount. `title` defaults to "<siteName> feed", else "Feed". For a host-owned page (for example one using `HyleList`, which emits nothing in the head), `hyleFeedLink(options, locale)` returns the same `{ url, title }`. `markdownTwin: true` (set it when the markdown route below is mounted) adds `<link rel="alternate" type="text/markdown">` to `<canonical>.md` on article pages only; the twin stays noindex and is not in the sitemap.
254
+
255
+ ### Markdown twins, llms.txt and per-locale feeds (optional)
256
+
257
+ `app/api/hyle/md/[...path]/route.ts` (under `[locale]` for a locale-prefixed site, so `locale(params)` works):
258
+
259
+ ```ts
260
+ import { createMarkdownRoute } from "@tdacorp/hyle-sdk/next";
261
+ export const { GET } = createMarkdownRoute(configs); // the same configs as hyleRootPage
262
+ ```
263
+
264
+ Middleware (or `proxy.ts`) rewrites `/learn/x.md` to it, so the visitor's URL stays the `.md` one:
265
+
266
+ ```ts
267
+ import { markdownRewritePath } from "@tdacorp/hyle-sdk/next";
268
+ const rewritten = markdownRewritePath(request.nextUrl.pathname);
269
+ if (rewritten) return NextResponse.rewrite(new URL(rewritten, request.url));
270
+ ```
271
+
272
+ The response is `text/markdown; charset=utf-8` with `X-Robots-Tag: noindex` (the twin must not compete with the page). If your matcher skips `/api`, this rewrite still works: it runs on the public URL. `app/llms.txt/route.ts`: `export const { GET } = createLlmsTxtRoute(configs, { origin: "https://example.com", title: "Example" })` lists every mount's default-locale pages as `- [title](origin/path.md): description`.
273
+
274
+ One feed per locale needs no new helper: `hyleFeed` takes the options of `hylePage`, so give each locale its own route file (`app/feed.xml/route.ts`, `app/fr/feed.xml/route.ts`) with `export const GET = () => hyleFeed({ ...options, basePath: "/apprendre", locale: "fr", localePrefix: (l) => (l === "en" ? "" : "/" + l), siteOrigin, feedPath: "/fr/feed.xml" })`.
244
275
 
245
276
  Bundler only: `@tdacorp/hyle-sdk/next` and `/next/use-cache` import `next/navigation` and `next/cache` the way a Next app does, so plain Node ESM cannot import them. Real `next build` runs of the packed package passed with Next 16.2.7, 16.3.4 and 16.4.2 (Turbopack, the default).
246
277
 
@@ -315,7 +346,7 @@ import { HyleArticle, HyleComments, HyleCommentsFallback, HyleList } from "@tdac
315
346
  </Suspense>
316
347
  ```
317
348
 
318
- - `HyleList`: `section` (a slug other than the default `posts`, resolved under `basePath`), `limit` (default 5, at most 100), `layout` (`"list"` or `"grid"`, default list), `title`, `headingLevel` (2, 3 or 4, default 2), `moreHref` (a "View all" link to a URL you choose, usually the mount) and `locale` (needed when `options.locale` is a function of route params, which a component cannot evaluate). It is a flat list, newest first, with no month groups and no pagination. The slots `list.item` and `list.empty` of `options.slots` apply.
349
+ - `HyleList`: `limit` (default 5, at most 100), `layout` (`"list"` or `"grid"`, default list), `title`, `headingLevel` (2, 3 or 4, default 2), `moreHref` (a "View all" link to a URL you choose, usually the mount) and `locale` (needed when `options.locale` is a function of route params, which a component cannot evaluate). It is a flat list, newest first, with no month groups. Pagination is opt-in: `cursor` (the page's `?cursor=`) starts after a `next_cursor`, and `olderHref={(next) => `/blog?cursor=${next}`}` is called with the list's `next_cursor`, when there is one, to build the "Older posts" link. The slots `list.item` and `list.empty` of `options.slots` apply. The `list.item` slot's item also carries the document's authored fields when the server sends them: `tags` (slug tokens), `kicker`, `status` (a free label), `cover` (`{ path }`, root-relative `/assets/<id>`, or `null`) and `author` (`{ name, url }` or `null`); an older server omits them. An article's `publication` carries the same fields, and its `author` is the byline used for the page metadata and JSON-LD ahead of `jsonLd.author` and `frontmatter.author`.
319
350
  - `HyleArticle`: `path`, `headingLevel` (default 2), `locale`. Title, date, description, the body, and a visible "Read at source" link. No table of contents, pager, languages bar, comments or JSON-LD. A path that is not an article (a redirect included) renders nothing.
320
351
  - `HyleComments`: `options: { baseUrl, token, locale? }`, `path` (the article's canonical path), `revalidate` (seconds, default 60) and `interactive`. The listing is public and cached for `revalidate` seconds, not purged by a webhook. It renders the thread as server HTML (`ol > li > article`, names, dates, sanitized bodies, links `rel="nofollow ugc"`, removed comments as tombstones) and nothing at all when there are no comments or hyle answers 404 (engagement off, unknown article) or fails. With `interactive` (`true`, or `{ endpoint?, signInHref? }`) the `Comments` island is rendered INSTEAD, seeded from the same listing: the thread is still in the server HTML, there is no skeleton flash, readers can comment and like (it needs `createEngagementRoute`, as in "Comments and likes"), and it refetches silently on mount. The listing is serialized once into the page for the island (up to 500 comments), so leave `interactive` off where you only need to show comments.
321
352
 
@@ -337,7 +368,8 @@ Zero setup. A Mermaid fence arrives from hyle as a sandboxed `<iframe srcdoc>` t
337
368
  - 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).
338
369
  - 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.
339
370
  - 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.
340
- - 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.
371
+ - Stored renders: when hyle has a pre-rendered image of the diagram in both themes (the editor renders it in the author's browser, hyle sanitizes and stores it, ADR 0024), the page gets a sized `<img>` (aspect ratio reserved, so no layout shift), the diagram source in a `<details>` for crawlers and no-JS readers, and no Mermaid layout runs in any browser. The image goes through your asset route (`createAssetRoute`, `img-src 'self'`). Click-to-expand fetches that same sanitized SVG for the viewer. If the image fails to load, or hyle has no stored render yet, the page renders the diagram client-side as above, with a loader and a reserved height.
372
+ - A source that is not the renderer's template is dropped. There is no length cap on the diagram beyond the 1 MiB `srcdoc` guard, and no cdnjs frame. If Mermaid cannot render the source (a syntax error), the code block stays and a short "diagram could not be rendered" note appears.
341
373
  - 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`).
342
374
  - 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.
343
375
 
@@ -395,17 +427,19 @@ Chrome strings exist for en, fr and es (fr and es are unreviewed drafts). The pa
395
427
 
396
428
  - 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).
397
429
  - The path is sent as a query parameter (encoded once); catch-all segments are decoded and refused if they contain `/`, `\`, control characters, `.` or `..`.
398
- - 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.
399
- - 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'`.
430
+ - 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 1 MiB); the SDK never renders that frame, it only reads the diagram text out of it. `data-light` and `data-dark` on it are kept only as `/assets/<uuid>.svg <width> <height>`. 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.
431
+ - Mermaid renders into your page, so: the source comes only from hyle content, passes the exact-template check and the 1 MiB `srcdoc` guard, and is rendered with `securityLevel: "strict"` (Mermaid's own DOMPurify pass, no raw HTML labels), `maxTextSize` set to that bound and `maxEdges` 5000. 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'`.
400
432
  - 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`).
401
433
  - The comments client talks only to the host's own `createEngagementRoute` (same origin; no credential, no hyle URL, no storage, no cookie access in the browser bundle, which a test pins). The route is an allowlist, not a proxy, and writes need same-origin plus a custom header (see "Comments and likes"). The private signing key stays on the server and is never logged; a malformed key is refused with a message that does not contain it.
402
434
  - 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.
403
435
 
404
436
  ## Not included
405
437
 
406
- Docs versions, reading time, "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".
438
+ Docs versions, "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".
439
+
440
+ Reading time: when the server sends `publication.word_count` (a positive integer; older servers omit it), article pages show the locale's "N min read" in the meta row (275 words per minute, at least 1), the BlogPosting carries `wordCount`, and the metadata adds `twitter:label1`/`twitter:data1` through `other`, keeping the host's own `other` keys read from `parent`. Nothing is shown or emitted without it.
407
441
 
408
- Social card images (`og:image`): the resolve contract carries no image data, so `hyleMetadata` emits none. Add your own by wrapping the returned function:
442
+ Social card images (`og:image`): the resolve contract carries no image data. Set `ogImage` to supply one per article. With `ogImageRoute: true` (off by default, because an unmounted route would 404), no `ogImage` and a valid `siteOrigin`, article metadata points at `/api/hyle/og/<canonical path>?locale=<locale>&v=<edit time>` (1200x630; `v` busts the year-long cache when the title changes) and the BlogPosting `image` is an ImageObject with that size; mount it first with `export const { GET } = createOgImageRoute(options)` in `app/api/hyle/og/[...path]/route.ts`. The card is cached for a year at the edge (`s-maxage`, `immutable`) and the route answers 404 when `HYLE_CONTENT_ENABLED=0`; `?locale=` is used only when it names a translation of the article. The card renderer (`next/og`) fetches Google Fonts and emoji assets from third parties at render time for non-Latin titles and emoji, so hosts with an egress allowlist should not enable `ogImageRoute`. The card is the title and `siteName` on a plain background in the system font, resolved from the article's canonical path (any mount, any locale section; a renamed slug redirects as the page does). List pages emit `og:type`, `og:url`, `og:site_name` and `og:locale`; the host layout's `og:image` is read from `parent` and passed through. To add your own image by hand, wrap the returned function:
409
443
 
410
444
  ```ts
411
445
  import { hyleMetadata, type PageProps } from "@tdacorp/hyle-sdk/next";
@@ -103,7 +103,7 @@ function createHyleClient(options) {
103
103
  const data = reply.parsed?.data;
104
104
  if (data && data.cp === 1 && typeof data.kind === "string" && KINDS.has(data.kind)) {
105
105
  const resolved = data;
106
- if (resolved.kind === "article" && resolved.content.format === "html" && opts.format !== "html") throw failure(reply);
106
+ if (resolved.kind === "article" && resolved.content.format !== "hast" && resolved.content.format !== opts.format) throw failure(reply);
107
107
  return resolved;
108
108
  }
109
109
  throw failure(reply);
@@ -345,17 +345,20 @@ var printable = (text) => {
345
345
  // src/sitemap.ts
346
346
  var PAGE_LIMIT = 100;
347
347
  var DEFAULT_MAX_PAGES = 20;
348
- var SECTION_SLUG = /^[A-Za-z0-9][A-Za-z0-9_-]*$/;
349
348
  var UNSAFE_PATH = /[\\?#<>&"'\u0000- \u007f]/;
349
+ var LOCALE_TAG = /^[a-z]{2,3}(-[A-Za-z0-9]{2,8})*$/;
350
+ var isSitePath = (path) => typeof path === "string" && path.startsWith("/") && !path.startsWith("//") && !UNSAFE_PATH.test(path);
351
+ function safeAlternates(raw) {
352
+ const kept = (raw ?? []).filter((a) => typeof a.locale === "string" && LOCALE_TAG.test(a.locale) && isSitePath(a.canonical_path));
353
+ return kept.length > 0 ? kept.map((a) => ({ locale: a.locale, path: a.canonical_path })) : void 0;
354
+ }
350
355
  async function listPublicationPaths(options) {
351
356
  const maxPages = options.maxPages ?? DEFAULT_MAX_PAGES;
352
357
  const prefix = `${options.basePath}/`;
353
- const indexes = [options.basePath || "/"];
354
- for (const slug of options.sections ?? []) if (slug !== "posts" && SECTION_SLUG.test(slug)) indexes.push(`${options.basePath}/${slug}`);
355
358
  const found = /* @__PURE__ */ new Map();
356
359
  let complete = true;
357
360
  try {
358
- for (const index of new Set(indexes)) {
361
+ for (const index of [options.basePath || "/"]) {
359
362
  let cursor;
360
363
  for (let page = 0; page < maxPages; page++) {
361
364
  const result = await options.client.resolve({
@@ -369,7 +372,16 @@ async function listPublicationPaths(options) {
369
372
  break;
370
373
  }
371
374
  for (const item of result.items) {
372
- if (item.canonical_path.startsWith(prefix) && !UNSAFE_PATH.test(item.canonical_path)) found.set(item.canonical_path, item.published_at);
375
+ if (!item.canonical_path.startsWith(prefix) || UNSAFE_PATH.test(item.canonical_path)) continue;
376
+ const alternates = safeAlternates(item.alternates);
377
+ found.set(item.canonical_path, {
378
+ path: item.canonical_path,
379
+ publishedAt: item.published_at,
380
+ ...typeof item.updated_at === "string" ? { updatedAt: item.updated_at } : {},
381
+ ...alternates ? { alternates } : {},
382
+ title: item.title,
383
+ description: item.description
384
+ });
373
385
  }
374
386
  if (!result.next_cursor) break;
375
387
  if (page === maxPages - 1) complete = false;
@@ -379,13 +391,13 @@ async function listPublicationPaths(options) {
379
391
  } catch {
380
392
  complete = false;
381
393
  }
382
- return { paths: [...found].map(([path, publishedAt]) => ({ path, publishedAt })), complete };
394
+ return { paths: [...found.values()], complete };
383
395
  }
384
396
 
385
397
  // src/check-routes-cli.ts
386
398
  var USAGE = `hyle-sdk-check-routes [--next-dir .next] [--base-url URL] [--json] [--print-reserved]
387
399
  [--sync [--strict] [--no-check] [--host ID] [--build-id ID] [--allow-empty] [--allow-non-production]]
388
- [--locales en,fr,es --default-locale en --locale-prefix as-needed|always|never] [--sections a,b] [--hyle-param hyle]
400
+ [--locales en,fr,es --default-locale en --locale-prefix as-needed|always|never] [--hyle-param hyle]
389
401
 
390
402
  Run after \`next build\`. Reads the build's route manifests and hyle's read-only endpoints (mounts, and the published pages of each mount).
391
403
  Credentials: HYLE_TARGET_BASE_URL (or --base-url) and HYLE_TARGET_TOKEN. The token is read from the environment only, never a flag.
@@ -398,7 +410,7 @@ Credentials: HYLE_TARGET_BASE_URL (or --base-url) and HYLE_TARGET_TOKEN. The tok
398
410
  from --host, HYLE_HOST_ID or VERCEL_PROJECT_PRODUCTION_URL; the build id from <next-dir>/BUILD_ID or --build-id.
399
411
  An empty list is refused unless --allow-empty.
400
412
  Exit: 0 no collision, 1 collision (a) or (c), 2 cannot run, 3 sync failed under --strict.`;
401
- var FLAGS = /* @__PURE__ */ new Set(["--next-dir", "--base-url", "--locales", "--default-locale", "--locale-prefix", "--sections", "--hyle-param", "--host", "--build-id"]);
413
+ var FLAGS = /* @__PURE__ */ new Set(["--next-dir", "--base-url", "--locales", "--default-locale", "--locale-prefix", "--hyle-param", "--host", "--build-id"]);
402
414
  var BOOLEAN = /* @__PURE__ */ new Set(["--json", "--print-reserved", "--help", "--sync", "--strict", "--no-check", "--allow-empty", "--allow-non-production"]);
403
415
  var CANNOT_RUN = 2;
404
416
  var SYNC_FAILED = 3;
@@ -518,17 +530,18 @@ async function runCli(argv, io) {
518
530
  io.err("CANNOT RUN: set HYLE_TARGET_BASE_URL (or --base-url) and HYLE_TARGET_TOKEN");
519
531
  return CANNOT_RUN;
520
532
  }
521
- const sections = args.get("--sections")?.split(",").filter(Boolean);
522
- const hylePaths = [];
523
- for (const { prefix } of mounts.mounts) {
524
- const listing = await listPublicationPaths({ client, basePath: normalizeBasePath(prefix), maxPages: 100, ...sections ? { sections } : {} });
525
- if (!listing.complete) {
526
- io.err(`CANNOT RUN: hyle's pages under ${printable(prefix)} could not be listed completely, so a collision could be missed`);
527
- return CANNOT_RUN;
533
+ const hylePaths = /* @__PURE__ */ new Set();
534
+ for (const { prefix, locales } of mounts.mounts) {
535
+ for (const locale2 of locales?.length ? locales : [void 0]) {
536
+ const listing = await listPublicationPaths({ client, basePath: normalizeBasePath(prefix), maxPages: 100, ...locale2 !== void 0 ? { locale: locale2 } : {} });
537
+ if (!listing.complete) {
538
+ io.err(`CANNOT RUN: hyle's pages under ${printable(prefix)} could not be listed completely, so a collision could be missed`);
539
+ return CANNOT_RUN;
540
+ }
541
+ listing.paths.forEach((p) => hylePaths.add(p.path));
528
542
  }
529
- hylePaths.push(...listing.paths.map((p) => p.path));
530
543
  }
531
- const report = checkRoutes({ hostRoutes, mounts: mounts.mounts.map((m) => m.prefix), hylePaths, hyleParam, ...locale ? { locale } : {} });
544
+ const report = checkRoutes({ hostRoutes, mounts: mounts.mounts.map((m) => m.prefix), hylePaths: [...hylePaths], hyleParam, ...locale ? { locale } : {} });
532
545
  io.out(args.has("--json") ? JSON.stringify(sync ? { ...report, sync } : report, null, 2) : formatReport(report));
533
546
  if (!report.ok) return 1;
534
547
  return sync?.status === "failed" && strict ? SYNC_FAILED : 0;
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  createHyleClient,
3
3
  isValidCacheTag
4
- } from "./chunk-N7ZQUAGM.js";
4
+ } from "./chunk-MGSUQBDW.js";
5
5
 
6
6
  // src/next/resolve.ts
7
7
  var DEFAULT_REVALIDATE = 300;
@@ -9,7 +9,7 @@ var MAX_TAGS = 64;
9
9
  function workspaceTags(workspaceId, sections = []) {
10
10
  const workspaceTag = `hyle:1:ws:${workspaceId}`;
11
11
  if (!isValidCacheTag(workspaceTag)) throw new TypeError("hyle: `workspaceId` is not a valid workspace id (a uuid)");
12
- const slugs = /* @__PURE__ */ new Set(["posts", ...sections]);
12
+ const slugs = new Set(sections);
13
13
  const tags = [...slugs].map((slug) => `hyle:1:sec:${workspaceId}:${slug}`);
14
14
  if (!tags.every(isValidCacheTag)) throw new TypeError("hyle: a configured `sections` slug cannot be used in a cache tag (printable ASCII, at most 200 characters)");
15
15
  return [workspaceTag, ...tags].slice(0, MAX_TAGS);
@@ -19,9 +19,10 @@ function fetchResolver(options) {
19
19
  const client = createHyleClient({ baseUrl: options.baseUrl, token: options.token });
20
20
  const revalidate = options.revalidate ?? DEFAULT_REVALIDATE;
21
21
  const tags = workspaceTags(options.workspaceId, options.sections);
22
- return (path, locale, limit, cursor, nav) => client.resolve({
22
+ return (path, locale, limit, cursor, nav, format) => client.resolve({
23
23
  path,
24
24
  ...nav !== void 0 ? { nav } : {},
25
+ ...format !== void 0 ? { format } : {},
25
26
  ...locale !== void 0 ? { locale } : {},
26
27
  ...limit !== void 0 ? { limit } : {},
27
28
  ...cursor !== void 0 ? { cursor } : {},