@stream-mdx/react 0.5.0 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (99) hide show
  1. package/CHANGELOG.md +371 -0
  2. package/README.md +79 -4
  3. package/dist/blocks-renderer-DAOBFBfi.d.ts +29 -0
  4. package/dist/blocks-renderer-DQEL1kJW.d.cts +29 -0
  5. package/dist/components/bottom-stick-scroll-area.cjs +117 -193
  6. package/dist/components/bottom-stick-scroll-area.mjs +112 -183
  7. package/dist/components/diff-renderer.cjs +86 -0
  8. package/dist/components/diff-renderer.d.cts +11 -0
  9. package/dist/components/diff-renderer.d.ts +11 -0
  10. package/dist/components/diff-renderer.mjs +66 -0
  11. package/dist/components/index.cjs +2761 -1508
  12. package/dist/components/index.d.cts +7 -2
  13. package/dist/components/index.d.ts +7 -2
  14. package/dist/components/index.mjs +2730 -1493
  15. package/dist/components/katex-math.cjs +220 -0
  16. package/dist/components/katex-math.d.cts +10 -0
  17. package/dist/components/katex-math.d.ts +10 -0
  18. package/dist/components/katex-math.mjs +188 -0
  19. package/dist/contexts/math-tracker.cjs +240 -521
  20. package/dist/contexts/math-tracker.mjs +235 -513
  21. package/dist/index-Cmne1yUK.d.cts +723 -0
  22. package/dist/index-D7dyyu3q.d.ts +723 -0
  23. package/dist/index.cjs +13029 -6475
  24. package/dist/index.d.cts +69 -39
  25. package/dist/index.d.ts +69 -39
  26. package/dist/index.mjs +13007 -6442
  27. package/dist/math/display-wrapper.cjs +7 -15
  28. package/dist/math/display-wrapper.d.cts +2 -2
  29. package/dist/math/display-wrapper.d.ts +2 -2
  30. package/dist/math/display-wrapper.mjs +2 -6
  31. package/dist/node-views-Bpc6Gkgl.d.cts +13 -0
  32. package/dist/node-views-DpnYdaAS.d.ts +13 -0
  33. package/dist/renderer/hooks.cjs +35 -20
  34. package/dist/renderer/hooks.d.cts +22 -1
  35. package/dist/renderer/hooks.d.ts +22 -1
  36. package/dist/renderer/hooks.mjs +27 -12
  37. package/dist/renderer/patch-batching.cjs +5 -8
  38. package/dist/renderer/patch-coalescing.cjs +5 -8
  39. package/dist/renderer/patch-commit-scheduler.cjs +138 -356
  40. package/dist/renderer/patch-commit-scheduler.d.cts +13 -1
  41. package/dist/renderer/patch-commit-scheduler.d.ts +13 -1
  42. package/dist/renderer/patch-commit-scheduler.mjs +133 -348
  43. package/dist/renderer/store.cjs +3775 -1373
  44. package/dist/renderer/store.d.cts +108 -3
  45. package/dist/renderer/store.d.ts +108 -3
  46. package/dist/renderer/store.mjs +3778 -1362
  47. package/dist/renderer/virtualized-code.cjs +415 -71
  48. package/dist/renderer/virtualized-code.d.cts +24 -23
  49. package/dist/renderer/virtualized-code.d.ts +24 -23
  50. package/dist/renderer/virtualized-code.mjs +409 -62
  51. package/dist/renderer.cjs +10655 -4334
  52. package/dist/renderer.d.cts +98 -29
  53. package/dist/renderer.d.ts +98 -29
  54. package/dist/renderer.mjs +10582 -4212
  55. package/dist/server-regions-CPLHGli0.d.cts +32 -0
  56. package/dist/server-regions-mUhyoKi7.d.ts +32 -0
  57. package/dist/server.cjs +10195 -3872
  58. package/dist/server.d.cts +17 -252
  59. package/dist/server.d.ts +17 -252
  60. package/dist/server.mjs +9997 -3649
  61. package/dist/{streaming-markdown-CEI9eDZm.d.ts → streaming-markdown-yELbJxyH.d.ts} +49 -55
  62. package/dist/{streaming-markdown-DRisClXb.d.cts → streaming-markdown-zVwFuaJG.d.cts} +49 -55
  63. package/dist/streaming-markdown.cjs +11660 -5378
  64. package/dist/streaming-markdown.d.cts +7 -2
  65. package/dist/streaming-markdown.d.ts +7 -2
  66. package/dist/streaming-markdown.mjs +11679 -5347
  67. package/dist/trusted-mdx/index.cjs +833 -0
  68. package/dist/trusted-mdx/index.d.cts +11 -0
  69. package/dist/trusted-mdx/index.d.ts +11 -0
  70. package/dist/trusted-mdx/index.mjs +807 -0
  71. package/dist/trusted-mdx/native-children-slot.cjs +45 -0
  72. package/dist/trusted-mdx/native-children-slot.d.cts +11 -0
  73. package/dist/trusted-mdx/native-children-slot.d.ts +11 -0
  74. package/dist/trusted-mdx/native-children-slot.mjs +24 -0
  75. package/dist/trusted-mdx/server.cjs +752 -0
  76. package/dist/trusted-mdx/server.d.cts +24 -0
  77. package/dist/trusted-mdx/server.d.ts +24 -0
  78. package/dist/trusted-mdx/server.mjs +724 -0
  79. package/dist/trusted-mdx-contract-ElKpkDI5.d.cts +113 -0
  80. package/dist/trusted-mdx-contract-ElKpkDI5.d.ts +113 -0
  81. package/dist/utils/inline-html.cjs +246 -147
  82. package/dist/utils/inline-html.d.cts +37 -6
  83. package/dist/utils/inline-html.d.ts +37 -6
  84. package/dist/utils/inline-html.mjs +237 -134
  85. package/package.json +41 -18
  86. package/dist/index-BVhp_pcF.d.ts +0 -251
  87. package/dist/index-EaeouYp2.d.cts +0 -251
  88. package/dist/mdx-client.cjs +0 -408
  89. package/dist/mdx-client.d.cts +0 -113
  90. package/dist/mdx-client.d.ts +0 -113
  91. package/dist/mdx-client.mjs +0 -369
  92. package/dist/mdx-coordinator.cjs +0 -584
  93. package/dist/mdx-coordinator.d.cts +0 -21
  94. package/dist/mdx-coordinator.d.ts +0 -21
  95. package/dist/mdx-coordinator.mjs +0 -550
  96. package/dist/renderer/node-views.cjs +0 -1887
  97. package/dist/renderer/node-views.d.cts +0 -14
  98. package/dist/renderer/node-views.d.ts +0 -14
  99. package/dist/renderer/node-views.mjs +0 -1861
@@ -0,0 +1,807 @@
1
+ "use client";
2
+
3
+ // src/trusted-mdx/engine.ts
4
+ import {
5
+ compileTrustedMdxDocument,
6
+ TRUSTED_MDX_COMPILER_REVISION
7
+ } from "@stream-mdx/worker/mdx-compile";
8
+
9
+ // src/trusted-mdx/evaluate.ts
10
+ import React from "react";
11
+ import * as jsxRuntime from "react/jsx-runtime";
12
+ var AsyncFunction = Object.getPrototypeOf(async function() {
13
+ }).constructor;
14
+ async function evaluateCompiledMdx(code, options, canInvoke) {
15
+ let hostImports = options.imports, resolveSyncHostImport = (specifier) => {
16
+ if (specifier === "react")
17
+ return { default: React, ...React };
18
+ if (specifier === "react/jsx-runtime")
19
+ return jsxRuntime;
20
+ if (hostImports && Object.prototype.hasOwnProperty.call(hostImports, specifier))
21
+ return hostImports[specifier];
22
+ throw new Error(
23
+ `Cannot resolve MDX import specifier "${specifier}": no host binding configured. Automatic fetching and network egress are disabled.`
24
+ );
25
+ };
26
+ async function resolveDynamicHostImport(specifier) {
27
+ return resolveSyncHostImport(specifier);
28
+ }
29
+ let runtime = {
30
+ Fragment: jsxRuntime.Fragment,
31
+ jsx: jsxRuntime.jsx,
32
+ jsxs: jsxRuntime.jsxs,
33
+ _resolveSyncHostImport: resolveSyncHostImport,
34
+ _resolveDynamicHostImport: resolveDynamicHostImport
35
+ }, fn = new AsyncFunction(code);
36
+ return canInvoke() ? fn(runtime) : null;
37
+ }
38
+
39
+ // src/trusted-mdx/projection.ts
40
+ function getActiveTrustedMdxNativeTree(meta) {
41
+ if (Array.isArray(meta?.trustedMdxNativeChildren)) return meta.trustedMdxNativeChildren;
42
+ if (meta?.htmlOwnership === !0 && Array.isArray(meta.htmlTree)) return meta.htmlTree;
43
+ if (Array.isArray(meta?.htmlParagraphTree)) return meta.htmlParagraphTree;
44
+ if (Array.isArray(meta?.htmlTree)) return meta.htmlTree;
45
+ }
46
+ function readSourceRange(value, sourceLength) {
47
+ if (typeof value != "object" || value === null || Array.isArray(value) || !("from" in value) || !("to" in value))
48
+ return null;
49
+ let from = value.from, to = value.to;
50
+ return typeof from != "number" || typeof to != "number" || !Number.isSafeInteger(from) || !Number.isSafeInteger(to) || from < 0 || to <= from || to > sourceLength ? null : { from, to };
51
+ }
52
+ function readSnapshotFields(value) {
53
+ if (typeof value != "object" || value === null || Array.isArray(value) || !("id" in value) || !("type" in value))
54
+ return null;
55
+ let id = value.id, type = value.type;
56
+ return typeof id != "string" || typeof type != "string" ? null : {
57
+ id,
58
+ type,
59
+ range: "range" in value ? value.range : void 0,
60
+ props: "props" in value ? value.props : void 0,
61
+ children: "children" in value ? value.children : void 0
62
+ };
63
+ }
64
+ function hasNativeBlockOwner(tree) {
65
+ if (!Array.isArray(tree)) return !1;
66
+ let pending = [...tree];
67
+ for (; pending.length > 0; ) {
68
+ let current = pending.pop();
69
+ if (!(typeof current != "object" || current === null || Array.isArray(current))) {
70
+ if ("kind" in current && current.kind === "block" && "block" in current) return !0;
71
+ "children" in current && Array.isArray(current.children) && pending.push(...current.children);
72
+ }
73
+ }
74
+ return !1;
75
+ }
76
+ function collectInlineOwners(value, sourceLength, matches) {
77
+ if (!Array.isArray(value)) return;
78
+ let visited = /* @__PURE__ */ new WeakSet(), pending = [...value];
79
+ for (; pending.length > 0; ) {
80
+ let current = pending.pop();
81
+ if (!(typeof current != "object" || current === null || visited.has(current))) {
82
+ if (visited.add(current), Array.isArray(current)) {
83
+ pending.push(...current);
84
+ continue;
85
+ }
86
+ "kind" in current && current.kind === "trusted-mdx-inline" && "ownerId" in current && typeof current.ownerId == "string" && addMdxOwner(
87
+ matches,
88
+ current.ownerId,
89
+ "inline expression",
90
+ "sourceRange" in current ? current.sourceRange : void 0,
91
+ sourceLength
92
+ ), "children" in current && Array.isArray(current.children) && pending.push(...current.children);
93
+ }
94
+ }
95
+ }
96
+ function isNestedMdxType(type) {
97
+ return type === "paragraph-mdx" || type === "blockquote-mdx" || type === "list-item-mdx";
98
+ }
99
+ function addMdxOwner(matches, id, label, range, sourceLength) {
100
+ let sourceRange = readSourceRange(range, sourceLength);
101
+ matches.push({
102
+ id,
103
+ label,
104
+ from: sourceRange?.from ?? null,
105
+ to: sourceRange?.to ?? null,
106
+ regions: [],
107
+ placement: null,
108
+ rootElementName: void 0,
109
+ nativeChildren: !1,
110
+ nativeChildOwners: [],
111
+ flowChildren: void 0,
112
+ nativeFlowOwnedBlockIds: [],
113
+ wholeBlockFlowRoot: !1,
114
+ ambiguous: !1
115
+ });
116
+ }
117
+ function readFlowChildRanges(flowChildren, flowRange, sourceLength) {
118
+ if (flowChildren === void 0) return;
119
+ let ranges = [], previousTo = flowRange.from;
120
+ for (let child of flowChildren) {
121
+ let range = readSourceRange(child, sourceLength);
122
+ if (!range || range.from < flowRange.from || range.to > flowRange.to || range.from < previousTo)
123
+ return null;
124
+ ranges.push(range), previousTo = range.to;
125
+ }
126
+ return ranges;
127
+ }
128
+ function classifyFlowRange(range, childRanges) {
129
+ let directChildIndex;
130
+ for (let index = 0; index < childRanges.length; index++) {
131
+ let childRange = childRanges[index];
132
+ if (!childRange) return null;
133
+ if (range.from >= childRange.from && range.to <= childRange.to) {
134
+ if (directChildIndex !== void 0) return null;
135
+ directChildIndex = index;
136
+ } else if (range.from < childRange.to && range.to > childRange.from)
137
+ return null;
138
+ }
139
+ return directChildIndex ?? "root-syntax";
140
+ }
141
+ function findInlineChildRunForRange(range, flowChildren, childRanges) {
142
+ if (!(flowChildren === void 0 || childRanges === void 0 || range.to <= range.from))
143
+ for (let startIndex = 0; startIndex < flowChildren.length; startIndex++) {
144
+ let firstChild = flowChildren[startIndex], firstRange = childRanges[startIndex];
145
+ if (firstChild?.kind !== "inline" || !firstRange || firstRange.from !== range.from || firstRange.to <= firstRange.from) continue;
146
+ let previousRange = firstRange;
147
+ for (let endIndex = startIndex + 1; endIndex < flowChildren.length; endIndex++) {
148
+ let child = flowChildren[endIndex], childRange = childRanges[endIndex];
149
+ if (child?.kind !== "inline" || !childRange || childRange.from !== previousRange.to || childRange.to <= childRange.from) break;
150
+ if (previousRange = childRange, previousRange.to === range.to)
151
+ return {
152
+ startIndex,
153
+ endIndex
154
+ };
155
+ if (previousRange.to > range.to) break;
156
+ }
157
+ }
158
+ }
159
+ function collectFlowOwnerBlocks(blocks) {
160
+ let flowOwnerBlocks = [], seenBlockIds = /* @__PURE__ */ new Set(), pendingBlocks = [...blocks], pendingNodes = [], visitedNodes = /* @__PURE__ */ new WeakSet();
161
+ for (let blockIndex = 0; blockIndex < pendingBlocks.length; blockIndex++) {
162
+ let block = pendingBlocks[blockIndex];
163
+ if (!block || seenBlockIds.has(block.id)) continue;
164
+ seenBlockIds.add(block.id), flowOwnerBlocks.push(block);
165
+ let meta = block.payload.meta, preparedTree = getActiveTrustedMdxNativeTree(meta);
166
+ for (preparedTree !== void 0 && pendingNodes.push(...preparedTree); pendingNodes.length > 0; ) {
167
+ let node = pendingNodes.pop();
168
+ !node || visitedNodes.has(node) || (visitedNodes.add(node), node.kind === "block" ? pendingBlocks.push(node.block) : (node.kind === "element" || node.kind === "component") && pendingNodes.push(...node.children));
169
+ }
170
+ }
171
+ return flowOwnerBlocks;
172
+ }
173
+ function hasWholeFlowRootMatch(block, childRange, matches) {
174
+ return matches.some(
175
+ (match) => match.wholeBlockFlowRoot && match.from === childRange.from && match.to === childRange.to && (match.id === block.id || block.payload.inline?.some(
176
+ (node) => node.kind === "trusted-mdx-inline" && node.ownerId === match.id && node.sourceRange?.from === childRange.from && node.sourceRange?.to === childRange.to
177
+ ) === !0)
178
+ );
179
+ }
180
+ function findPreparedTreeBlock(tree, childRange, sourceLength, exact = !1, wholeFlowRoots) {
181
+ if (!tree) return;
182
+ let pending = [...tree], owner, ownerWidth = -1;
183
+ for (; pending.length > 0; ) {
184
+ let node = pending.pop();
185
+ if (node)
186
+ if (node.kind === "block") {
187
+ let range = readSourceRange(node.block.payload.range, sourceLength);
188
+ if (!range) continue;
189
+ let wholeFlowRoot = wholeFlowRoots !== void 0 && hasWholeFlowRootMatch(node.block, childRange, wholeFlowRoots) && range.from === childRange.from && range.to <= childRange.to;
190
+ (exact ? range.from === childRange.from && range.to === childRange.to || wholeFlowRoot : range.from >= childRange.from && range.to <= childRange.to) && (wholeFlowRoots === void 0 || node.block.type === "mdx" || wholeFlowRoot) && range.to - range.from > ownerWidth && (owner = node.block, ownerWidth = range.to - range.from);
191
+ } else (node.kind === "element" || node.kind === "component") && pending.push(...node.children);
192
+ }
193
+ return owner;
194
+ }
195
+ function assertPreparedTreeOwnersFitFlowChildren(tree, childRanges, flowChildren, flowRange, sourceLength) {
196
+ if (!tree) return;
197
+ let pending = [...tree];
198
+ for (; pending.length > 0; ) {
199
+ let node = pending.pop();
200
+ if (node)
201
+ if (node.kind === "block") {
202
+ let range = readSourceRange(node.block.payload.range, sourceLength);
203
+ if (!range)
204
+ throw new Error("A trusted MDX flow region has a prepared worker block without a source span.");
205
+ if (range.from < flowRange.from || range.to > flowRange.to || range.from === flowRange.from && range.to === flowRange.to) continue;
206
+ if (childRanges === void 0)
207
+ throw new Error("A trusted MDX flow region has prepared tree owners but no direct-child spans.");
208
+ let inlineRun = node.block.type === "paragraph" && Array.isArray(node.block.payload.inline) && node.block.payload.inline.length > 0 ? findInlineChildRunForRange(range, flowChildren, childRanges) : void 0;
209
+ if (classifyFlowRange(range, childRanges) === null && inlineRun === void 0)
210
+ throw new Error("A trusted MDX flow region has prepared tree owners crossing direct-child boundaries.");
211
+ } else (node.kind === "element" || node.kind === "component") && pending.push(...node.children);
212
+ }
213
+ }
214
+ function collectFlowNativeBlocks(flowChildren, flowRange, blocks, rootOwnerId, sourceLength, matches, flowOwnerBlocks) {
215
+ let childRanges = readFlowChildRanges(flowChildren, flowRange, sourceLength);
216
+ if (childRanges === null)
217
+ throw new Error("A trusted MDX flow region has invalid or overlapping direct-child spans.");
218
+ let meta = flowOwnerBlocks.find((block) => block.id === rootOwnerId)?.payload.meta, preparedTree = getActiveTrustedMdxNativeTree(meta), preparedTrees = preparedTree === void 0 ? [] : [preparedTree], ownedBlockIds = [];
219
+ for (let block of blocks) {
220
+ if (block.id === rootOwnerId) continue;
221
+ let blockRange = readSourceRange(block.payload.range, sourceLength);
222
+ if (!blockRange || blockRange.from < flowRange.from || blockRange.to > flowRange.to || blockRange.from === flowRange.from && blockRange.to === flowRange.to) continue;
223
+ if (childRanges === void 0)
224
+ throw new Error("A trusted MDX flow region has worker owners but no direct-child spans.");
225
+ let ownership = classifyFlowRange(blockRange, childRanges), inlineRun = block.type === "paragraph" && Array.isArray(block.payload.inline) && block.payload.inline.length > 0 ? findInlineChildRunForRange(blockRange, flowChildren, childRanges) : void 0;
226
+ if (ownership === null && inlineRun === void 0)
227
+ throw new Error("A trusted MDX flow region has worker owners crossing direct-child boundaries.");
228
+ ownedBlockIds.push(block.id);
229
+ }
230
+ for (let tree of preparedTrees)
231
+ hasNativeBlockOwner(tree) && assertPreparedTreeOwnersFitFlowChildren(tree, childRanges, flowChildren, flowRange, sourceLength);
232
+ if (flowChildren === void 0 || flowChildren.length === 0)
233
+ return { childOwners: [], ownedBlockIds };
234
+ if (childRanges === void 0)
235
+ throw new Error("A trusted MDX flow region has native children but no direct-child spans.");
236
+ let groupedInlineOwners, registerGroupedInlineOwner = (block, kind) => {
237
+ if (block.id === rootOwnerId || block.type !== "paragraph" || !Array.isArray(block.payload.inline) || block.payload.inline.length === 0)
238
+ return;
239
+ let range = readSourceRange(block.payload.range, sourceLength);
240
+ if (!range) return;
241
+ let run = findInlineChildRunForRange(range, flowChildren, childRanges);
242
+ if (!run) return;
243
+ let groupedOwners = groupedInlineOwners ?? (groupedInlineOwners = new Array(flowChildren.length));
244
+ for (let index = run.startIndex; index <= run.endIndex; index++) {
245
+ let existing2 = groupedOwners[index];
246
+ if (existing2 && (existing2.block.id !== block.id || existing2.startIndex !== run.startIndex || existing2.endIndex !== run.endIndex))
247
+ throw new Error("A trusted MDX flow region has duplicate native owners for one inline child run.");
248
+ }
249
+ if (groupedOwners[run.startIndex]?.owner.kind === "block" && kind === "prepared-tree") return;
250
+ let candidate = {
251
+ startIndex: run.startIndex,
252
+ endIndex: run.endIndex,
253
+ block,
254
+ owner: kind === "block" ? { kind: "block", blockId: block.id } : { kind: "prepared-tree", blockId: block.id }
255
+ };
256
+ for (let index = run.startIndex; index <= run.endIndex; index++)
257
+ groupedOwners[index] = candidate;
258
+ };
259
+ for (let block of blocks)
260
+ registerGroupedInlineOwner(block, "block");
261
+ for (let tree of preparedTrees) {
262
+ let pending = [...tree], visited = /* @__PURE__ */ new WeakSet();
263
+ for (; pending.length > 0; ) {
264
+ let node = pending.pop();
265
+ !node || visited.has(node) || (visited.add(node), node.kind === "block" ? registerGroupedInlineOwner(node.block, "prepared-tree") : (node.kind === "element" || node.kind === "component") && pending.push(...node.children));
266
+ }
267
+ }
268
+ let groupedChildRanges;
269
+ for (let startIndex = 0; startIndex < (groupedInlineOwners?.length ?? 0); startIndex++) {
270
+ let groupedOwner = groupedInlineOwners?.[startIndex];
271
+ if (!(!groupedOwner || groupedOwner.startIndex !== startIndex))
272
+ for (let childIndex = groupedOwner.startIndex; childIndex <= groupedOwner.endIndex; childIndex++) {
273
+ let childRange = childRanges[childIndex];
274
+ if (!childRange)
275
+ throw new Error("A trusted MDX flow region has an invalid grouped inline child span.");
276
+ groupedChildRanges ?? (groupedChildRanges = /* @__PURE__ */ new Map()), groupedChildRanges.set(childRange.from, childRange.to);
277
+ }
278
+ }
279
+ if (groupedChildRanges !== void 0) {
280
+ for (let block of blocks) {
281
+ if (block.id === rootOwnerId) continue;
282
+ let blockRange = readSourceRange(block.payload.range, sourceLength);
283
+ if (blockRange && groupedChildRanges.get(blockRange.from) === blockRange.to)
284
+ throw new Error("A trusted MDX flow region has duplicate native owners inside a grouped inline run.");
285
+ }
286
+ for (let tree of preparedTrees) {
287
+ let pending = [...tree], visited = /* @__PURE__ */ new WeakSet();
288
+ for (; pending.length > 0; ) {
289
+ let node = pending.pop();
290
+ if (!(!node || visited.has(node)))
291
+ if (visited.add(node), node.kind === "block") {
292
+ let blockRange = readSourceRange(node.block.payload.range, sourceLength);
293
+ if (blockRange && groupedChildRanges.get(blockRange.from) === blockRange.to)
294
+ throw new Error("A trusted MDX flow region has duplicate native owners inside a grouped inline run.");
295
+ } else (node.kind === "element" || node.kind === "component") && pending.push(...node.children);
296
+ }
297
+ }
298
+ }
299
+ let childOwners = [];
300
+ for (let childIndex = 0; childIndex < flowChildren.length; childIndex++) {
301
+ let child = flowChildren[childIndex], childRange = childRanges?.[childIndex];
302
+ if (!child || !childRange)
303
+ throw new Error("A trusted MDX flow region has invalid direct-child spans.");
304
+ let groupedOwner = groupedInlineOwners?.[childIndex];
305
+ if (groupedOwner) {
306
+ if (groupedOwner.startIndex !== childIndex || child.kind !== "inline")
307
+ throw new Error("A trusted MDX flow region has an invalid grouped inline native owner.");
308
+ childOwners.push(groupedOwner.owner);
309
+ for (let coveredIndex = childIndex + 1; coveredIndex <= groupedOwner.endIndex; coveredIndex++)
310
+ childOwners.push({ kind: "continuation", ownerIndex: childIndex });
311
+ childIndex = groupedOwner.endIndex;
312
+ continue;
313
+ }
314
+ let ownerId, ownerWidth = -1;
315
+ if (child.kind !== "expression")
316
+ for (let block of blocks) {
317
+ if (block.id === rootOwnerId) continue;
318
+ let blockRange = readSourceRange(block.payload.range, sourceLength);
319
+ if (!blockRange || blockRange.from === flowRange.from && blockRange.to === flowRange.to || !(child.kind === "markdown" ? blockRange.from >= childRange.from && blockRange.to <= childRange.to : child.kind === "inline" || block.type === "mdx" ? blockRange.from === childRange.from && blockRange.to === childRange.to : blockRange.from === childRange.from && hasWholeFlowRootMatch(block, childRange, matches))) continue;
320
+ let width = blockRange.to - blockRange.from;
321
+ width > ownerWidth && (ownerId = block.id, ownerWidth = width);
322
+ }
323
+ if (ownerId !== void 0) {
324
+ childOwners.push({ kind: "block", blockId: ownerId });
325
+ continue;
326
+ }
327
+ if (child.kind !== "expression") {
328
+ let preparedOwner;
329
+ for (let tree of preparedTrees)
330
+ if (preparedOwner = findPreparedTreeBlock(
331
+ tree,
332
+ childRange,
333
+ sourceLength,
334
+ child.kind === "jsx",
335
+ child.kind === "jsx" ? matches : void 0
336
+ ), preparedOwner) break;
337
+ if (preparedOwner) {
338
+ if (child.kind === "inline") {
339
+ let preparedRange = readSourceRange(preparedOwner.payload.range, sourceLength);
340
+ if (preparedRange?.from !== childRange.from || preparedRange.to !== childRange.to)
341
+ throw new Error("A compiler-authored inline child has no exact prepared native owner.");
342
+ }
343
+ childOwners.push({ kind: "prepared-tree", blockId: preparedOwner.id });
344
+ continue;
345
+ }
346
+ }
347
+ if (child.kind === "markdown" || child.kind === "inline")
348
+ throw new Error("A compiler-authored Markdown child has no prepared native block owner.");
349
+ childOwners.push(null);
350
+ }
351
+ return { childOwners, ownedBlockIds };
352
+ }
353
+ function collectCompilerFlowBlockOwners(source, blocks, regions, matches) {
354
+ let ownerIds = new Set(matches.map((match) => match.id));
355
+ for (let region of regions) {
356
+ if (region.kind !== "render" || region.placement !== "flow" || !("rootElementName" in region)) continue;
357
+ let range = readSourceRange(region, source.length);
358
+ if (!range) continue;
359
+ let exactMatches = matches.filter((match) => match.from === range.from && match.to === range.to);
360
+ if (exactMatches.length > 0) {
361
+ for (let match of exactMatches) match.wholeBlockFlowRoot = !0;
362
+ continue;
363
+ }
364
+ let block = blocks.find((candidate) => {
365
+ let blockRange = readSourceRange(candidate.payload.range, source.length);
366
+ return blockRange !== null && blockRange.from === range.from && blockRange.to <= range.to;
367
+ });
368
+ !block || ownerIds.has(block.id) || (addMdxOwner(matches, block.id, `${block.type} compiler flow root`, range, source.length), matches[matches.length - 1].wholeBlockFlowRoot = !0, ownerIds.add(block.id));
369
+ }
370
+ }
371
+ function collectPreparedNestedOwners(prepared, sourceLength, matches) {
372
+ if (typeof prepared != "object" || prepared === null || Array.isArray(prepared) || !("children" in prepared) || !Array.isArray(prepared.children))
373
+ return;
374
+ let visited = /* @__PURE__ */ new WeakSet(), pending = [];
375
+ for (let index = 0; index < prepared.children.length; index++) {
376
+ let child = prepared.children[index];
377
+ pending.push(child);
378
+ }
379
+ for (; pending.length > 0; ) {
380
+ let value = pending.pop();
381
+ if (typeof value != "object" || value === null || Array.isArray(value) || visited.has(value))
382
+ continue;
383
+ visited.add(value);
384
+ let node = readSnapshotFields(value), nodeProps = node?.props && typeof node.props == "object" ? node.props : void 0;
385
+ if (nodeProps && "inline" in nodeProps && collectInlineOwners(nodeProps.inline, sourceLength, matches), node && isNestedMdxType(node.type) && addMdxOwner(matches, node.id, `${node.type} segment`, node.range, sourceLength), !(!node || !Array.isArray(node.children)))
386
+ for (let index = 0; index < node.children.length; index++) {
387
+ let child = node.children[index];
388
+ pending.push(child);
389
+ }
390
+ }
391
+ }
392
+ function collectHtmlTreeOwners(tree, sourceLength, matches) {
393
+ if (!Array.isArray(tree)) return;
394
+ let pending = [...tree], visited = /* @__PURE__ */ new WeakSet();
395
+ for (; pending.length > 0; ) {
396
+ let current = pending.pop();
397
+ if (!(typeof current != "object" || current === null || visited.has(current))) {
398
+ if (visited.add(current), Array.isArray(current)) {
399
+ pending.push(...current);
400
+ continue;
401
+ }
402
+ if ("kind" in current && current.kind === "block" && "block" in current) {
403
+ let candidate = current.block;
404
+ if (typeof candidate == "object" && candidate !== null && !Array.isArray(candidate) && "id" in candidate && typeof candidate.id == "string" && "type" in candidate && typeof candidate.type == "string" && "payload" in candidate && typeof candidate.payload == "object" && candidate.payload !== null) {
405
+ let block = candidate, meta = block.payload.meta;
406
+ if (block.type === "mdx" && addMdxOwner(
407
+ matches,
408
+ block.id,
409
+ "nested block",
410
+ block.payload.range,
411
+ sourceLength
412
+ ), collectInlineOwners(block.payload.inline, sourceLength, matches), meta) {
413
+ if (block.type === "paragraph" && Array.isArray(meta.mixedSegments))
414
+ for (let index = 0; index < meta.mixedSegments.length; index++) {
415
+ let segment = meta.mixedSegments[index];
416
+ typeof segment != "object" || segment === null || Array.isArray(segment) || !("kind" in segment) || segment.kind !== "mdx" || addMdxOwner(
417
+ matches,
418
+ `${block.id}::paragraph:segment:${index}`,
419
+ "paragraph segment",
420
+ "range" in segment ? segment.range : void 0,
421
+ sourceLength
422
+ );
423
+ }
424
+ collectInlineOwners(meta.header, sourceLength, matches), collectInlineOwners(meta.rows, sourceLength, matches), collectPreparedNestedOwners(meta.preparedNested, sourceLength, matches);
425
+ let preparedTree = getActiveTrustedMdxNativeTree(meta);
426
+ preparedTree !== void 0 && pending.push(preparedTree);
427
+ }
428
+ }
429
+ }
430
+ "children" in current && Array.isArray(current.children) && pending.push(...current.children);
431
+ }
432
+ }
433
+ }
434
+ function collectMdxOwners(source, blocks) {
435
+ let matches = [];
436
+ for (let block of blocks) {
437
+ if (block.type === "mdx" && addMdxOwner(
438
+ matches,
439
+ block.id,
440
+ "block",
441
+ block.payload.range,
442
+ source.length
443
+ ), block.type === "paragraph") {
444
+ let segments = block.payload.meta?.mixedSegments;
445
+ if (Array.isArray(segments))
446
+ for (let index = 0; index < segments.length; index++) {
447
+ let segment = segments[index];
448
+ typeof segment != "object" || segment === null || Array.isArray(segment) || !("kind" in segment) || segment.kind !== "mdx" || addMdxOwner(
449
+ matches,
450
+ `${block.id}::paragraph:segment:${index}`,
451
+ "paragraph segment",
452
+ "range" in segment ? segment.range : void 0,
453
+ source.length
454
+ );
455
+ }
456
+ }
457
+ collectInlineOwners(block.payload.inline, source.length, matches);
458
+ let tableMeta = block.payload.meta;
459
+ if (tableMeta) {
460
+ collectInlineOwners(tableMeta.header, source.length, matches), collectInlineOwners(tableMeta.rows, source.length, matches), collectPreparedNestedOwners(tableMeta.preparedNested, source.length, matches);
461
+ let preparedTree = getActiveTrustedMdxNativeTree(tableMeta);
462
+ preparedTree !== void 0 && collectHtmlTreeOwners(preparedTree, source.length, matches);
463
+ }
464
+ }
465
+ let unique = /* @__PURE__ */ new Map();
466
+ for (let match of matches) {
467
+ let existing = unique.get(match.id);
468
+ existing ? (existing.from !== match.from || existing.to !== match.to) && (existing.ambiguous = !0) : unique.set(match.id, match);
469
+ }
470
+ return Array.from(unique.values());
471
+ }
472
+ function describeOwner(match) {
473
+ return match.label === "block" ? `MDX block "${match.id}"` : `MDX ${match.label} "${match.id}"`;
474
+ }
475
+ function isExactNativeMdxAliasRegion(region, owners) {
476
+ if (owners.length !== 2) return !1;
477
+ let first = owners[0], second = owners[1];
478
+ return !first || !second || first.from === null || first.to === null || first.from !== second.from || first.to !== second.to || region.from !== first.from || region.to !== first.to ? !1 : (first.label === "block" || first.label === "nested block") && second.label === "inline expression" && second.id.startsWith(`${first.id}::native-mdx:`) || (second.label === "block" || second.label === "nested block") && first.label === "inline expression" && first.id.startsWith(`${second.id}::native-mdx:`);
479
+ }
480
+ function placementFields(match) {
481
+ return match.placement === null ? {} : { placement: match.placement };
482
+ }
483
+ function projectMdxBlocks(source, blocks, regions, regionComponents) {
484
+ let projections = /* @__PURE__ */ new Map(), flowOwnerBlocks = collectFlowOwnerBlocks(blocks), matches = collectMdxOwners(source, blocks);
485
+ collectCompilerFlowBlockOwners(source, flowOwnerBlocks, regions, matches);
486
+ let ownersByRegion = /* @__PURE__ */ new Map();
487
+ for (let region of regions) {
488
+ let regionRange = readSourceRange(region, source.length);
489
+ if (!regionRange) continue;
490
+ let owners = [];
491
+ for (let match of matches) {
492
+ if (match.from === null || match.to === null) continue;
493
+ let ownerFrom = match.from, ownerTo = match.to;
494
+ if (regionRange.to <= match.from || regionRange.from >= match.to) continue;
495
+ let compilerFlowRoot = region.kind === "render" && "rootElementName" in region, regionContainsOwner = regionRange.from <= match.from && regionRange.to >= match.to;
496
+ if (region.kind !== "module" && (regionRange.from < match.from || regionRange.to > match.to)) {
497
+ if (compilerFlowRoot && regionContainsOwner) continue;
498
+ match.ambiguous = !0;
499
+ continue;
500
+ }
501
+ if (!(match.wholeBlockFlowRoot && regionRange.from >= ownerFrom && regionRange.to <= ownerTo && (regionRange.from > ownerFrom || regionRange.to < ownerTo)) && (match.regions.push(region), region.kind !== "module")) {
502
+ if (owners.push(match), region.placement !== "flow" && region.placement !== "inline" || match.placement !== null && match.placement !== region.placement ? match.ambiguous = !0 : match.placement = region.placement, region.kind === "render" && region.placement === "flow" && "rootElementName" in region && regionRange.from === match.from && regionRange.to === match.to && region.kind === "render" && "rootElementName" in region) {
503
+ match.wholeBlockFlowRoot = !0;
504
+ let flowNativeBlocks = collectFlowNativeBlocks(
505
+ region.flowChildren,
506
+ regionRange,
507
+ blocks,
508
+ match.id,
509
+ source.length,
510
+ matches,
511
+ flowOwnerBlocks
512
+ );
513
+ match.nativeFlowOwnedBlockIds = flowNativeBlocks.ownedBlockIds, match.nativeChildOwners = flowNativeBlocks.childOwners, match.flowChildren = region.flowChildren;
514
+ }
515
+ match.nativeChildren = match.nativeChildOwners.some((owner) => owner !== null) && match.placement === "flow", "rootElementName" in region && (match.rootElementName !== void 0 && match.rootElementName !== region.rootElementName ? match.ambiguous = !0 : match.rootElementName = region.rootElementName);
516
+ }
517
+ }
518
+ owners.length > 1 && ownersByRegion.set(region, owners);
519
+ }
520
+ for (let [region, owners] of ownersByRegion)
521
+ if (!isExactNativeMdxAliasRegion(region, owners))
522
+ for (let owner of owners) owner.ambiguous = !0;
523
+ for (let match of matches) {
524
+ let description = describeOwner(match);
525
+ if (match.from === null || match.to === null) {
526
+ projections.set(match.id, {
527
+ kind: "unmapped",
528
+ diagnostic: `${description} has no valid authored source range.`
529
+ });
530
+ continue;
531
+ }
532
+ if (!match.ambiguous && match.regions.length > 0) {
533
+ let orderedRegions = match.regions.slice().sort((left, right) => left.from - right.from || left.to - right.to), coveredUntil = match.from;
534
+ for (let region of orderedRegions) {
535
+ let from = Math.max(match.from, region.from), to = Math.min(match.to, region.to);
536
+ if (from < coveredUntil || source.slice(coveredUntil, from).trim().length > 0) {
537
+ match.ambiguous = !0;
538
+ break;
539
+ }
540
+ coveredUntil = to;
541
+ }
542
+ !match.ambiguous && source.slice(coveredUntil, match.to).trim().length > 0 && (match.ambiguous = !0);
543
+ }
544
+ if (match.ambiguous || match.regions.length === 0) {
545
+ projections.set(match.id, {
546
+ kind: "unmapped",
547
+ diagnostic: match.ambiguous ? `${description} cannot be mapped exactly to unique authored regions.` : `${description} (${match.from}..${match.to}) has no corresponding authored MDX region.`,
548
+ ...placementFields(match)
549
+ });
550
+ continue;
551
+ }
552
+ let renderRegions = match.regions.filter((region) => region.kind === "render");
553
+ if (renderRegions.length > 0) {
554
+ let placement = match.placement;
555
+ if (placement === null) {
556
+ projections.set(match.id, {
557
+ kind: "unmapped",
558
+ diagnostic: `${description} has render regions without compiler placement provenance.`
559
+ });
560
+ continue;
561
+ }
562
+ if (match.nativeChildren && match.rootElementName === void 0) {
563
+ projections.set(match.id, {
564
+ kind: "unmapped",
565
+ diagnostic: `${description} has prepared native children but no compiler-authored flow JSX root.`,
566
+ placement
567
+ });
568
+ continue;
569
+ }
570
+ let components = [], missingKey = null;
571
+ for (let region of renderRegions) {
572
+ if (!Object.prototype.hasOwnProperty.call(regionComponents, region.key)) {
573
+ missingKey = region.key;
574
+ break;
575
+ }
576
+ let component = regionComponents[region.key];
577
+ if (typeof component != "function") {
578
+ missingKey = region.key;
579
+ break;
580
+ }
581
+ components.push(component);
582
+ }
583
+ projections.set(
584
+ match.id,
585
+ missingKey === null ? {
586
+ kind: "render",
587
+ regions: Object.freeze(components),
588
+ placement,
589
+ ...match.nativeChildren ? { nativeChildren: !0 } : {},
590
+ ...match.nativeChildOwners.length > 0 ? { nativeChildOwners: Object.freeze([...match.nativeChildOwners]) } : {},
591
+ ...match.flowChildren ? { flowChildren: match.flowChildren } : {},
592
+ ...match.nativeFlowOwnedBlockIds.length > 0 ? { nativeFlowOwnedBlockIds: Object.freeze([...match.nativeFlowOwnedBlockIds]) } : {},
593
+ ...match.wholeBlockFlowRoot ? { wholeBlockFlowRoot: !0 } : {},
594
+ ...match.rootElementName === void 0 ? {} : { rootElementName: match.rootElementName }
595
+ } : {
596
+ kind: "unmapped",
597
+ diagnostic: `No evaluated renderer exists for MDX region "${missingKey}".`,
598
+ placement
599
+ }
600
+ );
601
+ continue;
602
+ }
603
+ if (match.regions.some((region) => region.kind === "module")) {
604
+ projections.set(match.id, { kind: "module" });
605
+ continue;
606
+ }
607
+ projections.set(match.id, {
608
+ kind: "unmapped",
609
+ diagnostic: `${description} has no renderable or module region.`
610
+ });
611
+ }
612
+ let moduleRanges = [];
613
+ for (let region of regions) {
614
+ if (region.kind !== "module") continue;
615
+ let range = readSourceRange(region, source.length);
616
+ range && moduleRanges.push(range);
617
+ }
618
+ for (let block of blocks) {
619
+ let range = readSourceRange(block.payload.range, source.length);
620
+ range && moduleRanges.some((module) => module.from <= range.from && module.to >= range.to) && projections.set(block.id, { kind: "module" });
621
+ }
622
+ let nativeChildIds = /* @__PURE__ */ new Set();
623
+ for (let projection of projections.values())
624
+ if (projection.kind === "render")
625
+ for (let id of projection.nativeFlowOwnedBlockIds ?? []) nativeChildIds.add(id);
626
+ for (let id of nativeChildIds) {
627
+ let projection = projections.get(id);
628
+ projection ? projections.set(id, { ...projection, nativeFlowParent: !0 }) : projections.set(id, { kind: "native-child", nativeFlowParent: !0 });
629
+ }
630
+ return Object.freeze(Object.fromEntries(projections));
631
+ }
632
+
633
+ // src/trusted-mdx/document.ts
634
+ var EMPTY_PROJECTIONS = Object.freeze({});
635
+ function createTrustedMdxDocumentLease(context) {
636
+ let { options, getFactoryEpoch, getOrCompileArtifact, onDispose } = context, leaseEpoch = 0, isDisposed = !1, requestedRevision = 0, projectionRevision = null, renderedRevision = null, status = "idle", error = null, components = Object.freeze({
637
+ ...options.components
638
+ }), layout = null, projections = EMPTY_PROJECTIONS, candidateRevision = null, candidateProjections = null, candidateLayout = null, committedRevision = null, committedProjections = null, committedLayout = null, listeners = /* @__PURE__ */ new Set(), createSnapshot = () => Object.freeze({
639
+ requestedRevision,
640
+ projectionRevision,
641
+ renderedRevision,
642
+ status,
643
+ error,
644
+ components,
645
+ layout,
646
+ projections
647
+ }), currentSnapshot = createSnapshot(), publishIfChanged = () => {
648
+ let previous = currentSnapshot;
649
+ if (!(previous.requestedRevision === requestedRevision && previous.projectionRevision === projectionRevision && previous.renderedRevision === renderedRevision && previous.status === status && previous.error === error && previous.components === components && previous.layout === layout && previous.projections === projections)) {
650
+ currentSnapshot = createSnapshot();
651
+ for (let listener of listeners) listener();
652
+ }
653
+ }, getSnapshot = () => currentSnapshot, subscribe = (listener) => (isDisposed || listeners.add(listener), () => {
654
+ listeners.delete(listener);
655
+ }), ownsRevision = (targetRevision, startLeaseEpoch, startFactoryEpoch) => !isDisposed && leaseEpoch === startLeaseEpoch && getFactoryEpoch() === startFactoryEpoch && requestedRevision === targetRevision, failRevision = (targetRevision, startLeaseEpoch, startFactoryEpoch, cause) => {
656
+ ownsRevision(targetRevision, startLeaseEpoch, startFactoryEpoch) && (candidateRevision = null, candidateProjections = null, candidateLayout = null, projectionRevision = committedRevision, projections = committedProjections ?? EMPTY_PROJECTIONS, layout = committedLayout, status = "error", error = cause instanceof Error ? cause.message : String(cause), publishIfChanged());
657
+ };
658
+ return {
659
+ getSnapshot,
660
+ subscribe,
661
+ compileRevision: async (revision) => {
662
+ if (isDisposed) return;
663
+ let targetRevision = ++requestedRevision, startLeaseEpoch = leaseEpoch, startFactoryEpoch = getFactoryEpoch(), isCurrent = () => ownsRevision(targetRevision, startLeaseEpoch, startFactoryEpoch);
664
+ if (status = "compiling", error = null, publishIfChanged(), !isCurrent()) return;
665
+ let artifact;
666
+ try {
667
+ artifact = await getOrCompileArtifact(revision.source);
668
+ } catch (cause) {
669
+ failRevision(targetRevision, startLeaseEpoch, startFactoryEpoch, cause);
670
+ return;
671
+ }
672
+ if (!isCurrent()) return;
673
+ let evaluated;
674
+ try {
675
+ evaluated = await evaluateCompiledMdx(
676
+ artifact.code,
677
+ { imports: options.imports },
678
+ isCurrent
679
+ );
680
+ } catch (cause) {
681
+ failRevision(targetRevision, startLeaseEpoch, startFactoryEpoch, cause);
682
+ return;
683
+ }
684
+ if (!isCurrent() || evaluated === null) return;
685
+ let nextProjections, nextLayout;
686
+ try {
687
+ if (!isCurrent()) return;
688
+ let regionComponents = evaluated.createRegions({ components });
689
+ if (!isCurrent()) return;
690
+ nextProjections = projectMdxBlocks(revision.source, revision.blocks, artifact.regions, regionComponents), nextLayout = evaluated.layout ?? null;
691
+ } catch (cause) {
692
+ failRevision(targetRevision, startLeaseEpoch, startFactoryEpoch, cause);
693
+ return;
694
+ }
695
+ isCurrent() && (candidateRevision = targetRevision, candidateProjections = nextProjections, candidateLayout = nextLayout, projectionRevision = targetRevision, projections = nextProjections, layout = nextLayout, status = "ready", error = null, publishIfChanged());
696
+ },
697
+ confirmRenderedRevision: (revision) => {
698
+ isDisposed || candidateRevision !== revision || candidateProjections === null || renderedRevision === revision && committedRevision === revision || (renderedRevision = revision, committedRevision = revision, committedProjections = candidateProjections, committedLayout = candidateLayout, candidateRevision = null, candidateProjections = null, candidateLayout = null, publishIfChanged());
699
+ },
700
+ reportRenderError: (revision, cause) => {
701
+ isDisposed || candidateRevision !== revision || candidateProjections === null || (candidateRevision = null, candidateProjections = null, candidateLayout = null, projectionRevision = committedRevision, projections = committedProjections ?? EMPTY_PROJECTIONS, layout = committedLayout, status = "error", error = cause instanceof Error ? cause.message : String(cause), publishIfChanged());
702
+ },
703
+ clear: () => {
704
+ isDisposed || (leaseEpoch += 1, candidateRevision = null, candidateProjections = null, candidateLayout = null, committedRevision = null, committedProjections = null, committedLayout = null, projectionRevision = null, renderedRevision = null, status = "idle", error = null, projections = EMPTY_PROJECTIONS, layout = null, publishIfChanged());
705
+ },
706
+ dispose: () => {
707
+ isDisposed || (isDisposed = !0, leaseEpoch += 1, candidateRevision = null, candidateProjections = null, candidateLayout = null, committedRevision = null, committedProjections = null, committedLayout = null, projectionRevision = null, renderedRevision = null, status = "disposed", error = null, projections = EMPTY_PROJECTIONS, layout = null, listeners.clear(), currentSnapshot = createSnapshot(), onDispose());
708
+ }
709
+ };
710
+ }
711
+
712
+ // src/trusted-mdx/engine.ts
713
+ function createTrustedMdxEngine(options = {}) {
714
+ let frozenComponents = options.components ? Object.freeze({ ...options.components }) : void 0, frozenImports;
715
+ if (options.imports) {
716
+ let importNamespaces = [];
717
+ for (let [specifier, namespace] of Object.entries(options.imports))
718
+ importNamespaces.push([specifier, Object.freeze({ ...namespace })]);
719
+ frozenImports = Object.freeze(Object.fromEntries(importNamespaces));
720
+ }
721
+ let immutableOptions = Object.freeze({
722
+ components: frozenComponents,
723
+ imports: frozenImports,
724
+ compile: options.compile,
725
+ compilerIdentity: options.compilerIdentity ?? TRUSTED_MDX_COMPILER_REVISION
726
+ }), compileFn = immutableOptions.compile, factoryEpoch = 0, isDisposed = !1, lastArtifactSource = null, lastArtifact = null, inflightCompilations = /* @__PURE__ */ new Map(), activeLeases = /* @__PURE__ */ new Set(), generationListeners = /* @__PURE__ */ new Set(), getOrCompileArtifact = (source) => {
727
+ if (isDisposed)
728
+ return Promise.reject(new Error("Cannot compile MDX revision: TrustedMdxEngine has been disposed."));
729
+ if (lastArtifactSource === source && lastArtifact !== null)
730
+ return Promise.resolve(lastArtifact);
731
+ let existingCompilation = inflightCompilations.get(source);
732
+ if (existingCompilation) return existingCompilation;
733
+ let startFactoryEpoch = factoryEpoch, compilation;
734
+ return compilation = Promise.resolve().then(() => {
735
+ if (isDisposed || factoryEpoch !== startFactoryEpoch)
736
+ throw new Error("TrustedMDX compilation was invalidated before it started.");
737
+ return compileFn ? compileFn(source) : compileTrustedMdxDocument(source);
738
+ }).then((artifact) => (!isDisposed && factoryEpoch === startFactoryEpoch && (lastArtifactSource = source, lastArtifact = artifact), artifact)).finally(() => {
739
+ inflightCompilations.get(source) === compilation && inflightCompilations.delete(source);
740
+ }), inflightCompilations.set(source, compilation), compilation;
741
+ }, getFactoryEpoch = () => factoryEpoch, getGeneration = () => factoryEpoch, subscribe = (listener) => (isDisposed || generationListeners.add(listener), () => {
742
+ generationListeners.delete(listener);
743
+ }), notifyGenerationListeners = () => {
744
+ let notificationFailed = !1, notificationFailure;
745
+ for (let listener of generationListeners)
746
+ try {
747
+ listener();
748
+ } catch (cause) {
749
+ notificationFailed || (notificationFailed = !0, notificationFailure = cause);
750
+ }
751
+ if (notificationFailed) throw notificationFailure;
752
+ };
753
+ return {
754
+ createDocument: () => {
755
+ if (isDisposed)
756
+ throw new Error("Cannot create document: TrustedMdxEngine has been disposed.");
757
+ let document = null, createdDocument = createTrustedMdxDocumentLease({
758
+ options: immutableOptions,
759
+ getFactoryEpoch,
760
+ getOrCompileArtifact,
761
+ onDispose: () => {
762
+ document !== null && activeLeases.delete(document);
763
+ }
764
+ });
765
+ return document = createdDocument, activeLeases.add(createdDocument), createdDocument;
766
+ },
767
+ getGeneration,
768
+ subscribe,
769
+ clearCache: () => {
770
+ if (isDisposed) return;
771
+ factoryEpoch += 1, lastArtifactSource = null, lastArtifact = null, inflightCompilations.clear();
772
+ let notificationFailed = !1, notificationFailure;
773
+ try {
774
+ notifyGenerationListeners();
775
+ } catch (cause) {
776
+ notificationFailed = !0, notificationFailure = cause;
777
+ }
778
+ for (let document of activeLeases)
779
+ try {
780
+ document.clear();
781
+ } catch (cause) {
782
+ notificationFailed || (notificationFailed = !0, notificationFailure = cause);
783
+ }
784
+ if (notificationFailed) throw notificationFailure;
785
+ },
786
+ dispose: () => {
787
+ if (isDisposed) return;
788
+ isDisposed = !0, factoryEpoch += 1, lastArtifactSource = null, lastArtifact = null, inflightCompilations.clear();
789
+ let notificationFailed = !1, notificationFailure;
790
+ try {
791
+ notifyGenerationListeners();
792
+ } catch (cause) {
793
+ notificationFailed = !0, notificationFailure = cause;
794
+ }
795
+ for (let document of activeLeases)
796
+ try {
797
+ document.dispose();
798
+ } catch (cause) {
799
+ notificationFailed || (notificationFailed = !0, notificationFailure = cause);
800
+ }
801
+ if (activeLeases.clear(), generationListeners.clear(), notificationFailed) throw notificationFailure;
802
+ }
803
+ };
804
+ }
805
+ export {
806
+ createTrustedMdxEngine
807
+ };