@tdacorp/hyle-sdk 0.14.1 → 0.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (86) hide show
  1. package/README.md +171 -32
  2. package/dist/check-routes-bin.js +48 -21
  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 +733 -278
  17. package/dist/comments.d.cts +66 -3
  18. package/dist/comments.d.ts +66 -3
  19. package/dist/comments.js +414 -330
  20. package/dist/{diagram-viewer-DYX6R63Y.js → diagram-viewer-XY3CG75U.js} +107 -46
  21. package/dist/{embed-B76zRRPa.d.cts → embed-BUFRQboD.d.ts} +10 -5
  22. package/dist/{embed-SqOBGI-E.d.ts → embed-CYt-q13P.d.cts} +10 -5
  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-CrA-iqTN.d.cts +46 -0
  36. package/dist/labels-CrA-iqTN.d.ts +46 -0
  37. package/dist/mermaid-diagram.cjs +453 -148
  38. package/dist/mermaid-diagram.d.cts +25 -42
  39. package/dist/mermaid-diagram.d.ts +25 -42
  40. package/dist/mermaid-diagram.js +205 -50
  41. package/dist/mermaid-image.cjs +1456 -0
  42. package/dist/mermaid-image.d.cts +30 -0
  43. package/dist/mermaid-image.d.ts +30 -0
  44. package/dist/mermaid-image.js +93 -0
  45. package/dist/next.cjs +1709 -1134
  46. package/dist/next.d.cts +67 -14
  47. package/dist/next.d.ts +67 -14
  48. package/dist/next.js +950 -794
  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 +677 -264
  54. package/dist/react.d.cts +161 -31
  55. package/dist/react.d.ts +161 -31
  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-DC2ccfwA.d.ts → resolve-BjAK0k_Y.d.ts} +2 -2
  62. package/dist/{resolve-DKLVftk_.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 +107 -47
  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-ByodIyEv.d.cts → types-3F0wqD-o.d.cts} +44 -4
  73. package/dist/{types-ByodIyEv.d.ts → types-3F0wqD-o.d.ts} +44 -4
  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-4V4VKB3O.js +0 -1471
  84. package/dist/chunk-R5EMI4HQ.js +0 -61
  85. package/dist/revalidation-callback-D7Ms_Puz.d.cts +0 -42
  86. package/dist/revalidation-callback-D7Ms_Puz.d.ts +0 -42
@@ -21,6 +21,18 @@ var Cp1ClientError = class extends Error {
21
21
  };
22
22
 
23
23
  // src/client.ts
24
+ var RENDERER_VERSION = "4";
25
+ function applyCredential(headers, credential, method, url) {
26
+ if (!credential.auth) {
27
+ headers.set("authorization", `Bearer ${credential.token}`);
28
+ return void 0;
29
+ }
30
+ const { workspaceId } = credential;
31
+ return credential.auth({ method, url }).then((extra) => {
32
+ for (const [name, value] of Object.entries(extra)) headers.set(name, value);
33
+ headers.set("cp-workspace", workspaceId);
34
+ });
35
+ }
24
36
  var DEFAULT_TIMEOUT_MS = 1e4;
25
37
  var DEFAULT_MAX_RESPONSE_BYTES = 5 * 1024 * 1024;
26
38
  var LOOPBACK = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "[::1]"]);
@@ -62,14 +74,16 @@ function checkBaseUrl(baseUrl, allowInsecureHttp) {
62
74
  }
63
75
  function createHyleClient(options) {
64
76
  checkBaseUrl(options.baseUrl, options.allowInsecureHttp);
65
- if (!options.token) throw new TypeError("token is required");
77
+ if (!options.auth && !options.token) throw new TypeError("token is required");
66
78
  const base = options.baseUrl.replace(/\/+$/, "");
67
79
  const fetchImpl = options.fetch ?? fetch;
68
80
  async function get(pathname, query, init) {
69
81
  const url = new URL(`${base}${pathname}`);
70
82
  url.search = query.toString();
71
83
  const headers = new Headers(init?.headers);
72
- headers.set("authorization", `Bearer ${options.token}`);
84
+ headers.set("cp-renderer-version", RENDERER_VERSION);
85
+ const applied = applyCredential(headers, options, "GET", url.toString());
86
+ if (applied) await applied;
73
87
  const timeout = AbortSignal.timeout(options.timeoutMs ?? DEFAULT_TIMEOUT_MS);
74
88
  const signal = init?.signal ? AbortSignal.any([init.signal, timeout]) : timeout;
75
89
  const res = await fetchImpl(url.toString(), { ...init, method: "GET", headers, redirect: "error", signal });
@@ -109,16 +123,28 @@ function createHyleClient(options) {
109
123
  if (data?.cp === 1 && data.kind === "mounts" && isMounts(data)) return data;
110
124
  throw failure(reply);
111
125
  }
126
+ async function pushPosts(opts) {
127
+ if (!/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/.test(opts.section)) throw new TypeError("section must be a section slug");
128
+ const query = new URLSearchParams();
129
+ if (opts.cursor !== void 0) query.set("cursor", opts.cursor);
130
+ const reply = await get(`/cp1/read/sections/${opts.section}/posts`, query, opts.init);
131
+ const data = reply.parsed?.data;
132
+ if (data?.cp === 1 && data.kind === "push_posts" && Array.isArray(data.posts) && typeof data.complete === "boolean") return data;
133
+ throw failure(reply);
134
+ }
112
135
  async function asset(file, opts = {}) {
113
136
  if (!ASSET_FILE.test(file)) throw new TypeError("asset file must be <uuid>[.<ext>]");
114
- const headers = new Headers({ authorization: `Bearer ${options.token}` });
137
+ const url = `${base}/cp1/read/assets/${file}`;
138
+ const headers = new Headers();
139
+ const applied = applyCredential(headers, options, "GET", url);
140
+ if (applied) await applied;
115
141
  for (const name of ["range", "if-range", "if-none-match"]) {
116
142
  const value = opts.headers?.[name];
117
143
  if (value) headers.set(name, value);
118
144
  }
119
- return fetchImpl(`${base}/cp1/read/assets/${file}`, { method: "GET", headers, redirect: "error", signal: AbortSignal.timeout(opts.timeoutMs ?? options.timeoutMs ?? DEFAULT_TIMEOUT_MS) });
145
+ return fetchImpl(url, { method: "GET", headers, redirect: "error", signal: AbortSignal.timeout(opts.timeoutMs ?? options.timeoutMs ?? DEFAULT_TIMEOUT_MS) });
120
146
  }
121
- return { resolve, mounts, asset };
147
+ return { resolve, mounts, pushPosts, asset };
122
148
  }
123
149
 
124
150
  // src/host-sync.ts
@@ -128,21 +154,20 @@ var MAX_RESPONSE_BYTES = 1024 * 1024;
128
154
  var PATH = "/cp1/control/workspace/host-reserved-paths";
129
155
  async function syncHostReserved(input) {
130
156
  checkBaseUrl(input.baseUrl, input.allowInsecureHttp);
131
- if (!input.token.startsWith(CONTROL_TOKEN_PREFIX)) {
157
+ if (input.token !== void 0 && !input.token.startsWith(CONTROL_TOKEN_PREFIX)) {
132
158
  throw new TypeError("syncing needs a control credential (hyle_tc_...); a target token is read-only and cannot write");
133
159
  }
134
160
  const fetchImpl = input.fetch ?? fetch;
135
- const res = await fetchImpl(`${input.baseUrl.replace(/\/+$/, "")}${PATH}`, {
161
+ const url = `${input.baseUrl.replace(/\/+$/, "")}${PATH}`;
162
+ const headers = new Headers({ "content-type": "application/json", "idempotency-key": `sync-${crypto.randomUUID()}` });
163
+ await applyCredential(headers, input.auth ? { auth: input.auth, workspaceId: input.workspaceId } : { token: input.token }, "PUT", url);
164
+ headers.set("cp-workspace", input.workspaceId);
165
+ const res = await fetchImpl(url, {
136
166
  method: "PUT",
137
167
  // redirect "error": the bearer token must never follow a redirect to another host.
138
168
  redirect: "error",
139
169
  signal: AbortSignal.timeout(input.timeoutMs ?? DEFAULT_TIMEOUT_MS2),
140
- headers: {
141
- authorization: `Bearer ${input.token}`,
142
- "content-type": "application/json",
143
- "cp-workspace": input.workspaceId,
144
- "idempotency-key": `sync-${crypto.randomUUID()}`
145
- },
170
+ headers,
146
171
  body: JSON.stringify({ paths: input.paths, host: input.host, build_id: input.buildId })
147
172
  });
148
173
  const text = await readCapped(res, MAX_RESPONSE_BYTES);
@@ -235,6 +260,35 @@ function isValidCacheTag(tag) {
235
260
  // src/revalidation-callback.ts
236
261
  var MAX_BODY_BYTES = 65536;
237
262
  var MAX_TAGS = 1e3;
263
+ var HOOK_WAIT_MS = 3e3;
264
+ var COMMENT_EVENT_TYPES = ["comment.held", "comment.reply", "comment.approved", "comment.hidden"];
265
+ var isRecord = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
266
+ var isText = (v) => typeof v === "string" && v.length > 0;
267
+ var isTextOrNull = (v) => v === null || isText(v);
268
+ var isEventPath = (v) => typeof v === "string" && v.startsWith("/") && !v.startsWith("//") && v.length <= 2048 && !/[\\\u0000-\u001f\u007f]/.test(v);
269
+ function parseCommentEvent(payload) {
270
+ if (!isRecord(payload) || payload.cp !== 1 || !isRecord(payload.data)) return void 0;
271
+ const type = COMMENT_EVENT_TYPES.find((t) => t === payload.type);
272
+ const { id, created_at, workspace_id, event_id, data } = payload;
273
+ if (!type || !isText(id) || !isText(created_at) || !isText(workspace_id) || !isText(event_id)) return void 0;
274
+ const { comment_id, parent_comment_id, publication_path, reader_sub, parent_reader_sub, status } = data;
275
+ if (!isText(comment_id) || !isTextOrNull(parent_comment_id) || !isEventPath(publication_path) || !isTextOrNull(reader_sub) || !isTextOrNull(parent_reader_sub)) return void 0;
276
+ if (status !== "held" && status !== "visible" && status !== "hidden") return void 0;
277
+ 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 } };
278
+ }
279
+ async function runHook(hook, event) {
280
+ let timer;
281
+ try {
282
+ await Promise.race([
283
+ Promise.resolve().then(() => hook(event)),
284
+ new Promise((_, reject) => timer = setTimeout(() => reject(new Error("timeout")), HOOK_WAIT_MS))
285
+ ]);
286
+ } catch {
287
+ console.error(`hyle: onCommentEvent failed or timed out for ${event.type} ${event.id}`);
288
+ } finally {
289
+ clearTimeout(timer);
290
+ }
291
+ }
238
292
  function createRevalidationCallbackRoute(options) {
239
293
  const dedupe = new DeliveryDedupe(options.dedupeCapacity);
240
294
  return {
@@ -269,7 +323,7 @@ function createRevalidationCallbackRoute(options) {
269
323
  if (body.workspace_id !== options.workspaceId) {
270
324
  return okResponse(0);
271
325
  }
272
- const deliveryId = req.headers.get("hyle-delivery-id");
326
+ const deliveryId = typeof body.id === "string" ? body.id : void 0;
273
327
  if (deliveryId && dedupe.has(deliveryId)) {
274
328
  return okResponse(0);
275
329
  }
@@ -284,6 +338,9 @@ function createRevalidationCallbackRoute(options) {
284
338
  return new Response(null, { status: 500 });
285
339
  }
286
340
  if (deliveryId) dedupe.add(deliveryId);
341
+ const hook = options.onCommentEvent;
342
+ const event = hook && parseCommentEvent(body);
343
+ if (hook && event) await runHook(hook, event);
287
344
  return okResponse(purged);
288
345
  }
289
346
  };
@@ -314,6 +371,106 @@ function okResponse(purged) {
314
371
  });
315
372
  }
316
373
 
374
+ // src/push.ts
375
+ var MAX_PUSH_BODY_BYTES = 2 * 1024 * 1024;
376
+ var seqKey = (sectionId, publicationId) => `${sectionId}:${publicationId}`;
377
+ var TYPES = /* @__PURE__ */ new Set(["post.published", "post.updated", "post.unpublished", "post.deleted", "post.moved", "section.moved"]);
378
+ var WITH_POST = /* @__PURE__ */ new Set(["post.published", "post.updated", "post.moved"]);
379
+ var ok = (applied) => new Response(JSON.stringify({ ok: true, applied }), { status: 200, headers: { "Content-Type": "application/json; charset=utf-8", "Cache-Control": "no-store" } });
380
+ function parseEvent(body) {
381
+ if (typeof body !== "object" || body === null || Array.isArray(body)) return void 0;
382
+ const e = body;
383
+ if (e.type === "webhook.test") return "ignore";
384
+ if (e.schema !== "hyle.push/1") return "ignore";
385
+ const section = e.section;
386
+ const hasPost = typeof e.post === "object" && e.post !== null;
387
+ 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;
388
+ return e;
389
+ }
390
+ function createPushRoute(options) {
391
+ const secrets = typeof options.secret === "string" ? [options.secret] : options.secret;
392
+ if (secrets.length === 0 || secrets.some((s) => !s)) throw new TypeError("secret is required");
393
+ return {
394
+ async POST(req) {
395
+ const declared = Number(req.headers.get("content-length"));
396
+ if (Number.isFinite(declared) && declared > MAX_PUSH_BODY_BYTES) return new Response(null, { status: 413 });
397
+ const raw = await readCapped3(req);
398
+ if (raw === void 0) return new Response(null, { status: 413 });
399
+ const verified = verifyHyleSignature({
400
+ header: req.headers.get("hyle-signature"),
401
+ rawBody: raw,
402
+ secrets,
403
+ ...options.toleranceSeconds !== void 0 ? { toleranceSeconds: options.toleranceSeconds } : {},
404
+ ...options.now !== void 0 ? { now: options.now } : {}
405
+ });
406
+ if (!verified) return new Response(null, { status: 401 });
407
+ let parsed;
408
+ try {
409
+ parsed = parseEvent(JSON.parse(raw));
410
+ } catch {
411
+ parsed = void 0;
412
+ }
413
+ if (parsed === void 0) return new Response(null, { status: 400 });
414
+ if (parsed === "ignore") return ok(false);
415
+ const event = parsed;
416
+ try {
417
+ if (event.publication_id !== void 0) {
418
+ const last = await options.store.getSeq(seqKey(event.section.id, event.publication_id));
419
+ if (last !== void 0 && event.seq <= last) return ok(false);
420
+ }
421
+ await options.onEvent(event);
422
+ if (event.publication_id !== void 0) await options.store.setSeq(seqKey(event.section.id, event.publication_id), event.seq);
423
+ } catch {
424
+ return new Response(null, { status: 500 });
425
+ }
426
+ return ok(true);
427
+ }
428
+ };
429
+ }
430
+ async function readCapped3(req) {
431
+ if (!req.body) return "";
432
+ const reader = req.body.getReader();
433
+ const chunks = [];
434
+ let total = 0;
435
+ for (; ; ) {
436
+ const { done, value } = await reader.read();
437
+ if (done) break;
438
+ total += value.byteLength;
439
+ if (total > MAX_PUSH_BODY_BYTES) {
440
+ await reader.cancel();
441
+ return void 0;
442
+ }
443
+ chunks.push(value);
444
+ }
445
+ return Buffer.concat(chunks).toString("utf8");
446
+ }
447
+ function staleAfterResync(result, local) {
448
+ const seen = /* @__PURE__ */ new Set([...result.publicationIds, ...result.skipped.map((s) => s.publication_id)]);
449
+ return local.filter((row) => !seen.has(row.publicationId) && row.seq <= result.asOfSeq).map((row) => row.publicationId);
450
+ }
451
+ async function resyncPath(client, options) {
452
+ const ids = [];
453
+ const skipped = [];
454
+ let asOfSeq;
455
+ let cursor;
456
+ for (; ; ) {
457
+ const page = await client.pushPosts({ section: options.section, ...cursor ? { cursor } : {} });
458
+ asOfSeq ??= page.as_of_seq;
459
+ if (asOfSeq === void 0) throw new Error("hyle resync: the first page carried no as_of_seq");
460
+ skipped.push(...page.skipped ?? []);
461
+ for (const post of page.posts) {
462
+ await options.onPost(post);
463
+ if (options.store) {
464
+ const key = seqKey(page.section.id, post.publication_id);
465
+ await options.store.setSeq(key, Math.max(asOfSeq, await options.store.getSeq(key) ?? 0));
466
+ }
467
+ ids.push(post.publication_id);
468
+ }
469
+ if (page.complete || page.next_cursor === null) return { asOfSeq, publicationIds: ids, skipped };
470
+ cursor = page.next_cursor;
471
+ }
472
+ }
473
+
317
474
  // src/sitemap.ts
318
475
  var PAGE_LIMIT = 100;
319
476
  var DEFAULT_MAX_PAGES = 20;
@@ -575,7 +732,12 @@ export {
575
732
  verifyHyleSignature,
576
733
  CACHE_TAG_PATTERN,
577
734
  isValidCacheTag,
735
+ parseCommentEvent,
578
736
  createRevalidationCallbackRoute,
737
+ MAX_PUSH_BODY_BYTES,
738
+ createPushRoute,
739
+ staleAfterResync,
740
+ resyncPath,
579
741
  listPublicationPaths,
580
742
  normalizeRoute,
581
743
  hostRoutesFromManifests,