@farm.js/plugin 0.1.61 → 0.1.63

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 (40) hide show
  1. package/dist/index.d.ts +1 -1
  2. package/dist/index.js +1 -1
  3. package/dist/middleware/index.d.ts +8 -1
  4. package/dist/middleware/index.d.ts.map +1 -1
  5. package/dist/middleware/index.js +16 -10
  6. package/dist/middleware/matching.d.ts +4 -2
  7. package/dist/middleware/matching.d.ts.map +1 -1
  8. package/dist/middleware/matching.js +7 -47
  9. package/dist/rsc/client-sourcemaps.d.ts +13 -0
  10. package/dist/rsc/client-sourcemaps.d.ts.map +1 -0
  11. package/dist/rsc/client-sourcemaps.js +52 -0
  12. package/dist/rsc/document-layouts.d.ts +16 -0
  13. package/dist/rsc/document-layouts.d.ts.map +1 -0
  14. package/dist/rsc/document-layouts.js +82 -0
  15. package/dist/rsc/entries/client.d.ts.map +1 -1
  16. package/dist/rsc/entries/client.js +92 -16
  17. package/dist/rsc/entries/rsc.d.ts.map +1 -1
  18. package/dist/rsc/entries/rsc.js +567 -47
  19. package/dist/rsc/entries/ssr.d.ts.map +1 -1
  20. package/dist/rsc/entries/ssr.js +27 -10
  21. package/dist/rsc/index.d.ts +38 -3
  22. package/dist/rsc/index.d.ts.map +1 -1
  23. package/dist/rsc/index.js +300 -292
  24. package/dist/rsc/middleware-config-module.d.ts +3 -0
  25. package/dist/rsc/middleware-config-module.d.ts.map +1 -1
  26. package/dist/rsc/middleware-config-module.js +41 -28
  27. package/dist/rsc/mobile-client.d.ts +67 -0
  28. package/dist/rsc/mobile-client.d.ts.map +1 -0
  29. package/dist/rsc/mobile-client.js +148 -0
  30. package/dist/rsc/nitro-build.d.ts.map +1 -1
  31. package/dist/rsc/nitro-build.js +268 -81
  32. package/dist/rsc/server-fn-transform.d.ts +1 -5
  33. package/dist/rsc/server-fn-transform.d.ts.map +1 -1
  34. package/dist/rsc/server-fn-transform.js +3 -338
  35. package/dist/rsc/types.d.ts +39 -0
  36. package/dist/rsc/types.d.ts.map +1 -1
  37. package/dist/rsc/vite-plugin-nitro.d.ts +2 -0
  38. package/dist/rsc/vite-plugin-nitro.d.ts.map +1 -1
  39. package/dist/rsc/vite-plugin-nitro.js +12 -2
  40. package/package.json +3 -3
package/dist/index.d.ts CHANGED
@@ -39,5 +39,5 @@
39
39
  * })
40
40
  * ```
41
41
  */
42
- export declare const version = "0.1.21";
42
+ export declare const version = "0.1.63";
43
43
  //# sourceMappingURL=index.d.ts.map
package/dist/index.js CHANGED
@@ -39,7 +39,7 @@
39
39
  * })
40
40
  * ```
41
41
  */
42
- export const version = "0.1.21";
42
+ export const version = "0.1.63";
43
43
  // Note: Import plugins from their respective subpaths:
44
44
  // - @farm.js/plugin/rsc
45
45
  // - @farm.js/plugin/middleware
@@ -40,7 +40,7 @@ export interface CookieOptions {
40
40
  export interface CookieJar {
41
41
  get(name: string): string | undefined;
42
42
  set(name: string, value: string, options?: CookieOptions): void;
43
- delete(name: string): void;
43
+ delete(name: string, options?: CookieOptions): void;
44
44
  getAll(): Record<string, string>;
45
45
  }
46
46
  /**
@@ -50,7 +50,14 @@ export interface MiddlewareContext {
50
50
  request: IncomingMessage;
51
51
  response: ServerResponse;
52
52
  url: URL;
53
+ /** Request pathname as received: still percent-encoded. */
53
54
  pathname: string;
55
+ /**
56
+ * The pathname the router matches: each segment decoded once, as core's
57
+ * `ctx.routePathname`. `.when()` conditions and function matchers also see it,
58
+ * so `/%61dmin` cannot skip a check written for `/admin`. Updated by `rewrite()`.
59
+ */
60
+ readonly routePathname: string;
54
61
  searchParams: URLSearchParams;
55
62
  method: string;
56
63
  params: Record<string, string>;
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/middleware/index.ts"],"names":[],"mappings":"AACA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,KAAK,EAAE,MAAM,EAAE,aAAa,EAAE,MAAM,MAAM,CAAC;AAClD,OAAO,KAAK,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AC;IAC3B,IAAI,CAAC,IAAI,EAAE,GAAG,EAAE,MAAM,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACvC,IAAI,CAAC,OAAO,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC7C,IAAI,CAAC,OAAO,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;CAC9C;AAED,MAAM,MAAM,iBAAiB,GAAG,CAC9B,GAAG,EAAE,iBAAiB,EACtB,IAAI,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,KACtB,OAAO,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC;AAE1B,MAAM,WAAW,oBAAoB;IACnC,IAAI,EAAE,MAAM,CAAC;IACb,QAAQ,EAAE,MAAM,CAAC;IACjB,MAAM,EACF,iBAAiB,GACjB;QAAE,KAAK,EAAE,MAAM;YAAE,QAAQ,EAAE,iBAAiB,EAAE,CAAA;SAAE,CAAC;QAAC,WAAW,CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,CAAA;KAAE,CAAC;IAC7F,MAAM,CAAC,EAAE,gBAAgB,CAAC;CAC3B;AA6KD;;GAEG;AACH,MAAM,CAAC,OAAO,UAAU,cAAc,CAAC,OAAO,GAAE,qBAA0B,GAAG,MAAM,CAoUlF;AAED,OAAO,EAAE,cAAc,EAAE,CAAC"}
@@ -3,7 +3,7 @@ import { createRequire } from "node:module";
3
3
  import { _withAfterNodeMiddleware } from "@farm.js/core/after";
4
4
  import { devServableFileExists } from "../dev-static.js";
5
5
  import { resolveDevRequestURL, resolveViteHtmlFallbackUrl } from "../dev-request.js";
6
- import { matchesMiddlewareConfig } from "@farm.js/core/middleware";
6
+ import { canonicalizeRequestPathname, matchesMiddlewareConfig, serializeMiddlewareCookieDeletion, } from "@farm.js/core/middleware";
7
7
  import { middlewareMatchesPath, parseCookies, serializeCookie } from "./matching.js";
8
8
  // Create require for ESM compatibility
9
9
  const require_ = createRequire(import.meta.url);
@@ -37,24 +37,27 @@ const getColors = () => {
37
37
  */
38
38
  function createCookieJar(req, res) {
39
39
  const cookies = parseCookies(req.headers.cookie);
40
- const setCookies = [];
40
+ // Keep any Set-Cookie an earlier handler already wrote.
41
+ const existing = res.getHeader("Set-Cookie");
42
+ const setCookies = Array.isArray(existing)
43
+ ? existing.map(String)
44
+ : existing === undefined
45
+ ? []
46
+ : [String(existing)];
41
47
  return {
42
48
  get(name) {
43
49
  return cookies[name];
44
50
  },
45
51
  set(name, value, options = {}) {
46
52
  cookies[name] = value;
47
- const cookieString = serializeCookie(name, value, options);
48
- setCookies.push(cookieString);
53
+ setCookies.push(serializeCookie(name, value, options));
49
54
  res.setHeader("Set-Cookie", setCookies);
50
55
  },
51
- delete(name) {
56
+ delete(name, options = {}) {
52
57
  delete cookies[name];
53
- const cookieString = serializeCookie(name, "", {
54
- maxAge: 0,
55
- expires: new Date(0),
56
- });
57
- setCookies.push(cookieString);
58
+ // Path and Domain must match the cookie that was set, or the tombstone
59
+ // addresses a different cookie and the original survives.
60
+ setCookies.push(serializeMiddlewareCookieDeletion(name, options));
58
61
  res.setHeader("Set-Cookie", setCookies);
59
62
  },
60
63
  getAll() {
@@ -91,6 +94,8 @@ function createContext(req, res, viteServer) {
91
94
  response: res,
92
95
  url,
93
96
  pathname: url.pathname,
97
+ // Vite has already removed its base from the URL, so this is the app's path.
98
+ routePathname: canonicalizeRequestPathname(url.pathname),
94
99
  searchParams: url.searchParams,
95
100
  method: req.method || "GET",
96
101
  params: {},
@@ -125,6 +130,7 @@ function createContext(req, res, viteServer) {
125
130
  const newUrl = new URL(rewriteUrl, `http://${req.headers.host || "localhost"}`);
126
131
  ctx.url = newUrl;
127
132
  ctx.pathname = newUrl.pathname;
133
+ ctx.routePathname = canonicalizeRequestPathname(newUrl.pathname);
128
134
  ctx.searchParams = newUrl.searchParams;
129
135
  // Update the original request URL
130
136
  req.url = rewriteUrl;
@@ -6,7 +6,8 @@ import type { CookieOptions } from "./index.js";
6
6
  * (a latin-1 value from an old link, a crawler, or a bare `%`) must not take
7
7
  * the whole map down: an unguarded `decodeURIComponent` throws `URIError`,
8
8
  * which fails the request before any middleware runs. Decoding falls back to
9
- * the raw value per entry instead.
9
+ * the raw value per entry instead. This is core's parser, so dev and production
10
+ * agree on which duplicate wins.
10
11
  */
11
12
  export declare function parseCookies(cookieHeader?: string): Record<string, string>;
12
13
  /**
@@ -28,7 +29,8 @@ export declare function middlewareMatchesPath(pathname: string, middlewarePath:
28
29
  *
29
30
  * `Max-Age=0` is the canonical immediate-expiry directive, so the attribute is
30
31
  * emitted whenever `maxAge` is provided — a `0` must not be dropped the way a
31
- * plain truthiness check would drop it.
32
+ * plain truthiness check would drop it. This is core's serializer, so a dev
33
+ * Set-Cookie carries the attributes a browser requires, as production does.
32
34
  */
33
35
  export declare function serializeCookie(name: string, value: string, options?: CookieOptions): string;
34
36
  //# sourceMappingURL=matching.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"matching.d.ts","sourceRoot":"","sources":["../../src/middleware/matching.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AAEhD;;;;;;;;GAQG;AACH,wBAAgB,YAAY,CAAC,YAAY,CAAC,EAAE,MAAM,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAc1E;AAUD;;;;;;;;;;;;GAYG;AACH,wBAAgB,qBAAqB,CAAC,QAAQ,EAAE,MAAM,EAAE,cAAc,EAAE,MAAM,GAAG,OAAO,CAMvF;AAED;;;;;;GAMG;AACH,wBAAgB,eAAe,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,OAAO,GAAE,aAAkB,GAAG,MAAM,CAkChG"}
1
+ {"version":3,"file":"matching.d.ts","sourceRoot":"","sources":["../../src/middleware/matching.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AAEhD;;;;;;;;;GASG;AACH,wBAAgB,YAAY,CAAC,YAAY,CAAC,EAAE,MAAM,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAE1E;AAED;;;;;;;;;;;;GAYG;AACH,wBAAgB,qBAAqB,CAAC,QAAQ,EAAE,MAAM,EAAE,cAAc,EAAE,MAAM,GAAG,OAAO,CAMvF;AAED;;;;;;;GAOG;AACH,wBAAgB,eAAe,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,OAAO,GAAE,aAAkB,GAAG,MAAM,CAEhG"}
@@ -1,4 +1,4 @@
1
- import { canonicalizeRequestPathSegments } from "@farm.js/core/middleware";
1
+ import { canonicalizeRequestPathSegments, parseMiddlewareCookieHeader, serializeMiddlewareCookie, } from "@farm.js/core/middleware";
2
2
  /**
3
3
  * Parse cookies from a Cookie header.
4
4
  *
@@ -6,27 +6,11 @@ import { canonicalizeRequestPathSegments } from "@farm.js/core/middleware";
6
6
  * (a latin-1 value from an old link, a crawler, or a bare `%`) must not take
7
7
  * the whole map down: an unguarded `decodeURIComponent` throws `URIError`,
8
8
  * which fails the request before any middleware runs. Decoding falls back to
9
- * the raw value per entry instead.
9
+ * the raw value per entry instead. This is core's parser, so dev and production
10
+ * agree on which duplicate wins.
10
11
  */
11
12
  export function parseCookies(cookieHeader) {
12
- if (!cookieHeader)
13
- return {};
14
- return cookieHeader.split(";").reduce((cookies, cookie) => {
15
- const [name, ...rest] = cookie.split("=");
16
- const value = rest.join("=").trim();
17
- if (name && value) {
18
- cookies[name.trim()] = decodeCookieValue(value);
19
- }
20
- return cookies;
21
- }, {});
22
- }
23
- function decodeCookieValue(value) {
24
- try {
25
- return decodeURIComponent(value);
26
- }
27
- catch {
28
- return value;
29
- }
13
+ return parseMiddlewareCookieHeader(cookieHeader);
30
14
  }
31
15
  /**
32
16
  * Whether a middleware registered at `middlewarePath` applies to `pathname`.
@@ -55,33 +39,9 @@ export function middlewareMatchesPath(pathname, middlewarePath) {
55
39
  *
56
40
  * `Max-Age=0` is the canonical immediate-expiry directive, so the attribute is
57
41
  * emitted whenever `maxAge` is provided — a `0` must not be dropped the way a
58
- * plain truthiness check would drop it.
42
+ * plain truthiness check would drop it. This is core's serializer, so a dev
43
+ * Set-Cookie carries the attributes a browser requires, as production does.
59
44
  */
60
45
  export function serializeCookie(name, value, options = {}) {
61
- let cookie = `${encodeURIComponent(name)}=${encodeURIComponent(value)}`;
62
- if (options.maxAge != null) {
63
- cookie += `; Max-Age=${options.maxAge}`;
64
- }
65
- if (options.expires) {
66
- cookie += `; Expires=${options.expires.toUTCString()}`;
67
- }
68
- if (options.path) {
69
- cookie += `; Path=${options.path}`;
70
- }
71
- else {
72
- cookie += "; Path=/";
73
- }
74
- if (options.domain) {
75
- cookie += `; Domain=${options.domain}`;
76
- }
77
- if (options.secure) {
78
- cookie += "; Secure";
79
- }
80
- if (options.httpOnly) {
81
- cookie += "; HttpOnly";
82
- }
83
- if (options.sameSite) {
84
- cookie += `; SameSite=${options.sameSite.charAt(0).toUpperCase() + options.sameSite.slice(1)}`;
85
- }
86
- return cookie;
46
+ return serializeMiddlewareCookie(name, value, options);
87
47
  }
@@ -0,0 +1,13 @@
1
+ import type { Plugin } from "vite";
2
+ /** Where an RSC build keeps client source maps, beside (not inside) the public client output. */
3
+ export declare const RSC_CLIENT_SOURCEMAPS_DIR = "client-sourcemaps";
4
+ /**
5
+ * Keep the client environment's source maps out of the public output, as core
6
+ * client builds do. A client map carries the original source of every module
7
+ * in a chunk, including code stripped from the client JS, such as
8
+ * `createServerOnlyFn` bodies. Any enabled `build.sourcemap` becomes
9
+ * `"hidden"` (the JS names no map), and the maps are moved beside the client
10
+ * output.
11
+ */
12
+ export declare function rscPrivateClientSourcemaps(environmentName?: string): Plugin;
13
+ //# sourceMappingURL=client-sourcemaps.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client-sourcemaps.d.ts","sourceRoot":"","sources":["../../src/rsc/client-sourcemaps.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,MAAM,CAAC;AAEnC,iGAAiG;AACjG,eAAO,MAAM,yBAAyB,sBAAsB,CAAC;AAI7D;;;;;;;GAOG;AACH,wBAAgB,0BAA0B,CAAC,eAAe,SAAW,GAAG,MAAM,CAqC7E"}
@@ -0,0 +1,52 @@
1
+ import fs from "node:fs/promises";
2
+ import path from "node:path";
3
+ /** Where an RSC build keeps client source maps, beside (not inside) the public client output. */
4
+ export const RSC_CLIENT_SOURCEMAPS_DIR = "client-sourcemaps";
5
+ /**
6
+ * Keep the client environment's source maps out of the public output, as core
7
+ * client builds do. A client map carries the original source of every module
8
+ * in a chunk, including code stripped from the client JS, such as
9
+ * `createServerOnlyFn` bodies. Any enabled `build.sourcemap` becomes
10
+ * `"hidden"` (the JS names no map), and the maps are moved beside the client
11
+ * output.
12
+ */
13
+ export function rscPrivateClientSourcemaps(environmentName = "client") {
14
+ let maps = [];
15
+ let mapsDir;
16
+ const isClient = (environment) => environment?.name === environmentName;
17
+ return {
18
+ name: "@farm.js/plugin/rsc:private-client-sourcemaps",
19
+ enforce: "post",
20
+ apply: "build",
21
+ configEnvironment(name, config) {
22
+ if (name !== environmentName || !config.build?.sourcemap)
23
+ return;
24
+ return { build: { sourcemap: "hidden" } };
25
+ },
26
+ generateBundle(outputOptions, bundle) {
27
+ if (!isClient(this.environment))
28
+ return;
29
+ maps = [];
30
+ mapsDir = outputOptions.dir
31
+ ? path.join(path.dirname(outputOptions.dir), RSC_CLIENT_SOURCEMAPS_DIR)
32
+ : undefined;
33
+ for (const [fileName, output] of Object.entries(bundle)) {
34
+ if (output.type !== "asset" || !fileName.endsWith(".map"))
35
+ continue;
36
+ maps.push([fileName, output.source ?? ""]);
37
+ delete bundle[fileName];
38
+ }
39
+ },
40
+ async writeBundle() {
41
+ if (!isClient(this.environment) || !mapsDir)
42
+ return;
43
+ await fs.rm(mapsDir, { recursive: true, force: true });
44
+ for (const [fileName, source] of maps) {
45
+ const target = path.join(mapsDir, fileName);
46
+ await fs.mkdir(path.dirname(target), { recursive: true });
47
+ await fs.writeFile(target, source);
48
+ }
49
+ maps = [];
50
+ },
51
+ };
52
+ }
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Whether a layout module renders the whole `<html>` document, following re-exports of its default
3
+ * export a few modules deep (`export { default } from "../site/app/layout"`).
4
+ */
5
+ export declare function layoutRendersDocument(file: string, depth?: number): Promise<boolean>;
6
+ /**
7
+ * Files below `routesDir` whose name passes `test`, as route-relative keys (`/layout.tsx`,
8
+ * `/(docs)/layout.tsx`): the keys the RSC entry gives its merged route module maps.
9
+ */
10
+ export declare function findRouteFiles(routesDir: string, test: (name: string) => boolean): Promise<Array<{
11
+ key: string;
12
+ file: string;
13
+ }>>;
14
+ /** The layouts below `routesDir` that render the `<html>` document themselves. */
15
+ export declare function findDocumentLayouts(routesDir: string): Promise<string[]>;
16
+ //# sourceMappingURL=document-layouts.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"document-layouts.d.ts","sourceRoot":"","sources":["../../src/rsc/document-layouts.ts"],"names":[],"mappings":"AA2BA;;;GAGG;AACH,wBAAsB,qBAAqB,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,SAAI,GAAG,OAAO,CAAC,OAAO,CAAC,CAYrF;AAED;;;GAGG;AACH,wBAAsB,cAAc,CAClC,SAAS,EAAE,MAAM,EACjB,IAAI,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,OAAO,GAC9B,OAAO,CAAC,KAAK,CAAC;IAAE,GAAG,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE,CAAC,CAAC,CAuB/C;AAED,kFAAkF;AAClF,wBAAsB,mBAAmB,CAAC,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC,CAI9E"}
@@ -0,0 +1,82 @@
1
+ import { promises as fs } from "node:fs";
2
+ import path from "node:path";
3
+ const LAYOUT_FILE = /^layout\.(tsx|jsx|ts|js)$/;
4
+ const SOURCE_EXTENSIONS = [".tsx", ".ts", ".jsx", ".js"];
5
+ const RENDERS_HTML = /<html[\s>]/;
6
+ // `export { default } from "./x"` and `export { Layout as default } from "./x"`.
7
+ const DEFAULT_REEXPORT = /export\s*\{[^}]*\b(?:default|[\w$]+\s+as\s+default)\b[^}]*\}\s*from\s*["'](\.{1,2}\/[^"']+)["']/;
8
+ async function resolveRelativeModule(fromFile, specifier) {
9
+ const base = path.resolve(path.dirname(fromFile), specifier);
10
+ const candidates = [
11
+ base,
12
+ ...SOURCE_EXTENSIONS.map((extension) => base + extension),
13
+ ...SOURCE_EXTENSIONS.map((extension) => path.join(base, "index" + extension)),
14
+ ];
15
+ for (const candidate of candidates) {
16
+ try {
17
+ if ((await fs.stat(candidate)).isFile())
18
+ return candidate;
19
+ }
20
+ catch {
21
+ // try the next candidate
22
+ }
23
+ }
24
+ return null;
25
+ }
26
+ /**
27
+ * Whether a layout module renders the whole `<html>` document, following re-exports of its default
28
+ * export a few modules deep (`export { default } from "../site/app/layout"`).
29
+ */
30
+ export async function layoutRendersDocument(file, depth = 0) {
31
+ let source;
32
+ try {
33
+ source = await fs.readFile(file, "utf8");
34
+ }
35
+ catch {
36
+ return false;
37
+ }
38
+ if (RENDERS_HTML.test(source))
39
+ return true;
40
+ const reexport = DEFAULT_REEXPORT.exec(source);
41
+ if (!reexport || depth >= 4)
42
+ return false;
43
+ const target = await resolveRelativeModule(file, reexport[1]);
44
+ return target ? layoutRendersDocument(target, depth + 1) : false;
45
+ }
46
+ /**
47
+ * Files below `routesDir` whose name passes `test`, as route-relative keys (`/layout.tsx`,
48
+ * `/(docs)/layout.tsx`): the keys the RSC entry gives its merged route module maps.
49
+ */
50
+ export async function findRouteFiles(routesDir, test) {
51
+ const found = [];
52
+ const walk = async (dir) => {
53
+ let entries;
54
+ try {
55
+ entries = await fs.readdir(dir, { withFileTypes: true });
56
+ }
57
+ catch {
58
+ return;
59
+ }
60
+ for (const entry of entries) {
61
+ const full = path.join(dir, entry.name);
62
+ if (entry.isDirectory()) {
63
+ if (entry.name !== "node_modules" && !entry.name.startsWith("."))
64
+ await walk(full);
65
+ }
66
+ else if (test(entry.name)) {
67
+ found.push({
68
+ key: "/" + path.relative(routesDir, full).split(path.sep).join("/"),
69
+ file: full,
70
+ });
71
+ }
72
+ }
73
+ };
74
+ await walk(routesDir);
75
+ return found.sort((left, right) => (left.key < right.key ? -1 : left.key > right.key ? 1 : 0));
76
+ }
77
+ /** The layouts below `routesDir` that render the `<html>` document themselves. */
78
+ export async function findDocumentLayouts(routesDir) {
79
+ const layouts = await findRouteFiles(routesDir, (name) => LAYOUT_FILE.test(name));
80
+ const owners = await Promise.all(layouts.map(({ file }) => layoutRendersDocument(file)));
81
+ return layouts.filter((_, index) => owners[index]).map(({ key }) => key);
82
+ }
@@ -1 +1 @@
1
- {"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../../../src/rsc/entries/client.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAEhD,eAAO,MAAM,mCAAmC,62BA6B9C,CAAC;AAEH;;;;;;;;;;GAUG;AACH,wBAAgB,mBAAmB,CAAC,GAAG,EAAE,YAAY,GAAG,MAAM,CAyT7D"}
1
+ {"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../../../src/rsc/entries/client.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAGhD,eAAO,MAAM,mCAAmC,62BA6B9C,CAAC;AAEH;;;;;;;;;;GAUG;AACH,wBAAgB,mBAAmB,CAAC,GAAG,EAAE,YAAY,GAAG,MAAM,CAqY7D"}
@@ -1,3 +1,4 @@
1
+ import { generateMobileShellNavigation } from "../mobile-client.js";
1
2
  export const serverFnTransportErrorClientRuntime = `function createFarmServerFnTransportError(value) {
2
3
  const message = value && typeof value === 'object' && typeof value.message === 'string'
3
4
  ? value.message
@@ -60,10 +61,15 @@ import {
60
61
  createFarmDeploymentRequestHeaders,
61
62
  isFarmDeploymentMismatchResponse,
62
63
  } from '@farm.js/core/deployment';
64
+ import { runFarmNavigationDelegates } from '@farm.js/core/internal/client-runtime';
63
65
  `;
66
+ // farm dev --mobile: every page runs in the shell's WebView, so this entry is the mobile client.
67
+ if (ctx.mobileClient === "inline") {
68
+ imports += generateMobileShellNavigation();
69
+ }
64
70
  if (ctx.actionsEnabled) {
65
71
  imports += `import { setServerCallback, encodeReply, createTemporaryReferenceSet } from '@vitejs/plugin-rsc/browser';
66
- import { applyFarmCacheInvalidations } from '@farm.js/core/cache';
72
+ import { applyFarmCacheInvalidations } from '@farm.js/core/internal/client-runtime';
67
73
  import {
68
74
  beginFarmServerQueryAction,
69
75
  completeFarmServerQueryAction,
@@ -137,8 +143,7 @@ setServerCallback(async (id, args) => {
137
143
  // router performs the navigation here.
138
144
  if (p.returnValue?.redirect?.url) {
139
145
  debug('Server action redirected:', p.returnValue.redirect.url);
140
- history.pushState(null, '', p.returnValue.redirect.url);
141
- await farmNavigateRef.current?.(location.href);
146
+ await farmNavigateRef.current?.(p.returnValue.redirect.url, 'push');
142
147
  return;
143
148
  }
144
149
  debug('Server action failed:', id);
@@ -171,15 +176,44 @@ function debug(...args) {
171
176
  ${debugLog}
172
177
  }
173
178
 
179
+ // A server component that fails while a client navigation renders it: a redirect() becomes a
180
+ // client navigation to its target, and anything else loads the URL as a document, so the server
181
+ // answers with its status and error.tsx. Errors in the first render are left to React.
182
+ class FarmNavigationErrorBoundary extends React.Component {
183
+ constructor(props) {
184
+ super(props);
185
+ this.state = { error: null, payload: props.payload };
186
+ }
187
+ static getDerivedStateFromProps(props, state) {
188
+ return props.payload === state.payload ? null : { error: null, payload: props.payload };
189
+ }
190
+ static getDerivedStateFromError(error) {
191
+ return { error };
192
+ }
193
+ componentDidCatch(error) {
194
+ const digest = error && typeof error.digest === 'string' ? error.digest : '';
195
+ if (digest.startsWith('FARM_REDIRECT;')) {
196
+ farmNavigateRef.current?.(digest.split(';').slice(2).join(';'), 'replace');
197
+ return;
198
+ }
199
+ location.reload();
200
+ }
201
+ render() {
202
+ if (this.state.error && !this.props.navigated) throw this.state.error;
203
+ return this.state.error ? null : this.props.children;
204
+ }
205
+ }
206
+
174
207
  async function main() {
175
208
  // Prevent double execution (e.g. script loaded twice)
176
209
  if (globalThis.__FARM_RSC_HYDRATED) return;
177
210
 
178
211
  debug('Starting client hydration');
179
212
 
180
- // Clean duplicate DOM as early as possible (server may have sent two blocks)
213
+ // Clean duplicate DOM as early as possible (server may have sent two blocks). Only Farm's own
214
+ // wrapper: an app that owns the document can have an element with id="root" in its content.
181
215
  const rootEl = document.getElementById('root');
182
- if (rootEl) {
216
+ if (rootEl && rootEl.firstElementChild?.hasAttribute('data-farm-root')) {
183
217
  while (rootEl.children.length > 1) rootEl.lastElementChild.remove();
184
218
  while (rootEl.nextElementSibling) rootEl.nextElementSibling.remove();
185
219
  }
@@ -251,8 +285,8 @@ async function main() {
251
285
  }
252
286
 
253
287
  e.preventDefault();
254
- history.pushState(null, '', a.href);
255
- nav();
288
+ // Link replace marks its anchor; a plain anchor pushes.
289
+ navigate(a.href, a.hasAttribute('data-replace') ? 'replace' : 'push');
256
290
  }
257
291
  };
258
292
 
@@ -271,17 +305,46 @@ async function main() {
271
305
  if (payload.root != null) console.warn('[Farm.js] payload.rootContent missing; not using payload.root to avoid duplicate block. Keys:', Object.keys(payload));
272
306
  return null;
273
307
  }
274
- return content;
308
+ return React.createElement(
309
+ FarmNavigationErrorBoundary,
310
+ { payload, navigated: payload !== initial },
311
+ content,
312
+ );
275
313
  }
276
314
 
315
+ // An in-app navigation (a link click, a redirect after a server action). Navigation delegates
316
+ // get it first, after the router's own checks, as Farm's other routers offer it: one that takes
317
+ // it (a native shell showing the URL on its own screen) leaves the page and URL as they are.
318
+ // Back/forward, refreshes and same-page moves are not offered; other origins load as documents.
319
+ async function navigate(href, action) {
320
+ const url = new URL(href, location.href);
321
+ if (url.origin !== location.origin) {
322
+ location.assign(url.href);
323
+ return;
324
+ }
325
+ const from = location.pathname + location.search;
326
+ const to = url.pathname + url.search;
327
+ if (to !== from && (await runFarmNavigationDelegates({ url: url.href, from, to, action }))) {
328
+ return;
329
+ }
330
+ if (action === 'replace') history.replaceState(null, '', url.href);
331
+ else history.pushState(null, '', url.href);
332
+ await refetch(location.href);
333
+ }
334
+ farmNavigateRef.current = navigate;
335
+
277
336
  // Fetch new RSC payload for a URL
278
- farmNavigateRef.current = (url) => refetch(url);
279
337
  async function refetch(url) {
280
338
  debug('Fetching RSC for:', url);
281
339
 
282
340
  try {
283
- // Request RSC format instead of HTML
284
- const res = await fetch(url, {
341
+ // Request the page's RSC payload, '<page>.rsc', which a prerendered page serves as a
342
+ // static file. The page URL itself may be static HTML.
343
+ const payloadUrl = new URL(url, location.href);
344
+ payloadUrl.pathname = payloadUrl.pathname.endsWith('/')
345
+ ? payloadUrl.pathname + 'index.rsc'
346
+ : payloadUrl.pathname + '.rsc';
347
+ const res = await fetch(payloadUrl, {
285
348
  headers: createFarmDeploymentRequestHeaders(farmDeploymentId, {
286
349
  Accept: 'text/x-component',
287
350
  }),
@@ -305,6 +368,10 @@ async function main() {
305
368
  // reflect the page actually rendered (auth gates redirect this way).
306
369
  if (res.redirected && res.url) {
307
370
  const dest = new URL(res.url);
371
+ if (dest.pathname.endsWith('.rsc')) {
372
+ const page = dest.pathname.slice(0, -'.rsc'.length);
373
+ dest.pathname = page.endsWith('/index') ? page.slice(0, -'index'.length) : page;
374
+ }
308
375
  if (dest.origin === location.origin) {
309
376
  const target = dest.pathname + dest.search + dest.hash;
310
377
  if (target !== location.pathname + location.search + location.hash) {
@@ -321,17 +388,26 @@ async function main() {
321
388
  location.href = url;
322
389
  }
323
390
  }
324
- const rootElForHydrate = document.getElementById('root');
391
+ // A root layout that renders <html> owns the document: hydrate it whole, as Next.js does.
392
+ const rootElForHydrate = initial.ownsDocument ? document : document.getElementById('root');
325
393
  if (!rootElForHydrate) {
326
394
  console.error('[Farm.js] #root element not found');
327
395
  return;
328
396
  }
329
- // Final cleanup pass before hydrate (in case DOM changed during async)
330
- while (rootElForHydrate.children.length > 1) rootElForHydrate.lastElementChild.remove();
331
- while (rootElForHydrate.nextElementSibling) rootElForHydrate.nextElementSibling.remove();
397
+ if (!initial.ownsDocument) {
398
+ // Final cleanup pass before hydrate (in case DOM changed during async)
399
+ while (rootElForHydrate.children.length > 1) rootElForHydrate.lastElementChild.remove();
400
+ while (rootElForHydrate.nextElementSibling) rootElForHydrate.nextElementSibling.remove();
401
+ }
332
402
  debug('Hydrating application');
333
403
  globalThis.__FARM_RSC_HYDRATED = true;
334
- hydrateRoot(rootElForHydrate, React.createElement(BrowserRoot), {
404
+ // The server renders #root inside <html>{[<head>, <body>]}</html>. That two-child fork is part of
405
+ // every useId below it, so the client hydrates #root at the same position (second of two) and
406
+ // its ids match the HTML's. A document the root layout owns is hydrated whole, as rendered.
407
+ const hydrated = initial.ownsDocument
408
+ ? React.createElement(BrowserRoot)
409
+ : [null, React.createElement(BrowserRoot, { key: 'root' })];
410
+ hydrateRoot(rootElForHydrate, hydrated, {
335
411
  formState: initial.formState,
336
412
  });
337
413
 
@@ -1 +1 @@
1
- {"version":3,"file":"rsc.d.ts","sourceRoot":"","sources":["../../../src/rsc/entries/rsc.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAEhD;;;GAGG;AACH,wBAAgB,mCAAmC,IAAI,MAAM,CAe5D;AAED;;;;;;;;;GASG;AACH,wBAAgB,gBAAgB,CAAC,GAAG,EAAE,YAAY,GAAG,MAAM,CAy+B1D"}
1
+ {"version":3,"file":"rsc.d.ts","sourceRoot":"","sources":["../../../src/rsc/entries/rsc.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAahD;;;GAGG;AACH,wBAAgB,mCAAmC,IAAI,MAAM,CAe5D;AAED;;;;;;;;;GASG;AACH,wBAAgB,gBAAgB,CAAC,GAAG,EAAE,YAAY,GAAG,MAAM,CAmgD1D"}