@farm.js/plugin 0.1.69 → 0.1.71

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.
package/dist/index.d.ts CHANGED
@@ -39,5 +39,5 @@
39
39
  * })
40
40
  * ```
41
41
  */
42
- export declare const version = "0.1.69";
42
+ export declare const version = "0.1.71";
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.69";
42
+ export const version = "0.1.71";
43
43
  // Note: Import plugins from their respective subpaths:
44
44
  // - @farm.js/plugin/rsc
45
45
  // - @farm.js/plugin/middleware
@@ -0,0 +1,53 @@
1
+ import type { ResolvedFarmI18nConfig } from "@farm.js/core/i18n";
2
+ import type { Connect } from "vite";
3
+ import type { HeaderConfig, RedirectConfig, RewriteConfig } from "./types.js";
4
+ /** A config `redirects`, `rewrites` or `headers` value: an array, or a function returning one. */
5
+ export type RscConfigRouteList<T> = readonly T[] | (() => readonly T[] | Promise<readonly T[]>);
6
+ export interface RscConfigRoutes {
7
+ redirects: RedirectConfig[];
8
+ rewrites: RewriteConfig[];
9
+ headers: HeaderConfig[];
10
+ }
11
+ /**
12
+ * The config `redirects()`, `rewrites()` and `headers()`, called once as core's config resolution
13
+ * calls them. `undefined` when none has an entry, so such an app generates the same entries.
14
+ */
15
+ export declare function resolveRscConfigRoutes(config: {
16
+ redirects?: RscConfigRouteList<RedirectConfig>;
17
+ rewrites?: RscConfigRouteList<RewriteConfig>;
18
+ headers?: RscConfigRouteList<HeaderConfig>;
19
+ }): Promise<RscConfigRoutes | undefined>;
20
+ type ConfigRouteMatchers = Pick<typeof import("@farm.js/core/internal/production-runtime"), "createConfigHeadersMatcher" | "createConfigRedirectMatcher" | "createConfigRewriteMatcher">;
21
+ export interface RscDevConfigRoutes {
22
+ redirect: ReturnType<ConfigRouteMatchers["createConfigRedirectMatcher"]>;
23
+ rewrite: ReturnType<ConfigRouteMatchers["createConfigRewriteMatcher"]>;
24
+ headers: ReturnType<ConfigRouteMatchers["createConfigHeadersMatcher"]>;
25
+ hasRewrites: boolean;
26
+ }
27
+ /**
28
+ * Core's matchers for the resolved config routes. Creating them checks each source and redirect
29
+ * status as core does, so `farm dev` and `farm build` fail on the same config.
30
+ */
31
+ export declare function createRscConfigRouteMatchers(routes: RscConfigRoutes, options: {
32
+ i18n: ResolvedFarmI18nConfig;
33
+ basePath: string;
34
+ }): RscDevConfigRoutes;
35
+ export interface RscConfigRoutesMiddlewareOptions {
36
+ routes: () => RscDevConfigRoutes | undefined;
37
+ root: string;
38
+ publicDir: string | false;
39
+ isApiPathname: (pathname: string) => boolean;
40
+ /** Whether the RSC entry answers the URL itself, which a config rewrite yields to. */
41
+ hasLocalRoute: (url: URL) => Promise<boolean>;
42
+ bodySizeLimit: number;
43
+ }
44
+ /**
45
+ * The config `headers()`, `redirects()` and `rewrites()` under `farm dev`, ahead of Vite, the API
46
+ * routes and the RSC entry, as core's dev server applies them: headers and redirects see the URL
47
+ * as requested, and a rewrite applies when no route answers it, once. Requests the running app
48
+ * makes for Vite's modules and files, and public files, stay Vite's (#2685). A payload request
49
+ * ('<page>.rsc') matches as its page, as in production.
50
+ */
51
+ export declare function createRscConfigRoutesMiddleware(options: RscConfigRoutesMiddlewareOptions): Connect.NextHandleFunction;
52
+ export {};
53
+ //# sourceMappingURL=config-routes.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"config-routes.d.ts","sourceRoot":"","sources":["../../src/rsc/config-routes.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,oBAAoB,CAAC;AACjE,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AAIpC,OAAO,KAAK,EAAE,YAAY,EAAE,cAAc,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AAI9E,kGAAkG;AAClG,MAAM,MAAM,kBAAkB,CAAC,CAAC,IA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AM,GAAG,KAAK,CAAC;IAC1B,aAAa,EAAE,CAAC,QAAQ,EAAE,MAAM,KAAK,OAAO,CAAC;IAC7C,sFAAsF;IACtF,aAAa,EAAE,CAAC,GAAG,EAAE,GAAG,KAAK,OAAO,CAAC,OAAO,CAAC,CAAC;IAC9C,aAAa,EAAE,MAAM,CAAC;CACvB;AAcD;;;;;;GAMG;AACH,wBAAgB,+BAA+B,CAC7C,OAAO,EAAE,gCAAgC,GACxC,OAAO,CAAC,kBAAkB,CA6F5B"}
@@ -0,0 +1,136 @@
1
+ import { createRequire } from "node:module";
2
+ import { devServableFileExists } from "../dev-static.js";
3
+ import { createDevRequestHeaders, resolveDevRequestURL } from "../dev-request.js";
4
+ import { sendRscDevelopmentResponse } from "./dev-response.js";
5
+ const require_ = createRequire(import.meta.url);
6
+ async function resolveRscConfigRouteList(value, field) {
7
+ const list = typeof value === "function" ? await value() : (value ?? []);
8
+ if (!Array.isArray(list)) {
9
+ throw new TypeError(`[Farm.js] ${field} must be an array or a function that returns one.`);
10
+ }
11
+ return [...list];
12
+ }
13
+ /**
14
+ * The config `redirects()`, `rewrites()` and `headers()`, called once as core's config resolution
15
+ * calls them. `undefined` when none has an entry, so such an app generates the same entries.
16
+ */
17
+ export async function resolveRscConfigRoutes(config) {
18
+ const [redirects, rewrites, headers] = await Promise.all([
19
+ resolveRscConfigRouteList(config.redirects, "redirects"),
20
+ resolveRscConfigRouteList(config.rewrites, "rewrites"),
21
+ resolveRscConfigRouteList(config.headers, "headers"),
22
+ ]);
23
+ if (redirects.length === 0 && rewrites.length === 0 && headers.length === 0)
24
+ return undefined;
25
+ return { redirects, rewrites, headers };
26
+ }
27
+ /**
28
+ * Core's matchers for the resolved config routes. Creating them checks each source and redirect
29
+ * status as core does, so `farm dev` and `farm build` fail on the same config.
30
+ */
31
+ export function createRscConfigRouteMatchers(routes, options) {
32
+ const { createConfigHeadersMatcher, createConfigRedirectMatcher, createConfigRewriteMatcher } = require_("@farm.js/core/internal/production-runtime");
33
+ return {
34
+ redirect: createConfigRedirectMatcher(routes.redirects, options),
35
+ rewrite: createConfigRewriteMatcher(routes.rewrites, options),
36
+ headers: createConfigHeadersMatcher(routes.headers, options),
37
+ hasRewrites: routes.rewrites.length > 0,
38
+ };
39
+ }
40
+ /** The page a '<page>.rsc' payload request is for, as the RSC entry reads it. */
41
+ function toPayloadPageUrl(url) {
42
+ const pageUrl = new URL(url);
43
+ const page = url.pathname.slice(0, -".rsc".length);
44
+ pageUrl.pathname = page.endsWith("/index") ? page.slice(0, -"index".length) : page;
45
+ return pageUrl;
46
+ }
47
+ function toPayloadPath(pathname) {
48
+ return pathname.endsWith("/") ? `${pathname}index.rsc` : `${pathname}.rsc`;
49
+ }
50
+ /**
51
+ * The config `headers()`, `redirects()` and `rewrites()` under `farm dev`, ahead of Vite, the API
52
+ * routes and the RSC entry, as core's dev server applies them: headers and redirects see the URL
53
+ * as requested, and a rewrite applies when no route answers it, once. Requests the running app
54
+ * makes for Vite's modules and files, and public files, stay Vite's (#2685). A payload request
55
+ * ('<page>.rsc') matches as its page, as in production.
56
+ */
57
+ export function createRscConfigRoutesMiddleware(options) {
58
+ let helpers;
59
+ return async (req, res, next) => {
60
+ const routes = options.routes();
61
+ if (!routes)
62
+ return next();
63
+ helpers ??= require_("@farm.js/core/vite");
64
+ let url;
65
+ try {
66
+ url = resolveDevRequestURL(req);
67
+ }
68
+ catch {
69
+ return next();
70
+ }
71
+ const method = (req.method || "GET").toUpperCase();
72
+ const rawUrl = req.url || "/";
73
+ const viteOwned = rawUrl.startsWith("/@") ||
74
+ rawUrl.startsWith("/node_modules/") ||
75
+ rawUrl.startsWith("/__farm/") ||
76
+ helpers.isViteModuleRequest(url, req.headers) ||
77
+ ((method === "GET" || method === "HEAD") &&
78
+ url.pathname.includes(".") &&
79
+ (devServableFileExists(url.pathname, [options.publicDir || undefined]) ||
80
+ (helpers.isViteDevClientRequest(url, req.headers) &&
81
+ devServableFileExists(url.pathname, [options.root]))));
82
+ if (viteOwned)
83
+ return next();
84
+ const payloadRequested = (method === "GET" || method === "HEAD") &&
85
+ url.pathname.endsWith(".rsc") &&
86
+ !options.isApiPathname(url.pathname);
87
+ const routeUrl = payloadRequested ? toPayloadPageUrl(url) : url;
88
+ try {
89
+ helpers.installConfigResponseHeaders(res, routes.headers(routeUrl));
90
+ const redirect = routes.redirect(routeUrl);
91
+ if (redirect) {
92
+ let location = redirect.destination;
93
+ if (payloadRequested) {
94
+ const target = new URL(location, url);
95
+ if (target.origin === url.origin)
96
+ location = toPayloadPath(target.pathname) + target.search;
97
+ }
98
+ await sendRscDevelopmentResponse(res, new Response(`Redirecting to ${location}`, {
99
+ status: redirect.statusCode,
100
+ headers: { Location: location },
101
+ }));
102
+ return;
103
+ }
104
+ if (routes.hasRewrites) {
105
+ const destination = routes.rewrite(routeUrl);
106
+ if (destination && !(await options.hasLocalRoute(routeUrl))) {
107
+ if (destination.origin !== url.origin) {
108
+ const { readNodeRequestBody, fetchFarmExternalRewrite } = require_("@farm.js/core/internal/production-runtime");
109
+ const body = method === "GET" || method === "HEAD"
110
+ ? undefined
111
+ : await readNodeRequestBody(req, options.bodySizeLimit);
112
+ await sendRscDevelopmentResponse(res, await fetchFarmExternalRewrite(new Request(destination, {
113
+ method,
114
+ headers: createDevRequestHeaders(req.headers),
115
+ body: body && body.length > 0 ? new Uint8Array(body) : undefined,
116
+ })));
117
+ return;
118
+ }
119
+ req.url =
120
+ (payloadRequested ? toPayloadPath(destination.pathname) : destination.pathname) +
121
+ destination.search;
122
+ }
123
+ }
124
+ }
125
+ catch (error) {
126
+ console.error("[Farm.js] Config route failed:", error);
127
+ if (!res.headersSent) {
128
+ res.statusCode = 500;
129
+ res.setHeader("Content-Type", "text/plain; charset=utf-8");
130
+ }
131
+ res.end("Internal Server Error");
132
+ return;
133
+ }
134
+ next();
135
+ };
136
+ }
@@ -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;AAIhD,eAAO,MAAM,yBAAyB,6IAK5B,CAAC;AAEX,kEAAkE;AAClE,eAAO,MAAM,yBAAyB,8DAG5B,CAAC;AAEX,eAAO,MAAM,mCAAmC,62BA6B9C,CAAC;AAEH;;;;;;;;;;GAUG;AACH,wBAAgB,mBAAmB,CAAC,GAAG,EAAE,YAAY,GAAG,MAAM,CAmkB7D"}
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;AAIhD,eAAO,MAAM,yBAAyB,6IAK5B,CAAC;AAEX,kEAAkE;AAClE,eAAO,MAAM,yBAAyB,8DAG5B,CAAC;AAEX,eAAO,MAAM,mCAAmC,62BA6B9C,CAAC;AAEH;;;;;;;;;;GAUG;AACH,wBAAgB,mBAAmB,CAAC,GAAG,EAAE,YAAY,GAAG,MAAM,CA6jB7D"}
@@ -73,7 +73,11 @@ import {
73
73
  createFarmDeploymentRequestHeaders,
74
74
  isFarmDeploymentMismatchResponse,
75
75
  } from '@farm.js/core/deployment';
76
- import { createFarmRouteAnnouncer, runFarmNavigationDelegates } from '@farm.js/core/internal/client-runtime';
76
+ import {
77
+ createFarmMetadataHeadReconciler,
78
+ createFarmRouteAnnouncer,
79
+ runFarmNavigationDelegates,
80
+ } from '@farm.js/core/internal/client-runtime';
77
81
  `;
78
82
  // <Link href="/about"> renders /console/about under basePath "/console", as the RSC server
79
83
  // rendered it, so the page hydrates with the same href.
@@ -344,6 +348,8 @@ async function main() {
344
348
 
345
349
  // The page the document loaded with is the baseline: it is never announced.
346
350
  const announceRoute = createFarmRouteAnnouncer();
351
+ // The head tags the server rendered from the page's metadata, which navigations replace.
352
+ const applyMetadataHead = createFarmMetadataHeadReconciler(initial.metadataHead ?? '');
347
353
  ${i18n
348
354
  ? ` // The locale the server rendered with, before anything hydrates (window.__FARM_I18N__).
349
355
  if (initial.i18n) _setFarmI18nClientSnapshot(initial.i18n);
@@ -364,25 +370,13 @@ ${i18n
364
370
  : "(p) => React.startTransition(() => set(p));"}
365
371
  }, []);
366
372
 
367
- // Keep document metadata in sync when an RSC navigation swaps only #root.
373
+ // Keep the document head in sync when an RSC navigation swaps only #root: the title, and the
374
+ // tags the server renders from the route's metadata (description, canonical, alternates,
375
+ // robots, Open Graph...), replaced as a page load of the route renders them.
368
376
  React.useEffect(() => {
369
- if (typeof payload.metadata?.title === 'string') {
370
- document.title = payload.metadata.title;
371
- } else {
372
- document.title = '';
373
- }
374
- let description = document.querySelector('meta[name="description"]');
375
- if (typeof payload.metadata?.description === 'string') {
376
- if (!description) {
377
- description = document.createElement('meta');
378
- description.setAttribute('name', 'description');
379
- document.head.appendChild(description);
380
- }
381
- description.setAttribute('content', payload.metadata.description);
382
- } else {
383
- description?.remove();
384
- }
385
- }, [payload.metadata?.title, payload.metadata?.description]);
377
+ document.title = typeof payload.metadata?.title === 'string' ? payload.metadata.title : '';
378
+ applyMetadataHead(payload.metadataHead ?? '');
379
+ }, [payload]);
386
380
  ${i18n
387
381
  ? `
388
382
  // A payload from back/forward or a refresh carries its locale (and, in development, edited
@@ -1,4 +1,18 @@
1
1
  import type { EntryContext } from "../types.js";
2
+ /**
3
+ * The import query the entry globs static `opengraph-image`/`twitter-image` files with. The
4
+ * plugin's loader answers it with the file's info and bytes (index.ts).
5
+ */
6
+ export declare const FARM_METADATA_IMAGE_QUERY = "?farm-metadata-image";
7
+ /**
8
+ * The config `redirects()`, `rewrites()` and `headers()` in the production server, with core's
9
+ * matchers: sources match the path below the basePath and locale, a redirect keeps the query and
10
+ * an internal destination stays below the basePath (in the request's locale under i18n), and a
11
+ * rewrite keeps the query when its destination names none. A payload request ('<page>.rsc')
12
+ * matches as its page and is sent to the destination's payload. Development gets only the check
13
+ * for a local route, which its dev server asks before a rewrite.
14
+ */
15
+ export declare function generateConfigRoutesRuntime(ctx: EntryContext, configRoutes: EntryContext["configRoutes"], localRouteCheck: boolean): string;
2
16
  /**
3
17
  * Generates the terminal middleware-result handling shared by the RSC entry
4
18
  * and its executable contract tests.
@@ -1 +1 @@
1
- {"version":3,"file":"rsc.d.ts","sourceRoot":"","sources":["../../../src/rsc/entries/rsc.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AA+HhD;;;GAGG;AACH,wBAAgB,mCAAmC,IAAI,MAAM,CAe5D;AAED;;;;;;;;;GASG;AACH,wBAAgB,gBAAgB,CAAC,GAAG,EAAE,YAAY,GAAG,MAAM,CAu4D1D"}
1
+ {"version":3,"file":"rsc.d.ts","sourceRoot":"","sources":["../../../src/rsc/entries/rsc.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAQhD;;;GAGG;AACH,eAAO,MAAM,yBAAyB,yBAAyB,CAAC;AAgKhE;;;;;;;GAOG;AACH,wBAAgB,2BAA2B,CACzC,GAAG,EAAE,YAAY,EACjB,YAAY,EAAE,YAAY,CAAC,cAAc,CAAC,EAC1C,eAAe,EAAE,OAAO,GACvB,MAAM,CAqGR;AAED;;;GAGG;AACH,wBAAgB,mCAAmC,IAAI,MAAM,CAe5D;AAED;;;;;;;;;GASG;AACH,wBAAgB,gBAAgB,CAAC,GAAG,EAAE,YAAY,GAAG,MAAM,CAo7E1D"}