tempo-sdk 0.0.22 → 0.0.24

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.
@@ -139,6 +139,10 @@ function tempoNextjsPlugin(pluginOptions = {}) {
139
139
  ...inputConfig,
140
140
  webpack: webpackHook
141
141
  };
142
+ const distDirOverride = process.env.TEMPO_NEXT_DIST_DIR;
143
+ if (distDirOverride) {
144
+ next.distDir = distDirOverride;
145
+ }
142
146
  if (!omitTurbopack) {
143
147
  if (useExperimental) {
144
148
  next.experimental = {
@@ -170,4 +174,4 @@ export {
170
174
  nextjs_default,
171
175
  _internal
172
176
  };
173
- //# sourceMappingURL=chunk-BRNAFXET.js.map
177
+ //# sourceMappingURL=chunk-GLTGROU6.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../nextjs.ts"],"sourcesContent":["/**\n * Next.js plugin that registers the tempo-annotate loader for Webpack and\n * Turbopack. Mirrors the user-facing pattern of `@next/mdx`: a higher-order\n * function that takes plugin options, returns a function that takes the user's\n * `next.config`, and returns a new config with the plugin's loader rules\n * merged in.\n *\n * See SPEC_NEXTJS.md (in this directory) for the full design rationale.\n *\n * @example\n * ```js\n * // next.config.js\n * const tempoNextjsPlugin = require(\"tempo-sdk/nextjs\");\n * module.exports = tempoNextjsPlugin()({ reactStrictMode: true });\n * ```\n */\n\nimport { existsSync, realpathSync } from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport { dirname, resolve } from \"node:path\";\n\nimport type { ElementInfo, PropValue } from \"@modules/annotation\";\n\n// ---------------------------------------------------------------------------\n// Types. We keep these minimal and self-contained rather than depending on\n// Next.js types — the plugin file is loaded by `next.config.js` evaluation,\n// before `next` itself is fully resolved in some environments.\n// ---------------------------------------------------------------------------\n\nexport type ComputeAnnotatedProps = (\n info: ElementInfo,\n filepath: string,\n modifiedtsMs: number,\n) => Record<string, PropValue>;\n\nexport interface TempoNextjsOptions {\n /** Path to a JS/TS module that default-exports a `ComputeAnnotatedProps`\n * function. Resolved relative to the project root (CWD where the user\n * invokes `next dev` / `next build`). Turbopack does not allow function-\n * valued loader options, so this must be a path. */\n computeAnnotatedPropsModule?: string;\n\n /** File patterns to include. Default: `[\"**\\/*.tsx\", \"**\\/*.jsx\"]`. */\n include?: string | RegExp | Array<string | RegExp>;\n\n /** File patterns to exclude. Default: `[\"**\\/node_modules\\/**\"]`. */\n exclude?: string | RegExp | Array<string | RegExp>;\n\n /** Auto-inject `<meta name=\"tempo-project-root\">` into JSX `<head>`.\n * Default: `true`. */\n autoInjectRootMeta?: boolean;\n\n /** Run the loader during production builds too. Default: `false`. */\n productionBuild?: boolean;\n}\n\ninterface TurbopackRule {\n condition?: unknown;\n loaders?: Array<{ loader: string; options?: unknown } | string>;\n}\n\ninterface TurbopackConfig {\n rules?: Record<string, TurbopackRule | TurbopackRule[]>;\n [key: string]: unknown;\n}\n\ninterface NextConfigLike {\n webpack?:\n | ((\n config: unknown,\n context: { dev: boolean; [k: string]: unknown },\n ) => unknown)\n | null;\n turbopack?: TurbopackConfig;\n experimental?: { turbo?: TurbopackConfig; [k: string]: unknown };\n [key: string]: unknown;\n}\n\ntype NextConfigInput = NextConfigLike | undefined;\n\ninterface WebpackHookContext {\n dev: boolean;\n [key: string]: unknown;\n}\n\ninterface WebpackConfigLike {\n module?: { rules?: unknown[] };\n [key: string]: unknown;\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nconst TURBOPACK_RULE_KEY = \"*.{tsx,jsx}\";\n\nconst requireFromHere = createRequire(\n typeof import.meta.url === \"string\" && import.meta.url.length > 0\n ? import.meta.url\n : __filename,\n);\n\nfunction resolveLoaderPath(): string {\n // Production: dist/nextjs.{js,cjs} sits next to dist/nextjs-loader.cjs.\n // Development: source nextjs.ts sits at <pkg>/nextjs.ts; the built\n // loader is at <pkg>/dist/nextjs-loader.cjs. Try both so unit tests\n // running directly against the .ts source file still find the loader.\n for (const candidate of [\"./nextjs-loader.cjs\", \"./dist/nextjs-loader.cjs\"]) {\n try {\n return requireFromHere.resolve(candidate);\n } catch {\n // try next candidate\n }\n }\n throw new Error(\n \"tempo-sdk/nextjs: could not resolve nextjs-loader.cjs. \" +\n \"Run `pnpm build` in the tempo-sdk package to produce the dist/ output.\",\n );\n}\n\ninterface NextVersionInfo {\n major: number;\n minor: number;\n}\n\nfunction detectNextVersion(): NextVersionInfo | null {\n try {\n const pkg = requireFromHere(\"next/package.json\") as { version: string };\n const m = /^(\\d+)\\.(\\d+)/.exec(pkg.version);\n if (!m) return null;\n return { major: Number(m[1]), minor: Number(m[2]) };\n } catch {\n return null;\n }\n}\n\n/** Should the wrapper write to `experimental.turbo` instead of `turbopack`? */\nfunction useExperimentalTurbo(version: NextVersionInfo | null): boolean {\n if (!version) return false;\n if (version.major < 15) return true;\n if (version.major === 15 && version.minor < 3) return true;\n return false;\n}\n\n/** Should the wrapper omit Turbopack registration entirely? Some pre-13 versions\n * error on unknown config keys. */\nfunction shouldOmitTurbopack(version: NextVersionInfo | null): boolean {\n if (!version) return false;\n return version.major < 13;\n}\n\nfunction buildTurbopackRule(\n loaderPath: string,\n options: TempoNextjsOptions,\n): TurbopackRule {\n const loaderOptions: Record<string, unknown> = {};\n if (options.computeAnnotatedPropsModule !== undefined) {\n loaderOptions.computeAnnotatedPropsModule =\n options.computeAnnotatedPropsModule;\n }\n if (options.autoInjectRootMeta !== undefined) {\n loaderOptions.autoInjectRootMeta = options.autoInjectRootMeta;\n }\n\n // {all: [{not: \"foreign\"}, \"development\"]} — exclude node_modules / Next\n // internals AND only run during `next dev`. The \"development\" condition is\n // a Turbopack built-in; it matches both `next dev` and `next build` in dev\n // mode but is inert during a production `next build`.\n const condition = options.productionBuild\n ? { not: \"foreign\" }\n : { all: [{ not: \"foreign\" }, \"development\"] };\n\n return {\n condition,\n loaders: [{ loader: loaderPath, options: loaderOptions }],\n };\n}\n\nfunction mergeTurbopackRules(\n existing: TurbopackConfig | undefined,\n newRule: TurbopackRule,\n): TurbopackConfig {\n const existingRule = existing?.rules?.[TURBOPACK_RULE_KEY];\n let mergedRule: TurbopackRule | TurbopackRule[];\n if (!existingRule) {\n mergedRule = newRule;\n } else if (Array.isArray(existingRule)) {\n mergedRule = [...existingRule, newRule];\n } else {\n mergedRule = [existingRule, newRule];\n }\n return {\n ...existing,\n rules: {\n ...existing?.rules,\n [TURBOPACK_RULE_KEY]: mergedRule,\n },\n };\n}\n\nfunction buildWebpackHook(\n loaderPath: string,\n options: TempoNextjsOptions,\n userWebpack: NextConfigLike[\"webpack\"],\n): NonNullable<NextConfigLike[\"webpack\"]> {\n const loaderOptions: Record<string, unknown> = {};\n if (options.computeAnnotatedPropsModule !== undefined) {\n loaderOptions.computeAnnotatedPropsModule =\n options.computeAnnotatedPropsModule;\n }\n if (options.autoInjectRootMeta !== undefined) {\n loaderOptions.autoInjectRootMeta = options.autoInjectRootMeta;\n }\n\n const allowProduction = options.productionBuild === true;\n\n return (configIn, context) => {\n const config = configIn as WebpackConfigLike;\n const ctx = context as WebpackHookContext;\n if (ctx.dev || allowProduction) {\n config.module ??= {};\n config.module.rules ??= [];\n config.module.rules.push({\n test: /\\.(tsx|jsx)$/,\n exclude: /node_modules/,\n enforce: \"pre\",\n use: [{ loader: loaderPath, options: loaderOptions }],\n });\n }\n if (typeof userWebpack === \"function\") {\n return userWebpack(config, context);\n }\n return config;\n };\n}\n\n// ---------------------------------------------------------------------------\n// tempoProjectRoot — sync helper for Pages Router users (Section 6.4)\n// ---------------------------------------------------------------------------\n\nlet cachedTempoProjectRoot: string | null = null;\n\n/**\n * Returns the canonical project root that the Tempo loader uses to compute\n * `data-tempo-filepath` values. Use this in `pages/_document.tsx` to set the\n * content of `<meta name=\"tempo-project-root\">`, ensuring the manual meta tag\n * value matches what the loader produces.\n */\nexport function tempoProjectRoot(): string {\n if (cachedTempoProjectRoot !== null) return cachedTempoProjectRoot;\n\n // Walk upward from CWD looking for the nearest package.json. CWD is what\n // Next.js itself uses as the project root when the user invokes\n // `next dev` / `next build` — the loader's `rootContext` matches.\n let dir = process.cwd();\n // eslint-disable-next-line no-constant-condition\n while (true) {\n if (existsSync(resolve(dir, \"package.json\"))) break;\n const parent = dirname(dir);\n if (parent === dir) break;\n dir = parent;\n }\n let canonical = dir;\n try {\n canonical = realpathSync.native(dir);\n } catch {\n // Keep `dir` as fallback.\n }\n cachedTempoProjectRoot = canonical;\n return canonical;\n}\n\n/** Reset the cached project root. For tests only. */\nexport function _resetTempoProjectRoot(): void {\n cachedTempoProjectRoot = null;\n}\n\n// ---------------------------------------------------------------------------\n// tempoNextjsPlugin — the wrapper\n// ---------------------------------------------------------------------------\n\n/**\n * Higher-order function that wraps a Next.js config to register the\n * tempo-annotate loader with both Webpack and Turbopack. No-op when\n * `process.env.TEMPO` is not set.\n *\n * @example\n * ```js\n * // next.config.js\n * const tempoNextjsPlugin = require(\"tempo-sdk/nextjs\");\n * module.exports = tempoNextjsPlugin()({ reactStrictMode: true });\n * ```\n */\nexport function tempoNextjsPlugin(\n pluginOptions: TempoNextjsOptions = {},\n): (inputConfig?: NextConfigLike) => NextConfigLike {\n return (inputConfigArg?: NextConfigLike): NextConfigLike => {\n const inputConfig: NextConfigLike = inputConfigArg ?? {};\n\n if (!process.env.TEMPO) return inputConfig;\n\n // Routed through `_internal.*` so unit tests can spy on these helpers\n // without rewiring the imports.\n const loaderPath = _internal.resolveLoaderPath();\n const version = _internal.detectNextVersion();\n const omitTurbopack = _internal.shouldOmitTurbopack(version);\n const useExperimental = _internal.useExperimentalTurbo(version);\n\n const newRule = buildTurbopackRule(loaderPath, pluginOptions);\n\n const existingTurbo = useExperimental\n ? inputConfig.experimental?.turbo\n : inputConfig.turbopack;\n const mergedTurbo = mergeTurbopackRules(existingTurbo, newRule);\n\n const webpackHook = buildWebpackHook(\n loaderPath,\n pluginOptions,\n inputConfig.webpack ?? null,\n );\n\n const next: NextConfigLike = {\n ...inputConfig,\n webpack: webpackHook,\n };\n\n // Dev-lock sidestep: Next.js 16 holds an OS file lock at `<distDir>/lock`\n // while `next dev` runs, and a second launch in the same directory aborts\n // with \"Another next dev server is already running\". When an orphaned\n // canvas host from a dead Tempo session holds that lock and cannot be\n // killed, the supervisor relaunches with TEMPO_NEXT_DIST_DIR pointing at a\n // fresh directory — a lock nobody holds, and a build cache the orphan\n // isn't sharing. Only the Tempo-managed canvas host ever sets this env.\n const distDirOverride = process.env.TEMPO_NEXT_DIST_DIR;\n if (distDirOverride) {\n next.distDir = distDirOverride;\n }\n\n if (!omitTurbopack) {\n if (useExperimental) {\n next.experimental = {\n ...inputConfig.experimental,\n turbo: mergedTurbo,\n };\n } else {\n next.turbopack = mergedTurbo;\n }\n }\n\n return next;\n };\n}\n\nexport default tempoNextjsPlugin;\n\n// ---------------------------------------------------------------------------\n// Type re-exports for users writing custom strategies.\n// ---------------------------------------------------------------------------\n\nexport type { ElementInfo, PropValue } from \"@modules/annotation\";\n\n// Internal exports used by tests.\nexport const _internal = {\n buildTurbopackRule,\n mergeTurbopackRules,\n buildWebpackHook,\n detectNextVersion,\n useExperimentalTurbo,\n shouldOmitTurbopack,\n resolveLoaderPath,\n};\n"],"mappings":";AAiBA,SAAS,YAAY,oBAAoB;AACzC,SAAS,qBAAqB;AAC9B,SAAS,SAAS,eAAe;AA2EjC,IAAM,qBAAqB;AAE3B,IAAM,kBAAkB;AAAA,EACtB,OAAO,YAAY,QAAQ,YAAY,YAAY,IAAI,SAAS,IAC5D,YAAY,MACZ;AACN;AAEA,SAAS,oBAA4B;AAKnC,aAAW,aAAa,CAAC,uBAAuB,0BAA0B,GAAG;AAC3E,QAAI;AACF,aAAO,gBAAgB,QAAQ,SAAS;AAAA,IAC1C,QAAQ;AAAA,IAER;AAAA,EACF;AACA,QAAM,IAAI;AAAA,IACR;AAAA,EAEF;AACF;AAOA,SAAS,oBAA4C;AACnD,MAAI;AACF,UAAM,MAAM,gBAAgB,mBAAmB;AAC/C,UAAM,IAAI,gBAAgB,KAAK,IAAI,OAAO;AAC1C,QAAI,CAA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I,MAAO,QAAO;AAI/B,UAAM,aAAa,UAAU,kBAAkB;AAC/C,UAAM,UAAU,UAAU,kBAAkB;AAC5C,UAAM,gBAAgB,UAAU,oBAAoB,OAAO;AAC3D,UAAM,kBAAkB,UAAU,qBAAqB,OAAO;AAE9D,UAAM,UAAU,mBAAmB,YAAY,aAAa;AAE5D,UAAM,gBAAgB,kBAClB,YAAY,cAAc,QAC1B,YAAY;AAChB,UAAM,cAAc,oBAAoB,eAAe,OAAO;AAE9D,UAAM,cAAc;AAAA,MAClB;AAAA,MACA;AAAA,MACA,YAAY,WAAW;AAAA,IACzB;AAEA,UAAM,OAAuB;AAAA,MAC3B,GAAG;AAAA,MACH,SAAS;AAAA,IACX;AASA,UAAM,kBAAkB,QAAQ,IAAI;AACpC,QAAI,iBAAiB;AACnB,WAAK,UAAU;AAAA,IACjB;AAEA,QAAI,CAAC,eAAe;AAClB,UAAI,iBAAiB;AACnB,aAAK,eAAe;AAAA,UAClB,GAAG,YAAY;AAAA,UACf,OAAO;AAAA,QACT;AAAA,MACF,OAAO;AACL,aAAK,YAAY;AAAA,MACnB;AAAA,IACF;AAEA,WAAO;AAAA,EACT;AACF;AAEA,IAAO,iBAAQ;AASR,IAAM,YAAY;AAAA,EACvB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;","names":[]}
package/dist/index.d.ts CHANGED
@@ -2,7 +2,7 @@ import { ServerResponse, IncomingMessage } from 'node:http';
2
2
  import { FilterPattern } from '@rollup/pluginutils';
3
3
  import { Plugin } from 'vite';
4
4
  import { JSXElement } from 'oxc-parser';
5
- export { S as StoryboardLayout, T as TempoCanvasConfig, a as TempoHtmlStoryboard, b as TempoPage, c as TempoRouteStoryboard, d as TempoStoryboard } from './page-BUbHO0BI.js';
5
+ export { S as StoryboardLayout, T as TempoCanvasConfig, a as TempoHtmlStoryboard, b as TempoPage, c as TempoRouteStoryboard, d as TempoStoryboard } from './page-xi1aI5a7.js';
6
6
  import 'react';
7
7
 
8
8
  interface ElementInfo {
package/dist/index.js CHANGED
@@ -4,6 +4,7 @@ import {
4
4
 
5
5
  // index.ts
6
6
  import {
7
+ existsSync,
7
8
  readFileSync,
8
9
  realpathSync as realpathSync2,
9
10
  statSync as statSync2,
@@ -11,6 +12,7 @@ import {
11
12
  } from "fs";
12
13
  import { createRequire } from "module";
13
14
  import { dirname, isAbsolute, join, relative as relative2, resolve } from "path";
15
+ import { fileURLToPath } from "url";
14
16
  import { createFilter } from "@rollup/pluginutils";
15
17
 
16
18
  // ../../modules/annotation/annotate-file.ts
@@ -369,6 +371,20 @@ function createRapidHotUpdateReplay(options) {
369
371
  const schedule = options?.schedule ?? setTimeout;
370
372
  const cancel = options?.cancel ?? clearTimeout;
371
373
  const bursts = /* @__PURE__ */ new Map();
374
+ const armGate = (burst, previous) => {
375
+ if (burst.eventCount < 2) return;
376
+ if (previous?.gate && previous.release) {
377
+ burst.gate = previous.gate;
378
+ burst.release = previous.release;
379
+ previous.release = void 0;
380
+ if (previous.expiry) cancel(previous.expiry);
381
+ } else {
382
+ burst.gate = new Promise((resolve2) => {
383
+ burst.release = resolve2;
384
+ });
385
+ }
386
+ burst.expiry = schedule(() => burst.release?.(), quietMs * 2);
387
+ };
372
388
  return {
373
389
  observe(file, replay) {
374
390
  const previous = bursts.get(file);
@@ -377,11 +393,17 @@ function createRapidHotUpdateReplay(options) {
377
393
  eventCount: (previous?.eventCount ?? 0) + 1,
378
394
  replay
379
395
  };
396
+ armGate(burst, previous);
380
397
  burst.timer = schedule(() => {
381
398
  if (bursts.get(file) !== burst) return;
382
399
  bursts.delete(file);
400
+ if (burst.expiry) cancel(burst.expiry);
401
+ burst.release?.();
383
402
  if (burst.eventCount < 2) return;
384
- const replayAllowance = { eventCount: -1, replay: burst.replay };
403
+ const replayAllowance = {
404
+ eventCount: -1,
405
+ replay: burst.replay
406
+ };
385
407
  replayAllowance.timer = schedule(() => {
386
408
  if (bursts.get(file) === replayAllowance) bursts.delete(file);
387
409
  }, quietMs);
@@ -390,15 +412,133 @@ function createRapidHotUpdateReplay(options) {
390
412
  }, quietMs);
391
413
  bursts.set(file, burst);
392
414
  },
415
+ settled(file) {
416
+ return bursts.get(file)?.gate ?? Promise.resolve();
417
+ },
393
418
  clear() {
394
419
  for (const burst of bursts.values()) {
395
420
  if (burst.timer) cancel(burst.timer);
421
+ if (burst.expiry) cancel(burst.expiry);
422
+ burst.release?.();
396
423
  }
397
424
  bursts.clear();
398
425
  }
399
426
  };
400
427
  }
401
428
 
429
+ // tailwind-scan-net.ts
430
+ var SCANNABLE_EXTENSIONS = /* @__PURE__ */ new Set([
431
+ "ts",
432
+ "tsx",
433
+ "js",
434
+ "jsx",
435
+ "mjs",
436
+ "cjs",
437
+ "html",
438
+ "mdx",
439
+ "md",
440
+ "svelte",
441
+ "vue",
442
+ "astro"
443
+ ]);
444
+ var IGNORED_PATH_SEGMENTS = [
445
+ "/node_modules/",
446
+ "/.git/",
447
+ "/.vite/",
448
+ "/.tempo/"
449
+ ];
450
+ var TAILWIND_SCAN_NET_DEBOUNCE_MS = 100;
451
+ var TAILWIND_SCAN_NET_MAX_POKES_PER_PAIR = 2;
452
+ var POKE_LEDGER_MAX_ENTRIES = 2e4;
453
+ function normalizeSlashes(path) {
454
+ return path.replace(/\\/g, "/");
455
+ }
456
+ function fileExtension(path) {
457
+ const base = path.slice(path.lastIndexOf("/") + 1);
458
+ const dot = base.lastIndexOf(".");
459
+ return dot <= 0 ? "" : base.slice(dot + 1).toLowerCase();
460
+ }
461
+ function isScannableSourceFile(file) {
462
+ const normalized = normalizeSlashes(file);
463
+ if (!SCANNABLE_EXTENSIONS.has(fileExtension(normalized))) return false;
464
+ return !IGNORED_PATH_SEGMENTS.some(
465
+ (segment) => normalized.includes(segment)
466
+ );
467
+ }
468
+ function isScanDep(dep) {
469
+ if (dep.includes("*")) return true;
470
+ const ext = fileExtension(normalizeSlashes(dep));
471
+ return ext !== "" && ext !== "css" && SCANNABLE_EXTENSIONS.has(ext);
472
+ }
473
+ function cssEntryNeedsRescanFor(entry, file) {
474
+ if (entry.deps === null) return false;
475
+ const normalizedFile = normalizeSlashes(file);
476
+ let scansClasses = false;
477
+ for (const dep of entry.deps) {
478
+ const normalizedDep = normalizeSlashes(dep);
479
+ if (normalizedDep === normalizedFile) return false;
480
+ if (!scansClasses && isScanDep(normalizedDep)) scansClasses = true;
481
+ }
482
+ return scansClasses;
483
+ }
484
+ function createTailwindScanNet(args) {
485
+ const debounceMs = args.debounceMs ?? TAILWIND_SCAN_NET_DEBOUNCE_MS;
486
+ const maxPokesPerPair = args.maxPokesPerPair ?? TAILWIND_SCAN_NET_MAX_POKES_PER_PAIR;
487
+ const pendingCssFiles = /* @__PURE__ */ new Set();
488
+ const pokeLedger = /* @__PURE__ */ new Map();
489
+ const countedThisWindow = /* @__PURE__ */ new Set();
490
+ let flushTimer = null;
491
+ let lastFlushAt = Number.NEGATIVE_INFINITY;
492
+ let disposed = false;
493
+ const flush = () => {
494
+ flushTimer = null;
495
+ lastFlushAt = Date.now();
496
+ countedThisWindow.clear();
497
+ const cssFiles = [...pendingCssFiles];
498
+ pendingCssFiles.clear();
499
+ for (const cssFile of cssFiles) {
500
+ args.emitChange(cssFile);
501
+ }
502
+ };
503
+ return {
504
+ handleWatcherFile(file) {
505
+ if (disposed) return false;
506
+ if (!isScannableSourceFile(file)) return false;
507
+ let scheduled = false;
508
+ for (const entry of args.listCssEntries()) {
509
+ if (!cssEntryNeedsRescanFor(entry, file)) continue;
510
+ const pairKey = `${entry.cssFile}\0${normalizeSlashes(file)}`;
511
+ if (!countedThisWindow.has(pairKey)) {
512
+ const pokes = pokeLedger.get(pairKey) ?? 0;
513
+ if (pokes >= maxPokesPerPair) continue;
514
+ if (pokeLedger.size >= POKE_LEDGER_MAX_ENTRIES) pokeLedger.clear();
515
+ pokeLedger.set(pairKey, pokes + 1);
516
+ countedThisWindow.add(pairKey);
517
+ }
518
+ pendingCssFiles.add(entry.cssFile);
519
+ scheduled = true;
520
+ }
521
+ if (scheduled && flushTimer === null) {
522
+ const sinceLastFlush = Date.now() - lastFlushAt;
523
+ const delay = sinceLastFlush >= debounceMs ? 0 : debounceMs;
524
+ flushTimer = setTimeout(flush, delay);
525
+ flushTimer.unref?.();
526
+ }
527
+ return scheduled;
528
+ },
529
+ dispose() {
530
+ disposed = true;
531
+ pendingCssFiles.clear();
532
+ pokeLedger.clear();
533
+ countedThisWindow.clear();
534
+ if (flushTimer !== null) {
535
+ clearTimeout(flushTimer);
536
+ flushTimer = null;
537
+ }
538
+ }
539
+ };
540
+ }
541
+
402
542
  // index.ts
403
543
  var DEFAULT_INCLUDE = ["**/*.tsx", "**/*.jsx"];
404
544
  var DEFAULT_EXCLUDE = ["**/node_modules/**"];
@@ -406,6 +546,17 @@ var ROOT_META_NAME = "tempo-project-root";
406
546
  var SOURCE_IDENTITY_ROOT_META_NAME = "tempo-source-identity-root";
407
547
  var INTERACT_PROJECTION_CLIENT_PATH = "/@tempo/interact-projection";
408
548
  var INTERACT_PROJECTION_CLIENT_ID = "\0tempo:interact-projection";
549
+ var INTERACT_PROJECTION_SDK_SPECIFIER = "tempo-sdk/canvas/interact-projection";
550
+ function resolveOwnInteractProjectionModule() {
551
+ const selfDir = dirname(fileURLToPath(import.meta.url));
552
+ for (const candidate of [
553
+ join(selfDir, "canvas", "interact-projection.ts"),
554
+ join(selfDir, "canvas", "interact-projection.js")
555
+ ]) {
556
+ if (existsSync(candidate)) return candidate.replace(/\\/g, "/");
557
+ }
558
+ return null;
559
+ }
409
560
  var INTERACT_PROJECTION_BOOTSTRAP = `
410
561
  (function() {
411
562
  if (window.parent === window || (window.name !== ${JSON.stringify(TEMPO_INTERACT_FRAME_NAME)} && !window.name.startsWith(${JSON.stringify(`${TEMPO_INTERACT_FRAME_NAME}:`)}))) return;
@@ -749,6 +900,41 @@ function installMissedChangeSweep(server, listErrorFiles, lastHotUpdateMtimeMs,
749
900
  timer.unref?.();
750
901
  server.httpServer?.once("close", () => clearInterval(timer));
751
902
  }
903
+ function installTailwindScanNet(server) {
904
+ const net = createTailwindScanNet({
905
+ listCssEntries: function* () {
906
+ const fileToModules = server.moduleGraph?.fileToModulesMap ?? /* @__PURE__ */ new Map();
907
+ for (const [file, modules] of fileToModules) {
908
+ if (!file.endsWith(".css")) continue;
909
+ for (const module of modules) {
910
+ const deps = [];
911
+ for (const imported of module.importedModules ?? []) {
912
+ const dep = imported.file ?? imported.url ?? imported.id;
913
+ if (dep) deps.push(dep);
914
+ }
915
+ yield { cssFile: file, deps };
916
+ }
917
+ }
918
+ },
919
+ emitChange: (cssFile) => {
920
+ server.config?.logger?.info?.(
921
+ `[tempo] new source file outside the Tailwind scan \u2014 re-emitting change: ${cssFile}`,
922
+ { timestamp: true }
923
+ );
924
+ server.watcher?.emit?.("change", cssFile);
925
+ }
926
+ });
927
+ const onWatcherFile = (file) => {
928
+ net.handleWatcherFile(file);
929
+ };
930
+ server.watcher?.on?.("add", onWatcherFile);
931
+ server.watcher?.on?.("change", onWatcherFile);
932
+ server.httpServer?.once("close", () => {
933
+ server.watcher?.off?.("add", onWatcherFile);
934
+ server.watcher?.off?.("change", onWatcherFile);
935
+ net.dispose();
936
+ });
937
+ }
752
938
  function tempoVitePlugin(options = {}) {
753
939
  const enabled = !!process.env.TEMPO;
754
940
  const include = options.include === void 0 ? DEFAULT_INCLUDE : options.include;
@@ -772,6 +958,7 @@ function tempoVitePlugin(options = {}) {
772
958
  const rapidHotUpdateReplay = createRapidHotUpdateReplay();
773
959
  const hotUpdateMtimesMs = /* @__PURE__ */ new Map();
774
960
  const normalizedFileKey = (file) => file.replace(/\\/g, "/");
961
+ const burstKey = (file) => normalizedFileKey(fsPathFromModuleId(file));
775
962
  const recordHotUpdateCoverage = (file) => {
776
963
  const cleanFile = fsPathFromModuleId(file);
777
964
  const key = normalizedFileKey(cleanFile);
@@ -1087,6 +1274,14 @@ function tempoVitePlugin(options = {}) {
1087
1274
  if (id === INTERACT_PROJECTION_CLIENT_PATH) {
1088
1275
  return INTERACT_PROJECTION_CLIENT_ID;
1089
1276
  }
1277
+ if (id === INTERACT_PROJECTION_SDK_SPECIFIER && importer === INTERACT_PROJECTION_CLIENT_ID) {
1278
+ const resolved = await this.resolve(id, importer, {
1279
+ ...resolveOptions,
1280
+ skipSelf: true
1281
+ });
1282
+ if (resolved) return resolved;
1283
+ return resolveOwnInteractProjectionModule();
1284
+ }
1090
1285
  if (enabled && importer && !importer.startsWith("\0")) {
1091
1286
  const packageName = barePackageName(id);
1092
1287
  if (!isRelativeImportSpecifier(id) && !packageName) return null;
@@ -1105,13 +1300,21 @@ function tempoVitePlugin(options = {}) {
1105
1300
  return null;
1106
1301
  }
1107
1302
  },
1108
- load(id) {
1109
- if (id === INTERACT_PROJECTION_CLIENT_ID) {
1110
- return `let stop;
1303
+ // `order: "pre"` + a null return: this hook never loads anything of its
1304
+ // own for a project file, it only decides WHEN Vite core is allowed to
1305
+ // read it. Awaiting the burst gate here (rather than in `transform`) is
1306
+ // what makes the content terminal — by `transform` the bytes have already
1307
+ // been read, so delaying there would ship a stale revision late instead of
1308
+ // not shipping it at all.
1309
+ load: {
1310
+ order: "pre",
1311
+ async handler(id) {
1312
+ if (id === INTERACT_PROJECTION_CLIENT_ID) {
1313
+ return `let stop;
1111
1314
  let disposed = false;
1112
1315
  if (window.parent !== window && (window.name === ${JSON.stringify(TEMPO_INTERACT_FRAME_NAME)} || window.name.startsWith(${JSON.stringify(`${TEMPO_INTERACT_FRAME_NAME}:`)}))) {
1113
1316
  window.__tempoInteractProjectionOwner = "vite";
1114
- void import("tempo-sdk/canvas/interact-projection").then(({ installTempoInteractProjectionSource }) => {
1317
+ void import(${JSON.stringify(INTERACT_PROJECTION_SDK_SPECIFIER)}).then(({ installTempoInteractProjectionSource }) => {
1115
1318
  if (disposed) return;
1116
1319
  stop = installTempoInteractProjectionSource();
1117
1320
  });
@@ -1120,8 +1323,11 @@ if (import.meta.hot) import.meta.hot.dispose(() => {
1120
1323
  disposed = true;
1121
1324
  stop?.();
1122
1325
  });`;
1326
+ }
1327
+ if (!enabled || command === "build" || id.startsWith("\0")) return null;
1328
+ await rapidHotUpdateReplay.settled(burstKey(id));
1329
+ return null;
1123
1330
  }
1124
- return null;
1125
1331
  },
1126
1332
  // Expose error server for testing
1127
1333
  _tempoErrorServer: errorServer,
@@ -1177,6 +1383,12 @@ if (import.meta.hot) import.meta.hot.dispose(() => {
1177
1383
  },
1178
1384
  configureServer(server) {
1179
1385
  if (!enabled) return;
1386
+ const ownInteractModule = resolveOwnInteractProjectionModule();
1387
+ const allow = server.config?.server?.fs?.allow;
1388
+ if (ownInteractModule && Array.isArray(allow)) {
1389
+ const ownDir = dirname(ownInteractModule);
1390
+ if (!allow.includes(ownDir)) allow.push(ownDir);
1391
+ }
1180
1392
  devServer = server;
1181
1393
  syncUnresolvedImportWatcher();
1182
1394
  server.watcher?.once?.("close", closeUnresolvedImportWatchers);
@@ -1190,6 +1402,7 @@ if (import.meta.hot) import.meta.hot.dispose(() => {
1190
1402
  (file) => hotUpdateMtimesMs.get(normalizedFileKey(file)),
1191
1403
  () => pollCompileErrorRecovery(server)
1192
1404
  );
1405
+ installTailwindScanNet(server);
1193
1406
  const interceptHmrSend = (target) => {
1194
1407
  const orig = target.send.bind(target);
1195
1408
  target.send = ((...args) => {
@@ -1247,7 +1460,7 @@ if (import.meta.hot) import.meta.hot.dispose(() => {
1247
1460
  if (!enabled || this.environment.config.consumer !== "client") return;
1248
1461
  recordHotUpdateCoverage(context.file);
1249
1462
  if (context.type === "update" && context.modules.length > 0) {
1250
- rapidHotUpdateReplay.observe(context.file, () => {
1463
+ rapidHotUpdateReplay.observe(burstKey(context.file), () => {
1251
1464
  context.server.config.logger.info(
1252
1465
  `[tempo] replaying settled rapid watcher change: ${context.file}`,
1253
1466
  { timestamp: true }
@@ -1279,7 +1492,7 @@ if (import.meta.hot) import.meta.hot.dispose(() => {
1279
1492
  if (!enabled) return;
1280
1493
  recordHotUpdateCoverage(context.file);
1281
1494
  if (context.modules.length > 0) {
1282
- rapidHotUpdateReplay.observe(context.file, () => {
1495
+ rapidHotUpdateReplay.observe(burstKey(context.file), () => {
1283
1496
  context.server.config.logger.info(
1284
1497
  `[tempo] replaying settled rapid watcher change: ${context.file}`,
1285
1498
  { timestamp: true }