@timber-js/app 0.2.0-alpha.225 → 0.2.0-alpha.227

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 (45) hide show
  1. package/dist/_chunks/{build-output-helper-B7wWGTfR.js → build-output-helper-5UsltK-S.js} +29 -2
  2. package/dist/_chunks/build-output-helper-5UsltK-S.js.map +1 -0
  3. package/dist/_chunks/{cloudflare-B75X6u4O.js → cloudflare-_2fhxQE8.js} +4 -20
  4. package/dist/_chunks/{cloudflare-B75X6u4O.js.map → cloudflare-_2fhxQE8.js.map} +1 -1
  5. package/dist/_chunks/navigation-root-M3B2ZrdO.js.map +1 -1
  6. package/dist/adapters/cloudflare-dev.js +1 -1
  7. package/dist/adapters/cloudflare-kv-cache.js +1 -1
  8. package/dist/adapters/cloudflare.d.ts +0 -7
  9. package/dist/adapters/cloudflare.d.ts.map +1 -1
  10. package/dist/adapters/cloudflare.js +1 -1
  11. package/dist/adapters/nitro.d.ts.map +1 -1
  12. package/dist/adapters/nitro.js +6 -5
  13. package/dist/adapters/nitro.js.map +1 -1
  14. package/dist/adapters/shared.d.ts +18 -0
  15. package/dist/adapters/shared.d.ts.map +1 -1
  16. package/dist/client/navigation-root.d.ts.map +1 -1
  17. package/dist/client/nuqs-adapter.d.ts +4 -1
  18. package/dist/client/nuqs-adapter.d.ts.map +1 -1
  19. package/dist/rsc-runtime/rsc.d.ts +2 -2
  20. package/dist/rsc-runtime/rsc.d.ts.map +1 -1
  21. package/dist/rsc-runtime/server-reference-load-error.d.ts +14 -0
  22. package/dist/rsc-runtime/server-reference-load-error.d.ts.map +1 -0
  23. package/dist/rsc-runtime/server-references.d.ts +11 -0
  24. package/dist/rsc-runtime/server-references.d.ts.map +1 -1
  25. package/dist/server/action-handler.d.ts +7 -5
  26. package/dist/server/action-handler.d.ts.map +1 -1
  27. package/dist/server/ssr-entry.d.ts.map +1 -1
  28. package/dist/server/ssr-wrappers.d.ts +9 -10
  29. package/dist/server/ssr-wrappers.d.ts.map +1 -1
  30. package/package.json +2 -2
  31. package/src/adapters/cloudflare.ts +7 -19
  32. package/src/adapters/nitro.ts +12 -5
  33. package/src/adapters/shared.ts +31 -0
  34. package/src/client/navigation-root.tsx +7 -6
  35. package/src/client/nuqs-adapter.tsx +46 -28
  36. package/src/rsc-runtime/rsc.ts +8 -7
  37. package/src/rsc-runtime/server-reference-load-error.ts +16 -0
  38. package/src/rsc-runtime/server-references.ts +63 -1
  39. package/src/server/action-handler.ts +31 -17
  40. package/src/server/ssr-entry.ts +0 -2
  41. package/src/server/ssr-wrappers.tsx +39 -49
  42. package/dist/_chunks/build-output-helper-B7wWGTfR.js.map +0 -1
  43. package/dist/server/nuqs-ssr-provider.d.ts +0 -32
  44. package/dist/server/nuqs-ssr-provider.d.ts.map +0 -1
  45. package/src/server/nuqs-ssr-provider.tsx +0 -64
@@ -1 +1 @@
1
- {"version":3,"file":"ssr-wrappers.d.ts","sourceRoot":"","sources":["../../src/server/ssr-wrappers.tsx"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6CG;AAEH,OAAO,EAA2B,KAAK,SAAS,EAAE,MAAM,OAAO,CAAC;AAkDhE,oDAAoD;AACpD,MAAM,WAAW,cAAc;IAC7B,+CAA+C;IAC/C,QAAQ,EAAE,MAAM,CAAC;IACjB;;;;OAIG;IACH,MAAM,EAAE,MAAM,CAAC;IACf;;;;OAIG;IACH,YAAY,EAAE,OAAO,CAAC;IACtB,oEAAoE;IACpE,YAAY,EAAE,OAAO,CAAC;CACvB;AAED;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AACH,wBAAgB,cAAc,CAAC,OAAO,EAAE,SAAS,EAAE,IAAI,EAAE,cAAc,GAAG,SAAS,CAmBlF"}
1
+ {"version":3,"file":"ssr-wrappers.d.ts","sourceRoot":"","sources":["../../src/server/ssr-wrappers.tsx"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8CG;AAEH,OAAO,EAA2B,KAAK,SAAS,EAAE,MAAM,OAAO,CAAC;AAyChE,oDAAoD;AACpD,MAAM,WAAW,cAAc;IAC7B,+CAA+C;IAC/C,QAAQ,EAAE,MAAM,CAAC;IACjB;;;;OAIG;IACH,MAAM,EAAE,MAAM,CAAC;IACf;;;;OAIG;IACH,YAAY,EAAE,OAAO,CAAC;CACvB;AAED;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AACH,wBAAgB,cAAc,CAAC,OAAO,EAAE,SAAS,EAAE,IAAI,EAAE,cAAc,GAAG,SAAS,CAmBlF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@timber-js/app",
3
- "version": "0.2.0-alpha.225",
3
+ "version": "0.2.0-alpha.227",
4
4
  "description": "Vite-native React framework built for Servers and Serverless Platforms — correct HTTP semantics, real status codes, pages that work without JavaScript",
5
5
  "keywords": [
6
6
  "cloudflare-workers",
@@ -167,7 +167,7 @@
167
167
  "@content-collections/vite": "^0.2.0 || ^0.3.0",
168
168
  "@typescript/native-preview": "^7.0.0-dev.0",
169
169
  "@vitejs/plugin-react": "^6.1.0",
170
- "@vitejs/plugin-rsc": "^0.5.36",
170
+ "@vitejs/plugin-rsc": "^0.5.39",
171
171
  "nuqs": "^2.0.0",
172
172
  "react": "19.3.1",
173
173
  "react-dom": "19.3.1",
@@ -21,7 +21,12 @@ import {
21
21
  buildStaticDirectoryOutput,
22
22
  writeHeadersFile,
23
23
  } from './build-output-helper.ts';
24
- import { adapterBase, generateHeadersFile } from './shared.ts';
24
+ import {
25
+ adapterBase,
26
+ generateHeadersFile,
27
+ generateRuntimeInitModule,
28
+ RUNTIME_INIT_MODULE,
29
+ } from './shared.ts';
25
30
  // Isomorphic, zero-import module — safe to load from an adapter, which Node's
26
31
  // native ESM loader evaluates before Vite's resolver exists. Same precedent as
27
32
  // `adapters/shared.ts` importing `../shared/base-path.js`.
@@ -321,7 +326,7 @@ export function cloudflare(options: CloudflareAdapterOptions = {}): TimberPlatfo
321
326
  // BEFORE the RSC entry evaluates (ESM import order). Without this,
322
327
  // createRequestHandler's auto-wire for WorkersCachePurge would not
323
328
  // detect the Cloudflare runtime (TIM-1170).
324
- await writeFile(join(outDir, '_timber-runtime-init.js'), generateRuntimeInitModule());
329
+ await writeFile(join(outDir, RUNTIME_INIT_MODULE), generateRuntimeInitModule('cloudflare'));
325
330
 
326
331
  // Generate the Workers entry point
327
332
  const hasManifestInit = !!artifacts.manifestInit;
@@ -647,23 +652,6 @@ globalThis.__TIMBER_PREBUILT_SOURCE__ = {
647
652
  `;
648
653
  }
649
654
 
650
- /**
651
- * Generate the runtime init module that sets TIMBER_RUNTIME before the
652
- * RSC entry evaluates. Imported as a side-effect module in _worker.js.
653
- *
654
- * @internal Exported for testing.
655
- */
656
- export function generateRuntimeInitModule(): string {
657
- return `// Generated by @timber-js/app/adapters/cloudflare
658
- // Sets TIMBER_RUNTIME before the RSC handler evaluates (TIM-1170).
659
- // Must be a separate module imported before rsc/index.js so that ESM
660
- // evaluation order guarantees the env var is set when
661
- // createRequestHandler() runs its auto-wire logic.
662
- globalThis.process ??= { env: {} }
663
- process.env.TIMBER_RUNTIME = 'cloudflare'
664
- `;
665
- }
666
-
667
655
  /** Wrangler binding sections generated from `CloudflareBindings`. */
668
656
  export interface WranglerBindingsConfig {
669
657
  kv_namespaces?: Array<{ binding: string; id: string }>;
@@ -23,7 +23,7 @@ import {
23
23
  generateSendResponseModule,
24
24
  spawnNitroPreview,
25
25
  } from './nitro-preview.ts';
26
- import { adapterBase } from './shared.ts';
26
+ import { adapterBase, generateRuntimeInitModule, RUNTIME_INIT_MODULE } from './shared.ts';
27
27
  import { HEADERS_FILE, REDIRECTS_FILE } from '../shared/static-platform-files.ts';
28
28
  import type {
29
29
  BuildArtifacts,
@@ -215,6 +215,13 @@ export function nitro(options: NitroAdapterOptions = {}): TimberPlatformAdapter
215
215
  await writeFile(rscEntry, `${artifacts.manifestInit}\n${rscContent}`);
216
216
  }
217
217
 
218
+ // Sets TIMBER_RUNTIME ahead of the RSC entry's top-level await of
219
+ // instrumentation register(); the entry imports it first.
220
+ await writeFile(
221
+ join(outDir, RUNTIME_INIT_MODULE),
222
+ generateRuntimeInitModule(PRESET_CONFIGS[preset].runtimeName)
223
+ );
224
+
218
225
  // Generate the Nitro entry point (imports from ./rsc/ within nitro dir)
219
226
  const entry = generateNitroEntry(preset, compress, artifacts.immutableDirs);
220
227
  await writeFile(join(outDir, 'entry.ts'), entry);
@@ -303,7 +310,6 @@ export function generateNitroEntry(
303
310
  // The manifest init is prepended to rsc/index.js before the nitro build,
304
311
  // so globalThis.__TIMBER_BUILD_MANIFEST__ is set before any code reads it.
305
312
  const serverEntryRelative = './rsc/index.js';
306
- const runtimeName = PRESET_CONFIGS[preset].runtimeName;
307
313
  const earlyHints = PRESET_CONFIGS[preset].supportsEarlyHints;
308
314
  const supportsWaitUntil = PRESET_CONFIGS[preset].supportsWaitUntil;
309
315
 
@@ -363,11 +369,12 @@ export function generateNitroEntry(
363
369
  return `// Generated by @timber-js/app/adapters/nitro
364
370
  // Do not edit — this file is regenerated on each build.
365
371
 
372
+ // Side-effect import, first: sets TIMBER_RUNTIME before the RSC entry (and
373
+ // its top-level await of instrumentation register()) evaluates.
374
+ // See design/25-production-deployments.md §"TIMBER_RUNTIME".
375
+ import './${RUNTIME_INIT_MODULE}'
366
376
  import handler, { runWithEarlyHintsSender${waitUntilImport} } from '${serverEntryRelative}'
367
377
  ${compressImport}${immutableAssets.imports}
368
- // Set TIMBER_RUNTIME for instrumentation.ts conditional SDK initialization.
369
- // See design/25-production-deployments.md §"TIMBER_RUNTIME".
370
- process.env.TIMBER_RUNTIME = '${runtimeName}'
371
378
 
372
379
  // Nitro's index.mjs wraps this import with defineLazyEventHandler, which
373
380
  // already handles the event handler protocol. We export a plain async
@@ -281,3 +281,34 @@ export function generateHeadersFile({
281
281
 
282
282
  return content;
283
283
  }
284
+
285
+ // ─── TIMBER_RUNTIME ──────────────────────────────────────────────────────
286
+
287
+ /** File name of the generated module that sets `TIMBER_RUNTIME`. */
288
+ export const RUNTIME_INIT_MODULE = '_timber-runtime-init.js';
289
+
290
+ /**
291
+ * Generate the module that sets `process.env.TIMBER_RUNTIME`.
292
+ *
293
+ * It must be its own module, imported for side effects ahead of the RSC
294
+ * entry. ESM evaluates every import of a module — including the imported
295
+ * module's top-level await — before that module's own body runs, and the
296
+ * RSC entry awaits `register()` from instrumentation.ts at top level. An
297
+ * assignment in the importing entry's body would therefore run after
298
+ * `register()` has already read the variable. A side-effect import listed
299
+ * first is evaluated first. See design/25-production-deployments.md
300
+ * §"TIMBER_RUNTIME".
301
+ *
302
+ * `globalThis.process ??= { env: {} }` covers runtimes without a Node
303
+ * `process` global (Workers without nodejs_compat, some edge presets).
304
+ */
305
+ export function generateRuntimeInitModule(runtimeName: string): string {
306
+ return `// Generated by @timber-js/app — do not edit.
307
+ // Sets TIMBER_RUNTIME before the RSC entry evaluates. Imported as a
308
+ // side-effect module ahead of the RSC entry so ESM evaluation order
309
+ // guarantees instrumentation.ts register() sees it.
310
+ globalThis.process ??= { env: {} }
311
+ globalThis.process.env ??= {}
312
+ process.env.TIMBER_RUNTIME = ${JSON.stringify(runtimeName)}
313
+ `;
314
+ }
@@ -218,19 +218,20 @@ export function NavigationRoot({
218
218
 
219
219
  // Inject TopLoader alongside the element tree. It subscribes to the router's
220
220
  // pending store itself, so it takes no props from here beyond its config,
221
- // and only it re-renders when a navigation starts or ends. Rendered only
222
- // when not explicitly disabled via config.
221
+ // and only it re-renders when a navigation starts or ends. Its slot holds
222
+ // `null` when the loader is disabled via config.
223
223
  //
224
224
  // This Fragment is a FORK — two children — so it advances React's tree
225
225
  // context and shifts every `useId` below it. `server/ssr-wrappers.tsx`
226
- // mirrors it for exactly that reason; a single-child wrapper would not need
227
- // a mirror. See tests/ssr-wrapper-parity.test.ts.
226
+ // mirrors it for exactly that reason, and renders the document's default
227
+ // <meta> tags in the first slot. The fork is unconditional so the server
228
+ // never needs to know whether the loader is enabled: a `null` child still
229
+ // counts toward the fork on both sides. See tests/ssr-wrapper-parity.test.ts.
228
230
  const showTopLoader = topLoaderConfig?.enabled !== false;
229
- if (!showTopLoader) return rendered.element;
230
231
  return createElement(
231
232
  Fragment,
232
233
  null,
233
- createElement(TopLoader, { config: topLoaderConfig }),
234
+ showTopLoader ? createElement(TopLoader, { config: topLoaderConfig }) : null,
234
235
  rendered.element
235
236
  );
236
237
  }
@@ -12,7 +12,7 @@
12
12
  */
13
13
  'use client';
14
14
 
15
- import { useState, useEffect, useMemo, type ReactNode } from 'react';
15
+ import { useMemo, type ReactNode } from 'react';
16
16
  import {
17
17
  unstable_createAdapterProvider as createAdapterProvider,
18
18
  renderQueryString,
@@ -22,6 +22,7 @@ import {
22
22
  import { getRouter } from './router-ref.ts';
23
23
  import { getNavigationApi } from './navigation-api.ts';
24
24
  import { locationSearch } from './location-search.ts';
25
+ import { useNavigationContext } from './navigation-context.ts';
25
26
 
26
27
  // ─── Adapter Hook ─────────────────────────────────────────────────
27
28
 
@@ -29,28 +30,36 @@ import { locationSearch } from './location-search.ts';
29
30
  * Custom adapter hook for nuqs. Returns the current search params
30
31
  * and an updateUrl function that integrates with timber's router.
31
32
  *
32
- * @param _watchKeys - param keys this hook instance cares about
33
- * (used by nuqs for selective re-rendering)
33
+ * nuqs calls this once per `useQueryStates` call, from the calling
34
+ * component, so every instance must read ONE source. It reads the router's:
35
+ * `NavigationContext.search`, the value `useSearchParams()` reads. The router
36
+ * moves it on every navigation, traversal and shallow write — the Navigation
37
+ * API's shallow handler and the History API patch both run
38
+ * `syncShallowSearch` (browser-entry/router-init.ts) — so the adapter needs
39
+ * no listeners of its own, and nuqs and `useSearchParams()` cannot disagree.
40
+ * During SSR the same provider carries the request's raw query string, so
41
+ * this one hook serves both sides.
42
+ *
43
+ * Per-instance state used to live here instead: a shallow write moved only
44
+ * the writer's copy, and every other `useQueryStates` call snapped back to
45
+ * the old value on its next render.
46
+ *
47
+ * @param watchKeys - URL keys this hook instance reads. The returned params
48
+ * hold only those keys and keep their identity while those keys are
49
+ * unchanged, so a write to another key does not re-render this instance's
50
+ * consumers through nuqs.
34
51
  */
35
- function useTimberAdapter(_watchKeys: string[]): AdapterInterface {
36
- const [searchParams, setSearchParams] = useState(() => new URLSearchParams(locationSearch()));
37
-
38
- // Sync search params on popstate (back/forward) and after
39
- // timber navigations that change the URL.
40
- useEffect(() => {
41
- function sync() {
42
- setSearchParams(new URLSearchParams(locationSearch()));
43
- }
44
-
45
- window.addEventListener('popstate', sync);
46
- // timber dispatches a custom event after client navigations complete
47
- window.addEventListener('timber:navigation-end', sync);
48
-
49
- return () => {
50
- window.removeEventListener('popstate', sync);
51
- window.removeEventListener('timber:navigation-end', sync);
52
- };
53
- }, []);
52
+ function useTimberAdapter(watchKeys: string[]): AdapterInterface {
53
+ const nav = useNavigationContext();
54
+ if (nav === null) {
55
+ throw new Error(
56
+ '[timber] useQueryStates() was called outside the timber app tree ' +
57
+ '(no NavigationProvider found). In tests, render the component ' +
58
+ 'inside the timber providers.'
59
+ );
60
+ }
61
+ const watched = filterKeys(new URLSearchParams(nav.search), watchKeys).toString();
62
+ const searchParams = useMemo(() => new URLSearchParams(watched), [watched]);
54
63
 
55
64
  const updateUrl = useMemo(() => {
56
65
  return (search: URLSearchParams, options: Required<AdapterOptions>) => {
@@ -63,9 +72,9 @@ function useTimberAdapter(_watchKeys: string[]): AdapterInterface {
63
72
  // info: { shallow: true } so the navigate event handler knows to
64
73
  // skip interception. Without this, the navigate event fired by
65
74
  // history.pushState/replaceState would trigger a full RSC fetch.
66
- const nav = getNavigationApi();
67
- if (nav) {
68
- nav.navigate(url.toString(), {
75
+ const navigation = getNavigationApi();
76
+ if (navigation) {
77
+ navigation.navigate(url.toString(), {
69
78
  history: options.history === 'push' ? 'push' : 'replace',
70
79
  info: { shallow: true },
71
80
  });
@@ -75,8 +84,8 @@ function useTimberAdapter(_watchKeys: string[]): AdapterInterface {
75
84
  method.call(window.history, window.history.state, '', url.toString());
76
85
  }
77
86
 
78
- // Update local state to reflect the new URL
79
- setSearchParams(new URLSearchParams(url.search));
87
+ // No local state to set: both paths reach the router's
88
+ // syncShallowSearch, which re-renders NavigationContext.
80
89
  } else {
81
90
  // Non-shallow (timber default): trigger RSC navigation to fetch
82
91
  // fresh server data for the new search params.
@@ -100,6 +109,12 @@ function useTimberAdapter(_watchKeys: string[]): AdapterInterface {
100
109
  };
101
110
  }
102
111
 
112
+ /** The entries of `search` whose key is in `keys`; all of them when `keys` is empty. */
113
+ function filterKeys(search: URLSearchParams, keys: string[]): URLSearchParams {
114
+ if (keys.length === 0) return search;
115
+ return new URLSearchParams([...search].filter(([key]) => keys.includes(key)));
116
+ }
117
+
103
118
  // ─── Provider Component ───────────────────────────────────────────
104
119
 
105
120
  // Lazily created — createAdapterProvider calls React.createElement internally,
@@ -111,7 +126,10 @@ let _TimberNuqsProvider: ReturnType<typeof createAdapterProvider> | undefined;
111
126
  * Wraps the React tree with nuqs's adapter context, configured with
112
127
  * timber's default options.
113
128
  *
114
- * Auto-injected in browser-entry.ts — no user setup required.
129
+ * Auto-injected around the app on both sides — the browser's root render
130
+ * (browser-entry/router-init.ts) and the SSR wrapper chain
131
+ * (server/ssr-wrappers.tsx) — no user setup required. It must sit above
132
+ * NavigationProvider's consumers, which every `useQueryStates` caller is.
115
133
  */
116
134
  export function TimberNuqsAdapter({ children }: { children: ReactNode }) {
117
135
  const Provider = (_TimberNuqsProvider ??= createAdapterProvider(useTimberAdapter));
@@ -11,8 +11,9 @@
11
11
  *
12
12
  * Keep this as thin pass-through re-exports — the value is the single choke
13
13
  * point, not abstraction. The exceptions are `renderFlight`, the only way to
14
- * render Flight (render-flight.ts), and `loadServerAction`, which tells an
15
- * unknown reference from a broken module (server-references.ts). Bound-args encryption is plugin-rsc's
14
+ * render Flight (render-flight.ts), and `loadServerAction`, `decodeReply` and
15
+ * `decodeAction`, which tell an unknown reference from a broken module
16
+ * (server-references.ts). Bound-args encryption is plugin-rsc's
16
17
  * injected runtime, resolved to encryption-runtime.ts so it renders through
17
18
  * `renderFlight` too.
18
19
  */
@@ -22,13 +23,13 @@ import { scopeReferenceCacheToGeneration } from './dev-reference-cache.ts';
22
23
  // The only way to render Flight; see render-flight.ts.
23
24
  export { renderFlight } from './render-flight.ts';
24
25
 
25
- // Resolves an unknown reference to undefined instead of rejecting, so a
26
- // rejection means a real module failed to load; see server-references.ts.
27
- export { loadServerAction } from './server-references.ts';
26
+ // `loadServerAction` resolves an unknown reference to undefined instead of
27
+ // rejecting, so a rejection means a real module failed to load. The decoders
28
+ // reject with `ServerReferenceLoadError` (server-reference-load-error.ts) for
29
+ // that case alone. See server-references.ts.
30
+ export { loadServerAction, decodeReply, decodeAction } from './server-references.ts';
28
31
 
29
32
  export {
30
- decodeReply,
31
- decodeAction,
32
33
  // No-JS action result → the `useActionState` hook that submitted it
33
34
  // (server/action-handler.ts), as Next.js does in its action handler.
34
35
  decodeFormState,
@@ -0,0 +1,16 @@
1
+ /**
2
+ * A server reference a request body named is a known module that failed to
3
+ * load: the server's fault, where any other decode failure is the client's.
4
+ * `cause` is the module's own error. Thrown by `decodeReply` and
5
+ * `decodeAction` (server-references.ts); kept apart from them so code that
6
+ * only checks for it does not import plugin-rsc's virtual modules.
7
+ */
8
+ export class ServerReferenceLoadError extends Error {
9
+ constructor(
10
+ readonly referenceId: string,
11
+ options: { cause: unknown }
12
+ ) {
13
+ super(`Server reference "${referenceId}" failed to load`, options);
14
+ this.name = 'ServerReferenceLoadError';
15
+ }
16
+ }
@@ -16,10 +16,18 @@
16
16
  * plugin-rsc's loader reads, and an unknown module resolves to `undefined`:
17
17
  * what plugin-rsc already resolves for an unknown export of a known module.
18
18
  * A rejection from the load itself is then a real failure.
19
+ *
20
+ * `decodeReply` and `decodeAction` make the same split for the references a
21
+ * request body names, which React loads while it decodes.
19
22
  */
20
23
 
21
- import { loadServerAction as loadServerReference } from '@vitejs/plugin-rsc/rsc';
24
+ import {
25
+ decodeAction as decodeActionWith,
26
+ decodeReply as decodeReplyWith,
27
+ loadServerAction as loadServerReference,
28
+ } from '@vitejs/plugin-rsc/rsc';
22
29
  import serverReferences from 'virtual:vite-rsc/server-references';
30
+ import { ServerReferenceLoadError } from './server-reference-load-error.ts';
23
31
 
24
32
  /**
25
33
  * Whether plugin-rsc knows `moduleId` as a `'use server'` module.
@@ -71,3 +79,57 @@ export async function loadServerAction(id: string): Promise<unknown> {
71
79
  if (!(await isServerReferenceModule(moduleId))) return undefined;
72
80
  return loadServerReference(id);
73
81
  }
82
+
83
+ type ServerReferenceListener = (reference: { id: string; name: string }) => void;
84
+
85
+ /**
86
+ * Run a plugin-rsc decode, and when it rejects, say whose fault it was.
87
+ *
88
+ * React loads every server reference the body names while it decodes (the
89
+ * no-JS action itself, and server functions passed as arguments or bound to
90
+ * one) and rejects the same way for a reference that does not exist and a
91
+ * module that fails to load. plugin-rsc reports each reference before it
92
+ * loads (`onServerReference`). The callback is synchronous and the dev
93
+ * lookup is not, so the references are only collected here. After a failed
94
+ * decode, each is loaded again through `loadServerAction`, which resolves an
95
+ * unknown one to undefined and rejects only for a known module that does not
96
+ * load. That rejection becomes a `ServerReferenceLoadError`. Anything else
97
+ * (a made-up reference, a body that will not parse) rethrows as the client
98
+ * error it is.
99
+ */
100
+ async function decodeNamingFaults<T>(
101
+ decode: (onServerReference: ServerReferenceListener) => Promise<T>
102
+ ): Promise<T> {
103
+ const references = new Set<string>();
104
+ try {
105
+ return await decode(({ id, name }) => references.add(`${id}#${name}`));
106
+ } catch (error) {
107
+ for (const reference of references) {
108
+ try {
109
+ await loadServerAction(reference);
110
+ } catch (loadError) {
111
+ throw new ServerReferenceLoadError(reference, { cause: loadError });
112
+ }
113
+ }
114
+ throw error;
115
+ }
116
+ }
117
+
118
+ /**
119
+ * plugin-rsc's `decodeReply`, rejecting with `ServerReferenceLoadError` when
120
+ * a server function among the arguments names a module that fails to load.
121
+ */
122
+ export function decodeReply(body: string | FormData): Promise<unknown[]> {
123
+ return decodeNamingFaults((onServerReference) =>
124
+ decodeReplyWith(body, undefined, { onServerReference })
125
+ );
126
+ }
127
+
128
+ /**
129
+ * plugin-rsc's `decodeAction`, rejecting with `ServerReferenceLoadError`
130
+ * when the form's action, or a server function bound to it, names a module
131
+ * that fails to load.
132
+ */
133
+ export function decodeAction(body: FormData): Promise<() => Promise<void>> {
134
+ return decodeNamingFaults((onServerReference) => decodeActionWith(body, { onServerReference }));
135
+ }
@@ -21,6 +21,9 @@ import {
21
21
  decodeFormState,
22
22
  renderFlight,
23
23
  } from '../rsc-runtime/rsc.ts';
24
+ // Not through rsc.ts: the class has no plugin-rsc dependency, so tests that
25
+ // stand in for the runtime do not have to provide it.
26
+ import { ServerReferenceLoadError } from '../rsc-runtime/server-reference-load-error.ts';
24
27
  import { flightChunkBytes, flightResponse, openFlightReader } from './flight-source.ts';
25
28
  import { concatBytes } from './stream-utils.ts';
26
29
 
@@ -96,11 +99,13 @@ export function isActionRequest(req: Request): boolean {
96
99
  * with `formState` — React's `decodeFormState` of the result, present
97
100
  * only when the submitted form used `useActionState` — handed to SSR
98
101
  * and hydration, where React gives it to the hook that submitted.
99
- * - `error`: the action threw. The page is rendered again with the error
100
- * in place of the page component, so the route's nearest error page
101
- * answers, with the
102
- * status the pipeline gives any unhandled error. The JS path rejects
103
- * the action for the same throw, so both reach an error boundary.
102
+ * - `error`: the action threw, or a module it needs (its own, or the one a
103
+ * server function bound to it lives in) failed to load. The page is
104
+ * rendered again with the error in place of the page component, so the
105
+ * route's nearest error page answers, with the status the pipeline gives
106
+ * any unhandled error. The JS path rejects the action for the same
107
+ * throw, and answers the load failure with a 500, so both reach an
108
+ * error boundary.
104
109
  *
105
110
  * Carries two cookie-related snapshots taken before the action's ALS scope
106
111
  * exits, so the rerender pipeline (which establishes its own fresh cookie
@@ -277,11 +282,11 @@ async function reportRevalidationErrors(req: Request, errors: readonly unknown[]
277
282
  * Any client can send these, so they are logged at warn with the reason and
278
283
  * no stack, and are not reported to `onRequestError`: an error tracker would
279
284
  * otherwise record whatever a client makes up (TIM-1601). A known action
280
- * module that fails to load is the server's fault, and `decodeRscActionCall`
281
- * answers it with a 500 and reports it. Two loads cannot be split that way
282
- * and land here: a server function passed as an argument, which
283
- * `decodeReply` loads, and the no-JS action, which `decodeAction` loads.
284
- * Their module's error is still the logged reason.
285
+ * module that fails to load is the server's fault, wherever it is loaded:
286
+ * the action by ID, a server function passed as an argument (`decodeReply`),
287
+ * or the no-JS action and what is bound to it (`decodeAction`). It is
288
+ * answered with a 500 (the no-JS path renders the error page) and reported,
289
+ * and never gets here.
285
290
  */
286
291
  function rejectActionRequest(req: Request, reason: unknown): Response {
287
292
  logActionRejected({
@@ -382,6 +387,12 @@ async function decodeRscActionCall(
382
387
  decoded = await decodeReply(await req.text());
383
388
  }
384
389
  } catch (error) {
390
+ if (error instanceof ServerReferenceLoadError) {
391
+ // A server function among the arguments lives in a module that does
392
+ // not load: the same server fault as the action's own module above.
393
+ await reportActionError(req, error.cause);
394
+ return new Response(null, { status: 500 });
395
+ }
385
396
  return rejectActionRequest(req, error);
386
397
  }
387
398
  // The client always encodes an argument list. Anything else would fail
@@ -643,13 +654,16 @@ async function handleFormAction(
643
654
  try {
644
655
  actionFn = (await decodeAction(formData)) as ((...args: unknown[]) => Promise<unknown>) | null;
645
656
  } catch (error) {
646
- // decodeAction both decodes the form's `$ACTION_REF_` metadata and loads
647
- // the module, and React does not say which failed. On a no-JS POST that
648
- // metadata is written by React into the form, so a failure is almost
649
- // always a forged or truncated request: 400, logged at warn with the
650
- // error as the reason. A module that genuinely fails to import also
651
- // breaks the RSC render of a page that imports it, which reports it; an
652
- // action module only a client component imports gets the warning alone.
657
+ if (error instanceof ServerReferenceLoadError) {
658
+ // The action's module, or the module of a server function bound to
659
+ // it, does not load: a server fault, answered with the error page as
660
+ // an action that threw is.
661
+ const errorId = randomUUID();
662
+ await reportActionError(req, error.cause, errorId);
663
+ return { kind: 'error', error: error.cause, errorId };
664
+ }
665
+ // Forged or truncated `$ACTION_REF_` metadata, or a reference to a
666
+ // module or export that does not exist: the client's mistake.
653
667
  return rejectActionRequest(req, error);
654
668
  }
655
669
  if (!actionFn) {
@@ -175,12 +175,10 @@ export async function handleSsr(
175
175
  // real NavigationProvider and PayloadRoot, not no-op mirrors —
176
176
  // so hooks resolve identically and useId() matches on both sides.
177
177
  // See TIM-532, TIM-1424.
178
- const hasTopLoader = _runtimeConfig.topLoader?.enabled !== false;
179
178
  const wrappedElement = wrapSsrElement(element, {
180
179
  pathname: navContext.pathname,
181
180
  search: navContext.search,
182
181
  paramsSource: params,
183
- hasTopLoader,
184
182
  });
185
183
 
186
184
  // Render to HTML stream (waits for onShellReady).