@tdacorp/hyle-sdk 0.3.0 → 0.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/README.md +135 -5
  2. package/bin/hyle-sdk-check-routes.mjs +3 -0
  3. package/dist/check-routes-bin.js +537 -0
  4. package/dist/chunk-67IOIAVW.js +35 -0
  5. package/dist/chunk-BUJFMR3M.js +38 -0
  6. package/dist/chunk-EBNIKRQH.js +536 -0
  7. package/dist/{chunk-EARQBSMF.js → chunk-LGW2KP4X.js} +109 -5
  8. package/dist/{chunk-7VCMJUPC.js → chunk-N4QYPO7S.js} +1 -1
  9. package/dist/diagram-viewer-DYX6R63Y.js +1132 -0
  10. package/dist/index.cjs +279 -23
  11. package/dist/index.d.cts +147 -3
  12. package/dist/index.d.ts +147 -3
  13. package/dist/index.js +18 -1
  14. package/dist/mermaid-diagram.cjs +1267 -16
  15. package/dist/mermaid-diagram.d.cts +39 -1
  16. package/dist/mermaid-diagram.d.ts +39 -1
  17. package/dist/mermaid-diagram.js +35 -5
  18. package/dist/next.cjs +385 -30
  19. package/dist/next.d.cts +93 -5
  20. package/dist/next.d.ts +93 -5
  21. package/dist/next.js +210 -5
  22. package/dist/react.cjs +118 -5
  23. package/dist/react.d.cts +44 -4
  24. package/dist/react.d.ts +44 -4
  25. package/dist/react.js +2 -1
  26. package/dist/{resolve-fMx2W8RR.d.ts → resolve-1rQntRBh.d.ts} +1 -1
  27. package/dist/{resolve-B_p0p4Zn.d.cts → resolve-36-Ng1H0.d.cts} +1 -1
  28. package/dist/styles.css +76 -0
  29. package/dist/{types-CBvLhUPr.d.ts → types-BoyBWF2F.d.ts} +1 -1
  30. package/dist/{types-DjXf6iPo.d.cts → types-CwBCPh6K.d.cts} +20 -1
  31. package/dist/{types-DjXf6iPo.d.ts → types-CwBCPh6K.d.ts} +20 -1
  32. package/dist/{types-D0qoLh4E.d.cts → types-DnPzhrFx.d.cts} +1 -1
  33. package/dist/use-cache.cjs +55 -23
  34. package/dist/use-cache.d.cts +2 -2
  35. package/dist/use-cache.d.ts +2 -2
  36. package/dist/use-cache.js +3 -2
  37. package/package.json +5 -1
  38. package/dist/chunk-HFUJRNFP.js +0 -290
package/dist/next.d.ts CHANGED
@@ -1,10 +1,10 @@
1
1
  import { ReactElement } from 'react';
2
- import { H as HyleComponents, a as HyleSlots } from './types-CBvLhUPr.js';
3
- import { F as FetchResolverOptions, H as HyleResolver } from './resolve-fMx2W8RR.js';
4
- export { f as fetchResolver, w as workspaceTags } from './resolve-fMx2W8RR.js';
2
+ import { H as HyleComponents, a as HyleSlots } from './types-BoyBWF2F.js';
3
+ import { F as FetchResolverOptions, H as HyleResolver } from './resolve-1rQntRBh.js';
4
+ export { f as fetchResolver, w as workspaceTags } from './resolve-1rQntRBh.js';
5
5
  import { MetadataRoute, Metadata } from 'next';
6
6
  import { a as RevalidationCallbackRoute } from './revalidation-callback-D7Ms_Puz.js';
7
- import './types-DjXf6iPo.js';
7
+ import './types-CwBCPh6K.js';
8
8
 
9
9
  type RouteParams = Record<string, string | string[] | undefined>;
10
10
  interface CommonOptions {
@@ -139,4 +139,92 @@ interface RevalidateRouteOptions {
139
139
  */
140
140
  declare function createRevalidateRoute(options: RevalidateRouteOptions): RevalidationCallbackRoute;
141
141
 
142
- export { FetchResolverOptions, type HyleNextOptions, HyleResolver, type HyleSitemapOptions, type PageProps, type RevalidateRouteOptions, type RouteParams, createRevalidateRoute, hyleMetadata, hylePage, hyleSitemap };
142
+ /**
143
+ * One workspace of a root catch-all: the options of `hylePage` without `basePath` (the mount prefix comes from hyle's mounts)
144
+ * and without `resolver` (the mounts are read through Next's fetch cache, so `baseUrl`, `token` and `workspaceId` are required).
145
+ * `revalidate` (default 300) also bounds the mounts fetch.
146
+ */
147
+ type HyleRootConfig = Omit<Extract<HyleNextOptions, {
148
+ resolver?: undefined;
149
+ }>, "basePath">;
150
+ type Configs = HyleRootConfig | readonly HyleRootConfig[];
151
+ /** How long a mounts copy that could not be refreshed may still be used. Past this a transient failure is rethrown. */
152
+ declare const MOUNTS_MAX_STALE_MS: number;
153
+ /**
154
+ * An async server component for the REQUIRED catch-all `app/.../[...hyle]/page.tsx`: `export default hyleRootPage({ ... })`,
155
+ * or an array of configs when one site serves several workspaces. It hands hyle every URL no other route of the host matched,
156
+ * but only the ones under a mount hyle reports (`GET /cp1/read/mounts`):
157
+ *
158
+ * - no mount matches (segment-boundary, case-sensitive, longest prefix wins) or the path is one of the workspace's `reserved`
159
+ * entries: `notFound()` with ZERO resolve calls, so junk URLs and bot probes never reach hyle;
160
+ * - otherwise the request is served by `hylePage` with `basePath` = the matched prefix (same locale, redirect and error rules).
161
+ *
162
+ * Failure of the mounts fetch: a 4xx or the kill switch means nothing is served (404). A transient failure (network, timeout,
163
+ * 5xx, 429, malformed body) uses the last mounts read successfully for up to 15 minutes, so a hyle outage keeps
164
+ * unmatched URLs a plain 404 and mounted pages on their last good render; with no such copy (a cold server) it is RETHROWN,
165
+ * because the URL might be a mounted page: Next keeps the last good ISR page, or a first render is an uncached 500. A host
166
+ * route never depends on this at all: Next matches it first. With a ROOT mount and no copy, every unmatched URL errors
167
+ * until hyle is back.
168
+ *
169
+ * The folder must be a required catch-all: an optional `[[...hyle]]` at the app root conflicts with a sibling `page.tsx` (the
170
+ * host's home page) at the same level.
171
+ */
172
+ declare function hyleRootPage(options: Configs): (props: PageProps) => Promise<ReactElement>;
173
+ /** `export const generateMetadata = hyleRootMetadata({ ... })` with the same options as `hyleRootPage`: no metadata for a path no mount serves. */
174
+ declare function hyleRootMetadata(options: Configs): (props: PageProps) => Promise<Metadata>;
175
+ interface HyleRootSitemapOptions {
176
+ /** The site's public origin, for example "https://tdacorp.in": https, no path, query or credentials. */
177
+ readonly origin: string;
178
+ /** See `hyleSitemap`. Applies to every mount. */
179
+ readonly onIncomplete?: "partial" | "throw";
180
+ }
181
+ /**
182
+ * Sitemap entries for every mount of every workspace, to spread into `app/sitemap.ts`: `[...hostEntries, ...(await hyleRootSitemap(configs, { origin }))]`.
183
+ * Each mount is listed with `hyleSitemap` (so `sections`, `locale`, `localePrefix` and `onIncomplete` behave as there). The mounts
184
+ * themselves must be readable: a failure with no last good copy throws, so a build never ships a sitemap without hyle's pages.
185
+ */
186
+ declare function hyleRootSitemap(options: Configs, sitemap: HyleRootSitemapOptions): Promise<MetadataRoute.Sitemap>;
187
+
188
+ interface AssetRouteOptions {
189
+ /** hyle's origin (HYLE_TARGET_BASE_URL). */
190
+ readonly baseUrl: string | undefined;
191
+ /** This workspace's target credential (HYLE_TARGET_TOKEN). Used only server-side; it never reaches the browser. */
192
+ readonly token: string | undefined;
193
+ /** Environment to read the site switch from. Default process.env. */
194
+ readonly env?: Readonly<Record<string, string | undefined>>;
195
+ /** Refuse (502) an asset larger than this many bytes. Default 16 MiB; hyle's own upload limit is 4 MiB. */
196
+ readonly maxBytes?: number;
197
+ /** Abort the upstream request, body included, after this many milliseconds. Default 30000. */
198
+ readonly timeoutMs?: number;
199
+ /** Injectable for tests. */
200
+ readonly fetch?: typeof fetch;
201
+ }
202
+ interface AssetRoute {
203
+ GET(req: Request, ctx: {
204
+ params: Promise<{
205
+ file?: string;
206
+ }>;
207
+ }): Promise<Response>;
208
+ HEAD(req: Request, ctx: {
209
+ params: Promise<{
210
+ file?: string;
211
+ }>;
212
+ }): Promise<Response>;
213
+ }
214
+ /**
215
+ * `export const { GET, HEAD } = createAssetRoute({ ... })` in `app/api/hyle/assets/[file]/route.ts` (ADR 0015).
216
+ *
217
+ * The SDK rewrites hyle's `/assets/<uuid>.<ext>` in rendered content to `/api/hyle/assets/<uuid>.<ext>`; this route answers it by
218
+ * asking hyle for exactly that file with the target credential and streaming the bytes back, same-origin, so a strict
219
+ * `img-src 'self'` (and `media-src 'self'`) CSP needs no change. hyle serves only assets that a currently published page of this
220
+ * workspace references, so an unpublished or other workspace's asset is a 404 here too.
221
+ *
222
+ * Safety: the only input is the `file` segment, matched against `<uuid>[.<ext>]` before anything is sent, so this is not an open
223
+ * proxy. The browser's cookies and authorization header are never forwarded; only `Range`, `If-Range` and `If-None-Match` are.
224
+ * The response headers are built here (no upstream header is copied blindly), the content type must be on the asset allowlist,
225
+ * the body is size-capped and time-bounded, and every failure is an empty 404 or 502 that says nothing about hyle.
226
+ * The site switch `HYLE_CONTENT_ENABLED=0`/`false`, or missing configuration, answers 404.
227
+ */
228
+ declare function createAssetRoute(options: AssetRouteOptions): AssetRoute;
229
+
230
+ export { type AssetRoute, type AssetRouteOptions, FetchResolverOptions, type HyleNextOptions, HyleResolver, type HyleRootConfig, type HyleRootSitemapOptions, type HyleSitemapOptions, MOUNTS_MAX_STALE_MS, type PageProps, type RevalidateRouteOptions, type RouteParams, createAssetRoute, createRevalidateRoute, hyleMetadata, hylePage, hyleRootMetadata, hyleRootPage, hyleRootSitemap, hyleSitemap };
package/dist/next.js CHANGED
@@ -2,16 +2,22 @@ import {
2
2
  ArticlePage,
3
3
  DocsPage,
4
4
  ListPage
5
- } from "./chunk-EARQBSMF.js";
5
+ } from "./chunk-LGW2KP4X.js";
6
6
  import {
7
+ DEFAULT_REVALIDATE,
7
8
  fetchResolver,
8
9
  workspaceTags
9
- } from "./chunk-7VCMJUPC.js";
10
+ } from "./chunk-N4QYPO7S.js";
10
11
  import {
11
12
  Cp1ClientError,
13
+ createHyleClient,
12
14
  createRevalidationCallbackRoute,
13
15
  listPublicationPaths
14
- } from "./chunk-HFUJRNFP.js";
16
+ } from "./chunk-EBNIKRQH.js";
17
+ import {
18
+ ASSET_CONTENT_TYPES,
19
+ ASSET_FILE
20
+ } from "./chunk-67IOIAVW.js";
15
21
 
16
22
  // src/next/page.tsx
17
23
  import { notFound, permanentRedirect, redirect } from "next/navigation";
@@ -21,9 +27,10 @@ import { unstable_rethrow } from "next/navigation";
21
27
 
22
28
  // src/next/paths.ts
23
29
  function normalizeBasePath(basePath) {
24
- const value = (basePath ?? "").replace(/\/+$/, "");
30
+ const raw = basePath ?? "";
31
+ const value = raw === "/" ? "" : raw.replace(/\/$/, "");
25
32
  if (value === "") return "";
26
- if (!/^\/[^\s?#\\]+$/.test(value) || value.includes("//")) throw new TypeError(`basePath must look like "/learn", got "${basePath}"`);
33
+ if (!/^\/[^\s?#\\]+$/.test(value) || raw.includes("//")) throw new TypeError(`basePath must look like "/learn", got "${basePath}"`);
27
34
  return value;
28
35
  }
29
36
  var MAX_PATH_LENGTH = 1024;
@@ -204,11 +211,209 @@ function createRevalidateRoute(options) {
204
211
  }
205
212
  };
206
213
  }
214
+
215
+ // src/next/root.ts
216
+ import { notFound as notFound2 } from "next/navigation";
217
+
218
+ // src/next/mount-match.ts
219
+ function activeMounts(mounts) {
220
+ const out = [];
221
+ for (const { prefix, default_section } of mounts) {
222
+ try {
223
+ const normalized = normalizeBasePath(prefix);
224
+ out.push({ prefix: normalized, defaultSection: default_section, depth: normalized === "" ? 0 : normalized.split("/").length - 1 });
225
+ } catch (error) {
226
+ console.error(`hyle: ignoring a mount with an invalid prefix (${error instanceof Error ? error.name : "Error"})`);
227
+ }
228
+ }
229
+ return out;
230
+ }
231
+ var prefixMatches = (prefix, path) => prefix === "" || path === prefix || path.startsWith(`${prefix}/`);
232
+ function isReserved(path, reserved) {
233
+ return reserved.some((entry) => entry.endsWith("/*") ? prefixMatches(entry.slice(0, -2), path) : entry === path);
234
+ }
235
+
236
+ // src/next/root.ts
237
+ var MOUNTS_MAX_STALE_MS = 15 * 60 * 1e3;
238
+ var SECTION_SLUG = /^[A-Za-z0-9][A-Za-z0-9_-]*$/;
239
+ var NONE = { mounts: [], reserved: [] };
240
+ var lastKnownGood = /* @__PURE__ */ new Map();
241
+ function mountsLoader(config) {
242
+ if (!config.workspaceId) throw new TypeError("hyleRootPage: `workspaceId` is required for the fetch cache");
243
+ const client = createHyleClient({ baseUrl: config.baseUrl, token: config.token });
244
+ const init = { next: { revalidate: config.revalidate ?? DEFAULT_REVALIDATE, tags: workspaceTags(config.workspaceId).slice(0, 1) } };
245
+ const key = `${new URL(config.baseUrl).origin}|${config.workspaceId}`;
246
+ return async function load() {
247
+ try {
248
+ const result = await client.mounts({ init });
249
+ if (result.kind !== "mounts") {
250
+ lastKnownGood.delete(key);
251
+ return NONE;
252
+ }
253
+ const loaded = { mounts: activeMounts(result.mounts), reserved: result.reserved };
254
+ lastKnownGood.set(key, { loaded, at: Date.now() });
255
+ return loaded;
256
+ } catch (error) {
257
+ if (isRejectedRequest(error)) {
258
+ lastKnownGood.delete(key);
259
+ return NONE;
260
+ }
261
+ if (error instanceof Cp1ClientError && (error.status === 401 || error.status === 403)) {
262
+ lastKnownGood.delete(key);
263
+ throw error;
264
+ }
265
+ const kept = lastKnownGood.get(key);
266
+ if (kept && Date.now() - kept.at <= MOUNTS_MAX_STALE_MS) return kept.loaded;
267
+ throw error;
268
+ }
269
+ };
270
+ }
271
+ var asArray = (options) => Array.isArray(options) ? options : [options];
272
+ function setup(options) {
273
+ const configs = asArray(options);
274
+ if (configs.length === 0) throw new TypeError("hyleRootPage: pass at least one workspace config");
275
+ const param = configs[0].param ?? "hyle";
276
+ if (configs.some((c) => (c.param ?? "hyle") !== param)) throw new TypeError("hyleRootPage: every config must use the same `param`");
277
+ return { configs, param, loaders: configs.map(mountsLoader) };
278
+ }
279
+ function createRouter(options, make) {
280
+ const { configs, param, loaders } = setup(options);
281
+ const handlers = /* @__PURE__ */ new Map();
282
+ return async function route(params) {
283
+ const raw = params[param];
284
+ const segments = typeof raw === "string" ? [raw] : raw;
285
+ const path = sitePathFrom("", segments);
286
+ if (path === void 0 || path === "/" || !segments) return void 0;
287
+ const loaded = await Promise.all(loaders.map((load) => load()));
288
+ let best;
289
+ loaded.forEach(({ mounts, reserved }, index2) => {
290
+ if (isReserved(path, reserved)) return;
291
+ for (const mount2 of mounts) if (prefixMatches(mount2.prefix, path) && (!best || mount2.depth > best.mount.depth)) best = { index: index2, mount: mount2 };
292
+ });
293
+ if (!best) return void 0;
294
+ const { index, mount } = best;
295
+ const config = configs[index];
296
+ const id = `${index}|${mount.prefix}|${mount.defaultSection}`;
297
+ let handler = handlers.get(id);
298
+ if (!handler) {
299
+ const sections = [...config.sections ?? [], ...SECTION_SLUG.test(mount.defaultSection) ? [mount.defaultSection] : []];
300
+ handler = make({ ...config, basePath: mount.prefix, sections });
301
+ handlers.set(id, handler);
302
+ }
303
+ return { handler, params: { ...params, [param]: segments.slice(mount.depth) } };
304
+ };
305
+ }
306
+ function hyleRootPage(options) {
307
+ const route = createRouter(options, hylePage);
308
+ return async function HyleRootPage({ params, searchParams }) {
309
+ const hit = await route(await params ?? {});
310
+ if (!hit) notFound2();
311
+ return hit.handler({ params: Promise.resolve(hit.params), ...searchParams ? { searchParams } : {} });
312
+ };
313
+ }
314
+ function hyleRootMetadata(options) {
315
+ const route = createRouter(options, hyleMetadata);
316
+ return async function generateMetadata({ params }) {
317
+ const hit = await route(await params ?? {});
318
+ return hit ? hit.handler({ params: Promise.resolve(hit.params) }) : {};
319
+ };
320
+ }
321
+ async function hyleRootSitemap(options, sitemap) {
322
+ const { configs, loaders } = setup(options);
323
+ const entries = /* @__PURE__ */ new Map();
324
+ for (const [index, load] of loaders.entries()) {
325
+ const config = configs[index];
326
+ for (const mount of (await load()).mounts) {
327
+ const sections = [...config.sections ?? [], ...SECTION_SLUG.test(mount.defaultSection) ? [mount.defaultSection] : []];
328
+ for (const entry of await hyleSitemap({ ...config, basePath: mount.prefix, sections, ...sitemap })) entries.set(entry.url, entry);
329
+ }
330
+ }
331
+ return [...entries.values()];
332
+ }
333
+
334
+ // src/next/asset.ts
335
+ var DEFAULT_MAX_BYTES = 16 * 1024 * 1024;
336
+ var DEFAULT_TIMEOUT_MS = 3e4;
337
+ var CACHE_CONTROL = "public, max-age=3600, s-maxage=86400, stale-while-revalidate=86400";
338
+ var PARTIAL_CACHE_CONTROL = "no-store";
339
+ var SAFE_HEADERS = { "X-Content-Type-Options": "nosniff", "Content-Security-Policy": "default-src 'none'; style-src 'unsafe-inline'; sandbox" };
340
+ var empty = (status, headers = {}) => new Response(null, { status, headers: { "Cache-Control": "no-store", ...headers } });
341
+ var isSwitchedOff2 = (value) => ["0", "false"].includes(value?.trim().toLowerCase() ?? "");
342
+ function capped(body, max) {
343
+ let seen = 0;
344
+ return body.pipeThrough(
345
+ new TransformStream({
346
+ transform(chunk, controller) {
347
+ seen += chunk.byteLength;
348
+ if (seen > max) return controller.error(new Error("asset too large"));
349
+ controller.enqueue(chunk);
350
+ }
351
+ })
352
+ );
353
+ }
354
+ function createAssetRoute(options) {
355
+ let client;
356
+ const maxBytes = options.maxBytes ?? DEFAULT_MAX_BYTES;
357
+ async function serve(req, ctx, head) {
358
+ if (isSwitchedOff2((options.env ?? process.env).HYLE_CONTENT_ENABLED)) return empty(404);
359
+ const file = (await ctx.params).file;
360
+ if (typeof file !== "string" || !ASSET_FILE.test(file)) return empty(404);
361
+ try {
362
+ client ??= createHyleClient({ baseUrl: options.baseUrl?.trim() ?? "", token: options.token?.trim() ?? "", ...options.fetch ? { fetch: options.fetch } : {} });
363
+ } catch {
364
+ return empty(404);
365
+ }
366
+ let upstream;
367
+ try {
368
+ upstream = await client.asset(file, {
369
+ timeoutMs: options.timeoutMs ?? DEFAULT_TIMEOUT_MS,
370
+ headers: { range: req.headers.get("range"), "if-range": req.headers.get("if-range"), "if-none-match": req.headers.get("if-none-match") }
371
+ });
372
+ } catch {
373
+ return empty(502);
374
+ }
375
+ const drop = () => void upstream.body?.cancel().catch(() => {
376
+ });
377
+ const etag = upstream.headers.get("etag");
378
+ if (upstream.status === 304) {
379
+ drop();
380
+ return new Response(null, { status: 304, headers: { "Cache-Control": CACHE_CONTROL, Vary: "Range", ...SAFE_HEADERS, ...etag ? { ETag: etag } : {} } });
381
+ }
382
+ if (upstream.status === 404 || upstream.status === 416) {
383
+ drop();
384
+ const range = upstream.status === 416 ? upstream.headers.get("content-range") : null;
385
+ return empty(upstream.status, range ? { "Content-Range": range } : {});
386
+ }
387
+ const type = upstream.headers.get("content-type")?.split(";")[0]?.trim().toLowerCase();
388
+ const length = Number(upstream.headers.get("content-length"));
389
+ const expectedStatus = upstream.status === 200 || upstream.status === 206;
390
+ if (!expectedStatus || !upstream.body || !type || !ASSET_CONTENT_TYPES.has(type) || Number.isFinite(length) && length > maxBytes) {
391
+ drop();
392
+ return empty(502);
393
+ }
394
+ const headers = new Headers({ "Content-Type": type, "Accept-Ranges": "bytes", "Cache-Control": upstream.status === 206 ? PARTIAL_CACHE_CONTROL : CACHE_CONTROL, Vary: "Range", ...SAFE_HEADERS });
395
+ if (etag) headers.set("ETag", etag);
396
+ const contentRange = upstream.headers.get("content-range");
397
+ if (upstream.status === 206 && contentRange) headers.set("Content-Range", contentRange);
398
+ if (!upstream.headers.get("content-encoding") && upstream.headers.get("content-length")) headers.set("Content-Length", String(length));
399
+ if (head) {
400
+ drop();
401
+ return new Response(null, { status: upstream.status, headers });
402
+ }
403
+ return new Response(capped(upstream.body, maxBytes), { status: upstream.status, headers });
404
+ }
405
+ return { GET: (req, ctx) => serve(req, ctx, false), HEAD: (req, ctx) => serve(req, ctx, true) };
406
+ }
207
407
  export {
408
+ MOUNTS_MAX_STALE_MS,
409
+ createAssetRoute,
208
410
  createRevalidateRoute,
209
411
  fetchResolver,
210
412
  hyleMetadata,
211
413
  hylePage,
414
+ hyleRootMetadata,
415
+ hyleRootPage,
416
+ hyleRootSitemap,
212
417
  hyleSitemap,
213
418
  workspaceTags
214
419
  };
package/dist/react.cjs CHANGED
@@ -42,6 +42,20 @@ var import_hast_util_to_jsx_runtime = require("hast-util-to-jsx-runtime");
42
42
  var import_react = require("react");
43
43
  var import_jsx_runtime2 = require("react/jsx-runtime");
44
44
 
45
+ // src/asset-path.ts
46
+ var ASSET_ROUTE_PREFIX = "/api/hyle/assets";
47
+ var UUID = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}";
48
+ var EXTENSIONS = "png|jpg|gif|webp|svg|pdf|mp4|webm|mp3|ogg";
49
+ var ASSET_FILE = new RegExp(`^${UUID}(?:\\.(?:${EXTENSIONS}))?$`);
50
+ var HYLE_ASSET_URL = new RegExp(`^/assets/(${UUID}(?:\\.(?:${EXTENSIONS}))?)$`, "i");
51
+ function hostAssetSrc(src) {
52
+ const file = HYLE_ASSET_URL.exec(src)?.[1];
53
+ return file ? `${ASSET_ROUTE_PREFIX}/${file.toLowerCase()}` : src;
54
+ }
55
+ function hostAssetHtml(html) {
56
+ return html.replace(new RegExp(`(\\ssrc=")(/assets/${UUID}(?:\\.(?:${EXTENSIONS}))?)(")`, "gi"), (_m, open, url, close) => `${open}${hostAssetSrc(url)}${close}`);
57
+ }
58
+
45
59
  // src/react/icons.tsx
46
60
  var import_jsx_runtime = require("react/jsx-runtime");
47
61
  var SHAPES = {
@@ -233,6 +247,7 @@ function clean(node, depth, ctx2, budget) {
233
247
  if (Object.hasOwn(rules, key) && rules[key](value, inner)) properties[key] = value;
234
248
  }
235
249
  }
250
+ if ((tag === "img" || tag === "video" || tag === "audio") && typeof properties.src === "string") properties.src = hostAssetSrc(properties.src);
236
251
  if (tag === "iframe") {
237
252
  if (properties.sandbox === void 0 || properties.srcdoc === void 0) return [];
238
253
  properties.sandbox = "allow-scripts";
@@ -258,6 +273,101 @@ function sanitizeHast(tree, title) {
258
273
  return { type: "root", children: raw.filter((n) => n !== skip).flatMap((n) => clean(n, 0, { katex: false }, budget)) };
259
274
  }
260
275
 
276
+ // src/react/viewer/labels.ts
277
+ var VIEWER_LABELS_EN = {
278
+ expand: "Expand diagram",
279
+ expandHint: "Expand",
280
+ viewer: "Diagram viewer",
281
+ close: "Close",
282
+ zoomIn: "Zoom in",
283
+ zoomOut: "Zoom out",
284
+ fit: "Fit to window",
285
+ actual: "Actual size",
286
+ search: "Find in diagram",
287
+ searchPlaceholder: "Find",
288
+ noMatch: "No match",
289
+ matchOf: "{n} of {total}",
290
+ copySource: "Copy diagram source",
291
+ downloadSvg: "Download SVG",
292
+ downloadPng: "Download PNG",
293
+ copyImage: "Copy as image",
294
+ pngScale: "PNG scale",
295
+ fullscreen: "Fullscreen",
296
+ exitFullscreen: "Exit fullscreen",
297
+ copied: "Copied",
298
+ saved: "Saved",
299
+ unavailable: "Not available here",
300
+ hint: "Scroll to zoom, drag to pan, click a node to trace its paths, press / to search",
301
+ legendSelected: "Selected",
302
+ legendUpstream: "Upstream",
303
+ legendDownstream: "Downstream",
304
+ outgoing: "outgoing",
305
+ tracing: "{label}: {up} upstream, {down} downstream",
306
+ map: "Overview map"
307
+ };
308
+ var VIEWER_LABELS_FR = {
309
+ expand: "Agrandir le sch\xE9ma",
310
+ expandHint: "Agrandir",
311
+ viewer: "Visionneuse de sch\xE9ma",
312
+ close: "Fermer",
313
+ zoomIn: "Zoom avant",
314
+ zoomOut: "Zoom arri\xE8re",
315
+ fit: "Ajuster \xE0 la fen\xEAtre",
316
+ actual: "Taille r\xE9elle",
317
+ search: "Rechercher dans le sch\xE9ma",
318
+ searchPlaceholder: "Rechercher",
319
+ noMatch: "Aucun r\xE9sultat",
320
+ matchOf: "{n} sur {total}",
321
+ copySource: "Copier la source du sch\xE9ma",
322
+ downloadSvg: "T\xE9l\xE9charger le SVG",
323
+ downloadPng: "T\xE9l\xE9charger le PNG",
324
+ copyImage: "Copier comme image",
325
+ pngScale: "\xC9chelle du PNG",
326
+ fullscreen: "Plein \xE9cran",
327
+ exitFullscreen: "Quitter le plein \xE9cran",
328
+ copied: "Copi\xE9",
329
+ saved: "Enregistr\xE9",
330
+ unavailable: "Indisponible ici",
331
+ hint: "Molette pour zoomer, glisser pour d\xE9placer, cliquer un n\u0153ud pour suivre ses chemins, / pour chercher",
332
+ legendSelected: "S\xE9lection",
333
+ legendUpstream: "En amont",
334
+ legendDownstream: "En aval",
335
+ outgoing: "sortants",
336
+ tracing: "{label} : {up} en amont, {down} en aval",
337
+ map: "Carte d'ensemble"
338
+ };
339
+ var VIEWER_LABELS_ES = {
340
+ expand: "Ampliar el diagrama",
341
+ expandHint: "Ampliar",
342
+ viewer: "Visor de diagramas",
343
+ close: "Cerrar",
344
+ zoomIn: "Acercar",
345
+ zoomOut: "Alejar",
346
+ fit: "Ajustar a la ventana",
347
+ actual: "Tama\xF1o real",
348
+ search: "Buscar en el diagrama",
349
+ searchPlaceholder: "Buscar",
350
+ noMatch: "Sin resultados",
351
+ matchOf: "{n} de {total}",
352
+ copySource: "Copiar el c\xF3digo del diagrama",
353
+ downloadSvg: "Descargar SVG",
354
+ downloadPng: "Descargar PNG",
355
+ copyImage: "Copiar como imagen",
356
+ pngScale: "Escala del PNG",
357
+ fullscreen: "Pantalla completa",
358
+ exitFullscreen: "Salir de pantalla completa",
359
+ copied: "Copiado",
360
+ saved: "Guardado",
361
+ unavailable: "No disponible aqu\xED",
362
+ hint: "Rueda para acercar, arrastra para mover, pulsa un nodo para seguir sus caminos, / para buscar",
363
+ legendSelected: "Seleccionado",
364
+ legendUpstream: "Aguas arriba",
365
+ legendDownstream: "Aguas abajo",
366
+ outgoing: "salientes",
367
+ tracing: "{label}: {up} aguas arriba, {down} aguas abajo",
368
+ map: "Mapa general"
369
+ };
370
+
261
371
  // src/react/strings.ts
262
372
  var en = {
263
373
  toc: "On this page",
@@ -297,7 +407,8 @@ var en = {
297
407
  rdFallback: "If nothing happens, go to the new address.",
298
408
  unKind: "Unavailable",
299
409
  unTitle: "This page is temporarily unavailable",
300
- unBody: "The content could not be loaded. Please try again in a moment."
410
+ unBody: "The content could not be loaded. Please try again in a moment.",
411
+ viewer: VIEWER_LABELS_EN
301
412
  };
302
413
  var fr = {
303
414
  toc: "Sur cette page",
@@ -337,7 +448,8 @@ var fr = {
337
448
  rdFallback: "Si rien ne se passe, allez \xE0 la nouvelle adresse.",
338
449
  unKind: "Indisponible",
339
450
  unTitle: "Cette page est momentan\xE9ment indisponible",
340
- unBody: "Le contenu n'a pas pu \xEAtre charg\xE9. R\xE9essayez dans un instant."
451
+ unBody: "Le contenu n'a pas pu \xEAtre charg\xE9. R\xE9essayez dans un instant.",
452
+ viewer: VIEWER_LABELS_FR
341
453
  };
342
454
  var es = {
343
455
  toc: "En esta p\xE1gina",
@@ -377,7 +489,8 @@ var es = {
377
489
  rdFallback: "Si no pasa nada, ve a la nueva direcci\xF3n.",
378
490
  unKind: "No disponible",
379
491
  unTitle: "Esta p\xE1gina no est\xE1 disponible por el momento",
380
- unBody: "No se pudo cargar el contenido. Int\xE9ntalo de nuevo en un momento."
492
+ unBody: "No se pudo cargar el contenido. Int\xE9ntalo de nuevo en un momento.",
493
+ viewer: VIEWER_LABELS_ES
381
494
  };
382
495
  var TABLE = { en, fr, es };
383
496
  function stringsFor(locale) {
@@ -445,7 +558,7 @@ function buildComponents(c, s) {
445
558
  if (typeof srcDoc !== "string") return null;
446
559
  const source = mermaidSource(srcDoc);
447
560
  if (c.Mermaid) return /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(c.Mermaid, { srcDoc, source, title: s.diagram });
448
- if (source !== void 0) return /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(import_mermaid_diagram.MermaidDiagram, { source, title: s.diagram, errorText: s.diagramError });
561
+ if (source !== void 0) return /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(import_mermaid_diagram.MermaidDiagram, { source, title: s.diagram, errorText: s.diagramError, labels: s.viewer });
449
562
  return /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("figure", { className: "hyle-mermaid", "data-slot-component": "Mermaid", children: /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("iframe", { srcDoc, sandbox: String(sandbox), title: s.diagram, loading: "lazy", referrerPolicy: "no-referrer", ...{ csp: MERMAID_FRAME_CSP } }) });
450
563
  };
451
564
  const Heading = (level) => function HyleHeading({ id, children, ...rest }) {
@@ -482,7 +595,7 @@ function HastContent({ tree, title, components = {}, locale }) {
482
595
  });
483
596
  }
484
597
  function TrustedServerHtml({ html }) {
485
- return /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("div", { dangerouslySetInnerHTML: { __html: html } });
598
+ return /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("div", { dangerouslySetInnerHTML: { __html: hostAssetHtml(html) } });
486
599
  }
487
600
 
488
601
  // src/react/index.ts
package/dist/react.d.cts CHANGED
@@ -1,9 +1,9 @@
1
1
  import * as react from 'react';
2
2
  import { ReactElement } from 'react';
3
- import { H as HyleComponents, P as PageBaseProps } from './types-D0qoLh4E.cjs';
4
- export { C as CalloutKind, b as CalloutProps, c as CodeBlockProps, a as HyleSlots, I as ImageProps, L as LinkProps, d as ListItemProps, M as MermaidProps } from './types-D0qoLh4E.cjs';
3
+ import { H as HyleComponents, P as PageBaseProps } from './types-DnPzhrFx.cjs';
4
+ export { C as CalloutKind, b as CalloutProps, c as CodeBlockProps, a as HyleSlots, I as ImageProps, L as LinkProps, d as ListItemProps, M as MermaidProps } from './types-DnPzhrFx.cjs';
5
5
  import { Root } from 'hast';
6
- import { b as ResolvedArticle, d as ResolvedList } from './types-DjXf6iPo.cjs';
6
+ import { d as ResolvedArticle, f as ResolvedList } from './types-CwBCPh6K.cjs';
7
7
 
8
8
  interface HastContentProps {
9
9
  /** `content.tree` from an article result. Anything that is not a hast root renders nothing. */
@@ -24,6 +24,42 @@ declare function TrustedServerHtml({ html }: {
24
24
  html: string;
25
25
  }): ReactElement;
26
26
 
27
+ /**
28
+ * Every string the diagram viewer shows. Pure data, so the client component can carry the English defaults without importing
29
+ * the viewer chunk, and the server passes the host's locale in (strings.ts holds fr and es, unreviewed drafts like the rest).
30
+ */
31
+ interface ViewerLabels {
32
+ expand: string;
33
+ expandHint: string;
34
+ viewer: string;
35
+ close: string;
36
+ zoomIn: string;
37
+ zoomOut: string;
38
+ fit: string;
39
+ actual: string;
40
+ search: string;
41
+ searchPlaceholder: string;
42
+ noMatch: string;
43
+ matchOf: string;
44
+ copySource: string;
45
+ downloadSvg: string;
46
+ downloadPng: string;
47
+ copyImage: string;
48
+ pngScale: string;
49
+ fullscreen: string;
50
+ exitFullscreen: string;
51
+ copied: string;
52
+ saved: string;
53
+ unavailable: string;
54
+ hint: string;
55
+ legendSelected: string;
56
+ legendUpstream: string;
57
+ legendDownstream: string;
58
+ outgoing: string;
59
+ tracing: string;
60
+ map: string;
61
+ }
62
+
27
63
  /**
28
64
  * The SDK's only client component. It receives the diagram text and presentational strings and nothing else: never a token,
29
65
  * base URL or client (a test pins this). Mermaid is a dynamic import, so the chunk loads only on pages that have a diagram,
@@ -35,8 +71,10 @@ interface MermaidDiagramProps {
35
71
  title: string;
36
72
  /** Shown when Mermaid cannot render the source. */
37
73
  errorText: string;
74
+ /** Strings of the diagram viewer (English when omitted). */
75
+ labels?: ViewerLabels;
38
76
  }
39
- declare function MermaidDiagram({ source, title, errorText }: MermaidDiagramProps): react.JSX.Element;
77
+ declare function MermaidDiagram({ source, title, errorText, labels }: MermaidDiagramProps): react.JSX.Element;
40
78
 
41
79
  /**
42
80
  * Defense in depth. hyle sanitizes server-side (packages/renderer/src/render.ts); this guard repeats the same allowlist
@@ -90,6 +128,7 @@ declare function Redirecting({ from, to, ...base }: RedirectingProps): ReactElem
90
128
  * Chrome strings for en, fr and es. The fr and es copy is a draft carried over from the design kit and has not been
91
129
  * reviewed by a native speaker. Content itself is never translated here; it comes from hyle.
92
130
  */
131
+
93
132
  declare const en: {
94
133
  toc: string;
95
134
  prev: string;
@@ -129,6 +168,7 @@ declare const en: {
129
168
  unKind: string;
130
169
  unTitle: string;
131
170
  unBody: string;
171
+ viewer: ViewerLabels;
132
172
  };
133
173
  type Strings = typeof en;
134
174
  /** Strings for a BCP 47 tag; the primary subtag decides, anything unknown falls back to English. */