@tdacorp/hyle-sdk 0.14.1 → 0.21.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 +171 -32
- package/dist/check-routes-bin.js +48 -21
- package/dist/chunk-56Y24XBV.js +840 -0
- package/dist/{chunk-MGSUQBDW.js → chunk-75JFLML4.js} +176 -14
- package/dist/chunk-HJX57NLI.js +1105 -0
- package/dist/chunk-K5VDLROQ.js +145 -0
- package/dist/{chunk-BUJFMR3M.js → chunk-QVYQM5R2.js} +15 -6
- package/dist/chunk-U74B7AUG.js +398 -0
- package/dist/{chunk-6VOHFFA5.js → chunk-X2TLYM7Y.js} +2 -2
- package/dist/client-41fU6OY2.d.cts +201 -0
- package/dist/client-LwzHwqpM.d.ts +201 -0
- package/dist/code-copy.cjs +72 -0
- package/dist/code-copy.d.cts +15 -0
- package/dist/code-copy.d.ts +15 -0
- package/dist/code-copy.js +48 -0
- package/dist/comments.cjs +733 -278
- package/dist/comments.d.cts +66 -3
- package/dist/comments.d.ts +66 -3
- package/dist/comments.js +414 -330
- package/dist/{diagram-viewer-DYX6R63Y.js → diagram-viewer-XY3CG75U.js} +107 -46
- package/dist/{embed-B76zRRPa.d.cts → embed-BUFRQboD.d.ts} +10 -5
- package/dist/{embed-SqOBGI-E.d.ts → embed-CYt-q13P.d.cts} +10 -5
- package/dist/fragment-alias.cjs +51 -0
- package/dist/fragment-alias.d.cts +7 -0
- package/dist/fragment-alias.d.ts +7 -0
- package/dist/fragment-alias.js +27 -0
- package/dist/html.cjs +881 -0
- package/dist/html.d.cts +20 -0
- package/dist/html.d.ts +20 -0
- package/dist/html.js +45 -0
- package/dist/index.cjs +181 -14
- package/dist/index.d.cts +14 -62
- package/dist/index.d.ts +14 -62
- package/dist/index.js +11 -1
- package/dist/labels-CrA-iqTN.d.cts +46 -0
- package/dist/labels-CrA-iqTN.d.ts +46 -0
- package/dist/mermaid-diagram.cjs +453 -148
- package/dist/mermaid-diagram.d.cts +25 -42
- package/dist/mermaid-diagram.d.ts +25 -42
- package/dist/mermaid-diagram.js +205 -50
- package/dist/mermaid-image.cjs +1456 -0
- package/dist/mermaid-image.d.cts +30 -0
- package/dist/mermaid-image.d.ts +30 -0
- package/dist/mermaid-image.js +93 -0
- package/dist/next.cjs +1709 -1134
- package/dist/next.d.cts +67 -14
- package/dist/next.d.ts +67 -14
- package/dist/next.js +950 -794
- package/dist/print-coordinator.cjs +157 -0
- package/dist/print-coordinator.d.cts +27 -0
- package/dist/print-coordinator.d.ts +27 -0
- package/dist/print-coordinator.js +83 -0
- package/dist/react.cjs +677 -264
- package/dist/react.d.cts +161 -31
- package/dist/react.d.ts +161 -31
- package/dist/react.js +23 -3
- package/dist/reactions.cjs +653 -0
- package/dist/reactions.d.cts +27 -0
- package/dist/reactions.d.ts +27 -0
- package/dist/reactions.js +364 -0
- package/dist/{resolve-DC2ccfwA.d.ts → resolve-BjAK0k_Y.d.ts} +2 -2
- package/dist/{resolve-DKLVftk_.d.cts → resolve-eI1muCKL.d.cts} +2 -2
- package/dist/revalidation-callback-BQl77tQR.d.cts +75 -0
- package/dist/revalidation-callback-BQl77tQR.d.ts +75 -0
- package/dist/sanitize-ijiWjEm9.d.cts +23 -0
- package/dist/sanitize-ijiWjEm9.d.ts +23 -0
- package/dist/styles.css +107 -47
- package/dist/toc-spy.cjs +59 -0
- package/dist/toc-spy.d.cts +15 -0
- package/dist/toc-spy.d.ts +15 -0
- package/dist/toc-spy.js +35 -0
- package/dist/{types-ByodIyEv.d.cts → types-3F0wqD-o.d.cts} +44 -4
- package/dist/{types-ByodIyEv.d.ts → types-3F0wqD-o.d.ts} +44 -4
- package/dist/use-cache.cjs +37 -11
- package/dist/use-cache.d.cts +12 -5
- package/dist/use-cache.d.ts +12 -5
- package/dist/use-cache.js +7 -7
- package/dist/youtube-facade.cjs +50 -0
- package/dist/youtube-facade.d.cts +17 -0
- package/dist/youtube-facade.d.ts +17 -0
- package/dist/youtube-facade.js +26 -0
- package/package.json +16 -3
- package/dist/chunk-4V4VKB3O.js +0 -1471
- package/dist/chunk-R5EMI4HQ.js +0 -61
- package/dist/revalidation-callback-D7Ms_Puz.d.cts +0 -42
- package/dist/revalidation-callback-D7Ms_Puz.d.ts +0 -42
package/README.md
CHANGED
|
@@ -70,18 +70,57 @@ export const GET = () => hyleFeed({ ...options, siteOrigin: "https://tdacorp.in"
|
|
|
70
70
|
- The channel title and description come from `list.title` and `list.description`, else hyle's section title. Each item carries the title, the link on the mount (through `localePrefix`), a permalink `guid` equal to the link, `pubDate` from `published_at` and the description when there is one. Every value is XML-escaped, and an item whose `canonical_path` does not start with `/` is dropped.
|
|
71
71
|
- The list is read through the same resolver as `hylePage`, so it shares its fetch cache and publish tags. `export const revalidate` is Next's own route-handler setting and decides how long Next keeps the generated XML; the SDK adds no `cache-control`.
|
|
72
72
|
- A hyle failure answers 503 with an empty body instead of throwing; Next control flow still propagates.
|
|
73
|
+
- `hyleFeed` carries titles and descriptions only. For full-content feeds that you build yourself, see "Feed content".
|
|
74
|
+
|
|
75
|
+
## Article body in your own page
|
|
76
|
+
|
|
77
|
+
When the page is yours (your title, metadata, JSON-LD, sitemap and feeds) and hyle draws only the article body:
|
|
78
|
+
|
|
79
|
+
```tsx
|
|
80
|
+
import { HyleBody, HyleToc } from "@tdacorp/hyle-sdk/react";
|
|
81
|
+
import "@tdacorp/hyle-sdk/styles.css";
|
|
82
|
+
|
|
83
|
+
// `article` is a resolve result with `content.format === "hast"` (check `kind` and `format` first).
|
|
84
|
+
<h1>{article.publication.title}</h1>
|
|
85
|
+
<HyleToc toc={article.toc} variant="inline" locale="en" />
|
|
86
|
+
<HyleBody tree={article.content.tree} title={article.publication.title} description={article.publication.description} components={{ Link }} locale="en" />
|
|
87
|
+
<HyleToc toc={article.toc} variant="rail" aside={<Newsletter />} locale="en" />
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
- `HyleBody({ tree, title?, description?, components?, locale?, id? })` renders `div.hyle.hyle-body.hyle-prose` around the same content as `HastContent`, plus its client islands: code copy buttons, the fragment alias and the YouTube player. It carries `hyle` itself, so the `--hyle-*` tokens apply with no wrapper; keep `hyle-prose` selectable if something of yours (an offline search, say) reads the body by it. `title` and `description` drop a leading body h1 and paragraph that repeat them (never a paragraph with an embed link, so a body that opens with a video keeps it). `id` is generated when omitted. The element is a size container (`container: hyle / inline-size`), so give it a width from its parent: in a flex row or an auto-sized grid track, let it grow (`flex: 1; min-width: 0`).
|
|
91
|
+
- `HyleToc({ toc, variant, aside?, locale? })`: `"rail"` is a sticky `aside` (offset by `--hyle-sticky-top`) with scroll-spy (`aria-current="location"`), `"inline"` a collapsed `<details>`. `aside` shows under the rail's list. Only h2 and h3 are listed, and with nothing to list (and no `aside`) nothing renders. Both are shown wherever you put them: render both and hide one per breakpoint in your own CSS. `rail` is sticky only inside a parent taller than itself.
|
|
92
|
+
- `HastContent` on its own stays free of client code: no copy button and no player (a YouTube link stays a link).
|
|
93
|
+
|
|
94
|
+
What the body does, here and on the SDK's own pages:
|
|
95
|
+
|
|
96
|
+
- **Code blocks** have a copy button in `figure.hyle-codeblock > header`. One delegated listener per body writes the code to the clipboard; "Copied" or "Copy blocked" shows and is announced for 1.5 s. A successful copy dispatches a bubbling `hyle:code-copied` event on the figure (`event.detail.language`), if you count copies. A `components.CodeBlock` override replaces the block, button included.
|
|
97
|
+
- **Fragments**: when `#x` matches no element but `#user-content-x` does, the history entry is replaced with the latter, on load and on `hashchange`.
|
|
98
|
+
- **YouTube**: a paragraph that is only a link the renderer marked (`data-embed="youtube"`, with exactly `https://www.youtube.com/watch?v=<11 characters>`) becomes a thumbnail and a play button, with the link (through your `a` override) under it. Before the click the only third-party request is the thumbnail; the click swaps in a `youtube-nocookie.com` frame with a fixed `sandbox`, `allow` and title. A host with a CSP adds `img-src https://i.ytimg.com` and `frame-src https://www.youtube-nocookie.com`. Without them the thumbnail or the player is blocked and the link still works.
|
|
99
|
+
- **Images**: a paragraph that is one image (linked or not) renders `figure[data-slot-component="Image"] > img + figcaption`, the caption from the image title. The image is eager and high priority only when the body, after the dropped title and description, opens with such a figure; every other image is lazy.
|
|
100
|
+
- **Headings** h2 to h4 with an id get an empty `a.hyle-anchor` labelled "Link to this section"; the stylesheet draws the `#`, so heading text never contains it. A heading with the class `sr-only` gets none.
|
|
101
|
+
|
|
102
|
+
### Feed content
|
|
103
|
+
|
|
104
|
+
```ts
|
|
105
|
+
import { hastToHtml } from "@tdacorp/hyle-sdk/html"; // server only
|
|
106
|
+
|
|
107
|
+
const html = hastToHtml(article.content.tree, { baseUrl: "https://example.com/blog/post", title: article.publication.title });
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
`hastToHtml(tree, { baseUrl, title?, description?, locale? })` runs the same allowlist as the pages and returns a string for `content:encoded`, Atom `content` or JSON Feed `content_html` (escape it, or wrap it in CDATA, as your feed format needs). Callouts and figures are applied; every `href` and `src` is made absolute against `baseUrl` (pass the article's own URL, so `#footnote` links point back to it); there are no anchors, copy buttons, players or client code; a diagram is its source in `pre > code.language-mermaid`; a YouTube embed is its link. Asset URLs point at your own `/api/hyle/assets` route. It throws `TypeError` for a `baseUrl` that is not absolute http(s) and `HastLimitError` (exported here too) for a tree over the caps: leave the body out of that item.
|
|
73
111
|
|
|
74
112
|
## Entry points
|
|
75
113
|
|
|
76
114
|
| Import | Contents | Needs |
|
|
77
115
|
|---|---|---|
|
|
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
|
-
| `@tdacorp/hyle-sdk/react` | `ArticlePage`, `Comments`, `ListPage`, `HyleListView`, `HyleArticleView`, `DocsPage`, `NotFound`, `Redirecting`, `Unavailable`, `HastContent`, `TrustedServerHtml`, `sanitizeHast` | react >= 19 |
|
|
80
|
-
| `@tdacorp/hyle-sdk/
|
|
116
|
+
| `@tdacorp/hyle-sdk` | `createHyleClient` (typed `resolve`, `mounts` and `asset`), `listPublicationPaths`, `checkRoutes` and the other route-check functions, `Cp1ClientError`, `verifyHyleSignature`, `parseSignatureHeader`, `isValidCacheTag`, `DeliveryDedupe`, `createRevalidationCallbackRoute`, `parseCommentEvent`, the result types | nothing (no framework) |
|
|
117
|
+
| `@tdacorp/hyle-sdk/react` | `ArticlePage`, `Comments`, `HyleReactions`, `ListPage`, `HyleListView`, `HyleArticleView`, `DocsPage`, `NotFound`, `Redirecting`, `Unavailable`, `HyleBody`, `HyleToc`, `HastContent`, `TrustedServerHtml`, `sanitizeHast` | react >= 19 |
|
|
118
|
+
| `@tdacorp/hyle-sdk/html` | `hastToHtml`, `HastLimitError` (server only) | nothing (no framework) |
|
|
119
|
+
| `@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
120
|
| `@tdacorp/hyle-sdk/next/use-cache` | `cachedResolver` | next >= 16 with `cacheComponents: true` |
|
|
82
121
|
| `@tdacorp/hyle-sdk/styles.css` | the stylesheet | |
|
|
83
122
|
|
|
84
|
-
|
|
123
|
+
Runtime dependencies are `hast-util-to-jsx-runtime` (hast to React elements, the library behind react-markdown), `hast-util-to-html` (hast to a string, used only by `./html`), both MIT from the unified collective and both doing more than a short hand-rolled function would get right, and `mermaid` (see "Mermaid diagrams"). Everything else is hand-written.
|
|
85
124
|
|
|
86
125
|
## Locale
|
|
87
126
|
|
|
@@ -120,7 +159,7 @@ The revalidate route expires tags immediately (`revalidateTag(tag, { expire: 0 }
|
|
|
120
159
|
|
|
121
160
|
`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
161
|
|
|
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`
|
|
162
|
+
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
163
|
|
|
125
164
|
## Errors
|
|
126
165
|
|
|
@@ -134,6 +173,10 @@ How `hylePage` treats a hyle failure is chosen so a bad moment never replaces a
|
|
|
134
173
|
|
|
135
174
|
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
175
|
|
|
176
|
+
### More in this section
|
|
177
|
+
|
|
178
|
+
`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.
|
|
179
|
+
|
|
137
180
|
## Sitemap
|
|
138
181
|
|
|
139
182
|
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:
|
|
@@ -239,10 +282,15 @@ Checklist for a site that mounts hyle at the root (details in the sections named
|
|
|
239
282
|
|
|
240
283
|
- 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
284
|
- `app/api/hyle/assets/[file]/route.ts` exporting `GET` and `HEAD` from `createAssetRoute`, if content has images, video or audio, see "Media".
|
|
285
|
+
- `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
286
|
- 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
287
|
- No parent layout or page above the mount may export `dynamicParams = false` (below).
|
|
244
288
|
- Optional, for AI readers: the `.md` twin and `llms.txt` (next section).
|
|
245
289
|
|
|
290
|
+
### Feed and markdown discovery
|
|
291
|
+
|
|
292
|
+
`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.
|
|
293
|
+
|
|
246
294
|
### Markdown twins, llms.txt and per-locale feeds (optional)
|
|
247
295
|
|
|
248
296
|
`app/api/hyle/md/[...path]/route.ts` (under `[locale]` for a locale-prefixed site, so `locale(params)` works):
|
|
@@ -272,9 +320,13 @@ Verify after `next build`: `.next/prerender-manifest.json` must not show `"fallb
|
|
|
272
320
|
|
|
273
321
|
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.
|
|
274
322
|
|
|
323
|
+
## Push mode
|
|
324
|
+
|
|
325
|
+
A path in push mode delivers whole posts to your route (`createPushRoute`) and rebuilds from `resyncPath`; see `docs/cp1-spec.md` 5.3.3 and 5.3.4 in the hyle repository. Store `html` (sanitized) and render that. The `markdown` field is the author's source: never render it with raw HTML enabled. Sweep after a resync with `staleAfterResync`, never "everything not returned".
|
|
326
|
+
|
|
275
327
|
## Media
|
|
276
328
|
|
|
277
|
-
hyle stores an image, video or audio reference as `/assets/<uuid>.<ext>`, a path that exists only on hyle's own (authenticated) origin. On a host site it would 404, so the SDK rewrites it while rendering (`HastContent`, so every page component, and the `format: "html"` escape hatch) to `/api/hyle/assets/<uuid>.<ext>` on the host's own origin. That path is answered by the one route file in the quickstart, `app/api/hyle/assets/[file]/route.ts`; nothing else is needed per site, and a strict CSP such as `img-src 'self' data:` (and `media-src` left at `default-src 'self'`) works unchanged. The `Image` slot receives the rewritten `src`, so a `next/image` slot also works; the default is a plain `<img
|
|
329
|
+
hyle stores an image, video or audio reference as `/assets/<uuid>.<ext>`, a path that exists only on hyle's own (authenticated) origin. On a host site it would 404, so the SDK rewrites it while rendering (`HastContent`, so every page component, and the `format: "html"` escape hatch) to `/api/hyle/assets/<uuid>.<ext>` on the host's own origin. That path is answered by the one route file in the quickstart, `app/api/hyle/assets/[file]/route.ts`; nothing else is needed per site, and a strict CSP such as `img-src 'self' data:` (and `media-src` left at `default-src 'self'`) works unchanged. The `Image` slot receives the rewritten `src`, so a `next/image` slot also works; the default is a plain `<img>`, lazy unless it opens the body.
|
|
278
330
|
|
|
279
331
|
How it works: `createAssetRoute` asks hyle for exactly that file (`GET /cp1/read/assets/<file>`, ADR 0015) with the target credential and streams the bytes back. hyle answers only for an asset that a currently published, non-trashed page of this workspace references, so a draft, unpublished or other workspace's asset is a 404 on your site too. Responses carry `Cache-Control: public, max-age=3600, s-maxage=86400, stale-while-revalidate=86400`, hyle's strong `ETag` (revalidation is a 304) and `Accept-Ranges`; `Range` is forwarded, so video and audio seek. After an unpublish a cached copy can still be served for up to the cache window (about a day on a CDN).
|
|
280
332
|
|
|
@@ -282,9 +334,9 @@ Safety: the only input is the `file` segment and it must match `<lowercase uuid>
|
|
|
282
334
|
|
|
283
335
|
The route sits under `/api/hyle/*`, which hyle's Reserved paths must cover (`hyle-sdk-check-routes --print-reserved` always lists `/api/hyle/*`, and so does `--sync`), and the checker prints a note when the build has no `/api/hyle/assets/...` route. If your proxy or middleware matcher intercepts `/api`, exclude `/api/hyle/assets`. Nothing renders `/assets/...` for you outside the SDK's components: a custom renderer of the `hast` tree should map `src` the same way (`/assets/<id>.<ext>` to `/api/hyle/assets/<id>.<ext>`).
|
|
284
336
|
|
|
285
|
-
## Comments and
|
|
337
|
+
## Comments, votes and reactions
|
|
286
338
|
|
|
287
|
-
Readers can comment and like
|
|
339
|
+
Readers can comment under an article, vote comments up or down and react (like, love, insightful, celebrate) to the article and to comments (hyle ADR 0017 and 0021, `docs/cp1-spec.md` section 3.11). It is off unless you turn it on in three places, and nothing on a cached page changes when someone reacts or votes: the section is fetched in the browser, uncached, after the article has rendered.
|
|
288
340
|
|
|
289
341
|
1. **hyle**: switch engagement on for the workspace and register the site's public key (below).
|
|
290
342
|
2. **A key pair.** `npx hyle-sdk-engage-keygen --out .env.engage` makes an Ed25519 pair: the private key goes to a new file (mode 0600, never overwritten) as `HYLE_ENGAGE_SIGNING_KEY=...`, and the PUBLIC key is printed only after that write succeeded, with a warning if git does not ignore the file. `--stdout` is the only mode that prints the private key; with no arguments the tool prints usage and nothing else. Register the public key in hyle. hyle never sees the private key. To rotate, register the new public key; the old one stays valid for 24 hours.
|
|
@@ -307,15 +359,75 @@ export const { GET, POST, PATCH, PUT, DELETE } = createEngagementRoute({
|
|
|
307
359
|
});
|
|
308
360
|
```
|
|
309
361
|
|
|
310
|
-
**Rate-limit this route yourself.** hyle limits per reader and per site, but every anonymous read of `/api/hyle/engage/comments` and every `session` check reaches your server first. The route shares ANONYMOUS listings between visitors for 3 seconds (`cacheTtlMs`, 0 turns it off); a signed-in reader's listing is shared only with that same reader (never across readers), a fallback answer is never kept, bodies over 256 KB are never kept, and the whole share is capped at 8 MB (least recently used out first); a write on that server makes everything stale at once, other servers catch up within the window, and `onRequest(req, { action })` runs before any work so you can answer with your own 429 (`action` is `session`, `comments.list`, `comments.create`, `comments.edit`, `comments.delete`, `reactions.add` or `
|
|
362
|
+
**Rate-limit this route yourself.** hyle limits per reader and per site, but every anonymous read of `/api/hyle/engage/comments` and every `session` check reaches your server first. The route shares ANONYMOUS listings between visitors for 3 seconds (`cacheTtlMs`, 0 turns it off); a signed-in reader's listing is shared only with that same reader (never across readers), a fallback answer is never kept, bodies over 256 KB are never kept, and the whole share is capped at 8 MB (least recently used out first); a write on that server makes everything stale at once, other servers catch up within the window, and `onRequest(req, { action })` runs before any work so you can answer with your own 429 (`action` is `session`, `comments.list`, `comments.create`, `comments.edit`, `comments.delete`, `reactions.add`, `reactions.remove`, `votes.set` or `votes.remove`); put a limit on `/api/hyle/engage` in your middleware or CDN as well. A `400` from hyle (an older hyle refusing `sort=new`) is shared for the same window. The listing share is keyed by path, `sort` and `cursor`, and a cursor is only checked for its alphabet and length (hyle decodes it), so a caller who varies it gets past the 3 s share and spends your site's hyle read allowance (100 reads, then 20 per second, per credential): this limit is what stops that. hyle counts votes in the same bucket as comments (per reader: 5, then 1 every 30 seconds), so a reader who votes quickly is also held back from posting for a while; reactions have their own bucket (30, then 1 every 2 seconds). `getReader` runs once per request and its answer is never kept for the next one, so keep it cheap. The name you return is cleaned as hyle cleans it (control, bidi and invisible characters stripped, spaces collapsed, 80 characters) and a reader whose assertion would pass hyle's 2 KiB cap is treated as signed out.
|
|
311
363
|
|
|
312
364
|
Then pass `engagement` to the page: `hylePage({ ..., engagement: { signInHref: "/sign-in" } })`, or `<ArticlePage engagement={{ signInHref: "/sign-in" }} />`. `engagement.endpoint` defaults to `/api/hyle/engage`. `layout: "docs"` has no comments.
|
|
313
365
|
|
|
314
|
-
What the route does, per request: it matches (method, path) against a fixed allowlist (`session`, `comments`, `comments/<uuid>`, `reactions`), rebuilds the body with only the known keys (a comment is 1 to 4000 characters, a path is a canonical site path), and calls hyle with the target credential. An anonymous read carries the bearer only. A signed-in reader's read also carries a separate Ed25519 read assertion (`scope: "read"`, 30 s, not single use) so hyle can add that reader's own state; a write carries a fresh single-use assertion (30 s) of the reader `getReader` returned; a missing or invalid reader is a bare 401 before hyle is called. The browser's cookies and `Authorization` are never forwarded. Writes must be same-origin (`Sec-Fetch-Site: same-origin` when sent, and an `Origin` equal to the request's host, with the scheme compared too when the proxy sends `X-Forwarded-Proto`), carry the header `x-hyle-engage: 1` and `application/json` (at most 20 KiB), otherwise 403/415/413. The host is taken from `X-Forwarded-Host`, else `Host`: behind a proxy that rewrites `Host` or terminates TLS without forwarding these headers, pass `allowedOrigins: ["https://www.example.com"]`, which replaces the derivation with an exact list (scheme, host and port). Every response is `Cache-Control: no-store`. Failures are mapped to a fixed set of codes with no text from hyle: hyle 404 stays 404 (a disabled workspace, a banned reader and a hidden comment look the same), 429 keeps a clamped `Retry-After`, a 409 is an edit after the 10 minute window, and everything else, including a 401 from hyle (a wrong key or credential, which a visitor must not learn), is a 502. The kill switch is `HYLE_ENGAGE_ENABLED` (and `HYLE_CONTENT_ENABLED`): unset, empty, `1` or `true` leave the route on, and ANY other non-empty value (`0`, `false`, `off`, `no`, a typo) answers 404 everywhere; a missing or malformed configuration also answers 404 and never throws at build time. Your proxy or middleware matcher must let `/api/hyle/engage` through, and the route sits under `/api/hyle/*`, which hyle's Reserved paths already cover (see "Collision checker": `--print-reserved` and `--sync` always list it).
|
|
366
|
+
What the route does, per request: it matches (method, path) against a fixed allowlist (`session`, `comments`, `comments/<uuid>`, `reactions`, `votes`), rebuilds the body with only the known keys (a comment is 1 to 4000 characters, a path is a canonical site path, a reaction `kind` is one of `like`, `love`, `insightful`, `celebrate`, a vote is `{ comment_id, value: 1 | -1 }`), accepts on the listing only `path`, `cursor` and `sort=new` or `sort=top`, each once, and calls hyle with the target credential. An anonymous read carries the bearer only. A signed-in reader's read also carries a separate Ed25519 read assertion (`scope: "read"`, 30 s, not single use) so hyle can add that reader's own state; a write carries a fresh single-use assertion (30 s) of the reader `getReader` returned; a missing or invalid reader is a bare 401 before hyle is called. The browser's cookies and `Authorization` are never forwarded. Writes must be same-origin (`Sec-Fetch-Site: same-origin` when sent, and an `Origin` equal to the request's host, with the scheme compared too when the proxy sends `X-Forwarded-Proto`), carry the header `x-hyle-engage: 1` and `application/json` (at most 20 KiB), otherwise 403/415/413. The host is taken from `X-Forwarded-Host`, else `Host`: behind a proxy that rewrites `Host` or terminates TLS without forwarding these headers, pass `allowedOrigins: ["https://www.example.com"]`, which replaces the derivation with an exact list (scheme, host and port). Every response is `Cache-Control: no-store`. Failures are mapped to a fixed set of codes with no text from hyle: hyle 404 stays 404 (a disabled workspace, a banned reader and a hidden comment look the same), 429 keeps a clamped `Retry-After`, a 409 is an edit after the 10 minute window, and everything else, including a 401 from hyle (a wrong key or credential, which a visitor must not learn), is a 502. The kill switch is `HYLE_ENGAGE_ENABLED` (and `HYLE_CONTENT_ENABLED`): unset, empty, `1` or `true` leave the route on, and ANY other non-empty value (`0`, `false`, `off`, `no`, a typo) answers 404 everywhere; a missing or malformed configuration also answers 404 and never throws at build time. Your proxy or middleware matcher must let `/api/hyle/engage` through, and the route sits under `/api/hyle/*`, which hyle's Reserved paths already cover (see "Collision checker": `--print-reserved` and `--sync` always list it).
|
|
367
|
+
|
|
368
|
+
The component (`Comments`, a client component with no dependency) renders the states of the design kit: signed out, composer, threads to depth 4 (no Reply at depth 4), up and down votes, reactions with a pressed state and optimistic counts, a Newest/Top control, a reader's own pending comment ("Awaiting approval", visible only to them), edited marks, tombstones for removed and deleted comments, a notice for a comment hyle cannot render (`unrenderable`; its author keeps Edit and Delete), empty, loading, load error with Try again, post error that keeps the text, rate limited (the box is disabled, the button is `aria-disabled` and stays focusable), banned, and Load more (20 threads at a time, then hyle's next page). A write that answers 404 is not taken for a ban: the listing and the session are reloaded and a plain error shows; only a second 404 for a still valid session shows the banned message. Comment bodies are the sanitized hast hyle renders; the client sanitizes again with a narrower allowlist (links, emphasis, code, quotes, lists) and builds React elements, never HTML strings. Ctrl or Cmd+Enter posts, Escape closes a reply and returns focus to its button. Styling uses the existing `--hyle-*` variables plus six optional ones: `--hyle-comments-indent`, `--hyle-comments-gap`, `--hyle-comments-avatar-size`, `--hyle-comments-rule`, `--hyle-comments-held` and `--hyle-comments-like-on`. Strings are in en, fr and es (fr and es are unreviewed drafts).
|
|
315
369
|
|
|
316
|
-
The
|
|
370
|
+
The listing is viewer-aware (hyle cp1 spec section 3.11): for a signed-in reader the route sends a separate read assertion (`scope: "read"`, 30 s, not single use) with the `GET`, and hyle adds the reader's own state, so a reload restores their pending comment (`mine_held`), their pressed reactions of all four kinds (`my_reactions`, on the article and each comment) and Edit (only while `can_edit_until` is in the future; Delete stays available on the reader's own comments, as hyle allows it at any time). Edit after a reload starts from Markdown rebuilt from the rendered comment (hyle lists rendered comments, not their source), which can differ from the original in whitespace and escaping. Viewer reads are never shared between readers; a 401 on the read assertion is re-signed once and retried. If the viewer read cannot be served for the reader's own sake (a 401 after one re-sign, which means a wrong or rotated key; a 404, which means no key is registered at hyle yet; or a 429 that hyle marks `Hyle-Throttle: viewer`, the reader's own view bucket) the route answers with the public listing, so a signed-in reader never loses the section. Any other 429, the site-wide read bucket, is passed on with its `Retry-After` and not retried. A reader hyle has never seen, a banned reader and an anonymous visitor all get the public listing (no viewer members). Tombstones say whether a moderator removed the comment or its author deleted it.
|
|
317
371
|
|
|
318
|
-
|
|
372
|
+
**Votes, reactions, order and pages.**
|
|
373
|
+
|
|
374
|
+
- Votes: each visible comment shows its score between an up and a down button (`aria-pressed`); pressing the pressed one again retracts the vote. A reader's own comment shows the score only. A tombstone has no votes.
|
|
375
|
+
- Reactions: the like is always there; another kind appears once somebody used it, and "React" reveals the rest (focus moves into them, Escape returns it to the button). A reader may hold one of each kind.
|
|
376
|
+
- Changes show at once, are announced through a polite live region, and are put back with an error message if hyle refuses them. A signed-out visitor gets links to the sign-in prompt instead of buttons.
|
|
377
|
+
- Order: with votes available the thread shows newest threads first (`sort=new`), with a Top control (`sort=top`, best score first). Replies stay oldest first. Against a hyle without votes the thread stays oldest first with no control.
|
|
378
|
+
- A comment the reader has just posted is on screen at once, even when no loaded page holds it yet; as soon as a listing has it, the listing decides. A new thread goes on top under Newest and at the end under Top.
|
|
379
|
+
- Pages: Load more first reveals what is already loaded, then fetches `next_cursor` with the sort that issued it and merges the page by comment id (a long thread continues on later pages, which repeat its ancestors). Changing the order starts again from the first page, as does a cursor hyle refuses. A refresh after a write refetches every loaded page. The section starts over, session check included, when `path` or `endpoint` changes, and when a write that met an ended session (or followed one) finds another reader signed in (told apart by the `reader.id` of the `session` answer, a digest of the reader's `sub`, so two accounts with one name are two readers). A switch of account that no write runs into is not noticed until then. A page that brings no comment, or hands back the cursor it was asked with, ends the walk.
|
|
380
|
+
- An older hyle sends no score, reaction counts or cursor: the section then shows likes only, with no vote, picker or sort controls.
|
|
381
|
+
|
|
382
|
+
Older hyle versions: one that has votes but refuses `sort=new` with a `400` gets the default (oldest first) listing instead, without an error; the section turns the loaded pages newest first and says that newer comments appear as more are loaded. In each page view `Comments` and `HyleReactions` then each ask for `sort=new` once first (one shared request when they load together); the route shares the refusal like any listing, and each one that does reach hyle spends your site's read allowance. One without `my_reactions` restores pressed likes only, so after a reload a reader's love, insightful or celebrate shows its count without the pressed state (pressing it again adds nothing, a second press removes it). One without cursors for long pages answers `truncated` with no `next_cursor`: nothing after the cut can be loaded and the section says only the first part is shown.
|
|
383
|
+
|
|
384
|
+
An edit can put a visible comment back in the moderation queue, in which case it moves to the reader's pending list.
|
|
385
|
+
|
|
386
|
+
### Load on approach, and cached pages
|
|
387
|
+
|
|
388
|
+
`lazy` makes the island fetch nothing (neither listing nor session) until it is within 600px of the viewport. Compose it in a page you cache statically; there is no server fetch, so the page's caching is untouched:
|
|
389
|
+
|
|
390
|
+
```tsx
|
|
391
|
+
import { Comments, stringsFor } from "@tdacorp/hyle-sdk/react";
|
|
392
|
+
|
|
393
|
+
<div className="hyle hyle-embed">
|
|
394
|
+
<Comments lazy path="/learn/computing-reading-time" endpoint="/api/hyle/engage" signInHref="/sign-in" locale="en" labels={stringsFor("en").comments} />
|
|
395
|
+
</div>
|
|
396
|
+
```
|
|
397
|
+
|
|
398
|
+
`Comments` is a client component and every prop above is a plain string or object, so a server component can render it. Without `initial` the comments are not in the server HTML; use `HyleComments` (below) where search engines must see them.
|
|
399
|
+
|
|
400
|
+
### Article reactions on their own
|
|
401
|
+
|
|
402
|
+
`HyleReactions` puts the article's reactions anywhere, for example under the title:
|
|
403
|
+
|
|
404
|
+
```tsx
|
|
405
|
+
import { HyleReactions } from "@tdacorp/hyle-sdk/react";
|
|
406
|
+
|
|
407
|
+
<HyleReactions path={publication.canonical_path} engagement={{ signInHref: "/sign-in" }} locale="en" />
|
|
408
|
+
```
|
|
409
|
+
|
|
410
|
+
`engagement` is the object `ArticlePage` takes (`endpoint` defaults to `/api/hyle/engage`; without `signInHref` the buttons are inert for signed-out visitors). It renders nothing when engagement is off or the article is unknown. It is its own `.hyle` block, so give it a block-level parent (the stylesheet sizes by container width). hyle has no counts-only endpoint, so it reads the first page of the comment listing (the one `Comments` reads), one request plus the session check, when it mounts, whether or not a `Comments` on the page is `lazy`. If the same page also renders `Comments`, pass that one `articleReactions={false}` so the two never disagree; two islands loading at the same moment share the requests.
|
|
411
|
+
|
|
412
|
+
### Comment notifications
|
|
413
|
+
|
|
414
|
+
Switch comment notifications on for the webhook endpoint in hyle, then give your revalidate route `onCommentEvent`:
|
|
415
|
+
|
|
416
|
+
```ts
|
|
417
|
+
export const { POST } = createRevalidateRoute({
|
|
418
|
+
workspaceId: process.env.HYLE_WORKSPACE_ID,
|
|
419
|
+
secrets: [process.env.HYLE_WEBHOOK_SECRET],
|
|
420
|
+
onCommentEvent: async (event) => {
|
|
421
|
+
// event.type: "comment.held" | "comment.reply" | "comment.approved" | "comment.hidden"
|
|
422
|
+
await queue.add("hyle-comment", event); // yours: enqueue, then send mail from a worker
|
|
423
|
+
},
|
|
424
|
+
});
|
|
425
|
+
```
|
|
426
|
+
|
|
427
|
+
- The hook runs only after the signature, workspace and shape checks, once per delivery id (the signed `event.id`, not the request header) per server instance (dedupe in your queue on `event.id` if you run several).
|
|
428
|
+
- **It is not retried.** A throw, or no answer within 3 seconds, is logged (type and delivery id only) and the delivery is still answered 200. A failing answer would be retried, then dead-lettered, and hyle disables an endpoint after five dead-lettered deliveries in a row, which would also stop your content revalidation. Anything that must not be lost belongs on a durable queue inside the hook. On a serverless host, work left running after the 3 seconds may be frozen.
|
|
429
|
+
- The event carries ids, the article path, a status and `reader_sub` / `parent_reader_sub` (your own reader ids, null after erasure), never comment text. Treat the subs as personal data: do not log them, and delete what you stored when you erase a reader. A reply held for review sends `comment.held`, then `comment.approved` and `comment.reply` once approved. For `comment.reply`, decide who to notify from `parent_reader_sub` and skip a reader replying to themselves.
|
|
430
|
+
- `parseCommentEvent(payload)` is exported for a receiver of your own. It checks the shape only (including that `publication_path` is a site path), so verify the signature first.
|
|
319
431
|
|
|
320
432
|
## Embeds
|
|
321
433
|
|
|
@@ -337,9 +449,9 @@ import { HyleArticle, HyleComments, HyleCommentsFallback, HyleList } from "@tdac
|
|
|
337
449
|
</Suspense>
|
|
338
450
|
```
|
|
339
451
|
|
|
340
|
-
- `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 and
|
|
452
|
+
- `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`.
|
|
341
453
|
- `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.
|
|
342
|
-
- `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
|
|
454
|
+
- `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, vote and react (it needs `createEngagementRoute`, as in "Comments, votes and reactions"; the island, its server HTML included, shows newest threads first when hyle has votes), and it refetches silently on mount with `sort=new` (the seed is the oldest-first first page, so on a thread longer than one page the newest threads arrive with that refetch). 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.
|
|
343
455
|
|
|
344
456
|
SEO rules the embeds follow, and one you must:
|
|
345
457
|
|
|
@@ -348,26 +460,46 @@ SEO rules the embeds follow, and one you must:
|
|
|
348
460
|
- **Canonical:** a page that embeds a full article with `HyleArticle` must set its own canonical URL to the article's URL on the mount (for example `alternates.canonical` in `generateMetadata`), or the two pages compete as duplicates. A list or a comments embed needs nothing. The embeds build no absolute URLs; those belong to the mount (see its documentation).
|
|
349
461
|
- Headings: the default level is 2, and the article body's headings are h2 and below (a body `h1` is demoted), so under your page's `h1` and a section heading of your own, set `headingLevel` to 3.
|
|
350
462
|
- Failure: an embed never calls `notFound()`, never redirects and never throws on a hyle outage. A missing page, a request hyle rejects and an empty section render nothing (or the `list.empty` slot). Any other failure is logged by name and renders `onError(error)` if you gave one, else nothing. A missing `workspaceId`, a bad `baseUrl` or an empty `token` is a configuration error and throws.
|
|
351
|
-
- The token is used only in the server-side request. `HyleComments` sends the target credential and nothing else (no reader assertion, no cookie, no header of the visitor), so every visitor shares one cached listing. The `Comments` island receives the listing, the path, your own `/api/hyle/engage` route and the chrome strings: never the token or hyle's URL.
|
|
463
|
+
- The token is used only in the server-side request. `HyleComments` sends the target credential and nothing else (no reader assertion, no cookie, no header of the visitor), so every visitor shares one cached listing. The server-rendered thread (without `interactive`) is oldest first and has no votes or reactions. The `Comments` island receives the listing, the path, your own `/api/hyle/engage` route and the chrome strings: never the token or hyle's URL.
|
|
352
464
|
|
|
353
465
|
Styling: import `@tdacorp/hyle-sdk/styles.css`. An embed is a `.hyle.hyle-embed` block with no page padding or maximum width, so the host's layout sets its width; `data-layout="grid"` lays the items out as cards (260px minimum columns). The pure markup is also exported as `HyleListView` and `HyleArticleView` from `@tdacorp/hyle-sdk/react` for hosts that fetch for themselves.
|
|
354
466
|
|
|
355
467
|
## Mermaid diagrams
|
|
356
468
|
|
|
357
|
-
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.
|
|
469
|
+
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.16.0`, MIT). No cdnjs, no extra package, no config.
|
|
358
470
|
|
|
359
|
-
- 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.
|
|
360
|
-
- Rendering: a diagram renders when it is within 200 px of the viewport, one at a time
|
|
361
|
-
- Themes:
|
|
362
|
-
-
|
|
471
|
+
- 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. A page loads only the chunks its diagram type needs. `mermaid` itself is 83 MB on disk in `node_modules` (it is not shipped to browsers).
|
|
472
|
+
- Rendering: a small diagram renders when it is within 200 px of the viewport, one at a time; a large one waits for a click (below). The 10 s limit starts after the Mermaid chunk has loaded and covers drawing: past it the code block and the note appear and the next diagram starts, and a result that still arrives is shown. 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. A throw anywhere in a diagram or its viewer shows that figure's source instead of blanking the page.
|
|
473
|
+
- Themes: your CSS decides, however you switch themes. The figure's computed background picks dark or default (`rgb`, `color(srgb)`, `lab`, `lch`, `oklab`, `oklch`); when it is transparent or unreadable, its computed `color-scheme` does (if it names exactly one scheme), then `prefers-color-scheme`. The diagram redraws when that answer changes after any attribute of `<html>` or `<body>` changes (a class, a `data-*` flag, an inline style) or the OS scheme changes. A switch made only on a wrapper deeper in the page is not watched. The drawn figure carries `data-mermaid-theme`. The dark theme gets a darker edge label box so label text passes WCAG AA.
|
|
474
|
+
- 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. Showing a stored render runs no layout, so it is never gated. If the image fails to load, or hyle has no stored render yet, the page renders the diagram client-side as above (a small one with a loader and a reserved height, a large one behind the Draw button).
|
|
475
|
+
- 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.
|
|
363
476
|
- 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`).
|
|
364
|
-
- 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
|
|
477
|
+
- 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, loadingText?, labels? }`) is exported from `./react` if you want to wrap it. It takes nothing but those strings: no token or client ever crosses the boundary.
|
|
478
|
+
|
|
479
|
+
### Large diagrams
|
|
480
|
+
|
|
481
|
+
Mermaid lays a diagram out in one synchronous task. Nothing can interrupt it, no timeout included, so a few hundred edges freeze the tab for seconds, longer on a phone. The SDK therefore does not draw a large diagram until the reader presses Draw diagram.
|
|
482
|
+
|
|
483
|
+
- What counts as large (`isLargeDiagram`, exported from `./react`): more than 100 flowchart link tokens (an upper bound on edges, not a parse, so label text such as `--flag` counts), 6000 characters, 250 statements, 800 words or 25 groups, with lower limits for mindmap, kanban, block, ER, venn, class and state diagrams, whose statements cost more. It errs toward asking. It reads the source in linear time and never calls Mermaid.
|
|
484
|
+
- Before the click: a notice with the button, then the source, clamped behind a Show full source toggle when over 12 lines (all of it stays in the DOM). The server renders these boxes, so nothing moves at hydration. Until then the notice and toggle are `inert`, and CSS shows them, and clamps the source, only under `@media (scripting: enabled)`: a reader without JavaScript and a crawler get the whole source and no notice. A reader whose scripts are blocked or fail sees the inert notice above the scrollable source.
|
|
485
|
+
- After the click: a "Drawing" placeholder is painted first (Mermaid waits two animation frames), then the layout blocks the page. The spinner animates `transform` only, so the compositor keeps turning it while the main thread is busy. Focus moves to Expand if the reader has not moved it elsewhere. A failure keeps the source and offers Draw again. Once drawn, a theme change redraws it without asking.
|
|
486
|
+
- Hard limit: Mermaid's `maxEdges` is 500. A flowchart above it fails with the "could not be rendered" note; a stored render of it still shows.
|
|
487
|
+
- Keep drawing cheap in your own CSS: a draw changes the DOM over a thousand times and forces style recalculation each time, and a `:has()` rule on `html`, `body` or another wide ancestor is re-checked on each one, whether or not its element is on the page. In one measured host a 295-edge flowchart took 16.7 s to draw with such rules in its stylesheet and 0.85 s without them (desktop Chromium). Prefer a class you set yourself, as the viewer does for scroll lock and fullscreen. `styles.css` still has a few `:has()` rules of its own (one on `html` for the docs drawer, one for the docs tree, one for task lists).
|
|
488
|
+
|
|
489
|
+
### Printing
|
|
490
|
+
|
|
491
|
+
- Starting a print draws every small diagram, however far down. A large one nobody asked to draw, and one that failed, prints its whole source.
|
|
492
|
+
- Ctrl+P or Cmd+P while a diagram is still undrawn is held: a note shows, the diagrams draw, then `window.print()` runs (it waits at most 10 s for the download and 10 s for drawing, though a layout in progress cannot be cut short). Escape cancels. File > Print cannot be intercepted: what is not drawn by then prints as source.
|
|
493
|
+
- A diagram drawn in the browser in the dark theme is printed on white with its colours inverted (hue kept). A stored render prints as the image on screen.
|
|
494
|
+
- A host that loads `MermaidDiagram` lazily itself should call `installPrintShortcut()` (it returns the cleanup) and pass the load promise to `holdPrintUntil()`, so a press during the download waits for the diagrams.
|
|
495
|
+
|
|
496
|
+
A host that writes the server markup itself can reuse `isLargeDiagram`, `isClampedSource`, `stripMermaidConfig` and `VIEWER_LABELS_EN` from `./react`; the class names are the ones in `styles.css`.
|
|
365
497
|
|
|
366
498
|
## Diagram viewer
|
|
367
499
|
|
|
368
|
-
Every Mermaid diagram
|
|
500
|
+
Every drawn Mermaid diagram has an Expand button. Click or tap anywhere on the diagram, or press Enter or Space on the button, 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.
|
|
369
501
|
|
|
370
|
-
- Lazy: the viewer is its own chunk, fetched by the first click and never before
|
|
502
|
+
- Lazy: the viewer is its own chunk, fetched by the first click and never before (about 52 KB as published and 15 KB gzipped; about 30 KB raw once a Next production build minifies it). 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.
|
|
371
503
|
- 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.
|
|
372
504
|
- 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.
|
|
373
505
|
- 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.
|
|
@@ -401,13 +533,13 @@ Import `@tdacorp/hyle-sdk/styles.css`. It is the design kit's stylesheet: every
|
|
|
401
533
|
:root { --hyle-accent: #ff8a3d; --hyle-radius: 12px; --hyle-font-heading: "Fraunces", serif; }
|
|
402
534
|
```
|
|
403
535
|
|
|
404
|
-
The 52 variables are listed in the token block at the top of `styles.css`. Layout reacts to the width of the mount (container queries), not the window. Code uses highlight.js token classes (`hljs-*`, mapped to `--hyle-syn-*`). Math arrives as KaTeX HTML from the server: load `katex/dist/katex.min.css` in the host (it brings the fonts and resolves their URLs relative to itself). It is not bundled here because the fonts are about 1 MB of binary assets that would tie this package's version to KaTeX's and double-load in hosts that already use KaTeX.
|
|
536
|
+
The 52 variables are listed in the token block at the top of `styles.css`. Layout reacts to the width of the mount (container queries), not the window. Code uses highlight.js token classes (`hljs-*`, mapped to `--hyle-syn-*`). Math arrives as KaTeX HTML from the server: load `katex/dist/katex.min.css` from KaTeX 0.16 in the host (it brings the fonts and resolves their URLs relative to itself; hyle emits 0.16 markup, and the 0.18 stylesheet renamed classes it needs, so superscript sizes and rules break). It is not bundled here because the fonts are about 1 MB of binary assets that would tie this package's version to KaTeX's and double-load in hosts that already use KaTeX.
|
|
405
537
|
|
|
406
538
|
## Customization
|
|
407
539
|
|
|
408
540
|
`components` replaces how a part is drawn, `slots` fills named places. Both are props of the pages and options of `hylePage`.
|
|
409
541
|
|
|
410
|
-
- 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
|
|
542
|
+
- 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's copy button goes with it), `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]`; `kind` is `note`, `tip`, `important`, `warning` or `caution`). The raw element overrides `a`, `img`, `code`, `pre`, `table`, `blockquote` and `h1` to `h6` also work.
|
|
411
543
|
- 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.
|
|
412
544
|
- Layout: `layout: "docs"` renders articles as `DocsPage`, with no host code. The sidebar is the whole section (hyle sends it when the request carries `nav=tree`, which the layout adds; hidden pages are excluded and their children promoted, one locale): collapsible groups (`<details>`, so it works without JavaScript), the path to the current page open and the page marked `aria-current="page"`. Also a breadcrumb, previous and next links, an on-page contents list with scroll-spy (`aria-current="location"`, an IntersectionObserver, no dependency, no inline script), "Last updated" from the document's `updated_at`, and on a narrow mount (container width under 760px) a Menu button that opens the sidebar as a drawer (the native `popover` attribute: Escape and an outside click close it, focus returns to the button). A section above 2,000 pages in one locale is sent without the tree, and so is an older hyle: the sidebar then shows only the path to the page and its children. Restyle with the `--hyle-*` variables (`--hyle-nav-width`, `--hyle-toc-width`, `--hyle-sticky-top` for a sticky host header) and the slots above. A version badge is only what you put in `docs.version`: hyle has no docs-version data.
|
|
413
545
|
|
|
@@ -417,17 +549,20 @@ Chrome strings exist for en, fr and es (fr and es are unreviewed drafts). The pa
|
|
|
417
549
|
|
|
418
550
|
- 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).
|
|
419
551
|
- The path is sent as a query parameter (encoded once); catch-all segments are decoded and refused if they contain `/`, `\`, control characters, `.` or `..`.
|
|
420
|
-
- 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
|
|
421
|
-
- Mermaid renders into your page, so: the source comes only from hyle content, passes the exact-template check and
|
|
422
|
-
- 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 (`
|
|
423
|
-
- The
|
|
424
|
-
-
|
|
552
|
+
- 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), `kbd` with no property, an image `title` as a string only, a link's `data-embed` only as `youtube` and only on exactly `https://www.youtube.com/watch?v=<11 characters>`, `figure` and `figcaption` never taken from the input (the SDK builds them for image paragraphs), 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.
|
|
553
|
+
- 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` 500. The SDK strips every `%%{ ... }%%` directive (multi-line, unterminated and `init`, `initialize`, `config`, `wrap` forms) and every leading YAML frontmatter block (indented ones too, which Mermaid 11.16 reads; a source still changing after 16 rounds is dropped whole) 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; the browser check serves such payloads against a loopback canary server and expects no request, and a unit test asks Mermaid itself that no config survives the stripping. 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'`.
|
|
554
|
+
- 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 (`hyleMermaid-N`) to another SDK-generated token (`hyleViewer-N`), which also replaces the render-id prefix on node ids, 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`).
|
|
555
|
+
- The article islands receive ids and chrome strings only (the player a video id the server validated). The copy button reads the block's text on click and writes it to the clipboard; none of them writes HTML. The YouTube frame is another origin, which is why it may have `allow-scripts` with `allow-same-origin`; its source is built from the 11 character id alone.
|
|
556
|
+
- 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, votes and reactions"). 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.
|
|
557
|
+
- 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. `onCommentEvent` is the exception: its failures are not retried (see "Comment notifications").
|
|
425
558
|
|
|
426
559
|
## Not included
|
|
427
560
|
|
|
428
|
-
Docs versions
|
|
561
|
+
Docs versions and "closest matches" on the 404 page: hyle does not provide that data. Image URLs in content such as `/assets/<id>` are no longer passed through unchanged: see "Media".
|
|
429
562
|
|
|
430
|
-
|
|
563
|
+
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.
|
|
564
|
+
|
|
565
|
+
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:
|
|
431
566
|
|
|
432
567
|
```ts
|
|
433
568
|
import { hyleMetadata, type PageProps } from "@tdacorp/hyle-sdk/next";
|
|
@@ -442,3 +577,7 @@ export async function generateMetadata(props: PageProps) {
|
|
|
442
577
|
## Contract
|
|
443
578
|
|
|
444
579
|
Types in `src/types.ts` mirror `packages/cp1-read/src/resolve.ts`. `src/__tests__/contract.test.ts` pins them against fixture JSON for every result kind, so a server-side shape change fails a test here.
|
|
580
|
+
|
|
581
|
+
## Identity machine tokens (`auth` instead of `token`)
|
|
582
|
+
|
|
583
|
+
`createHyleClient`, `syncHostReserved` and `cachedResolver` accept `auth` (a `HyleAuth`) instead of `token`, for a service account of identity (hyle ADR 0027, needs `HYLE_MACHINE_IDENTITY_TOKENS=dual` or `identity` on hyle). The hook is called for every request with `{ method, url }` and returns the headers to send, so the DPoP proof matches that request; with the identity SDK: `auth: (req) => serviceClient.headersFor(token, req)`. `workspaceId` is required and sent as `CP-Workspace`; the token needs `hyle.document.read` on it (`hyle.workspace.manage` for `syncHostReserved`). Page, asset and embed helpers still take `token`.
|
package/dist/check-routes-bin.js
CHANGED
|
@@ -27,6 +27,18 @@ var Cp1ClientError = class extends Error {
|
|
|
27
27
|
};
|
|
28
28
|
|
|
29
29
|
// src/client.ts
|
|
30
|
+
var RENDERER_VERSION = "4";
|
|
31
|
+
function applyCredential(headers, credential, method, url) {
|
|
32
|
+
if (!credential.auth) {
|
|
33
|
+
headers.set("authorization", `Bearer ${credential.token}`);
|
|
34
|
+
return void 0;
|
|
35
|
+
}
|
|
36
|
+
const { workspaceId } = credential;
|
|
37
|
+
return credential.auth({ method, url }).then((extra) => {
|
|
38
|
+
for (const [name, value] of Object.entries(extra)) headers.set(name, value);
|
|
39
|
+
headers.set("cp-workspace", workspaceId);
|
|
40
|
+
});
|
|
41
|
+
}
|
|
30
42
|
var DEFAULT_TIMEOUT_MS = 1e4;
|
|
31
43
|
var DEFAULT_MAX_RESPONSE_BYTES = 5 * 1024 * 1024;
|
|
32
44
|
var LOOPBACK = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "[::1]"]);
|
|
@@ -68,14 +80,16 @@ function checkBaseUrl(baseUrl, allowInsecureHttp) {
|
|
|
68
80
|
}
|
|
69
81
|
function createHyleClient(options) {
|
|
70
82
|
checkBaseUrl(options.baseUrl, options.allowInsecureHttp);
|
|
71
|
-
if (!options.token) throw new TypeError("token is required");
|
|
83
|
+
if (!options.auth && !options.token) throw new TypeError("token is required");
|
|
72
84
|
const base = options.baseUrl.replace(/\/+$/, "");
|
|
73
85
|
const fetchImpl = options.fetch ?? fetch;
|
|
74
86
|
async function get(pathname, query, init) {
|
|
75
87
|
const url = new URL(`${base}${pathname}`);
|
|
76
88
|
url.search = query.toString();
|
|
77
89
|
const headers = new Headers(init?.headers);
|
|
78
|
-
headers.set("
|
|
90
|
+
headers.set("cp-renderer-version", RENDERER_VERSION);
|
|
91
|
+
const applied = applyCredential(headers, options, "GET", url.toString());
|
|
92
|
+
if (applied) await applied;
|
|
79
93
|
const timeout = AbortSignal.timeout(options.timeoutMs ?? DEFAULT_TIMEOUT_MS);
|
|
80
94
|
const signal = init?.signal ? AbortSignal.any([init.signal, timeout]) : timeout;
|
|
81
95
|
const res = await fetchImpl(url.toString(), { ...init, method: "GET", headers, redirect: "error", signal });
|
|
@@ -115,16 +129,28 @@ function createHyleClient(options) {
|
|
|
115
129
|
if (data?.cp === 1 && data.kind === "mounts" && isMounts(data)) return data;
|
|
116
130
|
throw failure(reply);
|
|
117
131
|
}
|
|
132
|
+
async function pushPosts(opts) {
|
|
133
|
+
if (!/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/.test(opts.section)) throw new TypeError("section must be a section slug");
|
|
134
|
+
const query = new URLSearchParams();
|
|
135
|
+
if (opts.cursor !== void 0) query.set("cursor", opts.cursor);
|
|
136
|
+
const reply = await get(`/cp1/read/sections/${opts.section}/posts`, query, opts.init);
|
|
137
|
+
const data = reply.parsed?.data;
|
|
138
|
+
if (data?.cp === 1 && data.kind === "push_posts" && Array.isArray(data.posts) && typeof data.complete === "boolean") return data;
|
|
139
|
+
throw failure(reply);
|
|
140
|
+
}
|
|
118
141
|
async function asset(file, opts = {}) {
|
|
119
142
|
if (!ASSET_FILE.test(file)) throw new TypeError("asset file must be <uuid>[.<ext>]");
|
|
120
|
-
const
|
|
143
|
+
const url = `${base}/cp1/read/assets/${file}`;
|
|
144
|
+
const headers = new Headers();
|
|
145
|
+
const applied = applyCredential(headers, options, "GET", url);
|
|
146
|
+
if (applied) await applied;
|
|
121
147
|
for (const name of ["range", "if-range", "if-none-match"]) {
|
|
122
148
|
const value = opts.headers?.[name];
|
|
123
149
|
if (value) headers.set(name, value);
|
|
124
150
|
}
|
|
125
|
-
return fetchImpl(
|
|
151
|
+
return fetchImpl(url, { method: "GET", headers, redirect: "error", signal: AbortSignal.timeout(opts.timeoutMs ?? options.timeoutMs ?? DEFAULT_TIMEOUT_MS) });
|
|
126
152
|
}
|
|
127
|
-
return { resolve, mounts, asset };
|
|
153
|
+
return { resolve, mounts, pushPosts, asset };
|
|
128
154
|
}
|
|
129
155
|
|
|
130
156
|
// src/host-sync.ts
|
|
@@ -134,21 +160,20 @@ var MAX_RESPONSE_BYTES = 1024 * 1024;
|
|
|
134
160
|
var PATH = "/cp1/control/workspace/host-reserved-paths";
|
|
135
161
|
async function syncHostReserved(input) {
|
|
136
162
|
checkBaseUrl(input.baseUrl, input.allowInsecureHttp);
|
|
137
|
-
if (!input.token.startsWith(CONTROL_TOKEN_PREFIX)) {
|
|
163
|
+
if (input.token !== void 0 && !input.token.startsWith(CONTROL_TOKEN_PREFIX)) {
|
|
138
164
|
throw new TypeError("syncing needs a control credential (hyle_tc_...); a target token is read-only and cannot write");
|
|
139
165
|
}
|
|
140
166
|
const fetchImpl = input.fetch ?? fetch;
|
|
141
|
-
const
|
|
167
|
+
const url = `${input.baseUrl.replace(/\/+$/, "")}${PATH}`;
|
|
168
|
+
const headers = new Headers({ "content-type": "application/json", "idempotency-key": `sync-${crypto.randomUUID()}` });
|
|
169
|
+
await applyCredential(headers, input.auth ? { auth: input.auth, workspaceId: input.workspaceId } : { token: input.token }, "PUT", url);
|
|
170
|
+
headers.set("cp-workspace", input.workspaceId);
|
|
171
|
+
const res = await fetchImpl(url, {
|
|
142
172
|
method: "PUT",
|
|
143
173
|
// redirect "error": the bearer token must never follow a redirect to another host.
|
|
144
174
|
redirect: "error",
|
|
145
175
|
signal: AbortSignal.timeout(input.timeoutMs ?? DEFAULT_TIMEOUT_MS2),
|
|
146
|
-
headers
|
|
147
|
-
authorization: `Bearer ${input.token}`,
|
|
148
|
-
"content-type": "application/json",
|
|
149
|
-
"cp-workspace": input.workspaceId,
|
|
150
|
-
"idempotency-key": `sync-${crypto.randomUUID()}`
|
|
151
|
-
},
|
|
176
|
+
headers,
|
|
152
177
|
body: JSON.stringify({ paths: input.paths, host: input.host, build_id: input.buildId })
|
|
153
178
|
});
|
|
154
179
|
const text = await readCapped(res, MAX_RESPONSE_BYTES);
|
|
@@ -530,16 +555,18 @@ async function runCli(argv, io) {
|
|
|
530
555
|
io.err("CANNOT RUN: set HYLE_TARGET_BASE_URL (or --base-url) and HYLE_TARGET_TOKEN");
|
|
531
556
|
return CANNOT_RUN;
|
|
532
557
|
}
|
|
533
|
-
const hylePaths =
|
|
534
|
-
for (const { prefix } of mounts.mounts) {
|
|
535
|
-
const
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
558
|
+
const hylePaths = /* @__PURE__ */ new Set();
|
|
559
|
+
for (const { prefix, locales } of mounts.mounts) {
|
|
560
|
+
for (const locale2 of locales?.length ? locales : [void 0]) {
|
|
561
|
+
const listing = await listPublicationPaths({ client, basePath: normalizeBasePath(prefix), maxPages: 100, ...locale2 !== void 0 ? { locale: locale2 } : {} });
|
|
562
|
+
if (!listing.complete) {
|
|
563
|
+
io.err(`CANNOT RUN: hyle's pages under ${printable(prefix)} could not be listed completely, so a collision could be missed`);
|
|
564
|
+
return CANNOT_RUN;
|
|
565
|
+
}
|
|
566
|
+
listing.paths.forEach((p) => hylePaths.add(p.path));
|
|
539
567
|
}
|
|
540
|
-
hylePaths.push(...listing.paths.map((p) => p.path));
|
|
541
568
|
}
|
|
542
|
-
const report = checkRoutes({ hostRoutes, mounts: mounts.mounts.map((m) => m.prefix), hylePaths, hyleParam, ...locale ? { locale } : {} });
|
|
569
|
+
const report = checkRoutes({ hostRoutes, mounts: mounts.mounts.map((m) => m.prefix), hylePaths: [...hylePaths], hyleParam, ...locale ? { locale } : {} });
|
|
543
570
|
io.out(args.has("--json") ? JSON.stringify(sync ? { ...report, sync } : report, null, 2) : formatReport(report));
|
|
544
571
|
if (!report.ok) return 1;
|
|
545
572
|
return sync?.status === "failed" && strict ? SYNC_FAILED : 0;
|