@timber-js/app 0.2.0-alpha.220 → 0.2.0-alpha.221

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 (152) hide show
  1. package/dist/_chunks/{actions-BwkmAYXq.js → actions-BDqn4Oxj.js} +2 -2
  2. package/dist/_chunks/{actions-BwkmAYXq.js.map → actions-BDqn4Oxj.js.map} +1 -1
  3. package/dist/_chunks/{cache-api-LA3sBpUS.js → cache-api-GE4AOe2H.js} +30 -151
  4. package/dist/_chunks/cache-api-GE4AOe2H.js.map +1 -0
  5. package/dist/_chunks/dev-server-BiWNMBVU.js +1 -0
  6. package/dist/_chunks/{dev-server-DnODXuNM.js → dev-server-DIy-SY-J.js} +11 -6
  7. package/dist/_chunks/{dev-server-DnODXuNM.js.map → dev-server-DIy-SY-J.js.map} +1 -1
  8. package/dist/_chunks/dev-store-BOa304m_.js +283 -0
  9. package/dist/_chunks/dev-store-BOa304m_.js.map +1 -0
  10. package/dist/_chunks/{error-boundary-xxxLtXt6.js → error-boundary-Bc8QPZuq.js} +71 -21
  11. package/dist/_chunks/error-boundary-Bc8QPZuq.js.map +1 -0
  12. package/dist/_chunks/{flight-source-node-0dE-t3kq.js → flight-source-node-HptmGMT8.js} +6 -7
  13. package/dist/_chunks/flight-source-node-HptmGMT8.js.map +1 -0
  14. package/dist/_chunks/{node-response-Dibufw_b.js → node-response-rkQqcFGq.js} +48 -2
  15. package/dist/_chunks/node-response-rkQqcFGq.js.map +1 -0
  16. package/dist/_chunks/{purge-store-Byr8XOjU.js → purge-store-WZaxu-3m.js} +2 -2
  17. package/dist/_chunks/purge-store-WZaxu-3m.js.map +1 -0
  18. package/dist/_chunks/{render-timeout-DOf_BBcO.js → render-timeout-joFhz4KH.js} +1 -10
  19. package/dist/_chunks/render-timeout-joFhz4KH.js.map +1 -0
  20. package/dist/cache/cache-api.d.ts.map +1 -1
  21. package/dist/cache/handler-store.d.ts +13 -1
  22. package/dist/cache/handler-store.d.ts.map +1 -1
  23. package/dist/cache/index.js +2 -1
  24. package/dist/cache/invalidation-epoch.d.ts +7 -0
  25. package/dist/cache/invalidation-epoch.d.ts.map +1 -1
  26. package/dist/cache/timber-cache.d.ts.map +1 -1
  27. package/dist/cdn/index.js +1 -1
  28. package/dist/cdn/purge-store.d.ts +10 -1
  29. package/dist/cdn/purge-store.d.ts.map +1 -1
  30. package/dist/cli.js +1 -1
  31. package/dist/client/browser-entry/router-init.d.ts.map +1 -1
  32. package/dist/client/error-boundary.js +1 -1
  33. package/dist/client/index.js +6 -15
  34. package/dist/client/index.js.map +1 -1
  35. package/dist/client/internal.js +37 -64
  36. package/dist/client/internal.js.map +1 -1
  37. package/dist/client/link.d.ts.map +1 -1
  38. package/dist/client/navigation-transition.d.ts +68 -14
  39. package/dist/client/navigation-transition.d.ts.map +1 -1
  40. package/dist/client/router-effects.d.ts +35 -31
  41. package/dist/client/router-effects.d.ts.map +1 -1
  42. package/dist/client/router-pipeline.d.ts +2 -6
  43. package/dist/client/router-pipeline.d.ts.map +1 -1
  44. package/dist/client/router-types.d.ts +10 -30
  45. package/dist/client/router-types.d.ts.map +1 -1
  46. package/dist/client/router.d.ts.map +1 -1
  47. package/dist/dev-tools/logs.d.ts +2 -2
  48. package/dist/dev-tools/logs.d.ts.map +1 -1
  49. package/dist/index.js +144 -51
  50. package/dist/index.js.map +1 -1
  51. package/dist/plugins/dev-server.d.ts.map +1 -1
  52. package/dist/plugins/entries.d.ts +5 -0
  53. package/dist/plugins/entries.d.ts.map +1 -1
  54. package/dist/plugins/orphaned-modules.d.ts +57 -0
  55. package/dist/plugins/orphaned-modules.d.ts.map +1 -0
  56. package/dist/plugins/prebuilt.d.ts +6 -6
  57. package/dist/plugins/prerender-sugar.d.ts.map +1 -1
  58. package/dist/plugins/routing.d.ts +1 -1
  59. package/dist/plugins/routing.d.ts.map +1 -1
  60. package/dist/rsc-runtime/dev-reference-cache.d.ts +47 -0
  61. package/dist/rsc-runtime/dev-reference-cache.d.ts.map +1 -0
  62. package/dist/rsc-runtime/rsc.d.ts +0 -15
  63. package/dist/rsc-runtime/rsc.d.ts.map +1 -1
  64. package/dist/rsc-runtime/ssr.d.ts +0 -11
  65. package/dist/rsc-runtime/ssr.d.ts.map +1 -1
  66. package/dist/server/abort-scope.d.ts +27 -0
  67. package/dist/server/abort-scope.d.ts.map +1 -0
  68. package/dist/server/flight-source-node.d.ts.map +1 -1
  69. package/dist/server/index.js +1 -1
  70. package/dist/server/instrumentation.d.ts +2 -1
  71. package/dist/server/instrumentation.d.ts.map +1 -1
  72. package/dist/server/internal.d.ts +1 -1
  73. package/dist/server/internal.d.ts.map +1 -1
  74. package/dist/server/internal.js +328 -132
  75. package/dist/server/internal.js.map +1 -1
  76. package/dist/server/pipeline-helpers.d.ts.map +1 -1
  77. package/dist/server/pipeline.d.ts +10 -7
  78. package/dist/server/pipeline.d.ts.map +1 -1
  79. package/dist/server/prebuilt/cache-key.d.ts +26 -0
  80. package/dist/server/prebuilt/cache-key.d.ts.map +1 -1
  81. package/dist/server/prebuilt/capture-render.d.ts +9 -4
  82. package/dist/server/prebuilt/capture-render.d.ts.map +1 -1
  83. package/dist/server/prebuilt/capture-routes.d.ts +1 -1
  84. package/dist/server/prebuilt/dev-store.d.ts +103 -0
  85. package/dist/server/prebuilt/dev-store.d.ts.map +1 -0
  86. package/dist/server/prebuilt/overlay.d.ts +5 -0
  87. package/dist/server/prebuilt/overlay.d.ts.map +1 -1
  88. package/dist/server/prebuilt/payload-source.d.ts +8 -0
  89. package/dist/server/prebuilt/payload-source.d.ts.map +1 -1
  90. package/dist/server/prebuilt/slots.d.ts +5 -6
  91. package/dist/server/prebuilt/slots.d.ts.map +1 -1
  92. package/dist/server/prebuilt-builder.d.ts.map +1 -1
  93. package/dist/server/prebuilt-runtime.d.ts +5 -10
  94. package/dist/server/prebuilt-runtime.d.ts.map +1 -1
  95. package/dist/server/render-timeout.d.ts.map +1 -1
  96. package/dist/server/rsc-entry/action-dispatcher.d.ts.map +1 -1
  97. package/dist/server/rsc-entry/index.d.ts.map +1 -1
  98. package/dist/server/ssr-render.d.ts.map +1 -1
  99. package/docs/api/32-api-cache.mdx +2 -0
  100. package/docs/learn/10-caching.mdx +12 -0
  101. package/docs/learn/11-middleware.mdx +2 -0
  102. package/package.json +1 -1
  103. package/src/cache/cache-api.ts +7 -1
  104. package/src/cache/handler-store.ts +38 -1
  105. package/src/cache/invalidation-epoch.ts +18 -6
  106. package/src/cache/timber-cache.ts +6 -2
  107. package/src/cdn/purge-store.ts +29 -1
  108. package/src/client/browser-entry/action-dispatch.ts +5 -5
  109. package/src/client/browser-entry/router-init.ts +2 -4
  110. package/src/client/link.tsx +14 -18
  111. package/src/client/navigation-transition.ts +86 -33
  112. package/src/client/router-effects.ts +70 -45
  113. package/src/client/router-lifecycle.ts +1 -1
  114. package/src/client/router-pipeline.ts +52 -65
  115. package/src/client/router-types.ts +11 -31
  116. package/src/client/router.ts +98 -104
  117. package/src/dev-tools/logs.ts +76 -50
  118. package/src/plugins/dev-server.ts +23 -8
  119. package/src/plugins/entries.ts +6 -0
  120. package/src/plugins/orphaned-modules.ts +78 -0
  121. package/src/plugins/prebuilt.ts +17 -17
  122. package/src/plugins/prerender-sugar.ts +38 -6
  123. package/src/plugins/routing.ts +23 -1
  124. package/src/rsc-runtime/dev-reference-cache.ts +115 -0
  125. package/src/rsc-runtime/rsc.ts +10 -0
  126. package/src/rsc-runtime/ssr.ts +10 -0
  127. package/src/server/abort-scope.ts +49 -0
  128. package/src/server/flight-source-node.ts +5 -4
  129. package/src/server/instrumentation.ts +32 -8
  130. package/src/server/internal.ts +1 -6
  131. package/src/server/pipeline-helpers.ts +5 -3
  132. package/src/server/pipeline.ts +31 -20
  133. package/src/server/prebuilt/cache-key.ts +41 -0
  134. package/src/server/prebuilt/capture-render.ts +10 -6
  135. package/src/server/prebuilt/capture-routes.ts +1 -1
  136. package/src/server/prebuilt/dev-store.ts +173 -0
  137. package/src/server/prebuilt/overlay.ts +7 -1
  138. package/src/server/prebuilt/payload-source.ts +19 -0
  139. package/src/server/prebuilt/slots.ts +5 -6
  140. package/src/server/prebuilt-builder.ts +3 -2
  141. package/src/server/prebuilt-runtime.ts +174 -176
  142. package/src/server/render-timeout.ts +12 -17
  143. package/src/server/rsc-entry/action-dispatcher.ts +3 -1
  144. package/src/server/rsc-entry/index.ts +47 -13
  145. package/src/server/ssr-render.ts +9 -11
  146. package/dist/_chunks/cache-api-LA3sBpUS.js.map +0 -1
  147. package/dist/_chunks/dev-server-DkytOEG2.js +0 -1
  148. package/dist/_chunks/error-boundary-xxxLtXt6.js.map +0 -1
  149. package/dist/_chunks/flight-source-node-0dE-t3kq.js.map +0 -1
  150. package/dist/_chunks/node-response-Dibufw_b.js.map +0 -1
  151. package/dist/_chunks/purge-store-Byr8XOjU.js.map +0 -1
  152. package/dist/_chunks/render-timeout-DOf_BBcO.js.map +0 -1
@@ -283,6 +283,14 @@ export function isFrameworkInternalCaller(): boolean {
283
283
 
284
284
  // ─── Console Patching ────────────────────────────────────────────────────
285
285
 
286
+ /** Where a patched console method forwards: its dev server, until that closes. */
287
+ interface ForwardTarget {
288
+ server: ViteDevServer | null;
289
+ projectRoot: string;
290
+ }
291
+
292
+ type ConsoleMethod = (...args: unknown[]) => void;
293
+
286
294
  /**
287
295
  * Patch console methods to forward logs to the browser via HMR WebSocket.
288
296
  *
@@ -290,60 +298,78 @@ export function isFrameworkInternalCaller(): boolean {
290
298
  * 1. Calls the original console method (server terminal still works)
291
299
  * 2. Serializes arguments for JSON transport
292
300
  * 3. Sends via server.hot.send() — dropped if no clients connected
301
+ *
302
+ * The returned cleanup stops forwarding to `server`, and unwraps a method
303
+ * only while this patch is still the outermost one. Vite's
304
+ * `server.restart()` configures the new server, whose patch wraps this one,
305
+ * before it closes this server. React's dev Flight server also wraps the
306
+ * console when it loads. Restoring the method this patch found would drop
307
+ * every wrapper installed since, the new server's included (TIM-1589). A
308
+ * patch left inside another passes calls through once its server is closed.
293
309
  */
294
310
  function patchConsole(server: ViteDevServer, projectRoot: string): () => void {
295
- const prevConsole = new Map<ServerLogLevel, (...args: unknown[]) => void>();
296
- // Per-level guard so a console.warn inside a console.error handler isn't
311
+ const target: ForwardTarget = { server, projectRoot };
312
+ const installed = new Map<ServerLogLevel, { method: ConsoleMethod; prev: ConsoleMethod }>();
313
+ for (const level of LOG_LEVELS) {
314
+ const prev = console[level].bind(console);
315
+ const method = createForwardingMethod(level, prev, target);
316
+ console[level] = method;
317
+ installed.set(level, { method, prev });
318
+ }
319
+ return () => {
320
+ target.server = null;
321
+ for (const [level, { method, prev }] of installed) {
322
+ if (console[level] === method) console[level] = prev;
323
+ }
324
+ };
325
+ }
326
+
327
+ function createForwardingMethod(
328
+ level: ServerLogLevel,
329
+ prev: (...args: unknown[]) => void,
330
+ target: ForwardTarget
331
+ ): ConsoleMethod {
332
+ // Same-level guard so a console.warn inside a console.error handler isn't
297
333
  // suppressed — only same-level synchronous re-entrancy is blocked.
298
- const patchingLevel = new Set<ServerLogLevel>();
334
+ let forwarding = false;
335
+ return (...args: unknown[]) => {
336
+ // Same-level re-entrancy guard: if prev's wrapper calls back into
337
+ // console[level], just pass through without forwarding.
338
+ if (forwarding) {
339
+ prev(...args);
340
+ return;
341
+ }
299
342
 
300
- for (const level of LOG_LEVELS) {
301
- prevConsole.set(level, console[level].bind(console));
302
-
303
- console[level] = (...args: unknown[]) => {
304
- // Same-level re-entrancy guard: if prevConsole's wrapper calls back
305
- // into console[level], just pass through without forwarding.
306
- if (patchingLevel.has(level)) {
307
- prevConsole.get(level)!(...args);
308
- return;
309
- }
343
+ forwarding = true;
344
+ try {
345
+ // Call the previous console method first — guarantees terminal output
346
+ // even if serialization or forwarding fails downstream. If prev throws,
347
+ // the error propagates (not swallowed) but the guard is still reset by
348
+ // the outer finally.
349
+ prev(...args);
350
+
351
+ const { server } = target;
352
+ if (!server) return;
353
+ // Skip framework-internal logs (plugins/, adapters/) from browser forwarding.
354
+ if (isFrameworkInternalCaller()) return;
310
355
 
311
- patchingLevel.add(level);
312
356
  try {
313
- // Call the previous console method first — guarantees terminal output
314
- // even if serialization or forwarding fails downstream. If prevConsole
315
- // throws, the error propagates (not swallowed) but patchingLevel is
316
- // still cleaned up by the outer finally.
317
- prevConsole.get(level)!(...args);
318
-
319
- // Skip framework-internal logs (plugins/, adapters/) from browser forwarding.
320
- if (isFrameworkInternalCaller()) return;
321
-
322
- try {
323
- const payload: ServerLogPayload = {
324
- level,
325
- args: args.map((arg) => serializeArg(arg)),
326
- location: extractCallerLocation(projectRoot),
327
- timestamp: Date.now(),
328
- };
329
-
330
- server.hot.send('timber:server-log', payload);
331
- } catch (e) {
332
- originalConsole.debug(
333
- '[timber] server log forwarding failed:',
334
- e instanceof Error ? e.message : e
335
- );
336
- }
337
- } finally {
338
- patchingLevel.delete(level);
357
+ const payload: ServerLogPayload = {
358
+ level,
359
+ args: args.map((arg) => serializeArg(arg)),
360
+ location: extractCallerLocation(target.projectRoot),
361
+ timestamp: Date.now(),
362
+ };
363
+
364
+ server.hot.send('timber:server-log', payload);
365
+ } catch (e) {
366
+ originalConsole.debug(
367
+ '[timber] server log forwarding failed:',
368
+ e instanceof Error ? e.message : e
369
+ );
339
370
  }
340
- };
341
- }
342
-
343
- // Return a cleanup function to restore the previous console methods
344
- return () => {
345
- for (const [level, prev] of prevConsole) {
346
- console[level] = prev;
371
+ } finally {
372
+ forwarding = false;
347
373
  }
348
374
  };
349
375
  }
@@ -353,8 +379,8 @@ function patchConsole(server: ViteDevServer, projectRoot: string): () => void {
353
379
  /**
354
380
  * Create the timber-dev-logs Vite plugin.
355
381
  *
356
- * Patches console methods when the dev server starts and restores them
357
- * when the server closes. Only active during `vite dev`.
382
+ * Patches console methods when the dev server starts and stops forwarding
383
+ * to it when it closes. Only active during `vite dev`.
358
384
  */
359
385
  export function timberDevLogs(_ctx: PluginContext): Plugin {
360
386
  let cleanup: (() => void) | null = null;
@@ -366,7 +392,7 @@ export function timberDevLogs(_ctx: PluginContext): Plugin {
366
392
  configureServer(server: ViteDevServer) {
367
393
  cleanup = patchConsole(server, _ctx.root);
368
394
 
369
- // Restore console on server close
395
+ // Stop forwarding to this server once it closes
370
396
  server.httpServer?.on('close', () => {
371
397
  cleanup?.();
372
398
  cleanup = null;
@@ -41,6 +41,7 @@ import {
41
41
  import { compressResponse } from '../server/compress.ts';
42
42
  import { isMetadataRouteServePath } from '../server/metadata-routes.ts';
43
43
  import { canonicalize } from '../server/canonicalize.ts';
44
+ import { PREBUILT_DEV_CLEAR_EVENT } from '../server/prebuilt/dev-store.ts';
44
45
  import { matchUrlParts } from '../server/tree-match.ts';
45
46
  import type { RouteTree } from '../routing/types.ts';
46
47
 
@@ -132,10 +133,12 @@ export function timberDevServer(ctx: PluginContext): Plugin {
132
133
  async configureServer(server: ViteDevServer) {
133
134
  // Watch config files for changes. When running under the CLI
134
135
  // supervisor (__TIMBER_DEV_WORKER), exit the process so the
135
- // supervisor respawns with a fresh require cache. When running
136
- // via `vite dev` directly (no supervisor), fall back to Vite's
137
- // in-process server.restart() — it serves stale config, but at
138
- // least the server stays alive. See TIM-1444.
136
+ // supervisor respawns with a fresh require cache. Under `vite dev`
137
+ // directly (no supervisor) only say so: an in-process
138
+ // server.restart() would serve the stale config anyway (TIM-1444),
139
+ // and each one leaks the whole previous server — its environments,
140
+ // module runners, and React's dev Flight server stay reachable — so a
141
+ // few config saves ran the dev server out of heap (TIM-1589).
139
142
  const configPaths = CONFIG_FILE_NAMES.map((name) => join(ctx.root, name));
140
143
  server.watcher.add(configPaths);
141
144
  const configPathSet = new Set(configPaths);
@@ -146,11 +149,10 @@ export function timberDevServer(ctx: PluginContext): Plugin {
146
149
  console.log(`\n[timber] ${basename(filePath)} changed — restarting dev server...\n`);
147
150
  process.exit(RESTART_EXIT_CODE);
148
151
  } else {
149
- console.log(
150
- `\n[timber] ${basename(filePath)} changed — restarting dev server...` +
151
- `\n[timber] Run \`timber dev\` instead of \`vite dev\` for guaranteed fresh config on restart.\n`
152
+ console.warn(
153
+ `\n[timber] ${basename(filePath)} changed. Restart the dev server to apply it,` +
154
+ ` or run \`timber dev\` instead of \`vite dev\` to restart automatically.\n`
152
155
  );
153
- server.restart();
154
156
  }
155
157
  };
156
158
  server.watcher.on('change', onConfigChange);
@@ -169,6 +171,19 @@ export function timberDevServer(ctx: PluginContext): Plugin {
169
171
  // never reach the app pipeline. Dev-only by construction (this
170
172
  // plugin is apply: 'serve'). See design/47 §"Dev-server endpoint".
171
173
  server.middlewares.use(createGraphEndpointMiddleware(server, ctx));
174
+
175
+ // Every watcher event clears the RSC environment's cache.component dev
176
+ // store (TIM-1588) — source files, and files outside the module graph
177
+ // that a component reads with fs. A raw listener, not hotUpdate: it
178
+ // runs in the same synchronous dispatch as every other watcher
179
+ // listener (timber-routing's reloads included), before Vite's own
180
+ // handling sends any HMR update. A browser that a reload or update
181
+ // makes refetch can only reach the server after the clear has gone
182
+ // out.
183
+ const rscHot = server.environments.rsc?.hot;
184
+ server.watcher.on('all', () => {
185
+ rscHot?.send({ type: 'custom', event: PREBUILT_DEV_CLEAR_EVENT });
186
+ });
172
187
  graphChannel = makeGraphUpdateChannel(
173
188
  ctx,
174
189
  (payload) => server.hot.send(payload),
@@ -60,6 +60,12 @@ const ENTRY_FILE_MAP: Record<string, string> = {
60
60
  */
61
61
  export const BROWSER_ENTRY_FILE = ENTRY_FILE_MAP[VIRTUAL_IDS.browserEntry];
62
62
 
63
+ /**
64
+ * The real file behind virtual:timber-rsc-entry, the RSC environment's HMR
65
+ * boundary (see plugins/orphaned-modules.ts).
66
+ */
67
+ export const RSC_ENTRY_FILE = ENTRY_FILE_MAP[VIRTUAL_IDS.rscEntry];
68
+
63
69
  /** The \0-prefixed resolved ID for virtual:timber-config */
64
70
  const RESOLVED_CONFIG_ID = `\0${VIRTUAL_IDS.config}`;
65
71
 
@@ -0,0 +1,78 @@
1
+ /**
2
+ * Keep an update to an orphaned RSC module from reloading the RSC module runner.
3
+ *
4
+ * Vite propagates a server-module update up its importers to an HMR
5
+ * boundary (the RSC entry self-accepts). A module with no importers is a dead
6
+ * end, and Vite answers a dead end by full-reloading the environment's
7
+ * runner, which in the RSC environment leaks the whole module generation:
8
+ * React's dev Flight server leaves its async hook and console patches
9
+ * installed, and they keep every discarded copy reachable (TIM-1588,
10
+ * TIM-1589). Two kinds of module have no importers:
11
+ *
12
+ * - A deleted route file's module. The regenerated route manifest no longer
13
+ * imports it, but its node stays in the graph, so a file that appears at
14
+ * that path again (re-added, renamed back, a branch switch) updates it.
15
+ * - A server-reference module (`'use server'`) that only client components
16
+ * import. plugin-rsc loads server references with a runtime
17
+ * `import(/* @vite-ignore *\/ id)`, which records no importer edge.
18
+ *
19
+ * Neither can simply be dropped from the update. The module runner keeps the
20
+ * module's evaluated instance until something invalidates it, and the update
21
+ * is what advances the source generation that keys plugin-rsc's reference
22
+ * caches (rsc-runtime/dev-reference-cache.ts): without it, a no-JS form
23
+ * submit would keep running the edited action's old code. So the orphan is
24
+ * invalidated in the server graph and in the runner, and the update goes to
25
+ * the RSC entry instead, re-running its boot as any other server edit does.
26
+ *
27
+ * See design/21-dev-server.md §HMR Wiring.
28
+ */
29
+
30
+ /** What this reads of a server module node (Vite's `EnvironmentModuleNode`). */
31
+ export interface OrphanCandidate {
32
+ id: string | null;
33
+ importers: { readonly size: number };
34
+ isSelfAccepting?: boolean;
35
+ }
36
+
37
+ /**
38
+ * The slice of the RSC dev environment this needs: its server module graph
39
+ * and, when the runner runs in this process, the runner's evaluated modules.
40
+ */
41
+ export interface OrphanEnvironment<M extends OrphanCandidate, E> {
42
+ moduleGraph: {
43
+ invalidateModule(mod: M): void;
44
+ getModulesByFile(file: string): Set<M> | undefined;
45
+ };
46
+ evaluatedModules?: {
47
+ getModuleById(id: string): E | undefined;
48
+ invalidateModule(node: E): void;
49
+ };
50
+ }
51
+
52
+ /**
53
+ * The update's modules with each orphan replaced by the RSC entry (whose
54
+ * file is `entryFile`). `undefined` when there are no orphans, so Vite keeps
55
+ * the update as it is.
56
+ */
57
+ export function redirectOrphanedModules<M extends OrphanCandidate, E>(
58
+ environment: OrphanEnvironment<M, E>,
59
+ modules: M[],
60
+ entryFile: string
61
+ ): M[] | undefined {
62
+ const entry = environment.moduleGraph.getModulesByFile(entryFile)?.values().next().value;
63
+ const orphans = modules.filter(
64
+ (mod) => mod !== entry && mod.importers.size === 0 && !mod.isSelfAccepting
65
+ );
66
+ if (orphans.length === 0) return undefined;
67
+
68
+ const { moduleGraph, evaluatedModules } = environment;
69
+ for (const mod of orphans) {
70
+ moduleGraph.invalidateModule(mod);
71
+ const evaluated = mod.id ? evaluatedModules?.getModuleById(mod.id) : undefined;
72
+ if (evaluated) evaluatedModules?.invalidateModule(evaluated);
73
+ }
74
+ const rest = modules.filter((mod) => !orphans.includes(mod));
75
+ // Not loaded yet: nothing has run, so there is nothing to update.
76
+ if (entry && !rest.includes(entry)) rest.push(entry);
77
+ return rest;
78
+ }
@@ -32,13 +32,13 @@
32
32
  * cannot see a shadow of an import binding (redeclaration error). Calls in
33
33
  * other positions fall back to the runtime path like other untraceable forms.
34
34
  *
35
- * The rewrite per mode:
36
- * production: cache.component(fn, opts) → __prebuilt("<id>", fn, opts)
37
- * dev: cache.component(fn, opts) → __prebuiltDev("<name>", fn, opts)
35
+ * The rewrite, in dev and production alike:
36
+ * cache.component(fn, opts) → __prebuilt("<id>", fn, opts)
38
37
  *
39
- * with `import { __prebuilt } from '#server-internal'` prepended. In dev the
40
- * wrapper is a no-op that logs once per component and renders dynamically —
41
- * no caching, no markers (design/44 §Dev Mode).
38
+ * with `import { __prebuilt } from '#server-internal'` prepended. Dev uses the
39
+ * same IDs: they key the dev store too, and because the hash covers the
40
+ * call-site text, editing the call site re-keys its entries (design/44
41
+ * §Dev Mode). Build attribution is recorded in production only.
42
42
  *
43
43
  * Component identity: `<name>_<hash16>`, e.g. `blogbody_a1b2c3d4e5f6a7b8`.
44
44
  * The name prefix is the declaring variable's name (lowercased, for legible
@@ -447,7 +447,6 @@ export function timberPrebuilt(ctx: PluginContext): Plugin & { api: PrebuiltBuil
447
447
  const relPath = relative(root, id);
448
448
  const s = new MagicString(code);
449
449
  const occurrences = new Map<string, number>();
450
- const wrapperName = ctx.dev ? '__prebuiltDev' : '__prebuilt';
451
450
  const componentIds: string[] = [];
452
451
 
453
452
  for (const { call, stmt, displayName } of callSites) {
@@ -459,18 +458,19 @@ export function timberPrebuilt(ctx: PluginContext): Plugin & { api: PrebuiltBuil
459
458
  const occurrence = occurrences.get(dupKey) ?? 0;
460
459
  occurrences.set(dupKey, occurrence + 1);
461
460
 
462
- // Production gets the stable ID (keys build artifacts and cache
463
- // entries); dev gets the display name (only used for the one-time
464
- // "rendering dynamically" log).
465
- const firstArg = ctx.dev
466
- ? displayName
467
- : generatePrebuiltId(relPath, stmtText, spanText, occurrence, displayName);
461
+ const componentId = generatePrebuiltId(
462
+ relPath,
463
+ stmtText,
464
+ spanText,
465
+ occurrence,
466
+ displayName
467
+ );
468
468
  // Only prerender-capable call sites feed the capture attribution —
469
469
  // runtime-tier components (ttl/tags only) must do no build work.
470
- if (!ctx.dev && mayPrerender(call)) componentIds.push(firstArg);
470
+ if (!ctx.dev && mayPrerender(call)) componentIds.push(componentId);
471
471
 
472
- s.overwrite(call.callee.start, call.callee.end, wrapperName);
473
- s.appendLeft(call.arguments[0].start, `${JSON.stringify(firstArg)}, `);
472
+ s.overwrite(call.callee.start, call.callee.end, '__prebuilt');
473
+ s.appendLeft(call.arguments[0].start, `${JSON.stringify(componentId)}, `);
474
474
  }
475
475
 
476
476
  // Record this module's component IDs for the RSC generateBundle
@@ -558,7 +558,7 @@ export function timberPrebuilt(ctx: PluginContext): Plugin & { api: PrebuiltBuil
558
558
 
559
559
  s.appendLeft(
560
560
  importInsertionOffset(program),
561
- `import { ${wrapperName} } from '#server-internal';\n`
561
+ `import { __prebuilt } from '#server-internal';\n`
562
562
  );
563
563
 
564
564
  return {
@@ -163,14 +163,13 @@ function findDefaultExport(program: { body: AstNode[] }, source: string): Defaul
163
163
 
164
164
  export function timberPrerenderSugar(ctx: PluginContext): Plugin {
165
165
  let resolvedPages: Map<string, PrerenderExportValue> | null = null;
166
+ /** The route tree `resolvedPages` was computed from — a rescan replaces it. */
167
+ let resolvedFor: PluginContext['routeTree'] | undefined;
166
168
 
167
169
  function ensureResolved() {
168
- if (resolvedPages) return;
169
- if (!ctx.routeTree) {
170
- resolvedPages = new Map();
171
- return;
172
- }
173
- resolvedPages = resolvePagePrerender(ctx.routeTree.root);
170
+ if (resolvedPages && resolvedFor === ctx.routeTree) return;
171
+ resolvedFor = ctx.routeTree;
172
+ resolvedPages = ctx.routeTree ? resolvePagePrerender(ctx.routeTree.root) : new Map();
174
173
  }
175
174
 
176
175
  return {
@@ -181,6 +180,39 @@ export function timberPrerenderSugar(ctx: PluginContext): Plugin {
181
180
  resolvedPages = null;
182
181
  },
183
182
 
183
+ /**
184
+ * Dev: an edit can change the resolved prerender value of pages other
185
+ * than the edited file — a layout's `export const prerender` cascades to
186
+ * every descendant page. Vite re-transforms only the edited file, so
187
+ * the pages whose value changed are added to the update; through the
188
+ * RSC entry's HMR boundary they re-execute with the new wrapping
189
+ * (TIM-1588: dev caches prerendered output, so a stale wrapping is
190
+ * observable — a page switched to `prerender = false` would still be
191
+ * captured under the build rules). Runs after timber-routing's watcher
192
+ * rescan, which happens synchronously when the event fires.
193
+ */
194
+ hotUpdate({ file, modules }) {
195
+ if (this.environment.name !== 'rsc' || !file.startsWith(ctx.appDir)) return;
196
+ const previous = resolvedPages ?? new Map<string, PrerenderExportValue>();
197
+ // Values are read from disk (mtime-checked), so resolve again even
198
+ // when the tree object is unchanged.
199
+ resolvedPages = null;
200
+ ensureResolved();
201
+ const next = resolvedPages!;
202
+ const changedPages = new Set([...previous.keys(), ...next.keys()]);
203
+ for (const page of changedPages) {
204
+ if (JSON.stringify(previous.get(page)) === JSON.stringify(next.get(page))) {
205
+ changedPages.delete(page);
206
+ }
207
+ }
208
+ changedPages.delete(file);
209
+ const extra = [...changedPages].flatMap((page) => [
210
+ ...(this.environment.moduleGraph.getModulesByFile(page) ?? []),
211
+ ]);
212
+ if (extra.length === 0) return;
213
+ return [...modules, ...extra];
214
+ },
215
+
184
216
  transform(code, id) {
185
217
  // Only process in RSC environment (same gate as prebuilt.ts)
186
218
  if (this?.environment?.name === 'client') return;
@@ -8,7 +8,7 @@
8
8
  * Design docs: 18-build-system.md §"Virtual Modules", 07-routing.md
9
9
  */
10
10
 
11
- import type { Plugin, ViteDevServer } from 'vite';
11
+ import { isRunnableDevEnvironment, type Plugin, type ViteDevServer } from 'vite';
12
12
  import { join } from 'node:path';
13
13
  import { scanRoutes } from '../routing/scanner.ts';
14
14
  import { buildDirToRouteMap, type SegmentInfo } from '../routing/segment-codegen.ts';
@@ -21,6 +21,8 @@ import {
21
21
  formatConventionWarnings,
22
22
  } from '../routing/convention-lint.ts';
23
23
  import type { PluginContext } from '../plugin-context.ts';
24
+ import { redirectOrphanedModules } from './orphaned-modules.ts';
25
+ import { RSC_ENTRY_FILE } from './entries.ts';
24
26
 
25
27
  const VIRTUAL_MODULE_ID = 'virtual:timber-route-manifest';
26
28
  const RESOLVED_VIRTUAL_ID = `\0${VIRTUAL_MODULE_ID}`;
@@ -138,6 +140,26 @@ export function timberRouting(ctx: PluginContext): Plugin {
138
140
  return {
139
141
  name: 'timber-routing',
140
142
 
143
+ /**
144
+ * Keep an update to an orphaned RSC module (a deleted route file created
145
+ * again, a server-reference module) from full-reloading the RSC module
146
+ * runner, which leaks a module generation. See plugins/orphaned-modules.ts.
147
+ */
148
+ hotUpdate({ modules }) {
149
+ if (this.environment.name !== 'rsc') return;
150
+ const environment = this.environment;
151
+ return redirectOrphanedModules(
152
+ {
153
+ moduleGraph: environment.moduleGraph,
154
+ evaluatedModules: isRunnableDevEnvironment(environment)
155
+ ? environment.runner.evaluatedModules
156
+ : undefined,
157
+ },
158
+ modules,
159
+ RSC_ENTRY_FILE
160
+ );
161
+ },
162
+
141
163
  /**
142
164
  * Resolve the virtual module ID.
143
165
  *
@@ -0,0 +1,115 @@
1
+ /**
2
+ * Dev-only: key plugin-rsc's reference-module caches by source generation
3
+ * instead of by render.
4
+ *
5
+ * In dev, plugin-rsc appends a fresh random tag (`$$cache=<random>`) to every
6
+ * reference id each time it builds a manifest, and it builds one per call: a
7
+ * client manifest per Flight render, a server manifest per `decodeReply` /
8
+ * `decodeAction`. The tag forces a fresh module load after an edit. But the
9
+ * module loaders behind those ids (`globalThis.__vite_rsc_client_require__`
10
+ * in SSR, `__vite_rsc_server_require__` in RSC) are memoized by the full
11
+ * tagged id in a Map that is never pruned, so every request adds one entry
12
+ * per reference it touches, for the life of the dev server.
13
+ *
14
+ * Each entry is a promise created mid-render. React's dev Flight server
15
+ * records every live promise in an async-hook Map, with a debug chain that
16
+ * reaches the render's components, props, and request. A promise that lives
17
+ * forever therefore pins the request that created it: the dev server kept
18
+ * every rendered request, response, and socket (TIM-1589).
19
+ *
20
+ * The wrapper here rewrites the tag to the current source generation, which
21
+ * the environment's HMR updates advance. Within a generation every render
22
+ * shares one load per module (the cache grows per edit, not per request);
23
+ * after an edit the new generation loads fresh modules, as the random tag
24
+ * did. A render keeps the generation it started in: its tag is bound to a
25
+ * generation the first time it is seen, so a render that spans an edit still
26
+ * finds the promises it preloaded (Flight's synchronous `requireModule`
27
+ * reads the settled value of the very promise it preloaded).
28
+ *
29
+ * Production ids carry no tag and pass through untouched; the install calls
30
+ * sit behind `import.meta.hot`, so production never wraps anything.
31
+ */
32
+
33
+ const CACHE_TAG = '$$cache=';
34
+
35
+ /**
36
+ * How long a tag keeps its generation. A render cannot outlive its render
37
+ * timeout (at most RENDER_TIMEOUT_CEILING_MS, two minutes, unless configured
38
+ * higher), so a tag older than this belongs to a finished render. Expiring by
39
+ * age, not by count, means no number of newer renders can evict a render
40
+ * still in flight (TIM-1589).
41
+ */
42
+ const TAG_TTL_MS = 10 * 60_000;
43
+
44
+ /** The two module loaders plugin-rsc memoizes by tagged reference id. */
45
+ export type ReferenceRequireGlobal = '__vite_rsc_client_require__' | '__vite_rsc_server_require__';
46
+
47
+ type ReferenceRequire = (id: string) => unknown;
48
+
49
+ /** The slice of `import.meta.hot` this module needs. */
50
+ export interface ReferenceCacheHot {
51
+ on(event: 'vite:beforeUpdate' | 'vite:beforeFullReload', listener: () => void): void;
52
+ }
53
+
54
+ interface GenerationState {
55
+ generation: number;
56
+ }
57
+
58
+ /** Marks an installed wrapper, carrying its generation, on the function itself. */
59
+ const STATE = Symbol.for('timber.devReferenceCache');
60
+
61
+ function isReferenceRequire(value: unknown): value is ReferenceRequire {
62
+ return typeof value === 'function';
63
+ }
64
+
65
+ function isGenerationState(value: unknown): value is GenerationState {
66
+ return typeof value === 'object' && value !== null && 'generation' in value;
67
+ }
68
+
69
+ /**
70
+ * Wrap plugin-rsc's memoized loader `name` so its cache is keyed by source
71
+ * generation. Idempotent: a re-executed caller reuses the installed wrapper
72
+ * and its generation (resetting it would hand later renders the previous
73
+ * generation's modules), and re-registers the HMR listeners, which Vite drops
74
+ * with the re-executed module's hot context. A runner reload evaluates
75
+ * plugin-rsc again, which installs a fresh loader and cache to wrap.
76
+ */
77
+ export function scopeReferenceCacheToGeneration(
78
+ name: ReferenceRequireGlobal,
79
+ hot: ReferenceCacheHot
80
+ ): void {
81
+ const installed: unknown = Reflect.get(globalThis, name);
82
+ if (!isReferenceRequire(installed)) return;
83
+
84
+ const existing: unknown = Reflect.get(installed, STATE);
85
+ const state: GenerationState = isGenerationState(existing) ? existing : { generation: 0 };
86
+ if (state !== existing) {
87
+ const original = installed;
88
+ // In first-seen order (Map insertion order), so expired tags are at the front.
89
+ const tagGeneration = new Map<string, { generation: number; seenAt: number }>();
90
+ const scoped: ReferenceRequire = (id) => {
91
+ const at = id.indexOf(CACHE_TAG);
92
+ if (at < 0) return original(id);
93
+ const tag = id.slice(at + CACHE_TAG.length);
94
+ const now = Date.now();
95
+ let binding = tagGeneration.get(tag);
96
+ if (!binding) {
97
+ for (const [seen, { seenAt }] of tagGeneration) {
98
+ if (now - seenAt < TAG_TTL_MS) break;
99
+ tagGeneration.delete(seen);
100
+ }
101
+ binding = { generation: state.generation, seenAt: now };
102
+ tagGeneration.set(tag, binding);
103
+ }
104
+ return original(`${id.slice(0, at)}${CACHE_TAG}g${binding.generation}`);
105
+ };
106
+ Reflect.set(scoped, STATE, state);
107
+ Reflect.set(globalThis, name, scoped);
108
+ }
109
+
110
+ const advance = (): void => {
111
+ state.generation++;
112
+ };
113
+ hot.on('vite:beforeUpdate', advance);
114
+ hot.on('vite:beforeFullReload', advance);
115
+ }
@@ -1,3 +1,5 @@
1
+ /// <reference types="vite/client" />
2
+
1
3
  /**
2
4
  * RSC Runtime Adapter — Re-exports from @vitejs/plugin-rsc/rsc.
3
5
  *
@@ -14,6 +16,8 @@
14
16
  * `renderFlight` too.
15
17
  */
16
18
 
19
+ import { scopeReferenceCacheToGeneration } from './dev-reference-cache.ts';
20
+
17
21
  // The only way to render Flight; see render-flight.ts.
18
22
  export { renderFlight } from './render-flight.ts';
19
23
 
@@ -32,3 +36,9 @@ export {
32
36
  // "use cache" (use-cache-wrapper.ts).
33
37
  createFromReadableStream,
34
38
  } from '@vitejs/plugin-rsc/rsc';
39
+
40
+ // plugin-rsc caches server-reference modules per decode in dev, which pins
41
+ // every action request; scope the cache to the source generation instead.
42
+ if (import.meta.hot) {
43
+ scopeReferenceCacheToGeneration('__vite_rsc_server_require__', import.meta.hot);
44
+ }
@@ -1,3 +1,5 @@
1
+ /// <reference types="vite/client" />
2
+
1
3
  /**
2
4
  * SSR Runtime Adapter — Re-exports from @vitejs/plugin-rsc/ssr.
3
5
  *
@@ -12,8 +14,16 @@
12
14
 
13
15
  import { nodeStreamsPlatform } from '../server/node-streams-platform.ts';
14
16
 
17
+ import { scopeReferenceCacheToGeneration } from './dev-reference-cache.ts';
18
+
15
19
  export { createFromReadableStream } from '@vitejs/plugin-rsc/ssr';
16
20
 
21
+ // plugin-rsc caches client-reference modules per render in dev, which pins
22
+ // every request; scope the cache to the source generation instead.
23
+ if (import.meta.hot) {
24
+ scopeReferenceCacheToGeneration('__vite_rsc_client_require__', import.meta.hot);
25
+ }
26
+
17
27
  /**
18
28
  * Decode a Node Flight source (`server/flight-source.ts`) for SSR — plugin-rsc's
19
29
  * `ssr.node` entry, which reads a Node `Readable`, string chunks included.