tempo-sdk 0.0.99 → 0.0.102

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 (170) hide show
  1. package/README.md +3 -403
  2. package/dist/assets/editor.d.ts +43 -65
  3. package/dist/assets/editor.js +1 -573
  4. package/dist/assets/index.d.ts +11 -61
  5. package/dist/assets/index.js +1 -338
  6. package/dist/assets/parser.d.ts +68 -78
  7. package/dist/assets/parser.js +1 -33
  8. package/dist/astro/asset-preview-client.d.ts +3 -2
  9. package/dist/astro/asset-preview-client.js +1 -93
  10. package/dist/astro/controls.d.ts +1 -3
  11. package/dist/astro/controls.js +1 -7
  12. package/dist/astro/document-client.d.ts +5 -6
  13. package/dist/astro/document-client.js +1 -78
  14. package/dist/astro/runtime.d.ts +23 -11
  15. package/dist/astro/runtime.js +1 -86
  16. package/dist/astro.d.ts +19 -13
  17. package/dist/astro.js +1 -818
  18. package/dist/canvas/astro-contract.d.ts +0 -3
  19. package/dist/canvas/astro-contract.js +1 -9
  20. package/dist/canvas/astro.d.ts +3 -4
  21. package/dist/canvas/astro.js +1 -42
  22. package/dist/canvas/editor.d.ts +187 -183
  23. package/dist/canvas/editor.js +1 -1094
  24. package/dist/canvas/flutter-preview.d.ts +0 -1
  25. package/dist/canvas/flutter-preview.js +1 -9
  26. package/dist/canvas/index.d.ts +46 -100
  27. package/dist/canvas/index.js +1 -3926
  28. package/dist/canvas/interact-projection.d.ts +7 -5
  29. package/dist/canvas/interact-projection.js +1 -12
  30. package/dist/canvas/parser.d.ts +10 -303
  31. package/dist/canvas/parser.js +1 -30
  32. package/dist/canvas/svelte.d.ts +6 -7
  33. package/dist/canvas/svelte.js +1 -91
  34. package/dist/canvas/vue.d.ts +9 -49
  35. package/dist/canvas/vue.js +1 -264
  36. package/dist/chunk-CXCUJCXD.js +1 -0
  37. package/dist/chunk-FH6TMWFA.js +1 -0
  38. package/dist/chunk-FL7FSJSL.js +1 -0
  39. package/dist/chunk-GQIOB5SV.js +1 -0
  40. package/dist/chunk-HBQ7FFH7.js +1 -0
  41. package/dist/chunk-JRJOWLCN.js +1 -0
  42. package/dist/chunk-LJCBFTMP.js +1 -0
  43. package/dist/chunk-M3GN2KUH.js +1 -0
  44. package/dist/chunk-MPIHFFML.js +1 -0
  45. package/dist/chunk-T5TY3U2H.js +1 -0
  46. package/dist/chunk-XO2BSHWM.js +1 -0
  47. package/dist/chunk-XUSV3KOD.js +1 -0
  48. package/dist/chunk-ZXBMP6RV.js +1 -0
  49. package/dist/{controls-uCaQ3CNX.d.ts → controls-DKslABtM.d.ts} +0 -3
  50. package/dist/expo/plugin.cjs +1 -1928
  51. package/dist/expo/plugin.js +1 -8
  52. package/dist/expo-babel-plugin.cjs +1 -1928
  53. package/dist/expo-babel-plugin.d.cts +46 -40
  54. package/dist/expo-babel-plugin.d.ts +46 -40
  55. package/dist/expo-babel-plugin.js +1 -8
  56. package/dist/flutter-preview-path.d.ts +23 -7
  57. package/dist/flutter-preview-path.js +1 -16
  58. package/dist/index.d.ts +33 -45
  59. package/dist/index.js +1 -20
  60. package/dist/nextjs/plugin.cjs +1 -413
  61. package/dist/nextjs/plugin.js +1 -7
  62. package/dist/nextjs-loader.cjs +1 -2277
  63. package/dist/nextjs.cjs +1 -484
  64. package/dist/nextjs.d.cts +2 -58
  65. package/dist/nextjs.d.ts +2 -58
  66. package/dist/nextjs.js +1 -17
  67. package/dist/nuxt/runtime/identity.d.ts +2 -4
  68. package/dist/nuxt/runtime/identity.js +1 -18
  69. package/dist/nuxt.d.ts +31 -92
  70. package/dist/nuxt.js +1 -5854
  71. package/dist/{page-DwLnOM5d.d.ts → page-Bc8PekIX.d.ts} +1 -5
  72. package/dist/parser.d-MO5ciJ5n.d.ts +236 -0
  73. package/dist/{storyboard-CMJVBSXn.d.ts → storyboard.contract.d-UQ4MUYN5.d.ts} +3 -25
  74. package/dist/svelte.d.ts +8 -18
  75. package/dist/svelte.js +1 -917
  76. package/dist/types-CfUgM2w4.d.ts +57 -0
  77. package/dist/v1-client-compat-n0E0XxuX.d.ts +5 -0
  78. package/dist/vue.d.ts +17 -58
  79. package/dist/vue.js +1 -1501
  80. package/package.json +12 -62
  81. package/dist/assets/editor.js.map +0 -1
  82. package/dist/assets/index.js.map +0 -1
  83. package/dist/assets/parser.js.map +0 -1
  84. package/dist/astro/asset-preview-client.js.map +0 -1
  85. package/dist/astro/controls.js.map +0 -1
  86. package/dist/astro/document-client.js.map +0 -1
  87. package/dist/astro/runtime.js.map +0 -1
  88. package/dist/astro.js.map +0 -1
  89. package/dist/canvas/astro-contract.js.map +0 -1
  90. package/dist/canvas/astro.js.map +0 -1
  91. package/dist/canvas/editor.js.map +0 -1
  92. package/dist/canvas/flutter-preview.js.map +0 -1
  93. package/dist/canvas/index.js.map +0 -1
  94. package/dist/canvas/interact-projection.js.map +0 -1
  95. package/dist/canvas/parser.js.map +0 -1
  96. package/dist/canvas/svelte.js.map +0 -1
  97. package/dist/canvas/vue.js.map +0 -1
  98. package/dist/chunk-27WT3XUG.js +0 -455
  99. package/dist/chunk-27WT3XUG.js.map +0 -1
  100. package/dist/chunk-5HIIF354.js +0 -67
  101. package/dist/chunk-5HIIF354.js.map +0 -1
  102. package/dist/chunk-65B52AR7.js +0 -11
  103. package/dist/chunk-65B52AR7.js.map +0 -1
  104. package/dist/chunk-6HYKKP5N.js +0 -2658
  105. package/dist/chunk-6HYKKP5N.js.map +0 -1
  106. package/dist/chunk-6SOP4XU6.js +0 -1891
  107. package/dist/chunk-6SOP4XU6.js.map +0 -1
  108. package/dist/chunk-AFXE462X.js +0 -1253
  109. package/dist/chunk-AFXE462X.js.map +0 -1
  110. package/dist/chunk-BQPKOVI5.js +0 -115
  111. package/dist/chunk-BQPKOVI5.js.map +0 -1
  112. package/dist/chunk-CYDF4LYJ.js +0 -342
  113. package/dist/chunk-CYDF4LYJ.js.map +0 -1
  114. package/dist/chunk-CYQE3TLC.js +0 -37
  115. package/dist/chunk-CYQE3TLC.js.map +0 -1
  116. package/dist/chunk-DI2ZFAWL.js +0 -14
  117. package/dist/chunk-DI2ZFAWL.js.map +0 -1
  118. package/dist/chunk-EGRHWZRV.js +0 -1
  119. package/dist/chunk-EGRHWZRV.js.map +0 -1
  120. package/dist/chunk-FGWGY3G3.js +0 -157
  121. package/dist/chunk-FGWGY3G3.js.map +0 -1
  122. package/dist/chunk-HOBTDB6G.js +0 -112
  123. package/dist/chunk-HOBTDB6G.js.map +0 -1
  124. package/dist/chunk-I7VF4ZOV.js +0 -630
  125. package/dist/chunk-I7VF4ZOV.js.map +0 -1
  126. package/dist/chunk-JVVHU3A7.js +0 -1077
  127. package/dist/chunk-JVVHU3A7.js.map +0 -1
  128. package/dist/chunk-MIXQVPDH.js +0 -8606
  129. package/dist/chunk-MIXQVPDH.js.map +0 -1
  130. package/dist/chunk-MU7S7NU7.js +0 -183
  131. package/dist/chunk-MU7S7NU7.js.map +0 -1
  132. package/dist/chunk-OX2YKYSL.js +0 -13
  133. package/dist/chunk-OX2YKYSL.js.map +0 -1
  134. package/dist/chunk-PYAJHLXO.js +0 -903
  135. package/dist/chunk-PYAJHLXO.js.map +0 -1
  136. package/dist/chunk-SGN7BDRE.js +0 -16
  137. package/dist/chunk-SGN7BDRE.js.map +0 -1
  138. package/dist/chunk-SGTGDLOX.js +0 -285
  139. package/dist/chunk-SGTGDLOX.js.map +0 -1
  140. package/dist/chunk-T364NBR3.js +0 -1440
  141. package/dist/chunk-T364NBR3.js.map +0 -1
  142. package/dist/chunk-U66QI3EN.js +0 -1524
  143. package/dist/chunk-U66QI3EN.js.map +0 -1
  144. package/dist/chunk-WTXOWQ7N.js +0 -47
  145. package/dist/chunk-WTXOWQ7N.js.map +0 -1
  146. package/dist/chunk-X5DJKVBT.js +0 -1308
  147. package/dist/chunk-X5DJKVBT.js.map +0 -1
  148. package/dist/chunk-ZT7HJ6YU.js +0 -38
  149. package/dist/chunk-ZT7HJ6YU.js.map +0 -1
  150. package/dist/chunk-ZW26VZHX.js +0 -3169
  151. package/dist/chunk-ZW26VZHX.js.map +0 -1
  152. package/dist/controls-reader-5MFHYBZZ.js +0 -192
  153. package/dist/controls-reader-5MFHYBZZ.js.map +0 -1
  154. package/dist/expo/plugin.cjs.map +0 -1
  155. package/dist/expo/plugin.js.map +0 -1
  156. package/dist/expo-babel-plugin.cjs.map +0 -1
  157. package/dist/expo-babel-plugin.js.map +0 -1
  158. package/dist/flutter-preview-path.js.map +0 -1
  159. package/dist/index.js.map +0 -1
  160. package/dist/nextjs/plugin.cjs.map +0 -1
  161. package/dist/nextjs/plugin.js.map +0 -1
  162. package/dist/nextjs-loader.cjs.map +0 -1
  163. package/dist/nextjs.cjs.map +0 -1
  164. package/dist/nextjs.js.map +0 -1
  165. package/dist/nuxt/runtime/identity.js.map +0 -1
  166. package/dist/nuxt.js.map +0 -1
  167. package/dist/svelte.js.map +0 -1
  168. package/dist/types-C8OIU-kc.d.ts +0 -106
  169. package/dist/v1-client-compat-qxaXEDm_.d.ts +0 -23
  170. package/dist/vue.js.map +0 -1
@@ -1,3926 +1 @@
1
- import {
2
- installTempoInteractProjectionSource
3
- } from "../chunk-MIXQVPDH.js";
4
- import "../chunk-SGN7BDRE.js";
5
- import "../chunk-I7VF4ZOV.js";
6
- import {
7
- VITE_ERROR_FEED_KEY
8
- } from "../chunk-WTXOWQ7N.js";
9
- import {
10
- TEMPO_INTERACT_FRAME_NAME,
11
- isTempoInteractFrameName
12
- } from "../chunk-65B52AR7.js";
13
- import {
14
- FLUTTER_PREVIEW_KEY_ATTRIBUTE,
15
- parseFlutterPreview
16
- } from "../chunk-CYQE3TLC.js";
17
- import {
18
- AdmissionBudgetError,
19
- Canvas,
20
- CanvasContext,
21
- CanvasHostContext,
22
- CanvasPendingMarker,
23
- CanvasUnavailableMarker,
24
- HtmlStoryboard,
25
- LegacyStoryboardV1,
26
- RouteStoryboard,
27
- Storyboard,
28
- StoryboardSlot,
29
- emitRenderErrorRecoveryBeat,
30
- getCanvasStoryboardRenderId,
31
- getStoryboardKey,
32
- getStoryboardPortalSelectors,
33
- isV1CanvasClient,
34
- normalizeId,
35
- useActiveState,
36
- useRenderErrorRecovery,
37
- useRequiredCanvasHost,
38
- useStoryboardSize,
39
- v1DirectUrlSize,
40
- v1RenderRequestSize
41
- } from "../chunk-X5DJKVBT.js";
42
- import {
43
- PROJECTION_PENDING_ATTRIBUTE,
44
- PROJECTION_SCOPE_ROLE,
45
- isPreV3CanvasClient,
46
- isProjectionUnavailableOnly
47
- } from "../chunk-ZW26VZHX.js";
48
- import "../chunk-T364NBR3.js";
49
-
50
- // canvas/canvas-host.tsx
51
- import {
52
- useEffect as useEffect3,
53
- useCallback as useCallback3,
54
- useLayoutEffect as useLayoutEffect3,
55
- useRef as useRef3,
56
- useState as useState3,
57
- useMemo as useMemo3,
58
- useSyncExternalStore
59
- } from "react";
60
-
61
- // canvas/canvas-import-boundary.tsx
62
- import {
63
- Component,
64
- lazy,
65
- Suspense,
66
- useCallback,
67
- useEffect,
68
- useLayoutEffect,
69
- useMemo,
70
- useRef,
71
- useState
72
- } from "react";
73
-
74
- // canvas/host-recovery-feed.ts
75
- var FEED_KEY = "__tempoCanvasHostRecoveryFeed";
76
- function createFeed() {
77
- const listeners = /* @__PURE__ */ new Set();
78
- return {
79
- publish(event) {
80
- for (const listener of [...listeners]) listener(event);
81
- },
82
- subscribe(listener) {
83
- listeners.add(listener);
84
- return () => listeners.delete(listener);
85
- }
86
- };
87
- }
88
- function getCanvasHostRecoveryFeed() {
89
- const globals = globalThis;
90
- return globals[FEED_KEY] ?? (globals[FEED_KEY] = createFeed());
91
- }
92
-
93
- // canvas/canvas-import-boundary.tsx
94
- import { jsx, jsxs } from "react/jsx-runtime";
95
- var CanvasImportErrorBoundary = class extends Component {
96
- constructor() {
97
- super(...arguments);
98
- this.state = { hasError: false };
99
- }
100
- static getDerivedStateFromError() {
101
- return { hasError: true };
102
- }
103
- componentDidCatch(error, info) {
104
- this.props.reportError({
105
- message: error instanceof Error ? error.message : String(error),
106
- stack: error instanceof Error ? error.stack : void 0,
107
- componentStack: info.componentStack ?? void 0
108
- });
109
- }
110
- render() {
111
- return this.state.hasError ? null : this.props.children;
112
- }
113
- };
114
- function CanvasCommitSignal({ onCommit }) {
115
- const onCommitRef = useRef(onCommit);
116
- const didCommitRef = useRef(false);
117
- onCommitRef.current = onCommit;
118
- useLayoutEffect(() => {
119
- if (didCommitRef.current) return;
120
- didCommitRef.current = true;
121
- onCommitRef.current();
122
- }, []);
123
- return null;
124
- }
125
- function CanvasImportBoundary({
126
- canvasPath,
127
- load
128
- }) {
129
- const {
130
- clearCanvasImportError,
131
- registerCanvasProblemScope,
132
- reportCanvasImportError
133
- } = useRequiredCanvasHost();
134
- const failedRef = useRef(false);
135
- const importRejectedRef = useRef(false);
136
- const loadRef = useRef(load);
137
- const currentExportRef = useRef(null);
138
- const [replacement, setReplacement] = useState(null);
139
- const loadGenerationRef = useRef(0);
140
- const previousLoadRef = useRef(load);
141
- loadRef.current = load;
142
- const [retryRevision, setRetryRevision] = useState(0);
143
- const retryRenderNow = useCallback(() => {
144
- if (!failedRef.current || importRejectedRef.current) return false;
145
- currentExportRef.current = null;
146
- setReplacement(null);
147
- setRetryRevision((revision) => revision + 1);
148
- return true;
149
- }, []);
150
- const { noteRenderError, noteRecovered } = useRenderErrorRecovery(retryRenderNow);
151
- const lazyIdentity = `${canvasPath}:${retryRevision}`;
152
- const LazyCanvas = useMemo(() => {
153
- void lazyIdentity;
154
- return lazy(
155
- () => Promise.resolve().then(() => {
156
- importRejectedRef.current = false;
157
- return loadRef.current();
158
- }).then((module) => {
159
- const current = module;
160
- if (currentExportRef.current === null) {
161
- currentExportRef.current = module.default;
162
- }
163
- return {
164
- default: function LoadedCanvas({
165
- replacement: replacement2
166
- }) {
167
- const Component2 = replacement2 ?? current.default;
168
- return /* @__PURE__ */ jsx(Component2, {});
169
- }
170
- };
171
- }).catch((error) => {
172
- importRejectedRef.current = true;
173
- getCanvasHostRecoveryFeed().publish({
174
- type: "module-load-failure",
175
- path: canvasPath,
176
- message: error instanceof Error ? error.message : String(error)
177
- });
178
- throw error;
179
- })
180
- );
181
- }, [lazyIdentity, canvasPath]);
182
- const reportError = useCallback(
183
- (error) => {
184
- failedRef.current = true;
185
- if (importRejectedRef.current) noteRecovered();
186
- else noteRenderError();
187
- reportCanvasImportError(canvasPath, error);
188
- },
189
- [canvasPath, noteRecovered, noteRenderError, reportCanvasImportError]
190
- );
191
- const markCommitted = useCallback(() => {
192
- failedRef.current = false;
193
- noteRecovered();
194
- clearCanvasImportError(canvasPath);
195
- }, [canvasPath, clearCanvasImportError, noteRecovered]);
196
- useEffect(() => {
197
- const loadChanged = previousLoadRef.current !== load;
198
- previousLoadRef.current = load;
199
- const generation = ++loadGenerationRef.current;
200
- if (!loadChanged) return;
201
- if (failedRef.current) {
202
- currentExportRef.current = null;
203
- setReplacement(null);
204
- setRetryRevision((revision) => revision + 1);
205
- return;
206
- }
207
- Promise.resolve().then(load).then(
208
- (module) => {
209
- if (generation !== loadGenerationRef.current) return;
210
- const getFamily = globalThis[/* @__PURE__ */ Symbol.for("tempo.react-refresh.family")];
211
- if (typeof getFamily === "function") {
212
- const family = getFamily(currentExportRef.current);
213
- if (family && family === getFamily(module.default)) {
214
- const flush = globalThis[/* @__PURE__ */ Symbol.for("tempo.react-refresh.flush")];
215
- if (typeof flush === "function") flush();
216
- return;
217
- }
218
- }
219
- currentExportRef.current = module.default;
220
- setReplacement(() => module.default);
221
- },
222
- (error) => {
223
- if (generation !== loadGenerationRef.current) return;
224
- getCanvasHostRecoveryFeed().publish({
225
- type: "module-load-failure",
226
- path: canvasPath,
227
- message: error instanceof Error ? error.message : String(error)
228
- });
229
- }
230
- );
231
- return () => {
232
- ++loadGenerationRef.current;
233
- };
234
- }, [load, canvasPath]);
235
- useEffect(
236
- () => () => {
237
- clearCanvasImportError(canvasPath);
238
- },
239
- [canvasPath, clearCanvasImportError]
240
- );
241
- useEffect(
242
- () => registerCanvasProblemScope(canvasPath),
243
- [canvasPath, registerCanvasProblemScope]
244
- );
245
- const canvasElement = useMemo(
246
- () => /* @__PURE__ */ jsx(LazyCanvas, { replacement }),
247
- [LazyCanvas, replacement]
248
- );
249
- return /* @__PURE__ */ jsx(CanvasImportErrorBoundary, { reportError, children: /* @__PURE__ */ jsx(Suspense, { fallback: /* @__PURE__ */ jsx(CanvasPendingMarker, {}), children: /* @__PURE__ */ jsxs(CanvasContext, { path: canvasPath, children: [
250
- canvasElement,
251
- /* @__PURE__ */ jsx(CanvasCommitSignal, { onCommit: markCommitted })
252
- ] }) }) }, retryRevision);
253
- }
254
-
255
- // canvas/interact-projection-fallback.ts
256
- function installTempoInteractProjectionFallback(owner = "electron") {
257
- if (typeof window === "undefined" || window.parent === window || !isTempoInteractFrameName(window.name)) {
258
- return null;
259
- }
260
- if (window.__tempoInteractProjectionOwner) return null;
261
- window.__tempoInteractProjectionOwner = owner;
262
- const stopSource = installTempoInteractProjectionSource();
263
- return () => {
264
- stopSource();
265
- if (window.__tempoInteractProjectionOwner === owner) {
266
- delete window.__tempoInteractProjectionOwner;
267
- }
268
- };
269
- }
270
-
271
- // canvas/use-canvas-host-postmessage.ts
272
- import {
273
- useCallback as useCallback2,
274
- useEffect as useEffect2,
275
- useLayoutEffect as useLayoutEffect2,
276
- useMemo as useMemo2,
277
- useRef as useRef2,
278
- useState as useState2
279
- } from "react";
280
-
281
- // ../../modules/frame-pool/capture-discard.ts
282
- function formatCaptureDiscardToken(code) {
283
- return `[frame-pool-capture:${code}]`;
284
- }
285
-
286
- // canvas/canvas-host-runtime.ts
287
- function getCanvasHostRuntime() {
288
- const runtime = window.__tempoCanvasHostRuntime;
289
- if (!runtime) {
290
- throw new Error("window.__tempoCanvasHostRuntime is not installed.");
291
- }
292
- return runtime;
293
- }
294
- function getOptionalCanvasHostRuntime() {
295
- return typeof window === "undefined" ? void 0 : window.__tempoCanvasHostRuntime;
296
- }
297
-
298
- // canvas/canvas-host-operations.ts
299
- var escapeRenderId = (renderId) => renderId.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
300
- var buildRenderSelector = (renderId) => `[data-render-id="${escapeRenderId(renderId)}"]`;
301
- var buildRenderContentSelector = (renderId) => `[data-render-content="${escapeRenderId(renderId)}"]`;
302
- var buildRenderContentFiberSelector = (renderId) => [
303
- `${buildRenderContentSelector(renderId)} > :not([data-tempo-hide-fiber="true"])`,
304
- `${buildRenderContentSelector(renderId)}:not(:has(> *))`
305
- ].join(", ");
306
- function stripRenderContentWrapperAttributes(capture, renderId) {
307
- if (!capture || typeof capture !== "object") return capture;
308
- const dom = capture.dom;
309
- if (!dom) return capture;
310
- const shouldStripAttributes = dom.selector === "" && dom.attributes?.["data-render-content"] === renderId;
311
- const shouldStripRootAttributes = dom.rootAttributes?.["data-render-content"] === renderId;
312
- if (!shouldStripAttributes && !shouldStripRootAttributes) return capture;
313
- return {
314
- ...capture,
315
- dom: {
316
- ...dom,
317
- attributes: shouldStripAttributes ? void 0 : dom.attributes,
318
- rootAttributes: shouldStripRootAttributes ? void 0 : dom.rootAttributes
319
- }
320
- };
321
- }
322
- function stripRenderContentWrapperFromCombinedCapture(capture, renderId) {
323
- if (!capture || typeof capture !== "object" || !("html" in capture)) {
324
- return capture;
325
- }
326
- const html = capture.html;
327
- if (!html) return capture;
328
- return {
329
- ...capture,
330
- html: stripRenderContentWrapperAttributes(html, renderId)
331
- };
332
- }
333
- var nextAnimationFrame = () => new Promise((resolve) => {
334
- requestAnimationFrame(() => resolve());
335
- });
336
- var CAPTURE_CANVAS_ATTRIBUTE = "data-tempo-capture-canvas";
337
- var contentUnavailable = (renderId, why) => new Error(
338
- `${formatCaptureDiscardToken("content_unavailable")} storyboard ${renderId} ${why}`
339
- );
340
- async function captureStoryboardImage(renderId, options) {
341
- if (options?.fromCanvas) return captureStoryboardCanvas(renderId, options);
342
- const portalSelectors = [
343
- ...options?.portalSelectors ?? [],
344
- ...getStoryboardPortalSelectors(renderId)
345
- ];
346
- const renderSelector = buildRenderSelector(renderId);
347
- const { childSelector, ...captureOptions } = options ?? {};
348
- const captureSelector = childSelector ? `${renderSelector} ${childSelector}` : renderSelector;
349
- await nextAnimationFrame();
350
- await nextAnimationFrame();
351
- const content = document.querySelector(buildRenderContentSelector(renderId));
352
- if (content && isProjectionUnavailableOnly(content)) {
353
- throw contentUnavailable(renderId, "has no content to photograph yet");
354
- }
355
- return await getCanvasHostRuntime().captureSelector(
356
- captureSelector,
357
- portalSelectors.length > 0 ? { ...captureOptions, portalSelectors: [...new Set(portalSelectors)] } : captureOptions
358
- );
359
- }
360
- async function captureStoryboardCanvas(renderId, options) {
361
- const contentSelector = buildRenderContentSelector(renderId);
362
- const content = document.querySelector(contentSelector);
363
- const canvasSelector = `${contentSelector} canvas[${CAPTURE_CANVAS_ATTRIBUTE}]`;
364
- const painted = content !== null && content.querySelector(`canvas[${CAPTURE_CANVAS_ATTRIBUTE}]`) !== null && content.querySelector(`[${PROJECTION_PENDING_ATTRIBUTE}]`) === null && !isProjectionUnavailableOnly(content);
365
- if (!painted) throw contentUnavailable(renderId, "has no painted canvas yet");
366
- const runtime = getCanvasHostRuntime();
367
- if (!runtime.captureCanvas) {
368
- throw new Error(
369
- "This Tempo app cannot read a storyboard's canvas; update Tempo to capture this board."
370
- );
371
- }
372
- return await runtime.captureCanvas(canvasSelector, {
373
- format: options.format,
374
- quality: options.quality,
375
- outputPath: options.outputPath
376
- });
377
- }
378
- async function captureStoryboardHtml(renderId, options) {
379
- const capture = await getCanvasHostRuntime().captureHtml?.({
380
- selector: buildRenderContentSelector(renderId),
381
- timeout: options?.timeout
382
- });
383
- return capture ? stripRenderContentWrapperAttributes(capture, renderId) : null;
384
- }
385
- function captureStoryboardStaticHtml(renderId, options) {
386
- return getCanvasHostRuntime().captureStaticHtml?.({
387
- selector: buildRenderContentSelector(renderId),
388
- timeout: options?.timeout
389
- }) ?? Promise.resolve(null);
390
- }
391
- async function captureStoryboardCombined(renderId, options) {
392
- const capture = await getCanvasHostRuntime().captureCombined?.({
393
- selector: buildRenderContentSelector(renderId),
394
- fiberSelector: options?.fiberSelector ?? buildRenderContentFiberSelector(renderId),
395
- fiberTags: options?.fiberTags,
396
- timeout: options?.timeout
397
- });
398
- return capture ? stripRenderContentWrapperFromCombinedCapture(capture, renderId) : null;
399
- }
400
- function watchStoryboardHtml(renderId, options) {
401
- const runtime = getCanvasHostRuntime();
402
- if (!runtime.watchHtml) {
403
- return Promise.reject(new Error("watchHtml is not available."));
404
- }
405
- return runtime.watchHtml({
406
- selector: buildRenderContentSelector(renderId),
407
- onUpdate(capture) {
408
- options.onUpdate(stripRenderContentWrapperAttributes(capture, renderId));
409
- },
410
- onError: options.onError,
411
- debounceDelay: options.debounceDelay,
412
- maxWait: options.maxWait,
413
- timeout: options.timeout
414
- });
415
- }
416
- function watchStoryboardCombined(renderId, options) {
417
- const runtime = getCanvasHostRuntime();
418
- if (!runtime.watchCombined) {
419
- return Promise.reject(new Error("watchCombined is not available."));
420
- }
421
- return runtime.watchCombined({
422
- selector: buildRenderContentSelector(renderId),
423
- fiberSelector: options.fiberSelector ?? buildRenderContentFiberSelector(renderId),
424
- fiberTags: options.fiberTags,
425
- onUpdate(capture) {
426
- options.onUpdate(
427
- stripRenderContentWrapperFromCombinedCapture(capture, renderId)
428
- );
429
- },
430
- onError: options.onError,
431
- debounceDelay: options.debounceDelay,
432
- maxWait: options.maxWait,
433
- timeout: options.timeout,
434
- knownSourceVersion: options.knownSourceVersion
435
- });
436
- }
437
-
438
- // canvas/canvas-host-legacy-compat.ts
439
- var sourceAnnotationSelector = "[data-tempo-source-file], [data-tempo-source-loc], [data-tempo-filepath], [data-tempo-html-filepath]";
440
- function getObservedSourceFiles(slot) {
441
- if (!slot) return [];
442
- return [
443
- ...new Set(
444
- [...slot.querySelectorAll(sourceAnnotationSelector)].flatMap((element) => [
445
- element.getAttribute("data-tempo-source-file"),
446
- element.getAttribute("data-tempo-filepath"),
447
- element.getAttribute("data-tempo-html-filepath"),
448
- element.getAttribute("data-tempo-source-loc")
449
- ]).filter((file) => Boolean(file))
450
- )
451
- ];
452
- }
453
- function latestTimestamp(values) {
454
- let latest = null;
455
- for (const value of values.values()) {
456
- latest = latest === null ? value : Math.max(latest, value);
457
- }
458
- return latest;
459
- }
460
- function isReactConnected() {
461
- const hook = window.__REACT_DEVTOOLS_GLOBAL_HOOK__;
462
- return (hook?.renderers?.size ?? 0) > 0;
463
- }
464
- function createLegacyHostHealth() {
465
- const renderCommitTimes = /* @__PURE__ */ new Map();
466
- const sourceAnnotatedCommitTimes = /* @__PURE__ */ new Map();
467
- const recordSourceAnnotatedCommit = (renderId, observedAt = Date.now()) => {
468
- const slot = document.querySelector(buildRenderContentSelector(renderId));
469
- if (getObservedSourceFiles(slot).length > 0) {
470
- sourceAnnotatedCommitTimes.set(renderId, observedAt);
471
- }
472
- };
473
- return {
474
- recordRenderCommit(renderId) {
475
- const committedAt = Date.now();
476
- renderCommitTimes.set(renderId, committedAt);
477
- recordSourceAnnotatedCommit(renderId, committedAt);
478
- },
479
- recordSourceAnnotatedCommit(renderId) {
480
- recordSourceAnnotatedCommit(renderId);
481
- },
482
- forgetRender(renderId) {
483
- renderCommitTimes.delete(renderId);
484
- sourceAnnotatedCommitTimes.delete(renderId);
485
- },
486
- buildSnapshot(renderId, context) {
487
- const slot = renderId ? document.querySelector(buildRenderContentSelector(renderId)) : null;
488
- const observedSourceFiles = getObservedSourceFiles(slot);
489
- return {
490
- alive: true,
491
- reactConnected: isReactConnected() || renderCommitTimes.size > 0 || context.hasRenderEntries,
492
- documentReadyState: document.readyState,
493
- hasViteOverlayElement: document.querySelector("vite-error-overlay") !== null,
494
- lastHostRenderCommitAt: latestTimestamp(renderCommitTimes),
495
- lastClaimRenderCommitAt: renderCommitTimes.get(renderId) ?? null,
496
- lastHostSourceAnnotatedCommitAt: latestTimestamp(
497
- sourceAnnotatedCommitTimes
498
- ),
499
- lastClaimSourceAnnotatedCommitAt: sourceAnnotatedCommitTimes.get(renderId) ?? null,
500
- renderSlotExists: slot !== null,
501
- renderSlotHasSourceAnnotatedContent: observedSourceFiles.length > 0,
502
- renderSlotObservedSourceFiles: observedSourceFiles,
503
- claimErrorBoundaryTripped: context.claimErrorBoundaryTripped,
504
- observedAt: Date.now()
505
- };
506
- }
507
- };
508
- }
509
- function applyLegacyRenderIsolation(renderId) {
510
- document.querySelector("[data-render-isolation]")?.remove();
511
- if (!renderId) return;
512
- const style = document.createElement("style");
513
- style.setAttribute("data-render-isolation", "");
514
- const escapedId = typeof CSS !== "undefined" && typeof CSS.escape === "function" ? CSS.escape(renderId) : renderId;
515
- style.textContent = '[data-render-id]:not([data-render-id="' + escapedId + '"]) { opacity: 0 !important; pointer-events: none !important; }';
516
- document.head.appendChild(style);
517
- }
518
-
519
- // canvas/canvas-host-protocol.ts
520
- function isRecord(value) {
521
- return typeof value === "object" && value !== null && !Array.isArray(value);
522
- }
523
- function readCanvasHostCommand(message) {
524
- if (!isRecord(message) || typeof message.type !== "string") return null;
525
- return {
526
- type: message.type,
527
- requestId: message.requestId,
528
- payload: isRecord(message.payload) ? message.payload : {}
529
- };
530
- }
531
- var readTrimmedString = (value) => {
532
- if (typeof value !== "string") return void 0;
533
- const normalized = value.trim();
534
- return normalized.length > 0 ? normalized : void 0;
535
- };
536
- var readStringArray = (value) => {
537
- if (!Array.isArray(value)) return void 0;
538
- const values = value.map(readTrimmedString).filter((entry) => entry !== void 0);
539
- return values.length > 0 ? [...new Set(values)] : void 0;
540
- };
541
- function resolveRenderTarget(payload) {
542
- const explicitRenderId = readTrimmedString(payload.renderId);
543
- const canvasPath = readTrimmedString(payload.canvasPath);
544
- const storyboardId = readTrimmedString(payload.storyboardId);
545
- const sourcePaths = readStringArray(payload.sourcePaths);
546
- const renderId = explicitRenderId || (canvasPath && storyboardId ? getCanvasStoryboardRenderId(canvasPath, storyboardId) : storyboardId);
547
- return renderId ? {
548
- renderId,
549
- ...canvasPath ? { canvasPath } : {},
550
- ...storyboardId ? { storyboardId } : {},
551
- ...sourcePaths ? { sourcePaths } : {}
552
- } : null;
553
- }
554
- function requireRenderTarget(commandType, payload) {
555
- const target = resolveRenderTarget(payload);
556
- if (!target) {
557
- throw new Error(
558
- `${commandType} requires payload.renderId or payload.canvasPath + payload.storyboardId`
559
- );
560
- }
561
- return target;
562
- }
563
- var readPositiveFiniteNumber = (value, fieldName) => {
564
- if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) {
565
- throw new Error(`${fieldName} must be a positive finite number`);
566
- }
567
- return value;
568
- };
569
- function readOptionalNumber(payload, fieldName) {
570
- return typeof payload[fieldName] === "number" ? payload[fieldName] : void 0;
571
- }
572
- function readOptionalSize(payload) {
573
- const hasWidth = payload.width != null;
574
- const hasHeight = payload.height != null;
575
- if (!hasWidth && !hasHeight) return {};
576
- if (!hasWidth || !hasHeight) {
577
- throw new Error("width and height must be provided together");
578
- }
579
- return {
580
- width: readPositiveFiniteNumber(payload.width, "width"),
581
- height: readPositiveFiniteNumber(payload.height, "height")
582
- };
583
- }
584
- function readRenderRequest(commandType, payload) {
585
- const target = requireRenderTarget(commandType, payload);
586
- const importPath = readTrimmedString(payload.importPath);
587
- const importName = readTrimmedString(payload.importName);
588
- const props = isRecord(payload.props) ? payload.props : void 0;
589
- return {
590
- ...target,
591
- importPath: importPath ?? target.canvasPath ?? target.renderId,
592
- importName: importName ?? target.storyboardId ?? target.renderId,
593
- ...props ? { props } : {},
594
- ...payload.userInitiated === true ? { userInitiated: true } : {},
595
- ...readOptionalSize(payload),
596
- ...isV1CanvasClient() ? v1RenderRequestSize(payload) : {}
597
- };
598
- }
599
- function readWatchId(commandType, payload) {
600
- const watchId = readTrimmedString(payload.watchId);
601
- if (!watchId) {
602
- throw new Error(`${commandType} requires payload.watchId`);
603
- }
604
- return watchId;
605
- }
606
- function readPinId(commandType, payload) {
607
- const pinId = readTrimmedString(payload.pinId);
608
- if (!pinId) throw new Error(`${commandType} requires payload.pinId`);
609
- return pinId;
610
- }
611
-
612
- // canvas/canvas-host-render-state.ts
613
- var propsMatch = (a, b) => JSON.stringify(a ?? {}) === JSON.stringify(b ?? {});
614
- function renderRequestMatchesEntry(entry, request) {
615
- return entry?.sourceOnly !== true && entry?.importPath === request.importPath && entry.importName === request.importName && entry.width === request.width && entry.height === request.height && (!isV1CanvasClient() || entry.intrinsicSize === request.intrinsicSize) && propsMatch(entry.props, request.props);
616
- }
617
- function renderRequestTargetsEntry(entry, request) {
618
- return entry?.importPath === request.importPath && entry.importName === request.importName && propsMatch(entry.props, request.props);
619
- }
620
- function acquireRender(entries, request) {
621
- const next = new Map(entries);
622
- const current = next.get(request.renderId);
623
- const changed = !renderRequestMatchesEntry(current, request);
624
- next.set(request.renderId, {
625
- ...request,
626
- lastUsedAt: request.userInitiated ? Date.now() : current?.lastUsedAt,
627
- status: "active",
628
- activeCount: (current?.activeCount ?? 0) + 1,
629
- revision: changed ? (current?.revision ?? 0) + 1 : current?.revision ?? 1
630
- });
631
- return next;
632
- }
633
- function pinRenderSource(entries, request) {
634
- const next = new Map(entries);
635
- const current = next.get(request.renderId);
636
- if (current) {
637
- next.set(request.renderId, {
638
- ...current,
639
- status: "active",
640
- activeCount: current.activeCount + 1
641
- });
642
- } else {
643
- const {
644
- width: _width,
645
- height: _height,
646
- intrinsicSize: _intrinsicSize,
647
- userInitiated: _userInitiated,
648
- ...source
649
- } = request;
650
- next.set(request.renderId, {
651
- ...source,
652
- sourceOnly: true,
653
- status: "active",
654
- activeCount: 1,
655
- revision: 1
656
- });
657
- }
658
- return next;
659
- }
660
- function releaseRender(entries, renderId, maxCached, now = Date.now(), cacheWhenIdle) {
661
- const previous = entries.get(renderId);
662
- if (!previous) return entries;
663
- const current = cacheWhenIdle === true ? { ...previous, lastUsedAt: now } : previous;
664
- const next = new Map(entries);
665
- const activeCount = Math.max(0, current.activeCount - 1);
666
- if (activeCount > 0) {
667
- next.set(renderId, { ...current, activeCount, status: "active" });
668
- return next;
669
- }
670
- if (cacheWhenIdle === false && current.lastUsedAt === void 0) {
671
- next.delete(renderId);
672
- return next;
673
- }
674
- next.set(renderId, {
675
- ...current,
676
- activeCount: 0,
677
- status: "cached",
678
- lastInactiveAt: now
679
- });
680
- return evictCachedRenders(next, maxCached);
681
- }
682
- function evictCachedRenders(entries, maxCached) {
683
- const cached = [...entries.values()].filter((entry) => entry.status === "cached").sort(
684
- (a, b) => (a.lastUsedAt ?? 0) - (b.lastUsedAt ?? 0) || (a.lastInactiveAt ?? 0) - (b.lastInactiveAt ?? 0)
685
- );
686
- const evicted = cached.slice(0, Math.max(0, cached.length - maxCached));
687
- if (evicted.length === 0) return entries;
688
- const next = new Map(entries);
689
- for (const entry of evicted) next.delete(entry.renderId);
690
- return next;
691
- }
692
- function buildRenderStatePayload(entries, maxCached, canvasPaths = []) {
693
- return {
694
- canvasPaths: [...canvasPaths],
695
- renders: [...entries.values()].map(
696
- ({
697
- activeCount: _activeCount,
698
- lastInactiveAt: _lastInactiveAt,
699
- lastUsedAt: _lastUsedAt,
700
- userInitiated: _userInitiated,
701
- revision: _revision,
702
- sourceOnly: _sourceOnly,
703
- ...entry
704
- }) => entry
705
- ),
706
- maxCached
707
- };
708
- }
709
- function sameMap(previous, next, same) {
710
- if (!previous || previous.size !== next.size) return false;
711
- for (const [id, value] of next) {
712
- const before = previous.get(id);
713
- if (before === void 0 || !same(before, value)) return false;
714
- }
715
- return true;
716
- }
717
- function buildRenderStatusMap(entries, previous) {
718
- const next = new Map([...entries].map(([id, entry]) => [id, entry.status]));
719
- return previous && sameMap(previous, next, (a, b) => a === b) ? previous : next;
720
- }
721
- function buildRenderSizeMap(entries, previous) {
722
- const v1Client = isV1CanvasClient();
723
- const next = new Map(
724
- [...entries].filter(([, entry]) => !entry.sourceOnly).map(([id, entry]) => [
725
- id,
726
- {
727
- width: entry.width,
728
- height: entry.height,
729
- revision: entry.revision,
730
- ...v1Client ? { intrinsicSize: entry.intrinsicSize } : {}
731
- }
732
- ])
733
- );
734
- const sameSize = (a, b) => a.width === b.width && a.height === b.height && a.revision === b.revision && (!v1Client || a.intrinsicSize === b.intrinsicSize);
735
- return previous && sameMap(previous, next, sameSize) ? previous : next;
736
- }
737
-
738
- // canvas/fresh-mounts.ts
739
- var FRESH_MOUNTS_GLOBAL = "__tempoCanvasFreshMounts";
740
- function freshMounts() {
741
- const scope = globalThis;
742
- return scope[FRESH_MOUNTS_GLOBAL] ?? (scope[FRESH_MOUNTS_GLOBAL] = /* @__PURE__ */ new Set());
743
- }
744
- function noteFreshMount(renderId) {
745
- freshMounts().add(renderId);
746
- }
747
- function forgetFreshMount(renderId) {
748
- freshMounts().delete(renderId);
749
- }
750
-
751
- // canvas/source-identity.ts
752
- function normalizeSourceIdentity(value) {
753
- let normalized = value.trim().replace(/\\/g, "/");
754
- const suffixIndex = normalized.search(/[?#]/);
755
- if (suffixIndex !== -1) normalized = normalized.slice(0, suffixIndex);
756
- try {
757
- normalized = decodeURIComponent(normalized);
758
- } catch {
759
- }
760
- normalized = normalized.replace(/^file:\/\//, "").replace(/^\/@fs\//, "/");
761
- return normalized.replace(/^\.\//, "").replace(/\/{2,}/g, "/");
762
- }
763
- function distinctSourceIdentities(paths) {
764
- return [
765
- ...new Set(
766
- paths.map(normalizeSourceIdentity).filter((path) => path.length)
767
- )
768
- ];
769
- }
770
- function normalizeDiagnosticText(value) {
771
- const normalized = value.replace(/\\/g, "/");
772
- try {
773
- return decodeURIComponent(normalized).replace(/\bhttps?:\/\/[^/\s)]+/g, "").replace(/\/@fs\//g, "/");
774
- } catch {
775
- return normalized.replace(/\bhttps?:\/\/[^/\s)]+/g, "").replace(/\/@fs\//g, "/");
776
- }
777
- }
778
- function isPathCharacter(value) {
779
- return /[A-Za-z0-9._@+-]/.test(value);
780
- }
781
- function textMentionsPathSuffix(text, suffix) {
782
- let fromIndex = 0;
783
- while (fromIndex < text.length) {
784
- const index = text.indexOf(suffix, fromIndex);
785
- if (index < 0) return false;
786
- const before = index === 0 ? "" : text[index - 1];
787
- const after = text[index + suffix.length] ?? "";
788
- if ((before === "" || before === "/" || !isPathCharacter(before)) && (after === "" || !isPathCharacter(after))) {
789
- return true;
790
- }
791
- fromIndex = index + 1;
792
- }
793
- return false;
794
- }
795
- function textMentionsExactPath(text, path) {
796
- let fromIndex = 0;
797
- while (fromIndex < text.length) {
798
- const index = text.indexOf(path, fromIndex);
799
- if (index < 0) return false;
800
- const before = index === 0 ? "" : text[index - 1];
801
- const after = text[index + path.length] ?? "";
802
- if ((before === "" || before !== "/" && !isPathCharacter(before)) && (after === "" || after !== "/" && !isPathCharacter(after))) {
803
- return true;
804
- }
805
- fromIndex = index + 1;
806
- }
807
- return false;
808
- }
809
- function projectRootSpellings(projectRoot) {
810
- const spellings = [projectRoot];
811
- if (/^\/(?:var|tmp)\//.test(projectRoot)) {
812
- spellings.push(`/private${projectRoot}`);
813
- } else if (/^\/private\/(?:var|tmp)\//.test(projectRoot)) {
814
- spellings.push(projectRoot.slice("/private".length));
815
- }
816
- return spellings;
817
- }
818
- function rootedDiagnosticAliases(identityValue, projectRootValue) {
819
- const identity = normalizeSourceIdentity(identityValue);
820
- const projectRoot = normalizeSourceIdentity(projectRootValue).replace(
821
- /\/+$/,
822
- ""
823
- );
824
- if (!identity || !projectRoot) return [];
825
- const roots = projectRootSpellings(projectRoot);
826
- const rootPrefix = roots.find((root) => identity.startsWith(`${root}/`));
827
- const relative = rootPrefix ? identity.slice(rootPrefix.length + 1) : identity.startsWith("/") ? identity.slice(1) : identity;
828
- return [
829
- .../* @__PURE__ */ new Set([
830
- relative,
831
- `/${relative}`,
832
- ...roots.map((root) => `${root}/${relative}`)
833
- ])
834
- ];
835
- }
836
- function matchingDiagnosticSegments(text, identity) {
837
- const segments = identity.split("/").filter(Boolean);
838
- for (let count = segments.length; count >= 2; count -= 1) {
839
- if (textMentionsPathSuffix(text, segments.slice(-count).join("/"))) {
840
- return count;
841
- }
842
- }
843
- return 0;
844
- }
845
- function resolveUniqueDiagnosticSourceMatches(textValue, candidates, options = {}) {
846
- const text = normalizeDiagnosticText(textValue);
847
- if (!text) return [];
848
- const projectRoot = options.projectRoot?.trim();
849
- if (projectRoot) {
850
- const exactMatches = candidates.filter((candidate) => {
851
- const aliases = rootedDiagnosticAliases(candidate, projectRoot);
852
- if (aliases.some((alias) => textMentionsExactPath(text, alias))) {
853
- return true;
854
- }
855
- if (!options.allowExtensionlessJsTs || /\.(?:[cm]?[jt]sx?)$/i.test(normalizeSourceIdentity(candidate))) {
856
- return false;
857
- }
858
- return aliases.some(
859
- (alias) => [".js", ".jsx", ".ts", ".tsx", ".mjs", ".mts", ".cjs", ".cts"].some(
860
- (extension) => textMentionsExactPath(text, `${alias}${extension}`)
861
- )
862
- );
863
- });
864
- return distinctSourceIdentities(exactMatches).length === 1 ? exactMatches : [];
865
- }
866
- const evaluated = candidates.map((candidate) => {
867
- const identity = normalizeSourceIdentity(candidate);
868
- return {
869
- candidate,
870
- identity,
871
- identitySegments: identity.split("/").filter(Boolean).length,
872
- matchSegments: matchingDiagnosticSegments(text, identity)
873
- };
874
- });
875
- const pathMatches = evaluated.filter(
876
- ({ matchSegments }) => matchSegments > 0
877
- );
878
- if (pathMatches.length > 0) {
879
- const strongest = Math.max(
880
- ...pathMatches.map(({ matchSegments }) => matchSegments)
881
- );
882
- const strongestMatches = pathMatches.filter(
883
- ({ matchSegments }) => matchSegments === strongest
884
- );
885
- const fullMatches = strongestMatches.filter(
886
- ({ identitySegments, matchSegments }) => identitySegments === matchSegments
887
- );
888
- const unambiguousMatches = fullMatches.length > 0 ? fullMatches : strongestMatches;
889
- if (distinctSourceIdentities(
890
- unambiguousMatches.map(({ identity }) => identity)
891
- ).length === 1) {
892
- return unambiguousMatches.map(({ candidate }) => candidate);
893
- }
894
- return [];
895
- }
896
- const basenameMatches = evaluated.filter(({ identity }) => {
897
- const basename = identity.split("/").pop() ?? "";
898
- return basename.length > 0 && textMentionsPathSuffix(text, basename);
899
- });
900
- return distinctSourceIdentities(
901
- basenameMatches.map(({ identity }) => identity)
902
- ).length === 1 ? basenameMatches.map(({ candidate }) => candidate) : [];
903
- }
904
-
905
- // canvas/runtime-problems.ts
906
- var CanvasHostProblemTracker = class {
907
- constructor() {
908
- this.hostProblemWasNearRender = false;
909
- this.componentProblems = /* @__PURE__ */ new Map();
910
- this.canvasProblems = /* @__PURE__ */ new Map();
911
- this.registeredCanvasPaths = /* @__PURE__ */ new Map();
912
- this.registeredRenderSourcePaths = /* @__PURE__ */ new Map();
913
- this.watchers = /* @__PURE__ */ new Set();
914
- this.hostProblemClearedWatchers = /* @__PURE__ */ new Set();
915
- }
916
- snapshot() {
917
- const componentProblems = new Map(this.componentProblems);
918
- const canvasProblems = new Map(this.canvasProblems);
919
- const projectViteProblem = (problem) => {
920
- const canvasPaths = this.matchingCanvasPaths(problem);
921
- if (canvasPaths.length > 0) {
922
- for (const canvasPath of canvasPaths) {
923
- canvasProblems.set(canvasPath, problem);
924
- }
925
- return true;
926
- }
927
- const renderIds = this.matchingRenderIds(problem);
928
- if (renderIds.length === 0) return false;
929
- for (const renderId of renderIds) {
930
- componentProblems.set(
931
- renderId,
932
- this.problemForMatchedRender(problem, renderId)
933
- );
934
- }
935
- return true;
936
- };
937
- const currentViteOverlay = readCurrentViteOverlay();
938
- let hostProblem = this.hostProblem?.sourceKind === "vite-overlay" ? void 0 : this.hostProblem;
939
- if (hostProblem && isViteProblemSourceKind(hostProblem.sourceKind) && projectViteProblem(hostProblem)) {
940
- hostProblem = void 0;
941
- }
942
- if (hostProblem && (this.hostProblemWasNearRender || isNearRenderProblemSourceKind(hostProblem.sourceKind)) && projectViteProblem(hostProblem)) {
943
- hostProblem = void 0;
944
- }
945
- if (currentViteOverlay && !projectViteProblem(currentViteOverlay)) {
946
- hostProblem = currentViteOverlay;
947
- }
948
- return {
949
- hostProblem,
950
- componentProblems: [...componentProblems].map(([renderId, problem]) => ({
951
- renderId,
952
- problem
953
- })),
954
- canvasProblems: [...canvasProblems].map(([canvasPath, problem]) => ({
955
- canvasPath,
956
- problem
957
- }))
958
- };
959
- }
960
- watch(callback) {
961
- this.watchers.add(callback);
962
- return () => {
963
- this.watchers.delete(callback);
964
- };
965
- }
966
- watchHostProblemCleared(callback) {
967
- this.hostProblemClearedWatchers.add(callback);
968
- return () => {
969
- this.hostProblemClearedWatchers.delete(callback);
970
- };
971
- }
972
- reportHostProblem(sourceKind, error, details = {}) {
973
- this.hostProblem = createProblem(sourceKind, error, details);
974
- this.hostProblemWasNearRender = false;
975
- this.publish();
976
- }
977
- reportProblemNearRender(sourceKind, error, details = {}) {
978
- const problem = createProblem(sourceKind, error, details);
979
- const renderIds = this.matchingRenderIds(problem);
980
- if (renderIds.length > 0) {
981
- for (const renderId of renderIds) {
982
- this.componentProblems.set(
983
- renderId,
984
- this.problemForMatchedRender(problem, renderId)
985
- );
986
- }
987
- } else {
988
- this.hostProblem = problem;
989
- this.hostProblemWasNearRender = true;
990
- }
991
- this.publish();
992
- }
993
- // A whole-canvas failure (its module failed to import, so none of its
994
- // storyboards ever registered). Keyed by canvas path, not renderId — the
995
- // renderer scopes it to that canvas's storyboards.
996
- reportCanvasProblem(canvasPath, sourceKind, error, details = {}) {
997
- this.canvasProblems.set(
998
- canvasPath,
999
- createProblem(sourceKind, error, details)
1000
- );
1001
- this.publish();
1002
- }
1003
- clearCanvasProblem(canvasPath, sourceKinds) {
1004
- const problem = this.canvasProblems.get(canvasPath);
1005
- if (!problem) return;
1006
- if (sourceKinds && !sourceKinds.includes(problem.sourceKind)) return;
1007
- this.canvasProblems.delete(canvasPath);
1008
- this.publish();
1009
- }
1010
- registerCanvasPath(canvasPath) {
1011
- const normalizedPath = normalizeCanvasPath(canvasPath);
1012
- if (!normalizedPath) return () => {
1013
- };
1014
- this.registeredCanvasPaths.set(
1015
- normalizedPath,
1016
- (this.registeredCanvasPaths.get(normalizedPath) ?? 0) + 1
1017
- );
1018
- this.publishIfViteProjectionChanged();
1019
- return () => {
1020
- const count = this.registeredCanvasPaths.get(normalizedPath) ?? 0;
1021
- if (count <= 1) {
1022
- this.registeredCanvasPaths.delete(normalizedPath);
1023
- this.clearCanvasProblem(normalizedPath, ["vite-overlay"]);
1024
- } else {
1025
- this.registeredCanvasPaths.set(normalizedPath, count - 1);
1026
- }
1027
- this.publishIfViteProjectionChanged();
1028
- };
1029
- }
1030
- matchingCanvasPaths(problem) {
1031
- const candidates = [...this.registeredCanvasPaths.keys()];
1032
- const filenameMatches = resolveUniqueDiagnosticSourceMatches(
1033
- problem.filename ?? "",
1034
- candidates,
1035
- { projectRoot: readTempoProjectRoot() }
1036
- );
1037
- if (filenameMatches.length > 0) return filenameMatches;
1038
- const text = [problem.message, problem.stack, problem.filename].filter(Boolean).join("\n");
1039
- return resolveUniqueDiagnosticSourceMatches(text, candidates, {
1040
- projectRoot: readTempoProjectRoot()
1041
- });
1042
- }
1043
- clearHostProblem(sourceKinds) {
1044
- if (!this.hostProblem) return;
1045
- if (sourceKinds && !sourceKinds.includes(this.hostProblem.sourceKind))
1046
- return;
1047
- const clearedProblem = this.hostProblem;
1048
- this.hostProblem = void 0;
1049
- this.hostProblemWasNearRender = false;
1050
- this.publish();
1051
- this.publishHostProblemCleared(clearedProblem);
1052
- }
1053
- reportComponentProblem(renderId, sourceKind, error, details = {}) {
1054
- this.componentProblems.set(
1055
- renderId,
1056
- createProblem(sourceKind, error, details)
1057
- );
1058
- this.publish();
1059
- }
1060
- clearComponentProblem(renderId, sourceKinds) {
1061
- const problem = this.componentProblems.get(renderId);
1062
- if (!problem) return;
1063
- if (sourceKinds && !sourceKinds.includes(problem.sourceKind)) return;
1064
- this.componentProblems.delete(renderId);
1065
- this.publish();
1066
- }
1067
- hasComponentProblem(renderId) {
1068
- return this.componentProblems.has(renderId);
1069
- }
1070
- syncRenderSourcePaths(entries) {
1071
- const next = new Map(
1072
- entries.flatMap(
1073
- (entry) => entry.sourcePaths?.length ? [[entry.renderId, entry.sourcePaths]] : []
1074
- )
1075
- );
1076
- const changed = JSON.stringify([...this.registeredRenderSourcePaths]) !== JSON.stringify([...next]);
1077
- if (!changed) return;
1078
- this.registeredRenderSourcePaths = next;
1079
- if (this.hostProblem && (this.hostProblemWasNearRender || isNearRenderProblemSourceKind(this.hostProblem.sourceKind)) && this.matchingRenderIds(this.hostProblem).length > 0) {
1080
- this.publish();
1081
- } else {
1082
- this.publishIfViteProjectionChanged();
1083
- }
1084
- }
1085
- matchingRenderIds(problem) {
1086
- return findRenderIdsForProblem(
1087
- problem,
1088
- [...this.registeredRenderSourcePaths].flatMap(
1089
- ([renderId, sourcePaths]) => sourcePaths.map((sourceFile) => ({ renderId, sourceFile }))
1090
- )
1091
- );
1092
- }
1093
- problemForMatchedRender(problem, renderId) {
1094
- if (problem.sourceKind !== "unhandled-rejection" || !this.matchingDeclaredRenderIds(problem).includes(renderId)) {
1095
- return problem;
1096
- }
1097
- return { ...problem, sourceKind: "render-error-boundary" };
1098
- }
1099
- matchingDeclaredRenderIds(problem) {
1100
- return findRenderIdsForProblem(
1101
- problem,
1102
- [...this.registeredRenderSourcePaths].flatMap(
1103
- ([renderId, sourcePaths]) => sourcePaths.map((sourceFile) => ({ renderId, sourceFile }))
1104
- ),
1105
- false
1106
- );
1107
- }
1108
- clearRecoveredComponentProblemsAfterRender(renderId) {
1109
- let changed = false;
1110
- const problem = this.componentProblems.get(renderId);
1111
- if (problem && problem.sourceKind !== "render-error-boundary") {
1112
- this.componentProblems.delete(renderId);
1113
- changed = true;
1114
- }
1115
- if (this.clearRecoveredHostProblemAfterRender(renderId)) changed = true;
1116
- if (changed) {
1117
- this.publish();
1118
- } else {
1119
- this.publishIfViteProjectionChanged();
1120
- }
1121
- }
1122
- reconcileViteOverlayProjection() {
1123
- this.publishIfViteProjectionChanged();
1124
- }
1125
- dispose() {
1126
- this.watchers.clear();
1127
- this.hostProblemClearedWatchers.clear();
1128
- this.registeredCanvasPaths.clear();
1129
- this.registeredRenderSourcePaths.clear();
1130
- }
1131
- publish() {
1132
- this.publishedViteProjectionSignature = this.viteProjectionSignature();
1133
- for (const watcher of this.watchers) {
1134
- watcher();
1135
- }
1136
- }
1137
- publishIfViteProjectionChanged() {
1138
- const signature = this.viteProjectionSignature();
1139
- if (this.publishedViteProjectionSignature === void 0) {
1140
- this.publishedViteProjectionSignature = signature;
1141
- return;
1142
- }
1143
- if (signature === this.publishedViteProjectionSignature) return;
1144
- this.publish();
1145
- }
1146
- viteProjectionSignature() {
1147
- const snapshot = this.snapshot();
1148
- const identify = (problem) => [problem.sourceKind, problem.filename, problem.message].join("\0");
1149
- return JSON.stringify({
1150
- host: snapshot.hostProblem && isProjectedViteProblemSourceKind(snapshot.hostProblem.sourceKind) ? identify(snapshot.hostProblem) : null,
1151
- components: snapshot.componentProblems.flatMap(
1152
- ({ renderId, problem }) => isProjectedViteProblemSourceKind(problem.sourceKind) ? [[renderId, identify(problem)]] : []
1153
- ),
1154
- canvases: snapshot.canvasProblems.flatMap(
1155
- ({ canvasPath, problem }) => isProjectedViteProblemSourceKind(problem.sourceKind) ? [[canvasPath, identify(problem)]] : []
1156
- )
1157
- });
1158
- }
1159
- publishHostProblemCleared(problem) {
1160
- for (const watcher of this.hostProblemClearedWatchers) {
1161
- watcher(problem);
1162
- }
1163
- }
1164
- clearRecoveredHostProblemAfterRender(renderId) {
1165
- if (!this.hostProblem || !renderRecoveredHostProblemSourceKinds.includes(
1166
- this.hostProblem.sourceKind
1167
- )) {
1168
- return false;
1169
- }
1170
- const matchingRenderIds = this.matchingRenderIds(this.hostProblem);
1171
- if (matchingRenderIds.length > 0 && !matchingRenderIds.includes(renderId))
1172
- return false;
1173
- const clearedProblem = this.hostProblem;
1174
- this.hostProblem = void 0;
1175
- this.hostProblemWasNearRender = false;
1176
- this.publishHostProblemCleared(clearedProblem);
1177
- return true;
1178
- }
1179
- };
1180
- function createCanvasHostProblemTracker() {
1181
- return new CanvasHostProblemTracker();
1182
- }
1183
- function installCanvasHostRuntimeProblemTracking(tracker) {
1184
- if (typeof window === "undefined") return () => {
1185
- };
1186
- const startupProblems = takeFrameStartupProblems();
1187
- const cleanupHostCapture = installHostProblemCapture(tracker);
1188
- const cleanupViteCapture = installViteProblemCapture(tracker);
1189
- const cleanupViteErrorStream = installViteErrorStream(tracker);
1190
- for (const problem of startupProblems) {
1191
- tracker.reportProblemNearRender(
1192
- problem.kind === "error" ? "page-error" : "unhandled-rejection",
1193
- problem.message,
1194
- {
1195
- timestamp: problem.timestamp,
1196
- stack: problem.stack,
1197
- filename: problem.filename,
1198
- line: problem.line,
1199
- column: problem.column
1200
- }
1201
- );
1202
- }
1203
- return () => {
1204
- cleanupHostCapture();
1205
- cleanupViteCapture();
1206
- cleanupViteErrorStream();
1207
- };
1208
- }
1209
- function installViteErrorStream(tracker) {
1210
- const receive = (problem) => {
1211
- if (problem === null) {
1212
- tracker.clearHostProblem(["vite-hmr-error"]);
1213
- return;
1214
- }
1215
- if (typeof problem?.message !== "string") return;
1216
- tracker.reportHostProblem("vite-hmr-error", problem.message, {
1217
- stack: problem.stack,
1218
- filename: problem.file ?? problem.loc?.file
1219
- });
1220
- };
1221
- const feed = globalThis[VITE_ERROR_FEED_KEY];
1222
- if (feed) return feed.subscribe(receive);
1223
- if (typeof EventSource === "undefined") return () => {
1224
- };
1225
- const source = new EventSource("/__tempo/errors");
1226
- source.onmessage = (event) => {
1227
- let problem;
1228
- try {
1229
- problem = JSON.parse(event.data);
1230
- } catch {
1231
- return;
1232
- }
1233
- receive(problem);
1234
- };
1235
- return () => {
1236
- source.close();
1237
- };
1238
- }
1239
- function takeFrameStartupProblems() {
1240
- const take = window.framePool?.takeStartupErrors;
1241
- if (typeof take !== "function") return [];
1242
- let value;
1243
- try {
1244
- value = take();
1245
- } catch {
1246
- return [];
1247
- }
1248
- if (!Array.isArray(value)) return [];
1249
- return value.flatMap((candidate) => {
1250
- if (!candidate || typeof candidate !== "object" || candidate.kind !== "error" && candidate.kind !== "unhandledrejection" || typeof candidate.message !== "string" || typeof candidate.timestamp !== "number") {
1251
- return [];
1252
- }
1253
- const record = candidate;
1254
- return [
1255
- {
1256
- kind: record.kind,
1257
- timestamp: record.timestamp,
1258
- message: record.message,
1259
- ...typeof record.stack === "string" && { stack: record.stack },
1260
- ...typeof record.filename === "string" && {
1261
- filename: record.filename
1262
- },
1263
- ...typeof record.line === "number" && { line: record.line },
1264
- ...typeof record.column === "number" && { column: record.column }
1265
- }
1266
- ];
1267
- });
1268
- }
1269
- var renderRecoveredHostProblemSourceKinds = ["page-error", "unhandled-rejection", "console-vite-error", "vite-hmr-error"];
1270
- var FAILED_RELOAD_PROBE_DELAYS_MS = [50, 400, 1600];
1271
- async function moduleTransformSucceeds(path) {
1272
- const [pathname, query = ""] = path.split("?");
1273
- const url = `${pathname}?${query ? `${query}&` : ""}t=${Date.now()}`;
1274
- const response = await fetch(url, {
1275
- cache: "no-store",
1276
- headers: { Accept: "application/javascript" }
1277
- });
1278
- return response.ok && /javascript/i.test(response.headers.get("content-type") ?? "");
1279
- }
1280
- async function compileErrorFileStillBroken(file) {
1281
- const cleaned = file.replace(/:\d+(?::\d+)?$/, "");
1282
- const candidates = cleaned.startsWith("/@") ? [cleaned] : [`/@fs${cleaned}`, cleaned];
1283
- for (const candidate of candidates) {
1284
- try {
1285
- if (await moduleTransformSucceeds(candidate)) return false;
1286
- } catch {
1287
- return true;
1288
- }
1289
- }
1290
- return true;
1291
- }
1292
- function isViteProblemSourceKind(sourceKind) {
1293
- return sourceKind === "vite-hmr-error" || sourceKind === "console-vite-error";
1294
- }
1295
- function isNearRenderProblemSourceKind(sourceKind) {
1296
- return sourceKind === "page-error" || sourceKind === "unhandled-rejection" || sourceKind === "console-vite-error";
1297
- }
1298
- function isProjectedViteProblemSourceKind(sourceKind) {
1299
- return sourceKind === "vite-overlay" || isViteProblemSourceKind(sourceKind);
1300
- }
1301
- function createProblem(sourceKind, error, details = {}) {
1302
- return {
1303
- sourceKind,
1304
- ...describeError(error),
1305
- frameUrl: typeof window === "undefined" ? void 0 : window.location.href,
1306
- timestamp: Date.now(),
1307
- ...details
1308
- };
1309
- }
1310
- function describeError(error) {
1311
- if (!(error instanceof Error)) return { message: String(error) };
1312
- const cause = error.cause;
1313
- if (cause === void 0 || cause === null) {
1314
- return { message: error.message, stack: error.stack };
1315
- }
1316
- const inner = describeError(cause);
1317
- return {
1318
- message: `${error.message} Cause: ${inner.message}`,
1319
- stack: inner.stack ?? error.stack
1320
- };
1321
- }
1322
- function findRenderIdsForProblem(problem, registered = [], includeDom = true) {
1323
- const observed = [
1324
- ...registered
1325
- ];
1326
- if (includeDom && typeof document !== "undefined") {
1327
- for (const slot of document.querySelectorAll("[data-render-id]")) {
1328
- const renderId = slot.getAttribute("data-render-id");
1329
- if (!renderId) continue;
1330
- for (const sourceFile of getObservedSourceFiles2(slot)) {
1331
- observed.push({ renderId, sourceFile });
1332
- }
1333
- }
1334
- }
1335
- if (observed.length === 0) return [];
1336
- const exactFilenameMatches = new Set(
1337
- resolveUniqueDiagnosticSourceMatches(
1338
- problem.filename ?? "",
1339
- observed.map(({ sourceFile }) => sourceFile),
1340
- {
1341
- projectRoot: readTempoProjectRoot(),
1342
- allowExtensionlessJsTs: true
1343
- }
1344
- )
1345
- );
1346
- if (exactFilenameMatches.size > 0) {
1347
- return uniqueRenderIds(
1348
- observed.filter(({ sourceFile }) => exactFilenameMatches.has(sourceFile))
1349
- );
1350
- }
1351
- const filenameMatches = matchObservedRenderIds(
1352
- problem.filename ?? "",
1353
- observed
1354
- );
1355
- if (filenameMatches.length > 0) return filenameMatches;
1356
- const haystack = [problem.message, problem.stack, problem.componentStack].filter(Boolean).join("\n");
1357
- return matchObservedRenderIds(haystack, observed);
1358
- }
1359
- var sourceAnnotationSelector2 = "[data-tempo-source-file], [data-tempo-source-loc], [data-tempo-filepath], [data-tempo-html-filepath]";
1360
- function getObservedSourceFiles2(slot) {
1361
- const sourceFiles = /* @__PURE__ */ new Set();
1362
- for (const element of slot.querySelectorAll(sourceAnnotationSelector2)) {
1363
- for (const attribute of [
1364
- "data-tempo-source-file",
1365
- "data-tempo-filepath",
1366
- "data-tempo-html-filepath"
1367
- ]) {
1368
- const value = element.getAttribute(attribute);
1369
- if (value) sourceFiles.add(value);
1370
- }
1371
- const sourceLoc = element.getAttribute("data-tempo-source-loc");
1372
- const sourceFile = sourceLoc?.split(":")[0];
1373
- if (sourceFile) sourceFiles.add(sourceFile);
1374
- }
1375
- return [...sourceFiles];
1376
- }
1377
- function matchObservedRenderIds(text, observed) {
1378
- const matches = new Set(
1379
- resolveUniqueDiagnosticSourceMatches(
1380
- text,
1381
- observed.map(({ sourceFile }) => sourceFile),
1382
- {
1383
- projectRoot: readTempoProjectRoot(),
1384
- allowExtensionlessJsTs: true
1385
- }
1386
- )
1387
- );
1388
- return uniqueRenderIds(
1389
- observed.filter(({ sourceFile }) => matches.has(sourceFile))
1390
- );
1391
- }
1392
- function readTempoProjectRoot() {
1393
- if (typeof document === "undefined") return null;
1394
- return document.querySelector('meta[name="tempo-source-identity-root"]')?.content.trim() || document.querySelector('meta[name="tempo-project-root"]')?.content.trim() || null;
1395
- }
1396
- function uniqueRenderIds(matches) {
1397
- return [...new Set(matches.map(({ renderId }) => renderId))];
1398
- }
1399
- function normalizeCanvasPath(value) {
1400
- return value.trim();
1401
- }
1402
- function isRecoveredAdmissionBudgetError(error) {
1403
- return error instanceof Error && error.cause instanceof AdmissionBudgetError;
1404
- }
1405
- function installHostProblemCapture(tracker) {
1406
- const onError = (event) => {
1407
- if (event.target instanceof Element) return;
1408
- if (isRecoveredAdmissionBudgetError(event.error)) return;
1409
- tracker.reportProblemNearRender(
1410
- "page-error",
1411
- event.error ?? event.message,
1412
- {
1413
- filename: event.filename || void 0,
1414
- line: typeof event.lineno === "number" ? event.lineno : void 0,
1415
- column: typeof event.colno === "number" ? event.colno : void 0
1416
- }
1417
- );
1418
- };
1419
- const onUnhandledRejection = (event) => {
1420
- tracker.reportProblemNearRender("unhandled-rejection", event.reason);
1421
- };
1422
- const resourceTags = /* @__PURE__ */ new Set([
1423
- "IMG",
1424
- "SCRIPT",
1425
- "LINK",
1426
- "AUDIO",
1427
- "VIDEO",
1428
- "SOURCE"
1429
- ]);
1430
- const onResourceError = (event) => {
1431
- const target = event.target;
1432
- if (!(target instanceof Element) || !resourceTags.has(target.tagName)) {
1433
- return;
1434
- }
1435
- const url = target.getAttribute("src") || target.getAttribute("href") || "";
1436
- const message = `Failed to load ${target.tagName.toLowerCase()}${url ? `: ${url}` : ""}`;
1437
- const renderId = target.closest("[data-render-id]")?.getAttribute("data-render-id");
1438
- if (renderId) {
1439
- tracker.reportComponentProblem(renderId, "resource-load", message);
1440
- } else {
1441
- tracker.reportHostProblem("resource-load", message, {
1442
- filename: url || void 0
1443
- });
1444
- }
1445
- };
1446
- const onFontLoadingError = (event) => {
1447
- const faces = event.fontfaces ?? [];
1448
- const families = faces.map((face) => face.family).filter(Boolean).join(", ");
1449
- tracker.reportHostProblem(
1450
- "resource-load",
1451
- `Failed to load font${families ? `: ${families}` : ""}`
1452
- );
1453
- };
1454
- const fontFaceSet = typeof document.fonts?.addEventListener === "function" ? document.fonts : void 0;
1455
- window.addEventListener("error", onError);
1456
- window.addEventListener("unhandledrejection", onUnhandledRejection);
1457
- window.addEventListener("error", onResourceError, { capture: true });
1458
- document.addEventListener("error", onResourceError, { capture: true });
1459
- fontFaceSet?.addEventListener("loadingerror", onFontLoadingError);
1460
- return () => {
1461
- window.removeEventListener("error", onError);
1462
- window.removeEventListener("unhandledrejection", onUnhandledRejection);
1463
- window.removeEventListener("error", onResourceError, { capture: true });
1464
- document.removeEventListener("error", onResourceError, { capture: true });
1465
- fontFaceSet?.removeEventListener("loadingerror", onFontLoadingError);
1466
- };
1467
- }
1468
- function installViteProblemCapture(tracker) {
1469
- const reconcileViteOverlay = () => {
1470
- tracker.reconcileViteOverlayProjection();
1471
- };
1472
- const observer = new MutationObserver(reconcileViteOverlay);
1473
- if (document.body) {
1474
- observer.observe(document.body, { childList: true });
1475
- reconcileViteOverlay();
1476
- void Promise.resolve().then(reconcileViteOverlay);
1477
- }
1478
- const evalFailedModules = /* @__PURE__ */ new Map();
1479
- const latestEvaluationFailure = () => {
1480
- let latest;
1481
- for (const problem of evalFailedModules.values()) {
1482
- if (!latest || problem.timestamp >= latest.timestamp) latest = problem;
1483
- }
1484
- return latest;
1485
- };
1486
- const reconcileEvaluationHostProblem = () => {
1487
- const latest = latestEvaluationFailure();
1488
- if (latest) {
1489
- tracker.reportHostProblem("vite-hmr-error", latest.message, latest);
1490
- } else {
1491
- tracker.clearHostProblem(["vite-hmr-error"]);
1492
- }
1493
- };
1494
- const failedReloadPattern = /^Failed to reload (.+?)\. This could be due to/;
1495
- let lastViteConsoleErrorDetail = null;
1496
- const stopClearedWatch = tracker.watchHostProblemCleared((problem) => {
1497
- if (problem.sourceKind !== "vite-hmr-error") return;
1498
- const removed = problem.filename ? evalFailedModules.delete(problem.filename) : false;
1499
- if (!removed) return;
1500
- queueMicrotask(reconcileEvaluationHostProblem);
1501
- });
1502
- const originalConsoleError = console.error;
1503
- const patchedConsoleError = (...args) => {
1504
- originalConsoleError(...args);
1505
- const error = readViteConsoleError(args[0], args[1]);
1506
- if (!error) return;
1507
- const failedReload = failedReloadPattern.exec(error.message);
1508
- if (failedReload) {
1509
- const path = failedReload[1] ?? error.message;
1510
- const detail = lastViteConsoleErrorDetail;
1511
- lastViteConsoleErrorDetail = null;
1512
- if (detail && !/failed to fetch/i.test(detail.message)) {
1513
- const problem = createProblem("vite-hmr-error", detail.message, {
1514
- stack: detail.stack,
1515
- filename: path
1516
- });
1517
- evalFailedModules.set(path, problem);
1518
- reconcileEvaluationHostProblem();
1519
- getCanvasHostRecoveryFeed().publish({
1520
- type: "module-load-failure",
1521
- path,
1522
- message: detail.message
1523
- });
1524
- return;
1525
- }
1526
- void (async () => {
1527
- for (const delayMs of FAILED_RELOAD_PROBE_DELAYS_MS) {
1528
- await new Promise((resolve) => setTimeout(resolve, delayMs));
1529
- try {
1530
- if (!await moduleTransformSucceeds(path)) continue;
1531
- const snapshot = tracker.snapshot();
1532
- const compileErrorFiles = /* @__PURE__ */ new Set();
1533
- for (const problem of [
1534
- snapshot.hostProblem,
1535
- ...snapshot.componentProblems.map((entry) => entry.problem),
1536
- ...snapshot.canvasProblems.map((entry) => entry.problem)
1537
- ]) {
1538
- if (!problem) continue;
1539
- if (!isProjectedViteProblemSourceKind(problem.sourceKind)) {
1540
- continue;
1541
- }
1542
- if (problem.filename) compileErrorFiles.add(problem.filename);
1543
- }
1544
- for (const file of compileErrorFiles) {
1545
- if (await compileErrorFileStillBroken(file)) return;
1546
- }
1547
- getCanvasHostRecoveryFeed().publish({
1548
- type: "module-update-dropped",
1549
- path,
1550
- message: error.message
1551
- });
1552
- return;
1553
- } catch {
1554
- return;
1555
- }
1556
- }
1557
- })();
1558
- return;
1559
- }
1560
- lastViteConsoleErrorDetail = error;
1561
- queueMicrotask(() => {
1562
- if (lastViteConsoleErrorDetail !== error) return;
1563
- lastViteConsoleErrorDetail = null;
1564
- tracker.reportProblemNearRender("console-vite-error", error.message, {
1565
- stack: error.stack,
1566
- filename: error.filename
1567
- });
1568
- });
1569
- };
1570
- console.error = patchedConsoleError;
1571
- return () => {
1572
- observer.disconnect();
1573
- stopClearedWatch();
1574
- if (console.error === patchedConsoleError) {
1575
- console.error = originalConsoleError;
1576
- }
1577
- };
1578
- }
1579
- function readCurrentViteOverlay() {
1580
- if (typeof document === "undefined") return void 0;
1581
- const overlay = document.querySelector("vite-error-overlay");
1582
- if (!overlay) return void 0;
1583
- const { message, stack, filename } = readViteOverlayContent(overlay);
1584
- return createProblem("vite-overlay", message, { stack, filename });
1585
- }
1586
- function readViteOverlayContent(overlay) {
1587
- const root = overlay.shadowRoot ?? overlay;
1588
- const text = (selector) => {
1589
- const value = root.querySelector(selector)?.textContent?.trim();
1590
- return value ? value : void 0;
1591
- };
1592
- const message = text(".message-body") ?? text(".message") ?? overlay.textContent?.trim() ?? "Unknown Vite error";
1593
- const stack = [text(".stack"), text(".plugin"), text(".frame")].filter(Boolean).join("\n");
1594
- return {
1595
- message,
1596
- stack: stack || void 0,
1597
- filename: text(".file")
1598
- };
1599
- }
1600
- function readViteError(value) {
1601
- if (value instanceof Error) {
1602
- return {
1603
- message: value.message,
1604
- stack: value.stack,
1605
- filename: typeof value.id === "string" ? value.id : void 0
1606
- };
1607
- }
1608
- if (typeof value === "string") return { message: value };
1609
- if (typeof value !== "object" || value === null) return void 0;
1610
- const record = value;
1611
- const nested = typeof record.err === "object" && record.err !== null ? record.err : record;
1612
- const message = typeof nested.message === "string" ? nested.message : typeof record.message === "string" ? record.message : void 0;
1613
- if (!message) return void 0;
1614
- return {
1615
- message,
1616
- stack: typeof nested.stack === "string" ? nested.stack : typeof record.stack === "string" ? record.stack : void 0,
1617
- filename: typeof nested.filename === "string" ? nested.filename : typeof nested.file === "string" ? nested.file : typeof nested.id === "string" ? nested.id : typeof record.id === "string" ? record.id : void 0
1618
- };
1619
- }
1620
- function readViteConsoleError(first, second) {
1621
- if (first === "[vite]") return readViteError(second);
1622
- if (typeof first !== "string" || !first.startsWith("[vite]")) {
1623
- return void 0;
1624
- }
1625
- const detail = readViteError(second);
1626
- const message = first.replace(/^\[vite\]\s*/, "") || detail?.message;
1627
- return message ? {
1628
- message,
1629
- stack: detail?.stack,
1630
- filename: detail?.filename
1631
- } : void 0;
1632
- }
1633
-
1634
- // canvas/use-canvas-host-postmessage.ts
1635
- var DEFAULT_MAX_CACHED_RENDERS = 20;
1636
- function postToMessageSource(source, response, targetOrigin) {
1637
- const origin = safePostMessageTargetOrigin(targetOrigin);
1638
- if (source && "postMessage" in source && source !== window) {
1639
- source.postMessage(response, origin);
1640
- } else {
1641
- window.postMessage(response, origin);
1642
- }
1643
- }
1644
- function safePostMessageTargetOrigin(targetOrigin) {
1645
- if (targetOrigin && targetOrigin !== "null" && targetOrigin !== "file://") {
1646
- return targetOrigin;
1647
- }
1648
- const currentOrigin = window.location.origin;
1649
- return currentOrigin && currentOrigin !== "null" ? currentOrigin : "*";
1650
- }
1651
- function acknowledgeWatchEstablishment(request) {
1652
- if (request.establishment.status !== "pending") return;
1653
- request.establishment.status = "established";
1654
- postToMessageSource(
1655
- request.source,
1656
- {
1657
- type: "render-pool:ack",
1658
- requestId: request.requestId,
1659
- command: request.commandType
1660
- },
1661
- request.targetOrigin
1662
- );
1663
- }
1664
- function rejectWatchEstablishment(request, error) {
1665
- if (request.establishment.status !== "pending") return;
1666
- request.establishment.status = "failed";
1667
- postWatchError(request, error);
1668
- }
1669
- function postWatchError(request, error) {
1670
- postToMessageSource(
1671
- request.source,
1672
- {
1673
- type: "render-pool:error",
1674
- requestId: request.requestId,
1675
- watchId: request.watchId,
1676
- command: request.commandType,
1677
- error: error.message
1678
- },
1679
- request.targetOrigin
1680
- );
1681
- }
1682
- function readWatchResumeOptions(payload) {
1683
- const flush = payload.flush;
1684
- const triggers = Array.isArray(payload.triggers) ? payload.triggers.filter(
1685
- (trigger) => trigger === "viewport-capture"
1686
- ) : [];
1687
- const validFlush = flush === "always" || flush === "if-dirty" || flush === "never" ? flush : void 0;
1688
- return validFlush === void 0 && triggers.length === 0 ? void 0 : { flush: validFlush, triggers };
1689
- }
1690
- function setRuntimeWatchPaused(watch, paused, resumeOptions) {
1691
- if (watch.setPaused) {
1692
- if (resumeOptions === void 0) {
1693
- watch.setPaused(paused);
1694
- } else {
1695
- watch.setPaused(paused, resumeOptions);
1696
- }
1697
- } else if (paused) {
1698
- watch.pause?.();
1699
- } else {
1700
- if (resumeOptions === void 0) {
1701
- watch.resume?.();
1702
- } else {
1703
- watch.resume?.(resumeOptions);
1704
- }
1705
- }
1706
- }
1707
- function useCanvasHostPostMessage(registeredCanvasPaths = [], urlPinnedRenderId = null, registerCanvas) {
1708
- const [renderEntriesById, setRenderEntriesById] = useState2(() => /* @__PURE__ */ new Map());
1709
- const [watchRequestsById, setWatchRequestsById] = useState2(
1710
- () => /* @__PURE__ */ new Map()
1711
- );
1712
- const [renderCommitVersionById, setRenderCommitVersionById] = useState2(
1713
- () => /* @__PURE__ */ new Map()
1714
- );
1715
- const renderEntriesRef = useRef2(renderEntriesById);
1716
- const committedRenderEntriesRef = useRef2(renderEntriesById);
1717
- useLayoutEffect2(() => {
1718
- committedRenderEntriesRef.current = renderEntriesById;
1719
- }, [renderEntriesById]);
1720
- const renderStatusRef = useRef2();
1721
- const renderSizeRef = useRef2();
1722
- const watchRequestsRef = useRef2(watchRequestsById);
1723
- const registeredCanvasPathsRef = useRef2([]);
1724
- registeredCanvasPathsRef.current = registeredCanvasPaths;
1725
- const urlPinnedRenderIdRef = useRef2(null);
1726
- urlPinnedRenderIdRef.current = urlPinnedRenderId;
1727
- const registerCanvasRef = useRef2(registerCanvas);
1728
- registerCanvasRef.current = registerCanvas;
1729
- const maxCachedRef = useRef2(DEFAULT_MAX_CACHED_RENDERS);
1730
- const legacyHealthRef = useRef2(createLegacyHostHealth());
1731
- const renderedRenderIdsRef = useRef2(/* @__PURE__ */ new Set());
1732
- const pendingRenderWaitersRef = useRef2(
1733
- /* @__PURE__ */ new Map()
1734
- );
1735
- const sourcePinsRef = useRef2(
1736
- /* @__PURE__ */ new Map()
1737
- );
1738
- const watchesRef = useRef2(/* @__PURE__ */ new Map());
1739
- const startingWatchesRef = useRef2(
1740
- /* @__PURE__ */ new Map()
1741
- );
1742
- const problemWatchersRef = useRef2(/* @__PURE__ */ new Map());
1743
- const problemTrackerRef = useRef2(createCanvasHostProblemTracker());
1744
- const updateWatchRequests = useCallback2(
1745
- (update) => {
1746
- const current = watchRequestsRef.current;
1747
- const next = update(current);
1748
- if (next === current) return;
1749
- watchRequestsRef.current = next;
1750
- setWatchRequestsById(next);
1751
- },
1752
- []
1753
- );
1754
- const buildProblemSnapshot = useCallback2(
1755
- () => problemTrackerRef.current.snapshot(),
1756
- []
1757
- );
1758
- const publishProblemSnapshot = useCallback2(() => {
1759
- const payload = buildProblemSnapshot();
1760
- for (const watcher of problemWatchersRef.current.values()) {
1761
- postToMessageSource(
1762
- watcher.source,
1763
- {
1764
- type: "render-pool:problem-snapshot",
1765
- requestId: watcher.requestId,
1766
- watchId: watcher.watchId,
1767
- payload
1768
- },
1769
- watcher.targetOrigin
1770
- );
1771
- }
1772
- }, [buildProblemSnapshot]);
1773
- const setEntries = useCallback2(
1774
- (update) => {
1775
- setRenderEntriesById((entries) => {
1776
- const next = update(entries);
1777
- if (next === entries) return entries;
1778
- renderEntriesRef.current = next;
1779
- problemTrackerRef.current.syncRenderSourcePaths([...next.values()]);
1780
- for (const renderId of [...renderedRenderIdsRef.current]) {
1781
- if (!next.has(renderId)) {
1782
- renderedRenderIdsRef.current.delete(renderId);
1783
- legacyHealthRef.current.forgetRender(renderId);
1784
- }
1785
- }
1786
- return next;
1787
- });
1788
- },
1789
- []
1790
- );
1791
- const waitForRender = useCallback2(
1792
- (request) => {
1793
- const committed = committedRenderEntriesRef.current.get(request.renderId);
1794
- const rendered = renderedRenderIdsRef.current.has(request.renderId);
1795
- const alreadyRendered = rendered && (urlPinnedRenderIdRef.current === request.renderId || committed?.status === "active" && renderRequestMatchesEntry(committed, request));
1796
- setEntries((entries) => acquireRender(entries, request));
1797
- if (alreadyRendered) {
1798
- return Promise.resolve();
1799
- }
1800
- return new Promise((resolve, reject) => {
1801
- const pendingWaiters = pendingRenderWaitersRef.current.get(request.renderId) ?? [];
1802
- pendingWaiters.push({ resolve, reject });
1803
- pendingRenderWaitersRef.current.set(request.renderId, pendingWaiters);
1804
- });
1805
- },
1806
- [setEntries]
1807
- );
1808
- const releaseRenderLease = useCallback2(
1809
- (renderId, cacheWhenIdle) => {
1810
- setEntries(
1811
- (entries) => releaseRender(
1812
- entries,
1813
- renderId,
1814
- maxCachedRef.current,
1815
- Date.now(),
1816
- cacheWhenIdle
1817
- )
1818
- );
1819
- },
1820
- [setEntries]
1821
- );
1822
- const stopRuntimeWatch = useCallback2(
1823
- async (watchId, establishment) => {
1824
- const existingWatch = watchesRef.current.get(watchId);
1825
- if (!existingWatch || establishment && existingWatch.establishment !== establishment) {
1826
- return;
1827
- }
1828
- watchesRef.current.delete(watchId);
1829
- await existingWatch.watch.stop();
1830
- },
1831
- []
1832
- );
1833
- const removeWatchRequest = useCallback2(
1834
- async (watchId, reason) => {
1835
- const existingRequest = watchRequestsRef.current.get(watchId);
1836
- if (existingRequest) {
1837
- rejectWatchEstablishment(
1838
- existingRequest,
1839
- reason ?? new Error(
1840
- `Canvas host watch ${watchId} was cancelled before establishment`
1841
- )
1842
- );
1843
- }
1844
- try {
1845
- await stopRuntimeWatch(watchId, existingRequest?.establishment);
1846
- } finally {
1847
- if (existingRequest) {
1848
- updateWatchRequests((requests) => {
1849
- if (requests.get(watchId)?.establishment !== existingRequest.establishment) {
1850
- return requests;
1851
- }
1852
- const next = new Map(requests);
1853
- next.delete(watchId);
1854
- return next;
1855
- });
1856
- releaseRenderLease(existingRequest.request.renderId);
1857
- }
1858
- }
1859
- },
1860
- [releaseRenderLease, stopRuntimeWatch, updateWatchRequests]
1861
- );
1862
- const suspendEstablishedWatch = useCallback2(
1863
- (request) => {
1864
- if (request.establishment.status !== "established") return;
1865
- void stopRuntimeWatch(request.watchId, request.establishment).catch(
1866
- () => {
1867
- }
1868
- );
1869
- },
1870
- [stopRuntimeWatch]
1871
- );
1872
- const runtimeIdRef = useRef2(void 0);
1873
- const buildState = useCallback2(
1874
- () => ({
1875
- runtimeId: runtimeIdRef.current,
1876
- sourceCapturePins: true,
1877
- ...registerCanvasRef.current ? { incrementalCanvasRegistration: true } : {},
1878
- ...buildRenderStatePayload(
1879
- renderEntriesRef.current,
1880
- maxCachedRef.current,
1881
- registeredCanvasPathsRef.current
1882
- )
1883
- }),
1884
- []
1885
- );
1886
- const markStoryboardRendered = useCallback2((storyboardId) => {
1887
- renderedRenderIdsRef.current.add(storyboardId);
1888
- legacyHealthRef.current.recordRenderCommit(storyboardId);
1889
- setRenderCommitVersionById((versions) => {
1890
- const next = new Map(versions);
1891
- next.set(storyboardId, (next.get(storyboardId) ?? 0) + 1);
1892
- return next;
1893
- });
1894
- problemTrackerRef.current.clearRecoveredComponentProblemsAfterRender(
1895
- storyboardId
1896
- );
1897
- const pendingWaiters = pendingRenderWaitersRef.current.get(storyboardId);
1898
- if (!pendingWaiters) return;
1899
- pendingRenderWaitersRef.current.delete(storyboardId);
1900
- for (const waiter of pendingWaiters) {
1901
- waiter.resolve();
1902
- }
1903
- }, []);
1904
- const markStoryboardUnmounted = useCallback2(
1905
- (storyboardId) => {
1906
- queueMicrotask(() => {
1907
- const remounted = [
1908
- ...document.querySelectorAll("[data-render-id]")
1909
- ].some(
1910
- (element) => element.getAttribute("data-render-id") === storyboardId
1911
- );
1912
- if (remounted) return;
1913
- renderedRenderIdsRef.current.delete(storyboardId);
1914
- for (const request of watchRequestsRef.current.values()) {
1915
- if (request.request.renderId === storyboardId) {
1916
- suspendEstablishedWatch(request);
1917
- }
1918
- }
1919
- const pendingWaiters = pendingRenderWaitersRef.current.get(storyboardId);
1920
- if (!pendingWaiters) return;
1921
- pendingRenderWaitersRef.current.delete(storyboardId);
1922
- const error = new Error(
1923
- `Storyboard ${JSON.stringify(storyboardId)} unmounted before its requested render committed`
1924
- );
1925
- for (const waiter of pendingWaiters) {
1926
- waiter.reject(error);
1927
- }
1928
- });
1929
- },
1930
- [suspendEstablishedWatch]
1931
- );
1932
- const reportStoryboardError = useCallback2(
1933
- (storyboardId, error) => {
1934
- renderedRenderIdsRef.current.delete(storyboardId);
1935
- problemTrackerRef.current.reportComponentProblem(
1936
- storyboardId,
1937
- "render-error-boundary",
1938
- error.message,
1939
- {
1940
- stack: error.stack,
1941
- componentStack: error.componentStack
1942
- }
1943
- );
1944
- const renderError = new Error(error.message);
1945
- const pendingWaiters = pendingRenderWaitersRef.current.get(storyboardId);
1946
- if (pendingWaiters) {
1947
- pendingRenderWaitersRef.current.delete(storyboardId);
1948
- for (const waiter of pendingWaiters) {
1949
- waiter.reject(renderError);
1950
- }
1951
- }
1952
- for (const request of watchRequestsRef.current.values()) {
1953
- if (request.request.renderId !== storyboardId || request.establishment.status === "failed") {
1954
- continue;
1955
- }
1956
- if (request.establishment.status === "pending") {
1957
- rejectWatchEstablishment(request, renderError);
1958
- void removeWatchRequest(request.watchId, renderError);
1959
- } else {
1960
- postWatchError(request, renderError);
1961
- suspendEstablishedWatch(request);
1962
- }
1963
- }
1964
- },
1965
- [removeWatchRequest, suspendEstablishedWatch]
1966
- );
1967
- const clearStoryboardError = useCallback2((storyboardId) => {
1968
- problemTrackerRef.current.clearComponentProblem(storyboardId, [
1969
- "render-error-boundary"
1970
- ]);
1971
- }, []);
1972
- const reportCanvasImportError = useCallback2(
1973
- (canvasPath, error) => {
1974
- const normalizedPath = canvasPath.trim();
1975
- if (!normalizedPath) return;
1976
- problemTrackerRef.current.reportCanvasProblem(
1977
- normalizedPath,
1978
- "runtime-bootstrap",
1979
- error.message,
1980
- {
1981
- stack: error.stack,
1982
- componentStack: error.componentStack,
1983
- filename: normalizedPath
1984
- }
1985
- );
1986
- for (const pin of sourcePinsRef.current.values()) {
1987
- if (pin.canvasPath === normalizedPath)
1988
- pin.cancel(new Error(error.message));
1989
- }
1990
- },
1991
- []
1992
- );
1993
- const clearCanvasImportError = useCallback2((canvasPath) => {
1994
- const normalizedPath = canvasPath.trim();
1995
- if (!normalizedPath) return;
1996
- problemTrackerRef.current.clearCanvasProblem(normalizedPath, [
1997
- "runtime-bootstrap"
1998
- ]);
1999
- }, []);
2000
- const registerCanvasProblemScope = useCallback2(
2001
- (canvasPath) => problemTrackerRef.current.registerCanvasPath(canvasPath),
2002
- []
2003
- );
2004
- useEffect2(
2005
- () => () => {
2006
- problemTrackerRef.current.dispose();
2007
- },
2008
- []
2009
- );
2010
- useLayoutEffect2(() => {
2011
- if (typeof window === "undefined") return;
2012
- const stopRuntimeProblemTracking = installCanvasHostRuntimeProblemTracking(
2013
- problemTrackerRef.current
2014
- );
2015
- return () => {
2016
- stopRuntimeProblemTracking();
2017
- };
2018
- }, []);
2019
- useEffect2(() => {
2020
- if (typeof window === "undefined") return;
2021
- const activeWatchIds = new Set(watchRequestsById.keys());
2022
- for (const watchId of watchesRef.current.keys()) {
2023
- if (!activeWatchIds.has(watchId)) {
2024
- void stopRuntimeWatch(watchId);
2025
- }
2026
- }
2027
- for (const request of watchRequestsById.values()) {
2028
- if (request.establishment.status === "failed") continue;
2029
- const renderEntry = renderEntriesById.get(request.request.renderId);
2030
- const renderReady = renderEntry?.status === "active" && renderedRenderIdsRef.current.has(request.request.renderId) && renderRequestTargetsEntry(renderEntry, request.request);
2031
- if (!renderReady) continue;
2032
- const existing = watchesRef.current.get(request.watchId);
2033
- if (existing?.bindingKey === request.bindingKey && existing.establishment === request.establishment) {
2034
- const currentRequest = watchRequestsRef.current.get(request.watchId);
2035
- if (currentRequest?.establishment !== request.establishment) continue;
2036
- if (currentRequest.paused) setRuntimeWatchPaused(existing.watch, true);
2037
- acknowledgeWatchEstablishment(currentRequest);
2038
- continue;
2039
- }
2040
- if (!existing && request.paused) continue;
2041
- const starting = startingWatchesRef.current.get(request.watchId);
2042
- if (starting?.bindingKey === request.bindingKey && starting.establishment === request.establishment) {
2043
- continue;
2044
- }
2045
- const startToken = {
2046
- bindingKey: request.bindingKey,
2047
- establishment: request.establishment
2048
- };
2049
- startingWatchesRef.current.set(request.watchId, startToken);
2050
- void (async () => {
2051
- if (existing) {
2052
- await stopRuntimeWatch(request.watchId, existing.establishment);
2053
- }
2054
- const onUpdate = (capture) => {
2055
- const currentRequest2 = watchRequestsRef.current.get(request.watchId);
2056
- if (currentRequest2?.establishment !== request.establishment || currentRequest2.establishment.status === "failed") {
2057
- return;
2058
- }
2059
- legacyHealthRef.current.recordSourceAnnotatedCommit(
2060
- request.request.renderId
2061
- );
2062
- postToMessageSource(
2063
- request.source,
2064
- {
2065
- type: "render-pool:watch-update",
2066
- requestId: request.requestId,
2067
- watchId: request.watchId,
2068
- command: request.commandType,
2069
- payload: { capture }
2070
- },
2071
- request.targetOrigin
2072
- );
2073
- };
2074
- const onError = (error) => {
2075
- const currentRequest2 = watchRequestsRef.current.get(request.watchId);
2076
- if (currentRequest2?.establishment !== request.establishment) return;
2077
- if (currentRequest2.establishment.status === "pending") {
2078
- rejectWatchEstablishment(currentRequest2, error);
2079
- void removeWatchRequest(request.watchId, error);
2080
- return;
2081
- }
2082
- postWatchError(request, error);
2083
- };
2084
- const common = {
2085
- onUpdate,
2086
- onError,
2087
- debounceDelay: readOptionalNumber(request.payload, "debounceDelay"),
2088
- maxWait: readOptionalNumber(request.payload, "maxWait"),
2089
- timeout: readOptionalNumber(request.payload, "timeout")
2090
- };
2091
- const watch = request.commandType === "render-pool:watch-html" ? await watchStoryboardHtml(request.request.renderId, common) : await watchStoryboardCombined(request.request.renderId, {
2092
- ...common,
2093
- fiberSelector: typeof request.payload.fiberSelector === "string" ? request.payload.fiberSelector : void 0,
2094
- fiberTags: Array.isArray(request.payload.fiberTags) ? request.payload.fiberTags : void 0,
2095
- knownSourceVersion: typeof request.payload.knownSourceVersion === "object" && request.payload.knownSourceVersion !== null ? request.payload.knownSourceVersion : void 0
2096
- });
2097
- const currentRequest = watchRequestsRef.current.get(request.watchId);
2098
- if (currentRequest?.establishment !== request.establishment || currentRequest.establishment.status === "failed") {
2099
- await watch.stop();
2100
- return;
2101
- }
2102
- watchesRef.current.set(request.watchId, {
2103
- renderId: request.request.renderId,
2104
- bindingKey: request.bindingKey,
2105
- establishment: request.establishment,
2106
- watch
2107
- });
2108
- if (currentRequest.paused) {
2109
- setRuntimeWatchPaused(watch, true);
2110
- }
2111
- acknowledgeWatchEstablishment(currentRequest);
2112
- })().catch((caught) => {
2113
- const currentRequest = watchRequestsRef.current.get(request.watchId);
2114
- if (currentRequest?.establishment !== request.establishment) {
2115
- return;
2116
- }
2117
- const error = caught instanceof Error ? caught : new Error(String(caught));
2118
- if (currentRequest.establishment.status === "pending") {
2119
- rejectWatchEstablishment(currentRequest, error);
2120
- } else {
2121
- postWatchError(currentRequest, error);
2122
- }
2123
- void removeWatchRequest(request.watchId, error);
2124
- }).finally(() => {
2125
- if (startingWatchesRef.current.get(request.watchId) === startToken) {
2126
- startingWatchesRef.current.delete(request.watchId);
2127
- }
2128
- });
2129
- }
2130
- }, [
2131
- renderCommitVersionById,
2132
- renderEntriesById,
2133
- removeWatchRequest,
2134
- stopRuntimeWatch,
2135
- watchRequestsById
2136
- ]);
2137
- useEffect2(() => {
2138
- if (typeof window === "undefined") return;
2139
- runtimeIdRef.current = Array.from(
2140
- crypto.getRandomValues(new Uint32Array(4))
2141
- ).join("-");
2142
- const waitForRenderLease = async (request) => {
2143
- try {
2144
- await waitForRender(request);
2145
- } catch (caught) {
2146
- releaseRenderLease(request.renderId);
2147
- throw caught;
2148
- }
2149
- };
2150
- const withRenderLease = async (request, run) => {
2151
- await waitForRenderLease(request);
2152
- try {
2153
- return await run();
2154
- } finally {
2155
- releaseRenderLease(request.renderId);
2156
- }
2157
- };
2158
- const releaseSourcePin = (pinId) => {
2159
- const pin = sourcePinsRef.current.get(pinId);
2160
- if (!pin) return;
2161
- sourcePinsRef.current.delete(pinId);
2162
- pin.cancel(new Error(`Canvas host source pin ${pinId} was cancelled`));
2163
- forgetFreshMount(pin.renderId);
2164
- releaseRenderLease(pin.renderId, false);
2165
- };
2166
- const acquireSourcePin = (pinId, request) => {
2167
- const existing = sourcePinsRef.current.get(pinId);
2168
- if (existing) {
2169
- if (existing.renderId !== request.renderId)
2170
- throw new Error(
2171
- `Canvas host source pin ${pinId} targets another render`
2172
- );
2173
- return existing;
2174
- }
2175
- const canvasProblem = problemTrackerRef.current.snapshot().canvasProblems.find(
2176
- (entry) => entry.canvasPath === request.canvasPath
2177
- );
2178
- if (canvasProblem) throw new Error(canvasProblem.problem.message);
2179
- const committed = committedRenderEntriesRef.current.get(request.renderId);
2180
- const alreadyRendered = renderedRenderIdsRef.current.has(request.renderId) && (urlPinnedRenderIdRef.current === request.renderId || committed?.status === "active");
2181
- let resolve;
2182
- let reject;
2183
- let settled = false;
2184
- const ready = new Promise((resolveReady, rejectReady) => {
2185
- resolve = resolveReady;
2186
- reject = rejectReady;
2187
- });
2188
- const removeWaiter = () => {
2189
- const waiters = pendingRenderWaitersRef.current.get(request.renderId);
2190
- if (!waiters) return;
2191
- const remaining = waiters.filter((candidate) => candidate !== waiter);
2192
- if (remaining.length)
2193
- pendingRenderWaitersRef.current.set(request.renderId, remaining);
2194
- else pendingRenderWaitersRef.current.delete(request.renderId);
2195
- };
2196
- const waiter = {
2197
- resolve() {
2198
- if (settled) return;
2199
- settled = true;
2200
- removeWaiter();
2201
- resolve();
2202
- },
2203
- reject(error) {
2204
- if (settled) return;
2205
- settled = true;
2206
- removeWaiter();
2207
- reject(error);
2208
- }
2209
- };
2210
- const pin = {
2211
- renderId: request.renderId,
2212
- canvasPath: request.canvasPath,
2213
- ready,
2214
- cancel: waiter.reject
2215
- };
2216
- sourcePinsRef.current.set(pinId, pin);
2217
- setEntries((entries) => pinRenderSource(entries, request));
2218
- if (alreadyRendered) waiter.resolve();
2219
- else {
2220
- noteFreshMount(request.renderId);
2221
- const waiters = pendingRenderWaitersRef.current.get(request.renderId) ?? [];
2222
- pendingRenderWaitersRef.current.set(request.renderId, [
2223
- ...waiters,
2224
- waiter
2225
- ]);
2226
- }
2227
- return pin;
2228
- };
2229
- const handleCommand = (message, source, targetOrigin) => {
2230
- const command = readCanvasHostCommand(message);
2231
- if (!command) return;
2232
- const payload = command.payload;
2233
- const post = (response) => postToMessageSource(source, response, targetOrigin);
2234
- const ack = () => post({
2235
- type: "render-pool:ack",
2236
- requestId: command.requestId,
2237
- command: command.type
2238
- });
2239
- const error = (message2) => post({
2240
- type: "render-pool:error",
2241
- requestId: command.requestId,
2242
- command: command.type,
2243
- error: message2
2244
- });
2245
- const postAsyncError = (caught) => {
2246
- error(caught instanceof Error ? caught.message : String(caught));
2247
- };
2248
- const postCaptureResult = (renderId) => (capture) => {
2249
- legacyHealthRef.current.recordSourceAnnotatedCommit(renderId);
2250
- post({
2251
- type: "render-pool:capture-result",
2252
- requestId: command.requestId,
2253
- command: command.type,
2254
- payload: { capture }
2255
- });
2256
- };
2257
- try {
2258
- if (command.type === "render-pool:pin-render") {
2259
- const pinId = readPinId(command.type, payload);
2260
- const pin = acquireSourcePin(
2261
- pinId,
2262
- readRenderRequest(command.type, payload)
2263
- );
2264
- void pin.ready.then(() => {
2265
- if (sourcePinsRef.current.get(pinId) !== pin)
2266
- throw new Error(
2267
- `Canvas host source pin ${pinId} was cancelled`
2268
- );
2269
- ack();
2270
- }).catch((caught) => {
2271
- if (sourcePinsRef.current.get(pinId) === pin)
2272
- releaseSourcePin(pinId);
2273
- postAsyncError(caught);
2274
- });
2275
- return;
2276
- }
2277
- if (command.type === "render-pool:unpin-render") {
2278
- releaseSourcePin(readPinId(command.type, payload));
2279
- ack();
2280
- return;
2281
- }
2282
- if (command.type === "render-pool:capture-image") {
2283
- const captureOptions = {
2284
- captureOverflow: payload.captureOverflow === true,
2285
- childSelector: typeof payload.childSelector === "string" ? payload.childSelector : void 0,
2286
- overlaySelector: typeof payload.overlaySelector === "string" ? payload.overlaySelector : void 0,
2287
- format: payload.format === "jpeg" || payload.format === "png" ? payload.format : void 0,
2288
- quality: readOptionalNumber(payload, "quality"),
2289
- scale: readOptionalNumber(payload, "scale"),
2290
- outputPath: typeof payload.outputPath === "string" ? payload.outputPath : void 0,
2291
- forceRefresh: payload.forceRefresh === true,
2292
- portalSelectors: Array.isArray(payload.portalSelectors) ? payload.portalSelectors.filter(
2293
- (selector) => typeof selector === "string"
2294
- ) : void 0
2295
- };
2296
- if (payload.fromCanvas === true) {
2297
- const { renderId } = requireRenderTarget(command.type, payload);
2298
- void captureStoryboardImage(renderId, {
2299
- ...captureOptions,
2300
- fromCanvas: true
2301
- }).then(postCaptureResult(renderId)).catch(postAsyncError);
2302
- return;
2303
- }
2304
- const request = readRenderRequest(command.type, payload);
2305
- void withRenderLease(
2306
- request,
2307
- () => captureStoryboardImage(request.renderId, captureOptions)
2308
- ).then(postCaptureResult(request.renderId)).catch(postAsyncError);
2309
- return;
2310
- }
2311
- if (command.type === "render-pool:capture-html") {
2312
- const request = readRenderRequest(command.type, payload);
2313
- void withRenderLease(
2314
- request,
2315
- () => captureStoryboardHtml(request.renderId, {
2316
- timeout: readOptionalNumber(payload, "timeout")
2317
- })
2318
- ).then(postCaptureResult(request.renderId)).catch(postAsyncError);
2319
- return;
2320
- }
2321
- if (command.type === "render-pool:capture-combined") {
2322
- const request = readRenderRequest(command.type, payload);
2323
- void withRenderLease(
2324
- request,
2325
- () => captureStoryboardCombined(request.renderId, {
2326
- fiberSelector: typeof payload.fiberSelector === "string" ? payload.fiberSelector : void 0,
2327
- fiberTags: Array.isArray(payload.fiberTags) ? payload.fiberTags : void 0,
2328
- timeout: readOptionalNumber(payload, "timeout")
2329
- })
2330
- ).then(postCaptureResult(request.renderId)).catch(postAsyncError);
2331
- return;
2332
- }
2333
- if (command.type === "render-pool:watch-combined" || command.type === "render-pool:watch-html") {
2334
- const request = readRenderRequest(command.type, payload);
2335
- const watchId = readWatchId(command.type, payload);
2336
- void removeWatchRequest(watchId).then(() => {
2337
- setEntries((entries) => acquireRender(entries, request));
2338
- const establishment = { status: "pending" };
2339
- const watchRequest = {
2340
- commandType: command.type,
2341
- requestId: command.requestId,
2342
- watchId,
2343
- source,
2344
- targetOrigin,
2345
- request,
2346
- payload,
2347
- paused: payload.paused === true,
2348
- bindingKey: buildWatchBindingKey(command.type, payload),
2349
- establishment
2350
- };
2351
- updateWatchRequests((requests) => {
2352
- const next = new Map(requests);
2353
- next.set(watchId, watchRequest);
2354
- return next;
2355
- });
2356
- acknowledgeWatchEstablishment(watchRequest);
2357
- }).catch(postAsyncError);
2358
- return;
2359
- }
2360
- if (command.type === "render-pool:unwatch") {
2361
- const watchId = readWatchId(command.type, payload);
2362
- void removeWatchRequest(watchId).then(ack).catch(postAsyncError);
2363
- return;
2364
- }
2365
- if (command.type === "render-pool:set-watch-paused") {
2366
- const watchId = readWatchId(command.type, payload);
2367
- const paused = payload.paused === true;
2368
- const watch = watchesRef.current.get(watchId)?.watch;
2369
- if (watch) {
2370
- setRuntimeWatchPaused(
2371
- watch,
2372
- paused,
2373
- paused ? void 0 : readWatchResumeOptions(payload)
2374
- );
2375
- }
2376
- updateWatchRequests((requests) => {
2377
- const current = requests.get(watchId);
2378
- if (!current || current.paused === paused) return requests;
2379
- const next = new Map(requests);
2380
- next.set(watchId, { ...current, paused });
2381
- return next;
2382
- });
2383
- ack();
2384
- return;
2385
- }
2386
- if (command.type === "render-pool:register-canvas") {
2387
- if (!registerCanvasRef.current || typeof payload.canvasPath !== "string" || !payload.canvasPath.trim() || typeof payload.moduleUrl !== "string")
2388
- throw new Error("Invalid canvas registration command");
2389
- void registerCanvasRef.current(payload.canvasPath, payload.moduleUrl).then(ack).catch(postAsyncError);
2390
- return;
2391
- }
2392
- if (command.type === "render-pool:list") {
2393
- post({
2394
- type: "render-pool:state",
2395
- requestId: command.requestId,
2396
- payload: buildState()
2397
- });
2398
- return;
2399
- }
2400
- if (command.type === "render-pool:watch-problems") {
2401
- const watchId = typeof payload.watchId === "string" && payload.watchId.trim() ? payload.watchId : String(command.requestId ?? "default");
2402
- problemWatchersRef.current.set(watchId, {
2403
- requestId: command.requestId,
2404
- watchId,
2405
- source,
2406
- targetOrigin
2407
- });
2408
- ack();
2409
- post({
2410
- type: "render-pool:problem-snapshot",
2411
- requestId: command.requestId,
2412
- watchId,
2413
- payload: buildProblemSnapshot()
2414
- });
2415
- return;
2416
- }
2417
- if (command.type === "render-pool:unwatch-problems") {
2418
- const watchId = typeof payload.watchId === "string" && payload.watchId.trim() ? payload.watchId : String(command.requestId ?? "default");
2419
- problemWatchersRef.current.delete(watchId);
2420
- ack();
2421
- return;
2422
- }
2423
- if (command.type === "render-pool:query-problems") {
2424
- post({
2425
- type: "render-pool:problem-snapshot",
2426
- requestId: command.requestId,
2427
- payload: buildProblemSnapshot()
2428
- });
2429
- return;
2430
- }
2431
- if (command.type === "render-pool:render") {
2432
- const request = readRenderRequest(command.type, payload);
2433
- void waitForRenderLease(request).then(ack).catch(postAsyncError);
2434
- return;
2435
- }
2436
- if (command.type === "render-pool:unrender") {
2437
- const target = requireRenderTarget(command.type, payload);
2438
- releaseRenderLease(
2439
- target.renderId,
2440
- typeof payload.cacheWhenIdle === "boolean" ? payload.cacheWhenIdle : void 0
2441
- );
2442
- ack();
2443
- return;
2444
- }
2445
- if (command.type === "render-pool:capture-static-html") {
2446
- const request = readRenderRequest(command.type, payload);
2447
- void withRenderLease(
2448
- request,
2449
- () => captureStoryboardStaticHtml(request.renderId, {
2450
- timeout: readOptionalNumber(payload, "timeout")
2451
- })
2452
- ).then(postCaptureResult(request.renderId)).catch(postAsyncError);
2453
- return;
2454
- }
2455
- if (command.type === "render-pool:set-cache-limit") {
2456
- if (typeof payload.maxCached === "number" && Number.isInteger(payload.maxCached)) {
2457
- maxCachedRef.current = Math.max(0, payload.maxCached);
2458
- }
2459
- setEntries(
2460
- (entries) => evictCachedRenders(entries, maxCachedRef.current)
2461
- );
2462
- ack();
2463
- return;
2464
- }
2465
- if (command.type === "render-pool:isolate") {
2466
- applyLegacyRenderIsolation(
2467
- resolveRenderTarget(payload)?.renderId ?? null
2468
- );
2469
- ack();
2470
- return;
2471
- }
2472
- if (command.type === "render-pool:query-health") {
2473
- const renderId = resolveRenderTarget(payload)?.renderId ?? "";
2474
- post({
2475
- type: "render-pool:health-snapshot",
2476
- requestId: command.requestId,
2477
- snapshot: legacyHealthRef.current.buildSnapshot(renderId, {
2478
- hasRenderEntries: renderEntriesRef.current.size > 0,
2479
- claimErrorBoundaryTripped: problemTrackerRef.current.hasComponentProblem(renderId)
2480
- })
2481
- });
2482
- return;
2483
- }
2484
- } catch (caught) {
2485
- postAsyncError(caught);
2486
- }
2487
- };
2488
- const onMessage = (event) => handleCommand(event.data, event.source, event.origin);
2489
- const onBridgeCommand = (event) => handleCommand(event instanceof CustomEvent ? event.detail : void 0);
2490
- window.addEventListener("message", onMessage);
2491
- window.addEventListener("__render-pool:command", onBridgeCommand);
2492
- const stopProblemPublisher = problemTrackerRef.current.watch(
2493
- publishProblemSnapshot
2494
- );
2495
- window.postMessage(
2496
- { type: "render-pool:ready", runtimeId: runtimeIdRef.current },
2497
- "*"
2498
- );
2499
- return () => {
2500
- window.removeEventListener("message", onMessage);
2501
- window.removeEventListener("__render-pool:command", onBridgeCommand);
2502
- stopProblemPublisher();
2503
- for (const pinId of sourcePinsRef.current.keys()) releaseSourcePin(pinId);
2504
- for (const { watch } of watchesRef.current.values()) {
2505
- void watch.stop();
2506
- }
2507
- watchesRef.current.clear();
2508
- problemWatchersRef.current.clear();
2509
- };
2510
- }, [
2511
- buildProblemSnapshot,
2512
- buildState,
2513
- publishProblemSnapshot,
2514
- releaseRenderLease,
2515
- removeWatchRequest,
2516
- setEntries,
2517
- updateWatchRequests,
2518
- waitForRender
2519
- ]);
2520
- return {
2521
- renderStatusById: useMemo2(
2522
- () => renderStatusRef.current = buildRenderStatusMap(
2523
- renderEntriesById,
2524
- renderStatusRef.current
2525
- ),
2526
- [renderEntriesById]
2527
- ),
2528
- renderSizeById: useMemo2(
2529
- () => renderSizeRef.current = buildRenderSizeMap(
2530
- renderEntriesById,
2531
- renderSizeRef.current
2532
- ),
2533
- [renderEntriesById]
2534
- ),
2535
- markStoryboardRendered,
2536
- markStoryboardUnmounted,
2537
- reportStoryboardError,
2538
- clearStoryboardError,
2539
- reportCanvasImportError,
2540
- clearCanvasImportError,
2541
- registerCanvasProblemScope
2542
- };
2543
- }
2544
- function buildWatchBindingKey(commandType, payload) {
2545
- try {
2546
- return JSON.stringify({ commandType, payload });
2547
- } catch {
2548
- return `${commandType}:${Date.now()}`;
2549
- }
2550
- }
2551
-
2552
- // canvas/canvas-host.tsx
2553
- import { jsx as jsx2, jsxs as jsxs2 } from "react/jsx-runtime";
2554
- installTempoInteractProjectionFallback("canvas-host");
2555
- var CANVAS_HOST_DOCUMENT_TITLE = "INTERNAL tempo-host \u2014 Tempo component host, do not interact";
2556
- function protectCanvasHostDocumentTitle(doc) {
2557
- const restoreTitle = () => {
2558
- if (doc.title !== CANVAS_HOST_DOCUMENT_TITLE) {
2559
- doc.title = CANVAS_HOST_DOCUMENT_TITLE;
2560
- }
2561
- };
2562
- restoreTitle();
2563
- const Observer = doc.defaultView?.MutationObserver;
2564
- const observer = Observer ? new Observer(restoreTitle) : null;
2565
- observer?.observe(doc.head ?? doc.documentElement, {
2566
- childList: true,
2567
- subtree: true,
2568
- characterData: true
2569
- });
2570
- const interval = doc.defaultView?.setInterval(restoreTitle, 250);
2571
- return () => {
2572
- observer?.disconnect();
2573
- if (interval !== void 0) doc.defaultView?.clearInterval(interval);
2574
- };
2575
- }
2576
- function keepSharedHostUnscrolled(view) {
2577
- const reset = () => {
2578
- if (view.scrollX !== 0 || view.scrollY !== 0) {
2579
- view.scrollTo({ left: 0, top: 0, behavior: "instant" });
2580
- }
2581
- };
2582
- reset();
2583
- view.addEventListener("scroll", reset);
2584
- return () => view.removeEventListener("scroll", reset);
2585
- }
2586
- var CanvasHostContractError = class extends Error {
2587
- constructor() {
2588
- super(...arguments);
2589
- this.name = "CanvasHostContractError";
2590
- }
2591
- };
2592
- function readDirectUrlDimension(value) {
2593
- const match = value.trim().match(/^([0-9]*\.?[0-9]+)(px|vw|vh)?$/);
2594
- if (!match) {
2595
- throw new Error(
2596
- "Direct URL dimensions must be positive finite numbers, optionally with px, vw, or vh units"
2597
- );
2598
- }
2599
- const numberPart = match[1] ?? "";
2600
- const unit = match[2] ?? "";
2601
- const numberValue = Number(numberPart);
2602
- if (!numberPart || !Number.isFinite(numberValue) || numberValue <= 0) {
2603
- throw new Error(
2604
- "Direct URL dimensions must be positive finite numbers, optionally with px, vw, or vh units"
2605
- );
2606
- }
2607
- return unit && unit !== "px" ? `${numberValue}${unit}` : numberValue;
2608
- }
2609
- function readDirectUrlSize(params) {
2610
- if (isV1CanvasClient())
2611
- return v1DirectUrlSize(params, readDirectUrlDimension);
2612
- const width = params.get("width")?.trim();
2613
- const height = params.get("height")?.trim();
2614
- if (!width || !height) return { revision: 1 };
2615
- return {
2616
- width: readDirectUrlDimension(width),
2617
- height: readDirectUrlDimension(height),
2618
- revision: 1
2619
- };
2620
- }
2621
- function readDirectUrlRender() {
2622
- if (typeof window === "undefined") return null;
2623
- const params = new URLSearchParams(window.location.search);
2624
- const canvasPath = params.get("canvasPath")?.trim() ?? params.get("pageFile")?.trim() ?? params.get("importPath")?.trim() ?? "";
2625
- const storyboardId = params.get("storyboardId")?.trim() ?? params.get("exportName")?.trim() ?? params.get("importName")?.trim() ?? "";
2626
- if (!canvasPath || !storyboardId) return null;
2627
- return {
2628
- canvasPath,
2629
- renderId: getCanvasStoryboardRenderId(canvasPath, storyboardId),
2630
- size: readDirectUrlSize(params)
2631
- };
2632
- }
2633
- function subscribeDirectUrlSearch(onChange) {
2634
- window.addEventListener("popstate", onChange);
2635
- return () => window.removeEventListener("popstate", onChange);
2636
- }
2637
- function readDirectUrlSearch() {
2638
- return window.location.search;
2639
- }
2640
- function CanvasHost({
2641
- children,
2642
- canvasModules,
2643
- incremental = false,
2644
- activeStoryboardIds,
2645
- isStoryboardActive
2646
- }) {
2647
- if (children !== void 0 && canvasModules !== void 0) {
2648
- throw new CanvasHostContractError(
2649
- "CanvasHost cannot receive both children and canvasModules."
2650
- );
2651
- }
2652
- const [admitted, setAdmitted] = useState3([]);
2653
- const pendingAdmissions = useRef3(
2654
- /* @__PURE__ */ new Map()
2655
- );
2656
- const admittedRef = useRef3(admitted);
2657
- const modules = useMemo3(() => {
2658
- const all = new Map(
2659
- canvasModules?.map((module) => [module.canvasPath, module])
2660
- );
2661
- for (const module of admitted)
2662
- if (!all.has(module.canvasPath)) all.set(module.canvasPath, module);
2663
- return [...all.values()];
2664
- }, [canvasModules, admitted]);
2665
- const registerCanvas = useCallback3((canvasPath, rawUrl) => {
2666
- const url = new URL(rawUrl, window.location.href);
2667
- const isViteFsModule = url.pathname.includes("/@fs/");
2668
- if (url.origin !== window.location.origin || !isViteFsModule) {
2669
- return Promise.reject(
2670
- new Error("Canvas registration requires a same-origin Vite module URL")
2671
- );
2672
- }
2673
- if (admittedRef.current.some((module) => module.canvasPath === canvasPath))
2674
- return Promise.resolve();
2675
- return new Promise((resolve, reject) => {
2676
- const pending = pendingAdmissions.current.get(canvasPath) ?? [];
2677
- pending.push({ resolve, reject });
2678
- pendingAdmissions.current.set(canvasPath, pending);
2679
- setAdmitted(
2680
- (current) => current.some((module) => module.canvasPath === canvasPath) ? current : [
2681
- ...current,
2682
- // Vite-only registration stays a runtime import. Expo also
2683
- // bundles this shared host, and must not resolve a variable URL.
2684
- {
2685
- canvasPath,
2686
- load: () => import(
2687
- /* @vite-ignore @metro-ignore */
2688
- url.href
2689
- )
2690
- }
2691
- ]
2692
- );
2693
- });
2694
- }, []);
2695
- useLayoutEffect3(() => {
2696
- admittedRef.current = admitted;
2697
- for (const module of admitted) {
2698
- const pending = pendingAdmissions.current.get(module.canvasPath);
2699
- pendingAdmissions.current.delete(module.canvasPath);
2700
- pending?.forEach(({ resolve }) => resolve());
2701
- }
2702
- }, [admitted]);
2703
- useEffect3(
2704
- () => () => {
2705
- for (const pending of pendingAdmissions.current.values())
2706
- pending.forEach(
2707
- ({ reject }) => reject(new Error("Canvas host disposed during registration"))
2708
- );
2709
- pendingAdmissions.current.clear();
2710
- },
2711
- []
2712
- );
2713
- const directUrlSearch = useSyncExternalStore(
2714
- subscribeDirectUrlSearch,
2715
- readDirectUrlSearch,
2716
- () => ""
2717
- );
2718
- const demandRegistration = incremental && new URLSearchParams(directUrlSearch).get("canvasRegistration") === "incremental";
2719
- const registeredCanvasPaths = useMemo3(
2720
- () => [
2721
- ...new Set(
2722
- (demandRegistration ? admitted : modules).map(
2723
- ({ canvasPath }) => canvasPath.trim()
2724
- )
2725
- )
2726
- ].filter(Boolean),
2727
- [modules, admitted, demandRegistration]
2728
- );
2729
- const directUrlRender = useMemo3(() => {
2730
- return readDirectUrlRender();
2731
- }, [directUrlSearch]);
2732
- const {
2733
- renderStatusById,
2734
- renderSizeById,
2735
- markStoryboardRendered,
2736
- markStoryboardUnmounted,
2737
- reportStoryboardError,
2738
- clearStoryboardError,
2739
- reportCanvasImportError,
2740
- clearCanvasImportError,
2741
- registerCanvasProblemScope
2742
- } = useCanvasHostPostMessage(
2743
- registeredCanvasPaths,
2744
- directUrlRender?.renderId ?? null,
2745
- incremental ? registerCanvas : void 0
2746
- );
2747
- useEffect3(() => {
2748
- if (typeof document === "undefined") return;
2749
- return protectCanvasHostDocumentTitle(document);
2750
- }, []);
2751
- const isSharedHost = directUrlRender === null && !isPreV3CanvasClient();
2752
- useEffect3(() => {
2753
- if (typeof window === "undefined") return;
2754
- if (!isSharedHost) return;
2755
- return keepSharedHostUnscrolled(window);
2756
- }, [isSharedHost]);
2757
- const propActiveIds = useMemo3(
2758
- () => new Set(activeStoryboardIds ?? []),
2759
- [activeStoryboardIds]
2760
- );
2761
- const directUrlIdle = useMemo3(
2762
- () => new URLSearchParams(directUrlSearch).has("tempoCaptureIdle"),
2763
- [directUrlSearch]
2764
- );
2765
- const mountedCanvasModules = useMemo3(
2766
- () => directUrlIdle ? [] : directUrlRender ? modules.filter(
2767
- ({ canvasPath }) => canvasPath.trim() === directUrlRender.canvasPath
2768
- ) : demandRegistration ? modules.filter(
2769
- (module) => admitted.some(
2770
- (entry) => entry.canvasPath === module.canvasPath
2771
- )
2772
- ) : modules,
2773
- [modules, admitted, demandRegistration, directUrlIdle, directUrlRender]
2774
- );
2775
- const runtime = useMemo3(
2776
- () => ({
2777
- getStoryboardStatus(storyboardId) {
2778
- const normalizedId = normalizeId(storyboardId, "Storyboard id");
2779
- if (propActiveIds.has(normalizedId) || directUrlRender?.renderId === normalizedId || (isStoryboardActive ? isStoryboardActive(normalizedId) : false)) {
2780
- return "active";
2781
- }
2782
- return renderStatusById.get(normalizedId) ?? "unmounted";
2783
- },
2784
- getStoryboardSize(storyboardId) {
2785
- const normalizedId = normalizeId(storyboardId, "Storyboard id");
2786
- if (directUrlRender?.renderId === normalizedId) {
2787
- return directUrlRender.size;
2788
- }
2789
- return renderSizeById.get(normalizedId);
2790
- },
2791
- getStoryboardPlacement(storyboardId) {
2792
- const normalizedId = normalizeId(storyboardId, "Storyboard id");
2793
- return directUrlRender?.renderId === normalizedId ? { left: 0, top: 0 } : void 0;
2794
- },
2795
- prepareStoryboardCapture(storyboardId) {
2796
- if (directUrlRender?.renderId !== storyboardId) return;
2797
- const captureGlobal = globalThis;
2798
- captureGlobal.__tempoResetCaptureDeterminism?.();
2799
- },
2800
- markStoryboardRendered,
2801
- markStoryboardUnmounted,
2802
- reportStoryboardError,
2803
- clearStoryboardError,
2804
- reportCanvasImportError,
2805
- clearCanvasImportError,
2806
- registerCanvasProblemScope
2807
- }),
2808
- [
2809
- clearStoryboardError,
2810
- clearCanvasImportError,
2811
- directUrlRender,
2812
- isStoryboardActive,
2813
- markStoryboardRendered,
2814
- markStoryboardUnmounted,
2815
- propActiveIds,
2816
- registerCanvasProblemScope,
2817
- reportCanvasImportError,
2818
- reportStoryboardError,
2819
- renderSizeById,
2820
- renderStatusById
2821
- ]
2822
- );
2823
- const canvasBoundaries = useMemo3(
2824
- () => mountedCanvasModules?.map(({ canvasPath, load }) => /* @__PURE__ */ jsx2(
2825
- CanvasImportBoundary,
2826
- {
2827
- canvasPath,
2828
- load
2829
- },
2830
- canvasPath
2831
- )),
2832
- [mountedCanvasModules]
2833
- );
2834
- return /* @__PURE__ */ jsxs2(CanvasHostContext.Provider, { value: runtime, children: [
2835
- children,
2836
- canvasBoundaries
2837
- ] });
2838
- }
2839
-
2840
- // canvas/flutter-layers.ts
2841
- var FLUTTER_VIEW_ATTRIBUTE = "data-tempo-flutter-view";
2842
- var FLUTTER_REV_ATTRIBUTE = "data-tempo-flutter-rev";
2843
- var FLUTTER_SOURCE_URL = "/__tempo/flutter/__tempo_flutter_source";
2844
- var TABLE_RETRY_DELAYS_MS = [2e3, 4e3, 8e3, 16e3, 3e4];
2845
- function createFlutterLayerStore(win, options = {}) {
2846
- const sourceUrl = options.sourceUrl ?? FLUTTER_SOURCE_URL;
2847
- const roots = /* @__PURE__ */ new Map();
2848
- const views = /* @__PURE__ */ new Map();
2849
- const revisions = /* @__PURE__ */ new Map();
2850
- const tables = /* @__PURE__ */ new Map();
2851
- const held = /* @__PURE__ */ new Map();
2852
- let lastReloads = null;
2853
- let nextToken = 1;
2854
- let warnedMalformed = false;
2855
- function warnMalformed(reason) {
2856
- if (warnedMalformed) return;
2857
- warnedMalformed = true;
2858
- console.warn(`[tempo] Flutter layer snapshot dropped: ${reason}`);
2859
- }
2860
- function filesOf(snapshot) {
2861
- return new Set(snapshot.nodes.map((node) => node.file));
2862
- }
2863
- function referenced(file) {
2864
- for (const view of views.values()) {
2865
- if (filesOf(view.bridge).has(file)) return true;
2866
- }
2867
- for (const snapshot of held.values()) {
2868
- if (filesOf(snapshot).has(file)) return true;
2869
- }
2870
- return false;
2871
- }
2872
- function settled(file) {
2873
- const kind = tables.get(file)?.kind;
2874
- return kind === "ready" || kind === "missing" || kind === "failed";
2875
- }
2876
- function publishSettledHeld() {
2877
- for (const [viewId, snapshot] of held) {
2878
- if (snapshot.reloads !== lastReloads) {
2879
- held.delete(viewId);
2880
- continue;
2881
- }
2882
- if (![...filesOf(snapshot)].every(settled)) continue;
2883
- held.delete(viewId);
2884
- store(viewId, snapshot);
2885
- }
2886
- }
2887
- function convert(snapshot) {
2888
- const currentEpoch = snapshot.reloads === lastReloads;
2889
- return snapshot.nodes.map((node) => {
2890
- const entry = tables.get(node.file);
2891
- if (!currentEpoch || entry?.kind !== "ready") {
2892
- return { ...node, position: null, modifiedTs: null };
2893
- }
2894
- const lineStart = entry.table.lineStarts[node.line - 1];
2895
- if (lineStart === void 0) {
2896
- return { ...node, position: null, modifiedTs: null };
2897
- }
2898
- return {
2899
- ...node,
2900
- position: lineStart + (node.column - 1),
2901
- modifiedTs: entry.table.modifiedTs
2902
- };
2903
- });
2904
- }
2905
- function store(viewId, bridge) {
2906
- const root = roots.get(viewId);
2907
- if (!root) return;
2908
- const rev = (revisions.get(viewId) ?? 0) + 1;
2909
- revisions.set(viewId, rev);
2910
- views.set(viewId, {
2911
- bridge,
2912
- converted: { viewId, rev, nodes: convert(bridge) }
2913
- });
2914
- root.setAttribute(FLUTTER_REV_ATTRIBUTE, String(rev));
2915
- options.onPublished?.(viewId);
2916
- }
2917
- function reconvertViewsReferencing(file) {
2918
- for (const [viewId, view] of views) {
2919
- const currentEpoch = view.bridge.reloads === lastReloads;
2920
- if (currentEpoch && filesOf(view.bridge).has(file))
2921
- store(viewId, view.bridge);
2922
- }
2923
- }
2924
- function dropTables() {
2925
- for (const entry of tables.values()) {
2926
- if (entry.kind === "failed") win.clearTimeout(entry.timer);
2927
- }
2928
- tables.clear();
2929
- }
2930
- function scheduleRetry(file, attempts) {
2931
- const token = nextToken++;
2932
- const delay = TABLE_RETRY_DELAYS_MS[Math.min(attempts - 1, TABLE_RETRY_DELAYS_MS.length - 1)] ?? 3e4;
2933
- const timer = win.setTimeout(() => {
2934
- const current = tables.get(file);
2935
- if (current?.kind !== "failed" || current.token !== token) return;
2936
- if (!referenced(file)) {
2937
- tables.delete(file);
2938
- return;
2939
- }
2940
- void fetchTable(file, attempts);
2941
- }, delay);
2942
- tables.set(file, { kind: "failed", token, attempts, timer });
2943
- }
2944
- async function fetchTable(file, previousAttempts = 0) {
2945
- const token = nextToken++;
2946
- tables.set(file, { kind: "pending", token });
2947
- let entry = null;
2948
- try {
2949
- const response = await win.fetch(
2950
- `${sourceUrl}?file=${encodeURIComponent(file)}`,
2951
- { cache: "no-store" }
2952
- );
2953
- if (response.status === 404) entry = { kind: "missing" };
2954
- else if (response.ok) {
2955
- const table = readLineTable(await response.json());
2956
- if (table) entry = { kind: "ready", table };
2957
- }
2958
- } catch {
2959
- }
2960
- const current = tables.get(file);
2961
- if (current?.kind !== "pending" || current.token !== token) return;
2962
- if (entry === null) {
2963
- scheduleRetry(file, previousAttempts + 1);
2964
- } else {
2965
- tables.set(file, entry);
2966
- if (entry.kind === "ready") reconvertViewsReferencing(file);
2967
- }
2968
- publishSettledHeld();
2969
- }
2970
- function ensureTables(snapshot) {
2971
- for (const file of filesOf(snapshot)) {
2972
- if (!tables.has(file)) void fetchTable(file);
2973
- }
2974
- }
2975
- function onLayers(json) {
2976
- try {
2977
- const snapshot = readSnapshot(json);
2978
- if (!snapshot) {
2979
- warnMalformed("not a {viewId, rev, reloads, nodes[]} snapshot");
2980
- return;
2981
- }
2982
- if (!roots.has(snapshot.viewId)) return;
2983
- if (lastReloads !== null && snapshot.reloads !== lastReloads) {
2984
- dropTables();
2985
- }
2986
- lastReloads = snapshot.reloads;
2987
- ensureTables(snapshot);
2988
- const published = views.get(snapshot.viewId);
2989
- const newerEpoch = published !== void 0 && published.bridge.reloads !== lastReloads;
2990
- if (newerEpoch && ![...filesOf(snapshot)].every(settled)) {
2991
- held.set(snapshot.viewId, snapshot);
2992
- return;
2993
- }
2994
- held.delete(snapshot.viewId);
2995
- store(snapshot.viewId, snapshot);
2996
- } catch (error) {
2997
- warnMalformed(error instanceof Error ? error.message : String(error));
2998
- }
2999
- }
3000
- function viewRemoved(viewId) {
3001
- const root = roots.get(viewId);
3002
- roots.delete(viewId);
3003
- views.delete(viewId);
3004
- held.delete(viewId);
3005
- revisions.delete(viewId);
3006
- root?.removeAttribute(FLUTTER_VIEW_ATTRIBUTE);
3007
- root?.removeAttribute(FLUTTER_REV_ATTRIBUTE);
3008
- }
3009
- return {
3010
- onLayers,
3011
- get: (viewId) => views.get(viewId)?.converted,
3012
- viewAdded(viewId, viewRoot) {
3013
- roots.set(viewId, viewRoot);
3014
- viewRoot.setAttribute(FLUTTER_VIEW_ATTRIBUTE, String(viewId));
3015
- },
3016
- viewRemoved,
3017
- reset() {
3018
- for (const viewId of [...roots.keys()]) viewRemoved(viewId);
3019
- dropTables();
3020
- lastReloads = null;
3021
- }
3022
- };
3023
- }
3024
- function readSnapshot(json) {
3025
- const value = typeof json === "string" ? JSON.parse(json) : json;
3026
- if (typeof value !== "object" || value === null) return null;
3027
- const { viewId, rev, reloads, nodes } = value;
3028
- if (!Number.isInteger(viewId) || typeof rev !== "number" || typeof reloads !== "number" || !Array.isArray(nodes)) {
3029
- return null;
3030
- }
3031
- if (!nodes.every(isBridgeNode)) return null;
3032
- return {
3033
- viewId,
3034
- rev,
3035
- reloads,
3036
- nodes
3037
- };
3038
- }
3039
- function isBridgeNode(value) {
3040
- if (typeof value !== "object" || value === null) return false;
3041
- const node = value;
3042
- const numbers = [
3043
- node.line,
3044
- node.column,
3045
- node.x,
3046
- node.y,
3047
- node.width,
3048
- node.height
3049
- ];
3050
- return typeof node.id === "string" && (node.parent === null || typeof node.parent === "string") && typeof node.name === "string" && typeof node.file === "string" && typeof node.painted === "boolean" && numbers.every((n) => typeof n === "number" && Number.isFinite(n));
3051
- }
3052
- function readLineTable(value) {
3053
- if (typeof value !== "object" || value === null) return null;
3054
- const { modifiedTs, lineStarts } = value;
3055
- const validStarts = Array.isArray(lineStarts) && lineStarts.every((n) => typeof n === "number" && Number.isFinite(n));
3056
- if (!validStarts) return null;
3057
- return {
3058
- modifiedTs: typeof modifiedTs === "number" ? modifiedTs : null,
3059
- lineStarts
3060
- };
3061
- }
3062
-
3063
- // canvas/flutter-view-sizing.ts
3064
- var FLUTTER_MULTI_VIEW_SIZING_WORKAROUND = true;
3065
- var FLUTTER_SIZING_SENTINEL_PREVIEW = "__tempo_sentinel__";
3066
- var FLUTTER_SIZING_SENTINEL_ATTRIBUTE = "data-tempo-flutter-sizing-sentinel";
3067
- function createFlutterViewSizing(win, readState) {
3068
- let sentinel = null;
3069
- let refreshQueued = false;
3070
- function forgetSentinel() {
3071
- const current = sentinel;
3072
- sentinel = null;
3073
- current?.host.remove();
3074
- return current;
3075
- }
3076
- function refresh() {
3077
- refreshQueued = false;
3078
- const removed = forgetSentinel();
3079
- if (removed) {
3080
- try {
3081
- removed.app.removeView(removed.viewId);
3082
- } catch {
3083
- }
3084
- }
3085
- const { app, views } = readState();
3086
- if (!app || views.length === 0) return;
3087
- const width = Math.max(...views.map((view) => view.width));
3088
- const height = Math.max(...views.map((view) => view.height));
3089
- const host = win.document.createElement("div");
3090
- host.setAttribute(FLUTTER_SIZING_SENTINEL_ATTRIBUTE, "");
3091
- host.setAttribute("aria-hidden", "true");
3092
- host.setAttribute("data-tempo-hide-fiber", "true");
3093
- Object.assign(host.style, {
3094
- position: "absolute",
3095
- left: "-10000px",
3096
- top: "0px",
3097
- width: `${width}px`,
3098
- height: `${height}px`,
3099
- pointerEvents: "none"
3100
- });
3101
- win.document.body.append(host);
3102
- try {
3103
- const viewId = app.addView({
3104
- hostElement: host,
3105
- initialData: {
3106
- preview: FLUTTER_SIZING_SENTINEL_PREVIEW,
3107
- width,
3108
- height
3109
- }
3110
- });
3111
- sentinel = { app, viewId, host };
3112
- } catch {
3113
- host.remove();
3114
- }
3115
- }
3116
- return {
3117
- viewsChanged() {
3118
- if (refreshQueued) return;
3119
- refreshQueued = true;
3120
- queueMicrotask(refresh);
3121
- },
3122
- engineRestarted() {
3123
- forgetSentinel();
3124
- }
3125
- };
3126
- }
3127
-
3128
- // canvas/flutter-runtime.ts
3129
- var FLUTTER_BOOTSTRAP_URL = "/__tempo/flutter/flutter_bootstrap.js";
3130
- var FLUTTER_APP_EVENT = "tempo-flutter-app";
3131
- var FLUTTER_ERROR_EVENT = "tempo-flutter-error";
3132
- var BOOTSTRAP_SCRIPT_ATTRIBUTE = "data-tempo-flutter-bootstrap";
3133
- var PROBE_RETRY_DELAYS_MS = [1e3, 2e3, 4e3, 8e3];
3134
- var PROBE_TIMEOUT_MS = 1e4;
3135
- var STARTING_PROBE_INTERVAL_MS = 2e3;
3136
- var GATE_STATUS_NAME = "__tempo_flutter_status";
3137
- var SCRIPT_LOAD_BUDGET_MS = 3e4;
3138
- var EMPTY_SCENE_GRACE_MS = 1500;
3139
- var FLUTTER_LAYERS_GRACE_MS = 1e3;
3140
- var FLUTTER_DEVICE_PIXEL_RATIO = 2;
3141
- var FlutterRuntimeError = class extends Error {
3142
- constructor(code, message) {
3143
- super(`[${code}] ${message}`);
3144
- this.name = "FlutterRuntimeError";
3145
- this.code = code;
3146
- }
3147
- };
3148
- var documentRuntime = null;
3149
- function getFlutterRuntime() {
3150
- documentRuntime ?? (documentRuntime = createFlutterRuntime(window));
3151
- return documentRuntime;
3152
- }
3153
- var MODULE_IMPORT_FAILURE = /(?:Failed to fetch dynamically imported module|error loading dynamically imported module): (\S+)/i;
3154
- var FETCH_FAILURE = /Failed to fetch|NetworkError when attempting to fetch|Importing a module script failed/i;
3155
- function bootFailure(caught) {
3156
- const url = MODULE_IMPORT_FAILURE.exec(caught)?.[1];
3157
- if (url) {
3158
- return `The Flutter engine failed to start: it could not load ${url}. That is a network or asset failure, not a Dart compile error: check that this machine can reach that URL, then reload the canvas.`;
3159
- }
3160
- if (FETCH_FAILURE.test(caught)) {
3161
- return `The Flutter engine failed to start: ${caught}. That is a network or asset failure, not a Dart compile error: check that the canvas dev server is running and reachable, then reload the canvas.`;
3162
- }
3163
- return `The Flutter engine failed to start: ${caught}. Check the canvas dev server log for Dart compile errors.`;
3164
- }
3165
- function createFlutterRuntime(win, options = {}) {
3166
- const bootstrapUrl = options.bootstrapUrl ?? FLUTTER_BOOTSTRAP_URL;
3167
- const reachBudgetMs = options.reachBudgetMs ?? 6e4;
3168
- const bootBudgetMs = options.bootBudgetMs ?? 6e4;
3169
- const scriptBudgetMs = options.scriptBudgetMs ?? SCRIPT_LOAD_BUDGET_MS;
3170
- const listeners = /* @__PURE__ */ new Set();
3171
- const views = /* @__PURE__ */ new Map();
3172
- let bootstrapScript = null;
3173
- let bootstrapScriptAddedAt = 0;
3174
- let bootstrapScriptLoaded = false;
3175
- const scriptLoadingInBudget = () => bootstrapScript !== null && !bootstrapScriptLoaded && Date.now() - bootstrapScriptAddedAt < scriptBudgetMs;
3176
- const gateStatusUrl = bootstrapUrl.replace(/[^/]*$/, GATE_STATUS_NAME);
3177
- let state = { kind: "loading" };
3178
- let previewProblems = null;
3179
- let resolutionRevision;
3180
- let latestGate = null;
3181
- async function pollGate() {
3182
- const gate = await readGateStatus(win, gateStatusUrl);
3183
- if (gate) {
3184
- latestGate = gate;
3185
- if (gate.status === "failed") fail(gate.error);
3186
- if (Array.isArray(gate.previewProblems) && (gate.resolutionRevision !== resolutionRevision || previewProblems === null)) {
3187
- resolutionRevision = gate.resolutionRevision;
3188
- previewProblems = gate.previewProblems ?? [];
3189
- for (const listener of [...listeners]) listener();
3190
- emitRenderErrorRecoveryBeat();
3191
- }
3192
- }
3193
- win.setTimeout(() => {
3194
- void pollGate();
3195
- }, STARTING_PROBE_INTERVAL_MS);
3196
- }
3197
- void pollGate();
3198
- const sizing = FLUTTER_MULTI_VIEW_SIZING_WORKAROUND ? createFlutterViewSizing(win, () => ({
3199
- app: state.kind === "ready" ? state.app : null,
3200
- views: [...views.values()].map((entry) => entry.init)
3201
- })) : null;
3202
- const layers = createFlutterLayerStore(win, {
3203
- onPublished: noteLayersPublished
3204
- });
3205
- function setState(next) {
3206
- state = next;
3207
- for (const listener of [...listeners]) listener();
3208
- }
3209
- function fail(error) {
3210
- if (state.kind === "failed" && state.error.message === error.message) {
3211
- return;
3212
- }
3213
- setState({ kind: "failed", error });
3214
- }
3215
- function adoptHandoff(handoff) {
3216
- if (!isFlutterAppHandoff(handoff)) return;
3217
- const unchanged = state.kind === "ready" && state.app === handoff.app && state.generation === handoff.generation;
3218
- if (unchanged) return;
3219
- views.clear();
3220
- layers.reset();
3221
- sizing?.engineRestarted();
3222
- installFrameHook();
3223
- setState({
3224
- kind: "ready",
3225
- app: handoff.app,
3226
- generation: handoff.generation
3227
- });
3228
- }
3229
- function installFrameHook() {
3230
- const globals = win;
3231
- if (typeof globals.__tempoFlutter !== "object" || globals.__tempoFlutter === null) {
3232
- globals.__tempoFlutter = {};
3233
- }
3234
- const hooks = globals.__tempoFlutter;
3235
- hooks.devicePixelRatio = FLUTTER_DEVICE_PIXEL_RATIO;
3236
- hooks.onFrame = handleFrame;
3237
- hooks.onLayers = layers.onLayers;
3238
- hooks.layers = { get: layers.get };
3239
- hooks.wantLayers = true;
3240
- installViewPaintHook(win);
3241
- }
3242
- function handleFrame(viewIds) {
3243
- try {
3244
- const ids = viewIds === void 0 || viewIds === null ? [...views.keys()] : Array.from(viewIds, Number);
3245
- for (const id of ids) {
3246
- const entry = views.get(id);
3247
- if (entry) copyFrame(entry);
3248
- }
3249
- } catch {
3250
- }
3251
- }
3252
- function copyFrame(entry) {
3253
- let copied = false;
3254
- try {
3255
- copied = copyViewToRelay(entry);
3256
- } catch {
3257
- }
3258
- if (copied) markPainted(entry);
3259
- }
3260
- function markPainted(entry) {
3261
- if (entry.painted) return;
3262
- entry.painted = true;
3263
- win.clearTimeout(entry.emptySceneTimer);
3264
- settleContent(entry);
3265
- }
3266
- function noteLayersPublished(viewId) {
3267
- const entry = views.get(viewId);
3268
- if (!entry || entry.layersPublished) return;
3269
- entry.layersPublished = true;
3270
- settleContent(entry);
3271
- }
3272
- function settleContent(entry) {
3273
- if (!entry.painted || entry.contentReady) return;
3274
- if (entry.layersPublished) {
3275
- reportContentReady(entry);
3276
- return;
3277
- }
3278
- if (entry.layersGraceTimer !== null) return;
3279
- entry.layersGraceTimer = win.setTimeout(() => {
3280
- entry.layersGraceTimer = null;
3281
- if (views.get(entry.viewId) === entry) reportContentReady(entry);
3282
- }, FLUTTER_LAYERS_GRACE_MS);
3283
- }
3284
- function reportContentReady(entry) {
3285
- if (entry.contentReady) return;
3286
- entry.contentReady = true;
3287
- if (entry.layersGraceTimer !== null) {
3288
- win.clearTimeout(entry.layersGraceTimer);
3289
- entry.layersGraceTimer = null;
3290
- }
3291
- entry.init.onContentReady();
3292
- }
3293
- function settleEmptyScene(entry) {
3294
- if (views.get(entry.viewId) !== entry || entry.painted) return;
3295
- if (!entry.init.hostElement.querySelector("flutter-view")) return;
3296
- const relay = entry.init.relay;
3297
- const size = sizeRelay(
3298
- relay,
3299
- entry.init.width,
3300
- entry.init.height,
3301
- FLUTTER_DEVICE_PIXEL_RATIO
3302
- );
3303
- entry.context ?? (entry.context = relay.getContext("2d"));
3304
- entry.context?.clearRect(0, 0, size.width, size.height);
3305
- markPainted(entry);
3306
- }
3307
- function becomeStarting() {
3308
- if (state.kind === "ready" || state.kind === "starting") return;
3309
- if (state.kind === "loading" && scriptLoadingInBudget()) return;
3310
- setState({ kind: "starting" });
3311
- }
3312
- function becomeLoading() {
3313
- if (state.kind !== "starting" && state.kind !== "failed") return;
3314
- setState({ kind: "loading" });
3315
- }
3316
- async function loadBootstrap() {
3317
- if (bootstrapScript === null) {
3318
- bootstrapScript = injectBootstrapScript(win, bootstrapUrl);
3319
- bootstrapScriptAddedAt = Date.now();
3320
- }
3321
- const remainingMs = bootstrapScriptAddedAt + scriptBudgetMs - Date.now();
3322
- if (remainingMs > 0) becomeLoading();
3323
- const loaded = await settledWithin(
3324
- win,
3325
- bootstrapScript,
3326
- Math.max(0, remainingMs)
3327
- );
3328
- if (loaded === true) {
3329
- bootstrapScriptLoaded = true;
3330
- becomeLoading();
3331
- return "loaded";
3332
- }
3333
- if (loaded === false) {
3334
- bootstrapScript = null;
3335
- becomeStarting();
3336
- return "failed";
3337
- }
3338
- const stalledBudgetMs = scriptBudgetMs + bootBudgetMs;
3339
- if (Date.now() - bootstrapScriptAddedAt >= stalledBudgetMs) {
3340
- fail(
3341
- new FlutterRuntimeError(
3342
- "flutter_bootstrap_stalled",
3343
- `The Flutter dev server answered ${bootstrapUrl}, but the script did not finish loading within ${Math.round(stalledBudgetMs / 1e3)} s. Reload the canvas; if it persists, check the canvas dev server log.`
3344
- )
3345
- );
3346
- } else becomeStarting();
3347
- return "loading";
3348
- }
3349
- const engineReady = () => state.kind === "ready";
3350
- async function bootEngine() {
3351
- let answer = null;
3352
- let since = Date.now();
3353
- let attempt = 0;
3354
- while (!engineReady()) {
3355
- const probe = await probeBootstrap(win, bootstrapUrl);
3356
- if (engineReady()) return;
3357
- if (probe.kind === "unconfigured") {
3358
- fail(probe.error);
3359
- return;
3360
- }
3361
- if (probe.kind === "ok") {
3362
- const loaded = await loadBootstrap();
3363
- if (engineReady()) return;
3364
- if (loaded === "loaded") {
3365
- await awaitHandoff();
3366
- return;
3367
- }
3368
- }
3369
- const observed = probe.kind === "reported" ? `reported:${probe.error.code}` : probe.kind;
3370
- if (observed !== answer) {
3371
- answer = observed;
3372
- since = Date.now();
3373
- attempt = 0;
3374
- }
3375
- if (probe.kind === "starting") {
3376
- becomeStarting();
3377
- await new Promise(
3378
- (resolve) => win.setTimeout(resolve, STARTING_PROBE_INTERVAL_MS)
3379
- );
3380
- continue;
3381
- }
3382
- if (probe.kind === "unanswered" && state.kind !== "failed")
3383
- becomeStarting();
3384
- if (probe.kind === "reported") fail(probe.error);
3385
- const delay = PROBE_RETRY_DELAYS_MS[Math.min(attempt, PROBE_RETRY_DELAYS_MS.length - 1)] ?? 8e3;
3386
- attempt += 1;
3387
- const budgetSpent = Date.now() - since + delay > reachBudgetMs;
3388
- if (probe.kind === "unanswered" && budgetSpent) {
3389
- fail(
3390
- new FlutterRuntimeError(
3391
- "flutter_unreachable",
3392
- `The Flutter dev server did not answer ${bootstrapUrl} within ${Math.round(reachBudgetMs / 1e3)} s. Tempo starts Flutter when a canvas preview resolves; check the canvas dev server log (install Flutter or set TEMPO_FLUTTER_BIN if it reports flutter_sdk_missing).`
3393
- )
3394
- );
3395
- }
3396
- await new Promise((resolve) => win.setTimeout(resolve, delay));
3397
- }
3398
- }
3399
- async function awaitHandoff() {
3400
- let deadline = null;
3401
- let clockStopped = false;
3402
- const startClock = () => {
3403
- deadline = win.setTimeout(() => {
3404
- deadline = null;
3405
- if (engineReady()) return;
3406
- fail(
3407
- new FlutterRuntimeError(
3408
- "flutter_boot_timeout",
3409
- `${bootstrapUrl} loaded but the Flutter engine did not start within ${Math.round(bootBudgetMs / 1e3)} s of Flutter serving it. Check the canvas dev server log and the browser console for Dart compile errors.`
3410
- )
3411
- );
3412
- }, bootBudgetMs);
3413
- };
3414
- const stopClock = () => {
3415
- if (deadline !== null) win.clearTimeout(deadline);
3416
- deadline = null;
3417
- clockStopped = true;
3418
- };
3419
- startClock();
3420
- while (!engineReady()) {
3421
- await new Promise(
3422
- (resolve) => win.setTimeout(resolve, STARTING_PROBE_INTERVAL_MS)
3423
- );
3424
- if (engineReady()) break;
3425
- const gate = latestGate;
3426
- if (engineReady()) break;
3427
- if (gate === null) continue;
3428
- if (gate.status === "ready") {
3429
- if (!clockStopped) continue;
3430
- clockStopped = false;
3431
- becomeLoading();
3432
- startClock();
3433
- continue;
3434
- }
3435
- stopClock();
3436
- if (gate.status === "starting") becomeStarting();
3437
- if (gate.status === "failed") fail(gate.error);
3438
- }
3439
- stopClock();
3440
- }
3441
- installFrameHook();
3442
- win.addEventListener(FLUTTER_APP_EVENT, (event) => {
3443
- adoptHandoff(event.detail);
3444
- });
3445
- win.addEventListener(FLUTTER_ERROR_EVENT, (event) => {
3446
- const detail = event.detail;
3447
- const message = typeof detail?.message === "string" ? detail.message : "unknown error";
3448
- fail(new FlutterRuntimeError("flutter_boot_failed", bootFailure(message)));
3449
- });
3450
- const published = win.__tempoFlutterApp;
3451
- if (isFlutterAppHandoff(published)) adoptHandoff(published);
3452
- else void bootEngine();
3453
- return {
3454
- getState: () => state,
3455
- getPreviewProblems: () => previewProblems,
3456
- subscribe(listener) {
3457
- listeners.add(listener);
3458
- return () => {
3459
- listeners.delete(listener);
3460
- };
3461
- },
3462
- addView(init) {
3463
- if (state.kind !== "ready") {
3464
- throw state.kind === "failed" ? state.error : new Error("The Flutter engine is not ready yet.");
3465
- }
3466
- const { app } = state;
3467
- init.hostElement.replaceChildren();
3468
- const viewId = app.addView({
3469
- hostElement: init.hostElement,
3470
- initialData: {
3471
- preview: init.preview,
3472
- width: init.width,
3473
- height: init.height
3474
- }
3475
- });
3476
- const entry = {
3477
- viewId,
3478
- app,
3479
- init,
3480
- painted: false,
3481
- layersPublished: false,
3482
- contentReady: false,
3483
- context: null,
3484
- emptySceneTimer: 0,
3485
- layersGraceTimer: null
3486
- };
3487
- entry.emptySceneTimer = win.setTimeout(
3488
- () => settleEmptyScene(entry),
3489
- EMPTY_SCENE_GRACE_MS
3490
- );
3491
- views.set(viewId, entry);
3492
- layers.viewAdded(viewId, init.viewRoot);
3493
- sizing?.viewsChanged();
3494
- return entry;
3495
- },
3496
- removeView(view) {
3497
- const entry = view;
3498
- if (views.get(entry.viewId) !== entry) return;
3499
- views.delete(entry.viewId);
3500
- layers.viewRemoved(entry.viewId);
3501
- win.clearTimeout(entry.emptySceneTimer);
3502
- if (entry.layersGraceTimer !== null) {
3503
- win.clearTimeout(entry.layersGraceTimer);
3504
- }
3505
- try {
3506
- entry.app.removeView(entry.viewId);
3507
- } catch {
3508
- }
3509
- sizing?.viewsChanged();
3510
- }
3511
- };
3512
- }
3513
- function isFlutterAppHandoff(value) {
3514
- if (typeof value !== "object" || value === null) return false;
3515
- const { app, generation } = value;
3516
- return typeof generation === "number" && typeof app === "object" && app !== null && typeof app.addView === "function" && typeof app.removeView === "function";
3517
- }
3518
- async function probeBootstrap(win, url) {
3519
- const controller = new AbortController();
3520
- const timeout = win.setTimeout(() => controller.abort(), PROBE_TIMEOUT_MS);
3521
- try {
3522
- const response = await win.fetch(url, {
3523
- cache: "no-store",
3524
- signal: controller.signal
3525
- });
3526
- const contentType = response.headers.get("content-type") ?? "";
3527
- if (response.ok && contentType.includes("text/html")) {
3528
- return {
3529
- kind: "unconfigured",
3530
- error: new FlutterRuntimeError(
3531
- "flutter_not_configured",
3532
- `This canvas host has no Flutter dev server: ${url} returned the host page. Tempo enables Flutter when a canvas declares a FlutterStoryboard; a newly added board triggers one host reload.`
3533
- )
3534
- };
3535
- }
3536
- if (response.ok) return { kind: "ok" };
3537
- const body = await response.json().catch(() => null);
3538
- const code = typeof body?.error === "string" && body.error.trim() ? body.error.trim() : null;
3539
- if (code === "flutter_starting") return { kind: "starting" };
3540
- if (code && code !== "flutter_unreachable") {
3541
- const message = typeof body?.message === "string" && body.message.trim() ? body.message.trim() : `The Flutter dev server reported ${code} for ${url}.`;
3542
- return {
3543
- kind: "reported",
3544
- error: new FlutterRuntimeError(code, message)
3545
- };
3546
- }
3547
- return { kind: "unanswered" };
3548
- } catch {
3549
- return { kind: "unanswered" };
3550
- } finally {
3551
- win.clearTimeout(timeout);
3552
- }
3553
- }
3554
- async function readGateStatus(win, url) {
3555
- const controller = new AbortController();
3556
- const timeout = win.setTimeout(() => controller.abort(), PROBE_TIMEOUT_MS);
3557
- try {
3558
- const response = await win.fetch(url, {
3559
- cache: "no-store",
3560
- signal: controller.signal
3561
- });
3562
- if (!response.ok) return null;
3563
- const body = await response.json().catch(() => null);
3564
- const status = body?.status;
3565
- if (status === "failed") {
3566
- const code = typeof body.error === "string" && body.error ? body.error : "flutter_run_failed";
3567
- const message = typeof body.message === "string" && body.message.trim() ? body.message.trim() : `The Flutter dev server reported ${code}.`;
3568
- return {
3569
- status,
3570
- error: new FlutterRuntimeError(code, message),
3571
- resolutionRevision: body.resolutionRevision,
3572
- previewProblems: body.previewProblems
3573
- };
3574
- }
3575
- const known = status === "starting" || status === "ready" || status === "reloading";
3576
- return known ? {
3577
- status,
3578
- resolutionRevision: body.resolutionRevision,
3579
- previewProblems: body.previewProblems
3580
- } : null;
3581
- } catch {
3582
- return null;
3583
- } finally {
3584
- win.clearTimeout(timeout);
3585
- }
3586
- }
3587
- function injectBootstrapScript(win, url) {
3588
- const document2 = win.document;
3589
- const ran = win._flutter !== void 0;
3590
- if (ran || document2.querySelector(`script[${BOOTSTRAP_SCRIPT_ATTRIBUTE}]`)) {
3591
- return Promise.resolve(true);
3592
- }
3593
- return new Promise((resolve) => {
3594
- const script = document2.createElement("script");
3595
- script.src = url;
3596
- script.setAttribute(BOOTSTRAP_SCRIPT_ATTRIBUTE, "");
3597
- script.addEventListener("load", () => resolve(true), { once: true });
3598
- script.addEventListener(
3599
- "error",
3600
- () => {
3601
- script.remove();
3602
- resolve(false);
3603
- },
3604
- { once: true }
3605
- );
3606
- document2.head.append(script);
3607
- });
3608
- }
3609
- function settledWithin(win, promise, budgetMs) {
3610
- return new Promise((resolve) => {
3611
- const deadline = win.setTimeout(() => resolve("pending"), budgetMs);
3612
- void promise.then((value) => {
3613
- win.clearTimeout(deadline);
3614
- resolve(value);
3615
- });
3616
- });
3617
- }
3618
- var WRAPPED_FUNCTION_LINK = /* @__PURE__ */ Symbol.for(
3619
- "iframe-projection.canvas-frames.draw-tracker.inner"
3620
- );
3621
- var VIEW_PAINT_HOOK = /* @__PURE__ */ Symbol.for("tempo-sdk.flutter.view-paint-hook");
3622
- function installViewPaintHook(win) {
3623
- const prototype = win.ImageBitmapRenderingContext?.prototype;
3624
- if (!prototype || prototype[VIEW_PAINT_HOOK]) return;
3625
- const descriptor = Object.getOwnPropertyDescriptor(
3626
- prototype,
3627
- "transferFromImageBitmap"
3628
- );
3629
- const replaced = descriptor?.value;
3630
- if (typeof replaced !== "function") return;
3631
- const hook = function(bitmap) {
3632
- const result = Reflect.apply(
3633
- hook[WRAPPED_FUNCTION_LINK] ?? replaced,
3634
- this,
3635
- [bitmap]
3636
- );
3637
- reportViewPaint(win, this);
3638
- return result;
3639
- };
3640
- hook[WRAPPED_FUNCTION_LINK] = replaced;
3641
- Object.defineProperty(prototype, "transferFromImageBitmap", {
3642
- ...descriptor,
3643
- value: hook
3644
- });
3645
- Object.defineProperty(prototype, VIEW_PAINT_HOOK, { value: true });
3646
- }
3647
- function reportViewPaint(win, context) {
3648
- try {
3649
- const canvas = context.canvas;
3650
- if (typeof canvas.getRootNode !== "function") return;
3651
- const pane = canvas.getRootNode().host;
3652
- if (pane?.localName !== "flt-glass-pane") return;
3653
- const viewId = pane.closest("flutter-view")?.getAttribute("flt-view-id");
3654
- if (viewId === null || viewId === void 0) return;
3655
- const hooks = win.__tempoFlutter;
3656
- hooks?.onFrame?.([Number(viewId)]);
3657
- } catch {
3658
- }
3659
- }
3660
- function renderedPixelRatio(canvas) {
3661
- const cssWidth = Number.parseFloat(canvas.style.width);
3662
- return cssWidth > 0 ? canvas.width / cssWidth : null;
3663
- }
3664
- function isClippedByMultiViewSizingBug(entry, sources) {
3665
- const ratio = renderedPixelRatio(sources[0]);
3666
- if (ratio === null) return false;
3667
- const viewWidth = Math.round(entry.init.width * ratio);
3668
- const viewHeight = Math.round(entry.init.height * ratio);
3669
- return sources.some(
3670
- (source) => source.width < viewWidth - 1 || source.height < viewHeight - 1
3671
- );
3672
- }
3673
- function sizeRelay(relay, width, height, devicePixelRatio) {
3674
- const backingWidth = Math.max(1, Math.round(width * devicePixelRatio));
3675
- const backingHeight = Math.max(1, Math.round(height * devicePixelRatio));
3676
- if (relay.width !== backingWidth) relay.width = backingWidth;
3677
- if (relay.height !== backingHeight) relay.height = backingHeight;
3678
- const cssWidth = `${width}px`;
3679
- const cssHeight = `${height}px`;
3680
- if (relay.style.width !== cssWidth) relay.style.width = cssWidth;
3681
- if (relay.style.height !== cssHeight) relay.style.height = cssHeight;
3682
- return { width: backingWidth, height: backingHeight };
3683
- }
3684
- function copyViewToRelay(entry) {
3685
- const sources = [
3686
- ...entry.init.hostElement.querySelector("flt-glass-pane")?.shadowRoot?.querySelectorAll("canvas") ?? []
3687
- ].filter((canvas) => canvas.width > 0 && canvas.height > 0);
3688
- if (sources.length === 0) return false;
3689
- if (isClippedByMultiViewSizingBug(entry, sources)) return false;
3690
- const relay = entry.init.relay;
3691
- const size = sizeRelay(
3692
- relay,
3693
- entry.init.width,
3694
- entry.init.height,
3695
- renderedPixelRatio(sources[0]) ?? FLUTTER_DEVICE_PIXEL_RATIO
3696
- );
3697
- entry.context ?? (entry.context = relay.getContext("2d"));
3698
- const context = entry.context;
3699
- if (!context) return false;
3700
- context.clearRect(0, 0, size.width, size.height);
3701
- for (const source of sources) {
3702
- context.drawImage(
3703
- source,
3704
- 0,
3705
- 0,
3706
- size.width,
3707
- size.height,
3708
- 0,
3709
- 0,
3710
- size.width,
3711
- size.height
3712
- );
3713
- }
3714
- return true;
3715
- }
3716
-
3717
- // canvas/flutter.tsx
3718
- import { useLayoutEffect as useLayoutEffect4, useRef as useRef4, useState as useState4, useSyncExternalStore as useSyncExternalStore2 } from "react";
3719
- import { Fragment, jsx as jsx3, jsxs as jsxs3 } from "react/jsx-runtime";
3720
- function FlutterStoryboard({
3721
- id,
3722
- name,
3723
- preview,
3724
- layout,
3725
- vrt,
3726
- [FLUTTER_PREVIEW_KEY_ATTRIBUTE]: previewKey
3727
- }) {
3728
- return /* @__PURE__ */ jsx3(
3729
- StoryboardSlot,
3730
- {
3731
- "data-tempo-hide-fiber": "true",
3732
- id,
3733
- name,
3734
- layout,
3735
- kind: "component",
3736
- vrt: !!vrt,
3737
- preview,
3738
- previewKey: typeof previewKey === "string" ? previewKey : void 0,
3739
- keepLayoutWhenParked: true,
3740
- children: /* @__PURE__ */ jsx3(
3741
- FlutterViewMount,
3742
- {
3743
- id,
3744
- preview,
3745
- previewKey,
3746
- layout
3747
- }
3748
- )
3749
- }
3750
- );
3751
- }
3752
- function useFlutterViewSize(id, layout) {
3753
- const renderSize = useStoryboardSize(id);
3754
- return {
3755
- width: typeof renderSize?.width === "number" ? renderSize.width : layout.width,
3756
- height: typeof renderSize?.height === "number" ? renderSize.height : layout.height
3757
- };
3758
- }
3759
- var subscribeNowhere = () => () => {
3760
- };
3761
- var noDocument = () => null;
3762
- function useFlutterEngine(runtime) {
3763
- const state = useSyncExternalStore2(
3764
- runtime ? runtime.subscribe : subscribeNowhere,
3765
- runtime ? runtime.getState : noDocument,
3766
- noDocument
3767
- );
3768
- if (!state) return null;
3769
- return state;
3770
- }
3771
- function FlutterViewMount({
3772
- id,
3773
- preview: authoredPreview,
3774
- previewKey,
3775
- layout
3776
- }) {
3777
- const { width, height } = useFlutterViewSize(id, layout);
3778
- const runtime = typeof window === "undefined" ? null : getFlutterRuntime();
3779
- const snapshot = useSyncExternalStore2(
3780
- runtime ? runtime.subscribe : subscribeNowhere,
3781
- runtime ? () => runtime.getPreviewProblems() ?? runtime.getState() : noDocument,
3782
- noDocument
3783
- );
3784
- const problems = Array.isArray(snapshot) ? snapshot : null;
3785
- const preview = typeof previewKey === "string" ? previewKey : "";
3786
- const engineState = useFlutterEngine(runtime);
3787
- const engine = engineState?.kind === "ready" ? engineState : null;
3788
- const viewRootRef = useRef4(null);
3789
- const hostRef = useRef4(null);
3790
- const relayRef = useRef4(null);
3791
- const [mountError, setMountError] = useState4(null);
3792
- const viewKey = engine ? `${engine.generation}
3793
- ${preview}
3794
- ${width}x${height}` : null;
3795
- const [readyViewKey, setReadyViewKey] = useState4(null);
3796
- const contentReady = viewKey !== null && readyViewKey === viewKey;
3797
- const [everContentReady, setEverContentReady] = useState4(false);
3798
- const app = engine?.app;
3799
- useLayoutEffect4(() => {
3800
- const viewRoot = viewRootRef.current;
3801
- const hostElement = hostRef.current;
3802
- const relay = relayRef.current;
3803
- if (!runtime || !app || !viewRoot || !hostElement || !relay) return;
3804
- let view;
3805
- try {
3806
- view = runtime.addView({
3807
- viewRoot,
3808
- hostElement,
3809
- relay,
3810
- preview,
3811
- width,
3812
- height,
3813
- onContentReady: () => {
3814
- setReadyViewKey(viewKey);
3815
- setEverContentReady(true);
3816
- }
3817
- });
3818
- } catch (error) {
3819
- setMountError(error);
3820
- return;
3821
- }
3822
- return () => runtime.removeView(view);
3823
- }, [runtime, app, viewKey, preview, width, height]);
3824
- const parsed = parseFlutterPreview(authoredPreview);
3825
- if ("error" in parsed)
3826
- throw new FlutterRuntimeError("flutter_preview_invalid", parsed.error);
3827
- if (typeof previewKey !== "string")
3828
- throw new FlutterRuntimeError(
3829
- "flutter_preview_unresolved",
3830
- "This Flutter board's preview was not resolved by Tempo's canvas compiler; it renders only inside a Tempo canvas host."
3831
- );
3832
- const problem = problems?.find((problem2) => problem2.key === previewKey);
3833
- if (problem) throw new FlutterRuntimeError(problem.code, problem.message);
3834
- if (engineState?.kind === "failed") throw engineState.error;
3835
- if (mountError) throw mountError;
3836
- if (engineState?.kind === "loading") return /* @__PURE__ */ jsx3(CanvasPendingMarker, {});
3837
- if (engineState?.kind === "starting") return /* @__PURE__ */ jsx3(CanvasUnavailableMarker, {});
3838
- return /* @__PURE__ */ jsxs3(Fragment, { children: [
3839
- /* @__PURE__ */ jsxs3(
3840
- "div",
3841
- {
3842
- ref: viewRootRef,
3843
- "data-tempo-flutter-root": "",
3844
- ...everContentReady ? {} : { [PROJECTION_PENDING_ATTRIBUTE]: "" },
3845
- style: { position: "relative", width, height, overflow: "hidden" },
3846
- children: [
3847
- /* @__PURE__ */ jsx3(
3848
- "div",
3849
- {
3850
- ref: hostRef,
3851
- "data-tempo-flutter-host": "",
3852
- style: { position: "absolute", inset: 0 }
3853
- }
3854
- ),
3855
- /* @__PURE__ */ jsx3(FlutterRelay, { canvasRef: relayRef, width, height })
3856
- ]
3857
- }
3858
- ),
3859
- contentReady ? null : /* @__PURE__ */ jsx3(CanvasPendingMarker, {})
3860
- ] });
3861
- }
3862
- function FlutterRelay({
3863
- canvasRef,
3864
- width,
3865
- height
3866
- }) {
3867
- const [createdBox] = useState4(() => ({ width, height }));
3868
- return /* @__PURE__ */ jsx3(
3869
- "canvas",
3870
- {
3871
- ref: canvasRef,
3872
- "data-tempo-flutter-relay": "",
3873
- ...{ [CAPTURE_CANVAS_ATTRIBUTE]: "" },
3874
- "data-tempo-hide-fiber": "true",
3875
- style: {
3876
- position: "absolute",
3877
- left: 0,
3878
- top: 0,
3879
- width: createdBox.width,
3880
- height: createdBox.height,
3881
- pointerEvents: "none"
3882
- }
3883
- }
3884
- );
3885
- }
3886
- Object.assign(FlutterViewMount, { [PROJECTION_SCOPE_ROLE]: "transparent" });
3887
- Object.assign(FlutterRelay, { [PROJECTION_SCOPE_ROLE]: "transparent" });
3888
-
3889
- // canvas/host-capability.ts
3890
- var canvasHostCapability = {
3891
- protocolVersion: 1,
3892
- supportsModules: true
3893
- };
3894
- export {
3895
- CANVAS_HOST_DOCUMENT_TITLE,
3896
- Canvas,
3897
- CanvasContext,
3898
- CanvasHost,
3899
- CanvasHostContractError,
3900
- CanvasImportBoundary,
3901
- FlutterStoryboard,
3902
- HtmlStoryboard,
3903
- LegacyStoryboardV1,
3904
- RouteStoryboard,
3905
- Storyboard,
3906
- StoryboardSlot,
3907
- TEMPO_INTERACT_FRAME_NAME,
3908
- buildRenderContentFiberSelector,
3909
- buildRenderContentSelector,
3910
- buildRenderSelector,
3911
- canvasHostCapability,
3912
- captureStoryboardCombined,
3913
- captureStoryboardHtml,
3914
- captureStoryboardImage,
3915
- getCanvasHostRecoveryFeed,
3916
- getCanvasHostRuntime,
3917
- getCanvasStoryboardRenderId,
3918
- getOptionalCanvasHostRuntime,
3919
- getStoryboardKey,
3920
- isTempoInteractFrameName,
3921
- stripRenderContentWrapperAttributes,
3922
- stripRenderContentWrapperFromCombinedCapture,
3923
- useActiveState,
3924
- watchStoryboardCombined
3925
- };
3926
- //# sourceMappingURL=index.js.map
1
+ import{a as b,b as u,c as f,d as S,e as l}from"../chunk-HBQ7FFH7.js";import{a,b as n,c as p,d as c,n as e,o as s,p as C,q as y,r as i,s as r}from"../chunk-GQIOB5SV.js";import"../chunk-JRJOWLCN.js";import"../chunk-XO2BSHWM.js";import{a as d,b as m}from"../chunk-M3GN2KUH.js";import"../chunk-FH6TMWFA.js";import{a as o}from"../chunk-XUSV3KOD.js";var v="INTERNAL tempo-host \u2014 Tempo component host, do not interact";var R=o(((...t)=>r("canvas/canvas-host").CanvasHost(...t)),"CanvasHost");var H=o(((...t)=>r("canvas/canvas-host-operations").buildRenderSelector(...t)),"buildRenderSelector"),x=o(((...t)=>r("canvas/canvas-host-operations").buildRenderContentSelector(...t)),"buildRenderContentSelector"),h=o(((...t)=>r("canvas/canvas-host-operations").buildRenderContentFiberSelector(...t)),"buildRenderContentFiberSelector"),T=o(((...t)=>r("canvas/canvas-host-operations").stripRenderContentWrapperAttributes(...t)),"stripRenderContentWrapperAttributes"),F=o(((...t)=>r("canvas/canvas-host-operations").stripRenderContentWrapperFromCombinedCapture(...t)),"stripRenderContentWrapperFromCombinedCapture");var I=o(((...t)=>r("canvas/canvas-host-operations").captureStoryboardImage(...t)),"captureStoryboardImage"),g=o(((...t)=>r("canvas/canvas-host-operations").captureStoryboardHtml(...t)),"captureStoryboardHtml");var A=o(((...t)=>r("canvas/canvas-host-operations").captureStoryboardCombined(...t)),"captureStoryboardCombined");var P=o(((...t)=>r("canvas/canvas-host-operations").watchStoryboardCombined(...t)),"watchStoryboardCombined");var w=o(((...t)=>r("canvas/canvas-import-boundary").CanvasImportBoundary(...t)),"CanvasImportBoundary");var E=o(((...t)=>r("canvas/flutter").FlutterStoryboard(...t)),"FlutterStoryboard");var W={protocolVersion:1,supportsModules:!0};export{v as CANVAS_HOST_DOCUMENT_TITLE,p as Canvas,c as CanvasContext,R as CanvasHost,e as CanvasHostContractError,w as CanvasImportBoundary,E as FlutterStoryboard,S as HtmlStoryboard,u as LegacyStoryboardV1,f as RouteStoryboard,b as Storyboard,l as StoryboardSlot,d as TEMPO_INTERACT_FRAME_NAME,h as buildRenderContentFiberSelector,x as buildRenderContentSelector,H as buildRenderSelector,W as canvasHostCapability,A as captureStoryboardCombined,g as captureStoryboardHtml,I as captureStoryboardImage,y as getCanvasHostRecoveryFeed,s as getCanvasHostRuntime,n as getCanvasStoryboardRenderId,C as getOptionalCanvasHostRuntime,a as getStoryboardKey,m as isTempoInteractFrameName,T as stripRenderContentWrapperAttributes,F as stripRenderContentWrapperFromCombinedCapture,i as useActiveState,P as watchStoryboardCombined};