@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
package/dist/next.d.cts CHANGED
@@ -1,11 +1,11 @@
1
1
  import { ReactElement } from 'react';
2
- import { A as ArticleRef, O as OgImage, J as JsonLdConfig, H as HyleComponents, a as HyleSlots, E as EngagementConfig, b as EmbedHeading } from './embed-BmdwA2G9.cjs';
3
- export { c as HyleCommentsFallback } from './embed-BmdwA2G9.cjs';
4
- import { F as FetchResolverOptions, H as HyleResolver } from './resolve-euZ4-aC9.cjs';
5
- export { f as fetchResolver, w as workspaceTags } from './resolve-euZ4-aC9.cjs';
2
+ import { A as ArticleRef, O as OgImage, J as JsonLdConfig, H as HyleComponents, a as HyleSlots, E as EngagementConfig, b as EmbedHeading } from './embed-CYt-q13P.cjs';
3
+ export { c as HyleCommentsFallback } from './embed-CYt-q13P.cjs';
4
+ import { F as FetchResolverOptions, H as HyleResolver } from './resolve-eI1muCKL.cjs';
5
+ export { f as fetchResolver, w as workspaceTags } from './resolve-eI1muCKL.cjs';
6
6
  import { MetadataRoute, ResolvingMetadata, Metadata } from 'next';
7
- import { a as RevalidationCallbackRoute } from './revalidation-callback-D7Ms_Puz.cjs';
8
- import './types-Czt887Iv.cjs';
7
+ import { R as RevalidationCallbackOptions, b as RevalidationCallbackRoute } from './revalidation-callback-BQl77tQR.cjs';
8
+ import './types-3F0wqD-o.cjs';
9
9
 
10
10
  type RouteParams = Record<string, string | string[] | undefined>;
11
11
  interface CommonOptions {
@@ -218,6 +218,8 @@ interface RevalidateRouteOptions {
218
218
  readonly workspaceId: string | undefined;
219
219
  /** Current signing secret first, previous ones after during rotation (HYLE_WEBHOOK_SECRET). */
220
220
  readonly secrets: readonly (string | undefined)[];
221
+ /** Comment notifications, see `RevalidationCallbackOptions.onCommentEvent`. */
222
+ readonly onCommentEvent?: RevalidationCallbackOptions["onCommentEvent"];
221
223
  /** Environment to read the site switch from. Default process.env. */
222
224
  readonly env?: Readonly<Record<string, string | undefined>>;
223
225
  }
@@ -233,7 +235,7 @@ declare function createRevalidateRoute(options: RevalidateRouteOptions): Revalid
233
235
  /**
234
236
  * One workspace of a root catch-all: the options of `hylePage` without `basePath` (the mount prefix comes from hyle's mounts)
235
237
  * and without `resolver` (the mounts are read through Next's fetch cache, so `baseUrl`, `token` and `workspaceId` are required).
236
- * `revalidate` (default 300) also bounds the mounts fetch.
238
+ * `revalidate` (default 86400, a safety net behind tag webhooks) also bounds the mounts fetch.
237
239
  */
238
240
  type HyleRootConfig = Omit<Extract<HyleNextOptions, {
239
241
  resolver?: undefined;
@@ -464,7 +466,8 @@ interface EngagementRouteOptions {
464
466
  readonly allowedOrigins?: readonly string[];
465
467
  /**
466
468
  * Called for every matched request before any work (after the allowlist and CSRF checks), with the action name:
467
- * "session", "comments.list", "comments.create", "comments.edit", "comments.delete", "reactions.add" or "reactions.remove".
469
+ * "session", "comments.list", "comments.create", "comments.edit", "comments.delete", "reactions.add", "reactions.remove",
470
+ * "votes.set" or "votes.remove".
468
471
  * Return a Response (for example a 429 from your own rate limiter) to answer instead; return nothing to continue. A throw is a 502.
469
472
  * hyle rate-limits too, but every anonymous read reaches your server first: limit /api/hyle/engage in your own middleware or here.
470
473
  */
package/dist/next.d.ts CHANGED
@@ -1,11 +1,11 @@
1
1
  import { ReactElement } from 'react';
2
- import { A as ArticleRef, O as OgImage, J as JsonLdConfig, H as HyleComponents, a as HyleSlots, E as EngagementConfig, b as EmbedHeading } from './embed-DNTZ2UXv.js';
3
- export { c as HyleCommentsFallback } from './embed-DNTZ2UXv.js';
4
- import { F as FetchResolverOptions, H as HyleResolver } from './resolve-Ae7UFjsQ.js';
5
- export { f as fetchResolver, w as workspaceTags } from './resolve-Ae7UFjsQ.js';
2
+ import { A as ArticleRef, O as OgImage, J as JsonLdConfig, H as HyleComponents, a as HyleSlots, E as EngagementConfig, b as EmbedHeading } from './embed-BUFRQboD.js';
3
+ export { c as HyleCommentsFallback } from './embed-BUFRQboD.js';
4
+ import { F as FetchResolverOptions, H as HyleResolver } from './resolve-BjAK0k_Y.js';
5
+ export { f as fetchResolver, w as workspaceTags } from './resolve-BjAK0k_Y.js';
6
6
  import { MetadataRoute, ResolvingMetadata, Metadata } from 'next';
7
- import { a as RevalidationCallbackRoute } from './revalidation-callback-D7Ms_Puz.js';
8
- import './types-Czt887Iv.js';
7
+ import { R as RevalidationCallbackOptions, b as RevalidationCallbackRoute } from './revalidation-callback-BQl77tQR.js';
8
+ import './types-3F0wqD-o.js';
9
9
 
10
10
  type RouteParams = Record<string, string | string[] | undefined>;
11
11
  interface CommonOptions {
@@ -218,6 +218,8 @@ interface RevalidateRouteOptions {
218
218
  readonly workspaceId: string | undefined;
219
219
  /** Current signing secret first, previous ones after during rotation (HYLE_WEBHOOK_SECRET). */
220
220
  readonly secrets: readonly (string | undefined)[];
221
+ /** Comment notifications, see `RevalidationCallbackOptions.onCommentEvent`. */
222
+ readonly onCommentEvent?: RevalidationCallbackOptions["onCommentEvent"];
221
223
  /** Environment to read the site switch from. Default process.env. */
222
224
  readonly env?: Readonly<Record<string, string | undefined>>;
223
225
  }
@@ -233,7 +235,7 @@ declare function createRevalidateRoute(options: RevalidateRouteOptions): Revalid
233
235
  /**
234
236
  * One workspace of a root catch-all: the options of `hylePage` without `basePath` (the mount prefix comes from hyle's mounts)
235
237
  * and without `resolver` (the mounts are read through Next's fetch cache, so `baseUrl`, `token` and `workspaceId` are required).
236
- * `revalidate` (default 300) also bounds the mounts fetch.
238
+ * `revalidate` (default 86400, a safety net behind tag webhooks) also bounds the mounts fetch.
237
239
  */
238
240
  type HyleRootConfig = Omit<Extract<HyleNextOptions, {
239
241
  resolver?: undefined;
@@ -464,7 +466,8 @@ interface EngagementRouteOptions {
464
466
  readonly allowedOrigins?: readonly string[];
465
467
  /**
466
468
  * Called for every matched request before any work (after the allowlist and CSRF checks), with the action name:
467
- * "session", "comments.list", "comments.create", "comments.edit", "comments.delete", "reactions.add" or "reactions.remove".
469
+ * "session", "comments.list", "comments.create", "comments.edit", "comments.delete", "reactions.add", "reactions.remove",
470
+ * "votes.set" or "votes.remove".
468
471
  * Return a Response (for example a 429 from your own rate limiter) to answer instead; return nothing to continue. A throw is a 502.
469
472
  * hyle rate-limits too, but every anonymous read reaches your server first: limit /api/hyle/engage in your own middleware or here.
470
473
  */
package/dist/next.js CHANGED
@@ -8,22 +8,26 @@ import {
8
8
  HyleCommentsView,
9
9
  HyleListView,
10
10
  ListPage,
11
+ REACTION_KINDS,
11
12
  absoluteUrl,
12
13
  articleAuthor,
13
14
  bareOrigin,
14
15
  hreflangLanguages,
16
+ isCursor,
15
17
  modifiedAt,
16
18
  parseListing,
17
19
  readingMinutes,
18
- stringsFor,
19
20
  validOgImage,
20
21
  wordCountOf
21
- } from "./chunk-DMK4XQLU.js";
22
+ } from "./chunk-HJX57NLI.js";
23
+ import {
24
+ stringsFor
25
+ } from "./chunk-56Y24XBV.js";
22
26
  import {
23
27
  DEFAULT_REVALIDATE,
24
28
  fetchResolver,
25
29
  workspaceTags
26
- } from "./chunk-6VOHFFA5.js";
30
+ } from "./chunk-X2TLYM7Y.js";
27
31
  import {
28
32
  Cp1ClientError,
29
33
  checkBaseUrl,
@@ -34,7 +38,7 @@ import {
34
38
  listPublicationPaths,
35
39
  readCapped,
36
40
  signReaderAssertion
37
- } from "./chunk-MGSUQBDW.js";
41
+ } from "./chunk-75JFLML4.js";
38
42
  import {
39
43
  ASSET_CONTENT_TYPES,
40
44
  ASSET_FILE,
@@ -110,6 +114,7 @@ function isRejectedRequest(error) {
110
114
  import { unstable_rethrow as unstable_rethrow2 } from "next/navigation";
111
115
 
112
116
  // src/next/engage.ts
117
+ import { createHash } from "crypto";
113
118
  var ENGAGE_CSRF_HEADER = "x-hyle-engage";
114
119
  var DEFAULT_TIMEOUT_MS = 1e4;
115
120
  var DEFAULT_SHARE_MS = 3e3;
@@ -143,9 +148,8 @@ function match(segments) {
143
148
  methods: ["GET", "POST"],
144
149
  rebuild: (method, body, url) => {
145
150
  if (method === "GET") {
146
- const keys = [...url.searchParams.keys()];
147
- const path = url.searchParams.get("path");
148
- return keys.length === 1 && isSitePath(path) ? { upstream: "/comments", query: new URLSearchParams({ path }) } : void 0;
151
+ const query = listingQuery(url.searchParams);
152
+ return query && { upstream: "/comments", query };
149
153
  }
150
154
  const clean = pick(body, ["path", "body", "parent_id"], ["path", "body"]);
151
155
  if (!clean || !isSitePath(clean.path) || !isCommentText(clean.body)) return void 0;
@@ -172,15 +176,38 @@ function match(segments) {
172
176
  methods: ["PUT", "DELETE"],
173
177
  rebuild: (_method, body) => {
174
178
  const type = body?.subject_type;
175
- 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;
176
- if (!clean) return void 0;
179
+ const subject = type === "article" ? "path" : type === "comment" ? "comment_id" : void 0;
180
+ const clean = subject && pick(body, ["subject_type", subject, "kind"], ["subject_type", subject]);
181
+ if (!clean || clean.kind !== void 0 && !REACTION_KINDS.includes(clean.kind)) return void 0;
177
182
  const valid = type === "article" ? isSitePath(clean.path) : typeof clean.comment_id === "string" && UUID.test(clean.comment_id);
178
183
  return valid ? { upstream: "/reactions", body: clean } : void 0;
179
184
  }
180
185
  };
181
186
  }
187
+ if (a === "votes" && b === void 0) {
188
+ return {
189
+ action: (m) => m === "PUT" ? "votes.set" : "votes.remove",
190
+ methods: ["PUT", "DELETE"],
191
+ rebuild: (method, body) => {
192
+ const keys = method === "PUT" ? ["comment_id", "value"] : ["comment_id"];
193
+ const clean = pick(body, keys, keys);
194
+ if (!clean || typeof clean.comment_id !== "string" || !UUID.test(clean.comment_id)) return void 0;
195
+ if (method === "PUT" && clean.value !== 1 && clean.value !== -1) return void 0;
196
+ return { upstream: "/votes", body: clean };
197
+ }
198
+ };
199
+ }
182
200
  return void 0;
183
201
  }
202
+ function listingQuery(params) {
203
+ const keys = [...params.keys()];
204
+ if (new Set(keys).size !== keys.length || keys.some((k) => k !== "path" && k !== "cursor" && k !== "sort")) return void 0;
205
+ const path = params.get("path");
206
+ const cursor = params.get("cursor");
207
+ const sort = params.get("sort");
208
+ if (!isSitePath(path) || cursor !== null && !isCursor(cursor) || sort !== null && sort !== "new" && sort !== "top") return void 0;
209
+ return new URLSearchParams({ path, ...cursor === null ? {} : { cursor }, ...sort === null ? {} : { sort } });
210
+ }
184
211
  function pick(body, allowed, required) {
185
212
  if (!body || Object.keys(body).some((k) => !allowed.includes(k)) || !required.every((k) => k in body)) return void 0;
186
213
  return Object.fromEntries(allowed.filter((k) => k in body).map((k) => [k, body[k]]));
@@ -289,7 +316,7 @@ function createEngagementRoute(options) {
289
316
  entry.result.then(
290
317
  (o) => {
291
318
  if (cache.get(key) !== entry) return;
292
- if (o.status !== 200 && o.status !== 404 || o.noShare || o.text.length > MAX_SHARED_ENTRY_BYTES) return forget(key, entry);
319
+ if (![200, 400, 404].includes(o.status) || o.noShare || o.text.length > MAX_SHARED_ENTRY_BYTES) return forget(key, entry);
293
320
  entry.bytes = o.text.length;
294
321
  cacheBytes += entry.bytes;
295
322
  while ((cacheBytes > MAX_SHARED_BYTES || cache.size > MAX_SHARED) && cache.size > 0) {
@@ -352,7 +379,7 @@ function createEngagementRoute(options) {
352
379
  }
353
380
  if (route.local === "session") {
354
381
  const who = await reader(req, config);
355
- return json(200, { data: { reader: who ? { name: who.reader.name } : null } });
382
+ return json(200, { data: { reader: who ? { id: createHash("sha256").update(who.reader.sub).digest("base64url"), name: who.reader.name } : null } });
356
383
  }
357
384
  let assertion;
358
385
  let viewer = null;
@@ -745,7 +772,7 @@ function createRevalidateRoute(options) {
745
772
  if (!workspaceId || secrets.length === 0) return new Response(null, { status: 503 });
746
773
  const key = `${workspaceId}\0${secrets.join("\0")}`;
747
774
  if (cached?.key !== key) {
748
- cached = { key, route: createRevalidationCallbackRoute({ workspaceId, secrets, revalidateTag: (tag2) => revalidateTag(tag2, { expire: 0 }) }) };
775
+ cached = { key, route: createRevalidationCallbackRoute({ workspaceId, secrets, revalidateTag: (tag2) => revalidateTag(tag2, { expire: 0 }), onCommentEvent: options.onCommentEvent }) };
749
776
  }
750
777
  return cached.route.POST(req);
751
778
  }
@@ -0,0 +1,157 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/react/print-coordinator.ts
21
+ var print_coordinator_exports = {};
22
+ __export(print_coordinator_exports, {
23
+ holdPrintUntil: () => holdPrintUntil,
24
+ installPrintShortcut: () => installPrintShortcut,
25
+ registerPrintTarget: () => registerPrintTarget
26
+ });
27
+ module.exports = __toCommonJS(print_coordinator_exports);
28
+
29
+ // src/react/mermaid-config.ts
30
+ var MAX_MERMAID_SOURCE = 1024 * 1024;
31
+ var RENDER_TIMEOUT_MS = 1e4;
32
+ function withTimeout(promise, ms) {
33
+ let timer;
34
+ const timeout = new Promise((_, reject) => {
35
+ timer = setTimeout(() => reject(new Error("timeout")), ms);
36
+ });
37
+ return Promise.race([promise, timeout]).finally(() => clearTimeout(timer));
38
+ }
39
+
40
+ // src/react/viewer/labels.ts
41
+ var VIEWER_LABELS_EN = {
42
+ expand: "Expand diagram",
43
+ expandHint: "Expand",
44
+ viewer: "Diagram viewer",
45
+ close: "Close",
46
+ zoomIn: "Zoom in",
47
+ zoomOut: "Zoom out",
48
+ fit: "Fit to window",
49
+ actual: "100%: actual size",
50
+ search: "Find in diagram",
51
+ searchPlaceholder: "Find",
52
+ noMatch: "No match",
53
+ matchOf: "{n} of {total}",
54
+ copySource: "MMD: copy diagram source",
55
+ downloadSvg: "SVG: download",
56
+ downloadPng: "PNG: download",
57
+ copyImage: "IMG: copy as image",
58
+ pngScale: "PNG scale",
59
+ fullscreen: "Fullscreen",
60
+ exitFullscreen: "Exit fullscreen",
61
+ copied: "Copied",
62
+ saved: "Saved",
63
+ unavailable: "Not available here",
64
+ hint: "Scroll to zoom, drag to pan, click a node to trace its paths, press / to search",
65
+ legendSelected: "Selected",
66
+ legendUpstream: "Upstream",
67
+ legendDownstream: "Downstream",
68
+ outgoing: "outgoing",
69
+ tracing: "{label}: {up} upstream, {down} downstream",
70
+ map: "Overview map",
71
+ largeTitle: "Large diagram, not drawn automatically",
72
+ largeBody: "Drawing a diagram this size can freeze this page for a few seconds, so it waits until you ask. Press Draw diagram: it takes a couple of seconds (a few more on a phone) and the page may pause while it works.",
73
+ drawLarge: "Draw diagram",
74
+ drawing: "Drawing\u2026",
75
+ drawingBody: "Drawing the diagram\u2026 this takes a couple of seconds.",
76
+ drawAgain: "Draw again",
77
+ showSource: "Show full source",
78
+ hideSource: "Show less",
79
+ printPreparing: "Preparing diagrams for print\u2026 Esc cancels between steps."
80
+ };
81
+
82
+ // src/react/print-coordinator.ts
83
+ var targets = /* @__PURE__ */ new Set();
84
+ var loading = /* @__PURE__ */ new Set();
85
+ function holdPrintUntil(loaded) {
86
+ loading.add(loaded);
87
+ const release = () => void loading.delete(loaded);
88
+ void loaded.then(release, release);
89
+ }
90
+ function registerPrintTarget(target) {
91
+ targets.add(target);
92
+ return () => void targets.delete(target);
93
+ }
94
+ function isPrintChord(e) {
95
+ const platform = navigator.userAgentData?.platform || navigator.platform;
96
+ const modifier = /mac/i.test(platform) ? e.metaKey && !e.ctrlKey : e.ctrlKey && !e.metaKey;
97
+ const nonLatinLetter = /^\p{L}$/u.test(e.key) && !/\p{Script=Latin}/u.test(e.key);
98
+ const isP = e.key.toLowerCase() === "p" || nonLatinLetter && e.code === "KeyP";
99
+ return modifier && !e.altKey && !e.shiftKey && isP;
100
+ }
101
+ function showStatus() {
102
+ const note = document.createElement("div");
103
+ note.className = "hyle-print-status";
104
+ note.setAttribute("role", "status");
105
+ note.textContent = [...targets].find((t) => t.status)?.status ?? VIEWER_LABELS_EN.printPreparing;
106
+ const dialogs = document.querySelectorAll("dialog[open]");
107
+ (dialogs[dialogs.length - 1] ?? document.body).append(note);
108
+ return () => note.remove();
109
+ }
110
+ var cancel = null;
111
+ var installs = 0;
112
+ async function printWhenDrawn() {
113
+ let cancelled = false;
114
+ const escaped = new Promise((resolve) => {
115
+ cancel = () => {
116
+ cancelled = true;
117
+ resolve();
118
+ };
119
+ });
120
+ const hideStatus = showStatus();
121
+ const drawn = withTimeout(Promise.all(loading).then(() => Promise.all([...targets].map((t) => t.prepare?.()))), RENDER_TIMEOUT_MS).catch((error) => {
122
+ loading.clear();
123
+ throw error;
124
+ }).then(() => withTimeout(Promise.all([...targets].map((t) => t.ensureDrawn())), RENDER_TIMEOUT_MS)).catch(() => void 0);
125
+ await Promise.race([drawn, escaped]);
126
+ cancel = null;
127
+ hideStatus();
128
+ if (!cancelled) window.print();
129
+ }
130
+ function onKeyDown(e) {
131
+ if (e.defaultPrevented) return;
132
+ if (cancel && e.key === "Escape") {
133
+ e.preventDefault();
134
+ return cancel();
135
+ }
136
+ if (!isPrintChord(e)) return;
137
+ if (!cancel && loading.size === 0 && [...targets].every((t) => t.settled())) return;
138
+ e.preventDefault();
139
+ if (!cancel) void printWhenDrawn();
140
+ }
141
+ function installPrintShortcut() {
142
+ if (installs++ === 0) document.addEventListener("keydown", onKeyDown);
143
+ let installed = true;
144
+ return () => {
145
+ if (!installed) return;
146
+ installed = false;
147
+ if (--installs > 0) return;
148
+ document.removeEventListener("keydown", onKeyDown);
149
+ cancel?.();
150
+ };
151
+ }
152
+ // Annotate the CommonJS export names for ESM import in node:
153
+ 0 && (module.exports = {
154
+ holdPrintUntil,
155
+ installPrintShortcut,
156
+ registerPrintTarget
157
+ });
@@ -0,0 +1,27 @@
1
+ /** One mounted diagram, as the print shortcut sees it. */
2
+ interface PrintTarget {
3
+ /** True once the diagram is drawn, has failed, or is a large one the reader has not asked for (print shows its source). */
4
+ settled: () => boolean;
5
+ /** Fetches the code drawing needs (Mermaid), so a slow download is not counted against the draw budget. */
6
+ prepare?: () => Promise<unknown>;
7
+ /** Forces the diagram to draw; resolves once it is settled (at once when it already is, which includes a large one not asked for). */
8
+ ensureDrawn: () => Promise<void>;
9
+ /** The note shown while the print waits, in the diagram's locale (English when omitted). */
10
+ status?: string;
11
+ }
12
+ /** `loaded` must settle (never reject) once every diagram it mounts has registered; a failed load settles it too. */
13
+ declare function holdPrintUntil(loaded: Promise<unknown>): void;
14
+ /** Called by each mounted diagram; returns the cleanup. */
15
+ declare function registerPrintTarget(target: PrintTarget): () => void;
16
+ /**
17
+ * Ctrl/Cmd+P while a diagram is not drawn yet: hold the browser's print, draw every diagram, then call `window.print()`.
18
+ * Otherwise the key is left alone. Escape during the wait cancels the print.
19
+ * File > Print cannot be intercepted and still prints the source.
20
+ * Every MermaidDiagram installs it. One document listener serves every caller: it goes with the last cleanup, which
21
+ * also cancels a wait in progress.
22
+ * shortcut: the budgets and Escape are only served between tasks. Mermaid lays a diagram out in one synchronous task, so a diagram that
23
+ * is one huge layout holds the press until that layout ends, timers and Escape included; upgrade by not drawing such diagrams at all.
24
+ */
25
+ declare function installPrintShortcut(): () => void;
26
+
27
+ export { type PrintTarget, holdPrintUntil, installPrintShortcut, registerPrintTarget };
@@ -0,0 +1,27 @@
1
+ /** One mounted diagram, as the print shortcut sees it. */
2
+ interface PrintTarget {
3
+ /** True once the diagram is drawn, has failed, or is a large one the reader has not asked for (print shows its source). */
4
+ settled: () => boolean;
5
+ /** Fetches the code drawing needs (Mermaid), so a slow download is not counted against the draw budget. */
6
+ prepare?: () => Promise<unknown>;
7
+ /** Forces the diagram to draw; resolves once it is settled (at once when it already is, which includes a large one not asked for). */
8
+ ensureDrawn: () => Promise<void>;
9
+ /** The note shown while the print waits, in the diagram's locale (English when omitted). */
10
+ status?: string;
11
+ }
12
+ /** `loaded` must settle (never reject) once every diagram it mounts has registered; a failed load settles it too. */
13
+ declare function holdPrintUntil(loaded: Promise<unknown>): void;
14
+ /** Called by each mounted diagram; returns the cleanup. */
15
+ declare function registerPrintTarget(target: PrintTarget): () => void;
16
+ /**
17
+ * Ctrl/Cmd+P while a diagram is not drawn yet: hold the browser's print, draw every diagram, then call `window.print()`.
18
+ * Otherwise the key is left alone. Escape during the wait cancels the print.
19
+ * File > Print cannot be intercepted and still prints the source.
20
+ * Every MermaidDiagram installs it. One document listener serves every caller: it goes with the last cleanup, which
21
+ * also cancels a wait in progress.
22
+ * shortcut: the budgets and Escape are only served between tasks. Mermaid lays a diagram out in one synchronous task, so a diagram that
23
+ * is one huge layout holds the press until that layout ends, timers and Escape included; upgrade by not drawing such diagrams at all.
24
+ */
25
+ declare function installPrintShortcut(): () => void;
26
+
27
+ export { type PrintTarget, holdPrintUntil, installPrintShortcut, registerPrintTarget };
@@ -0,0 +1,83 @@
1
+ import {
2
+ RENDER_TIMEOUT_MS,
3
+ withTimeout
4
+ } from "./chunk-K5VDLROQ.js";
5
+ import {
6
+ VIEWER_LABELS_EN
7
+ } from "./chunk-QVYQM5R2.js";
8
+
9
+ // src/react/print-coordinator.ts
10
+ var targets = /* @__PURE__ */ new Set();
11
+ var loading = /* @__PURE__ */ new Set();
12
+ function holdPrintUntil(loaded) {
13
+ loading.add(loaded);
14
+ const release = () => void loading.delete(loaded);
15
+ void loaded.then(release, release);
16
+ }
17
+ function registerPrintTarget(target) {
18
+ targets.add(target);
19
+ return () => void targets.delete(target);
20
+ }
21
+ function isPrintChord(e) {
22
+ const platform = navigator.userAgentData?.platform || navigator.platform;
23
+ const modifier = /mac/i.test(platform) ? e.metaKey && !e.ctrlKey : e.ctrlKey && !e.metaKey;
24
+ const nonLatinLetter = /^\p{L}$/u.test(e.key) && !/\p{Script=Latin}/u.test(e.key);
25
+ const isP = e.key.toLowerCase() === "p" || nonLatinLetter && e.code === "KeyP";
26
+ return modifier && !e.altKey && !e.shiftKey && isP;
27
+ }
28
+ function showStatus() {
29
+ const note = document.createElement("div");
30
+ note.className = "hyle-print-status";
31
+ note.setAttribute("role", "status");
32
+ note.textContent = [...targets].find((t) => t.status)?.status ?? VIEWER_LABELS_EN.printPreparing;
33
+ const dialogs = document.querySelectorAll("dialog[open]");
34
+ (dialogs[dialogs.length - 1] ?? document.body).append(note);
35
+ return () => note.remove();
36
+ }
37
+ var cancel = null;
38
+ var installs = 0;
39
+ async function printWhenDrawn() {
40
+ let cancelled = false;
41
+ const escaped = new Promise((resolve) => {
42
+ cancel = () => {
43
+ cancelled = true;
44
+ resolve();
45
+ };
46
+ });
47
+ const hideStatus = showStatus();
48
+ const drawn = withTimeout(Promise.all(loading).then(() => Promise.all([...targets].map((t) => t.prepare?.()))), RENDER_TIMEOUT_MS).catch((error) => {
49
+ loading.clear();
50
+ throw error;
51
+ }).then(() => withTimeout(Promise.all([...targets].map((t) => t.ensureDrawn())), RENDER_TIMEOUT_MS)).catch(() => void 0);
52
+ await Promise.race([drawn, escaped]);
53
+ cancel = null;
54
+ hideStatus();
55
+ if (!cancelled) window.print();
56
+ }
57
+ function onKeyDown(e) {
58
+ if (e.defaultPrevented) return;
59
+ if (cancel && e.key === "Escape") {
60
+ e.preventDefault();
61
+ return cancel();
62
+ }
63
+ if (!isPrintChord(e)) return;
64
+ if (!cancel && loading.size === 0 && [...targets].every((t) => t.settled())) return;
65
+ e.preventDefault();
66
+ if (!cancel) void printWhenDrawn();
67
+ }
68
+ function installPrintShortcut() {
69
+ if (installs++ === 0) document.addEventListener("keydown", onKeyDown);
70
+ let installed = true;
71
+ return () => {
72
+ if (!installed) return;
73
+ installed = false;
74
+ if (--installs > 0) return;
75
+ document.removeEventListener("keydown", onKeyDown);
76
+ cancel?.();
77
+ };
78
+ }
79
+ export {
80
+ holdPrintUntil,
81
+ installPrintShortcut,
82
+ registerPrintTarget
83
+ };