tempo-sdk 0.0.60 → 0.0.69

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 (108) hide show
  1. package/astro/client.d.ts +4 -0
  2. package/dist/assets/editor.js +1 -1
  3. package/dist/assets/index.d.ts +10 -63
  4. package/dist/assets/index.js +35 -33
  5. package/dist/assets/index.js.map +1 -1
  6. package/dist/assets/parser.js +1 -1
  7. package/dist/astro/asset-preview-client.d.ts +4 -0
  8. package/dist/astro/asset-preview-client.js +93 -0
  9. package/dist/astro/asset-preview-client.js.map +1 -0
  10. package/dist/astro/controls.d.ts +7 -0
  11. package/dist/astro/controls.js +7 -0
  12. package/dist/astro/controls.js.map +1 -0
  13. package/dist/astro/document-client.d.ts +10 -0
  14. package/dist/astro/document-client.js +78 -0
  15. package/dist/astro/document-client.js.map +1 -0
  16. package/dist/astro/runtime.d.ts +15 -0
  17. package/dist/astro/runtime.js +86 -0
  18. package/dist/astro/runtime.js.map +1 -0
  19. package/dist/astro.d.ts +21 -0
  20. package/dist/astro.js +808 -0
  21. package/dist/astro.js.map +1 -0
  22. package/dist/canvas/astro-contract.d.ts +21 -0
  23. package/dist/canvas/astro-contract.js +9 -0
  24. package/dist/canvas/astro-contract.js.map +1 -0
  25. package/dist/canvas/astro.d.ts +18 -0
  26. package/dist/canvas/astro.js +42 -0
  27. package/dist/canvas/astro.js.map +1 -0
  28. package/dist/canvas/editor.d.ts +1 -1
  29. package/dist/canvas/editor.js +3 -2
  30. package/dist/canvas/editor.js.map +1 -1
  31. package/dist/canvas/index.d.ts +1 -1
  32. package/dist/canvas/index.js +40 -16
  33. package/dist/canvas/index.js.map +1 -1
  34. package/dist/canvas/interact-projection.js +4 -4
  35. package/dist/canvas/parser.d.ts +3 -1
  36. package/dist/canvas/parser.js +1 -1
  37. package/dist/canvas/svelte.d.ts +1 -1
  38. package/dist/canvas/svelte.js +3 -3
  39. package/dist/{chunk-5BHIHP25.js → chunk-2JRAG36X.js} +37 -11
  40. package/dist/chunk-2JRAG36X.js.map +1 -0
  41. package/dist/{chunk-N2TYN3RB.js → chunk-6AAE4LYV.js} +123 -123
  42. package/dist/chunk-6AAE4LYV.js.map +1 -0
  43. package/dist/{chunk-FQSZRVSL.js → chunk-6BSLP7P3.js} +46 -5
  44. package/dist/chunk-6BSLP7P3.js.map +1 -0
  45. package/dist/{chunk-7DT5DDSH.js → chunk-6IR5JY6W.js} +106 -7
  46. package/dist/chunk-6IR5JY6W.js.map +1 -0
  47. package/dist/chunk-77DZCV5Z.js +38 -0
  48. package/dist/chunk-77DZCV5Z.js.map +1 -0
  49. package/dist/{chunk-MXKZZOLM.js → chunk-EYKOOLPL.js} +368 -32
  50. package/dist/chunk-EYKOOLPL.js.map +1 -0
  51. package/dist/chunk-F23JGM4U.js +107 -0
  52. package/dist/chunk-F23JGM4U.js.map +1 -0
  53. package/dist/chunk-FE6TYCLF.js +1514 -0
  54. package/dist/chunk-FE6TYCLF.js.map +1 -0
  55. package/dist/chunk-H6OZIX2U.js +133 -0
  56. package/dist/chunk-H6OZIX2U.js.map +1 -0
  57. package/dist/chunk-JVVHU3A7.js +1077 -0
  58. package/dist/chunk-JVVHU3A7.js.map +1 -0
  59. package/dist/{chunk-2IQD2KPS.js → chunk-KOSJXE4G.js} +3 -102
  60. package/dist/chunk-KOSJXE4G.js.map +1 -0
  61. package/dist/{chunk-TL4MGN7E.js → chunk-NSKYOKG5.js} +254 -10
  62. package/dist/chunk-NSKYOKG5.js.map +1 -0
  63. package/dist/chunk-OX2YKYSL.js +13 -0
  64. package/dist/chunk-OX2YKYSL.js.map +1 -0
  65. package/dist/{chunk-VMTQDG4U.js → chunk-PXDTH36X.js} +12 -10
  66. package/dist/chunk-PXDTH36X.js.map +1 -0
  67. package/dist/{chunk-XLEKCOB7.js → chunk-PYAJHLXO.js} +56 -1
  68. package/dist/chunk-PYAJHLXO.js.map +1 -0
  69. package/dist/{chunk-OTVBSF7U.js → chunk-Q2A46HHW.js} +17 -12
  70. package/dist/chunk-Q2A46HHW.js.map +1 -0
  71. package/dist/chunk-WTQQOLXM.js +2495 -0
  72. package/dist/chunk-WTQQOLXM.js.map +1 -0
  73. package/dist/controls-reader-SNMI2UY7.js +191 -0
  74. package/dist/controls-reader-SNMI2UY7.js.map +1 -0
  75. package/dist/controls-uCaQ3CNX.d.ts +61 -0
  76. package/dist/expo/plugin.cjs +16 -11
  77. package/dist/expo/plugin.cjs.map +1 -1
  78. package/dist/expo/plugin.js +1 -1
  79. package/dist/expo-babel-plugin.cjs +16 -11
  80. package/dist/expo-babel-plugin.cjs.map +1 -1
  81. package/dist/expo-babel-plugin.js +1 -1
  82. package/dist/index.d.ts +4 -0
  83. package/dist/index.js +10 -2465
  84. package/dist/index.js.map +1 -1
  85. package/dist/nextjs/plugin.cjs +45 -4
  86. package/dist/nextjs/plugin.cjs.map +1 -1
  87. package/dist/nextjs/plugin.js +1 -1
  88. package/dist/nextjs-loader.cjs +61 -15
  89. package/dist/nextjs-loader.cjs.map +1 -1
  90. package/dist/nextjs.cjs +45 -4
  91. package/dist/nextjs.cjs.map +1 -1
  92. package/dist/nextjs.d.cts +4 -4
  93. package/dist/nextjs.d.ts +4 -4
  94. package/dist/nextjs.js +1 -1
  95. package/dist/{storyboard-DjOF61B_.d.ts → storyboard-4YdTYq_e.d.ts} +1 -1
  96. package/dist/svelte.js +7 -1075
  97. package/dist/svelte.js.map +1 -1
  98. package/package.json +45 -4
  99. package/dist/chunk-2IQD2KPS.js.map +0 -1
  100. package/dist/chunk-5BHIHP25.js.map +0 -1
  101. package/dist/chunk-7DT5DDSH.js.map +0 -1
  102. package/dist/chunk-FQSZRVSL.js.map +0 -1
  103. package/dist/chunk-MXKZZOLM.js.map +0 -1
  104. package/dist/chunk-N2TYN3RB.js.map +0 -1
  105. package/dist/chunk-OTVBSF7U.js.map +0 -1
  106. package/dist/chunk-TL4MGN7E.js.map +0 -1
  107. package/dist/chunk-VMTQDG4U.js.map +0 -1
  108. package/dist/chunk-XLEKCOB7.js.map +0 -1
@@ -0,0 +1,2495 @@
1
+ import {
2
+ appendModuleVersionRecord,
3
+ computeTempoAnnotatedProps
4
+ } from "./chunk-F23JGM4U.js";
5
+ import {
6
+ annotateFile
7
+ } from "./chunk-H6OZIX2U.js";
8
+ import {
9
+ sourceVersionHash
10
+ } from "./chunk-KOSJXE4G.js";
11
+ import {
12
+ parseCanvasFile
13
+ } from "./chunk-PXDTH36X.js";
14
+ import {
15
+ parseControlsFile
16
+ } from "./chunk-PYAJHLXO.js";
17
+ import {
18
+ VITE_ERROR_CLIENT_PATH,
19
+ VITE_ERROR_CLIENT_SOURCE,
20
+ VITE_ERROR_STATE_EVENT,
21
+ VITE_ERROR_SUBSCRIBE_EVENT
22
+ } from "./chunk-K3EYTZLL.js";
23
+ import {
24
+ TEMPO_INTERACT_FRAME_NAME
25
+ } 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
+ }
94
+
95
+ // local-prebuilt-aliases.ts
96
+ import { existsSync } from "fs";
97
+ import { join, resolve as resolve2 } from "path";
98
+ function localPrebuiltAliases(root) {
99
+ if (process.env.TEMPO_MONOREPO_SDK_SOURCE !== "local-prebuilt") return [];
100
+ const sdk = resolve2(root ?? process.cwd(), "node_modules/tempo-sdk");
101
+ if (!existsSync(join(sdk, ".tempo-prebuilt-source.json"))) return [];
102
+ return ["canvas", "assets"].flatMap((entry) => {
103
+ const replacement = join(sdk, "dist", entry, "index.js");
104
+ return existsSync(replacement) ? [{ find: new RegExp(`^tempo-sdk/${entry}$`), replacement }] : [];
105
+ });
106
+ }
107
+
108
+ // canvas-dependency-scan.ts
109
+ import { relative, resolve as resolve3 } from "path";
110
+ function applyManagedCanvasDependencyScan(config, env = process.env) {
111
+ const host = env.TEMPO_CANVAS_HOST_ROOT;
112
+ const canvases = env.TEMPO_CANVAS_SOURCE_ROOT;
113
+ if (!host || !canvases || resolve3(config.root ?? process.cwd()) !== resolve3(host))
114
+ return;
115
+ const legacyGlob = [
116
+ relative(host, canvases).replace(/\\/g, "/"),
117
+ "**/index.canvas.tsx"
118
+ ].filter(Boolean).join("/");
119
+ const entries = config.optimizeDeps?.entries;
120
+ const retained = (entries === void 0 ? [] : typeof entries === "string" ? [entries] : entries).filter(
121
+ (entry) => entry.replace(/\\/g, "/").replace(/^\.\//, "") !== legacyGlob
122
+ );
123
+ config.optimizeDeps ?? (config.optimizeDeps = {});
124
+ config.optimizeDeps.entries = [.../* @__PURE__ */ new Set(["index.html", ...retained])];
125
+ for (const client of [
126
+ "tempo-sdk/canvas",
127
+ "tempo-sdk/canvas/interact-projection"
128
+ ]) {
129
+ if (config.optimizeDeps.exclude?.some(
130
+ (id) => client === id || client.startsWith(`${id}/`)
131
+ ))
132
+ continue;
133
+ config.optimizeDeps.include = [
134
+ .../* @__PURE__ */ new Set([...config.optimizeDeps.include ?? [], client])
135
+ ];
136
+ }
137
+ }
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
+ }
204
+ }
205
+
206
+ // index.ts
207
+ 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
+
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
+ }
278
+
279
+ // pruned-module-deletion.ts
280
+ function createPrunedModuleDeletionGuard() {
281
+ let sequence = 0;
282
+ let activeReceipts = 0;
283
+ let receipts = /* @__PURE__ */ new WeakMap();
284
+ 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);
292
+ }
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;
630
+ }
631
+ previous = coveredMtimeMs;
632
+ lastSeenMtimeMs.set(file, coveredMtimeMs);
633
+ }
634
+ if (mtimeMs > previous) {
635
+ if (now() - mtimeMs < graceMs) continue;
636
+ lastSeenMtimeMs.set(file, mtimeMs);
637
+ } else if (mtimeMs < previous) {
638
+ lastSeenMtimeMs.set(file, mtimeMs);
639
+ }
640
+ const entry = pending.get(file);
641
+ if (mtimeMs <= previous && entry === void 0) continue;
642
+ const hotUpdateMtimeMs = args.lastHotUpdateMtimeMs?.(file);
643
+ let delivered;
644
+ if (hotUpdateMtimeMs !== void 0) {
645
+ delivered = hotUpdateMtimeMs >= mtimeMs;
646
+ } else {
647
+ delivered = false;
648
+ for (const module of modules) {
649
+ if ((module.lastInvalidationTimestamp ?? 0) >= mtimeMs) {
650
+ delivered = true;
651
+ break;
652
+ }
653
+ }
654
+ }
655
+ if (delivered) {
656
+ pending.delete(file);
657
+ continue;
658
+ }
659
+ const revision = entry !== void 0 && entry.mtimeMs === mtimeMs ? entry : { mtimeMs, emits: 0 };
660
+ pending.set(file, revision);
661
+ if (revision.emits >= maxEmits) continue;
662
+ revision.emits += 1;
663
+ args.emitChange(file);
664
+ emitted.push(file);
665
+ }
666
+ return emitted;
667
+ }
668
+ };
669
+ }
670
+
671
+ // rapid-hot-update-replay.ts
672
+ var RAPID_HOT_UPDATE_QUIET_MS = 100;
673
+ function createRapidHotUpdateReplay(options) {
674
+ const quietMs = options?.quietMs ?? RAPID_HOT_UPDATE_QUIET_MS;
675
+ const schedule = options?.schedule ?? setTimeout;
676
+ const cancel = options?.cancel ?? clearTimeout;
677
+ const bursts = /* @__PURE__ */ new Map();
678
+ const armGate = (burst, previous) => {
679
+ if (burst.eventCount < 2) return;
680
+ if (previous?.gate && previous.release) {
681
+ burst.gate = previous.gate;
682
+ burst.release = previous.release;
683
+ previous.release = void 0;
684
+ if (previous.expiry) cancel(previous.expiry);
685
+ } else {
686
+ burst.gate = new Promise((resolve6) => {
687
+ burst.release = resolve6;
688
+ });
689
+ }
690
+ burst.expiry = schedule(() => burst.release?.(), quietMs * 2);
691
+ };
692
+ return {
693
+ observe(file, replay) {
694
+ const previous = bursts.get(file);
695
+ if (previous?.timer) cancel(previous.timer);
696
+ const burst = {
697
+ eventCount: (previous?.eventCount ?? 0) + 1,
698
+ replay
699
+ };
700
+ armGate(burst, previous);
701
+ burst.timer = schedule(() => {
702
+ if (bursts.get(file) !== burst) return;
703
+ bursts.delete(file);
704
+ if (burst.expiry) cancel(burst.expiry);
705
+ burst.release?.();
706
+ if (burst.eventCount < 2) return;
707
+ const replayAllowance = {
708
+ eventCount: -1,
709
+ replay: burst.replay
710
+ };
711
+ replayAllowance.timer = schedule(() => {
712
+ if (bursts.get(file) === replayAllowance) bursts.delete(file);
713
+ }, quietMs);
714
+ bursts.set(file, replayAllowance);
715
+ burst.replay();
716
+ }, quietMs);
717
+ bursts.set(file, burst);
718
+ },
719
+ settled(file) {
720
+ return bursts.get(file)?.gate ?? Promise.resolve();
721
+ },
722
+ clear() {
723
+ for (const burst of bursts.values()) {
724
+ if (burst.timer) cancel(burst.timer);
725
+ if (burst.expiry) cancel(burst.expiry);
726
+ burst.release?.();
727
+ }
728
+ bursts.clear();
729
+ }
730
+ };
731
+ }
732
+
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
+ }
778
+ }
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;
815
+ try {
816
+ realFile = realpathSync2.native(file);
817
+ } catch {
818
+ }
819
+ return nearestPackageIsSdk(dirname2(realFile));
820
+ };
821
+ }
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;
834
+ }
835
+ }
836
+
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;
1109
+ }
1110
+ function createErrorServer(onErrorFile, onState) {
1111
+ const errorsByFile = /* @__PURE__ */ new Map();
1112
+ function getMostRecentError() {
1113
+ if (errorsByFile.size === 0) return null;
1114
+ let latest = null;
1115
+ for (const err of errorsByFile.values()) latest = err;
1116
+ return latest;
1117
+ }
1118
+ function broadcastCurrentState() {
1119
+ onState?.(server.currentError);
1120
+ const data = JSON.stringify(server.currentError);
1121
+ for (const client of server.clients) {
1122
+ client.write(`data: ${data}
1123
+
1124
+ `);
1125
+ }
1126
+ }
1127
+ const server = {
1128
+ get currentError() {
1129
+ return getMostRecentError();
1130
+ },
1131
+ get errorFiles() {
1132
+ return [...errorsByFile.keys()].filter((file) => file !== "unknown");
1133
+ },
1134
+ clients: /* @__PURE__ */ new Set(),
1135
+ setError(error) {
1136
+ const key = error.file ?? error.loc?.file ?? "unknown";
1137
+ const recorded = errorsByFile.get(key);
1138
+ if (recorded && isSameError(recorded, error)) return;
1139
+ if (key !== "unknown" && !recorded) onErrorFile?.(key);
1140
+ errorsByFile.delete(key);
1141
+ errorsByFile.set(key, error);
1142
+ broadcastCurrentState();
1143
+ },
1144
+ clearErrorForModules(updatedPaths) {
1145
+ if (errorsByFile.size === 0) return;
1146
+ let changed = false;
1147
+ for (const errorKey of [...errorsByFile.keys()]) {
1148
+ if (errorKey !== "unknown" && updatedPaths.some((path) => moduleIdsMatch(errorKey, path))) {
1149
+ errorsByFile.delete(errorKey);
1150
+ changed = true;
1151
+ }
1152
+ }
1153
+ if (changed) broadcastCurrentState();
1154
+ },
1155
+ clearAll() {
1156
+ errorsByFile.clear();
1157
+ broadcastCurrentState();
1158
+ }
1159
+ };
1160
+ return server;
1161
+ }
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
+ });
1169
+ }
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)) {
1175
+ 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
+ }
1182
+ }
1183
+ return [...paths];
1184
+ }
1185
+ async function synchronizeCanvasHostRegistrationTransform(server, canvasPath) {
1186
+ const wrapperPath = resolve5(server.config.root, ".tempo", "tempo-host.tsx");
1187
+ let wrapperSource;
1188
+ try {
1189
+ wrapperSource = readFileSync4(wrapperPath, "utf8");
1190
+ } catch (error) {
1191
+ throw new Error(
1192
+ `Canvas host wrapper is unavailable at ${wrapperPath}: ${error instanceof Error ? error.message : String(error)}`
1193
+ );
1194
+ }
1195
+ const registeredCanvasPaths = readGeneratedCanvasPaths(wrapperSource);
1196
+ if (!registeredCanvasPaths.includes(canvasPath)) {
1197
+ throw Object.assign(
1198
+ new Error(
1199
+ `Generated canvas host wrapper does not contain ${JSON.stringify(
1200
+ canvasPath
1201
+ )}`
1202
+ ),
1203
+ { statusCode: 409 }
1204
+ );
1205
+ }
1206
+ const canonicalWrapperPath = realpathSync3(wrapperPath);
1207
+ const modulePattern = /\bcanvasPath:\s*("(?:\\.|[^"\\])*")\s*,\s*load:\s*\(\)\s*=>\s*import\(\s*("(?:\\.|[^"\\])*")\s*\)/g;
1208
+ let moduleUrl;
1209
+ const transformer = server.environments?.client ?? server;
1210
+ for (const match of wrapperSource.matchAll(modulePattern)) {
1211
+ if (normalizeCanvasRegistrationPath(JSON.parse(match[1])) !== canvasPath)
1212
+ continue;
1213
+ const resolvedModule = await transformer.pluginContainer.resolveId(
1214
+ JSON.parse(match[2]),
1215
+ wrapperPath
1216
+ );
1217
+ if (!resolvedModule) throw new Error(`Cannot resolve canvas ${canvasPath}`);
1218
+ const modulePath = fsPathFromModuleId(resolvedModule.id);
1219
+ moduleUrl = `/@fs/${modulePath.replace(/^\/+/, "")}`;
1220
+ await retransformCanvasHostWrapper(
1221
+ server,
1222
+ transformer,
1223
+ realpathSync3(modulePath),
1224
+ modulePath,
1225
+ `/@fs/${modulePath.replace(/^\/+/, "")}`
1226
+ );
1227
+ break;
1228
+ }
1229
+ await retransformCanvasHostWrapper(
1230
+ server,
1231
+ transformer,
1232
+ canonicalWrapperPath,
1233
+ wrapperPath
1234
+ );
1235
+ return wrapperSource.includes("tempo-incremental-canvas-registration") ? moduleUrl : void 0;
1236
+ }
1237
+ var registrationTransforms = /* @__PURE__ */ new WeakMap();
1238
+ var registrationActivity = /* @__PURE__ */ new WeakMap();
1239
+ function registrationProgress(server) {
1240
+ const optimizer = server.environments?.client?.depsOptimizer;
1241
+ const phase = optimizer?.scanProcessing ? "scanning" : Object.values(optimizer?.metadata.discovered ?? {}).some(
1242
+ (dep) => dep.processing
1243
+ ) ? "bundling" : "transforming";
1244
+ return {
1245
+ status: "compiling",
1246
+ phase,
1247
+ progress: registrationActivity.get(server) ?? 0
1248
+ };
1249
+ }
1250
+ async function retransformCanvasHostWrapper(server, transformer, canonicalWrapperPath, wrapperPath, requestUrl = CANVAS_HOST_WRAPPER_URL) {
1251
+ let confirm = registrationTransforms.get(transformer);
1252
+ if (!confirm) {
1253
+ confirm = createRegistrationTransforms();
1254
+ registrationTransforms.set(transformer, confirm);
1255
+ }
1256
+ await confirm(
1257
+ canonicalWrapperPath,
1258
+ () => traceSlowRegistration(
1259
+ async () => {
1260
+ const modules = () => transformer.moduleGraph.getModulesByFile(canonicalWrapperPath) ?? transformer.moduleGraph.getModulesByFile(wrapperPath);
1261
+ for (const module of modules() ?? []) {
1262
+ transformer.moduleGraph.invalidateModule(module);
1263
+ }
1264
+ const result = await transformer.transformRequest(requestUrl);
1265
+ if (!result) {
1266
+ throw new Error(
1267
+ `Vite did not transform ${requestUrl} after registration`
1268
+ );
1269
+ }
1270
+ const transformed = [...modules() ?? []].map(
1271
+ (module) => [
1272
+ module,
1273
+ module.transformResult
1274
+ ]
1275
+ );
1276
+ return () => transformed.length > 0 && transformed.every(
1277
+ ([module, value]) => value != null && modules()?.has(module) && module.transformResult === value
1278
+ );
1279
+ },
1280
+ (status, elapsedMs) => {
1281
+ server.config.logger.info(
1282
+ `[tempo] canvas registration ${JSON.stringify({
1283
+ ...registrationProgress(server),
1284
+ status,
1285
+ module: relative2(server.config.root, canonicalWrapperPath),
1286
+ elapsedMs
1287
+ })}`
1288
+ );
1289
+ }
1290
+ )
1291
+ );
1292
+ }
1293
+ function writeCanvasRegistrationResponseHeaders(res) {
1294
+ res.setHeader("Access-Control-Allow-Origin", "*");
1295
+ res.setHeader(
1296
+ "Access-Control-Expose-Headers",
1297
+ CANVAS_HOST_REGISTRATION_CAPABILITY_HEADER
1298
+ );
1299
+ res.setHeader(CANVAS_HOST_REGISTRATION_CAPABILITY_HEADER, "1");
1300
+ }
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));
1314
+ return;
1315
+ }
1316
+ if (url === CANVAS_HOST_REGISTRATION_ENDPOINT && req.method === "OPTIONS") {
1317
+ writeCanvasRegistrationResponseHeaders(res);
1318
+ res.writeHead(204, {
1319
+ "Access-Control-Allow-Methods": "POST, OPTIONS",
1320
+ "Access-Control-Allow-Headers": "content-type"
1321
+ });
1322
+ res.end();
1323
+ return;
1324
+ }
1325
+ if (url === CANVAS_HOST_REGISTRATION_ENDPOINT && req.method === "POST") {
1326
+ writeCanvasRegistrationResponseHeaders(res);
1327
+ void readBody(req).then(async (body) => {
1328
+ const parsed = JSON.parse(body);
1329
+ const canvasPath = typeof parsed.canvasPath === "string" ? normalizeCanvasRegistrationPath(parsed.canvasPath) : "";
1330
+ if (!canvasPath) {
1331
+ throw Object.assign(
1332
+ new Error("canvasPath must be a non-empty string"),
1333
+ { statusCode: 400 }
1334
+ );
1335
+ }
1336
+ let moduleUrl;
1337
+ const progress = await registrationReply(
1338
+ synchronizeCanvasHostRegistrationTransform(
1339
+ viteServer,
1340
+ canvasPath
1341
+ ).then((url2) => {
1342
+ moduleUrl = url2;
1343
+ }),
1344
+ () => registrationProgress(viteServer),
1345
+ parsed.poll === true
1346
+ );
1347
+ res.statusCode = progress ? 202 : 200;
1348
+ res.setHeader("Content-Type", "application/json");
1349
+ res.setHeader("Cache-Control", "no-store");
1350
+ res.end(
1351
+ JSON.stringify(
1352
+ progress ?? { canvasPath, ...moduleUrl ? { moduleUrl } : {} }
1353
+ )
1354
+ );
1355
+ }).catch((error) => {
1356
+ res.statusCode = typeof error === "object" && error !== null && "statusCode" in error && typeof error.statusCode === "number" ? error.statusCode : 500;
1357
+ res.setHeader("Content-Type", "text/plain; charset=utf-8");
1358
+ res.end(error instanceof Error ? error.message : String(error));
1359
+ });
1360
+ return;
1361
+ }
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;
1372
+ }
1373
+ if (url === "/__tempo/report-clear" && req.method === "POST") {
1374
+ errorServer.clearAll();
1375
+ res.statusCode = 200;
1376
+ res.end("ok");
1377
+ return;
1378
+ }
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;
1387
+ }
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);
1401
+ });
1402
+ return;
1403
+ }
1404
+ next();
1405
+ }
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
+ }
1458
+ function installTailwindScanNet(server) {
1459
+ const net = createTailwindScanNet({
1460
+ listCssEntries: function* () {
1461
+ const fileToModules = server.moduleGraph?.fileToModulesMap ?? /* @__PURE__ */ new Map();
1462
+ for (const [file, modules] of fileToModules) {
1463
+ if (!file.endsWith(".css")) continue;
1464
+ for (const module of modules) {
1465
+ const deps = [];
1466
+ for (const imported of module.importedModules ?? []) {
1467
+ const dep = imported.file ?? imported.url ?? imported.id;
1468
+ if (dep) deps.push(dep);
1469
+ }
1470
+ yield { cssFile: file, deps };
1471
+ }
1472
+ }
1473
+ },
1474
+ emitChange: (cssFile) => {
1475
+ server.config?.logger?.info?.(
1476
+ `[tempo] new source file outside the Tailwind scan \u2014 re-emitting change: ${cssFile}`,
1477
+ { timestamp: true }
1478
+ );
1479
+ server.watcher?.emit?.("change", cssFile);
1480
+ }
1481
+ });
1482
+ const onWatcherFile = (file) => {
1483
+ net.handleWatcherFile(file);
1484
+ };
1485
+ server.watcher?.on?.("add", onWatcherFile);
1486
+ server.watcher?.on?.("change", onWatcherFile);
1487
+ server.httpServer?.once("close", () => {
1488
+ server.watcher?.off?.("add", onWatcherFile);
1489
+ server.watcher?.off?.("change", onWatcherFile);
1490
+ net.dispose();
1491
+ });
1492
+ }
1493
+ function tempoVitePlugin(options = {}) {
1494
+ const enabled = options.enabled ?? !!process.env.TEMPO;
1495
+ const include = options.include === void 0 ? DEFAULT_INCLUDE : options.include;
1496
+ const exclude = options.exclude === void 0 ? DEFAULT_EXCLUDE : options.exclude;
1497
+ const isSdkFile = createSdkFileMatcher();
1498
+ const userFilter = createFilter(include, exclude);
1499
+ const filter = (id) => userFilter(id) && !isSdkFile(id);
1500
+ const userControlsFilter = createFilter(
1501
+ ["**/*.tsx", "**/*.jsx", "**/*.ts", "**/*.js"],
1502
+ exclude
1503
+ );
1504
+ const controlsFilter = (id) => userControlsFilter(id) && !isSdkFile(id);
1505
+ const controlsModules = /* @__PURE__ */ new Set();
1506
+ const astroDescriptorDependencies = /* @__PURE__ */ new Map();
1507
+ const invalidateAstroDescriptors = (file, graph, modules) => {
1508
+ const affected = new Set(modules);
1509
+ for (const [id, dependencies] of astroDescriptorDependencies)
1510
+ if (dependencies.has(file)) {
1511
+ const module = graph.getModuleById(id);
1512
+ if (module) {
1513
+ graph.invalidateModule(module);
1514
+ affected.add(module);
1515
+ }
1516
+ }
1517
+ return [...affected];
1518
+ };
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
+ let canonicalRoot = process.cwd();
1525
+ let sourceIdentityRoot = canonicalRoot;
1526
+ let command = "serve";
1527
+ let hmrEnabled = true;
1528
+ const errorServer = createErrorServer(
1529
+ (file) => pinErroneousRevisionCoverage(file),
1530
+ (error) => devServer?.ws.send(VITE_ERROR_STATE_EVENT, error)
1531
+ );
1532
+ const unresolvedImports = /* @__PURE__ */ new Map();
1533
+ let devServer;
1534
+ const unresolvedImportWatchers = /* @__PURE__ */ new Map();
1535
+ let unresolvedImportResolutionScheduled = false;
1536
+ let unresolvedImportResolutionRunning = false;
1537
+ let rerunUnresolvedImportResolution = false;
1538
+ let unresolvedImportWatchRearmTimer = null;
1539
+ const processedUpdatePayloads = /* @__PURE__ */ new WeakSet();
1540
+ const prunedModuleDeletion = createPrunedModuleDeletionGuard();
1541
+ 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
+ };
1555
+ const pinErroneousRevisionCoverage = (file) => {
1556
+ recordHotUpdateCoverage(file);
1557
+ };
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
+ 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 {
1655
+ 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
+ devServer?.ws.send({ type: "full-reload", path: "*" });
1663
+ return true;
1664
+ };
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
+ };
1691
+ const rememberUnresolvedImport = (specifier, importer, packageName) => {
1692
+ const key = `${importer}\0${specifier}`;
1693
+ unresolvedImports.delete(key);
1694
+ unresolvedImports.set(key, { specifier, importer, packageName });
1695
+ while (unresolvedImports.size > MAX_UNRESOLVED_IMPORTS) {
1696
+ const oldestKey = unresolvedImports.keys().next().value;
1697
+ if (oldestKey === void 0) break;
1698
+ unresolvedImports.delete(oldestKey);
1699
+ }
1700
+ syncUnresolvedImportWatcher();
1701
+ };
1702
+ const forgetUnresolvedImportsFrom = (file) => {
1703
+ for (const [key, unresolved] of unresolvedImports) {
1704
+ if (resolvedIdMatchesFile(unresolved.importer, file)) {
1705
+ unresolvedImports.delete(key);
1706
+ }
1707
+ }
1708
+ syncUnresolvedImportWatcher();
1709
+ };
1710
+ const closeUnresolvedImportWatcher = (path) => {
1711
+ unresolvedImportWatchers.get(path)?.watcher.close();
1712
+ unresolvedImportWatchers.delete(path);
1713
+ };
1714
+ const cancelUnresolvedImportWatchRearm = () => {
1715
+ if (unresolvedImportWatchRearmTimer === null) return;
1716
+ clearTimeout(unresolvedImportWatchRearmTimer);
1717
+ unresolvedImportWatchRearmTimer = null;
1718
+ };
1719
+ const scheduleUnresolvedImportWatchRearm = () => {
1720
+ if (unresolvedImportWatchRearmTimer !== null || !devServer || unresolvedImports.size === 0) {
1721
+ return;
1722
+ }
1723
+ unresolvedImportWatchRearmTimer = setTimeout(() => {
1724
+ unresolvedImportWatchRearmTimer = null;
1725
+ if (devServer && unresolvedImports.size > 0) {
1726
+ syncUnresolvedImportWatcher();
1727
+ scheduleUnresolvedImportResolution();
1728
+ }
1729
+ }, UNRESOLVED_IMPORT_WATCH_REARM_MS);
1730
+ unresolvedImportWatchRearmTimer.unref?.();
1731
+ };
1732
+ const closeUnresolvedImportWatchers = () => {
1733
+ cancelUnresolvedImportWatchRearm();
1734
+ for (const path of [...unresolvedImportWatchers.keys()]) {
1735
+ closeUnresolvedImportWatcher(path);
1736
+ }
1737
+ };
1738
+ const hasUnresolvedBarePackages = () => [...unresolvedImports.values()].some(
1739
+ (unresolved) => unresolved.packageName !== void 0
1740
+ );
1741
+ const packageWatchTarget = (unresolved) => {
1742
+ let candidate = dirname3(cleanModuleId(unresolved.importer));
1743
+ let nearestPackageRoot;
1744
+ while (true) {
1745
+ try {
1746
+ if (statSync(join3(candidate, "node_modules")).isDirectory()) {
1747
+ return join3(candidate, "node_modules", unresolved.packageName);
1748
+ }
1749
+ } catch {
1750
+ }
1751
+ if (nearestPackageRoot === void 0) {
1752
+ try {
1753
+ if (statSync(join3(candidate, "package.json")).isFile()) {
1754
+ nearestPackageRoot = candidate;
1755
+ }
1756
+ } catch {
1757
+ }
1758
+ }
1759
+ const parent = dirname3(candidate);
1760
+ if (parent === candidate) break;
1761
+ candidate = parent;
1762
+ }
1763
+ return join3(
1764
+ nearestPackageRoot ?? canonicalRoot,
1765
+ "node_modules",
1766
+ unresolved.packageName
1767
+ );
1768
+ };
1769
+ const unresolvedImportWatchTarget = (unresolved) => {
1770
+ return unresolved.packageName ? packageWatchTarget(
1771
+ unresolved
1772
+ ) : resolve5(
1773
+ dirname3(cleanModuleId(unresolved.importer)),
1774
+ cleanModuleId(unresolved.specifier)
1775
+ );
1776
+ };
1777
+ const nearestExistingDirectory = (target) => {
1778
+ let candidate = target;
1779
+ while (true) {
1780
+ try {
1781
+ if (statSync(candidate).isDirectory()) return candidate;
1782
+ } catch {
1783
+ }
1784
+ const parent = dirname3(candidate);
1785
+ if (parent === candidate) return void 0;
1786
+ candidate = parent;
1787
+ }
1788
+ };
1789
+ function syncUnresolvedImportWatcher() {
1790
+ if (!devServer || unresolvedImports.size === 0) {
1791
+ closeUnresolvedImportWatchers();
1792
+ return;
1793
+ }
1794
+ const desired = /* @__PURE__ */ new Map();
1795
+ for (const unresolved of unresolvedImports.values()) {
1796
+ const target = unresolvedImportWatchTarget(unresolved);
1797
+ const watchPath = nearestExistingDirectory(target);
1798
+ if (!watchPath) continue;
1799
+ const previous = desired.get(watchPath);
1800
+ desired.set(watchPath, {
1801
+ recursive: previous?.recursive === true || watchPath === target
1802
+ });
1803
+ }
1804
+ for (const [path, existing] of [...unresolvedImportWatchers]) {
1805
+ const next = desired.get(path);
1806
+ if (!next || next.recursive !== existing.recursive) {
1807
+ closeUnresolvedImportWatcher(path);
1808
+ }
1809
+ }
1810
+ for (const [path, options2] of desired) {
1811
+ if (unresolvedImportWatchers.has(path)) continue;
1812
+ try {
1813
+ const watcher = watchFileSystem(
1814
+ path,
1815
+ { recursive: options2.recursive },
1816
+ scheduleUnresolvedImportResolution
1817
+ );
1818
+ unresolvedImportWatchers.set(path, {
1819
+ watcher,
1820
+ recursive: options2.recursive
1821
+ });
1822
+ watcher.on("error", () => {
1823
+ closeUnresolvedImportWatcher(path);
1824
+ scheduleUnresolvedImportWatchRearm();
1825
+ });
1826
+ if (options2.recursive) scheduleUnresolvedImportResolution();
1827
+ } catch {
1828
+ closeUnresolvedImportWatcher(path);
1829
+ scheduleUnresolvedImportWatchRearm();
1830
+ }
1831
+ }
1832
+ if ([...desired.keys()].every((path) => unresolvedImportWatchers.has(path))) {
1833
+ cancelUnresolvedImportWatchRearm();
1834
+ }
1835
+ }
1836
+ function scheduleUnresolvedImportResolution() {
1837
+ if (unresolvedImportResolutionScheduled || unresolvedImportResolutionRunning) {
1838
+ rerunUnresolvedImportResolution = true;
1839
+ return;
1840
+ }
1841
+ unresolvedImportResolutionScheduled = true;
1842
+ queueMicrotask(() => {
1843
+ unresolvedImportResolutionScheduled = false;
1844
+ void runUnresolvedImportResolution();
1845
+ });
1846
+ }
1847
+ async function runUnresolvedImportResolution() {
1848
+ const server = devServer;
1849
+ if (!server || unresolvedImportResolutionRunning) return;
1850
+ unresolvedImportResolutionRunning = true;
1851
+ try {
1852
+ do {
1853
+ rerunUnresolvedImportResolution = false;
1854
+ syncUnresolvedImportWatcher();
1855
+ let resolvedImportInPass = false;
1856
+ for (const [key, unresolved] of [...unresolvedImports]) {
1857
+ let file;
1858
+ if (isRelativeImportSpecifier(unresolved.specifier)) {
1859
+ const suffixIndex = unresolved.specifier.search(/[?#]/);
1860
+ const relativePath = suffixIndex < 0 ? unresolved.specifier : unresolved.specifier.slice(0, suffixIndex);
1861
+ const candidate = resolve5(
1862
+ dirname3(cleanModuleId(unresolved.importer)),
1863
+ relativePath
1864
+ );
1865
+ const probes = [
1866
+ candidate,
1867
+ ...RELATIVE_IMPORT_RESOLVE_EXTENSIONS.map(
1868
+ (extension) => `${candidate}${extension}`
1869
+ ),
1870
+ ...RELATIVE_IMPORT_RESOLVE_EXTENSIONS.map(
1871
+ (extension) => join3(candidate, `index${extension}`)
1872
+ )
1873
+ ];
1874
+ for (const probe of probes) {
1875
+ try {
1876
+ if (statSync(probe).isFile()) {
1877
+ file = probe;
1878
+ break;
1879
+ }
1880
+ } catch {
1881
+ }
1882
+ }
1883
+ }
1884
+ if (!file && unresolved.packageName) {
1885
+ try {
1886
+ file = createRequire(cleanModuleId(unresolved.importer)).resolve(
1887
+ unresolved.specifier
1888
+ );
1889
+ } catch {
1890
+ }
1891
+ }
1892
+ if (!file) continue;
1893
+ server.watcher.add(file);
1894
+ unresolvedImports.delete(key);
1895
+ errorServer.clearErrorForModules([unresolved.importer]);
1896
+ resolvedImportInPass = true;
1897
+ }
1898
+ if (resolvedImportInPass) {
1899
+ server.ws.send({ type: "full-reload", path: "*" });
1900
+ }
1901
+ syncUnresolvedImportWatcher();
1902
+ } while (rerunUnresolvedImportResolution);
1903
+ } finally {
1904
+ unresolvedImportResolutionRunning = false;
1905
+ }
1906
+ }
1907
+ return {
1908
+ name: "tempo-annotate",
1909
+ apply: "serve",
1910
+ enforce: "pre",
1911
+ config(config, environment) {
1912
+ if (!enabled || environment.command !== "serve") return;
1913
+ applyManagedCanvasDependencyScan(config);
1914
+ const dedupe = ["react", "react-dom"].filter(
1915
+ (name) => !config.resolve?.dedupe?.includes(name)
1916
+ );
1917
+ const localAliases = localPrebuiltAliases(config.root);
1918
+ return {
1919
+ resolve: {
1920
+ dedupe,
1921
+ ...localAliases.length ? { alias: localAliases } : {}
1922
+ },
1923
+ ...config.css?.devSourcemap === void 0 ? { css: { devSourcemap: true } } : {}
1924
+ };
1925
+ },
1926
+ resolveId: {
1927
+ order: "pre",
1928
+ async handler(id, importer, resolveOptions) {
1929
+ if (id.endsWith(".astro?tempo-component")) {
1930
+ const resolved = await this.resolve(
1931
+ id.slice(0, -"?tempo-component".length),
1932
+ importer,
1933
+ { ...resolveOptions, skipSelf: true }
1934
+ );
1935
+ if (!resolved) return null;
1936
+ return `\0tempo:astro-component:${encodeURIComponent(resolved.id)}.js`;
1937
+ }
1938
+ if (enabled && id === VITE_ERROR_CLIENT_PATH) {
1939
+ return VITE_ERROR_CLIENT_ID;
1940
+ }
1941
+ if (id === INTERACT_PROJECTION_CLIENT_PATH) {
1942
+ return INTERACT_PROJECTION_CLIENT_ID;
1943
+ }
1944
+ if (id === INTERACT_PROJECTION_SDK_SPECIFIER && importer === INTERACT_PROJECTION_CLIENT_ID) {
1945
+ const resolved = await this.resolve(id, importer, {
1946
+ ...resolveOptions,
1947
+ skipSelf: true
1948
+ });
1949
+ if (resolved) return resolved;
1950
+ return resolveOwnInteractProjectionModule();
1951
+ }
1952
+ if (enabled && importer && !importer.startsWith("\0")) {
1953
+ const packageName = barePackageName(id);
1954
+ if (!isRelativeImportSpecifier(id) && !packageName) return null;
1955
+ try {
1956
+ const resolved = await this.resolve(id, importer, {
1957
+ ...resolveOptions,
1958
+ skipSelf: true
1959
+ });
1960
+ if (!resolved) rememberUnresolvedImport(id, importer, packageName);
1961
+ return resolved;
1962
+ } catch (error) {
1963
+ rememberUnresolvedImport(id, importer, packageName);
1964
+ throw error;
1965
+ }
1966
+ }
1967
+ return null;
1968
+ }
1969
+ },
1970
+ // `order: "pre"` + a null return: this hook never loads anything of its
1971
+ // own for a project file, it only decides WHEN Vite core is allowed to
1972
+ // read it. Awaiting the burst gate here (rather than in `transform`) is
1973
+ // what makes the content terminal — by `transform` the bytes have already
1974
+ // been read, so delaying there would ship a stale revision late instead of
1975
+ // not shipping it at all.
1976
+ load: {
1977
+ order: "pre",
1978
+ async handler(id) {
1979
+ if (id.startsWith("\0tempo:astro-component:")) {
1980
+ const file = decodeURIComponent(
1981
+ id.slice("\0tempo:astro-component:".length, -3)
1982
+ );
1983
+ const { readAstroControlsMetadata } = await import("./controls-reader-SNMI2UY7.js");
1984
+ const controls = await readAstroControlsMetadata(
1985
+ file,
1986
+ async (specifier, importer) => (await this.resolve(specifier, importer, { skipSelf: true }))?.id ?? null,
1987
+ // These files are read as metadata, never executed in the host.
1988
+ // Vite turns load-hook addWatchFile entries into implicit imports,
1989
+ // including optional controls files that do not exist yet.
1990
+ (dependency) => devServer?.watcher.add(dependency),
1991
+ [
1992
+ resolve5(sourceIdentityRoot, "tempo/controls.ts"),
1993
+ resolve5(canonicalRoot, "controls.ts")
1994
+ ]
1995
+ );
1996
+ astroDescriptorDependencies.set(id, new Set(controls.dependencies));
1997
+ return `export default {kind:"astro-component",module:${JSON.stringify(file.replaceAll("\\", "/"))},__tempoAstroControls:${JSON.stringify(controls).replaceAll("<", "\\u003c")}};`;
1998
+ }
1999
+ if (enabled && id === VITE_ERROR_CLIENT_ID) {
2000
+ return VITE_ERROR_CLIENT_SOURCE;
2001
+ }
2002
+ if (id === INTERACT_PROJECTION_CLIENT_ID) {
2003
+ return `import { installTempoInteractProjectionSource } from ${JSON.stringify(INTERACT_PROJECTION_SDK_SPECIFIER)};
2004
+ let stop;
2005
+ const releaseOwner = () => {
2006
+ if (window.__tempoInteractProjectionOwner === "vite") delete window.__tempoInteractProjectionOwner;
2007
+ };
2008
+ if (window.parent !== window && !window.__tempoInteractProjectionOwner && (window.name === ${JSON.stringify(TEMPO_INTERACT_FRAME_NAME)} || window.name.startsWith(${JSON.stringify(`${TEMPO_INTERACT_FRAME_NAME}:`)}))) {
2009
+ window.__tempoInteractProjectionOwner = "vite";
2010
+ const stopSource = installTempoInteractProjectionSource();
2011
+ stop = () => {
2012
+ stopSource();
2013
+ releaseOwner();
2014
+ };
2015
+ }
2016
+ if (import.meta.hot) import.meta.hot.dispose(() => {
2017
+ stop?.();
2018
+ releaseOwner();
2019
+ });`;
2020
+ }
2021
+ if (!enabled || command === "build" || id.startsWith("\0")) return null;
2022
+ await rapidHotUpdateReplay.settled(burstKey(id));
2023
+ return null;
2024
+ }
2025
+ },
2026
+ // Expose error server for testing
2027
+ _tempoErrorServer: errorServer,
2028
+ // Test seam pinning the exact evidence the missed-change sweep reads.
2029
+ _tempoHotUpdateState: {
2030
+ lastHotUpdateMtimeMs(file) {
2031
+ return hotUpdateMtimesMs.get(normalizedFileKey(file));
2032
+ }
2033
+ },
2034
+ _tempoUnresolvedImportState: {
2035
+ get size() {
2036
+ return unresolvedImports.size;
2037
+ },
2038
+ get barePackageCount() {
2039
+ return [...unresolvedImports.values()].filter(
2040
+ (unresolved) => unresolved.packageName !== void 0
2041
+ ).length;
2042
+ },
2043
+ get hasBarePackageWatcher() {
2044
+ return unresolvedImportWatchers.size > 0 && hasUnresolvedBarePackages();
2045
+ },
2046
+ get barePackageWatchPath() {
2047
+ return hasUnresolvedBarePackages() ? unresolvedImportWatchers.keys().next().value : void 0;
2048
+ },
2049
+ get hasUnresolvedImportWatcher() {
2050
+ return unresolvedImportWatchers.size > 0;
2051
+ },
2052
+ get unresolvedImportWatchPath() {
2053
+ return unresolvedImportWatchers.keys().next().value;
2054
+ },
2055
+ get unresolvedImportWatchPaths() {
2056
+ return [...unresolvedImportWatchers.keys()];
2057
+ },
2058
+ get hasUnresolvedImportWatchRearm() {
2059
+ return unresolvedImportWatchRearmTimer !== null;
2060
+ },
2061
+ emitUnresolvedImportWatcherErrorForTesting() {
2062
+ for (const { watcher } of unresolvedImportWatchers.values()) {
2063
+ watcher.emit(
2064
+ "error",
2065
+ new Error("Simulated unresolved-import watcher failure")
2066
+ );
2067
+ }
2068
+ }
2069
+ },
2070
+ configResolved(resolvedConfig) {
2071
+ if (!enabled) return;
2072
+ command = resolvedConfig.command;
2073
+ hmrEnabled = resolvedConfig.server?.hmr !== false;
2074
+ if (command === "serve" && hmrEnabled) {
2075
+ installSynchronousReactRefreshBoundary(resolvedConfig.plugins ?? []);
2076
+ }
2077
+ canonicalRoot = resolveCanonicalRoot(options.root ?? resolvedConfig.root);
2078
+ sourceIdentityRoot = options.sourceIdentityRoot ? resolveCanonicalRoot(
2079
+ resolve5(resolvedConfig.root, options.sourceIdentityRoot)
2080
+ ) : canonicalRoot;
2081
+ },
2082
+ configureServer(server) {
2083
+ 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);
2089
+ const ownInteractModule = resolveOwnInteractProjectionModule();
2090
+ const allow = server.config?.server?.fs?.allow;
2091
+ if (Array.isArray(allow)) {
2092
+ const requiredRoots = [
2093
+ sourceIdentityRoot,
2094
+ ...ownInteractModule ? [dirname3(ownInteractModule)] : []
2095
+ ];
2096
+ for (const requiredRoot of requiredRoots) {
2097
+ if (!allow.includes(requiredRoot)) allow.push(requiredRoot);
2098
+ }
2099
+ }
2100
+ devServer = server;
2101
+ server.ws.on?.(VITE_ERROR_SUBSCRIBE_EVENT, (_data, client) => {
2102
+ client.send(VITE_ERROR_STATE_EVENT, errorServer.currentError);
2103
+ });
2104
+ syncUnresolvedImportWatcher();
2105
+ server.watcher?.once?.("close", closeUnresolvedImportWatchers);
2106
+ server.httpServer?.once("close", closeUnresolvedImportWatchers);
2107
+ server.middlewares.use((req, res, next) => {
2108
+ const graph = server.environments?.client?.moduleGraph;
2109
+ if (graph && req.url && (req.method === "GET" || req.method === "HEAD")) {
2110
+ const observeResponse = prunedModuleDeletion.observeRequest(
2111
+ graph,
2112
+ req.url,
2113
+ server.config.base,
2114
+ req.headers["sec-fetch-dest"],
2115
+ req.headers["if-none-match"]
2116
+ );
2117
+ if (observeResponse)
2118
+ res.once("finish", () => {
2119
+ void observeResponse(
2120
+ res.statusCode,
2121
+ res.getHeader("content-type"),
2122
+ res.getHeader("etag")
2123
+ );
2124
+ });
2125
+ }
2126
+ const name = req.url?.match(
2127
+ /^\/tempo-assets\/([a-zA-Z0-9._-]+)(?:\?.*)?$/
2128
+ )?.[1];
2129
+ if (name) {
2130
+ const file = ["public", "static"].map(
2131
+ (directory) => join3(sourceIdentityRoot, directory, "tempo-assets", name)
2132
+ ).find((file2) => existsSync2(file2));
2133
+ if (file) req.url = `/@fs/${file.replace(/\\/g, "/")}`;
2134
+ }
2135
+ handleTempoMiddleware(errorServer, server, req, res, next);
2136
+ });
2137
+ installMissedChangeSweep(
2138
+ server,
2139
+ () => errorServer.errorFiles,
2140
+ (file) => hotUpdateMtimesMs.get(normalizedFileKey(file)),
2141
+ () => pollCompileErrorRecovery(server)
2142
+ );
2143
+ installTailwindScanNet(server);
2144
+ const interceptHmrSend = (target) => {
2145
+ const orig = target.send.bind(target);
2146
+ target.send = ((...args) => {
2147
+ const payload = args[0];
2148
+ if (typeof payload === "object" && payload !== null && "type" in payload) {
2149
+ const typed = payload;
2150
+ if (typed.type === "prune") {
2151
+ const graph = server.environments?.client?.moduleGraph;
2152
+ if (graph)
2153
+ prunedModuleDeletion.observePrune(
2154
+ graph,
2155
+ typed.paths ?? []
2156
+ );
2157
+ }
2158
+ 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
+ });
2169
+ } else if (typed.type === "update" && !processedUpdatePayloads.has(payload)) {
2170
+ processedUpdatePayloads.add(payload);
2171
+ const updatePayload = typed;
2172
+ const updates = updatePayload.updates;
2173
+ const acceptedUpdates = updates ? hmrGenerationFence.filter(updates) : void 0;
2174
+ if (updates && acceptedUpdates && acceptedUpdates.length !== updates.length) {
2175
+ updatePayload.updates = acceptedUpdates;
2176
+ }
2177
+ const paths = acceptedUpdates?.map((u) => u.path).filter((p) => typeof p === "string") ?? [];
2178
+ errorServer.clearErrorForModules(paths);
2179
+ if (updates && updates.length > 0 && acceptedUpdates?.length === 0) {
2180
+ return;
2181
+ }
2182
+ }
2183
+ }
2184
+ return orig(...args);
2185
+ });
2186
+ };
2187
+ interceptHmrSend(server.ws);
2188
+ return () => {
2189
+ const clientHot = server.environments?.client?.hot;
2190
+ if (clientHot && clientHot !== server.ws) {
2191
+ interceptHmrSend(clientHot);
2192
+ }
2193
+ };
2194
+ },
2195
+ closeBundle() {
2196
+ astroDescriptorDependencies.clear();
2197
+ devServer = void 0;
2198
+ rapidHotUpdateReplay.clear();
2199
+ hmrGenerationFence.clear();
2200
+ prunedModuleDeletion.clear();
2201
+ hotUpdateMtimesMs.clear();
2202
+ compileErrorPollSchedule.clear();
2203
+ closeUnresolvedImportWatchers();
2204
+ },
2205
+ hotUpdate: {
2206
+ order: "post",
2207
+ async handler(context) {
2208
+ const affected = invalidateAstroDescriptors(
2209
+ context.file,
2210
+ this.environment.moduleGraph,
2211
+ context.modules
2212
+ );
2213
+ if (!enabled || this.environment.config.consumer !== "client")
2214
+ return affected;
2215
+ context.modules.splice(0, context.modules.length, ...affected);
2216
+ if (isIncrementalRegistration(context.file)) return [];
2217
+ if (context.type === "create" && /\/\.tempo\/asset-edit-previews\/\d+\/index\.canvas\.tsx$/.test(
2218
+ context.file.replace(/\\/g, "/")
2219
+ )) {
2220
+ return [];
2221
+ }
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
+ }
2231
+ if (context.type !== "create") {
2232
+ forgetUnresolvedImportsFrom(context.file);
2233
+ }
2234
+ if (context.type === "update" && hasActiveCompileError(context.file) && await recoverActiveCompileError(context.server, context.file)) {
2235
+ return [];
2236
+ }
2237
+ if (context.type === "delete") {
2238
+ defaultExportIdentityByFile.delete(
2239
+ canonicalIdentityKey(context.file)
2240
+ );
2241
+ if (prunedModuleDeletion.suppressDeletion(
2242
+ this.environment.moduleGraph,
2243
+ context.modules
2244
+ ))
2245
+ return [];
2246
+ return;
2247
+ }
2248
+ if (context.type === "update" && await repairDefaultExportIdentityRewrite(context)) {
2249
+ return [];
2250
+ }
2251
+ if (context.type === "update") {
2252
+ return invalidateCanvasLoader(
2253
+ context.file,
2254
+ this.environment.moduleGraph,
2255
+ context.modules
2256
+ );
2257
+ }
2258
+ }
2259
+ },
2260
+ // Vite 5 compatibility. Vite 6+ prefers `hotUpdate` above.
2261
+ handleHotUpdate: {
2262
+ order: "post",
2263
+ async handler(context) {
2264
+ const affected = invalidateAstroDescriptors(
2265
+ context.file,
2266
+ context.server.moduleGraph,
2267
+ context.modules
2268
+ );
2269
+ context.modules.splice(0, context.modules.length, ...affected);
2270
+ if (!enabled) return;
2271
+ 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
+ }
2281
+ forgetUnresolvedImportsFrom(context.file);
2282
+ if (hasActiveCompileError(context.file) && await recoverActiveCompileError(context.server, context.file)) {
2283
+ return [];
2284
+ }
2285
+ if (await repairDefaultExportIdentityRewrite(context)) {
2286
+ return [];
2287
+ }
2288
+ return invalidateCanvasLoader(
2289
+ context.file,
2290
+ context.server.moduleGraph,
2291
+ context.modules
2292
+ );
2293
+ }
2294
+ },
2295
+ transformIndexHtml(html, context) {
2296
+ if (!enabled || command !== "serve") {
2297
+ return;
2298
+ }
2299
+ const tags = [];
2300
+ if (hmrEnabled) {
2301
+ tags.push({
2302
+ tag: "script",
2303
+ attrs: { type: "module", src: VITE_ERROR_CLIENT_PATH },
2304
+ injectTo: "head-prepend"
2305
+ });
2306
+ }
2307
+ if (!hasRootMetaTag(html)) {
2308
+ tags.push({
2309
+ tag: "meta",
2310
+ attrs: {
2311
+ name: ROOT_META_NAME,
2312
+ content: canonicalRoot
2313
+ },
2314
+ injectTo: "head"
2315
+ });
2316
+ }
2317
+ if (!hasSourceIdentityRootMetaTag(html)) {
2318
+ tags.push({
2319
+ tag: "meta",
2320
+ attrs: {
2321
+ name: SOURCE_IDENTITY_ROOT_META_NAME,
2322
+ content: sourceIdentityRoot
2323
+ },
2324
+ injectTo: "head"
2325
+ });
2326
+ }
2327
+ const workspaceNonce = createTempoHostIdentity("vite", {
2328
+ root: canonicalRoot,
2329
+ pluginActive: true
2330
+ }).workspaceNonce;
2331
+ if (workspaceNonce && !hasWorkspaceNonceMetaTag(html)) {
2332
+ tags.push({
2333
+ tag: "meta",
2334
+ attrs: {
2335
+ name: TEMPO_WORKSPACE_NONCE_META_NAME,
2336
+ content: workspaceNonce
2337
+ },
2338
+ injectTo: "head"
2339
+ });
2340
+ }
2341
+ const requestPath = context?.originalUrl ?? context?.path;
2342
+ const isDeclarativeCanvasHost = requestPath ? isDeclarativeCanvasHostRequest(requestPath) : false;
2343
+ if (requestPath && !isDeclarativeCanvasHost) {
2344
+ tags.push({
2345
+ tag: "script",
2346
+ children: INTERACT_PROJECTION_BOOTSTRAP,
2347
+ injectTo: "head-prepend"
2348
+ });
2349
+ tags.push({
2350
+ tag: "script",
2351
+ attrs: { type: "module", src: INTERACT_PROJECTION_CLIENT_PATH },
2352
+ injectTo: "head-prepend"
2353
+ });
2354
+ }
2355
+ return tags.length > 0 ? tags : void 0;
2356
+ },
2357
+ async transform(source, id) {
2358
+ if (!enabled || command === "build") {
2359
+ return null;
2360
+ }
2361
+ if (devServer) {
2362
+ registrationActivity.set(
2363
+ devServer,
2364
+ (registrationActivity.get(devServer) ?? 0) + 1
2365
+ );
2366
+ }
2367
+ if (id.startsWith("\0")) {
2368
+ return null;
2369
+ }
2370
+ const cleanId = cleanModuleId(id);
2371
+ if (cleanId.replace(/\\/g, "/").endsWith("/vite/dist/client/client.mjs")) {
2372
+ const code = preservePendingViteModuleUpdates(source);
2373
+ return code === source ? null : { code, map: null };
2374
+ }
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
+ }
2483
+ }
2484
+ };
2485
+ }
2486
+ var tempoAnnotate = tempoVitePlugin;
2487
+
2488
+ export {
2489
+ TEMPO_HOST_IDENTITY_ENDPOINT,
2490
+ TEMPO_HOST_IDENTITY_CAPABILITY_HEADER,
2491
+ createTempoHostIdentity,
2492
+ tempoVitePlugin,
2493
+ tempoAnnotate
2494
+ };
2495
+ //# sourceMappingURL=chunk-WTQQOLXM.js.map