tempo-sdk 0.0.57 → 0.0.66

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 +12 -32
  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 +749 -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 +4 -2
  32. package/dist/canvas/index.js +138 -34
  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-U3SLJNRS.js → chunk-6IR5JY6W.js} +106 -7
  44. package/dist/chunk-6IR5JY6W.js.map +1 -0
  45. package/dist/{chunk-QXL6GL2P.js → chunk-6W6UKDSY.js} +46 -5
  46. package/dist/chunk-6W6UKDSY.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-DELFOKU3.js +2495 -0
  50. package/dist/chunk-DELFOKU3.js.map +1 -0
  51. package/dist/{chunk-U64AHDHZ.js → chunk-EYKOOLPL.js} +380 -34
  52. package/dist/chunk-EYKOOLPL.js.map +1 -0
  53. package/dist/chunk-F23JGM4U.js +107 -0
  54. package/dist/chunk-F23JGM4U.js.map +1 -0
  55. package/dist/chunk-FE6TYCLF.js +1514 -0
  56. package/dist/chunk-FE6TYCLF.js.map +1 -0
  57. package/dist/chunk-H6OZIX2U.js +133 -0
  58. package/dist/chunk-H6OZIX2U.js.map +1 -0
  59. package/dist/chunk-JVVHU3A7.js +1077 -0
  60. package/dist/chunk-JVVHU3A7.js.map +1 -0
  61. package/dist/{chunk-2IQD2KPS.js → chunk-KOSJXE4G.js} +3 -102
  62. package/dist/chunk-KOSJXE4G.js.map +1 -0
  63. package/dist/{chunk-TL4MGN7E.js → chunk-NSKYOKG5.js} +254 -10
  64. package/dist/chunk-NSKYOKG5.js.map +1 -0
  65. package/dist/chunk-OX2YKYSL.js +13 -0
  66. package/dist/chunk-OX2YKYSL.js.map +1 -0
  67. package/dist/{chunk-RHHVVWAC.js → chunk-PXDTH36X.js} +14 -12
  68. package/dist/chunk-PXDTH36X.js.map +1 -0
  69. package/dist/{chunk-XLEKCOB7.js → chunk-PYAJHLXO.js} +56 -1
  70. package/dist/chunk-PYAJHLXO.js.map +1 -0
  71. package/dist/{chunk-EMYYTS6D.js → chunk-Q2A46HHW.js} +19 -14
  72. package/dist/chunk-Q2A46HHW.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 +18 -13
  77. package/dist/expo/plugin.cjs.map +1 -1
  78. package/dist/expo/plugin.js +1 -1
  79. package/dist/expo-babel-plugin.cjs +18 -13
  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 -2294
  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 +63 -17
  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-BtQuVGpl.d.ts → storyboard-4YdTYq_e.d.ts} +3 -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-EMYYTS6D.js.map +0 -1
  102. package/dist/chunk-N2TYN3RB.js.map +0 -1
  103. package/dist/chunk-QXL6GL2P.js.map +0 -1
  104. package/dist/chunk-RHHVVWAC.js.map +0 -1
  105. package/dist/chunk-TL4MGN7E.js.map +0 -1
  106. package/dist/chunk-U3SLJNRS.js.map +0 -1
  107. package/dist/chunk-U64AHDHZ.js.map +0 -1
  108. package/dist/chunk-XLEKCOB7.js.map +0 -1
package/dist/index.js CHANGED
@@ -1,2299 +1,15 @@
1
1
  import {
2
- appendModuleVersionRecord,
3
- computeTempoAnnotatedProps,
4
- sourceVersionHash
5
- } from "./chunk-2IQD2KPS.js";
6
- import {
7
- VITE_ERROR_CLIENT_PATH,
8
- VITE_ERROR_CLIENT_SOURCE,
9
- VITE_ERROR_STATE_EVENT,
10
- VITE_ERROR_SUBSCRIBE_EVENT
11
- } from "./chunk-K3EYTZLL.js";
12
- import {
13
- TEMPO_INTERACT_FRAME_NAME
14
- } from "./chunk-65B52AR7.js";
15
- import {
16
- parseCanvasFile
17
- } from "./chunk-RHHVVWAC.js";
18
- import {
19
- parseControlsFile
20
- } from "./chunk-XLEKCOB7.js";
2
+ tempoAnnotate,
3
+ tempoVitePlugin
4
+ } from "./chunk-DELFOKU3.js";
5
+ import "./chunk-F23JGM4U.js";
6
+ import "./chunk-H6OZIX2U.js";
7
+ import "./chunk-KOSJXE4G.js";
8
+ import "./chunk-PXDTH36X.js";
9
+ import "./chunk-PYAJHLXO.js";
21
10
  import "./chunk-DI2ZFAWL.js";
22
-
23
- // canvas-component-reference.ts
24
- import { realpathSync } from "fs";
25
- import { dirname, isAbsolute, normalize, posix, resolve } from "path";
26
- var COMPONENT_REFERENCE_ATTRIBUTE = "data-tempo-component-reference";
27
- function moduleIdentity(file, specifier, resolved) {
28
- const bundled = resolved?.get(specifier);
29
- const target = bundled === void 0 ? specifier : bundled.replace(/\bt=\d{13}&?\b/, "").replace(/[?&]$/, "");
30
- if (target.startsWith("\0")) return target;
31
- const suffixAt = target.search(/[?#]/);
32
- let path = (suffixAt < 0 ? target : target.slice(0, suffixAt)).replace(
33
- /\\/g,
34
- "/"
35
- );
36
- const suffix = suffixAt < 0 ? "" : target.slice(suffixAt);
37
- if (bundled === void 0 && path.startsWith("."))
38
- path = resolve(dirname(file), path);
39
- if (!isAbsolute(path) && !/^[A-Za-z]:\//.test(path)) return target;
40
- if (bundled !== void 0) {
41
- try {
42
- path = realpathSync.native(path);
43
- } catch {
44
- }
45
- }
46
- return normalize(path).replace(/\\/g, "/") + suffix;
47
- }
48
- function canvasComponentAnnotations(file, source, resolved) {
49
- const result = /* @__PURE__ */ new Map();
50
- if (!source.includes("tempo-sdk/canvas")) return result;
51
- const parsed = parseCanvasFile(file, source);
52
- for (const board of parsed.storyboards) {
53
- const ref = board.component;
54
- if (board.kind !== "component" || !ref?.localName || board.openingElementSpan === void 0)
55
- continue;
56
- const member = ref.expression.match(
57
- /^\s*([$\w]+)(?:\s*\.\s*([$\w]+))?\s*$/
58
- );
59
- if (!member) continue;
60
- let name;
61
- if (ref.import) {
62
- if (ref.import.kind === "namespace") {
63
- if (!member[2]) continue;
64
- name = member[2];
65
- } else {
66
- if (member[2]) continue;
67
- name = ref.import.importedName;
68
- }
69
- } else {
70
- if (member[2]) continue;
71
- name = ref.localName;
72
- }
73
- const specifier = ref.import?.source.replace(/\\/g, "/").replace(/[?#].*/, "");
74
- const canvasDir = posix.dirname(file.replace(/\\/g, "/"));
75
- const external = specifier !== void 0 && (!specifier.startsWith(".") || !posix.join(canvasDir, specifier).startsWith(`${canvasDir}/`));
76
- result.set(board.openingElementSpan.start, {
77
- [COMPONENT_REFERENCE_ATTRIBUTE]: JSON.stringify([
78
- ref.import ? "import" : "local",
79
- moduleIdentity(file, ref.import?.source ?? file, resolved),
80
- name
81
- ]),
82
- ...external ? { "data-tempo-external-component": "true" } : {}
83
- });
84
- }
85
- return result;
86
- }
87
-
88
- // index.ts
89
- import {
90
- existsSync,
91
- openSync,
92
- closeSync,
93
- fstatSync,
94
- readFileSync as readFileSync3,
95
- realpathSync as realpathSync3,
96
- statSync,
97
- watch as watchFileSystem
98
- } from "fs";
99
- import { createRequire } from "module";
100
-
101
- // assets/controls-transform.ts
102
- function transformControlsForHmr(source, filePath, previouslyDefinedControls = false) {
103
- const calls = source.includes("defineControls") ? parseControlsFile(filePath, source) : [];
104
- if (!calls.length && !previouslyDefinedControls) return source;
105
- for (const { start, end } of calls.reverse()) {
106
- 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);
107
- }
108
- return `if (import.meta.hot) {
109
- for (const dispose of import.meta.hot.data.__tempoControlsDisposers ?? []) dispose();
110
- import.meta.hot.data.__tempoControlsDisposers = [];
111
- import.meta.hot.dispose(() => {
112
- for (const dispose of import.meta.hot.data.__tempoControlsDisposers ?? []) dispose();
113
- import.meta.hot.data.__tempoControlsDisposers = [];
114
- });
115
- }
116
- ${source}`;
117
- }
118
-
119
- // index.ts
120
- import { dirname as dirname3, isAbsolute as isAbsolute2, join as join2, relative, resolve as resolve3 } from "path";
121
- import { fileURLToPath } from "url";
122
- import { createFilter } from "@rollup/pluginutils";
123
-
124
- // ../../modules/annotation/annotate-file.ts
125
- import { parseSync as parseSync2 } from "oxc-parser";
126
-
127
- // ../../modules/file-parser/utils.ts
128
- function getTagName(name) {
129
- switch (name.type) {
130
- case "JSXIdentifier":
131
- return name.name;
132
- case "JSXNamespacedName":
133
- return `${name.namespace.name}:${name.name.name}`;
134
- case "JSXMemberExpression":
135
- return getJSXMemberExpressionName(name);
136
- }
137
- }
138
- function getJSXMemberExpressionName(node) {
139
- const object = node.object.type === "JSXIdentifier" ? node.object.name : getJSXMemberExpressionName(node.object);
140
- return `${object}.${node.property.name}`;
141
- }
142
-
143
- // ../../modules/file-parser/walk.ts
144
- import visitorKeysImport from "oxc-parser/src-js/generated/visit/keys.js";
145
- var importedKeys = visitorKeysImport;
146
- var visitorKeys = importedKeys.default ?? importedKeys;
147
- function walk(node, callbacks, parent = null) {
148
- if (node === null || node === void 0 || typeof node !== "object") return;
149
- if (Array.isArray(node)) {
150
- for (const child of node) {
151
- walk(child, callbacks, parent);
152
- }
153
- return;
154
- }
155
- const record = node;
156
- const type = record.type;
157
- if (typeof type === "string" && type in callbacks) {
158
- callbacks[type](node, parent);
159
- }
160
- const enclosing = typeof type === "string" ? node : parent;
161
- for (const value of Object.values(record)) {
162
- if (value !== null && typeof value === "object") {
163
- walk(value, callbacks, enclosing);
164
- }
165
- }
166
- }
167
-
168
- // ../../modules/file-parser/scope-analyzer/types.ts
169
- var ScopeFlags = {
170
- Top: 1 << 0,
171
- Function: 1 << 1,
172
- Block: 1 << 2,
173
- Catch: 1 << 3,
174
- Class: 1 << 4,
175
- For: 1 << 5,
176
- Switch: 1 << 6,
177
- Module: 1 << 7,
178
- StrictMode: 1 << 8,
179
- ClassStaticBlock: 1 << 9,
180
- TsModuleBlock: 1 << 10,
181
- TsConditional: 1 << 11,
182
- Type: 1 << 12,
183
- Enum: 1 << 13
184
- };
185
-
186
- // ../../modules/file-parser/scope-analyzer/scopeAnalyzer.ts
187
- import { parseSync } from "oxc-parser";
188
-
189
- // ../../modules/annotation/annotate-file.ts
190
- function formatPropValue(value) {
191
- if (value === void 0) return null;
192
- if (typeof value === "function") return value.toString();
193
- return JSON.stringify(value);
194
- }
195
- function formatProps(props) {
196
- return Object.entries(props).map(([key, value]) => {
197
- const formatted = formatPropValue(value);
198
- if (formatted === null) return null;
199
- return ` ${key}={${formatted}}`;
200
- }).filter((s) => s !== null).join("");
201
- }
202
- function getExistingAttributeNames(element) {
203
- const names = /* @__PURE__ */ new Set();
204
- for (const attr of element.openingElement.attributes ?? []) {
205
- if (attr.type !== "JSXAttribute") continue;
206
- names.add(getTagName(attr.name));
207
- }
208
- return names;
209
- }
210
- function removeExistingProps(props, existingNames) {
211
- return Object.fromEntries(
212
- Object.entries(props).filter(([key]) => !existingNames.has(key))
213
- );
214
- }
215
- var FRAGMENT_TAG_NAMES = /* @__PURE__ */ new Set(["Fragment", "React.Fragment"]);
216
- function annotateFile(source, filename, computeAnnotatedProps) {
217
- const parseResult = parseSync2(filename, source);
218
- const insertions = [];
219
- walk(parseResult.program, {
220
- JSXElement(node, parent) {
221
- const element = node;
222
- const tagName = getTagName(element.openingElement.name);
223
- if (FRAGMENT_TAG_NAMES.has(tagName)) return;
224
- const parentType = parent?.type ?? null;
225
- const props = removeExistingProps(
226
- computeAnnotatedProps({ element, tagName, parentType }),
227
- getExistingAttributeNames(element)
228
- );
229
- if (Object.keys(props).length === 0) return;
230
- const openingElement = element.openingElement;
231
- let insertPos = openingElement.end - 1;
232
- if (openingElement.selfClosing) {
233
- insertPos--;
234
- while (insertPos > openingElement.start && /\s/.test(source[insertPos - 1])) {
235
- insertPos--;
236
- }
237
- }
238
- insertions.push({ position: insertPos, text: formatProps(props) });
239
- }
240
- });
241
- insertions.sort((a, b) => a.position - b.position);
242
- const chunks = [];
243
- let lastPos = 0;
244
- for (const { position, text } of insertions) {
245
- chunks.push(source.slice(lastPos, position));
246
- chunks.push(text);
247
- lastPos = position;
248
- }
249
- chunks.push(source.slice(lastPos));
250
- return { annotatedSource: chunks.join(""), elementsAnnotated: insertions.length, parseResult };
251
- }
252
-
253
- // canvas-host-registration-contract.ts
254
- var CANVAS_HOST_REGISTRATION_ENDPOINT = "/__tempo/canvas-host-registration";
255
- var CANVAS_HOST_REGISTRATION_CAPABILITY_HEADER = "x-tempo-canvas-host-registration";
256
- function normalizeCanvasRegistrationPath(canvasPath) {
257
- return canvasPath.trim().replace(/\\/g, "/").replace(/^\.\/+/, "").replace(/^\/+/, "");
258
- }
259
-
260
- // default-export-identity.ts
261
- var FUNCTION_DEFAULT_RE = /^(?:async\s+)?function(?:\s*\*)?(?:\s+([A-Za-z_$][\w$]*))?\s*\(/;
262
- var CLASS_DEFAULT_RE = /^(?:abstract\s+)?class(?:\s+([A-Za-z_$][\w$]*))?(?=[\s{])/;
263
- var ARROW_DEFAULT_RE = /^(?:async\s+)?(?:\([^()]*\)|[A-Za-z_$][\w$]*)\s*=>/;
264
- var IDENTIFIER_DEFAULT_RE = /^([A-Za-z_$][\w$]*)[ \t]*(?:;|\r?\n|$)/;
265
- function readDefaultExportIdentity(source) {
266
- const start = /\bexport\s+default\s+/.exec(source);
267
- if (!start) return null;
268
- const tail = source.slice(start.index + start[0].length);
269
- const fn = FUNCTION_DEFAULT_RE.exec(tail);
270
- if (fn) return { kind: "function", name: fn[1] ?? null };
271
- const cls = CLASS_DEFAULT_RE.exec(tail);
272
- if (cls) return { kind: "class", name: cls[1] ?? null };
273
- if (ARROW_DEFAULT_RE.test(tail)) return { kind: "function", name: null };
274
- const identifier = IDENTIFIER_DEFAULT_RE.exec(tail);
275
- if (identifier) return { kind: "identifier", name: identifier[1] };
276
- return null;
277
- }
278
- function isDefaultExportIdentityRewrite(before, after) {
279
- if (!before) return false;
280
- if (before.name === null) return true;
281
- if (!after) return false;
282
- if (before.name === after.name) return false;
283
- return isComponentShaped(before) && isComponentShaped(after);
284
- }
285
- function isComponentShaped(identity) {
286
- return identity.name === null || /^[A-Z]/.test(identity.name);
287
- }
288
-
289
- // pruned-module-deletion.ts
290
- function createPrunedModuleDeletionGuard() {
291
- let sequence = 0;
292
- let activeReceipts = 0;
293
- let receipts = /* @__PURE__ */ new WeakMap();
294
- return {
295
- observePrune(graph, paths) {
296
- const receipt = ++sequence;
297
- for (const path of paths) {
298
- const module = graph.urlToModuleMap.get(path);
299
- if (module) {
300
- if (!receipts.has(module)) activeReceipts++;
301
- receipts.set(module, receipt);
302
- }
303
- }
304
- },
305
- observeRequest(graph, url, base, fetchDestination, ifNoneMatch) {
306
- if (!activeReceipts || ["document", "iframe", "frame"].includes(String(fetchDestination)))
307
- return;
308
- const requestSequence = sequence;
309
- return async (status, contentType, responseEtag) => {
310
- if (!activeReceipts || status < 200 || status >= 400) return;
311
- if (status !== 304 && !/^text\/(?:javascript|css)(?:;|$)/i.test(String(contentType)))
312
- return;
313
- const etag = status === 304 ? ifNoneMatch : responseEtag;
314
- if (typeof etag !== "string" || !graph.getModuleByEtag(etag)) return;
315
- let moduleUrl = url;
316
- if (base !== "/" && moduleUrl.startsWith(base))
317
- moduleUrl = `/${moduleUrl.slice(base.length)}`;
318
- try {
319
- moduleUrl = decodeURI(moduleUrl).replace(/__x00__/g, "\0");
320
- if (moduleUrl.startsWith("/@id/")) moduleUrl = moduleUrl.slice(5);
321
- const [, id] = await graph.resolveUrl(moduleUrl);
322
- const module = graph.getModuleById(id);
323
- if (module && module.transformResult?.etag === etag && (receipts.get(module) ?? Infinity) <= requestSequence) {
324
- receipts.delete(module);
325
- activeReceipts--;
326
- }
327
- } catch {
328
- }
329
- };
330
- },
331
- suppressDeletion(graph, modules) {
332
- if (!modules.length || !modules.every(
333
- (module) => receipts.has(module) && module.importers.size === 0
334
- ))
335
- return false;
336
- const invalidated = /* @__PURE__ */ new Set();
337
- for (const module of modules) graph.invalidateModule(module, invalidated);
338
- return true;
339
- },
340
- clear() {
341
- receipts = /* @__PURE__ */ new WeakMap();
342
- activeReceipts = 0;
343
- }
344
- };
345
- }
346
-
347
- // hmr-generation-fence.ts
348
- function generationIdentity(update) {
349
- const type = typeof update.type === "string" ? update.type : null;
350
- const acceptedPath = typeof update.acceptedPath === "string" ? update.acceptedPath : typeof update.path === "string" ? update.path : null;
351
- if (!type || !acceptedPath) return null;
352
- return `${type}\0${acceptedPath}`;
353
- }
354
- function createHmrGenerationFence() {
355
- const newestTimestampByIdentity = /* @__PURE__ */ new Map();
356
- return {
357
- filter(updates) {
358
- const accepted = [];
359
- for (const update of updates) {
360
- const identity = generationIdentity(update);
361
- const timestamp = update.timestamp;
362
- if (identity === null || typeof timestamp !== "number" || !Number.isFinite(timestamp)) {
363
- accepted.push(update);
364
- continue;
365
- }
366
- const newestTimestamp = newestTimestampByIdentity.get(identity);
367
- if (newestTimestamp !== void 0 && timestamp < newestTimestamp) {
368
- continue;
369
- }
370
- if (newestTimestamp === void 0 || timestamp > newestTimestamp) {
371
- newestTimestampByIdentity.set(identity, timestamp);
372
- }
373
- accepted.push(update);
374
- }
375
- return accepted;
376
- },
377
- clear() {
378
- newestTimestampByIdentity.clear();
379
- }
380
- };
381
- }
382
-
383
- // host-identity.ts
384
- import { readFileSync } from "fs";
385
- import { resolve as resolve2 } from "path";
386
-
387
- // package.json
388
- var package_default = {
389
- name: "tempo-sdk",
390
- version: "0.0.57",
391
- publishConfig: {
392
- tag: "sdk-v2-latest"
393
- },
394
- type: "module",
395
- description: "Tempo SDK \u2014 Vite, Next.js, and Expo plugins for JSX annotation and shared page/storyboard types",
396
- repository: {
397
- type: "git",
398
- url: "git+https://github.com/TempoLabsAI/tempo-monorepo.git",
399
- directory: "tempo-modules/tempo-sdk"
400
- },
401
- exports: {
402
- ".": {
403
- types: "./dist/index.d.ts",
404
- import: "./dist/index.js"
405
- },
406
- "./canvas": {
407
- types: "./dist/canvas/index.d.ts",
408
- import: "./dist/canvas/index.js"
409
- },
410
- "./canvas/svelte": {
411
- types: "./dist/canvas/svelte.d.ts",
412
- import: "./dist/canvas/svelte.js"
413
- },
414
- "./canvas/interact-projection": {
415
- types: "./dist/canvas/interact-projection.d.ts",
416
- import: "./dist/canvas/interact-projection.js"
417
- },
418
- "./canvas/parser": {
419
- types: "./dist/canvas/parser.d.ts",
420
- import: "./dist/canvas/parser.js"
421
- },
422
- "./canvas/editor": {
423
- types: "./dist/canvas/editor.d.ts",
424
- import: "./dist/canvas/editor.js"
425
- },
426
- "./assets": {
427
- types: "./dist/assets/index.d.ts",
428
- import: "./dist/assets/index.js"
429
- },
430
- "./assets/parser": {
431
- types: "./dist/assets/parser.d.ts",
432
- import: "./dist/assets/parser.js"
433
- },
434
- "./assets/editor": {
435
- types: "./dist/assets/editor.d.ts",
436
- import: "./dist/assets/editor.js"
437
- },
438
- "./nextjs": {
439
- types: "./dist/nextjs.d.ts",
440
- import: "./dist/nextjs.js",
441
- require: "./dist/nextjs.cjs"
442
- },
443
- "./nextjs/plugin": {
444
- types: "./dist/nextjs/plugin.d.ts",
445
- import: "./dist/nextjs/plugin.js"
446
- },
447
- "./expo": {
448
- types: "./dist/expo-babel-plugin.d.ts",
449
- import: "./dist/expo-babel-plugin.js",
450
- require: "./dist/expo-babel-plugin.cjs"
451
- },
452
- "./expo/plugin": {
453
- types: "./dist/expo/plugin.d.ts",
454
- import: "./dist/expo/plugin.js",
455
- require: "./dist/expo/plugin.cjs"
456
- },
457
- "./svelte": {
458
- types: "./dist/svelte.d.ts",
459
- import: "./dist/svelte.js"
460
- }
461
- },
462
- files: [
463
- "dist"
464
- ],
465
- scripts: {
466
- clean: "rm -rf dist",
467
- build: "pnpm run clean && tsup",
468
- "build:if-missing": "test -f dist/index.js || pnpm run build",
469
- prepare: "pnpm run build",
470
- prepublishOnly: "pnpm build",
471
- demo: "TEMPO=true pnpm --filter @tempo-modules/vite-annotate-plugin-demo dev",
472
- "demo:nextjs": "TEMPO=true pnpm --filter @tempo-modules/tempo-sdk-nextjs-demo dev",
473
- test: "vitest run",
474
- "test:browser": "vitest run 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",
475
- "test:watch": "vitest",
476
- "test:nextjs:unit": "vitest run nextjs-loader.test.ts nextjs-wrapper.test.ts nextjs-fixtures.test.ts nextjs-published.test.ts",
477
- "test:nextjs:integration": "vitest run nextjs-e2e-correctness.test.ts",
478
- "test:nextjs:production": "vitest run nextjs-production.test.ts",
479
- "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"
480
- },
481
- dependencies: {
482
- "@rollup/pluginutils": "^5.1.0",
483
- "oxc-parser": "^0.110.0"
484
- },
485
- peerDependencies: {
486
- "@babel/core": "^7.0.0",
487
- next: "^13 || ^14 || ^15 || ^16",
488
- react: "^18 || ^19",
489
- svelte: "^5.0.0",
490
- vite: "^5 || ^6 || ^7 || ^8"
491
- },
492
- peerDependenciesMeta: {
493
- "@babel/core": {
494
- optional: true
495
- },
496
- next: {
497
- optional: true
498
- },
499
- svelte: {
500
- optional: true
501
- },
502
- vite: {
503
- optional: true
504
- }
505
- },
506
- devDependencies: {
507
- "@babel/core": "^7.29.0",
508
- "@babel/types": "^7.29.0",
509
- "@modules/annotation": "workspace:*",
510
- "@modules/file-parser": "workspace:*",
511
- "@modules/svelte-editor": "workspace:*",
512
- "@types/babel__core": "^7.20.5",
513
- "@types/node": "^25.0.8",
514
- "@types/react": "catalog:",
515
- "@types/react-dom": "catalog:",
516
- "@vitejs/plugin-react": "catalog:",
517
- playwright: "^1.58.2",
518
- "react-dom": "catalog:",
519
- svelte: "5.56.9",
520
- tsup: "^8.5.1",
521
- typescript: "catalog:",
522
- vite: "catalog:",
523
- vitest: "catalog:"
524
- }
525
- };
526
-
527
- // release-channel.ts
528
- var TEMPO_SDK_CHANNEL = package_default.publishConfig.tag;
529
- function sdkChannelGeneration(channel) {
530
- if (typeof channel !== "string") return null;
531
- const match = /^sdk-v([1-9]\d*)-latest$/.exec(channel);
532
- return match ? Number(match[1]) : null;
533
- }
534
- if (sdkChannelGeneration(TEMPO_SDK_CHANNEL) === null) {
535
- throw new Error("tempo-sdk publishConfig.tag must be sdk-v<N>-latest");
536
- }
537
-
538
- // host-identity.ts
539
- var TEMPO_HOST_IDENTITY_ENDPOINT = "/__tempo/identity";
540
- var TEMPO_HOST_IDENTITY_CAPABILITY_HEADER = "x-tempo-host-identity";
541
- var TEMPO_HOST_IDENTITY_CONTRACT_VERSION = 1;
542
- var TEMPO_WORKSPACE_NONCE_ENV = "TEMPO_WORKSPACE_NONCE";
543
- var TEMPO_WORKSPACE_NONCE_META_NAME = "tempo-workspace-nonce";
544
- var WORKSPACE_NONCE_RELATIVE_PATH = ".tempo/workspace-nonce";
545
- var MAX_WORKSPACE_NONCE_LENGTH = 128;
546
- function normalizeWorkspaceNonce(value) {
547
- const nonce = value?.trim() ?? "";
548
- return nonce.length > 0 && nonce.length <= MAX_WORKSPACE_NONCE_LENGTH ? nonce : "";
549
- }
550
- function readTempoWorkspaceNonce(root = process.cwd()) {
551
- const fromEnvironment = normalizeWorkspaceNonce(
552
- process.env[TEMPO_WORKSPACE_NONCE_ENV]
553
- );
554
- if (fromEnvironment) return fromEnvironment;
555
- try {
556
- return normalizeWorkspaceNonce(
557
- readFileSync(resolve2(root, WORKSPACE_NONCE_RELATIVE_PATH), "utf-8")
558
- );
559
- } catch {
560
- return "";
561
- }
562
- }
563
- function createTempoHostIdentity(framework, options = {}) {
564
- return {
565
- tempoHost: true,
566
- contractVersion: TEMPO_HOST_IDENTITY_CONTRACT_VERSION,
567
- workspaceNonce: readTempoWorkspaceNonce(options.root),
568
- sdkVersion: package_default.version,
569
- sdkChannel: TEMPO_SDK_CHANNEL,
570
- pluginActive: options.pluginActive ?? Boolean(process.env.TEMPO),
571
- framework
572
- };
573
- }
574
-
575
- // missed-change-sweep.ts
576
- var MISSED_CHANGE_WATCHER_GRACE_MS = 1e3;
577
- var MISSED_CHANGE_MAX_EMITS_PER_REVISION = 3;
578
- function createMissedChangeSweep(args) {
579
- const now = args.now ?? Date.now;
580
- const graceMs = args.watcherGraceMs ?? MISSED_CHANGE_WATCHER_GRACE_MS;
581
- const maxEmits = args.maxEmitsPerRevision ?? MISSED_CHANGE_MAX_EMITS_PER_REVISION;
582
- const lastSeenMtimeMs = /* @__PURE__ */ new Map();
583
- const pending = /* @__PURE__ */ new Map();
584
- return {
585
- async sweep() {
586
- const emitted = [];
587
- for (const [file, modules] of args.listServedFiles()) {
588
- const mtimeMs = await args.statMtimeMs(file);
589
- if (mtimeMs === null) {
590
- pending.delete(file);
591
- continue;
592
- }
593
- let previous = lastSeenMtimeMs.get(file);
594
- if (previous === void 0) {
595
- const coveredMtimeMs = args.lastHotUpdateMtimeMs?.(file);
596
- if (coveredMtimeMs === void 0 || coveredMtimeMs >= mtimeMs) {
597
- lastSeenMtimeMs.set(file, mtimeMs);
598
- continue;
599
- }
600
- previous = coveredMtimeMs;
601
- lastSeenMtimeMs.set(file, coveredMtimeMs);
602
- }
603
- if (mtimeMs > previous) {
604
- if (now() - mtimeMs < graceMs) continue;
605
- lastSeenMtimeMs.set(file, mtimeMs);
606
- } else if (mtimeMs < previous) {
607
- lastSeenMtimeMs.set(file, mtimeMs);
608
- }
609
- const entry = pending.get(file);
610
- if (mtimeMs <= previous && entry === void 0) continue;
611
- const hotUpdateMtimeMs = args.lastHotUpdateMtimeMs?.(file);
612
- let delivered;
613
- if (hotUpdateMtimeMs !== void 0) {
614
- delivered = hotUpdateMtimeMs >= mtimeMs;
615
- } else {
616
- delivered = false;
617
- for (const module of modules) {
618
- if ((module.lastInvalidationTimestamp ?? 0) >= mtimeMs) {
619
- delivered = true;
620
- break;
621
- }
622
- }
623
- }
624
- if (delivered) {
625
- pending.delete(file);
626
- continue;
627
- }
628
- const revision = entry !== void 0 && entry.mtimeMs === mtimeMs ? entry : { mtimeMs, emits: 0 };
629
- pending.set(file, revision);
630
- if (revision.emits >= maxEmits) continue;
631
- revision.emits += 1;
632
- args.emitChange(file);
633
- emitted.push(file);
634
- }
635
- return emitted;
636
- }
637
- };
638
- }
639
-
640
- // rapid-hot-update-replay.ts
641
- var RAPID_HOT_UPDATE_QUIET_MS = 100;
642
- function createRapidHotUpdateReplay(options) {
643
- const quietMs = options?.quietMs ?? RAPID_HOT_UPDATE_QUIET_MS;
644
- const schedule = options?.schedule ?? setTimeout;
645
- const cancel = options?.cancel ?? clearTimeout;
646
- const bursts = /* @__PURE__ */ new Map();
647
- const armGate = (burst, previous) => {
648
- if (burst.eventCount < 2) return;
649
- if (previous?.gate && previous.release) {
650
- burst.gate = previous.gate;
651
- burst.release = previous.release;
652
- previous.release = void 0;
653
- if (previous.expiry) cancel(previous.expiry);
654
- } else {
655
- burst.gate = new Promise((resolve4) => {
656
- burst.release = resolve4;
657
- });
658
- }
659
- burst.expiry = schedule(() => burst.release?.(), quietMs * 2);
660
- };
661
- return {
662
- observe(file, replay) {
663
- const previous = bursts.get(file);
664
- if (previous?.timer) cancel(previous.timer);
665
- const burst = {
666
- eventCount: (previous?.eventCount ?? 0) + 1,
667
- replay
668
- };
669
- armGate(burst, previous);
670
- burst.timer = schedule(() => {
671
- if (bursts.get(file) !== burst) return;
672
- bursts.delete(file);
673
- if (burst.expiry) cancel(burst.expiry);
674
- burst.release?.();
675
- if (burst.eventCount < 2) return;
676
- const replayAllowance = {
677
- eventCount: -1,
678
- replay: burst.replay
679
- };
680
- replayAllowance.timer = schedule(() => {
681
- if (bursts.get(file) === replayAllowance) bursts.delete(file);
682
- }, quietMs);
683
- bursts.set(file, replayAllowance);
684
- burst.replay();
685
- }, quietMs);
686
- bursts.set(file, burst);
687
- },
688
- settled(file) {
689
- return bursts.get(file)?.gate ?? Promise.resolve();
690
- },
691
- clear() {
692
- for (const burst of bursts.values()) {
693
- if (burst.timer) cancel(burst.timer);
694
- if (burst.expiry) cancel(burst.expiry);
695
- burst.release?.();
696
- }
697
- bursts.clear();
698
- }
699
- };
700
- }
701
-
702
- // react-refresh-boundary.ts
703
- var installed = /* @__PURE__ */ new WeakSet();
704
- function installSynchronousReactRefreshBoundary(plugins) {
705
- for (const plugin of plugins) {
706
- if (plugin.name === "vite:react-refresh" && plugin.load && !installed.has(plugin)) {
707
- installed.add(plugin);
708
- const hook2 = plugin.load;
709
- const load = typeof hook2 === "function" ? hook2 : hook2.handler;
710
- const wrapped2 = async function(...args) {
711
- const result = await load.apply(this, args);
712
- if (!result || args[0] !== "/@react-refresh") return result;
713
- const source = typeof result === "string" ? result : result.code;
714
- if (!source || !/\b(?:let|const) allFamiliesByType = new WeakMap\(\)/.test(source) || !source.includes("function performReactRefresh()"))
715
- return result;
716
- const code = `${source}
717
- globalThis[Symbol.for("tempo.react-refresh.family")] = (type) => allFamiliesByType.get(type);
718
- `;
719
- return typeof result === "string" ? code : { ...result, code };
720
- };
721
- plugin.load = typeof hook2 === "function" ? wrapped2 : { ...hook2, handler: wrapped2 };
722
- }
723
- if (plugin.name !== "vite:react-babel" || !plugin.transform || installed.has(plugin))
724
- continue;
725
- installed.add(plugin);
726
- const hook = plugin.transform;
727
- const transform = typeof hook === "function" ? hook : hook.handler;
728
- const wrapped = async function(...args) {
729
- const result = await transform.apply(this, args);
730
- if (!result) return result;
731
- const source = typeof result === "string" ? result : result.code;
732
- if (!source) return result;
733
- const code = source.replace(
734
- /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*\}\);/,
735
- (_match, register, accept) => `const __tempoReactRefreshExports = RefreshRuntime.__hmr_import(import.meta.url).then((currentExports) => {
736
- ${register}
737
- return currentExports;
738
- });
739
- import.meta.hot.accept(async (nextExports) => {
740
- const currentExports = await __tempoReactRefreshExports;${accept}
741
- });`
742
- );
743
- return code === source ? result : typeof result === "string" ? code : { ...result, code };
744
- };
745
- plugin.transform = typeof hook === "function" ? wrapped : { ...hook, handler: wrapped };
746
- }
747
- }
748
-
749
- // sdk-package-files.ts
750
- import { readFileSync as readFileSync2, realpathSync as realpathSync2 } from "fs";
751
- import { dirname as dirname2, join } from "path";
752
- var SDK_PACKAGE_NAME = "tempo-sdk";
753
- var SDK_NODE_MODULES_SEGMENT = `/node_modules/${SDK_PACKAGE_NAME}/`;
754
- function createSdkFileMatcher() {
755
- const ownerIsSdkByDirectory = /* @__PURE__ */ new Map();
756
- const nearestPackageIsSdk = (startDirectory) => {
757
- const visited = [];
758
- let directory = startDirectory;
759
- let isSdk = false;
760
- while (true) {
761
- const cached = ownerIsSdkByDirectory.get(directory);
762
- if (cached !== void 0) {
763
- isSdk = cached;
764
- break;
765
- }
766
- visited.push(directory);
767
- const manifest = readPackageManifest(directory);
768
- if (manifest !== void 0) {
769
- isSdk = manifest?.name === SDK_PACKAGE_NAME;
770
- break;
771
- }
772
- const parent = dirname2(directory);
773
- if (parent === directory) break;
774
- directory = parent;
775
- }
776
- for (const entry of visited) ownerIsSdkByDirectory.set(entry, isSdk);
777
- return isSdk;
778
- };
779
- return (file) => {
780
- if (file.replace(/\\/g, "/").includes(SDK_NODE_MODULES_SEGMENT)) {
781
- return true;
782
- }
783
- let realFile = file;
784
- try {
785
- realFile = realpathSync2.native(file);
786
- } catch {
787
- }
788
- return nearestPackageIsSdk(dirname2(realFile));
789
- };
790
- }
791
- function readPackageManifest(directory) {
792
- let text;
793
- try {
794
- text = readFileSync2(join(directory, "package.json"), "utf8");
795
- } catch {
796
- return void 0;
797
- }
798
- try {
799
- const manifest = JSON.parse(text);
800
- return manifest && typeof manifest === "object" ? manifest : null;
801
- } catch {
802
- return null;
803
- }
804
- }
805
-
806
- // vite-client-pending-updates.ts
807
- function preservePendingViteModuleUpdates(source) {
808
- const missingBoundary = /(const mod = this\.hotModulesMap\.get\(path\);\s*)if \(!mod\)\s*(?:return;|\{\s*return;\s*\})/;
809
- const registeredBoundary = "this.hmrClient.hotModulesMap.set(this.ownerPath, mod);";
810
- if (!missingBoundary.test(source) || !source.includes(registeredBoundary)) {
811
- return source;
812
- }
813
- return source.replace(
814
- missingBoundary,
815
- `$1if (!mod || mod.pendingUpdates) {
816
- const pending = mod || {
817
- id: path,
818
- callbacks: [],
819
- pendingUpdates: new Map(),
820
- };
821
- pending.pendingUpdates.set(acceptedPath, update);
822
- this.hotModulesMap.set(path, pending);
823
- return;
824
- }`
825
- ).replace(
826
- registeredBoundary,
827
- `${registeredBoundary}
828
- if (mod.pendingUpdates) {
829
- const pendingUpdates = [...mod.pendingUpdates.values()];
830
- delete mod.pendingUpdates;
831
- queueMicrotask(() => {
832
- for (const update of pendingUpdates) {
833
- void this.hmrClient.queueUpdate(update).catch((error) => {
834
- this.hmrClient.logger.error(error);
835
- });
836
- }
837
- });
838
- }`
839
- );
840
- }
841
-
842
- // tailwind-scan-net.ts
843
- var SCANNABLE_EXTENSIONS = /* @__PURE__ */ new Set([
844
- "ts",
845
- "tsx",
846
- "js",
847
- "jsx",
848
- "mjs",
849
- "cjs",
850
- "html",
851
- "mdx",
852
- "md",
853
- "svelte",
854
- "vue",
855
- "astro"
856
- ]);
857
- var IGNORED_PATH_SEGMENTS = [
858
- "/node_modules/",
859
- "/.git/",
860
- "/.vite/",
861
- "/.tempo/"
862
- ];
863
- var TAILWIND_SCAN_NET_DEBOUNCE_MS = 100;
864
- var TAILWIND_SCAN_NET_MAX_POKES_PER_PAIR = 2;
865
- var POKE_LEDGER_MAX_ENTRIES = 2e4;
866
- function normalizeSlashes(path) {
867
- return path.replace(/\\/g, "/");
868
- }
869
- function fileExtension(path) {
870
- const base = path.slice(path.lastIndexOf("/") + 1);
871
- const dot = base.lastIndexOf(".");
872
- return dot <= 0 ? "" : base.slice(dot + 1).toLowerCase();
873
- }
874
- function isScannableSourceFile(file) {
875
- const normalized = normalizeSlashes(file);
876
- if (!SCANNABLE_EXTENSIONS.has(fileExtension(normalized))) return false;
877
- return !IGNORED_PATH_SEGMENTS.some(
878
- (segment) => normalized.includes(segment)
879
- );
880
- }
881
- function isScanDep(dep) {
882
- if (dep.includes("*")) return true;
883
- const ext = fileExtension(normalizeSlashes(dep));
884
- return ext !== "" && ext !== "css" && SCANNABLE_EXTENSIONS.has(ext);
885
- }
886
- function cssEntryNeedsRescanFor(entry, file) {
887
- if (entry.deps === null) return false;
888
- const normalizedFile = normalizeSlashes(file);
889
- let scansClasses = false;
890
- for (const dep of entry.deps) {
891
- const normalizedDep = normalizeSlashes(dep);
892
- if (normalizedDep === normalizedFile) return false;
893
- if (!scansClasses && isScanDep(normalizedDep)) scansClasses = true;
894
- }
895
- return scansClasses;
896
- }
897
- function createTailwindScanNet(args) {
898
- const debounceMs = args.debounceMs ?? TAILWIND_SCAN_NET_DEBOUNCE_MS;
899
- const maxPokesPerPair = args.maxPokesPerPair ?? TAILWIND_SCAN_NET_MAX_POKES_PER_PAIR;
900
- const pendingCssFiles = /* @__PURE__ */ new Set();
901
- const pokeLedger = /* @__PURE__ */ new Map();
902
- const countedThisWindow = /* @__PURE__ */ new Set();
903
- let flushTimer = null;
904
- let lastFlushAt = Number.NEGATIVE_INFINITY;
905
- let disposed = false;
906
- const flush = () => {
907
- flushTimer = null;
908
- lastFlushAt = Date.now();
909
- countedThisWindow.clear();
910
- const cssFiles = [...pendingCssFiles];
911
- pendingCssFiles.clear();
912
- for (const cssFile of cssFiles) {
913
- args.emitChange(cssFile);
914
- }
915
- };
916
- return {
917
- handleWatcherFile(file) {
918
- if (disposed) return false;
919
- if (!isScannableSourceFile(file)) return false;
920
- let scheduled = false;
921
- for (const entry of args.listCssEntries()) {
922
- if (!cssEntryNeedsRescanFor(entry, file)) continue;
923
- const pairKey = `${entry.cssFile}\0${normalizeSlashes(file)}`;
924
- if (!countedThisWindow.has(pairKey)) {
925
- const pokes = pokeLedger.get(pairKey) ?? 0;
926
- if (pokes >= maxPokesPerPair) continue;
927
- if (pokeLedger.size >= POKE_LEDGER_MAX_ENTRIES) pokeLedger.clear();
928
- pokeLedger.set(pairKey, pokes + 1);
929
- countedThisWindow.add(pairKey);
930
- }
931
- pendingCssFiles.add(entry.cssFile);
932
- scheduled = true;
933
- }
934
- if (scheduled && flushTimer === null) {
935
- const sinceLastFlush = Date.now() - lastFlushAt;
936
- const delay = sinceLastFlush >= debounceMs ? 0 : debounceMs;
937
- flushTimer = setTimeout(flush, delay);
938
- flushTimer.unref?.();
939
- }
940
- return scheduled;
941
- },
942
- dispose() {
943
- disposed = true;
944
- pendingCssFiles.clear();
945
- pokeLedger.clear();
946
- countedThisWindow.clear();
947
- if (flushTimer !== null) {
948
- clearTimeout(flushTimer);
949
- flushTimer = null;
950
- }
951
- }
952
- };
953
- }
954
-
955
- // index.ts
956
- var DEFAULT_INCLUDE = ["**/*.tsx", "**/*.jsx"];
957
- var DEFAULT_EXCLUDE = ["**/node_modules/**"];
958
- var ROOT_META_NAME = "tempo-project-root";
959
- var SOURCE_IDENTITY_ROOT_META_NAME = "tempo-source-identity-root";
960
- var INTERACT_PROJECTION_CLIENT_PATH = "/@tempo/interact-projection";
961
- var INTERACT_PROJECTION_CLIENT_ID = "\0tempo:interact-projection";
962
- var VITE_ERROR_CLIENT_ID = "\0tempo:server-errors";
963
- var INTERACT_PROJECTION_SDK_SPECIFIER = "tempo-sdk/canvas/interact-projection";
964
- function resolveOwnInteractProjectionModule() {
965
- const selfDir = dirname3(fileURLToPath(import.meta.url));
966
- for (const candidate of [
967
- join2(selfDir, "canvas", "interact-projection.ts"),
968
- join2(selfDir, "canvas", "interact-projection.js")
969
- ]) {
970
- if (existsSync(candidate)) return candidate.replace(/\\/g, "/");
971
- }
972
- return null;
973
- }
974
- var INTERACT_PROJECTION_BOOTSTRAP = `
975
- (function() {
976
- if (window.parent === window || (window.name !== ${JSON.stringify(TEMPO_INTERACT_FRAME_NAME)} && !window.name.startsWith(${JSON.stringify(`${TEMPO_INTERACT_FRAME_NAME}:`)}))) return;
977
- var roots = new Map();
978
- var existing = window.__REACT_DEVTOOLS_GLOBAL_HOOK__;
979
- if (existing) {
980
- if (existing.__tempoPendingFiberRoots) return;
981
- existing.__tempoPendingFiberRoots = roots;
982
- var originalCommit = existing.onCommitFiberRoot && existing.onCommitFiberRoot.bind(existing);
983
- existing.onCommitFiberRoot = function(rendererId, root) {
984
- if (existing.__tempoPendingFiberRoots === roots) roots.set(rendererId, root);
985
- if (originalCommit) originalCommit.apply(null, arguments);
986
- };
987
- return;
988
- }
989
- window.__REACT_DEVTOOLS_GLOBAL_HOOK__ = {
990
- supportsFiber: true,
991
- renderers: new Map(),
992
- __tempoPendingFiberRoots: roots,
993
- inject: function(renderer) {
994
- var id = this.renderers.size + 1;
995
- this.renderers.set(id, renderer);
996
- return id;
997
- },
998
- onCommitFiberRoot: function(rendererId, root) {
999
- if (this.__tempoPendingFiberRoots === roots) roots.set(rendererId, root);
1000
- },
1001
- onCommitFiberUnmount: function() {},
1002
- checkDCE: function() {},
1003
- onScheduleFiberRoot: function() {}
1004
- };
1005
- })();`;
1006
- function cleanModuleId(id) {
1007
- return id.replace(/[?#].*$/, "");
1008
- }
1009
- function fsPathFromModuleId(id) {
1010
- return cleanModuleId(id).replace(/^\/@fs\//, "/");
1011
- }
1012
- function isCanvasHostRequest(requestPath) {
1013
- const url = new URL(requestPath, "http://tempo.local");
1014
- return url.pathname.replace(/\/+$/, "") === "/tempo-host";
1015
- }
1016
- function isDeclarativeCanvasHostRequest(requestPath) {
1017
- if (!isCanvasHostRequest(requestPath)) return false;
1018
- const params = new URL(requestPath, "http://tempo.local").searchParams;
1019
- const canvasPath = params.get("canvasPath")?.trim() ?? params.get("pageFile")?.trim() ?? params.get("importPath")?.trim();
1020
- const storyboardId = params.get("storyboardId")?.trim() ?? params.get("exportName")?.trim() ?? params.get("importName")?.trim();
1021
- return !canvasPath || !storyboardId;
1022
- }
1023
- var MAX_UNRESOLVED_IMPORTS = 256;
1024
- var RELATIVE_IMPORT_RESOLVE_EXTENSIONS = [
1025
- ".mjs",
1026
- ".js",
1027
- ".mts",
1028
- ".ts",
1029
- ".jsx",
1030
- ".tsx",
1031
- ".json"
1032
- ];
1033
- var UNRESOLVED_IMPORT_WATCH_REARM_MS = 1e3;
1034
- function isRelativeImportSpecifier(specifier) {
1035
- return specifier.startsWith("./") || specifier.startsWith("../");
1036
- }
1037
- function barePackageName(specifier) {
1038
- if (!specifier || specifier.startsWith(".") || specifier.startsWith("/") || specifier.startsWith("\0") || specifier.startsWith("#") || specifier.includes(":")) {
1039
- return void 0;
1040
- }
1041
- const segments = specifier.split("/");
1042
- const packageName = specifier.startsWith("@") ? segments.length >= 2 && segments[0] !== "@" && segments[1] ? `${segments[0]}/${segments[1]}` : void 0 : segments[0];
1043
- return packageName && /^@?[A-Za-z0-9_][A-Za-z0-9._/-]*$/.test(packageName) ? packageName : void 0;
1044
- }
1045
- function resolvedIdMatchesFile(id, file) {
1046
- const resolvedFile = fsPathFromModuleId(id);
1047
- try {
1048
- return realpathSync3.native(resolvedFile) === realpathSync3.native(file);
1049
- } catch {
1050
- return resolvedFile.replace(/\\/g, "/") === file.replace(/\\/g, "/");
1051
- }
1052
- }
1053
- function moduleIdsMatch(left, right) {
1054
- const normalize2 = (value) => cleanModuleId(value).replace(/^file:\/\//, "").replace(/^\/@fs\//, "/").replace(/\\/g, "/").replace(/^\/+/, "");
1055
- return normalize2(left) === normalize2(right);
1056
- }
1057
- function resolveCanonicalRoot(root) {
1058
- try {
1059
- return realpathSync3.native(root);
1060
- } catch {
1061
- return root;
1062
- }
1063
- }
1064
- function hasRootMetaTag(html) {
1065
- return /<meta[^>]+name=["']tempo-project-root["'][^>]*>/i.test(html);
1066
- }
1067
- function hasSourceIdentityRootMetaTag(html) {
1068
- return /<meta[^>]+name=["']tempo-source-identity-root["'][^>]*>/i.test(html);
1069
- }
1070
- function hasWorkspaceNonceMetaTag(html) {
1071
- return new RegExp(
1072
- `<meta[^>]+name=["']${TEMPO_WORKSPACE_NONCE_META_NAME}["'][^>]*>`,
1073
- "i"
1074
- ).test(html);
1075
- }
1076
- function isSameError(left, right) {
1077
- return left.type === right.type && left.message === right.message && left.loc?.line === right.loc?.line && left.loc?.column === right.loc?.column;
1078
- }
1079
- function createErrorServer(onErrorFile, onState) {
1080
- const errorsByFile = /* @__PURE__ */ new Map();
1081
- function getMostRecentError() {
1082
- if (errorsByFile.size === 0) return null;
1083
- let latest = null;
1084
- for (const err of errorsByFile.values()) latest = err;
1085
- return latest;
1086
- }
1087
- function broadcastCurrentState() {
1088
- onState?.(server.currentError);
1089
- const data = JSON.stringify(server.currentError);
1090
- for (const client of server.clients) {
1091
- client.write(`data: ${data}
1092
-
1093
- `);
1094
- }
1095
- }
1096
- const server = {
1097
- get currentError() {
1098
- return getMostRecentError();
1099
- },
1100
- get errorFiles() {
1101
- return [...errorsByFile.keys()].filter((file) => file !== "unknown");
1102
- },
1103
- clients: /* @__PURE__ */ new Set(),
1104
- setError(error) {
1105
- const key = error.file ?? error.loc?.file ?? "unknown";
1106
- const recorded = errorsByFile.get(key);
1107
- if (recorded && isSameError(recorded, error)) return;
1108
- if (key !== "unknown" && !recorded) onErrorFile?.(key);
1109
- errorsByFile.delete(key);
1110
- errorsByFile.set(key, error);
1111
- broadcastCurrentState();
1112
- },
1113
- clearErrorForModules(updatedPaths) {
1114
- if (errorsByFile.size === 0) return;
1115
- let changed = false;
1116
- for (const errorKey of [...errorsByFile.keys()]) {
1117
- if (errorKey !== "unknown" && updatedPaths.some((path) => moduleIdsMatch(errorKey, path))) {
1118
- errorsByFile.delete(errorKey);
1119
- changed = true;
1120
- }
1121
- }
1122
- if (changed) broadcastCurrentState();
1123
- },
1124
- clearAll() {
1125
- errorsByFile.clear();
1126
- broadcastCurrentState();
1127
- }
1128
- };
1129
- return server;
1130
- }
1131
- function readBody(req) {
1132
- return new Promise((resolve4, reject) => {
1133
- const chunks = [];
1134
- req.on("data", (chunk) => chunks.push(chunk));
1135
- req.on("end", () => resolve4(Buffer.concat(chunks).toString()));
1136
- req.on("error", reject);
1137
- });
1138
- }
1139
- var CANVAS_HOST_WRAPPER_URL = "/.tempo/tempo-host";
1140
- function readGeneratedCanvasPaths(source) {
1141
- const paths = /* @__PURE__ */ new Set();
1142
- const canvasPathPattern = /\bcanvasPath:\s*("(?:\\.|[^"\\])*")/g;
1143
- for (const match of source.matchAll(canvasPathPattern)) {
1144
- try {
1145
- const parsed = JSON.parse(match[1] ?? "");
1146
- if (typeof parsed !== "string") continue;
1147
- const normalized = normalizeCanvasRegistrationPath(parsed);
1148
- if (normalized) paths.add(normalized);
1149
- } catch {
1150
- }
1151
- }
1152
- return [...paths];
1153
- }
1154
- async function synchronizeCanvasHostRegistrationTransform(server, canvasPath) {
1155
- const wrapperPath = resolve3(server.config.root, ".tempo", "tempo-host.tsx");
1156
- let wrapperSource;
1157
- try {
1158
- wrapperSource = readFileSync3(wrapperPath, "utf8");
1159
- } catch (error) {
1160
- throw new Error(
1161
- `Canvas host wrapper is unavailable at ${wrapperPath}: ${error instanceof Error ? error.message : String(error)}`
1162
- );
1163
- }
1164
- const registeredCanvasPaths = readGeneratedCanvasPaths(wrapperSource);
1165
- if (!registeredCanvasPaths.includes(canvasPath)) {
1166
- throw Object.assign(
1167
- new Error(
1168
- `Generated canvas host wrapper does not contain ${JSON.stringify(
1169
- canvasPath
1170
- )}`
1171
- ),
1172
- { statusCode: 409 }
1173
- );
1174
- }
1175
- const canonicalWrapperPath = realpathSync3(wrapperPath);
1176
- const modulePattern = /\bcanvasPath:\s*("(?:\\.|[^"\\])*")\s*,\s*load:\s*\(\)\s*=>\s*import\(\s*("(?:\\.|[^"\\])*")\s*\)/g;
1177
- const transformer = server.environments?.client ?? server;
1178
- for (const match of wrapperSource.matchAll(modulePattern)) {
1179
- if (normalizeCanvasRegistrationPath(JSON.parse(match[1])) !== canvasPath)
1180
- continue;
1181
- const resolvedModule = await transformer.pluginContainer.resolveId(
1182
- JSON.parse(match[2]),
1183
- wrapperPath
1184
- );
1185
- if (!resolvedModule) throw new Error(`Cannot resolve canvas ${canvasPath}`);
1186
- const modulePath = fsPathFromModuleId(resolvedModule.id);
1187
- await retransformCanvasHostWrapper(
1188
- transformer,
1189
- realpathSync3(modulePath),
1190
- modulePath,
1191
- `/@fs/${modulePath.replace(/^\/+/, "")}`
1192
- );
1193
- break;
1194
- }
1195
- await retransformCanvasHostWrapper(
1196
- transformer,
1197
- canonicalWrapperPath,
1198
- wrapperPath
1199
- );
1200
- }
1201
- async function retransformCanvasHostWrapper(transformer, canonicalWrapperPath, wrapperPath, requestUrl = CANVAS_HOST_WRAPPER_URL) {
1202
- const modules = transformer.moduleGraph.getModulesByFile(canonicalWrapperPath) ?? transformer.moduleGraph.getModulesByFile(wrapperPath);
1203
- for (const module of modules ?? []) {
1204
- transformer.moduleGraph.invalidateModule(module);
1205
- }
1206
- const result = await transformer.transformRequest(requestUrl);
1207
- if (!result) {
1208
- throw new Error(`Vite did not transform ${requestUrl} after registration`);
1209
- }
1210
- }
1211
- function writeCanvasRegistrationResponseHeaders(res) {
1212
- res.setHeader("Access-Control-Allow-Origin", "*");
1213
- res.setHeader(
1214
- "Access-Control-Expose-Headers",
1215
- CANVAS_HOST_REGISTRATION_CAPABILITY_HEADER
1216
- );
1217
- res.setHeader(CANVAS_HOST_REGISTRATION_CAPABILITY_HEADER, "1");
1218
- }
1219
- function handleTempoMiddleware(errorServer, viteServer, req, res, next) {
1220
- const url = req.url;
1221
- if (!url?.startsWith("/__tempo/")) return next();
1222
- if (url === TEMPO_HOST_IDENTITY_ENDPOINT && req.method === "GET") {
1223
- const identity = createTempoHostIdentity("vite", {
1224
- root: viteServer.config?.root,
1225
- pluginActive: true
1226
- });
1227
- res.statusCode = 200;
1228
- res.setHeader("Cache-Control", "no-store");
1229
- res.setHeader("Content-Type", "application/json; charset=utf-8");
1230
- res.setHeader(TEMPO_HOST_IDENTITY_CAPABILITY_HEADER, "1");
1231
- res.end(JSON.stringify(identity));
1232
- return;
1233
- }
1234
- if (url === CANVAS_HOST_REGISTRATION_ENDPOINT && req.method === "OPTIONS") {
1235
- writeCanvasRegistrationResponseHeaders(res);
1236
- res.writeHead(204, {
1237
- "Access-Control-Allow-Methods": "POST, OPTIONS",
1238
- "Access-Control-Allow-Headers": "content-type"
1239
- });
1240
- res.end();
1241
- return;
1242
- }
1243
- if (url === CANVAS_HOST_REGISTRATION_ENDPOINT && req.method === "POST") {
1244
- writeCanvasRegistrationResponseHeaders(res);
1245
- void readBody(req).then(async (body) => {
1246
- const parsed = JSON.parse(body);
1247
- const canvasPath = typeof parsed.canvasPath === "string" ? normalizeCanvasRegistrationPath(parsed.canvasPath) : "";
1248
- if (!canvasPath) {
1249
- throw Object.assign(
1250
- new Error("canvasPath must be a non-empty string"),
1251
- { statusCode: 400 }
1252
- );
1253
- }
1254
- await synchronizeCanvasHostRegistrationTransform(
1255
- viteServer,
1256
- canvasPath
1257
- );
1258
- res.statusCode = 200;
1259
- res.setHeader("Content-Type", "application/json");
1260
- res.end(JSON.stringify({ canvasPath }));
1261
- }).catch((error) => {
1262
- res.statusCode = typeof error === "object" && error !== null && "statusCode" in error && typeof error.statusCode === "number" ? error.statusCode : 500;
1263
- res.setHeader("Content-Type", "text/plain; charset=utf-8");
1264
- res.end(error instanceof Error ? error.message : String(error));
1265
- });
1266
- return;
1267
- }
1268
- if (url === "/__tempo/report-error" && req.method === "POST") {
1269
- readBody(req).then((body) => {
1270
- try {
1271
- errorServer.setError(JSON.parse(body));
1272
- } catch {
1273
- }
1274
- res.statusCode = 200;
1275
- res.end("ok");
1276
- });
1277
- return;
1278
- }
1279
- if (url === "/__tempo/report-clear" && req.method === "POST") {
1280
- errorServer.clearAll();
1281
- res.statusCode = 200;
1282
- res.end("ok");
1283
- return;
1284
- }
1285
- if (url === "/__tempo/errors" && req.method === "OPTIONS") {
1286
- res.writeHead(204, {
1287
- "Access-Control-Allow-Origin": "*",
1288
- "Access-Control-Allow-Methods": "GET, OPTIONS",
1289
- "Access-Control-Allow-Headers": "*"
1290
- });
1291
- res.end();
1292
- return;
1293
- }
1294
- if (url === "/__tempo/errors" && req.method === "GET") {
1295
- res.writeHead(200, {
1296
- "Content-Type": "text/event-stream",
1297
- "Cache-Control": "no-cache",
1298
- Connection: "keep-alive",
1299
- "Access-Control-Allow-Origin": "*"
1300
- });
1301
- res.write(`data: ${JSON.stringify(errorServer.currentError)}
1302
-
1303
- `);
1304
- errorServer.clients.add(res);
1305
- req.on("close", () => {
1306
- errorServer.clients.delete(res);
1307
- });
1308
- return;
1309
- }
1310
- next();
1311
- }
1312
- var MISSED_CHANGE_SWEEP_INTERVAL_MS = 3e3;
1313
- var COMPILE_ERROR_POLL_MAX_INTERVAL_MS = 3e4;
1314
- function installMissedChangeSweep(server, listErrorFiles, lastHotUpdateMtimeMs, pollCompileErrorRecovery) {
1315
- const cacheDir = server.config.cacheDir?.replace(/\\/g, "/").replace(/\/+$/, "");
1316
- const sweep = createMissedChangeSweep({
1317
- listServedFiles: () => {
1318
- const files = new Map(
1319
- server.moduleGraph?.fileToModulesMap ?? /* @__PURE__ */ new Map()
1320
- );
1321
- const errorFiles = listErrorFiles();
1322
- for (const errorFile of errorFiles) {
1323
- const cleanFile = fsPathFromModuleId(errorFile);
1324
- const file = isAbsolute2(cleanFile) ? cleanFile : resolve3(server.config.root, cleanFile);
1325
- if (!files.has(file)) files.set(file, []);
1326
- }
1327
- if (cacheDir) {
1328
- for (const file of files.keys()) {
1329
- if (file.replace(/\\/g, "/").startsWith(`${cacheDir}/`)) {
1330
- files.delete(file);
1331
- }
1332
- }
1333
- }
1334
- return files.entries();
1335
- },
1336
- statMtimeMs: async (file) => {
1337
- try {
1338
- return statSync(file).mtimeMs;
1339
- } catch {
1340
- return null;
1341
- }
1342
- },
1343
- emitChange: (file) => {
1344
- server.config?.logger?.info?.(
1345
- `[tempo] re-emitting lost watcher change: ${file}`,
1346
- { timestamp: true }
1347
- );
1348
- server.watcher?.emit?.("change", file);
1349
- },
1350
- lastHotUpdateMtimeMs
1351
- });
1352
- let passRunning = false;
1353
- const timer = setInterval(() => {
1354
- if (passRunning) return;
1355
- passRunning = true;
1356
- void sweep.sweep().then(() => pollCompileErrorRecovery()).catch(() => {
1357
- }).finally(() => {
1358
- passRunning = false;
1359
- });
1360
- }, MISSED_CHANGE_SWEEP_INTERVAL_MS);
1361
- timer.unref?.();
1362
- server.httpServer?.once("close", () => clearInterval(timer));
1363
- }
1364
- function installTailwindScanNet(server) {
1365
- const net = createTailwindScanNet({
1366
- listCssEntries: function* () {
1367
- const fileToModules = server.moduleGraph?.fileToModulesMap ?? /* @__PURE__ */ new Map();
1368
- for (const [file, modules] of fileToModules) {
1369
- if (!file.endsWith(".css")) continue;
1370
- for (const module of modules) {
1371
- const deps = [];
1372
- for (const imported of module.importedModules ?? []) {
1373
- const dep = imported.file ?? imported.url ?? imported.id;
1374
- if (dep) deps.push(dep);
1375
- }
1376
- yield { cssFile: file, deps };
1377
- }
1378
- }
1379
- },
1380
- emitChange: (cssFile) => {
1381
- server.config?.logger?.info?.(
1382
- `[tempo] new source file outside the Tailwind scan \u2014 re-emitting change: ${cssFile}`,
1383
- { timestamp: true }
1384
- );
1385
- server.watcher?.emit?.("change", cssFile);
1386
- }
1387
- });
1388
- const onWatcherFile = (file) => {
1389
- net.handleWatcherFile(file);
1390
- };
1391
- server.watcher?.on?.("add", onWatcherFile);
1392
- server.watcher?.on?.("change", onWatcherFile);
1393
- server.httpServer?.once("close", () => {
1394
- server.watcher?.off?.("add", onWatcherFile);
1395
- server.watcher?.off?.("change", onWatcherFile);
1396
- net.dispose();
1397
- });
1398
- }
1399
- function tempoVitePlugin(options = {}) {
1400
- const enabled = !!process.env.TEMPO;
1401
- const include = options.include === void 0 ? DEFAULT_INCLUDE : options.include;
1402
- const exclude = options.exclude === void 0 ? DEFAULT_EXCLUDE : options.exclude;
1403
- const isSdkFile = createSdkFileMatcher();
1404
- const userFilter = createFilter(include, exclude);
1405
- const filter = (id) => userFilter(id) && !isSdkFile(id);
1406
- const userControlsFilter = createFilter(
1407
- ["**/*.tsx", "**/*.jsx", "**/*.ts", "**/*.js"],
1408
- exclude
1409
- );
1410
- const controlsFilter = (id) => userControlsFilter(id) && !isSdkFile(id);
1411
- const controlsModules = /* @__PURE__ */ new Set();
1412
- function transformControls(source, id) {
1413
- const code = transformControlsForHmr(source, id, controlsModules.has(id));
1414
- if (code !== source) controlsModules.add(id);
1415
- return code;
1416
- }
1417
- let canonicalRoot = process.cwd();
1418
- let sourceIdentityRoot = canonicalRoot;
1419
- let command = "serve";
1420
- let hmrEnabled = true;
1421
- const errorServer = createErrorServer(
1422
- (file) => pinErroneousRevisionCoverage(file),
1423
- (error) => devServer?.ws.send(VITE_ERROR_STATE_EVENT, error)
1424
- );
1425
- const unresolvedImports = /* @__PURE__ */ new Map();
1426
- let devServer;
1427
- const unresolvedImportWatchers = /* @__PURE__ */ new Map();
1428
- let unresolvedImportResolutionScheduled = false;
1429
- let unresolvedImportResolutionRunning = false;
1430
- let rerunUnresolvedImportResolution = false;
1431
- let unresolvedImportWatchRearmTimer = null;
1432
- const processedUpdatePayloads = /* @__PURE__ */ new WeakSet();
1433
- const prunedModuleDeletion = createPrunedModuleDeletionGuard();
1434
- const hmrGenerationFence = createHmrGenerationFence();
1435
- const rapidHotUpdateReplay = createRapidHotUpdateReplay();
1436
- const hotUpdateMtimesMs = /* @__PURE__ */ new Map();
1437
- const normalizedFileKey = (file) => file.replace(/\\/g, "/");
1438
- const burstKey = (file) => normalizedFileKey(fsPathFromModuleId(file));
1439
- const recordHotUpdateCoverage = (file) => {
1440
- const cleanFile = fsPathFromModuleId(file);
1441
- const key = normalizedFileKey(cleanFile);
1442
- try {
1443
- hotUpdateMtimesMs.set(key, statSync(cleanFile).mtimeMs);
1444
- } catch {
1445
- hotUpdateMtimesMs.delete(key);
1446
- }
1447
- };
1448
- const pinErroneousRevisionCoverage = (file) => {
1449
- recordHotUpdateCoverage(file);
1450
- };
1451
- const hasActiveCompileError = (file) => errorServer.errorFiles.some((errorFile) => moduleIdsMatch(errorFile, file));
1452
- const recoverActiveCompileError = async (server, file) => {
1453
- if (!hasActiveCompileError(file)) return false;
1454
- const cleanFile = fsPathFromModuleId(file);
1455
- const requestId = `/@fs/${cleanFile.replace(/^\/+/, "")}`;
1456
- const clientEnvironment = server.environments?.client;
1457
- const transformer = clientEnvironment ?? server;
1458
- try {
1459
- let canonicalFile = cleanFile;
1460
- try {
1461
- canonicalFile = realpathSync3(cleanFile);
1462
- } catch {
1463
- }
1464
- const modules = /* @__PURE__ */ new Set([
1465
- ...transformer.moduleGraph.getModulesByFile(canonicalFile) ?? [],
1466
- ...transformer.moduleGraph.getModulesByFile(cleanFile) ?? []
1467
- ]);
1468
- for (const module of modules) {
1469
- transformer.moduleGraph.invalidateModule(module);
1470
- }
1471
- const result = await transformer.transformRequest(requestId);
1472
- if (!result) return false;
1473
- } catch {
1474
- return false;
1475
- }
1476
- errorServer.clearErrorForModules([file, cleanFile, requestId]);
1477
- server.config.logger.info(
1478
- `[tempo] recovered compile-error module after validated transform: ${cleanFile}`,
1479
- { timestamp: true }
1480
- );
1481
- (clientEnvironment?.hot ?? server.ws).send({
1482
- type: "full-reload",
1483
- path: "*"
1484
- });
1485
- return true;
1486
- };
1487
- const compileErrorPollSchedule = /* @__PURE__ */ new Map();
1488
- const pollCompileErrorRecovery = async (server) => {
1489
- const activeFiles = new Map(
1490
- errorServer.errorFiles.map((file) => [
1491
- normalizedFileKey(fsPathFromModuleId(file)),
1492
- file
1493
- ])
1494
- );
1495
- for (const key of [...compileErrorPollSchedule.keys()]) {
1496
- if (!activeFiles.has(key)) compileErrorPollSchedule.delete(key);
1497
- }
1498
- const nowMs = Date.now();
1499
- for (const [key, file] of activeFiles) {
1500
- const schedule = compileErrorPollSchedule.get(key);
1501
- if (schedule && nowMs < schedule.nextAttemptAtMs) continue;
1502
- if (await recoverActiveCompileError(server, file)) {
1503
- compileErrorPollSchedule.delete(key);
1504
- continue;
1505
- }
1506
- const intervalMs = schedule?.intervalMs ?? MISSED_CHANGE_SWEEP_INTERVAL_MS;
1507
- compileErrorPollSchedule.set(key, {
1508
- nextAttemptAtMs: nowMs + intervalMs,
1509
- intervalMs: Math.min(
1510
- intervalMs * 2,
1511
- COMPILE_ERROR_POLL_MAX_INTERVAL_MS
1512
- )
1513
- });
1514
- }
1515
- };
1516
- const defaultExportIdentityByFile = /* @__PURE__ */ new Map();
1517
- const canonicalIdentityKey = (idOrFile) => {
1518
- const file = fsPathFromModuleId(idOrFile);
1519
- try {
1520
- return realpathSync3.native(file);
1521
- } catch {
1522
- return file.replace(/\\/g, "/");
1523
- }
1524
- };
1525
- const repairDefaultExportIdentityRewrite = async (context) => {
1526
- const { file } = context;
1527
- const key = canonicalIdentityKey(file);
1528
- if (!defaultExportIdentityByFile.has(key)) return false;
1529
- let source;
1530
- try {
1531
- source = readFileSync3(file, "utf8");
1532
- if (source.length === 0) source = await context.read();
1533
- } catch {
1534
- return false;
1535
- }
1536
- const before = defaultExportIdentityByFile.get(key);
1537
- if (before === void 0) return false;
1538
- const after = readDefaultExportIdentity(source);
1539
- defaultExportIdentityByFile.set(key, after);
1540
- if (!isDefaultExportIdentityRewrite(before, after)) return false;
1541
- devServer?.ws.send({ type: "full-reload", path: "*" });
1542
- return true;
1543
- };
1544
- const invalidateCanvasLoader = (file, graph, modules) => {
1545
- const canvasPath = relative(sourceIdentityRoot, file).replace(/\\/g, "/");
1546
- const wrapperPath = resolve3(canonicalRoot, ".tempo", "tempo-host.tsx");
1547
- let source;
1548
- try {
1549
- source = readFileSync3(wrapperPath, "utf8");
1550
- } catch {
1551
- return;
1552
- }
1553
- if (!readGeneratedCanvasPaths(source).includes(canvasPath)) return;
1554
- const wrappers = graph.getModulesByFile(wrapperPath);
1555
- if (!wrappers?.size) return;
1556
- for (const wrapper of wrappers) graph.invalidateModule(wrapper);
1557
- return [.../* @__PURE__ */ new Set([...modules, ...wrappers])];
1558
- };
1559
- const rememberUnresolvedImport = (specifier, importer, packageName) => {
1560
- const key = `${importer}\0${specifier}`;
1561
- unresolvedImports.delete(key);
1562
- unresolvedImports.set(key, { specifier, importer, packageName });
1563
- while (unresolvedImports.size > MAX_UNRESOLVED_IMPORTS) {
1564
- const oldestKey = unresolvedImports.keys().next().value;
1565
- if (oldestKey === void 0) break;
1566
- unresolvedImports.delete(oldestKey);
1567
- }
1568
- syncUnresolvedImportWatcher();
1569
- };
1570
- const forgetUnresolvedImportsFrom = (file) => {
1571
- for (const [key, unresolved] of unresolvedImports) {
1572
- if (resolvedIdMatchesFile(unresolved.importer, file)) {
1573
- unresolvedImports.delete(key);
1574
- }
1575
- }
1576
- syncUnresolvedImportWatcher();
1577
- };
1578
- const closeUnresolvedImportWatcher = (path) => {
1579
- unresolvedImportWatchers.get(path)?.watcher.close();
1580
- unresolvedImportWatchers.delete(path);
1581
- };
1582
- const cancelUnresolvedImportWatchRearm = () => {
1583
- if (unresolvedImportWatchRearmTimer === null) return;
1584
- clearTimeout(unresolvedImportWatchRearmTimer);
1585
- unresolvedImportWatchRearmTimer = null;
1586
- };
1587
- const scheduleUnresolvedImportWatchRearm = () => {
1588
- if (unresolvedImportWatchRearmTimer !== null || !devServer || unresolvedImports.size === 0) {
1589
- return;
1590
- }
1591
- unresolvedImportWatchRearmTimer = setTimeout(() => {
1592
- unresolvedImportWatchRearmTimer = null;
1593
- if (devServer && unresolvedImports.size > 0) {
1594
- syncUnresolvedImportWatcher();
1595
- scheduleUnresolvedImportResolution();
1596
- }
1597
- }, UNRESOLVED_IMPORT_WATCH_REARM_MS);
1598
- unresolvedImportWatchRearmTimer.unref?.();
1599
- };
1600
- const closeUnresolvedImportWatchers = () => {
1601
- cancelUnresolvedImportWatchRearm();
1602
- for (const path of [...unresolvedImportWatchers.keys()]) {
1603
- closeUnresolvedImportWatcher(path);
1604
- }
1605
- };
1606
- const hasUnresolvedBarePackages = () => [...unresolvedImports.values()].some(
1607
- (unresolved) => unresolved.packageName !== void 0
1608
- );
1609
- const packageWatchTarget = (unresolved) => {
1610
- let candidate = dirname3(cleanModuleId(unresolved.importer));
1611
- let nearestPackageRoot;
1612
- while (true) {
1613
- try {
1614
- if (statSync(join2(candidate, "node_modules")).isDirectory()) {
1615
- return join2(candidate, "node_modules", unresolved.packageName);
1616
- }
1617
- } catch {
1618
- }
1619
- if (nearestPackageRoot === void 0) {
1620
- try {
1621
- if (statSync(join2(candidate, "package.json")).isFile()) {
1622
- nearestPackageRoot = candidate;
1623
- }
1624
- } catch {
1625
- }
1626
- }
1627
- const parent = dirname3(candidate);
1628
- if (parent === candidate) break;
1629
- candidate = parent;
1630
- }
1631
- return join2(
1632
- nearestPackageRoot ?? canonicalRoot,
1633
- "node_modules",
1634
- unresolved.packageName
1635
- );
1636
- };
1637
- const unresolvedImportWatchTarget = (unresolved) => {
1638
- return unresolved.packageName ? packageWatchTarget(
1639
- unresolved
1640
- ) : resolve3(
1641
- dirname3(cleanModuleId(unresolved.importer)),
1642
- cleanModuleId(unresolved.specifier)
1643
- );
1644
- };
1645
- const nearestExistingDirectory = (target) => {
1646
- let candidate = target;
1647
- while (true) {
1648
- try {
1649
- if (statSync(candidate).isDirectory()) return candidate;
1650
- } catch {
1651
- }
1652
- const parent = dirname3(candidate);
1653
- if (parent === candidate) return void 0;
1654
- candidate = parent;
1655
- }
1656
- };
1657
- function syncUnresolvedImportWatcher() {
1658
- if (!devServer || unresolvedImports.size === 0) {
1659
- closeUnresolvedImportWatchers();
1660
- return;
1661
- }
1662
- const desired = /* @__PURE__ */ new Map();
1663
- for (const unresolved of unresolvedImports.values()) {
1664
- const target = unresolvedImportWatchTarget(unresolved);
1665
- const watchPath = nearestExistingDirectory(target);
1666
- if (!watchPath) continue;
1667
- const previous = desired.get(watchPath);
1668
- desired.set(watchPath, {
1669
- recursive: previous?.recursive === true || watchPath === target
1670
- });
1671
- }
1672
- for (const [path, existing] of [...unresolvedImportWatchers]) {
1673
- const next = desired.get(path);
1674
- if (!next || next.recursive !== existing.recursive) {
1675
- closeUnresolvedImportWatcher(path);
1676
- }
1677
- }
1678
- for (const [path, options2] of desired) {
1679
- if (unresolvedImportWatchers.has(path)) continue;
1680
- try {
1681
- const watcher = watchFileSystem(
1682
- path,
1683
- { recursive: options2.recursive },
1684
- scheduleUnresolvedImportResolution
1685
- );
1686
- unresolvedImportWatchers.set(path, {
1687
- watcher,
1688
- recursive: options2.recursive
1689
- });
1690
- watcher.on("error", () => {
1691
- closeUnresolvedImportWatcher(path);
1692
- scheduleUnresolvedImportWatchRearm();
1693
- });
1694
- if (options2.recursive) scheduleUnresolvedImportResolution();
1695
- } catch {
1696
- closeUnresolvedImportWatcher(path);
1697
- scheduleUnresolvedImportWatchRearm();
1698
- }
1699
- }
1700
- if ([...desired.keys()].every((path) => unresolvedImportWatchers.has(path))) {
1701
- cancelUnresolvedImportWatchRearm();
1702
- }
1703
- }
1704
- function scheduleUnresolvedImportResolution() {
1705
- if (unresolvedImportResolutionScheduled || unresolvedImportResolutionRunning) {
1706
- rerunUnresolvedImportResolution = true;
1707
- return;
1708
- }
1709
- unresolvedImportResolutionScheduled = true;
1710
- queueMicrotask(() => {
1711
- unresolvedImportResolutionScheduled = false;
1712
- void runUnresolvedImportResolution();
1713
- });
1714
- }
1715
- async function runUnresolvedImportResolution() {
1716
- const server = devServer;
1717
- if (!server || unresolvedImportResolutionRunning) return;
1718
- unresolvedImportResolutionRunning = true;
1719
- try {
1720
- do {
1721
- rerunUnresolvedImportResolution = false;
1722
- syncUnresolvedImportWatcher();
1723
- let resolvedImportInPass = false;
1724
- for (const [key, unresolved] of [...unresolvedImports]) {
1725
- let file;
1726
- if (isRelativeImportSpecifier(unresolved.specifier)) {
1727
- const suffixIndex = unresolved.specifier.search(/[?#]/);
1728
- const relativePath = suffixIndex < 0 ? unresolved.specifier : unresolved.specifier.slice(0, suffixIndex);
1729
- const candidate = resolve3(
1730
- dirname3(cleanModuleId(unresolved.importer)),
1731
- relativePath
1732
- );
1733
- const probes = [
1734
- candidate,
1735
- ...RELATIVE_IMPORT_RESOLVE_EXTENSIONS.map(
1736
- (extension) => `${candidate}${extension}`
1737
- ),
1738
- ...RELATIVE_IMPORT_RESOLVE_EXTENSIONS.map(
1739
- (extension) => join2(candidate, `index${extension}`)
1740
- )
1741
- ];
1742
- for (const probe of probes) {
1743
- try {
1744
- if (statSync(probe).isFile()) {
1745
- file = probe;
1746
- break;
1747
- }
1748
- } catch {
1749
- }
1750
- }
1751
- }
1752
- if (!file && unresolved.packageName) {
1753
- try {
1754
- file = createRequire(cleanModuleId(unresolved.importer)).resolve(
1755
- unresolved.specifier
1756
- );
1757
- } catch {
1758
- }
1759
- }
1760
- if (!file) continue;
1761
- server.watcher.add(file);
1762
- unresolvedImports.delete(key);
1763
- errorServer.clearErrorForModules([unresolved.importer]);
1764
- resolvedImportInPass = true;
1765
- }
1766
- if (resolvedImportInPass) {
1767
- server.ws.send({ type: "full-reload", path: "*" });
1768
- }
1769
- syncUnresolvedImportWatcher();
1770
- } while (rerunUnresolvedImportResolution);
1771
- } finally {
1772
- unresolvedImportResolutionRunning = false;
1773
- }
1774
- }
1775
- return {
1776
- name: "tempo-annotate",
1777
- apply: "serve",
1778
- enforce: "pre",
1779
- config(config, environment) {
1780
- if (!enabled || environment.command !== "serve") return;
1781
- const dedupe = ["react", "react-dom"].filter(
1782
- (name) => !config.resolve?.dedupe?.includes(name)
1783
- );
1784
- return {
1785
- resolve: { dedupe },
1786
- ...config.css?.devSourcemap === void 0 ? { css: { devSourcemap: true } } : {}
1787
- };
1788
- },
1789
- resolveId: {
1790
- order: "pre",
1791
- async handler(id, importer, resolveOptions) {
1792
- if (enabled && id === VITE_ERROR_CLIENT_PATH) {
1793
- return VITE_ERROR_CLIENT_ID;
1794
- }
1795
- if (id === INTERACT_PROJECTION_CLIENT_PATH) {
1796
- return INTERACT_PROJECTION_CLIENT_ID;
1797
- }
1798
- if (id === INTERACT_PROJECTION_SDK_SPECIFIER && importer === INTERACT_PROJECTION_CLIENT_ID) {
1799
- const resolved = await this.resolve(id, importer, {
1800
- ...resolveOptions,
1801
- skipSelf: true
1802
- });
1803
- if (resolved) return resolved;
1804
- return resolveOwnInteractProjectionModule();
1805
- }
1806
- if (enabled && importer && !importer.startsWith("\0")) {
1807
- const packageName = barePackageName(id);
1808
- if (!isRelativeImportSpecifier(id) && !packageName) return null;
1809
- try {
1810
- const resolved = await this.resolve(id, importer, {
1811
- ...resolveOptions,
1812
- skipSelf: true
1813
- });
1814
- if (!resolved) rememberUnresolvedImport(id, importer, packageName);
1815
- return resolved;
1816
- } catch (error) {
1817
- rememberUnresolvedImport(id, importer, packageName);
1818
- throw error;
1819
- }
1820
- }
1821
- return null;
1822
- }
1823
- },
1824
- // `order: "pre"` + a null return: this hook never loads anything of its
1825
- // own for a project file, it only decides WHEN Vite core is allowed to
1826
- // read it. Awaiting the burst gate here (rather than in `transform`) is
1827
- // what makes the content terminal — by `transform` the bytes have already
1828
- // been read, so delaying there would ship a stale revision late instead of
1829
- // not shipping it at all.
1830
- load: {
1831
- order: "pre",
1832
- async handler(id) {
1833
- if (enabled && id === VITE_ERROR_CLIENT_ID) {
1834
- return VITE_ERROR_CLIENT_SOURCE;
1835
- }
1836
- if (id === INTERACT_PROJECTION_CLIENT_ID) {
1837
- return `import { installTempoInteractProjectionSource } from ${JSON.stringify(INTERACT_PROJECTION_SDK_SPECIFIER)};
1838
- let stop;
1839
- const releaseOwner = () => {
1840
- if (window.__tempoInteractProjectionOwner === "vite") delete window.__tempoInteractProjectionOwner;
1841
- };
1842
- if (window.parent !== window && !window.__tempoInteractProjectionOwner && (window.name === ${JSON.stringify(TEMPO_INTERACT_FRAME_NAME)} || window.name.startsWith(${JSON.stringify(`${TEMPO_INTERACT_FRAME_NAME}:`)}))) {
1843
- window.__tempoInteractProjectionOwner = "vite";
1844
- const stopSource = installTempoInteractProjectionSource();
1845
- stop = () => {
1846
- stopSource();
1847
- releaseOwner();
1848
- };
1849
- }
1850
- if (import.meta.hot) import.meta.hot.dispose(() => {
1851
- stop?.();
1852
- releaseOwner();
1853
- });`;
1854
- }
1855
- if (!enabled || command === "build" || id.startsWith("\0")) return null;
1856
- await rapidHotUpdateReplay.settled(burstKey(id));
1857
- return null;
1858
- }
1859
- },
1860
- // Expose error server for testing
1861
- _tempoErrorServer: errorServer,
1862
- // Test seam pinning the exact evidence the missed-change sweep reads.
1863
- _tempoHotUpdateState: {
1864
- lastHotUpdateMtimeMs(file) {
1865
- return hotUpdateMtimesMs.get(normalizedFileKey(file));
1866
- }
1867
- },
1868
- _tempoUnresolvedImportState: {
1869
- get size() {
1870
- return unresolvedImports.size;
1871
- },
1872
- get barePackageCount() {
1873
- return [...unresolvedImports.values()].filter(
1874
- (unresolved) => unresolved.packageName !== void 0
1875
- ).length;
1876
- },
1877
- get hasBarePackageWatcher() {
1878
- return unresolvedImportWatchers.size > 0 && hasUnresolvedBarePackages();
1879
- },
1880
- get barePackageWatchPath() {
1881
- return hasUnresolvedBarePackages() ? unresolvedImportWatchers.keys().next().value : void 0;
1882
- },
1883
- get hasUnresolvedImportWatcher() {
1884
- return unresolvedImportWatchers.size > 0;
1885
- },
1886
- get unresolvedImportWatchPath() {
1887
- return unresolvedImportWatchers.keys().next().value;
1888
- },
1889
- get unresolvedImportWatchPaths() {
1890
- return [...unresolvedImportWatchers.keys()];
1891
- },
1892
- get hasUnresolvedImportWatchRearm() {
1893
- return unresolvedImportWatchRearmTimer !== null;
1894
- },
1895
- emitUnresolvedImportWatcherErrorForTesting() {
1896
- for (const { watcher } of unresolvedImportWatchers.values()) {
1897
- watcher.emit(
1898
- "error",
1899
- new Error("Simulated unresolved-import watcher failure")
1900
- );
1901
- }
1902
- }
1903
- },
1904
- configResolved(resolvedConfig) {
1905
- if (!enabled) return;
1906
- command = resolvedConfig.command;
1907
- hmrEnabled = resolvedConfig.server?.hmr !== false;
1908
- if (command === "serve" && hmrEnabled) {
1909
- installSynchronousReactRefreshBoundary(resolvedConfig.plugins ?? []);
1910
- }
1911
- canonicalRoot = resolveCanonicalRoot(resolvedConfig.root);
1912
- sourceIdentityRoot = options.sourceIdentityRoot ? resolveCanonicalRoot(
1913
- resolve3(resolvedConfig.root, options.sourceIdentityRoot)
1914
- ) : canonicalRoot;
1915
- },
1916
- configureServer(server) {
1917
- if (!enabled) return;
1918
- const events = ["change", "add", "unlink"];
1919
- for (const event of events)
1920
- server.watcher?.prependListener?.(event, recordHotUpdateCoverage);
1921
- const ownInteractModule = resolveOwnInteractProjectionModule();
1922
- const allow = server.config?.server?.fs?.allow;
1923
- if (Array.isArray(allow)) {
1924
- const requiredRoots = [
1925
- sourceIdentityRoot,
1926
- ...ownInteractModule ? [dirname3(ownInteractModule)] : []
1927
- ];
1928
- for (const requiredRoot of requiredRoots) {
1929
- if (!allow.includes(requiredRoot)) allow.push(requiredRoot);
1930
- }
1931
- }
1932
- devServer = server;
1933
- server.ws.on?.(VITE_ERROR_SUBSCRIBE_EVENT, (_data, client) => {
1934
- client.send(VITE_ERROR_STATE_EVENT, errorServer.currentError);
1935
- });
1936
- syncUnresolvedImportWatcher();
1937
- server.watcher?.once?.("close", closeUnresolvedImportWatchers);
1938
- server.httpServer?.once("close", closeUnresolvedImportWatchers);
1939
- server.middlewares.use((req, res, next) => {
1940
- const graph = server.environments?.client?.moduleGraph;
1941
- if (graph && req.url && (req.method === "GET" || req.method === "HEAD")) {
1942
- const observeResponse = prunedModuleDeletion.observeRequest(
1943
- graph,
1944
- req.url,
1945
- server.config.base,
1946
- req.headers["sec-fetch-dest"],
1947
- req.headers["if-none-match"]
1948
- );
1949
- if (observeResponse)
1950
- res.once("finish", () => {
1951
- void observeResponse(
1952
- res.statusCode,
1953
- res.getHeader("content-type"),
1954
- res.getHeader("etag")
1955
- );
1956
- });
1957
- }
1958
- const name = req.url?.match(
1959
- /^\/tempo-assets\/([a-zA-Z0-9._-]+)(?:\?.*)?$/
1960
- )?.[1];
1961
- if (name) {
1962
- const file = ["public", "static"].map(
1963
- (directory) => join2(sourceIdentityRoot, directory, "tempo-assets", name)
1964
- ).find((file2) => existsSync(file2));
1965
- if (file) req.url = `/@fs/${file.replace(/\\/g, "/")}`;
1966
- }
1967
- handleTempoMiddleware(errorServer, server, req, res, next);
1968
- });
1969
- installMissedChangeSweep(
1970
- server,
1971
- () => errorServer.errorFiles,
1972
- (file) => hotUpdateMtimesMs.get(normalizedFileKey(file)),
1973
- () => pollCompileErrorRecovery(server)
1974
- );
1975
- installTailwindScanNet(server);
1976
- const interceptHmrSend = (target) => {
1977
- const orig = target.send.bind(target);
1978
- target.send = ((...args) => {
1979
- const payload = args[0];
1980
- if (typeof payload === "object" && payload !== null && "type" in payload) {
1981
- const typed = payload;
1982
- if (typed.type === "prune") {
1983
- const graph = server.environments?.client?.moduleGraph;
1984
- if (graph)
1985
- prunedModuleDeletion.observePrune(
1986
- graph,
1987
- typed.paths ?? []
1988
- );
1989
- }
1990
- if (typed.type === "error") {
1991
- const err = typed.err;
1992
- errorServer.setError({
1993
- type: "compile",
1994
- message: err?.message ?? "Unknown error",
1995
- stack: err?.stack,
1996
- file: err?.id ?? err?.loc?.file,
1997
- frame: err?.frame,
1998
- plugin: err?.plugin,
1999
- loc: err?.loc
2000
- });
2001
- } else if (typed.type === "update" && !processedUpdatePayloads.has(payload)) {
2002
- processedUpdatePayloads.add(payload);
2003
- const updatePayload = typed;
2004
- const updates = updatePayload.updates;
2005
- const acceptedUpdates = updates ? hmrGenerationFence.filter(updates) : void 0;
2006
- if (updates && acceptedUpdates && acceptedUpdates.length !== updates.length) {
2007
- updatePayload.updates = acceptedUpdates;
2008
- }
2009
- const paths = acceptedUpdates?.map((u) => u.path).filter((p) => typeof p === "string") ?? [];
2010
- errorServer.clearErrorForModules(paths);
2011
- if (updates && updates.length > 0 && acceptedUpdates?.length === 0) {
2012
- return;
2013
- }
2014
- }
2015
- }
2016
- return orig(...args);
2017
- });
2018
- };
2019
- interceptHmrSend(server.ws);
2020
- return () => {
2021
- const clientHot = server.environments?.client?.hot;
2022
- if (clientHot && clientHot !== server.ws) {
2023
- interceptHmrSend(clientHot);
2024
- }
2025
- };
2026
- },
2027
- closeBundle() {
2028
- devServer = void 0;
2029
- rapidHotUpdateReplay.clear();
2030
- hmrGenerationFence.clear();
2031
- prunedModuleDeletion.clear();
2032
- hotUpdateMtimesMs.clear();
2033
- compileErrorPollSchedule.clear();
2034
- closeUnresolvedImportWatchers();
2035
- },
2036
- hotUpdate: {
2037
- order: "post",
2038
- async handler(context) {
2039
- if (!enabled || this.environment.config.consumer !== "client") return;
2040
- if (context.type === "create" && /\/\.tempo\/asset-edit-previews\/\d+\/index\.canvas\.tsx$/.test(
2041
- context.file.replace(/\\/g, "/")
2042
- )) {
2043
- return [];
2044
- }
2045
- if (context.type === "update" && context.modules.length > 0) {
2046
- rapidHotUpdateReplay.observe(burstKey(context.file), () => {
2047
- context.server.config.logger.info(
2048
- `[tempo] replaying settled rapid watcher change: ${context.file}`,
2049
- { timestamp: true }
2050
- );
2051
- context.server.watcher.emit("change", context.file);
2052
- });
2053
- }
2054
- if (context.type !== "create") {
2055
- forgetUnresolvedImportsFrom(context.file);
2056
- }
2057
- if (context.type === "update" && hasActiveCompileError(context.file) && await recoverActiveCompileError(context.server, context.file)) {
2058
- return [];
2059
- }
2060
- if (context.type === "delete") {
2061
- defaultExportIdentityByFile.delete(
2062
- canonicalIdentityKey(context.file)
2063
- );
2064
- if (prunedModuleDeletion.suppressDeletion(
2065
- this.environment.moduleGraph,
2066
- context.modules
2067
- ))
2068
- return [];
2069
- return;
2070
- }
2071
- if (context.type === "update" && await repairDefaultExportIdentityRewrite(context)) {
2072
- return [];
2073
- }
2074
- if (context.type === "update") {
2075
- return invalidateCanvasLoader(
2076
- context.file,
2077
- this.environment.moduleGraph,
2078
- context.modules
2079
- );
2080
- }
2081
- }
2082
- },
2083
- // Vite 5 compatibility. Vite 6+ prefers `hotUpdate` above.
2084
- handleHotUpdate: {
2085
- order: "post",
2086
- async handler(context) {
2087
- if (!enabled) return;
2088
- if (context.modules.length > 0) {
2089
- rapidHotUpdateReplay.observe(burstKey(context.file), () => {
2090
- context.server.config.logger.info(
2091
- `[tempo] replaying settled rapid watcher change: ${context.file}`,
2092
- { timestamp: true }
2093
- );
2094
- context.server.watcher.emit("change", context.file);
2095
- });
2096
- }
2097
- forgetUnresolvedImportsFrom(context.file);
2098
- if (hasActiveCompileError(context.file) && await recoverActiveCompileError(context.server, context.file)) {
2099
- return [];
2100
- }
2101
- if (await repairDefaultExportIdentityRewrite(context)) {
2102
- return [];
2103
- }
2104
- return invalidateCanvasLoader(
2105
- context.file,
2106
- context.server.moduleGraph,
2107
- context.modules
2108
- );
2109
- }
2110
- },
2111
- transformIndexHtml(html, context) {
2112
- if (!enabled || command !== "serve") {
2113
- return;
2114
- }
2115
- const tags = [];
2116
- if (hmrEnabled) {
2117
- tags.push({
2118
- tag: "script",
2119
- attrs: { type: "module", src: VITE_ERROR_CLIENT_PATH },
2120
- injectTo: "head-prepend"
2121
- });
2122
- }
2123
- if (!hasRootMetaTag(html)) {
2124
- tags.push({
2125
- tag: "meta",
2126
- attrs: {
2127
- name: ROOT_META_NAME,
2128
- content: canonicalRoot
2129
- },
2130
- injectTo: "head"
2131
- });
2132
- }
2133
- if (!hasSourceIdentityRootMetaTag(html)) {
2134
- tags.push({
2135
- tag: "meta",
2136
- attrs: {
2137
- name: SOURCE_IDENTITY_ROOT_META_NAME,
2138
- content: sourceIdentityRoot
2139
- },
2140
- injectTo: "head"
2141
- });
2142
- }
2143
- const workspaceNonce = createTempoHostIdentity("vite", {
2144
- root: canonicalRoot,
2145
- pluginActive: true
2146
- }).workspaceNonce;
2147
- if (workspaceNonce && !hasWorkspaceNonceMetaTag(html)) {
2148
- tags.push({
2149
- tag: "meta",
2150
- attrs: {
2151
- name: TEMPO_WORKSPACE_NONCE_META_NAME,
2152
- content: workspaceNonce
2153
- },
2154
- injectTo: "head"
2155
- });
2156
- }
2157
- const requestPath = context?.originalUrl ?? context?.path;
2158
- const isDeclarativeCanvasHost = requestPath ? isDeclarativeCanvasHostRequest(requestPath) : false;
2159
- if (requestPath && !isDeclarativeCanvasHost) {
2160
- tags.push({
2161
- tag: "script",
2162
- children: INTERACT_PROJECTION_BOOTSTRAP,
2163
- injectTo: "head-prepend"
2164
- });
2165
- tags.push({
2166
- tag: "script",
2167
- attrs: { type: "module", src: INTERACT_PROJECTION_CLIENT_PATH },
2168
- injectTo: "head-prepend"
2169
- });
2170
- }
2171
- return tags.length > 0 ? tags : void 0;
2172
- },
2173
- async transform(source, id) {
2174
- if (!enabled || command === "build") {
2175
- return null;
2176
- }
2177
- if (id.startsWith("\0")) {
2178
- return null;
2179
- }
2180
- const cleanId = cleanModuleId(id);
2181
- if (cleanId.replace(/\\/g, "/").endsWith("/vite/dist/client/client.mjs")) {
2182
- const code = preservePendingViteModuleUpdates(source);
2183
- return code === source ? null : { code, map: null };
2184
- }
2185
- const controlsSource = controlsFilter(cleanId) ? transformControls(source, cleanId) : source;
2186
- if (!filter(cleanId)) {
2187
- if (controlsSource !== source)
2188
- return { code: controlsSource, map: null };
2189
- return null;
2190
- }
2191
- try {
2192
- const filepath = relative(canonicalRoot, cleanId);
2193
- const descriptor = openSync(cleanId, "r");
2194
- let snapshot;
2195
- try {
2196
- const before2 = fstatSync(descriptor);
2197
- const rawSource2 = readFileSync3(descriptor, "utf8");
2198
- snapshot = { before: before2, rawSource: rawSource2, after: fstatSync(descriptor) };
2199
- } finally {
2200
- closeSync(descriptor);
2201
- }
2202
- const { before, after, rawSource } = snapshot;
2203
- const stable = ["mtimeMs", "ctimeMs", "size", "ino", "dev"];
2204
- let loadedSource = source === rawSource ? source : void 0;
2205
- if (loadedSource === void 0 && typeof this.getCombinedSourcemap === "function") {
2206
- try {
2207
- const map = this.getCombinedSourcemap();
2208
- const sourceRoot = map.sourceRoot;
2209
- const matches = map.sources.flatMap((path, index) => {
2210
- const sourcePath = path.startsWith("file:") ? fileURLToPath(path) : path;
2211
- const file = isAbsolute2(sourcePath) ? sourcePath : resolve3(
2212
- dirname3(cleanId),
2213
- typeof sourceRoot === "string" ? sourceRoot : "",
2214
- sourcePath
2215
- );
2216
- let sameFile = cleanModuleId(file).replace(/\\/g, "/") === cleanId.replace(/\\/g, "/");
2217
- if (!sameFile) {
2218
- try {
2219
- sameFile = realpathSync3.native(file) === realpathSync3.native(cleanId);
2220
- } catch {
2221
- }
2222
- }
2223
- return sameFile && typeof map.sourcesContent?.[index] === "string" ? [map.sourcesContent[index]] : [];
2224
- });
2225
- if (matches.length === 1) loadedSource = matches[0];
2226
- } catch {
2227
- }
2228
- }
2229
- const witnessed = loadedSource === rawSource && stable.every((key) => before[key] === after[key]);
2230
- const modifiedtsMs = witnessed ? Math.trunc(before.mtimeMs) : 0;
2231
- const sourceVersion = witnessed ? sourceVersionHash(rawSource) : "";
2232
- const identityKey = canonicalIdentityKey(cleanId);
2233
- if (!defaultExportIdentityByFile.has(identityKey)) {
2234
- defaultExportIdentityByFile.set(
2235
- identityKey,
2236
- readDefaultExportIdentity(rawSource)
2237
- );
2238
- }
2239
- const resolvedComponents = /* @__PURE__ */ new Map();
2240
- if (source.includes("tempo-sdk/canvas") && typeof this.resolve === "function") {
2241
- const imports = parseCanvasFile(cleanId, source).storyboards.flatMap(
2242
- (board) => board.component?.import?.source ?? []
2243
- );
2244
- await Promise.all(
2245
- [...new Set(imports)].map(async (specifier) => {
2246
- const resolved = await this.resolve(specifier, cleanId, {
2247
- skipSelf: true
2248
- });
2249
- if (resolved) resolvedComponents.set(specifier, resolved.id);
2250
- })
2251
- );
2252
- }
2253
- const componentReferences = canvasComponentAnnotations(
2254
- cleanId,
2255
- source,
2256
- resolvedComponents
2257
- );
2258
- const result = annotateFile(source, cleanId, (info) => {
2259
- const props = {
2260
- ...componentReferences.get(info.element.openingElement.start),
2261
- ...computeTempoAnnotatedProps({
2262
- info,
2263
- filepath,
2264
- modifiedtsMs,
2265
- sourceVersion,
2266
- computeAnnotatedProps: options.computeAnnotatedProps
2267
- })
2268
- };
2269
- if (!witnessed) {
2270
- delete props["data-tempo-filepath"];
2271
- delete props["data-tempo-position"];
2272
- delete props["data-tempo-expr"];
2273
- delete props["data-tempo-modifiedts"];
2274
- delete props["data-tempo-source-version"];
2275
- }
2276
- return props;
2277
- });
2278
- if (result.parseResult.errors.length > 0) return null;
2279
- const annotated = result.elementsAnnotated === 0 ? source : result.annotatedSource;
2280
- const withControls = controlsFilter(cleanId) ? transformControls(annotated, cleanId) : annotated;
2281
- return {
2282
- code: witnessed ? appendModuleVersionRecord(
2283
- withControls,
2284
- filepath,
2285
- modifiedtsMs,
2286
- sourceVersion
2287
- ) : withControls,
2288
- map: null
2289
- };
2290
- } catch {
2291
- return null;
2292
- }
2293
- }
2294
- };
2295
- }
2296
- var tempoAnnotate = tempoVitePlugin;
11
+ import "./chunk-K3EYTZLL.js";
12
+ import "./chunk-65B52AR7.js";
2297
13
  export {
2298
14
  tempoAnnotate,
2299
15
  tempoVitePlugin