@publisle/adapter-core 0.1.1 → 0.2.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.
package/src/html.ts CHANGED
@@ -99,25 +99,59 @@ function publicationAttributes(
99
99
  return result;
100
100
  }
101
101
 
102
- function readAttributes(source: string): Map<string, string> {
103
- const attributes = new Map<string, string>();
102
+ interface AttributeToken {
103
+ readonly name: string;
104
+ readonly value: string;
105
+ readonly start: number;
106
+ readonly end: number;
107
+ }
108
+
109
+ // Only changed placement references are decoded. These are emitted by our
110
+ // serializer, which uses the five XML entities; numeric references are supported
111
+ // as well. All unrelated authored HTML remains byte-for-byte unchanged.
112
+ function decodeReference(value: string): string {
113
+ const entities: Record<string, string> = {
114
+ amp: "&",
115
+ quot: '"',
116
+ apos: "'",
117
+ lt: "<",
118
+ gt: ">",
119
+ };
120
+ return value.replace(
121
+ /&(#x[0-9a-f]+|#[0-9]+|amp|quot|apos|lt|gt);/giu,
122
+ (source, entity: string) => {
123
+ if (!entity.startsWith("#"))
124
+ return entities[entity.toLowerCase()] ?? source;
125
+ const point =
126
+ entity[1]?.toLowerCase() === "x"
127
+ ? Number.parseInt(entity.slice(2), 16)
128
+ : Number(entity.slice(1));
129
+ return point > 0 &&
130
+ point <= 0x10ffff &&
131
+ !(point >= 0xd800 && point <= 0xdfff)
132
+ ? String.fromCodePoint(point)
133
+ : "\uFFFD";
134
+ },
135
+ );
136
+ }
137
+
138
+ function readAttributes(tag: string): AttributeToken[] {
139
+ if (!/^<[A-Za-z]/u.test(tag)) return [];
140
+ const nameEnd = tag.search(/[\s/>]/u);
141
+ if (nameEnd < 0) return [];
142
+ const tokens: AttributeToken[] = [];
104
143
  const pattern =
105
144
  /([^\s=/><]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+)))?/gu;
145
+ const source = tag.slice(nameEnd, tag.endsWith("/>") ? -2 : -1);
106
146
  for (const match of source.matchAll(pattern)) {
107
- const name = match[1];
108
- if (!name) continue;
109
- const value = match[2] ?? match[3] ?? match[4] ?? "";
110
- attributes.set(name, value);
111
- }
112
- return attributes;
113
- }
114
-
115
- function writeAttributes(attributes: ReadonlyMap<string, string>): string {
116
- let result = "";
117
- for (const [name, value] of attributes) {
118
- result += ` ${name}="${escapeAttribute(value)}"`;
147
+ tokens.push({
148
+ name: (match[1] ?? "").toLowerCase(),
149
+ value: match[2] ?? match[3] ?? match[4] ?? "",
150
+ start: nameEnd + match.index,
151
+ end: nameEnd + match.index + match[0].length,
152
+ });
119
153
  }
120
- return result;
154
+ return tokens;
121
155
  }
122
156
 
123
157
  /** Assign placement ids from recorded attributes. This walks tags, not document text. */
@@ -125,33 +159,53 @@ export function instantiateHtml(html: string, instanceId: string): string {
125
159
  if (!/^[A-Za-z][A-Za-z0-9_-]{0,63}$/u.test(instanceId))
126
160
  throw new Error("Placement ID must be a bounded safe host identifier.");
127
161
  const generated = new Set<string>();
128
- for (let offset = 0; offset < html.length;) {
162
+ for (const { tag } of htmlTags(html)) {
163
+ const rawId = readAttributes(tag).find(
164
+ (token) => token.name === "data-publisle-id",
165
+ )?.value;
166
+ if (rawId !== undefined) generated.add(decodeReference(rawId));
167
+ }
168
+ let result = "";
169
+ let offset = 0;
170
+ for (const { start, end, tag } of htmlTags(html)) {
171
+ result +=
172
+ html.slice(offset, start) + rewriteTag(tag, instanceId, generated);
173
+ offset = end + 1;
174
+ }
175
+ return result + html.slice(offset);
176
+ }
177
+
178
+ function* htmlTags(
179
+ html: string,
180
+ ): Generator<{ start: number; end: number; tag: string }> {
181
+ let offset = 0;
182
+ while (offset < html.length) {
129
183
  const start = html.indexOf("<", offset);
130
- if (start < 0) break;
184
+ if (start < 0) return;
131
185
  const end = tagEnd(html, start);
132
186
  const tag = html.slice(start, end + 1);
133
- const id = /\bdata-publisle-id="([^"]*)"/u.exec(tag)?.[1];
134
- if (id !== undefined) generated.add(id);
187
+ yield { start, end, tag };
135
188
  offset = end + 1;
136
- }
137
- let result = "";
138
- let index = 0;
139
- while (index < html.length) {
140
- const start = html.indexOf("<", index);
141
- if (start === -1) {
142
- result += html.slice(index);
143
- break;
189
+ const raw = /^<(script|style|textarea|title)(?:\s|>)/iu.exec(tag)?.[1];
190
+ if (raw) {
191
+ const closing = new RegExp(`</${raw}\\s*>`, "giu");
192
+ closing.lastIndex = offset;
193
+ const match = closing.exec(html);
194
+ if (!match) return;
195
+ offset = match.index;
144
196
  }
145
- result += html.slice(index, start);
146
- const end = tagEnd(html, start);
147
- const tag = html.slice(start, end + 1);
148
- result += rewriteTag(tag, instanceId, generated);
149
- index = end + 1;
150
197
  }
151
- return result;
152
198
  }
153
199
 
154
200
  function tagEnd(html: string, start: number): number {
201
+ if (html.startsWith("<![CDATA[", start)) {
202
+ const end = html.indexOf("]]>", start + 9);
203
+ return end < 0 ? html.length - 1 : end + 2;
204
+ }
205
+ if (html.startsWith("<!--", start)) {
206
+ const end = html.indexOf("-->", start + 4);
207
+ return end < 0 ? html.length - 1 : end + 2;
208
+ }
155
209
  let quote = "";
156
210
  for (let index = start + 1; index < html.length; index += 1) {
157
211
  const character = html[index] ?? "";
@@ -175,18 +229,15 @@ function rewriteTag(
175
229
  ): string {
176
230
  if (!tag.startsWith("<") || tag.startsWith("</") || tag.startsWith("<!"))
177
231
  return tag;
178
- const nameEnd = tag.search(/[\s/>]/u);
179
- const tagName = tag.slice(1, nameEnd === -1 ? undefined : nameEnd);
180
- const attributeSource = tag.slice(
181
- tagName.length + 1,
182
- tag.endsWith("/>") ? -2 : -1,
232
+ const tokens = readAttributes(tag);
233
+ const attributes = new Map(
234
+ tokens.map((token) => [token.name, decodeReference(token.value)]),
183
235
  );
184
- const attributes = readAttributes(attributeSource);
236
+ const changes = new Map<string, string>();
185
237
  const localId = attributes.get("data-publisle-id");
186
- if (localId !== undefined) attributes.set("id", `${instanceId}-${localId}`);
238
+ if (localId !== undefined) changes.set("id", `${instanceId}-${localId}`);
187
239
  const localRef = attributes.get("data-publisle-ref");
188
- if (localRef !== undefined)
189
- attributes.set("href", `#${instanceId}-${localRef}`);
240
+ if (localRef !== undefined) changes.set("href", `#${instanceId}-${localRef}`);
190
241
  for (const name of [
191
242
  "aria-labelledby",
192
243
  "aria-describedby",
@@ -202,20 +253,43 @@ function rewriteTag(
202
253
  "form",
203
254
  ]) {
204
255
  const value = attributes.get(name);
205
- if (value !== undefined)
206
- attributes.set(
207
- name,
208
- value
209
- .split(/\s+/u)
210
- .map((id) => (generated.has(id) ? `${instanceId}-${id}` : id))
211
- .join(" "),
212
- );
256
+ if (value !== undefined) {
257
+ const rewritten = value
258
+ .split(/\s+/u)
259
+ .map((id) => (generated.has(id) ? `${instanceId}-${id}` : id))
260
+ .join(" ");
261
+ if (rewritten !== value) changes.set(name, rewritten);
262
+ }
213
263
  }
214
264
  for (const name of ["href", "xlink:href"]) {
215
265
  const value = attributes.get(name);
216
- if (value?.startsWith("#") && generated.has(value.slice(1)))
217
- attributes.set(name, `#${instanceId}-${value.slice(1)}`);
266
+ if (
267
+ !changes.has(name) &&
268
+ value?.startsWith("#") &&
269
+ generated.has(value.slice(1))
270
+ )
271
+ changes.set(name, `#${instanceId}-${value.slice(1)}`);
218
272
  }
219
- const closing = tag.endsWith("/>") ? " />" : ">";
220
- return `<${tagName}${writeAttributes(attributes)}${closing}`;
273
+ let result = "";
274
+ let offset = 0;
275
+ for (const token of tokens) {
276
+ const value = changes.get(token.name);
277
+ if (value === undefined) continue;
278
+ result +=
279
+ tag.slice(offset, token.start) +
280
+ `${token.name}="${escapeAttribute(value)}"`;
281
+ offset = token.end;
282
+ }
283
+ result += tag.slice(offset);
284
+ const added = [...changes].filter(([name]) => !attributes.has(name));
285
+ if (added.length) {
286
+ const end = result.length - (result.endsWith("/>") ? 2 : 1);
287
+ result =
288
+ result.slice(0, end) +
289
+ added
290
+ .map(([name, value]) => ` ${name}="${escapeAttribute(value)}"`)
291
+ .join("") +
292
+ result.slice(end);
293
+ }
294
+ return result;
221
295
  }
package/src/index.ts CHANGED
@@ -34,3 +34,4 @@ export {
34
34
  publicationReaderManifest,
35
35
  type PublicationReaderManifest,
36
36
  } from "./publication.ts";
37
+ export { citationKey } from "./render-plan.ts";
@@ -133,17 +133,19 @@ export function createIslandController(
133
133
  options.activation === "visible" &&
134
134
  "IntersectionObserver" in globalThis
135
135
  ) {
136
+ let wasVisible = false;
136
137
  const observer = new IntersectionObserver((entries) => {
137
138
  const visible = entries.some(({ isIntersecting }) => isIntersecting);
138
- if (visible) void activate();
139
- else if (options.suspend) {
139
+ const entering = visible && !wasVisible;
140
+ wasVisible = visible;
141
+ if (entering) void activate();
142
+ else if (!visible && options.suspend) {
140
143
  generation += 1;
141
144
  abort?.abort();
142
145
  pending = undefined;
143
146
  scope.setAttribute?.("aria-busy", "false");
144
147
  release();
145
148
  }
146
- if (visible && !options.suspend) observer.disconnect();
147
149
  });
148
150
  observer.observe(scope);
149
151
  cleanup = () => observer.disconnect();
@@ -191,9 +193,20 @@ export function createIslandController(
191
193
  destroyed = true;
192
194
  generation += 1;
193
195
  abort?.abort();
194
- cleanup();
195
- release();
196
- scope.removeAttribute?.("aria-busy");
196
+ const errors: unknown[] = [];
197
+ for (const operation of [
198
+ cleanup,
199
+ release,
200
+ () => scope.removeAttribute?.("aria-busy"),
201
+ ]) {
202
+ try {
203
+ operation();
204
+ } catch (error) {
205
+ errors.push(error);
206
+ }
207
+ }
208
+ if (errors.length)
209
+ throw new AggregateError(errors, "Island cleanup failed.");
197
210
  },
198
211
  };
199
212
  }
@@ -163,8 +163,20 @@ export function attachPublication(
163
163
  dispose() {
164
164
  if (disposed) return;
165
165
  disposed = true;
166
- for (const controller of controllers) controller.destroy();
167
- if (attachments.get(root)?.handle === handle) attachments.delete(root);
166
+ const errors: unknown[] = [];
167
+ try {
168
+ for (const controller of controllers) {
169
+ try {
170
+ controller.destroy();
171
+ } catch (error) {
172
+ errors.push(error);
173
+ }
174
+ }
175
+ } finally {
176
+ if (attachments.get(root)?.handle === handle) attachments.delete(root);
177
+ }
178
+ if (errors.length)
179
+ throw new AggregateError(errors, "Publication cleanup failed.");
168
180
  },
169
181
  };
170
182
  attachments.set(root, { key: artifact.identity, handle });
@@ -315,6 +315,12 @@ export function compilePublication(
315
315
  if (isRenderPlan(source))
316
316
  return compilePlan(source, styles, options.build, options.rawHtmlPlacement);
317
317
  const compilerOptions: AdapterCompilerOptions = {
318
+ ...(options.citations === undefined
319
+ ? {}
320
+ : { citations: options.citations }),
321
+ ...(options.bibliography === undefined
322
+ ? {}
323
+ : { bibliography: options.bibliography }),
318
324
  ...(options.renderers === undefined
319
325
  ? {}
320
326
  : { renderers: options.renderers }),
@@ -30,6 +30,29 @@ const element = (
30
30
  children: readonly RenderNode[],
31
31
  ): RenderNode => ({ kind: "element", tag, attributes, children });
32
32
 
33
+ /** Stable identity for a citation cluster, independent of object property order. */
34
+ export function citationKey(cluster: {
35
+ readonly items: readonly {
36
+ readonly id: string;
37
+ readonly locator?: string;
38
+ readonly label?: string;
39
+ readonly suppressAuthor?: boolean;
40
+ }[];
41
+ readonly prefix?: string;
42
+ readonly suffix?: string;
43
+ }): string {
44
+ return JSON.stringify([
45
+ cluster.items.map((item) => [
46
+ item.id,
47
+ item.locator ?? "",
48
+ item.label ?? "",
49
+ item.suppressAuthor ?? false,
50
+ ]),
51
+ cluster.prefix ?? "",
52
+ cluster.suffix ?? "",
53
+ ]);
54
+ }
55
+
33
56
  function referenceText(target: ReferenceTarget): string {
34
57
  if (target.kind === "heading") return target.title ?? target.label;
35
58
  const name = target.kind.charAt(0).toUpperCase() + target.kind.slice(1);
@@ -74,7 +97,10 @@ function renderMath(
74
97
  }
75
98
 
76
99
  function safeUrl(url: string): string | undefined {
77
- const normalized = url.trim().toLowerCase();
100
+ // Conservative superset of browser URL preprocessing, shared with Python.
101
+ // Browsers remove embedded TAB/LF/CR before identifying a scheme.
102
+ // eslint-disable-next-line no-control-regex -- deliberately remove URL control characters
103
+ const normalized = url.replace(/[\u0000-\u0020]/gu, "").toLowerCase();
78
104
  return /^(?:javascript|vbscript|data):/u.test(normalized) ? undefined : url;
79
105
  }
80
106
 
@@ -109,7 +135,7 @@ function inline(
109
135
  block: Block<BlockType, unknown>,
110
136
  references: readonly ReferenceTarget[] = [],
111
137
  ): RenderNode[] {
112
- return nodes.flatMap((node): RenderNode[] => {
138
+ return nodes.flatMap((node, index): RenderNode[] => {
113
139
  switch (node.type) {
114
140
  case "text": {
115
141
  const value = String(node["value"] ?? "");
@@ -200,6 +226,12 @@ function inline(
200
226
  {
201
227
  class: "publisle-citation",
202
228
  "data-publisle-citation": JSON.stringify(items),
229
+ ...(node["prefix"]
230
+ ? { "data-publisle-citation-prefix": String(node["prefix"]) }
231
+ : {}),
232
+ ...(node["suffix"]
233
+ ? { "data-publisle-citation-suffix": String(node["suffix"]) }
234
+ : {}),
203
235
  },
204
236
  [text(`[${value}]`)],
205
237
  ),
@@ -208,9 +240,29 @@ function inline(
208
240
  case "crossReference": {
209
241
  const target = String(node["target"] ?? "");
210
242
  const resolved = references.find((entry) => entry.label === target);
243
+ const preceding = nodes
244
+ .slice(0, index)
245
+ .map(function plain(item): string {
246
+ return item.type === "text"
247
+ ? String(item["value"] ?? "")
248
+ : Array.isArray(item["children"])
249
+ ? (item["children"] as Inline[]).map(plain).join("")
250
+ : "";
251
+ })
252
+ .join("");
253
+ const kind = resolved?.kind;
254
+ const authoredKind =
255
+ kind &&
256
+ kind !== "heading" &&
257
+ new RegExp(`\\b${kind}\\s+$`, "iu").test(preceding);
258
+ const label = resolved
259
+ ? authoredKind
260
+ ? String(resolved.ordinal ?? resolved.label)
261
+ : referenceText(resolved)
262
+ : target;
211
263
  const children = Array.isArray(node["children"])
212
264
  ? inline(node["children"] as Inline[], diagnostics, block, references)
213
- : [text(resolved ? referenceText(resolved) : target)];
265
+ : [text(label)];
214
266
  return [
215
267
  element(
216
268
  "a",
@@ -653,7 +705,10 @@ function blockNodes(
653
705
  element(
654
706
  data["display"] === true ? "div" : "span",
655
707
  {
656
- class: "publisle-math",
708
+ class:
709
+ data["display"] === true && reference?.ordinal
710
+ ? "publisle-math publisle-math-numbered"
711
+ : "publisle-math",
657
712
  ...(typeof data["label"] === "string"
658
713
  ? { id: `reference-${data["label"]}` }
659
714
  : {}),
@@ -691,12 +746,35 @@ function blockNodes(
691
746
  message: "An unsafe figure URL was removed.",
692
747
  blockId: block.id,
693
748
  });
749
+ // Alternative renditions keyed by variant name ("dark", …). The host's
750
+ // CSS decides which variant its active theme consumes; hosts without a
751
+ // mapping keep the base rendition.
752
+ const variants = Object.entries(
753
+ (data["variants"] ?? {}) as Record<string, unknown>,
754
+ ).flatMap(([name, value]): [string, string][] => {
755
+ if (typeof value !== "string") return [];
756
+ const variantSrc = safeUrl(value);
757
+ if (!variantSrc) {
758
+ diagnostics.push({
759
+ level: "warning",
760
+ code: "unsafe-url",
761
+ message: `An unsafe figure ${name} variant URL was removed.`,
762
+ blockId: block.id,
763
+ });
764
+ return [];
765
+ }
766
+ return [[name, variantSrc]];
767
+ });
768
+ const themed = src !== undefined && variants.length > 0;
694
769
  return [
695
770
  element(
696
771
  "figure",
697
- typeof data["label"] === "string"
698
- ? { id: `reference-${data["label"]}` }
699
- : {},
772
+ {
773
+ ...(typeof data["label"] === "string"
774
+ ? { id: `reference-${data["label"]}` }
775
+ : {}),
776
+ ...(themed ? { class: "publisle-figure-themed" } : {}),
777
+ },
700
778
  [
701
779
  element(
702
780
  "img",
@@ -706,6 +784,19 @@ function blockNodes(
706
784
  },
707
785
  [],
708
786
  ),
787
+ ...variants.map(([name, variantSrc]) =>
788
+ // The base image carries the description; renditions are decorative.
789
+ element(
790
+ "img",
791
+ {
792
+ src: variantSrc,
793
+ alt: "",
794
+ "data-publisle-variant": name,
795
+ "aria-hidden": "true",
796
+ },
797
+ [],
798
+ ),
799
+ ),
709
800
  ...(data["alt"] === undefined
710
801
  ? [
711
802
  element("p", { class: "publisle-figure-missing-alt" }, [
@@ -1064,6 +1155,18 @@ function blockNodes(
1064
1155
  }
1065
1156
  case "publisle:bibliography": {
1066
1157
  const entries = Array.isArray(data["entries"]) ? data["entries"] : [];
1158
+ if (options.bibliography)
1159
+ return [
1160
+ element(
1161
+ "section",
1162
+ { class: "publisle-bibliography" },
1163
+ options.bibliography.map((entry) =>
1164
+ element("p", { "data-publisle-bibliography-id": entry.id }, [
1165
+ text(entry.text),
1166
+ ]),
1167
+ ),
1168
+ ),
1169
+ ];
1067
1170
  return [
1068
1171
  element(
1069
1172
  "section",
@@ -1160,20 +1263,23 @@ export function createRenderPlan(
1160
1263
  options: AdapterCompilerOptions = {},
1161
1264
  ): RenderPlan {
1162
1265
  const diagnostics: Diagnostic[] = [];
1163
- const nodes = document.blocks.flatMap((block) =>
1164
- blockNodes(
1165
- block,
1166
- options,
1167
- diagnostics,
1168
- document.references.targets,
1169
- document.islands.find((island) => island.blockId === block.id)
1170
- ?.displayName,
1171
- document.dependencies ?? [],
1266
+ const nodes = applyFootnoteNumbers(
1267
+ document.blocks.flatMap((block) =>
1268
+ blockNodes(
1269
+ block,
1270
+ options,
1271
+ diagnostics,
1272
+ document.references.targets,
1273
+ document.islands.find((island) => island.blockId === block.id)
1274
+ ?.displayName,
1275
+ document.dependencies ?? [],
1276
+ ),
1172
1277
  ),
1278
+ collectFootnoteNumbers(document.blocks),
1173
1279
  );
1174
1280
  const base = {
1175
1281
  document,
1176
- nodes: wrapInputs(nodes, document),
1282
+ nodes: wrapInputs(resolveCitations(nodes, options.citations), document),
1177
1283
  diagnostics: diagnostics.map((diagnostic) =>
1178
1284
  locateDiagnostic(diagnostic, document.sourceMap),
1179
1285
  ),
@@ -1183,6 +1289,105 @@ export function createRenderPlan(
1183
1289
  : { ...base, metadata: document.metadata };
1184
1290
  }
1185
1291
 
1292
+ /** Footnote numbers by first-reference order, over the raw block payloads. */
1293
+ function collectFootnoteNumbers(
1294
+ blocks: readonly { readonly data: unknown }[],
1295
+ ): ReadonlyMap<string, number> {
1296
+ const numbers = new Map<string, number>();
1297
+ const visit = (value: unknown): void => {
1298
+ if (Array.isArray(value)) {
1299
+ value.forEach(visit);
1300
+ return;
1301
+ }
1302
+ if (!value || typeof value !== "object") return;
1303
+ const node = value as Record<string, unknown>;
1304
+ if (
1305
+ node["type"] === "footnoteReference" &&
1306
+ typeof node["identifier"] === "string" &&
1307
+ !numbers.has(node["identifier"])
1308
+ )
1309
+ numbers.set(node["identifier"], numbers.size + 1);
1310
+ for (const child of Object.values(node)) visit(child);
1311
+ };
1312
+ for (const block of blocks) visit(block.data);
1313
+ return numbers;
1314
+ }
1315
+
1316
+ /** Replace raw footnote labels with numbers on markers and definitions. */
1317
+ function applyFootnoteNumbers(
1318
+ nodes: readonly RenderNode[],
1319
+ numbers: ReadonlyMap<string, number>,
1320
+ ): RenderNode[] {
1321
+ return nodes.map((node) => {
1322
+ if (node.kind !== "element") return node;
1323
+ const reference = node.tag === "sup" ? node : undefined;
1324
+ const anchor = reference?.children.find(
1325
+ (child): child is Extract<RenderNode, { kind: "element" }> =>
1326
+ child.kind === "element" &&
1327
+ child.tag === "a" &&
1328
+ typeof child.attributes["data-publisle-ref"] === "string" &&
1329
+ child.attributes["data-publisle-ref"].startsWith("footnote-"),
1330
+ );
1331
+ if (anchor) {
1332
+ const identifier = String(anchor.attributes["data-publisle-ref"]).slice(
1333
+ "footnote-".length,
1334
+ );
1335
+ const number = numbers.get(identifier);
1336
+ return number === undefined
1337
+ ? node
1338
+ : {
1339
+ ...node,
1340
+ children: node.children.map((child) =>
1341
+ child === anchor
1342
+ ? { ...anchor, children: [text(String(number))] }
1343
+ : child,
1344
+ ),
1345
+ };
1346
+ }
1347
+ if (node.tag === "aside" && typeof node.attributes["id"] === "string") {
1348
+ const number = numbers.get(
1349
+ node.attributes["id"].slice("footnote-".length),
1350
+ );
1351
+ if (number !== undefined)
1352
+ return {
1353
+ ...node,
1354
+ children: [
1355
+ element("span", { class: "publisle-footnote-number" }, [
1356
+ text(`${String(number)}. `),
1357
+ ]),
1358
+ ...node.children,
1359
+ ],
1360
+ };
1361
+ }
1362
+ return { ...node, children: applyFootnoteNumbers(node.children, numbers) };
1363
+ });
1364
+ }
1365
+
1366
+ function resolveCitations(
1367
+ nodes: readonly RenderNode[],
1368
+ citations: AdapterCompilerOptions["citations"],
1369
+ ): RenderNode[] {
1370
+ if (!citations) return [...nodes];
1371
+ return nodes.map((node) => {
1372
+ if (node.kind === "island")
1373
+ return { ...node, fallback: resolveCitations(node.fallback, citations) };
1374
+ if (node.kind === "component" && node.artifact)
1375
+ return { ...node, artifact: resolveCitations(node.artifact, citations) };
1376
+ if (node.kind !== "element") return node;
1377
+ const raw = node.attributes["data-publisle-citation"];
1378
+ if (typeof raw === "string") {
1379
+ const key = citationKey({
1380
+ items: JSON.parse(raw) as Parameters<typeof citationKey>[0]["items"],
1381
+ prefix: String(node.attributes["data-publisle-citation-prefix"] ?? ""),
1382
+ suffix: String(node.attributes["data-publisle-citation-suffix"] ?? ""),
1383
+ });
1384
+ const value = citations[key];
1385
+ if (value !== undefined) return { ...node, children: [text(value)] };
1386
+ }
1387
+ return { ...node, children: resolveCitations(node.children, citations) };
1388
+ });
1389
+ }
1390
+
1186
1391
  function wrapInputs(
1187
1392
  nodes: readonly RenderNode[],
1188
1393
  document: PreparedDocument,
package/src/types.ts CHANGED
@@ -87,6 +87,12 @@ export type DiagramRenderer = (input: {
87
87
  readonly alt: string;
88
88
  }) => DiagramRenderResult;
89
89
  export interface AdapterCompilerOptions {
90
+ /** Preformatted citation text keyed by citationKey; keeps CSL out of readers. */
91
+ readonly citations?: Readonly<Record<string, string>>;
92
+ readonly bibliography?: readonly {
93
+ readonly id: string;
94
+ readonly text: string;
95
+ }[];
90
96
  /** Raw HTML's authored IDs cannot be safely rewritten by a generic compiler. */
91
97
  readonly rawHtmlPlacement?: "reject" | "preserve";
92
98
  readonly renderers?: Readonly<Record<string, IslandRendererReference>>;