tempo-sdk 0.0.18 → 0.0.20

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.
package/dist/index.js CHANGED
@@ -1,6 +1,17 @@
1
+ import {
2
+ TEMPO_INTERACT_FRAME_NAME
3
+ } from "./chunk-QXB32HG4.js";
4
+
1
5
  // index.ts
2
- import { realpathSync as realpathSync2, statSync as statSync2 } from "fs";
3
- import { relative as relative2 } from "path";
6
+ import {
7
+ readFileSync,
8
+ realpathSync as realpathSync2,
9
+ statSync as statSync2,
10
+ watch as watchFileSystem
11
+ } from "fs";
12
+ import { createRequire } from "module";
13
+ import { dirname, join, relative as relative2, resolve } from "path";
14
+ import { createFilter } from "@rollup/pluginutils";
4
15
 
5
16
  // ../../modules/annotation/annotate-file.ts
6
17
  import { parseSync as parseSync2 } from "oxc-parser";
@@ -142,9 +153,6 @@ function toHex8(n) {
142
153
  return (n >>> 0).toString(16).padStart(8, "0");
143
154
  }
144
155
 
145
- // index.ts
146
- import { createFilter } from "@rollup/pluginutils";
147
-
148
156
  // annotation-strategy.ts
149
157
  import { realpathSync, statSync } from "fs";
150
158
  import { relative } from "path";
@@ -217,13 +225,154 @@ function computeTempoAnnotatedProps(params) {
217
225
  return userProps;
218
226
  }
219
227
 
228
+ // default-export-identity.ts
229
+ var FUNCTION_DEFAULT_RE = /^(?:async\s+)?function(?:\s*\*)?(?:\s+([A-Za-z_$][\w$]*))?\s*\(/;
230
+ var CLASS_DEFAULT_RE = /^(?:abstract\s+)?class(?:\s+([A-Za-z_$][\w$]*))?(?=[\s{])/;
231
+ var IDENTIFIER_DEFAULT_RE = /^([A-Za-z_$][\w$]*)[ \t]*(?:;|\r?\n|$)/;
232
+ function readDefaultExportIdentity(source) {
233
+ const start = /\bexport\s+default\s+/.exec(source);
234
+ if (!start) return null;
235
+ const tail = source.slice(start.index + start[0].length);
236
+ const fn = FUNCTION_DEFAULT_RE.exec(tail);
237
+ if (fn) return { kind: "function", name: fn[1] ?? null };
238
+ const cls = CLASS_DEFAULT_RE.exec(tail);
239
+ if (cls) return { kind: "class", name: cls[1] ?? null };
240
+ const identifier = IDENTIFIER_DEFAULT_RE.exec(tail);
241
+ if (identifier) return { kind: "identifier", name: identifier[1] };
242
+ return null;
243
+ }
244
+ function isDefaultExportIdentityRewrite(before, after) {
245
+ if (!before || !after) return false;
246
+ if (before.name === after.name) return false;
247
+ return isComponentShaped(before) && isComponentShaped(after);
248
+ }
249
+ function isComponentShaped(identity) {
250
+ return identity.name === null || /^[A-Z]/.test(identity.name);
251
+ }
252
+
253
+ // missed-change-sweep.ts
254
+ var MISSED_CHANGE_WATCHER_GRACE_MS = 1e3;
255
+ function createMissedChangeSweep(args) {
256
+ const now = args.now ?? Date.now;
257
+ const graceMs = args.watcherGraceMs ?? MISSED_CHANGE_WATCHER_GRACE_MS;
258
+ const lastSeenMtimeMs = /* @__PURE__ */ new Map();
259
+ return {
260
+ async sweep() {
261
+ const emitted = [];
262
+ for (const [file, modules] of args.listServedFiles()) {
263
+ const mtimeMs = await args.statMtimeMs(file);
264
+ if (mtimeMs === null) continue;
265
+ const previous = lastSeenMtimeMs.get(file);
266
+ if (previous === void 0 || mtimeMs <= previous) {
267
+ lastSeenMtimeMs.set(file, mtimeMs);
268
+ continue;
269
+ }
270
+ if (now() - mtimeMs < graceMs) continue;
271
+ lastSeenMtimeMs.set(file, mtimeMs);
272
+ let viteAlreadySawIt = false;
273
+ for (const module of modules) {
274
+ if ((module.lastInvalidationTimestamp ?? 0) >= mtimeMs) {
275
+ viteAlreadySawIt = true;
276
+ break;
277
+ }
278
+ }
279
+ if (viteAlreadySawIt) continue;
280
+ args.emitChange(file);
281
+ emitted.push(file);
282
+ }
283
+ return emitted;
284
+ }
285
+ };
286
+ }
287
+
220
288
  // index.ts
221
289
  var DEFAULT_INCLUDE = ["**/*.tsx", "**/*.jsx"];
222
290
  var DEFAULT_EXCLUDE = ["**/node_modules/**"];
223
291
  var ROOT_META_NAME = "tempo-project-root";
292
+ var SOURCE_IDENTITY_ROOT_META_NAME = "tempo-source-identity-root";
293
+ var INTERACT_PROJECTION_CLIENT_PATH = "/@tempo/interact-projection";
294
+ var INTERACT_PROJECTION_CLIENT_ID = "\0tempo:interact-projection";
295
+ var INTERACT_PROJECTION_BOOTSTRAP = `
296
+ (function() {
297
+ if (window.parent === window || (window.name !== ${JSON.stringify(TEMPO_INTERACT_FRAME_NAME)} && !window.name.startsWith(${JSON.stringify(`${TEMPO_INTERACT_FRAME_NAME}:`)}))) return;
298
+ window.__tempoInteractProjectionOwner = "vite";
299
+ var roots = new Map();
300
+ var existing = window.__REACT_DEVTOOLS_GLOBAL_HOOK__;
301
+ if (existing) {
302
+ if (existing.__tempoPendingFiberRoots) return;
303
+ existing.__tempoPendingFiberRoots = roots;
304
+ var originalCommit = existing.onCommitFiberRoot && existing.onCommitFiberRoot.bind(existing);
305
+ existing.onCommitFiberRoot = function(rendererId, root) {
306
+ if (existing.__tempoPendingFiberRoots === roots) roots.set(rendererId, root);
307
+ if (originalCommit) originalCommit.apply(null, arguments);
308
+ };
309
+ return;
310
+ }
311
+ window.__REACT_DEVTOOLS_GLOBAL_HOOK__ = {
312
+ supportsFiber: true,
313
+ renderers: new Map(),
314
+ __tempoPendingFiberRoots: roots,
315
+ inject: function(renderer) {
316
+ var id = this.renderers.size + 1;
317
+ this.renderers.set(id, renderer);
318
+ return id;
319
+ },
320
+ onCommitFiberRoot: function(rendererId, root) {
321
+ if (this.__tempoPendingFiberRoots === roots) roots.set(rendererId, root);
322
+ },
323
+ onCommitFiberUnmount: function() {},
324
+ checkDCE: function() {},
325
+ onScheduleFiberRoot: function() {}
326
+ };
327
+ })();`;
224
328
  function cleanModuleId(id) {
225
329
  return id.replace(/[?#].*$/, "");
226
330
  }
331
+ function isCanvasHostRequest(requestPath) {
332
+ const url = new URL(requestPath, "http://tempo.local");
333
+ return url.pathname.replace(/\/+$/, "") === "/tempo-host";
334
+ }
335
+ function isDeclarativeCanvasHostRequest(requestPath) {
336
+ if (!isCanvasHostRequest(requestPath)) return false;
337
+ const params = new URL(requestPath, "http://tempo.local").searchParams;
338
+ const canvasPath = params.get("canvasPath")?.trim() ?? params.get("pageFile")?.trim() ?? params.get("importPath")?.trim();
339
+ const storyboardId = params.get("storyboardId")?.trim() ?? params.get("exportName")?.trim() ?? params.get("importName")?.trim();
340
+ return !canvasPath || !storyboardId;
341
+ }
342
+ var MAX_UNRESOLVED_IMPORTS = 256;
343
+ var RELATIVE_IMPORT_RESOLVE_EXTENSIONS = [
344
+ ".mjs",
345
+ ".js",
346
+ ".mts",
347
+ ".ts",
348
+ ".jsx",
349
+ ".tsx",
350
+ ".json"
351
+ ];
352
+ var UNRESOLVED_IMPORT_WATCH_REARM_MS = 1e3;
353
+ function isRelativeImportSpecifier(specifier) {
354
+ return specifier.startsWith("./") || specifier.startsWith("../");
355
+ }
356
+ function barePackageName(specifier) {
357
+ if (!specifier || specifier.startsWith(".") || specifier.startsWith("/") || specifier.startsWith("\0") || specifier.startsWith("#") || specifier.includes(":")) {
358
+ return void 0;
359
+ }
360
+ const segments = specifier.split("/");
361
+ const packageName = specifier.startsWith("@") ? segments.length >= 2 && segments[0] !== "@" && segments[1] ? `${segments[0]}/${segments[1]}` : void 0 : segments[0];
362
+ return packageName && /^@?[A-Za-z0-9_][A-Za-z0-9._/-]*$/.test(packageName) ? packageName : void 0;
363
+ }
364
+ function resolvedIdMatchesFile(id, file) {
365
+ const resolvedFile = cleanModuleId(id).replace(/^\/@fs\//, "/");
366
+ try {
367
+ return realpathSync2.native(resolvedFile) === realpathSync2.native(file);
368
+ } catch {
369
+ return resolvedFile.replace(/\\/g, "/") === file.replace(/\\/g, "/");
370
+ }
371
+ }
372
+ function moduleIdsMatch(left, right) {
373
+ const normalize = (value) => cleanModuleId(value).replace(/^file:\/\//, "").replace(/^\/@fs\//, "/").replace(/\\/g, "/").replace(/^\/+/, "");
374
+ return normalize(left) === normalize(right);
375
+ }
227
376
  function resolveCanonicalRoot(root) {
228
377
  try {
229
378
  return realpathSync2.native(root);
@@ -234,6 +383,9 @@ function resolveCanonicalRoot(root) {
234
383
  function hasRootMetaTag(html) {
235
384
  return /<meta[^>]+name=["']tempo-project-root["'][^>]*>/i.test(html);
236
385
  }
386
+ function hasSourceIdentityRootMetaTag(html) {
387
+ return /<meta[^>]+name=["']tempo-source-identity-root["'][^>]*>/i.test(html);
388
+ }
237
389
  function createErrorServer() {
238
390
  const errorsByFile = /* @__PURE__ */ new Map();
239
391
  function getMostRecentError() {
@@ -265,7 +417,7 @@ function createErrorServer() {
265
417
  if (errorsByFile.size === 0) return;
266
418
  let changed = false;
267
419
  for (const errorKey of [...errorsByFile.keys()]) {
268
- if (errorKey === "unknown" || updatedPaths.some((p) => errorKey.endsWith(p) || p.endsWith(errorKey))) {
420
+ if (errorKey !== "unknown" && updatedPaths.some((path) => moduleIdsMatch(errorKey, path))) {
269
421
  errorsByFile.delete(errorKey);
270
422
  changed = true;
271
423
  }
@@ -280,14 +432,14 @@ function createErrorServer() {
280
432
  return server;
281
433
  }
282
434
  function readBody(req) {
283
- return new Promise((resolve, reject) => {
435
+ return new Promise((resolve2, reject) => {
284
436
  const chunks = [];
285
437
  req.on("data", (chunk) => chunks.push(chunk));
286
- req.on("end", () => resolve(Buffer.concat(chunks).toString()));
438
+ req.on("end", () => resolve2(Buffer.concat(chunks).toString()));
287
439
  req.on("error", reject);
288
440
  });
289
441
  }
290
- function handleErrorMiddleware(errorServer, req, res, next) {
442
+ function handleTempoMiddleware(errorServer, req, res, next) {
291
443
  const url = req.url;
292
444
  if (!url?.startsWith("/__tempo/")) return next();
293
445
  if (url === "/__tempo/report-error" && req.method === "POST") {
@@ -334,29 +486,397 @@ function handleErrorMiddleware(errorServer, req, res, next) {
334
486
  }
335
487
  next();
336
488
  }
489
+ var MISSED_CHANGE_SWEEP_INTERVAL_MS = 3e3;
490
+ function installMissedChangeSweep(server) {
491
+ const sweep = createMissedChangeSweep({
492
+ listServedFiles: () => (server.moduleGraph?.fileToModulesMap ?? /* @__PURE__ */ new Map()).entries(),
493
+ statMtimeMs: async (file) => {
494
+ try {
495
+ return statSync2(file).mtimeMs;
496
+ } catch {
497
+ return null;
498
+ }
499
+ },
500
+ emitChange: (file) => {
501
+ server.config?.logger?.info?.(
502
+ `[tempo] re-emitting lost watcher change: ${file}`,
503
+ { timestamp: true }
504
+ );
505
+ server.watcher?.emit?.("change", file);
506
+ }
507
+ });
508
+ let sweeping = false;
509
+ const timer = setInterval(() => {
510
+ if (sweeping) return;
511
+ sweeping = true;
512
+ void sweep.sweep().catch(() => {
513
+ }).finally(() => {
514
+ sweeping = false;
515
+ });
516
+ }, MISSED_CHANGE_SWEEP_INTERVAL_MS);
517
+ timer.unref?.();
518
+ server.httpServer?.once("close", () => clearInterval(timer));
519
+ }
337
520
  function tempoVitePlugin(options = {}) {
338
521
  const enabled = !!process.env.TEMPO;
339
522
  const include = options.include === void 0 ? DEFAULT_INCLUDE : options.include;
340
523
  const exclude = options.exclude === void 0 ? DEFAULT_EXCLUDE : options.exclude;
341
524
  const filter = createFilter(include, exclude);
342
525
  let canonicalRoot = process.cwd();
526
+ let sourceIdentityRoot = canonicalRoot;
343
527
  let command = "serve";
344
528
  const errorServer = createErrorServer();
529
+ const unresolvedImports = /* @__PURE__ */ new Map();
530
+ let devServer;
531
+ const unresolvedImportWatchers = /* @__PURE__ */ new Map();
532
+ let unresolvedImportResolutionScheduled = false;
533
+ let unresolvedImportResolutionRunning = false;
534
+ let rerunUnresolvedImportResolution = false;
535
+ let unresolvedImportWatchRearmTimer = null;
536
+ const processedUpdatePayloads = /* @__PURE__ */ new WeakSet();
537
+ const defaultExportIdentityByFile = /* @__PURE__ */ new Map();
538
+ const canonicalIdentityKey = (idOrFile) => {
539
+ const file = cleanModuleId(idOrFile).replace(/^\/@fs\//, "/");
540
+ try {
541
+ return realpathSync2.native(file);
542
+ } catch {
543
+ return file.replace(/\\/g, "/");
544
+ }
545
+ };
546
+ const repairDefaultExportIdentityRewrite = (file) => {
547
+ const key = canonicalIdentityKey(file);
548
+ const before = defaultExportIdentityByFile.get(key);
549
+ if (before === void 0) return false;
550
+ let source;
551
+ try {
552
+ source = readFileSync(file, "utf8");
553
+ } catch {
554
+ return false;
555
+ }
556
+ const after = readDefaultExportIdentity(source);
557
+ defaultExportIdentityByFile.set(key, after);
558
+ if (!isDefaultExportIdentityRewrite(before, after)) return false;
559
+ devServer?.ws.send({ type: "full-reload", path: "*" });
560
+ return true;
561
+ };
562
+ const rememberUnresolvedImport = (specifier, importer, packageName) => {
563
+ const key = `${importer}\0${specifier}`;
564
+ unresolvedImports.delete(key);
565
+ unresolvedImports.set(key, { specifier, importer, packageName });
566
+ while (unresolvedImports.size > MAX_UNRESOLVED_IMPORTS) {
567
+ const oldestKey = unresolvedImports.keys().next().value;
568
+ if (oldestKey === void 0) break;
569
+ unresolvedImports.delete(oldestKey);
570
+ }
571
+ syncUnresolvedImportWatcher();
572
+ };
573
+ const forgetUnresolvedImportsFrom = (file) => {
574
+ for (const [key, unresolved] of unresolvedImports) {
575
+ if (resolvedIdMatchesFile(unresolved.importer, file)) {
576
+ unresolvedImports.delete(key);
577
+ }
578
+ }
579
+ syncUnresolvedImportWatcher();
580
+ };
581
+ const closeUnresolvedImportWatcher = (path) => {
582
+ unresolvedImportWatchers.get(path)?.watcher.close();
583
+ unresolvedImportWatchers.delete(path);
584
+ };
585
+ const cancelUnresolvedImportWatchRearm = () => {
586
+ if (unresolvedImportWatchRearmTimer === null) return;
587
+ clearTimeout(unresolvedImportWatchRearmTimer);
588
+ unresolvedImportWatchRearmTimer = null;
589
+ };
590
+ const scheduleUnresolvedImportWatchRearm = () => {
591
+ if (unresolvedImportWatchRearmTimer !== null || !devServer || unresolvedImports.size === 0) {
592
+ return;
593
+ }
594
+ unresolvedImportWatchRearmTimer = setTimeout(() => {
595
+ unresolvedImportWatchRearmTimer = null;
596
+ if (devServer && unresolvedImports.size > 0) {
597
+ syncUnresolvedImportWatcher();
598
+ scheduleUnresolvedImportResolution();
599
+ }
600
+ }, UNRESOLVED_IMPORT_WATCH_REARM_MS);
601
+ unresolvedImportWatchRearmTimer.unref?.();
602
+ };
603
+ const closeUnresolvedImportWatchers = () => {
604
+ cancelUnresolvedImportWatchRearm();
605
+ for (const path of [...unresolvedImportWatchers.keys()]) {
606
+ closeUnresolvedImportWatcher(path);
607
+ }
608
+ };
609
+ const hasUnresolvedBarePackages = () => [...unresolvedImports.values()].some(
610
+ (unresolved) => unresolved.packageName !== void 0
611
+ );
612
+ const packageWatchTarget = (unresolved) => {
613
+ let candidate = dirname(cleanModuleId(unresolved.importer));
614
+ let nearestPackageRoot;
615
+ while (true) {
616
+ try {
617
+ if (statSync2(join(candidate, "node_modules")).isDirectory()) {
618
+ return join(candidate, "node_modules", unresolved.packageName);
619
+ }
620
+ } catch {
621
+ }
622
+ if (nearestPackageRoot === void 0) {
623
+ try {
624
+ if (statSync2(join(candidate, "package.json")).isFile()) {
625
+ nearestPackageRoot = candidate;
626
+ }
627
+ } catch {
628
+ }
629
+ }
630
+ const parent = dirname(candidate);
631
+ if (parent === candidate) break;
632
+ candidate = parent;
633
+ }
634
+ return join(
635
+ nearestPackageRoot ?? canonicalRoot,
636
+ "node_modules",
637
+ unresolved.packageName
638
+ );
639
+ };
640
+ const unresolvedImportWatchTarget = (unresolved) => {
641
+ return unresolved.packageName ? packageWatchTarget(
642
+ unresolved
643
+ ) : resolve(
644
+ dirname(cleanModuleId(unresolved.importer)),
645
+ cleanModuleId(unresolved.specifier)
646
+ );
647
+ };
648
+ const nearestExistingDirectory = (target) => {
649
+ let candidate = target;
650
+ while (true) {
651
+ try {
652
+ if (statSync2(candidate).isDirectory()) return candidate;
653
+ } catch {
654
+ }
655
+ const parent = dirname(candidate);
656
+ if (parent === candidate) return void 0;
657
+ candidate = parent;
658
+ }
659
+ };
660
+ function syncUnresolvedImportWatcher() {
661
+ if (!devServer || unresolvedImports.size === 0) {
662
+ closeUnresolvedImportWatchers();
663
+ return;
664
+ }
665
+ const desired = /* @__PURE__ */ new Map();
666
+ for (const unresolved of unresolvedImports.values()) {
667
+ const target = unresolvedImportWatchTarget(unresolved);
668
+ const watchPath = nearestExistingDirectory(target);
669
+ if (!watchPath) continue;
670
+ const previous = desired.get(watchPath);
671
+ desired.set(watchPath, {
672
+ recursive: previous?.recursive === true || watchPath === target
673
+ });
674
+ }
675
+ for (const [path, existing] of [...unresolvedImportWatchers]) {
676
+ const next = desired.get(path);
677
+ if (!next || next.recursive !== existing.recursive) {
678
+ closeUnresolvedImportWatcher(path);
679
+ }
680
+ }
681
+ for (const [path, options2] of desired) {
682
+ if (unresolvedImportWatchers.has(path)) continue;
683
+ try {
684
+ const watcher = watchFileSystem(
685
+ path,
686
+ { recursive: options2.recursive },
687
+ scheduleUnresolvedImportResolution
688
+ );
689
+ unresolvedImportWatchers.set(path, {
690
+ watcher,
691
+ recursive: options2.recursive
692
+ });
693
+ watcher.on("error", () => {
694
+ closeUnresolvedImportWatcher(path);
695
+ scheduleUnresolvedImportWatchRearm();
696
+ });
697
+ if (options2.recursive) scheduleUnresolvedImportResolution();
698
+ } catch {
699
+ closeUnresolvedImportWatcher(path);
700
+ scheduleUnresolvedImportWatchRearm();
701
+ }
702
+ }
703
+ if ([...desired.keys()].every((path) => unresolvedImportWatchers.has(path))) {
704
+ cancelUnresolvedImportWatchRearm();
705
+ }
706
+ }
707
+ function scheduleUnresolvedImportResolution() {
708
+ if (unresolvedImportResolutionScheduled || unresolvedImportResolutionRunning) {
709
+ rerunUnresolvedImportResolution = true;
710
+ return;
711
+ }
712
+ unresolvedImportResolutionScheduled = true;
713
+ queueMicrotask(() => {
714
+ unresolvedImportResolutionScheduled = false;
715
+ void runUnresolvedImportResolution();
716
+ });
717
+ }
718
+ async function runUnresolvedImportResolution() {
719
+ const server = devServer;
720
+ if (!server || unresolvedImportResolutionRunning) return;
721
+ unresolvedImportResolutionRunning = true;
722
+ try {
723
+ do {
724
+ rerunUnresolvedImportResolution = false;
725
+ syncUnresolvedImportWatcher();
726
+ let resolvedImportInPass = false;
727
+ for (const [key, unresolved] of [...unresolvedImports]) {
728
+ let file;
729
+ if (isRelativeImportSpecifier(unresolved.specifier)) {
730
+ const suffixIndex = unresolved.specifier.search(/[?#]/);
731
+ const relativePath = suffixIndex < 0 ? unresolved.specifier : unresolved.specifier.slice(0, suffixIndex);
732
+ const candidate = resolve(
733
+ dirname(cleanModuleId(unresolved.importer)),
734
+ relativePath
735
+ );
736
+ const probes = [
737
+ candidate,
738
+ ...RELATIVE_IMPORT_RESOLVE_EXTENSIONS.map(
739
+ (extension) => `${candidate}${extension}`
740
+ ),
741
+ ...RELATIVE_IMPORT_RESOLVE_EXTENSIONS.map(
742
+ (extension) => join(candidate, `index${extension}`)
743
+ )
744
+ ];
745
+ for (const probe of probes) {
746
+ try {
747
+ if (statSync2(probe).isFile()) {
748
+ file = probe;
749
+ break;
750
+ }
751
+ } catch {
752
+ }
753
+ }
754
+ }
755
+ if (!file && unresolved.packageName) {
756
+ try {
757
+ file = createRequire(cleanModuleId(unresolved.importer)).resolve(
758
+ unresolved.specifier
759
+ );
760
+ } catch {
761
+ }
762
+ }
763
+ if (!file) continue;
764
+ server.watcher.add(file);
765
+ unresolvedImports.delete(key);
766
+ errorServer.clearErrorForModules([unresolved.importer]);
767
+ resolvedImportInPass = true;
768
+ }
769
+ if (resolvedImportInPass) {
770
+ server.ws.send({ type: "full-reload", path: "*" });
771
+ }
772
+ syncUnresolvedImportWatcher();
773
+ } while (rerunUnresolvedImportResolution);
774
+ } finally {
775
+ unresolvedImportResolutionRunning = false;
776
+ }
777
+ }
345
778
  return {
346
779
  name: "tempo-annotate",
780
+ apply: "serve",
347
781
  enforce: "pre",
782
+ resolveId: {
783
+ order: "pre",
784
+ async handler(id, importer, resolveOptions) {
785
+ if (id === INTERACT_PROJECTION_CLIENT_PATH) {
786
+ return INTERACT_PROJECTION_CLIENT_ID;
787
+ }
788
+ if (enabled && importer && !importer.startsWith("\0")) {
789
+ const packageName = barePackageName(id);
790
+ if (!isRelativeImportSpecifier(id) && !packageName) return null;
791
+ try {
792
+ const resolved = await this.resolve(id, importer, {
793
+ ...resolveOptions,
794
+ skipSelf: true
795
+ });
796
+ if (!resolved) rememberUnresolvedImport(id, importer, packageName);
797
+ return resolved;
798
+ } catch (error) {
799
+ rememberUnresolvedImport(id, importer, packageName);
800
+ throw error;
801
+ }
802
+ }
803
+ return null;
804
+ }
805
+ },
806
+ load(id) {
807
+ if (id === INTERACT_PROJECTION_CLIENT_ID) {
808
+ return `let stop;
809
+ let disposed = false;
810
+ if (window.parent !== window && (window.name === ${JSON.stringify(TEMPO_INTERACT_FRAME_NAME)} || window.name.startsWith(${JSON.stringify(`${TEMPO_INTERACT_FRAME_NAME}:`)}))) {
811
+ window.__tempoInteractProjectionOwner = "vite";
812
+ void import("tempo-sdk/canvas/interact-projection").then(({ installTempoInteractProjectionSource }) => {
813
+ if (disposed) return;
814
+ stop = installTempoInteractProjectionSource();
815
+ });
816
+ }
817
+ if (import.meta.hot) import.meta.hot.dispose(() => {
818
+ disposed = true;
819
+ stop?.();
820
+ });`;
821
+ }
822
+ return null;
823
+ },
348
824
  // Expose error server for testing
349
825
  _tempoErrorServer: errorServer,
826
+ _tempoUnresolvedImportState: {
827
+ get size() {
828
+ return unresolvedImports.size;
829
+ },
830
+ get barePackageCount() {
831
+ return [...unresolvedImports.values()].filter(
832
+ (unresolved) => unresolved.packageName !== void 0
833
+ ).length;
834
+ },
835
+ get hasBarePackageWatcher() {
836
+ return unresolvedImportWatchers.size > 0 && hasUnresolvedBarePackages();
837
+ },
838
+ get barePackageWatchPath() {
839
+ return hasUnresolvedBarePackages() ? unresolvedImportWatchers.keys().next().value : void 0;
840
+ },
841
+ get hasUnresolvedImportWatcher() {
842
+ return unresolvedImportWatchers.size > 0;
843
+ },
844
+ get unresolvedImportWatchPath() {
845
+ return unresolvedImportWatchers.keys().next().value;
846
+ },
847
+ get unresolvedImportWatchPaths() {
848
+ return [...unresolvedImportWatchers.keys()];
849
+ },
850
+ get hasUnresolvedImportWatchRearm() {
851
+ return unresolvedImportWatchRearmTimer !== null;
852
+ },
853
+ emitUnresolvedImportWatcherErrorForTesting() {
854
+ for (const { watcher } of unresolvedImportWatchers.values()) {
855
+ watcher.emit(
856
+ "error",
857
+ new Error("Simulated unresolved-import watcher failure")
858
+ );
859
+ }
860
+ }
861
+ },
350
862
  configResolved(resolvedConfig) {
351
863
  if (!enabled) return;
352
864
  command = resolvedConfig.command;
353
865
  canonicalRoot = resolveCanonicalRoot(resolvedConfig.root);
866
+ sourceIdentityRoot = options.sourceIdentityRoot ? resolveCanonicalRoot(
867
+ resolve(resolvedConfig.root, options.sourceIdentityRoot)
868
+ ) : canonicalRoot;
354
869
  },
355
870
  configureServer(server) {
356
871
  if (!enabled) return;
872
+ devServer = server;
873
+ syncUnresolvedImportWatcher();
874
+ server.watcher?.once?.("close", closeUnresolvedImportWatchers);
875
+ server.httpServer?.once("close", closeUnresolvedImportWatchers);
357
876
  server.middlewares.use((req, res, next) => {
358
- handleErrorMiddleware(errorServer, req, res, next);
877
+ handleTempoMiddleware(errorServer, req, res, next);
359
878
  });
879
+ installMissedChangeSweep(server);
360
880
  const interceptHmrSend = (target) => {
361
881
  const orig = target.send.bind(target);
362
882
  target.send = ((...args) => {
@@ -374,7 +894,8 @@ function tempoVitePlugin(options = {}) {
374
894
  plugin: err?.plugin,
375
895
  loc: err?.loc
376
896
  });
377
- } else if (typed.type === "update") {
897
+ } else if (typed.type === "update" && !processedUpdatePayloads.has(payload)) {
898
+ processedUpdatePayloads.add(payload);
378
899
  const updates = typed.updates;
379
900
  const paths = updates?.map((u) => u.path).filter((p) => typeof p === "string") ?? [];
380
901
  errorServer.clearErrorForModules(paths);
@@ -389,23 +910,78 @@ function tempoVitePlugin(options = {}) {
389
910
  interceptHmrSend(clientHot);
390
911
  }
391
912
  },
392
- transformIndexHtml(html) {
393
- if (!enabled || command !== "serve") {
394
- return;
913
+ closeBundle() {
914
+ devServer = void 0;
915
+ closeUnresolvedImportWatchers();
916
+ },
917
+ hotUpdate: {
918
+ order: "post",
919
+ handler(context) {
920
+ if (this.environment.name !== "client") return;
921
+ if (context.type !== "create") {
922
+ forgetUnresolvedImportsFrom(context.file);
923
+ }
924
+ if (context.type === "delete") {
925
+ defaultExportIdentityByFile.delete(
926
+ canonicalIdentityKey(context.file)
927
+ );
928
+ return;
929
+ }
930
+ if (context.type === "update" && repairDefaultExportIdentityRewrite(context.file)) {
931
+ return [];
932
+ }
933
+ }
934
+ },
935
+ // Vite 5 compatibility. Vite 6+ prefers `hotUpdate` above.
936
+ handleHotUpdate: {
937
+ order: "post",
938
+ handler(context) {
939
+ forgetUnresolvedImportsFrom(context.file);
940
+ if (repairDefaultExportIdentityRewrite(context.file)) {
941
+ return [];
942
+ }
395
943
  }
396
- if (hasRootMetaTag(html)) {
944
+ },
945
+ transformIndexHtml(html, context) {
946
+ if (!enabled || command !== "serve") {
397
947
  return;
398
948
  }
399
- return [
400
- {
949
+ const tags = [];
950
+ if (!hasRootMetaTag(html)) {
951
+ tags.push({
401
952
  tag: "meta",
402
953
  attrs: {
403
954
  name: ROOT_META_NAME,
404
955
  content: canonicalRoot
405
956
  },
406
957
  injectTo: "head"
407
- }
408
- ];
958
+ });
959
+ }
960
+ if (!hasSourceIdentityRootMetaTag(html)) {
961
+ tags.push({
962
+ tag: "meta",
963
+ attrs: {
964
+ name: SOURCE_IDENTITY_ROOT_META_NAME,
965
+ content: sourceIdentityRoot
966
+ },
967
+ injectTo: "head"
968
+ });
969
+ }
970
+ const requestPath = context?.originalUrl ?? context?.path;
971
+ const isDeclarativeCanvasHost = requestPath ? isDeclarativeCanvasHostRequest(requestPath) : false;
972
+ if (requestPath && !isDeclarativeCanvasHost) {
973
+ tags.push({
974
+ tag: "script",
975
+ children: INTERACT_PROJECTION_BOOTSTRAP,
976
+ injectTo: "head-prepend"
977
+ });
978
+ tags.push({
979
+ tag: "script",
980
+ attrs: { type: "module", src: INTERACT_PROJECTION_CLIENT_PATH },
981
+ injectTo: "head-prepend"
982
+ });
983
+ }
984
+ return tags.length > 0 ? tags : void 0;
409
985
  },
410
986
  transform(source, id) {
411
987
  if (!enabled || command === "build") {
@@ -421,7 +997,12 @@ function tempoVitePlugin(options = {}) {
421
997
  try {
422
998
  const filepath = relative2(canonicalRoot, cleanId);
423
999
  const modifiedtsMs = Math.trunc(statSync2(cleanId).mtimeMs);
424
- const sourceVersion = sourceVersionHash(source);
1000
+ const rawSource = readFileSync(cleanId, "utf8");
1001
+ const sourceVersion = sourceVersionHash(rawSource);
1002
+ defaultExportIdentityByFile.set(
1003
+ canonicalIdentityKey(cleanId),
1004
+ readDefaultExportIdentity(rawSource)
1005
+ );
425
1006
  const result = annotateFile(
426
1007
  source,
427
1008
  cleanId,