tempo-sdk 0.0.66 → 0.0.75

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 (110) hide show
  1. package/dist/assets/index.js +27 -5
  2. package/dist/assets/index.js.map +1 -1
  3. package/dist/astro/asset-preview-client.js +2 -2
  4. package/dist/astro.js +96 -31
  5. package/dist/astro.js.map +1 -1
  6. package/dist/canvas/astro.d.ts +1 -1
  7. package/dist/canvas/astro.js +2 -2
  8. package/dist/canvas/editor.d.ts +15 -5
  9. package/dist/canvas/editor.js +13 -8
  10. package/dist/canvas/editor.js.map +1 -1
  11. package/dist/canvas/flutter-preview.d.ts +18 -0
  12. package/dist/canvas/flutter-preview.js +9 -0
  13. package/dist/canvas/flutter-preview.js.map +1 -0
  14. package/dist/canvas/index.d.ts +33 -2
  15. package/dist/canvas/index.js +1134 -26
  16. package/dist/canvas/index.js.map +1 -1
  17. package/dist/canvas/interact-projection.js +5 -4
  18. package/dist/canvas/parser.d.ts +142 -3
  19. package/dist/canvas/parser.js +14 -1
  20. package/dist/canvas/svelte.d.ts +1 -1
  21. package/dist/canvas/svelte.js +2 -2
  22. package/dist/canvas/vue.d.ts +74 -0
  23. package/dist/canvas/vue.js +264 -0
  24. package/dist/canvas/vue.js.map +1 -0
  25. package/dist/{chunk-6W6UKDSY.js → chunk-2YX4WVFH.js} +49 -7
  26. package/dist/chunk-2YX4WVFH.js.map +1 -0
  27. package/dist/chunk-5HIIF354.js +67 -0
  28. package/dist/chunk-5HIIF354.js.map +1 -0
  29. package/dist/{chunk-FE6TYCLF.js → chunk-5VIBKVFO.js} +2 -2
  30. package/dist/{chunk-FE6TYCLF.js.map → chunk-5VIBKVFO.js.map} +1 -1
  31. package/dist/{chunk-77DZCV5Z.js → chunk-CXIW4IKC.js} +2 -2
  32. package/dist/chunk-CYQE3TLC.js +37 -0
  33. package/dist/chunk-CYQE3TLC.js.map +1 -0
  34. package/dist/{chunk-DELFOKU3.js → chunk-DNSCVLKV.js} +1571 -1410
  35. package/dist/chunk-DNSCVLKV.js.map +1 -0
  36. package/dist/chunk-EGRHWZRV.js +1 -0
  37. package/dist/chunk-EGRHWZRV.js.map +1 -0
  38. package/dist/{chunk-EYKOOLPL.js → chunk-GKDDNDG3.js} +1039 -134
  39. package/dist/chunk-GKDDNDG3.js.map +1 -0
  40. package/dist/{chunk-KOSJXE4G.js → chunk-H6BQZOAW.js} +4 -3
  41. package/dist/chunk-HOBTDB6G.js +112 -0
  42. package/dist/chunk-HOBTDB6G.js.map +1 -0
  43. package/dist/chunk-HZXQPM4W.js +285 -0
  44. package/dist/chunk-HZXQPM4W.js.map +1 -0
  45. package/dist/chunk-SGN7BDRE.js +16 -0
  46. package/dist/chunk-SGN7BDRE.js.map +1 -0
  47. package/dist/{chunk-F23JGM4U.js → chunk-UBTL6JUF.js} +6 -2
  48. package/dist/{chunk-F23JGM4U.js.map → chunk-UBTL6JUF.js.map} +1 -1
  49. package/dist/{chunk-2JRAG36X.js → chunk-WBMO4ZYO.js} +2 -2
  50. package/dist/chunk-WBMO4ZYO.js.map +1 -0
  51. package/dist/{chunk-K3EYTZLL.js → chunk-WTXOWQ7N.js} +3 -1
  52. package/dist/chunk-WTXOWQ7N.js.map +1 -0
  53. package/dist/{chunk-Q2A46HHW.js → chunk-XFPFWTWX.js} +276 -43
  54. package/dist/chunk-XFPFWTWX.js.map +1 -0
  55. package/dist/chunk-XMFVWJUY.js +342 -0
  56. package/dist/chunk-XMFVWJUY.js.map +1 -0
  57. package/dist/{chunk-PXDTH36X.js → chunk-Y72PIE3I.js} +212 -20
  58. package/dist/chunk-Y72PIE3I.js.map +1 -0
  59. package/dist/{chunk-6IR5JY6W.js → chunk-YECMP34I.js} +41 -9
  60. package/dist/chunk-YECMP34I.js.map +1 -0
  61. package/dist/{chunk-NSKYOKG5.js → chunk-ZXC7SZIT.js} +278 -26
  62. package/dist/chunk-ZXC7SZIT.js.map +1 -0
  63. package/dist/{controls-reader-SNMI2UY7.js → controls-reader-Z7OQWYWQ.js} +4 -3
  64. package/dist/{controls-reader-SNMI2UY7.js.map → controls-reader-Z7OQWYWQ.js.map} +1 -1
  65. package/dist/expo/plugin.cjs +301 -58
  66. package/dist/expo/plugin.cjs.map +1 -1
  67. package/dist/expo/plugin.js +1 -1
  68. package/dist/expo-babel-plugin.cjs +301 -58
  69. package/dist/expo-babel-plugin.cjs.map +1 -1
  70. package/dist/expo-babel-plugin.js +1 -1
  71. package/dist/flutter-preview-path.d.ts +9 -0
  72. package/dist/flutter-preview-path.js +16 -0
  73. package/dist/flutter-preview-path.js.map +1 -0
  74. package/dist/index.d.ts +16 -15
  75. package/dist/index.js +9 -6
  76. package/dist/nextjs/plugin.cjs +46 -5
  77. package/dist/nextjs/plugin.cjs.map +1 -1
  78. package/dist/nextjs/plugin.js +1 -1
  79. package/dist/nextjs-loader.cjs +343 -68
  80. package/dist/nextjs-loader.cjs.map +1 -1
  81. package/dist/nextjs.cjs +48 -6
  82. package/dist/nextjs.cjs.map +1 -1
  83. package/dist/nextjs.d.cts +9 -1
  84. package/dist/nextjs.d.ts +9 -1
  85. package/dist/nextjs.js +1 -1
  86. package/dist/nuxt/runtime/identity.d.ts +24 -0
  87. package/dist/nuxt/runtime/identity.js +18 -0
  88. package/dist/nuxt/runtime/identity.js.map +1 -0
  89. package/dist/nuxt.d.ts +102 -0
  90. package/dist/nuxt.js +5673 -0
  91. package/dist/nuxt.js.map +1 -0
  92. package/dist/{storyboard-4YdTYq_e.d.ts → storyboard-CMJVBSXn.d.ts} +9 -3
  93. package/dist/svelte.d.ts +4 -2
  94. package/dist/svelte.js +21 -88
  95. package/dist/svelte.js.map +1 -1
  96. package/dist/vue.d.ts +66 -0
  97. package/dist/vue.js +1403 -0
  98. package/dist/vue.js.map +1 -0
  99. package/package.json +48 -5
  100. package/dist/chunk-2JRAG36X.js.map +0 -1
  101. package/dist/chunk-6IR5JY6W.js.map +0 -1
  102. package/dist/chunk-6W6UKDSY.js.map +0 -1
  103. package/dist/chunk-DELFOKU3.js.map +0 -1
  104. package/dist/chunk-EYKOOLPL.js.map +0 -1
  105. package/dist/chunk-K3EYTZLL.js.map +0 -1
  106. package/dist/chunk-NSKYOKG5.js.map +0 -1
  107. package/dist/chunk-PXDTH36X.js.map +0 -1
  108. package/dist/chunk-Q2A46HHW.js.map +0 -1
  109. /package/dist/{chunk-77DZCV5Z.js.map → chunk-CXIW4IKC.js.map} +0 -0
  110. /package/dist/{chunk-KOSJXE4G.js.map → chunk-H6BQZOAW.js.map} +0 -0
@@ -1,18 +1,32 @@
1
1
  import {
2
2
  installTempoInteractProjectionSource
3
- } from "../chunk-EYKOOLPL.js";
4
- import "../chunk-2JRAG36X.js";
3
+ } from "../chunk-GKDDNDG3.js";
4
+ import "../chunk-SGN7BDRE.js";
5
+ import "../chunk-WBMO4ZYO.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";
5
17
  import {
6
18
  AdmissionBudgetError,
7
19
  Canvas,
8
20
  CanvasContext,
9
21
  CanvasHostContext,
10
22
  CanvasPendingMarker,
23
+ CanvasUnavailableMarker,
11
24
  HtmlStoryboard,
12
25
  LegacyStoryboardV1,
13
26
  RouteStoryboard,
14
27
  Storyboard,
15
28
  StoryboardSlot,
29
+ emitRenderErrorRecoveryBeat,
16
30
  getCanvasStoryboardRenderId,
17
31
  getStoryboardKey,
18
32
  getStoryboardPortalSelectors,
@@ -21,18 +35,16 @@ import {
21
35
  useActiveState,
22
36
  useRenderErrorRecovery,
23
37
  useRequiredCanvasHost,
38
+ useStoryboardSize,
24
39
  v1DirectUrlSize,
25
40
  v1RenderRequestSize
26
- } from "../chunk-6IR5JY6W.js";
27
- import "../chunk-NSKYOKG5.js";
28
- import "../chunk-6AAE4LYV.js";
41
+ } from "../chunk-YECMP34I.js";
29
42
  import {
30
- VITE_ERROR_FEED_KEY
31
- } from "../chunk-K3EYTZLL.js";
32
- import {
33
- TEMPO_INTERACT_FRAME_NAME,
34
- isTempoInteractFrameName
35
- } from "../chunk-65B52AR7.js";
43
+ PROJECTION_PENDING_ATTRIBUTE,
44
+ PROJECTION_SCOPE_ROLE,
45
+ isProjectionUnavailableOnly
46
+ } from "../chunk-ZXC7SZIT.js";
47
+ import "../chunk-6AAE4LYV.js";
36
48
 
37
49
  // canvas/canvas-host.tsx
38
50
  import {
@@ -261,6 +273,11 @@ import {
261
273
  useState as useState2
262
274
  } from "react";
263
275
 
276
+ // ../../modules/frame-pool/capture-discard.ts
277
+ function formatCaptureDiscardToken(code) {
278
+ return `[frame-pool-capture:${code}]`;
279
+ }
280
+
264
281
  // canvas/canvas-host-runtime.ts
265
282
  function getCanvasHostRuntime() {
266
283
  const runtime = window.__tempoCanvasHostRuntime;
@@ -311,7 +328,12 @@ function stripRenderContentWrapperFromCombinedCapture(capture, renderId) {
311
328
  var nextAnimationFrame = () => new Promise((resolve) => {
312
329
  requestAnimationFrame(() => resolve());
313
330
  });
331
+ var CAPTURE_CANVAS_ATTRIBUTE = "data-tempo-capture-canvas";
332
+ var contentUnavailable = (renderId, why) => new Error(
333
+ `${formatCaptureDiscardToken("content_unavailable")} storyboard ${renderId} ${why}`
334
+ );
314
335
  async function captureStoryboardImage(renderId, options) {
336
+ if (options?.fromCanvas) return captureStoryboardCanvas(renderId, options);
315
337
  const portalSelectors = [
316
338
  ...options?.portalSelectors ?? [],
317
339
  ...getStoryboardPortalSelectors(renderId)
@@ -321,11 +343,33 @@ async function captureStoryboardImage(renderId, options) {
321
343
  const captureSelector = childSelector ? `${renderSelector} ${childSelector}` : renderSelector;
322
344
  await nextAnimationFrame();
323
345
  await nextAnimationFrame();
346
+ const content = document.querySelector(buildRenderContentSelector(renderId));
347
+ if (content && isProjectionUnavailableOnly(content)) {
348
+ throw contentUnavailable(renderId, "has no content to photograph yet");
349
+ }
324
350
  return await getCanvasHostRuntime().captureSelector(
325
351
  captureSelector,
326
352
  portalSelectors.length > 0 ? { ...captureOptions, portalSelectors: [...new Set(portalSelectors)] } : captureOptions
327
353
  );
328
354
  }
355
+ async function captureStoryboardCanvas(renderId, options) {
356
+ const contentSelector = buildRenderContentSelector(renderId);
357
+ const content = document.querySelector(contentSelector);
358
+ const canvasSelector = `${contentSelector} canvas[${CAPTURE_CANVAS_ATTRIBUTE}]`;
359
+ const painted = content !== null && content.querySelector(`canvas[${CAPTURE_CANVAS_ATTRIBUTE}]`) !== null && content.querySelector(`[${PROJECTION_PENDING_ATTRIBUTE}]`) === null && !isProjectionUnavailableOnly(content);
360
+ if (!painted) throw contentUnavailable(renderId, "has no painted canvas yet");
361
+ const runtime = getCanvasHostRuntime();
362
+ if (!runtime.captureCanvas) {
363
+ throw new Error(
364
+ "This Tempo app cannot read a storyboard's canvas; update Tempo to capture this board."
365
+ );
366
+ }
367
+ return await runtime.captureCanvas(canvasSelector, {
368
+ format: options.format,
369
+ quality: options.quality,
370
+ outputPath: options.outputPath
371
+ });
372
+ }
329
373
  async function captureStoryboardHtml(renderId, options) {
330
374
  const capture = await getCanvasHostRuntime().captureHtml?.({
331
375
  selector: buildRenderContentSelector(renderId),
@@ -1618,6 +1662,10 @@ function useCanvasHostPostMessage(registeredCanvasPaths = [], urlPinnedRenderId
1618
1662
  () => /* @__PURE__ */ new Map()
1619
1663
  );
1620
1664
  const renderEntriesRef = useRef2(renderEntriesById);
1665
+ const committedRenderEntriesRef = useRef2(renderEntriesById);
1666
+ useLayoutEffect2(() => {
1667
+ committedRenderEntriesRef.current = renderEntriesById;
1668
+ }, [renderEntriesById]);
1621
1669
  const renderStatusRef = useRef2();
1622
1670
  const renderSizeRef = useRef2();
1623
1671
  const watchRequestsRef = useRef2(watchRequestsById);
@@ -1688,9 +1736,9 @@ function useCanvasHostPostMessage(registeredCanvasPaths = [], urlPinnedRenderId
1688
1736
  );
1689
1737
  const waitForRender = useCallback2(
1690
1738
  (request) => {
1691
- const current = renderEntriesRef.current.get(request.renderId);
1739
+ const committed = committedRenderEntriesRef.current.get(request.renderId);
1692
1740
  const rendered = renderedRenderIdsRef.current.has(request.renderId);
1693
- const alreadyRendered = rendered && (urlPinnedRenderIdRef.current === request.renderId || current?.status === "active" && renderRequestMatchesEntry(current, request));
1741
+ const alreadyRendered = rendered && (urlPinnedRenderIdRef.current === request.renderId || committed?.status === "active" && renderRequestMatchesEntry(committed, request));
1694
1742
  setEntries((entries) => acquireRender(entries, request));
1695
1743
  if (alreadyRendered) {
1696
1744
  return Promise.resolve();
@@ -2073,21 +2121,30 @@ function useCanvasHostPostMessage(registeredCanvasPaths = [], urlPinnedRenderId
2073
2121
  };
2074
2122
  try {
2075
2123
  if (command.type === "render-pool:capture-image") {
2124
+ const captureOptions = {
2125
+ childSelector: typeof payload.childSelector === "string" ? payload.childSelector : void 0,
2126
+ overlaySelector: typeof payload.overlaySelector === "string" ? payload.overlaySelector : void 0,
2127
+ format: payload.format === "jpeg" || payload.format === "png" ? payload.format : void 0,
2128
+ quality: readOptionalNumber(payload, "quality"),
2129
+ scale: readOptionalNumber(payload, "scale"),
2130
+ outputPath: typeof payload.outputPath === "string" ? payload.outputPath : void 0,
2131
+ forceRefresh: payload.forceRefresh === true,
2132
+ portalSelectors: Array.isArray(payload.portalSelectors) ? payload.portalSelectors.filter(
2133
+ (selector) => typeof selector === "string"
2134
+ ) : void 0
2135
+ };
2136
+ if (payload.fromCanvas === true) {
2137
+ const { renderId } = requireRenderTarget(command.type, payload);
2138
+ void captureStoryboardImage(renderId, {
2139
+ ...captureOptions,
2140
+ fromCanvas: true
2141
+ }).then(postCaptureResult(renderId)).catch(postAsyncError);
2142
+ return;
2143
+ }
2076
2144
  const request = readRenderRequest(command.type, payload);
2077
2145
  void withRenderLease(
2078
2146
  request,
2079
- () => captureStoryboardImage(request.renderId, {
2080
- childSelector: typeof payload.childSelector === "string" ? payload.childSelector : void 0,
2081
- overlaySelector: typeof payload.overlaySelector === "string" ? payload.overlaySelector : void 0,
2082
- format: payload.format === "jpeg" || payload.format === "png" ? payload.format : void 0,
2083
- quality: readOptionalNumber(payload, "quality"),
2084
- scale: readOptionalNumber(payload, "scale"),
2085
- outputPath: typeof payload.outputPath === "string" ? payload.outputPath : void 0,
2086
- forceRefresh: payload.forceRefresh === true,
2087
- portalSelectors: Array.isArray(payload.portalSelectors) ? payload.portalSelectors.filter(
2088
- (selector) => typeof selector === "string"
2089
- ) : void 0
2090
- })
2147
+ () => captureStoryboardImage(request.renderId, captureOptions)
2091
2148
  ).then(postCaptureResult(request.renderId)).catch(postAsyncError);
2092
2149
  return;
2093
2150
  }
@@ -2433,7 +2490,8 @@ function CanvasHost({
2433
2490
  }, [canvasModules, admitted]);
2434
2491
  const registerCanvas = useCallback3((canvasPath, rawUrl) => {
2435
2492
  const url = new URL(rawUrl, window.location.href);
2436
- if (url.origin !== window.location.origin || !url.pathname.startsWith("/@fs/")) {
2493
+ const isViteFsModule = url.pathname.includes("/@fs/");
2494
+ if (url.origin !== window.location.origin || !isViteFsModule) {
2437
2495
  return Promise.reject(
2438
2496
  new Error("Canvas registration requires a same-origin Vite module URL")
2439
2497
  );
@@ -2594,6 +2652,1055 @@ function CanvasHost({
2594
2652
  ] });
2595
2653
  }
2596
2654
 
2655
+ // canvas/flutter-layers.ts
2656
+ var FLUTTER_VIEW_ATTRIBUTE = "data-tempo-flutter-view";
2657
+ var FLUTTER_REV_ATTRIBUTE = "data-tempo-flutter-rev";
2658
+ var FLUTTER_SOURCE_URL = "/__tempo/flutter/__tempo_flutter_source";
2659
+ var TABLE_RETRY_DELAYS_MS = [2e3, 4e3, 8e3, 16e3, 3e4];
2660
+ function createFlutterLayerStore(win, options = {}) {
2661
+ const sourceUrl = options.sourceUrl ?? FLUTTER_SOURCE_URL;
2662
+ const roots = /* @__PURE__ */ new Map();
2663
+ const views = /* @__PURE__ */ new Map();
2664
+ const revisions = /* @__PURE__ */ new Map();
2665
+ const tables = /* @__PURE__ */ new Map();
2666
+ const held = /* @__PURE__ */ new Map();
2667
+ let lastReloads = null;
2668
+ let nextToken = 1;
2669
+ let warnedMalformed = false;
2670
+ function warnMalformed(reason) {
2671
+ if (warnedMalformed) return;
2672
+ warnedMalformed = true;
2673
+ console.warn(`[tempo] Flutter layer snapshot dropped: ${reason}`);
2674
+ }
2675
+ function filesOf(snapshot) {
2676
+ return new Set(snapshot.nodes.map((node) => node.file));
2677
+ }
2678
+ function referenced(file) {
2679
+ for (const view of views.values()) {
2680
+ if (filesOf(view.bridge).has(file)) return true;
2681
+ }
2682
+ for (const snapshot of held.values()) {
2683
+ if (filesOf(snapshot).has(file)) return true;
2684
+ }
2685
+ return false;
2686
+ }
2687
+ function settled(file) {
2688
+ const kind = tables.get(file)?.kind;
2689
+ return kind === "ready" || kind === "missing" || kind === "failed";
2690
+ }
2691
+ function publishSettledHeld() {
2692
+ for (const [viewId, snapshot] of held) {
2693
+ if (snapshot.reloads !== lastReloads) {
2694
+ held.delete(viewId);
2695
+ continue;
2696
+ }
2697
+ if (![...filesOf(snapshot)].every(settled)) continue;
2698
+ held.delete(viewId);
2699
+ store(viewId, snapshot);
2700
+ }
2701
+ }
2702
+ function convert(snapshot) {
2703
+ const currentEpoch = snapshot.reloads === lastReloads;
2704
+ return snapshot.nodes.map((node) => {
2705
+ const entry = tables.get(node.file);
2706
+ if (!currentEpoch || entry?.kind !== "ready") {
2707
+ return { ...node, position: null, modifiedTs: null };
2708
+ }
2709
+ const lineStart = entry.table.lineStarts[node.line - 1];
2710
+ if (lineStart === void 0) {
2711
+ return { ...node, position: null, modifiedTs: null };
2712
+ }
2713
+ return {
2714
+ ...node,
2715
+ position: lineStart + (node.column - 1),
2716
+ modifiedTs: entry.table.modifiedTs
2717
+ };
2718
+ });
2719
+ }
2720
+ function store(viewId, bridge) {
2721
+ const root = roots.get(viewId);
2722
+ if (!root) return;
2723
+ const rev = (revisions.get(viewId) ?? 0) + 1;
2724
+ revisions.set(viewId, rev);
2725
+ views.set(viewId, {
2726
+ bridge,
2727
+ converted: { viewId, rev, nodes: convert(bridge) }
2728
+ });
2729
+ root.setAttribute(FLUTTER_REV_ATTRIBUTE, String(rev));
2730
+ options.onPublished?.(viewId);
2731
+ }
2732
+ function reconvertViewsReferencing(file) {
2733
+ for (const [viewId, view] of views) {
2734
+ const currentEpoch = view.bridge.reloads === lastReloads;
2735
+ if (currentEpoch && filesOf(view.bridge).has(file))
2736
+ store(viewId, view.bridge);
2737
+ }
2738
+ }
2739
+ function dropTables() {
2740
+ for (const entry of tables.values()) {
2741
+ if (entry.kind === "failed") win.clearTimeout(entry.timer);
2742
+ }
2743
+ tables.clear();
2744
+ }
2745
+ function scheduleRetry(file, attempts) {
2746
+ const token = nextToken++;
2747
+ const delay = TABLE_RETRY_DELAYS_MS[Math.min(attempts - 1, TABLE_RETRY_DELAYS_MS.length - 1)] ?? 3e4;
2748
+ const timer = win.setTimeout(() => {
2749
+ const current = tables.get(file);
2750
+ if (current?.kind !== "failed" || current.token !== token) return;
2751
+ if (!referenced(file)) {
2752
+ tables.delete(file);
2753
+ return;
2754
+ }
2755
+ void fetchTable(file, attempts);
2756
+ }, delay);
2757
+ tables.set(file, { kind: "failed", token, attempts, timer });
2758
+ }
2759
+ async function fetchTable(file, previousAttempts = 0) {
2760
+ const token = nextToken++;
2761
+ tables.set(file, { kind: "pending", token });
2762
+ let entry = null;
2763
+ try {
2764
+ const response = await win.fetch(
2765
+ `${sourceUrl}?file=${encodeURIComponent(file)}`,
2766
+ { cache: "no-store" }
2767
+ );
2768
+ if (response.status === 404) entry = { kind: "missing" };
2769
+ else if (response.ok) {
2770
+ const table = readLineTable(await response.json());
2771
+ if (table) entry = { kind: "ready", table };
2772
+ }
2773
+ } catch {
2774
+ }
2775
+ const current = tables.get(file);
2776
+ if (current?.kind !== "pending" || current.token !== token) return;
2777
+ if (entry === null) {
2778
+ scheduleRetry(file, previousAttempts + 1);
2779
+ } else {
2780
+ tables.set(file, entry);
2781
+ if (entry.kind === "ready") reconvertViewsReferencing(file);
2782
+ }
2783
+ publishSettledHeld();
2784
+ }
2785
+ function ensureTables(snapshot) {
2786
+ for (const file of filesOf(snapshot)) {
2787
+ if (!tables.has(file)) void fetchTable(file);
2788
+ }
2789
+ }
2790
+ function onLayers(json) {
2791
+ try {
2792
+ const snapshot = readSnapshot(json);
2793
+ if (!snapshot) {
2794
+ warnMalformed("not a {viewId, rev, reloads, nodes[]} snapshot");
2795
+ return;
2796
+ }
2797
+ if (!roots.has(snapshot.viewId)) return;
2798
+ if (lastReloads !== null && snapshot.reloads !== lastReloads) {
2799
+ dropTables();
2800
+ }
2801
+ lastReloads = snapshot.reloads;
2802
+ ensureTables(snapshot);
2803
+ const published = views.get(snapshot.viewId);
2804
+ const newerEpoch = published !== void 0 && published.bridge.reloads !== lastReloads;
2805
+ if (newerEpoch && ![...filesOf(snapshot)].every(settled)) {
2806
+ held.set(snapshot.viewId, snapshot);
2807
+ return;
2808
+ }
2809
+ held.delete(snapshot.viewId);
2810
+ store(snapshot.viewId, snapshot);
2811
+ } catch (error) {
2812
+ warnMalformed(error instanceof Error ? error.message : String(error));
2813
+ }
2814
+ }
2815
+ function viewRemoved(viewId) {
2816
+ const root = roots.get(viewId);
2817
+ roots.delete(viewId);
2818
+ views.delete(viewId);
2819
+ held.delete(viewId);
2820
+ revisions.delete(viewId);
2821
+ root?.removeAttribute(FLUTTER_VIEW_ATTRIBUTE);
2822
+ root?.removeAttribute(FLUTTER_REV_ATTRIBUTE);
2823
+ }
2824
+ return {
2825
+ onLayers,
2826
+ get: (viewId) => views.get(viewId)?.converted,
2827
+ viewAdded(viewId, viewRoot) {
2828
+ roots.set(viewId, viewRoot);
2829
+ viewRoot.setAttribute(FLUTTER_VIEW_ATTRIBUTE, String(viewId));
2830
+ },
2831
+ viewRemoved,
2832
+ reset() {
2833
+ for (const viewId of [...roots.keys()]) viewRemoved(viewId);
2834
+ dropTables();
2835
+ lastReloads = null;
2836
+ }
2837
+ };
2838
+ }
2839
+ function readSnapshot(json) {
2840
+ const value = typeof json === "string" ? JSON.parse(json) : json;
2841
+ if (typeof value !== "object" || value === null) return null;
2842
+ const { viewId, rev, reloads, nodes } = value;
2843
+ if (!Number.isInteger(viewId) || typeof rev !== "number" || typeof reloads !== "number" || !Array.isArray(nodes)) {
2844
+ return null;
2845
+ }
2846
+ if (!nodes.every(isBridgeNode)) return null;
2847
+ return {
2848
+ viewId,
2849
+ rev,
2850
+ reloads,
2851
+ nodes
2852
+ };
2853
+ }
2854
+ function isBridgeNode(value) {
2855
+ if (typeof value !== "object" || value === null) return false;
2856
+ const node = value;
2857
+ const numbers = [
2858
+ node.line,
2859
+ node.column,
2860
+ node.x,
2861
+ node.y,
2862
+ node.width,
2863
+ node.height
2864
+ ];
2865
+ 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));
2866
+ }
2867
+ function readLineTable(value) {
2868
+ if (typeof value !== "object" || value === null) return null;
2869
+ const { modifiedTs, lineStarts } = value;
2870
+ const validStarts = Array.isArray(lineStarts) && lineStarts.every((n) => typeof n === "number" && Number.isFinite(n));
2871
+ if (!validStarts) return null;
2872
+ return {
2873
+ modifiedTs: typeof modifiedTs === "number" ? modifiedTs : null,
2874
+ lineStarts
2875
+ };
2876
+ }
2877
+
2878
+ // canvas/flutter-view-sizing.ts
2879
+ var FLUTTER_MULTI_VIEW_SIZING_WORKAROUND = true;
2880
+ var FLUTTER_SIZING_SENTINEL_PREVIEW = "__tempo_sentinel__";
2881
+ var FLUTTER_SIZING_SENTINEL_ATTRIBUTE = "data-tempo-flutter-sizing-sentinel";
2882
+ function createFlutterViewSizing(win, readState) {
2883
+ let sentinel = null;
2884
+ let refreshQueued = false;
2885
+ function forgetSentinel() {
2886
+ const current = sentinel;
2887
+ sentinel = null;
2888
+ current?.host.remove();
2889
+ return current;
2890
+ }
2891
+ function refresh() {
2892
+ refreshQueued = false;
2893
+ const removed = forgetSentinel();
2894
+ if (removed) {
2895
+ try {
2896
+ removed.app.removeView(removed.viewId);
2897
+ } catch {
2898
+ }
2899
+ }
2900
+ const { app, views } = readState();
2901
+ if (!app || views.length === 0) return;
2902
+ const width = Math.max(...views.map((view) => view.width));
2903
+ const height = Math.max(...views.map((view) => view.height));
2904
+ const host = win.document.createElement("div");
2905
+ host.setAttribute(FLUTTER_SIZING_SENTINEL_ATTRIBUTE, "");
2906
+ host.setAttribute("aria-hidden", "true");
2907
+ host.setAttribute("data-tempo-hide-fiber", "true");
2908
+ Object.assign(host.style, {
2909
+ position: "absolute",
2910
+ left: "-10000px",
2911
+ top: "0px",
2912
+ width: `${width}px`,
2913
+ height: `${height}px`,
2914
+ pointerEvents: "none"
2915
+ });
2916
+ win.document.body.append(host);
2917
+ try {
2918
+ const viewId = app.addView({
2919
+ hostElement: host,
2920
+ initialData: {
2921
+ preview: FLUTTER_SIZING_SENTINEL_PREVIEW,
2922
+ width,
2923
+ height
2924
+ }
2925
+ });
2926
+ sentinel = { app, viewId, host };
2927
+ } catch {
2928
+ host.remove();
2929
+ }
2930
+ }
2931
+ return {
2932
+ viewsChanged() {
2933
+ if (refreshQueued) return;
2934
+ refreshQueued = true;
2935
+ queueMicrotask(refresh);
2936
+ },
2937
+ engineRestarted() {
2938
+ forgetSentinel();
2939
+ }
2940
+ };
2941
+ }
2942
+
2943
+ // canvas/flutter-runtime.ts
2944
+ var FLUTTER_BOOTSTRAP_URL = "/__tempo/flutter/flutter_bootstrap.js";
2945
+ var FLUTTER_APP_EVENT = "tempo-flutter-app";
2946
+ var FLUTTER_ERROR_EVENT = "tempo-flutter-error";
2947
+ var BOOTSTRAP_SCRIPT_ATTRIBUTE = "data-tempo-flutter-bootstrap";
2948
+ var PROBE_RETRY_DELAYS_MS = [1e3, 2e3, 4e3, 8e3];
2949
+ var PROBE_TIMEOUT_MS = 1e4;
2950
+ var STARTING_PROBE_INTERVAL_MS = 2e3;
2951
+ var GATE_STATUS_NAME = "__tempo_flutter_status";
2952
+ var SCRIPT_LOAD_BUDGET_MS = 3e4;
2953
+ var EMPTY_SCENE_GRACE_MS = 1500;
2954
+ var FLUTTER_LAYERS_GRACE_MS = 1e3;
2955
+ var FLUTTER_DEVICE_PIXEL_RATIO = 2;
2956
+ var FlutterRuntimeError = class extends Error {
2957
+ constructor(code, message) {
2958
+ super(`[${code}] ${message}`);
2959
+ this.name = "FlutterRuntimeError";
2960
+ this.code = code;
2961
+ }
2962
+ };
2963
+ var documentRuntime = null;
2964
+ function getFlutterRuntime() {
2965
+ documentRuntime ?? (documentRuntime = createFlutterRuntime(window));
2966
+ return documentRuntime;
2967
+ }
2968
+ var MODULE_IMPORT_FAILURE = /(?:Failed to fetch dynamically imported module|error loading dynamically imported module): (\S+)/i;
2969
+ var FETCH_FAILURE = /Failed to fetch|NetworkError when attempting to fetch|Importing a module script failed/i;
2970
+ function bootFailure(caught) {
2971
+ const url = MODULE_IMPORT_FAILURE.exec(caught)?.[1];
2972
+ if (url) {
2973
+ 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.`;
2974
+ }
2975
+ if (FETCH_FAILURE.test(caught)) {
2976
+ 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.`;
2977
+ }
2978
+ return `The Flutter engine failed to start: ${caught}. Check the canvas dev server log for Dart compile errors.`;
2979
+ }
2980
+ function createFlutterRuntime(win, options = {}) {
2981
+ const bootstrapUrl = options.bootstrapUrl ?? FLUTTER_BOOTSTRAP_URL;
2982
+ const reachBudgetMs = options.reachBudgetMs ?? 6e4;
2983
+ const bootBudgetMs = options.bootBudgetMs ?? 6e4;
2984
+ const scriptBudgetMs = options.scriptBudgetMs ?? SCRIPT_LOAD_BUDGET_MS;
2985
+ const listeners = /* @__PURE__ */ new Set();
2986
+ const views = /* @__PURE__ */ new Map();
2987
+ let bootstrapScript = null;
2988
+ let bootstrapScriptAddedAt = 0;
2989
+ let bootstrapScriptLoaded = false;
2990
+ const scriptLoadingInBudget = () => bootstrapScript !== null && !bootstrapScriptLoaded && Date.now() - bootstrapScriptAddedAt < scriptBudgetMs;
2991
+ const gateStatusUrl = bootstrapUrl.replace(/[^/]*$/, GATE_STATUS_NAME);
2992
+ let state = { kind: "loading" };
2993
+ let previewProblems = null;
2994
+ let resolutionRevision;
2995
+ let latestGate = null;
2996
+ async function pollGate() {
2997
+ const gate = await readGateStatus(win, gateStatusUrl);
2998
+ if (gate) {
2999
+ latestGate = gate;
3000
+ if (gate.status === "failed") fail(gate.error);
3001
+ if (Array.isArray(gate.previewProblems) && (gate.resolutionRevision !== resolutionRevision || previewProblems === null)) {
3002
+ resolutionRevision = gate.resolutionRevision;
3003
+ previewProblems = gate.previewProblems ?? [];
3004
+ for (const listener of [...listeners]) listener();
3005
+ emitRenderErrorRecoveryBeat();
3006
+ }
3007
+ }
3008
+ win.setTimeout(() => {
3009
+ void pollGate();
3010
+ }, STARTING_PROBE_INTERVAL_MS);
3011
+ }
3012
+ void pollGate();
3013
+ const sizing = FLUTTER_MULTI_VIEW_SIZING_WORKAROUND ? createFlutterViewSizing(win, () => ({
3014
+ app: state.kind === "ready" ? state.app : null,
3015
+ views: [...views.values()].map((entry) => entry.init)
3016
+ })) : null;
3017
+ const layers = createFlutterLayerStore(win, {
3018
+ onPublished: noteLayersPublished
3019
+ });
3020
+ function setState(next) {
3021
+ state = next;
3022
+ for (const listener of [...listeners]) listener();
3023
+ }
3024
+ function fail(error) {
3025
+ if (state.kind === "failed" && state.error.message === error.message) {
3026
+ return;
3027
+ }
3028
+ setState({ kind: "failed", error });
3029
+ }
3030
+ function adoptHandoff(handoff) {
3031
+ if (!isFlutterAppHandoff(handoff)) return;
3032
+ const unchanged = state.kind === "ready" && state.app === handoff.app && state.generation === handoff.generation;
3033
+ if (unchanged) return;
3034
+ views.clear();
3035
+ layers.reset();
3036
+ sizing?.engineRestarted();
3037
+ installFrameHook();
3038
+ setState({
3039
+ kind: "ready",
3040
+ app: handoff.app,
3041
+ generation: handoff.generation
3042
+ });
3043
+ }
3044
+ function installFrameHook() {
3045
+ const globals = win;
3046
+ if (typeof globals.__tempoFlutter !== "object" || globals.__tempoFlutter === null) {
3047
+ globals.__tempoFlutter = {};
3048
+ }
3049
+ const hooks = globals.__tempoFlutter;
3050
+ hooks.devicePixelRatio = FLUTTER_DEVICE_PIXEL_RATIO;
3051
+ hooks.onFrame = handleFrame;
3052
+ hooks.onLayers = layers.onLayers;
3053
+ hooks.layers = { get: layers.get };
3054
+ hooks.wantLayers = true;
3055
+ installViewPaintHook(win);
3056
+ }
3057
+ function handleFrame(viewIds) {
3058
+ try {
3059
+ const ids = viewIds === void 0 || viewIds === null ? [...views.keys()] : Array.from(viewIds, Number);
3060
+ for (const id of ids) {
3061
+ const entry = views.get(id);
3062
+ if (entry) copyFrame(entry);
3063
+ }
3064
+ } catch {
3065
+ }
3066
+ }
3067
+ function copyFrame(entry) {
3068
+ let copied = false;
3069
+ try {
3070
+ copied = copyViewToRelay(entry);
3071
+ } catch {
3072
+ }
3073
+ if (copied) markPainted(entry);
3074
+ }
3075
+ function markPainted(entry) {
3076
+ if (entry.painted) return;
3077
+ entry.painted = true;
3078
+ win.clearTimeout(entry.emptySceneTimer);
3079
+ settleContent(entry);
3080
+ }
3081
+ function noteLayersPublished(viewId) {
3082
+ const entry = views.get(viewId);
3083
+ if (!entry || entry.layersPublished) return;
3084
+ entry.layersPublished = true;
3085
+ settleContent(entry);
3086
+ }
3087
+ function settleContent(entry) {
3088
+ if (!entry.painted || entry.contentReady) return;
3089
+ if (entry.layersPublished) {
3090
+ reportContentReady(entry);
3091
+ return;
3092
+ }
3093
+ if (entry.layersGraceTimer !== null) return;
3094
+ entry.layersGraceTimer = win.setTimeout(() => {
3095
+ entry.layersGraceTimer = null;
3096
+ if (views.get(entry.viewId) === entry) reportContentReady(entry);
3097
+ }, FLUTTER_LAYERS_GRACE_MS);
3098
+ }
3099
+ function reportContentReady(entry) {
3100
+ if (entry.contentReady) return;
3101
+ entry.contentReady = true;
3102
+ if (entry.layersGraceTimer !== null) {
3103
+ win.clearTimeout(entry.layersGraceTimer);
3104
+ entry.layersGraceTimer = null;
3105
+ }
3106
+ entry.init.onContentReady();
3107
+ }
3108
+ function settleEmptyScene(entry) {
3109
+ if (views.get(entry.viewId) !== entry || entry.painted) return;
3110
+ if (!entry.init.hostElement.querySelector("flutter-view")) return;
3111
+ const relay = entry.init.relay;
3112
+ const size = sizeRelay(
3113
+ relay,
3114
+ entry.init.width,
3115
+ entry.init.height,
3116
+ FLUTTER_DEVICE_PIXEL_RATIO
3117
+ );
3118
+ entry.context ?? (entry.context = relay.getContext("2d"));
3119
+ entry.context?.clearRect(0, 0, size.width, size.height);
3120
+ markPainted(entry);
3121
+ }
3122
+ function becomeStarting() {
3123
+ if (state.kind === "ready" || state.kind === "starting") return;
3124
+ if (state.kind === "loading" && scriptLoadingInBudget()) return;
3125
+ setState({ kind: "starting" });
3126
+ }
3127
+ function becomeLoading() {
3128
+ if (state.kind !== "starting" && state.kind !== "failed") return;
3129
+ setState({ kind: "loading" });
3130
+ }
3131
+ async function loadBootstrap() {
3132
+ if (bootstrapScript === null) {
3133
+ bootstrapScript = injectBootstrapScript(win, bootstrapUrl);
3134
+ bootstrapScriptAddedAt = Date.now();
3135
+ }
3136
+ const remainingMs = bootstrapScriptAddedAt + scriptBudgetMs - Date.now();
3137
+ if (remainingMs > 0) becomeLoading();
3138
+ const loaded = await settledWithin(
3139
+ win,
3140
+ bootstrapScript,
3141
+ Math.max(0, remainingMs)
3142
+ );
3143
+ if (loaded === true) {
3144
+ bootstrapScriptLoaded = true;
3145
+ becomeLoading();
3146
+ return "loaded";
3147
+ }
3148
+ if (loaded === false) {
3149
+ bootstrapScript = null;
3150
+ becomeStarting();
3151
+ return "failed";
3152
+ }
3153
+ const stalledBudgetMs = scriptBudgetMs + bootBudgetMs;
3154
+ if (Date.now() - bootstrapScriptAddedAt >= stalledBudgetMs) {
3155
+ fail(
3156
+ new FlutterRuntimeError(
3157
+ "flutter_bootstrap_stalled",
3158
+ `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.`
3159
+ )
3160
+ );
3161
+ } else becomeStarting();
3162
+ return "loading";
3163
+ }
3164
+ const engineReady = () => state.kind === "ready";
3165
+ async function bootEngine() {
3166
+ let answer = null;
3167
+ let since = Date.now();
3168
+ let attempt = 0;
3169
+ while (!engineReady()) {
3170
+ const probe = await probeBootstrap(win, bootstrapUrl);
3171
+ if (engineReady()) return;
3172
+ if (probe.kind === "unconfigured") {
3173
+ fail(probe.error);
3174
+ return;
3175
+ }
3176
+ if (probe.kind === "ok") {
3177
+ const loaded = await loadBootstrap();
3178
+ if (engineReady()) return;
3179
+ if (loaded === "loaded") {
3180
+ await awaitHandoff();
3181
+ return;
3182
+ }
3183
+ }
3184
+ const observed = probe.kind === "reported" ? `reported:${probe.error.code}` : probe.kind;
3185
+ if (observed !== answer) {
3186
+ answer = observed;
3187
+ since = Date.now();
3188
+ attempt = 0;
3189
+ }
3190
+ if (probe.kind === "starting") {
3191
+ becomeStarting();
3192
+ await new Promise(
3193
+ (resolve) => win.setTimeout(resolve, STARTING_PROBE_INTERVAL_MS)
3194
+ );
3195
+ continue;
3196
+ }
3197
+ if (probe.kind === "unanswered" && state.kind !== "failed")
3198
+ becomeStarting();
3199
+ if (probe.kind === "reported") fail(probe.error);
3200
+ const delay = PROBE_RETRY_DELAYS_MS[Math.min(attempt, PROBE_RETRY_DELAYS_MS.length - 1)] ?? 8e3;
3201
+ attempt += 1;
3202
+ const budgetSpent = Date.now() - since + delay > reachBudgetMs;
3203
+ if (probe.kind === "unanswered" && budgetSpent) {
3204
+ fail(
3205
+ new FlutterRuntimeError(
3206
+ "flutter_unreachable",
3207
+ `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).`
3208
+ )
3209
+ );
3210
+ }
3211
+ await new Promise((resolve) => win.setTimeout(resolve, delay));
3212
+ }
3213
+ }
3214
+ async function awaitHandoff() {
3215
+ let deadline = null;
3216
+ let clockStopped = false;
3217
+ const startClock = () => {
3218
+ deadline = win.setTimeout(() => {
3219
+ deadline = null;
3220
+ if (engineReady()) return;
3221
+ fail(
3222
+ new FlutterRuntimeError(
3223
+ "flutter_boot_timeout",
3224
+ `${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.`
3225
+ )
3226
+ );
3227
+ }, bootBudgetMs);
3228
+ };
3229
+ const stopClock = () => {
3230
+ if (deadline !== null) win.clearTimeout(deadline);
3231
+ deadline = null;
3232
+ clockStopped = true;
3233
+ };
3234
+ startClock();
3235
+ while (!engineReady()) {
3236
+ await new Promise(
3237
+ (resolve) => win.setTimeout(resolve, STARTING_PROBE_INTERVAL_MS)
3238
+ );
3239
+ if (engineReady()) break;
3240
+ const gate = latestGate;
3241
+ if (engineReady()) break;
3242
+ if (gate === null) continue;
3243
+ if (gate.status === "ready") {
3244
+ if (!clockStopped) continue;
3245
+ clockStopped = false;
3246
+ becomeLoading();
3247
+ startClock();
3248
+ continue;
3249
+ }
3250
+ stopClock();
3251
+ if (gate.status === "starting") becomeStarting();
3252
+ if (gate.status === "failed") fail(gate.error);
3253
+ }
3254
+ stopClock();
3255
+ }
3256
+ installFrameHook();
3257
+ win.addEventListener(FLUTTER_APP_EVENT, (event) => {
3258
+ adoptHandoff(event.detail);
3259
+ });
3260
+ win.addEventListener(FLUTTER_ERROR_EVENT, (event) => {
3261
+ const detail = event.detail;
3262
+ const message = typeof detail?.message === "string" ? detail.message : "unknown error";
3263
+ fail(new FlutterRuntimeError("flutter_boot_failed", bootFailure(message)));
3264
+ });
3265
+ const published = win.__tempoFlutterApp;
3266
+ if (isFlutterAppHandoff(published)) adoptHandoff(published);
3267
+ else void bootEngine();
3268
+ return {
3269
+ getState: () => state,
3270
+ getPreviewProblems: () => previewProblems,
3271
+ subscribe(listener) {
3272
+ listeners.add(listener);
3273
+ return () => {
3274
+ listeners.delete(listener);
3275
+ };
3276
+ },
3277
+ addView(init) {
3278
+ if (state.kind !== "ready") {
3279
+ throw state.kind === "failed" ? state.error : new Error("The Flutter engine is not ready yet.");
3280
+ }
3281
+ const { app } = state;
3282
+ init.hostElement.replaceChildren();
3283
+ const viewId = app.addView({
3284
+ hostElement: init.hostElement,
3285
+ initialData: {
3286
+ preview: init.preview,
3287
+ width: init.width,
3288
+ height: init.height
3289
+ }
3290
+ });
3291
+ const entry = {
3292
+ viewId,
3293
+ app,
3294
+ init,
3295
+ painted: false,
3296
+ layersPublished: false,
3297
+ contentReady: false,
3298
+ context: null,
3299
+ emptySceneTimer: 0,
3300
+ layersGraceTimer: null
3301
+ };
3302
+ entry.emptySceneTimer = win.setTimeout(
3303
+ () => settleEmptyScene(entry),
3304
+ EMPTY_SCENE_GRACE_MS
3305
+ );
3306
+ views.set(viewId, entry);
3307
+ layers.viewAdded(viewId, init.viewRoot);
3308
+ sizing?.viewsChanged();
3309
+ return entry;
3310
+ },
3311
+ removeView(view) {
3312
+ const entry = view;
3313
+ if (views.get(entry.viewId) !== entry) return;
3314
+ views.delete(entry.viewId);
3315
+ layers.viewRemoved(entry.viewId);
3316
+ win.clearTimeout(entry.emptySceneTimer);
3317
+ if (entry.layersGraceTimer !== null) {
3318
+ win.clearTimeout(entry.layersGraceTimer);
3319
+ }
3320
+ try {
3321
+ entry.app.removeView(entry.viewId);
3322
+ } catch {
3323
+ }
3324
+ sizing?.viewsChanged();
3325
+ }
3326
+ };
3327
+ }
3328
+ function isFlutterAppHandoff(value) {
3329
+ if (typeof value !== "object" || value === null) return false;
3330
+ const { app, generation } = value;
3331
+ return typeof generation === "number" && typeof app === "object" && app !== null && typeof app.addView === "function" && typeof app.removeView === "function";
3332
+ }
3333
+ async function probeBootstrap(win, url) {
3334
+ const controller = new AbortController();
3335
+ const timeout = win.setTimeout(() => controller.abort(), PROBE_TIMEOUT_MS);
3336
+ try {
3337
+ const response = await win.fetch(url, {
3338
+ cache: "no-store",
3339
+ signal: controller.signal
3340
+ });
3341
+ const contentType = response.headers.get("content-type") ?? "";
3342
+ if (response.ok && contentType.includes("text/html")) {
3343
+ return {
3344
+ kind: "unconfigured",
3345
+ error: new FlutterRuntimeError(
3346
+ "flutter_not_configured",
3347
+ `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.`
3348
+ )
3349
+ };
3350
+ }
3351
+ if (response.ok) return { kind: "ok" };
3352
+ const body = await response.json().catch(() => null);
3353
+ const code = typeof body?.error === "string" && body.error.trim() ? body.error.trim() : null;
3354
+ if (code === "flutter_starting") return { kind: "starting" };
3355
+ if (code && code !== "flutter_unreachable") {
3356
+ const message = typeof body?.message === "string" && body.message.trim() ? body.message.trim() : `The Flutter dev server reported ${code} for ${url}.`;
3357
+ return {
3358
+ kind: "reported",
3359
+ error: new FlutterRuntimeError(code, message)
3360
+ };
3361
+ }
3362
+ return { kind: "unanswered" };
3363
+ } catch {
3364
+ return { kind: "unanswered" };
3365
+ } finally {
3366
+ win.clearTimeout(timeout);
3367
+ }
3368
+ }
3369
+ async function readGateStatus(win, url) {
3370
+ const controller = new AbortController();
3371
+ const timeout = win.setTimeout(() => controller.abort(), PROBE_TIMEOUT_MS);
3372
+ try {
3373
+ const response = await win.fetch(url, {
3374
+ cache: "no-store",
3375
+ signal: controller.signal
3376
+ });
3377
+ if (!response.ok) return null;
3378
+ const body = await response.json().catch(() => null);
3379
+ const status = body?.status;
3380
+ if (status === "failed") {
3381
+ const code = typeof body.error === "string" && body.error ? body.error : "flutter_run_failed";
3382
+ const message = typeof body.message === "string" && body.message.trim() ? body.message.trim() : `The Flutter dev server reported ${code}.`;
3383
+ return {
3384
+ status,
3385
+ error: new FlutterRuntimeError(code, message),
3386
+ resolutionRevision: body.resolutionRevision,
3387
+ previewProblems: body.previewProblems
3388
+ };
3389
+ }
3390
+ const known = status === "starting" || status === "ready" || status === "reloading";
3391
+ return known ? {
3392
+ status,
3393
+ resolutionRevision: body.resolutionRevision,
3394
+ previewProblems: body.previewProblems
3395
+ } : null;
3396
+ } catch {
3397
+ return null;
3398
+ } finally {
3399
+ win.clearTimeout(timeout);
3400
+ }
3401
+ }
3402
+ function injectBootstrapScript(win, url) {
3403
+ const document2 = win.document;
3404
+ const ran = win._flutter !== void 0;
3405
+ if (ran || document2.querySelector(`script[${BOOTSTRAP_SCRIPT_ATTRIBUTE}]`)) {
3406
+ return Promise.resolve(true);
3407
+ }
3408
+ return new Promise((resolve) => {
3409
+ const script = document2.createElement("script");
3410
+ script.src = url;
3411
+ script.setAttribute(BOOTSTRAP_SCRIPT_ATTRIBUTE, "");
3412
+ script.addEventListener("load", () => resolve(true), { once: true });
3413
+ script.addEventListener(
3414
+ "error",
3415
+ () => {
3416
+ script.remove();
3417
+ resolve(false);
3418
+ },
3419
+ { once: true }
3420
+ );
3421
+ document2.head.append(script);
3422
+ });
3423
+ }
3424
+ function settledWithin(win, promise, budgetMs) {
3425
+ return new Promise((resolve) => {
3426
+ const deadline = win.setTimeout(() => resolve("pending"), budgetMs);
3427
+ void promise.then((value) => {
3428
+ win.clearTimeout(deadline);
3429
+ resolve(value);
3430
+ });
3431
+ });
3432
+ }
3433
+ var WRAPPED_FUNCTION_LINK = /* @__PURE__ */ Symbol.for(
3434
+ "iframe-projection.canvas-frames.draw-tracker.inner"
3435
+ );
3436
+ var VIEW_PAINT_HOOK = /* @__PURE__ */ Symbol.for("tempo-sdk.flutter.view-paint-hook");
3437
+ function installViewPaintHook(win) {
3438
+ const prototype = win.ImageBitmapRenderingContext?.prototype;
3439
+ if (!prototype || prototype[VIEW_PAINT_HOOK]) return;
3440
+ const descriptor = Object.getOwnPropertyDescriptor(
3441
+ prototype,
3442
+ "transferFromImageBitmap"
3443
+ );
3444
+ const replaced = descriptor?.value;
3445
+ if (typeof replaced !== "function") return;
3446
+ const hook = function(bitmap) {
3447
+ const result = Reflect.apply(
3448
+ hook[WRAPPED_FUNCTION_LINK] ?? replaced,
3449
+ this,
3450
+ [bitmap]
3451
+ );
3452
+ reportViewPaint(win, this);
3453
+ return result;
3454
+ };
3455
+ hook[WRAPPED_FUNCTION_LINK] = replaced;
3456
+ Object.defineProperty(prototype, "transferFromImageBitmap", {
3457
+ ...descriptor,
3458
+ value: hook
3459
+ });
3460
+ Object.defineProperty(prototype, VIEW_PAINT_HOOK, { value: true });
3461
+ }
3462
+ function reportViewPaint(win, context) {
3463
+ try {
3464
+ const canvas = context.canvas;
3465
+ if (typeof canvas.getRootNode !== "function") return;
3466
+ const pane = canvas.getRootNode().host;
3467
+ if (pane?.localName !== "flt-glass-pane") return;
3468
+ const viewId = pane.closest("flutter-view")?.getAttribute("flt-view-id");
3469
+ if (viewId === null || viewId === void 0) return;
3470
+ const hooks = win.__tempoFlutter;
3471
+ hooks?.onFrame?.([Number(viewId)]);
3472
+ } catch {
3473
+ }
3474
+ }
3475
+ function renderedPixelRatio(canvas) {
3476
+ const cssWidth = Number.parseFloat(canvas.style.width);
3477
+ return cssWidth > 0 ? canvas.width / cssWidth : null;
3478
+ }
3479
+ function isClippedByMultiViewSizingBug(entry, sources) {
3480
+ const ratio = renderedPixelRatio(sources[0]);
3481
+ if (ratio === null) return false;
3482
+ const viewWidth = Math.round(entry.init.width * ratio);
3483
+ const viewHeight = Math.round(entry.init.height * ratio);
3484
+ return sources.some(
3485
+ (source) => source.width < viewWidth - 1 || source.height < viewHeight - 1
3486
+ );
3487
+ }
3488
+ function sizeRelay(relay, width, height, devicePixelRatio) {
3489
+ const backingWidth = Math.max(1, Math.round(width * devicePixelRatio));
3490
+ const backingHeight = Math.max(1, Math.round(height * devicePixelRatio));
3491
+ if (relay.width !== backingWidth) relay.width = backingWidth;
3492
+ if (relay.height !== backingHeight) relay.height = backingHeight;
3493
+ const cssWidth = `${width}px`;
3494
+ const cssHeight = `${height}px`;
3495
+ if (relay.style.width !== cssWidth) relay.style.width = cssWidth;
3496
+ if (relay.style.height !== cssHeight) relay.style.height = cssHeight;
3497
+ return { width: backingWidth, height: backingHeight };
3498
+ }
3499
+ function copyViewToRelay(entry) {
3500
+ const sources = [
3501
+ ...entry.init.hostElement.querySelector("flt-glass-pane")?.shadowRoot?.querySelectorAll("canvas") ?? []
3502
+ ].filter((canvas) => canvas.width > 0 && canvas.height > 0);
3503
+ if (sources.length === 0) return false;
3504
+ if (isClippedByMultiViewSizingBug(entry, sources)) return false;
3505
+ const relay = entry.init.relay;
3506
+ const size = sizeRelay(
3507
+ relay,
3508
+ entry.init.width,
3509
+ entry.init.height,
3510
+ renderedPixelRatio(sources[0]) ?? FLUTTER_DEVICE_PIXEL_RATIO
3511
+ );
3512
+ entry.context ?? (entry.context = relay.getContext("2d"));
3513
+ const context = entry.context;
3514
+ if (!context) return false;
3515
+ context.clearRect(0, 0, size.width, size.height);
3516
+ for (const source of sources) {
3517
+ context.drawImage(
3518
+ source,
3519
+ 0,
3520
+ 0,
3521
+ size.width,
3522
+ size.height,
3523
+ 0,
3524
+ 0,
3525
+ size.width,
3526
+ size.height
3527
+ );
3528
+ }
3529
+ return true;
3530
+ }
3531
+
3532
+ // canvas/flutter.tsx
3533
+ import { useLayoutEffect as useLayoutEffect4, useRef as useRef4, useState as useState4, useSyncExternalStore as useSyncExternalStore2 } from "react";
3534
+ import { Fragment, jsx as jsx3, jsxs as jsxs3 } from "react/jsx-runtime";
3535
+ function FlutterStoryboard({
3536
+ id,
3537
+ name,
3538
+ preview,
3539
+ layout,
3540
+ vrt,
3541
+ [FLUTTER_PREVIEW_KEY_ATTRIBUTE]: previewKey
3542
+ }) {
3543
+ return /* @__PURE__ */ jsx3(
3544
+ StoryboardSlot,
3545
+ {
3546
+ "data-tempo-hide-fiber": "true",
3547
+ id,
3548
+ name,
3549
+ layout,
3550
+ kind: "component",
3551
+ vrt: !!vrt,
3552
+ preview,
3553
+ previewKey: typeof previewKey === "string" ? previewKey : void 0,
3554
+ keepLayoutWhenParked: true,
3555
+ children: /* @__PURE__ */ jsx3(
3556
+ FlutterViewMount,
3557
+ {
3558
+ id,
3559
+ preview,
3560
+ previewKey,
3561
+ layout
3562
+ }
3563
+ )
3564
+ }
3565
+ );
3566
+ }
3567
+ function useFlutterViewSize(id, layout) {
3568
+ const renderSize = useStoryboardSize(id);
3569
+ return {
3570
+ width: typeof renderSize?.width === "number" ? renderSize.width : layout.width,
3571
+ height: typeof renderSize?.height === "number" ? renderSize.height : layout.height
3572
+ };
3573
+ }
3574
+ var subscribeNowhere = () => () => {
3575
+ };
3576
+ var noDocument = () => null;
3577
+ function useFlutterEngine(runtime) {
3578
+ const state = useSyncExternalStore2(
3579
+ runtime ? runtime.subscribe : subscribeNowhere,
3580
+ runtime ? runtime.getState : noDocument,
3581
+ noDocument
3582
+ );
3583
+ if (!state) return null;
3584
+ return state;
3585
+ }
3586
+ function FlutterViewMount({
3587
+ id,
3588
+ preview: authoredPreview,
3589
+ previewKey,
3590
+ layout
3591
+ }) {
3592
+ const { width, height } = useFlutterViewSize(id, layout);
3593
+ const runtime = typeof window === "undefined" ? null : getFlutterRuntime();
3594
+ const snapshot = useSyncExternalStore2(
3595
+ runtime ? runtime.subscribe : subscribeNowhere,
3596
+ runtime ? () => runtime.getPreviewProblems() ?? runtime.getState() : noDocument,
3597
+ noDocument
3598
+ );
3599
+ const problems = Array.isArray(snapshot) ? snapshot : null;
3600
+ const preview = typeof previewKey === "string" ? previewKey : "";
3601
+ const engineState = useFlutterEngine(runtime);
3602
+ const engine = engineState?.kind === "ready" ? engineState : null;
3603
+ const viewRootRef = useRef4(null);
3604
+ const hostRef = useRef4(null);
3605
+ const relayRef = useRef4(null);
3606
+ const [mountError, setMountError] = useState4(null);
3607
+ const viewKey = engine ? `${engine.generation}
3608
+ ${preview}
3609
+ ${width}x${height}` : null;
3610
+ const [readyViewKey, setReadyViewKey] = useState4(null);
3611
+ const contentReady = viewKey !== null && readyViewKey === viewKey;
3612
+ const [everContentReady, setEverContentReady] = useState4(false);
3613
+ const app = engine?.app;
3614
+ useLayoutEffect4(() => {
3615
+ const viewRoot = viewRootRef.current;
3616
+ const hostElement = hostRef.current;
3617
+ const relay = relayRef.current;
3618
+ if (!runtime || !app || !viewRoot || !hostElement || !relay) return;
3619
+ let view;
3620
+ try {
3621
+ view = runtime.addView({
3622
+ viewRoot,
3623
+ hostElement,
3624
+ relay,
3625
+ preview,
3626
+ width,
3627
+ height,
3628
+ onContentReady: () => {
3629
+ setReadyViewKey(viewKey);
3630
+ setEverContentReady(true);
3631
+ }
3632
+ });
3633
+ } catch (error) {
3634
+ setMountError(error);
3635
+ return;
3636
+ }
3637
+ return () => runtime.removeView(view);
3638
+ }, [runtime, app, viewKey, preview, width, height]);
3639
+ const parsed = parseFlutterPreview(authoredPreview);
3640
+ if ("error" in parsed)
3641
+ throw new FlutterRuntimeError("flutter_preview_invalid", parsed.error);
3642
+ if (typeof previewKey !== "string")
3643
+ throw new FlutterRuntimeError(
3644
+ "flutter_preview_unresolved",
3645
+ "This Flutter board's preview was not resolved by Tempo's canvas compiler; it renders only inside a Tempo canvas host."
3646
+ );
3647
+ const problem = problems?.find((problem2) => problem2.key === previewKey);
3648
+ if (problem) throw new FlutterRuntimeError(problem.code, problem.message);
3649
+ if (engineState?.kind === "failed") throw engineState.error;
3650
+ if (mountError) throw mountError;
3651
+ if (engineState?.kind === "loading") return /* @__PURE__ */ jsx3(CanvasPendingMarker, {});
3652
+ if (engineState?.kind === "starting") return /* @__PURE__ */ jsx3(CanvasUnavailableMarker, {});
3653
+ return /* @__PURE__ */ jsxs3(Fragment, { children: [
3654
+ /* @__PURE__ */ jsxs3(
3655
+ "div",
3656
+ {
3657
+ ref: viewRootRef,
3658
+ "data-tempo-flutter-root": "",
3659
+ ...everContentReady ? {} : { [PROJECTION_PENDING_ATTRIBUTE]: "" },
3660
+ style: { position: "relative", width, height, overflow: "hidden" },
3661
+ children: [
3662
+ /* @__PURE__ */ jsx3(
3663
+ "div",
3664
+ {
3665
+ ref: hostRef,
3666
+ "data-tempo-flutter-host": "",
3667
+ style: { position: "absolute", inset: 0 }
3668
+ }
3669
+ ),
3670
+ /* @__PURE__ */ jsx3(FlutterRelay, { canvasRef: relayRef, width, height })
3671
+ ]
3672
+ }
3673
+ ),
3674
+ contentReady ? null : /* @__PURE__ */ jsx3(CanvasPendingMarker, {})
3675
+ ] });
3676
+ }
3677
+ function FlutterRelay({
3678
+ canvasRef,
3679
+ width,
3680
+ height
3681
+ }) {
3682
+ const [createdBox] = useState4(() => ({ width, height }));
3683
+ return /* @__PURE__ */ jsx3(
3684
+ "canvas",
3685
+ {
3686
+ ref: canvasRef,
3687
+ "data-tempo-flutter-relay": "",
3688
+ ...{ [CAPTURE_CANVAS_ATTRIBUTE]: "" },
3689
+ "data-tempo-hide-fiber": "true",
3690
+ style: {
3691
+ position: "absolute",
3692
+ left: 0,
3693
+ top: 0,
3694
+ width: createdBox.width,
3695
+ height: createdBox.height,
3696
+ pointerEvents: "none"
3697
+ }
3698
+ }
3699
+ );
3700
+ }
3701
+ Object.assign(FlutterViewMount, { [PROJECTION_SCOPE_ROLE]: "transparent" });
3702
+ Object.assign(FlutterRelay, { [PROJECTION_SCOPE_ROLE]: "transparent" });
3703
+
2597
3704
  // canvas/host-capability.ts
2598
3705
  var canvasHostCapability = {
2599
3706
  protocolVersion: 1,
@@ -2606,6 +3713,7 @@ export {
2606
3713
  CanvasHost,
2607
3714
  CanvasHostContractError,
2608
3715
  CanvasImportBoundary,
3716
+ FlutterStoryboard,
2609
3717
  HtmlStoryboard,
2610
3718
  LegacyStoryboardV1,
2611
3719
  RouteStoryboard,