@tdacorp/hyle-sdk 0.8.1 → 0.11.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 (41) hide show
  1. package/README.md +82 -4
  2. package/bin/hyle-sdk-engage-keygen.mjs +3 -0
  3. package/dist/check-routes-bin.js +6 -1
  4. package/dist/{chunk-EBNIKRQH.js → chunk-N7ZQUAGM.js} +46 -2
  5. package/dist/chunk-R5EMI4HQ.js +61 -0
  6. package/dist/{chunk-LGW2KP4X.js → chunk-S3LT6G4M.js} +601 -77
  7. package/dist/{chunk-N4QYPO7S.js → chunk-S7PCCEHP.js} +3 -2
  8. package/dist/comments.cjs +1048 -0
  9. package/dist/comments.d.cts +152 -0
  10. package/dist/comments.d.ts +152 -0
  11. package/dist/comments.js +1025 -0
  12. package/dist/docs-enhance.cjs +97 -0
  13. package/dist/docs-enhance.d.cts +16 -0
  14. package/dist/docs-enhance.d.ts +16 -0
  15. package/dist/docs-enhance.js +73 -0
  16. package/dist/{types-DnPzhrFx.d.cts → embed-BC8Tlc6A.d.cts} +44 -3
  17. package/dist/{types-BoyBWF2F.d.ts → embed-CwSzvBUO.d.ts} +44 -3
  18. package/dist/engage-keygen-bin.js +67 -0
  19. package/dist/index.cjs +27 -1
  20. package/dist/index.d.cts +13 -3
  21. package/dist/index.d.ts +13 -3
  22. package/dist/index.js +5 -1
  23. package/dist/mermaid-diagram.js +9 -54
  24. package/dist/next.cjs +988 -66
  25. package/dist/next.d.cts +149 -6
  26. package/dist/next.d.ts +149 -6
  27. package/dist/next.js +391 -12
  28. package/dist/react.cjs +403 -75
  29. package/dist/react.d.cts +141 -33
  30. package/dist/react.d.ts +141 -33
  31. package/dist/react.js +7 -1
  32. package/dist/{resolve-36-Ng1H0.d.cts → resolve-BYL8jMg0.d.ts} +2 -2
  33. package/dist/{resolve-1rQntRBh.d.ts → resolve-Ra8-y2U-.d.cts} +2 -2
  34. package/dist/styles.css +149 -21
  35. package/dist/{types-CwBCPh6K.d.cts → types-C72FwzOd.d.cts} +71 -1
  36. package/dist/{types-CwBCPh6K.d.ts → types-C72FwzOd.d.ts} +71 -1
  37. package/dist/use-cache.cjs +9 -4
  38. package/dist/use-cache.d.cts +2 -2
  39. package/dist/use-cache.d.ts +2 -2
  40. package/dist/use-cache.js +5 -5
  41. package/package.json +4 -3
package/dist/next.js CHANGED
@@ -1,19 +1,31 @@
1
1
  import {
2
2
  ArticlePage,
3
+ Comments,
3
4
  DocsPage,
4
- ListPage
5
- } from "./chunk-LGW2KP4X.js";
5
+ HyleArticleView,
6
+ HyleCommentsFallback,
7
+ HyleCommentsView,
8
+ HyleListView,
9
+ ListPage,
10
+ parseListing,
11
+ stringsFor
12
+ } from "./chunk-S3LT6G4M.js";
6
13
  import {
7
14
  DEFAULT_REVALIDATE,
8
15
  fetchResolver,
9
16
  workspaceTags
10
- } from "./chunk-N4QYPO7S.js";
17
+ } from "./chunk-S7PCCEHP.js";
11
18
  import {
12
19
  Cp1ClientError,
20
+ checkBaseUrl,
21
+ cleanDisplayName,
13
22
  createHyleClient,
14
23
  createRevalidationCallbackRoute,
15
- listPublicationPaths
16
- } from "./chunk-EBNIKRQH.js";
24
+ engagementSigningKey,
25
+ listPublicationPaths,
26
+ readCapped,
27
+ signReaderAssertion
28
+ } from "./chunk-N7ZQUAGM.js";
17
29
  import {
18
30
  ASSET_CONTENT_TYPES,
19
31
  ASSET_FILE
@@ -87,11 +99,11 @@ function hylePage(options) {
87
99
  if (path === void 0) notFound();
88
100
  try {
89
101
  const cursor = options.paginate === "searchParams" ? validCursor((await searchParams)?.cursor) : void 0;
90
- const result = await resolve(path, locale, options.listLimit, cursor);
102
+ const result = await resolve(path, locale, options.listLimit, cursor, options.layout === "docs" ? "tree" : void 0);
91
103
  switch (result.kind) {
92
104
  case "article": {
93
105
  const props = { article: result, components: options.components, slots: options.slots, locale, toHref };
94
- return options.layout === "docs" ? /* @__PURE__ */ jsx(DocsPage, { ...props }) : /* @__PURE__ */ jsx(ArticlePage, { ...props });
106
+ return options.layout === "docs" ? /* @__PURE__ */ jsx(DocsPage, { ...props }) : /* @__PURE__ */ jsx(ArticlePage, { ...props, origin: options.siteOrigin, ...options.engagement ? { engagement: options.engagement } : {} });
95
107
  }
96
108
  case "list": {
97
109
  const list = options.list?.title ? { ...result, section: { ...result.section, title: options.list.title } } : result;
@@ -153,15 +165,21 @@ async function hyleSitemap(options) {
153
165
  // src/next/metadata.ts
154
166
  function hyleMetadata(options) {
155
167
  const resolve = resolverFor(options);
156
- return async function generateMetadata({ params }) {
168
+ return async function generateMetadata({ params, searchParams }) {
157
169
  const { path, locale, toHref } = routeContext(options, await params ?? {});
158
170
  if (path === void 0) return {};
159
171
  try {
160
- const result = await resolve(path, locale, options.listLimit);
172
+ const cursor = options.paginate === "searchParams" ? validCursor((await searchParams)?.cursor) : void 0;
173
+ const result = await resolve(path, locale, options.listLimit, cursor, options.layout === "docs" ? "tree" : void 0);
161
174
  if (result.kind === "list") {
162
- const title = options.list?.title || result.section.title;
175
+ const title = (options.list?.title || result.section.title) + (cursor ? ` - ${stringsFor(locale).older}` : "");
163
176
  const description2 = options.list?.description;
164
- return { title, ...description2 ? { description: description2 } : {}, openGraph: { title, ...description2 ? { description: description2 } : {} } };
177
+ return {
178
+ title,
179
+ ...description2 ? { description: description2 } : {},
180
+ alternates: { canonical: toHref(path) + (cursor ? `?cursor=${cursor}` : "") },
181
+ openGraph: { title, ...description2 ? { description: description2 } : {} }
182
+ };
165
183
  }
166
184
  if (result.kind !== "article") return {};
167
185
  const { publication: pub, alternates } = result;
@@ -172,7 +190,7 @@ function hyleMetadata(options) {
172
190
  ...description ? { description } : {},
173
191
  alternates: {
174
192
  canonical,
175
- ...alternates.length > 1 ? { languages: Object.fromEntries(alternates.map((a) => [a.locale, toHref(a.canonical_path, a.locale)])) } : {}
193
+ ...alternates.length > 1 ? { languages: { ...Object.fromEntries(alternates.map((a) => [a.locale, toHref(a.canonical_path, a.locale)])), "x-default": canonical } } : {}
176
194
  },
177
195
  openGraph: {
178
196
  type: "article",
@@ -404,9 +422,370 @@ function createAssetRoute(options) {
404
422
  }
405
423
  return { GET: (req, ctx) => serve(req, ctx, false), HEAD: (req, ctx) => serve(req, ctx, true) };
406
424
  }
425
+
426
+ // src/next/embed.tsx
427
+ import { unstable_rethrow as unstable_rethrow2 } from "next/navigation";
428
+
429
+ // src/next/engage.ts
430
+ var ENGAGE_CSRF_HEADER = "x-hyle-engage";
431
+ var DEFAULT_TIMEOUT_MS2 = 1e4;
432
+ var DEFAULT_SHARE_MS = 3e3;
433
+ var MAX_SHARED = 100;
434
+ var MAX_SHARED_BYTES = 8 * 1024 * 1024;
435
+ var MAX_SHARED_ENTRY_BYTES = 256 * 1024;
436
+ var MAX_BODY_BYTES = 20 * 1024;
437
+ var MAX_RESPONSE_BYTES = 4 * 1024 * 1024;
438
+ var MAX_COMMENT_CHARACTERS = 4e3;
439
+ var MAX_PATH_LENGTH2 = 1024;
440
+ var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
441
+ var CONTROL = /[\u0000-\u001f\u007f\\]/;
442
+ var HEADERS = { "Cache-Control": "no-store", "X-Content-Type-Options": "nosniff" };
443
+ var isSwitchedOff3 = (value) => {
444
+ const v = value?.trim().toLowerCase() ?? "";
445
+ return v !== "" && v !== "1" && v !== "true";
446
+ };
447
+ var json = (status, body, extra = {}) => new Response(JSON.stringify(body), { status, headers: { ...HEADERS, "Content-Type": "application/json; charset=utf-8", ...extra } });
448
+ var refuse = (status, code, extra = {}) => json(status, { error: { code } }, extra);
449
+ function isSitePath(value) {
450
+ if (typeof value !== "string" || value.length > MAX_PATH_LENGTH2 || !value.startsWith("/") || value.startsWith("//")) return false;
451
+ if (CONTROL.test(value) || /[?#]/.test(value)) return false;
452
+ return !value.split("/").some((segment) => segment === "." || segment === "..");
453
+ }
454
+ function match(segments) {
455
+ const [a, b, ...rest] = segments;
456
+ if (a === "session" && b === void 0) return { local: "session", action: () => "session", methods: ["GET"], rebuild: () => void 0 };
457
+ if (a === "comments" && b === void 0) {
458
+ return {
459
+ action: (m) => m === "GET" ? "comments.list" : "comments.create",
460
+ methods: ["GET", "POST"],
461
+ rebuild: (method, body, url) => {
462
+ if (method === "GET") {
463
+ const keys = [...url.searchParams.keys()];
464
+ const path = url.searchParams.get("path");
465
+ return keys.length === 1 && isSitePath(path) ? { upstream: "/comments", query: new URLSearchParams({ path }) } : void 0;
466
+ }
467
+ const clean = pick(body, ["path", "body", "parent_id"], ["path", "body"]);
468
+ if (!clean || !isSitePath(clean.path) || !isCommentText(clean.body)) return void 0;
469
+ if (clean.parent_id === null) delete clean.parent_id;
470
+ if (clean.parent_id !== void 0 && !(typeof clean.parent_id === "string" && UUID.test(clean.parent_id))) return void 0;
471
+ return { upstream: "/comments", body: clean };
472
+ }
473
+ };
474
+ }
475
+ if (a === "comments" && typeof b === "string" && UUID.test(b) && rest.length === 0) {
476
+ return {
477
+ action: (m) => m === "PATCH" ? "comments.edit" : "comments.delete",
478
+ methods: ["PATCH", "DELETE"],
479
+ rebuild: (method, body) => {
480
+ if (method === "DELETE") return body === void 0 ? { upstream: `/comments/${b}` } : void 0;
481
+ const clean = pick(body, ["body"], ["body"]);
482
+ return clean && isCommentText(clean.body) ? { upstream: `/comments/${b}`, body: clean } : void 0;
483
+ }
484
+ };
485
+ }
486
+ if (a === "reactions" && b === void 0) {
487
+ return {
488
+ action: (m) => m === "PUT" ? "reactions.add" : "reactions.remove",
489
+ methods: ["PUT", "DELETE"],
490
+ rebuild: (_method, body) => {
491
+ const type = body?.subject_type;
492
+ const clean = type === "article" ? pick(body, ["subject_type", "path"], ["subject_type", "path"]) : type === "comment" ? pick(body, ["subject_type", "comment_id"], ["subject_type", "comment_id"]) : void 0;
493
+ if (!clean) return void 0;
494
+ const valid = type === "article" ? isSitePath(clean.path) : typeof clean.comment_id === "string" && UUID.test(clean.comment_id);
495
+ return valid ? { upstream: "/reactions", body: clean } : void 0;
496
+ }
497
+ };
498
+ }
499
+ return void 0;
500
+ }
501
+ function pick(body, allowed, required) {
502
+ if (!body || Object.keys(body).some((k) => !allowed.includes(k)) || !required.every((k) => k in body)) return void 0;
503
+ return Object.fromEntries(allowed.filter((k) => k in body).map((k) => [k, body[k]]));
504
+ }
505
+ function isCommentText(value) {
506
+ return typeof value === "string" && value.trim().length > 0 && [...value].length <= MAX_COMMENT_CHARACTERS && !/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/.test(value);
507
+ }
508
+ function sameOriginProblem(req, write, allowedOrigins) {
509
+ const site = req.headers.get("sec-fetch-site");
510
+ if (site !== null && site !== "same-origin") return true;
511
+ if (!write) return false;
512
+ const origin = req.headers.get("origin");
513
+ if (origin === null) return true;
514
+ let parsed;
515
+ try {
516
+ parsed = new URL(origin);
517
+ } catch {
518
+ return true;
519
+ }
520
+ if (req.headers.get(ENGAGE_CSRF_HEADER) !== "1") return true;
521
+ if (allowedOrigins) return !allowedOrigins.some((o) => safeOrigin(o) === parsed.origin);
522
+ const host = req.headers.get("x-forwarded-host")?.split(",")[0]?.trim() || req.headers.get("host") || new URL(req.url).host;
523
+ const proto = req.headers.get("x-forwarded-proto")?.split(",")[0]?.trim().toLowerCase();
524
+ if (proto && proto !== parsed.protocol.slice(0, -1)) return true;
525
+ return parsed.host !== host;
526
+ }
527
+ var safeOrigin = (value) => {
528
+ try {
529
+ return new URL(value).origin;
530
+ } catch {
531
+ return void 0;
532
+ }
533
+ };
534
+ async function readBody(req, expected) {
535
+ if (!expected) return { kind: "ok", body: void 0 };
536
+ if (!/^application\/json(\s*;|$)/i.test(req.headers.get("content-type") ?? "")) return { kind: "refused", response: refuse(415, "UNSUPPORTED_MEDIA_TYPE") };
537
+ if (Number(req.headers.get("content-length")) > MAX_BODY_BYTES) return { kind: "refused", response: refuse(413, "PAYLOAD_TOO_LARGE") };
538
+ if (!req.body) return { kind: "refused", response: refuse(400, "VALIDATION_ERROR") };
539
+ const reader = req.body.getReader();
540
+ const chunks = [];
541
+ let total = 0;
542
+ for (; ; ) {
543
+ const { done, value } = await reader.read();
544
+ if (done) break;
545
+ total += value.byteLength;
546
+ if (total > MAX_BODY_BYTES) {
547
+ await reader.cancel().catch(() => {
548
+ });
549
+ return { kind: "refused", response: refuse(413, "PAYLOAD_TOO_LARGE") };
550
+ }
551
+ chunks.push(value);
552
+ }
553
+ try {
554
+ const parsed = JSON.parse(Buffer.concat(chunks).toString("utf8"));
555
+ if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) return { kind: "ok", body: parsed };
556
+ } catch {
557
+ }
558
+ return { kind: "refused", response: refuse(400, "VALIDATION_ERROR") };
559
+ }
560
+ var SUB_CONTROL = /[\u0000-\u001f\u007f-\u009f]/;
561
+ function validReader(r) {
562
+ if (!r || typeof r.sub !== "string" || typeof r.name !== "string") return null;
563
+ if (r.sub.length < 1 || [...r.sub].length > 255 || SUB_CONTROL.test(r.sub)) return null;
564
+ const name = cleanDisplayName(r.name);
565
+ return name === void 0 ? null : { sub: r.sub, name };
566
+ }
567
+ function relayFailure(status, retryAfter) {
568
+ if (status === 400) return refuse(400, "VALIDATION_ERROR");
569
+ if (status === 404) return refuse(404, "NOT_FOUND");
570
+ if (status === 409) return refuse(409, "INVALID_TRANSITION");
571
+ if (status === 413) return refuse(413, "PAYLOAD_TOO_LARGE");
572
+ if (status === 429) {
573
+ const seconds = Math.min(3600, Math.max(1, Math.trunc(Number(retryAfter)) || 60));
574
+ return refuse(429, "RATE_LIMITED", { "Retry-After": String(seconds) });
575
+ }
576
+ return refuse(502, "UPSTREAM_ERROR");
577
+ }
578
+ function createEngagementRoute(options) {
579
+ let ready;
580
+ const fetchImpl = options.fetch ?? fetch;
581
+ const cache = /* @__PURE__ */ new Map();
582
+ let cacheBytes = 0;
583
+ const clearCache = () => {
584
+ cache.clear();
585
+ cacheBytes = 0;
586
+ };
587
+ async function listing(viewer, call) {
588
+ if (!viewer) return call(void 0);
589
+ let out = await call(viewer.sign("read"));
590
+ if (out.status === 401) out = await call(viewer.sign("read"));
591
+ if (out.status !== 401 && out.status !== 404 && !(out.status === 429 && out.throttle === "viewer")) return out;
592
+ return { ...await call(void 0), noShare: true };
593
+ }
594
+ function shared(key, call) {
595
+ const ttl = options.cacheTtlMs ?? DEFAULT_SHARE_MS;
596
+ if (ttl <= 0) return call();
597
+ const hit = cache.get(key);
598
+ if (hit && Date.now() - hit.at < ttl) {
599
+ cache.delete(key);
600
+ cache.set(key, hit);
601
+ return hit.result;
602
+ }
603
+ if (hit) forget(key, hit);
604
+ const entry = { at: Date.now(), result: call(), bytes: 0 };
605
+ cache.set(key, entry);
606
+ entry.result.then(
607
+ (o) => {
608
+ if (cache.get(key) !== entry) return;
609
+ if (o.status !== 200 && o.status !== 404 || o.noShare || o.text.length > MAX_SHARED_ENTRY_BYTES) return forget(key, entry);
610
+ entry.bytes = o.text.length;
611
+ cacheBytes += entry.bytes;
612
+ while ((cacheBytes > MAX_SHARED_BYTES || cache.size > MAX_SHARED) && cache.size > 0) {
613
+ const oldest = cache.entries().next().value;
614
+ forget(oldest[0], oldest[1]);
615
+ }
616
+ },
617
+ () => forget(key, entry)
618
+ );
619
+ return entry.result;
620
+ }
621
+ function forget(key, entry) {
622
+ if (cache.get(key) !== entry) return;
623
+ cache.delete(key);
624
+ cacheBytes -= entry.bytes;
625
+ }
626
+ function configured() {
627
+ if (ready !== void 0) return ready;
628
+ try {
629
+ const baseUrl = options.baseUrl?.trim() ?? "";
630
+ checkBaseUrl(baseUrl);
631
+ if (!options.token?.trim() || !options.workspaceId?.trim() || !options.signingKey) throw new TypeError("not provisioned");
632
+ ready = { base: baseUrl.replace(/\/+$/, ""), key: engagementSigningKey(options.signingKey.trim()) };
633
+ } catch {
634
+ ready = null;
635
+ }
636
+ return ready;
637
+ }
638
+ async function reader(req, config) {
639
+ try {
640
+ const found = validReader(await options.getReader(req));
641
+ if (!found) return null;
642
+ const claims = { sub: found.sub, name: found.name, workspace: options.workspaceId.trim() };
643
+ const sign = (scope) => signReaderAssertion(config.key, claims, void 0, scope);
644
+ return { reader: found, assertion: sign(), sign };
645
+ } catch {
646
+ return null;
647
+ }
648
+ }
649
+ async function handle(req, ctx) {
650
+ const env = options.env ?? process.env;
651
+ if (isSwitchedOff3(env.HYLE_ENGAGE_ENABLED) || isSwitchedOff3(env.HYLE_CONTENT_ENABLED)) return refuse(404, "NOT_FOUND");
652
+ const config = configured();
653
+ const route = match((await ctx.params).path ?? []);
654
+ if (!config || !route) return refuse(404, "NOT_FOUND");
655
+ if (!route.methods.includes(req.method)) return refuse(405, "METHOD_NOT_ALLOWED", { Allow: route.methods.join(", ") });
656
+ const write = req.method !== "GET";
657
+ if (sameOriginProblem(req, write, options.allowedOrigins)) return refuse(403, "FORBIDDEN");
658
+ if (options.onRequest) {
659
+ try {
660
+ const early = await options.onRequest(req, { action: route.action(req.method) });
661
+ if (early instanceof Response) {
662
+ const headers = new Headers(early.headers);
663
+ headers.set("cache-control", "no-store");
664
+ return new Response(early.body, { status: early.status, headers });
665
+ }
666
+ } catch {
667
+ return refuse(502, "UPSTREAM_ERROR");
668
+ }
669
+ }
670
+ if (route.local === "session") {
671
+ const who = await reader(req, config);
672
+ return json(200, { data: { reader: who ? { name: who.reader.name } : null } });
673
+ }
674
+ let assertion;
675
+ let viewer = null;
676
+ if (route.action(req.method) === "comments.list") viewer = await reader(req, config);
677
+ if (write) {
678
+ const who = await reader(req, config);
679
+ if (!who) return refuse(401, "UNAUTHENTICATED");
680
+ assertion = who.assertion;
681
+ }
682
+ const url = new URL(req.url);
683
+ const hasBody = write && !(req.method === "DELETE" && (await ctx.params).path?.[0] === "comments");
684
+ const body = await readBody(req, hasBody);
685
+ if (body.kind === "refused") return body.response;
686
+ const built = route.rebuild(req.method, body.body, url);
687
+ if (!built) return refuse(400, "VALIDATION_ERROR");
688
+ const baseHeaders = new Headers({ authorization: `Bearer ${options.token.trim()}`, accept: "application/json" });
689
+ if (built.body) baseHeaders.set("content-type", "application/json");
690
+ const target = `${config.base}/cp1/engage${built.upstream}${built.query ? `?${built.query}` : ""}`;
691
+ const call = async (withAssertion = assertion) => {
692
+ const headers = new Headers(baseHeaders);
693
+ if (withAssertion) headers.set("hyle-reader-assertion", withAssertion);
694
+ const res = await fetchImpl(target, {
695
+ method: req.method,
696
+ headers,
697
+ ...built.body ? { body: JSON.stringify(built.body) } : {},
698
+ redirect: "error",
699
+ signal: AbortSignal.timeout(options.timeoutMs ?? DEFAULT_TIMEOUT_MS2)
700
+ });
701
+ return { status: res.status, ok: res.ok, text: await readCapped(res, MAX_RESPONSE_BYTES), retryAfter: res.headers.get("retry-after"), throttle: res.headers.get("hyle-throttle") };
702
+ };
703
+ try {
704
+ const out = route.action(req.method) === "comments.list" ? await shared(`${viewer?.reader.sub ?? ""}
705
+ ${built.query.toString()}`, () => listing(viewer, call)) : await call();
706
+ if (!out.ok) return relayFailure(out.status, out.retryAfter);
707
+ if (write) clearCache();
708
+ const data = JSON.parse(out.text).data;
709
+ return typeof data === "object" && data !== null ? json(out.status === 201 ? 201 : 200, { data }) : refuse(502, "UPSTREAM_ERROR");
710
+ } catch {
711
+ return refuse(502, "UPSTREAM_ERROR");
712
+ }
713
+ }
714
+ return { GET: handle, POST: handle, PATCH: handle, PUT: handle, DELETE: handle };
715
+ }
716
+
717
+ // src/next/embed.tsx
718
+ import { jsx as jsx2 } from "react/jsx-runtime";
719
+ async function resolveEmbed(options, run) {
720
+ try {
721
+ return { result: await run() };
722
+ } catch (error) {
723
+ if (isRejectedRequest(error)) return {};
724
+ console.error(`hyle: ${error instanceof Error ? error.name : "UnknownError"}`);
725
+ return { failure: options.onError ? options.onError(error) : null };
726
+ }
727
+ }
728
+ async function HyleList({ options, section, limit = 5, locale, layout, title, headingLevel, moreHref }) {
729
+ const resolve = resolverFor(options);
730
+ const route = routeContext(locale ? { ...options, locale } : options, {});
731
+ const path = sitePathFrom(route.basePath, section && section !== "posts" ? [section] : void 0);
732
+ if (path === void 0) return null;
733
+ const { result, failure } = await resolveEmbed(options, () => resolve(path, route.locale, limit));
734
+ if (failure !== void 0) return failure;
735
+ return /* @__PURE__ */ jsx2(HyleListView, { items: result?.kind === "list" ? result.items : [], layout, title, headingLevel, moreHref, components: options.components, slots: options.slots, locale: route.locale, toHref: route.toHref });
736
+ }
737
+ async function HyleArticle({ options, path, locale, headingLevel }) {
738
+ if (!isSitePath(path)) return null;
739
+ const resolve = resolverFor(options);
740
+ const route = routeContext(locale ? { ...options, locale } : options, {});
741
+ const { result, failure } = await resolveEmbed(options, () => resolve(path, route.locale));
742
+ if (failure !== void 0) return failure;
743
+ if (result?.kind !== "article") return null;
744
+ return /* @__PURE__ */ jsx2(HyleArticleView, { article: result, headingLevel, components: options.components, slots: options.slots, locale: route.locale, toHref: route.toHref });
745
+ }
746
+ var MAX_LISTING_BYTES = 4 * 1024 * 1024;
747
+ var COMMENTS_TIMEOUT_MS = 1e4;
748
+ async function HyleComments({ options, path, revalidate = 60, interactive }) {
749
+ checkBaseUrl(options.baseUrl);
750
+ if (!options.token) throw new TypeError("token is required");
751
+ if (!isSitePath(path)) return null;
752
+ const locale = options.locale ?? "en";
753
+ let listing;
754
+ let fetchedAt;
755
+ try {
756
+ const init = {
757
+ headers: { authorization: `Bearer ${options.token}`, accept: "application/json" },
758
+ redirect: "error",
759
+ signal: AbortSignal.timeout(COMMENTS_TIMEOUT_MS),
760
+ next: { revalidate }
761
+ };
762
+ const res = await fetch(`${options.baseUrl.replace(/\/+$/, "")}/cp1/engage/comments?${new URLSearchParams({ path })}`, init);
763
+ if (!res.ok) {
764
+ if (res.status !== 404) console.error(`hyle: comments answered HTTP ${res.status}`);
765
+ return null;
766
+ }
767
+ listing = parseListing(JSON.parse(await readCapped(res, MAX_LISTING_BYTES)).data);
768
+ const date = Date.parse(res.headers.get("date") ?? "");
769
+ fetchedAt = Number.isFinite(date) ? date : void 0;
770
+ } catch (error) {
771
+ unstable_rethrow2(error);
772
+ console.error(`hyle: ${error instanceof Error ? error.name : "UnknownError"}`);
773
+ return null;
774
+ }
775
+ if (!listing) return null;
776
+ if (!interactive) return /* @__PURE__ */ jsx2(HyleCommentsView, { listing, locale });
777
+ const config = interactive === true ? {} : interactive;
778
+ return /* @__PURE__ */ jsx2("div", { className: "hyle hyle-embed", children: /* @__PURE__ */ jsx2(Comments, { path, endpoint: config.endpoint ?? "/api/hyle/engage", signInHref: config.signInHref, locale, labels: stringsFor(locale).comments, initial: listing, initialAt: fetchedAt }) });
779
+ }
407
780
  export {
781
+ ENGAGE_CSRF_HEADER,
782
+ HyleArticle,
783
+ HyleComments,
784
+ HyleCommentsFallback,
785
+ HyleList,
408
786
  MOUNTS_MAX_STALE_MS,
409
787
  createAssetRoute,
788
+ createEngagementRoute,
410
789
  createRevalidateRoute,
411
790
  fetchResolver,
412
791
  hyleMetadata,