@tdacorp/hyle-sdk 0.17.0 → 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.
Files changed (86) hide show
  1. package/README.md +155 -28
  2. package/dist/check-routes-bin.js +38 -13
  3. package/dist/chunk-56Y24XBV.js +840 -0
  4. package/dist/{chunk-MGSUQBDW.js → chunk-75JFLML4.js} +176 -14
  5. package/dist/chunk-HJX57NLI.js +1105 -0
  6. package/dist/chunk-K5VDLROQ.js +145 -0
  7. package/dist/{chunk-BUJFMR3M.js → chunk-QVYQM5R2.js} +15 -6
  8. package/dist/chunk-U74B7AUG.js +398 -0
  9. package/dist/{chunk-6VOHFFA5.js → chunk-X2TLYM7Y.js} +2 -2
  10. package/dist/client-41fU6OY2.d.cts +201 -0
  11. package/dist/client-LwzHwqpM.d.ts +201 -0
  12. package/dist/code-copy.cjs +72 -0
  13. package/dist/code-copy.d.cts +15 -0
  14. package/dist/code-copy.d.ts +15 -0
  15. package/dist/code-copy.js +48 -0
  16. package/dist/comments.cjs +728 -275
  17. package/dist/comments.d.cts +66 -3
  18. package/dist/comments.d.ts +66 -3
  19. package/dist/comments.js +409 -326
  20. package/dist/{diagram-viewer-FJPED4SN.js → diagram-viewer-XY3CG75U.js} +62 -21
  21. package/dist/{embed-BmdwA2G9.d.cts → embed-BUFRQboD.d.ts} +2 -2
  22. package/dist/{embed-DNTZ2UXv.d.ts → embed-CYt-q13P.d.cts} +2 -2
  23. package/dist/fragment-alias.cjs +51 -0
  24. package/dist/fragment-alias.d.cts +7 -0
  25. package/dist/fragment-alias.d.ts +7 -0
  26. package/dist/fragment-alias.js +27 -0
  27. package/dist/html.cjs +881 -0
  28. package/dist/html.d.cts +20 -0
  29. package/dist/html.d.ts +20 -0
  30. package/dist/html.js +45 -0
  31. package/dist/index.cjs +181 -14
  32. package/dist/index.d.cts +14 -62
  33. package/dist/index.d.ts +14 -62
  34. package/dist/index.js +11 -1
  35. package/dist/{labels-nmukKYgL.d.ts → labels-CrA-iqTN.d.cts} +9 -0
  36. package/dist/{labels-nmukKYgL.d.cts → labels-CrA-iqTN.d.ts} +9 -0
  37. package/dist/mermaid-diagram.cjs +401 -125
  38. package/dist/mermaid-diagram.d.cts +23 -7
  39. package/dist/mermaid-diagram.d.ts +23 -7
  40. package/dist/mermaid-diagram.js +204 -51
  41. package/dist/mermaid-image.cjs +134 -60
  42. package/dist/mermaid-image.d.cts +4 -3
  43. package/dist/mermaid-image.d.ts +4 -3
  44. package/dist/mermaid-image.js +27 -28
  45. package/dist/next.cjs +627 -264
  46. package/dist/next.d.cts +11 -8
  47. package/dist/next.d.ts +11 -8
  48. package/dist/next.js +39 -12
  49. package/dist/print-coordinator.cjs +157 -0
  50. package/dist/print-coordinator.d.cts +27 -0
  51. package/dist/print-coordinator.d.ts +27 -0
  52. package/dist/print-coordinator.js +83 -0
  53. package/dist/react.cjs +556 -226
  54. package/dist/react.d.cts +136 -29
  55. package/dist/react.d.ts +136 -29
  56. package/dist/react.js +23 -3
  57. package/dist/reactions.cjs +653 -0
  58. package/dist/reactions.d.cts +27 -0
  59. package/dist/reactions.d.ts +27 -0
  60. package/dist/reactions.js +364 -0
  61. package/dist/{resolve-Ae7UFjsQ.d.ts → resolve-BjAK0k_Y.d.ts} +2 -2
  62. package/dist/{resolve-euZ4-aC9.d.cts → resolve-eI1muCKL.d.cts} +2 -2
  63. package/dist/revalidation-callback-BQl77tQR.d.cts +75 -0
  64. package/dist/revalidation-callback-BQl77tQR.d.ts +75 -0
  65. package/dist/sanitize-ijiWjEm9.d.cts +23 -0
  66. package/dist/sanitize-ijiWjEm9.d.ts +23 -0
  67. package/dist/styles.css +96 -25
  68. package/dist/toc-spy.cjs +59 -0
  69. package/dist/toc-spy.d.cts +15 -0
  70. package/dist/toc-spy.d.ts +15 -0
  71. package/dist/toc-spy.js +35 -0
  72. package/dist/{types-Czt887Iv.d.cts → types-3F0wqD-o.d.cts} +26 -2
  73. package/dist/{types-Czt887Iv.d.ts → types-3F0wqD-o.d.ts} +26 -2
  74. package/dist/use-cache.cjs +37 -11
  75. package/dist/use-cache.d.cts +12 -5
  76. package/dist/use-cache.d.ts +12 -5
  77. package/dist/use-cache.js +7 -7
  78. package/dist/youtube-facade.cjs +50 -0
  79. package/dist/youtube-facade.d.cts +17 -0
  80. package/dist/youtube-facade.d.ts +17 -0
  81. package/dist/youtube-facade.js +26 -0
  82. package/package.json +16 -3
  83. package/dist/chunk-DMK4XQLU.js +0 -1556
  84. package/dist/chunk-PJMJMP66.js +0 -63
  85. package/dist/revalidation-callback-D7Ms_Puz.d.cts +0 -42
  86. package/dist/revalidation-callback-D7Ms_Puz.d.ts +0 -42
@@ -0,0 +1,20 @@
1
+ export { H as HastLimitError } from './sanitize-ijiWjEm9.cjs';
2
+ import 'hast';
3
+
4
+ interface HastToHtmlOptions {
5
+ /** The article's own absolute http(s) URL: relative links, images and `#fragments` are resolved against it. */
6
+ readonly baseUrl: string;
7
+ /** As in `HastContent`: a leading body h1 that repeats it is dropped. */
8
+ readonly title?: string | undefined;
9
+ /** As in `HastContent`: a leading body paragraph that starts with it is dropped. */
10
+ readonly description?: string | null | undefined;
11
+ /** Language of the callout titles and checkbox names. */
12
+ readonly locale?: string | undefined;
13
+ }
14
+ /**
15
+ * @throws TypeError when `baseUrl` is not an absolute http(s) URL.
16
+ * @throws HastLimitError when the tree is over the sanitizer's caps, so a feed never silently publishes an empty body.
17
+ */
18
+ declare function hastToHtml(tree: unknown, { baseUrl, title, description, locale }: HastToHtmlOptions): string;
19
+
20
+ export { type HastToHtmlOptions, hastToHtml };
package/dist/html.d.ts ADDED
@@ -0,0 +1,20 @@
1
+ export { H as HastLimitError } from './sanitize-ijiWjEm9.js';
2
+ import 'hast';
3
+
4
+ interface HastToHtmlOptions {
5
+ /** The article's own absolute http(s) URL: relative links, images and `#fragments` are resolved against it. */
6
+ readonly baseUrl: string;
7
+ /** As in `HastContent`: a leading body h1 that repeats it is dropped. */
8
+ readonly title?: string | undefined;
9
+ /** As in `HastContent`: a leading body paragraph that starts with it is dropped. */
10
+ readonly description?: string | null | undefined;
11
+ /** Language of the callout titles and checkbox names. */
12
+ readonly locale?: string | undefined;
13
+ }
14
+ /**
15
+ * @throws TypeError when `baseUrl` is not an absolute http(s) URL.
16
+ * @throws HastLimitError when the tree is over the sanitizer's caps, so a feed never silently publishes an empty body.
17
+ */
18
+ declare function hastToHtml(tree: unknown, { baseUrl, title, description, locale }: HastToHtmlOptions): string;
19
+
20
+ export { type HastToHtmlOptions, hastToHtml };
package/dist/html.js ADDED
@@ -0,0 +1,45 @@
1
+ import {
2
+ HastLimitError,
3
+ mermaidSource,
4
+ sanitizeHast,
5
+ stringsFor
6
+ } from "./chunk-56Y24XBV.js";
7
+ import "./chunk-67IOIAVW.js";
8
+
9
+ // src/html.ts
10
+ import { toHtml } from "hast-util-to-html";
11
+ var el = (tagName, properties, children) => ({ type: "element", tagName, properties, children });
12
+ var text = (value) => ({ type: "text", value });
13
+ var URL_ATTRS = ["href", "src"];
14
+ function forFeed(node, base, s) {
15
+ if (node.type !== "element") return node;
16
+ if (node.tagName === "iframe") {
17
+ const source = mermaidSource(String(node.properties.srcdoc)) ?? "";
18
+ return el("pre", {}, [el("code", { className: ["language-mermaid"] }, [text(source)])]);
19
+ }
20
+ const children = node.children.map((child) => forFeed(child, base, s));
21
+ if (node.tagName === "callout") {
22
+ const kind = String(node.properties.kind);
23
+ return el("aside", { className: ["hyle-callout"], dataKind: kind, role: "note" }, [
24
+ el("div", {}, [el("p", { className: ["ttl"] }, [text(s[kind])]), el("div", { className: ["bd"] }, children)])
25
+ ]);
26
+ }
27
+ const { dataEmbed: _embed, dataLight: _light, dataDark: _dark, ...properties } = node.properties;
28
+ for (const key of URL_ATTRS) {
29
+ const value = properties[key];
30
+ if (typeof value === "string") properties[key] = new URL(value, base).href;
31
+ }
32
+ if (node.tagName === "input") properties.ariaLabel = properties.checked ? s.done : s.notDone;
33
+ return el(node.tagName, properties, children);
34
+ }
35
+ function hastToHtml(tree, { baseUrl, title, description, locale }) {
36
+ const base = new URL(baseUrl);
37
+ if (base.protocol !== "https:" && base.protocol !== "http:") throw new TypeError("hastToHtml: baseUrl must be an absolute http(s) URL");
38
+ const s = stringsFor(locale);
39
+ const root = sanitizeHast(tree, title, description);
40
+ return toHtml({ type: "root", children: root.children.map((child) => forFeed(child, base, s)) });
41
+ }
42
+ export {
43
+ HastLimitError,
44
+ hastToHtml
45
+ };
package/dist/index.cjs CHANGED
@@ -23,9 +23,11 @@ __export(src_exports, {
23
23
  CACHE_TAG_PATTERN: () => CACHE_TAG_PATTERN,
24
24
  Cp1ClientError: () => Cp1ClientError,
25
25
  DeliveryDedupe: () => DeliveryDedupe,
26
+ MAX_PUSH_BODY_BYTES: () => MAX_PUSH_BODY_BYTES,
26
27
  SDK_OWN_RESERVED: () => SDK_OWN_RESERVED,
27
28
  checkRoutes: () => checkRoutes,
28
29
  createHyleClient: () => createHyleClient,
30
+ createPushRoute: () => createPushRoute,
29
31
  createRevalidationCallbackRoute: () => createRevalidationCallbackRoute,
30
32
  engagementPublicKey: () => engagementPublicKey,
31
33
  formatReport: () => formatReport,
@@ -34,9 +36,12 @@ __export(src_exports, {
34
36
  isValidCacheTag: () => isValidCacheTag,
35
37
  listPublicationPaths: () => listPublicationPaths,
36
38
  normalizeRoute: () => normalizeRoute,
39
+ parseCommentEvent: () => parseCommentEvent,
37
40
  parseSignatureHeader: () => parseSignatureHeader,
38
41
  reservedFor: () => reservedFor,
42
+ resyncPath: () => resyncPath,
39
43
  routeMatches: () => routeMatches,
44
+ staleAfterResync: () => staleAfterResync,
40
45
  syncHostReserved: () => syncHostReserved,
41
46
  verifyHyleSignature: () => verifyHyleSignature
42
47
  });
@@ -67,6 +72,18 @@ var Cp1ClientError = class extends Error {
67
72
  };
68
73
 
69
74
  // src/client.ts
75
+ var RENDERER_VERSION = "4";
76
+ function applyCredential(headers, credential, method, url) {
77
+ if (!credential.auth) {
78
+ headers.set("authorization", `Bearer ${credential.token}`);
79
+ return void 0;
80
+ }
81
+ const { workspaceId } = credential;
82
+ return credential.auth({ method, url }).then((extra) => {
83
+ for (const [name, value] of Object.entries(extra)) headers.set(name, value);
84
+ headers.set("cp-workspace", workspaceId);
85
+ });
86
+ }
70
87
  var DEFAULT_TIMEOUT_MS = 1e4;
71
88
  var DEFAULT_MAX_RESPONSE_BYTES = 5 * 1024 * 1024;
72
89
  var LOOPBACK = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "[::1]"]);
@@ -108,14 +125,16 @@ function checkBaseUrl(baseUrl, allowInsecureHttp) {
108
125
  }
109
126
  function createHyleClient(options) {
110
127
  checkBaseUrl(options.baseUrl, options.allowInsecureHttp);
111
- if (!options.token) throw new TypeError("token is required");
128
+ if (!options.auth && !options.token) throw new TypeError("token is required");
112
129
  const base = options.baseUrl.replace(/\/+$/, "");
113
130
  const fetchImpl = options.fetch ?? fetch;
114
131
  async function get(pathname, query, init) {
115
132
  const url = new URL(`${base}${pathname}`);
116
133
  url.search = query.toString();
117
134
  const headers = new Headers(init?.headers);
118
- headers.set("authorization", `Bearer ${options.token}`);
135
+ headers.set("cp-renderer-version", RENDERER_VERSION);
136
+ const applied = applyCredential(headers, options, "GET", url.toString());
137
+ if (applied) await applied;
119
138
  const timeout = AbortSignal.timeout(options.timeoutMs ?? DEFAULT_TIMEOUT_MS);
120
139
  const signal = init?.signal ? AbortSignal.any([init.signal, timeout]) : timeout;
121
140
  const res = await fetchImpl(url.toString(), { ...init, method: "GET", headers, redirect: "error", signal });
@@ -155,16 +174,28 @@ function createHyleClient(options) {
155
174
  if (data?.cp === 1 && data.kind === "mounts" && isMounts(data)) return data;
156
175
  throw failure(reply);
157
176
  }
177
+ async function pushPosts(opts) {
178
+ if (!/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/.test(opts.section)) throw new TypeError("section must be a section slug");
179
+ const query = new URLSearchParams();
180
+ if (opts.cursor !== void 0) query.set("cursor", opts.cursor);
181
+ const reply = await get(`/cp1/read/sections/${opts.section}/posts`, query, opts.init);
182
+ const data = reply.parsed?.data;
183
+ if (data?.cp === 1 && data.kind === "push_posts" && Array.isArray(data.posts) && typeof data.complete === "boolean") return data;
184
+ throw failure(reply);
185
+ }
158
186
  async function asset(file, opts = {}) {
159
187
  if (!ASSET_FILE.test(file)) throw new TypeError("asset file must be <uuid>[.<ext>]");
160
- const headers = new Headers({ authorization: `Bearer ${options.token}` });
188
+ const url = `${base}/cp1/read/assets/${file}`;
189
+ const headers = new Headers();
190
+ const applied = applyCredential(headers, options, "GET", url);
191
+ if (applied) await applied;
161
192
  for (const name of ["range", "if-range", "if-none-match"]) {
162
193
  const value = opts.headers?.[name];
163
194
  if (value) headers.set(name, value);
164
195
  }
165
- return fetchImpl(`${base}/cp1/read/assets/${file}`, { method: "GET", headers, redirect: "error", signal: AbortSignal.timeout(opts.timeoutMs ?? options.timeoutMs ?? DEFAULT_TIMEOUT_MS) });
196
+ return fetchImpl(url, { method: "GET", headers, redirect: "error", signal: AbortSignal.timeout(opts.timeoutMs ?? options.timeoutMs ?? DEFAULT_TIMEOUT_MS) });
166
197
  }
167
- return { resolve, mounts, asset };
198
+ return { resolve, mounts, pushPosts, asset };
168
199
  }
169
200
 
170
201
  // src/host-sync.ts
@@ -174,21 +205,20 @@ var MAX_RESPONSE_BYTES = 1024 * 1024;
174
205
  var PATH = "/cp1/control/workspace/host-reserved-paths";
175
206
  async function syncHostReserved(input) {
176
207
  checkBaseUrl(input.baseUrl, input.allowInsecureHttp);
177
- if (!input.token.startsWith(CONTROL_TOKEN_PREFIX)) {
208
+ if (input.token !== void 0 && !input.token.startsWith(CONTROL_TOKEN_PREFIX)) {
178
209
  throw new TypeError("syncing needs a control credential (hyle_tc_...); a target token is read-only and cannot write");
179
210
  }
180
211
  const fetchImpl = input.fetch ?? fetch;
181
- const res = await fetchImpl(`${input.baseUrl.replace(/\/+$/, "")}${PATH}`, {
212
+ const url = `${input.baseUrl.replace(/\/+$/, "")}${PATH}`;
213
+ const headers = new Headers({ "content-type": "application/json", "idempotency-key": `sync-${crypto.randomUUID()}` });
214
+ await applyCredential(headers, input.auth ? { auth: input.auth, workspaceId: input.workspaceId } : { token: input.token }, "PUT", url);
215
+ headers.set("cp-workspace", input.workspaceId);
216
+ const res = await fetchImpl(url, {
182
217
  method: "PUT",
183
218
  // redirect "error": the bearer token must never follow a redirect to another host.
184
219
  redirect: "error",
185
220
  signal: AbortSignal.timeout(input.timeoutMs ?? DEFAULT_TIMEOUT_MS2),
186
- headers: {
187
- authorization: `Bearer ${input.token}`,
188
- "content-type": "application/json",
189
- "cp-workspace": input.workspaceId,
190
- "idempotency-key": `sync-${crypto.randomUUID()}`
191
- },
221
+ headers,
192
222
  body: JSON.stringify({ paths: input.paths, host: input.host, build_id: input.buildId })
193
223
  });
194
224
  const text = await readCapped(res, MAX_RESPONSE_BYTES);
@@ -281,6 +311,35 @@ function isValidCacheTag(tag) {
281
311
  // src/revalidation-callback.ts
282
312
  var MAX_BODY_BYTES = 65536;
283
313
  var MAX_TAGS = 1e3;
314
+ var HOOK_WAIT_MS = 3e3;
315
+ var COMMENT_EVENT_TYPES = ["comment.held", "comment.reply", "comment.approved", "comment.hidden"];
316
+ var isRecord = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
317
+ var isText = (v) => typeof v === "string" && v.length > 0;
318
+ var isTextOrNull = (v) => v === null || isText(v);
319
+ var isEventPath = (v) => typeof v === "string" && v.startsWith("/") && !v.startsWith("//") && v.length <= 2048 && !/[\\\u0000-\u001f\u007f]/.test(v);
320
+ function parseCommentEvent(payload) {
321
+ if (!isRecord(payload) || payload.cp !== 1 || !isRecord(payload.data)) return void 0;
322
+ const type = COMMENT_EVENT_TYPES.find((t) => t === payload.type);
323
+ const { id, created_at, workspace_id, event_id, data } = payload;
324
+ if (!type || !isText(id) || !isText(created_at) || !isText(workspace_id) || !isText(event_id)) return void 0;
325
+ const { comment_id, parent_comment_id, publication_path, reader_sub, parent_reader_sub, status } = data;
326
+ if (!isText(comment_id) || !isTextOrNull(parent_comment_id) || !isEventPath(publication_path) || !isTextOrNull(reader_sub) || !isTextOrNull(parent_reader_sub)) return void 0;
327
+ if (status !== "held" && status !== "visible" && status !== "hidden") return void 0;
328
+ return { cp: 1, id, type, created_at, workspace_id, event_id, data: { comment_id, parent_comment_id, publication_path, reader_sub, parent_reader_sub, status } };
329
+ }
330
+ async function runHook(hook, event) {
331
+ let timer;
332
+ try {
333
+ await Promise.race([
334
+ Promise.resolve().then(() => hook(event)),
335
+ new Promise((_, reject) => timer = setTimeout(() => reject(new Error("timeout")), HOOK_WAIT_MS))
336
+ ]);
337
+ } catch {
338
+ console.error(`hyle: onCommentEvent failed or timed out for ${event.type} ${event.id}`);
339
+ } finally {
340
+ clearTimeout(timer);
341
+ }
342
+ }
284
343
  function createRevalidationCallbackRoute(options) {
285
344
  const dedupe = new DeliveryDedupe(options.dedupeCapacity);
286
345
  return {
@@ -315,7 +374,7 @@ function createRevalidationCallbackRoute(options) {
315
374
  if (body.workspace_id !== options.workspaceId) {
316
375
  return okResponse(0);
317
376
  }
318
- const deliveryId = req.headers.get("hyle-delivery-id");
377
+ const deliveryId = typeof body.id === "string" ? body.id : void 0;
319
378
  if (deliveryId && dedupe.has(deliveryId)) {
320
379
  return okResponse(0);
321
380
  }
@@ -330,6 +389,9 @@ function createRevalidationCallbackRoute(options) {
330
389
  return new Response(null, { status: 500 });
331
390
  }
332
391
  if (deliveryId) dedupe.add(deliveryId);
392
+ const hook = options.onCommentEvent;
393
+ const event = hook && parseCommentEvent(body);
394
+ if (hook && event) await runHook(hook, event);
333
395
  return okResponse(purged);
334
396
  }
335
397
  };
@@ -360,6 +422,106 @@ function okResponse(purged) {
360
422
  });
361
423
  }
362
424
 
425
+ // src/push.ts
426
+ var MAX_PUSH_BODY_BYTES = 2 * 1024 * 1024;
427
+ var seqKey = (sectionId, publicationId) => `${sectionId}:${publicationId}`;
428
+ var TYPES = /* @__PURE__ */ new Set(["post.published", "post.updated", "post.unpublished", "post.deleted", "post.moved", "section.moved"]);
429
+ var WITH_POST = /* @__PURE__ */ new Set(["post.published", "post.updated", "post.moved"]);
430
+ var ok = (applied) => new Response(JSON.stringify({ ok: true, applied }), { status: 200, headers: { "Content-Type": "application/json; charset=utf-8", "Cache-Control": "no-store" } });
431
+ function parseEvent(body) {
432
+ if (typeof body !== "object" || body === null || Array.isArray(body)) return void 0;
433
+ const e = body;
434
+ if (e.type === "webhook.test") return "ignore";
435
+ if (e.schema !== "hyle.push/1") return "ignore";
436
+ const section = e.section;
437
+ const hasPost = typeof e.post === "object" && e.post !== null;
438
+ if (typeof e.type !== "string" || !TYPES.has(e.type) || typeof e.event_id !== "string" || typeof e.seq !== "number" || !Number.isSafeInteger(e.seq) || typeof section?.id !== "string" || typeof section.site_path !== "string" || hasPost !== WITH_POST.has(e.type) || e.type !== "section.moved" && typeof e.publication_id !== "string") return void 0;
439
+ return e;
440
+ }
441
+ function createPushRoute(options) {
442
+ const secrets = typeof options.secret === "string" ? [options.secret] : options.secret;
443
+ if (secrets.length === 0 || secrets.some((s) => !s)) throw new TypeError("secret is required");
444
+ return {
445
+ async POST(req) {
446
+ const declared = Number(req.headers.get("content-length"));
447
+ if (Number.isFinite(declared) && declared > MAX_PUSH_BODY_BYTES) return new Response(null, { status: 413 });
448
+ const raw = await readCapped3(req);
449
+ if (raw === void 0) return new Response(null, { status: 413 });
450
+ const verified = verifyHyleSignature({
451
+ header: req.headers.get("hyle-signature"),
452
+ rawBody: raw,
453
+ secrets,
454
+ ...options.toleranceSeconds !== void 0 ? { toleranceSeconds: options.toleranceSeconds } : {},
455
+ ...options.now !== void 0 ? { now: options.now } : {}
456
+ });
457
+ if (!verified) return new Response(null, { status: 401 });
458
+ let parsed;
459
+ try {
460
+ parsed = parseEvent(JSON.parse(raw));
461
+ } catch {
462
+ parsed = void 0;
463
+ }
464
+ if (parsed === void 0) return new Response(null, { status: 400 });
465
+ if (parsed === "ignore") return ok(false);
466
+ const event = parsed;
467
+ try {
468
+ if (event.publication_id !== void 0) {
469
+ const last = await options.store.getSeq(seqKey(event.section.id, event.publication_id));
470
+ if (last !== void 0 && event.seq <= last) return ok(false);
471
+ }
472
+ await options.onEvent(event);
473
+ if (event.publication_id !== void 0) await options.store.setSeq(seqKey(event.section.id, event.publication_id), event.seq);
474
+ } catch {
475
+ return new Response(null, { status: 500 });
476
+ }
477
+ return ok(true);
478
+ }
479
+ };
480
+ }
481
+ async function readCapped3(req) {
482
+ if (!req.body) return "";
483
+ const reader = req.body.getReader();
484
+ const chunks = [];
485
+ let total = 0;
486
+ for (; ; ) {
487
+ const { done, value } = await reader.read();
488
+ if (done) break;
489
+ total += value.byteLength;
490
+ if (total > MAX_PUSH_BODY_BYTES) {
491
+ await reader.cancel();
492
+ return void 0;
493
+ }
494
+ chunks.push(value);
495
+ }
496
+ return Buffer.concat(chunks).toString("utf8");
497
+ }
498
+ function staleAfterResync(result, local) {
499
+ const seen = /* @__PURE__ */ new Set([...result.publicationIds, ...result.skipped.map((s) => s.publication_id)]);
500
+ return local.filter((row) => !seen.has(row.publicationId) && row.seq <= result.asOfSeq).map((row) => row.publicationId);
501
+ }
502
+ async function resyncPath(client, options) {
503
+ const ids = [];
504
+ const skipped = [];
505
+ let asOfSeq;
506
+ let cursor;
507
+ for (; ; ) {
508
+ const page = await client.pushPosts({ section: options.section, ...cursor ? { cursor } : {} });
509
+ asOfSeq ??= page.as_of_seq;
510
+ if (asOfSeq === void 0) throw new Error("hyle resync: the first page carried no as_of_seq");
511
+ skipped.push(...page.skipped ?? []);
512
+ for (const post of page.posts) {
513
+ await options.onPost(post);
514
+ if (options.store) {
515
+ const key = seqKey(page.section.id, post.publication_id);
516
+ await options.store.setSeq(key, Math.max(asOfSeq, await options.store.getSeq(key) ?? 0));
517
+ }
518
+ ids.push(post.publication_id);
519
+ }
520
+ if (page.complete || page.next_cursor === null) return { asOfSeq, publicationIds: ids, skipped };
521
+ cursor = page.next_cursor;
522
+ }
523
+ }
524
+
363
525
  // src/sitemap.ts
364
526
  var PAGE_LIMIT = 100;
365
527
  var DEFAULT_MAX_PAGES = 20;
@@ -599,9 +761,11 @@ function engagementPublicKey(seed) {
599
761
  CACHE_TAG_PATTERN,
600
762
  Cp1ClientError,
601
763
  DeliveryDedupe,
764
+ MAX_PUSH_BODY_BYTES,
602
765
  SDK_OWN_RESERVED,
603
766
  checkRoutes,
604
767
  createHyleClient,
768
+ createPushRoute,
605
769
  createRevalidationCallbackRoute,
606
770
  engagementPublicKey,
607
771
  formatReport,
@@ -610,9 +774,12 @@ function engagementPublicKey(seed) {
610
774
  isValidCacheTag,
611
775
  listPublicationPaths,
612
776
  normalizeRoute,
777
+ parseCommentEvent,
613
778
  parseSignatureHeader,
614
779
  reservedFor,
780
+ resyncPath,
615
781
  routeMatches,
782
+ staleAfterResync,
616
783
  syncHostReserved,
617
784
  verifyHyleSignature
618
785
  });
package/dist/index.d.cts CHANGED
@@ -1,60 +1,7 @@
1
- import { R as Resolved, M as MountsResult } from './types-Czt887Iv.cjs';
2
- export { A as Alternate, a as ArticleContent, B as Breadcrumb, C as CacheInfo, D as DocumentMetaFields, E as EngageComment, b as EngageHeldComment, c as EngageListing, F as Fallback, L as ListItem, d as Mount, e as Mounts, N as NavItem, f as NavNode, g as NavTree, h as ResolvedArticle, i as ResolvedDisabled, j as ResolvedList, k as ResolvedNotFound, l as ResolvedRedirect, T as TocEntry } from './types-Czt887Iv.cjs';
3
- export { R as RevalidationCallbackOptions, a as RevalidationCallbackRoute, b as RevalidationPayload, c as createRevalidationCallbackRoute } from './revalidation-callback-D7Ms_Puz.cjs';
4
-
5
- /** `next` is a Next.js fetch extension with no lib.dom type; typed structurally so this module needs no Next import. */
6
- type HyleRequestInit = Omit<RequestInit, "method" | "body"> & {
7
- readonly next?: {
8
- readonly revalidate?: number | false;
9
- readonly tags?: readonly string[];
10
- };
11
- };
12
- interface HyleClientOptions {
13
- /** hyle's origin, for example https://hyle.tdacorp.in. */
14
- readonly baseUrl: string;
15
- /** A target credential (hyle_tr_...). Server-side only: it is sent as a header and never put in a URL. */
16
- readonly token: string;
17
- /** Injectable for tests; defaults to the global fetch. */
18
- readonly fetch?: typeof fetch;
19
- /** Abort a request after this many milliseconds. Default 10000. */
20
- readonly timeoutMs?: number;
21
- /** Refuse a response body larger than this many bytes. Default 5 MiB. */
22
- readonly maxResponseBytes?: number;
23
- /** Allow a plain http baseUrl on a non-loopback host (tests, private networks). Default false: the token would travel unencrypted. */
24
- readonly allowInsecureHttp?: boolean;
25
- }
26
- interface ResolveOptions {
27
- /** The site path as a visitor sees it, including the workspace's path prefix. Sent as a query parameter, so it is encoded once. */
28
- readonly path: string;
29
- readonly locale?: string;
30
- readonly format?: "hast" | "html" | "md";
31
- /** "tree" adds the whole section's navigation (`article.nav`); the docs layout asks for it. An older hyle ignores it. */
32
- readonly nav?: "tree";
33
- readonly cursor?: string;
34
- readonly limit?: number;
35
- /** Extra fetch options (for example Next's `next: { tags, revalidate }`). Method, body and the auth header cannot be overridden. */
36
- readonly init?: HyleRequestInit;
37
- }
38
- interface MountsOptions {
39
- /** Extra fetch options (for example Next's `next: { tags, revalidate }`). Method, body and the auth header cannot be overridden. */
40
- readonly init?: HyleRequestInit;
41
- }
42
- interface AssetOptions {
43
- /** Only these request headers are sent upstream: a browser's own cache validators and byte range. Everything else is dropped. */
44
- readonly headers?: {
45
- readonly range?: string | null;
46
- readonly "if-range"?: string | null;
47
- readonly "if-none-match"?: string | null;
48
- };
49
- /** Abort after this many milliseconds, body included. Default: the client's `timeoutMs`. */
50
- readonly timeoutMs?: number;
51
- }
52
- declare function createHyleClient(options: HyleClientOptions): {
53
- resolve: (opts: ResolveOptions) => Promise<Resolved>;
54
- mounts: (opts?: MountsOptions) => Promise<MountsResult>;
55
- asset: (file: string, opts?: AssetOptions) => Promise<Response>;
56
- };
57
- type HyleClient = ReturnType<typeof createHyleClient>;
1
+ import { H as HyleAuth, a as HyleClient } from './client-41fU6OY2.cjs';
2
+ export { A as AssetOptions, b as HyleClientOptions, c as HyleCredential, d as HyleRequestInit, M as MAX_PUSH_BODY_BYTES, e as MountsOptions, P as PushEvent, f as PushEventType, g as PushPage, h as PushPost, i as PushRoute, j as PushRouteOptions, k as PushStore, R as ResolveOptions, l as ResyncOptions, m as ResyncResult, n as createHyleClient, o as createPushRoute, r as resyncPath, s as staleAfterResync } from './client-41fU6OY2.cjs';
3
+ export { A as Alternate, a as ArticleContent, B as Breadcrumb, C as CacheInfo, D as DocumentMetaFields, E as EngageComment, b as EngageHeldComment, c as EngageListing, F as Fallback, L as ListItem, M as Mount, d as Mounts, e as MountsResult, N as NavItem, f as NavNode, g as NavTree, R as ReactionCounts, h as ReactionKind, i as Resolved, j as ResolvedArticle, k as ResolvedDisabled, l as ResolvedList, m as ResolvedNotFound, n as ResolvedRedirect, T as TocEntry, V as VoteValue } from './types-3F0wqD-o.cjs';
4
+ export { C as CommentEvent, a as CommentEventType, R as RevalidationCallbackOptions, b as RevalidationCallbackRoute, c as RevalidationPayload, d as createRevalidationCallbackRoute, p as parseCommentEvent } from './revalidation-callback-BQl77tQR.cjs';
58
5
 
59
6
  declare class Cp1ClientError extends Error {
60
7
  readonly code: string;
@@ -64,11 +11,9 @@ declare class Cp1ClientError extends Error {
64
11
  constructor(code: string, message: string, status: number, requestId: string, details?: Record<string, unknown>);
65
12
  }
66
13
 
67
- interface HostSyncInput {
14
+ type HostSyncInput = {
68
15
  /** hyle's origin. */
69
16
  readonly baseUrl: string;
70
- /** A CONTROL credential (hyle_tc_...) holding hyle.workspace.manage on the workspace. Never a target (read) token. */
71
- readonly token: string;
72
17
  /** The workspace to write, from `client.mounts()`; the credential must be granted on it. */
73
18
  readonly workspaceId: string;
74
19
  /** The host's complete list of reserved paths (a replace). */
@@ -78,7 +23,14 @@ interface HostSyncInput {
78
23
  readonly fetch?: typeof fetch;
79
24
  readonly timeoutMs?: number;
80
25
  readonly allowInsecureHttp?: boolean;
81
- }
26
+ } & ({
27
+ /** A CONTROL credential (hyle_tc_...) holding hyle.workspace.manage on the workspace. Never a target (read) token. */
28
+ readonly token: string;
29
+ readonly auth?: never;
30
+ } | {
31
+ readonly auth: HyleAuth;
32
+ readonly token?: never;
33
+ });
82
34
  interface HostSyncResult {
83
35
  /** What hyle stored: sorted, de-duplicated. */
84
36
  readonly paths: readonly string[];
@@ -289,4 +241,4 @@ declare function generateEngagementKeyPair(): {
289
241
  /** The public half to register in hyle, from the private seed. */
290
242
  declare function engagementPublicKey(seed: string): string;
291
243
 
292
- export { type AssetOptions, CACHE_TAG_PATTERN, Cp1ClientError, DeliveryDedupe, type DynamicOverlap, type HostSyncInput, type HostSyncResult, type HyleClient, type HyleClientOptions, type HyleRequestInit, type ListPublicationPathsOptions, type LocaleOptions, type LocalePrefix, type MountsOptions, MountsResult, type NextManifests, type ParsedSignatureHeader, type PublicationPath, type PublicationPaths, type ResolveOptions, Resolved, type RouteCheckInput, type RouteCheckReport, SDK_OWN_RESERVED, type VerifySignatureParams, checkRoutes, createHyleClient, engagementPublicKey, formatReport, generateEngagementKeyPair, hostRoutesFromManifests, isValidCacheTag, listPublicationPaths, normalizeRoute, parseSignatureHeader, reservedFor, routeMatches, syncHostReserved, verifyHyleSignature };
244
+ export { CACHE_TAG_PATTERN, Cp1ClientError, DeliveryDedupe, type DynamicOverlap, type HostSyncInput, type HostSyncResult, HyleAuth, HyleClient, type ListPublicationPathsOptions, type LocaleOptions, type LocalePrefix, type NextManifests, type ParsedSignatureHeader, type PublicationPath, type PublicationPaths, type RouteCheckInput, type RouteCheckReport, SDK_OWN_RESERVED, type VerifySignatureParams, checkRoutes, engagementPublicKey, formatReport, generateEngagementKeyPair, hostRoutesFromManifests, isValidCacheTag, listPublicationPaths, normalizeRoute, parseSignatureHeader, reservedFor, routeMatches, syncHostReserved, verifyHyleSignature };
package/dist/index.d.ts CHANGED
@@ -1,60 +1,7 @@
1
- import { R as Resolved, M as MountsResult } from './types-Czt887Iv.js';
2
- export { A as Alternate, a as ArticleContent, B as Breadcrumb, C as CacheInfo, D as DocumentMetaFields, E as EngageComment, b as EngageHeldComment, c as EngageListing, F as Fallback, L as ListItem, d as Mount, e as Mounts, N as NavItem, f as NavNode, g as NavTree, h as ResolvedArticle, i as ResolvedDisabled, j as ResolvedList, k as ResolvedNotFound, l as ResolvedRedirect, T as TocEntry } from './types-Czt887Iv.js';
3
- export { R as RevalidationCallbackOptions, a as RevalidationCallbackRoute, b as RevalidationPayload, c as createRevalidationCallbackRoute } from './revalidation-callback-D7Ms_Puz.js';
4
-
5
- /** `next` is a Next.js fetch extension with no lib.dom type; typed structurally so this module needs no Next import. */
6
- type HyleRequestInit = Omit<RequestInit, "method" | "body"> & {
7
- readonly next?: {
8
- readonly revalidate?: number | false;
9
- readonly tags?: readonly string[];
10
- };
11
- };
12
- interface HyleClientOptions {
13
- /** hyle's origin, for example https://hyle.tdacorp.in. */
14
- readonly baseUrl: string;
15
- /** A target credential (hyle_tr_...). Server-side only: it is sent as a header and never put in a URL. */
16
- readonly token: string;
17
- /** Injectable for tests; defaults to the global fetch. */
18
- readonly fetch?: typeof fetch;
19
- /** Abort a request after this many milliseconds. Default 10000. */
20
- readonly timeoutMs?: number;
21
- /** Refuse a response body larger than this many bytes. Default 5 MiB. */
22
- readonly maxResponseBytes?: number;
23
- /** Allow a plain http baseUrl on a non-loopback host (tests, private networks). Default false: the token would travel unencrypted. */
24
- readonly allowInsecureHttp?: boolean;
25
- }
26
- interface ResolveOptions {
27
- /** The site path as a visitor sees it, including the workspace's path prefix. Sent as a query parameter, so it is encoded once. */
28
- readonly path: string;
29
- readonly locale?: string;
30
- readonly format?: "hast" | "html" | "md";
31
- /** "tree" adds the whole section's navigation (`article.nav`); the docs layout asks for it. An older hyle ignores it. */
32
- readonly nav?: "tree";
33
- readonly cursor?: string;
34
- readonly limit?: number;
35
- /** Extra fetch options (for example Next's `next: { tags, revalidate }`). Method, body and the auth header cannot be overridden. */
36
- readonly init?: HyleRequestInit;
37
- }
38
- interface MountsOptions {
39
- /** Extra fetch options (for example Next's `next: { tags, revalidate }`). Method, body and the auth header cannot be overridden. */
40
- readonly init?: HyleRequestInit;
41
- }
42
- interface AssetOptions {
43
- /** Only these request headers are sent upstream: a browser's own cache validators and byte range. Everything else is dropped. */
44
- readonly headers?: {
45
- readonly range?: string | null;
46
- readonly "if-range"?: string | null;
47
- readonly "if-none-match"?: string | null;
48
- };
49
- /** Abort after this many milliseconds, body included. Default: the client's `timeoutMs`. */
50
- readonly timeoutMs?: number;
51
- }
52
- declare function createHyleClient(options: HyleClientOptions): {
53
- resolve: (opts: ResolveOptions) => Promise<Resolved>;
54
- mounts: (opts?: MountsOptions) => Promise<MountsResult>;
55
- asset: (file: string, opts?: AssetOptions) => Promise<Response>;
56
- };
57
- type HyleClient = ReturnType<typeof createHyleClient>;
1
+ import { H as HyleAuth, a as HyleClient } from './client-LwzHwqpM.js';
2
+ export { A as AssetOptions, b as HyleClientOptions, c as HyleCredential, d as HyleRequestInit, M as MAX_PUSH_BODY_BYTES, e as MountsOptions, P as PushEvent, f as PushEventType, g as PushPage, h as PushPost, i as PushRoute, j as PushRouteOptions, k as PushStore, R as ResolveOptions, l as ResyncOptions, m as ResyncResult, n as createHyleClient, o as createPushRoute, r as resyncPath, s as staleAfterResync } from './client-LwzHwqpM.js';
3
+ export { A as Alternate, a as ArticleContent, B as Breadcrumb, C as CacheInfo, D as DocumentMetaFields, E as EngageComment, b as EngageHeldComment, c as EngageListing, F as Fallback, L as ListItem, M as Mount, d as Mounts, e as MountsResult, N as NavItem, f as NavNode, g as NavTree, R as ReactionCounts, h as ReactionKind, i as Resolved, j as ResolvedArticle, k as ResolvedDisabled, l as ResolvedList, m as ResolvedNotFound, n as ResolvedRedirect, T as TocEntry, V as VoteValue } from './types-3F0wqD-o.js';
4
+ export { C as CommentEvent, a as CommentEventType, R as RevalidationCallbackOptions, b as RevalidationCallbackRoute, c as RevalidationPayload, d as createRevalidationCallbackRoute, p as parseCommentEvent } from './revalidation-callback-BQl77tQR.js';
58
5
 
59
6
  declare class Cp1ClientError extends Error {
60
7
  readonly code: string;
@@ -64,11 +11,9 @@ declare class Cp1ClientError extends Error {
64
11
  constructor(code: string, message: string, status: number, requestId: string, details?: Record<string, unknown>);
65
12
  }
66
13
 
67
- interface HostSyncInput {
14
+ type HostSyncInput = {
68
15
  /** hyle's origin. */
69
16
  readonly baseUrl: string;
70
- /** A CONTROL credential (hyle_tc_...) holding hyle.workspace.manage on the workspace. Never a target (read) token. */
71
- readonly token: string;
72
17
  /** The workspace to write, from `client.mounts()`; the credential must be granted on it. */
73
18
  readonly workspaceId: string;
74
19
  /** The host's complete list of reserved paths (a replace). */
@@ -78,7 +23,14 @@ interface HostSyncInput {
78
23
  readonly fetch?: typeof fetch;
79
24
  readonly timeoutMs?: number;
80
25
  readonly allowInsecureHttp?: boolean;
81
- }
26
+ } & ({
27
+ /** A CONTROL credential (hyle_tc_...) holding hyle.workspace.manage on the workspace. Never a target (read) token. */
28
+ readonly token: string;
29
+ readonly auth?: never;
30
+ } | {
31
+ readonly auth: HyleAuth;
32
+ readonly token?: never;
33
+ });
82
34
  interface HostSyncResult {
83
35
  /** What hyle stored: sorted, de-duplicated. */
84
36
  readonly paths: readonly string[];
@@ -289,4 +241,4 @@ declare function generateEngagementKeyPair(): {
289
241
  /** The public half to register in hyle, from the private seed. */
290
242
  declare function engagementPublicKey(seed: string): string;
291
243
 
292
- export { type AssetOptions, CACHE_TAG_PATTERN, Cp1ClientError, DeliveryDedupe, type DynamicOverlap, type HostSyncInput, type HostSyncResult, type HyleClient, type HyleClientOptions, type HyleRequestInit, type ListPublicationPathsOptions, type LocaleOptions, type LocalePrefix, type MountsOptions, MountsResult, type NextManifests, type ParsedSignatureHeader, type PublicationPath, type PublicationPaths, type ResolveOptions, Resolved, type RouteCheckInput, type RouteCheckReport, SDK_OWN_RESERVED, type VerifySignatureParams, checkRoutes, createHyleClient, engagementPublicKey, formatReport, generateEngagementKeyPair, hostRoutesFromManifests, isValidCacheTag, listPublicationPaths, normalizeRoute, parseSignatureHeader, reservedFor, routeMatches, syncHostReserved, verifyHyleSignature };
244
+ export { CACHE_TAG_PATTERN, Cp1ClientError, DeliveryDedupe, type DynamicOverlap, type HostSyncInput, type HostSyncResult, HyleAuth, HyleClient, type ListPublicationPathsOptions, type LocaleOptions, type LocalePrefix, type NextManifests, type ParsedSignatureHeader, type PublicationPath, type PublicationPaths, type RouteCheckInput, type RouteCheckReport, SDK_OWN_RESERVED, type VerifySignatureParams, checkRoutes, engagementPublicKey, formatReport, generateEngagementKeyPair, hostRoutesFromManifests, isValidCacheTag, listPublicationPaths, normalizeRoute, parseSignatureHeader, reservedFor, routeMatches, syncHostReserved, verifyHyleSignature };
package/dist/index.js CHANGED
@@ -2,9 +2,11 @@ import {
2
2
  CACHE_TAG_PATTERN,
3
3
  Cp1ClientError,
4
4
  DeliveryDedupe,
5
+ MAX_PUSH_BODY_BYTES,
5
6
  SDK_OWN_RESERVED,
6
7
  checkRoutes,
7
8
  createHyleClient,
9
+ createPushRoute,
8
10
  createRevalidationCallbackRoute,
9
11
  engagementPublicKey,
10
12
  formatReport,
@@ -13,20 +15,25 @@ import {
13
15
  isValidCacheTag,
14
16
  listPublicationPaths,
15
17
  normalizeRoute,
18
+ parseCommentEvent,
16
19
  parseSignatureHeader,
17
20
  reservedFor,
21
+ resyncPath,
18
22
  routeMatches,
23
+ staleAfterResync,
19
24
  syncHostReserved,
20
25
  verifyHyleSignature
21
- } from "./chunk-MGSUQBDW.js";
26
+ } from "./chunk-75JFLML4.js";
22
27
  import "./chunk-67IOIAVW.js";
23
28
  export {
24
29
  CACHE_TAG_PATTERN,
25
30
  Cp1ClientError,
26
31
  DeliveryDedupe,
32
+ MAX_PUSH_BODY_BYTES,
27
33
  SDK_OWN_RESERVED,
28
34
  checkRoutes,
29
35
  createHyleClient,
36
+ createPushRoute,
30
37
  createRevalidationCallbackRoute,
31
38
  engagementPublicKey,
32
39
  formatReport,
@@ -35,9 +42,12 @@ export {
35
42
  isValidCacheTag,
36
43
  listPublicationPaths,
37
44
  normalizeRoute,
45
+ parseCommentEvent,
38
46
  parseSignatureHeader,
39
47
  reservedFor,
48
+ resyncPath,
40
49
  routeMatches,
50
+ staleAfterResync,
41
51
  syncHostReserved,
42
52
  verifyHyleSignature
43
53
  };