@publisle/adapter-core 0.2.1 → 0.2.3

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.
@@ -1,977 +1,9 @@
1
- import { isInteractiveEnvelope, locateDiagnostic, richText, createIslandInput, } from "@publisle/schema";
2
1
  import katex from "katex";
3
- const text = (value) => ({ kind: "text", value });
4
- const element = (tag, attributes, children) => ({ kind: "element", tag, attributes, children });
5
- /** Stable identity for a citation cluster, independent of object property order. */
6
- export function citationKey(cluster) {
7
- return JSON.stringify([
8
- cluster.items.map((item) => [
9
- item.id,
10
- item.locator ?? "",
11
- item.label ?? "",
12
- item.suppressAuthor ?? false,
13
- ]),
14
- cluster.prefix ?? "",
15
- cluster.suffix ?? "",
16
- ]);
17
- }
18
- function referenceText(target) {
19
- if (target.kind === "heading")
20
- return target.title ?? target.label;
21
- const name = target.kind.charAt(0).toUpperCase() + target.kind.slice(1);
22
- return `${name} ${target.ordinal ?? ""}`.trim();
23
- }
24
- function renderMath(value, display, diagnostics, block) {
25
- try {
26
- return [
27
- {
28
- kind: "raw",
29
- value: katex.renderToString(value, {
30
- displayMode: display,
31
- throwOnError: true,
32
- trust: false,
33
- strict: "warn",
34
- maxExpand: 1000,
35
- maxSize: 100,
36
- output: "htmlAndMathml",
37
- }),
38
- },
39
- ];
40
- }
41
- catch (error) {
42
- diagnostics.push({
43
- level: "warning",
44
- code: "invalid-math",
45
- message: error instanceof Error ? error.message : "Math rendering failed.",
46
- blockId: block.id,
47
- });
48
- return [
49
- element(display ? "pre" : "code", { class: "publisle-math-error" }, [
50
- text(value),
51
- ]),
52
- ];
53
- }
54
- }
55
- function safeUrl(url) {
56
- // Conservative superset of browser URL preprocessing, shared with Python.
57
- // Browsers remove embedded TAB/LF/CR before identifying a scheme.
58
- // eslint-disable-next-line no-control-regex -- deliberately remove URL control characters
59
- const normalized = url.replace(/[\u0000-\u0020]/gu, "").toLowerCase();
60
- return /^(?:javascript|vbscript|data):/u.test(normalized) ? undefined : url;
61
- }
62
- function safeEmbedUrl(url) {
63
- return /^https:\/\//iu.test(url.trim()) ? url : undefined;
64
- }
65
- const builtinEmbedProviders = {
66
- youtube: (resourceId) => {
67
- return /^[\w-]{6,20}$/u.test(resourceId)
68
- ? {
69
- src: `https://www.youtube-nocookie.com/embed/${resourceId}`,
70
- allow: "accelerometer; autoplay; encrypted-media; picture-in-picture",
71
- allowFullscreen: true,
72
- }
73
- : undefined;
74
- },
75
- vimeo: (resourceId) => {
76
- return /^\d+$/u.test(resourceId)
77
- ? {
78
- src: `https://player.vimeo.com/video/${resourceId}`,
79
- allow: "autoplay; fullscreen; picture-in-picture",
80
- allowFullscreen: true,
81
- }
82
- : undefined;
83
- },
84
- };
85
- function inline(nodes, diagnostics, block, references = []) {
86
- return nodes.flatMap((node, index) => {
87
- switch (node.type) {
88
- case "text": {
89
- const value = String(node["value"] ?? "");
90
- const direction = node["direction"];
91
- if (direction === "ltr" || direction === "rtl" || direction === "auto")
92
- return [element("span", { dir: direction }, [text(value)])];
93
- return [text(value)];
94
- }
95
- case "emphasis":
96
- return [
97
- element("em", {}, inline(node["children"], diagnostics, block, references)),
98
- ];
99
- case "strong":
100
- return [
101
- element("strong", {}, inline(node["children"], diagnostics, block, references)),
102
- ];
103
- case "strikethrough":
104
- return [
105
- element("del", {}, inline(node["children"], diagnostics, block, references)),
106
- ];
107
- case "inlineCode":
108
- return [element("code", {}, [text(String(node["value"] ?? ""))])];
109
- case "inlineMath":
110
- return renderMath(String(node["value"] ?? ""), false, diagnostics, block);
111
- case "hardBreak":
112
- return [element("br", {}, [])];
113
- case "softBreak":
114
- return [text("\n")];
115
- case "footnoteReference": {
116
- const localId = `footnote-${String(node["identifier"] ?? "")}`;
117
- return [
118
- element("sup", {}, [
119
- element("a", { href: `#${localId}`, "data-publisle-ref": localId }, [text(String(node["identifier"] ?? ""))]),
120
- ]),
121
- ];
122
- }
123
- case "citationReference": {
124
- const items = Array.isArray(node["items"])
125
- ? node["items"]
126
- : [];
127
- const value = `${String(node["prefix"] ?? "")}${items
128
- .map((item) => {
129
- const id = String(item["id"] ?? "");
130
- const locator = typeof item["locator"] === "string" ? `, ${item["locator"]}` : "";
131
- return `${id}${locator}`;
132
- })
133
- .join("; ")}${String(node["suffix"] ?? "")}`;
134
- return [
135
- element("span", {
136
- class: "publisle-citation",
137
- "data-publisle-citation": JSON.stringify(items),
138
- ...(node["prefix"]
139
- ? { "data-publisle-citation-prefix": String(node["prefix"]) }
140
- : {}),
141
- ...(node["suffix"]
142
- ? { "data-publisle-citation-suffix": String(node["suffix"]) }
143
- : {}),
144
- }, [text(`[${value}]`)]),
145
- ];
146
- }
147
- case "crossReference": {
148
- const target = String(node["target"] ?? "");
149
- const resolved = references.find((entry) => entry.label === target);
150
- const preceding = nodes
151
- .slice(0, index)
152
- .map(function plain(item) {
153
- return item.type === "text"
154
- ? String(item["value"] ?? "")
155
- : Array.isArray(item["children"])
156
- ? item["children"].map(plain).join("")
157
- : "";
158
- })
159
- .join("");
160
- const kind = resolved?.kind;
161
- const authoredKind = kind &&
162
- kind !== "heading" &&
163
- new RegExp(`\\b${kind}\\s+$`, "iu").test(preceding);
164
- const label = resolved
165
- ? authoredKind
166
- ? String(resolved.ordinal ?? resolved.label)
167
- : referenceText(resolved)
168
- : target;
169
- const children = Array.isArray(node["children"])
170
- ? inline(node["children"], diagnostics, block, references)
171
- : [text(label)];
172
- return [
173
- element("a", {
174
- href: `#reference-${target}`,
175
- "data-publisle-ref": `reference-${target}`,
176
- ...(resolved ? {} : { "data-publisle-unresolved": true }),
177
- }, children),
178
- ];
179
- }
180
- case "rawHtml":
181
- return [
182
- element("pre", { "data-publisle-raw-html": true }, [
183
- text(String(node["value"] ?? "")),
184
- ]),
185
- ];
186
- case "link": {
187
- const url = safeUrl(String(node["url"] ?? ""));
188
- if (!url)
189
- diagnostics.push({
190
- level: "warning",
191
- code: "unsafe-url",
192
- message: "An unsafe link URL was removed.",
193
- blockId: block.id,
194
- });
195
- return [
196
- element("a", url ? { href: url } : {}, inline(node["children"], diagnostics, block, references)),
197
- ];
198
- }
199
- case "inlineImage": {
200
- const url = safeUrl(String(node["url"] ?? ""));
201
- if (!url)
202
- diagnostics.push({
203
- level: "warning",
204
- code: "unsafe-url",
205
- message: "An unsafe image URL was removed.",
206
- blockId: block.id,
207
- });
208
- return [
209
- element("img", { ...(url ? { src: url } : {}), alt: String(node["alt"] ?? "") }, []),
210
- ];
211
- }
212
- default:
213
- return [];
214
- }
215
- });
216
- }
217
- function flow(nodes, diagnostics, block, references = []) {
218
- return nodes.flatMap((node) => {
219
- switch (node.type) {
220
- case "paragraph":
221
- return [
222
- element("p", {}, inline(node["content"], diagnostics, block, references)),
223
- ];
224
- case "heading":
225
- return [
226
- element(`h${Number(node["level"])}`, {}, inline(node["content"], diagnostics, block, references)),
227
- ];
228
- case "quote":
229
- return [
230
- element("blockquote", {}, flow(node["children"], diagnostics, block, references)),
231
- ];
232
- case "code":
233
- return [
234
- element("pre", {}, [
235
- element("code", typeof node["language"] === "string"
236
- ? { class: `language-${node["language"]}` }
237
- : {}, [text(String(node["value"] ?? ""))]),
238
- ]),
239
- ];
240
- case "divider":
241
- return [element("hr", {}, [])];
242
- case "rawHtml":
243
- return [
244
- element("pre", { "data-publisle-raw-html": true }, [
245
- text(String(node["value"] ?? "")),
246
- ]),
247
- ];
248
- case "list": {
249
- const ordered = node["ordered"] === true;
250
- const items = node["items"];
251
- return [
252
- element(ordered ? "ol" : "ul", ordered && typeof node["start"] === "number"
253
- ? { start: node["start"] }
254
- : {}, items.map((item) => element("li", typeof item.checked === "boolean"
255
- ? { class: "publisle-task-list-item" }
256
- : {}, [
257
- ...(typeof item.checked === "boolean"
258
- ? [
259
- element("input", {
260
- type: "checkbox",
261
- disabled: true,
262
- ...(item.checked ? { checked: true } : {}),
263
- }, []),
264
- ]
265
- : []),
266
- ...flow(item.children, diagnostics, block, references),
267
- ]))),
268
- ];
269
- }
270
- default:
271
- return [];
272
- }
273
- });
274
- }
275
- function inlinePlain(nodes) {
276
- return nodes
277
- .map((node) => {
278
- if (typeof node !== "object" || node === null || Array.isArray(node))
279
- return "";
280
- const record = node;
281
- if (record["type"] === "text" && typeof record["value"] === "string")
282
- return record["value"];
283
- return Array.isArray(record["children"])
284
- ? inlinePlain(record["children"])
285
- : "";
286
- })
287
- .join("");
288
- }
289
- function envelopeProps(envelope) {
290
- const props = {
291
- activation: envelope.activation,
292
- payload: envelope.payload,
293
- };
294
- if (envelope.content !== undefined)
295
- props["content"] = envelope.content;
296
- if (envelope.fallback !== undefined)
297
- props["fallback"] = envelope.fallback;
298
- if (envelope.initialState !== undefined)
299
- props["initialState"] = envelope.initialState;
300
- if (envelope.accessibility !== undefined)
301
- props["accessibility"] = envelope.accessibility;
302
- return props;
303
- }
304
- function nonempty(value, fallback) {
305
- return value !== undefined && value.length > 0 ? value : fallback;
306
- }
307
- function accessibleName(envelope, displayName) {
308
- const title = envelope.content?.title
309
- ? inlinePlain(envelope.content.title).trim()
310
- : "";
311
- return nonempty(envelope.accessibility?.label, nonempty(title, displayName ?? "Interactive"));
312
- }
313
- function exploreLabel(envelope, displayName) {
314
- const title = envelope.content?.title
315
- ? inlinePlain(envelope.content.title).trim()
316
- : "";
317
- const name = nonempty(title, envelope.accessibility?.label ?? displayName ?? "");
318
- return name.length > 0 ? `Explore ${name}` : "Explore";
319
- }
320
- function contractProvenance(type, pins) {
321
- const pin = pins.find((entry) => entry.type === type);
322
- return pin ? `${pin.id} ${pin.digest}` : undefined;
323
- }
324
- function interactiveReference(renderer) {
325
- if (renderer.interactive)
326
- return {
327
- module: renderer.interactive.module,
328
- exportName: renderer.interactive.exportName ?? "default",
329
- };
330
- if (renderer.module)
331
- return {
332
- module: renderer.module,
333
- exportName: renderer.exportName ?? "default",
334
- };
335
- return undefined;
336
- }
337
- function interactiveNodes(block, envelope, options, diagnostics, references, displayName, pins = []) {
338
- const renderer = options.renderers?.[block.type];
339
- const interactive = renderer ? interactiveReference(renderer) : undefined;
340
- const staticRenderer = renderer?.static;
341
- const description = envelope.content?.description;
342
- const hasDescription = Array.isArray(description) && description.length > 0;
343
- const fallbackContent = envelope.fallback ?? envelope.content?.fallback;
344
- const hasFallback = Array.isArray(fallbackContent) && fallbackContent.length > 0;
345
- if (!staticRenderer && !hasFallback && !hasDescription) {
346
- diagnostics.push({
347
- level: "warning",
348
- code: "missing-static-representation",
349
- message: `Interactive block ${block.type} has no static representation.`,
350
- blockId: block.id,
351
- });
352
- }
353
- const explanation = [];
354
- if (envelope.content?.title?.length) {
355
- explanation.push(element("p", { class: "publisle-interactive-title" }, inline(envelope.content.title, diagnostics, block, references)));
356
- }
357
- if (hasDescription)
358
- explanation.push(...flow(description, diagnostics, block, references));
359
- if (envelope.content?.instructions?.length)
360
- explanation.push(...flow(envelope.content.instructions, diagnostics, block, references));
361
- for (const key of ["purpose", "observations", "assumptions"]) {
362
- const content = envelope.content?.[key];
363
- if (content?.length)
364
- explanation.push(...flow(content, diagnostics, block, references));
365
- }
366
- for (const preset of envelope.content?.presets ?? []) {
367
- if (preset.description?.length)
368
- explanation.push(...flow(preset.description, diagnostics, block, references));
369
- }
370
- const visualization = staticRenderer
371
- ? [
372
- {
373
- kind: "component",
374
- module: staticRenderer.module,
375
- exportName: staticRenderer.exportName ?? "default",
376
- blockId: block.id,
377
- props: envelopeProps(envelope),
378
- artifact: staticRenderer.lower
379
- ? staticRenderer.lower(createIslandInput(block, envelope, pins))
380
- : hasFallback
381
- ? flow(fallbackContent, diagnostics, block, references)
382
- : [],
383
- },
384
- ]
385
- : hasFallback
386
- ? flow(fallbackContent, diagnostics, block, references)
387
- : [];
388
- const provenance = contractProvenance(block.type, pins);
389
- const region = (children) => [
390
- element("section", {
391
- class: "publisle-interactive",
392
- ...(provenance ? { "data-publisle-contract": provenance } : {}),
393
- }, children),
394
- ];
395
- if (!interactive) {
396
- diagnostics.push({
397
- level: "warning",
398
- code: "missing-island-renderer",
399
- message: `No island renderer is configured for ${block.type}.`,
400
- blockId: block.id,
401
- });
402
- return region([...explanation, ...visualization]);
403
- }
404
- const fallback = [...visualization];
405
- if (envelope.activation === "interaction") {
406
- fallback.push(element("button", { type: "button", "data-publisle-activate": "true" }, [
407
- text(exploreLabel(envelope, displayName)),
408
- ]));
409
- }
410
- return region([
411
- ...explanation,
412
- {
413
- kind: "island",
414
- blockId: block.id,
415
- activation: envelope.activation,
416
- label: accessibleName(envelope, displayName),
417
- module: interactive.module,
418
- exportName: interactive.exportName,
419
- props: envelopeProps(envelope),
420
- fallback,
421
- ...(provenance ? { provenance } : {}),
422
- },
423
- ]);
424
- }
425
- function blockNodes(block, options, diagnostics, references, displayName, pins = []) {
426
- if (isInteractiveEnvelope(block.data))
427
- return interactiveNodes(block, block.data, options, diagnostics, references, displayName, pins);
428
- const data = block.data;
429
- const reference = references.find((entry) => entry.blockId === block.id);
430
- switch (block.type) {
431
- case "publisle:paragraph":
432
- return [
433
- element("p", {}, inline(data["content"], diagnostics, block, references)),
434
- ];
435
- case "publisle:heading":
436
- return [
437
- element(`h${Number(data["level"])}`, {
438
- "data-publisle-id": block.id,
439
- ...(typeof data["label"] === "string"
440
- ? { id: `reference-${data["label"]}` }
441
- : {}),
442
- }, inline(data["content"], diagnostics, block, references)),
443
- ];
444
- case "publisle:list":
445
- return flow([{ type: "list", ...data }], diagnostics, block, references);
446
- case "publisle:quote":
447
- return [
448
- element("blockquote", {}, flow(data["children"], diagnostics, block, references)),
449
- ];
450
- case "publisle:code":
451
- return flow([{ type: "code", ...data }], diagnostics, block, references);
452
- case "publisle:math":
453
- return [
454
- element(data["display"] === true ? "div" : "span", {
455
- class: data["display"] === true && reference?.ordinal
456
- ? "publisle-math publisle-math-numbered"
457
- : "publisle-math",
458
- ...(typeof data["label"] === "string"
459
- ? { id: `reference-${data["label"]}` }
460
- : {}),
461
- }, [
462
- ...renderMath(String(data["value"] ?? ""), data["display"] === true, diagnostics, block),
463
- ...(reference?.ordinal
464
- ? [
465
- element("span", { class: "publisle-equation-number" }, [
466
- text(`(${reference.ordinal})`),
467
- ]),
468
- ]
469
- : []),
470
- ]),
471
- ];
472
- case "publisle:divider":
473
- return [element("hr", {}, [])];
474
- case "publisle:figure": {
475
- const src = safeUrl(String(data["src"] ?? ""));
476
- const original = data["original"];
477
- const originalSrc = typeof original?.["src"] === "string"
478
- ? safeUrl(original["src"])
479
- : undefined;
480
- if (!src)
481
- diagnostics.push({
482
- level: "warning",
483
- code: "unsafe-url",
484
- message: "An unsafe figure URL was removed.",
485
- blockId: block.id,
486
- });
487
- // Alternative renditions keyed by variant name ("dark", …). The host's
488
- // CSS decides which variant its active theme consumes; hosts without a
489
- // mapping keep the base rendition.
490
- const variants = Object.entries((data["variants"] ?? {})).flatMap(([name, value]) => {
491
- if (typeof value !== "string")
492
- return [];
493
- const variantSrc = safeUrl(value);
494
- if (!variantSrc) {
495
- diagnostics.push({
496
- level: "warning",
497
- code: "unsafe-url",
498
- message: `An unsafe figure ${name} variant URL was removed.`,
499
- blockId: block.id,
500
- });
501
- return [];
502
- }
503
- return [[name, variantSrc]];
504
- });
505
- const themed = src !== undefined && variants.length > 0;
506
- return [
507
- element("figure", {
508
- ...(typeof data["label"] === "string"
509
- ? { id: `reference-${data["label"]}` }
510
- : {}),
511
- ...(themed ? { class: "publisle-figure-themed" } : {}),
512
- }, [
513
- element("img", {
514
- ...(src ? { src } : {}),
515
- alt: String(data["alt"] ?? "Figure description missing."),
516
- }, []),
517
- ...variants.map(([name, variantSrc]) =>
518
- // The base image carries the description; renditions are decorative.
519
- element("img", {
520
- src: variantSrc,
521
- alt: "",
522
- "data-publisle-variant": name,
523
- "aria-hidden": "true",
524
- }, [])),
525
- ...(data["alt"] === undefined
526
- ? [
527
- element("p", { class: "publisle-figure-missing-alt" }, [
528
- text("Figure description missing."),
529
- ]),
530
- ]
531
- : []),
532
- ...(reference || Array.isArray(data["caption"])
533
- ? [
534
- element("figcaption", {}, [
535
- ...(reference
536
- ? [
537
- element("span", { class: "publisle-figure-number" }, [
538
- text(`${referenceText(reference)}. `),
539
- ]),
540
- ]
541
- : []),
542
- ...(Array.isArray(data["caption"])
543
- ? flow(data["caption"], diagnostics, block, references)
544
- : []),
545
- ]),
546
- ]
547
- : []),
548
- ...(Array.isArray(data["credit"])
549
- ? [
550
- element("small", { class: "publisle-figure-credit" }, inline(data["credit"], diagnostics, block, references)),
551
- ]
552
- : []),
553
- ...(originalSrc
554
- ? [
555
- element("a", {
556
- class: "publisle-figure-original",
557
- href: originalSrc,
558
- download: String(original?.["filename"] ?? true),
559
- }, [text("Download original")]),
560
- ]
561
- : []),
562
- ]),
563
- ];
564
- }
565
- case "publisle:table": {
566
- const rows = data["rows"];
567
- const align = data["align"];
568
- return [
569
- element("figure", typeof data["label"] === "string"
570
- ? { id: `reference-${data["label"]}` }
571
- : {}, [
572
- ...(reference || Array.isArray(data["caption"])
573
- ? [
574
- element("figcaption", {}, [
575
- ...(reference
576
- ? [
577
- element("span", { class: "publisle-table-number" }, [
578
- text(`${referenceText(reference)}. `),
579
- ]),
580
- ]
581
- : []),
582
- ...(Array.isArray(data["caption"])
583
- ? flow(data["caption"], diagnostics, block, references)
584
- : []),
585
- ]),
586
- ]
587
- : []),
588
- element("table", {}, [
589
- element("tbody", {}, rows.map((row, rowIndex) => element("tr", {}, row.map((cell, cellIndex) => element((typeof data["headerRows"] === "number"
590
- ? data["headerRows"]
591
- : 1) > rowIndex
592
- ? "th"
593
- : "td", {
594
- ...((typeof data["headerRows"] === "number"
595
- ? data["headerRows"]
596
- : 1) > rowIndex
597
- ? { scope: "col" }
598
- : {}),
599
- ...(align[cellIndex]
600
- ? { class: `publisle-align-${align[cellIndex]}` }
601
- : {}),
602
- }, inline(cell, diagnostics, block, references)))))),
603
- ]),
604
- ]),
605
- ];
606
- }
607
- case "publisle:callout":
608
- return [
609
- element("aside", {
610
- class: `publisle-callout publisle-callout-${String(data["variant"] ?? "note")}`,
611
- }, [
612
- ...(typeof data["title"] === "string"
613
- ? [element("strong", {}, [text(data["title"])])]
614
- : []),
615
- ...flow(data["children"], diagnostics, block, references),
616
- ]),
617
- ];
618
- case "publisle:footnote":
619
- return [
620
- element("aside", { id: `footnote-${String(data["identifier"] ?? "")}` }, flow(data["children"], diagnostics, block, references)),
621
- ];
622
- case "publisle:embed": {
623
- const providerName = String(data["provider"] ?? "");
624
- const configuredProvider = options.embedProviders?.[providerName];
625
- const builtinProvider = builtinEmbedProviders[providerName];
626
- const provider = configuredProvider ??
627
- (builtinProvider
628
- ? (resourceId) => builtinProvider(resourceId)
629
- : undefined);
630
- const result = provider?.(String(data["resourceId"] ?? ""));
631
- const embedSrc = result ? safeEmbedUrl(result.src) : undefined;
632
- if (!result || !embedSrc) {
633
- diagnostics.push({
634
- level: "warning",
635
- code: "missing-embed-provider",
636
- message: `Embed provider ${providerName} is unavailable or rejected the resource ID.`,
637
- blockId: block.id,
638
- });
639
- return Array.isArray(data["fallback"])
640
- ? flow(data["fallback"], diagnostics, block, references)
641
- : [
642
- element("p", { "data-publisle-embed-unavailable": providerName }, [text(String(data["title"] ?? "Embedded content"))]),
643
- ];
644
- }
645
- const ratio = data["aspectRatio"];
646
- return [
647
- element("figure", { class: "publisle-embed" }, [
648
- element("iframe", {
649
- src: embedSrc,
650
- title: String(data["title"] ?? ""),
651
- loading: "lazy",
652
- referrerpolicy: "strict-origin-when-cross-origin",
653
- allow: result.allow ?? "fullscreen",
654
- sandbox: ("sandbox" in result ? result.sandbox : undefined) ??
655
- "allow-scripts allow-same-origin allow-presentation",
656
- ...(result.allowFullscreen ? { allowfullscreen: true } : {}),
657
- style: `aspect-ratio:${Number(ratio["width"] ?? 16)}/${Number(ratio["height"] ?? 9)}`,
658
- }, []),
659
- ...(Array.isArray(data["caption"])
660
- ? [
661
- element("figcaption", {}, flow(data["caption"], diagnostics, block, references)),
662
- ]
663
- : []),
664
- ]),
665
- ];
666
- }
667
- case "publisle:diagram": {
668
- const engine = String(data["engine"] ?? "");
669
- const renderer = options.diagramRenderers?.[engine];
670
- if (!renderer) {
671
- diagnostics.push({
672
- level: "warning",
673
- code: "missing-diagram-renderer",
674
- message: `No renderer is registered for diagram engine ${engine}.`,
675
- blockId: block.id,
676
- });
677
- const print = data["printFallback"];
678
- const printSrc = typeof print?.["src"] === "string"
679
- ? safeUrl(print["src"])
680
- : undefined;
681
- const fallback = printSrc
682
- ? [
683
- element("img", { src: printSrc, alt: String(data["alt"] ?? "") }, []),
684
- ]
685
- : Array.isArray(data["fallback"])
686
- ? flow(data["fallback"], diagnostics, block, references)
687
- : [element("pre", {}, [text(String(data["source"] ?? ""))])];
688
- return [
689
- element("figure", typeof data["label"] === "string"
690
- ? { id: `reference-${data["label"]}` }
691
- : {}, [
692
- ...fallback,
693
- ...(reference || Array.isArray(data["caption"])
694
- ? [
695
- element("figcaption", {}, [
696
- ...(reference
697
- ? [
698
- element("span", { class: "publisle-diagram-number" }, [text(`${referenceText(reference)}. `)]),
699
- ]
700
- : []),
701
- ...(Array.isArray(data["caption"])
702
- ? flow(data["caption"], diagnostics, block, references)
703
- : []),
704
- ]),
705
- ]
706
- : []),
707
- ]),
708
- ];
709
- }
710
- let result;
711
- try {
712
- result = renderer({
713
- engine,
714
- source: String(data["source"] ?? ""),
715
- alt: String(data["alt"] ?? ""),
716
- });
717
- }
718
- catch (error) {
719
- diagnostics.push({
720
- level: "warning",
721
- code: "diagram-render-failed",
722
- message: error instanceof Error
723
- ? error.message
724
- : `Rendering ${engine} failed.`,
725
- blockId: block.id,
726
- });
727
- return Array.isArray(data["fallback"])
728
- ? flow(data["fallback"], diagnostics, block, references)
729
- : [element("pre", {}, [text(String(data["source"] ?? ""))])];
730
- }
731
- const rendered = [...result.static];
732
- if (result.interactive)
733
- rendered.push({
734
- kind: "island",
735
- blockId: block.id,
736
- implementation: result.interactive.implementation,
737
- activation: result.interactive.activation ?? "visible",
738
- label: result.accessibleText ?? String(data["alt"] ?? "Diagram"),
739
- module: result.interactive.module,
740
- exportName: result.interactive.exportName ?? "default",
741
- props: result.interactive.props ?? {},
742
- fallback: result.static,
743
- });
744
- return [
745
- element("figure", typeof data["label"] === "string"
746
- ? { id: `reference-${data["label"]}` }
747
- : {}, [
748
- element("div", { class: "publisle-diagram-screen" }, rendered),
749
- ...(result.print
750
- ? [
751
- element("div", { class: "publisle-diagram-print" }, result.print),
752
- ]
753
- : []),
754
- ...(reference || Array.isArray(data["caption"])
755
- ? [
756
- element("figcaption", {}, [
757
- ...(reference
758
- ? [
759
- element("span", { class: "publisle-diagram-number" }, [text(`${referenceText(reference)}. `)]),
760
- ]
761
- : []),
762
- ...(Array.isArray(data["caption"])
763
- ? flow(data["caption"], diagnostics, block, references)
764
- : []),
765
- ]),
766
- ]
767
- : []),
768
- ]),
769
- ];
770
- }
771
- case "publisle:bibliography": {
772
- const entries = Array.isArray(data["entries"]) ? data["entries"] : [];
773
- if (options.bibliography)
774
- return [
775
- element("section", { class: "publisle-bibliography" }, options.bibliography.map((entry) => element("p", { "data-publisle-bibliography-id": entry.id }, [
776
- text(entry.text),
777
- ]))),
778
- ];
779
- return [
780
- element("section", { class: "publisle-bibliography" }, entries.flatMap((entry) => {
781
- if (typeof entry !== "object" ||
782
- entry === null ||
783
- Array.isArray(entry))
784
- return [];
785
- const record = entry;
786
- const authors = Array.isArray(record["authors"])
787
- ? record["authors"].filter((author) => typeof author === "string")
788
- : [];
789
- const parts = [
790
- record["id"],
791
- ...authors,
792
- record["title"],
793
- record["raw"],
794
- ].filter((part) => typeof part === "string");
795
- return [element("p", {}, [text(parts.join(" "))])];
796
- })),
797
- ];
798
- }
799
- case "publisle:raw-html":
800
- return options.rawHtml === "omit"
801
- ? []
802
- : options.rawHtml === "trusted" || typeof options.rawHtml === "function"
803
- ? [
804
- {
805
- kind: "raw",
806
- value: typeof options.rawHtml === "function"
807
- ? options.rawHtml(String(data["value"] ?? ""))
808
- : String(data["value"] ?? ""),
809
- },
810
- ]
811
- : [
812
- element("pre", { "data-publisle-raw-html": true }, [
813
- text(String(data["value"] ?? "")),
814
- ]),
815
- ];
816
- default:
817
- diagnostics.push({
818
- level: "warning",
819
- code: "missing-renderer",
820
- message: `No renderer is available for ${block.type}.`,
821
- blockId: block.id,
822
- });
823
- if ("readableContent" in block && block.readableContent) {
824
- const content = block.readableContent;
825
- const prose = content.fallback?.length
826
- ? [content.fallback]
827
- : [
828
- content.title,
829
- content.description,
830
- content.purpose,
831
- content.instructions,
832
- content.observations,
833
- content.assumptions,
834
- ...(content.presets?.map((preset) => preset.description) ?? []),
835
- ];
836
- return [
837
- element("section", { "data-publisle-unknown-block": block.type }, [
838
- ...(block.readable?.provenance.kind === "generated"
839
- ? [
840
- element("p", { "data-publisle-generated": true }, [
841
- text(`Generated by ${block.readable.provenance.generator} (${block.readable.provenance.version}); source: ${block.readable.provenance.source}.`),
842
- ]),
843
- ]
844
- : []),
845
- ...prose
846
- .filter((nodes) => nodes?.length)
847
- .map((nodes) => element("p", {}, [text(richText(nodes))])),
848
- ]),
849
- ];
850
- }
851
- return [
852
- element("div", { "data-publisle-unknown-block": block.type }, [
853
- text(`Unsupported block: ${block.type}`),
854
- ]),
855
- ];
856
- }
857
- }
858
- export function createRenderPlan(document, options = {}) {
859
- const diagnostics = [];
860
- const nodes = applyFootnoteNumbers(document.blocks.flatMap((block) => blockNodes(block, options, diagnostics, document.references.targets, document.islands.find((island) => island.blockId === block.id)
861
- ?.displayName, document.dependencies ?? [])), collectFootnoteNumbers(document.blocks));
862
- const base = {
863
- document,
864
- nodes: wrapInputs(resolveCitations(nodes, options.citations), document),
865
- diagnostics: diagnostics.map((diagnostic) => locateDiagnostic(diagnostic, document.sourceMap)),
866
- };
867
- return document.metadata === undefined
868
- ? base
869
- : { ...base, metadata: document.metadata };
870
- }
871
- /** Footnote numbers by first-reference order, over the raw block payloads. */
872
- function collectFootnoteNumbers(blocks) {
873
- const numbers = new Map();
874
- const visit = (value) => {
875
- if (Array.isArray(value)) {
876
- value.forEach(visit);
877
- return;
878
- }
879
- if (!value || typeof value !== "object")
880
- return;
881
- const node = value;
882
- if (node["type"] === "footnoteReference" &&
883
- typeof node["identifier"] === "string" &&
884
- !numbers.has(node["identifier"]))
885
- numbers.set(node["identifier"], numbers.size + 1);
886
- for (const child of Object.values(node))
887
- visit(child);
888
- };
889
- for (const block of blocks)
890
- visit(block.data);
891
- return numbers;
892
- }
893
- /** Replace raw footnote labels with numbers on markers and definitions. */
894
- function applyFootnoteNumbers(nodes, numbers) {
895
- return nodes.map((node) => {
896
- if (node.kind !== "element")
897
- return node;
898
- const reference = node.tag === "sup" ? node : undefined;
899
- const anchor = reference?.children.find((child) => child.kind === "element" &&
900
- child.tag === "a" &&
901
- typeof child.attributes["data-publisle-ref"] === "string" &&
902
- child.attributes["data-publisle-ref"].startsWith("footnote-"));
903
- if (anchor) {
904
- const identifier = String(anchor.attributes["data-publisle-ref"]).slice("footnote-".length);
905
- const number = numbers.get(identifier);
906
- return number === undefined
907
- ? node
908
- : {
909
- ...node,
910
- children: node.children.map((child) => child === anchor
911
- ? { ...anchor, children: [text(String(number))] }
912
- : child),
913
- };
914
- }
915
- if (node.tag === "aside" && typeof node.attributes["id"] === "string") {
916
- const number = numbers.get(node.attributes["id"].slice("footnote-".length));
917
- if (number !== undefined)
918
- return {
919
- ...node,
920
- children: [
921
- element("span", { class: "publisle-footnote-number" }, [
922
- text(`${String(number)}. `),
923
- ]),
924
- ...node.children,
925
- ],
926
- };
927
- }
928
- return { ...node, children: applyFootnoteNumbers(node.children, numbers) };
929
- });
930
- }
931
- function resolveCitations(nodes, citations) {
932
- if (!citations)
933
- return [...nodes];
934
- return nodes.map((node) => {
935
- if (node.kind === "island")
936
- return { ...node, fallback: resolveCitations(node.fallback, citations) };
937
- if (node.kind === "component" && node.artifact)
938
- return { ...node, artifact: resolveCitations(node.artifact, citations) };
939
- if (node.kind !== "element")
940
- return node;
941
- const raw = node.attributes["data-publisle-citation"];
942
- if (typeof raw === "string") {
943
- const key = citationKey({
944
- items: JSON.parse(raw),
945
- prefix: String(node.attributes["data-publisle-citation-prefix"] ?? ""),
946
- suffix: String(node.attributes["data-publisle-citation-suffix"] ?? ""),
947
- });
948
- const value = citations[key];
949
- if (value !== undefined)
950
- return { ...node, children: [text(value)] };
951
- }
952
- return { ...node, children: resolveCitations(node.children, citations) };
953
- });
954
- }
955
- function wrapInputs(nodes, document) {
956
- return nodes.map((node) => {
957
- if (node.kind === "element")
958
- return { ...node, children: wrapInputs(node.children, document) };
959
- if (node.kind !== "island" && !(node.kind === "component" && node.blockId))
960
- return node;
961
- const block = document.blocks.find((entry) => entry.id === node.blockId);
962
- if (!block)
963
- throw new Error("Island input requires a corresponding prepared block.");
964
- const activation = node.kind === "island" ? node.activation : "visible";
965
- const envelope = isInteractiveEnvelope(node.props)
966
- ? node.props
967
- : { activation, payload: node.props };
968
- return {
969
- ...node,
970
- ...(node.kind === "island"
971
- ? { fallback: wrapInputs(node.fallback, document) }
972
- : {}),
973
- props: createIslandInput(block, envelope, document.dependencies),
974
- };
975
- });
2
+ import { createRenderPlan as create, installMathRenderer, } from "./render-plan-core.js";
3
+ export { citationKey } from "./render-plan-core.js";
4
+ /** Synchronous compiler with bundled math support. */
5
+ export function createRenderPlan(...args) {
6
+ installMathRenderer(katex);
7
+ return create(...args);
976
8
  }
977
9
  //# sourceMappingURL=render-plan.js.map