@ai-markdown/core 3.2.1 → 3.3.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/dist/index.js CHANGED
@@ -1,990 +1,956 @@
1
- // src/blockPlan.ts
2
1
  import { SKIP, visit } from "unist-util-visit";
3
- import { isFootnoteSection, normalizeId } from "@ai-markdown/engine";
4
- var TAINT_TYPES = /* @__PURE__ */ new Set([
5
- "footnoteReference",
6
- "footnoteDefinition",
7
- "linkReference",
8
- "imageReference",
9
- "definition"
2
+ import { EngineRawHtmlDepthError, advanceIncrementalParse, buildCrossChunkHandlers, buildPhantomSuffix, extractContributions, extractDefBodiesFromHast, footnoteSafeId, isFootnoteSection, lastMeaningfulIdx, normalizeForMatch, normalizeId, parseStage, phantomSuffixCloser, transformStage } from "@ai-markdown/engine";
3
+ const TAINT_TYPES = /* @__PURE__ */ new Set([
4
+ "footnoteReference",
5
+ "footnoteDefinition",
6
+ "linkReference",
7
+ "imageReference",
8
+ "definition"
10
9
  ]);
11
- var CTX_TYPES = TAINT_TYPES;
10
+ const CTX_TYPES = TAINT_TYPES;
12
11
  function extractRaw(node, source) {
13
- if (!node.position) return "";
14
- return source.slice(node.position.start.offset, node.position.end.offset);
12
+ if (!node.position) return "";
13
+ return source.slice(node.position.start.offset, node.position.end.offset);
15
14
  }
16
15
  function hasMdastSource(node) {
17
- return node.position !== void 0;
16
+ return node.position !== void 0;
18
17
  }
19
18
  function computeHtmlBlockDigest(el, source, ownEnd) {
20
- return computeHtmlBlockDigestWithExtent(el, source, ownEnd).digest;
19
+ return computeHtmlBlockDigestWithExtent(el, source, ownEnd).digest;
21
20
  }
22
21
  function computeHtmlBlockDigestWithExtent(el, source, ownEnd) {
23
- let maxEnd = el.position?.end?.offset ?? 0;
24
- let count = 0;
25
- let hasFootnoteSection = false;
26
- const stack = [...el.children];
27
- while (stack.length > 0) {
28
- const node = stack.pop();
29
- count++;
30
- const end = node.position?.end?.offset;
31
- if (end !== void 0 && end > maxEnd) {
32
- maxEnd = end;
33
- }
34
- if (node.type === "element") {
35
- if (isFootnoteSection(node)) {
36
- hasFootnoteSection = true;
37
- }
38
- for (const child of node.children) {
39
- stack.push(child);
40
- }
41
- }
42
- }
43
- const swallowed = source !== void 0 && ownEnd !== void 0 && maxEnd > ownEnd ? source.slice(ownEnd, maxEnd) : "";
44
- return { digest: `${maxEnd}:${count}:${hasFootnoteSection ? 1 : 0}:${fnv1a(swallowed)}`, maxEnd };
22
+ let maxEnd = el.position?.end?.offset ?? 0;
23
+ let count = 0;
24
+ let hasFootnoteSection = false;
25
+ const stack = [...el.children];
26
+ while (stack.length > 0) {
27
+ const node = stack.pop();
28
+ count++;
29
+ const end = node.position?.end?.offset;
30
+ if (end !== void 0 && end > maxEnd) maxEnd = end;
31
+ if (node.type === "element") {
32
+ if (isFootnoteSection(node)) hasFootnoteSection = true;
33
+ for (const child of node.children) stack.push(child);
34
+ }
35
+ }
36
+ const swallowed = source !== void 0 && ownEnd !== void 0 && maxEnd > ownEnd ? source.slice(ownEnd, maxEnd) : "";
37
+ return {
38
+ digest: `${maxEnd}:${count}:${hasFootnoteSection ? 1 : 0}:${fnv1a(swallowed)}`,
39
+ maxEnd
40
+ };
45
41
  }
46
42
  function fnv1a(text) {
47
- let h = 2166136261;
48
- for (let i = 0; i < text.length; i++) {
49
- h ^= text.charCodeAt(i);
50
- h = Math.imul(h, 16777619) >>> 0;
51
- }
52
- return h.toString(36);
43
+ let h = 2166136261;
44
+ for (let i = 0; i < text.length; i++) {
45
+ h ^= text.charCodeAt(i);
46
+ h = Math.imul(h, 16777619) >>> 0;
47
+ }
48
+ return h.toString(36);
53
49
  }
54
- var EMPTY_LABELS = /* @__PURE__ */ new Set();
55
- var FOOTNOTE_SECTION_KEY = "__footnote_section__";
50
+ const EMPTY_LABELS = /* @__PURE__ */ new Set();
51
+ const FOOTNOTE_SECTION_KEY = "__footnote_section__";
56
52
  function buildBlocks(mdast, hast, source, options = {}) {
57
- const phantomFootnotes = options.phantomFootnoteLabels ?? EMPTY_LABELS;
58
- const mdastByOffset = /* @__PURE__ */ new Map();
59
- const mdastRanges = [];
60
- for (const child of mdast.children) {
61
- const off = child.position?.start.offset;
62
- const endOff = child.position?.end.offset;
63
- if (off !== void 0) {
64
- mdastByOffset.set(off, child);
65
- }
66
- if (off !== void 0 && endOff !== void 0) {
67
- mdastRanges.push({ start: off, end: endOff, node: child });
68
- }
69
- }
70
- if (false) {
71
- for (let i = 1; i < mdastRanges.length; i++) {
72
- if (mdastRanges[i].start < mdastRanges[i - 1].start) {
73
- throw new Error(
74
- "block-memo: mdast.children not sorted by source offset \u2014 a remark plugin is reordering top-level children."
75
- );
76
- }
77
- }
78
- }
79
- function findContainingMdast(offset) {
80
- let lo = 0;
81
- let hi = mdastRanges.length;
82
- while (lo < hi) {
83
- const mid = lo + hi >>> 1;
84
- if (mdastRanges[mid].start <= offset) lo = mid + 1;
85
- else hi = mid;
86
- }
87
- const idx = lo - 1;
88
- if (idx < 0) return void 0;
89
- const r = mdastRanges[idx];
90
- return offset < r.end ? r.node : void 0;
91
- }
92
- const ctxParts = [];
93
- const taintOffsets = [];
94
- const firstTaintAtOrAfter = (offset) => {
95
- let lo = 0;
96
- let hi = taintOffsets.length;
97
- while (lo < hi) {
98
- const mid = lo + hi >>> 1;
99
- if (taintOffsets[mid] < offset) lo = mid + 1;
100
- else hi = mid;
101
- }
102
- return lo;
103
- };
104
- visit(options.contextMdast ?? mdast, (n) => {
105
- if (!CTX_TYPES.has(n.type)) return;
106
- const at = n.position?.start?.offset;
107
- if (at !== void 0) taintOffsets.push(at);
108
- if (n.type === "footnoteReference") ctxParts.push(["fr", n.identifier]);
109
- else if (n.type === "footnoteDefinition") ctxParts.push(["fd", n.identifier, extractRaw(n, source)]);
110
- else if (n.type === "linkReference") ctxParts.push(["lr", n.identifier]);
111
- else if (n.type === "imageReference") ctxParts.push(["ir", n.identifier]);
112
- else if (n.type === "definition") ctxParts.push(["d", n.identifier, n.url, n.title ?? null]);
113
- });
114
- if (false) {
115
- for (let i = 1; i < taintOffsets.length; i++) {
116
- if (taintOffsets[i] < taintOffsets[i - 1]) {
117
- throw new Error(
118
- "block-memo: taint node start offsets are not source-ordered \u2014 a remark plugin is reordering nodes or emitting bad positions."
119
- );
120
- }
121
- }
122
- }
123
- const globalCtx = JSON.stringify(ctxParts);
124
- const plan = [];
125
- const blocks = [];
126
- const blockHasts = [];
127
- let synthetic;
128
- const refLocalCtx = /* @__PURE__ */ new Map();
129
- {
130
- const counts = /* @__PURE__ */ new Map();
131
- const ranks = /* @__PURE__ */ new Map();
132
- const rankOf = (id) => {
133
- if (phantomFootnotes.has(id)) return -1;
134
- let rank = ranks.get(id);
135
- if (rank === void 0) {
136
- rank = ranks.size;
137
- ranks.set(id, rank);
138
- }
139
- return rank;
140
- };
141
- visit(options.contextMdast ?? mdast, (n) => {
142
- if (n.type === "footnoteDefinition") {
143
- rankOf(normalizeId(String(n.identifier)));
144
- return SKIP;
145
- }
146
- if (n.type !== "footnoteReference") return;
147
- const id = normalizeId(String(n.identifier));
148
- const prior = counts.get(id) ?? 0;
149
- refLocalCtx.set(n, [prior, rankOf(id)]);
150
- counts.set(id, prior + 1);
151
- });
152
- }
153
- for (let i = 0; i < hast.children.length; i++) {
154
- const hastChild = hast.children[i];
155
- if (hastChild.type !== "element") {
156
- const off = hastChild.position?.start.offset;
157
- const key = off !== void 0 ? `inline-${off}` : `inline-i${i}`;
158
- plan.push({ kind: "inline", el: hastChild, key });
159
- continue;
160
- }
161
- const el = hastChild;
162
- if (isFootnoteSection(el)) {
163
- synthetic = el;
164
- plan.push({ kind: "synthetic", el, key: FOOTNOTE_SECTION_KEY });
165
- continue;
166
- }
167
- const hastOffset = el.position?.start.offset;
168
- if (hastOffset === void 0) {
169
- plan.push({ kind: "inline", el, key: `inline-i${i}` });
170
- continue;
171
- }
172
- let mdastNode = mdastByOffset.get(hastOffset);
173
- let viaRangeFallback = false;
174
- if (!mdastNode) {
175
- mdastNode = findContainingMdast(hastOffset);
176
- viaRangeFallback = mdastNode !== void 0;
177
- }
178
- if (!mdastNode) {
179
- if (false) {
180
- throw new Error(
181
- `block-memo: hast block at offset ${hastOffset} has no mdast counterpart. A rehype plugin may have synthesized positions outside source. tagName=${el.tagName}`
182
- );
183
- }
184
- plan.push({ kind: "inline", el, key: `inline-${hastOffset}` });
185
- continue;
186
- }
187
- if (mdastNode.type === "footnoteDefinition") {
188
- plan.push({ kind: "inline", el, key: `inline-${hastOffset}` });
189
- continue;
190
- }
191
- const isRawHtmlBlock = mdastNode.type === "html" || viaRangeFallback;
192
- let hasReference = false;
193
- const swallowed = isRawHtmlBlock ? scanSwallowedSubtree(el) : null;
194
- const footnoteRefLabels = [];
195
- const linkRefLabels = [];
196
- const imageRefLabels = [];
197
- const footnoteDefLabels = [];
198
- const local = [];
199
- visit(mdastNode, (n) => {
200
- if (!TAINT_TYPES.has(n.type)) return;
201
- hasReference = true;
202
- const id = "identifier" in n ? normalizeId(String(n.identifier)) : null;
203
- if (id === null) return;
204
- if (n.type === "footnoteReference") {
205
- footnoteRefLabels.push(id);
206
- const ctx = refLocalCtx.get(n);
207
- if (ctx) local.push([id, ctx[0], ctx[1]]);
208
- } else if (n.type === "linkReference") linkRefLabels.push(id);
209
- else if (n.type === "imageReference") imageRefLabels.push(id);
210
- else if (n.type === "footnoteDefinition") footnoteDefLabels.push(id);
211
- });
212
- if (swallowed !== null && swallowed.hasReference) {
213
- hasReference = true;
214
- footnoteRefLabels.push(...swallowed.refLabels);
215
- linkRefLabels.push(...swallowed.linkLabels);
216
- imageRefLabels.push(...swallowed.imageLabels);
217
- local.push(...swallowed.local);
218
- }
219
- const footnoteRefLocalCtx = local.length > 0 ? JSON.stringify(local) : void 0;
220
- const swallowedDefCtx = swallowed !== null && swallowed.bakedDefs.length > 0 ? JSON.stringify(swallowed.bakedDefs) : void 0;
221
- const mdastPos = mdastNode.position;
222
- if (!mdastPos || mdastPos.start?.offset === void 0 || mdastPos.end?.offset === void 0) {
223
- plan.push({ kind: "inline", el, key: `inline-${hastOffset}` });
224
- continue;
225
- }
226
- let hastDigest;
227
- let swallowedSource;
228
- let swallowedTaint = false;
229
- if (isRawHtmlBlock) {
230
- const d = computeHtmlBlockDigestWithExtent(el, source, mdastPos.end.offset);
231
- hastDigest = d.digest;
232
- swallowedSource = source.slice(mdastPos.end.offset, d.maxEnd);
233
- const first = firstTaintAtOrAfter(mdastPos.end.offset);
234
- swallowedTaint = first < taintOffsets.length && taintOffsets[first] < d.maxEnd;
235
- }
236
- if (swallowedTaint) hasReference = true;
237
- const info = {
238
- raw: extractRaw(mdastNode, source),
239
- startOffset: mdastPos.start.offset,
240
- endOffset: mdastPos.end.offset,
241
- startLine: mdastPos.start.line,
242
- startColumn: mdastPos.start.column,
243
- hasReference,
244
- ...hastDigest !== void 0 ? { hastDigest } : {},
245
- ...swallowedSource !== void 0 ? { swallowedSource } : {},
246
- ...swallowed?.hasFootnoteSection ? { containsFootnoteSection: true } : {},
247
- ...hasReference ? {
248
- taintLabels: {
249
- footnoteRefLabels,
250
- linkRefLabels,
251
- imageRefLabels,
252
- footnoteDefLabels,
253
- ...footnoteRefLocalCtx !== void 0 ? { footnoteRefLocalCtx } : {},
254
- ...swallowedDefCtx !== void 0 ? { swallowedDefCtx } : {}
255
- }
256
- } : {}
257
- };
258
- blocks.push(info);
259
- blockHasts.push(el);
260
- plan.push({ kind: "block", el, info, key: `block-${hastOffset}` });
261
- }
262
- return { plan, globalCtx, blocks, blockHasts, synthetic };
53
+ const phantomFootnotes = options.phantomFootnoteLabels ?? EMPTY_LABELS;
54
+ const mdastByOffset = /* @__PURE__ */ new Map();
55
+ const mdastRanges = [];
56
+ for (const child of mdast.children) {
57
+ const off = child.position?.start.offset;
58
+ const endOff = child.position?.end.offset;
59
+ if (off !== void 0) mdastByOffset.set(off, child);
60
+ if (off !== void 0 && endOff !== void 0) mdastRanges.push({
61
+ start: off,
62
+ end: endOff,
63
+ node: child
64
+ });
65
+ }
66
+ function findContainingMdast(offset) {
67
+ let lo = 0;
68
+ let hi = mdastRanges.length;
69
+ while (lo < hi) {
70
+ const mid = lo + hi >>> 1;
71
+ if (mdastRanges[mid].start <= offset) lo = mid + 1;
72
+ else hi = mid;
73
+ }
74
+ const idx = lo - 1;
75
+ if (idx < 0) return void 0;
76
+ const r = mdastRanges[idx];
77
+ return offset < r.end ? r.node : void 0;
78
+ }
79
+ const ctxParts = [];
80
+ const taintOffsets = [];
81
+ const firstTaintAtOrAfter = (offset) => {
82
+ let lo = 0;
83
+ let hi = taintOffsets.length;
84
+ while (lo < hi) {
85
+ const mid = lo + hi >>> 1;
86
+ if (taintOffsets[mid] < offset) lo = mid + 1;
87
+ else hi = mid;
88
+ }
89
+ return lo;
90
+ };
91
+ visit(options.contextMdast ?? mdast, (n) => {
92
+ if (!CTX_TYPES.has(n.type)) return;
93
+ const at = n.position?.start?.offset;
94
+ if (at !== void 0) taintOffsets.push(at);
95
+ if (n.type === "footnoteReference") ctxParts.push(["fr", n.identifier]);
96
+ else if (n.type === "footnoteDefinition") ctxParts.push([
97
+ "fd",
98
+ n.identifier,
99
+ extractRaw(n, source)
100
+ ]);
101
+ else if (n.type === "linkReference") ctxParts.push(["lr", n.identifier]);
102
+ else if (n.type === "imageReference") ctxParts.push(["ir", n.identifier]);
103
+ else if (n.type === "definition") ctxParts.push([
104
+ "d",
105
+ n.identifier,
106
+ n.url,
107
+ n.title ?? null
108
+ ]);
109
+ });
110
+ const globalCtx = JSON.stringify(ctxParts);
111
+ const plan = [];
112
+ const blocks = [];
113
+ const blockHasts = [];
114
+ let synthetic;
115
+ const refLocalCtx = /* @__PURE__ */ new Map();
116
+ {
117
+ const counts = /* @__PURE__ */ new Map();
118
+ const ranks = /* @__PURE__ */ new Map();
119
+ const rankOf = (id) => {
120
+ if (phantomFootnotes.has(id)) return -1;
121
+ let rank = ranks.get(id);
122
+ if (rank === void 0) {
123
+ rank = ranks.size;
124
+ ranks.set(id, rank);
125
+ }
126
+ return rank;
127
+ };
128
+ visit(options.contextMdast ?? mdast, (n) => {
129
+ if (n.type === "footnoteDefinition") {
130
+ rankOf(normalizeId(String(n.identifier)));
131
+ return SKIP;
132
+ }
133
+ if (n.type !== "footnoteReference") return;
134
+ const id = normalizeId(String(n.identifier));
135
+ const prior = counts.get(id) ?? 0;
136
+ refLocalCtx.set(n, [prior, rankOf(id)]);
137
+ counts.set(id, prior + 1);
138
+ });
139
+ }
140
+ for (let i = 0; i < hast.children.length; i++) {
141
+ const hastChild = hast.children[i];
142
+ if (hastChild.type !== "element") {
143
+ const off = hastChild.position?.start.offset;
144
+ const key = off !== void 0 ? `inline-${off}` : `inline-i${i}`;
145
+ plan.push({
146
+ kind: "inline",
147
+ el: hastChild,
148
+ key
149
+ });
150
+ continue;
151
+ }
152
+ const el = hastChild;
153
+ if (isFootnoteSection(el)) {
154
+ synthetic = el;
155
+ plan.push({
156
+ kind: "synthetic",
157
+ el,
158
+ key: FOOTNOTE_SECTION_KEY
159
+ });
160
+ continue;
161
+ }
162
+ const hastOffset = el.position?.start.offset;
163
+ if (hastOffset === void 0) {
164
+ plan.push({
165
+ kind: "inline",
166
+ el,
167
+ key: `inline-i${i}`
168
+ });
169
+ continue;
170
+ }
171
+ let mdastNode = mdastByOffset.get(hastOffset);
172
+ let viaRangeFallback = false;
173
+ if (!mdastNode) {
174
+ mdastNode = findContainingMdast(hastOffset);
175
+ viaRangeFallback = mdastNode !== void 0;
176
+ }
177
+ if (!mdastNode) {
178
+ plan.push({
179
+ kind: "inline",
180
+ el,
181
+ key: `inline-${hastOffset}`
182
+ });
183
+ continue;
184
+ }
185
+ if (mdastNode.type === "footnoteDefinition") {
186
+ plan.push({
187
+ kind: "inline",
188
+ el,
189
+ key: `inline-${hastOffset}`
190
+ });
191
+ continue;
192
+ }
193
+ const isRawHtmlBlock = mdastNode.type === "html" || viaRangeFallback;
194
+ let hasReference = false;
195
+ const swallowed = isRawHtmlBlock ? scanSwallowedSubtree(el) : null;
196
+ const footnoteRefLabels = [];
197
+ const linkRefLabels = [];
198
+ const imageRefLabels = [];
199
+ const footnoteDefLabels = [];
200
+ const local = [];
201
+ visit(mdastNode, (n) => {
202
+ if (!TAINT_TYPES.has(n.type)) return;
203
+ hasReference = true;
204
+ const id = "identifier" in n ? normalizeId(String(n.identifier)) : null;
205
+ if (id === null) return;
206
+ if (n.type === "footnoteReference") {
207
+ footnoteRefLabels.push(id);
208
+ const ctx = refLocalCtx.get(n);
209
+ if (ctx) local.push([
210
+ id,
211
+ ctx[0],
212
+ ctx[1]
213
+ ]);
214
+ } else if (n.type === "linkReference") linkRefLabels.push(id);
215
+ else if (n.type === "imageReference") imageRefLabels.push(id);
216
+ else if (n.type === "footnoteDefinition") footnoteDefLabels.push(id);
217
+ });
218
+ if (swallowed !== null && swallowed.hasReference) {
219
+ hasReference = true;
220
+ footnoteRefLabels.push(...swallowed.refLabels);
221
+ linkRefLabels.push(...swallowed.linkLabels);
222
+ imageRefLabels.push(...swallowed.imageLabels);
223
+ local.push(...swallowed.local);
224
+ }
225
+ const footnoteRefLocalCtx = local.length > 0 ? JSON.stringify(local) : void 0;
226
+ const swallowedDefCtx = swallowed !== null && swallowed.bakedDefs.length > 0 ? JSON.stringify(swallowed.bakedDefs) : void 0;
227
+ const mdastPos = mdastNode.position;
228
+ if (!mdastPos || mdastPos.start?.offset === void 0 || mdastPos.end?.offset === void 0) {
229
+ plan.push({
230
+ kind: "inline",
231
+ el,
232
+ key: `inline-${hastOffset}`
233
+ });
234
+ continue;
235
+ }
236
+ let hastDigest;
237
+ let swallowedSource;
238
+ let swallowedTaint = false;
239
+ if (isRawHtmlBlock) {
240
+ const d = computeHtmlBlockDigestWithExtent(el, source, mdastPos.end.offset);
241
+ hastDigest = d.digest;
242
+ swallowedSource = source.slice(mdastPos.end.offset, d.maxEnd);
243
+ const first = firstTaintAtOrAfter(mdastPos.end.offset);
244
+ swallowedTaint = first < taintOffsets.length && taintOffsets[first] < d.maxEnd;
245
+ }
246
+ if (swallowedTaint) hasReference = true;
247
+ const info = {
248
+ raw: extractRaw(mdastNode, source),
249
+ startOffset: mdastPos.start.offset,
250
+ endOffset: mdastPos.end.offset,
251
+ startLine: mdastPos.start.line,
252
+ startColumn: mdastPos.start.column,
253
+ hasReference,
254
+ ...hastDigest !== void 0 ? { hastDigest } : {},
255
+ ...swallowedSource !== void 0 ? { swallowedSource } : {},
256
+ ...swallowed?.hasFootnoteSection ? { containsFootnoteSection: true } : {},
257
+ ...hasReference ? { taintLabels: {
258
+ footnoteRefLabels,
259
+ linkRefLabels,
260
+ imageRefLabels,
261
+ footnoteDefLabels,
262
+ ...footnoteRefLocalCtx !== void 0 ? { footnoteRefLocalCtx } : {},
263
+ ...swallowedDefCtx !== void 0 ? { swallowedDefCtx } : {}
264
+ } } : {}
265
+ };
266
+ blocks.push(info);
267
+ blockHasts.push(el);
268
+ plan.push({
269
+ kind: "block",
270
+ el,
271
+ info,
272
+ key: `block-${hastOffset}`
273
+ });
274
+ }
275
+ return {
276
+ plan,
277
+ globalCtx,
278
+ blocks,
279
+ blockHasts,
280
+ synthetic
281
+ };
263
282
  }
264
283
  function computeBlockFingerprint(taintLabels, registry, thisChunkSym, clobberPrefix) {
265
- const parts = [clobberPrefix];
266
- for (const label of taintLabels.footnoteRefLabels) {
267
- parts.push(`fn:${label}=${registry.globalNumber(label) ?? "null"}`);
268
- }
269
- if (taintLabels.footnoteRefLocalCtx !== void 0) parts.push(`fl:${taintLabels.footnoteRefLocalCtx}`);
270
- if (taintLabels.swallowedDefCtx !== void 0) parts.push(`sd:${taintLabels.swallowedDefCtx}`);
271
- for (const label of taintLabels.linkRefLabels) {
272
- const def = registry.resolveLinkDef(label);
273
- parts.push(`lr:${label}=${def ? JSON.stringify([def.url, def.title ?? null]) : "null"}`);
274
- }
275
- for (const label of taintLabels.imageRefLabels) {
276
- const def = registry.resolveLinkDef(label);
277
- parts.push(`ir:${label}=${def ? JSON.stringify([def.url, def.title ?? null]) : "null"}`);
278
- }
279
- for (const label of taintLabels.footnoteDefLabels) {
280
- const isCanonical = registry.canonicalFootnoteFor(label) === thisChunkSym ? 1 : 0;
281
- parts.push(`fd:${label}=${isCanonical}/${registry.getRefsForLabel(label)}`);
282
- }
283
- return parts.join("|");
284
+ const parts = [clobberPrefix];
285
+ for (const label of taintLabels.footnoteRefLabels) parts.push(`fn:${label}=${registry.globalNumber(label) ?? "null"}`);
286
+ if (taintLabels.footnoteRefLocalCtx !== void 0) parts.push(`fl:${taintLabels.footnoteRefLocalCtx}`);
287
+ if (taintLabels.swallowedDefCtx !== void 0) parts.push(`sd:${taintLabels.swallowedDefCtx}`);
288
+ for (const label of taintLabels.linkRefLabels) {
289
+ const def = registry.resolveLinkDef(label);
290
+ parts.push(`lr:${label}=${def ? JSON.stringify([def.url, def.title ?? null]) : "null"}`);
291
+ }
292
+ for (const label of taintLabels.imageRefLabels) {
293
+ const def = registry.resolveLinkDef(label);
294
+ parts.push(`ir:${label}=${def ? JSON.stringify([def.url, def.title ?? null]) : "null"}`);
295
+ }
296
+ for (const label of taintLabels.footnoteDefLabels) {
297
+ const isCanonical = registry.canonicalFootnoteFor(label) === thisChunkSym ? 1 : 0;
298
+ parts.push(`fd:${label}=${isCanonical}/${registry.getRefsForLabel(label)}`);
299
+ }
300
+ return parts.join("|");
284
301
  }
285
- var PLACEHOLDER_TAGS = /* @__PURE__ */ new Set(["footnote-sup", "cross-chunk-link", "cross-chunk-image"]);
302
+ const PLACEHOLDER_TAGS = /* @__PURE__ */ new Set([
303
+ "footnote-sup",
304
+ "cross-chunk-link",
305
+ "cross-chunk-image"
306
+ ]);
286
307
  function scanSwallowedSubtree(el) {
287
- const refLabels = [];
288
- const linkLabels = [];
289
- const imageLabels = [];
290
- const local = [];
291
- const bakedDefs = [];
292
- let hasReference = false;
293
- let hasFootnoteSection = false;
294
- visit(el, "element", (node) => {
295
- if (isFootnoteSection(node)) {
296
- hasFootnoteSection = true;
297
- hasReference = true;
298
- return;
299
- }
300
- const props = node.properties ?? {};
301
- if (PLACEHOLDER_TAGS.has(node.tagName)) {
302
- hasReference = true;
303
- const identifier = props.identifier ?? props.label;
304
- const label = identifier === void 0 ? null : normalizeId(String(identifier));
305
- if (label === null) return;
306
- if (node.tagName === "footnote-sup") {
307
- refLabels.push(label);
308
- const occ = Number(props.localOccurrence);
309
- const num = Number(props.localNumber);
310
- local.push([label, Number.isFinite(occ) ? occ : -1, Number.isFinite(num) ? num : -1]);
311
- return;
312
- }
313
- if (node.tagName === "cross-chunk-link") linkLabels.push(label);
314
- else imageLabels.push(label);
315
- if (typeof props.localUrl === "string") {
316
- bakedDefs.push([label, props.localUrl, typeof props.localTitle === "string" ? props.localTitle : null]);
317
- }
318
- return;
319
- }
320
- if (node.tagName === "a" && props.dataFootnoteRef !== void 0) hasReference = true;
321
- });
322
- return { hasReference, refLabels, linkLabels, imageLabels, local, bakedDefs, hasFootnoteSection };
308
+ const refLabels = [];
309
+ const linkLabels = [];
310
+ const imageLabels = [];
311
+ const local = [];
312
+ const bakedDefs = [];
313
+ let hasReference = false;
314
+ let hasFootnoteSection = false;
315
+ visit(el, "element", (node) => {
316
+ if (isFootnoteSection(node)) {
317
+ hasFootnoteSection = true;
318
+ hasReference = true;
319
+ return;
320
+ }
321
+ const props = node.properties ?? {};
322
+ if (PLACEHOLDER_TAGS.has(node.tagName)) {
323
+ hasReference = true;
324
+ const identifier = props.identifier ?? props.label;
325
+ const label = identifier === void 0 ? null : normalizeId(String(identifier));
326
+ if (label === null) return;
327
+ if (node.tagName === "footnote-sup") {
328
+ refLabels.push(label);
329
+ const occ = Number(props.localOccurrence);
330
+ const num = Number(props.localNumber);
331
+ local.push([
332
+ label,
333
+ Number.isFinite(occ) ? occ : -1,
334
+ Number.isFinite(num) ? num : -1
335
+ ]);
336
+ return;
337
+ }
338
+ if (node.tagName === "cross-chunk-link") linkLabels.push(label);
339
+ else imageLabels.push(label);
340
+ if (typeof props.localUrl === "string") bakedDefs.push([
341
+ label,
342
+ props.localUrl,
343
+ typeof props.localTitle === "string" ? props.localTitle : null
344
+ ]);
345
+ return;
346
+ }
347
+ if (node.tagName === "a" && props.dataFootnoteRef !== void 0) hasReference = true;
348
+ });
349
+ return {
350
+ hasReference,
351
+ refLabels,
352
+ linkLabels,
353
+ imageLabels,
354
+ local,
355
+ bakedDefs,
356
+ hasFootnoteSection
357
+ };
323
358
  }
324
-
325
- // src/blockPlanner.ts
326
- import { visit as visit2 } from "unist-util-visit";
327
- var UNPAIRED_TYPES = /* @__PURE__ */ new Set(["html", "definition", "footnoteDefinition"]);
359
+ const UNPAIRED_TYPES = /* @__PURE__ */ new Set([
360
+ "html",
361
+ "definition",
362
+ "footnoteDefinition"
363
+ ]);
328
364
  function createBlockPlanner() {
329
- let previous;
330
- const eligible = /* @__PURE__ */ new WeakMap();
331
- const isEligible = (node) => {
332
- let result = eligible.get(node);
333
- if (result === void 0) {
334
- result = true;
335
- visit2(node, (child) => {
336
- if (UNPAIRED_TYPES.has(child.type)) result = false;
337
- });
338
- eligible.set(node, result);
339
- }
340
- return result;
341
- };
342
- return (mdast, hast, source, options = {}) => {
343
- let m = 0;
344
- let h = 0;
345
- let reusedContext = false;
346
- if (previous && source.startsWith(previous.source) && options.phantomFootnoteLabels === previous.phantoms) {
347
- const prevHast = previous.hast.children;
348
- const prevPlan = previous.result.plan;
349
- const isRetainedGap = (i) => {
350
- const gap = hast.children[i];
351
- return gap === prevHast[i] && gap.type === "text" && !/\S/.test(gap.value);
352
- };
353
- while (m < mdast.children.length) {
354
- const node = mdast.children[m];
355
- const el = hast.children[h];
356
- const item = prevPlan[h];
357
- if (node !== previous.mdast.children[m] || el !== prevHast[h] || !el || el.type !== "element" || !item || item.kind !== "block" || item.info.startOffset !== node.position?.start.offset || !isEligible(node))
358
- break;
359
- const startOffset = item.info.startOffset;
360
- let next = h + 1;
361
- let complete = true;
362
- for (; ; ) {
363
- let probe = next;
364
- while (probe < hast.children.length && isRetainedGap(probe)) probe++;
365
- const sibling = prevPlan[probe];
366
- if (!sibling || sibling.kind !== "block" || sibling.info.startOffset !== startOffset) break;
367
- if (hast.children[probe] !== prevHast[probe]) {
368
- complete = false;
369
- break;
370
- }
371
- next = probe + 1;
372
- }
373
- if (!complete) break;
374
- reusedContext ||= item.info.hasReference;
375
- m++;
376
- h = next;
377
- while (h < hast.children.length && isRetainedGap(h)) h++;
378
- }
379
- if (m > 0) {
380
- const prefixEnd = mdast.children[m - 1].position?.end.offset ?? 0;
381
- for (let i = h; i < hast.children.length; i++) {
382
- const child = hast.children[i];
383
- const at = child.type === "element" ? child.position?.start.offset : void 0;
384
- if (at !== void 0 && at < prefixEnd) {
385
- m = 0;
386
- h = 0;
387
- reusedContext = false;
388
- break;
389
- }
390
- }
391
- }
392
- }
393
- let result;
394
- if (m > 0 && previous) {
395
- const tail = buildBlocks(
396
- { ...mdast, children: mdast.children.slice(m) },
397
- { ...hast, children: hast.children.slice(h) },
398
- source,
399
- reusedContext ? { ...options, contextMdast: options.contextMdast ?? mdast } : options
400
- );
401
- const prefix = previous.result.plan.slice(0, h);
402
- const prefixBlocks = prefix.filter(
403
- (item) => item.kind === "block"
404
- );
405
- result = {
406
- ...tail,
407
- plan: [
408
- ...prefix,
409
- ...tail.plan.map(
410
- (item) => /^inline-i\d+$/.test(item.key) ? { ...item, key: `inline-i${Number(item.key.slice(8)) + h}` } : item
411
- )
412
- ],
413
- blocks: [...prefixBlocks.map((item) => item.info), ...tail.blocks],
414
- blockHasts: [...prefixBlocks.map((item) => item.el), ...tail.blockHasts]
415
- };
416
- } else result = buildBlocks(mdast, hast, source, options);
417
- previous = { mdast, hast, source, result, phantoms: options.phantomFootnoteLabels };
418
- return result;
419
- };
365
+ let previous;
366
+ const eligible = /* @__PURE__ */ new WeakMap();
367
+ const isEligible = (node) => {
368
+ let result = eligible.get(node);
369
+ if (result === void 0) {
370
+ result = true;
371
+ visit(node, (child) => {
372
+ if (UNPAIRED_TYPES.has(child.type)) result = false;
373
+ });
374
+ eligible.set(node, result);
375
+ }
376
+ return result;
377
+ };
378
+ return (mdast, hast, source, options = {}) => {
379
+ let m = 0;
380
+ let h = 0;
381
+ let reusedContext = false;
382
+ if (previous && source.startsWith(previous.source) && options.phantomFootnoteLabels === previous.phantoms) {
383
+ const prevHast = previous.hast.children;
384
+ const prevPlan = previous.result.plan;
385
+ const isRetainedGap = (i) => {
386
+ const gap = hast.children[i];
387
+ return gap === prevHast[i] && gap.type === "text" && !/\S/.test(gap.value);
388
+ };
389
+ while (m < mdast.children.length) {
390
+ const node = mdast.children[m];
391
+ const el = hast.children[h];
392
+ const item = prevPlan[h];
393
+ if (node !== previous.mdast.children[m] || el !== prevHast[h] || !el || el.type !== "element" || !item || item.kind !== "block" || item.info.startOffset !== node.position?.start.offset || !isEligible(node)) break;
394
+ const startOffset = item.info.startOffset;
395
+ let next = h + 1;
396
+ let complete = true;
397
+ for (;;) {
398
+ let probe = next;
399
+ while (probe < hast.children.length && isRetainedGap(probe)) probe++;
400
+ const sibling = prevPlan[probe];
401
+ if (!sibling || sibling.kind !== "block" || sibling.info.startOffset !== startOffset) break;
402
+ if (hast.children[probe] !== prevHast[probe]) {
403
+ complete = false;
404
+ break;
405
+ }
406
+ next = probe + 1;
407
+ }
408
+ if (!complete) break;
409
+ reusedContext ||= item.info.hasReference;
410
+ m++;
411
+ h = next;
412
+ while (h < hast.children.length && isRetainedGap(h)) h++;
413
+ }
414
+ if (m > 0) {
415
+ const prefixEnd = mdast.children[m - 1].position?.end.offset ?? 0;
416
+ for (let i = h; i < hast.children.length; i++) {
417
+ const child = hast.children[i];
418
+ const at = child.type === "element" ? child.position?.start.offset : void 0;
419
+ if (at !== void 0 && at < prefixEnd) {
420
+ m = 0;
421
+ h = 0;
422
+ reusedContext = false;
423
+ break;
424
+ }
425
+ }
426
+ }
427
+ }
428
+ let result;
429
+ if (m > 0 && previous) {
430
+ const tail = buildBlocks({
431
+ ...mdast,
432
+ children: mdast.children.slice(m)
433
+ }, {
434
+ ...hast,
435
+ children: hast.children.slice(h)
436
+ }, source, reusedContext ? {
437
+ ...options,
438
+ contextMdast: options.contextMdast ?? mdast
439
+ } : options);
440
+ const prefix = previous.result.plan.slice(0, h);
441
+ const prefixBlocks = prefix.filter((item) => item.kind === "block");
442
+ result = {
443
+ ...tail,
444
+ plan: [...prefix, ...tail.plan.map((item) => /^inline-i\d+$/.test(item.key) ? {
445
+ ...item,
446
+ key: `inline-i${Number(item.key.slice(8)) + h}`
447
+ } : item)],
448
+ blocks: [...prefixBlocks.map((item) => item.info), ...tail.blocks],
449
+ blockHasts: [...prefixBlocks.map((item) => item.el), ...tail.blockHasts]
450
+ };
451
+ } else result = buildBlocks(mdast, hast, source, options);
452
+ previous = {
453
+ mdast,
454
+ hast,
455
+ source,
456
+ result,
457
+ phantoms: options.phantomFootnoteLabels
458
+ };
459
+ return result;
460
+ };
420
461
  }
421
-
422
- // src/contribution.ts
423
- import { extractContributions, extractDefBodiesFromHast, footnoteSafeId } from "@ai-markdown/engine";
424
462
  function createContributionSession() {
425
- let lastContribution = null;
426
- return {
427
- commit({ pipeline, ownLabels, registry, targetPhantoms, sym, clobberPrefix, chain }) {
428
- if (!registry || !sym) return;
429
- const refs = [];
430
- const defMeta = /* @__PURE__ */ new Map();
431
- const linkDefs = /* @__PURE__ */ new Map();
432
- for (const node of extractContributions(pipeline.mdast, {
433
- phantomFootnoteLabels: targetPhantoms.missingFootnotes
434
- })) {
435
- if (node.kind === "ref") {
436
- refs.push({
437
- label: node.label,
438
- kind: node.refKind,
439
- referenceType: node.referenceType,
440
- ...node.nestedIn !== void 0 ? { nestedIn: node.nestedIn } : {}
441
- });
442
- } else if (node.kind === "fnDef") {
443
- defMeta.set(node.label, {
444
- identifier: node.label,
445
- sourceIdentifier: node.sourceIdentifier,
446
- contentSource: node.content
447
- });
448
- } else if (node.kind === "linkDef") {
449
- linkDefs.set(node.label, { identifier: node.label, url: node.url, title: node.title });
450
- }
451
- }
452
- const fp = JSON.stringify({
453
- r: refs,
454
- d: Array.from(defMeta.entries()).map(([k, v]) => [k, v.sourceIdentifier, v.contentSource]),
455
- l: Array.from(linkDefs.entries()).map(([k, v]) => [k, v.url, v.title ?? ""]),
456
- ofn: Array.from(ownLabels.footnoteLabels).sort(),
457
- ol: Array.from(ownLabels.linkLabels).sort(),
458
- // Include targetPhantoms in the fingerprint: a phantom→resolved
459
- // transition (another chunk publishes a def for a label this chunk
460
- // references inside one of its OWN def bodies) changes the rendered
461
- // hast — the `<cross-chunk-link>` / `<cross-chunk-image>` placeholder
462
- // disappears and a real `<a>` / `<img>` takes its place — without
463
- // touching this chunk's refs / defMeta / linkDefs / ownLabels. Without
464
- // including the phantom snapshot in the fingerprint, the fp check
465
- // would short-circuit and the registry would keep stale bodyHast
466
- // forever, leaving the aggregate footer rendering the placeholder
467
- // long after the label was resolved.
468
- tpfn: Array.from(targetPhantoms.missingFootnotes).sort(),
469
- tpl: Array.from(targetPhantoms.missingLinks).sort()
470
- });
471
- const last = lastContribution;
472
- if (last?.registry === registry && last.symbol === sym && last.fp === fp && last.chain.length === chain.length && last.chain.every((dep, i) => dep === chain[i])) {
473
- return;
474
- }
475
- const bodiesBySafeId = extractDefBodiesFromHast(pipeline.hast, clobberPrefix);
476
- const defs = /* @__PURE__ */ new Map();
477
- for (const [label, meta] of defMeta) {
478
- defs.set(label, {
479
- identifier: meta.identifier,
480
- sourceIdentifier: meta.sourceIdentifier,
481
- contentSource: meta.contentSource,
482
- bodyHast: bodiesBySafeId.get(footnoteSafeId(meta.sourceIdentifier)) ?? []
483
- });
484
- }
485
- lastContribution = { registry, symbol: sym, fp, chain };
486
- registry.contributeChunkData(sym, {
487
- refs,
488
- defs,
489
- linkDefs,
490
- ownFootnoteLabels: ownLabels.footnoteLabels,
491
- ownLinkLabels: ownLabels.linkLabels
492
- });
493
- }
494
- };
463
+ let lastContribution = null;
464
+ return { commit({ pipeline, ownLabels, registry, targetPhantoms, sym, clobberPrefix, chain }) {
465
+ if (!registry || !sym) return;
466
+ const refs = [];
467
+ const defMeta = /* @__PURE__ */ new Map();
468
+ const linkDefs = /* @__PURE__ */ new Map();
469
+ for (const node of extractContributions(pipeline.mdast, { phantomFootnoteLabels: targetPhantoms.missingFootnotes })) if (node.kind === "ref") refs.push({
470
+ label: node.label,
471
+ kind: node.refKind,
472
+ referenceType: node.referenceType,
473
+ ...node.nestedIn !== void 0 ? { nestedIn: node.nestedIn } : {}
474
+ });
475
+ else if (node.kind === "fnDef") defMeta.set(node.label, {
476
+ identifier: node.label,
477
+ sourceIdentifier: node.sourceIdentifier,
478
+ contentSource: node.content
479
+ });
480
+ else if (node.kind === "linkDef") linkDefs.set(node.label, {
481
+ identifier: node.label,
482
+ url: node.url,
483
+ title: node.title
484
+ });
485
+ const fp = JSON.stringify({
486
+ r: refs,
487
+ d: Array.from(defMeta.entries()).map(([k, v]) => [
488
+ k,
489
+ v.sourceIdentifier,
490
+ v.contentSource
491
+ ]),
492
+ l: Array.from(linkDefs.entries()).map(([k, v]) => [
493
+ k,
494
+ v.url,
495
+ v.title ?? ""
496
+ ]),
497
+ ofn: Array.from(ownLabels.footnoteLabels).sort(),
498
+ ol: Array.from(ownLabels.linkLabels).sort(),
499
+ tpfn: Array.from(targetPhantoms.missingFootnotes).sort(),
500
+ tpl: Array.from(targetPhantoms.missingLinks).sort()
501
+ });
502
+ const last = lastContribution;
503
+ if (last?.registry === registry && last.symbol === sym && last.fp === fp && last.chain.length === chain.length && last.chain.every((dep, i) => dep === chain[i])) return;
504
+ const bodiesBySafeId = extractDefBodiesFromHast(pipeline.hast, clobberPrefix);
505
+ const defs = /* @__PURE__ */ new Map();
506
+ for (const [label, meta] of defMeta) defs.set(label, {
507
+ identifier: meta.identifier,
508
+ sourceIdentifier: meta.sourceIdentifier,
509
+ contentSource: meta.contentSource,
510
+ bodyHast: bodiesBySafeId.get(footnoteSafeId(meta.sourceIdentifier)) ?? []
511
+ });
512
+ lastContribution = {
513
+ registry,
514
+ symbol: sym,
515
+ fp,
516
+ chain
517
+ };
518
+ registry.contributeChunkData(sym, {
519
+ refs,
520
+ defs,
521
+ linkDefs,
522
+ ownFootnoteLabels: ownLabels.footnoteLabels,
523
+ ownLinkLabels: ownLabels.linkLabels
524
+ });
525
+ } };
495
526
  }
496
-
497
- // src/smoothCoordinator.ts
498
- function createSmoothCoordinator(onEmpty) {
499
- const order = [];
500
- const done = /* @__PURE__ */ new Set();
501
- const lastProgressAt = /* @__PURE__ */ new Map();
502
- const coord = {
503
- order,
504
- done,
505
- lastProgressAt,
506
- version: 0,
507
- _refcounts: /* @__PURE__ */ new Map(),
508
- _subscribers: /* @__PURE__ */ new Set(),
509
- _notifyScheduled: false,
510
- register(chunkId) {
511
- const count = this._refcounts.get(chunkId) ?? 0;
512
- this._refcounts.set(chunkId, count + 1);
513
- if (count === 0 && !order.includes(chunkId)) {
514
- order.push(chunkId);
515
- this._notify();
516
- }
517
- },
518
- release(chunkId) {
519
- const count = this._refcounts.get(chunkId);
520
- if (count === void 0) return;
521
- if (count > 1) {
522
- this._refcounts.set(chunkId, count - 1);
523
- return;
524
- }
525
- this._refcounts.set(chunkId, 0);
526
- queueMicrotask(() => {
527
- if (this._refcounts.get(chunkId) !== 0) return;
528
- this._refcounts.delete(chunkId);
529
- const idx = order.indexOf(chunkId);
530
- if (idx !== -1) order.splice(idx, 1);
531
- done.delete(chunkId);
532
- lastProgressAt.delete(chunkId);
533
- this._notify();
534
- if (order.length === 0 && onEmpty) onEmpty();
535
- });
536
- },
537
- markDone(chunkId) {
538
- if (done.has(chunkId)) return;
539
- done.add(chunkId);
540
- this._notify();
541
- },
542
- stampProgress(chunkId, at) {
543
- lastProgressAt.set(chunkId, at);
544
- },
545
- isReleased(chunkId) {
546
- for (const id of order) {
547
- if (id === chunkId) return true;
548
- if (!done.has(id)) return false;
549
- }
550
- return true;
551
- },
552
- earliestBlockerOf(chunkId) {
553
- for (const id of order) {
554
- if (id === chunkId) return null;
555
- if (!done.has(id)) return id;
556
- }
557
- return null;
558
- },
559
- subscribe(cb) {
560
- this._subscribers.add(cb);
561
- return () => {
562
- this._subscribers.delete(cb);
563
- };
564
- },
565
- _notify() {
566
- this.version++;
567
- if (this._notifyScheduled) return;
568
- this._notifyScheduled = true;
569
- queueMicrotask(() => {
570
- this._notifyScheduled = false;
571
- for (const cb of [...this._subscribers]) cb();
572
- });
573
- }
574
- };
575
- return coord;
527
+ function createSmoothCoordinator$1(onEmpty) {
528
+ const order = [];
529
+ const done = /* @__PURE__ */ new Set();
530
+ const lastProgressAt = /* @__PURE__ */ new Map();
531
+ return {
532
+ order,
533
+ done,
534
+ lastProgressAt,
535
+ version: 0,
536
+ _refcounts: /* @__PURE__ */ new Map(),
537
+ _subscribers: /* @__PURE__ */ new Set(),
538
+ _notifyScheduled: false,
539
+ register(chunkId) {
540
+ const count = this._refcounts.get(chunkId) ?? 0;
541
+ this._refcounts.set(chunkId, count + 1);
542
+ if (count === 0 && !order.includes(chunkId)) {
543
+ order.push(chunkId);
544
+ this._notify();
545
+ }
546
+ },
547
+ release(chunkId) {
548
+ const count = this._refcounts.get(chunkId);
549
+ if (count === void 0) return;
550
+ if (count > 1) {
551
+ this._refcounts.set(chunkId, count - 1);
552
+ return;
553
+ }
554
+ this._refcounts.set(chunkId, 0);
555
+ queueMicrotask(() => {
556
+ if (this._refcounts.get(chunkId) !== 0) return;
557
+ this._refcounts.delete(chunkId);
558
+ const idx = order.indexOf(chunkId);
559
+ if (idx !== -1) order.splice(idx, 1);
560
+ done.delete(chunkId);
561
+ lastProgressAt.delete(chunkId);
562
+ this._notify();
563
+ if (order.length === 0 && onEmpty) onEmpty();
564
+ });
565
+ },
566
+ markDone(chunkId) {
567
+ if (done.has(chunkId)) return;
568
+ done.add(chunkId);
569
+ this._notify();
570
+ },
571
+ stampProgress(chunkId, at) {
572
+ lastProgressAt.set(chunkId, at);
573
+ },
574
+ isReleased(chunkId) {
575
+ for (const id of order) {
576
+ if (id === chunkId) return true;
577
+ if (!done.has(id)) return false;
578
+ }
579
+ return true;
580
+ },
581
+ earliestBlockerOf(chunkId) {
582
+ for (const id of order) {
583
+ if (id === chunkId) return null;
584
+ if (!done.has(id)) return id;
585
+ }
586
+ return null;
587
+ },
588
+ subscribe(cb) {
589
+ this._subscribers.add(cb);
590
+ return () => {
591
+ this._subscribers.delete(cb);
592
+ };
593
+ },
594
+ _notify() {
595
+ this.version++;
596
+ if (this._notifyScheduled) return;
597
+ this._notifyScheduled = true;
598
+ queueMicrotask(() => {
599
+ this._notifyScheduled = false;
600
+ for (const cb of [...this._subscribers]) cb();
601
+ });
602
+ }
603
+ };
576
604
  }
577
605
  function evaluateGateWarn(coordinator, chunkId, nowMs, thresholdMs) {
578
- const blocker = coordinator.earliestBlockerOf(chunkId);
579
- if (!blocker) return "clear";
580
- const progressedAt = coordinator.lastProgressAt.get(blocker) ?? 0;
581
- return nowMs - progressedAt < thresholdMs ? "rearm" : "warn";
606
+ const blocker = coordinator.earliestBlockerOf(chunkId);
607
+ if (!blocker) return "clear";
608
+ return nowMs - (coordinator.lastProgressAt.get(blocker) ?? 0) < thresholdMs ? "rearm" : "warn";
582
609
  }
583
-
584
- // src/coordinator.ts
585
- function createSmoothCoordinator2(onEmpty) {
586
- return createSmoothCoordinator(onEmpty);
610
+ function createSmoothCoordinator(onEmpty) {
611
+ return createSmoothCoordinator$1(onEmpty);
587
612
  }
588
-
589
- // src/tailSignal.ts
590
- var DESCEND_THROUGH = /* @__PURE__ */ new Set(["blockquote", "list", "listItem", "footnoteDefinition"]);
613
+ const DESCEND_THROUGH = /* @__PURE__ */ new Set([
614
+ "blockquote",
615
+ "list",
616
+ "listItem",
617
+ "footnoteDefinition"
618
+ ]);
591
619
  function deriveTailSignal(mdast, contentLength) {
592
- const children = mdast.children;
593
- let index = children.length - 1;
594
- while (index >= 0) {
595
- const offset = children[index].position?.start?.offset;
596
- if (offset !== void 0 && offset >= contentLength) {
597
- index--;
598
- continue;
599
- }
600
- break;
601
- }
602
- if (index < 0) return null;
603
- let node = children[index];
604
- let deepestFootnoteDef = null;
605
- for (; ; ) {
606
- if (node.type === "footnoteDefinition") deepestFootnoteDef = node;
607
- if (node.type === "definition") {
608
- return { kind: "invisible-def" };
609
- }
610
- if (!DESCEND_THROUGH.has(node.type)) break;
611
- const kids = node.children;
612
- if (!kids || kids.length === 0) break;
613
- node = kids[kids.length - 1];
614
- }
615
- return deepestFootnoteDef ? { kind: "footnote-def", identifier: deepestFootnoteDef.identifier } : null;
620
+ const children = mdast.children;
621
+ let index = children.length - 1;
622
+ while (index >= 0) {
623
+ const offset = children[index].position?.start?.offset;
624
+ if (offset !== void 0 && offset >= contentLength) {
625
+ index--;
626
+ continue;
627
+ }
628
+ break;
629
+ }
630
+ if (index < 0) return null;
631
+ let node = children[index];
632
+ let deepestFootnoteDef = null;
633
+ for (;;) {
634
+ if (node.type === "footnoteDefinition") deepestFootnoteDef = node;
635
+ if (node.type === "definition") return { kind: "invisible-def" };
636
+ if (!DESCEND_THROUGH.has(node.type)) break;
637
+ const kids = node.children;
638
+ if (!kids || kids.length === 0) break;
639
+ node = kids[kids.length - 1];
640
+ }
641
+ return deepestFootnoteDef ? {
642
+ kind: "footnote-def",
643
+ identifier: deepestFootnoteDef.identifier
644
+ } : null;
616
645
  }
617
-
618
- // src/aggregateFootnotes.ts
619
- import { footnoteSafeId as footnoteSafeId2, lastMeaningfulIdx } from "@ai-markdown/engine";
620
-
621
- // src/cloneHastForRender.ts
622
646
  function cloneHastForRender(node) {
623
- const copy = { ...node };
624
- const withChildren = copy;
625
- if (Array.isArray(withChildren.children)) {
626
- withChildren.children = withChildren.children.map((child) => cloneHastForRender(child));
627
- }
628
- const withProperties = copy;
629
- if (withProperties.properties) {
630
- withProperties.properties = { ...withProperties.properties };
631
- }
632
- if (copy.data) {
633
- copy.data = { ...copy.data };
634
- const data = copy.data;
635
- if (data.originalUrls) data.originalUrls = { ...data.originalUrls };
636
- }
637
- return copy;
647
+ const copy = { ...node };
648
+ const withChildren = copy;
649
+ if (Array.isArray(withChildren.children)) withChildren.children = withChildren.children.map((child) => cloneHastForRender(child));
650
+ const withProperties = copy;
651
+ if (withProperties.properties) withProperties.properties = { ...withProperties.properties };
652
+ if (copy.data) {
653
+ copy.data = { ...copy.data };
654
+ const data = copy.data;
655
+ if (data.originalUrls) data.originalUrls = { ...data.originalUrls };
656
+ }
657
+ return copy;
638
658
  }
639
-
640
- // src/aggregateFootnotes.ts
641
659
  function buildBackref(href, occurrence, globalNumber) {
642
- const children = [{ type: "text", value: "\u21A9" }];
643
- if (occurrence > 1) {
644
- children.push({
645
- type: "element",
646
- tagName: "sup",
647
- properties: {},
648
- children: [{ type: "text", value: String(occurrence) }]
649
- });
650
- }
651
- const ariaLabel = occurrence === 1 ? `Back to reference ${globalNumber}` : `Back to reference ${globalNumber}-${occurrence}`;
652
- return {
653
- type: "element",
654
- tagName: "a",
655
- properties: {
656
- href,
657
- dataFootnoteBackref: "",
658
- className: ["data-footnote-backref"],
659
- ariaLabel
660
- },
661
- children
662
- };
660
+ const children = [{
661
+ type: "text",
662
+ value: "↩"
663
+ }];
664
+ if (occurrence > 1) children.push({
665
+ type: "element",
666
+ tagName: "sup",
667
+ properties: {},
668
+ children: [{
669
+ type: "text",
670
+ value: String(occurrence)
671
+ }]
672
+ });
673
+ return {
674
+ type: "element",
675
+ tagName: "a",
676
+ properties: {
677
+ href,
678
+ dataFootnoteBackref: "",
679
+ className: ["data-footnote-backref"],
680
+ ariaLabel: occurrence === 1 ? `Back to reference ${globalNumber}` : `Back to reference ${globalNumber}-${occurrence}`
681
+ },
682
+ children
683
+ };
663
684
  }
664
685
  function buildAggregateTree(registry, clobberPrefix, preserveOrphanReferences = false) {
665
- const seen = /* @__PURE__ */ new Set();
666
- const ordered = [];
667
- for (const sym of registry.chunkOrder) {
668
- const data = registry.chunkData.get(sym);
669
- if (!data) continue;
670
- for (const ref of data.refs) {
671
- if (ref.kind !== "footnote") continue;
672
- if (seen.has(ref.label)) continue;
673
- seen.add(ref.label);
674
- const canonicalSym = registry.canonicalFootnoteFor(ref.label);
675
- if (!canonicalSym) continue;
676
- const def = registry.chunkData.get(canonicalSym)?.defs.get(ref.label);
677
- if (!def) continue;
678
- const n = registry.globalNumber(ref.label);
679
- if (n === null) continue;
680
- const sourceIdentifier = def.sourceIdentifier ?? ref.label;
681
- ordered.push({
682
- normalizedLabel: ref.label,
683
- sourceIdentifier,
684
- bodyHast: def.bodyHast ?? [],
685
- n,
686
- withBackref: true
687
- });
688
- }
689
- }
690
- ordered.sort((a, b) => (a.n ?? 0) - (b.n ?? 0));
691
- if (preserveOrphanReferences) {
692
- for (const sym of registry.chunkOrder) {
693
- const data = registry.chunkData.get(sym);
694
- if (!data) continue;
695
- for (const [label, def] of data.defs) {
696
- if (seen.has(label)) continue;
697
- if (registry.canonicalFootnoteFor(label) !== sym) continue;
698
- seen.add(label);
699
- ordered.push({
700
- normalizedLabel: label,
701
- sourceIdentifier: def.sourceIdentifier ?? label,
702
- bodyHast: def.bodyHast ?? [],
703
- n: null,
704
- withBackref: false
705
- });
706
- }
707
- }
708
- }
709
- if (ordered.length === 0) return null;
710
- const liElements = ordered.map(({ normalizedLabel, sourceIdentifier, bodyHast, n, withBackref }) => {
711
- const safeId = footnoteSafeId2(sourceIdentifier);
712
- const liChildren = bodyHast.map((c) => cloneHastForRender(c));
713
- if (withBackref) {
714
- const totalRefs = registry.getRefsForLabel(normalizedLabel);
715
- const tailIdx = lastMeaningfulIdx(liChildren);
716
- const tail = tailIdx !== -1 ? liChildren[tailIdx] : null;
717
- const dest = tail && tail.type === "element" && tail.tagName === "p" ? tail : null;
718
- const appended = [];
719
- for (let i = 1; i <= Math.max(totalRefs, 1); i++) {
720
- appended.push({ type: "text", value: " " });
721
- const href = i === 1 ? `#${clobberPrefix}fnref-${safeId}` : `#${clobberPrefix}fnref-${safeId}-${i}`;
722
- appended.push(buildBackref(href, i, n ?? 0));
723
- }
724
- if (dest) {
725
- dest.children = [...dest.children, ...appended];
726
- } else if (tailIdx !== -1) {
727
- liChildren.splice(tailIdx + 1, 0, ...appended);
728
- } else {
729
- liChildren.push(...appended);
730
- }
731
- }
732
- return {
733
- type: "element",
734
- tagName: "li",
735
- properties: {
736
- id: `${clobberPrefix}fn-${safeId}`,
737
- // Stringified: @types/hast (≥3.0.5) types li's `value` as string;
738
- // React serializes value={3} and value="3" to identical markup.
739
- ...n !== null ? { value: String(n) } : {}
740
- },
741
- children: liChildren
742
- };
743
- });
744
- return {
745
- type: "element",
746
- tagName: "section",
747
- properties: {
748
- className: ["footnotes"],
749
- dataFootnotes: true,
750
- // a11y: name the section landmark so screen readers still announce it
751
- // even though the visible "Footnotes" h2 is omitted in coordinated mode.
752
- ariaLabel: "Footnotes"
753
- },
754
- children: [
755
- // Conventional separator above the footnote list. The default
756
- // mdast-util-to-hast footer doesn't emit one (GitHub renders the
757
- // separation via CSS `border-top` on `.footnotes`); we render a literal
758
- // `<hr>` so the visual break is preserved without sanitize-friendly CSS.
759
- {
760
- type: "element",
761
- tagName: "hr",
762
- properties: {},
763
- children: []
764
- },
765
- {
766
- type: "element",
767
- tagName: "ol",
768
- properties: {},
769
- children: liElements
770
- }
771
- ]
772
- };
686
+ const seen = /* @__PURE__ */ new Set();
687
+ const ordered = [];
688
+ for (const sym of registry.chunkOrder) {
689
+ const data = registry.chunkData.get(sym);
690
+ if (!data) continue;
691
+ for (const ref of data.refs) {
692
+ if (ref.kind !== "footnote") continue;
693
+ if (seen.has(ref.label)) continue;
694
+ seen.add(ref.label);
695
+ const canonicalSym = registry.canonicalFootnoteFor(ref.label);
696
+ if (!canonicalSym) continue;
697
+ const def = registry.chunkData.get(canonicalSym)?.defs.get(ref.label);
698
+ if (!def) continue;
699
+ const n = registry.globalNumber(ref.label);
700
+ if (n === null) continue;
701
+ const sourceIdentifier = def.sourceIdentifier ?? ref.label;
702
+ ordered.push({
703
+ normalizedLabel: ref.label,
704
+ sourceIdentifier,
705
+ bodyHast: def.bodyHast ?? [],
706
+ n,
707
+ withBackref: true
708
+ });
709
+ }
710
+ }
711
+ ordered.sort((a, b) => (a.n ?? 0) - (b.n ?? 0));
712
+ if (preserveOrphanReferences) for (const sym of registry.chunkOrder) {
713
+ const data = registry.chunkData.get(sym);
714
+ if (!data) continue;
715
+ for (const [label, def] of data.defs) {
716
+ if (seen.has(label)) continue;
717
+ if (registry.canonicalFootnoteFor(label) !== sym) continue;
718
+ seen.add(label);
719
+ ordered.push({
720
+ normalizedLabel: label,
721
+ sourceIdentifier: def.sourceIdentifier ?? label,
722
+ bodyHast: def.bodyHast ?? [],
723
+ n: null,
724
+ withBackref: false
725
+ });
726
+ }
727
+ }
728
+ if (ordered.length === 0) return null;
729
+ return {
730
+ type: "element",
731
+ tagName: "section",
732
+ properties: {
733
+ className: ["footnotes"],
734
+ dataFootnotes: true,
735
+ ariaLabel: "Footnotes"
736
+ },
737
+ children: [{
738
+ type: "element",
739
+ tagName: "hr",
740
+ properties: {},
741
+ children: []
742
+ }, {
743
+ type: "element",
744
+ tagName: "ol",
745
+ properties: {},
746
+ children: ordered.map(({ normalizedLabel, sourceIdentifier, bodyHast, n, withBackref }) => {
747
+ const safeId = footnoteSafeId(sourceIdentifier);
748
+ const liChildren = bodyHast.map((c) => cloneHastForRender(c));
749
+ if (withBackref) {
750
+ const totalRefs = registry.getRefsForLabel(normalizedLabel);
751
+ const tailIdx = lastMeaningfulIdx(liChildren);
752
+ const tail = tailIdx !== -1 ? liChildren[tailIdx] : null;
753
+ const dest = tail && tail.type === "element" && tail.tagName === "p" ? tail : null;
754
+ const appended = [];
755
+ for (let i = 1; i <= Math.max(totalRefs, 1); i++) {
756
+ appended.push({
757
+ type: "text",
758
+ value: " "
759
+ });
760
+ const href = i === 1 ? `#${clobberPrefix}fnref-${safeId}` : `#${clobberPrefix}fnref-${safeId}-${i}`;
761
+ appended.push(buildBackref(href, i, n ?? 0));
762
+ }
763
+ if (dest) dest.children = [...dest.children, ...appended];
764
+ else if (tailIdx !== -1) liChildren.splice(tailIdx + 1, 0, ...appended);
765
+ else liChildren.push(...appended);
766
+ }
767
+ return {
768
+ type: "element",
769
+ tagName: "li",
770
+ properties: {
771
+ id: `${clobberPrefix}fn-${safeId}`,
772
+ ...n !== null ? { value: String(n) } : {}
773
+ },
774
+ children: liChildren
775
+ };
776
+ })
777
+ }]
778
+ };
773
779
  }
774
-
775
- // src/pipelineSession.ts
776
- import {
777
- EngineRawHtmlDepthError,
778
- advanceIncrementalParse,
779
- buildPhantomSuffix,
780
- phantomSuffixCloser,
781
- parseStage,
782
- transformStage
783
- } from "@ai-markdown/engine";
784
- var unmeasured = (_stage, fn) => fn();
780
+ const unmeasured = (_stage, fn) => fn();
785
781
  function endPoint(text) {
786
- let line = 1;
787
- let lineStart = 0;
788
- for (let i = 0; i < text.length; i++) {
789
- const code = text.charCodeAt(i);
790
- if (code === 10 || code === 13 && text.charCodeAt(i + 1) !== 10) {
791
- line += 1;
792
- lineStart = i + 1;
793
- }
794
- }
795
- return { line, column: text.length - lineStart + 1, offset: text.length };
782
+ let line = 1;
783
+ let lineStart = 0;
784
+ for (let i = 0; i < text.length; i++) {
785
+ const code = text.charCodeAt(i);
786
+ if (code === 10 || code === 13 && text.charCodeAt(i + 1) !== 10) {
787
+ line += 1;
788
+ lineStart = i + 1;
789
+ }
790
+ }
791
+ return {
792
+ line,
793
+ column: text.length - lineStart + 1,
794
+ offset: text.length
795
+ };
796
796
  }
797
797
  function plainTextTrees(content) {
798
- const position = { start: { line: 1, column: 1, offset: 0 }, end: endPoint(content) };
799
- const text = { type: "text", value: content, position };
800
- return {
801
- mdast: { type: "root", children: [{ type: "paragraph", children: [text], position }], position },
802
- hast: {
803
- type: "root",
804
- children: [{ type: "element", tagName: "p", properties: {}, children: [text], position }],
805
- position
806
- }
807
- };
798
+ const position = {
799
+ start: {
800
+ line: 1,
801
+ column: 1,
802
+ offset: 0
803
+ },
804
+ end: endPoint(content)
805
+ };
806
+ const text = {
807
+ type: "text",
808
+ value: content,
809
+ position
810
+ };
811
+ return {
812
+ mdast: {
813
+ type: "root",
814
+ children: [{
815
+ type: "paragraph",
816
+ children: [text],
817
+ position
818
+ }],
819
+ position
820
+ },
821
+ hast: {
822
+ type: "root",
823
+ children: [{
824
+ type: "element",
825
+ tagName: "p",
826
+ properties: {},
827
+ children: [text],
828
+ position
829
+ }],
830
+ position
831
+ }
832
+ };
808
833
  }
809
834
  function createPipelineSession() {
810
- let state = null;
811
- return {
812
- reset() {
813
- state = null;
814
- },
815
- parse({
816
- content,
817
- targetPhantoms,
818
- remarkPlugins,
819
- rehypePlugins,
820
- remarkRehypeOptions,
821
- handlers,
822
- preserveForBodyHarvest,
823
- documentId,
824
- provenance,
825
- incrementalParse,
826
- defListEnabled,
827
- gfmTaskListItems = false,
828
- // No default: omitted is its own (undeclared) state at the engine.
829
- mathFlow,
830
- measure: measureHere = unmeasured
831
- }) {
832
- const phantomDefs = buildPhantomSuffix(targetPhantoms);
833
- const phantomSuffix = phantomDefs === "" ? "" : phantomSuffixCloser(content ?? "") + phantomDefs;
834
- const augmented = (content ?? "") + phantomSuffix;
835
- const baseHandlers = remarkRehypeOptions?.handlers ?? {};
836
- const mergedRemarkRehypeOptions = handlers ? {
837
- ...remarkRehypeOptions,
838
- handlers: { ...baseHandlers, ...handlers },
839
- // Phantom label sets are empty in standalone mode (no PASS 0.5
840
- // injection happened); the footnoteDefinition handler still reads
841
- // them via `state.options.phantomFootnoteLabels.has(id)`, which
842
- // returns false for every id → orphan-protect path proceeds.
843
- phantomFootnoteLabels: targetPhantoms.missingFootnotes,
844
- phantomLinkLabels: targetPhantoms.missingLinks,
845
- preserveOrphan: preserveForBodyHarvest,
846
- documentId,
847
- // The SAME value `buildCoreRehypePlugins` received — the
848
- // verifier unwraps every placeholder stamped with anything else.
849
- provenance
850
- } : {
851
- ...remarkRehypeOptions
852
- };
853
- const fullPipeline = () => {
854
- try {
855
- const parsed = measureHere(
856
- "parse",
857
- () => parseStage({
858
- children: augmented,
859
- remarkPlugins,
860
- rehypePlugins,
861
- remarkRehypeOptions: mergedRemarkRehypeOptions
862
- })
863
- );
864
- const hastRoot = measureHere("transform", () => transformStage(parsed));
865
- return { mdast: parsed.mdast, hast: hastRoot };
866
- } catch (error) {
867
- if (!(error instanceof EngineRawHtmlDepthError)) throw error;
868
- if (false) {
869
- console.error(
870
- "[ai-react-markdown] raw HTML nested past the engine depth bound \u2014 rendering this frame as plain text:",
871
- error
872
- );
873
- }
874
- return plainTextTrees(content ?? "");
875
- }
876
- };
877
- if (!incrementalParse) {
878
- state = null;
879
- return fullPipeline();
880
- }
881
- try {
882
- const result = advanceIncrementalParse(state, content ?? "", {
883
- remarkPlugins,
884
- rehypePlugins,
885
- remarkRehypeOptions: mergedRemarkRehypeOptions,
886
- // Identity tuple over every parse input beyond the content itself.
887
- // Deliberately covers MORE than the G3 flush's 12 fields (handlers /
888
- // preserveForBodyHarvest / documentId can change without touching
889
- // any G3 field — e.g. a `preserveOrphanReferences` flip). The
890
- // phantom label sets are deliberately NOT here: their churn tracks
891
- // the suffix (always re-parsed with the tail), never the prefix.
892
- depsKey: [
893
- remarkPlugins,
894
- rehypePlugins,
895
- remarkRehypeOptions,
896
- handlers,
897
- preserveForBodyHarvest,
898
- documentId,
899
- // Explicit even though `rehypePlugins` already carries it: a
900
- // credential change must never reuse trees stamped under the
901
- // old one.
902
- provenance,
903
- // The boundary scanner's grammar profile. The scan checkpoint
904
- // already refuses to resume under a different profile, but the
905
- // retained TREES were still spliced against — a prefix frozen
906
- // under one profile must not survive into frames under the other.
907
- defListEnabled,
908
- gfmTaskListItems,
909
- mathFlow
910
- ],
911
- defListEnabled,
912
- gfmTaskListItems,
913
- mathFlow,
914
- phantomSuffix,
915
- measure: measureHere
916
- });
917
- state = result.nextState;
918
- return { mdast: result.mdast, hast: result.hast };
919
- } catch (error) {
920
- state = null;
921
- if (false) {
922
- console.error("[ai-react-markdown] incremental parse failed \u2014 full parse fallback for this frame:", error);
923
- }
924
- return fullPipeline();
925
- }
926
- }
927
- };
835
+ let state = null;
836
+ return {
837
+ reset() {
838
+ state = null;
839
+ },
840
+ parse({ content, targetPhantoms, remarkPlugins, rehypePlugins, remarkRehypeOptions, handlers, preserveForBodyHarvest, documentId, provenance, incrementalParse, defListEnabled, gfmTaskListItems = false, mathFlow, measure: measureHere = unmeasured }) {
841
+ const phantomDefs = buildPhantomSuffix(targetPhantoms);
842
+ const phantomSuffix = phantomDefs === "" ? "" : phantomSuffixCloser(content ?? "") + phantomDefs;
843
+ const augmented = (content ?? "") + phantomSuffix;
844
+ const baseHandlers = remarkRehypeOptions?.handlers ?? {};
845
+ const mergedRemarkRehypeOptions = handlers ? {
846
+ ...remarkRehypeOptions,
847
+ handlers: {
848
+ ...baseHandlers,
849
+ ...handlers
850
+ },
851
+ phantomFootnoteLabels: targetPhantoms.missingFootnotes,
852
+ phantomLinkLabels: targetPhantoms.missingLinks,
853
+ preserveOrphan: preserveForBodyHarvest,
854
+ documentId,
855
+ provenance
856
+ } : { ...remarkRehypeOptions };
857
+ const fullPipeline = () => {
858
+ try {
859
+ const parsed = measureHere("parse", () => parseStage({
860
+ children: augmented,
861
+ remarkPlugins,
862
+ rehypePlugins,
863
+ remarkRehypeOptions: mergedRemarkRehypeOptions
864
+ }));
865
+ const hastRoot = measureHere("transform", () => transformStage(parsed));
866
+ return {
867
+ mdast: parsed.mdast,
868
+ hast: hastRoot
869
+ };
870
+ } catch (error) {
871
+ if (!(error instanceof EngineRawHtmlDepthError)) throw error;
872
+ return plainTextTrees(content ?? "");
873
+ }
874
+ };
875
+ if (!incrementalParse) {
876
+ state = null;
877
+ return fullPipeline();
878
+ }
879
+ try {
880
+ const result = advanceIncrementalParse(state, content ?? "", {
881
+ remarkPlugins,
882
+ rehypePlugins,
883
+ remarkRehypeOptions: mergedRemarkRehypeOptions,
884
+ depsKey: [
885
+ remarkPlugins,
886
+ rehypePlugins,
887
+ remarkRehypeOptions,
888
+ handlers,
889
+ preserveForBodyHarvest,
890
+ documentId,
891
+ provenance,
892
+ defListEnabled,
893
+ gfmTaskListItems,
894
+ mathFlow
895
+ ],
896
+ defListEnabled,
897
+ gfmTaskListItems,
898
+ mathFlow,
899
+ phantomSuffix,
900
+ measure: measureHere
901
+ });
902
+ state = result.nextState;
903
+ return {
904
+ mdast: result.mdast,
905
+ hast: result.hast
906
+ };
907
+ } catch (error) {
908
+ state = null;
909
+ return fullPipeline();
910
+ }
911
+ }
912
+ };
928
913
  }
929
-
930
- // src/coordinationPreparation.ts
931
- import { buildCrossChunkHandlers, normalizeForMatch } from "@ai-markdown/engine";
932
914
  function derivePhantomTargets({ content, ownLabels, labels }, previous) {
933
- const missingFootnotes = /* @__PURE__ */ new Set();
934
- const missingLinks = /* @__PURE__ */ new Set();
935
- if (labels) {
936
- const footnotes = [...labels.footnoteLabels].filter((label) => !ownLabels.footnoteLabels.has(label));
937
- const links = [...labels.linkLabels].filter((label) => !ownLabels.linkLabels.has(label));
938
- if (footnotes.length || links.length) {
939
- const normalized = normalizeForMatch(content);
940
- for (const label of footnotes) if (normalized.includes(label)) missingFootnotes.add(label);
941
- for (const label of links) if (normalized.includes(label)) missingLinks.add(label);
942
- }
943
- }
944
- if (previous && missingFootnotes.size === previous.missingFootnotes.size && missingLinks.size === previous.missingLinks.size && [...missingFootnotes].every((label) => previous.missingFootnotes.has(label)) && [...missingLinks].every((label) => previous.missingLinks.has(label)))
945
- return previous;
946
- return { missingFootnotes, missingLinks };
915
+ const missingFootnotes = /* @__PURE__ */ new Set();
916
+ const missingLinks = /* @__PURE__ */ new Set();
917
+ if (labels) {
918
+ const footnotes = [...labels.footnoteLabels].filter((label) => !ownLabels.footnoteLabels.has(label));
919
+ const links = [...labels.linkLabels].filter((label) => !ownLabels.linkLabels.has(label));
920
+ if (footnotes.length || links.length) {
921
+ const normalized = normalizeForMatch(content);
922
+ for (const label of footnotes) if (normalized.includes(label)) missingFootnotes.add(label);
923
+ for (const label of links) if (normalized.includes(label)) missingLinks.add(label);
924
+ }
925
+ }
926
+ if (previous && missingFootnotes.size === previous.missingFootnotes.size && missingLinks.size === previous.missingLinks.size && [...missingFootnotes].every((label) => previous.missingFootnotes.has(label)) && [...missingLinks].every((label) => previous.missingLinks.has(label))) return previous;
927
+ return {
928
+ missingFootnotes,
929
+ missingLinks
930
+ };
947
931
  }
948
- function deriveCoordinationPolicy({
949
- coordinated,
950
- registered,
951
- preserveOrphanReferences
952
- }, previous) {
953
- const mode = coordinated ? "coordinated" : preserveOrphanReferences ? "orphan" : "standalone";
954
- const preserveForBodyHarvest = preserveOrphanReferences || coordinated && registered;
955
- if (previous?.mode === mode && previous.preserveForBodyHarvest === preserveForBodyHarvest) return previous;
956
- const handlers = previous?.mode === mode ? previous.handlers : mode === "coordinated" ? buildCrossChunkHandlers() : mode === "orphan" ? { footnoteDefinition: buildCrossChunkHandlers().footnoteDefinition } : void 0;
957
- return { mode, handlers, preserveForBodyHarvest };
932
+ function deriveCoordinationPolicy({ coordinated, registered, preserveOrphanReferences }, previous) {
933
+ const mode = coordinated ? "coordinated" : preserveOrphanReferences ? "orphan" : "standalone";
934
+ const preserveForBodyHarvest = preserveOrphanReferences || coordinated && registered;
935
+ if (previous?.mode === mode && previous.preserveForBodyHarvest === preserveForBodyHarvest) return previous;
936
+ return {
937
+ mode,
938
+ handlers: previous?.mode === mode ? previous.handlers : mode === "coordinated" ? buildCrossChunkHandlers() : mode === "orphan" ? { footnoteDefinition: buildCrossChunkHandlers().footnoteDefinition } : void 0,
939
+ preserveForBodyHarvest
940
+ };
958
941
  }
959
942
  function buildContributionChain(inputs) {
960
- return [
961
- inputs.remarkPlugins,
962
- inputs.rehypePlugins,
963
- inputs.remarkRehypeOptions,
964
- inputs.handlers,
965
- inputs.preserveForBodyHarvest,
966
- inputs.clobberPrefix,
967
- inputs.documentId,
968
- inputs.provenance
969
- ];
943
+ return [
944
+ inputs.remarkPlugins,
945
+ inputs.rehypePlugins,
946
+ inputs.remarkRehypeOptions,
947
+ inputs.handlers,
948
+ inputs.preserveForBodyHarvest,
949
+ inputs.clobberPrefix,
950
+ inputs.documentId,
951
+ inputs.provenance
952
+ ];
970
953
  }
971
- export {
972
- buildAggregateTree,
973
- buildBlocks,
974
- buildContributionChain,
975
- cloneHastForRender,
976
- computeBlockFingerprint,
977
- computeHtmlBlockDigest,
978
- computeHtmlBlockDigestWithExtent,
979
- createBlockPlanner,
980
- createContributionSession,
981
- createPipelineSession,
982
- createSmoothCoordinator2 as createSmoothCoordinator,
983
- deriveCoordinationPolicy,
984
- derivePhantomTargets,
985
- deriveTailSignal,
986
- evaluateGateWarn,
987
- hasMdastSource,
988
- isFootnoteSection
989
- };
954
+ export { buildAggregateTree, buildBlocks, buildContributionChain, cloneHastForRender, computeBlockFingerprint, computeHtmlBlockDigest, computeHtmlBlockDigestWithExtent, createBlockPlanner, createContributionSession, createPipelineSession, createSmoothCoordinator, deriveCoordinationPolicy, derivePhantomTargets, deriveTailSignal, evaluateGateWarn, hasMdastSource, isFootnoteSection };
955
+
990
956
  //# sourceMappingURL=index.js.map