@tdacorp/hyle-sdk 0.2.1 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/README.md +105 -4
  2. package/bin/hyle-sdk-check-routes.mjs +3 -0
  3. package/dist/check-routes-bin.js +389 -0
  4. package/dist/chunk-4OB77ZOD.js +455 -0
  5. package/dist/chunk-BUJFMR3M.js +38 -0
  6. package/dist/{chunk-7VCMJUPC.js → chunk-OW6S7IZX.js} +1 -1
  7. package/dist/{chunk-MHVWHSKC.js → chunk-SO6H2UGL.js} +124 -6
  8. package/dist/diagram-viewer-DYX6R63Y.js +1132 -0
  9. package/dist/index.cjs +191 -20
  10. package/dist/index.d.cts +95 -3
  11. package/dist/index.d.ts +95 -3
  12. package/dist/index.js +13 -1
  13. package/dist/mermaid-diagram.cjs +1395 -0
  14. package/dist/mermaid-diagram.d.cts +55 -0
  15. package/dist/mermaid-diagram.d.ts +55 -0
  16. package/dist/mermaid-diagram.js +140 -0
  17. package/dist/next.cjs +286 -27
  18. package/dist/next.d.cts +51 -5
  19. package/dist/next.d.ts +51 -5
  20. package/dist/next.js +131 -5
  21. package/dist/react.cjs +124 -5
  22. package/dist/react.d.cts +60 -4
  23. package/dist/react.d.ts +60 -4
  24. package/dist/react.js +3 -1
  25. package/dist/{resolve-fMx2W8RR.d.ts → resolve-1rQntRBh.d.ts} +1 -1
  26. package/dist/{resolve-B_p0p4Zn.d.cts → resolve-36-Ng1H0.d.cts} +1 -1
  27. package/dist/styles.css +82 -1
  28. package/dist/{types-BNaGecO7.d.ts → types-BoyBWF2F.d.ts} +3 -1
  29. package/dist/{types-DjXf6iPo.d.cts → types-CwBCPh6K.d.cts} +20 -1
  30. package/dist/{types-DjXf6iPo.d.ts → types-CwBCPh6K.d.ts} +20 -1
  31. package/dist/{types-DLWvqanV.d.cts → types-DnPzhrFx.d.cts} +3 -1
  32. package/dist/use-cache.cjs +34 -20
  33. package/dist/use-cache.d.cts +2 -2
  34. package/dist/use-cache.d.ts +2 -2
  35. package/dist/use-cache.js +2 -2
  36. package/package.json +8 -3
  37. package/dist/chunk-HFUJRNFP.js +0 -290
package/dist/next.cjs CHANGED
@@ -20,10 +20,14 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
20
20
  // src/next/index.ts
21
21
  var next_exports = {};
22
22
  __export(next_exports, {
23
+ MOUNTS_MAX_STALE_MS: () => MOUNTS_MAX_STALE_MS,
23
24
  createRevalidateRoute: () => createRevalidateRoute,
24
25
  fetchResolver: () => fetchResolver,
25
26
  hyleMetadata: () => hyleMetadata,
26
27
  hylePage: () => hylePage,
28
+ hyleRootMetadata: () => hyleRootMetadata,
29
+ hyleRootPage: () => hyleRootPage,
30
+ hyleRootSitemap: () => hyleRootSitemap,
27
31
  hyleSitemap: () => hyleSitemap,
28
32
  workspaceTags: () => workspaceTags
29
33
  });
@@ -72,6 +76,11 @@ async function readCapped(res, max) {
72
76
  return Buffer.concat(chunks).toString("utf8");
73
77
  }
74
78
  var KINDS = /* @__PURE__ */ new Set(["article", "list", "redirect", "notfound", "disabled"]);
79
+ var isStrings = (value) => Array.isArray(value) && value.every((v) => typeof v === "string");
80
+ function isMounts(data) {
81
+ const mounts = data.mounts;
82
+ return typeof data.workspace_id === "string" && isStrings(data.reserved) && isStrings(data.supported_locales) && Array.isArray(mounts) && mounts.every((m) => typeof m?.prefix === "string" && typeof m.default_section === "string");
83
+ }
75
84
  function createHyleClient(options) {
76
85
  let origin;
77
86
  try {
@@ -85,18 +94,14 @@ function createHyleClient(options) {
85
94
  if (!options.token) throw new TypeError("token is required");
86
95
  const base = options.baseUrl.replace(/\/+$/, "");
87
96
  const fetchImpl = options.fetch ?? fetch;
88
- async function resolve(opts) {
89
- const url = new URL(`${base}/cp1/read/resolve`);
90
- url.searchParams.set("path", opts.path);
91
- if (opts.locale !== void 0) url.searchParams.set("locale", opts.locale);
92
- if (opts.format !== void 0) url.searchParams.set("format", opts.format);
93
- if (opts.cursor !== void 0) url.searchParams.set("cursor", opts.cursor);
94
- if (opts.limit !== void 0) url.searchParams.set("limit", String(opts.limit));
95
- const headers = new Headers(opts.init?.headers);
97
+ async function get(pathname, query, init) {
98
+ const url = new URL(`${base}${pathname}`);
99
+ url.search = query.toString();
100
+ const headers = new Headers(init?.headers);
96
101
  headers.set("authorization", `Bearer ${options.token}`);
97
102
  const timeout = AbortSignal.timeout(options.timeoutMs ?? DEFAULT_TIMEOUT_MS);
98
- const signal = opts.init?.signal ? AbortSignal.any([opts.init.signal, timeout]) : timeout;
99
- const res = await fetchImpl(url.toString(), { ...opts.init, method: "GET", headers, redirect: "error", signal });
103
+ const signal = init?.signal ? AbortSignal.any([init.signal, timeout]) : timeout;
104
+ const res = await fetchImpl(url.toString(), { ...init, method: "GET", headers, redirect: "error", signal });
100
105
  const text = await readCapped(res, options.maxResponseBytes ?? DEFAULT_MAX_RESPONSE_BYTES);
101
106
  let parsed;
102
107
  try {
@@ -104,18 +109,31 @@ function createHyleClient(options) {
104
109
  } catch {
105
110
  parsed = void 0;
106
111
  }
107
- const data = parsed?.data;
108
- if (data && data.cp === 1 && typeof data.kind === "string" && KINDS.has(data.kind)) return data;
112
+ return { parsed, status: res.status };
113
+ }
114
+ const failure = ({ parsed, status }) => {
109
115
  const err = parsed?.error;
110
- throw new Cp1ClientError(
111
- err?.code ?? "INVALID_RESPONSE",
112
- err?.message ?? `Unexpected response from hyle (HTTP ${res.status})`,
113
- res.status,
114
- err?.request_id ?? "",
115
- err?.details
116
- );
116
+ return new Cp1ClientError(err?.code ?? "INVALID_RESPONSE", err?.message ?? `Unexpected response from hyle (HTTP ${status})`, status, err?.request_id ?? "", err?.details);
117
+ };
118
+ async function resolve(opts) {
119
+ const query = new URLSearchParams({ path: opts.path });
120
+ if (opts.locale !== void 0) query.set("locale", opts.locale);
121
+ if (opts.format !== void 0) query.set("format", opts.format);
122
+ if (opts.cursor !== void 0) query.set("cursor", opts.cursor);
123
+ if (opts.limit !== void 0) query.set("limit", String(opts.limit));
124
+ const reply = await get("/cp1/read/resolve", query, opts.init);
125
+ const data = reply.parsed?.data;
126
+ if (data && data.cp === 1 && typeof data.kind === "string" && KINDS.has(data.kind)) return data;
127
+ throw failure(reply);
128
+ }
129
+ async function mounts(opts = {}) {
130
+ const reply = await get("/cp1/read/mounts", new URLSearchParams(), opts.init);
131
+ const data = reply.parsed?.data;
132
+ if (data?.cp === 1 && data.kind === "disabled") return data;
133
+ if (data?.cp === 1 && data.kind === "mounts" && isMounts(data)) return data;
134
+ throw failure(reply);
117
135
  }
118
- return { resolve };
136
+ return { resolve, mounts };
119
137
  }
120
138
 
121
139
  // src/delivery-dedupe.ts
@@ -352,6 +370,12 @@ function Icon({ name, className }) {
352
370
  return /* @__PURE__ */ (0, import_jsx_runtime.jsx)("svg", { className: className ? `hyle-ic ${className}` : "hyle-ic", viewBox: "0 0 16 16", "aria-hidden": "true", children: SHAPES[name] });
353
371
  }
354
372
 
373
+ // src/react/content.tsx
374
+ var import_mermaid_diagram = require("./mermaid-diagram.cjs");
375
+
376
+ // src/react/mermaid-config.ts
377
+ var MAX_MERMAID_SOURCE = 2e4;
378
+
355
379
  // src/react/sanitize.ts
356
380
  var HastLimitError = class extends Error {
357
381
  constructor(message) {
@@ -410,9 +434,14 @@ var isHref = (v) => isSafeUrl(v, "href") && (typeof v !== "string" || !v.trim().
410
434
  var isSrc = (v) => isSafeUrl(v, "src");
411
435
  var MERMAID_SCRIPT_URL = "https://cdnjs.cloudflare.com/ajax/libs/mermaid/11.9.0/mermaid.min.js";
412
436
  var MERMAID_SRCDOC = new RegExp(
413
- `^<!doctype html><html><head><meta charset="utf-8"></head><body><div class="mermaid">[^<]*</div><script src="${MERMAID_SCRIPT_URL.replace(/[.]/g, "\\.")}"></script><script>mermaid\\.initialize\\(\\{ startOnLoad: true, securityLevel: "strict" \\}\\);</script></body></html>$`
437
+ `^<!doctype html><html><head><meta charset="utf-8"></head><body><div class="mermaid">([^<]*)</div><script src="${MERMAID_SCRIPT_URL.replace(/[.]/g, "\\.")}"></script><script>mermaid\\.initialize\\(\\{ startOnLoad: true, securityLevel: "strict" \\}\\);</script></body></html>$`
414
438
  );
415
439
  var isMermaidSrcdoc = (v) => typeof v === "string" && v.length <= MAX_SRCDOC && MERMAID_SRCDOC.test(v);
440
+ var ENTITIES = { "&#x3c;": "<", "&#x26;": "&", "&lt;": "<", "&gt;": ">", "&amp;": "&", "&quot;": '"', "&#x27;": "'" };
441
+ function mermaidSource(srcDoc) {
442
+ const text = MERMAID_SRCDOC.exec(srcDoc)?.[1]?.replace(/&(?:#x3c|#x26|#x27|lt|gt|amp|quot);/gi, (e) => ENTITIES[e.toLowerCase()]);
443
+ return text === void 0 || text.length > MAX_MERMAID_SOURCE ? void 0 : text;
444
+ }
416
445
  var MERMAID_FRAME_CSP = `default-src 'none'; script-src ${MERMAID_SCRIPT_URL} 'unsafe-inline'; style-src 'unsafe-inline'; img-src data:`;
417
446
  var heading = { id: isIdValue, className: isClass };
418
447
  var ATTRS = new Map(
@@ -521,6 +550,101 @@ function sanitizeHast(tree, title) {
521
550
  return { type: "root", children: raw.filter((n) => n !== skip).flatMap((n) => clean(n, 0, { katex: false }, budget)) };
522
551
  }
523
552
 
553
+ // src/react/viewer/labels.ts
554
+ var VIEWER_LABELS_EN = {
555
+ expand: "Expand diagram",
556
+ expandHint: "Expand",
557
+ viewer: "Diagram viewer",
558
+ close: "Close",
559
+ zoomIn: "Zoom in",
560
+ zoomOut: "Zoom out",
561
+ fit: "Fit to window",
562
+ actual: "Actual size",
563
+ search: "Find in diagram",
564
+ searchPlaceholder: "Find",
565
+ noMatch: "No match",
566
+ matchOf: "{n} of {total}",
567
+ copySource: "Copy diagram source",
568
+ downloadSvg: "Download SVG",
569
+ downloadPng: "Download PNG",
570
+ copyImage: "Copy as image",
571
+ pngScale: "PNG scale",
572
+ fullscreen: "Fullscreen",
573
+ exitFullscreen: "Exit fullscreen",
574
+ copied: "Copied",
575
+ saved: "Saved",
576
+ unavailable: "Not available here",
577
+ hint: "Scroll to zoom, drag to pan, click a node to trace its paths, press / to search",
578
+ legendSelected: "Selected",
579
+ legendUpstream: "Upstream",
580
+ legendDownstream: "Downstream",
581
+ outgoing: "outgoing",
582
+ tracing: "{label}: {up} upstream, {down} downstream",
583
+ map: "Overview map"
584
+ };
585
+ var VIEWER_LABELS_FR = {
586
+ expand: "Agrandir le sch\xE9ma",
587
+ expandHint: "Agrandir",
588
+ viewer: "Visionneuse de sch\xE9ma",
589
+ close: "Fermer",
590
+ zoomIn: "Zoom avant",
591
+ zoomOut: "Zoom arri\xE8re",
592
+ fit: "Ajuster \xE0 la fen\xEAtre",
593
+ actual: "Taille r\xE9elle",
594
+ search: "Rechercher dans le sch\xE9ma",
595
+ searchPlaceholder: "Rechercher",
596
+ noMatch: "Aucun r\xE9sultat",
597
+ matchOf: "{n} sur {total}",
598
+ copySource: "Copier la source du sch\xE9ma",
599
+ downloadSvg: "T\xE9l\xE9charger le SVG",
600
+ downloadPng: "T\xE9l\xE9charger le PNG",
601
+ copyImage: "Copier comme image",
602
+ pngScale: "\xC9chelle du PNG",
603
+ fullscreen: "Plein \xE9cran",
604
+ exitFullscreen: "Quitter le plein \xE9cran",
605
+ copied: "Copi\xE9",
606
+ saved: "Enregistr\xE9",
607
+ unavailable: "Indisponible ici",
608
+ hint: "Molette pour zoomer, glisser pour d\xE9placer, cliquer un n\u0153ud pour suivre ses chemins, / pour chercher",
609
+ legendSelected: "S\xE9lection",
610
+ legendUpstream: "En amont",
611
+ legendDownstream: "En aval",
612
+ outgoing: "sortants",
613
+ tracing: "{label} : {up} en amont, {down} en aval",
614
+ map: "Carte d'ensemble"
615
+ };
616
+ var VIEWER_LABELS_ES = {
617
+ expand: "Ampliar el diagrama",
618
+ expandHint: "Ampliar",
619
+ viewer: "Visor de diagramas",
620
+ close: "Cerrar",
621
+ zoomIn: "Acercar",
622
+ zoomOut: "Alejar",
623
+ fit: "Ajustar a la ventana",
624
+ actual: "Tama\xF1o real",
625
+ search: "Buscar en el diagrama",
626
+ searchPlaceholder: "Buscar",
627
+ noMatch: "Sin resultados",
628
+ matchOf: "{n} de {total}",
629
+ copySource: "Copiar el c\xF3digo del diagrama",
630
+ downloadSvg: "Descargar SVG",
631
+ downloadPng: "Descargar PNG",
632
+ copyImage: "Copiar como imagen",
633
+ pngScale: "Escala del PNG",
634
+ fullscreen: "Pantalla completa",
635
+ exitFullscreen: "Salir de pantalla completa",
636
+ copied: "Copiado",
637
+ saved: "Guardado",
638
+ unavailable: "No disponible aqu\xED",
639
+ hint: "Rueda para acercar, arrastra para mover, pulsa un nodo para seguir sus caminos, / para buscar",
640
+ legendSelected: "Seleccionado",
641
+ legendUpstream: "Aguas arriba",
642
+ legendDownstream: "Aguas abajo",
643
+ outgoing: "salientes",
644
+ tracing: "{label}: {up} aguas arriba, {down} aguas abajo",
645
+ map: "Mapa general"
646
+ };
647
+
524
648
  // src/react/strings.ts
525
649
  var en = {
526
650
  toc: "On this page",
@@ -538,6 +662,7 @@ var en = {
538
662
  tip: "Tip",
539
663
  caution: "Caution",
540
664
  diagram: "Diagram",
665
+ diagramError: "This diagram could not be rendered.",
541
666
  contentError: "This content cannot be displayed.",
542
667
  fallbackTitle: "Not translated into {language} yet.",
543
668
  fallbackBody: "You are reading the original.",
@@ -559,7 +684,8 @@ var en = {
559
684
  rdFallback: "If nothing happens, go to the new address.",
560
685
  unKind: "Unavailable",
561
686
  unTitle: "This page is temporarily unavailable",
562
- unBody: "The content could not be loaded. Please try again in a moment."
687
+ unBody: "The content could not be loaded. Please try again in a moment.",
688
+ viewer: VIEWER_LABELS_EN
563
689
  };
564
690
  var fr = {
565
691
  toc: "Sur cette page",
@@ -577,6 +703,7 @@ var fr = {
577
703
  tip: "Astuce",
578
704
  caution: "Danger",
579
705
  diagram: "Sch\xE9ma",
706
+ diagramError: "Ce sch\xE9ma n'a pas pu \xEAtre affich\xE9.",
580
707
  contentError: "Ce contenu ne peut pas \xEAtre affich\xE9.",
581
708
  fallbackTitle: "Pas encore traduit en {language}.",
582
709
  fallbackBody: "Vous lisez l'original.",
@@ -598,7 +725,8 @@ var fr = {
598
725
  rdFallback: "Si rien ne se passe, allez \xE0 la nouvelle adresse.",
599
726
  unKind: "Indisponible",
600
727
  unTitle: "Cette page est momentan\xE9ment indisponible",
601
- unBody: "Le contenu n'a pas pu \xEAtre charg\xE9. R\xE9essayez dans un instant."
728
+ unBody: "Le contenu n'a pas pu \xEAtre charg\xE9. R\xE9essayez dans un instant.",
729
+ viewer: VIEWER_LABELS_FR
602
730
  };
603
731
  var es = {
604
732
  toc: "En esta p\xE1gina",
@@ -616,6 +744,7 @@ var es = {
616
744
  tip: "Consejo",
617
745
  caution: "Peligro",
618
746
  diagram: "Diagrama",
747
+ diagramError: "No se pudo mostrar este diagrama.",
619
748
  contentError: "No se puede mostrar este contenido.",
620
749
  fallbackTitle: "A\xFAn no est\xE1 traducida al {language}.",
621
750
  fallbackBody: "Est\xE1s leyendo el original.",
@@ -637,7 +766,8 @@ var es = {
637
766
  rdFallback: "Si no pasa nada, ve a la nueva direcci\xF3n.",
638
767
  unKind: "No disponible",
639
768
  unTitle: "Esta p\xE1gina no est\xE1 disponible por el momento",
640
- unBody: "No se pudo cargar el contenido. Int\xE9ntalo de nuevo en un momento."
769
+ unBody: "No se pudo cargar el contenido. Int\xE9ntalo de nuevo en un momento.",
770
+ viewer: VIEWER_LABELS_ES
641
771
  };
642
772
  var TABLE = { en, fr, es };
643
773
  function stringsFor(locale) {
@@ -703,7 +833,9 @@ function buildComponents(c, s) {
703
833
  };
704
834
  const Frame = ({ srcDoc, sandbox }) => {
705
835
  if (typeof srcDoc !== "string") return null;
706
- if (c.Mermaid) return /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(c.Mermaid, { srcDoc, title: s.diagram });
836
+ const source = mermaidSource(srcDoc);
837
+ if (c.Mermaid) return /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(c.Mermaid, { srcDoc, source, title: s.diagram });
838
+ 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 });
707
839
  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 } }) });
708
840
  };
709
841
  const Heading = (level) => function HyleHeading({ id, children, ...rest }) {
@@ -743,6 +875,9 @@ function TrustedServerHtml({ html }) {
743
875
  return /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("div", { dangerouslySetInnerHTML: { __html: html } });
744
876
  }
745
877
 
878
+ // src/react/index.ts
879
+ var import_mermaid_diagram2 = require("./mermaid-diagram.cjs");
880
+
746
881
  // src/react/pages.tsx
747
882
  var import_jsx_runtime4 = require("react/jsx-runtime");
748
883
  function Slot({ name, slots, tag: Tag = "div", className }) {
@@ -989,9 +1124,10 @@ var import_navigation = require("next/navigation");
989
1124
 
990
1125
  // src/next/paths.ts
991
1126
  function normalizeBasePath(basePath) {
992
- const value = (basePath ?? "").replace(/\/+$/, "");
1127
+ const raw = basePath ?? "";
1128
+ const value = raw === "/" ? "" : raw.replace(/\/$/, "");
993
1129
  if (value === "") return "";
994
- if (!/^\/[^\s?#\\]+$/.test(value) || value.includes("//")) throw new TypeError(`basePath must look like "/learn", got "${basePath}"`);
1130
+ if (!/^\/[^\s?#\\]+$/.test(value) || raw.includes("//")) throw new TypeError(`basePath must look like "/learn", got "${basePath}"`);
995
1131
  return value;
996
1132
  }
997
1133
  var MAX_PATH_LENGTH = 1024;
@@ -1197,12 +1333,135 @@ function createRevalidateRoute(options) {
1197
1333
  }
1198
1334
  };
1199
1335
  }
1336
+
1337
+ // src/next/root.ts
1338
+ var import_navigation3 = require("next/navigation");
1339
+
1340
+ // src/next/mount-match.ts
1341
+ function activeMounts(mounts) {
1342
+ const out = [];
1343
+ for (const { prefix, default_section } of mounts) {
1344
+ try {
1345
+ const normalized = normalizeBasePath(prefix);
1346
+ out.push({ prefix: normalized, defaultSection: default_section, depth: normalized === "" ? 0 : normalized.split("/").length - 1 });
1347
+ } catch (error) {
1348
+ console.error(`hyle: ignoring a mount with an invalid prefix (${error instanceof Error ? error.name : "Error"})`);
1349
+ }
1350
+ }
1351
+ return out;
1352
+ }
1353
+ var prefixMatches = (prefix, path) => prefix === "" || path === prefix || path.startsWith(`${prefix}/`);
1354
+ function isReserved(path, reserved) {
1355
+ return reserved.some((entry) => entry.endsWith("/*") ? prefixMatches(entry.slice(0, -2), path) : entry === path);
1356
+ }
1357
+
1358
+ // src/next/root.ts
1359
+ var MOUNTS_MAX_STALE_MS = 15 * 60 * 1e3;
1360
+ var SECTION_SLUG2 = /^[A-Za-z0-9][A-Za-z0-9_-]*$/;
1361
+ var NONE = { mounts: [], reserved: [] };
1362
+ var lastKnownGood = /* @__PURE__ */ new Map();
1363
+ function mountsLoader(config) {
1364
+ if (!config.workspaceId) throw new TypeError("hyleRootPage: `workspaceId` is required for the fetch cache");
1365
+ const client = createHyleClient({ baseUrl: config.baseUrl, token: config.token });
1366
+ const init = { next: { revalidate: config.revalidate ?? DEFAULT_REVALIDATE, tags: workspaceTags(config.workspaceId).slice(0, 1) } };
1367
+ const key = `${new URL(config.baseUrl).origin}|${config.workspaceId}`;
1368
+ return async function load() {
1369
+ try {
1370
+ const result = await client.mounts({ init });
1371
+ if (result.kind !== "mounts") {
1372
+ lastKnownGood.delete(key);
1373
+ return NONE;
1374
+ }
1375
+ const loaded = { mounts: activeMounts(result.mounts), reserved: result.reserved };
1376
+ lastKnownGood.set(key, { loaded, at: Date.now() });
1377
+ return loaded;
1378
+ } catch (error) {
1379
+ if (isRejectedRequest(error)) {
1380
+ lastKnownGood.delete(key);
1381
+ return NONE;
1382
+ }
1383
+ if (error instanceof Cp1ClientError && (error.status === 401 || error.status === 403)) {
1384
+ lastKnownGood.delete(key);
1385
+ throw error;
1386
+ }
1387
+ const kept = lastKnownGood.get(key);
1388
+ if (kept && Date.now() - kept.at <= MOUNTS_MAX_STALE_MS) return kept.loaded;
1389
+ throw error;
1390
+ }
1391
+ };
1392
+ }
1393
+ var asArray = (options) => Array.isArray(options) ? options : [options];
1394
+ function setup(options) {
1395
+ const configs = asArray(options);
1396
+ if (configs.length === 0) throw new TypeError("hyleRootPage: pass at least one workspace config");
1397
+ const param = configs[0].param ?? "hyle";
1398
+ if (configs.some((c) => (c.param ?? "hyle") !== param)) throw new TypeError("hyleRootPage: every config must use the same `param`");
1399
+ return { configs, param, loaders: configs.map(mountsLoader) };
1400
+ }
1401
+ function createRouter(options, make) {
1402
+ const { configs, param, loaders } = setup(options);
1403
+ const handlers = /* @__PURE__ */ new Map();
1404
+ return async function route(params) {
1405
+ const raw = params[param];
1406
+ const segments = typeof raw === "string" ? [raw] : raw;
1407
+ const path = sitePathFrom("", segments);
1408
+ if (path === void 0 || path === "/" || !segments) return void 0;
1409
+ const loaded = await Promise.all(loaders.map((load) => load()));
1410
+ let best;
1411
+ loaded.forEach(({ mounts, reserved }, index2) => {
1412
+ if (isReserved(path, reserved)) return;
1413
+ for (const mount2 of mounts) if (prefixMatches(mount2.prefix, path) && (!best || mount2.depth > best.mount.depth)) best = { index: index2, mount: mount2 };
1414
+ });
1415
+ if (!best) return void 0;
1416
+ const { index, mount } = best;
1417
+ const config = configs[index];
1418
+ const id = `${index}|${mount.prefix}|${mount.defaultSection}`;
1419
+ let handler = handlers.get(id);
1420
+ if (!handler) {
1421
+ const sections = [...config.sections ?? [], ...SECTION_SLUG2.test(mount.defaultSection) ? [mount.defaultSection] : []];
1422
+ handler = make({ ...config, basePath: mount.prefix, sections });
1423
+ handlers.set(id, handler);
1424
+ }
1425
+ return { handler, params: { ...params, [param]: segments.slice(mount.depth) } };
1426
+ };
1427
+ }
1428
+ function hyleRootPage(options) {
1429
+ const route = createRouter(options, hylePage);
1430
+ return async function HyleRootPage({ params, searchParams }) {
1431
+ const hit = await route(await params ?? {});
1432
+ if (!hit) (0, import_navigation3.notFound)();
1433
+ return hit.handler({ params: Promise.resolve(hit.params), ...searchParams ? { searchParams } : {} });
1434
+ };
1435
+ }
1436
+ function hyleRootMetadata(options) {
1437
+ const route = createRouter(options, hyleMetadata);
1438
+ return async function generateMetadata({ params }) {
1439
+ const hit = await route(await params ?? {});
1440
+ return hit ? hit.handler({ params: Promise.resolve(hit.params) }) : {};
1441
+ };
1442
+ }
1443
+ async function hyleRootSitemap(options, sitemap) {
1444
+ const { configs, loaders } = setup(options);
1445
+ const entries = /* @__PURE__ */ new Map();
1446
+ for (const [index, load] of loaders.entries()) {
1447
+ const config = configs[index];
1448
+ for (const mount of (await load()).mounts) {
1449
+ const sections = [...config.sections ?? [], ...SECTION_SLUG2.test(mount.defaultSection) ? [mount.defaultSection] : []];
1450
+ for (const entry of await hyleSitemap({ ...config, basePath: mount.prefix, sections, ...sitemap })) entries.set(entry.url, entry);
1451
+ }
1452
+ }
1453
+ return [...entries.values()];
1454
+ }
1200
1455
  // Annotate the CommonJS export names for ESM import in node:
1201
1456
  0 && (module.exports = {
1457
+ MOUNTS_MAX_STALE_MS,
1202
1458
  createRevalidateRoute,
1203
1459
  fetchResolver,
1204
1460
  hyleMetadata,
1205
1461
  hylePage,
1462
+ hyleRootMetadata,
1463
+ hyleRootPage,
1464
+ hyleRootSitemap,
1206
1465
  hyleSitemap,
1207
1466
  workspaceTags
1208
1467
  });
package/dist/next.d.cts CHANGED
@@ -1,10 +1,10 @@
1
1
  import { ReactElement } from 'react';
2
- import { H as HyleComponents, a as HyleSlots } from './types-DLWvqanV.cjs';
3
- import { F as FetchResolverOptions, H as HyleResolver } from './resolve-B_p0p4Zn.cjs';
4
- export { f as fetchResolver, w as workspaceTags } from './resolve-B_p0p4Zn.cjs';
2
+ import { H as HyleComponents, a as HyleSlots } from './types-DnPzhrFx.cjs';
3
+ import { F as FetchResolverOptions, H as HyleResolver } from './resolve-36-Ng1H0.cjs';
4
+ export { f as fetchResolver, w as workspaceTags } from './resolve-36-Ng1H0.cjs';
5
5
  import { MetadataRoute, Metadata } from 'next';
6
6
  import { a as RevalidationCallbackRoute } from './revalidation-callback-D7Ms_Puz.cjs';
7
- import './types-DjXf6iPo.cjs';
7
+ import './types-CwBCPh6K.cjs';
8
8
 
9
9
  type RouteParams = Record<string, string | string[] | undefined>;
10
10
  interface CommonOptions {
@@ -139,4 +139,50 @@ 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
+ export { FetchResolverOptions, type HyleNextOptions, HyleResolver, type HyleRootConfig, type HyleRootSitemapOptions, type HyleSitemapOptions, MOUNTS_MAX_STALE_MS, type PageProps, type RevalidateRouteOptions, type RouteParams, createRevalidateRoute, hyleMetadata, hylePage, hyleRootMetadata, hyleRootPage, hyleRootSitemap, hyleSitemap };
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-BNaGecO7.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,50 @@ 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
+ export { FetchResolverOptions, type HyleNextOptions, HyleResolver, type HyleRootConfig, type HyleRootSitemapOptions, type HyleSitemapOptions, MOUNTS_MAX_STALE_MS, type PageProps, type RevalidateRouteOptions, type RouteParams, createRevalidateRoute, hyleMetadata, hylePage, hyleRootMetadata, hyleRootPage, hyleRootSitemap, hyleSitemap };