tempo-sdk 0.0.69 → 0.0.76

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 (109) hide show
  1. package/dist/assets/index.js +3 -3
  2. package/dist/astro/asset-preview-client.js +2 -2
  3. package/dist/astro.js +24 -14
  4. package/dist/astro.js.map +1 -1
  5. package/dist/canvas/astro.d.ts +1 -1
  6. package/dist/canvas/astro.js +2 -2
  7. package/dist/canvas/editor.d.ts +15 -5
  8. package/dist/canvas/editor.js +13 -8
  9. package/dist/canvas/editor.js.map +1 -1
  10. package/dist/canvas/flutter-preview.d.ts +18 -0
  11. package/dist/canvas/flutter-preview.js +9 -0
  12. package/dist/canvas/flutter-preview.js.map +1 -0
  13. package/dist/canvas/index.d.ts +33 -2
  14. package/dist/canvas/index.js +1134 -26
  15. package/dist/canvas/index.js.map +1 -1
  16. package/dist/canvas/interact-projection.js +5 -4
  17. package/dist/canvas/parser.d.ts +142 -3
  18. package/dist/canvas/parser.js +14 -1
  19. package/dist/canvas/svelte.d.ts +1 -1
  20. package/dist/canvas/svelte.js +2 -2
  21. package/dist/canvas/vue.d.ts +74 -0
  22. package/dist/canvas/vue.js +264 -0
  23. package/dist/canvas/vue.js.map +1 -0
  24. package/dist/{chunk-6BSLP7P3.js → chunk-3W4CVWTK.js} +49 -7
  25. package/dist/chunk-3W4CVWTK.js.map +1 -0
  26. package/dist/chunk-5HIIF354.js +67 -0
  27. package/dist/chunk-5HIIF354.js.map +1 -0
  28. package/dist/chunk-5LUQSXSP.js +342 -0
  29. package/dist/chunk-5LUQSXSP.js.map +1 -0
  30. package/dist/{chunk-FE6TYCLF.js → chunk-5VIBKVFO.js} +2 -2
  31. package/dist/{chunk-FE6TYCLF.js.map → chunk-5VIBKVFO.js.map} +1 -1
  32. package/dist/{chunk-77DZCV5Z.js → chunk-CXIW4IKC.js} +2 -2
  33. package/dist/chunk-CYQE3TLC.js +37 -0
  34. package/dist/chunk-CYQE3TLC.js.map +1 -0
  35. package/dist/chunk-EGRHWZRV.js +1 -0
  36. package/dist/chunk-EGRHWZRV.js.map +1 -0
  37. package/dist/chunk-GCGRJTTS.js +285 -0
  38. package/dist/chunk-GCGRJTTS.js.map +1 -0
  39. package/dist/{chunk-EYKOOLPL.js → chunk-GKDDNDG3.js} +1039 -134
  40. package/dist/chunk-GKDDNDG3.js.map +1 -0
  41. package/dist/{chunk-KOSJXE4G.js → chunk-H6BQZOAW.js} +4 -3
  42. package/dist/chunk-HOBTDB6G.js +112 -0
  43. package/dist/chunk-HOBTDB6G.js.map +1 -0
  44. package/dist/{chunk-WTQQOLXM.js → chunk-R3RYGAPB.js} +1571 -1410
  45. package/dist/chunk-R3RYGAPB.js.map +1 -0
  46. package/dist/chunk-SGN7BDRE.js +16 -0
  47. package/dist/chunk-SGN7BDRE.js.map +1 -0
  48. package/dist/{chunk-F23JGM4U.js → chunk-UBTL6JUF.js} +6 -2
  49. package/dist/{chunk-F23JGM4U.js.map → chunk-UBTL6JUF.js.map} +1 -1
  50. package/dist/{chunk-2JRAG36X.js → chunk-WBMO4ZYO.js} +2 -2
  51. package/dist/chunk-WBMO4ZYO.js.map +1 -0
  52. package/dist/{chunk-K3EYTZLL.js → chunk-WTXOWQ7N.js} +3 -1
  53. package/dist/chunk-WTXOWQ7N.js.map +1 -0
  54. package/dist/{chunk-Q2A46HHW.js → chunk-XFPFWTWX.js} +276 -43
  55. package/dist/chunk-XFPFWTWX.js.map +1 -0
  56. package/dist/{chunk-PXDTH36X.js → chunk-Y72PIE3I.js} +212 -20
  57. package/dist/chunk-Y72PIE3I.js.map +1 -0
  58. package/dist/{chunk-6IR5JY6W.js → chunk-YECMP34I.js} +41 -9
  59. package/dist/chunk-YECMP34I.js.map +1 -0
  60. package/dist/{chunk-NSKYOKG5.js → chunk-ZXC7SZIT.js} +278 -26
  61. package/dist/chunk-ZXC7SZIT.js.map +1 -0
  62. package/dist/{controls-reader-SNMI2UY7.js → controls-reader-Z7OQWYWQ.js} +4 -3
  63. package/dist/{controls-reader-SNMI2UY7.js.map → controls-reader-Z7OQWYWQ.js.map} +1 -1
  64. package/dist/expo/plugin.cjs +301 -58
  65. package/dist/expo/plugin.cjs.map +1 -1
  66. package/dist/expo/plugin.js +1 -1
  67. package/dist/expo-babel-plugin.cjs +301 -58
  68. package/dist/expo-babel-plugin.cjs.map +1 -1
  69. package/dist/expo-babel-plugin.js +1 -1
  70. package/dist/flutter-preview-path.d.ts +9 -0
  71. package/dist/flutter-preview-path.js +16 -0
  72. package/dist/flutter-preview-path.js.map +1 -0
  73. package/dist/index.d.ts +16 -15
  74. package/dist/index.js +9 -6
  75. package/dist/nextjs/plugin.cjs +46 -5
  76. package/dist/nextjs/plugin.cjs.map +1 -1
  77. package/dist/nextjs/plugin.js +1 -1
  78. package/dist/nextjs-loader.cjs +343 -68
  79. package/dist/nextjs-loader.cjs.map +1 -1
  80. package/dist/nextjs.cjs +48 -6
  81. package/dist/nextjs.cjs.map +1 -1
  82. package/dist/nextjs.d.cts +9 -1
  83. package/dist/nextjs.d.ts +9 -1
  84. package/dist/nextjs.js +1 -1
  85. package/dist/nuxt/runtime/identity.d.ts +24 -0
  86. package/dist/nuxt/runtime/identity.js +18 -0
  87. package/dist/nuxt/runtime/identity.js.map +1 -0
  88. package/dist/nuxt.d.ts +102 -0
  89. package/dist/nuxt.js +5673 -0
  90. package/dist/nuxt.js.map +1 -0
  91. package/dist/{storyboard-4YdTYq_e.d.ts → storyboard-CMJVBSXn.d.ts} +9 -3
  92. package/dist/svelte.d.ts +4 -2
  93. package/dist/svelte.js +21 -88
  94. package/dist/svelte.js.map +1 -1
  95. package/dist/vue.d.ts +66 -0
  96. package/dist/vue.js +1403 -0
  97. package/dist/vue.js.map +1 -0
  98. package/package.json +48 -5
  99. package/dist/chunk-2JRAG36X.js.map +0 -1
  100. package/dist/chunk-6BSLP7P3.js.map +0 -1
  101. package/dist/chunk-6IR5JY6W.js.map +0 -1
  102. package/dist/chunk-EYKOOLPL.js.map +0 -1
  103. package/dist/chunk-K3EYTZLL.js.map +0 -1
  104. package/dist/chunk-NSKYOKG5.js.map +0 -1
  105. package/dist/chunk-PXDTH36X.js.map +0 -1
  106. package/dist/chunk-Q2A46HHW.js.map +0 -1
  107. package/dist/chunk-WTQQOLXM.js.map +0 -1
  108. /package/dist/{chunk-77DZCV5Z.js.map → chunk-CXIW4IKC.js.map} +0 -0
  109. /package/dist/{chunk-KOSJXE4G.js.map → chunk-H6BQZOAW.js.map} +0 -0
@@ -1,103 +1,53 @@
1
+ import {
2
+ parseControlsFile
3
+ } from "./chunk-PYAJHLXO.js";
4
+ import {
5
+ TEMPO_HOST_IDENTITY_CAPABILITY_HEADER,
6
+ TEMPO_HOST_IDENTITY_ENDPOINT,
7
+ TEMPO_VUE_ANNOTATION_PLUGIN_NAME,
8
+ TEMPO_WORKSPACE_NONCE_META_NAME,
9
+ createSdkFileMatcher,
10
+ createTempoHostIdentity
11
+ } from "./chunk-5LUQSXSP.js";
1
12
  import {
2
13
  appendModuleVersionRecord,
14
+ cleanModuleId,
3
15
  computeTempoAnnotatedProps
4
- } from "./chunk-F23JGM4U.js";
16
+ } from "./chunk-UBTL6JUF.js";
5
17
  import {
6
18
  annotateFile
7
19
  } from "./chunk-H6OZIX2U.js";
8
20
  import {
9
21
  sourceVersionHash
10
- } from "./chunk-KOSJXE4G.js";
22
+ } from "./chunk-H6BQZOAW.js";
11
23
  import {
12
24
  parseCanvasFile
13
- } from "./chunk-PXDTH36X.js";
25
+ } from "./chunk-Y72PIE3I.js";
14
26
  import {
15
- parseControlsFile
16
- } from "./chunk-PYAJHLXO.js";
27
+ canonicalPathAllowMissing,
28
+ flutterPreviewKey
29
+ } from "./chunk-5HIIF354.js";
17
30
  import {
31
+ VITE_ERROR_CLIENT_ID,
18
32
  VITE_ERROR_CLIENT_PATH,
19
33
  VITE_ERROR_CLIENT_SOURCE,
20
34
  VITE_ERROR_STATE_EVENT,
21
35
  VITE_ERROR_SUBSCRIBE_EVENT
22
- } from "./chunk-K3EYTZLL.js";
36
+ } from "./chunk-WTXOWQ7N.js";
23
37
  import {
24
38
  TEMPO_INTERACT_FRAME_NAME
25
39
  } from "./chunk-65B52AR7.js";
26
-
27
- // canvas-component-reference.ts
28
- import { realpathSync } from "fs";
29
- import { dirname, isAbsolute, normalize, posix, resolve } from "path";
30
- var COMPONENT_REFERENCE_ATTRIBUTE = "data-tempo-component-reference";
31
- function moduleIdentity(file, specifier, resolved) {
32
- const resolvedId = resolved?.get(specifier);
33
- const bundled = resolvedId?.startsWith("\0tempo:astro-component:") ? decodeURIComponent(
34
- resolvedId.slice("\0tempo:astro-component:".length, -3)
35
- ) : resolvedId;
36
- const target = bundled === void 0 ? specifier : bundled.replace(/\bt=\d{13}&?\b/, "").replace(/[?&]$/, "");
37
- if (target.startsWith("\0")) return target;
38
- const suffixAt = target.search(/[?#]/);
39
- let path = (suffixAt < 0 ? target : target.slice(0, suffixAt)).replace(
40
- /\\/g,
41
- "/"
42
- );
43
- const suffix = suffixAt < 0 || target.endsWith(".astro?tempo-component") ? "" : target.slice(suffixAt);
44
- if (bundled === void 0 && path.startsWith("."))
45
- path = resolve(dirname(file), path);
46
- if (!isAbsolute(path) && !/^[A-Za-z]:\//.test(path)) return target;
47
- if (bundled !== void 0) {
48
- try {
49
- path = realpathSync.native(path);
50
- } catch {
51
- }
52
- }
53
- return normalize(path).replace(/\\/g, "/") + suffix;
54
- }
55
- function canvasComponentAnnotations(file, source, resolved) {
56
- const result = /* @__PURE__ */ new Map();
57
- if (!source.includes("tempo-sdk/canvas")) return result;
58
- const parsed = parseCanvasFile(file, source);
59
- for (const board of parsed.storyboards) {
60
- const ref = board.component;
61
- if (board.kind !== "component" || !ref?.localName || board.openingElementSpan === void 0)
62
- continue;
63
- const member = ref.expression.match(
64
- /^\s*([$\w]+)(?:\s*\.\s*([$\w]+))?\s*$/
65
- );
66
- if (!member) continue;
67
- let name;
68
- if (ref.import) {
69
- if (ref.import.kind === "namespace") {
70
- if (!member[2]) continue;
71
- name = member[2];
72
- } else {
73
- if (member[2]) continue;
74
- name = ref.import.importedName;
75
- }
76
- } else {
77
- if (member[2]) continue;
78
- name = ref.localName;
79
- }
80
- const specifier = ref.import?.source.replace(/\\/g, "/").replace(/[?#].*/, "");
81
- const canvasDir = posix.dirname(file.replace(/\\/g, "/"));
82
- const external = specifier !== void 0 && (!specifier.startsWith(".") || !posix.join(canvasDir, specifier).startsWith(`${canvasDir}/`));
83
- result.set(board.openingElementSpan.start, {
84
- [COMPONENT_REFERENCE_ATTRIBUTE]: JSON.stringify([
85
- ref.import ? "import" : "local",
86
- moduleIdentity(file, ref.import?.source ?? file, resolved),
87
- name
88
- ]),
89
- ...external ? { "data-tempo-external-component": "true" } : {}
90
- });
91
- }
92
- return result;
93
- }
40
+ import {
41
+ FLUTTER_PREVIEW_KEY_ATTRIBUTE,
42
+ parseFlutterPreview
43
+ } from "./chunk-CYQE3TLC.js";
94
44
 
95
45
  // local-prebuilt-aliases.ts
96
46
  import { existsSync } from "fs";
97
- import { join, resolve as resolve2 } from "path";
47
+ import { join, resolve } from "path";
98
48
  function localPrebuiltAliases(root) {
99
49
  if (process.env.TEMPO_MONOREPO_SDK_SOURCE !== "local-prebuilt") return [];
100
- const sdk = resolve2(root ?? process.cwd(), "node_modules/tempo-sdk");
50
+ const sdk = resolve(root ?? process.cwd(), "node_modules/tempo-sdk");
101
51
  if (!existsSync(join(sdk, ".tempo-prebuilt-source.json"))) return [];
102
52
  return ["canvas", "assets"].flatMap((entry) => {
103
53
  const replacement = join(sdk, "dist", entry, "index.js");
@@ -106,11 +56,12 @@ function localPrebuiltAliases(root) {
106
56
  }
107
57
 
108
58
  // canvas-dependency-scan.ts
109
- import { relative, resolve as resolve3 } from "path";
59
+ import { existsSync as existsSync2 } from "fs";
60
+ import { join as join2, relative, resolve as resolve2 } from "path";
110
61
  function applyManagedCanvasDependencyScan(config, env = process.env) {
111
62
  const host = env.TEMPO_CANVAS_HOST_ROOT;
112
63
  const canvases = env.TEMPO_CANVAS_SOURCE_ROOT;
113
- if (!host || !canvases || resolve3(config.root ?? process.cwd()) !== resolve3(host))
64
+ if (!host || !canvases || resolve2(config.root ?? process.cwd()) !== resolve2(host))
114
65
  return;
115
66
  const legacyGlob = [
116
67
  relative(host, canvases).replace(/\\/g, "/"),
@@ -135,498 +86,54 @@ function applyManagedCanvasDependencyScan(config, env = process.env) {
135
86
  ];
136
87
  }
137
88
  }
138
-
139
- // canvas-host-registration-work.ts
140
- import { readFileSync } from "fs";
141
- async function traceSlowRegistration(work, report) {
142
- const startedAt = performance.now();
143
- let slow = false;
144
- const timer = setTimeout(() => {
145
- slow = true;
146
- report("pending", Math.round(performance.now() - startedAt));
147
- }, 5e3);
148
- const settled = (status) => {
149
- const elapsedMs = Math.round(performance.now() - startedAt);
150
- if (slow || elapsedMs >= 5e3) report(status, elapsedMs);
151
- };
152
- try {
153
- const result = await work();
154
- settled("ready");
155
- return result;
156
- } catch (error) {
157
- settled("error");
158
- throw error;
159
- } finally {
160
- clearTimeout(timer);
161
- }
162
- }
163
- function createRegistrationTransforms() {
164
- const receipts = /* @__PURE__ */ new Map();
165
- return async function confirm(file, transform) {
166
- const source = readFileSync(file, "utf8");
167
- const previous = receipts.get(file);
168
- if (previous?.source === source && (previous.pending || previous.current())) {
169
- return previous.result;
170
- }
171
- const receipt = {
172
- source,
173
- pending: true,
174
- current: () => false,
175
- result: Promise.resolve()
176
- };
177
- receipts.set(file, receipt);
178
- receipt.result = Promise.resolve().then(async () => {
179
- receipt.current = await transform();
180
- receipt.pending = false;
181
- }).catch((error) => {
182
- if (receipts.get(file) === receipt) receipts.delete(file);
183
- throw error;
184
- });
185
- return receipt.result;
186
- };
187
- }
188
- async function registrationReply(work, progress, poll, intervalMs = 1e3) {
189
- if (!poll) {
190
- await work;
191
- return null;
192
- }
193
- let timer;
194
- try {
195
- return await Promise.race([
196
- work.then(() => null),
197
- new Promise((resolve6) => {
198
- timer = setTimeout(() => resolve6(progress()), intervalMs);
199
- })
200
- ]);
201
- } finally {
202
- clearTimeout(timer);
203
- }
89
+ var TEMPO_HOST_DIR = "tempo";
90
+ function excludeTempoHostFromAppDependencyScan(config) {
91
+ if (config.optimizeDeps?.entries !== void 0) return;
92
+ if (config.build?.rollupOptions?.input !== void 0) return;
93
+ const root = resolve2(config.root ?? process.cwd());
94
+ const hostConfig = join2(root, TEMPO_HOST_DIR, "tempo.config.json");
95
+ if (!existsSync2(hostConfig)) return;
96
+ config.optimizeDeps ?? (config.optimizeDeps = {});
97
+ config.optimizeDeps.entries = [
98
+ "**/*.html",
99
+ "!**/__tests__/**",
100
+ "!**/coverage/**",
101
+ `!${TEMPO_HOST_DIR}/**`
102
+ ];
204
103
  }
205
104
 
206
- // index.ts
105
+ // compile-error-stream.ts
106
+ import { readFileSync, realpathSync } from "fs";
207
107
  import { parseSync } from "oxc-parser";
208
- import {
209
- existsSync as existsSync2,
210
- openSync,
211
- closeSync,
212
- fstatSync,
213
- readFileSync as readFileSync4,
214
- realpathSync as realpathSync3,
215
- statSync,
216
- watch as watchFileSystem
217
- } from "fs";
218
- import { createRequire } from "module";
219
-
220
- // assets/controls-transform.ts
221
- function transformControlsForHmr(source, filePath, previouslyDefinedControls = false) {
222
- const calls = source.includes("defineControls") ? parseControlsFile(filePath, source) : [];
223
- if (!calls.length && !previouslyDefinedControls) return source;
224
- for (const { start, end } of calls.reverse()) {
225
- source = source.slice(0, start) + `((dispose) => { if (import.meta.hot && typeof dispose === "function") import.meta.hot.data.__tempoControlsDisposers.push(dispose); })(${source.slice(start, end)})` + source.slice(end);
226
- }
227
- return `if (import.meta.hot) {
228
- for (const dispose of import.meta.hot.data.__tempoControlsDisposers ?? []) dispose();
229
- import.meta.hot.data.__tempoControlsDisposers = [];
230
- import.meta.hot.dispose(() => {
231
- for (const dispose of import.meta.hot.data.__tempoControlsDisposers ?? []) dispose();
232
- import.meta.hot.data.__tempoControlsDisposers = [];
233
- });
234
- }
235
- ${source}`;
236
- }
237
108
 
238
- // index.ts
239
- import { dirname as dirname3, isAbsolute as isAbsolute2, join as join3, relative as relative2, resolve as resolve5 } from "path";
240
- import { fileURLToPath } from "url";
241
- import { createFilter } from "@rollup/pluginutils";
242
-
243
- // canvas-host-registration-contract.ts
244
- var CANVAS_HOST_REGISTRATION_ENDPOINT = "/__tempo/canvas-host-registration";
245
- var CANVAS_HOST_REGISTRATION_CAPABILITY_HEADER = "x-tempo-canvas-host-registration";
246
- function normalizeCanvasRegistrationPath(canvasPath) {
247
- return canvasPath.trim().replace(/\\/g, "/").replace(/^\.\/+/, "").replace(/^\/+/, "");
248
- }
249
-
250
- // default-export-identity.ts
251
- var FUNCTION_DEFAULT_RE = /^(?:async\s+)?function(?:\s*\*)?(?:\s+([A-Za-z_$][\w$]*))?\s*\(/;
252
- var CLASS_DEFAULT_RE = /^(?:abstract\s+)?class(?:\s+([A-Za-z_$][\w$]*))?(?=[\s{])/;
253
- var ARROW_DEFAULT_RE = /^(?:async\s+)?(?:\([^()]*\)|[A-Za-z_$][\w$]*)\s*=>/;
254
- var IDENTIFIER_DEFAULT_RE = /^([A-Za-z_$][\w$]*)[ \t]*(?:;|\r?\n|$)/;
255
- function readDefaultExportIdentity(source) {
256
- const start = /\bexport\s+default\s+/.exec(source);
257
- if (!start) return null;
258
- const tail = source.slice(start.index + start[0].length);
259
- const fn = FUNCTION_DEFAULT_RE.exec(tail);
260
- if (fn) return { kind: "function", name: fn[1] ?? null };
261
- const cls = CLASS_DEFAULT_RE.exec(tail);
262
- if (cls) return { kind: "class", name: cls[1] ?? null };
263
- if (ARROW_DEFAULT_RE.test(tail)) return { kind: "function", name: null };
264
- const identifier = IDENTIFIER_DEFAULT_RE.exec(tail);
265
- if (identifier) return { kind: "identifier", name: identifier[1] };
266
- return null;
267
- }
268
- function isDefaultExportIdentityRewrite(before, after) {
269
- if (!before) return false;
270
- if (before.name === null) return true;
271
- if (!after) return false;
272
- if (before.name === after.name) return false;
273
- return isComponentShaped(before) && isComponentShaped(after);
274
- }
275
- function isComponentShaped(identity) {
276
- return identity.name === null || /^[A-Z]/.test(identity.name);
277
- }
109
+ // hot-update-net.ts
110
+ import { statSync } from "fs";
111
+ import { basename, dirname, isAbsolute, resolve as resolve3 } from "path";
278
112
 
279
- // pruned-module-deletion.ts
280
- function createPrunedModuleDeletionGuard() {
281
- let sequence = 0;
282
- let activeReceipts = 0;
283
- let receipts = /* @__PURE__ */ new WeakMap();
113
+ // missed-change-sweep.ts
114
+ var MISSED_CHANGE_WATCHER_GRACE_MS = 1e3;
115
+ var MISSED_CHANGE_MAX_EMITS_PER_REVISION = 3;
116
+ function createMissedChangeSweep(args) {
117
+ const now = args.now ?? Date.now;
118
+ const graceMs = args.watcherGraceMs ?? MISSED_CHANGE_WATCHER_GRACE_MS;
119
+ const maxEmits = args.maxEmitsPerRevision ?? MISSED_CHANGE_MAX_EMITS_PER_REVISION;
120
+ const lastSeenMtimeMs = /* @__PURE__ */ new Map();
121
+ const pending = /* @__PURE__ */ new Map();
284
122
  return {
285
- observePrune(graph, paths) {
286
- const receipt = ++sequence;
287
- for (const path of paths) {
288
- const module = graph.urlToModuleMap.get(path);
289
- if (module) {
290
- if (!receipts.has(module)) activeReceipts++;
291
- receipts.set(module, receipt);
123
+ async sweep() {
124
+ const emitted = [];
125
+ for (const [file, modules] of args.listServedFiles()) {
126
+ const mtimeMs = await args.statMtimeMs(file);
127
+ if (mtimeMs === null) {
128
+ pending.delete(file);
129
+ continue;
292
130
  }
293
- }
294
- },
295
- observeRequest(graph, url, base, fetchDestination, ifNoneMatch) {
296
- if (!activeReceipts || ["document", "iframe", "frame"].includes(String(fetchDestination)))
297
- return;
298
- const requestSequence = sequence;
299
- return async (status, contentType, responseEtag) => {
300
- if (!activeReceipts || status < 200 || status >= 400) return;
301
- if (status !== 304 && !/^text\/(?:javascript|css)(?:;|$)/i.test(String(contentType)))
302
- return;
303
- const etag = status === 304 ? ifNoneMatch : responseEtag;
304
- if (typeof etag !== "string" || !graph.getModuleByEtag(etag)) return;
305
- let moduleUrl = url;
306
- if (base !== "/" && moduleUrl.startsWith(base))
307
- moduleUrl = `/${moduleUrl.slice(base.length)}`;
308
- try {
309
- moduleUrl = decodeURI(moduleUrl).replace(/__x00__/g, "\0");
310
- if (moduleUrl.startsWith("/@id/")) moduleUrl = moduleUrl.slice(5);
311
- const [, id] = await graph.resolveUrl(moduleUrl);
312
- const module = graph.getModuleById(id);
313
- if (module && module.transformResult?.etag === etag && (receipts.get(module) ?? Infinity) <= requestSequence) {
314
- receipts.delete(module);
315
- activeReceipts--;
316
- }
317
- } catch {
318
- }
319
- };
320
- },
321
- suppressDeletion(graph, modules) {
322
- if (!modules.length || !modules.every(
323
- (module) => receipts.has(module) && module.importers.size === 0
324
- ))
325
- return false;
326
- const invalidated = /* @__PURE__ */ new Set();
327
- for (const module of modules) graph.invalidateModule(module, invalidated);
328
- return true;
329
- },
330
- clear() {
331
- receipts = /* @__PURE__ */ new WeakMap();
332
- activeReceipts = 0;
333
- }
334
- };
335
- }
336
-
337
- // hmr-generation-fence.ts
338
- function generationIdentity(update) {
339
- const type = typeof update.type === "string" ? update.type : null;
340
- const acceptedPath = typeof update.acceptedPath === "string" ? update.acceptedPath : typeof update.path === "string" ? update.path : null;
341
- if (!type || !acceptedPath) return null;
342
- return `${type}\0${acceptedPath}`;
343
- }
344
- function createHmrGenerationFence() {
345
- const newestTimestampByIdentity = /* @__PURE__ */ new Map();
346
- return {
347
- filter(updates) {
348
- const accepted = [];
349
- for (const update of updates) {
350
- const identity = generationIdentity(update);
351
- const timestamp = update.timestamp;
352
- if (identity === null || typeof timestamp !== "number" || !Number.isFinite(timestamp)) {
353
- accepted.push(update);
354
- continue;
355
- }
356
- const newestTimestamp = newestTimestampByIdentity.get(identity);
357
- if (newestTimestamp !== void 0 && timestamp < newestTimestamp) {
358
- continue;
359
- }
360
- if (newestTimestamp === void 0 || timestamp > newestTimestamp) {
361
- newestTimestampByIdentity.set(identity, timestamp);
362
- }
363
- accepted.push(update);
364
- }
365
- return accepted;
366
- },
367
- clear() {
368
- newestTimestampByIdentity.clear();
369
- }
370
- };
371
- }
372
-
373
- // host-identity.ts
374
- import { readFileSync as readFileSync2 } from "fs";
375
- import { resolve as resolve4 } from "path";
376
-
377
- // package.json
378
- var package_default = {
379
- name: "tempo-sdk",
380
- version: "0.0.69",
381
- publishConfig: {
382
- tag: "sdk-v2-latest"
383
- },
384
- type: "module",
385
- description: "Tempo SDK \u2014 Vite, Next.js, Expo, Svelte and Astro canvas integration, source annotations and storyboard types",
386
- repository: {
387
- type: "git",
388
- url: "git+https://github.com/TempoLabsAI/tempo-monorepo.git",
389
- directory: "tempo-modules/tempo-sdk"
390
- },
391
- exports: {
392
- "./astro/controls": {
393
- types: "./dist/astro/controls.d.ts",
394
- import: "./dist/astro/controls.js",
395
- default: "./dist/astro/controls.js"
396
- },
397
- "./astro": {
398
- types: "./dist/astro.d.ts",
399
- import: "./dist/astro.js"
400
- },
401
- "./astro/client": {
402
- types: "./astro/client.d.ts"
403
- },
404
- "./canvas/astro": {
405
- types: "./dist/canvas/astro.d.ts",
406
- import: "./dist/canvas/astro.js"
407
- },
408
- "./canvas/astro-contract": {
409
- types: "./dist/canvas/astro-contract.d.ts",
410
- import: "./dist/canvas/astro-contract.js"
411
- },
412
- ".": {
413
- types: "./dist/index.d.ts",
414
- import: "./dist/index.js"
415
- },
416
- "./canvas": {
417
- types: "./dist/canvas/index.d.ts",
418
- import: "./dist/canvas/index.js"
419
- },
420
- "./canvas/svelte": {
421
- types: "./dist/canvas/svelte.d.ts",
422
- import: "./dist/canvas/svelte.js"
423
- },
424
- "./canvas/interact-projection": {
425
- types: "./dist/canvas/interact-projection.d.ts",
426
- import: "./dist/canvas/interact-projection.js"
427
- },
428
- "./canvas/parser": {
429
- types: "./dist/canvas/parser.d.ts",
430
- import: "./dist/canvas/parser.js"
431
- },
432
- "./canvas/editor": {
433
- types: "./dist/canvas/editor.d.ts",
434
- import: "./dist/canvas/editor.js"
435
- },
436
- "./assets": {
437
- types: "./dist/assets/index.d.ts",
438
- import: "./dist/assets/index.js"
439
- },
440
- "./assets/parser": {
441
- types: "./dist/assets/parser.d.ts",
442
- import: "./dist/assets/parser.js"
443
- },
444
- "./assets/editor": {
445
- types: "./dist/assets/editor.d.ts",
446
- import: "./dist/assets/editor.js"
447
- },
448
- "./nextjs": {
449
- types: "./dist/nextjs.d.ts",
450
- import: "./dist/nextjs.js",
451
- require: "./dist/nextjs.cjs"
452
- },
453
- "./nextjs/plugin": {
454
- types: "./dist/nextjs/plugin.d.ts",
455
- import: "./dist/nextjs/plugin.js"
456
- },
457
- "./expo": {
458
- types: "./dist/expo-babel-plugin.d.ts",
459
- import: "./dist/expo-babel-plugin.js",
460
- require: "./dist/expo-babel-plugin.cjs"
461
- },
462
- "./expo/plugin": {
463
- types: "./dist/expo/plugin.d.ts",
464
- import: "./dist/expo/plugin.js",
465
- require: "./dist/expo/plugin.cjs"
466
- },
467
- "./svelte": {
468
- types: "./dist/svelte.d.ts",
469
- import: "./dist/svelte.js"
470
- },
471
- "./astro/asset-preview-client": {
472
- types: "./dist/astro/asset-preview-client.d.ts",
473
- import: "./dist/astro/asset-preview-client.js"
474
- }
475
- },
476
- files: [
477
- "dist",
478
- "astro/client.d.ts"
479
- ],
480
- scripts: {
481
- clean: "rm -rf dist",
482
- build: "pnpm run clean && tsup",
483
- "build:if-missing": "test -f dist/index.js || pnpm run build",
484
- prepare: "pnpm run build",
485
- prepublishOnly: "pnpm build",
486
- demo: "TEMPO=true pnpm --filter @tempo-modules/vite-annotate-plugin-demo dev",
487
- "demo:nextjs": "TEMPO=true pnpm --filter @tempo-modules/tempo-sdk-nextjs-demo dev",
488
- test: "vitest run",
489
- "test:browser": "vitest run canvas-dependency-scan-browser.test.ts pruned-module-deletion-browser.test.ts asset-live-preview-browser.test.ts asset-popover-lifecycle-browser.test.ts component-controls-browser.test.ts canvas-controls-browser.test.ts canvas-capture-determinism-browser.test.ts canvas-host-vite-e2e.test.ts canvas-host-packed-sdk-e2e.test.ts error-tracking-e2e.test.ts astro-integration.test.ts astro-storyboard-routing.test.ts astro-react-integration.test.ts astro-descriptor-browser.test.ts astro-packed.test.ts",
490
- "test:watch": "vitest",
491
- "test:nextjs:unit": "vitest run nextjs-loader.test.ts nextjs-wrapper.test.ts nextjs-fixtures.test.ts nextjs-published.test.ts",
492
- "test:nextjs:integration": "vitest run nextjs-e2e-correctness.test.ts",
493
- "test:nextjs:production": "vitest run nextjs-production.test.ts",
494
- "test:nextjs": "vitest run nextjs-loader.test.ts nextjs-wrapper.test.ts nextjs-fixtures.test.ts nextjs-published.test.ts nextjs-e2e-correctness.test.ts nextjs-production.test.ts"
495
- },
496
- dependencies: {
497
- "@rollup/pluginutils": "^5.1.0",
498
- "oxc-parser": "^0.110.0"
499
- },
500
- optionalDependencies: {
501
- "@astrojs/compiler-rs": "0.5.1"
502
- },
503
- peerDependencies: {
504
- astro: "^7.0.0",
505
- "@babel/core": "^7.0.0",
506
- next: "^13 || ^14 || ^15 || ^16",
507
- react: "^18 || ^19",
508
- svelte: "^5.0.0",
509
- vite: "^5 || ^6 || ^7 || ^8"
510
- },
511
- peerDependenciesMeta: {
512
- astro: {
513
- optional: true
514
- },
515
- react: {
516
- optional: true
517
- },
518
- "@babel/core": {
519
- optional: true
520
- },
521
- next: {
522
- optional: true
523
- },
524
- svelte: {
525
- optional: true
526
- },
527
- vite: {
528
- optional: true
529
- }
530
- },
531
- devDependencies: {
532
- "@astrojs/react": "7.0.1",
533
- "@babel/core": "^7.29.0",
534
- "@babel/types": "^7.29.0",
535
- "@modules/annotation": "workspace:*",
536
- "@modules/astro-editor": "workspace:*",
537
- "@modules/file-parser": "workspace:*",
538
- "@modules/svelte-editor": "workspace:*",
539
- "@types/babel__core": "^7.20.5",
540
- "@types/node": "^25.0.8",
541
- "@types/react": "catalog:",
542
- "@types/react-dom": "catalog:",
543
- "@vitejs/plugin-react": "catalog:",
544
- astro: "7.3.8",
545
- "magic-string": "^0.30.21",
546
- playwright: "^1.58.2",
547
- "react-dom": "catalog:",
548
- "react-dom18": "npm:react-dom@18.3.1",
549
- react18: "npm:react@18.3.1",
550
- svelte: "5.56.9",
551
- tsup: "^8.5.1",
552
- typescript: "catalog:",
553
- vite: "catalog:",
554
- vitest: "catalog:"
555
- }
556
- };
557
-
558
- // release-channel.ts
559
- var TEMPO_SDK_CHANNEL = package_default.publishConfig.tag;
560
- function sdkChannelGeneration(channel) {
561
- if (typeof channel !== "string") return null;
562
- const match = /^sdk-v([1-9]\d*)-latest$/.exec(channel);
563
- return match ? Number(match[1]) : null;
564
- }
565
- if (sdkChannelGeneration(TEMPO_SDK_CHANNEL) === null) {
566
- throw new Error("tempo-sdk publishConfig.tag must be sdk-v<N>-latest");
567
- }
568
-
569
- // host-identity.ts
570
- var TEMPO_HOST_IDENTITY_ENDPOINT = "/__tempo/identity";
571
- var TEMPO_HOST_IDENTITY_CAPABILITY_HEADER = "x-tempo-host-identity";
572
- var TEMPO_HOST_IDENTITY_CONTRACT_VERSION = 1;
573
- var TEMPO_WORKSPACE_NONCE_ENV = "TEMPO_WORKSPACE_NONCE";
574
- var TEMPO_WORKSPACE_NONCE_META_NAME = "tempo-workspace-nonce";
575
- var WORKSPACE_NONCE_RELATIVE_PATH = ".tempo/workspace-nonce";
576
- var MAX_WORKSPACE_NONCE_LENGTH = 128;
577
- function normalizeWorkspaceNonce(value) {
578
- const nonce = value?.trim() ?? "";
579
- return nonce.length > 0 && nonce.length <= MAX_WORKSPACE_NONCE_LENGTH ? nonce : "";
580
- }
581
- function readTempoWorkspaceNonce(root = process.cwd()) {
582
- const fromEnvironment = normalizeWorkspaceNonce(
583
- process.env[TEMPO_WORKSPACE_NONCE_ENV]
584
- );
585
- if (fromEnvironment) return fromEnvironment;
586
- try {
587
- return normalizeWorkspaceNonce(
588
- readFileSync2(resolve4(root, WORKSPACE_NONCE_RELATIVE_PATH), "utf-8")
589
- );
590
- } catch {
591
- return "";
592
- }
593
- }
594
- function createTempoHostIdentity(framework, options = {}) {
595
- return {
596
- tempoHost: true,
597
- contractVersion: TEMPO_HOST_IDENTITY_CONTRACT_VERSION,
598
- workspaceNonce: readTempoWorkspaceNonce(options.root),
599
- sdkVersion: package_default.version,
600
- sdkChannel: TEMPO_SDK_CHANNEL,
601
- pluginActive: options.pluginActive ?? Boolean(process.env.TEMPO),
602
- framework
603
- };
604
- }
605
-
606
- // missed-change-sweep.ts
607
- var MISSED_CHANGE_WATCHER_GRACE_MS = 1e3;
608
- var MISSED_CHANGE_MAX_EMITS_PER_REVISION = 3;
609
- function createMissedChangeSweep(args) {
610
- const now = args.now ?? Date.now;
611
- const graceMs = args.watcherGraceMs ?? MISSED_CHANGE_WATCHER_GRACE_MS;
612
- const maxEmits = args.maxEmitsPerRevision ?? MISSED_CHANGE_MAX_EMITS_PER_REVISION;
613
- const lastSeenMtimeMs = /* @__PURE__ */ new Map();
614
- const pending = /* @__PURE__ */ new Map();
615
- return {
616
- async sweep() {
617
- const emitted = [];
618
- for (const [file, modules] of args.listServedFiles()) {
619
- const mtimeMs = await args.statMtimeMs(file);
620
- if (mtimeMs === null) {
621
- pending.delete(file);
622
- continue;
623
- }
624
- let previous = lastSeenMtimeMs.get(file);
625
- if (previous === void 0) {
626
- const coveredMtimeMs = args.lastHotUpdateMtimeMs?.(file);
627
- if (coveredMtimeMs === void 0 || coveredMtimeMs >= mtimeMs) {
628
- lastSeenMtimeMs.set(file, mtimeMs);
629
- continue;
131
+ let previous = lastSeenMtimeMs.get(file);
132
+ if (previous === void 0) {
133
+ const coveredMtimeMs = args.lastHotUpdateMtimeMs?.(file);
134
+ if (coveredMtimeMs === void 0 || coveredMtimeMs >= mtimeMs) {
135
+ lastSeenMtimeMs.set(file, mtimeMs);
136
+ continue;
630
137
  }
631
138
  previous = coveredMtimeMs;
632
139
  lastSeenMtimeMs.set(file, coveredMtimeMs);
@@ -683,8 +190,8 @@ function createRapidHotUpdateReplay(options) {
683
190
  previous.release = void 0;
684
191
  if (previous.expiry) cancel(previous.expiry);
685
192
  } else {
686
- burst.gate = new Promise((resolve6) => {
687
- burst.release = resolve6;
193
+ burst.gate = new Promise((resolve8) => {
194
+ burst.release = resolve8;
688
195
  });
689
196
  }
690
197
  burst.expiry = schedule(() => burst.release?.(), quietMs * 2);
@@ -730,382 +237,117 @@ function createRapidHotUpdateReplay(options) {
730
237
  };
731
238
  }
732
239
 
733
- // react-refresh-boundary.ts
734
- var installed = /* @__PURE__ */ new WeakSet();
735
- function installSynchronousReactRefreshBoundary(plugins) {
736
- for (const plugin of plugins) {
737
- if (plugin.name === "vite:react-refresh" && plugin.load && !installed.has(plugin)) {
738
- installed.add(plugin);
739
- const hook2 = plugin.load;
740
- const load = typeof hook2 === "function" ? hook2 : hook2.handler;
741
- const wrapped2 = async function(...args) {
742
- const result = await load.apply(this, args);
743
- if (!result || args[0] !== "/@react-refresh") return result;
744
- const source = typeof result === "string" ? result : result.code;
745
- if (!source || !/\b(?:let|const) allFamiliesByType = new WeakMap\(\)/.test(source) || !source.includes("function performReactRefresh()"))
746
- return result;
747
- const code = `${source}
748
- globalThis[Symbol.for("tempo.react-refresh.family")] = (type) => allFamiliesByType.get(type);
749
- `;
750
- return typeof result === "string" ? code : { ...result, code };
751
- };
752
- plugin.load = typeof hook2 === "function" ? wrapped2 : { ...hook2, handler: wrapped2 };
753
- }
754
- if (plugin.name !== "vite:react-babel" || !plugin.transform || installed.has(plugin))
755
- continue;
756
- installed.add(plugin);
757
- const hook = plugin.transform;
758
- const transform = typeof hook === "function" ? hook : hook.handler;
759
- const wrapped = async function(...args) {
760
- const result = await transform.apply(this, args);
761
- if (!result) return result;
762
- const source = typeof result === "string" ? result : result.code;
763
- if (!source) return result;
764
- const code = source.replace(
765
- /RefreshRuntime\.__hmr_import\(import\.meta\.url\)\.then\(\(currentExports\) => \{\n(\s*RefreshRuntime\.registerExportsForReactRefresh\([^\n]+\);)\n\s*import\.meta\.hot\.accept\(\(nextExports\) => \{([\s\S]*?)\n\s*\}\);\n\s*\}\);/,
766
- (_match, register, accept) => `const __tempoReactRefreshExports = RefreshRuntime.__hmr_import(import.meta.url).then((currentExports) => {
767
- ${register}
768
- return currentExports;
769
- });
770
- import.meta.hot.accept(async (nextExports) => {
771
- const currentExports = await __tempoReactRefreshExports;${accept}
772
- });`
773
- );
774
- return code === source ? result : typeof result === "string" ? code : { ...result, code };
775
- };
776
- plugin.transform = typeof hook === "function" ? wrapped : { ...hook, handler: wrapped };
777
- }
240
+ // hot-update-net.ts
241
+ var HOT_UPDATE_NET_SWEEP_INTERVAL_MS = 3e3;
242
+ function fsPathFromModuleId(id) {
243
+ return cleanModuleId(id).replace(/^\/@fs\//, "/");
778
244
  }
779
-
780
- // sdk-package-files.ts
781
- import { readFileSync as readFileSync3, realpathSync as realpathSync2 } from "fs";
782
- import { dirname as dirname2, join as join2 } from "path";
783
- var SDK_PACKAGE_NAME = "tempo-sdk";
784
- var SDK_NODE_MODULES_SEGMENT = `/node_modules/${SDK_PACKAGE_NAME}/`;
785
- function createSdkFileMatcher() {
786
- const ownerIsSdkByDirectory = /* @__PURE__ */ new Map();
787
- const nearestPackageIsSdk = (startDirectory) => {
788
- const visited = [];
789
- let directory = startDirectory;
790
- let isSdk = false;
791
- while (true) {
792
- const cached = ownerIsSdkByDirectory.get(directory);
793
- if (cached !== void 0) {
794
- isSdk = cached;
795
- break;
796
- }
797
- visited.push(directory);
798
- const manifest = readPackageManifest(directory);
799
- if (manifest !== void 0) {
800
- isSdk = manifest?.name === SDK_PACKAGE_NAME;
801
- break;
802
- }
803
- const parent = dirname2(directory);
804
- if (parent === directory) break;
805
- directory = parent;
806
- }
807
- for (const entry of visited) ownerIsSdkByDirectory.set(entry, isSdk);
808
- return isSdk;
809
- };
810
- return (file) => {
811
- if (file.replace(/\\/g, "/").includes(SDK_NODE_MODULES_SEGMENT)) {
812
- return true;
813
- }
814
- let realFile = file;
245
+ function fileKey(file) {
246
+ return fsPathFromModuleId(file).replace(/\\/g, "/");
247
+ }
248
+ function createHotUpdateNet() {
249
+ const replay = createRapidHotUpdateReplay();
250
+ const covered = /* @__PURE__ */ new Map();
251
+ const recordCoverage = (file) => {
252
+ const cleanFile = fsPathFromModuleId(file);
253
+ const key = fileKey(file);
815
254
  try {
816
- realFile = realpathSync2.native(file);
255
+ covered.set(key, statSync(cleanFile).mtimeMs);
817
256
  } catch {
257
+ covered.delete(key);
258
+ }
259
+ };
260
+ return {
261
+ recordCoverage,
262
+ lastHotUpdateMtimeMs(file) {
263
+ return covered.get(fileKey(file));
264
+ },
265
+ observeUpdate(server, file) {
266
+ replay.observe(fileKey(file), () => {
267
+ server.config.logger.info(
268
+ `[tempo] replaying settled rapid watcher change: ${file}`,
269
+ { timestamp: true }
270
+ );
271
+ server.watcher.emit("change", file);
272
+ });
273
+ },
274
+ settled(id) {
275
+ return replay.settled(fileKey(id));
276
+ },
277
+ installCoverage(server) {
278
+ for (const event of ["change", "add", "unlink"])
279
+ server.watcher?.prependListener?.(event, recordCoverage);
280
+ },
281
+ installSweep(server, options = {}) {
282
+ const cacheDir = server.config.cacheDir?.replace(/\\/g, "/").replace(/\/+$/, "");
283
+ const sweep = createMissedChangeSweep({
284
+ listServedFiles: () => {
285
+ const files = new Map(
286
+ server.moduleGraph?.fileToModulesMap ?? /* @__PURE__ */ new Map()
287
+ );
288
+ for (const extra of options.listExtraFiles?.() ?? []) {
289
+ const cleanFile = fsPathFromModuleId(extra);
290
+ const file = isAbsolute(cleanFile) ? cleanFile : resolve3(server.config.root, cleanFile);
291
+ if (!files.has(file)) files.set(file, []);
292
+ }
293
+ if (cacheDir) {
294
+ for (const file of files.keys()) {
295
+ if (file.replace(/\\/g, "/").startsWith(`${cacheDir}/`)) {
296
+ files.delete(file);
297
+ }
298
+ }
299
+ }
300
+ dropUnwatched(server, files);
301
+ return files.entries();
302
+ },
303
+ statMtimeMs: async (file) => {
304
+ try {
305
+ return statSync(file).mtimeMs;
306
+ } catch {
307
+ return null;
308
+ }
309
+ },
310
+ emitChange: (file) => {
311
+ server.config?.logger?.info?.(
312
+ `[tempo] re-emitting lost watcher change: ${file}`,
313
+ { timestamp: true }
314
+ );
315
+ server.watcher?.emit?.("change", file);
316
+ },
317
+ lastHotUpdateMtimeMs: (file) => covered.get(fileKey(file))
318
+ });
319
+ let passRunning = false;
320
+ const timer = setInterval(() => {
321
+ if (passRunning) return;
322
+ passRunning = true;
323
+ void sweep.sweep().then(() => options.afterSweep?.()).catch(() => {
324
+ }).finally(() => {
325
+ passRunning = false;
326
+ });
327
+ }, options.sweepIntervalMs ?? HOT_UPDATE_NET_SWEEP_INTERVAL_MS);
328
+ timer.unref?.();
329
+ server.httpServer?.once("close", () => clearInterval(timer));
330
+ },
331
+ clear() {
332
+ replay.clear();
333
+ covered.clear();
818
334
  }
819
- return nearestPackageIsSdk(dirname2(realFile));
820
335
  };
821
336
  }
822
- function readPackageManifest(directory) {
823
- let text;
824
- try {
825
- text = readFileSync3(join2(directory, "package.json"), "utf8");
826
- } catch {
827
- return void 0;
828
- }
829
- try {
830
- const manifest = JSON.parse(text);
831
- return manifest && typeof manifest === "object" ? manifest : null;
832
- } catch {
833
- return null;
337
+ function dropUnwatched(server, files) {
338
+ const watcher = server.watcher;
339
+ const watched = watcher?.getWatched?.();
340
+ if (!watched) return;
341
+ for (const file of [...files.keys()]) {
342
+ const entries = watched[dirname(file)];
343
+ if (entries && !entries.includes(basename(file))) files.delete(file);
834
344
  }
835
345
  }
836
346
 
837
- // vite-client-pending-updates.ts
838
- function preservePendingViteModuleUpdates(source) {
839
- const missingBoundary = /(const mod = this\.hotModulesMap\.get\(path\);\s*)if \(!mod\)\s*(?:return;|\{\s*return;\s*\})/;
840
- const registeredBoundary = "this.hmrClient.hotModulesMap.set(this.ownerPath, mod);";
841
- if (!missingBoundary.test(source) || !source.includes(registeredBoundary)) {
842
- return source;
843
- }
844
- return source.replace(
845
- missingBoundary,
846
- `$1if (!mod || mod.pendingUpdates) {
847
- const pending = mod || {
848
- id: path,
849
- callbacks: [],
850
- pendingUpdates: new Map(),
851
- };
852
- pending.pendingUpdates.set(acceptedPath, update);
853
- this.hotModulesMap.set(path, pending);
854
- return;
855
- }`
856
- ).replace(
857
- registeredBoundary,
858
- `${registeredBoundary}
859
- if (mod.pendingUpdates) {
860
- const pendingUpdates = [...mod.pendingUpdates.values()];
861
- delete mod.pendingUpdates;
862
- queueMicrotask(() => {
863
- for (const update of pendingUpdates) {
864
- void this.hmrClient.queueUpdate(update).catch((error) => {
865
- this.hmrClient.logger.error(error);
866
- });
867
- }
868
- });
869
- }`
870
- );
871
- }
872
-
873
- // tailwind-scan-net.ts
874
- var SCANNABLE_EXTENSIONS = /* @__PURE__ */ new Set([
875
- "ts",
876
- "tsx",
877
- "js",
878
- "jsx",
879
- "mjs",
880
- "cjs",
881
- "html",
882
- "mdx",
883
- "md",
884
- "svelte",
885
- "vue",
886
- "astro"
887
- ]);
888
- var IGNORED_PATH_SEGMENTS = [
889
- "/node_modules/",
890
- "/.git/",
891
- "/.vite/",
892
- "/.tempo/"
893
- ];
894
- var TAILWIND_SCAN_NET_DEBOUNCE_MS = 100;
895
- var TAILWIND_SCAN_NET_MAX_POKES_PER_PAIR = 2;
896
- var POKE_LEDGER_MAX_ENTRIES = 2e4;
897
- function normalizeSlashes(path) {
898
- return path.replace(/\\/g, "/");
899
- }
900
- function fileExtension(path) {
901
- const base = path.slice(path.lastIndexOf("/") + 1);
902
- const dot = base.lastIndexOf(".");
903
- return dot <= 0 ? "" : base.slice(dot + 1).toLowerCase();
904
- }
905
- function isScannableSourceFile(file) {
906
- const normalized = normalizeSlashes(file);
907
- if (!SCANNABLE_EXTENSIONS.has(fileExtension(normalized))) return false;
908
- return !IGNORED_PATH_SEGMENTS.some(
909
- (segment) => normalized.includes(segment)
910
- );
911
- }
912
- function isScanDep(dep) {
913
- if (dep.includes("*")) return true;
914
- const ext = fileExtension(normalizeSlashes(dep));
915
- return ext !== "" && ext !== "css" && SCANNABLE_EXTENSIONS.has(ext);
916
- }
917
- function cssEntryNeedsRescanFor(entry, file) {
918
- if (entry.deps === null) return false;
919
- const normalizedFile = normalizeSlashes(file);
920
- let scansClasses = false;
921
- for (const dep of entry.deps) {
922
- const normalizedDep = normalizeSlashes(dep);
923
- if (normalizedDep === normalizedFile) return false;
924
- if (!scansClasses && isScanDep(normalizedDep)) scansClasses = true;
925
- }
926
- return scansClasses;
927
- }
928
- function createTailwindScanNet(args) {
929
- const debounceMs = args.debounceMs ?? TAILWIND_SCAN_NET_DEBOUNCE_MS;
930
- const maxPokesPerPair = args.maxPokesPerPair ?? TAILWIND_SCAN_NET_MAX_POKES_PER_PAIR;
931
- const pendingCssFiles = /* @__PURE__ */ new Set();
932
- const pokeLedger = /* @__PURE__ */ new Map();
933
- const countedThisWindow = /* @__PURE__ */ new Set();
934
- let flushTimer = null;
935
- let lastFlushAt = Number.NEGATIVE_INFINITY;
936
- let disposed = false;
937
- const flush = () => {
938
- flushTimer = null;
939
- lastFlushAt = Date.now();
940
- countedThisWindow.clear();
941
- const cssFiles = [...pendingCssFiles];
942
- pendingCssFiles.clear();
943
- for (const cssFile of cssFiles) {
944
- args.emitChange(cssFile);
945
- }
946
- };
947
- return {
948
- handleWatcherFile(file) {
949
- if (disposed) return false;
950
- if (!isScannableSourceFile(file)) return false;
951
- let scheduled = false;
952
- for (const entry of args.listCssEntries()) {
953
- if (!cssEntryNeedsRescanFor(entry, file)) continue;
954
- const pairKey = `${entry.cssFile}\0${normalizeSlashes(file)}`;
955
- if (!countedThisWindow.has(pairKey)) {
956
- const pokes = pokeLedger.get(pairKey) ?? 0;
957
- if (pokes >= maxPokesPerPair) continue;
958
- if (pokeLedger.size >= POKE_LEDGER_MAX_ENTRIES) pokeLedger.clear();
959
- pokeLedger.set(pairKey, pokes + 1);
960
- countedThisWindow.add(pairKey);
961
- }
962
- pendingCssFiles.add(entry.cssFile);
963
- scheduled = true;
964
- }
965
- if (scheduled && flushTimer === null) {
966
- const sinceLastFlush = Date.now() - lastFlushAt;
967
- const delay = sinceLastFlush >= debounceMs ? 0 : debounceMs;
968
- flushTimer = setTimeout(flush, delay);
969
- flushTimer.unref?.();
970
- }
971
- return scheduled;
972
- },
973
- dispose() {
974
- disposed = true;
975
- pendingCssFiles.clear();
976
- pokeLedger.clear();
977
- countedThisWindow.clear();
978
- if (flushTimer !== null) {
979
- clearTimeout(flushTimer);
980
- flushTimer = null;
981
- }
982
- }
983
- };
984
- }
985
-
986
- // index.ts
987
- var DEFAULT_INCLUDE = ["**/*.tsx", "**/*.jsx"];
988
- var DEFAULT_EXCLUDE = ["**/node_modules/**"];
989
- var ROOT_META_NAME = "tempo-project-root";
990
- var SOURCE_IDENTITY_ROOT_META_NAME = "tempo-source-identity-root";
991
- var INTERACT_PROJECTION_CLIENT_PATH = "/@tempo/interact-projection";
992
- var INTERACT_PROJECTION_CLIENT_ID = "\0tempo:interact-projection";
993
- var VITE_ERROR_CLIENT_ID = "\0tempo:server-errors";
994
- var INTERACT_PROJECTION_SDK_SPECIFIER = "tempo-sdk/canvas/interact-projection";
995
- function resolveOwnInteractProjectionModule() {
996
- const selfDir = dirname3(fileURLToPath(import.meta.url));
997
- for (const candidate of [
998
- join3(selfDir, "canvas", "interact-projection.ts"),
999
- join3(selfDir, "canvas", "interact-projection.js")
1000
- ]) {
1001
- if (existsSync2(candidate)) return candidate.replace(/\\/g, "/");
1002
- }
1003
- return null;
1004
- }
1005
- var INTERACT_PROJECTION_BOOTSTRAP = `
1006
- (function() {
1007
- if (window.parent === window || (window.name !== ${JSON.stringify(TEMPO_INTERACT_FRAME_NAME)} && !window.name.startsWith(${JSON.stringify(`${TEMPO_INTERACT_FRAME_NAME}:`)}))) return;
1008
- var roots = new Map();
1009
- var existing = window.__REACT_DEVTOOLS_GLOBAL_HOOK__;
1010
- if (existing) {
1011
- if (existing.__tempoPendingFiberRoots) return;
1012
- existing.__tempoPendingFiberRoots = roots;
1013
- var originalCommit = existing.onCommitFiberRoot && existing.onCommitFiberRoot.bind(existing);
1014
- existing.onCommitFiberRoot = function(rendererId, root) {
1015
- if (existing.__tempoPendingFiberRoots === roots) roots.set(rendererId, root);
1016
- if (originalCommit) originalCommit.apply(null, arguments);
1017
- };
1018
- return;
1019
- }
1020
- window.__REACT_DEVTOOLS_GLOBAL_HOOK__ = {
1021
- supportsFiber: true,
1022
- renderers: new Map(),
1023
- __tempoPendingFiberRoots: roots,
1024
- inject: function(renderer) {
1025
- var id = this.renderers.size + 1;
1026
- this.renderers.set(id, renderer);
1027
- return id;
1028
- },
1029
- onCommitFiberRoot: function(rendererId, root) {
1030
- if (this.__tempoPendingFiberRoots === roots) roots.set(rendererId, root);
1031
- },
1032
- onCommitFiberUnmount: function() {},
1033
- checkDCE: function() {},
1034
- onScheduleFiberRoot: function() {}
1035
- };
1036
- })();`;
1037
- function cleanModuleId(id) {
1038
- return id.replace(/[?#].*$/, "");
1039
- }
1040
- function fsPathFromModuleId(id) {
1041
- return cleanModuleId(id).replace(/^\/@fs\//, "/");
1042
- }
1043
- function isCanvasHostRequest(requestPath) {
1044
- const url = new URL(requestPath, "http://tempo.local");
1045
- return url.pathname.replace(/\/+$/, "") === "/tempo-host";
1046
- }
1047
- function isDeclarativeCanvasHostRequest(requestPath) {
1048
- if (!isCanvasHostRequest(requestPath)) return false;
1049
- const params = new URL(requestPath, "http://tempo.local").searchParams;
1050
- const canvasPath = params.get("canvasPath")?.trim() ?? params.get("pageFile")?.trim() ?? params.get("importPath")?.trim();
1051
- const storyboardId = params.get("storyboardId")?.trim() ?? params.get("exportName")?.trim() ?? params.get("importName")?.trim();
1052
- return !canvasPath || !storyboardId;
1053
- }
1054
- var MAX_UNRESOLVED_IMPORTS = 256;
1055
- var RELATIVE_IMPORT_RESOLVE_EXTENSIONS = [
1056
- ".mjs",
1057
- ".js",
1058
- ".mts",
1059
- ".ts",
1060
- ".jsx",
1061
- ".tsx",
1062
- ".json"
1063
- ];
1064
- var UNRESOLVED_IMPORT_WATCH_REARM_MS = 1e3;
1065
- function isRelativeImportSpecifier(specifier) {
1066
- return specifier.startsWith("./") || specifier.startsWith("../");
1067
- }
1068
- function barePackageName(specifier) {
1069
- if (!specifier || specifier.startsWith(".") || specifier.startsWith("/") || specifier.startsWith("\0") || specifier.startsWith("#") || specifier.includes(":")) {
1070
- return void 0;
1071
- }
1072
- const segments = specifier.split("/");
1073
- const packageName = specifier.startsWith("@") ? segments.length >= 2 && segments[0] !== "@" && segments[1] ? `${segments[0]}/${segments[1]}` : void 0 : segments[0];
1074
- return packageName && /^@?[A-Za-z0-9_][A-Za-z0-9._/-]*$/.test(packageName) ? packageName : void 0;
1075
- }
1076
- function resolvedIdMatchesFile(id, file) {
1077
- const resolvedFile = fsPathFromModuleId(id);
1078
- try {
1079
- return realpathSync3.native(resolvedFile) === realpathSync3.native(file);
1080
- } catch {
1081
- return resolvedFile.replace(/\\/g, "/") === file.replace(/\\/g, "/");
1082
- }
1083
- }
1084
- function moduleIdsMatch(left, right) {
1085
- const normalize2 = (value) => cleanModuleId(value).replace(/^file:\/\//, "").replace(/^\/@fs\//, "/").replace(/\\/g, "/").replace(/^\/+/, "");
1086
- return normalize2(left) === normalize2(right);
1087
- }
1088
- function resolveCanonicalRoot(root) {
1089
- try {
1090
- return realpathSync3.native(root);
1091
- } catch {
1092
- return root;
1093
- }
1094
- }
1095
- function hasRootMetaTag(html) {
1096
- return /<meta[^>]+name=["']tempo-project-root["'][^>]*>/i.test(html);
1097
- }
1098
- function hasSourceIdentityRootMetaTag(html) {
1099
- return /<meta[^>]+name=["']tempo-source-identity-root["'][^>]*>/i.test(html);
1100
- }
1101
- function hasWorkspaceNonceMetaTag(html) {
1102
- return new RegExp(
1103
- `<meta[^>]+name=["']${TEMPO_WORKSPACE_NONCE_META_NAME}["'][^>]*>`,
1104
- "i"
1105
- ).test(html);
1106
- }
1107
- function isSameError(left, right) {
1108
- return left.type === right.type && left.message === right.message && left.loc?.line === right.loc?.line && left.loc?.column === right.loc?.column;
347
+ // compile-error-stream.ts
348
+ var MISSED_CHANGE_SWEEP_INTERVAL_MS = HOT_UPDATE_NET_SWEEP_INTERVAL_MS;
349
+ function isSameError(left, right) {
350
+ return left.type === right.type && left.message === right.message && left.loc?.line === right.loc?.line && left.loc?.column === right.loc?.column;
1109
351
  }
1110
352
  function createErrorServer(onErrorFile, onState) {
1111
353
  const errorsByFile = /* @__PURE__ */ new Map();
@@ -1159,34 +401,278 @@ function createErrorServer(onErrorFile, onState) {
1159
401
  };
1160
402
  return server;
1161
403
  }
1162
- function readBody(req) {
1163
- return new Promise((resolve6, reject) => {
1164
- const chunks = [];
1165
- req.on("data", (chunk) => chunks.push(chunk));
1166
- req.on("end", () => resolve6(Buffer.concat(chunks).toString()));
1167
- req.on("error", reject);
1168
- });
404
+ function moduleIdsMatch(left, right) {
405
+ const normalize2 = (value) => cleanModuleId(value).replace(/^file:\/\//, "").replace(/^\/@fs\//, "/").replace(/\\/g, "/").replace(/^\/+/, "");
406
+ return normalize2(left) === normalize2(right);
1169
407
  }
1170
- var CANVAS_HOST_WRAPPER_URL = "/.tempo/tempo-host";
1171
- function readGeneratedCanvasPaths(source) {
1172
- const paths = /* @__PURE__ */ new Set();
1173
- const canvasPathPattern = /\bcanvasPath:\s*("(?:\\.|[^"\\])*")/g;
1174
- for (const match of source.matchAll(canvasPathPattern)) {
408
+ var COMPILE_ERROR_POLL_MAX_INTERVAL_MS = 3e4;
409
+ function createCompileErrorStream(options = {}) {
410
+ let attachedServer;
411
+ const errorServer = createErrorServer(
412
+ options.onErrorFile,
413
+ (error) => attachedServer?.ws.send(VITE_ERROR_STATE_EVENT, error)
414
+ );
415
+ const normalizedFileKey = (file) => file.replace(/\\/g, "/");
416
+ const hasActiveCompileError = (file) => errorServer.errorFiles.some((errorFile) => moduleIdsMatch(errorFile, file));
417
+ const recoverActiveCompileError = async (server, file) => {
418
+ if (!hasActiveCompileError(file)) return false;
419
+ const cleanFile = fsPathFromModuleId(file);
420
+ const requestId = `/@fs/${cleanFile.replace(/^\/+/, "")}`;
421
+ const clientEnvironment = server.environments?.client;
422
+ const transformer = clientEnvironment ?? server;
1175
423
  try {
1176
- const parsed = JSON.parse(match[1] ?? "");
1177
- if (typeof parsed !== "string") continue;
1178
- const normalized = normalizeCanvasRegistrationPath(parsed);
1179
- if (normalized) paths.add(normalized);
1180
- } catch {
1181
- }
424
+ const source = readFileSync(cleanFile, "utf8");
425
+ const canvasModule = /\.canvas\.[cm]?[jt]sx?$/.test(cleanFile);
426
+ const hasDefault = (code) => {
427
+ const parsed = parseSync(cleanFile, code);
428
+ return !parsed.errors.length && parsed.program.body.some(
429
+ (node) => node.type === "ExportDefaultDeclaration" || node.type === "ExportNamedDeclaration" && node.exportKind !== "type" && node.specifiers.some(
430
+ (specifier) => specifier.exportKind !== "type" && (specifier.exported.type === "Identifier" ? specifier.exported.name : specifier.exported.value) === "default"
431
+ )
432
+ );
433
+ };
434
+ if (canvasModule && !hasDefault(source)) return false;
435
+ let canonicalFile = cleanFile;
436
+ try {
437
+ canonicalFile = realpathSync(cleanFile);
438
+ } catch {
439
+ }
440
+ const modules = /* @__PURE__ */ new Set([
441
+ ...transformer.moduleGraph.getModulesByFile(canonicalFile) ?? [],
442
+ ...transformer.moduleGraph.getModulesByFile(cleanFile) ?? []
443
+ ]);
444
+ for (const module of modules) {
445
+ transformer.moduleGraph.invalidateModule(module);
446
+ }
447
+ const result = await transformer.transformRequest(requestId);
448
+ if (!result) return false;
449
+ if (readFileSync(cleanFile, "utf8") !== source) return false;
450
+ if (canvasModule && (typeof result !== "object" || !("code" in result) || typeof result.code !== "string" || !hasDefault(result.code)))
451
+ return false;
452
+ } catch {
453
+ return false;
454
+ }
455
+ errorServer.clearErrorForModules([file, cleanFile, requestId]);
456
+ server.config.logger.info(
457
+ `[tempo] recovered compile-error module after validated transform: ${cleanFile}`,
458
+ { timestamp: true }
459
+ );
460
+ (clientEnvironment?.hot ?? server.ws).send({
461
+ type: "full-reload",
462
+ path: "*"
463
+ });
464
+ return true;
465
+ };
466
+ const compileErrorPollSchedule = /* @__PURE__ */ new Map();
467
+ const pollCompileErrorRecovery = async (server) => {
468
+ const activeFiles = new Map(
469
+ errorServer.errorFiles.map((file) => [
470
+ normalizedFileKey(fsPathFromModuleId(file)),
471
+ file
472
+ ])
473
+ );
474
+ for (const key of [...compileErrorPollSchedule.keys()]) {
475
+ if (!activeFiles.has(key)) compileErrorPollSchedule.delete(key);
476
+ }
477
+ const nowMs = Date.now();
478
+ for (const [key, file] of activeFiles) {
479
+ const schedule = compileErrorPollSchedule.get(key);
480
+ if (schedule && nowMs < schedule.nextAttemptAtMs) continue;
481
+ if (await recoverActiveCompileError(server, file)) {
482
+ compileErrorPollSchedule.delete(key);
483
+ continue;
484
+ }
485
+ const intervalMs = schedule?.intervalMs ?? MISSED_CHANGE_SWEEP_INTERVAL_MS;
486
+ compileErrorPollSchedule.set(key, {
487
+ nextAttemptAtMs: nowMs + intervalMs,
488
+ intervalMs: Math.min(
489
+ intervalMs * 2,
490
+ COMPILE_ERROR_POLL_MAX_INTERVAL_MS
491
+ )
492
+ });
493
+ }
494
+ };
495
+ return {
496
+ errorServer,
497
+ attach(server) {
498
+ attachedServer = server;
499
+ server.ws.on?.(VITE_ERROR_SUBSCRIBE_EVENT, (_data, client) => {
500
+ client.send(VITE_ERROR_STATE_EVENT, errorServer.currentError);
501
+ });
502
+ },
503
+ handleRequest(req, res) {
504
+ const url = req.url;
505
+ if (url === "/__tempo/report-error" && req.method === "POST") {
506
+ readBody(req).then((body) => {
507
+ try {
508
+ errorServer.setError(JSON.parse(body));
509
+ } catch {
510
+ }
511
+ res.statusCode = 200;
512
+ res.end("ok");
513
+ });
514
+ return true;
515
+ }
516
+ if (url === "/__tempo/report-clear" && req.method === "POST") {
517
+ errorServer.clearAll();
518
+ res.statusCode = 200;
519
+ res.end("ok");
520
+ return true;
521
+ }
522
+ if (url === "/__tempo/errors" && req.method === "OPTIONS") {
523
+ res.writeHead(204, {
524
+ "Access-Control-Allow-Origin": "*",
525
+ "Access-Control-Allow-Methods": "GET, OPTIONS",
526
+ "Access-Control-Allow-Headers": "*"
527
+ });
528
+ res.end();
529
+ return true;
530
+ }
531
+ if (url === "/__tempo/errors" && req.method === "GET") {
532
+ res.writeHead(200, {
533
+ "Content-Type": "text/event-stream",
534
+ "Cache-Control": "no-cache",
535
+ Connection: "keep-alive",
536
+ "Access-Control-Allow-Origin": "*"
537
+ });
538
+ res.write(`data: ${JSON.stringify(errorServer.currentError)}
539
+
540
+ `);
541
+ errorServer.clients.add(res);
542
+ req.on("close", () => {
543
+ errorServer.clients.delete(res);
544
+ });
545
+ return true;
546
+ }
547
+ return false;
548
+ },
549
+ recordHmrError(err) {
550
+ errorServer.setError({
551
+ type: "compile",
552
+ message: err?.message ?? "Unknown error",
553
+ stack: err?.stack,
554
+ file: err?.id ?? err?.loc?.file,
555
+ frame: err?.frame,
556
+ plugin: err?.plugin,
557
+ loc: err?.loc
558
+ });
559
+ },
560
+ hasActiveCompileError,
561
+ recover: recoverActiveCompileError,
562
+ pollRecovery: pollCompileErrorRecovery,
563
+ reset() {
564
+ compileErrorPollSchedule.clear();
565
+ }
566
+ };
567
+ }
568
+ function readBody(req) {
569
+ return new Promise((resolve8, reject) => {
570
+ const chunks = [];
571
+ req.on("data", (chunk) => chunks.push(chunk));
572
+ req.on("end", () => resolve8(Buffer.concat(chunks).toString()));
573
+ req.on("error", reject);
574
+ });
575
+ }
576
+
577
+ // canvas-host-registration-barrier.ts
578
+ import { readFileSync as readFileSync3, realpathSync as realpathSync2 } from "fs";
579
+ import { relative as relative2, resolve as resolve4 } from "path";
580
+
581
+ // canvas-host-registration-contract.ts
582
+ var CANVAS_HOST_REGISTRATION_ENDPOINT = "/__tempo/canvas-host-registration";
583
+ var CANVAS_HOST_REGISTRATION_CAPABILITY_HEADER = "x-tempo-canvas-host-registration";
584
+ function normalizeCanvasRegistrationPath(canvasPath) {
585
+ return canvasPath.trim().replace(/\\/g, "/").replace(/^\.\/+/, "").replace(/^\/+/, "");
586
+ }
587
+
588
+ // canvas-host-registration-work.ts
589
+ import { readFileSync as readFileSync2 } from "fs";
590
+ async function traceSlowRegistration(work, report) {
591
+ const startedAt = performance.now();
592
+ let slow = false;
593
+ const timer = setTimeout(() => {
594
+ slow = true;
595
+ report("pending", Math.round(performance.now() - startedAt));
596
+ }, 5e3);
597
+ const settled = (status) => {
598
+ const elapsedMs = Math.round(performance.now() - startedAt);
599
+ if (slow || elapsedMs >= 5e3) report(status, elapsedMs);
600
+ };
601
+ try {
602
+ const result = await work();
603
+ settled("ready");
604
+ return result;
605
+ } catch (error) {
606
+ settled("error");
607
+ throw error;
608
+ } finally {
609
+ clearTimeout(timer);
610
+ }
611
+ }
612
+ function createRegistrationTransforms() {
613
+ const receipts = /* @__PURE__ */ new Map();
614
+ return async function confirm(file, transform) {
615
+ const source = readFileSync2(file, "utf8");
616
+ const previous = receipts.get(file);
617
+ if (previous?.source === source && (previous.pending || previous.current())) {
618
+ return previous.result;
619
+ }
620
+ const receipt = {
621
+ source,
622
+ pending: true,
623
+ current: () => false,
624
+ result: Promise.resolve()
625
+ };
626
+ receipts.set(file, receipt);
627
+ receipt.result = Promise.resolve().then(async () => {
628
+ receipt.current = await transform();
629
+ receipt.pending = false;
630
+ }).catch((error) => {
631
+ if (receipts.get(file) === receipt) receipts.delete(file);
632
+ throw error;
633
+ });
634
+ return receipt.result;
635
+ };
636
+ }
637
+ async function registrationReply(work, progress, poll, intervalMs = 1e3) {
638
+ if (!poll) {
639
+ await work;
640
+ return null;
641
+ }
642
+ let timer;
643
+ try {
644
+ return await Promise.race([
645
+ work.then(() => null),
646
+ new Promise((resolve8) => {
647
+ timer = setTimeout(() => resolve8(progress()), intervalMs);
648
+ })
649
+ ]);
650
+ } finally {
651
+ clearTimeout(timer);
652
+ }
653
+ }
654
+
655
+ // canvas-host-registration-barrier.ts
656
+ var CANVAS_HOST_WRAPPER_URL = "/.tempo/tempo-host";
657
+ function readGeneratedCanvasPaths(source) {
658
+ const paths = /* @__PURE__ */ new Set();
659
+ const canvasPathPattern = /\bcanvasPath:\s*("(?:\\.|[^"\\])*")/g;
660
+ for (const match of source.matchAll(canvasPathPattern)) {
661
+ try {
662
+ const parsed = JSON.parse(match[1] ?? "");
663
+ if (typeof parsed !== "string") continue;
664
+ const normalized = normalizeCanvasRegistrationPath(parsed);
665
+ if (normalized) paths.add(normalized);
666
+ } catch {
667
+ }
1182
668
  }
1183
669
  return [...paths];
1184
670
  }
1185
671
  async function synchronizeCanvasHostRegistrationTransform(server, canvasPath) {
1186
- const wrapperPath = resolve5(server.config.root, ".tempo", "tempo-host.tsx");
672
+ const wrapperPath = resolve4(server.config.root, ".tempo", "tempo-host.tsx");
1187
673
  let wrapperSource;
1188
674
  try {
1189
- wrapperSource = readFileSync4(wrapperPath, "utf8");
675
+ wrapperSource = readFileSync3(wrapperPath, "utf8");
1190
676
  } catch (error) {
1191
677
  throw new Error(
1192
678
  `Canvas host wrapper is unavailable at ${wrapperPath}: ${error instanceof Error ? error.message : String(error)}`
@@ -1203,7 +689,7 @@ async function synchronizeCanvasHostRegistrationTransform(server, canvasPath) {
1203
689
  { statusCode: 409 }
1204
690
  );
1205
691
  }
1206
- const canonicalWrapperPath = realpathSync3(wrapperPath);
692
+ const canonicalWrapperPath = realpathSync2(wrapperPath);
1207
693
  const modulePattern = /\bcanvasPath:\s*("(?:\\.|[^"\\])*")\s*,\s*load:\s*\(\)\s*=>\s*import\(\s*("(?:\\.|[^"\\])*")\s*\)/g;
1208
694
  let moduleUrl;
1209
695
  const transformer = server.environments?.client ?? server;
@@ -1216,13 +702,14 @@ async function synchronizeCanvasHostRegistrationTransform(server, canvasPath) {
1216
702
  );
1217
703
  if (!resolvedModule) throw new Error(`Cannot resolve canvas ${canvasPath}`);
1218
704
  const modulePath = fsPathFromModuleId(resolvedModule.id);
1219
- moduleUrl = `/@fs/${modulePath.replace(/^\/+/, "")}`;
705
+ const fsUrl = `/@fs/${modulePath.replace(/^\/+/, "")}`;
706
+ moduleUrl = `${viteBasePath(server)}${fsUrl.slice(1)}`;
1220
707
  await retransformCanvasHostWrapper(
1221
708
  server,
1222
709
  transformer,
1223
- realpathSync3(modulePath),
710
+ realpathSync2(modulePath),
1224
711
  modulePath,
1225
- `/@fs/${modulePath.replace(/^\/+/, "")}`
712
+ fsUrl
1226
713
  );
1227
714
  break;
1228
715
  }
@@ -1234,6 +721,11 @@ async function synchronizeCanvasHostRegistrationTransform(server, canvasPath) {
1234
721
  );
1235
722
  return wrapperSource.includes("tempo-incremental-canvas-registration") ? moduleUrl : void 0;
1236
723
  }
724
+ function viteBasePath(server) {
725
+ const base = server.config.base || "/";
726
+ const path = base.startsWith("/") ? base : new URL(base, "http://tempo.invalid").pathname;
727
+ return path.endsWith("/") ? path : `${path}/`;
728
+ }
1237
729
  var registrationTransforms = /* @__PURE__ */ new WeakMap();
1238
730
  var registrationActivity = /* @__PURE__ */ new WeakMap();
1239
731
  function registrationProgress(server) {
@@ -1298,21 +790,40 @@ function writeCanvasRegistrationResponseHeaders(res) {
1298
790
  );
1299
791
  res.setHeader(CANVAS_HOST_REGISTRATION_CAPABILITY_HEADER, "1");
1300
792
  }
1301
- function handleTempoMiddleware(errorServer, viteServer, req, res, next) {
1302
- const url = req.url;
1303
- if (!url?.startsWith("/__tempo/")) return next();
1304
- if (url === TEMPO_HOST_IDENTITY_ENDPOINT && req.method === "GET") {
1305
- const identity = createTempoHostIdentity("vite", {
1306
- root: viteServer.config?.root,
1307
- pluginActive: true
1308
- });
1309
- res.statusCode = 200;
1310
- res.setHeader("Cache-Control", "no-store");
1311
- res.setHeader("Content-Type", "application/json; charset=utf-8");
1312
- res.setHeader(TEMPO_HOST_IDENTITY_CAPABILITY_HEADER, "1");
1313
- res.end(JSON.stringify(identity));
793
+ function isIncrementalWrapperFile(file, wrapperPath) {
794
+ if (file.replace(/\\/g, "/") !== wrapperPath.replace(/\\/g, "/"))
795
+ return false;
796
+ try {
797
+ return readFileSync3(file, "utf8").includes(
798
+ "tempo-incremental-canvas-registration"
799
+ );
800
+ } catch {
801
+ return false;
802
+ }
803
+ }
804
+ function withRegisteredCanvasLoader(file, paths, graph, modules) {
805
+ const canvasPath = relative2(paths.sourceRoot, file).replace(/\\/g, "/");
806
+ let source;
807
+ try {
808
+ source = readFileSync3(paths.wrapperPath, "utf8");
809
+ } catch {
1314
810
  return;
1315
811
  }
812
+ if (!readGeneratedCanvasPaths(source).includes(canvasPath)) return;
813
+ const wrappers = graph.getModulesByFile(paths.wrapperPath);
814
+ if (!wrappers?.size) return;
815
+ for (const wrapper of wrappers) graph.invalidateModule(wrapper);
816
+ return [.../* @__PURE__ */ new Set([...modules, ...wrappers])];
817
+ }
818
+ function resetCanvasHostRegistration(server) {
819
+ registrationActivity.set(server, 0);
820
+ registrationTransforms.delete(server.environments?.client ?? server);
821
+ }
822
+ function noteCanvasHostRegistrationActivity(server) {
823
+ registrationActivity.set(server, (registrationActivity.get(server) ?? 0) + 1);
824
+ }
825
+ function handleCanvasHostRegistrationRequest(viteServer, req, res) {
826
+ const url = req.url;
1316
827
  if (url === CANVAS_HOST_REGISTRATION_ENDPOINT && req.method === "OPTIONS") {
1317
828
  writeCanvasRegistrationResponseHeaders(res);
1318
829
  res.writeHead(204, {
@@ -1320,11 +831,11 @@ function handleTempoMiddleware(errorServer, viteServer, req, res, next) {
1320
831
  "Access-Control-Allow-Headers": "content-type"
1321
832
  });
1322
833
  res.end();
1323
- return;
834
+ return true;
1324
835
  }
1325
836
  if (url === CANVAS_HOST_REGISTRATION_ENDPOINT && req.method === "POST") {
1326
837
  writeCanvasRegistrationResponseHeaders(res);
1327
- void readBody(req).then(async (body) => {
838
+ void readBody2(req).then(async (body) => {
1328
839
  const parsed = JSON.parse(body);
1329
840
  const canvasPath = typeof parsed.canvasPath === "string" ? normalizeCanvasRegistrationPath(parsed.canvasPath) : "";
1330
841
  if (!canvasPath) {
@@ -1357,104 +868,1004 @@ function handleTempoMiddleware(errorServer, viteServer, req, res, next) {
1357
868
  res.setHeader("Content-Type", "text/plain; charset=utf-8");
1358
869
  res.end(error instanceof Error ? error.message : String(error));
1359
870
  });
1360
- return;
871
+ return true;
1361
872
  }
1362
- if (url === "/__tempo/report-error" && req.method === "POST") {
1363
- readBody(req).then((body) => {
1364
- try {
1365
- errorServer.setError(JSON.parse(body));
1366
- } catch {
1367
- }
1368
- res.statusCode = 200;
1369
- res.end("ok");
1370
- });
1371
- return;
873
+ return false;
874
+ }
875
+ function readBody2(req) {
876
+ return new Promise((resolve8, reject) => {
877
+ const chunks = [];
878
+ req.on("data", (chunk) => chunks.push(chunk));
879
+ req.on("end", () => resolve8(Buffer.concat(chunks).toString()));
880
+ req.on("error", reject);
881
+ });
882
+ }
883
+
884
+ // index.ts
885
+ import {
886
+ existsSync as existsSync4,
887
+ realpathSync as realpathSync5,
888
+ statSync as statSync2,
889
+ watch as watchFileSystem
890
+ } from "fs";
891
+ import { createRequire } from "module";
892
+ import { dirname as dirname4, join as join4, relative as relative3, resolve as resolve7 } from "path";
893
+ import { fileURLToPath as fileURLToPath2 } from "url";
894
+ import { createFilter } from "@rollup/pluginutils";
895
+
896
+ // jsx-module-annotation.ts
897
+ import {
898
+ closeSync,
899
+ fstatSync,
900
+ openSync,
901
+ readFileSync as readFileSync4,
902
+ realpathSync as realpathSync4
903
+ } from "fs";
904
+ import { dirname as dirname3, isAbsolute as isAbsolute3, resolve as resolve6 } from "path";
905
+ import { fileURLToPath } from "url";
906
+
907
+ // assets/controls-transform.ts
908
+ function transformControlsForHmr(source, filePath, previouslyDefinedControls = false) {
909
+ const calls = source.includes("defineControls") ? parseControlsFile(filePath, source) : [];
910
+ if (!calls.length && !previouslyDefinedControls) return source;
911
+ for (const { start, end } of calls.reverse()) {
912
+ source = source.slice(0, start) + `((dispose) => { if (import.meta.hot && typeof dispose === "function") import.meta.hot.data.__tempoControlsDisposers.push(dispose); })(${source.slice(start, end)})` + source.slice(end);
913
+ }
914
+ return `if (import.meta.hot) {
915
+ for (const dispose of import.meta.hot.data.__tempoControlsDisposers ?? []) dispose();
916
+ import.meta.hot.data.__tempoControlsDisposers = [];
917
+ import.meta.hot.dispose(() => {
918
+ for (const dispose of import.meta.hot.data.__tempoControlsDisposers ?? []) dispose();
919
+ import.meta.hot.data.__tempoControlsDisposers = [];
920
+ });
921
+ }
922
+ ${source}`;
923
+ }
924
+
925
+ // canvas-component-reference.ts
926
+ import { realpathSync as realpathSync3 } from "fs";
927
+ import { dirname as dirname2, isAbsolute as isAbsolute2, normalize, posix, resolve as resolve5 } from "path";
928
+ var COMPONENT_REFERENCE_ATTRIBUTE = "data-tempo-component-reference";
929
+ function moduleIdentity(file, specifier, resolved) {
930
+ const resolvedId = resolved?.get(specifier);
931
+ const bundled = resolvedId?.startsWith("\0tempo:astro-component:") ? decodeURIComponent(
932
+ resolvedId.slice("\0tempo:astro-component:".length, -3)
933
+ ) : resolvedId;
934
+ const target = bundled === void 0 ? specifier : bundled.replace(/\bt=\d{13}&?\b/, "").replace(/[?&]$/, "");
935
+ if (target.startsWith("\0")) return target;
936
+ const suffixAt = target.search(/[?#]/);
937
+ let path = (suffixAt < 0 ? target : target.slice(0, suffixAt)).replace(
938
+ /\\/g,
939
+ "/"
940
+ );
941
+ const suffix = suffixAt < 0 || target.endsWith(".astro?tempo-component") ? "" : target.slice(suffixAt);
942
+ if (bundled === void 0 && path.startsWith("."))
943
+ path = resolve5(dirname2(file), path);
944
+ if (!isAbsolute2(path) && !/^[A-Za-z]:\//.test(path)) return target;
945
+ if (bundled !== void 0) {
946
+ try {
947
+ path = realpathSync3.native(path);
948
+ } catch {
949
+ }
950
+ }
951
+ return normalize(path).replace(/\\/g, "/") + suffix;
952
+ }
953
+ function canvasComponentAnnotations(file, source, resolved, hostRoot) {
954
+ const result = /* @__PURE__ */ new Map();
955
+ if (!source.includes("tempo-sdk/canvas")) return result;
956
+ const parsed = parseCanvasFile(file, source);
957
+ for (const board of parsed.storyboards) {
958
+ if (board.kind !== "component" || board.openingElementSpan === void 0)
959
+ continue;
960
+ const flutterPreview = board.preview ? parseFlutterPreview(board.preview) : null;
961
+ if (flutterPreview && !("error" in flutterPreview) && hostRoot) {
962
+ let key;
963
+ try {
964
+ const absolute = resolve5(
965
+ dirname2(canonicalPathAllowMissing(file)),
966
+ flutterPreview.file
967
+ );
968
+ key = flutterPreviewKey(
969
+ hostRoot,
970
+ absolute,
971
+ flutterPreview.functionName
972
+ );
973
+ } catch {
974
+ continue;
975
+ }
976
+ result.set(board.openingElementSpan.start, {
977
+ [FLUTTER_PREVIEW_KEY_ATTRIBUTE]: key,
978
+ [COMPONENT_REFERENCE_ATTRIBUTE]: JSON.stringify([
979
+ "flutter",
980
+ key.slice(0, key.lastIndexOf("#")),
981
+ flutterPreview.functionName
982
+ ]),
983
+ "data-tempo-external-component": "true"
984
+ });
985
+ continue;
986
+ }
987
+ const ref = board.component;
988
+ if (!ref?.localName) continue;
989
+ const member = ref.expression.match(
990
+ /^\s*([$\w]+)(?:\s*\.\s*([$\w]+))?\s*$/
991
+ );
992
+ if (!member) continue;
993
+ let name;
994
+ if (ref.import) {
995
+ if (ref.import.kind === "namespace") {
996
+ if (!member[2]) continue;
997
+ name = member[2];
998
+ } else {
999
+ if (member[2]) continue;
1000
+ name = ref.import.importedName;
1001
+ }
1002
+ } else {
1003
+ if (member[2]) continue;
1004
+ name = ref.localName;
1005
+ }
1006
+ const specifier = ref.import?.source.replace(/\\/g, "/").replace(/[?#].*/, "");
1007
+ const canvasDir = posix.dirname(file.replace(/\\/g, "/"));
1008
+ const external = specifier !== void 0 && (!specifier.startsWith(".") || !posix.join(canvasDir, specifier).startsWith(`${canvasDir}/`));
1009
+ result.set(board.openingElementSpan.start, {
1010
+ [COMPONENT_REFERENCE_ATTRIBUTE]: JSON.stringify([
1011
+ ref.import ? "import" : "local",
1012
+ moduleIdentity(file, ref.import?.source ?? file, resolved),
1013
+ name
1014
+ ]),
1015
+ ...external ? { "data-tempo-external-component": "true" } : {}
1016
+ });
1017
+ }
1018
+ return result;
1019
+ }
1020
+
1021
+ // default-export-identity.ts
1022
+ var FUNCTION_DEFAULT_RE = /^(?:async\s+)?function(?:\s*\*)?(?:\s+([A-Za-z_$][\w$]*))?\s*\(/;
1023
+ var CLASS_DEFAULT_RE = /^(?:abstract\s+)?class(?:\s+([A-Za-z_$][\w$]*))?(?=[\s{])/;
1024
+ var ARROW_DEFAULT_RE = /^(?:async\s+)?(?:\([^()]*\)|[A-Za-z_$][\w$]*)\s*=>/;
1025
+ var IDENTIFIER_DEFAULT_RE = /^([A-Za-z_$][\w$]*)[ \t]*(?:;|\r?\n|$)/;
1026
+ function readDefaultExportIdentity(source) {
1027
+ const start = /\bexport\s+default\s+/.exec(source);
1028
+ if (!start) return null;
1029
+ const tail = source.slice(start.index + start[0].length);
1030
+ const fn = FUNCTION_DEFAULT_RE.exec(tail);
1031
+ if (fn) return { kind: "function", name: fn[1] ?? null };
1032
+ const cls = CLASS_DEFAULT_RE.exec(tail);
1033
+ if (cls) return { kind: "class", name: cls[1] ?? null };
1034
+ if (ARROW_DEFAULT_RE.test(tail)) return { kind: "function", name: null };
1035
+ const identifier = IDENTIFIER_DEFAULT_RE.exec(tail);
1036
+ if (identifier) return { kind: "identifier", name: identifier[1] };
1037
+ return null;
1038
+ }
1039
+ function isDefaultExportIdentityRewrite(before, after) {
1040
+ if (!before) return false;
1041
+ if (before.name === null) return true;
1042
+ if (!after) return false;
1043
+ if (before.name === after.name) return false;
1044
+ return isComponentShaped(before) && isComponentShaped(after);
1045
+ }
1046
+ function isComponentShaped(identity) {
1047
+ return identity.name === null || /^[A-Z]/.test(identity.name);
1048
+ }
1049
+
1050
+ // jsx-module-annotation.ts
1051
+ function createJsxModuleAnnotation(options) {
1052
+ const controlsModules = /* @__PURE__ */ new Set();
1053
+ function transformControls(source, id) {
1054
+ const code = transformControlsForHmr(source, id, controlsModules.has(id));
1055
+ if (code !== source) controlsModules.add(id);
1056
+ return code;
1057
+ }
1058
+ const defaultExportIdentityByFile = /* @__PURE__ */ new Map();
1059
+ const canonicalIdentityKey = (idOrFile) => {
1060
+ const file = fsPathFromModuleId(idOrFile);
1061
+ try {
1062
+ return realpathSync4.native(file);
1063
+ } catch {
1064
+ return file.replace(/\\/g, "/");
1065
+ }
1066
+ };
1067
+ async function annotateJsxModule(context, source, cleanId) {
1068
+ const controlsSource = options.transformsControls(cleanId) ? transformControls(source, cleanId) : source;
1069
+ const filepath = options.stampedFilepath(cleanId);
1070
+ if (filepath === null) {
1071
+ if (controlsSource !== source) return { code: controlsSource, map: null };
1072
+ return null;
1073
+ }
1074
+ try {
1075
+ const descriptor = openSync(cleanId, "r");
1076
+ let snapshot;
1077
+ try {
1078
+ const before2 = fstatSync(descriptor);
1079
+ const rawSource2 = readFileSync4(descriptor, "utf8");
1080
+ snapshot = { before: before2, rawSource: rawSource2, after: fstatSync(descriptor) };
1081
+ } finally {
1082
+ closeSync(descriptor);
1083
+ }
1084
+ const { before, after, rawSource } = snapshot;
1085
+ const stable = ["mtimeMs", "ctimeMs", "size", "ino", "dev"];
1086
+ let loadedSource = source === rawSource ? source : void 0;
1087
+ if (loadedSource === void 0 && typeof context.getCombinedSourcemap === "function") {
1088
+ try {
1089
+ const map = context.getCombinedSourcemap();
1090
+ const sourceRoot = map.sourceRoot;
1091
+ const matches = map.sources.flatMap((path, index) => {
1092
+ const sourcePath = path.startsWith("file:") ? fileURLToPath(path) : path;
1093
+ const file = isAbsolute3(sourcePath) ? sourcePath : resolve6(
1094
+ dirname3(cleanId),
1095
+ typeof sourceRoot === "string" ? sourceRoot : "",
1096
+ sourcePath
1097
+ );
1098
+ let sameFile = cleanModuleId(file).replace(/\\/g, "/") === cleanId.replace(/\\/g, "/");
1099
+ if (!sameFile) {
1100
+ try {
1101
+ sameFile = realpathSync4.native(file) === realpathSync4.native(cleanId);
1102
+ } catch {
1103
+ }
1104
+ }
1105
+ return sameFile && typeof map.sourcesContent?.[index] === "string" ? [map.sourcesContent[index]] : [];
1106
+ });
1107
+ if (matches.length === 1) loadedSource = matches[0];
1108
+ } catch {
1109
+ }
1110
+ }
1111
+ const witnessed = loadedSource === rawSource && stable.every((key) => before[key] === after[key]);
1112
+ const modifiedtsMs = witnessed ? Math.trunc(before.mtimeMs) : 0;
1113
+ const sourceVersion = witnessed ? sourceVersionHash(rawSource) : "";
1114
+ const identityKey = canonicalIdentityKey(cleanId);
1115
+ if (!defaultExportIdentityByFile.has(identityKey)) {
1116
+ defaultExportIdentityByFile.set(
1117
+ identityKey,
1118
+ readDefaultExportIdentity(rawSource)
1119
+ );
1120
+ }
1121
+ const resolvedComponents = /* @__PURE__ */ new Map();
1122
+ if (source.includes("tempo-sdk/canvas") && typeof context.resolve === "function") {
1123
+ const imports = parseCanvasFile(cleanId, source).storyboards.flatMap(
1124
+ (board) => board.component?.import?.source ?? []
1125
+ );
1126
+ await Promise.all(
1127
+ [...new Set(imports)].map(async (specifier) => {
1128
+ const resolved = await context.resolve(specifier, cleanId, {
1129
+ skipSelf: true
1130
+ });
1131
+ if (resolved) resolvedComponents.set(specifier, resolved.id);
1132
+ })
1133
+ );
1134
+ }
1135
+ const componentReferences = canvasComponentAnnotations(
1136
+ cleanId,
1137
+ source,
1138
+ resolvedComponents
1139
+ );
1140
+ const result = annotateFile(source, cleanId, (info) => {
1141
+ const props = {
1142
+ ...componentReferences.get(info.element.openingElement.start),
1143
+ ...computeTempoAnnotatedProps({
1144
+ info,
1145
+ filepath,
1146
+ modifiedtsMs,
1147
+ sourceVersion,
1148
+ computeAnnotatedProps: options.computeAnnotatedProps
1149
+ })
1150
+ };
1151
+ if (!witnessed) {
1152
+ delete props["data-tempo-filepath"];
1153
+ delete props["data-tempo-position"];
1154
+ delete props["data-tempo-expr"];
1155
+ delete props["data-tempo-modifiedts"];
1156
+ delete props["data-tempo-source-version"];
1157
+ }
1158
+ return props;
1159
+ });
1160
+ if (result.parseResult.errors.length > 0) return null;
1161
+ const annotated = result.elementsAnnotated === 0 ? source : result.annotatedSource;
1162
+ const withControls = options.transformsControls(cleanId) ? transformControls(annotated, cleanId) : annotated;
1163
+ return {
1164
+ code: witnessed ? appendModuleVersionRecord(
1165
+ withControls,
1166
+ filepath,
1167
+ modifiedtsMs,
1168
+ sourceVersion
1169
+ ) : withControls,
1170
+ map: null
1171
+ };
1172
+ } catch {
1173
+ return null;
1174
+ }
1175
+ }
1176
+ async function defaultExportIdentityRewritten(change) {
1177
+ const { file } = change;
1178
+ const key = canonicalIdentityKey(file);
1179
+ if (!defaultExportIdentityByFile.has(key)) return false;
1180
+ let source;
1181
+ try {
1182
+ source = readFileSync4(file, "utf8");
1183
+ if (source.length === 0) source = await change.read();
1184
+ } catch {
1185
+ return false;
1186
+ }
1187
+ const before = defaultExportIdentityByFile.get(key);
1188
+ if (before === void 0) return false;
1189
+ const after = readDefaultExportIdentity(source);
1190
+ defaultExportIdentityByFile.set(key, after);
1191
+ return isDefaultExportIdentityRewrite(before, after);
1192
+ }
1193
+ return {
1194
+ annotateJsxModule,
1195
+ defaultExportIdentityRewritten,
1196
+ forgetDefaultExportIdentity(file) {
1197
+ defaultExportIdentityByFile.delete(canonicalIdentityKey(file));
1198
+ }
1199
+ };
1200
+ }
1201
+
1202
+ // pruned-module-deletion.ts
1203
+ function createPrunedModuleDeletionGuard() {
1204
+ let sequence = 0;
1205
+ let activeReceipts = 0;
1206
+ let receipts = /* @__PURE__ */ new WeakMap();
1207
+ return {
1208
+ observePrune(graph, paths) {
1209
+ const receipt = ++sequence;
1210
+ for (const path of paths) {
1211
+ const module = graph.urlToModuleMap.get(path);
1212
+ if (module) {
1213
+ if (!receipts.has(module)) activeReceipts++;
1214
+ receipts.set(module, receipt);
1215
+ }
1216
+ }
1217
+ },
1218
+ observeRequest(graph, url, base, fetchDestination, ifNoneMatch) {
1219
+ if (!activeReceipts || ["document", "iframe", "frame"].includes(String(fetchDestination)))
1220
+ return;
1221
+ const requestSequence = sequence;
1222
+ return async (status, contentType, responseEtag) => {
1223
+ if (!activeReceipts || status < 200 || status >= 400) return;
1224
+ if (status !== 304 && !/^text\/(?:javascript|css)(?:;|$)/i.test(String(contentType)))
1225
+ return;
1226
+ const etag = status === 304 ? ifNoneMatch : responseEtag;
1227
+ if (typeof etag !== "string" || !graph.getModuleByEtag(etag)) return;
1228
+ let moduleUrl = url;
1229
+ if (base !== "/" && moduleUrl.startsWith(base))
1230
+ moduleUrl = `/${moduleUrl.slice(base.length)}`;
1231
+ try {
1232
+ moduleUrl = decodeURI(moduleUrl).replace(/__x00__/g, "\0");
1233
+ if (moduleUrl.startsWith("/@id/")) moduleUrl = moduleUrl.slice(5);
1234
+ const [, id] = await graph.resolveUrl(moduleUrl);
1235
+ const module = graph.getModuleById(id);
1236
+ if (module && module.transformResult?.etag === etag && (receipts.get(module) ?? Infinity) <= requestSequence) {
1237
+ receipts.delete(module);
1238
+ activeReceipts--;
1239
+ }
1240
+ } catch {
1241
+ }
1242
+ };
1243
+ },
1244
+ suppressDeletion(graph, modules) {
1245
+ if (!modules.length || !modules.every(
1246
+ (module) => receipts.has(module) && module.importers.size === 0
1247
+ ))
1248
+ return false;
1249
+ const invalidated = /* @__PURE__ */ new Set();
1250
+ for (const module of modules) graph.invalidateModule(module, invalidated);
1251
+ return true;
1252
+ },
1253
+ clear() {
1254
+ receipts = /* @__PURE__ */ new WeakMap();
1255
+ activeReceipts = 0;
1256
+ }
1257
+ };
1258
+ }
1259
+
1260
+ // flutter-proxy.ts
1261
+ import { existsSync as existsSync3 } from "fs";
1262
+ import {
1263
+ request as httpRequest
1264
+ } from "http";
1265
+ import { connect } from "net";
1266
+ import { extname, join as join3, posix as posix2 } from "path";
1267
+ import { pipeline } from "stream";
1268
+ var FLUTTER_PROXY_PREFIX = "/__tempo/flutter";
1269
+ var FLUTTER_UNREACHABLE_BODY = { error: "flutter_unreachable" };
1270
+ var FLUTTER_HOST_WATCH_IGNORE = "**/.flutter-host/**";
1271
+ function readFlutterDevServerUrl(env, logger = console) {
1272
+ const raw = env.TEMPO_FLUTTER_URL?.trim();
1273
+ if (!raw) return null;
1274
+ try {
1275
+ const url = new URL(raw);
1276
+ if (url.protocol === "http:") return url;
1277
+ } catch {
1278
+ }
1279
+ logger.warn(
1280
+ `[tempo] ignoring TEMPO_FLUTTER_URL=${JSON.stringify(raw)}: expected an http:// origin such as http://127.0.0.1:<port>`
1281
+ );
1282
+ return null;
1283
+ }
1284
+ var FLUTTER_STATUS_PATH = "/__tempo_flutter_status";
1285
+ function watchFlutterRelaunches(options) {
1286
+ const intervalMs = options.intervalMs ?? 3e3;
1287
+ const statusUrl = new URL(FLUTTER_STATUS_PATH, options.target.origin);
1288
+ let lastReadySpawn = null;
1289
+ let stopped = false;
1290
+ let timer = null;
1291
+ async function poll() {
1292
+ try {
1293
+ const response = await fetch(statusUrl, {
1294
+ signal: AbortSignal.timeout(intervalMs)
1295
+ });
1296
+ const status = response.ok ? await response.json() : null;
1297
+ if (!stopped && status?.status === "ready" && typeof status.spawn === "number") {
1298
+ const relaunched = lastReadySpawn !== null && status.spawn !== lastReadySpawn;
1299
+ lastReadySpawn = status.spawn;
1300
+ if (relaunched) options.onRelaunch();
1301
+ }
1302
+ } catch {
1303
+ }
1304
+ if (stopped) return;
1305
+ timer = setTimeout(poll, intervalMs);
1306
+ timer.unref?.();
1307
+ }
1308
+ void poll();
1309
+ return () => {
1310
+ stopped = true;
1311
+ if (timer) clearTimeout(timer);
1312
+ };
1313
+ }
1314
+ function stripFlutterPrefix(path) {
1315
+ const stripped = path.slice(FLUTTER_PROXY_PREFIX.length);
1316
+ return stripped.startsWith("/") ? stripped : `/${stripped}`;
1317
+ }
1318
+ function isUnderFlutterPrefix(path) {
1319
+ if (!path.startsWith(FLUTTER_PROXY_PREFIX)) return false;
1320
+ const next = path.charAt(FLUTTER_PROXY_PREFIX.length);
1321
+ return next === "" || next === "/" || next === "?";
1322
+ }
1323
+ function createFlutterForwarding(options) {
1324
+ const { target, config } = options;
1325
+ const isViteUpgrade = createViteUpgradeMatcher(config);
1326
+ let reachable = true;
1327
+ function noteReachable() {
1328
+ if (reachable) return;
1329
+ reachable = true;
1330
+ config.logger.info(
1331
+ `[tempo] Flutter dev server reachable at ${target.origin}`
1332
+ );
1333
+ }
1334
+ function noteUnreachable(error) {
1335
+ if (!reachable) return;
1336
+ reachable = false;
1337
+ config.logger.warn(
1338
+ `[tempo] Flutter dev server unreachable at ${target.origin} (${error.code ?? error.message}); answering 502 until it is up`
1339
+ );
1340
+ }
1341
+ function forward(req, res, path) {
1342
+ const upstream = httpRequest(
1343
+ {
1344
+ hostname: target.hostname,
1345
+ port: target.port,
1346
+ method: req.method,
1347
+ path,
1348
+ headers: { ...endToEndHeaders(req.headers), host: target.host }
1349
+ },
1350
+ (response) => {
1351
+ noteReachable();
1352
+ res.writeHead(
1353
+ response.statusCode ?? 502,
1354
+ response.statusMessage,
1355
+ endToEndHeaders(response.headers)
1356
+ );
1357
+ pipeline(response, res, () => {
1358
+ });
1359
+ }
1360
+ );
1361
+ upstream.on("error", (error) => {
1362
+ if (res.headersSent || res.destroyed) {
1363
+ res.destroy();
1364
+ return;
1365
+ }
1366
+ noteUnreachable(error);
1367
+ res.writeHead(502, { "content-type": "application/json" });
1368
+ res.end(JSON.stringify(FLUTTER_UNREACHABLE_BODY));
1369
+ });
1370
+ res.on("close", () => {
1371
+ if (!res.writableFinished) upstream.destroy();
1372
+ });
1373
+ req.pipe(upstream);
1374
+ }
1375
+ function forwardUpgrade(req, socket, head, path) {
1376
+ let connected = false;
1377
+ const upstream = connect(
1378
+ { host: target.hostname, port: Number(target.port) || 80 },
1379
+ () => {
1380
+ connected = true;
1381
+ noteReachable();
1382
+ upstream.write(upgradeRequestHead(req, path, target.host));
1383
+ if (head.length > 0) upstream.write(head);
1384
+ upstream.pipe(socket);
1385
+ socket.pipe(upstream);
1386
+ }
1387
+ );
1388
+ upstream.on("error", (error) => {
1389
+ if (connected) {
1390
+ socket.destroy();
1391
+ return;
1392
+ }
1393
+ noteUnreachable(error);
1394
+ const body = JSON.stringify(FLUTTER_UNREACHABLE_BODY);
1395
+ socket.end(
1396
+ `HTTP/1.1 502 Bad Gateway\r
1397
+ Content-Type: application/json\r
1398
+ Content-Length: ${Buffer.byteLength(body)}\r
1399
+ Connection: close\r
1400
+ \r
1401
+ ${body}`
1402
+ );
1403
+ });
1404
+ upstream.on("close", () => {
1405
+ if (connected) socket.destroy();
1406
+ });
1407
+ socket.on("error", () => upstream.destroy());
1408
+ socket.on("close", () => upstream.destroy());
1409
+ }
1410
+ return {
1411
+ prefix(req, res, next) {
1412
+ const url = req.url ?? "/";
1413
+ if (!isUnderFlutterPrefix(url)) return next();
1414
+ forward(req, res, stripFlutterPrefix(url));
1415
+ },
1416
+ fallthrough(req, res, next) {
1417
+ const originalUrl = req.originalUrl ?? req.url ?? "/";
1418
+ const pathname = decodePathname(originalUrl);
1419
+ const isViteOwned = pathname === null || pathname.startsWith("/@") || pathname.startsWith("/__tempo/") || isCanvasHostPage(pathname) || isHtmlNavigation(req.headers.accept, pathname) || rootHasHtmlPage(config.root, pathname);
1420
+ if (isViteOwned) return next();
1421
+ forward(req, res, originalUrl);
1422
+ },
1423
+ upgrade(req, socket, head) {
1424
+ const url = req.url ?? "/";
1425
+ if (isViteUpgrade(req, url)) return;
1426
+ const path = isUnderFlutterPrefix(url) ? stripFlutterPrefix(url) : url;
1427
+ forwardUpgrade(req, socket, head, path);
1428
+ }
1429
+ };
1430
+ }
1431
+ function createViteUpgradeMatcher(config) {
1432
+ const hmr = config.server.hmr;
1433
+ const hmrPath = typeof hmr === "object" && hmr.path ? posix2.join(config.base || "/", hmr.path) : null;
1434
+ const proxyContexts = Object.keys(config.server.proxy ?? {});
1435
+ return (req, url) => {
1436
+ const protocol = req.headers["sec-websocket-protocol"] ?? "";
1437
+ if (protocol.includes("vite-hmr") || protocol.includes("vite-ping")) {
1438
+ return true;
1439
+ }
1440
+ if (hmrPath !== null && decodePathname(url) === hmrPath) return true;
1441
+ return proxyContexts.some(
1442
+ (context) => context.startsWith("^") ? new RegExp(context).test(url) : url.startsWith(context)
1443
+ );
1444
+ };
1445
+ }
1446
+ function upgradeRequestHead(req, path, host) {
1447
+ const lines = [`${req.method ?? "GET"} ${path} HTTP/${req.httpVersion}`];
1448
+ for (let index = 0; index < req.rawHeaders.length; index += 2) {
1449
+ const name = req.rawHeaders[index] ?? "";
1450
+ const value = name.toLowerCase() === "host" ? host : req.rawHeaders[index + 1];
1451
+ lines.push(`${name}: ${value}`);
1452
+ }
1453
+ return `${lines.join("\r\n")}\r
1454
+ \r
1455
+ `;
1456
+ }
1457
+ function isCanvasHostPage(pathname) {
1458
+ return pathname.replace(/\/+$/, "") === "/tempo-host";
1459
+ }
1460
+ function isHtmlNavigation(accept, pathname) {
1461
+ return Boolean(accept?.includes("text/html")) && extname(pathname) === "";
1462
+ }
1463
+ function rootHasHtmlPage(root, pathname) {
1464
+ if (pathname.split("/").includes("..")) return false;
1465
+ if (pathname.endsWith(".html")) return existsSync3(join3(root, pathname));
1466
+ if (pathname.endsWith("/")) {
1467
+ return existsSync3(join3(root, pathname, "index.html"));
1468
+ }
1469
+ return existsSync3(join3(root, `${pathname}.html`));
1470
+ }
1471
+ function decodePathname(url) {
1472
+ try {
1473
+ return decodeURIComponent(new URL(url, "http://host").pathname);
1474
+ } catch {
1475
+ return null;
1476
+ }
1477
+ }
1478
+ var HOP_BY_HOP_HEADERS = /* @__PURE__ */ new Set([
1479
+ "connection",
1480
+ "keep-alive",
1481
+ "proxy-authenticate",
1482
+ "proxy-authorization",
1483
+ "proxy-connection",
1484
+ "te",
1485
+ "trailer",
1486
+ "transfer-encoding",
1487
+ "upgrade"
1488
+ ]);
1489
+ function endToEndHeaders(headers) {
1490
+ const forwarded = {};
1491
+ for (const [name, value] of Object.entries(headers)) {
1492
+ if (value === void 0 || HOP_BY_HOP_HEADERS.has(name)) continue;
1493
+ forwarded[name] = value;
1494
+ }
1495
+ return forwarded;
1496
+ }
1497
+
1498
+ // hmr-generation-fence.ts
1499
+ function generationIdentity(update) {
1500
+ const type = typeof update.type === "string" ? update.type : null;
1501
+ const acceptedPath = typeof update.acceptedPath === "string" ? update.acceptedPath : typeof update.path === "string" ? update.path : null;
1502
+ if (!type || !acceptedPath) return null;
1503
+ return `${type}\0${acceptedPath}`;
1504
+ }
1505
+ function createHmrGenerationFence() {
1506
+ const newestTimestampByIdentity = /* @__PURE__ */ new Map();
1507
+ return {
1508
+ filter(updates) {
1509
+ const accepted = [];
1510
+ for (const update of updates) {
1511
+ const identity = generationIdentity(update);
1512
+ const timestamp = update.timestamp;
1513
+ if (identity === null || typeof timestamp !== "number" || !Number.isFinite(timestamp)) {
1514
+ accepted.push(update);
1515
+ continue;
1516
+ }
1517
+ const newestTimestamp = newestTimestampByIdentity.get(identity);
1518
+ if (newestTimestamp !== void 0 && timestamp < newestTimestamp) {
1519
+ continue;
1520
+ }
1521
+ if (newestTimestamp === void 0 || timestamp > newestTimestamp) {
1522
+ newestTimestampByIdentity.set(identity, timestamp);
1523
+ }
1524
+ accepted.push(update);
1525
+ }
1526
+ return accepted;
1527
+ },
1528
+ clear() {
1529
+ newestTimestampByIdentity.clear();
1530
+ }
1531
+ };
1532
+ }
1533
+
1534
+ // react-refresh-boundary.ts
1535
+ var installed = /* @__PURE__ */ new WeakSet();
1536
+ function installSynchronousReactRefreshBoundary(plugins) {
1537
+ for (const plugin of plugins) {
1538
+ if (plugin.name === "vite:react-refresh" && plugin.load && !installed.has(plugin)) {
1539
+ installed.add(plugin);
1540
+ const hook2 = plugin.load;
1541
+ const load = typeof hook2 === "function" ? hook2 : hook2.handler;
1542
+ const wrapped2 = async function(...args) {
1543
+ const result = await load.apply(this, args);
1544
+ if (!result || args[0] !== "/@react-refresh") return result;
1545
+ const source = typeof result === "string" ? result : result.code;
1546
+ if (!source || !/\b(?:let|const) allFamiliesByType = new WeakMap\(\)/.test(source) || !source.includes("function performReactRefresh()"))
1547
+ return result;
1548
+ const code = `${source}
1549
+ globalThis[Symbol.for("tempo.react-refresh.family")] = (type) => allFamiliesByType.get(type);
1550
+ `;
1551
+ return typeof result === "string" ? code : { ...result, code };
1552
+ };
1553
+ plugin.load = typeof hook2 === "function" ? wrapped2 : { ...hook2, handler: wrapped2 };
1554
+ }
1555
+ if (plugin.name !== "vite:react-babel" || !plugin.transform || installed.has(plugin))
1556
+ continue;
1557
+ installed.add(plugin);
1558
+ const hook = plugin.transform;
1559
+ const transform = typeof hook === "function" ? hook : hook.handler;
1560
+ const wrapped = async function(...args) {
1561
+ const result = await transform.apply(this, args);
1562
+ if (!result) return result;
1563
+ const source = typeof result === "string" ? result : result.code;
1564
+ if (!source) return result;
1565
+ const code = source.replace(
1566
+ /RefreshRuntime\.__hmr_import\(import\.meta\.url\)\.then\(\(currentExports\) => \{\n(\s*RefreshRuntime\.registerExportsForReactRefresh\([^\n]+\);)\n\s*import\.meta\.hot\.accept\(\(nextExports\) => \{([\s\S]*?)\n\s*\}\);\n\s*\}\);/,
1567
+ (_match, register, accept) => `const __tempoReactRefreshExports = RefreshRuntime.__hmr_import(import.meta.url).then((currentExports) => {
1568
+ ${register}
1569
+ return currentExports;
1570
+ });
1571
+ import.meta.hot.accept(async (nextExports) => {
1572
+ const currentExports = await __tempoReactRefreshExports;${accept}
1573
+ });`
1574
+ );
1575
+ return code === source ? result : typeof result === "string" ? code : { ...result, code };
1576
+ };
1577
+ plugin.transform = typeof hook === "function" ? wrapped : { ...hook, handler: wrapped };
1578
+ }
1579
+ }
1580
+
1581
+ // vite-client-pending-updates.ts
1582
+ function preservePendingViteModuleUpdates(source) {
1583
+ const missingBoundary = /(const mod = this\.hotModulesMap\.get\(path\);\s*)if \(!mod\)\s*(?:return;|\{\s*return;\s*\})/;
1584
+ const registeredBoundary = "this.hmrClient.hotModulesMap.set(this.ownerPath, mod);";
1585
+ if (!missingBoundary.test(source) || !source.includes(registeredBoundary)) {
1586
+ return source;
1587
+ }
1588
+ return source.replace(
1589
+ missingBoundary,
1590
+ `$1if (!mod || mod.pendingUpdates) {
1591
+ const pending = mod || {
1592
+ id: path,
1593
+ callbacks: [],
1594
+ pendingUpdates: new Map(),
1595
+ };
1596
+ pending.pendingUpdates.set(acceptedPath, update);
1597
+ this.hotModulesMap.set(path, pending);
1598
+ return;
1599
+ }`
1600
+ ).replace(
1601
+ registeredBoundary,
1602
+ `${registeredBoundary}
1603
+ if (mod.pendingUpdates) {
1604
+ const pendingUpdates = [...mod.pendingUpdates.values()];
1605
+ delete mod.pendingUpdates;
1606
+ queueMicrotask(() => {
1607
+ for (const update of pendingUpdates) {
1608
+ void this.hmrClient.queueUpdate(update).catch((error) => {
1609
+ this.hmrClient.logger.error(error);
1610
+ });
1611
+ }
1612
+ });
1613
+ }`
1614
+ );
1615
+ }
1616
+
1617
+ // tailwind-scan-net.ts
1618
+ var SCANNABLE_EXTENSIONS = /* @__PURE__ */ new Set([
1619
+ "ts",
1620
+ "tsx",
1621
+ "js",
1622
+ "jsx",
1623
+ "mjs",
1624
+ "cjs",
1625
+ "html",
1626
+ "mdx",
1627
+ "md",
1628
+ "svelte",
1629
+ "vue",
1630
+ "astro"
1631
+ ]);
1632
+ var IGNORED_PATH_SEGMENTS = [
1633
+ "/node_modules/",
1634
+ "/.git/",
1635
+ "/.vite/",
1636
+ "/.tempo/"
1637
+ ];
1638
+ var TAILWIND_SCAN_NET_DEBOUNCE_MS = 100;
1639
+ var TAILWIND_SCAN_NET_MAX_POKES_PER_PAIR = 2;
1640
+ var POKE_LEDGER_MAX_ENTRIES = 2e4;
1641
+ function normalizeSlashes(path) {
1642
+ return path.replace(/\\/g, "/");
1643
+ }
1644
+ function fileExtension(path) {
1645
+ const base = path.slice(path.lastIndexOf("/") + 1);
1646
+ const dot = base.lastIndexOf(".");
1647
+ return dot <= 0 ? "" : base.slice(dot + 1).toLowerCase();
1648
+ }
1649
+ function isScannableSourceFile(file) {
1650
+ const normalized = normalizeSlashes(file);
1651
+ if (!SCANNABLE_EXTENSIONS.has(fileExtension(normalized))) return false;
1652
+ return !IGNORED_PATH_SEGMENTS.some(
1653
+ (segment) => normalized.includes(segment)
1654
+ );
1655
+ }
1656
+ function isScanDep(dep) {
1657
+ if (dep.includes("*")) return true;
1658
+ const ext = fileExtension(normalizeSlashes(dep));
1659
+ return ext !== "" && ext !== "css" && SCANNABLE_EXTENSIONS.has(ext);
1660
+ }
1661
+ function cssEntryNeedsRescanFor(entry, file) {
1662
+ if (entry.deps === null) return false;
1663
+ const normalizedFile = normalizeSlashes(file);
1664
+ let scansClasses = false;
1665
+ for (const dep of entry.deps) {
1666
+ const normalizedDep = normalizeSlashes(dep);
1667
+ if (normalizedDep === normalizedFile) return false;
1668
+ if (!scansClasses && isScanDep(normalizedDep)) scansClasses = true;
1669
+ }
1670
+ return scansClasses;
1671
+ }
1672
+ function createTailwindScanNet(args) {
1673
+ const debounceMs = args.debounceMs ?? TAILWIND_SCAN_NET_DEBOUNCE_MS;
1674
+ const maxPokesPerPair = args.maxPokesPerPair ?? TAILWIND_SCAN_NET_MAX_POKES_PER_PAIR;
1675
+ const pendingCssFiles = /* @__PURE__ */ new Set();
1676
+ const pokeLedger = /* @__PURE__ */ new Map();
1677
+ const countedThisWindow = /* @__PURE__ */ new Set();
1678
+ let flushTimer = null;
1679
+ let lastFlushAt = Number.NEGATIVE_INFINITY;
1680
+ let disposed = false;
1681
+ const flush = () => {
1682
+ flushTimer = null;
1683
+ lastFlushAt = Date.now();
1684
+ countedThisWindow.clear();
1685
+ const cssFiles = [...pendingCssFiles];
1686
+ pendingCssFiles.clear();
1687
+ for (const cssFile of cssFiles) {
1688
+ args.emitChange(cssFile);
1689
+ }
1690
+ };
1691
+ return {
1692
+ handleWatcherFile(file) {
1693
+ if (disposed) return false;
1694
+ if (!isScannableSourceFile(file)) return false;
1695
+ let scheduled = false;
1696
+ for (const entry of args.listCssEntries()) {
1697
+ if (!cssEntryNeedsRescanFor(entry, file)) continue;
1698
+ const pairKey = `${entry.cssFile}\0${normalizeSlashes(file)}`;
1699
+ if (!countedThisWindow.has(pairKey)) {
1700
+ const pokes = pokeLedger.get(pairKey) ?? 0;
1701
+ if (pokes >= maxPokesPerPair) continue;
1702
+ if (pokeLedger.size >= POKE_LEDGER_MAX_ENTRIES) pokeLedger.clear();
1703
+ pokeLedger.set(pairKey, pokes + 1);
1704
+ countedThisWindow.add(pairKey);
1705
+ }
1706
+ pendingCssFiles.add(entry.cssFile);
1707
+ scheduled = true;
1708
+ }
1709
+ if (scheduled && flushTimer === null) {
1710
+ const sinceLastFlush = Date.now() - lastFlushAt;
1711
+ const delay = sinceLastFlush >= debounceMs ? 0 : debounceMs;
1712
+ flushTimer = setTimeout(flush, delay);
1713
+ flushTimer.unref?.();
1714
+ }
1715
+ return scheduled;
1716
+ },
1717
+ dispose() {
1718
+ disposed = true;
1719
+ pendingCssFiles.clear();
1720
+ pokeLedger.clear();
1721
+ countedThisWindow.clear();
1722
+ if (flushTimer !== null) {
1723
+ clearTimeout(flushTimer);
1724
+ flushTimer = null;
1725
+ }
1726
+ }
1727
+ };
1728
+ }
1729
+
1730
+ // index.ts
1731
+ var DEFAULT_INCLUDE = ["**/*.tsx", "**/*.jsx"];
1732
+ var DEFAULT_EXCLUDE = ["**/node_modules/**"];
1733
+ var ROOT_META_NAME = "tempo-project-root";
1734
+ var SOURCE_IDENTITY_ROOT_META_NAME = "tempo-source-identity-root";
1735
+ var INTERACT_PROJECTION_CLIENT_PATH = "/@tempo/interact-projection";
1736
+ var INTERACT_PROJECTION_CLIENT_ID = "\0tempo:interact-projection";
1737
+ var INTERACT_PROJECTION_SDK_SPECIFIER = "tempo-sdk/canvas/interact-projection";
1738
+ function resolveOwnInteractProjectionModule() {
1739
+ const selfDir = dirname4(fileURLToPath2(import.meta.url));
1740
+ for (const candidate of [
1741
+ join4(selfDir, "canvas", "interact-projection.ts"),
1742
+ join4(selfDir, "canvas", "interact-projection.js")
1743
+ ]) {
1744
+ if (existsSync4(candidate)) return candidate.replace(/\\/g, "/");
1745
+ }
1746
+ return null;
1747
+ }
1748
+ var INTERACT_PROJECTION_BOOTSTRAP = `
1749
+ (function() {
1750
+ if (window.parent === window || (window.name !== ${JSON.stringify(TEMPO_INTERACT_FRAME_NAME)} && !window.name.startsWith(${JSON.stringify(`${TEMPO_INTERACT_FRAME_NAME}:`)}))) return;
1751
+ var roots = new Map();
1752
+ var existing = window.__REACT_DEVTOOLS_GLOBAL_HOOK__;
1753
+ if (existing) {
1754
+ if (existing.__tempoPendingFiberRoots) return;
1755
+ existing.__tempoPendingFiberRoots = roots;
1756
+ var originalCommit = existing.onCommitFiberRoot && existing.onCommitFiberRoot.bind(existing);
1757
+ existing.onCommitFiberRoot = function(rendererId, root) {
1758
+ if (existing.__tempoPendingFiberRoots === roots) roots.set(rendererId, root);
1759
+ if (originalCommit) originalCommit.apply(null, arguments);
1760
+ };
1761
+ return;
1762
+ }
1763
+ window.__REACT_DEVTOOLS_GLOBAL_HOOK__ = {
1764
+ supportsFiber: true,
1765
+ renderers: new Map(),
1766
+ __tempoPendingFiberRoots: roots,
1767
+ inject: function(renderer) {
1768
+ var id = this.renderers.size + 1;
1769
+ this.renderers.set(id, renderer);
1770
+ return id;
1771
+ },
1772
+ onCommitFiberRoot: function(rendererId, root) {
1773
+ if (this.__tempoPendingFiberRoots === roots) roots.set(rendererId, root);
1774
+ },
1775
+ onCommitFiberUnmount: function() {},
1776
+ checkDCE: function() {},
1777
+ onScheduleFiberRoot: function() {}
1778
+ };
1779
+ })();`;
1780
+ function cleanModuleId2(id) {
1781
+ return id.replace(/[?#].*$/, "");
1782
+ }
1783
+ function isCanvasHostRequest(requestPath) {
1784
+ const url = new URL(requestPath, "http://tempo.local");
1785
+ return url.pathname.replace(/\/+$/, "") === "/tempo-host";
1786
+ }
1787
+ function isDeclarativeCanvasHostRequest(requestPath) {
1788
+ if (!isCanvasHostRequest(requestPath)) return false;
1789
+ const params = new URL(requestPath, "http://tempo.local").searchParams;
1790
+ const canvasPath = params.get("canvasPath")?.trim() ?? params.get("pageFile")?.trim() ?? params.get("importPath")?.trim();
1791
+ const storyboardId = params.get("storyboardId")?.trim() ?? params.get("exportName")?.trim() ?? params.get("importName")?.trim();
1792
+ return !canvasPath || !storyboardId;
1793
+ }
1794
+ var MAX_UNRESOLVED_IMPORTS = 256;
1795
+ var RELATIVE_IMPORT_RESOLVE_EXTENSIONS = [
1796
+ ".mjs",
1797
+ ".js",
1798
+ ".mts",
1799
+ ".ts",
1800
+ ".jsx",
1801
+ ".tsx",
1802
+ ".json"
1803
+ ];
1804
+ var UNRESOLVED_IMPORT_WATCH_REARM_MS = 1e3;
1805
+ function isRelativeImportSpecifier(specifier) {
1806
+ return specifier.startsWith("./") || specifier.startsWith("../");
1807
+ }
1808
+ function barePackageName(specifier) {
1809
+ if (!specifier || specifier.startsWith(".") || specifier.startsWith("/") || specifier.startsWith("\0") || specifier.startsWith("#") || specifier.includes(":")) {
1810
+ return void 0;
1372
1811
  }
1373
- if (url === "/__tempo/report-clear" && req.method === "POST") {
1374
- errorServer.clearAll();
1375
- res.statusCode = 200;
1376
- res.end("ok");
1377
- return;
1812
+ const segments = specifier.split("/");
1813
+ const packageName = specifier.startsWith("@") ? segments.length >= 2 && segments[0] !== "@" && segments[1] ? `${segments[0]}/${segments[1]}` : void 0 : segments[0];
1814
+ return packageName && /^@?[A-Za-z0-9_][A-Za-z0-9._/-]*$/.test(packageName) ? packageName : void 0;
1815
+ }
1816
+ function resolvedIdMatchesFile(id, file) {
1817
+ const resolvedFile = fsPathFromModuleId(id);
1818
+ try {
1819
+ return realpathSync5.native(resolvedFile) === realpathSync5.native(file);
1820
+ } catch {
1821
+ return resolvedFile.replace(/\\/g, "/") === file.replace(/\\/g, "/");
1378
1822
  }
1379
- if (url === "/__tempo/errors" && req.method === "OPTIONS") {
1380
- res.writeHead(204, {
1381
- "Access-Control-Allow-Origin": "*",
1382
- "Access-Control-Allow-Methods": "GET, OPTIONS",
1383
- "Access-Control-Allow-Headers": "*"
1384
- });
1385
- res.end();
1386
- return;
1823
+ }
1824
+ function resolveCanonicalRoot(root) {
1825
+ try {
1826
+ return realpathSync5.native(root);
1827
+ } catch {
1828
+ return root;
1387
1829
  }
1388
- if (url === "/__tempo/errors" && req.method === "GET") {
1389
- res.writeHead(200, {
1390
- "Content-Type": "text/event-stream",
1391
- "Cache-Control": "no-cache",
1392
- Connection: "keep-alive",
1393
- "Access-Control-Allow-Origin": "*"
1394
- });
1395
- res.write(`data: ${JSON.stringify(errorServer.currentError)}
1396
-
1397
- `);
1398
- errorServer.clients.add(res);
1399
- req.on("close", () => {
1400
- errorServer.clients.delete(res);
1830
+ }
1831
+ function hasRootMetaTag(html) {
1832
+ return /<meta[^>]+name=["']tempo-project-root["'][^>]*>/i.test(html);
1833
+ }
1834
+ function hasSourceIdentityRootMetaTag(html) {
1835
+ return /<meta[^>]+name=["']tempo-source-identity-root["'][^>]*>/i.test(html);
1836
+ }
1837
+ function hasWorkspaceNonceMetaTag(html) {
1838
+ return new RegExp(
1839
+ `<meta[^>]+name=["']${TEMPO_WORKSPACE_NONCE_META_NAME}["'][^>]*>`,
1840
+ "i"
1841
+ ).test(html);
1842
+ }
1843
+ function runsVueSourceAnnotation(plugins) {
1844
+ return (plugins ?? []).some(
1845
+ (plugin) => plugin.name === TEMPO_VUE_ANNOTATION_PLUGIN_NAME && plugin.api?.enabled === true
1846
+ );
1847
+ }
1848
+ function handleTempoMiddleware(compileErrors, viteServer, req, res, next) {
1849
+ const url = req.url;
1850
+ if (!url?.startsWith("/__tempo/")) return next();
1851
+ if (url === TEMPO_HOST_IDENTITY_ENDPOINT && req.method === "GET") {
1852
+ const identity = createTempoHostIdentity("vite", {
1853
+ root: viteServer.config?.root,
1854
+ pluginActive: true,
1855
+ ...runsVueSourceAnnotation(viteServer.config?.plugins) ? { capabilities: { vueSourceAnnotation: 1 } } : {}
1401
1856
  });
1857
+ res.statusCode = 200;
1858
+ res.setHeader("Cache-Control", "no-store");
1859
+ res.setHeader("Content-Type", "application/json; charset=utf-8");
1860
+ res.setHeader(TEMPO_HOST_IDENTITY_CAPABILITY_HEADER, "1");
1861
+ res.end(JSON.stringify(identity));
1402
1862
  return;
1403
1863
  }
1864
+ if (handleCanvasHostRegistrationRequest(viteServer, req, res)) return;
1865
+ if (compileErrors.handleRequest(req, res)) return;
1404
1866
  next();
1405
1867
  }
1406
- var MISSED_CHANGE_SWEEP_INTERVAL_MS = 3e3;
1407
- var COMPILE_ERROR_POLL_MAX_INTERVAL_MS = 3e4;
1408
- function installMissedChangeSweep(server, listErrorFiles, lastHotUpdateMtimeMs, pollCompileErrorRecovery) {
1409
- const cacheDir = server.config.cacheDir?.replace(/\\/g, "/").replace(/\/+$/, "");
1410
- const sweep = createMissedChangeSweep({
1411
- listServedFiles: () => {
1412
- const files = new Map(
1413
- server.moduleGraph?.fileToModulesMap ?? /* @__PURE__ */ new Map()
1414
- );
1415
- const errorFiles = listErrorFiles();
1416
- for (const errorFile of errorFiles) {
1417
- const cleanFile = fsPathFromModuleId(errorFile);
1418
- const file = isAbsolute2(cleanFile) ? cleanFile : resolve5(server.config.root, cleanFile);
1419
- if (!files.has(file)) files.set(file, []);
1420
- }
1421
- if (cacheDir) {
1422
- for (const file of files.keys()) {
1423
- if (file.replace(/\\/g, "/").startsWith(`${cacheDir}/`)) {
1424
- files.delete(file);
1425
- }
1426
- }
1427
- }
1428
- return files.entries();
1429
- },
1430
- statMtimeMs: async (file) => {
1431
- try {
1432
- return statSync(file).mtimeMs;
1433
- } catch {
1434
- return null;
1435
- }
1436
- },
1437
- emitChange: (file) => {
1438
- server.config?.logger?.info?.(
1439
- `[tempo] re-emitting lost watcher change: ${file}`,
1440
- { timestamp: true }
1441
- );
1442
- server.watcher?.emit?.("change", file);
1443
- },
1444
- lastHotUpdateMtimeMs
1445
- });
1446
- let passRunning = false;
1447
- const timer = setInterval(() => {
1448
- if (passRunning) return;
1449
- passRunning = true;
1450
- void sweep.sweep().then(() => pollCompileErrorRecovery()).catch(() => {
1451
- }).finally(() => {
1452
- passRunning = false;
1453
- });
1454
- }, MISSED_CHANGE_SWEEP_INTERVAL_MS);
1455
- timer.unref?.();
1456
- server.httpServer?.once("close", () => clearInterval(timer));
1457
- }
1868
+ var MISSED_CHANGE_SWEEP_INTERVAL_MS2 = HOT_UPDATE_NET_SWEEP_INTERVAL_MS;
1458
1869
  function installTailwindScanNet(server) {
1459
1870
  const net = createTailwindScanNet({
1460
1871
  listCssEntries: function* () {
@@ -1492,6 +1903,7 @@ function installTailwindScanNet(server) {
1492
1903
  }
1493
1904
  function tempoVitePlugin(options = {}) {
1494
1905
  const enabled = options.enabled ?? !!process.env.TEMPO;
1906
+ const flutterTarget = enabled ? readFlutterDevServerUrl(process.env) : null;
1495
1907
  const include = options.include === void 0 ? DEFAULT_INCLUDE : options.include;
1496
1908
  const exclude = options.exclude === void 0 ? DEFAULT_EXCLUDE : options.exclude;
1497
1909
  const isSdkFile = createSdkFileMatcher();
@@ -1502,7 +1914,6 @@ function tempoVitePlugin(options = {}) {
1502
1914
  exclude
1503
1915
  );
1504
1916
  const controlsFilter = (id) => userControlsFilter(id) && !isSdkFile(id);
1505
- const controlsModules = /* @__PURE__ */ new Set();
1506
1917
  const astroDescriptorDependencies = /* @__PURE__ */ new Map();
1507
1918
  const invalidateAstroDescriptors = (file, graph, modules) => {
1508
1919
  const affected = new Set(modules);
@@ -1516,19 +1927,18 @@ function tempoVitePlugin(options = {}) {
1516
1927
  }
1517
1928
  return [...affected];
1518
1929
  };
1519
- function transformControls(source, id) {
1520
- const code = transformControlsForHmr(source, id, controlsModules.has(id));
1521
- if (code !== source) controlsModules.add(id);
1522
- return code;
1523
- }
1524
1930
  let canonicalRoot = process.cwd();
1931
+ const jsxModuleAnnotation = createJsxModuleAnnotation({
1932
+ stampedFilepath: (cleanId) => filter(cleanId) ? relative3(canonicalRoot, cleanId) : null,
1933
+ transformsControls: controlsFilter,
1934
+ computeAnnotatedProps: options.computeAnnotatedProps
1935
+ });
1525
1936
  let sourceIdentityRoot = canonicalRoot;
1526
1937
  let command = "serve";
1527
1938
  let hmrEnabled = true;
1528
- const errorServer = createErrorServer(
1529
- (file) => pinErroneousRevisionCoverage(file),
1530
- (error) => devServer?.ws.send(VITE_ERROR_STATE_EVENT, error)
1531
- );
1939
+ const compileErrors = createCompileErrorStream({
1940
+ onErrorFile: (file) => pinErroneousRevisionCoverage(file)
1941
+ });
1532
1942
  const unresolvedImports = /* @__PURE__ */ new Map();
1533
1943
  let devServer;
1534
1944
  const unresolvedImportWatchers = /* @__PURE__ */ new Map();
@@ -1539,155 +1949,25 @@ function tempoVitePlugin(options = {}) {
1539
1949
  const processedUpdatePayloads = /* @__PURE__ */ new WeakSet();
1540
1950
  const prunedModuleDeletion = createPrunedModuleDeletionGuard();
1541
1951
  const hmrGenerationFence = createHmrGenerationFence();
1542
- const rapidHotUpdateReplay = createRapidHotUpdateReplay();
1543
- const hotUpdateMtimesMs = /* @__PURE__ */ new Map();
1544
- const normalizedFileKey = (file) => file.replace(/\\/g, "/");
1545
- const burstKey = (file) => normalizedFileKey(fsPathFromModuleId(file));
1546
- const recordHotUpdateCoverage = (file) => {
1547
- const cleanFile = fsPathFromModuleId(file);
1548
- const key = normalizedFileKey(cleanFile);
1549
- try {
1550
- hotUpdateMtimesMs.set(key, statSync(cleanFile).mtimeMs);
1551
- } catch {
1552
- hotUpdateMtimesMs.delete(key);
1553
- }
1554
- };
1952
+ const hotUpdateNet = createHotUpdateNet();
1953
+ const recordHotUpdateCoverage = hotUpdateNet.recordCoverage;
1555
1954
  const pinErroneousRevisionCoverage = (file) => {
1556
1955
  recordHotUpdateCoverage(file);
1557
1956
  };
1558
- const hasActiveCompileError = (file) => errorServer.errorFiles.some((errorFile) => moduleIdsMatch(errorFile, file));
1559
- const recoverActiveCompileError = async (server, file) => {
1560
- if (!hasActiveCompileError(file)) return false;
1561
- const cleanFile = fsPathFromModuleId(file);
1562
- const requestId = `/@fs/${cleanFile.replace(/^\/+/, "")}`;
1563
- const clientEnvironment = server.environments?.client;
1564
- const transformer = clientEnvironment ?? server;
1565
- try {
1566
- const source = readFileSync4(cleanFile, "utf8");
1567
- const canvasModule = /\.canvas\.[cm]?[jt]sx?$/.test(cleanFile);
1568
- const hasDefault = (code) => {
1569
- const parsed = parseSync(cleanFile, code);
1570
- return !parsed.errors.length && parsed.program.body.some(
1571
- (node) => node.type === "ExportDefaultDeclaration" || node.type === "ExportNamedDeclaration" && node.exportKind !== "type" && node.specifiers.some(
1572
- (specifier) => specifier.exportKind !== "type" && (specifier.exported.type === "Identifier" ? specifier.exported.name : specifier.exported.value) === "default"
1573
- )
1574
- );
1575
- };
1576
- if (canvasModule && !hasDefault(source)) return false;
1577
- let canonicalFile = cleanFile;
1578
- try {
1579
- canonicalFile = realpathSync3(cleanFile);
1580
- } catch {
1581
- }
1582
- const modules = /* @__PURE__ */ new Set([
1583
- ...transformer.moduleGraph.getModulesByFile(canonicalFile) ?? [],
1584
- ...transformer.moduleGraph.getModulesByFile(cleanFile) ?? []
1585
- ]);
1586
- for (const module of modules) {
1587
- transformer.moduleGraph.invalidateModule(module);
1588
- }
1589
- const result = await transformer.transformRequest(requestId);
1590
- if (!result) return false;
1591
- if (readFileSync4(cleanFile, "utf8") !== source) return false;
1592
- if (canvasModule && (typeof result !== "object" || !("code" in result) || typeof result.code !== "string" || !hasDefault(result.code)))
1593
- return false;
1594
- } catch {
1595
- return false;
1596
- }
1597
- errorServer.clearErrorForModules([file, cleanFile, requestId]);
1598
- server.config.logger.info(
1599
- `[tempo] recovered compile-error module after validated transform: ${cleanFile}`,
1600
- { timestamp: true }
1601
- );
1602
- (clientEnvironment?.hot ?? server.ws).send({
1603
- type: "full-reload",
1604
- path: "*"
1605
- });
1606
- return true;
1607
- };
1608
- const compileErrorPollSchedule = /* @__PURE__ */ new Map();
1609
- const pollCompileErrorRecovery = async (server) => {
1610
- const activeFiles = new Map(
1611
- errorServer.errorFiles.map((file) => [
1612
- normalizedFileKey(fsPathFromModuleId(file)),
1613
- file
1614
- ])
1615
- );
1616
- for (const key of [...compileErrorPollSchedule.keys()]) {
1617
- if (!activeFiles.has(key)) compileErrorPollSchedule.delete(key);
1618
- }
1619
- const nowMs = Date.now();
1620
- for (const [key, file] of activeFiles) {
1621
- const schedule = compileErrorPollSchedule.get(key);
1622
- if (schedule && nowMs < schedule.nextAttemptAtMs) continue;
1623
- if (await recoverActiveCompileError(server, file)) {
1624
- compileErrorPollSchedule.delete(key);
1625
- continue;
1626
- }
1627
- const intervalMs = schedule?.intervalMs ?? MISSED_CHANGE_SWEEP_INTERVAL_MS;
1628
- compileErrorPollSchedule.set(key, {
1629
- nextAttemptAtMs: nowMs + intervalMs,
1630
- intervalMs: Math.min(
1631
- intervalMs * 2,
1632
- COMPILE_ERROR_POLL_MAX_INTERVAL_MS
1633
- )
1634
- });
1635
- }
1636
- };
1637
- const defaultExportIdentityByFile = /* @__PURE__ */ new Map();
1638
- const canonicalIdentityKey = (idOrFile) => {
1639
- const file = fsPathFromModuleId(idOrFile);
1640
- try {
1641
- return realpathSync3.native(file);
1642
- } catch {
1643
- return file.replace(/\\/g, "/");
1644
- }
1645
- };
1646
1957
  const repairDefaultExportIdentityRewrite = async (context) => {
1647
- const { file } = context;
1648
- const key = canonicalIdentityKey(file);
1649
- if (!defaultExportIdentityByFile.has(key)) return false;
1650
- let source;
1651
- try {
1652
- source = readFileSync4(file, "utf8");
1653
- if (source.length === 0) source = await context.read();
1654
- } catch {
1958
+ if (!await jsxModuleAnnotation.defaultExportIdentityRewritten(context))
1655
1959
  return false;
1656
- }
1657
- const before = defaultExportIdentityByFile.get(key);
1658
- if (before === void 0) return false;
1659
- const after = readDefaultExportIdentity(source);
1660
- defaultExportIdentityByFile.set(key, after);
1661
- if (!isDefaultExportIdentityRewrite(before, after)) return false;
1662
1960
  devServer?.ws.send({ type: "full-reload", path: "*" });
1663
1961
  return true;
1664
1962
  };
1665
- const isIncrementalRegistration = (file) => {
1666
- if (file.replace(/\\/g, "/") !== resolve5(canonicalRoot, ".tempo", "tempo-host.tsx").replace(/\\/g, "/"))
1667
- return false;
1668
- try {
1669
- return readFileSync4(file, "utf8").includes(
1670
- "tempo-incremental-canvas-registration"
1671
- );
1672
- } catch {
1673
- return false;
1674
- }
1675
- };
1676
- const invalidateCanvasLoader = (file, graph, modules) => {
1677
- const canvasPath = relative2(sourceIdentityRoot, file).replace(/\\/g, "/");
1678
- const wrapperPath = resolve5(canonicalRoot, ".tempo", "tempo-host.tsx");
1679
- let source;
1680
- try {
1681
- source = readFileSync4(wrapperPath, "utf8");
1682
- } catch {
1683
- return;
1684
- }
1685
- if (!readGeneratedCanvasPaths(source).includes(canvasPath)) return;
1686
- const wrappers = graph.getModulesByFile(wrapperPath);
1687
- if (!wrappers?.size) return;
1688
- for (const wrapper of wrappers) graph.invalidateModule(wrapper);
1689
- return [.../* @__PURE__ */ new Set([...modules, ...wrappers])];
1690
- };
1963
+ const wrapperPath = () => resolve7(canonicalRoot, ".tempo", "tempo-host.tsx");
1964
+ const isIncrementalRegistration = (file) => isIncrementalWrapperFile(file, wrapperPath());
1965
+ const invalidateCanvasLoader = (file, graph, modules) => withRegisteredCanvasLoader(
1966
+ file,
1967
+ { wrapperPath: wrapperPath(), sourceRoot: sourceIdentityRoot },
1968
+ graph,
1969
+ modules
1970
+ );
1691
1971
  const rememberUnresolvedImport = (specifier, importer, packageName) => {
1692
1972
  const key = `${importer}\0${specifier}`;
1693
1973
  unresolvedImports.delete(key);
@@ -1739,28 +2019,28 @@ function tempoVitePlugin(options = {}) {
1739
2019
  (unresolved) => unresolved.packageName !== void 0
1740
2020
  );
1741
2021
  const packageWatchTarget = (unresolved) => {
1742
- let candidate = dirname3(cleanModuleId(unresolved.importer));
2022
+ let candidate = dirname4(cleanModuleId2(unresolved.importer));
1743
2023
  let nearestPackageRoot;
1744
2024
  while (true) {
1745
2025
  try {
1746
- if (statSync(join3(candidate, "node_modules")).isDirectory()) {
1747
- return join3(candidate, "node_modules", unresolved.packageName);
2026
+ if (statSync2(join4(candidate, "node_modules")).isDirectory()) {
2027
+ return join4(candidate, "node_modules", unresolved.packageName);
1748
2028
  }
1749
2029
  } catch {
1750
2030
  }
1751
2031
  if (nearestPackageRoot === void 0) {
1752
2032
  try {
1753
- if (statSync(join3(candidate, "package.json")).isFile()) {
2033
+ if (statSync2(join4(candidate, "package.json")).isFile()) {
1754
2034
  nearestPackageRoot = candidate;
1755
2035
  }
1756
2036
  } catch {
1757
2037
  }
1758
2038
  }
1759
- const parent = dirname3(candidate);
2039
+ const parent = dirname4(candidate);
1760
2040
  if (parent === candidate) break;
1761
2041
  candidate = parent;
1762
2042
  }
1763
- return join3(
2043
+ return join4(
1764
2044
  nearestPackageRoot ?? canonicalRoot,
1765
2045
  "node_modules",
1766
2046
  unresolved.packageName
@@ -1769,19 +2049,19 @@ function tempoVitePlugin(options = {}) {
1769
2049
  const unresolvedImportWatchTarget = (unresolved) => {
1770
2050
  return unresolved.packageName ? packageWatchTarget(
1771
2051
  unresolved
1772
- ) : resolve5(
1773
- dirname3(cleanModuleId(unresolved.importer)),
1774
- cleanModuleId(unresolved.specifier)
2052
+ ) : resolve7(
2053
+ dirname4(cleanModuleId2(unresolved.importer)),
2054
+ cleanModuleId2(unresolved.specifier)
1775
2055
  );
1776
2056
  };
1777
2057
  const nearestExistingDirectory = (target) => {
1778
2058
  let candidate = target;
1779
2059
  while (true) {
1780
2060
  try {
1781
- if (statSync(candidate).isDirectory()) return candidate;
2061
+ if (statSync2(candidate).isDirectory()) return candidate;
1782
2062
  } catch {
1783
2063
  }
1784
- const parent = dirname3(candidate);
2064
+ const parent = dirname4(candidate);
1785
2065
  if (parent === candidate) return void 0;
1786
2066
  candidate = parent;
1787
2067
  }
@@ -1858,8 +2138,8 @@ function tempoVitePlugin(options = {}) {
1858
2138
  if (isRelativeImportSpecifier(unresolved.specifier)) {
1859
2139
  const suffixIndex = unresolved.specifier.search(/[?#]/);
1860
2140
  const relativePath = suffixIndex < 0 ? unresolved.specifier : unresolved.specifier.slice(0, suffixIndex);
1861
- const candidate = resolve5(
1862
- dirname3(cleanModuleId(unresolved.importer)),
2141
+ const candidate = resolve7(
2142
+ dirname4(cleanModuleId2(unresolved.importer)),
1863
2143
  relativePath
1864
2144
  );
1865
2145
  const probes = [
@@ -1868,12 +2148,12 @@ function tempoVitePlugin(options = {}) {
1868
2148
  (extension) => `${candidate}${extension}`
1869
2149
  ),
1870
2150
  ...RELATIVE_IMPORT_RESOLVE_EXTENSIONS.map(
1871
- (extension) => join3(candidate, `index${extension}`)
2151
+ (extension) => join4(candidate, `index${extension}`)
1872
2152
  )
1873
2153
  ];
1874
2154
  for (const probe of probes) {
1875
2155
  try {
1876
- if (statSync(probe).isFile()) {
2156
+ if (statSync2(probe).isFile()) {
1877
2157
  file = probe;
1878
2158
  break;
1879
2159
  }
@@ -1883,7 +2163,7 @@ function tempoVitePlugin(options = {}) {
1883
2163
  }
1884
2164
  if (!file && unresolved.packageName) {
1885
2165
  try {
1886
- file = createRequire(cleanModuleId(unresolved.importer)).resolve(
2166
+ file = createRequire(cleanModuleId2(unresolved.importer)).resolve(
1887
2167
  unresolved.specifier
1888
2168
  );
1889
2169
  } catch {
@@ -1892,7 +2172,7 @@ function tempoVitePlugin(options = {}) {
1892
2172
  if (!file) continue;
1893
2173
  server.watcher.add(file);
1894
2174
  unresolvedImports.delete(key);
1895
- errorServer.clearErrorForModules([unresolved.importer]);
2175
+ compileErrors.errorServer.clearErrorForModules([unresolved.importer]);
1896
2176
  resolvedImportInPass = true;
1897
2177
  }
1898
2178
  if (resolvedImportInPass) {
@@ -1911,6 +2191,7 @@ function tempoVitePlugin(options = {}) {
1911
2191
  config(config, environment) {
1912
2192
  if (!enabled || environment.command !== "serve") return;
1913
2193
  applyManagedCanvasDependencyScan(config);
2194
+ excludeTempoHostFromAppDependencyScan(config);
1914
2195
  const dedupe = ["react", "react-dom"].filter(
1915
2196
  (name) => !config.resolve?.dedupe?.includes(name)
1916
2197
  );
@@ -1920,7 +2201,10 @@ function tempoVitePlugin(options = {}) {
1920
2201
  dedupe,
1921
2202
  ...localAliases.length ? { alias: localAliases } : {}
1922
2203
  },
1923
- ...config.css?.devSourcemap === void 0 ? { css: { devSourcemap: true } } : {}
2204
+ ...config.css?.devSourcemap === void 0 ? { css: { devSourcemap: true } } : {},
2205
+ // Vite concatenates this with the app's own ignored list. An app
2206
+ // that turned watching off (watch: null) keeps it off.
2207
+ ...flutterTarget && config.server?.watch !== null ? { server: { watch: { ignored: [FLUTTER_HOST_WATCH_IGNORE] } } } : {}
1924
2208
  };
1925
2209
  },
1926
2210
  resolveId: {
@@ -1980,7 +2264,7 @@ function tempoVitePlugin(options = {}) {
1980
2264
  const file = decodeURIComponent(
1981
2265
  id.slice("\0tempo:astro-component:".length, -3)
1982
2266
  );
1983
- const { readAstroControlsMetadata } = await import("./controls-reader-SNMI2UY7.js");
2267
+ const { readAstroControlsMetadata } = await import("./controls-reader-Z7OQWYWQ.js");
1984
2268
  const controls = await readAstroControlsMetadata(
1985
2269
  file,
1986
2270
  async (specifier, importer) => (await this.resolve(specifier, importer, { skipSelf: true }))?.id ?? null,
@@ -1989,8 +2273,8 @@ function tempoVitePlugin(options = {}) {
1989
2273
  // including optional controls files that do not exist yet.
1990
2274
  (dependency) => devServer?.watcher.add(dependency),
1991
2275
  [
1992
- resolve5(sourceIdentityRoot, "tempo/controls.ts"),
1993
- resolve5(canonicalRoot, "controls.ts")
2276
+ resolve7(sourceIdentityRoot, "tempo/controls.ts"),
2277
+ resolve7(canonicalRoot, "controls.ts")
1994
2278
  ]
1995
2279
  );
1996
2280
  astroDescriptorDependencies.set(id, new Set(controls.dependencies));
@@ -2019,16 +2303,16 @@ if (import.meta.hot) import.meta.hot.dispose(() => {
2019
2303
  });`;
2020
2304
  }
2021
2305
  if (!enabled || command === "build" || id.startsWith("\0")) return null;
2022
- await rapidHotUpdateReplay.settled(burstKey(id));
2306
+ await hotUpdateNet.settled(id);
2023
2307
  return null;
2024
2308
  }
2025
2309
  },
2026
2310
  // Expose error server for testing
2027
- _tempoErrorServer: errorServer,
2311
+ _tempoErrorServer: compileErrors.errorServer,
2028
2312
  // Test seam pinning the exact evidence the missed-change sweep reads.
2029
2313
  _tempoHotUpdateState: {
2030
2314
  lastHotUpdateMtimeMs(file) {
2031
- return hotUpdateMtimesMs.get(normalizedFileKey(file));
2315
+ return hotUpdateNet.lastHotUpdateMtimeMs(file);
2032
2316
  }
2033
2317
  },
2034
2318
  _tempoUnresolvedImportState: {
@@ -2076,31 +2360,26 @@ if (import.meta.hot) import.meta.hot.dispose(() => {
2076
2360
  }
2077
2361
  canonicalRoot = resolveCanonicalRoot(options.root ?? resolvedConfig.root);
2078
2362
  sourceIdentityRoot = options.sourceIdentityRoot ? resolveCanonicalRoot(
2079
- resolve5(resolvedConfig.root, options.sourceIdentityRoot)
2363
+ resolve7(resolvedConfig.root, options.sourceIdentityRoot)
2080
2364
  ) : canonicalRoot;
2081
2365
  },
2082
2366
  configureServer(server) {
2083
2367
  if (!enabled) return;
2084
- registrationActivity.set(server, 0);
2085
- registrationTransforms.delete(server.environments?.client ?? server);
2086
- const events = ["change", "add", "unlink"];
2087
- for (const event of events)
2088
- server.watcher?.prependListener?.(event, recordHotUpdateCoverage);
2368
+ resetCanvasHostRegistration(server);
2369
+ hotUpdateNet.installCoverage(server);
2089
2370
  const ownInteractModule = resolveOwnInteractProjectionModule();
2090
2371
  const allow = server.config?.server?.fs?.allow;
2091
2372
  if (Array.isArray(allow)) {
2092
2373
  const requiredRoots = [
2093
2374
  sourceIdentityRoot,
2094
- ...ownInteractModule ? [dirname3(ownInteractModule)] : []
2375
+ ...ownInteractModule ? [dirname4(ownInteractModule)] : []
2095
2376
  ];
2096
2377
  for (const requiredRoot of requiredRoots) {
2097
2378
  if (!allow.includes(requiredRoot)) allow.push(requiredRoot);
2098
2379
  }
2099
2380
  }
2100
2381
  devServer = server;
2101
- server.ws.on?.(VITE_ERROR_SUBSCRIBE_EVENT, (_data, client) => {
2102
- client.send(VITE_ERROR_STATE_EVENT, errorServer.currentError);
2103
- });
2382
+ compileErrors.attach(server);
2104
2383
  syncUnresolvedImportWatcher();
2105
2384
  server.watcher?.once?.("close", closeUnresolvedImportWatchers);
2106
2385
  server.httpServer?.once("close", closeUnresolvedImportWatchers);
@@ -2128,18 +2407,38 @@ if (import.meta.hot) import.meta.hot.dispose(() => {
2128
2407
  )?.[1];
2129
2408
  if (name) {
2130
2409
  const file = ["public", "static"].map(
2131
- (directory) => join3(sourceIdentityRoot, directory, "tempo-assets", name)
2132
- ).find((file2) => existsSync2(file2));
2410
+ (directory) => join4(sourceIdentityRoot, directory, "tempo-assets", name)
2411
+ ).find((file2) => existsSync4(file2));
2133
2412
  if (file) req.url = `/@fs/${file.replace(/\\/g, "/")}`;
2134
2413
  }
2135
- handleTempoMiddleware(errorServer, server, req, res, next);
2414
+ handleTempoMiddleware(compileErrors, server, req, res, next);
2415
+ });
2416
+ const flutterForwarding = flutterTarget ? createFlutterForwarding({
2417
+ target: flutterTarget,
2418
+ config: server.config
2419
+ }) : null;
2420
+ if (flutterForwarding) {
2421
+ server.middlewares.use(flutterForwarding.prefix);
2422
+ server.httpServer?.on("upgrade", flutterForwarding.upgrade);
2423
+ }
2424
+ if (flutterTarget) {
2425
+ const stopRelaunchWatch = watchFlutterRelaunches({
2426
+ target: flutterTarget,
2427
+ onRelaunch() {
2428
+ server.config.logger.info(
2429
+ "[tempo] Flutter dev server relaunched; reloading the canvas host page"
2430
+ );
2431
+ server.ws.send({ type: "full-reload" });
2432
+ }
2433
+ });
2434
+ server.httpServer?.once("close", stopRelaunchWatch);
2435
+ server.watcher?.once?.("close", stopRelaunchWatch);
2436
+ }
2437
+ hotUpdateNet.installSweep(server, {
2438
+ sweepIntervalMs: MISSED_CHANGE_SWEEP_INTERVAL_MS2,
2439
+ listExtraFiles: () => compileErrors.errorServer.errorFiles,
2440
+ afterSweep: () => compileErrors.pollRecovery(server)
2136
2441
  });
2137
- installMissedChangeSweep(
2138
- server,
2139
- () => errorServer.errorFiles,
2140
- (file) => hotUpdateMtimesMs.get(normalizedFileKey(file)),
2141
- () => pollCompileErrorRecovery(server)
2142
- );
2143
2442
  installTailwindScanNet(server);
2144
2443
  const interceptHmrSend = (target) => {
2145
2444
  const orig = target.send.bind(target);
@@ -2156,16 +2455,7 @@ if (import.meta.hot) import.meta.hot.dispose(() => {
2156
2455
  );
2157
2456
  }
2158
2457
  if (typed.type === "error") {
2159
- const err = typed.err;
2160
- errorServer.setError({
2161
- type: "compile",
2162
- message: err?.message ?? "Unknown error",
2163
- stack: err?.stack,
2164
- file: err?.id ?? err?.loc?.file,
2165
- frame: err?.frame,
2166
- plugin: err?.plugin,
2167
- loc: err?.loc
2168
- });
2458
+ compileErrors.recordHmrError(typed.err);
2169
2459
  } else if (typed.type === "update" && !processedUpdatePayloads.has(payload)) {
2170
2460
  processedUpdatePayloads.add(payload);
2171
2461
  const updatePayload = typed;
@@ -2175,7 +2465,7 @@ if (import.meta.hot) import.meta.hot.dispose(() => {
2175
2465
  updatePayload.updates = acceptedUpdates;
2176
2466
  }
2177
2467
  const paths = acceptedUpdates?.map((u) => u.path).filter((p) => typeof p === "string") ?? [];
2178
- errorServer.clearErrorForModules(paths);
2468
+ compileErrors.errorServer.clearErrorForModules(paths);
2179
2469
  if (updates && updates.length > 0 && acceptedUpdates?.length === 0) {
2180
2470
  return;
2181
2471
  }
@@ -2190,16 +2480,18 @@ if (import.meta.hot) import.meta.hot.dispose(() => {
2190
2480
  if (clientHot && clientHot !== server.ws) {
2191
2481
  interceptHmrSend(clientHot);
2192
2482
  }
2483
+ if (flutterForwarding) {
2484
+ server.middlewares.use(flutterForwarding.fallthrough);
2485
+ }
2193
2486
  };
2194
2487
  },
2195
2488
  closeBundle() {
2196
2489
  astroDescriptorDependencies.clear();
2197
2490
  devServer = void 0;
2198
- rapidHotUpdateReplay.clear();
2491
+ hotUpdateNet.clear();
2199
2492
  hmrGenerationFence.clear();
2200
2493
  prunedModuleDeletion.clear();
2201
- hotUpdateMtimesMs.clear();
2202
- compileErrorPollSchedule.clear();
2494
+ compileErrors.reset();
2203
2495
  closeUnresolvedImportWatchers();
2204
2496
  },
2205
2497
  hotUpdate: {
@@ -2219,25 +2511,16 @@ if (import.meta.hot) import.meta.hot.dispose(() => {
2219
2511
  )) {
2220
2512
  return [];
2221
2513
  }
2222
- if (context.type === "update" && context.modules.length > 0) {
2223
- rapidHotUpdateReplay.observe(burstKey(context.file), () => {
2224
- context.server.config.logger.info(
2225
- `[tempo] replaying settled rapid watcher change: ${context.file}`,
2226
- { timestamp: true }
2227
- );
2228
- context.server.watcher.emit("change", context.file);
2229
- });
2230
- }
2514
+ if (context.type === "update" && context.modules.length > 0)
2515
+ hotUpdateNet.observeUpdate(context.server, context.file);
2231
2516
  if (context.type !== "create") {
2232
2517
  forgetUnresolvedImportsFrom(context.file);
2233
2518
  }
2234
- if (context.type === "update" && hasActiveCompileError(context.file) && await recoverActiveCompileError(context.server, context.file)) {
2519
+ if (context.type === "update" && compileErrors.hasActiveCompileError(context.file) && await compileErrors.recover(context.server, context.file)) {
2235
2520
  return [];
2236
2521
  }
2237
2522
  if (context.type === "delete") {
2238
- defaultExportIdentityByFile.delete(
2239
- canonicalIdentityKey(context.file)
2240
- );
2523
+ jsxModuleAnnotation.forgetDefaultExportIdentity(context.file);
2241
2524
  if (prunedModuleDeletion.suppressDeletion(
2242
2525
  this.environment.moduleGraph,
2243
2526
  context.modules
@@ -2269,17 +2552,10 @@ if (import.meta.hot) import.meta.hot.dispose(() => {
2269
2552
  context.modules.splice(0, context.modules.length, ...affected);
2270
2553
  if (!enabled) return;
2271
2554
  if (isIncrementalRegistration(context.file)) return [];
2272
- if (context.modules.length > 0) {
2273
- rapidHotUpdateReplay.observe(burstKey(context.file), () => {
2274
- context.server.config.logger.info(
2275
- `[tempo] replaying settled rapid watcher change: ${context.file}`,
2276
- { timestamp: true }
2277
- );
2278
- context.server.watcher.emit("change", context.file);
2279
- });
2280
- }
2555
+ if (context.modules.length > 0)
2556
+ hotUpdateNet.observeUpdate(context.server, context.file);
2281
2557
  forgetUnresolvedImportsFrom(context.file);
2282
- if (hasActiveCompileError(context.file) && await recoverActiveCompileError(context.server, context.file)) {
2558
+ if (compileErrors.hasActiveCompileError(context.file) && await compileErrors.recover(context.server, context.file)) {
2283
2559
  return [];
2284
2560
  }
2285
2561
  if (await repairDefaultExportIdentityRewrite(context)) {
@@ -2358,138 +2634,23 @@ if (import.meta.hot) import.meta.hot.dispose(() => {
2358
2634
  if (!enabled || command === "build") {
2359
2635
  return null;
2360
2636
  }
2361
- if (devServer) {
2362
- registrationActivity.set(
2363
- devServer,
2364
- (registrationActivity.get(devServer) ?? 0) + 1
2365
- );
2366
- }
2637
+ if (devServer) noteCanvasHostRegistrationActivity(devServer);
2367
2638
  if (id.startsWith("\0")) {
2368
2639
  return null;
2369
2640
  }
2370
- const cleanId = cleanModuleId(id);
2641
+ const cleanId = cleanModuleId2(id);
2371
2642
  if (cleanId.replace(/\\/g, "/").endsWith("/vite/dist/client/client.mjs")) {
2372
2643
  const code = preservePendingViteModuleUpdates(source);
2373
2644
  return code === source ? null : { code, map: null };
2374
2645
  }
2375
- const controlsSource = controlsFilter(cleanId) ? transformControls(source, cleanId) : source;
2376
- if (!filter(cleanId)) {
2377
- if (controlsSource !== source)
2378
- return { code: controlsSource, map: null };
2379
- return null;
2380
- }
2381
- try {
2382
- const filepath = relative2(canonicalRoot, cleanId);
2383
- const descriptor = openSync(cleanId, "r");
2384
- let snapshot;
2385
- try {
2386
- const before2 = fstatSync(descriptor);
2387
- const rawSource2 = readFileSync4(descriptor, "utf8");
2388
- snapshot = { before: before2, rawSource: rawSource2, after: fstatSync(descriptor) };
2389
- } finally {
2390
- closeSync(descriptor);
2391
- }
2392
- const { before, after, rawSource } = snapshot;
2393
- const stable = ["mtimeMs", "ctimeMs", "size", "ino", "dev"];
2394
- let loadedSource = source === rawSource ? source : void 0;
2395
- if (loadedSource === void 0 && typeof this.getCombinedSourcemap === "function") {
2396
- try {
2397
- const map = this.getCombinedSourcemap();
2398
- const sourceRoot = map.sourceRoot;
2399
- const matches = map.sources.flatMap((path, index) => {
2400
- const sourcePath = path.startsWith("file:") ? fileURLToPath(path) : path;
2401
- const file = isAbsolute2(sourcePath) ? sourcePath : resolve5(
2402
- dirname3(cleanId),
2403
- typeof sourceRoot === "string" ? sourceRoot : "",
2404
- sourcePath
2405
- );
2406
- let sameFile = cleanModuleId(file).replace(/\\/g, "/") === cleanId.replace(/\\/g, "/");
2407
- if (!sameFile) {
2408
- try {
2409
- sameFile = realpathSync3.native(file) === realpathSync3.native(cleanId);
2410
- } catch {
2411
- }
2412
- }
2413
- return sameFile && typeof map.sourcesContent?.[index] === "string" ? [map.sourcesContent[index]] : [];
2414
- });
2415
- if (matches.length === 1) loadedSource = matches[0];
2416
- } catch {
2417
- }
2418
- }
2419
- const witnessed = loadedSource === rawSource && stable.every((key) => before[key] === after[key]);
2420
- const modifiedtsMs = witnessed ? Math.trunc(before.mtimeMs) : 0;
2421
- const sourceVersion = witnessed ? sourceVersionHash(rawSource) : "";
2422
- const identityKey = canonicalIdentityKey(cleanId);
2423
- if (!defaultExportIdentityByFile.has(identityKey)) {
2424
- defaultExportIdentityByFile.set(
2425
- identityKey,
2426
- readDefaultExportIdentity(rawSource)
2427
- );
2428
- }
2429
- const resolvedComponents = /* @__PURE__ */ new Map();
2430
- if (source.includes("tempo-sdk/canvas") && typeof this.resolve === "function") {
2431
- const imports = parseCanvasFile(cleanId, source).storyboards.flatMap(
2432
- (board) => board.component?.import?.source ?? []
2433
- );
2434
- await Promise.all(
2435
- [...new Set(imports)].map(async (specifier) => {
2436
- const resolved = await this.resolve(specifier, cleanId, {
2437
- skipSelf: true
2438
- });
2439
- if (resolved) resolvedComponents.set(specifier, resolved.id);
2440
- })
2441
- );
2442
- }
2443
- const componentReferences = canvasComponentAnnotations(
2444
- cleanId,
2445
- source,
2446
- resolvedComponents
2447
- );
2448
- const result = annotateFile(source, cleanId, (info) => {
2449
- const props = {
2450
- ...componentReferences.get(info.element.openingElement.start),
2451
- ...computeTempoAnnotatedProps({
2452
- info,
2453
- filepath,
2454
- modifiedtsMs,
2455
- sourceVersion,
2456
- computeAnnotatedProps: options.computeAnnotatedProps
2457
- })
2458
- };
2459
- if (!witnessed) {
2460
- delete props["data-tempo-filepath"];
2461
- delete props["data-tempo-position"];
2462
- delete props["data-tempo-expr"];
2463
- delete props["data-tempo-modifiedts"];
2464
- delete props["data-tempo-source-version"];
2465
- }
2466
- return props;
2467
- });
2468
- if (result.parseResult.errors.length > 0) return null;
2469
- const annotated = result.elementsAnnotated === 0 ? source : result.annotatedSource;
2470
- const withControls = controlsFilter(cleanId) ? transformControls(annotated, cleanId) : annotated;
2471
- return {
2472
- code: witnessed ? appendModuleVersionRecord(
2473
- withControls,
2474
- filepath,
2475
- modifiedtsMs,
2476
- sourceVersion
2477
- ) : withControls,
2478
- map: null
2479
- };
2480
- } catch {
2481
- return null;
2482
- }
2646
+ return jsxModuleAnnotation.annotateJsxModule(this, source, cleanId);
2483
2647
  }
2484
2648
  };
2485
2649
  }
2486
2650
  var tempoAnnotate = tempoVitePlugin;
2487
2651
 
2488
2652
  export {
2489
- TEMPO_HOST_IDENTITY_ENDPOINT,
2490
- TEMPO_HOST_IDENTITY_CAPABILITY_HEADER,
2491
- createTempoHostIdentity,
2492
2653
  tempoVitePlugin,
2493
2654
  tempoAnnotate
2494
2655
  };
2495
- //# sourceMappingURL=chunk-WTQQOLXM.js.map
2656
+ //# sourceMappingURL=chunk-R3RYGAPB.js.map