@timber-js/app 0.2.0-alpha.214 → 0.2.0-alpha.215

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.
@@ -18,6 +18,14 @@
18
18
  * the browser entry is listed too. Files that gain the directive after
19
19
  * startup still fall back to Vite's late discovery.
20
20
  *
21
+ * The crawl follows those entries' imports into `'use server'` modules
22
+ * too, because Vite's scanner does not run plugin-rsc's transforms — at
23
+ * runtime the browser only ever sees server references in their place.
24
+ * Without help the optimizer pre-bundles the actions' server-only
25
+ * packages (database clients, cloud SDKs) for the browser, slowing cold
26
+ * start or failing the whole client optimizer when one cannot bundle.
27
+ * `skipUseServerScanPlugin` stubs those modules out of the crawl.
28
+ *
21
29
  * Design docs: 21-dev-server.md §"Client Dependency Pre-Bundling".
22
30
  */
23
31
  /**
@@ -28,6 +36,34 @@
28
36
  * build output) are skipped.
29
37
  */
30
38
  export declare function findUseClientFiles(root: string, excludeDir?: string): Promise<string[]>;
39
+ /**
40
+ * The scanner's replacement for an app source file whose directive
41
+ * prologue holds `'use server'`: an empty module, so the crawl stops
42
+ * there. Returns null (load normally) for every other file. A
43
+ * `'use server'` inside a function body (an inline action in a server
44
+ * component) is not a module directive and leaves the file alone.
45
+ */
46
+ export declare function useServerScanStub(id: string): Promise<string | null>;
47
+ /**
48
+ * A rolldown plugin for the client environment's
49
+ * `optimizeDeps.rolldownOptions.plugins`. Vite's scanner runs these
50
+ * before its own scan plugin, so this `load` hook decides what the crawl
51
+ * sees of each app source file (Vite has no JS load hook of its own
52
+ * there; rolldown reads the file).
53
+ *
54
+ * Vite also runs these plugins in the optimizer's bundle step. That step
55
+ * bundles the discovered dependencies, which live in node_modules, so the
56
+ * node_modules guard makes the hook a no-op there. The exception is a
57
+ * linked package outside node_modules listed in `optimizeDeps.include`
58
+ * with a module-level `'use server'` file: named imports from the stub
59
+ * fail that bundle (MISSING_EXPORT). Unstubbed, it would ship the server
60
+ * code to the browser instead, so such a package must not be
61
+ * pre-bundled either way.
62
+ */
63
+ export declare function skipUseServerScanPlugin(): {
64
+ name: string;
65
+ load: (id: string) => Promise<string | null>;
66
+ };
31
67
  /**
32
68
  * Escape a path for use as an `optimizeDeps.entries` pattern. Vite globs
33
69
  * entries, and route directories are full of glob syntax: `(group)`,
@@ -1 +1 @@
1
- {"version":3,"file":"client-dep-entries.d.ts","sourceRoot":"","sources":["../../src/plugins/client-dep-entries.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;GAqBG;AAOH;;;;;;GAMG;AACH,wBAAsB,kBAAkB,CAAC,IAAI,EAAE,MAAM,EAAE,UAAU,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC,CAkB7F;AAED;;;;;;GAMG;AACH,wBAAgB,cAAc,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAEnD;AAED;;;GAGG;AACH,wBAAsB,yBAAyB,CAC7C,IAAI,EAAE,MAAM,EACZ,gBAAgB,EAAE,MAAM,EACxB,QAAQ,EAAE,MAAM,GACf,OAAO,CAAC,MAAM,EAAE,CAAC,CAGnB"}
1
+ {"version":3,"file":"client-dep-entries.d.ts","sourceRoot":"","sources":["../../src/plugins/client-dep-entries.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AAOH;;;;;;GAMG;AACH,wBAAsB,kBAAkB,CAAC,IAAI,EAAE,MAAM,EAAE,UAAU,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC,CAkB7F;AAED;;;;;;GAMG;AACH,wBAAsB,iBAAiB,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAM1E;AAED;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,uBAAuB,IAAI;IACzC,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,CAAC,EAAE,EAAE,MAAM,KAAK,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAAC;CAC9C,CAEA;AAED;;;;;;GAMG;AACH,wBAAgB,cAAc,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAEnD;AAED;;;GAGG;AACH,wBAAsB,yBAAyB,CAC7C,IAAI,EAAE,MAAM,EACZ,gBAAgB,EAAE,MAAM,EACxB,QAAQ,EAAE,MAAM,GACf,OAAO,CAAC,MAAM,EAAE,CAAC,CAGnB"}
@@ -1,5 +1,5 @@
1
- /** Port input precedence for dev and preview. Vite owns binding and restart reuse. */
2
- /** Default port used by `timber dev` and `timber preview`. */
1
+ /** Port input precedence for dev. Vite owns binding and restart reuse. */
2
+ /** Default port used by `timber dev`. */
3
3
  export declare const DEFAULT_PORT = 3000;
4
4
  export interface ResolvePortInput {
5
5
  /**
@@ -13,19 +13,10 @@ export interface ResolvePortInput {
13
13
  /** Default port to use when neither `configPort` nor `envPort` is set. */
14
14
  defaultPort?: number;
15
15
  }
16
- export interface ResolvedPortInput {
17
- /** Port to start binding from. */
18
- port: number;
19
- /**
20
- * `true` if the port came from an explicit user override (config or
21
- * env). Preview uses this to default to strict port binding.
22
- */
23
- explicit: boolean;
24
- }
25
16
  /**
26
17
  * Pure: compute the starting port from config / env / defaults.
27
18
  *
28
19
  * Performs no I/O.
29
20
  */
30
- export declare function resolveStartPort(input: ResolvePortInput): ResolvedPortInput;
21
+ export declare function resolveStartPort(input: ResolvePortInput): number;
31
22
  //# sourceMappingURL=port-resolution.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"port-resolution.d.ts","sourceRoot":"","sources":["../../src/server/port-resolution.ts"],"names":[],"mappings":"AAAA,sFAAsF;AAEtF,8DAA8D;AAC9D,eAAO,MAAM,YAAY,OAAO,CAAC;AAIjC,MAAM,WAAW,gBAAgB;IAC/B;;;;OAIG;IACH,UAAU,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IAChC,uCAAuC;IACvC,OAAO,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IAC7B,0EAA0E;IAC1E,WAAW,CAAC,EAAE,MAAM,CAAC;CACtB;AAED,MAAM,WAAW,iBAAiB;IAChC,kCAAkC;IAClC,IAAI,EAAE,MAAM,CAAC;IACb;;;OAGG;IACH,QAAQ,EAAE,OAAO,CAAC;CACnB;AAED;;;;GAIG;AACH,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,gBAAgB,GAAG,iBAAiB,CAiB3E"}
1
+ {"version":3,"file":"port-resolution.d.ts","sourceRoot":"","sources":["../../src/server/port-resolution.ts"],"names":[],"mappings":"AAAA,0EAA0E;AAE1E,yCAAyC;AACzC,eAAO,MAAM,YAAY,OAAO,CAAC;AAIjC,MAAM,WAAW,gBAAgB;IAC/B;;;;OAIG;IACH,UAAU,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IAChC,uCAAuC;IACvC,OAAO,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IAC7B,0EAA0E;IAC1E,WAAW,CAAC,EAAE,MAAM,CAAC;CACtB;AAED;;;;GAIG;AACH,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,gBAAgB,GAAG,MAAM,CAiBhE"}
@@ -29,7 +29,7 @@ When the requested port is available, the server shows a loading page while Vite
29
29
 
30
30
  #### Port selection
31
31
 
32
- The default port is **`3000`** for both `timber dev` and `timber preview` (matching Next.js and most Node web frameworks). If `3000` is already in use, timber automatically bumps to `3001`, then `3002`, and so on until it finds a free port:
32
+ The default port for `timber dev` is **`3000`** (matching Next.js and most Node web frameworks). If `3000` is already in use, timber automatically bumps to `3001`, then `3002`, and so on until it finds a free port:
33
33
 
34
34
  ```
35
35
  Port 3000 is in use, trying another one...
@@ -42,7 +42,7 @@ To override the default, use any of the following (highest precedence first):
42
42
 
43
43
  > **Note:** `timber dev --port 4000` is an error, not a silent no-op. `timber dev` accepts only `--config` — use `PORT` or `server.port` to change the port.
44
44
 
45
- For `timber dev`, an occupied port produces a notice and the server tries the next free port. Set `server.strictPort: true` in `vite.config.ts` to fail on a conflict instead. Preview and the production Node preview server report a conflict for an explicit port.
45
+ An occupied port produces a notice and the server tries the next free port. Set `server.strictPort: true` in `vite.config.ts` to fail on a conflict instead.
46
46
 
47
47
  Editing `timber.config.ts` triggers a full process restart so the updated config takes effect. The dev server briefly shuts down and restarts on the same port. Changing the configured port takes effect on restart.
48
48
 
@@ -78,7 +78,7 @@ Serve the production build locally for testing.
78
78
  timber preview
79
79
  ```
80
80
 
81
- If your adapter provides a `preview()` method, that takes priority. Otherwise falls back to Vite's built-in preview server.
81
+ Preview runs your adapter's `preview()`. The Cloudflare and Nitro adapters both provide one. If no adapter is configured, or your adapter has no `preview()`, preview exits with an error that says so. It does not fall back to Vite's preview server, because that would serve your build directory, server bundles included, as static files.
82
82
 
83
83
  Preview reads your project the same way `timber build` does: it resolves your Vite config, so options passed inline to `timber({ ... })`, a custom `--config`, and `build.outDir` all apply. It serves your last build using the `output` mode your config sets now. If you change `output`, rebuild before you preview:
84
84
 
@@ -90,7 +90,11 @@ Preview reads your project the same way `timber build` does: it resolves your Vi
90
90
 
91
91
  The Nitro static preview serves under your `base` path, but it does not apply `_redirects` or `_headers` rules. Check those on your hosting platform.
92
92
 
93
- A `timber.config.ts` that exists but fails to load is a hard error naming the file — preview never silently falls back to the plain Vite preview server with your adapter ignored.
93
+ A `timber.config.ts` that exists but fails to load is a hard error naming the file, so preview never runs with your adapter ignored.
94
+
95
+ The adapter picks the preview port, not `server.port`. The Nitro preview server starts at `3000` and tries the next free port, unless you set `PORT`, in which case a conflict is an error. Cloudflare preview uses wrangler's own default port.
96
+
97
+ Running `vite preview` directly is an error. It would serve your build directory, server bundles included, as static files.
94
98
 
95
99
  Always run `timber build` before `timber preview`.
96
100
 
@@ -200,6 +200,8 @@ export default {
200
200
 
201
201
  Pre-renders every route to HTML at build time. Add `clientJavascript: false` for zero-JavaScript output. Deploy to any static file host — S3, CloudFront, Cloudflare Pages, GitHub Pages, Netlify, or any HTTP server.
202
202
 
203
+ `timber preview` runs an adapter, so a static build with no adapter can't be previewed. Add `adapter: nitro()` to preview it locally. A static Nitro build doesn't need a Nitro server, and its preview works with any preset.
204
+
203
205
  ### Serving from a sub-path
204
206
 
205
207
  To deploy under a path instead of a domain root — `https://user.github.io/repo/` on GitHub Pages, for example — set Vite's `base`:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@timber-js/app",
3
- "version": "0.2.0-alpha.214",
3
+ "version": "0.2.0-alpha.215",
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",
@@ -152,7 +152,9 @@ export interface TimberPlatformAdapter {
152
152
 
153
153
  /**
154
154
  * Start a local preview server for the built output.
155
- * Falls back to Vite's preview server if not provided.
155
+ * Without it, `timber preview` fails with an error naming the adapter —
156
+ * there is no fallback to Vite preview, which would serve the build
157
+ * directory (server bundles included) as static files.
156
158
  *
157
159
  * Runs in a later process than the build (`timber preview`); see
158
160
  * {@link PreviewTarget}.
package/src/cli.ts CHANGED
@@ -140,7 +140,6 @@ export function parseArgs(args: string[]): ParsedArgs {
140
140
  export interface ViteDeps {
141
141
  createServer?: typeof import('vite').createServer;
142
142
  createBuilder?: typeof import('vite').createBuilder;
143
- preview?: typeof import('vite').preview;
144
143
  resolveViteConfig?: ResolveViteConfig;
145
144
  }
146
145
 
@@ -231,16 +230,17 @@ export async function runBuild(options: CommandOptions, _deps?: ViteDeps): Promi
231
230
 
232
231
  /**
233
232
  * Serve the production build for local testing.
234
- * If the adapter provides a preview() method, it takes priority.
235
- * Otherwise falls back to Vite's built-in preview server.
233
+ * The adapter's preview() serves it; without one, preview fails (TIM-1565).
234
+ * There is no fallback to Vite preview: it would serve the build directory
235
+ * itself — the server bundles as static files, with no root `index.html` —
236
+ * which is useless in either output mode.
236
237
  *
237
238
  * The project is resolved through Vite, as `timber check` resolves it
238
239
  * (`cli-context.ts`), so the adapter, the output mode, and the build
239
240
  * directory are the ones `timber build` used — including `--config`, inline
240
241
  * `timber({ ... })` options, Vite's `root`, and `build.outDir`, none of which
241
242
  * a re-read of `timber.config.ts` can see (TIM-1531). A config file that
242
- * exists but fails to load throws (naming the file) instead of silently
243
- * degrading to plain Vite preview (TIM-1066).
243
+ * exists but fails to load throws, naming the file (TIM-1066).
244
244
  */
245
245
  export async function runPreview(options: CommandOptions, _deps?: ViteDeps): Promise<void> {
246
246
  const { resolveTimberContext } = await import('./cli-context.ts');
@@ -249,20 +249,22 @@ export async function runPreview(options: CommandOptions, _deps?: ViteDeps): Pro
249
249
  const ctx = await resolveTimberContext('preview', options.config, _deps?.resolveViteConfig);
250
250
  const adapter = contextAdapter(ctx);
251
251
 
252
- if (typeof adapter?.preview === 'function') {
253
- await adapter.preview(adapterConfig(ctx), {
254
- output: ctx.config.output ?? 'server',
255
- outputDir: ctx.buildDir,
256
- });
257
- return;
252
+ if (typeof adapter?.preview !== 'function') {
253
+ const missing = adapter
254
+ ? `The adapter '${adapter.name}' has no preview(), so \`timber preview\` cannot serve this build.`
255
+ : `No adapter is configured, so \`timber preview\` has nothing to serve this build with.`;
256
+ throw new Error(
257
+ `[timber] ${missing} Use an adapter that implements preview() — ` +
258
+ `cloudflare() from '@timber-js/app/adapters/cloudflare', or nitro() from ` +
259
+ `'@timber-js/app/adapters/nitro' (any preset for a static build; node-server or bun ` +
260
+ `for a server build) — or serve the build with your platform's own tooling.`
261
+ );
258
262
  }
259
263
 
260
- // Fallback: Vite's built-in preview server
261
- const preview = _deps?.preview ?? (await import('vite')).preview;
262
- const server = await preview({
263
- configFile: options.config,
264
+ await adapter.preview(adapterConfig(ctx), {
265
+ output: ctx.config.output ?? 'server',
266
+ outputDir: ctx.buildDir,
264
267
  });
265
- server.printUrls();
266
268
  }
267
269
 
268
270
  /**
package/src/index.ts CHANGED
@@ -270,6 +270,19 @@ export function timber(config?: TimberUserConfig): PluginOption[] {
270
270
  api: { getContext: () => ctx } satisfies TimberPluginApi,
271
271
 
272
272
  async config(userConfig, { command, isPreview }) {
273
+ // `vite preview` serves Vite's build.outDir as static files, and timber
274
+ // sets that to the whole build directory (below): the rsc/ and ssr/
275
+ // server bundles, with no root index.html in either output mode. Refuse
276
+ // it rather than expose the server code. `timber preview` resolves the
277
+ // project under `build`, so it never lands here. TIM-1565, design/25.
278
+ if (isPreview) {
279
+ throw new Error(
280
+ '[timber] `vite preview` cannot serve a timber build: it would serve the build ' +
281
+ 'directory, server bundles included, as static files. Run `timber preview`, ' +
282
+ "which runs your adapter's preview()."
283
+ );
284
+ }
285
+
273
286
  // ── Load timber.config.ts from the correct root ───────────────
274
287
  // Vite's `config` hook fires before `configResolved`. The user's
275
288
  // `root` option (if set) tells us where the project lives.
@@ -319,23 +332,12 @@ export function timber(config?: TimberUserConfig): PluginOption[] {
319
332
  // production jsx-runtime doesn't export jsxDEV). The oxc.jsx
320
333
  // override below fixes Vite's native path; plugin-react's compiler
321
334
  // plugin is handled by patchReactCompilerForProdJsx above.
322
- // ── Resolve dev/preview port (TIM-842) ───────────────────────
335
+ // ── Resolve dev port (TIM-842) ───────────────────────────────
323
336
  // Default port is 3000. Vite handles conflicts and honors server.strictPort.
324
- //
325
- // For dev (`command === 'serve' && !isPreview`) we start the
326
- // holding server on the requested port when available.
327
- //
328
- // For `vite preview` (`command === 'serve' && isPreview`) we
329
- // resolve the config/env port but delegate the actual bind +
330
- // auto-bump to Vite's own preview server. Starting the holding
331
- // server in preview mode would self-conflict because the dev
332
- // plugin's `configureServer` handoff does not run for preview;
333
- // the holding server would keep the port occupied while Vite's
334
- // preview tried to bind the same port.
337
+ // We start the holding server on the requested port when available.
335
338
  //
336
339
  // See design/21-dev-server.md §"Default Port and Auto-Bump".
337
340
  let resolvedDevPort: number | null = null;
338
- let resolvedDevPortExplicit = false;
339
341
  // Middleware-mode embeddings (the analyze crawl, custom servers)
340
342
  // never bind a port, and the dev-server plugin's listen() handoff
341
343
  // that closes the holding server never runs — starting it would
@@ -351,39 +353,20 @@ export function timber(config?: TimberUserConfig): PluginOption[] {
351
353
  : userConfig.server?.host === true
352
354
  ? undefined
353
355
  : 'localhost';
354
- if (command === 'serve' && !isPreview && !isMiddlewareMode) {
355
- const start = resolveStartPort({
356
- configPort: userConfig.server?.port,
357
- envPort: process.env.PORT,
358
- });
356
+ if (command === 'serve' && !isMiddlewareMode) {
359
357
  // Vite owns port selection and remembers its bound port on restart.
360
358
  // Never forward a probed/bumped port: replacement config runs while
361
359
  // the old listener still owns the port. The holding page is optional.
362
- resolvedDevPort = start.port;
363
- resolvedDevPortExplicit = userConfig.server?.strictPort ?? false;
364
- if (start.port !== 0) {
360
+ resolvedDevPort = resolveStartPort({
361
+ configPort: userConfig.server?.port,
362
+ envPort: process.env.PORT,
363
+ });
364
+ if (resolvedDevPort !== 0) {
365
365
  ctx.holdingServer = createHoldingServer();
366
- await ctx.holdingServer.listen(start.port, resolvedHost).catch(() => {
366
+ await ctx.holdingServer.listen(resolvedDevPort, resolvedHost).catch(() => {
367
367
  ctx.holdingServer = null;
368
368
  });
369
369
  }
370
- } else if (command === 'serve' && isPreview) {
371
- // Preview mode: resolve the starting port from config/env/
372
- // default but do NOT probe. Vite's preview server handles the
373
- // bind itself, with `preview.strictPort` controlling whether
374
- // an in-use port auto-bumps (implicit) or errors (explicit).
375
- const previewConfigPort =
376
- typeof userConfig.preview?.port === 'number'
377
- ? userConfig.preview.port
378
- : typeof userConfig.server?.port === 'number'
379
- ? userConfig.server.port
380
- : undefined;
381
- const start = resolveStartPort({
382
- configPort: previewConfigPort,
383
- envPort: process.env.PORT,
384
- });
385
- resolvedDevPort = start.port;
386
- resolvedDevPortExplicit = start.explicit;
387
370
  }
388
371
 
389
372
  // Derive relative buildOutDir from the absolute buildDir (set above)
@@ -429,32 +412,20 @@ export function timber(config?: TimberUserConfig): PluginOption[] {
429
412
  };
430
413
  }
431
414
 
432
- // Dev/preview mode: set outDir so dev-time references are
433
- // consistent, and surface the resolved port to Vite.
415
+ // Dev mode: set outDir so dev-time references are consistent, and
416
+ // surface the resolved port to Vite.
434
417
  //
435
418
  // Dev auto-bumps unless the user sets server.strictPort.
436
419
  // Always forward the requested port so Vite can recognize unchanged
437
420
  // config and reuse its actual bound port across restarts (TIM-1456).
438
- //
439
- // For `vite preview`, we set `preview.strictPort` based on
440
- // whether the user explicitly set the port. Implicit (default)
441
- // preview uses strictPort: false so Vite's preview server can
442
- // auto-bump from 3000. Explicit preview uses strictPort: true
443
- // so conflicts fail loudly, matching the dev behavior and the
444
- // TIM-842 spec.
445
421
  const serverConfig: {
446
422
  port?: number;
447
423
  strictPort?: boolean;
448
424
  forwardConsole?: boolean | { unhandledErrors?: boolean; logLevels?: string[] };
449
425
  } = {};
450
- const previewConfig: { port?: number; strictPort?: boolean } = {};
451
426
  if (resolvedDevPort != null) {
452
- if (!isPreview) {
453
- serverConfig.port = resolvedDevPort;
454
- serverConfig.strictPort = resolvedDevPortExplicit;
455
- }
456
- previewConfig.port = resolvedDevPort;
457
- previewConfig.strictPort = resolvedDevPortExplicit;
427
+ serverConfig.port = resolvedDevPort;
428
+ serverConfig.strictPort = userConfig.server?.strictPort ?? false;
458
429
  }
459
430
 
460
431
  // Enable Vite 8's built-in browser→terminal console forwarding.
@@ -476,29 +447,35 @@ export function timber(config?: TimberUserConfig): PluginOption[] {
476
447
  // Seed the client optimizer's startup crawl with every 'use client'
477
448
  // file so client-only packages are pre-bundled before the first
478
449
  // request, not discovered mid-load (which full-reloads the page).
479
- // Vite concatenates these with any entries the user sets.
450
+ // Vite concatenates these with any entries the user sets. The scan
451
+ // plugin keeps that crawl out of 'use server' modules, whose imports
452
+ // the browser never loads; Vite's mergeConfig concatenates it with any
453
+ // user or plugin-rsc rolldownOptions.plugins rather than replacing them. Its per-file
454
+ // cost lands inside Vite's own scan, not in client-deps-scan.
480
455
  // See design/21-dev-server.md §"Client Dependency Pre-Bundling".
481
- let environments: Record<string, object> = envOutDirs;
482
- if (!isPreview) {
483
- ctx.timer.start('client-deps-scan');
484
- // Loaded lazily: directive detection pulls in @vitejs/plugin-rsc's
485
- // transforms, which builds and preview never need.
486
- const { clientOptimizeDepsEntries } = await import('./plugins/client-dep-entries.ts');
487
- const entries = await clientOptimizeDepsEntries(resolvedRoot, BROWSER_ENTRY_FILE, buildDir);
488
- ctx.timer.end('client-deps-scan');
489
- environments = {
490
- ...envOutDirs,
491
- client: { ...envOutDirs.client, optimizeDeps: { entries } },
492
- };
493
- }
456
+ ctx.timer.start('client-deps-scan');
457
+ // Loaded lazily: directive detection pulls in @vitejs/plugin-rsc's
458
+ // transforms, which builds never need.
459
+ const { clientOptimizeDepsEntries, skipUseServerScanPlugin } =
460
+ await import('./plugins/client-dep-entries.ts');
461
+ const entries = await clientOptimizeDepsEntries(resolvedRoot, BROWSER_ENTRY_FILE, buildDir);
462
+ ctx.timer.end('client-deps-scan');
494
463
 
495
464
  return {
496
465
  build: { outDir: buildOutDir },
497
- environments,
466
+ environments: {
467
+ ...envOutDirs,
468
+ client: {
469
+ ...envOutDirs.client,
470
+ optimizeDeps: {
471
+ entries,
472
+ rolldownOptions: { plugins: [skipUseServerScanPlugin()] },
473
+ },
474
+ },
475
+ },
498
476
  optimizeDeps: { exclude: timberOptimizeDepsExclude },
499
477
  customLogger,
500
478
  server: serverConfig,
501
- preview: previewConfig,
502
479
  };
503
480
  },
504
481
  configResolved(resolved) {
@@ -18,6 +18,14 @@
18
18
  * the browser entry is listed too. Files that gain the directive after
19
19
  * startup still fall back to Vite's late discovery.
20
20
  *
21
+ * The crawl follows those entries' imports into `'use server'` modules
22
+ * too, because Vite's scanner does not run plugin-rsc's transforms — at
23
+ * runtime the browser only ever sees server references in their place.
24
+ * Without help the optimizer pre-bundles the actions' server-only
25
+ * packages (database clients, cloud SDKs) for the browser, slowing cold
26
+ * start or failing the whole client optimizer when one cannot bundle.
27
+ * `skipUseServerScanPlugin` stubs those modules out of the crawl.
28
+ *
21
29
  * Design docs: 21-dev-server.md §"Client Dependency Pre-Bundling".
22
30
  */
23
31
 
@@ -53,6 +61,44 @@ export async function findUseClientFiles(root: string, excludeDir?: string): Pro
53
61
  return matches.filter((file): file is string => file !== null);
54
62
  }
55
63
 
64
+ /**
65
+ * The scanner's replacement for an app source file whose directive
66
+ * prologue holds `'use server'`: an empty module, so the crawl stops
67
+ * there. Returns null (load normally) for every other file. A
68
+ * `'use server'` inside a function body (an inline action in a server
69
+ * component) is not a module directive and leaves the file alone.
70
+ */
71
+ export async function useServerScanStub(id: string): Promise<string | null> {
72
+ const file = normalizeSlashes(id);
73
+ if (file.includes('/node_modules/') || !PARSEABLE_EXTENSIONS.test(file)) return null;
74
+ const code = await readFile(id, 'utf8').catch(() => null);
75
+ if (code === null || !code.includes('use server')) return null;
76
+ return detectDirective(code, file) === 'use server' ? 'export {}' : null;
77
+ }
78
+
79
+ /**
80
+ * A rolldown plugin for the client environment's
81
+ * `optimizeDeps.rolldownOptions.plugins`. Vite's scanner runs these
82
+ * before its own scan plugin, so this `load` hook decides what the crawl
83
+ * sees of each app source file (Vite has no JS load hook of its own
84
+ * there; rolldown reads the file).
85
+ *
86
+ * Vite also runs these plugins in the optimizer's bundle step. That step
87
+ * bundles the discovered dependencies, which live in node_modules, so the
88
+ * node_modules guard makes the hook a no-op there. The exception is a
89
+ * linked package outside node_modules listed in `optimizeDeps.include`
90
+ * with a module-level `'use server'` file: named imports from the stub
91
+ * fail that bundle (MISSING_EXPORT). Unstubbed, it would ship the server
92
+ * code to the browser instead, so such a package must not be
93
+ * pre-bundled either way.
94
+ */
95
+ export function skipUseServerScanPlugin(): {
96
+ name: string;
97
+ load: (id: string) => Promise<string | null>;
98
+ } {
99
+ return { name: 'timber:client-deps-skip-use-server', load: useServerScanStub };
100
+ }
101
+
56
102
  /**
57
103
  * Escape a path for use as an `optimizeDeps.entries` pattern. Vite globs
58
104
  * entries, and route directories are full of glob syntax: `(group)`,
@@ -1,6 +1,6 @@
1
- /** Port input precedence for dev and preview. Vite owns binding and restart reuse. */
1
+ /** Port input precedence for dev. Vite owns binding and restart reuse. */
2
2
 
3
- /** Default port used by `timber dev` and `timber preview`. */
3
+ /** Default port used by `timber dev`. */
4
4
  export const DEFAULT_PORT = 3000;
5
5
 
6
6
  // ── Pure resolution ────────────────────────────────────────────────────
@@ -18,36 +18,26 @@ export interface ResolvePortInput {
18
18
  defaultPort?: number;
19
19
  }
20
20
 
21
- export interface ResolvedPortInput {
22
- /** Port to start binding from. */
23
- port: number;
24
- /**
25
- * `true` if the port came from an explicit user override (config or
26
- * env). Preview uses this to default to strict port binding.
27
- */
28
- explicit: boolean;
29
- }
30
-
31
21
  /**
32
22
  * Pure: compute the starting port from config / env / defaults.
33
23
  *
34
24
  * Performs no I/O.
35
25
  */
36
- export function resolveStartPort(input: ResolvePortInput): ResolvedPortInput {
26
+ export function resolveStartPort(input: ResolvePortInput): number {
37
27
  const defaultPort = input.defaultPort ?? DEFAULT_PORT;
38
28
 
39
29
  // `configPort` wins over `envPort`. This matches Vite's behavior:
40
30
  // `vite --port 4000` overrides `PORT=5000` in the environment.
41
31
  if (typeof input.configPort === 'number' && Number.isFinite(input.configPort)) {
42
- return { port: input.configPort, explicit: true };
32
+ return input.configPort;
43
33
  }
44
34
 
45
35
  if (input.envPort != null && input.envPort !== '') {
46
36
  const parsed = Number(input.envPort);
47
37
  if (Number.isFinite(parsed) && parsed > 0) {
48
- return { port: parsed, explicit: true };
38
+ return parsed;
49
39
  }
50
40
  }
51
41
 
52
- return { port: defaultPort, explicit: false };
42
+ return defaultPort;
53
43
  }
@@ -1 +0,0 @@
1
- {"version":3,"file":"client-dep-entries-DyDqXOF9.js","names":[],"sources":["../../src/plugins/client-dep-entries.ts"],"sourcesContent":["/**\n * client-dep-entries — seed the client dep optimizer's startup scan with\n * the app's `'use client'` modules.\n *\n * Vite's dev optimizer discovers bare imports by crawling from its\n * entries before the first request. With no `optimizeDeps.entries`, the\n * client environment crawls its build input — timber's browser entry —\n * and nothing more: every `'use client'` module is reached only through\n * the RSC payload at runtime, never through a static import the crawl\n * can follow. A package imported only from client components is then\n * found on the first browser request, re-optimized mid-load, and the\n * page full-reloads (\"optimized dependencies changed. reloading\"). That\n * reload can leave react and react-dom from two optimizer runs in the\n * browser (duplicate React → \"Invalid hook call\").\n *\n * Listing the `'use client'` files as entries lets the startup crawl see\n * those imports. Setting `entries` replaces the build-input default, so\n * the browser entry is listed too. Files that gain the directive after\n * startup still fall back to Vite's late discovery.\n *\n * Design docs: 21-dev-server.md §\"Client Dependency Pre-Bundling\".\n */\n\nimport { readFile } from 'node:fs/promises';\nimport { sep } from 'node:path';\nimport { detectDirective, PARSEABLE_EXTENSIONS } from '../analyze/classify.ts';\nimport { normalizeSlashes, scanProjectSourceFiles } from '../analyze/scan.ts';\n\n/**\n * Every project source file under `root` whose directive prologue holds\n * `'use client'`. Uses the same walker as `timber graph` (node_modules,\n * root-level dot dirs and build outputs skipped) and the same AST\n * directive check the RSC plugin applies. Files under `excludeDir` (the\n * build output) are skipped.\n */\nexport async function findUseClientFiles(root: string, excludeDir?: string): Promise<string[]> {\n const files: string[] = [];\n // An unreadable directory only means its client deps are discovered\n // late, through Vite's normal fallback — never fatal for dev startup.\n await scanProjectSourceFiles(root, files, () => {}, 0, PARSEABLE_EXTENSIONS);\n const excludePrefix = excludeDir ? excludeDir + sep : undefined;\n const candidates = excludePrefix ? files.filter((f) => !f.startsWith(excludePrefix)) : files;\n\n const matches = await Promise.all(\n candidates.map(async (file) => {\n const code = await readFile(file, 'utf8').catch(() => null);\n // Cheap text gate before parsing: a directive is a literal\n // without escapes, so a file lacking the text cannot carry it.\n if (code === null || !code.includes('use client')) return null;\n return detectDirective(code, file) === 'use client' ? file : null;\n })\n );\n return matches.filter((file): file is string => file !== null);\n}\n\n/**\n * Escape a path for use as an `optimizeDeps.entries` pattern. Vite globs\n * entries, and route directories are full of glob syntax: `(group)`,\n * `[slug]`, `[[...catchAll]]`, `@slot`. Slashes are normalized first, so\n * the only backslashes left are literal (POSIX) ones, which are escaped\n * too.\n */\nexport function escapeGlobPath(path: string): string {\n return normalizeSlashes(path).replace(/[\\\\()[\\]{}*?|!+@]/g, '\\\\$&');\n}\n\n/**\n * The client environment's `optimizeDeps.entries`: timber's browser\n * entry plus every `'use client'` file in the project.\n */\nexport async function clientOptimizeDepsEntries(\n root: string,\n browserEntryFile: string,\n buildDir: string\n): Promise<string[]> {\n const clientFiles = await findUseClientFiles(root, buildDir);\n return [browserEntryFile, ...clientFiles].map(escapeGlobPath);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmCA,eAAsB,mBAAmB,MAAc,YAAwC;CAC7F,MAAM,QAAkB,CAAC;CAGzB,MAAM,uBAAuB,MAAM,aAAa,CAAC,GAAG,GAAG,oBAAoB;CAC3E,MAAM,gBAAgB,aAAa,aAAa,MAAM,KAAA;CACtD,MAAM,aAAa,gBAAgB,MAAM,QAAQ,MAAM,CAAC,EAAE,WAAW,aAAa,CAAC,IAAI;CAWvF,QAAO,MATe,QAAQ,IAC5B,WAAW,IAAI,OAAO,SAAS;EAC7B,MAAM,OAAO,MAAM,SAAS,MAAM,MAAM,CAAC,CAAC,YAAY,IAAI;EAG1D,IAAI,SAAS,QAAQ,CAAC,KAAK,SAAS,YAAY,GAAG,OAAO;EAC1D,OAAO,gBAAgB,MAAM,IAAI,MAAM,eAAe,OAAO;CAC/D,CAAC,CACH,EAAA,CACe,QAAQ,SAAyB,SAAS,IAAI;AAC/D;;;;;;;;AASA,SAAgB,eAAe,MAAsB;CACnD,OAAO,iBAAiB,IAAI,CAAC,CAAC,QAAQ,sBAAsB,MAAM;AACpE;;;;;AAMA,eAAsB,0BACpB,MACA,kBACA,UACmB;CAEnB,OAAO,CAAC,kBAAkB,GAAG,MADH,mBAAmB,MAAM,QAAQ,CACnB,CAAC,CAAC,IAAI,cAAc;AAC9D"}