tempo-sdk 0.0.99 → 0.0.101

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