@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
@@ -9,7 +9,7 @@
9
9
  *
10
10
  * The client tree (`renderTree` in browser-entry/router-init.ts, used by
11
11
  * hydrate.ts too) wraps the RSC element with:
12
- * NavigationRoot → Fragment(TopLoader, ...) →
12
+ * NavigationRoot → Fragment(TopLoader | null, ...) →
13
13
  * TimberNuqsAdapter → NuqsAdapterProvider →
14
14
  * SlotContentCacheContext.Provider → SegmentUpdateContext.Provider →
15
15
  * NavigationProvider → PayloadRoot → ParamsProvider → element
@@ -21,8 +21,9 @@
21
21
  * during SSR — the same code path as the browser — with the request's
22
22
  * pathname and raw search string. The raw string preserves repeated
23
23
  * query keys (`?tag=a&tag=b`) and, since TIM-1428, is the only
24
- * representation of search state here — it feeds the nuqs SSR adapter
25
- * too, so no collapsed record exists to drift from it.
24
+ * representation of search state here — nuqs reads it too, through the
25
+ * same TimberNuqsAdapter the browser renders, so no collapsed record
26
+ * exists to drift from it.
26
27
  * 2. `useSegmentParams()` resolves from ParamsContext, published by
27
28
  * PayloadRoot from the same payload root row the browser will read —
28
29
  * one derivation on both sides instead of two that must agree.
@@ -46,53 +47,44 @@
46
47
  */
47
48
 
48
49
  import { createElement, Fragment, type ReactNode } from 'react';
49
- import { withNuqsSsrAdapter } from './nuqs-ssr-provider.tsx';
50
+ import { TimberNuqsAdapter } from '../client/nuqs-adapter.tsx';
50
51
  import { NavigationProvider } from '../client/navigation-context.ts';
51
52
  import { PayloadRoot } from '../client/params-context.ts';
52
53
 
53
54
  /**
54
55
  * SSR equivalent of NavigationRoot.
55
56
  *
56
- * On the client, the router renders NavigationRoot via `root.render` in a transition,
57
- * rendering `Fragment(TopLoader, element)` — or the element alone when the top
58
- * loader is disabled.
59
- *
60
- * The Fragment is the part that matters: it forks, so it advances React's tree
61
- * context. Both sides must agree on whether it is there, which is why
62
- * `hasTopLoader` is threaded in from the same config the client reads.
63
- */
64
- function SsrNavigationRoot({
65
- children,
66
- hasTopLoader,
67
- }: {
68
- children?: ReactNode;
69
- hasTopLoader: boolean;
70
- }): ReactNode {
71
- if (hasTopLoader) {
72
- return createElement(Fragment, null, createElement(SsrTopLoader, null), children);
73
- }
74
- return children as ReactNode;
75
- }
76
-
77
- /**
78
- * SSR equivalent of TopLoader.
79
- * Exists as a fiber node to match the client tree depth; renders nothing.
57
+ * On the client, the router renders NavigationRoot via `root.render` in a
58
+ * transition, rendering `Fragment(TopLoader | null, element)`. The Fragment is
59
+ * the part that matters: it forks, so it advances React's tree context, and it
60
+ * is unconditional on both sides — the loader's config only decides what fills
61
+ * the first slot.
80
62
  */
81
- function SsrTopLoader(): ReactNode {
82
- return null;
63
+ function SsrNavigationRoot({ children }: { children?: ReactNode }): ReactNode {
64
+ return createElement(Fragment, null, createElement(DocumentDefaults, null), children);
83
65
  }
84
66
 
85
67
  /**
86
- * SSR equivalent of TimberNuqsAdapter component boundary.
87
- * The actual NuqsAdapterProvider (from createAdapterProvider) is added
88
- * inside this wrapper via withNuqsSsrAdapter, matching the client's
89
- * TimberNuqsAdapter → NuqsAdapterProvider nesting.
68
+ * The document's framework defaults (design/16-metadata.md §"No Separate
69
+ * Viewport Type"), in the TopLoader's slot.
70
+ *
71
+ * Server-only: the browser renders TopLoader (or nothing) here, and React
72
+ * leaves head nodes it did not render alone during hydration, so the tags
73
+ * stay for the life of the document — no RSC payload, partial or full,
74
+ * carries them.
75
+ *
76
+ * Rendered before the payload so these are the FIRST charset/viewport tags
77
+ * Fizz collects. React writes every viewport <meta> into the head in render
78
+ * order, and browsers apply the last one, so a viewport <meta> in the app's
79
+ * root layout overrides this default rather than being overridden by it.
90
80
  */
91
- function SsrNuqsWrapper({ search, children }: { search: string; children?: ReactNode }): ReactNode {
92
- // withNuqsSsrAdapter creates a NuqsAdapterProvider (from createAdapterProvider),
93
- // which is the same component factory used by TimberNuqsAdapter on the client.
94
- // Both produce the same internal component boundary depth.
95
- return withNuqsSsrAdapter(search, children);
81
+ function DocumentDefaults(): ReactNode {
82
+ return createElement(
83
+ Fragment,
84
+ null,
85
+ createElement('meta', { charSet: 'utf-8' }),
86
+ createElement('meta', { name: 'viewport', content: 'width=device-width, initial-scale=1' })
87
+ );
96
88
  }
97
89
 
98
90
  /** Per-request inputs for the SSR wrapper chain. */
@@ -101,7 +93,7 @@ export interface SsrWrapOptions {
101
93
  pathname: string;
102
94
  /**
103
95
  * Raw app-visible query string (`''` or `?…`) for NavigationProvider AND
104
- * the nuqs SSR adapter — one representation, preserving repeated keys
96
+ * nuqs (through NavigationContext) — one representation, preserving repeated keys
105
97
  * (`?tag=a&tag=b`) on both consumers (TIM-1428).
106
98
  */
107
99
  search: string;
@@ -111,8 +103,6 @@ export interface SsrWrapOptions {
111
103
  * hands to the same component during hydration.
112
104
  */
113
105
  paramsSource: unknown;
114
- /** Whether the top loader is enabled (must match client config). */
115
- hasTopLoader: boolean;
116
106
  }
117
107
 
118
108
  /**
@@ -122,7 +112,7 @@ export interface SsrWrapOptions {
122
112
  *
123
113
  * Client tree (browser-entry/hydrate.ts):
124
114
  * NavigationRoot
125
- * → Fragment(TopLoader, element)
115
+ * → Fragment(TopLoader | null, element)
126
116
  * → TimberNuqsAdapter
127
117
  * → NuqsAdapterProvider (from createAdapterProvider)
128
118
  * → SlotContentCacheContext.Provider (client-only, single child)
@@ -133,9 +123,9 @@ export interface SsrWrapOptions {
133
123
  *
134
124
  * SSR tree (this function):
135
125
  * SsrNavigationRoot
136
- * → Fragment(SsrTopLoader, element)
137
- * → SsrNuqsWrapper
138
- * → NuqsAdapterProvider (from withNuqsSsrAdapter → createAdapterProvider)
126
+ * → Fragment(DocumentDefaults, element)
127
+ * → TimberNuqsAdapter (real — same component)
128
+ * → NuqsAdapterProvider
139
129
  * → NavigationProvider (real — same component)
140
130
  * → PayloadRoot → ParamsProvider (real — same components)
141
131
  * → [RSC element]
@@ -154,9 +144,9 @@ export function wrapSsrElement(element: ReactNode, opts: SsrWrapOptions): ReactN
154
144
  withParams
155
145
  );
156
146
 
157
- // 3. TimberNuqsAdapter equivalent (wraps withNuqsSsrAdapter for the actual nuqs provider)
158
- const withNuqs = createElement(SsrNuqsWrapper, { search: opts.search }, withNav);
147
+ // 3. The nuqs adapter — the browser's own; it reads search from NavigationContext.
148
+ const withNuqs = createElement(TimberNuqsAdapter, null, withNav);
159
149
 
160
150
  // 4. Outermost: NavigationRoot equivalent (the TopLoader fork)
161
- return createElement(SsrNavigationRoot, { hasTopLoader: opts.hasTopLoader }, withNuqs);
151
+ return createElement(SsrNavigationRoot, null, withNuqs);
162
152
  }
@@ -1 +0,0 @@
1
- {"version":3,"file":"build-output-helper-B7wWGTfR.js","names":[],"sources":["../../src/adapters/shared.ts","../../src/adapters/build-output-helper.ts"],"sourcesContent":["// Shared adapter utilities — leaf module with zero deps on server/, client/,\n// or any Vite-dependent code.\n//\n// Adapters are loaded by Node at Vite startup time, before Vite's module\n// resolver is available. This module uses only Node built-ins and can be\n// imported by both adapters via a relative path.\n//\n// IMPORTANT: Do NOT add imports from ../server/, ../client/, ../plugins/,\n// or any module that transitively depends on Vite. A test in\n// tests/adapters/shared-no-forbidden-imports.test.ts enforces this.\n// ../shared/ is exempt: it is dependency-free by the same rule.\n\nimport { withBasePath } from '../shared/base-path.ts';\n\n/**\n * The deployment base an adapter should write platform rules against.\n *\n * `config.base` is optional on `TimberConfig` because adapters can be invoked\n * by callers that predate it (a hand-written adapter, a test harness). Falling\n * back to `'/'` reproduces the pre-TIM-1274 output exactly, which is correct\n * for the only deployments those callers can have: a build under a non-root\n * base always goes through `plugins/post-build.ts`, which populates it.\n *\n * Typed structurally rather than as `TimberConfig` so this module keeps no\n * import of `./types.js` at runtime.\n */\nexport function adapterBase(config: { base?: string }): string {\n return config.base ?? '/';\n}\n\n// ─── Static asset cache headers ──────────────────────────────────────────\n\n/** Cache-Control value for hashed (immutable) assets. */\nexport const IMMUTABLE_CACHE = 'public, max-age=31536000, immutable';\n\n/** Cache-Control value for unhashed static assets. */\nexport const STATIC_CACHE = 'public, max-age=3600, must-revalidate';\n\n/**\n * Generate a `_headers` file for static asset cache control.\n *\n * The `_headers` file is a platform convention supported by Cloudflare Workers\n * Static Assets, Cloudflare Pages, and Netlify. It maps URL patterns to\n * HTTP response headers.\n *\n * The build's content-hashed directories (`immutableDirs`, recorded on\n * `BuildArtifacts` by the phases that hashed them) get one wildcard rule\n * each. When\n * `unhashedPaths` is provided, per-file rules are appended for unhashed\n * static assets (favicon.ico, robots.txt, etc.) so they get Cache-Control\n * on platforms like Cloudflare Workers Static Assets where the server\n * handler never sees static file requests.\n *\n * A `/*` catch-all is NOT used — it would be additive on Cloudflare,\n * producing duplicate Cache-Control directives on hashed assets\n * (invalid per RFC 9111).\n *\n * **Every rule path is written in deployed-URL space** (TIM-1274). The\n * platform matches these patterns against the request path, which under a\n * non-root `base` sits below the prefix: with `base: '/repo/'` the assets are\n * at `/repo/assets/*`, so a rule saying `/assets/*` matches nothing. Silent\n * for the cache rules (slower, still correct) and not silent for the\n * Content-Type rules — an extensionless API route output is unreadable on\n * Cloudflare Workers Static Assets without one.\n *\n * The prefix is applied at exactly one point, `rulePath()`, which every rule\n * in this function goes through. Prefixing the wildcards and\n * hand-checking that the per-file rules agree is how the next rule gets\n * missed.\n */\n// Cloudflare Workers Static Assets caps _headers at 100 rules. The wildcard\n// rules for the immutable directories come out of the same budget.\nconst MAX_RULES = 100;\n\nexport interface HeadersFileOptions {\n /**\n * The deployment base, already normalized by `normalizeBasePath()` —\n * leading and trailing slash, `'/'` at the domain root.\n *\n * Required rather than defaulted: a caller that forgets it would emit\n * root-relative rules that match nothing, which is the bug this closes.\n */\n base: string;\n /**\n * Content-hashed directories, from `BuildArtifacts.immutableDirs`. Each\n * gets an immutable `Cache-Control` wildcard rule.\n */\n immutableDirs: readonly string[];\n /** Unhashed static files (route-space paths) needing per-file cache rules. */\n unhashedPaths?: string[];\n /** Route-space path → Content-Type, for extensionless API route outputs. */\n contentTypes?: Record<string, string>;\n /**\n * Verbatim contents of the user's `public/_headers`, appended after the\n * generated rules. See `mergeUserHeaders` for why it goes last.\n */\n userRules?: string;\n}\n\n/**\n * Count the rules in a `_headers` file — a rule is a path line, which is any\n * line that is neither blank, a comment, nor an indented header.\n *\n * @internal Exported for testing.\n */\nexport function countHeaderRules(content: string): number {\n return content\n .split('\\n')\n .filter((line) => line.trim() !== '' && !line.startsWith('#') && !/^\\s/.test(line)).length;\n}\n\n/** One `_headers` block: a path pattern and the headers it sets. */\nexport interface HeaderRule {\n pattern: string;\n headers: Array<{ name: string; value: string }>;\n}\n\n/**\n * Parse a `_headers` file. A non-indented, non-comment line opens a rule; the\n * indented `Name: value` lines beneath it belong to that rule.\n *\n * @internal Exported for testing.\n */\nexport function parseHeaderRules(content: string): HeaderRule[] {\n const rules: HeaderRule[] = [];\n for (const raw of content.split('\\n')) {\n const line = raw.replace(/\\r$/, '');\n if (line.trim() === '' || line.trimStart().startsWith('#')) continue;\n if (/^\\s/.test(line)) {\n const current = rules[rules.length - 1];\n if (!current) continue; // header with no rule above it — not ours to fix\n const colon = line.indexOf(':');\n if (colon === -1) continue;\n current.headers.push({\n name: line.slice(0, colon).trim(),\n value: line.slice(colon + 1).trim(),\n });\n } else {\n rules.push({ pattern: line.trim(), headers: [] });\n }\n }\n return rules;\n}\n\n/**\n * Whether a user pattern can match paths a generated pattern also matches.\n *\n * Deliberately narrow: equality, or a prefix-glob (`/x/*`, `/*`) whose literal\n * prefix contains the other's. Anything cleverer risks claiming an overlap\n * that is not there, and the only thing this drives is a warning — a false\n * positive is noise a developer cannot act on.\n */\nfunction patternsOverlap(a: string, b: string): boolean {\n if (a === b) return true;\n const prefixOf = (p: string) => (p.endsWith('*') ? p.slice(0, -1) : null);\n const [pa, pb] = [prefixOf(a), prefixOf(b)];\n if (pa !== null && (b.startsWith(pa) || pa === '')) return true;\n if (pb !== null && (a.startsWith(pb) || pb === '')) return true;\n return false;\n}\n\nexport function generateHeadersFile({\n base,\n immutableDirs,\n unhashedPaths,\n contentTypes,\n userRules,\n}: HeadersFileOptions): string {\n /** Route-space rule path → deployed-URL rule path. */\n const rulePath = (path: string) => withBasePath(base, path);\n\n // Cloudflare and Netlify apply *every* matching rule, so emitting a header\n // the user also sets on the same path yields two definitions of it — a\n // comma-joined `Cache-Control` that is invalid per RFC 9111, and neither\n // side's intent. This module already refuses to emit a `/*` catch-all for\n // that reason; appending the user's file verbatim reintroduced it through\n // the back door (TIM-1326).\n //\n // An explicit app rule beats a framework default, so where the user names\n // the same pattern and the same header, ours is dropped. Only exact pattern\n // matches are resolved this way: silently dropping asset immutability\n // because a `/*` rule *might* subsume it would be a worse surprise than the\n // duplicate, so overlapping-but-different patterns warn instead.\n const userRuleList = userRules ? parseHeaderRules(userRules) : [];\n const overriddenExactly = new Set(\n userRuleList.flatMap((rule) =>\n rule.headers.map((h) => `${rule.pattern}\\0${h.name.toLowerCase()}`)\n )\n );\n const overridden = (pattern: string, header: string) =>\n overriddenExactly.has(`${pattern}\\0${header.toLowerCase()}`);\n\n const warnedOverlaps = new Set<string>();\n const emit = (pattern: string, header: string, value: string): string => {\n if (overridden(pattern, header)) return '';\n for (const rule of userRuleList) {\n if (rule.pattern === pattern) continue;\n if (!patternsOverlap(rule.pattern, pattern)) continue;\n for (const h of rule.headers) {\n if (h.name.toLowerCase() !== header.toLowerCase()) continue;\n const key = `${rule.pattern}\\0${pattern}\\0${header.toLowerCase()}`;\n if (warnedOverlaps.has(key)) continue;\n warnedOverlaps.add(key);\n console.warn(\n `[timber] _headers: your rule \"${rule.pattern}\" sets ${header}, which ` +\n `timber also sets on \"${pattern}\". Cloudflare and Netlify apply both, ` +\n `so the response gets two ${header} values. Use the exact pattern ` +\n `\"${pattern}\" to replace timber's rule, or narrow yours so they do ` +\n `not overlap.`\n );\n }\n }\n return `\\n${pattern}\\n ${header}: ${value}\\n`;\n };\n\n let content = `# Auto-generated by @timber-js/app — static asset cache headers.\n# See design/25-production-deployments.md §\"CDN / Edge Cache\"\n`;\n for (const dir of immutableDirs) {\n content += emit(rulePath(`/${dir}/*`), 'Cache-Control', IMMUTABLE_CACHE);\n }\n const maxPerFileRules = MAX_RULES - immutableDirs.length;\n\n // Content-Type rules are higher priority than cache headers for\n // extensionless files — without them the file is unreadable.\n const allCtEntries = contentTypes\n ? Object.entries(contentTypes).sort(([a], [b]) => a.localeCompare(b))\n : [];\n const ctEntries = allCtEntries.slice(0, maxPerFileRules);\n if (allCtEntries.length > maxPerFileRules) {\n console.warn(\n `[timber] _headers: ${allCtEntries.length} content-type rules exceed ` +\n `Cloudflare's 100-rule limit. Only the first ${maxPerFileRules} ` +\n `extensionless API routes will get Content-Type headers.`\n );\n }\n const remainingBudget = maxPerFileRules - ctEntries.length;\n\n if (unhashedPaths && unhashedPaths.length > 0) {\n const capped = unhashedPaths.slice(0, Math.max(0, remainingBudget));\n if (unhashedPaths.length > remainingBudget) {\n console.warn(\n `[timber] _headers: ${unhashedPaths.length} unhashed static files + ` +\n `${ctEntries.length} content-type rules found, but Cloudflare limits ` +\n `_headers to 100 rules. Only the first ${capped.length} unhashed ` +\n `files will get Cache-Control headers.`\n );\n }\n // Section bodies are built before their comment header so a section the\n // user has overridden entirely does not leave a heading over nothing.\n const body = capped.map((p) => emit(rulePath(p), 'Cache-Control', STATIC_CACHE)).join('');\n if (body !== '') {\n content += `\\n# Unhashed static assets — short-lived cache with revalidation\\n${body}`;\n }\n }\n\n const ctBody = ctEntries\n .map(([urlPath, ct]) => emit(rulePath(urlPath), 'Content-Type', ct))\n .join('');\n if (ctBody !== '') {\n content += `\\n# Content-Type for extensionless API routes\\n${ctBody}`;\n }\n\n // User rules last, matching the `_redirects` merge. Their paths are left\n // verbatim: `_redirects` prefixes the rules it generates because it wrote\n // them in route space, but these are the user's own text, already authored\n // against the URLs the site is deployed at.\n if (userRules && userRules.trim() !== '') {\n content += `\\n# User-authored rules from public/_headers\\n\\n${userRules.trim()}\\n`;\n\n const total = countHeaderRules(content);\n if (total > MAX_RULES) {\n console.warn(\n `[timber] _headers: ${total} rules after merging public/_headers, over ` +\n `Cloudflare's ${MAX_RULES}-rule limit. Rules past the ` +\n `limit are dropped by the platform — remove some, or move static ` +\n `assets under a directory the wildcard rules already cover.`\n );\n }\n }\n\n return content;\n}\n","// Shared build-output helper for adapter buildOutput() methods.\n//\n// Steps 1–5 of every adapter's buildOutput are platform-agnostic:\n// 1. Copy client assets to the public/static directory\n// 2. Write _headers file for static asset cache control, where the platform reads it\n// 3. Copy RSC + SSR server bundles\n// 4. Write manifest-init module (if present)\n//\n// Only the final steps (entry codegen, platform config) vary per adapter.\n//\n// IMPORTANT: This module must remain a leaf — no imports from ../server/,\n// ../client/, or Vite-dependent code. See adapters/shared.ts header.\n\nimport { writeFile, mkdir, cp, rm, readdir, readFile } from 'node:fs/promises';\nimport { join, basename, relative } from 'node:path';\nimport { adapterBase, generateHeadersFile } from './shared.ts';\n// Isomorphic, zero-import module — safe to load from an adapter, which Node's\n// native ESM loader evaluates before Vite's resolver exists. Same precedent as\n// `adapters/shared.ts` importing `../shared/base-path.js`.\nimport {\n HEADERS_FILE,\n REDIRECTS_FILE,\n USER_MERGED_PLATFORM_FILES,\n USER_PLATFORM_DIR,\n} from '../shared/static-platform-files.ts';\nimport { detectFsIdentity, fsKey } from './fs-identity.ts';\nimport type {\n BuildArtifacts,\n ServerBuildArtifacts,\n StaticBuildArtifacts,\n TimberConfig,\n} from './types.ts';\n\n/** Options for the shared build output steps. */\nexport interface BuildOutputBaseOptions {\n /** Resolved timber config. */\n config: TimberConfig;\n /** What the build produced. */\n artifacts: ServerBuildArtifacts;\n /** Adapter-specific output directory (e.g. `.timber/dist/nitro`). */\n outDir: string;\n /**\n * Name of the public/static directory within outDir.\n * Nitro uses 'public', Cloudflare uses 'static'.\n */\n publicDirName: string;\n /**\n * Whether the platform reads `_headers` and `_redirects` from the public\n * directory (Cloudflare, Netlify). When false, the output has neither — no\n * generated `_headers`, and not the user's `public/_headers` or\n * `public/_redirects`, which Vite copies into the client output: on a host\n * that does not read them they are plain files, served to anyone who asks\n * for `/_headers` (TIM-1605).\n */\n platformFiles: boolean;\n}\n\n/**\n * Run the platform-agnostic build output steps shared by all adapters:\n *\n * 1. Create the output directory\n * 2. Copy client assets to the public/static directory\n * 3. Write the `_headers` file for static asset cache control, if `platformFiles`\n * 4. Copy RSC and SSR server bundles into the output directory\n * 5. Write the manifest-init module if present\n *\n * Returns the resolved public directory path for further adapter-specific use.\n */\nexport async function runSharedBuildSteps(opts: BuildOutputBaseOptions): Promise<string> {\n const { config, artifacts, outDir, publicDirName, platformFiles } = opts;\n\n // 1. Create the output directory.\n await mkdir(outDir, { recursive: true });\n\n // 2. Copy client assets to public/static directory.\n // When client JavaScript is disabled, skip .js files — only CSS,\n // fonts, images, and other static assets are needed.\n // Cleaned first: the adapter output directory outlives a build, and a file\n // an earlier build left here (a static build's pre-rendered `index.html`,\n // a `_headers` the preset no longer reads) would otherwise ship and be\n // served ahead of the app.\n const publicDir = join(outDir, publicDirName);\n await rm(publicDir, { recursive: true, force: true });\n await mkdir(publicDir, { recursive: true });\n const clientDir = artifacts.client.path;\n const userPlatformFiles = new Set(\n platformFiles ? [] : [HEADERS_FILE, REDIRECTS_FILE].map((name) => join(clientDir, name))\n );\n // Find WASM files that are referenced by client JS (legitimate client WASM)\n // vs orphaned server-only WASM (e.g. @takumi-rs for OG image generation).\n // Only strip orphaned WASM to avoid breaking client-side WASM usage.\n const referencedWasm = await findReferencedWasm(clientDir);\n\n await cp(clientDir, publicDir, {\n recursive: true,\n filter: (src: string) => {\n if (src.endsWith('.wasm') && !referencedWasm.has(basename(src))) {\n return false;\n }\n if (config.clientJavascriptDisabled && src.endsWith('.js')) return false;\n if (userPlatformFiles.has(src)) return false;\n return true;\n },\n });\n\n // 3. Write _headers file for static asset cache control.\n // Scan for unhashed files so they get per-file Cache-Control rules in the\n // _headers file. On platforms like Cloudflare Workers Static Assets, the\n // worker never sees static file requests — _headers is the only mechanism.\n // Elsewhere nothing reads it, so its rules never applied and the file was\n // only a public asset; the immutable header there comes from the server\n // instead (nitro-immutable-assets.ts).\n if (platformFiles) await writeHeadersFile(publicDir, config, artifacts);\n\n // 4. Copy RSC + SSR server bundles into the output directory. The RSC\n // bundle imports the SSR one by a path the RSC plugin computed between the\n // two *build* directories, which the build names `rsc/` and `ssr/` as\n // siblings (index.ts); deploying them under the same names keeps it valid.\n await cp(artifacts.rsc.path, join(outDir, 'rsc'), { recursive: true });\n await cp(artifacts.ssr.path, join(outDir, 'ssr'), { recursive: true });\n\n // 4b. Copy prebuilt/ flight payloads (cache.component artifacts). These\n // are produced by the post-build capture pass (design/44) and read at\n // request time via the adapter's PrebuiltPayloadSource.\n if (artifacts.prebuilt) {\n await cp(artifacts.prebuilt.path, join(outDir, 'prebuilt'), { recursive: true });\n }\n\n // 5. Write manifest-init module if present.\n if (artifacts.manifestInit) {\n await writeFile(join(outDir, '_timber-manifest-init.js'), artifacts.manifestInit);\n }\n\n return publicDir;\n}\n\n/**\n * Find unhashed static files in the public directory that need per-file\n * Cache-Control rules in the `_headers` file.\n *\n * Excludes:\n * - Files under the build's `immutableDirs` (covered by wildcard rules)\n * - Files under `rsc/` and `ssr/` (server bundles, never served)\n * - Underscore-prefixed files (`_headers`, `_worker.js`, etc.)\n *\n * Ordered for the rule cap: well-known metadata files, then everything\n * else, then files under an underscore-prefixed directory — the\n * framework's own output (unhashed RSC payloads in a static build with\n * client JavaScript disabled, which nothing fetches). Those can number one\n * per route, and must not take the budget from the app's real files.\n *\n * @internal Exported for testing.\n */\n// Well-known metadata files that should be prioritized when capping\n// _headers rules, so they're never dropped in favor of less important files.\nconst PRIORITY_FILES = new Set([\n '/favicon.ico',\n '/robots.txt',\n '/sitemap.xml',\n '/manifest.json',\n '/manifest.webmanifest',\n '/apple-touch-icon.png',\n]);\n\nexport async function findUnhashedStaticFiles(\n publicDir: string,\n immutableDirs: readonly string[]\n): Promise<string[]> {\n let files: string[];\n try {\n files = await collectFiles(publicDir);\n } catch {\n return [];\n }\n\n const priority: string[] = [];\n const rest: string[] = [];\n const framework: string[] = [];\n for (const file of files) {\n const rel = relative(publicDir, file).replace(/\\\\/g, '/');\n if (immutableDirs.some((dir) => rel.startsWith(`${dir}/`))) continue;\n if (rel.startsWith('rsc/') || rel.startsWith('ssr/')) continue;\n if (basename(rel).startsWith('_')) continue;\n const urlPath = '/' + rel;\n if (PRIORITY_FILES.has(urlPath)) {\n priority.push(urlPath);\n } else if (rel.startsWith('_')) {\n framework.push(urlPath);\n } else {\n rest.push(urlPath);\n }\n }\n\n return [...priority.sort(), ...rest.sort(), ...framework.sort()];\n}\n\n/**\n * Scan client JS files for references to .wasm filenames.\n * Returns the set of WASM basenames that are actually imported/referenced\n * by client code and must be preserved in the static output.\n */\nasync function findReferencedWasm(clientDir: string): Promise<Set<string>> {\n const referenced = new Set<string>();\n const files = await collectFiles(clientDir);\n\n const jsFiles = files.filter((f) => f.endsWith('.js'));\n const wasmFiles = files.filter((f) => f.endsWith('.wasm')).map((f) => basename(f));\n if (wasmFiles.length === 0) return referenced;\n\n for (const jsFile of jsFiles) {\n const content = await readFile(jsFile, 'utf-8');\n for (const wasmName of wasmFiles) {\n if (content.includes(wasmName)) {\n referenced.add(wasmName);\n }\n }\n }\n\n return referenced;\n}\n\n/**\n * Build a static-only output directory (no server entry). Copies client\n * assets and pre-rendered HTML/RSC/API files into `outDir/publicDirName`.\n * Used by both Cloudflare and Nitro adapters in `output: 'static'` mode.\n */\nexport async function buildStaticDirectoryOutput(\n config: TimberConfig,\n artifacts: StaticBuildArtifacts,\n outDir: string,\n publicDirName: string\n): Promise<void> {\n // Clean stale artifacts from prior builds (e.g. server-mode builds that\n // left rsc/, ssr/, _worker.js in the outDir). Without this, a static\n // build after a server build inherits 140+ unused server chunks.\n await rm(outDir, { recursive: true, force: true }).catch(() => {});\n await mkdir(outDir, { recursive: true });\n\n const publicDir = join(outDir, publicDirName);\n await mkdir(publicDir, { recursive: true });\n\n // Copy client assets (JS, CSS, fonts, images).\n await cp(artifacts.client.path, publicDir, {\n recursive: true,\n filter: (src: string) => {\n if (config.clientJavascriptDisabled && src.endsWith('.js')) return false;\n return true;\n },\n });\n\n // Copy pre-rendered static pages (HTML + RSC flight + API routes).\n //\n // This is the one place the build merges two independently-produced trees\n // into a single directory, and `cp` resolves an overlap by overwriting with\n // no diagnostic — the deployment then contains one of the two artifacts and\n // nothing recorded which. Refuse instead (TIM-1266).\n await assertNoTreeCollision(artifacts.pages.path, publicDir);\n await cp(artifacts.pages.path, publicDir, { recursive: true });\n}\n\n/**\n * Write the `_headers` file, folding in the user's `public/_headers`.\n *\n * Every adapter used to `writeFile` a generated `_headers` over whatever\n * Vite had copied out of `public/`, so an app shipping its own CSP, CORS, or\n * cache rules deployed without them and without a word (TIM-1326). The\n * generated rules and the user's are not competitors — they address different\n * paths — so this merges rather than refusing, the way `_redirects` has since\n * TIM-1249.\n *\n * **Read from the project, not the output.** The generated file lands under\n * the same name in the output directory, and `runSharedBuildSteps` does not\n * clean `outDir`; a reader aimed there would fold the previous build's\n * generated rules back in and compound them on every rebuild — the defect\n * this pass fixed for `_redirects`.\n *\n * User rules go last. On Cloudflare and Netlify a `_headers` file applies\n * every matching rule, so appending means the user's rules take effect; where\n * a platform resolves a conflict in favour of the earlier rule instead, the\n * framework keeps the paths it owns and the user keeps the rest. Under either\n * reading this is no worse than the previous behaviour, which was to drop the\n * user's rules entirely.\n *\n * @internal Exported for testing.\n */\nexport async function writeHeadersFile(\n dir: string,\n config: TimberConfig,\n artifacts: BuildArtifacts\n): Promise<void> {\n const userRules = await readUserPlatformFile(config.root, HEADERS_FILE);\n await writeFile(\n join(dir, HEADERS_FILE),\n generateHeadersFile({\n base: adapterBase(config),\n immutableDirs: artifacts.immutableDirs,\n // Scanned from the directory being deployed, which holds everything\n // the platform will serve from it.\n unhashedPaths: await findUnhashedStaticFiles(dir, artifacts.immutableDirs),\n contentTypes: artifacts.output === 'static' ? artifacts.contentTypes : undefined,\n userRules: userRules ?? undefined,\n })\n );\n}\n\n/**\n * Read a user-authored platform file from the project's `public/` directory.\n * Returns null when the project has none, or when no root is configured —\n * a caller without a root cannot locate the project at all, and inventing\n * one from `process.cwd()` would read a different project's file.\n */\nasync function readUserPlatformFile(\n root: string | undefined,\n name: string\n): Promise<string | null> {\n if (!root) return null;\n try {\n return await readFile(join(root, USER_PLATFORM_DIR, name), 'utf-8');\n } catch {\n return null;\n }\n}\n\n/**\n * Throw if copying `srcDir` over `destDir` would overwrite an existing file.\n *\n * Compared against the destination **as it stands**, not against the other\n * source tree: the first copy is filtered (client JS is dropped when client\n * JavaScript is disabled), so the files that are actually there are the only\n * ones a second copy can clobber.\n *\n * @internal Exported for testing.\n */\nexport async function assertNoTreeCollision(srcDir: string, destDir: string): Promise<void> {\n const [srcFiles, destFiles, identity] = await Promise.all([\n collectFiles(srcDir).catch(() => [] as string[]),\n collectFiles(destDir).catch(() => [] as string[]),\n // `cp` will resolve these paths the way the destination filesystem does,\n // so the comparison predicting it has to as well: on macOS a hand-written\n // `public/About/index.html` and a generated `about/index.html` are one\n // file, and an exact-string set waves the overwrite through (TIM-1266).\n detectFsIdentity(destDir),\n ]);\n\n const key = (p: string) => fsKey(p, identity);\n const existing = new Set(destFiles.map((f) => key(relative(destDir, f).replace(/\\\\/g, '/'))));\n const exempt = new Set(USER_MERGED_PLATFORM_FILES.map(key));\n const collisions = srcFiles\n .map((f) => relative(srcDir, f).replace(/\\\\/g, '/'))\n .filter((rel) => existing.has(key(rel)) && !exempt.has(key(rel)))\n .sort();\n\n if (collisions.length === 0) return;\n\n throw new Error(\n `[timber] Build output: ${collisions.length} file(s) in the pre-rendered site ` +\n `collide with files already in the output directory. Copying would silently ` +\n `overwrite them — a generated page and a file in public/ cannot share a path:\\n` +\n collisions.map((c) => ` - ${c}`).join('\\n')\n );\n}\n\nasync function collectFiles(dir: string): Promise<string[]> {\n const result: string[] = [];\n const entries = await readdir(dir, { withFileTypes: true });\n for (const entry of entries) {\n const fullPath = join(dir, entry.name);\n if (entry.isDirectory()) {\n result.push(...(await collectFiles(fullPath)));\n } else {\n result.push(fullPath);\n }\n }\n return result;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AA0BA,SAAgB,YAAY,QAAmC;CAC7D,OAAO,OAAO,QAAQ;AACxB;;AAKA,IAAa,kBAAkB;;AAG/B,IAAa,eAAe;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoC5B,IAAM,YAAY;;;;;;;AAiClB,SAAgB,iBAAiB,SAAyB;CACxD,OAAO,QACJ,MAAM,IAAI,CAAC,CACX,QAAQ,SAAS,KAAK,KAAK,MAAM,MAAM,CAAC,KAAK,WAAW,GAAG,KAAK,CAAC,MAAM,KAAK,IAAI,CAAC,CAAC,CAAC;AACxF;;;;;;;AAcA,SAAgB,iBAAiB,SAA+B;CAC9D,MAAM,QAAsB,CAAC;CAC7B,KAAK,MAAM,OAAO,QAAQ,MAAM,IAAI,GAAG;EACrC,MAAM,OAAO,IAAI,QAAQ,OAAO,EAAE;EAClC,IAAI,KAAK,KAAK,MAAM,MAAM,KAAK,UAAU,CAAC,CAAC,WAAW,GAAG,GAAG;EAC5D,IAAI,MAAM,KAAK,IAAI,GAAG;GACpB,MAAM,UAAU,MAAM,MAAM,SAAS;GACrC,IAAI,CA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AK,MAAM,SAAS,SAAS;EAC3B,MAAM,WAAW,KAAK,KAAK,MAAM,IAAI;EACrC,IAAI,MAAM,YAAY,GACpB,OAAO,KAAK,GAAI,MAAM,aAAa,QAAQ,CAAE;OAE7C,OAAO,KAAK,QAAQ;CAExB;CACA,OAAO;AACT"}
@@ -1,32 +0,0 @@
1
- /**
2
- * Server-side nuqs adapter provider for SSR rendering.
3
- *
4
- * During SSR, `'use client'` components that call nuqs hooks (useQueryStates,
5
- * useQueryState) need the nuqs adapter context. The client adapter
6
- * (TimberNuqsAdapter) relies on `window` and React hooks that are
7
- * client-only. This provider supplies a static, SSR-safe adapter
8
- * that feeds the current request's search params into the nuqs context.
9
- *
10
- * The returned component wraps the React tree so that nuqs hooks render
11
- * the correct initial values during server-side rendering. On the client,
12
- * TimberNuqsAdapter (injected by browser-entry.ts) takes over.
13
- *
14
- * Design doc: design/23-search-params.md §"Custom Adapter"
15
- */
16
- import { type ReactNode } from 'react';
17
- /**
18
- * Wrap the SSR element tree with a nuqs adapter context.
19
- *
20
- * Called by ssr-entry.ts before passing the element to renderSsrStream.
21
- * Takes the NavContext raw query string and provides it to nuqs hooks
22
- * running during SSR so they render with the correct initial values.
23
- *
24
- * The raw string — not a collapsed record — is what preserves repeated
25
- * query keys (`?tag=a&tag=b`) for nuqs multi parsers, matching the raw
26
- * `location.search` the client adapter reads after hydration (TIM-1428).
27
- *
28
- * @param search - The request's raw app-visible query string (`''` or `?…`)
29
- * @param children - The React element tree to wrap
30
- */
31
- export declare function withNuqsSsrAdapter(search: string, children: ReactNode): ReactNode;
32
- //# sourceMappingURL=nuqs-ssr-provider.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"nuqs-ssr-provider.d.ts","sourceRoot":"","sources":["../../src/server/nuqs-ssr-provider.tsx"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,EAAiB,KAAK,SAAS,EAAE,MAAM,OAAO,CAAC;AA2BtD;;;;;;;;;;;;;GAaG;AACH,wBAAgB,kBAAkB,CAAC,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,SAAS,GAAG,SAAS,CAMjF"}
@@ -1,64 +0,0 @@
1
- /**
2
- * Server-side nuqs adapter provider for SSR rendering.
3
- *
4
- * During SSR, `'use client'` components that call nuqs hooks (useQueryStates,
5
- * useQueryState) need the nuqs adapter context. The client adapter
6
- * (TimberNuqsAdapter) relies on `window` and React hooks that are
7
- * client-only. This provider supplies a static, SSR-safe adapter
8
- * that feeds the current request's search params into the nuqs context.
9
- *
10
- * The returned component wraps the React tree so that nuqs hooks render
11
- * the correct initial values during server-side rendering. On the client,
12
- * TimberNuqsAdapter (injected by browser-entry.ts) takes over.
13
- *
14
- * Design doc: design/23-search-params.md §"Custom Adapter"
15
- */
16
-
17
- import { createElement, type ReactNode } from 'react';
18
- import {
19
- unstable_createAdapterProvider as createAdapterProvider,
20
- type unstable_AdapterInterface as AdapterInterface,
21
- } from 'nuqs/adapters/custom';
22
-
23
- // ─── SSR Adapter ──────────────────────────────────────────────────
24
-
25
- /**
26
- * Create a nuqs adapter provider for SSR that serves a static snapshot
27
- * of search params. The `updateUrl` is a no-op because URL updates
28
- * cannot happen on the server.
29
- */
30
- function makeNuqsSsrAdapter(searchParams: URLSearchParams) {
31
- function useNuqsSsrAdapter(_watchKeys: string[]): AdapterInterface {
32
- return {
33
- searchParams,
34
- updateUrl: () => {},
35
- getSearchParamsSnapshot: () => searchParams,
36
- };
37
- }
38
-
39
- return createAdapterProvider(useNuqsSsrAdapter);
40
- }
41
-
42
- // ─── Provider Component ───────────────────────────────────────────
43
-
44
- /**
45
- * Wrap the SSR element tree with a nuqs adapter context.
46
- *
47
- * Called by ssr-entry.ts before passing the element to renderSsrStream.
48
- * Takes the NavContext raw query string and provides it to nuqs hooks
49
- * running during SSR so they render with the correct initial values.
50
- *
51
- * The raw string — not a collapsed record — is what preserves repeated
52
- * query keys (`?tag=a&tag=b`) for nuqs multi parsers, matching the raw
53
- * `location.search` the client adapter reads after hydration (TIM-1428).
54
- *
55
- * @param search - The request's raw app-visible query string (`''` or `?…`)
56
- * @param children - The React element tree to wrap
57
- */
58
- export function withNuqsSsrAdapter(search: string, children: ReactNode): ReactNode {
59
- const searchParams = new URLSearchParams(search);
60
- const Provider = makeNuqsSsrAdapter(searchParams);
61
- // AdapterProvider types require children in the props object (not as 3rd arg)
62
- // eslint-disable-next-line react/no-children-prop
63
- return createElement(Provider, { defaultOptions: { shallow: false, scroll: true }, children });
64
- }