@farm.js/core 0.1.63 → 0.1.65
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/{agent-mcp-handler-OV4WRFBL.cjs → agent-mcp-handler-OXT73ZBY.cjs} +5 -5
- package/dist/{agent-mcp-handler-7QMX2LUY.mjs → agent-mcp-handler-QLFDDTYN.mjs} +4 -4
- package/dist/{agent-mcp.d-CCQ-wKwg.d.mts → agent-mcp.d-CO_ABmNK.d.mts} +1 -1
- package/dist/{agent-mcp.d-DOJCBSh9.d.ts → agent-mcp.d-QD2WZ9BS.d.ts} +1 -1
- package/dist/agent-runtime.d.mts +1 -1
- package/dist/agent-runtime.d.ts +1 -1
- package/dist/analyzer-GHWK46LX.cjs +16 -0
- package/dist/{analyzer-WNPQPWFR.mjs → analyzer-PE33SK5W.mjs} +3 -2
- package/dist/api/route-manager.d.mts +3 -3
- package/dist/api/route-manager.d.ts +3 -3
- package/dist/api/runtime.d.mts +2 -2
- package/dist/api/runtime.d.ts +2 -2
- package/dist/api.d.mts +3 -3
- package/dist/api.d.ts +3 -3
- package/dist/{app-manifest.d-BaA0omsv.d.mts → app-manifest.d-BpKxiU_E.d.mts} +1 -1
- package/dist/{app-manifest.d-poayV4lq.d.ts → app-manifest.d-DDmNkYQQ.d.ts} +1 -1
- package/dist/app-markdown.cjs +4 -4
- package/dist/app-markdown.d.mts +2 -2
- package/dist/app-markdown.d.ts +2 -2
- package/dist/app-markdown.mjs +3 -3
- package/dist/{app.d-DdWxeIGU.d.mts → app.d-kuoVWhWM.d.mts} +4 -4
- package/dist/{app.d-D4Dn03E3.d.ts → app.d-x68Cwr0_.d.ts} +4 -4
- package/dist/{chunk-LT4VAF5Z.cjs → chunk-2C5L5RPM.cjs} +7 -6
- package/dist/{chunk-BA2IA32Q.mjs → chunk-2L54YV25.mjs} +13 -11
- package/dist/{chunk-5IKQ7BIR.cjs → chunk-32RPJAAS.cjs} +16 -16
- package/dist/{chunk-QN5WRQSQ.cjs → chunk-3KJPIO5D.cjs} +610 -3102
- package/dist/{chunk-EENTT56C.mjs → chunk-6X5NKNBE.mjs} +43 -38
- package/dist/{chunk-RFYL5OLP.mjs → chunk-72JSHQQQ.mjs} +1 -1
- package/dist/{chunk-LA45FN37.mjs → chunk-7GYCZRTH.mjs} +386 -2878
- package/dist/chunk-7QVRWGBL.cjs +3704 -0
- package/dist/{chunk-PRFNLQSP.cjs → chunk-7XGWBPQQ.cjs} +4 -4
- package/dist/{chunk-FNHN3RBD.cjs → chunk-A3G5IY2W.cjs} +1 -1
- package/dist/{chunk-EYLC6GD6.cjs → chunk-C7DCMGC4.cjs} +12 -12
- package/dist/chunk-CJNAUEVC.mjs +34 -0
- package/dist/{chunk-LFFSDZ4Y.cjs → chunk-CZF4XIRZ.cjs} +3 -3
- package/dist/{chunk-7FFW7DC4.mjs → chunk-E2TSYUHV.mjs} +4 -4
- package/dist/{chunk-55U5QIXQ.mjs → chunk-FIR62CR3.mjs} +1 -1
- package/dist/{chunk-MEQN6DDA.cjs → chunk-FJWN7RV4.cjs} +5 -5
- package/dist/{chunk-VVTJTMGQ.cjs → chunk-GL7N5UHF.cjs} +4 -4
- package/dist/{chunk-4DIKLG56.mjs → chunk-GRBJ7VKH.mjs} +1 -1
- package/dist/{chunk-UR25Z5Z6.mjs → chunk-HCGWDRZO.mjs} +1 -1
- package/dist/{chunk-GPKBUME5.mjs → chunk-HKNYNSOK.mjs} +2 -2
- package/dist/{chunk-U6WCUVSV.cjs → chunk-IMK32ERL.cjs} +23 -21
- package/dist/chunk-IOEXXZK3.mjs +88 -0
- package/dist/{chunk-IOF4KXMP.mjs → chunk-IP2KHSGF.mjs} +205 -26
- package/dist/{chunk-YSXTNSXS.mjs → chunk-K7OZAVOI.mjs} +7 -6
- package/dist/{chunk-KVW2M6PI.mjs → chunk-KL7SHLQB.mjs} +1 -1
- package/dist/{chunk-UZZ6IEQP.mjs → chunk-MESQF2JC.mjs} +2 -2
- package/dist/{chunk-DZPR2W6U.cjs → chunk-O6L3YYPM.cjs} +5 -5
- package/dist/{chunk-6BJJYOFL.cjs → chunk-OLIGNTWU.cjs} +7 -7
- package/dist/{chunk-5L7I6AMY.cjs → chunk-OSFIUSYK.cjs} +5 -5
- package/dist/{chunk-LA6O5EL2.mjs → chunk-Q75QPLBA.mjs} +1 -1
- package/dist/{chunk-O5FCWI6O.mjs → chunk-QHRCR44V.mjs} +2 -2
- package/dist/{chunk-E72UD6ME.mjs → chunk-RVGSVQWT.mjs} +1 -1
- package/dist/{chunk-Z74NNER4.cjs → chunk-T4M52BA5.cjs} +164 -159
- package/dist/{chunk-PCXIJKPM.mjs → chunk-TNBJ4LZG.mjs} +2 -2
- package/dist/{chunk-PAKCHVUS.mjs → chunk-TPA2PV5J.mjs} +3 -35
- package/dist/{chunk-Y2YBNQ3D.cjs → chunk-TRIDJQ6A.cjs} +6 -6
- package/dist/{chunk-PVJX4UPA.cjs → chunk-TZOGZKI7.cjs} +411 -295
- package/dist/{chunk-O27PLNQZ.cjs → chunk-UJ3R2AH2.cjs} +4 -4
- package/dist/{chunk-BPNOYILC.cjs → chunk-UVV3I5QA.cjs} +3 -35
- package/dist/{chunk-CBDRR3J3.mjs → chunk-VHHLKIDZ.mjs} +166 -50
- package/dist/{chunk-T4TBK5NY.mjs → chunk-VQ4NWOWO.mjs} +2 -2
- package/dist/{chunk-ZZ2QKCKW.mjs → chunk-WAY6LOQH.mjs} +1 -1
- package/dist/chunk-WBTHHTBO.cjs +88 -0
- package/dist/{chunk-IWRLV46X.cjs → chunk-WMTBBQHY.cjs} +4 -4
- package/dist/{chunk-LWWDTBGL.cjs → chunk-WNXVWXG3.cjs} +2 -2
- package/dist/{chunk-CI4UNQHO.cjs → chunk-XBSKPLHF.cjs} +2 -2
- package/dist/{chunk-QAS7KE7J.cjs → chunk-Y5TOT5F6.cjs} +5 -5
- package/dist/{chunk-ANXU3D32.cjs → chunk-YD4J37RN.cjs} +403 -32
- package/dist/{chunk-XICXQXYE.mjs → chunk-YUW7F6SK.mjs} +2 -2
- package/dist/chunk-ZAUOOGER.mjs +3704 -0
- package/dist/{chunk-DPE53XWL.mjs → chunk-ZEXE4TGY.mjs} +1 -1
- package/dist/chunk-ZIHWAN55.cjs +34 -0
- package/dist/{chunk-GVOMPU3Y.cjs → chunk-ZQQK4U66.cjs} +213 -34
- package/dist/{chunk-S2NUYHRY.mjs → chunk-ZX2JHEWW.mjs} +384 -13
- package/dist/{client-component.d-CSEFlHfG.d.mts → client-component.d-D74pqdea.d.mts} +2 -2
- package/dist/{client-component.d-CQLvqLAJ.d.ts → client-component.d-D8VcypQA.d.ts} +2 -2
- package/dist/{client-plugins.d-BgPUYPc9.d.ts → client-plugins.d-CXElzotB.d.ts} +8 -1
- package/dist/{client-plugins.d-BTF0gZm4.d.mts → client-plugins.d-D4-6hNx7.d.mts} +8 -1
- package/dist/client-plugins.d.mts +1 -1
- package/dist/client-plugins.d.ts +1 -1
- package/dist/client.d.mts +6 -6
- package/dist/client.d.ts +6 -6
- package/dist/config.d.mts +1 -1
- package/dist/config.d.ts +1 -1
- package/dist/desktop.d.mts +2 -2
- package/dist/desktop.d.ts +2 -2
- package/dist/{devtools-HDKTYIZF.mjs → devtools-PUVZB3F2.mjs} +7 -6
- package/dist/{devtools-ZHN5JLVI.cjs → devtools-SGYOG36E.cjs} +8 -7
- package/dist/docs.cjs +10 -9
- package/dist/docs.d.mts +2 -2
- package/dist/docs.d.ts +2 -2
- package/dist/docs.mjs +9 -8
- package/dist/environment/vite.cjs +9 -2
- package/dist/environment/vite.d.mts +3 -0
- package/dist/environment/vite.d.ts +3 -0
- package/dist/environment/vite.mjs +8 -1
- package/dist/index.cjs +29 -27
- package/dist/{index.d-Coow7bD4.d.ts → index.d-A_x10zGS.d.ts} +1 -1
- package/dist/{index.d-Dbjx0ku7.d.mts → index.d-SSgYDv4D.d.mts} +1 -1
- package/dist/index.d.mts +16 -16
- package/dist/index.d.ts +16 -16
- package/dist/index.mjs +28 -26
- package/dist/integrations.d.mts +1 -1
- package/dist/integrations.d.ts +1 -1
- package/dist/internal/app-markdown-runtime.cjs +3 -3
- package/dist/internal/app-markdown-runtime.d.mts +2 -2
- package/dist/internal/app-markdown-runtime.d.ts +2 -2
- package/dist/internal/app-markdown-runtime.mjs +2 -2
- package/dist/internal/build-runtime.cjs +27 -25
- package/dist/internal/build-runtime.d.mts +3 -3
- package/dist/internal/build-runtime.d.ts +3 -3
- package/dist/internal/build-runtime.mjs +26 -24
- package/dist/internal/cli-runtime.cjs +10 -9
- package/dist/internal/cli-runtime.mjs +9 -8
- package/dist/internal/client-error-overlay.cjs +4 -4
- package/dist/internal/client-error-overlay.mjs +1 -1
- package/dist/internal/client-runtime.d.mts +4 -4
- package/dist/internal/client-runtime.d.ts +4 -4
- package/dist/internal/compression-runtime.d.mts +1 -1
- package/dist/internal/compression-runtime.d.ts +1 -1
- package/dist/internal/config-runtime.cjs +9 -8
- package/dist/internal/config-runtime.d.mts +4 -4
- package/dist/internal/config-runtime.d.ts +4 -4
- package/dist/internal/config-runtime.mjs +8 -7
- package/dist/internal/infra-analytics-runtime.cjs +9 -9
- package/dist/internal/infra-analytics-runtime.mjs +7 -7
- package/dist/internal/native-server-fns.cjs +5 -4
- package/dist/internal/native-server-fns.mjs +4 -3
- package/dist/internal/product-telemetry-runtime.cjs +3 -3
- package/dist/internal/product-telemetry-runtime.mjs +2 -2
- package/dist/internal/production-runtime.cjs +11 -11
- package/dist/internal/production-runtime.d.mts +20 -12
- package/dist/internal/production-runtime.d.ts +20 -12
- package/dist/internal/production-runtime.mjs +10 -10
- package/dist/markdown.cjs +2 -2
- package/dist/markdown.d.mts +1 -1
- package/dist/markdown.d.ts +1 -1
- package/dist/markdown.mjs +1 -1
- package/dist/middleware.d.mts +3 -3
- package/dist/middleware.d.ts +3 -3
- package/dist/mobile.d.mts +2 -2
- package/dist/mobile.d.ts +2 -2
- package/dist/{native-tree-Z2WYUJEV.cjs → native-tree-HE2FLS72.cjs} +3 -3
- package/dist/{native-tree-AS5L3ID3.mjs → native-tree-YF2DSPKM.mjs} +2 -2
- package/dist/{navigation-delegate.d-Ca_BV0Wu.d.mts → navigation-delegate.d-DQVYKoaZ.d.mts} +1 -1
- package/dist/{navigation-delegate.d-aHiPI6GL.d.ts → navigation-delegate.d-GghbHJuK.d.ts} +1 -1
- package/dist/navigation.d.mts +4 -4
- package/dist/navigation.d.ts +4 -4
- package/dist/plugin.cjs +18 -17
- package/dist/plugin.d.mts +3 -3
- package/dist/plugin.d.ts +3 -3
- package/dist/plugin.mjs +17 -16
- package/dist/{production-runtime.d-C0rF7a10.d.ts → production-runtime.d-Bzns3NW9.d.ts} +1 -1
- package/dist/{production-runtime.d-CnAsSWgF.d.mts → production-runtime.d-DiFa5vHW.d.mts} +1 -1
- package/dist/{render-plan.d-BxeITFT1.d.ts → render-plan.d-CL_Ikfg_.d.ts} +1 -1
- package/dist/{render-plan.d-Z-93m5GZ.d.mts → render-plan.d-CcF0MeCf.d.mts} +1 -1
- package/dist/renderer-client.d.mts +4 -4
- package/dist/renderer-client.d.ts +4 -4
- package/dist/{request.d-X7Q1vmGF.d.ts → request.d-B1RnTLri.d.ts} +1 -1
- package/dist/{request.d-8_fMFNEb.d.mts → request.d-DarDOCk9.d.mts} +1 -1
- package/dist/request.d.mts +2 -2
- package/dist/request.d.ts +2 -2
- package/dist/{route-rendering.d-BUr3Jp8S.d.ts → route-rendering.d-BTUYCIj4.d.ts} +1 -1
- package/dist/{route-rendering.d-BInmBmul.d.mts → route-rendering.d-D_2Ual0-.d.mts} +1 -1
- package/dist/{router.d-crorSRiW.d.ts → router.d-CMANF6da.d.ts} +1 -1
- package/dist/{router.d-CZQmbpHx.d.mts → router.d-Cuv1jntg.d.mts} +1 -1
- package/dist/{routes.d-BknKQcTu.d.ts → routes.d-B6yFe6jm.d.ts} +1 -1
- package/dist/{routes.d-D1IrO9KK.d.mts → routes.d-c2HKfrfL.d.mts} +1 -1
- package/dist/routes.d.mts +1 -1
- package/dist/routes.d.ts +1 -1
- package/dist/{rsc-pipeline-3MPRULGA.mjs → rsc-pipeline-T3PWURLJ.mjs} +9 -8
- package/dist/{rsc-pipeline-RHEZNBFQ.cjs → rsc-pipeline-V4ANLRAA.cjs} +10 -9
- package/dist/{runtime-OZKFZQCU.cjs → runtime-5AROV2C3.cjs} +29 -17
- package/dist/{runtime-X5UR7VHP.mjs → runtime-LRIQ3XH7.mjs} +26 -14
- package/dist/{runtime.d-CCsjTZJW.d.ts → runtime.d-C3RQUj6_.d.ts} +1 -1
- package/dist/{runtime.d-CETtpLb-.d.mts → runtime.d-wvh4ngU0.d.mts} +1 -1
- package/dist/server-plugins.d.mts +2 -2
- package/dist/server-plugins.d.ts +2 -2
- package/dist/server.cjs +42 -41
- package/dist/server.d.mts +9 -9
- package/dist/server.d.ts +9 -9
- package/dist/server.mjs +26 -25
- package/dist/{spa-router.d-CtSHzXlC.d.mts → spa-router.d-WU_qS5gJ.d.mts} +2 -2
- package/dist/{spa-router.d-CCADbSqJ.d.ts → spa-router.d-m8H_Kl_B.d.ts} +2 -2
- package/dist/testing.d.mts +1 -1
- package/dist/testing.d.ts +1 -1
- package/dist/{utils.d-CjyE-npA.d.ts → utils.d-C9dQD5Zg.d.ts} +1 -1
- package/dist/{utils.d-zFPHKFFJ.d.mts → utils.d-W9IiEqmW.d.mts} +1 -1
- package/dist/version.cjs +2 -2
- package/dist/version.mjs +1 -1
- package/dist/vite.cjs +21 -19
- package/dist/vite.d.mts +4 -4
- package/dist/vite.d.ts +4 -4
- package/dist/vite.mjs +20 -18
- package/package.json +1 -1
- package/dist/analyzer-KEA5JVDR.cjs +0 -15
- package/dist/chunk-NK2VWS7P.cjs +0 -954
- package/dist/chunk-ZQ5BDNKW.mjs +0 -954
|
@@ -0,0 +1,3704 @@
|
|
|
1
|
+
import {
|
|
2
|
+
isFarmIslandStrategy
|
|
3
|
+
} from "./chunk-S32PDOLO.mjs";
|
|
4
|
+
import {
|
|
5
|
+
getFarmProjectSourceDir,
|
|
6
|
+
resolveFarmServerComponentsMode
|
|
7
|
+
} from "./chunk-CJNAUEVC.mjs";
|
|
8
|
+
import {
|
|
9
|
+
getFarmSourceRoots
|
|
10
|
+
} from "./chunk-52Y3C3HG.mjs";
|
|
11
|
+
import {
|
|
12
|
+
isReactRenderer
|
|
13
|
+
} from "./chunk-ES2LD2YD.mjs";
|
|
14
|
+
import {
|
|
15
|
+
PROGRAMMATIC_ROUTE_FILE_NAMES,
|
|
16
|
+
getProgrammaticRouteDefinitionSource,
|
|
17
|
+
parseProgrammaticRouteModuleId
|
|
18
|
+
} from "./chunk-6YFC3ZFX.mjs";
|
|
19
|
+
import {
|
|
20
|
+
logger
|
|
21
|
+
} from "./chunk-JSDV2NUN.mjs";
|
|
22
|
+
import {
|
|
23
|
+
FARM_VERSION
|
|
24
|
+
} from "./chunk-72JSHQQQ.mjs";
|
|
25
|
+
|
|
26
|
+
// src/environment-vite.ts
|
|
27
|
+
import { realpathSync } from "fs";
|
|
28
|
+
import path5 from "path";
|
|
29
|
+
|
|
30
|
+
// src/islands-react-server-exports.ts
|
|
31
|
+
import fs from "fs";
|
|
32
|
+
import path from "path";
|
|
33
|
+
import { parseAst } from "rolldown/parseAst";
|
|
34
|
+
var REACT_PACKAGES = /* @__PURE__ */ new Set([
|
|
35
|
+
"react",
|
|
36
|
+
"react-dom",
|
|
37
|
+
"scheduler",
|
|
38
|
+
"react-server-dom-webpack",
|
|
39
|
+
"react-server-dom-esm",
|
|
40
|
+
"react-server-dom-turbopack"
|
|
41
|
+
]);
|
|
42
|
+
var CLIENT_ONLY_PACKAGE = "client-only";
|
|
43
|
+
var SERVER_CONDITIONS = ["react-server", "node", "import", "module", "default"];
|
|
44
|
+
var DEFAULT_CONDITIONS = ["node", "import", "module", "default"];
|
|
45
|
+
var SCRIPT_EXTENSIONS = ["", ".js", ".mjs", ".cjs", ".jsx", ".ts", ".tsx", ".mts"];
|
|
46
|
+
var INDEX_FILES = ["index.js", "index.mjs", "index.cjs", "index.ts", "index.tsx"];
|
|
47
|
+
function packageNameOf(specifier) {
|
|
48
|
+
if (specifier.startsWith(".") || specifier.startsWith("/") || specifier.startsWith("#") || specifier.includes(":") || specifier.includes("\0")) {
|
|
49
|
+
return null;
|
|
50
|
+
}
|
|
51
|
+
const parts = specifier.split("/");
|
|
52
|
+
const name = specifier.startsWith("@") ? parts.slice(0, 2).join("/") : parts[0];
|
|
53
|
+
if (!name || specifier.startsWith("@") && parts.length < 2) return null;
|
|
54
|
+
return { name, subpath: parts.slice(name.startsWith("@") ? 2 : 1).join("/") };
|
|
55
|
+
}
|
|
56
|
+
function findPackageDirectory(importer, name) {
|
|
57
|
+
for (let current = path.dirname(importer); ; current = path.dirname(current)) {
|
|
58
|
+
const directory = path.join(current, "node_modules", name);
|
|
59
|
+
if (fs.existsSync(path.join(directory, "package.json"))) return fs.realpathSync(directory);
|
|
60
|
+
if (path.dirname(current) === current) return null;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
function pickTarget(value, conditions) {
|
|
64
|
+
if (typeof value === "string") return value;
|
|
65
|
+
if (Array.isArray(value)) {
|
|
66
|
+
for (const entry of value) {
|
|
67
|
+
const target = pickTarget(entry, conditions);
|
|
68
|
+
if (target) return target;
|
|
69
|
+
}
|
|
70
|
+
return null;
|
|
71
|
+
}
|
|
72
|
+
if (!value || typeof value !== "object") return null;
|
|
73
|
+
for (const [key, entry] of Object.entries(value)) {
|
|
74
|
+
if (key === "types" || !conditions.includes(key)) continue;
|
|
75
|
+
const target = pickTarget(entry, conditions);
|
|
76
|
+
if (target) return target;
|
|
77
|
+
}
|
|
78
|
+
return null;
|
|
79
|
+
}
|
|
80
|
+
function exportEntry(exportsField, subpath) {
|
|
81
|
+
const key = subpath ? `./${subpath}` : ".";
|
|
82
|
+
if (typeof exportsField === "string" || Array.isArray(exportsField)) {
|
|
83
|
+
return key === "." ? exportsField : void 0;
|
|
84
|
+
}
|
|
85
|
+
if (!exportsField || typeof exportsField !== "object") return void 0;
|
|
86
|
+
const entries = exportsField;
|
|
87
|
+
if (!Object.keys(entries).some((entry) => entry.startsWith("."))) {
|
|
88
|
+
return key === "." ? entries : void 0;
|
|
89
|
+
}
|
|
90
|
+
if (entries[key] !== void 0) return entries[key];
|
|
91
|
+
for (const [pattern, value] of Object.entries(entries)) {
|
|
92
|
+
const star = pattern.indexOf("*");
|
|
93
|
+
if (star === -1) continue;
|
|
94
|
+
const prefix = pattern.slice(0, star);
|
|
95
|
+
const suffix = pattern.slice(star + 1);
|
|
96
|
+
if (key.startsWith(prefix) && key.endsWith(suffix)) {
|
|
97
|
+
const match = key.slice(prefix.length, key.length - suffix.length);
|
|
98
|
+
const replace = (target) => typeof target === "string" ? target.replace("*", match) : target && typeof target === "object" && !Array.isArray(target) ? Object.fromEntries(
|
|
99
|
+
Object.entries(target).map(([k, v]) => [k, replace(v)])
|
|
100
|
+
) : target;
|
|
101
|
+
return replace(value);
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
return void 0;
|
|
105
|
+
}
|
|
106
|
+
var cache = /* @__PURE__ */ new Map();
|
|
107
|
+
function resolveFarmReactServerExport(importer, specifier) {
|
|
108
|
+
const parsed = packageNameOf(specifier);
|
|
109
|
+
if (!parsed || REACT_PACKAGES.has(parsed.name) || parsed.name.startsWith("@farm.js/"))
|
|
110
|
+
return null;
|
|
111
|
+
const directory = findPackageDirectory(importer, parsed.name);
|
|
112
|
+
if (!directory) return null;
|
|
113
|
+
const key = `${directory}\0${parsed.subpath}`;
|
|
114
|
+
if (cache.has(key)) return cache.get(key);
|
|
115
|
+
let resolved = null;
|
|
116
|
+
try {
|
|
117
|
+
const manifest = JSON.parse(fs.readFileSync(path.join(directory, "package.json"), "utf8"));
|
|
118
|
+
const entry = exportEntry(manifest.exports, parsed.subpath);
|
|
119
|
+
const server = pickTarget(entry, SERVER_CONDITIONS);
|
|
120
|
+
const fallback = pickTarget(entry, DEFAULT_CONDITIONS);
|
|
121
|
+
if (server && server !== fallback && server.startsWith("./")) {
|
|
122
|
+
const file = path.resolve(directory, server);
|
|
123
|
+
if (fs.existsSync(file)) resolved = file;
|
|
124
|
+
}
|
|
125
|
+
} catch {
|
|
126
|
+
resolved = null;
|
|
127
|
+
}
|
|
128
|
+
cache.set(key, resolved);
|
|
129
|
+
return resolved;
|
|
130
|
+
}
|
|
131
|
+
var parsedModules = /* @__PURE__ */ new Map();
|
|
132
|
+
function readModule(file) {
|
|
133
|
+
let stat;
|
|
134
|
+
try {
|
|
135
|
+
stat = fs.statSync(file);
|
|
136
|
+
} catch {
|
|
137
|
+
return null;
|
|
138
|
+
}
|
|
139
|
+
const cached = parsedModules.get(file);
|
|
140
|
+
if (cached && cached.size === stat.size && cached.mtimeMs === stat.mtimeMs) return cached.program;
|
|
141
|
+
let program = null;
|
|
142
|
+
try {
|
|
143
|
+
const code = fs.readFileSync(file, "utf8");
|
|
144
|
+
const extension = path.extname(file).slice(1);
|
|
145
|
+
const lang = extension === "ts" || extension === "mts" || extension === "cts" ? "ts" : "tsx";
|
|
146
|
+
program = parseAst(code, { lang });
|
|
147
|
+
} catch {
|
|
148
|
+
program = null;
|
|
149
|
+
}
|
|
150
|
+
parsedModules.set(file, { size: stat.size, mtimeMs: stat.mtimeMs, program });
|
|
151
|
+
return program;
|
|
152
|
+
}
|
|
153
|
+
function isClientModule(program) {
|
|
154
|
+
for (const node of program.body ?? []) {
|
|
155
|
+
if (node.type !== "ExpressionStatement" || typeof node.directive !== "string") break;
|
|
156
|
+
if (node.directive === "use client") return true;
|
|
157
|
+
}
|
|
158
|
+
return false;
|
|
159
|
+
}
|
|
160
|
+
function resolveRelative(from, specifier) {
|
|
161
|
+
const base = path.resolve(path.dirname(from), specifier);
|
|
162
|
+
for (const extension of SCRIPT_EXTENSIONS) {
|
|
163
|
+
const file = `${base}${extension}`;
|
|
164
|
+
if (fs.existsSync(file) && fs.statSync(file).isFile()) return file;
|
|
165
|
+
}
|
|
166
|
+
for (const index of INDEX_FILES) {
|
|
167
|
+
const file = path.join(base, index);
|
|
168
|
+
if (fs.existsSync(file)) return file;
|
|
169
|
+
}
|
|
170
|
+
return null;
|
|
171
|
+
}
|
|
172
|
+
function exportedName(node) {
|
|
173
|
+
return node?.type === "Identifier" ? node.name : node?.value;
|
|
174
|
+
}
|
|
175
|
+
function resolveFarmPackageDefaultEntry(importer, specifier, conditions = ["browser", ...DEFAULT_CONDITIONS]) {
|
|
176
|
+
const parsed = packageNameOf(specifier);
|
|
177
|
+
if (!parsed) return null;
|
|
178
|
+
const directory = findPackageDirectory(importer, parsed.name);
|
|
179
|
+
if (!directory) return null;
|
|
180
|
+
try {
|
|
181
|
+
const manifest = JSON.parse(fs.readFileSync(path.join(directory, "package.json"), "utf8"));
|
|
182
|
+
const target = pickTarget(exportEntry(manifest.exports, parsed.subpath), conditions) ?? (!parsed.subpath ? manifest.module ?? manifest.main ?? "index.js" : parsed.subpath);
|
|
183
|
+
return resolveRelative(
|
|
184
|
+
path.join(directory, "package.json"),
|
|
185
|
+
`./${String(target).replace(/^\.\//, "")}`
|
|
186
|
+
);
|
|
187
|
+
} catch {
|
|
188
|
+
return null;
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
function resolveSource(file, source) {
|
|
192
|
+
if (source.startsWith(".")) return resolveRelative(file, source);
|
|
193
|
+
return resolveFarmPackageDefaultEntry(file, source);
|
|
194
|
+
}
|
|
195
|
+
function traceFarmExport(file, name, depth = 0) {
|
|
196
|
+
if (depth > 8) return void 0;
|
|
197
|
+
const program = readModule(file);
|
|
198
|
+
if (!program) return void 0;
|
|
199
|
+
if (isClientModule(program)) return "client";
|
|
200
|
+
const follow = (source, imported) => {
|
|
201
|
+
const target = resolveSource(file, source);
|
|
202
|
+
return target ? traceFarmExport(target, imported, depth + 1) : void 0;
|
|
203
|
+
};
|
|
204
|
+
const imports = /* @__PURE__ */ new Map();
|
|
205
|
+
for (const node of program.body ?? []) {
|
|
206
|
+
if (node.type !== "ImportDeclaration" || typeof node.source?.value !== "string") continue;
|
|
207
|
+
for (const specifier of node.specifiers ?? []) {
|
|
208
|
+
if (specifier.type === "ImportNamespaceSpecifier") continue;
|
|
209
|
+
const imported = specifier.type === "ImportDefaultSpecifier" ? "default" : exportedName(specifier.imported) ?? specifier.local.name;
|
|
210
|
+
imports.set(specifier.local.name, { source: node.source.value, imported });
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
const local = (localName) => {
|
|
214
|
+
const binding = imports.get(localName);
|
|
215
|
+
return binding ? follow(binding.source, binding.imported) : "server";
|
|
216
|
+
};
|
|
217
|
+
const stars = [];
|
|
218
|
+
for (const node of program.body ?? []) {
|
|
219
|
+
if (node.type === "ExportNamedDeclaration" && node.source) {
|
|
220
|
+
for (const specifier of node.specifiers ?? []) {
|
|
221
|
+
if (exportedName(specifier.exported) !== name) continue;
|
|
222
|
+
return follow(node.source.value, exportedName(specifier.local) ?? name);
|
|
223
|
+
}
|
|
224
|
+
} else if (node.type === "ExportAllDeclaration" && node.source && !node.exported) {
|
|
225
|
+
stars.push(node.source.value);
|
|
226
|
+
} else if (node.type === "ExportNamedDeclaration" && !node.source) {
|
|
227
|
+
for (const specifier of node.specifiers ?? []) {
|
|
228
|
+
if (exportedName(specifier.exported) === name) {
|
|
229
|
+
return local(exportedName(specifier.local) ?? name);
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
const declared = [
|
|
233
|
+
...node.declaration?.id ? [node.declaration.id.name] : [],
|
|
234
|
+
...(node.declaration?.declarations ?? []).map((declarator) => declarator.id?.name)
|
|
235
|
+
];
|
|
236
|
+
if (declared.includes(name)) return "server";
|
|
237
|
+
} else if (node.type === "ExportDefaultDeclaration" && name === "default") {
|
|
238
|
+
return node.declaration?.type === "Identifier" ? local(node.declaration.name) : "server";
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
for (const source of stars) {
|
|
242
|
+
const traced = follow(source, name);
|
|
243
|
+
if (traced) return traced;
|
|
244
|
+
}
|
|
245
|
+
return void 0;
|
|
246
|
+
}
|
|
247
|
+
function isFarmClientExport(file, name) {
|
|
248
|
+
return traceFarmExport(file, name) === "client";
|
|
249
|
+
}
|
|
250
|
+
function isFarmPackageClientExport(importer, specifier, name) {
|
|
251
|
+
const entry = resolveFarmPackageDefaultEntry(importer, specifier);
|
|
252
|
+
return !entry || traceFarmExport(entry, name) !== "server";
|
|
253
|
+
}
|
|
254
|
+
function parseCode(code, file) {
|
|
255
|
+
const extension = path.extname(file).slice(1);
|
|
256
|
+
const lang = extension === "ts" || extension === "mts" || extension === "cts" ? "ts" : "tsx";
|
|
257
|
+
try {
|
|
258
|
+
return parseAst(code, { lang });
|
|
259
|
+
} catch {
|
|
260
|
+
return null;
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
function namespaceMembers(program, local) {
|
|
264
|
+
const members = /* @__PURE__ */ new Set();
|
|
265
|
+
let opaque = false;
|
|
266
|
+
const visit = (node, parent) => {
|
|
267
|
+
if (opaque || !node || typeof node !== "object") return;
|
|
268
|
+
if (Array.isArray(node)) {
|
|
269
|
+
for (const child of node) visit(child, parent);
|
|
270
|
+
return;
|
|
271
|
+
}
|
|
272
|
+
const current = node;
|
|
273
|
+
if (typeof current.type !== "string") return;
|
|
274
|
+
if ((current.type === "Identifier" || current.type === "JSXIdentifier") && current.name === local && parent?.type !== "ImportNamespaceSpecifier") {
|
|
275
|
+
const property = (parent?.type === "MemberExpression" || parent?.type === "JSXMemberExpression") && parent.object === current && !parent.computed ? parent.property?.name : void 0;
|
|
276
|
+
if (property) members.add(property);
|
|
277
|
+
else opaque = true;
|
|
278
|
+
return;
|
|
279
|
+
}
|
|
280
|
+
for (const [key, value] of Object.entries(current)) {
|
|
281
|
+
if (key === "start" || key === "end" || key === "loc" || key === "range") continue;
|
|
282
|
+
if (value && typeof value === "object") visit(value, current);
|
|
283
|
+
}
|
|
284
|
+
};
|
|
285
|
+
visit(program, null);
|
|
286
|
+
return opaque ? null : [...members];
|
|
287
|
+
}
|
|
288
|
+
function findPackageImports(program, accept) {
|
|
289
|
+
const found = [];
|
|
290
|
+
for (const node of program.body ?? []) {
|
|
291
|
+
if (node.type !== "ImportDeclaration" || node.importKind === "type") continue;
|
|
292
|
+
const specifier = node.source?.value;
|
|
293
|
+
if (typeof specifier !== "string" || !accept(specifier)) continue;
|
|
294
|
+
const specifiers = (node.specifiers ?? []).filter(
|
|
295
|
+
(entry2) => entry2.importKind !== "type"
|
|
296
|
+
);
|
|
297
|
+
if ((node.specifiers ?? []).length > 0 && specifiers.length === 0) continue;
|
|
298
|
+
const entry = {
|
|
299
|
+
start: node.start,
|
|
300
|
+
end: node.end,
|
|
301
|
+
specifier,
|
|
302
|
+
sideEffect: specifiers.length === 0,
|
|
303
|
+
named: []
|
|
304
|
+
};
|
|
305
|
+
for (const binding of specifiers) {
|
|
306
|
+
if (binding.type === "ImportDefaultSpecifier") entry.defaultLocal = binding.local.name;
|
|
307
|
+
else if (binding.type === "ImportNamespaceSpecifier") {
|
|
308
|
+
entry.namespace = {
|
|
309
|
+
local: binding.local.name,
|
|
310
|
+
members: namespaceMembers(program, binding.local.name)
|
|
311
|
+
};
|
|
312
|
+
} else {
|
|
313
|
+
const imported = exportedName(binding.imported);
|
|
314
|
+
if (imported) entry.named.push({ imported, local: binding.local.name });
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
found.push(entry);
|
|
318
|
+
}
|
|
319
|
+
return found;
|
|
320
|
+
}
|
|
321
|
+
function findFarmReactServerClientNames(code, file, specifier) {
|
|
322
|
+
const target = resolveFarmReactServerExport(file, specifier);
|
|
323
|
+
if (!target) return null;
|
|
324
|
+
const program = parseCode(code, file);
|
|
325
|
+
if (!program) return null;
|
|
326
|
+
const names = /* @__PURE__ */ new Set();
|
|
327
|
+
for (const entry of findPackageImports(program, (candidate) => candidate === specifier)) {
|
|
328
|
+
const wanted = [
|
|
329
|
+
...entry.defaultLocal ? ["default"] : [],
|
|
330
|
+
...entry.named.map((binding) => binding.imported),
|
|
331
|
+
...entry.namespace?.members ?? []
|
|
332
|
+
];
|
|
333
|
+
for (const name of wanted) if (isFarmClientExport(target, name)) names.add(name);
|
|
334
|
+
}
|
|
335
|
+
return [...names];
|
|
336
|
+
}
|
|
337
|
+
function rewriteFarmReactServerImports(options) {
|
|
338
|
+
if (!options.code.includes("import")) return null;
|
|
339
|
+
const program = parseCode(options.code, options.file);
|
|
340
|
+
if (!program) return null;
|
|
341
|
+
const targets = /* @__PURE__ */ new Map();
|
|
342
|
+
const imports = findPackageImports(program, (specifier) => {
|
|
343
|
+
const target = resolveFarmReactServerExport(options.file, specifier);
|
|
344
|
+
if (target) targets.set(specifier, target);
|
|
345
|
+
return target !== null;
|
|
346
|
+
});
|
|
347
|
+
if (imports.length === 0) return null;
|
|
348
|
+
let output = options.code;
|
|
349
|
+
let next = 0;
|
|
350
|
+
for (const entry of [...imports].sort((left, right) => right.start - left.start)) {
|
|
351
|
+
const target = targets.get(entry.specifier);
|
|
352
|
+
options.onServerFile?.(target);
|
|
353
|
+
const server = JSON.stringify(target);
|
|
354
|
+
const lines = [];
|
|
355
|
+
const bind = (name, local) => {
|
|
356
|
+
if (isFarmClientExport(target, name)) {
|
|
357
|
+
lines.push(
|
|
358
|
+
`import { ${name} as ${local} } from ${JSON.stringify(options.reference(entry.specifier, name))};`
|
|
359
|
+
);
|
|
360
|
+
} else lines.push(`import { ${name} as ${local} } from ${server};`);
|
|
361
|
+
};
|
|
362
|
+
if (entry.sideEffect) lines.push(`import ${server};`);
|
|
363
|
+
if (entry.defaultLocal) bind("default", entry.defaultLocal);
|
|
364
|
+
for (const binding of entry.named) bind(binding.imported, binding.local);
|
|
365
|
+
if (entry.namespace) {
|
|
366
|
+
if (entry.namespace.members === null) {
|
|
367
|
+
lines.push(`import * as ${entry.namespace.local} from ${server};`);
|
|
368
|
+
} else {
|
|
369
|
+
const fields = [];
|
|
370
|
+
for (const member of entry.namespace.members) {
|
|
371
|
+
const local = `__farm_react_server_${next++}__`;
|
|
372
|
+
bind(member, local);
|
|
373
|
+
fields.push(`${member}: ${local}`);
|
|
374
|
+
}
|
|
375
|
+
lines.push(`const ${entry.namespace.local} = Object.freeze({ ${fields.join(", ")} });`);
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
output = output.slice(0, entry.start) + lines.join("\n") + output.slice(entry.end);
|
|
379
|
+
}
|
|
380
|
+
return output;
|
|
381
|
+
}
|
|
382
|
+
function staticImportSources(program) {
|
|
383
|
+
const sources = [];
|
|
384
|
+
for (const node of program.body ?? []) {
|
|
385
|
+
if (node.type !== "ImportDeclaration" && node.type !== "ExportAllDeclaration" && !(node.type === "ExportNamedDeclaration" && node.source)) {
|
|
386
|
+
continue;
|
|
387
|
+
}
|
|
388
|
+
if (node.importKind === "type" || node.exportKind === "type") continue;
|
|
389
|
+
if (typeof node.source?.value === "string") sources.push(node.source.value);
|
|
390
|
+
}
|
|
391
|
+
return sources;
|
|
392
|
+
}
|
|
393
|
+
var clientOnlyFreeFiles = /* @__PURE__ */ new Set();
|
|
394
|
+
function invalidateFarmClientOnlyScan() {
|
|
395
|
+
clientOnlyFreeFiles.clear();
|
|
396
|
+
}
|
|
397
|
+
function resolveServerEntry(importer, specifier) {
|
|
398
|
+
const parsed = packageNameOf(specifier);
|
|
399
|
+
if (!parsed || REACT_PACKAGES.has(parsed.name) || parsed.name.startsWith("@farm.js/")) {
|
|
400
|
+
return null;
|
|
401
|
+
}
|
|
402
|
+
return resolveFarmReactServerExport(importer, specifier) ?? resolveFarmPackageDefaultEntry(importer, specifier, DEFAULT_CONDITIONS);
|
|
403
|
+
}
|
|
404
|
+
function walkToClientOnly(file, seen) {
|
|
405
|
+
if (seen.has(file) || clientOnlyFreeFiles.has(file)) return null;
|
|
406
|
+
seen.add(file);
|
|
407
|
+
const program = readModule(file);
|
|
408
|
+
if (!program || isClientModule(program)) return null;
|
|
409
|
+
for (const source of staticImportSources(program)) {
|
|
410
|
+
if (source === CLIENT_ONLY_PACKAGE) return [file];
|
|
411
|
+
const child = source.startsWith(".") ? resolveRelative(file, source) : resolveServerEntry(file, source);
|
|
412
|
+
const chain = child && walkToClientOnly(child, seen);
|
|
413
|
+
if (chain) return [file, ...chain];
|
|
414
|
+
}
|
|
415
|
+
return null;
|
|
416
|
+
}
|
|
417
|
+
function findFarmClientOnlyImport(code, file) {
|
|
418
|
+
if (!code.includes("import") && !code.includes("export")) return null;
|
|
419
|
+
const program = parseCode(code, file);
|
|
420
|
+
if (!program) return null;
|
|
421
|
+
for (const specifier of staticImportSources(program)) {
|
|
422
|
+
const entry = resolveServerEntry(file, specifier);
|
|
423
|
+
if (!entry) continue;
|
|
424
|
+
const seen = /* @__PURE__ */ new Set();
|
|
425
|
+
const chain = walkToClientOnly(entry, seen);
|
|
426
|
+
if (chain) return { specifier, chain };
|
|
427
|
+
for (const walked of seen) clientOnlyFreeFiles.add(walked);
|
|
428
|
+
}
|
|
429
|
+
return null;
|
|
430
|
+
}
|
|
431
|
+
function farmRelativeImportFiles(code, file) {
|
|
432
|
+
const program = parseCode(code, file);
|
|
433
|
+
if (!program) return [];
|
|
434
|
+
const files = [];
|
|
435
|
+
for (const node of program.body ?? []) {
|
|
436
|
+
const source = (node.type === "ImportDeclaration" || node.type === "ExportAllDeclaration" || node.type === "ExportNamedDeclaration" && node.source) && node.source?.value;
|
|
437
|
+
if (typeof source !== "string" || !source.startsWith(".")) continue;
|
|
438
|
+
const resolved = resolveRelative(file, source);
|
|
439
|
+
if (resolved) files.push(resolved);
|
|
440
|
+
}
|
|
441
|
+
return files;
|
|
442
|
+
}
|
|
443
|
+
function farmReactServerBuildReachesClientModules(importer, specifier, serverImported = false) {
|
|
444
|
+
const target = resolveFarmReactServerExport(importer, specifier) ?? (serverImported ? resolveFarmPackageDefaultEntry(importer, specifier) : null);
|
|
445
|
+
if (!target) return false;
|
|
446
|
+
const seen = /* @__PURE__ */ new Set();
|
|
447
|
+
const reaches = (file, depth) => {
|
|
448
|
+
if (depth > 6 || seen.has(file)) return false;
|
|
449
|
+
seen.add(file);
|
|
450
|
+
const program = readModule(file);
|
|
451
|
+
if (!program) return false;
|
|
452
|
+
if (depth > 0 && isClientModule(program)) return true;
|
|
453
|
+
for (const node of program.body ?? []) {
|
|
454
|
+
const source = (node.type === "ExportAllDeclaration" || node.type === "ExportNamedDeclaration" && node.source || node.type === "ImportDeclaration") && node.source?.value;
|
|
455
|
+
if (typeof source !== "string" || !source.startsWith(".")) continue;
|
|
456
|
+
const child = resolveRelative(file, source);
|
|
457
|
+
if (child && reaches(child, depth + 1)) return true;
|
|
458
|
+
}
|
|
459
|
+
return false;
|
|
460
|
+
};
|
|
461
|
+
return reaches(target, 0);
|
|
462
|
+
}
|
|
463
|
+
var IMPORT_SPECIFIER = /(?:\bfrom\s*|\bimport\s*\(?\s*)["']([^"'./][^"']*)["']/g;
|
|
464
|
+
var STYLESHEET_IMPORT = /(?:\bfrom\s*|\bimport\s*\(?\s*|\brequire\s*\(\s*)["'][^"']+\.(?:css|scss|sass|less|styl)["']/;
|
|
465
|
+
var MAX_SCANNED_FILES = 2e3;
|
|
466
|
+
var packageScans = /* @__PURE__ */ new Map();
|
|
467
|
+
function scanPackage(directory) {
|
|
468
|
+
const cached = packageScans.get(directory);
|
|
469
|
+
if (cached) return cached;
|
|
470
|
+
const scan = { imports: /* @__PURE__ */ new Set(), stylesheets: false };
|
|
471
|
+
const pending = [directory];
|
|
472
|
+
let scanned = 0;
|
|
473
|
+
while (pending.length > 0 && scanned < MAX_SCANNED_FILES) {
|
|
474
|
+
const current = pending.pop();
|
|
475
|
+
let entries;
|
|
476
|
+
try {
|
|
477
|
+
entries = fs.readdirSync(current, { withFileTypes: true });
|
|
478
|
+
} catch {
|
|
479
|
+
continue;
|
|
480
|
+
}
|
|
481
|
+
for (const entry of entries) {
|
|
482
|
+
if (entry.name === "node_modules" || entry.name.startsWith(".")) continue;
|
|
483
|
+
const file = path.join(current, entry.name);
|
|
484
|
+
if (entry.isDirectory()) pending.push(file);
|
|
485
|
+
else if (/\.(?:[cm]?js|jsx)$/.test(entry.name) && scanned++ < MAX_SCANNED_FILES) {
|
|
486
|
+
let code;
|
|
487
|
+
try {
|
|
488
|
+
code = fs.readFileSync(file, "utf8");
|
|
489
|
+
} catch {
|
|
490
|
+
continue;
|
|
491
|
+
}
|
|
492
|
+
for (const match of code.matchAll(IMPORT_SPECIFIER)) scan.imports.add(match[1]);
|
|
493
|
+
if (!scan.stylesheets && STYLESHEET_IMPORT.test(code)) scan.stylesheets = true;
|
|
494
|
+
}
|
|
495
|
+
}
|
|
496
|
+
}
|
|
497
|
+
packageScans.set(directory, scan);
|
|
498
|
+
return scan;
|
|
499
|
+
}
|
|
500
|
+
function findFarmServerBundledPackage(importer, specifier) {
|
|
501
|
+
const parsed = packageNameOf(specifier);
|
|
502
|
+
if (!parsed || REACT_PACKAGES.has(parsed.name) || parsed.name.startsWith("@farm.js/")) {
|
|
503
|
+
return null;
|
|
504
|
+
}
|
|
505
|
+
const directory = findPackageDirectory(importer, parsed.name);
|
|
506
|
+
if (!directory) return null;
|
|
507
|
+
try {
|
|
508
|
+
const manifest = JSON.parse(fs.readFileSync(path.join(directory, "package.json"), "utf8"));
|
|
509
|
+
if (manifest.exports === void 0 && manifest.type !== "module" && typeof manifest.module === "string" && typeof manifest.main === "string" && path.resolve(directory, manifest.main) !== path.resolve(directory, manifest.module)) {
|
|
510
|
+
return parsed.name;
|
|
511
|
+
}
|
|
512
|
+
} catch {
|
|
513
|
+
return null;
|
|
514
|
+
}
|
|
515
|
+
return scanPackage(directory).stylesheets ? parsed.name : null;
|
|
516
|
+
}
|
|
517
|
+
function findFarmPackageManifest(importer, specifier) {
|
|
518
|
+
const parsed = packageNameOf(specifier);
|
|
519
|
+
if (!parsed) return null;
|
|
520
|
+
const directory = findPackageDirectory(importer, parsed.name);
|
|
521
|
+
if (!directory) return null;
|
|
522
|
+
let names;
|
|
523
|
+
try {
|
|
524
|
+
const manifest = JSON.parse(fs.readFileSync(path.join(directory, "package.json"), "utf8"));
|
|
525
|
+
names = new Set(Object.keys(manifest.dependencies ?? {}));
|
|
526
|
+
} catch {
|
|
527
|
+
return null;
|
|
528
|
+
}
|
|
529
|
+
const dependencies = [...scanPackage(directory).imports].filter((imported) => {
|
|
530
|
+
const name = packageNameOf(imported)?.name;
|
|
531
|
+
return name !== void 0 && names.has(name);
|
|
532
|
+
});
|
|
533
|
+
return { name: parsed.name, dependencies: dependencies.sort() };
|
|
534
|
+
}
|
|
535
|
+
function listFarmPackageExports(importer, specifier) {
|
|
536
|
+
const entry = resolveFarmPackageDefaultEntry(importer, specifier);
|
|
537
|
+
if (!entry) return null;
|
|
538
|
+
const names = /* @__PURE__ */ new Set();
|
|
539
|
+
const seen = /* @__PURE__ */ new Set();
|
|
540
|
+
const collect = (file, depth) => {
|
|
541
|
+
if (depth > 8 || seen.has(file)) return true;
|
|
542
|
+
seen.add(file);
|
|
543
|
+
const program = readModule(file);
|
|
544
|
+
if (!program) return false;
|
|
545
|
+
let esm = false;
|
|
546
|
+
for (const node of program.body ?? []) {
|
|
547
|
+
if (node.type === "ExportAllDeclaration" && node.source && !node.exported) {
|
|
548
|
+
esm = true;
|
|
549
|
+
const child = resolveRelative(file, node.source.value);
|
|
550
|
+
if (!child || !collect(child, depth + 1)) return false;
|
|
551
|
+
} else if (node.type === "ExportAllDeclaration" && node.exported) {
|
|
552
|
+
esm = true;
|
|
553
|
+
const name = exportedName(node.exported);
|
|
554
|
+
if (name) names.add(name);
|
|
555
|
+
} else if (node.type === "ExportNamedDeclaration") {
|
|
556
|
+
esm = true;
|
|
557
|
+
for (const specifier2 of node.specifiers ?? []) {
|
|
558
|
+
const name = exportedName(specifier2.exported);
|
|
559
|
+
if (name) names.add(name);
|
|
560
|
+
}
|
|
561
|
+
if (node.declaration?.id?.name) names.add(node.declaration.id.name);
|
|
562
|
+
for (const declarator of node.declaration?.declarations ?? []) {
|
|
563
|
+
if (declarator.id?.type === "Identifier") names.add(declarator.id.name);
|
|
564
|
+
}
|
|
565
|
+
} else if (node.type === "ExportDefaultDeclaration") {
|
|
566
|
+
esm = true;
|
|
567
|
+
names.add("default");
|
|
568
|
+
} else if (node.type === "ImportDeclaration") {
|
|
569
|
+
esm = true;
|
|
570
|
+
}
|
|
571
|
+
}
|
|
572
|
+
return esm || depth > 0;
|
|
573
|
+
};
|
|
574
|
+
if (!collect(entry, 0)) return null;
|
|
575
|
+
return [...names].filter((name) => /^[A-Za-z_$][\w$]*$/.test(name)).sort();
|
|
576
|
+
}
|
|
577
|
+
|
|
578
|
+
// src/programmatic-routes-client.ts
|
|
579
|
+
import { builtinModules } from "module";
|
|
580
|
+
|
|
581
|
+
// src/browser-builtins.ts
|
|
582
|
+
import { isBuiltin } from "module";
|
|
583
|
+
var FARM_BROWSER_BUILTIN_PREFIX = "\0farm:browser-builtin:";
|
|
584
|
+
var BROWSER_IMPLEMENTATIONS = {
|
|
585
|
+
crypto: {
|
|
586
|
+
webcrypto: "globalThis.crypto",
|
|
587
|
+
subtle: "globalThis.crypto?.subtle",
|
|
588
|
+
getRandomValues: "(array) => globalThis.crypto.getRandomValues(array)",
|
|
589
|
+
randomUUID: "() => globalThis.crypto.randomUUID()"
|
|
590
|
+
}
|
|
591
|
+
};
|
|
592
|
+
var BROWSER_EXTERNAL_RE = /^(?:__vite-)?browser-external(?::|$)/;
|
|
593
|
+
var IDENTIFIER_RE = /^[A-Za-z_$][\w$]*$/;
|
|
594
|
+
async function resolveFarmBrowserBuiltin(context, source, importer, options) {
|
|
595
|
+
const resolved = await context.resolve(source, importer, { ...options, skipSelf: true });
|
|
596
|
+
if (!resolved || !BROWSER_EXTERNAL_RE.test(resolved.id)) return resolved;
|
|
597
|
+
return FARM_BROWSER_BUILTIN_PREFIX + source.replace(/^node:/, "");
|
|
598
|
+
}
|
|
599
|
+
function loadFarmBrowserBuiltin(id) {
|
|
600
|
+
if (!id.startsWith(FARM_BROWSER_BUILTIN_PREFIX)) return void 0;
|
|
601
|
+
const name = id.slice(FARM_BROWSER_BUILTIN_PREFIX.length);
|
|
602
|
+
const implementations = BROWSER_IMPLEMENTATIONS[name] ?? {};
|
|
603
|
+
const exports = Object.keys(process.getBuiltinModule(`node:${name}`) ?? {}).filter(
|
|
604
|
+
(key) => key !== "default" && IDENTIFIER_RE.test(key)
|
|
605
|
+
);
|
|
606
|
+
const implemented = exports.filter((key) => key in implementations);
|
|
607
|
+
return [
|
|
608
|
+
...exports.map((key) => `export const ${key} = ${implementations[key] ?? "undefined"};`),
|
|
609
|
+
`export default { ${implemented.join(", ")} };`
|
|
610
|
+
].join("\n");
|
|
611
|
+
}
|
|
612
|
+
function farmBrowserBuiltinsOptimizerPlugin() {
|
|
613
|
+
return {
|
|
614
|
+
name: "farm:browser-builtins-optimizer",
|
|
615
|
+
resolveId(source, importer, options) {
|
|
616
|
+
return isBuiltin(source) ? resolveFarmBrowserBuiltin(this, source, importer, options) : null;
|
|
617
|
+
},
|
|
618
|
+
load(id) {
|
|
619
|
+
return loadFarmBrowserBuiltin(id) ?? null;
|
|
620
|
+
}
|
|
621
|
+
};
|
|
622
|
+
}
|
|
623
|
+
|
|
624
|
+
// src/programmatic-routes-client.ts
|
|
625
|
+
import { fileURLToPath } from "url";
|
|
626
|
+
var SERVER_PROPS_KEYS = ["params", "search", "guard", "data"];
|
|
627
|
+
function programmaticClientRouteKey(routesFile, kind, routePath) {
|
|
628
|
+
return `${toPosixPath(routesFile)}\0${kind}\0${routePath}`;
|
|
629
|
+
}
|
|
630
|
+
function resolveProgrammaticClientRoutes(options) {
|
|
631
|
+
const routesFile = toPosixPath(options.routesFile);
|
|
632
|
+
const modules = collectGraph(options.graph, routesFile);
|
|
633
|
+
const routeSourceFiles = /* @__PURE__ */ new Set([routesFile]);
|
|
634
|
+
const exportsByValue = /* @__PURE__ */ new Map();
|
|
635
|
+
const modulesByFile = /* @__PURE__ */ new Map();
|
|
636
|
+
const definitions = options.routes.filter(isProgrammaticRouteDefinition);
|
|
637
|
+
for (const module of modules.values()) {
|
|
638
|
+
if (module.file) {
|
|
639
|
+
modulesByFile.set(module.file, [...modulesByFile.get(module.file) ?? [], module]);
|
|
640
|
+
}
|
|
641
|
+
for (const [exportName, value] of module.exports) {
|
|
642
|
+
if (!isReferenceValue(value)) continue;
|
|
643
|
+
if (!module.routeSource && holdsRouteDefinition(value, definitions)) {
|
|
644
|
+
module.routeSource = true;
|
|
645
|
+
}
|
|
646
|
+
const owners = exportsByValue.get(value) ?? [];
|
|
647
|
+
owners.push({ module, exportName });
|
|
648
|
+
exportsByValue.set(value, owners);
|
|
649
|
+
}
|
|
650
|
+
}
|
|
651
|
+
let untraced = false;
|
|
652
|
+
const definedIn = /* @__PURE__ */ new Map();
|
|
653
|
+
for (const route of definitions) {
|
|
654
|
+
const source = getProgrammaticRouteDefinitionSource(route);
|
|
655
|
+
const callers = (source?.stacks ?? []).map((stack) => findRouteCallers(stack, modulesByFile));
|
|
656
|
+
for (const caller of callers.flat()) caller.routeSource = true;
|
|
657
|
+
definedIn.set(route, callers.flat());
|
|
658
|
+
if (!source || source.raw || (callers[0] ?? []).length === 0) untraced = true;
|
|
659
|
+
}
|
|
660
|
+
for (const module of modules.values()) {
|
|
661
|
+
if (module.routeSource && module.file) routeSourceFiles.add(module.file);
|
|
662
|
+
}
|
|
663
|
+
const reaches = createReachability(modules);
|
|
664
|
+
const closure = createClosure(modules);
|
|
665
|
+
const routeCode = /* @__PURE__ */ new Map();
|
|
666
|
+
const definesRoutes = (module) => {
|
|
667
|
+
if (!routeCode.has(module)) routeCode.set(module, mayDefineRoutes(module.code));
|
|
668
|
+
return routeCode.get(module);
|
|
669
|
+
};
|
|
670
|
+
const refusal = /* @__PURE__ */ new Map();
|
|
671
|
+
const refuse = (module) => {
|
|
672
|
+
if (refusal.has(module)) return refusal.get(module);
|
|
673
|
+
let reason = null;
|
|
674
|
+
for (const reached of closure(module)) {
|
|
675
|
+
if (reached.routeSource) {
|
|
676
|
+
reason = reached === module ? `${module.file}, which defines routes` : `${module.file}, which imports ${reached.file ?? reached.id}, which defines routes`;
|
|
677
|
+
break;
|
|
678
|
+
}
|
|
679
|
+
if (untraced && !reached.external && definesRoutes(reached)) {
|
|
680
|
+
reason = `${module.file}, and a route defined as an object literal outside every export can't be traced to its module, so Farm can't tell that ${reached === module ? "it" : reached.file ?? reached.id} defines no routes (build such routes with page(), layout(), or api(), or export them)`;
|
|
681
|
+
break;
|
|
682
|
+
}
|
|
683
|
+
}
|
|
684
|
+
refusal.set(module, reason);
|
|
685
|
+
return reason;
|
|
686
|
+
};
|
|
687
|
+
const locate = (route, value, label) => {
|
|
688
|
+
if (!isReferenceValue(value)) return `its ${label} is not a component`;
|
|
689
|
+
const owners = exportsByValue.get(value) ?? [];
|
|
690
|
+
const local = owners.filter(({ module }) => module.file && !module.external);
|
|
691
|
+
const eligible = local.filter(({ module }) => !refuse(module));
|
|
692
|
+
if (eligible.length === 0) {
|
|
693
|
+
const refused = local.find(({ module }) => refuse(module));
|
|
694
|
+
if (refused) return `its ${label} is exported by ${refuse(refused.module)}`;
|
|
695
|
+
if (owners.some(({ module }) => module.external)) {
|
|
696
|
+
return `its ${label} comes from a package; re-export it from a module in your app`;
|
|
697
|
+
}
|
|
698
|
+
return `its ${label} is not exported by any module the routes file imports`;
|
|
699
|
+
}
|
|
700
|
+
let defining = eligible.filter(
|
|
701
|
+
(candidate) => !eligible.some(
|
|
702
|
+
(other) => other.module !== candidate.module && reaches(candidate.module, other.module)
|
|
703
|
+
)
|
|
704
|
+
);
|
|
705
|
+
if (defining.length === 0) defining = eligible;
|
|
706
|
+
if (new Set(defining.map(({ module }) => module)).size > 1) {
|
|
707
|
+
const importers = [...modulesByFile.get(routesFile) ?? [], ...definedIn.get(route) ?? []];
|
|
708
|
+
const imported = defining.filter(
|
|
709
|
+
(candidate) => importers.some((importer) => importsBinding(importer, candidate))
|
|
710
|
+
);
|
|
711
|
+
if (imported.length > 0) defining = imported;
|
|
712
|
+
const depth = Math.min(...defining.map(({ module }) => module.depth));
|
|
713
|
+
defining = defining.filter(({ module }) => module.depth === depth);
|
|
714
|
+
const files = [...new Set(defining.map(({ module }) => module.file))];
|
|
715
|
+
if (files.length > 1) {
|
|
716
|
+
return `its ${label} is exported by several modules (${files.join(", ")}) and Farm can't tell which one the routes file uses`;
|
|
717
|
+
}
|
|
718
|
+
}
|
|
719
|
+
const chosen = defining.sort(compareOwners)[0];
|
|
720
|
+
return { file: chosen.module.file, exportName: chosen.exportName };
|
|
721
|
+
};
|
|
722
|
+
const routes = /* @__PURE__ */ new Map();
|
|
723
|
+
for (const route of definitions) {
|
|
724
|
+
if (route.kind !== "page" && route.kind !== "layout" || typeof route.path !== "string") {
|
|
725
|
+
continue;
|
|
726
|
+
}
|
|
727
|
+
const routePath = options.normalizeRoutePath(route.path);
|
|
728
|
+
const clientRoute = {
|
|
729
|
+
kind: route.kind,
|
|
730
|
+
path: routePath,
|
|
731
|
+
routesFile
|
|
732
|
+
};
|
|
733
|
+
const problems = [];
|
|
734
|
+
const component = locate(route, route.component, "component");
|
|
735
|
+
if (typeof component === "string") problems.push(component);
|
|
736
|
+
else clientRoute.component = component;
|
|
737
|
+
if (route.kind === "page") {
|
|
738
|
+
if (route.pending) {
|
|
739
|
+
const pending = locate(route, route.pending, "pending component");
|
|
740
|
+
if (typeof pending === "string") problems.push(pending);
|
|
741
|
+
else clientRoute.pending = pending;
|
|
742
|
+
}
|
|
743
|
+
const serverProps = SERVER_PROPS_KEYS.filter((key) => Boolean(route[key]));
|
|
744
|
+
if (serverProps.length > 0) clientRoute.serverProps = serverProps;
|
|
745
|
+
}
|
|
746
|
+
if (problems.length > 0) clientRoute.problem = problems.join("; ");
|
|
747
|
+
routes.set(programmaticClientRouteKey(routesFile, route.kind, routePath), clientRoute);
|
|
748
|
+
}
|
|
749
|
+
return { routes, routeSourceFiles };
|
|
750
|
+
}
|
|
751
|
+
function createEvaluatedRouteGraph(server) {
|
|
752
|
+
const evaluated = server.environments?.ssr?.runner?.evaluatedModules;
|
|
753
|
+
if (!evaluated) return void 0;
|
|
754
|
+
const toGraphModule = (node) => ({
|
|
755
|
+
id: node.id,
|
|
756
|
+
file: node.file || void 0,
|
|
757
|
+
url: node.url,
|
|
758
|
+
imports: node.imports,
|
|
759
|
+
exports: node.exports,
|
|
760
|
+
external: Boolean(node.meta && "externalize" in node.meta),
|
|
761
|
+
code: node.meta && typeof node.meta.code === "string" ? node.meta.code : void 0
|
|
762
|
+
});
|
|
763
|
+
return {
|
|
764
|
+
getModuleById: (id) => {
|
|
765
|
+
const node = evaluated.getModuleById(id);
|
|
766
|
+
return node ? toGraphModule(node) : void 0;
|
|
767
|
+
},
|
|
768
|
+
getModulesByFile: (file) => [...evaluated.fileToModulesMap.get(file) ?? []].map(toGraphModule)
|
|
769
|
+
};
|
|
770
|
+
}
|
|
771
|
+
function mergeProgrammaticClientRoutes(entries) {
|
|
772
|
+
const routes = /* @__PURE__ */ new Map();
|
|
773
|
+
const routeSourceFiles = /* @__PURE__ */ new Set();
|
|
774
|
+
for (const entry of entries) {
|
|
775
|
+
for (const [key, route] of entry.routes) routes.set(key, route);
|
|
776
|
+
for (const file of entry.routeSourceFiles) routeSourceFiles.add(file);
|
|
777
|
+
}
|
|
778
|
+
return { routes, routeSourceFiles };
|
|
779
|
+
}
|
|
780
|
+
function generateProgrammaticClientRouteModule(options) {
|
|
781
|
+
const label = `Programmatic ${options.kind} route "${options.routePath}" in ${options.routesFile}`;
|
|
782
|
+
if (options.kind === "api") {
|
|
783
|
+
throw new Error(
|
|
784
|
+
`[Farm.js] ${label} is server-only, but the browser bundle imports it. API routes never reach the browser; call them over HTTP instead.`
|
|
785
|
+
);
|
|
786
|
+
}
|
|
787
|
+
const route = options.route;
|
|
788
|
+
if (!route) {
|
|
789
|
+
throw new Error(
|
|
790
|
+
`[Farm.js] ${label} renders in the browser, but Farm did not find it when it evaluated the routes file on the server, so it can't tell which module holds its component.`
|
|
791
|
+
);
|
|
792
|
+
}
|
|
793
|
+
if (route.problem || !route.component) {
|
|
794
|
+
throw new Error(
|
|
795
|
+
`[Farm.js] ${label} renders in the browser, but ${route.problem ?? "its component has no module"}. The browser never loads the routes file, so move the component to its own module and import it into the routes file (for example \`import { AdminPage } from "./features/admin/page"\`).`
|
|
796
|
+
);
|
|
797
|
+
}
|
|
798
|
+
const component = importExport(route.component, "__farmComponent", options.toImportSpecifier);
|
|
799
|
+
if (route.kind === "layout") {
|
|
800
|
+
return `${component}
|
|
801
|
+
export default __farmComponent;
|
|
802
|
+
`;
|
|
803
|
+
}
|
|
804
|
+
const pending = route.pending ? importExport(route.pending, "__farmPending", options.toImportSpecifier) : "";
|
|
805
|
+
if (!route.pending && !route.serverProps) {
|
|
806
|
+
return `${component}
|
|
807
|
+
export default __farmComponent;
|
|
808
|
+
`;
|
|
809
|
+
}
|
|
810
|
+
const definition = [
|
|
811
|
+
`kind: "page"`,
|
|
812
|
+
`path: ${JSON.stringify(route.path)}`,
|
|
813
|
+
"component: __farmComponent",
|
|
814
|
+
...route.pending ? ["pending: __farmPending"] : [],
|
|
815
|
+
// Read by createRouteModuleFromProgrammaticPage: the page renders only from props the
|
|
816
|
+
// server resolved for this document.
|
|
817
|
+
...route.serverProps ? [`__farmServerHooks: ${JSON.stringify(route.serverProps)}`] : []
|
|
818
|
+
];
|
|
819
|
+
return `
|
|
820
|
+
import * as __farmRendererRuntime from ${JSON.stringify(options.rendererServer)};
|
|
821
|
+
import { createRouteModuleFromProgrammaticPage as __farmCreatePageRouteModule } from "@farm.js/core/routes";
|
|
822
|
+
${component}
|
|
823
|
+
${pending}
|
|
824
|
+
|
|
825
|
+
const __farmRouteModule = __farmCreatePageRouteModule(
|
|
826
|
+
{ ${definition.join(", ")} },
|
|
827
|
+
{
|
|
828
|
+
createElement: __farmRendererRuntime.createElement,
|
|
829
|
+
Suspense: __farmRendererRuntime.Suspense,
|
|
830
|
+
// Optional hook: only renderers that need it export markFunctionComponent.
|
|
831
|
+
markFunctionComponent: Reflect.get(__farmRendererRuntime, "markFunctionComponent"),
|
|
832
|
+
},
|
|
833
|
+
);
|
|
834
|
+
|
|
835
|
+
export const __farmRouteSchemas = __farmRouteModule.__farmRouteSchemas;
|
|
836
|
+
export const __farmRouteParsesProps = __farmRouteModule.__farmRouteParsesProps;
|
|
837
|
+
export const __farmResolveRouteProps = __farmRouteModule.__farmResolveRouteProps;
|
|
838
|
+
export default __farmRouteModule.default;
|
|
839
|
+
`.trimStart();
|
|
840
|
+
}
|
|
841
|
+
function findClientNodeBuiltinChain(entry, getImportedIds) {
|
|
842
|
+
const parents = /* @__PURE__ */ new Map([[entry, null]]);
|
|
843
|
+
const queue = [entry];
|
|
844
|
+
while (queue.length > 0) {
|
|
845
|
+
const id = queue.shift();
|
|
846
|
+
for (const imported of getImportedIds(id) ?? []) {
|
|
847
|
+
if (isNodeBuiltinId(imported)) {
|
|
848
|
+
const chain = [imported];
|
|
849
|
+
for (let cursor = id; cursor; cursor = parents.get(cursor) ?? null) {
|
|
850
|
+
chain.unshift(cursor);
|
|
851
|
+
}
|
|
852
|
+
return chain;
|
|
853
|
+
}
|
|
854
|
+
if (parents.has(imported) || !isApplicationModuleId(imported)) continue;
|
|
855
|
+
parents.set(imported, id);
|
|
856
|
+
queue.push(imported);
|
|
857
|
+
}
|
|
858
|
+
}
|
|
859
|
+
return null;
|
|
860
|
+
}
|
|
861
|
+
var NODE_BUILTINS = new Set(builtinModules);
|
|
862
|
+
var MODULE_EXTENSION_RE = /\.[cm]?[jt]sx?$/;
|
|
863
|
+
function isApplicationModuleId(id) {
|
|
864
|
+
if (id.startsWith("\0") || id.includes("/node_modules/") || id.includes("\\node_modules\\")) {
|
|
865
|
+
return false;
|
|
866
|
+
}
|
|
867
|
+
return MODULE_EXTENSION_RE.test(id.split("?", 1)[0]);
|
|
868
|
+
}
|
|
869
|
+
function isNodeBuiltinId(id) {
|
|
870
|
+
if (id.startsWith(FARM_BROWSER_BUILTIN_PREFIX)) return true;
|
|
871
|
+
const external = id.indexOf("__vite-browser-external:");
|
|
872
|
+
const bare = external === 0 || external === 1 ? id.slice(external + 24) : id;
|
|
873
|
+
return bare.startsWith("node:") || NODE_BUILTINS.has(bare);
|
|
874
|
+
}
|
|
875
|
+
function isProgrammaticRouteActionProxy(code) {
|
|
876
|
+
return Boolean(code?.includes("__farmRouteActionTarget: true"));
|
|
877
|
+
}
|
|
878
|
+
function collectGraph(graph, routesFile) {
|
|
879
|
+
const modules = /* @__PURE__ */ new Map();
|
|
880
|
+
const queue = [...graph.getModulesByFile(routesFile)].map((node) => ({ node, depth: 0 }));
|
|
881
|
+
while (queue.length > 0) {
|
|
882
|
+
const { node, depth } = queue.shift();
|
|
883
|
+
if (modules.has(node.id)) continue;
|
|
884
|
+
const file = node.file ? toModuleFile(node.file) : void 0;
|
|
885
|
+
const entry = {
|
|
886
|
+
id: node.id,
|
|
887
|
+
file,
|
|
888
|
+
url: node.url,
|
|
889
|
+
code: node.code,
|
|
890
|
+
external: node.external === true,
|
|
891
|
+
imports: [...node.imports],
|
|
892
|
+
exports: readExports(node.exports),
|
|
893
|
+
routeSource: file === routesFile,
|
|
894
|
+
order: modules.size,
|
|
895
|
+
depth
|
|
896
|
+
};
|
|
897
|
+
modules.set(node.id, entry);
|
|
898
|
+
if (entry.external) continue;
|
|
899
|
+
for (const id of entry.imports) {
|
|
900
|
+
const imported = graph.getModuleById(id);
|
|
901
|
+
if (imported && !modules.has(imported.id)) queue.push({ node: imported, depth: depth + 1 });
|
|
902
|
+
}
|
|
903
|
+
}
|
|
904
|
+
return modules;
|
|
905
|
+
}
|
|
906
|
+
function createReachability(modules) {
|
|
907
|
+
const cache2 = /* @__PURE__ */ new Map();
|
|
908
|
+
const reachable = (start) => {
|
|
909
|
+
const cached = cache2.get(start.id);
|
|
910
|
+
if (cached) return cached;
|
|
911
|
+
const seen = /* @__PURE__ */ new Set();
|
|
912
|
+
const stack = [...start.imports];
|
|
913
|
+
while (stack.length > 0) {
|
|
914
|
+
const id = stack.pop();
|
|
915
|
+
if (seen.has(id)) continue;
|
|
916
|
+
seen.add(id);
|
|
917
|
+
const module = modules.get(id);
|
|
918
|
+
if (module && !module.external) stack.push(...module.imports);
|
|
919
|
+
}
|
|
920
|
+
cache2.set(start.id, seen);
|
|
921
|
+
return seen;
|
|
922
|
+
};
|
|
923
|
+
return (from, to) => reachable(from).has(to.id);
|
|
924
|
+
}
|
|
925
|
+
function createClosure(modules) {
|
|
926
|
+
return function* closure(start) {
|
|
927
|
+
const seen = /* @__PURE__ */ new Set([start.id]);
|
|
928
|
+
const queue = [start];
|
|
929
|
+
while (queue.length > 0) {
|
|
930
|
+
const module = queue.shift();
|
|
931
|
+
yield module;
|
|
932
|
+
if (module.external) continue;
|
|
933
|
+
for (const id of module.imports) {
|
|
934
|
+
const imported = modules.get(id);
|
|
935
|
+
if (!imported || seen.has(id)) continue;
|
|
936
|
+
seen.add(id);
|
|
937
|
+
queue.push(imported);
|
|
938
|
+
}
|
|
939
|
+
}
|
|
940
|
+
};
|
|
941
|
+
}
|
|
942
|
+
var WALK_DEPTH = 10;
|
|
943
|
+
var WALK_BUDGET = 2e4;
|
|
944
|
+
function holdsRouteDefinition(value, definitions) {
|
|
945
|
+
const seen = /* @__PURE__ */ new Set();
|
|
946
|
+
const queue = [{ value, depth: 0 }];
|
|
947
|
+
while (queue.length > 0 && seen.size < WALK_BUDGET) {
|
|
948
|
+
const { value: current, depth } = queue.shift();
|
|
949
|
+
if (!isReferenceValue(current) || seen.has(current)) continue;
|
|
950
|
+
seen.add(current);
|
|
951
|
+
if (isRouteManifest(current) || isDefinitionObject(current, definitions)) return true;
|
|
952
|
+
if (depth >= WALK_DEPTH || ArrayBuffer.isView(current) || current instanceof Promise) continue;
|
|
953
|
+
const next = (child) => {
|
|
954
|
+
if (isReferenceValue(child)) queue.push({ value: child, depth: depth + 1 });
|
|
955
|
+
};
|
|
956
|
+
try {
|
|
957
|
+
if (Array.isArray(current)) current.forEach(next);
|
|
958
|
+
else if (current instanceof Map) {
|
|
959
|
+
for (const [key, child] of current) {
|
|
960
|
+
next(key);
|
|
961
|
+
next(child);
|
|
962
|
+
}
|
|
963
|
+
} else if (current instanceof Set) current.forEach(next);
|
|
964
|
+
else {
|
|
965
|
+
for (const key of Object.keys(current)) {
|
|
966
|
+
const descriptor = Object.getOwnPropertyDescriptor(current, key);
|
|
967
|
+
if (descriptor && "value" in descriptor) next(descriptor.value);
|
|
968
|
+
}
|
|
969
|
+
}
|
|
970
|
+
} catch {
|
|
971
|
+
}
|
|
972
|
+
}
|
|
973
|
+
return false;
|
|
974
|
+
}
|
|
975
|
+
function isRouteManifest(value) {
|
|
976
|
+
return value.__farmRoutes === true && Array.isArray(value.routes);
|
|
977
|
+
}
|
|
978
|
+
function isDefinitionObject(value, definitions) {
|
|
979
|
+
if (!isProgrammaticRouteDefinition(value)) return false;
|
|
980
|
+
const route = value;
|
|
981
|
+
const where = route.kind === "redirect" ? route.source : route.path;
|
|
982
|
+
if (typeof where !== "string") return false;
|
|
983
|
+
const values = Object.values(route);
|
|
984
|
+
const own = (child) => typeof child === "function" || isReferenceValue(child) && Object.values(child).some((nested) => typeof nested === "function");
|
|
985
|
+
if (values.some(own)) return true;
|
|
986
|
+
return definitions.some(
|
|
987
|
+
(definition) => definition.kind === route.kind && Object.entries(definition).every(
|
|
988
|
+
([key, child]) => !isReferenceValue(child) || route[key] === child
|
|
989
|
+
) && definition[route.kind === "redirect" ? "source" : "path"] === where
|
|
990
|
+
);
|
|
991
|
+
}
|
|
992
|
+
function findRouteCallers(stack, modulesByFile) {
|
|
993
|
+
const files = stack.split("\n").slice(1).map(stackFrameFile).filter((file) => Boolean(file));
|
|
994
|
+
const own = files[0];
|
|
995
|
+
const callers = [];
|
|
996
|
+
for (const file of files) {
|
|
997
|
+
if (file === own) continue;
|
|
998
|
+
const modules = modulesByFile.get(file);
|
|
999
|
+
if (!modules) continue;
|
|
1000
|
+
callers.push(...modules);
|
|
1001
|
+
if (modules.some((module) => !module.external)) break;
|
|
1002
|
+
}
|
|
1003
|
+
return callers;
|
|
1004
|
+
}
|
|
1005
|
+
function stackFrameFile(frame) {
|
|
1006
|
+
const line = frame.trim();
|
|
1007
|
+
if (!line.startsWith("at ")) return void 0;
|
|
1008
|
+
const location = line.endsWith(")") ? line.slice(line.lastIndexOf("(") + 1, -1) : line.slice(3).replace(/^async /, "");
|
|
1009
|
+
const file = location.replace(/:\d+(?::\d+)?$/, "");
|
|
1010
|
+
if (!file || file === location || file.startsWith("node:") || file.includes("<anonymous>")) {
|
|
1011
|
+
return void 0;
|
|
1012
|
+
}
|
|
1013
|
+
return toModuleFile(file);
|
|
1014
|
+
}
|
|
1015
|
+
function importsBinding(importer, candidate) {
|
|
1016
|
+
if (!importer.code || !importer.imports.includes(candidate.module.id)) return false;
|
|
1017
|
+
const specifiers = new Set([candidate.module.url, candidate.module.id].filter(Boolean));
|
|
1018
|
+
for (const match of importer.code.matchAll(SSR_IMPORT_RE)) {
|
|
1019
|
+
if (!specifiers.has(readJsonString(match[1]))) continue;
|
|
1020
|
+
if (match[2] === void 0) return true;
|
|
1021
|
+
const names = readJsonArray(`[${match[2]}]`);
|
|
1022
|
+
if (!names || names.includes(candidate.exportName)) return true;
|
|
1023
|
+
}
|
|
1024
|
+
return false;
|
|
1025
|
+
}
|
|
1026
|
+
var SSR_IMPORT_RE = /__vite_ssr_import__\(("(?:[^"\\]|\\.)*")(?:\s*,\s*\{\s*"importedNames"\s*:\s*\[([^\]]*)\])?/g;
|
|
1027
|
+
var ROUTE_KINDS = /* @__PURE__ */ new Set(["page", "layout", "api", "redirect"]);
|
|
1028
|
+
var ROUTE_FACTORIES = /* @__PURE__ */ new Set([
|
|
1029
|
+
"page",
|
|
1030
|
+
"layout",
|
|
1031
|
+
"api",
|
|
1032
|
+
"redirect",
|
|
1033
|
+
"createRoute",
|
|
1034
|
+
"routesBuilder",
|
|
1035
|
+
"defineRoutes"
|
|
1036
|
+
]);
|
|
1037
|
+
function mayDefineRoutes(code) {
|
|
1038
|
+
if (code === void 0) return true;
|
|
1039
|
+
for (const match of code.matchAll(KIND_KEY_RE)) {
|
|
1040
|
+
const value = code.slice(match.index + match[0].length);
|
|
1041
|
+
const quote = value[0];
|
|
1042
|
+
if (quote !== '"' && quote !== "'" && quote !== "`") return true;
|
|
1043
|
+
const end = value.indexOf(quote, 1);
|
|
1044
|
+
if (end < 0 || ROUTE_KINDS.has(value.slice(1, end))) return true;
|
|
1045
|
+
}
|
|
1046
|
+
if (KIND_SHORTHAND_RE.test(code) || KIND_ASSIGNMENT_RE.test(code)) return true;
|
|
1047
|
+
for (const match of code.matchAll(SSR_IMPORT_RE)) {
|
|
1048
|
+
if (!FARM_CORE_RE.test(readJsonString(match[1]) ?? "")) continue;
|
|
1049
|
+
if (match[2] === void 0) return true;
|
|
1050
|
+
const names = readJsonArray(`[${match[2]}]`);
|
|
1051
|
+
if (!names || names.some((name) => ROUTE_FACTORIES.has(String(name)))) return true;
|
|
1052
|
+
}
|
|
1053
|
+
return false;
|
|
1054
|
+
}
|
|
1055
|
+
var KIND_KEY_RE = /(?<![\w$.])["']?kind["']?\s*:\s*/g;
|
|
1056
|
+
var KIND_SHORTHAND_RE = /[{,]\s*kind\s*[,}]/;
|
|
1057
|
+
var KIND_ASSIGNMENT_RE = /(?:\.kind|\[\s*["'`]kind["'`]\s*\])\s*=(?!=)/;
|
|
1058
|
+
var FARM_CORE_RE = /^@farm\.js\/core(?:\/routes)?$/;
|
|
1059
|
+
function readJsonString(text) {
|
|
1060
|
+
try {
|
|
1061
|
+
const value = JSON.parse(text);
|
|
1062
|
+
return typeof value === "string" ? value : void 0;
|
|
1063
|
+
} catch {
|
|
1064
|
+
return void 0;
|
|
1065
|
+
}
|
|
1066
|
+
}
|
|
1067
|
+
function readJsonArray(text) {
|
|
1068
|
+
try {
|
|
1069
|
+
const value = JSON.parse(text);
|
|
1070
|
+
return Array.isArray(value) ? value : void 0;
|
|
1071
|
+
} catch {
|
|
1072
|
+
return void 0;
|
|
1073
|
+
}
|
|
1074
|
+
}
|
|
1075
|
+
function readExports(namespace) {
|
|
1076
|
+
if (!namespace || typeof namespace !== "object" && typeof namespace !== "function") return [];
|
|
1077
|
+
const entries = [];
|
|
1078
|
+
let keys;
|
|
1079
|
+
try {
|
|
1080
|
+
keys = Object.keys(namespace);
|
|
1081
|
+
} catch {
|
|
1082
|
+
return [];
|
|
1083
|
+
}
|
|
1084
|
+
for (const key of keys) {
|
|
1085
|
+
try {
|
|
1086
|
+
entries.push([key, namespace[key]]);
|
|
1087
|
+
} catch {
|
|
1088
|
+
}
|
|
1089
|
+
}
|
|
1090
|
+
return entries;
|
|
1091
|
+
}
|
|
1092
|
+
function isReferenceValue(value) {
|
|
1093
|
+
return typeof value === "function" || typeof value === "object" && value !== null;
|
|
1094
|
+
}
|
|
1095
|
+
function isProgrammaticRouteDefinition(value) {
|
|
1096
|
+
if (!value || typeof value !== "object") return false;
|
|
1097
|
+
const kind = value.kind;
|
|
1098
|
+
return kind === "page" || kind === "layout" || kind === "api" || kind === "redirect";
|
|
1099
|
+
}
|
|
1100
|
+
function compareOwners(left, right) {
|
|
1101
|
+
if (left.module !== right.module) return right.module.order - left.module.order;
|
|
1102
|
+
if (left.exportName === "default") return -1;
|
|
1103
|
+
if (right.exportName === "default") return 1;
|
|
1104
|
+
return left.exportName < right.exportName ? -1 : left.exportName > right.exportName ? 1 : 0;
|
|
1105
|
+
}
|
|
1106
|
+
var IDENTIFIER_RE2 = /^[A-Za-z_$][\w$]*$/;
|
|
1107
|
+
function importExport(value, local, toImportSpecifier) {
|
|
1108
|
+
const source = JSON.stringify(toImportSpecifier(value.file));
|
|
1109
|
+
if (value.exportName === "default") return `import ${local} from ${source};`;
|
|
1110
|
+
const imported = IDENTIFIER_RE2.test(value.exportName) ? value.exportName : JSON.stringify(value.exportName);
|
|
1111
|
+
return `import { ${imported} as ${local} } from ${source};`;
|
|
1112
|
+
}
|
|
1113
|
+
function toPosixPath(filePath) {
|
|
1114
|
+
return filePath.replace(/\\/g, "/");
|
|
1115
|
+
}
|
|
1116
|
+
function toModuleFile(file) {
|
|
1117
|
+
if (file.startsWith("file://")) {
|
|
1118
|
+
try {
|
|
1119
|
+
return toPosixPath(fileURLToPath(file));
|
|
1120
|
+
} catch {
|
|
1121
|
+
return toPosixPath(file);
|
|
1122
|
+
}
|
|
1123
|
+
}
|
|
1124
|
+
return toPosixPath(file.split("?", 1)[0]);
|
|
1125
|
+
}
|
|
1126
|
+
|
|
1127
|
+
// src/utils/client-component.ts
|
|
1128
|
+
import fs4 from "fs";
|
|
1129
|
+
import path4 from "path";
|
|
1130
|
+
import { fileURLToPath as fileURLToPath2 } from "url";
|
|
1131
|
+
|
|
1132
|
+
// src/islands-package-references.ts
|
|
1133
|
+
import fs2 from "fs";
|
|
1134
|
+
import path2 from "path";
|
|
1135
|
+
import { parseAst as parseAst2 } from "rolldown/parseAst";
|
|
1136
|
+
var IDENTIFIER = /^[A-Za-z_$][\w$]*$/;
|
|
1137
|
+
function parse(code, file) {
|
|
1138
|
+
const extension = path2.extname(file).slice(1);
|
|
1139
|
+
const lang = extension === "ts" || extension === "mts" || extension === "cts" ? "ts" : "tsx";
|
|
1140
|
+
try {
|
|
1141
|
+
return parseAst2(code, { lang });
|
|
1142
|
+
} catch {
|
|
1143
|
+
return null;
|
|
1144
|
+
}
|
|
1145
|
+
}
|
|
1146
|
+
function walk(node, visit, parent = null) {
|
|
1147
|
+
if (!node || typeof node !== "object") return;
|
|
1148
|
+
if (Array.isArray(node)) {
|
|
1149
|
+
for (const child of node) walk(child, visit, parent);
|
|
1150
|
+
return;
|
|
1151
|
+
}
|
|
1152
|
+
const current = node;
|
|
1153
|
+
if (typeof current.type !== "string") return;
|
|
1154
|
+
visit(current, parent);
|
|
1155
|
+
for (const [key, value] of Object.entries(current)) {
|
|
1156
|
+
if (key === "start" || key === "end" || key === "loc" || key === "range") continue;
|
|
1157
|
+
if (value && typeof value === "object") walk(value, visit, current);
|
|
1158
|
+
}
|
|
1159
|
+
}
|
|
1160
|
+
function namespaceMembers2(program, local, declaration) {
|
|
1161
|
+
const members = /* @__PURE__ */ new Set();
|
|
1162
|
+
let opaque = false;
|
|
1163
|
+
walk(program, (node, parent) => {
|
|
1164
|
+
if (opaque || node === declaration) return;
|
|
1165
|
+
const name = node.type === "Identifier" || node.type === "JSXIdentifier" ? node.name : null;
|
|
1166
|
+
if (name !== local) return;
|
|
1167
|
+
if (parent?.type === "ImportNamespaceSpecifier") return;
|
|
1168
|
+
const member = (parent?.type === "MemberExpression" || parent?.type === "JSXMemberExpression") && parent.object === node ? parent.property : null;
|
|
1169
|
+
const property = member && !parent.computed && (member.type === "Identifier" || member.type === "JSXIdentifier") ? member.name : null;
|
|
1170
|
+
if (property) members.add(property);
|
|
1171
|
+
else opaque = true;
|
|
1172
|
+
});
|
|
1173
|
+
return opaque ? null : [...members];
|
|
1174
|
+
}
|
|
1175
|
+
function findFarmPackageClientImports(code, file, isClientPackage) {
|
|
1176
|
+
if (!code.includes("import")) return [];
|
|
1177
|
+
const program = parse(code, file);
|
|
1178
|
+
if (!program) return [];
|
|
1179
|
+
const found = [];
|
|
1180
|
+
for (const node of program.body ?? []) {
|
|
1181
|
+
if (node.type !== "ImportDeclaration" || node.importKind === "type") continue;
|
|
1182
|
+
const specifier = node.source?.value;
|
|
1183
|
+
if (typeof specifier !== "string" || specifier.startsWith(".") || specifier.startsWith("/"))
|
|
1184
|
+
continue;
|
|
1185
|
+
const specifiers = (node.specifiers ?? []).filter(
|
|
1186
|
+
(entry2) => entry2.importKind !== "type"
|
|
1187
|
+
);
|
|
1188
|
+
if (specifiers.length === 0 || !isClientPackage(specifier)) continue;
|
|
1189
|
+
const entry = {
|
|
1190
|
+
start: node.start,
|
|
1191
|
+
end: node.end,
|
|
1192
|
+
specifier,
|
|
1193
|
+
named: [],
|
|
1194
|
+
kept: []
|
|
1195
|
+
};
|
|
1196
|
+
const client = (name) => isFarmPackageClientExport(file, specifier, name);
|
|
1197
|
+
let supported = true;
|
|
1198
|
+
for (const binding of specifiers) {
|
|
1199
|
+
if (binding.type === "ImportDefaultSpecifier") {
|
|
1200
|
+
if (client("default")) entry.defaultLocal = binding.local.name;
|
|
1201
|
+
else entry.kept.push({ imported: "default", local: binding.local.name });
|
|
1202
|
+
} else if (binding.type === "ImportNamespaceSpecifier") {
|
|
1203
|
+
const read = namespaceMembers2(program, binding.local.name, node);
|
|
1204
|
+
const members = read ?? listFarmPackageExports(file, specifier);
|
|
1205
|
+
if (!members || members.some((member) => !IDENTIFIER.test(member))) {
|
|
1206
|
+
supported = false;
|
|
1207
|
+
continue;
|
|
1208
|
+
}
|
|
1209
|
+
const reference = (name) => client(name) && (read !== null || name === "default" || /^[A-Z]/.test(name));
|
|
1210
|
+
const values = members.filter((name) => !reference(name));
|
|
1211
|
+
entry.namespace = {
|
|
1212
|
+
local: binding.local.name,
|
|
1213
|
+
members: members.filter(reference),
|
|
1214
|
+
...values.length > 0 ? { values } : {}
|
|
1215
|
+
};
|
|
1216
|
+
} else {
|
|
1217
|
+
const imported = binding.imported?.type === "Identifier" ? binding.imported.name : binding.imported?.value;
|
|
1218
|
+
if (typeof imported !== "string" || !IDENTIFIER.test(imported)) supported = false;
|
|
1219
|
+
else if (client(imported)) entry.named.push({ imported, local: binding.local.name });
|
|
1220
|
+
else entry.kept.push({ imported, local: binding.local.name });
|
|
1221
|
+
}
|
|
1222
|
+
}
|
|
1223
|
+
if (supported) found.push(entry);
|
|
1224
|
+
}
|
|
1225
|
+
return found;
|
|
1226
|
+
}
|
|
1227
|
+
function farmPackageClientImportExports(entry) {
|
|
1228
|
+
return [
|
|
1229
|
+
...entry.defaultLocal ? ["default"] : [],
|
|
1230
|
+
...entry.named.map((binding) => binding.imported),
|
|
1231
|
+
...entry.namespace?.members ?? []
|
|
1232
|
+
];
|
|
1233
|
+
}
|
|
1234
|
+
var FARM_CLIENT_REFERENCE_PRAGMA = "// @farm-client-reference";
|
|
1235
|
+
var FARM_CLIENT_REFERENCE_DIRECTORY = "/.farm/client-references/";
|
|
1236
|
+
function farmPackageClientReferencePath(root, specifier, exportName) {
|
|
1237
|
+
const directory = specifier.replace(/^@/, "").replace(/[^A-Za-z0-9._-]/g, "+");
|
|
1238
|
+
return path2.join(root, ".farm", "client-references", directory, `${exportName}.tsx`);
|
|
1239
|
+
}
|
|
1240
|
+
function ensureFarmPackageClientReference(root, specifier, exportName) {
|
|
1241
|
+
const file = farmPackageClientReferencePath(root, specifier, exportName);
|
|
1242
|
+
const source = [
|
|
1243
|
+
`// Generated by Farm: ${specifier}'s ${exportName} export, as a client reference for server components.`,
|
|
1244
|
+
FARM_CLIENT_REFERENCE_PRAGMA,
|
|
1245
|
+
'"use client";',
|
|
1246
|
+
// An import, not `export { name } from`: a server graph applies CommonJS interop to imports
|
|
1247
|
+
// (react-wrap-balancer's `main` is CommonJS), not to re-exports.
|
|
1248
|
+
exportName === "default" ? `import __farm_reference__ from ${JSON.stringify(specifier)};` : `import { ${exportName} as __farm_reference__ } from ${JSON.stringify(specifier)};`,
|
|
1249
|
+
`export { __farm_reference__ as ${exportName} };`,
|
|
1250
|
+
""
|
|
1251
|
+
].join("\n");
|
|
1252
|
+
let current = null;
|
|
1253
|
+
try {
|
|
1254
|
+
current = fs2.readFileSync(file, "utf8");
|
|
1255
|
+
} catch {
|
|
1256
|
+
}
|
|
1257
|
+
if (current !== source) {
|
|
1258
|
+
fs2.mkdirSync(path2.dirname(file), { recursive: true });
|
|
1259
|
+
fs2.writeFileSync(file, source);
|
|
1260
|
+
}
|
|
1261
|
+
return file;
|
|
1262
|
+
}
|
|
1263
|
+
function rewriteFarmPackageClientImports(options) {
|
|
1264
|
+
const imports = findFarmPackageClientImports(options.code, options.file, options.isClientPackage);
|
|
1265
|
+
if (imports.length === 0) return null;
|
|
1266
|
+
const reference = (specifier, exportName) => JSON.stringify(ensureFarmPackageClientReference(options.root, specifier, exportName));
|
|
1267
|
+
let output = options.code;
|
|
1268
|
+
let next = 0;
|
|
1269
|
+
let changed = false;
|
|
1270
|
+
for (const entry of [...imports].sort((left, right) => right.start - left.start)) {
|
|
1271
|
+
if (farmPackageClientImportExports(entry).length === 0) continue;
|
|
1272
|
+
changed = true;
|
|
1273
|
+
const lines = [];
|
|
1274
|
+
if (entry.kept.length > 0) {
|
|
1275
|
+
const bindings = entry.kept.map((binding) => `${binding.imported} as ${binding.local}`);
|
|
1276
|
+
lines.push(`import { ${bindings.join(", ")} } from ${JSON.stringify(entry.specifier)};`);
|
|
1277
|
+
}
|
|
1278
|
+
if (entry.defaultLocal) {
|
|
1279
|
+
lines.push(`import ${entry.defaultLocal} from ${reference(entry.specifier, "default")};`);
|
|
1280
|
+
}
|
|
1281
|
+
for (const binding of entry.named) {
|
|
1282
|
+
lines.push(
|
|
1283
|
+
`import { ${binding.imported} as ${binding.local} } from ${reference(entry.specifier, binding.imported)};`
|
|
1284
|
+
);
|
|
1285
|
+
}
|
|
1286
|
+
if (entry.namespace) {
|
|
1287
|
+
const fields = [];
|
|
1288
|
+
for (const member of entry.namespace.members) {
|
|
1289
|
+
const local = `__farm_package_reference_${next++}__`;
|
|
1290
|
+
lines.push(`import { ${member} as ${local} } from ${reference(entry.specifier, member)};`);
|
|
1291
|
+
fields.push(`${member}: ${local}`);
|
|
1292
|
+
}
|
|
1293
|
+
if (entry.namespace.values?.length) {
|
|
1294
|
+
const local = `__farm_package_values_${next++}__`;
|
|
1295
|
+
lines.push(`import * as ${local} from ${JSON.stringify(entry.specifier)};`);
|
|
1296
|
+
for (const value of entry.namespace.values) fields.push(`${value}: ${local}.${value}`);
|
|
1297
|
+
}
|
|
1298
|
+
lines.push(`const ${entry.namespace.local} = Object.freeze({ ${fields.join(", ")} });`);
|
|
1299
|
+
}
|
|
1300
|
+
output = output.slice(0, entry.start) + lines.join("\n") + output.slice(entry.end);
|
|
1301
|
+
}
|
|
1302
|
+
return changed ? output : null;
|
|
1303
|
+
}
|
|
1304
|
+
|
|
1305
|
+
// src/utils/package-client-boundary-cache.ts
|
|
1306
|
+
import { AsyncLocalStorage } from "async_hooks";
|
|
1307
|
+
import fs3 from "fs";
|
|
1308
|
+
import path3 from "path";
|
|
1309
|
+
var SCHEMA_VERSION = 2;
|
|
1310
|
+
var NODE_MODULES_SEGMENT = `${path3.sep}node_modules${path3.sep}`;
|
|
1311
|
+
var PackageInspectionTrace = class {
|
|
1312
|
+
constructor() {
|
|
1313
|
+
this.files = /* @__PURE__ */ new Set();
|
|
1314
|
+
this.stops = /* @__PURE__ */ new Set();
|
|
1315
|
+
this.fileStamps = [];
|
|
1316
|
+
this.directoryStamps = /* @__PURE__ */ new Map();
|
|
1317
|
+
}
|
|
1318
|
+
visit(file) {
|
|
1319
|
+
this.files.add(file);
|
|
1320
|
+
const directory = path3.dirname(file);
|
|
1321
|
+
if (!this.directoryStamps.has(directory)) {
|
|
1322
|
+
this.directoryStamps.set(directory, stampPackagePath(directory, "directory"));
|
|
1323
|
+
}
|
|
1324
|
+
this.fileStamps.push(stampPackagePath(file, "file"));
|
|
1325
|
+
}
|
|
1326
|
+
/** The inspection reached `file` after it was already visited. */
|
|
1327
|
+
stop(file) {
|
|
1328
|
+
if (!this.files.has(file)) this.stops.add(file);
|
|
1329
|
+
}
|
|
1330
|
+
toEntry(result) {
|
|
1331
|
+
const entry = {
|
|
1332
|
+
result: { ...result },
|
|
1333
|
+
files: Array.from(this.files),
|
|
1334
|
+
stops: Array.from(this.stops)
|
|
1335
|
+
};
|
|
1336
|
+
const files = this.fileStamps.filter((stamp) => stamp !== void 0);
|
|
1337
|
+
const directories = Array.from(this.directoryStamps.values()).filter(
|
|
1338
|
+
(stamp) => stamp !== void 0
|
|
1339
|
+
);
|
|
1340
|
+
if (files.length === this.fileStamps.length && directories.length === this.directoryStamps.size) {
|
|
1341
|
+
entry.stamps = { files, directories };
|
|
1342
|
+
}
|
|
1343
|
+
return entry;
|
|
1344
|
+
}
|
|
1345
|
+
};
|
|
1346
|
+
function stampPackagePath(target, kind) {
|
|
1347
|
+
if (!`${target}${path3.sep}`.includes(NODE_MODULES_SEGMENT)) return void 0;
|
|
1348
|
+
try {
|
|
1349
|
+
const stat = fs3.statSync(target, { throwIfNoEntry: false });
|
|
1350
|
+
if (!stat || (kind === "file" ? !stat.isFile() : !stat.isDirectory())) return void 0;
|
|
1351
|
+
return [target, stat.size, stat.mtimeMs, stat.ctimeMs];
|
|
1352
|
+
} catch {
|
|
1353
|
+
return void 0;
|
|
1354
|
+
}
|
|
1355
|
+
}
|
|
1356
|
+
var PackageClientBoundaryCache = class {
|
|
1357
|
+
constructor() {
|
|
1358
|
+
this.entries = /* @__PURE__ */ new Map();
|
|
1359
|
+
this.stored = /* @__PURE__ */ new Map();
|
|
1360
|
+
this.storedPaths = [];
|
|
1361
|
+
this.unchangedPaths = /* @__PURE__ */ new Map();
|
|
1362
|
+
this.dirty = false;
|
|
1363
|
+
}
|
|
1364
|
+
load(file) {
|
|
1365
|
+
this.file = file;
|
|
1366
|
+
const stored = readStoredCache(file);
|
|
1367
|
+
if (!stored) {
|
|
1368
|
+
this.dirty = true;
|
|
1369
|
+
return;
|
|
1370
|
+
}
|
|
1371
|
+
this.storedPaths = stored.paths;
|
|
1372
|
+
this.stored = new Map(Object.entries(stored.entries));
|
|
1373
|
+
}
|
|
1374
|
+
/** An inspection of `key` that applies to `visited`. */
|
|
1375
|
+
find(key, visited) {
|
|
1376
|
+
let entries = this.entries.get(key);
|
|
1377
|
+
const stored = this.stored.get(key);
|
|
1378
|
+
if (stored) {
|
|
1379
|
+
this.stored.delete(key);
|
|
1380
|
+
entries ?? (entries = []);
|
|
1381
|
+
this.entries.set(key, entries);
|
|
1382
|
+
for (const entry of stored) {
|
|
1383
|
+
const restored = this.restore(entry);
|
|
1384
|
+
if (restored) entries.push(restored);
|
|
1385
|
+
else this.dirty = true;
|
|
1386
|
+
}
|
|
1387
|
+
}
|
|
1388
|
+
return entries?.find(
|
|
1389
|
+
(entry) => entry.stops.every((file) => visited.has(file)) && !entry.files.some((file) => visited.has(file))
|
|
1390
|
+
);
|
|
1391
|
+
}
|
|
1392
|
+
add(key, entry) {
|
|
1393
|
+
const entries = this.entries.get(key);
|
|
1394
|
+
if (entries) entries.push(entry);
|
|
1395
|
+
else this.entries.set(key, [entry]);
|
|
1396
|
+
if (entry.stamps) this.dirty = true;
|
|
1397
|
+
}
|
|
1398
|
+
async persist() {
|
|
1399
|
+
const file = this.file;
|
|
1400
|
+
if (!file || !this.dirty && this.stored.size === 0) return;
|
|
1401
|
+
const paths = [];
|
|
1402
|
+
const pathIndexes = /* @__PURE__ */ new Map();
|
|
1403
|
+
const indexOf = (stamp) => {
|
|
1404
|
+
let index = pathIndexes.get(stamp[0]);
|
|
1405
|
+
if (index === void 0) {
|
|
1406
|
+
index = paths.push(stamp) - 1;
|
|
1407
|
+
pathIndexes.set(stamp[0], index);
|
|
1408
|
+
}
|
|
1409
|
+
return index;
|
|
1410
|
+
};
|
|
1411
|
+
const entries = {};
|
|
1412
|
+
for (const [key, variants] of this.entries) {
|
|
1413
|
+
const persisted = variants.flatMap(
|
|
1414
|
+
({ result, stops, stamps }) => stamps ? [
|
|
1415
|
+
{
|
|
1416
|
+
result,
|
|
1417
|
+
files: stamps.files.map(indexOf),
|
|
1418
|
+
directories: stamps.directories.map(indexOf),
|
|
1419
|
+
stops
|
|
1420
|
+
}
|
|
1421
|
+
] : []
|
|
1422
|
+
);
|
|
1423
|
+
if (persisted.length > 0) entries[key] = persisted;
|
|
1424
|
+
}
|
|
1425
|
+
const contents = JSON.stringify({
|
|
1426
|
+
schema: SCHEMA_VERSION,
|
|
1427
|
+
farm: FARM_VERSION,
|
|
1428
|
+
paths,
|
|
1429
|
+
entries
|
|
1430
|
+
});
|
|
1431
|
+
const temporary = `${file}.${process.pid}.${Date.now()}.tmp`;
|
|
1432
|
+
try {
|
|
1433
|
+
await fs3.promises.mkdir(path3.dirname(file), { recursive: true });
|
|
1434
|
+
await fs3.promises.writeFile(temporary, contents);
|
|
1435
|
+
await fs3.promises.rename(temporary, file);
|
|
1436
|
+
} catch {
|
|
1437
|
+
await fs3.promises.rm(temporary, { force: true }).catch(() => {
|
|
1438
|
+
});
|
|
1439
|
+
}
|
|
1440
|
+
}
|
|
1441
|
+
restore(entry) {
|
|
1442
|
+
const files = this.restoreStamps(entry.files, "file");
|
|
1443
|
+
const directories = this.restoreStamps(entry.directories, "directory");
|
|
1444
|
+
if (!files || !directories) return void 0;
|
|
1445
|
+
return {
|
|
1446
|
+
result: entry.result,
|
|
1447
|
+
files: files.map(([file]) => file),
|
|
1448
|
+
stops: entry.stops,
|
|
1449
|
+
stamps: { files, directories }
|
|
1450
|
+
};
|
|
1451
|
+
}
|
|
1452
|
+
restoreStamps(indexes, kind) {
|
|
1453
|
+
const stamps = [];
|
|
1454
|
+
for (const index of indexes) {
|
|
1455
|
+
const stamp = this.storedPaths[index];
|
|
1456
|
+
let unchanged = this.unchangedPaths.get(index);
|
|
1457
|
+
if (unchanged === void 0) {
|
|
1458
|
+
const current = stampPackagePath(stamp[0], kind);
|
|
1459
|
+
unchanged = current !== void 0 && current[1] === stamp[1] && current[2] === stamp[2] && current[3] === stamp[3];
|
|
1460
|
+
this.unchangedPaths.set(index, unchanged);
|
|
1461
|
+
}
|
|
1462
|
+
if (!unchanged) return void 0;
|
|
1463
|
+
stamps.push(stamp);
|
|
1464
|
+
}
|
|
1465
|
+
return stamps;
|
|
1466
|
+
}
|
|
1467
|
+
};
|
|
1468
|
+
function readStoredCache(file) {
|
|
1469
|
+
let value;
|
|
1470
|
+
try {
|
|
1471
|
+
value = JSON.parse(fs3.readFileSync(file, "utf8"));
|
|
1472
|
+
} catch {
|
|
1473
|
+
return null;
|
|
1474
|
+
}
|
|
1475
|
+
if (!isRecord(value) || value.schema !== SCHEMA_VERSION || value.farm !== FARM_VERSION) {
|
|
1476
|
+
return null;
|
|
1477
|
+
}
|
|
1478
|
+
const { paths, entries } = value;
|
|
1479
|
+
if (!Array.isArray(paths) || !paths.every(isPathStamp) || !isRecord(entries)) return null;
|
|
1480
|
+
const valid = {};
|
|
1481
|
+
for (const [key, variants] of Object.entries(entries)) {
|
|
1482
|
+
if (!Array.isArray(variants)) continue;
|
|
1483
|
+
const usable = variants.filter((entry) => isStoredEntry(entry, paths.length));
|
|
1484
|
+
if (usable.length > 0) valid[key] = usable;
|
|
1485
|
+
}
|
|
1486
|
+
return { schema: SCHEMA_VERSION, farm: FARM_VERSION, paths, entries: valid };
|
|
1487
|
+
}
|
|
1488
|
+
function isRecord(value) {
|
|
1489
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1490
|
+
}
|
|
1491
|
+
function isPathStamp(value) {
|
|
1492
|
+
return Array.isArray(value) && value.length === 4 && typeof value[0] === "string" && path3.isAbsolute(value[0]) && value.slice(1).every((part) => typeof part === "number" && Number.isFinite(part));
|
|
1493
|
+
}
|
|
1494
|
+
function isPathIndexList(value, pathCount) {
|
|
1495
|
+
return Array.isArray(value) && value.length > 0 && value.every((index) => Number.isSafeInteger(index) && index >= 0 && index < pathCount);
|
|
1496
|
+
}
|
|
1497
|
+
function isStoredEntry(value, pathCount) {
|
|
1498
|
+
if (!isRecord(value) || !isRecord(value.result)) return false;
|
|
1499
|
+
const { isClientComponent, shouldHydrate, islandStrategy } = value.result;
|
|
1500
|
+
return isPathIndexList(value.files, pathCount) && isPathIndexList(value.directories, pathCount) && Array.isArray(value.stops) && value.stops.every((file) => typeof file === "string" && path3.isAbsolute(file)) && typeof isClientComponent === "boolean" && typeof shouldHydrate === "boolean" && (islandStrategy === null || isFarmIslandStrategy(islandStrategy)) && Object.keys(value.result).length === 3;
|
|
1501
|
+
}
|
|
1502
|
+
var STORAGE_KEY = /* @__PURE__ */ Symbol.for("@farm.js/core/package-client-boundary-cache");
|
|
1503
|
+
function getStorage() {
|
|
1504
|
+
const runtime = globalThis;
|
|
1505
|
+
const existing = runtime[STORAGE_KEY];
|
|
1506
|
+
if (existing instanceof AsyncLocalStorage) {
|
|
1507
|
+
return existing;
|
|
1508
|
+
}
|
|
1509
|
+
const storage = new AsyncLocalStorage();
|
|
1510
|
+
runtime[STORAGE_KEY] = storage;
|
|
1511
|
+
return storage;
|
|
1512
|
+
}
|
|
1513
|
+
function getPackageClientBoundaryCache() {
|
|
1514
|
+
return getStorage().getStore();
|
|
1515
|
+
}
|
|
1516
|
+
async function withPackageClientBoundaryCache(operation) {
|
|
1517
|
+
const cache2 = new PackageClientBoundaryCache();
|
|
1518
|
+
try {
|
|
1519
|
+
return await getStorage().run(cache2, operation);
|
|
1520
|
+
} finally {
|
|
1521
|
+
await cache2.persist();
|
|
1522
|
+
}
|
|
1523
|
+
}
|
|
1524
|
+
function usePackageClientBoundaryCacheFile(file) {
|
|
1525
|
+
getPackageClientBoundaryCache()?.load(file);
|
|
1526
|
+
}
|
|
1527
|
+
|
|
1528
|
+
// src/utils/client-component.ts
|
|
1529
|
+
function readIfExists(filePath) {
|
|
1530
|
+
try {
|
|
1531
|
+
if (!filePath || !fs4.existsSync(filePath)) {
|
|
1532
|
+
return null;
|
|
1533
|
+
}
|
|
1534
|
+
return fs4.readFileSync(filePath, "utf-8");
|
|
1535
|
+
} catch {
|
|
1536
|
+
return null;
|
|
1537
|
+
}
|
|
1538
|
+
}
|
|
1539
|
+
function resolveModuleSourcePath(modulePath, root) {
|
|
1540
|
+
const candidates = /* @__PURE__ */ new Set();
|
|
1541
|
+
const withoutQuery = modulePath.split("?")[0];
|
|
1542
|
+
if (modulePath) {
|
|
1543
|
+
candidates.add(modulePath);
|
|
1544
|
+
candidates.add(withoutQuery);
|
|
1545
|
+
if (modulePath.startsWith("file://")) {
|
|
1546
|
+
try {
|
|
1547
|
+
candidates.add(fileURLToPath2(modulePath));
|
|
1548
|
+
} catch {
|
|
1549
|
+
}
|
|
1550
|
+
}
|
|
1551
|
+
if (modulePath.startsWith("/@fs/")) {
|
|
1552
|
+
const fsPath = withoutQuery.slice("/@fs/".length);
|
|
1553
|
+
candidates.add(path4.normalize(/^[A-Za-z]:/.test(fsPath) ? fsPath : `/${fsPath}`));
|
|
1554
|
+
}
|
|
1555
|
+
}
|
|
1556
|
+
if (root && modulePath) {
|
|
1557
|
+
const normalized = withoutQuery.replace(/^\/+/, "");
|
|
1558
|
+
candidates.add(path4.join(root, normalized));
|
|
1559
|
+
candidates.add(path4.resolve(root, normalized));
|
|
1560
|
+
}
|
|
1561
|
+
if (withoutQuery?.startsWith("/src/")) {
|
|
1562
|
+
const normalized = withoutQuery.replace(/^\/+/, "");
|
|
1563
|
+
candidates.add(path4.join(process.cwd(), normalized));
|
|
1564
|
+
candidates.add(path4.resolve(process.cwd(), normalized));
|
|
1565
|
+
}
|
|
1566
|
+
for (const candidate of candidates) {
|
|
1567
|
+
if (fs4.existsSync(candidate)) {
|
|
1568
|
+
return candidate;
|
|
1569
|
+
}
|
|
1570
|
+
}
|
|
1571
|
+
return null;
|
|
1572
|
+
}
|
|
1573
|
+
function getFarmClientHydrationPlanOptions(renderer, hasUnsupportedIntegrationProvider) {
|
|
1574
|
+
return { asyncOwnerIslands: isReactRenderer(renderer) && !hasUnsupportedIntegrationProvider };
|
|
1575
|
+
}
|
|
1576
|
+
function describeSuppressedAsyncHydration(subject, reason) {
|
|
1577
|
+
const remediation = reason ? "Fix the reason above, or render the interactive UI from a synchronous owner." : 'Move the interactive UI into an eligible "use client" boundary, or render it from a synchronous owner.';
|
|
1578
|
+
return `${subject} is an async server component with client-side hydration enabled. React cannot hydrate an async component, and that hydration could not be moved to isolated islands${reason ? ` (${reason})` : ""}, so it stays server-rendered without client-side interactivity. ${remediation}`;
|
|
1579
|
+
}
|
|
1580
|
+
var FARM_ISOLATED_HYDRATION_MAX_BOUNDARIES = 4;
|
|
1581
|
+
function isolatedHydrationBoundaryLimit() {
|
|
1582
|
+
const benchmarkRoot = process.env.FARM_INTERNAL_ISOLATED_HYDRATION_BENCHMARK_ROOT;
|
|
1583
|
+
const benchmarkLimit = Number(process.env.FARM_INTERNAL_ISOLATED_HYDRATION_BENCHMARK_LIMIT);
|
|
1584
|
+
const resolvedBenchmarkRoot = benchmarkRoot ? path4.resolve(benchmarkRoot) : null;
|
|
1585
|
+
const isBenchmarkFixture = process.env.FARM_INTERNAL_BENCHMARK === "isolated-hydration" && resolvedBenchmarkRoot !== null && (process.cwd() === resolvedBenchmarkRoot || process.cwd().startsWith(`${resolvedBenchmarkRoot}${path4.sep}`));
|
|
1586
|
+
return isBenchmarkFixture && Number.isSafeInteger(benchmarkLimit) && benchmarkLimit > FARM_ISOLATED_HYDRATION_MAX_BOUNDARIES ? benchmarkLimit : FARM_ISOLATED_HYDRATION_MAX_BOUNDARIES;
|
|
1587
|
+
}
|
|
1588
|
+
var RESOLVABLE_SOURCE_EXTENSIONS = [
|
|
1589
|
+
".svelte",
|
|
1590
|
+
".vue",
|
|
1591
|
+
".tsx",
|
|
1592
|
+
".ts",
|
|
1593
|
+
".jsx",
|
|
1594
|
+
".js",
|
|
1595
|
+
".mts",
|
|
1596
|
+
".mjs",
|
|
1597
|
+
".cts",
|
|
1598
|
+
".cjs"
|
|
1599
|
+
];
|
|
1600
|
+
function resolveFarmIsolatedClientHydrationMode(mode, options = {}) {
|
|
1601
|
+
if (options.serverComponents) return "off";
|
|
1602
|
+
if (mode === "enabled" && options.hasUnsupportedIntegrationProvider) return "off";
|
|
1603
|
+
return mode ?? "off";
|
|
1604
|
+
}
|
|
1605
|
+
function hasUseClientDirective(content) {
|
|
1606
|
+
if (!content) {
|
|
1607
|
+
return false;
|
|
1608
|
+
}
|
|
1609
|
+
const normalized = content.trimStart();
|
|
1610
|
+
if (normalized.startsWith("'use client'") || normalized.startsWith('"use client"')) {
|
|
1611
|
+
return true;
|
|
1612
|
+
}
|
|
1613
|
+
if (!normalized.includes("use client")) {
|
|
1614
|
+
return false;
|
|
1615
|
+
}
|
|
1616
|
+
for (const token of tokenizeModuleSource(content)) {
|
|
1617
|
+
if (token.kind === "string") {
|
|
1618
|
+
if (token.value === "use client") {
|
|
1619
|
+
return true;
|
|
1620
|
+
}
|
|
1621
|
+
continue;
|
|
1622
|
+
}
|
|
1623
|
+
if (token.kind === "punctuation" && token.value === ";") {
|
|
1624
|
+
continue;
|
|
1625
|
+
}
|
|
1626
|
+
return false;
|
|
1627
|
+
}
|
|
1628
|
+
return false;
|
|
1629
|
+
}
|
|
1630
|
+
function hasHydrateExport(content) {
|
|
1631
|
+
if (!content) {
|
|
1632
|
+
return false;
|
|
1633
|
+
}
|
|
1634
|
+
if (/\bexport\s+const\s+hydrate\s*=\s*true\b/.test(content)) {
|
|
1635
|
+
return true;
|
|
1636
|
+
}
|
|
1637
|
+
for (const match of content.matchAll(/\bexport\s*\{([^}]*)\}/g)) {
|
|
1638
|
+
for (const specifier of match[1].split(",")) {
|
|
1639
|
+
const parts = specifier.trim().split(/\s+as\s+/);
|
|
1640
|
+
const exportedName2 = (parts[1] ?? parts[0])?.trim();
|
|
1641
|
+
if (exportedName2 === "hydrate") {
|
|
1642
|
+
return true;
|
|
1643
|
+
}
|
|
1644
|
+
}
|
|
1645
|
+
}
|
|
1646
|
+
return false;
|
|
1647
|
+
}
|
|
1648
|
+
var REGEXP_PREFIX_PUNCTUATION = /* @__PURE__ */ new Set([
|
|
1649
|
+
"(",
|
|
1650
|
+
"[",
|
|
1651
|
+
"{",
|
|
1652
|
+
",",
|
|
1653
|
+
";",
|
|
1654
|
+
":",
|
|
1655
|
+
"=",
|
|
1656
|
+
"!",
|
|
1657
|
+
"?",
|
|
1658
|
+
"&",
|
|
1659
|
+
"|",
|
|
1660
|
+
"+",
|
|
1661
|
+
"-",
|
|
1662
|
+
"*",
|
|
1663
|
+
"%",
|
|
1664
|
+
"^",
|
|
1665
|
+
"~",
|
|
1666
|
+
">"
|
|
1667
|
+
]);
|
|
1668
|
+
var REGEXP_PREFIX_KEYWORDS = /* @__PURE__ */ new Set([
|
|
1669
|
+
"await",
|
|
1670
|
+
"case",
|
|
1671
|
+
"delete",
|
|
1672
|
+
"do",
|
|
1673
|
+
"else",
|
|
1674
|
+
"in",
|
|
1675
|
+
"instanceof",
|
|
1676
|
+
"new",
|
|
1677
|
+
"of",
|
|
1678
|
+
"return",
|
|
1679
|
+
"throw",
|
|
1680
|
+
"typeof",
|
|
1681
|
+
"void",
|
|
1682
|
+
"yield"
|
|
1683
|
+
]);
|
|
1684
|
+
function canStartRegularExpression(previous) {
|
|
1685
|
+
if (!previous) return true;
|
|
1686
|
+
return previous.kind === "identifier" ? REGEXP_PREFIX_KEYWORDS.has(previous.value) : REGEXP_PREFIX_PUNCTUATION.has(previous.value);
|
|
1687
|
+
}
|
|
1688
|
+
function skipRegularExpression(content, startIndex) {
|
|
1689
|
+
let index = startIndex + 1;
|
|
1690
|
+
let inCharacterClass = false;
|
|
1691
|
+
while (index < content.length) {
|
|
1692
|
+
const character = content[index];
|
|
1693
|
+
if (character === "\n" || character === "\r") return null;
|
|
1694
|
+
if (character === "\\") {
|
|
1695
|
+
index += 2;
|
|
1696
|
+
continue;
|
|
1697
|
+
}
|
|
1698
|
+
if (character === "[") {
|
|
1699
|
+
inCharacterClass = true;
|
|
1700
|
+
index++;
|
|
1701
|
+
continue;
|
|
1702
|
+
}
|
|
1703
|
+
if (character === "]" && inCharacterClass) {
|
|
1704
|
+
inCharacterClass = false;
|
|
1705
|
+
index++;
|
|
1706
|
+
continue;
|
|
1707
|
+
}
|
|
1708
|
+
if (character === "/" && !inCharacterClass) {
|
|
1709
|
+
index++;
|
|
1710
|
+
while (index < content.length && /[A-Za-z]/.test(content[index])) index++;
|
|
1711
|
+
return index;
|
|
1712
|
+
}
|
|
1713
|
+
index++;
|
|
1714
|
+
}
|
|
1715
|
+
return null;
|
|
1716
|
+
}
|
|
1717
|
+
function tokenizeModuleSource(content) {
|
|
1718
|
+
const tokens = [];
|
|
1719
|
+
let index = 0;
|
|
1720
|
+
let line = 1;
|
|
1721
|
+
while (index < content.length) {
|
|
1722
|
+
const character = content[index];
|
|
1723
|
+
if (/\s/.test(character)) {
|
|
1724
|
+
if (character === "\n") line++;
|
|
1725
|
+
index++;
|
|
1726
|
+
continue;
|
|
1727
|
+
}
|
|
1728
|
+
if (character === "/" && content[index + 1] === "/") {
|
|
1729
|
+
index += 2;
|
|
1730
|
+
while (index < content.length && content[index] !== "\n") index++;
|
|
1731
|
+
continue;
|
|
1732
|
+
}
|
|
1733
|
+
if (character === "/" && content[index + 1] === "*") {
|
|
1734
|
+
index += 2;
|
|
1735
|
+
while (index < content.length) {
|
|
1736
|
+
if (content[index] === "\n") line++;
|
|
1737
|
+
if (content[index] === "*" && content[index + 1] === "/") {
|
|
1738
|
+
index += 2;
|
|
1739
|
+
break;
|
|
1740
|
+
}
|
|
1741
|
+
index++;
|
|
1742
|
+
}
|
|
1743
|
+
continue;
|
|
1744
|
+
}
|
|
1745
|
+
if (character === "/" && canStartRegularExpression(tokens[tokens.length - 1])) {
|
|
1746
|
+
const endIndex = skipRegularExpression(content, index);
|
|
1747
|
+
if (endIndex !== null) {
|
|
1748
|
+
index = endIndex;
|
|
1749
|
+
continue;
|
|
1750
|
+
}
|
|
1751
|
+
}
|
|
1752
|
+
if (character === '"' || character === "'") {
|
|
1753
|
+
const quote = character;
|
|
1754
|
+
const tokenLine = line;
|
|
1755
|
+
let value = "";
|
|
1756
|
+
index++;
|
|
1757
|
+
while (index < content.length) {
|
|
1758
|
+
const next = content[index];
|
|
1759
|
+
if (next === "\\") {
|
|
1760
|
+
value += next;
|
|
1761
|
+
if (index + 1 < content.length) value += content[index + 1];
|
|
1762
|
+
index += 2;
|
|
1763
|
+
continue;
|
|
1764
|
+
}
|
|
1765
|
+
if (next === quote) {
|
|
1766
|
+
index++;
|
|
1767
|
+
break;
|
|
1768
|
+
}
|
|
1769
|
+
if (next === "\n") line++;
|
|
1770
|
+
value += next;
|
|
1771
|
+
index++;
|
|
1772
|
+
}
|
|
1773
|
+
tokens.push({ kind: "string", value, line: tokenLine });
|
|
1774
|
+
continue;
|
|
1775
|
+
}
|
|
1776
|
+
if (character === "`") {
|
|
1777
|
+
index++;
|
|
1778
|
+
while (index < content.length) {
|
|
1779
|
+
const next = content[index];
|
|
1780
|
+
if (next === "\\") {
|
|
1781
|
+
index += 2;
|
|
1782
|
+
continue;
|
|
1783
|
+
}
|
|
1784
|
+
if (next === "`") {
|
|
1785
|
+
index++;
|
|
1786
|
+
break;
|
|
1787
|
+
}
|
|
1788
|
+
if (next === "\n") line++;
|
|
1789
|
+
index++;
|
|
1790
|
+
}
|
|
1791
|
+
continue;
|
|
1792
|
+
}
|
|
1793
|
+
if (/[A-Za-z_$]/.test(character)) {
|
|
1794
|
+
const start = index++;
|
|
1795
|
+
while (index < content.length && /[\w$]/.test(content[index])) index++;
|
|
1796
|
+
tokens.push({ kind: "identifier", value: content.slice(start, index), line });
|
|
1797
|
+
continue;
|
|
1798
|
+
}
|
|
1799
|
+
tokens.push({ kind: "punctuation", value: character, line });
|
|
1800
|
+
index++;
|
|
1801
|
+
}
|
|
1802
|
+
return tokens;
|
|
1803
|
+
}
|
|
1804
|
+
function isIslandExportStart(tokens, index) {
|
|
1805
|
+
const token = tokens[index];
|
|
1806
|
+
const previous = tokens[index - 1];
|
|
1807
|
+
const startsStatement = !previous || previous.value === ";" || previous.value === "{" || previous.value === "}" || token.line > previous.line;
|
|
1808
|
+
return startsStatement && token.value === "export" && tokens[index + 1]?.value === "const" && tokens[index + 2]?.value === "island";
|
|
1809
|
+
}
|
|
1810
|
+
function getIslandStrategyExport(content) {
|
|
1811
|
+
if (!content) return null;
|
|
1812
|
+
const tokens = tokenizeModuleSource(content);
|
|
1813
|
+
for (let index = 0; index < tokens.length - 2; index++) {
|
|
1814
|
+
if (!isIslandExportStart(tokens, index)) continue;
|
|
1815
|
+
let valueIndex = index + 3;
|
|
1816
|
+
if (tokens[valueIndex]?.value === ":") {
|
|
1817
|
+
while (valueIndex < tokens.length && tokens[valueIndex].value !== "=") valueIndex++;
|
|
1818
|
+
}
|
|
1819
|
+
if (tokens[valueIndex]?.value !== "=") break;
|
|
1820
|
+
valueIndex++;
|
|
1821
|
+
const literal = tokens[valueIndex];
|
|
1822
|
+
if (!literal || literal.kind !== "string" || !isFarmIslandStrategy(literal.value)) break;
|
|
1823
|
+
let trailingIndex = valueIndex + 1;
|
|
1824
|
+
if (tokens[trailingIndex]?.value === "as" && tokens[trailingIndex + 1]?.value === "const") {
|
|
1825
|
+
trailingIndex += 2;
|
|
1826
|
+
}
|
|
1827
|
+
const trailing = tokens[trailingIndex];
|
|
1828
|
+
if (trailing && trailing.value !== ";" && trailing.line === literal.line) break;
|
|
1829
|
+
return literal.value;
|
|
1830
|
+
}
|
|
1831
|
+
if (tokens.some((_token, index) => isIslandExportStart(tokens, index))) {
|
|
1832
|
+
throw new Error(
|
|
1833
|
+
'Farm island configuration must be a static "load", "interaction", "visible", or "idle" string literal.'
|
|
1834
|
+
);
|
|
1835
|
+
}
|
|
1836
|
+
return null;
|
|
1837
|
+
}
|
|
1838
|
+
function stripUseClientDirective(content) {
|
|
1839
|
+
return content.replace(
|
|
1840
|
+
/^((?:\s|\/\/[^\n]*(?:\n|$)|\/\*[\s\S]*?\*\/|(?:"[^"\n]*"|'[^'\n]*')\s*;?)*)(["'])use client\2\s*;?\s*/,
|
|
1841
|
+
(match, prefix) => prefix + match.slice(prefix.length).replace(/[^\r\n]/g, " ")
|
|
1842
|
+
);
|
|
1843
|
+
}
|
|
1844
|
+
function hasAsyncDefaultExport(content) {
|
|
1845
|
+
if (!content) return false;
|
|
1846
|
+
const tokens = tokenizeModuleSource(content);
|
|
1847
|
+
for (let index = 0; index < tokens.length - 2; index++) {
|
|
1848
|
+
const token = tokens[index];
|
|
1849
|
+
if (token.kind !== "identifier" || token.value !== "export") continue;
|
|
1850
|
+
if (tokens[index - 1]?.value === ".") continue;
|
|
1851
|
+
if (tokens[index + 1]?.value !== "default") continue;
|
|
1852
|
+
const exported = tokens[index + 2];
|
|
1853
|
+
if (exported.kind === "identifier" && exported.value === "async") {
|
|
1854
|
+
return true;
|
|
1855
|
+
}
|
|
1856
|
+
if (exported.kind === "identifier" && !["function", "class"].includes(exported.value) && tokens[index + 3]?.value !== "(" && isAsyncLocalDeclaration(tokens, exported.value)) {
|
|
1857
|
+
return true;
|
|
1858
|
+
}
|
|
1859
|
+
}
|
|
1860
|
+
return false;
|
|
1861
|
+
}
|
|
1862
|
+
function isAsyncLocalDeclaration(tokens, name) {
|
|
1863
|
+
for (let index = 0; index < tokens.length - 2; index++) {
|
|
1864
|
+
if (tokens[index].value === "async" && tokens[index + 1]?.value === "function" && tokens[index + 2]?.value === name) {
|
|
1865
|
+
return true;
|
|
1866
|
+
}
|
|
1867
|
+
if (tokens[index].value === name && tokens[index + 1]?.value === "=" && tokens[index + 2]?.value === "async") {
|
|
1868
|
+
return true;
|
|
1869
|
+
}
|
|
1870
|
+
}
|
|
1871
|
+
return false;
|
|
1872
|
+
}
|
|
1873
|
+
function parseClientModuleMetadata(content, inspectIslandExport) {
|
|
1874
|
+
if (!content) {
|
|
1875
|
+
return {
|
|
1876
|
+
isClientComponent: false,
|
|
1877
|
+
hasHydrateExport: false,
|
|
1878
|
+
islandStrategy: null
|
|
1879
|
+
};
|
|
1880
|
+
}
|
|
1881
|
+
const isClientComponent = hasUseClientDirective(content);
|
|
1882
|
+
const hasHydrate = hasHydrateExport(content);
|
|
1883
|
+
return {
|
|
1884
|
+
isClientComponent,
|
|
1885
|
+
hasHydrateExport: hasHydrate,
|
|
1886
|
+
islandStrategy: inspectIslandExport || isClientComponent || hasHydrate ? getIslandStrategyExport(content) : null
|
|
1887
|
+
};
|
|
1888
|
+
}
|
|
1889
|
+
var DEFAULT_REEXPORT = /export\s*\{\s*default(?:\s+as\s+default)?\s*\}\s*from\s*(["'])([^"']+)\1/;
|
|
1890
|
+
function resolveDefaultReexport(ownerPath, content, root) {
|
|
1891
|
+
const match = content ? DEFAULT_REEXPORT.exec(content) : null;
|
|
1892
|
+
if (!match) return null;
|
|
1893
|
+
const imported = resolveImportedModule(ownerPath, match[2], root);
|
|
1894
|
+
return imported.local ? imported.path : null;
|
|
1895
|
+
}
|
|
1896
|
+
function resolveOwnerSourcePath(resolvedPath, root) {
|
|
1897
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1898
|
+
let current = resolvedPath;
|
|
1899
|
+
while (current && !seen.has(current)) {
|
|
1900
|
+
seen.add(current);
|
|
1901
|
+
const target = resolveDefaultReexport(current, readIfExists(current), root);
|
|
1902
|
+
if (!target) return current;
|
|
1903
|
+
current = target;
|
|
1904
|
+
}
|
|
1905
|
+
return current;
|
|
1906
|
+
}
|
|
1907
|
+
function collectFarmRenderedClientModules(modulePath, root) {
|
|
1908
|
+
const resolvedPath = resolveOwnerSourcePath(resolveModuleSourcePath(modulePath, root), root);
|
|
1909
|
+
if (!resolvedPath) return null;
|
|
1910
|
+
if (hasUseClientDirective(readIfExists(resolvedPath))) return [resolvedPath];
|
|
1911
|
+
const collected = collectIsolatedClientBoundaries(resolvedPath, root, {
|
|
1912
|
+
allowDynamicCardinality: true,
|
|
1913
|
+
allowElementProps: true
|
|
1914
|
+
});
|
|
1915
|
+
if (collected.fallbackReason || collected.costGuardExceeded) return null;
|
|
1916
|
+
return collected.boundaries.map((boundary) => boundary.modulePath);
|
|
1917
|
+
}
|
|
1918
|
+
var SERVER_MODULE_SOURCE = /\.[cm]?[jt]sx?$/;
|
|
1919
|
+
var STYLESHEET_SOURCE = /\.(?:css|scss|sass|less|styl|stylus|pcss|postcss)$/;
|
|
1920
|
+
function collectFarmServerStylesheets(modulePaths, root) {
|
|
1921
|
+
const stylesheets = /* @__PURE__ */ new Set();
|
|
1922
|
+
const visited = /* @__PURE__ */ new Set();
|
|
1923
|
+
const visit = (file) => {
|
|
1924
|
+
if (visited.has(file) || !SERVER_MODULE_SOURCE.test(file)) return;
|
|
1925
|
+
visited.add(file);
|
|
1926
|
+
const content = readIfExists(file);
|
|
1927
|
+
if (!content || hasUseClientDirective(content)) return;
|
|
1928
|
+
for (const specifier of getImportSpecifiers(content)) {
|
|
1929
|
+
if (specifier.includes("?")) continue;
|
|
1930
|
+
const imported = resolveImportedModule(file, specifier, root);
|
|
1931
|
+
if (!imported.path) continue;
|
|
1932
|
+
if (STYLESHEET_SOURCE.test(imported.path)) stylesheets.add(imported.path);
|
|
1933
|
+
else if (imported.local) visit(imported.path);
|
|
1934
|
+
}
|
|
1935
|
+
};
|
|
1936
|
+
for (const modulePath of modulePaths) {
|
|
1937
|
+
const resolved = resolveOwnerSourcePath(resolveModuleSourcePath(modulePath, root), root);
|
|
1938
|
+
if (resolved) visit(resolved);
|
|
1939
|
+
}
|
|
1940
|
+
return [...stylesheets];
|
|
1941
|
+
}
|
|
1942
|
+
function getClientModuleMetadata(modulePath, root) {
|
|
1943
|
+
const resolvedPath = resolveModuleSourcePath(modulePath, root);
|
|
1944
|
+
return inspectClientModuleMetadata(resolvedPath, root, /* @__PURE__ */ new Set(), true);
|
|
1945
|
+
}
|
|
1946
|
+
function getClientModuleHydrationPlan(modulePath, root, mode = "off", options = {}) {
|
|
1947
|
+
const plan = planClientModuleHydration(modulePath, root, mode, options);
|
|
1948
|
+
if (options.serverTreeLayouts !== true || options.asyncOwnerIslands !== true || !plan.shouldHydrate || plan.isClientComponent || plan.asyncOwnerIslands) {
|
|
1949
|
+
return plan;
|
|
1950
|
+
}
|
|
1951
|
+
const resolvedPath = resolveOwnerSourcePath(resolveModuleSourcePath(modulePath, root), root);
|
|
1952
|
+
const owner = parseClientModuleMetadata(readIfExists(resolvedPath ?? ""), true);
|
|
1953
|
+
if (!resolvedPath || owner.isClientComponent || owner.hasHydrateExport) return plan;
|
|
1954
|
+
const layout = collectIsolatedClientBoundaries(resolvedPath, root, {
|
|
1955
|
+
allowDynamicCardinality: true,
|
|
1956
|
+
allowElementProps: true,
|
|
1957
|
+
packageReferences: true
|
|
1958
|
+
});
|
|
1959
|
+
const routeWide = {
|
|
1960
|
+
...plan,
|
|
1961
|
+
shouldHydrate: plan.legacyShouldHydrate,
|
|
1962
|
+
islandStrategy: plan.legacyIslandStrategy,
|
|
1963
|
+
hasIsolatedClientBoundaries: false,
|
|
1964
|
+
isolatedBoundaries: []
|
|
1965
|
+
};
|
|
1966
|
+
if (layout.fallbackReason) {
|
|
1967
|
+
return {
|
|
1968
|
+
...routeWide,
|
|
1969
|
+
shouldHydrate: false,
|
|
1970
|
+
islandStrategy: null,
|
|
1971
|
+
fallbackReason: layout.fallbackReason,
|
|
1972
|
+
islandsError: layout.fallbackHint ? `${layout.fallbackReason}. ${layout.fallbackHint}` : layout.fallbackReason
|
|
1973
|
+
};
|
|
1974
|
+
}
|
|
1975
|
+
const staticPackages = layout.staticPackages.length > 0 ? { staticPackageBoundaries: layout.staticPackages } : {};
|
|
1976
|
+
if (layout.boundaries.length === 0) {
|
|
1977
|
+
return { ...routeWide, shouldHydrate: false, islandStrategy: null, ...staticPackages };
|
|
1978
|
+
}
|
|
1979
|
+
return {
|
|
1980
|
+
...routeWide,
|
|
1981
|
+
serverTreeLayout: true,
|
|
1982
|
+
isolatedBoundaries: layout.boundaries,
|
|
1983
|
+
...staticPackages
|
|
1984
|
+
};
|
|
1985
|
+
}
|
|
1986
|
+
function planClientModuleHydration(modulePath, root, mode, options) {
|
|
1987
|
+
const metadata = getClientModuleMetadata(modulePath, root);
|
|
1988
|
+
const emptyPlan = (fallbackReason, costGuardExceeded = false, estimatedIsolatedRootCount = 0) => ({
|
|
1989
|
+
...metadata,
|
|
1990
|
+
mode,
|
|
1991
|
+
legacyShouldHydrate: metadata.shouldHydrate,
|
|
1992
|
+
legacyIslandStrategy: metadata.islandStrategy,
|
|
1993
|
+
estimatedIsolatedRootCount,
|
|
1994
|
+
isolatedHydrationEligible: false,
|
|
1995
|
+
hasIsolatedClientBoundaries: false,
|
|
1996
|
+
isolatedBoundaries: [],
|
|
1997
|
+
...costGuardExceeded ? { costGuardExceeded: true } : {},
|
|
1998
|
+
...fallbackReason ? { fallbackReason } : {}
|
|
1999
|
+
});
|
|
2000
|
+
const asyncOwner = (metadata.suppressedAsyncHydration === true || options.serverOwners === true) && options.asyncOwnerIslands === true;
|
|
2001
|
+
if (mode === "off" && !asyncOwner) return emptyPlan();
|
|
2002
|
+
const resolvedPath = resolveOwnerSourcePath(resolveModuleSourcePath(modulePath, root), root);
|
|
2003
|
+
const content = readIfExists(resolvedPath ?? "");
|
|
2004
|
+
const parsed = parseClientModuleMetadata(content, true);
|
|
2005
|
+
if (!resolvedPath) return emptyPlan("the owner source could not be resolved");
|
|
2006
|
+
if (parsed.isClientComponent) {
|
|
2007
|
+
return emptyPlan("the owner is already a client component");
|
|
2008
|
+
}
|
|
2009
|
+
if (parsed.hasHydrateExport) {
|
|
2010
|
+
return emptyPlan("the owner explicitly exports `hydrate = true`");
|
|
2011
|
+
}
|
|
2012
|
+
const inspection = collectIsolatedClientBoundaries(resolvedPath, root, {
|
|
2013
|
+
allowDynamicCardinality: asyncOwner,
|
|
2014
|
+
allowElementProps: asyncOwner,
|
|
2015
|
+
staticPackageBoundaries: asyncOwner,
|
|
2016
|
+
staticPackageLeaves: options.serverTreeLayouts === true && options.asyncOwnerIslands === true,
|
|
2017
|
+
// Islands mode: pages carry `serverOwners`, layouts `serverTreeLayouts`.
|
|
2018
|
+
packageReferences: options.serverOwners === true || options.serverTreeLayouts === true
|
|
2019
|
+
});
|
|
2020
|
+
if (inspection.fallbackReason && asyncOwner && options.serverOwners === true) {
|
|
2021
|
+
return {
|
|
2022
|
+
...emptyPlan(inspection.fallbackReason),
|
|
2023
|
+
shouldHydrate: false,
|
|
2024
|
+
islandStrategy: null,
|
|
2025
|
+
islandsError: inspection.fallbackHint ? `${inspection.fallbackReason}. ${inspection.fallbackHint}` : inspection.fallbackReason
|
|
2026
|
+
};
|
|
2027
|
+
}
|
|
2028
|
+
if (inspection.boundaries.length === 0) {
|
|
2029
|
+
return emptyPlan(inspection.fallbackReason);
|
|
2030
|
+
}
|
|
2031
|
+
if (inspection.fallbackReason) {
|
|
2032
|
+
return emptyPlan(
|
|
2033
|
+
inspection.fallbackReason,
|
|
2034
|
+
inspection.costGuardExceeded,
|
|
2035
|
+
inspection.estimatedBoundaryCount
|
|
2036
|
+
);
|
|
2037
|
+
}
|
|
2038
|
+
const boundaryLimit = isolatedHydrationBoundaryLimit();
|
|
2039
|
+
if (!asyncOwner && inspection.estimatedBoundaryCount > boundaryLimit) {
|
|
2040
|
+
return emptyPlan(
|
|
2041
|
+
`the client graph can create ${inspection.estimatedBoundaryCount} isolated roots, above the measured limit of ${boundaryLimit}`,
|
|
2042
|
+
true,
|
|
2043
|
+
inspection.estimatedBoundaryCount
|
|
2044
|
+
);
|
|
2045
|
+
}
|
|
2046
|
+
const enabled = mode === "enabled" || asyncOwner;
|
|
2047
|
+
const plan = {
|
|
2048
|
+
...metadata,
|
|
2049
|
+
shouldHydrate: enabled ? false : metadata.shouldHydrate,
|
|
2050
|
+
islandStrategy: enabled ? null : metadata.islandStrategy,
|
|
2051
|
+
mode,
|
|
2052
|
+
legacyShouldHydrate: metadata.shouldHydrate,
|
|
2053
|
+
legacyIslandStrategy: metadata.islandStrategy,
|
|
2054
|
+
estimatedIsolatedRootCount: inspection.estimatedBoundaryCount,
|
|
2055
|
+
isolatedHydrationEligible: true,
|
|
2056
|
+
hasIsolatedClientBoundaries: enabled,
|
|
2057
|
+
isolatedBoundaries: inspection.boundaries
|
|
2058
|
+
};
|
|
2059
|
+
if (asyncOwner) {
|
|
2060
|
+
delete plan.suppressedAsyncHydration;
|
|
2061
|
+
plan.asyncOwnerIslands = true;
|
|
2062
|
+
}
|
|
2063
|
+
if (inspection.staticPackages.length > 0)
|
|
2064
|
+
plan.staticPackageBoundaries = inspection.staticPackages;
|
|
2065
|
+
return plan;
|
|
2066
|
+
}
|
|
2067
|
+
function usesFarmServerTree(plan) {
|
|
2068
|
+
return plan?.asyncOwnerIslands === true && plan.isolatedBoundaries.length > 0 && plan.isolatedBoundaries.every((boundary) => boundary.islandStrategy === "load");
|
|
2069
|
+
}
|
|
2070
|
+
function getMarkdownPageHydrationPlan(componentsModulePath, root, mode = "off", options = {}) {
|
|
2071
|
+
const plan = {
|
|
2072
|
+
isClientComponent: false,
|
|
2073
|
+
shouldHydrate: false,
|
|
2074
|
+
islandStrategy: null,
|
|
2075
|
+
mode,
|
|
2076
|
+
legacyShouldHydrate: false,
|
|
2077
|
+
legacyIslandStrategy: null,
|
|
2078
|
+
estimatedIsolatedRootCount: 0,
|
|
2079
|
+
isolatedHydrationEligible: false,
|
|
2080
|
+
hasIsolatedClientBoundaries: false,
|
|
2081
|
+
isolatedBoundaries: []
|
|
2082
|
+
};
|
|
2083
|
+
if (!componentsModulePath || options.asyncOwnerIslands !== true) return plan;
|
|
2084
|
+
const resolvedPath = resolveModuleSourcePath(componentsModulePath, root);
|
|
2085
|
+
if (!resolvedPath) {
|
|
2086
|
+
return { ...plan, fallbackReason: "the MDX components module could not be resolved" };
|
|
2087
|
+
}
|
|
2088
|
+
const inspection = collectIsolatedClientBoundaries(resolvedPath, root, {
|
|
2089
|
+
allowDynamicCardinality: true,
|
|
2090
|
+
staticPackageBoundaries: true,
|
|
2091
|
+
packageReferences: options.packageReferences === true
|
|
2092
|
+
});
|
|
2093
|
+
if (inspection.fallbackReason) return { ...plan, fallbackReason: inspection.fallbackReason };
|
|
2094
|
+
if (inspection.staticPackages.length > 0)
|
|
2095
|
+
plan.staticPackageBoundaries = inspection.staticPackages;
|
|
2096
|
+
if (inspection.boundaries.length === 0) return plan;
|
|
2097
|
+
return {
|
|
2098
|
+
...plan,
|
|
2099
|
+
estimatedIsolatedRootCount: inspection.estimatedBoundaryCount,
|
|
2100
|
+
isolatedHydrationEligible: true,
|
|
2101
|
+
hasIsolatedClientBoundaries: true,
|
|
2102
|
+
isolatedBoundaries: inspection.boundaries,
|
|
2103
|
+
asyncOwnerIslands: true
|
|
2104
|
+
};
|
|
2105
|
+
}
|
|
2106
|
+
function createMarkdownPageHydrationPlanner(componentsModulePath, root, mode = "off", options = {}) {
|
|
2107
|
+
let plan;
|
|
2108
|
+
return () => ({
|
|
2109
|
+
...plan ?? (plan = getMarkdownPageHydrationPlan(componentsModulePath, root, mode, options))
|
|
2110
|
+
});
|
|
2111
|
+
}
|
|
2112
|
+
function restoreRouteWideHydration(metadata, fallbackReason) {
|
|
2113
|
+
metadata.shouldHydrate = metadata.legacyShouldHydrate;
|
|
2114
|
+
metadata.islandStrategy = metadata.legacyIslandStrategy;
|
|
2115
|
+
metadata.hasIsolatedClientBoundaries = false;
|
|
2116
|
+
metadata.isolatedBoundaries = [];
|
|
2117
|
+
if (metadata.asyncOwnerIslands) {
|
|
2118
|
+
delete metadata.asyncOwnerIslands;
|
|
2119
|
+
metadata.suppressedAsyncHydration = true;
|
|
2120
|
+
metadata.fallbackReason = fallbackReason ?? "a parent layout hydrates the whole route";
|
|
2121
|
+
return;
|
|
2122
|
+
}
|
|
2123
|
+
if (fallbackReason) {
|
|
2124
|
+
metadata.costGuardExceeded = true;
|
|
2125
|
+
metadata.fallbackReason = fallbackReason;
|
|
2126
|
+
}
|
|
2127
|
+
}
|
|
2128
|
+
function enforceFarmIsolatedHydrationRouteBudget(layouts, routes, layoutAppliesToRoute, options = {}) {
|
|
2129
|
+
const boundaryLimit = isolatedHydrationBoundaryLimit();
|
|
2130
|
+
const sortedLayouts = [...layouts].sort((left, right) => left.depth - right.depth);
|
|
2131
|
+
for (const route of options.serverOwners ? [] : routes) {
|
|
2132
|
+
if (route.metadata.mode !== "enabled") continue;
|
|
2133
|
+
const applicableLayouts = sortedLayouts.filter(
|
|
2134
|
+
(layout) => layoutAppliesToRoute(layout.pattern, route.pattern)
|
|
2135
|
+
);
|
|
2136
|
+
const layoutRootCount = applicableLayouts.reduce(
|
|
2137
|
+
(count, layout) => count + (layout.metadata.hasIsolatedClientBoundaries ? layout.metadata.estimatedIsolatedRootCount : 0),
|
|
2138
|
+
0
|
|
2139
|
+
);
|
|
2140
|
+
const routeRootCount = route.metadata.hasIsolatedClientBoundaries ? route.metadata.estimatedIsolatedRootCount : 0;
|
|
2141
|
+
const totalRootCount = layoutRootCount + routeRootCount;
|
|
2142
|
+
if (totalRootCount <= boundaryLimit) continue;
|
|
2143
|
+
const fallbackReason = `the matched route ${route.pattern} can create ${totalRootCount} isolated roots, above the measured limit of ${boundaryLimit}`;
|
|
2144
|
+
const remainingRootCount = () => applicableLayouts.reduce(
|
|
2145
|
+
(count, layout) => count + (layout.metadata.hasIsolatedClientBoundaries ? layout.metadata.estimatedIsolatedRootCount : 0),
|
|
2146
|
+
0
|
|
2147
|
+
) + (route.metadata.hasIsolatedClientBoundaries ? route.metadata.estimatedIsolatedRootCount : 0);
|
|
2148
|
+
while (remainingRootCount() > boundaryLimit) {
|
|
2149
|
+
let accumulatedLayoutRoots = 0;
|
|
2150
|
+
const overflowingLayout = applicableLayouts.find((layout) => {
|
|
2151
|
+
if (layout.metadata.hasIsolatedClientBoundaries) {
|
|
2152
|
+
accumulatedLayoutRoots += layout.metadata.estimatedIsolatedRootCount;
|
|
2153
|
+
}
|
|
2154
|
+
return accumulatedLayoutRoots > boundaryLimit;
|
|
2155
|
+
});
|
|
2156
|
+
if (overflowingLayout) {
|
|
2157
|
+
restoreRouteWideHydration(overflowingLayout.metadata, fallbackReason);
|
|
2158
|
+
continue;
|
|
2159
|
+
}
|
|
2160
|
+
if (route.metadata.hasIsolatedClientBoundaries) {
|
|
2161
|
+
restoreRouteWideHydration(route.metadata, fallbackReason);
|
|
2162
|
+
continue;
|
|
2163
|
+
}
|
|
2164
|
+
break;
|
|
2165
|
+
}
|
|
2166
|
+
}
|
|
2167
|
+
for (const layout of sortedLayouts) {
|
|
2168
|
+
const hasRouteWideAncestor = sortedLayouts.some(
|
|
2169
|
+
(ancestor) => ancestor !== layout && ancestor.depth < layout.depth && ancestor.metadata.shouldHydrate && layoutAppliesToRoute(ancestor.pattern, layout.pattern)
|
|
2170
|
+
);
|
|
2171
|
+
if (hasRouteWideAncestor && layout.metadata.hasIsolatedClientBoundaries) {
|
|
2172
|
+
restoreRouteWideHydration(layout.metadata);
|
|
2173
|
+
}
|
|
2174
|
+
}
|
|
2175
|
+
}
|
|
2176
|
+
function isIsolatableClientBoundarySource(content) {
|
|
2177
|
+
if (!content || !hasUseClientDirective(content)) return false;
|
|
2178
|
+
if (content.includes(FARM_CLIENT_REFERENCE_PRAGMA)) return true;
|
|
2179
|
+
if (/\bexport\s*\*/.test(content)) return false;
|
|
2180
|
+
return /\bexport\s+default\s+(?!(?:type|interface)\b)/.test(content) || /\bexport\s+(?:async\s+)?function\s+[A-Z][$\w]*/.test(content) || /\bexport\s+(?:const|let|var|class)\s+[A-Z][$\w]*/.test(content) || exportListNames(content).some((name) => name === "default" || /^[A-Z]/.test(name));
|
|
2181
|
+
}
|
|
2182
|
+
function exportListNames(content) {
|
|
2183
|
+
const names = [];
|
|
2184
|
+
for (const match of content.matchAll(/\bexport\s*(type\s*)?\{([^}]*)\}/g)) {
|
|
2185
|
+
if (match[1]) continue;
|
|
2186
|
+
for (const entry of match[2].split(",")) {
|
|
2187
|
+
const parts = entry.trim().split(/\s+/);
|
|
2188
|
+
if (parts[0] === "type" || !parts[0]) continue;
|
|
2189
|
+
names.push(parts[parts.length - 1].replace(/^["']|["']$/g, ""));
|
|
2190
|
+
}
|
|
2191
|
+
}
|
|
2192
|
+
return names;
|
|
2193
|
+
}
|
|
2194
|
+
function getStaticImportBindings(content) {
|
|
2195
|
+
const bindings = /* @__PURE__ */ new Map();
|
|
2196
|
+
if (!content) return bindings;
|
|
2197
|
+
const tokens = tokenizeModuleSource(content);
|
|
2198
|
+
for (let index = 0; index < tokens.length; index++) {
|
|
2199
|
+
if (tokens[index].value !== "import" || tokens[index - 1]?.value === ".") continue;
|
|
2200
|
+
const first = tokens[index + 1];
|
|
2201
|
+
if (!first || first.value === "type" || first.value === "(" || first.kind === "string") {
|
|
2202
|
+
continue;
|
|
2203
|
+
}
|
|
2204
|
+
let fromIndex = -1;
|
|
2205
|
+
for (let cursor = index + 1; cursor < tokens.length; cursor++) {
|
|
2206
|
+
if (tokens[cursor].value === ";") break;
|
|
2207
|
+
if (tokens[cursor].value === "from" && tokens[cursor + 1]?.kind === "string") {
|
|
2208
|
+
fromIndex = cursor;
|
|
2209
|
+
break;
|
|
2210
|
+
}
|
|
2211
|
+
}
|
|
2212
|
+
if (fromIndex === -1) continue;
|
|
2213
|
+
const specifier = tokens[fromIndex + 1].value;
|
|
2214
|
+
const clause = tokens.slice(index + 1, fromIndex);
|
|
2215
|
+
const localNames = [];
|
|
2216
|
+
if (clause[0]?.kind === "identifier" && clause[0].value !== "type") {
|
|
2217
|
+
localNames.push(clause[0].value);
|
|
2218
|
+
}
|
|
2219
|
+
const namespaceAs = clause.findIndex(
|
|
2220
|
+
(token, clauseIndex) => token.value === "*" && clause[clauseIndex + 1]?.value === "as"
|
|
2221
|
+
);
|
|
2222
|
+
if (namespaceAs !== -1 && clause[namespaceAs + 2]?.kind === "identifier") {
|
|
2223
|
+
localNames.push(clause[namespaceAs + 2].value);
|
|
2224
|
+
}
|
|
2225
|
+
const openingBrace = clause.findIndex((token) => token.value === "{");
|
|
2226
|
+
const closingBrace = clause.findIndex(
|
|
2227
|
+
(token, clauseIndex) => clauseIndex > openingBrace && token.value === "}"
|
|
2228
|
+
);
|
|
2229
|
+
if (openingBrace !== -1 && closingBrace !== -1) {
|
|
2230
|
+
let entryStart = openingBrace + 1;
|
|
2231
|
+
for (let cursor = entryStart; cursor <= closingBrace; cursor++) {
|
|
2232
|
+
if (cursor !== closingBrace && clause[cursor]?.value !== ",") continue;
|
|
2233
|
+
const entry = clause.slice(entryStart, cursor).filter((token) => token.value !== "type");
|
|
2234
|
+
const asIndex = entry.findIndex((token) => token.value === "as");
|
|
2235
|
+
const local = asIndex === -1 ? entry[0] : entry[asIndex + 1];
|
|
2236
|
+
if (local?.kind === "identifier") localNames.push(local.value);
|
|
2237
|
+
entryStart = cursor + 1;
|
|
2238
|
+
}
|
|
2239
|
+
}
|
|
2240
|
+
bindings.set(
|
|
2241
|
+
specifier,
|
|
2242
|
+
Array.from(/* @__PURE__ */ new Set([...bindings.get(specifier) ?? [], ...localNames]))
|
|
2243
|
+
);
|
|
2244
|
+
}
|
|
2245
|
+
return bindings;
|
|
2246
|
+
}
|
|
2247
|
+
var PARSER_SENSITIVE_JSX_CONTAINERS = /* @__PURE__ */ new Set([
|
|
2248
|
+
"table",
|
|
2249
|
+
"thead",
|
|
2250
|
+
"tbody",
|
|
2251
|
+
"tfoot",
|
|
2252
|
+
"tr",
|
|
2253
|
+
"select",
|
|
2254
|
+
"optgroup",
|
|
2255
|
+
"svg"
|
|
2256
|
+
]);
|
|
2257
|
+
var PARSER_FLOW_CONTENT_ELEMENTS = /* @__PURE__ */ new Set(["td", "th", "caption", "foreignObject"]);
|
|
2258
|
+
var PARSER_SENSITIVE_FLOW_HINTS = {
|
|
2259
|
+
table: ", or render it inside a <td>, <th> or <caption>",
|
|
2260
|
+
thead: ", or render it inside a <td> or <th>",
|
|
2261
|
+
tbody: ", or render it inside a <td> or <th>",
|
|
2262
|
+
tfoot: ", or render it inside a <td> or <th>",
|
|
2263
|
+
tr: ", or render it inside a <td> or <th>",
|
|
2264
|
+
svg: ", or render it inside a <foreignObject>"
|
|
2265
|
+
};
|
|
2266
|
+
function findParserSensitiveJsxContainer(content, localBindings) {
|
|
2267
|
+
if (!content || localBindings.length === 0) return void 0;
|
|
2268
|
+
const names = new Set(localBindings);
|
|
2269
|
+
const tokens = tokenizeModuleSource(content);
|
|
2270
|
+
const open = [];
|
|
2271
|
+
const isSelfClosing = (openingIndex) => {
|
|
2272
|
+
for (let index = openingIndex; index < tokens.length; index++) {
|
|
2273
|
+
if (tokens[index].value === ">") return tokens[index - 1]?.value === "/";
|
|
2274
|
+
}
|
|
2275
|
+
return false;
|
|
2276
|
+
};
|
|
2277
|
+
for (let index = 0; index < tokens.length - 1; index++) {
|
|
2278
|
+
if (tokens[index].value !== "<") continue;
|
|
2279
|
+
if (tokens[index + 1].value === "/") {
|
|
2280
|
+
const closing = tokens[index + 2]?.value;
|
|
2281
|
+
const at = closing ? open.lastIndexOf(closing) : -1;
|
|
2282
|
+
if (at !== -1) open.length = at;
|
|
2283
|
+
continue;
|
|
2284
|
+
}
|
|
2285
|
+
const tag = tokens[index + 1].value;
|
|
2286
|
+
if (names.has(tag)) {
|
|
2287
|
+
let container;
|
|
2288
|
+
for (let depth = open.length - 1; depth >= 0; depth--) {
|
|
2289
|
+
if (PARSER_FLOW_CONTENT_ELEMENTS.has(open[depth])) break;
|
|
2290
|
+
container = open[depth];
|
|
2291
|
+
}
|
|
2292
|
+
if (container) return container;
|
|
2293
|
+
continue;
|
|
2294
|
+
}
|
|
2295
|
+
if ((PARSER_SENSITIVE_JSX_CONTAINERS.has(tag) || open.length > 0 && PARSER_FLOW_CONTENT_ELEMENTS.has(tag)) && !isSelfClosing(index)) {
|
|
2296
|
+
open.push(tag);
|
|
2297
|
+
}
|
|
2298
|
+
}
|
|
2299
|
+
return void 0;
|
|
2300
|
+
}
|
|
2301
|
+
function countStaticJsxUses(content, localBindings) {
|
|
2302
|
+
if (!content || localBindings.length === 0) return 0;
|
|
2303
|
+
const names = new Set(localBindings);
|
|
2304
|
+
const tokens = tokenizeModuleSource(content);
|
|
2305
|
+
let count = 0;
|
|
2306
|
+
for (let index = 0; index < tokens.length - 1; index++) {
|
|
2307
|
+
if (tokens[index].value === "<" && names.has(tokens[index + 1].value)) count++;
|
|
2308
|
+
}
|
|
2309
|
+
return count;
|
|
2310
|
+
}
|
|
2311
|
+
function findMatchingToken(tokens, openingIndex, opening, closing) {
|
|
2312
|
+
let depth = 0;
|
|
2313
|
+
for (let index = openingIndex; index < tokens.length; index++) {
|
|
2314
|
+
if (tokens[index].value === opening) depth++;
|
|
2315
|
+
if (tokens[index].value !== closing) continue;
|
|
2316
|
+
depth--;
|
|
2317
|
+
if (depth === 0) return index;
|
|
2318
|
+
}
|
|
2319
|
+
return tokens.length - 1;
|
|
2320
|
+
}
|
|
2321
|
+
function containsClientJsx(tokens, start, end, clientBindings) {
|
|
2322
|
+
for (let index = start; index < end; index++) {
|
|
2323
|
+
if (tokens[index].value === "<" && clientBindings.has(tokens[index + 1]?.value)) return true;
|
|
2324
|
+
}
|
|
2325
|
+
return false;
|
|
2326
|
+
}
|
|
2327
|
+
function findStatementEnd(tokens, start) {
|
|
2328
|
+
let parentheses = 0;
|
|
2329
|
+
let brackets = 0;
|
|
2330
|
+
let braces = 0;
|
|
2331
|
+
const statementStarters = /* @__PURE__ */ new Set([
|
|
2332
|
+
"class",
|
|
2333
|
+
"const",
|
|
2334
|
+
"export",
|
|
2335
|
+
"function",
|
|
2336
|
+
"import",
|
|
2337
|
+
"let",
|
|
2338
|
+
"var"
|
|
2339
|
+
]);
|
|
2340
|
+
for (let index = start; index < tokens.length; index++) {
|
|
2341
|
+
const value = tokens[index].value;
|
|
2342
|
+
if (index > start && parentheses === 0 && brackets === 0 && braces === 0 && tokens[index].line > tokens[index - 1].line && statementStarters.has(value)) {
|
|
2343
|
+
return index;
|
|
2344
|
+
}
|
|
2345
|
+
if (value === ";" && parentheses === 0 && brackets === 0 && braces === 0) return index;
|
|
2346
|
+
if (value === "(") parentheses++;
|
|
2347
|
+
if (value === ")") parentheses--;
|
|
2348
|
+
if (value === "[") brackets++;
|
|
2349
|
+
if (value === "]") brackets--;
|
|
2350
|
+
if (value === "{") braces++;
|
|
2351
|
+
if (value === "}") braces--;
|
|
2352
|
+
}
|
|
2353
|
+
return tokens.length;
|
|
2354
|
+
}
|
|
2355
|
+
function getClientRenderingHelpers(tokens, clientBindings) {
|
|
2356
|
+
const helperBodies = /* @__PURE__ */ new Map();
|
|
2357
|
+
for (let index = 0; index < tokens.length; index++) {
|
|
2358
|
+
let helperName;
|
|
2359
|
+
let bodyStart = -1;
|
|
2360
|
+
let bodyEnd = -1;
|
|
2361
|
+
if (tokens[index].value === "function" && tokens[index + 1]?.kind === "identifier") {
|
|
2362
|
+
helperName = tokens[index + 1].value;
|
|
2363
|
+
const parametersStart = tokens.findIndex(
|
|
2364
|
+
(token, tokenIndex) => tokenIndex > index + 1 && token.value === "("
|
|
2365
|
+
);
|
|
2366
|
+
const parametersEnd = parametersStart === -1 ? index + 1 : findMatchingToken(tokens, parametersStart, "(", ")");
|
|
2367
|
+
bodyStart = tokens.findIndex(
|
|
2368
|
+
(token, tokenIndex) => tokenIndex > parametersEnd && token.value === "{"
|
|
2369
|
+
);
|
|
2370
|
+
if (bodyStart !== -1) bodyEnd = findMatchingToken(tokens, bodyStart, "{", "}");
|
|
2371
|
+
} else if ((tokens[index].value === "const" || tokens[index].value === "let" || tokens[index].value === "var") && tokens[index + 1]?.kind === "identifier") {
|
|
2372
|
+
helperName = tokens[index + 1].value;
|
|
2373
|
+
let assignmentIndex = -1;
|
|
2374
|
+
let arrowIndex = -1;
|
|
2375
|
+
for (let cursor = index + 2; cursor < tokens.length; cursor++) {
|
|
2376
|
+
if (tokens[cursor].value === ";") break;
|
|
2377
|
+
if (assignmentIndex === -1 && tokens[cursor].value === "=") assignmentIndex = cursor;
|
|
2378
|
+
if (tokens[cursor].value === "=" && tokens[cursor + 1]?.value === ">") {
|
|
2379
|
+
arrowIndex = cursor;
|
|
2380
|
+
break;
|
|
2381
|
+
}
|
|
2382
|
+
}
|
|
2383
|
+
if (arrowIndex !== -1) {
|
|
2384
|
+
bodyStart = arrowIndex + 2;
|
|
2385
|
+
bodyEnd = tokens[bodyStart]?.value === "{" ? findMatchingToken(tokens, bodyStart, "{", "}") : findStatementEnd(tokens, bodyStart);
|
|
2386
|
+
} else if (assignmentIndex !== -1) {
|
|
2387
|
+
bodyStart = assignmentIndex + 1;
|
|
2388
|
+
bodyEnd = findStatementEnd(tokens, bodyStart);
|
|
2389
|
+
}
|
|
2390
|
+
}
|
|
2391
|
+
if (helperName && bodyStart !== -1 && bodyEnd !== -1) {
|
|
2392
|
+
helperBodies.set(helperName, [bodyStart, bodyEnd]);
|
|
2393
|
+
}
|
|
2394
|
+
}
|
|
2395
|
+
const helpers = /* @__PURE__ */ new Set();
|
|
2396
|
+
let addedHelper = true;
|
|
2397
|
+
while (addedHelper) {
|
|
2398
|
+
addedHelper = false;
|
|
2399
|
+
for (const [helperName, [bodyStart, bodyEnd]] of helperBodies) {
|
|
2400
|
+
if (helpers.has(helperName)) continue;
|
|
2401
|
+
const rendersClientBoundary = containsClientJsx(tokens, bodyStart, bodyEnd, clientBindings) || tokens.slice(bodyStart, bodyEnd).some((token) => helpers.has(token.value));
|
|
2402
|
+
if (!rendersClientBoundary) continue;
|
|
2403
|
+
helpers.add(helperName);
|
|
2404
|
+
addedHelper = true;
|
|
2405
|
+
}
|
|
2406
|
+
}
|
|
2407
|
+
return helpers;
|
|
2408
|
+
}
|
|
2409
|
+
function passesElementValuedProps(content, localBindings) {
|
|
2410
|
+
if (!content || localBindings.length === 0) return false;
|
|
2411
|
+
const names = new Set(localBindings);
|
|
2412
|
+
const tokens = tokenizeModuleSource(content);
|
|
2413
|
+
for (let index = 0; index < tokens.length - 1; index++) {
|
|
2414
|
+
if (tokens[index].value !== "<" || !names.has(tokens[index + 1].value)) continue;
|
|
2415
|
+
const name = tokens[index + 1].value;
|
|
2416
|
+
let cursor = index + 2;
|
|
2417
|
+
let braceDepth = 0;
|
|
2418
|
+
let selfClosing = false;
|
|
2419
|
+
for (; cursor < tokens.length; cursor++) {
|
|
2420
|
+
const value = tokens[cursor].value;
|
|
2421
|
+
if (value === "{") braceDepth++;
|
|
2422
|
+
else if (value === "}") braceDepth--;
|
|
2423
|
+
else if (value === "<" && braceDepth > 0) return true;
|
|
2424
|
+
else if (value === ">" && braceDepth === 0) {
|
|
2425
|
+
selfClosing = tokens[cursor - 1]?.value === "/";
|
|
2426
|
+
break;
|
|
2427
|
+
}
|
|
2428
|
+
}
|
|
2429
|
+
if (selfClosing || cursor >= tokens.length) continue;
|
|
2430
|
+
for (let child = cursor + 1; child < tokens.length; child++) {
|
|
2431
|
+
if (tokens[child].value !== "<") continue;
|
|
2432
|
+
const closesBoundary = tokens[child + 1]?.value === "/" && tokens[child + 2]?.value === name;
|
|
2433
|
+
if (!closesBoundary) return true;
|
|
2434
|
+
break;
|
|
2435
|
+
}
|
|
2436
|
+
}
|
|
2437
|
+
return false;
|
|
2438
|
+
}
|
|
2439
|
+
function rendersOnlyLeafElements(content, localBindings) {
|
|
2440
|
+
if (!content) return false;
|
|
2441
|
+
const names = new Set(localBindings);
|
|
2442
|
+
const tokens = tokenizeModuleSource(content);
|
|
2443
|
+
for (let index = 0; index < tokens.length - 1; index++) {
|
|
2444
|
+
if (tokens[index].value !== "<" || !names.has(tokens[index + 1].value)) continue;
|
|
2445
|
+
let braceDepth = 0;
|
|
2446
|
+
let cursor = index + 2;
|
|
2447
|
+
for (; cursor < tokens.length; cursor++) {
|
|
2448
|
+
const value = tokens[cursor].value;
|
|
2449
|
+
if (value === "{") braceDepth++;
|
|
2450
|
+
else if (value === "}") braceDepth--;
|
|
2451
|
+
else if (value === "<" && braceDepth > 0) return false;
|
|
2452
|
+
else if (value === ">" && braceDepth === 0) break;
|
|
2453
|
+
}
|
|
2454
|
+
if (cursor >= tokens.length || tokens[cursor - 1]?.value !== "/") return false;
|
|
2455
|
+
}
|
|
2456
|
+
return true;
|
|
2457
|
+
}
|
|
2458
|
+
function hasDynamicJsxCardinality(content, localBindings) {
|
|
2459
|
+
if (!content || localBindings.length === 0) return false;
|
|
2460
|
+
const clientBindings = new Set(localBindings);
|
|
2461
|
+
const tokens = tokenizeModuleSource(content);
|
|
2462
|
+
const renderingHelpers = getClientRenderingHelpers(tokens, clientBindings);
|
|
2463
|
+
const containsDynamicRenderer = (start, end) => containsClientJsx(tokens, start, end, clientBindings) || tokens.slice(start, end).some((token) => renderingHelpers.has(token.value));
|
|
2464
|
+
for (let index = 0; index < tokens.length; index++) {
|
|
2465
|
+
let callStart = -1;
|
|
2466
|
+
if (tokens[index].value === "." && (tokens[index + 1]?.value === "map" || tokens[index + 1]?.value === "flatMap") && tokens[index + 2]?.value === "(") {
|
|
2467
|
+
callStart = index + 2;
|
|
2468
|
+
} else if (tokens[index].value === "Array" && tokens[index + 1]?.value === "." && tokens[index + 2]?.value === "from" && tokens[index + 3]?.value === "(") {
|
|
2469
|
+
callStart = index + 3;
|
|
2470
|
+
}
|
|
2471
|
+
if (callStart !== -1) {
|
|
2472
|
+
const callEnd = findMatchingToken(tokens, callStart, "(", ")");
|
|
2473
|
+
if (containsDynamicRenderer(callStart + 1, callEnd)) return true;
|
|
2474
|
+
index = callEnd;
|
|
2475
|
+
continue;
|
|
2476
|
+
}
|
|
2477
|
+
if ((tokens[index].value === "for" || tokens[index].value === "while") && tokens[index + 1]?.value === "(") {
|
|
2478
|
+
const conditionEnd = findMatchingToken(tokens, index + 1, "(", ")");
|
|
2479
|
+
const bodyStart = conditionEnd + 1;
|
|
2480
|
+
const bodyEnd = tokens[bodyStart]?.value === "{" ? findMatchingToken(tokens, bodyStart, "{", "}") : tokens.findIndex((token, tokenIndex) => tokenIndex > bodyStart && token.value === ";");
|
|
2481
|
+
if (containsDynamicRenderer(bodyStart, bodyEnd === -1 ? tokens.length : bodyEnd)) return true;
|
|
2482
|
+
}
|
|
2483
|
+
}
|
|
2484
|
+
return false;
|
|
2485
|
+
}
|
|
2486
|
+
function collectIsolatedClientBoundaries(ownerPath, root, options = {}) {
|
|
2487
|
+
const boundaries = /* @__PURE__ */ new Map();
|
|
2488
|
+
const staticPackages = /* @__PURE__ */ new Set();
|
|
2489
|
+
const estimates = /* @__PURE__ */ new Map();
|
|
2490
|
+
const visiting = /* @__PURE__ */ new Set();
|
|
2491
|
+
let fallbackReason;
|
|
2492
|
+
let fallbackHint;
|
|
2493
|
+
let costGuardExceeded = false;
|
|
2494
|
+
const projectRoot = root ? path4.resolve(root) : void 0;
|
|
2495
|
+
const visit = (moduleSourcePath) => {
|
|
2496
|
+
if (fallbackReason) return 0;
|
|
2497
|
+
const cached = estimates.get(moduleSourcePath);
|
|
2498
|
+
if (cached !== void 0) return cached;
|
|
2499
|
+
if (visiting.has(moduleSourcePath)) return 0;
|
|
2500
|
+
visiting.add(moduleSourcePath);
|
|
2501
|
+
const content = readIfExists(moduleSourcePath);
|
|
2502
|
+
const parsed = parseClientModuleMetadata(content, false);
|
|
2503
|
+
if (parsed.isClientComponent) {
|
|
2504
|
+
if (projectRoot && !path4.resolve(moduleSourcePath).startsWith(`${projectRoot}${path4.sep}`)) {
|
|
2505
|
+
fallbackReason = `client boundary ${moduleSourcePath} is outside the application root`;
|
|
2506
|
+
fallbackHint = "Move the component into the application, or publish it as a package (package client components render as static HTML)";
|
|
2507
|
+
return 0;
|
|
2508
|
+
}
|
|
2509
|
+
if (!isIsolatableClientBoundarySource(content)) {
|
|
2510
|
+
fallbackReason = `client boundary ${moduleSourcePath} uses an unsupported export shape`;
|
|
2511
|
+
fallbackHint = "Export each component by name (`export function Name`, `export { Name }`, or `export default`) instead of `export *`";
|
|
2512
|
+
return 0;
|
|
2513
|
+
}
|
|
2514
|
+
boundaries.set(moduleSourcePath, {
|
|
2515
|
+
modulePath: moduleSourcePath,
|
|
2516
|
+
islandStrategy: parsed.islandStrategy ?? "load"
|
|
2517
|
+
});
|
|
2518
|
+
estimates.set(moduleSourcePath, 1);
|
|
2519
|
+
visiting.delete(moduleSourcePath);
|
|
2520
|
+
return 1;
|
|
2521
|
+
}
|
|
2522
|
+
if (parsed.hasHydrateExport) {
|
|
2523
|
+
fallbackReason = `imported module ${moduleSourcePath} explicitly exports hydrate = true`;
|
|
2524
|
+
fallbackHint = "Islands mode never hydrates a whole page; remove `hydrate = true`";
|
|
2525
|
+
return 0;
|
|
2526
|
+
}
|
|
2527
|
+
const importedBindings = getStaticImportBindings(content);
|
|
2528
|
+
let estimatedBoundaryCount2 = 0;
|
|
2529
|
+
for (const specifier of new Set(getImportSpecifiers(content))) {
|
|
2530
|
+
const imported = resolveImportedModule(moduleSourcePath, specifier, root);
|
|
2531
|
+
const importedPath = imported.path;
|
|
2532
|
+
if (!importedPath) continue;
|
|
2533
|
+
let importedBoundaryCount;
|
|
2534
|
+
if (imported.local) {
|
|
2535
|
+
importedBoundaryCount = visit(importedPath);
|
|
2536
|
+
} else {
|
|
2537
|
+
const reactServerClientNames = options.packageReferences && projectRoot ? findFarmReactServerClientNames(content ?? "", moduleSourcePath, specifier) : null;
|
|
2538
|
+
if (reactServerClientNames) {
|
|
2539
|
+
importedBoundaryCount = 0;
|
|
2540
|
+
for (const exportName of reactServerClientNames) {
|
|
2541
|
+
importedBoundaryCount += visit(
|
|
2542
|
+
ensureFarmPackageClientReference(projectRoot, specifier, exportName)
|
|
2543
|
+
);
|
|
2544
|
+
}
|
|
2545
|
+
} else {
|
|
2546
|
+
const packageMetadata = inspectPackageClientBoundary(importedPath, root, /* @__PURE__ */ new Set());
|
|
2547
|
+
if (!packageMetadata.shouldHydrate) continue;
|
|
2548
|
+
const references = options.packageReferences && projectRoot ? findFarmPackageClientImports(
|
|
2549
|
+
content ?? "",
|
|
2550
|
+
moduleSourcePath,
|
|
2551
|
+
(candidate) => candidate === specifier
|
|
2552
|
+
) : [];
|
|
2553
|
+
if (references.length > 0) {
|
|
2554
|
+
importedBoundaryCount = 0;
|
|
2555
|
+
for (const reference of references) {
|
|
2556
|
+
for (const exportName of farmPackageClientImportExports(reference)) {
|
|
2557
|
+
importedBoundaryCount += visit(
|
|
2558
|
+
ensureFarmPackageClientReference(projectRoot, specifier, exportName)
|
|
2559
|
+
);
|
|
2560
|
+
}
|
|
2561
|
+
}
|
|
2562
|
+
} else if (options.staticPackageBoundaries || options.staticPackageLeaves && rendersOnlyLeafElements(content, importedBindings.get(specifier) ?? [])) {
|
|
2563
|
+
staticPackages.add(specifier);
|
|
2564
|
+
continue;
|
|
2565
|
+
} else {
|
|
2566
|
+
fallbackReason = `package client boundary ${specifier} cannot yet be isolated`;
|
|
2567
|
+
fallbackHint = `Render it from a local "use client" module (a providers.tsx that renders the ${specifier} component)`;
|
|
2568
|
+
return 0;
|
|
2569
|
+
}
|
|
2570
|
+
}
|
|
2571
|
+
}
|
|
2572
|
+
if (fallbackReason || importedBoundaryCount === 0) continue;
|
|
2573
|
+
const localBindings = importedBindings.get(specifier) ?? [];
|
|
2574
|
+
const staticUses = countStaticJsxUses(content, localBindings);
|
|
2575
|
+
if (staticUses > 0) {
|
|
2576
|
+
const container = findParserSensitiveJsxContainer(content, localBindings);
|
|
2577
|
+
if (container) {
|
|
2578
|
+
fallbackReason = `the client boundary imported from ${specifier} renders inside <${container}>, where the HTML parser relocates its hydration marker`;
|
|
2579
|
+
fallbackHint = `Move "use client" up to a component that renders the whole <${container}>${PARSER_SENSITIVE_FLOW_HINTS[container] ?? ""}`;
|
|
2580
|
+
return 0;
|
|
2581
|
+
}
|
|
2582
|
+
if (!options.allowElementProps && passesElementValuedProps(content, localBindings)) {
|
|
2583
|
+
fallbackReason = `the client boundary imported from ${specifier} receives React elements, which cannot cross the boundary as serialized props`;
|
|
2584
|
+
return 0;
|
|
2585
|
+
}
|
|
2586
|
+
}
|
|
2587
|
+
if (staticUses > 0 && !options.allowDynamicCardinality && hasDynamicJsxCardinality(content, localBindings)) {
|
|
2588
|
+
fallbackReason = `the client boundary count imported from ${specifier} is data-dependent`;
|
|
2589
|
+
costGuardExceeded = true;
|
|
2590
|
+
return 0;
|
|
2591
|
+
}
|
|
2592
|
+
estimatedBoundaryCount2 += importedBoundaryCount * Math.max(1, staticUses);
|
|
2593
|
+
}
|
|
2594
|
+
estimates.set(moduleSourcePath, estimatedBoundaryCount2);
|
|
2595
|
+
visiting.delete(moduleSourcePath);
|
|
2596
|
+
return estimatedBoundaryCount2;
|
|
2597
|
+
};
|
|
2598
|
+
const estimatedBoundaryCount = visit(ownerPath);
|
|
2599
|
+
return {
|
|
2600
|
+
boundaries: Array.from(boundaries.values()),
|
|
2601
|
+
estimatedBoundaryCount,
|
|
2602
|
+
staticPackages: Array.from(staticPackages),
|
|
2603
|
+
costGuardExceeded,
|
|
2604
|
+
fallbackReason,
|
|
2605
|
+
fallbackHint
|
|
2606
|
+
};
|
|
2607
|
+
}
|
|
2608
|
+
function inspectClientModuleMetadata(resolvedPath, root, visited, inspectIslandExport) {
|
|
2609
|
+
if (!resolvedPath || visited.has(resolvedPath)) {
|
|
2610
|
+
return {
|
|
2611
|
+
isClientComponent: false,
|
|
2612
|
+
shouldHydrate: false,
|
|
2613
|
+
islandStrategy: null
|
|
2614
|
+
};
|
|
2615
|
+
}
|
|
2616
|
+
visited.add(resolvedPath);
|
|
2617
|
+
const content = readIfExists(resolvedPath);
|
|
2618
|
+
if (inspectIslandExport) {
|
|
2619
|
+
const target = resolveDefaultReexport(resolvedPath, content, root);
|
|
2620
|
+
if (target) return inspectClientModuleMetadata(target, root, visited, true);
|
|
2621
|
+
}
|
|
2622
|
+
const parsed = parseClientModuleMetadata(content, inspectIslandExport);
|
|
2623
|
+
if (parsed.isClientComponent) {
|
|
2624
|
+
return {
|
|
2625
|
+
isClientComponent: true,
|
|
2626
|
+
shouldHydrate: true,
|
|
2627
|
+
islandStrategy: parsed.islandStrategy ?? "load"
|
|
2628
|
+
};
|
|
2629
|
+
}
|
|
2630
|
+
let importsClientBoundary = false;
|
|
2631
|
+
let importsAsyncOwner = false;
|
|
2632
|
+
let importedIslandStrategy = null;
|
|
2633
|
+
for (const specifier of getImportSpecifiers(content)) {
|
|
2634
|
+
const imported = resolveImportedModule(resolvedPath, specifier, root);
|
|
2635
|
+
const importedMetadata = imported.local ? inspectClientModuleMetadata(imported.path, root, visited, false) : inspectPackageClientBoundary(imported.path, root, visited);
|
|
2636
|
+
if (importedMetadata.suppressedAsyncHydration) importsAsyncOwner = true;
|
|
2637
|
+
if (importedMetadata.isClientComponent || importedMetadata.shouldHydrate) {
|
|
2638
|
+
importsClientBoundary = true;
|
|
2639
|
+
if (importedIslandStrategy === null) {
|
|
2640
|
+
importedIslandStrategy = importedMetadata.islandStrategy;
|
|
2641
|
+
} else if (importedIslandStrategy !== importedMetadata.islandStrategy) {
|
|
2642
|
+
importedIslandStrategy = "load";
|
|
2643
|
+
}
|
|
2644
|
+
}
|
|
2645
|
+
}
|
|
2646
|
+
const shouldHydrate = parsed.hasHydrateExport || importsClientBoundary;
|
|
2647
|
+
if (shouldHydrate && hasAsyncDefaultExport(content) || importsAsyncOwner) {
|
|
2648
|
+
return {
|
|
2649
|
+
isClientComponent: false,
|
|
2650
|
+
shouldHydrate: false,
|
|
2651
|
+
islandStrategy: null,
|
|
2652
|
+
suppressedAsyncHydration: true
|
|
2653
|
+
};
|
|
2654
|
+
}
|
|
2655
|
+
return {
|
|
2656
|
+
isClientComponent: false,
|
|
2657
|
+
shouldHydrate,
|
|
2658
|
+
islandStrategy: shouldHydrate ? parsed.islandStrategy ?? importedIslandStrategy ?? "load" : null
|
|
2659
|
+
};
|
|
2660
|
+
}
|
|
2661
|
+
function realpathOrSelf(file) {
|
|
2662
|
+
try {
|
|
2663
|
+
return fs4.realpathSync(file);
|
|
2664
|
+
} catch {
|
|
2665
|
+
return file;
|
|
2666
|
+
}
|
|
2667
|
+
}
|
|
2668
|
+
function getBarePackageReexports(content) {
|
|
2669
|
+
return getImportSpecifiers(content, { reexportsOnly: true }).filter(
|
|
2670
|
+
(specifier) => bareSpecifierPackage(specifier)
|
|
2671
|
+
);
|
|
2672
|
+
}
|
|
2673
|
+
function inspectPackageClientBoundary(resolvedPath, root, visited) {
|
|
2674
|
+
const cache2 = getPackageClientBoundaryCache();
|
|
2675
|
+
if (!cache2 || !resolvedPath || visited.has(resolvedPath)) {
|
|
2676
|
+
return traversePackageClientBoundary(resolvedPath, root, visited);
|
|
2677
|
+
}
|
|
2678
|
+
const key = `${root ?? ""}\0${resolvedPath}`;
|
|
2679
|
+
const cached = cache2.find(key, visited);
|
|
2680
|
+
if (cached) {
|
|
2681
|
+
for (const file of cached.files) visited.add(file);
|
|
2682
|
+
return { ...cached.result };
|
|
2683
|
+
}
|
|
2684
|
+
const trace = new PackageInspectionTrace();
|
|
2685
|
+
const result = traversePackageClientBoundary(resolvedPath, root, visited, trace);
|
|
2686
|
+
cache2.add(key, trace.toEntry(result));
|
|
2687
|
+
return result;
|
|
2688
|
+
}
|
|
2689
|
+
function traversePackageClientBoundary(resolvedPath, root, visited, trace) {
|
|
2690
|
+
if (!resolvedPath || visited.has(resolvedPath)) {
|
|
2691
|
+
if (resolvedPath) trace?.stop(resolvedPath);
|
|
2692
|
+
return {
|
|
2693
|
+
isClientComponent: false,
|
|
2694
|
+
shouldHydrate: false,
|
|
2695
|
+
islandStrategy: null
|
|
2696
|
+
};
|
|
2697
|
+
}
|
|
2698
|
+
visited.add(resolvedPath);
|
|
2699
|
+
trace?.visit(resolvedPath);
|
|
2700
|
+
const content = readIfExists(resolvedPath);
|
|
2701
|
+
const parsed = parseClientModuleMetadata(content, false);
|
|
2702
|
+
let importsClientBoundary = false;
|
|
2703
|
+
let importedIslandStrategy = null;
|
|
2704
|
+
const reexports = getBarePackageReexports(content);
|
|
2705
|
+
const realPath = reexports.length > 0 ? realpathOrSelf(resolvedPath) : resolvedPath;
|
|
2706
|
+
const followed = [
|
|
2707
|
+
...getImportSpecifiers(content).filter(
|
|
2708
|
+
(specifier) => specifier.startsWith(".") || specifier.startsWith("/")
|
|
2709
|
+
),
|
|
2710
|
+
...reexports
|
|
2711
|
+
];
|
|
2712
|
+
for (const specifier of followed) {
|
|
2713
|
+
const importedPath = resolveImportedModuleSourcePath(
|
|
2714
|
+
reexports.includes(specifier) ? realPath : resolvedPath,
|
|
2715
|
+
specifier,
|
|
2716
|
+
root
|
|
2717
|
+
);
|
|
2718
|
+
const importedMetadata = traversePackageClientBoundary(importedPath, root, visited, trace);
|
|
2719
|
+
if (!importedMetadata.shouldHydrate) continue;
|
|
2720
|
+
importsClientBoundary = true;
|
|
2721
|
+
if (importedIslandStrategy === null) {
|
|
2722
|
+
importedIslandStrategy = importedMetadata.islandStrategy;
|
|
2723
|
+
} else if (importedIslandStrategy !== importedMetadata.islandStrategy) {
|
|
2724
|
+
importedIslandStrategy = "load";
|
|
2725
|
+
}
|
|
2726
|
+
}
|
|
2727
|
+
const shouldHydrate = parsed.isClientComponent || parsed.hasHydrateExport || importsClientBoundary;
|
|
2728
|
+
return {
|
|
2729
|
+
isClientComponent: parsed.isClientComponent,
|
|
2730
|
+
shouldHydrate,
|
|
2731
|
+
islandStrategy: shouldHydrate ? parsed.islandStrategy ?? importedIslandStrategy ?? "load" : null
|
|
2732
|
+
};
|
|
2733
|
+
}
|
|
2734
|
+
function getImportSpecifiers(content, { reexportsOnly = false, dynamic = false } = {}) {
|
|
2735
|
+
if (!content) return [];
|
|
2736
|
+
const tokens = tokenizeModuleSource(content);
|
|
2737
|
+
const matches = /* @__PURE__ */ new Set();
|
|
2738
|
+
let braceDepth = 0;
|
|
2739
|
+
for (let index = 0; index < tokens.length; index++) {
|
|
2740
|
+
const keyword = tokens[index];
|
|
2741
|
+
if (keyword.value === "{") {
|
|
2742
|
+
braceDepth++;
|
|
2743
|
+
continue;
|
|
2744
|
+
}
|
|
2745
|
+
if (keyword.value === "}") {
|
|
2746
|
+
braceDepth = Math.max(0, braceDepth - 1);
|
|
2747
|
+
continue;
|
|
2748
|
+
}
|
|
2749
|
+
if (dynamic && keyword.kind === "identifier" && keyword.value === "import" && tokens[index - 1]?.value !== "." && tokens[index + 1]?.value === "(" && tokens[index + 2]?.kind === "string") {
|
|
2750
|
+
matches.add(tokens[index + 2].value);
|
|
2751
|
+
continue;
|
|
2752
|
+
}
|
|
2753
|
+
if (braceDepth !== 0) continue;
|
|
2754
|
+
if (keyword.kind !== "identifier" || !["import", "export"].includes(keyword.value)) {
|
|
2755
|
+
continue;
|
|
2756
|
+
}
|
|
2757
|
+
if (reexportsOnly && keyword.value !== "export") continue;
|
|
2758
|
+
const previous = tokens[index - 1];
|
|
2759
|
+
if (previous?.value === ".") continue;
|
|
2760
|
+
const first = tokens[index + 1];
|
|
2761
|
+
if (!first || first.value === "type" || first.value === "(" || first.value === ".") {
|
|
2762
|
+
continue;
|
|
2763
|
+
}
|
|
2764
|
+
let specifier;
|
|
2765
|
+
if (keyword.value === "import" && first.kind === "string") {
|
|
2766
|
+
specifier = first.value;
|
|
2767
|
+
} else {
|
|
2768
|
+
if (keyword.value === "export" && first.value !== "{" && first.value !== "*") {
|
|
2769
|
+
continue;
|
|
2770
|
+
}
|
|
2771
|
+
let fromIndex = -1;
|
|
2772
|
+
for (let cursor = index + 1; cursor < tokens.length; cursor++) {
|
|
2773
|
+
const token = tokens[cursor];
|
|
2774
|
+
if (token.value === ";") break;
|
|
2775
|
+
if (token.value === "from" && tokens[cursor + 1]?.kind === "string") {
|
|
2776
|
+
fromIndex = cursor;
|
|
2777
|
+
break;
|
|
2778
|
+
}
|
|
2779
|
+
}
|
|
2780
|
+
if (fromIndex === -1 || isTypeOnlyNamedClause(tokens, index + 1, fromIndex)) {
|
|
2781
|
+
continue;
|
|
2782
|
+
}
|
|
2783
|
+
specifier = tokens[fromIndex + 1].value;
|
|
2784
|
+
}
|
|
2785
|
+
if (!specifier || specifier.startsWith("node:") || specifier.includes("?")) {
|
|
2786
|
+
continue;
|
|
2787
|
+
}
|
|
2788
|
+
matches.add(specifier);
|
|
2789
|
+
}
|
|
2790
|
+
return Array.from(matches);
|
|
2791
|
+
}
|
|
2792
|
+
function isTypeOnlyNamedClause(tokens, startIndex, endIndex) {
|
|
2793
|
+
if (tokens[startIndex]?.value !== "{") return false;
|
|
2794
|
+
const closingBraceIndex = tokens.findIndex(
|
|
2795
|
+
(token, index) => index > startIndex && index < endIndex && token.value === "}"
|
|
2796
|
+
);
|
|
2797
|
+
if (closingBraceIndex === -1) return false;
|
|
2798
|
+
let entryStartsAt = startIndex + 1;
|
|
2799
|
+
for (let index = entryStartsAt; index <= closingBraceIndex; index++) {
|
|
2800
|
+
if (index !== closingBraceIndex && tokens[index]?.value !== ",") continue;
|
|
2801
|
+
const entry = tokens.slice(entryStartsAt, index);
|
|
2802
|
+
if (entry.length > 0 && entry[0].value !== "type") return false;
|
|
2803
|
+
entryStartsAt = index + 1;
|
|
2804
|
+
}
|
|
2805
|
+
return true;
|
|
2806
|
+
}
|
|
2807
|
+
function resolveImportedModule(importerPath, specifier, root) {
|
|
2808
|
+
if (specifier.startsWith(".") || specifier.startsWith("/")) {
|
|
2809
|
+
return { path: resolveImportedModuleSourcePath(importerPath, specifier, root), local: true };
|
|
2810
|
+
}
|
|
2811
|
+
const aliased = resolveProjectAliasSourcePath(specifier, root);
|
|
2812
|
+
if (aliased) return { path: aliased, local: true };
|
|
2813
|
+
const packagePath = resolvePackageModuleSourcePath(importerPath, specifier, root);
|
|
2814
|
+
if (!packagePath) warnUnresolvedAliasImport(importerPath, specifier, root);
|
|
2815
|
+
return { path: packagePath, local: false };
|
|
2816
|
+
}
|
|
2817
|
+
var warnedUnresolvedAliasImports = /* @__PURE__ */ new Set();
|
|
2818
|
+
var ALIAS_IMPORT = /^(?:@\/|~\/|#)/;
|
|
2819
|
+
function warnUnresolvedAliasImport(importerPath, specifier, root) {
|
|
2820
|
+
if (!ALIAS_IMPORT.test(specifier) || warnedUnresolvedAliasImports.has(specifier)) return;
|
|
2821
|
+
warnedUnresolvedAliasImports.add(specifier);
|
|
2822
|
+
const importer = root ? path4.relative(root, importerPath) : importerPath;
|
|
2823
|
+
logger.warn(
|
|
2824
|
+
`Could not resolve "${specifier}" (imported by ${importer}) while checking which pages need client JavaScript. If it holds client components, they will not hydrate. Map the alias in tsconfig.json "paths" or package.json "imports".`
|
|
2825
|
+
);
|
|
2826
|
+
}
|
|
2827
|
+
var projectImportAliasCache = /* @__PURE__ */ new Map();
|
|
2828
|
+
var PROJECT_ALIAS_FILES = ["tsconfig.json", "jsconfig.json", "package.json"];
|
|
2829
|
+
function resolveProjectAliasSourcePath(specifier, root) {
|
|
2830
|
+
if (!root) return void 0;
|
|
2831
|
+
const projectRoot = path4.resolve(root);
|
|
2832
|
+
let match;
|
|
2833
|
+
for (const alias of getProjectImportAliases(projectRoot)) {
|
|
2834
|
+
const captured = matchProjectImportAlias(alias, specifier);
|
|
2835
|
+
if (captured === null) continue;
|
|
2836
|
+
if (!match || alias.prefix.length > match.alias.prefix.length) match = { alias, captured };
|
|
2837
|
+
}
|
|
2838
|
+
if (!match) return void 0;
|
|
2839
|
+
const resolved = resolveSourceCandidate(
|
|
2840
|
+
match.alias.targets.map(
|
|
2841
|
+
(target) => path4.normalize(match.alias.wildcard ? target.replace("*", match.captured) : target)
|
|
2842
|
+
)
|
|
2843
|
+
);
|
|
2844
|
+
return resolved && /\.d\.[cm]?ts$/.test(resolved) ? null : resolved;
|
|
2845
|
+
}
|
|
2846
|
+
function matchProjectImportAlias(alias, specifier) {
|
|
2847
|
+
if (!alias.wildcard) return specifier === alias.prefix ? "" : null;
|
|
2848
|
+
if (specifier.length < alias.prefix.length + alias.suffix.length || !specifier.startsWith(alias.prefix) || !specifier.endsWith(alias.suffix)) {
|
|
2849
|
+
return null;
|
|
2850
|
+
}
|
|
2851
|
+
return specifier.slice(alias.prefix.length, specifier.length - alias.suffix.length);
|
|
2852
|
+
}
|
|
2853
|
+
function getProjectImportAliases(projectRoot) {
|
|
2854
|
+
const stamp = PROJECT_ALIAS_FILES.map((file) => {
|
|
2855
|
+
try {
|
|
2856
|
+
return String(fs4.statSync(path4.join(projectRoot, file)).mtimeMs);
|
|
2857
|
+
} catch {
|
|
2858
|
+
return "-";
|
|
2859
|
+
}
|
|
2860
|
+
}).join(":");
|
|
2861
|
+
const sourceDir = getFarmProjectSourceDir(projectRoot);
|
|
2862
|
+
const cacheStamp = `${stamp}:${sourceDir}`;
|
|
2863
|
+
const cached = projectImportAliasCache.get(projectRoot);
|
|
2864
|
+
if (cached?.stamp === cacheStamp) return cached.aliases;
|
|
2865
|
+
const aliases = [
|
|
2866
|
+
...readTsconfigPathAliases(projectRoot),
|
|
2867
|
+
...readPackageImportAliases(projectRoot)
|
|
2868
|
+
];
|
|
2869
|
+
if (!aliases.some((alias) => alias.prefix === "@/")) {
|
|
2870
|
+
aliases.push({
|
|
2871
|
+
prefix: "@/",
|
|
2872
|
+
suffix: "",
|
|
2873
|
+
wildcard: true,
|
|
2874
|
+
targets: [path4.join(projectRoot, sourceDir, "*")]
|
|
2875
|
+
});
|
|
2876
|
+
}
|
|
2877
|
+
projectImportAliasCache.set(projectRoot, { stamp: cacheStamp, aliases });
|
|
2878
|
+
return aliases;
|
|
2879
|
+
}
|
|
2880
|
+
function readTsconfigPathAliases(projectRoot) {
|
|
2881
|
+
for (const name of ["tsconfig.json", "jsconfig.json"]) {
|
|
2882
|
+
const configPath = path4.join(projectRoot, name);
|
|
2883
|
+
if (!fs4.existsSync(configPath)) continue;
|
|
2884
|
+
const resolved = readTsconfigPaths(configPath, /* @__PURE__ */ new Set());
|
|
2885
|
+
if (!resolved?.paths) return [];
|
|
2886
|
+
const base = resolved.baseUrl ?? resolved.pathsDirectory;
|
|
2887
|
+
return Object.entries(resolved.paths).flatMap(([pattern, targets]) => {
|
|
2888
|
+
if (!Array.isArray(targets)) return [];
|
|
2889
|
+
const wildcardIndex = pattern.indexOf("*");
|
|
2890
|
+
return [
|
|
2891
|
+
{
|
|
2892
|
+
prefix: wildcardIndex === -1 ? pattern : pattern.slice(0, wildcardIndex),
|
|
2893
|
+
suffix: wildcardIndex === -1 ? "" : pattern.slice(wildcardIndex + 1),
|
|
2894
|
+
wildcard: wildcardIndex !== -1,
|
|
2895
|
+
targets: targets.filter((target) => typeof target === "string").map((target) => path4.resolve(base, target))
|
|
2896
|
+
}
|
|
2897
|
+
];
|
|
2898
|
+
});
|
|
2899
|
+
}
|
|
2900
|
+
return [];
|
|
2901
|
+
}
|
|
2902
|
+
function readTsconfigPaths(configPath, visited) {
|
|
2903
|
+
if (visited.has(configPath)) return null;
|
|
2904
|
+
visited.add(configPath);
|
|
2905
|
+
const config = readJsonWithComments(configPath);
|
|
2906
|
+
if (!config) return null;
|
|
2907
|
+
const directory = path4.dirname(configPath);
|
|
2908
|
+
const parents = (Array.isArray(config.extends) ? config.extends : [config.extends]).filter(
|
|
2909
|
+
(parent) => typeof parent === "string" && parent.startsWith(".")
|
|
2910
|
+
);
|
|
2911
|
+
let inherited = null;
|
|
2912
|
+
for (const parent of parents) {
|
|
2913
|
+
const parentPath = path4.resolve(
|
|
2914
|
+
directory,
|
|
2915
|
+
parent.endsWith(".json") ? parent : `${parent}.json`
|
|
2916
|
+
);
|
|
2917
|
+
inherited = readTsconfigPaths(parentPath, visited) ?? inherited;
|
|
2918
|
+
}
|
|
2919
|
+
const options = config.compilerOptions ?? {};
|
|
2920
|
+
const baseUrl = typeof options.baseUrl === "string" ? path4.resolve(directory, options.baseUrl) : inherited?.baseUrl;
|
|
2921
|
+
if (options.paths && typeof options.paths === "object") {
|
|
2922
|
+
return { paths: options.paths, pathsDirectory: directory, baseUrl };
|
|
2923
|
+
}
|
|
2924
|
+
return inherited ? { ...inherited, baseUrl } : { pathsDirectory: directory, baseUrl };
|
|
2925
|
+
}
|
|
2926
|
+
function readPackageImportAliases(projectRoot) {
|
|
2927
|
+
const imports = readPackageJson(path4.join(projectRoot, "package.json"))?.imports;
|
|
2928
|
+
if (!imports || typeof imports !== "object") return [];
|
|
2929
|
+
return Object.entries(imports).flatMap(([pattern, value]) => {
|
|
2930
|
+
const target = resolveConditionalExportTarget(value);
|
|
2931
|
+
if (!pattern.startsWith("#") || !target?.startsWith("./")) return [];
|
|
2932
|
+
const wildcardIndex = pattern.indexOf("*");
|
|
2933
|
+
return [
|
|
2934
|
+
{
|
|
2935
|
+
prefix: wildcardIndex === -1 ? pattern : pattern.slice(0, wildcardIndex),
|
|
2936
|
+
suffix: wildcardIndex === -1 ? "" : pattern.slice(wildcardIndex + 1),
|
|
2937
|
+
wildcard: wildcardIndex !== -1,
|
|
2938
|
+
targets: [path4.resolve(projectRoot, target)]
|
|
2939
|
+
}
|
|
2940
|
+
];
|
|
2941
|
+
});
|
|
2942
|
+
}
|
|
2943
|
+
function readJsonWithComments(filePath) {
|
|
2944
|
+
let source;
|
|
2945
|
+
try {
|
|
2946
|
+
source = fs4.readFileSync(filePath, "utf8");
|
|
2947
|
+
} catch {
|
|
2948
|
+
return null;
|
|
2949
|
+
}
|
|
2950
|
+
let output = "";
|
|
2951
|
+
let inString = false;
|
|
2952
|
+
for (let index = 0; index < source.length; index++) {
|
|
2953
|
+
const char = source[index];
|
|
2954
|
+
if (inString) {
|
|
2955
|
+
output += char;
|
|
2956
|
+
if (char === "\\") output += source[++index] ?? "";
|
|
2957
|
+
else if (char === '"') inString = false;
|
|
2958
|
+
continue;
|
|
2959
|
+
}
|
|
2960
|
+
if (char === '"') {
|
|
2961
|
+
inString = true;
|
|
2962
|
+
output += char;
|
|
2963
|
+
} else if (char === "/" && source[index + 1] === "/") {
|
|
2964
|
+
while (index < source.length && source[index] !== "\n") index++;
|
|
2965
|
+
output += "\n";
|
|
2966
|
+
} else if (char === "/" && source[index + 1] === "*") {
|
|
2967
|
+
const end = source.indexOf("*/", index + 2);
|
|
2968
|
+
index = end === -1 ? source.length : end + 1;
|
|
2969
|
+
} else {
|
|
2970
|
+
output += char;
|
|
2971
|
+
}
|
|
2972
|
+
}
|
|
2973
|
+
try {
|
|
2974
|
+
return JSON.parse(output.replace(/,(\s*[}\]])/g, "$1"));
|
|
2975
|
+
} catch {
|
|
2976
|
+
return null;
|
|
2977
|
+
}
|
|
2978
|
+
}
|
|
2979
|
+
function resolveImportedModuleSourcePath(importerPath, specifier, root) {
|
|
2980
|
+
if (!specifier.startsWith(".") && !specifier.startsWith("/")) {
|
|
2981
|
+
return resolvePackageModuleSourcePath(importerPath, specifier, root);
|
|
2982
|
+
}
|
|
2983
|
+
const candidates = /* @__PURE__ */ new Set();
|
|
2984
|
+
const basePath = specifier.startsWith(".") ? path4.resolve(path4.dirname(importerPath), specifier) : root ? path4.resolve(root, specifier.replace(/^\/+/, "")) : path4.resolve(specifier);
|
|
2985
|
+
candidates.add(basePath);
|
|
2986
|
+
return resolveSourceCandidate(candidates);
|
|
2987
|
+
}
|
|
2988
|
+
function resolvePackageModuleSourcePath(importerPath, specifier, root) {
|
|
2989
|
+
const packageParts = specifier.split("/");
|
|
2990
|
+
const packageName = specifier.startsWith("@") ? packageParts.slice(0, 2).join("/") : packageParts[0];
|
|
2991
|
+
const packageSubpath = packageParts.slice(packageName.startsWith("@") ? 2 : 1).join("/");
|
|
2992
|
+
const packageDirectory = findPackageDirectory2(importerPath, packageName, root);
|
|
2993
|
+
if (!packageDirectory) return null;
|
|
2994
|
+
const packageJsonPath = path4.join(packageDirectory, "package.json");
|
|
2995
|
+
const packageJson = readPackageJson(packageJsonPath);
|
|
2996
|
+
const exportKey = packageSubpath ? `./${packageSubpath}` : ".";
|
|
2997
|
+
const exportTarget = resolvePackageExport(packageJson?.exports, exportKey);
|
|
2998
|
+
const candidates = /* @__PURE__ */ new Set();
|
|
2999
|
+
if (exportTarget?.startsWith("./")) {
|
|
3000
|
+
candidates.add(path4.resolve(packageDirectory, exportTarget));
|
|
3001
|
+
}
|
|
3002
|
+
if (packageSubpath) {
|
|
3003
|
+
candidates.add(path4.join(packageDirectory, packageSubpath));
|
|
3004
|
+
} else {
|
|
3005
|
+
for (const entry of [packageJson?.browser, packageJson?.module, packageJson?.main]) {
|
|
3006
|
+
if (typeof entry === "string") candidates.add(path4.resolve(packageDirectory, entry));
|
|
3007
|
+
}
|
|
3008
|
+
candidates.add(path4.join(packageDirectory, "index"));
|
|
3009
|
+
}
|
|
3010
|
+
return resolveSourceCandidate(candidates);
|
|
3011
|
+
}
|
|
3012
|
+
function findPackageDirectory2(importerPath, packageName, root) {
|
|
3013
|
+
const searchRoots = /* @__PURE__ */ new Set();
|
|
3014
|
+
let current = path4.dirname(importerPath);
|
|
3015
|
+
while (true) {
|
|
3016
|
+
searchRoots.add(current);
|
|
3017
|
+
const parent = path4.dirname(current);
|
|
3018
|
+
if (parent === current) break;
|
|
3019
|
+
current = parent;
|
|
3020
|
+
}
|
|
3021
|
+
if (root) {
|
|
3022
|
+
current = path4.resolve(root);
|
|
3023
|
+
while (true) {
|
|
3024
|
+
searchRoots.add(current);
|
|
3025
|
+
const parent = path4.dirname(current);
|
|
3026
|
+
if (parent === current) break;
|
|
3027
|
+
current = parent;
|
|
3028
|
+
}
|
|
3029
|
+
}
|
|
3030
|
+
for (const searchRoot of searchRoots) {
|
|
3031
|
+
const packageDirectory = path4.join(searchRoot, "node_modules", packageName);
|
|
3032
|
+
if (fs4.existsSync(path4.join(packageDirectory, "package.json"))) {
|
|
3033
|
+
return packageDirectory;
|
|
3034
|
+
}
|
|
3035
|
+
}
|
|
3036
|
+
return null;
|
|
3037
|
+
}
|
|
3038
|
+
function readPackageJson(packageJsonPath) {
|
|
3039
|
+
try {
|
|
3040
|
+
return JSON.parse(fs4.readFileSync(packageJsonPath, "utf8"));
|
|
3041
|
+
} catch {
|
|
3042
|
+
return null;
|
|
3043
|
+
}
|
|
3044
|
+
}
|
|
3045
|
+
function resolvePackageExport(exportsField, exportKey) {
|
|
3046
|
+
if (typeof exportsField === "string") {
|
|
3047
|
+
return exportKey === "." ? exportsField : null;
|
|
3048
|
+
}
|
|
3049
|
+
if (Array.isArray(exportsField)) {
|
|
3050
|
+
for (const candidate of exportsField) {
|
|
3051
|
+
const resolved = resolvePackageExport(candidate, exportKey);
|
|
3052
|
+
if (resolved) return resolved;
|
|
3053
|
+
}
|
|
3054
|
+
return null;
|
|
3055
|
+
}
|
|
3056
|
+
if (!exportsField || typeof exportsField !== "object") return null;
|
|
3057
|
+
const entries = Object.entries(exportsField);
|
|
3058
|
+
const subpathExports = entries.some(([key]) => key.startsWith("."));
|
|
3059
|
+
if (subpathExports) {
|
|
3060
|
+
const exact = exportsField[exportKey];
|
|
3061
|
+
if (exact !== void 0) return resolveConditionalExportTarget(exact);
|
|
3062
|
+
for (const [key, value] of entries) {
|
|
3063
|
+
const wildcardIndex = key.indexOf("*");
|
|
3064
|
+
if (wildcardIndex === -1) continue;
|
|
3065
|
+
const prefix = key.slice(0, wildcardIndex);
|
|
3066
|
+
const suffix = key.slice(wildcardIndex + 1);
|
|
3067
|
+
if (!exportKey.startsWith(prefix) || !exportKey.endsWith(suffix)) continue;
|
|
3068
|
+
const wildcard = exportKey.slice(prefix.length, exportKey.length - suffix.length);
|
|
3069
|
+
const target = resolveConditionalExportTarget(value);
|
|
3070
|
+
return target?.replace("*", wildcard) ?? null;
|
|
3071
|
+
}
|
|
3072
|
+
return null;
|
|
3073
|
+
}
|
|
3074
|
+
return exportKey === "." ? resolveConditionalExportTarget(exportsField) : null;
|
|
3075
|
+
}
|
|
3076
|
+
function resolveConditionalExportTarget(value) {
|
|
3077
|
+
if (typeof value === "string") return value;
|
|
3078
|
+
if (Array.isArray(value)) {
|
|
3079
|
+
for (const candidate of value) {
|
|
3080
|
+
const resolved = resolveConditionalExportTarget(candidate);
|
|
3081
|
+
if (resolved) return resolved;
|
|
3082
|
+
}
|
|
3083
|
+
return null;
|
|
3084
|
+
}
|
|
3085
|
+
if (!value || typeof value !== "object") return null;
|
|
3086
|
+
const conditions = value;
|
|
3087
|
+
for (const condition of ["browser", "import", "module", "node", "default", "require"]) {
|
|
3088
|
+
if (conditions[condition] === void 0) continue;
|
|
3089
|
+
const resolved = resolveConditionalExportTarget(conditions[condition]);
|
|
3090
|
+
if (resolved) return resolved;
|
|
3091
|
+
}
|
|
3092
|
+
return null;
|
|
3093
|
+
}
|
|
3094
|
+
function resolveSourceCandidate(candidates) {
|
|
3095
|
+
for (const candidate of candidates) {
|
|
3096
|
+
const paths = [candidate];
|
|
3097
|
+
for (const extension of RESOLVABLE_SOURCE_EXTENSIONS) {
|
|
3098
|
+
paths.push(`${candidate}${extension}`, path4.join(candidate, `index${extension}`));
|
|
3099
|
+
}
|
|
3100
|
+
for (const sourcePath of paths) {
|
|
3101
|
+
try {
|
|
3102
|
+
if (fs4.statSync(sourcePath).isFile()) return sourcePath;
|
|
3103
|
+
} catch {
|
|
3104
|
+
}
|
|
3105
|
+
}
|
|
3106
|
+
}
|
|
3107
|
+
return null;
|
|
3108
|
+
}
|
|
3109
|
+
function isFarmPackageClientBoundary(importerPath, specifier, root) {
|
|
3110
|
+
const imported = resolveImportedModule(importerPath, specifier, root);
|
|
3111
|
+
if (imported.local || !imported.path) return false;
|
|
3112
|
+
return inspectPackageClientBoundary(imported.path, root, /* @__PURE__ */ new Set()).shouldHydrate;
|
|
3113
|
+
}
|
|
3114
|
+
var CLIENT_PACKAGE_SCAN_EXTENSIONS = /\.(?:[cm]?[jt]sx?)$/;
|
|
3115
|
+
var CLIENT_PACKAGE_SCAN_SKIP = /* @__PURE__ */ new Set(["node_modules", ".farm", ".git", "dist", ".output"]);
|
|
3116
|
+
function bareSpecifierPackage(specifier) {
|
|
3117
|
+
if (specifier.startsWith(".") || specifier.startsWith("/") || specifier.startsWith("#") || specifier.startsWith("node:") || specifier.startsWith("virtual:") || specifier.includes("\0") || // A package's stylesheet or asset is not a module for the optimizer.
|
|
3118
|
+
/\.(?:css|scss|sass|less|styl|svg|png|jpe?g|gif|webp|avif|ico|woff2?|ttf|json|wasm)$/.test(
|
|
3119
|
+
specifier
|
|
3120
|
+
)) {
|
|
3121
|
+
return null;
|
|
3122
|
+
}
|
|
3123
|
+
return specifier;
|
|
3124
|
+
}
|
|
3125
|
+
function collectFarmClientPackageImports(directory, root) {
|
|
3126
|
+
return scanFarmPackageImports(directory, root).client;
|
|
3127
|
+
}
|
|
3128
|
+
function scanFarmPackageImports(directory, root) {
|
|
3129
|
+
const found = /* @__PURE__ */ new Set();
|
|
3130
|
+
const server = /* @__PURE__ */ new Set();
|
|
3131
|
+
const walk2 = (current) => {
|
|
3132
|
+
let entries;
|
|
3133
|
+
try {
|
|
3134
|
+
entries = fs4.readdirSync(current, { withFileTypes: true });
|
|
3135
|
+
} catch {
|
|
3136
|
+
return;
|
|
3137
|
+
}
|
|
3138
|
+
for (const entry of entries) {
|
|
3139
|
+
if (entry.name.startsWith(".") && entry.isDirectory()) continue;
|
|
3140
|
+
const file = path4.join(current, entry.name);
|
|
3141
|
+
if (entry.isDirectory()) {
|
|
3142
|
+
if (!CLIENT_PACKAGE_SCAN_SKIP.has(entry.name)) walk2(file);
|
|
3143
|
+
continue;
|
|
3144
|
+
}
|
|
3145
|
+
if (!CLIENT_PACKAGE_SCAN_EXTENSIONS.test(entry.name) || entry.name.endsWith(".d.ts"))
|
|
3146
|
+
continue;
|
|
3147
|
+
const content = readIfExists(file);
|
|
3148
|
+
if (!content) continue;
|
|
3149
|
+
const client = hasUseClientDirective(content);
|
|
3150
|
+
for (const specifier of new Set(getImportSpecifiers(content))) {
|
|
3151
|
+
const name = bareSpecifierPackage(specifier);
|
|
3152
|
+
if (!name) continue;
|
|
3153
|
+
if (!client) server.add(name);
|
|
3154
|
+
if (found.has(name)) continue;
|
|
3155
|
+
if (client || isFarmPackageClientBoundary(file, name, root)) found.add(name);
|
|
3156
|
+
}
|
|
3157
|
+
}
|
|
3158
|
+
};
|
|
3159
|
+
walk2(directory);
|
|
3160
|
+
return { client: [...found].sort(), server };
|
|
3161
|
+
}
|
|
3162
|
+
function collectFarmServerBundledPackages(directory) {
|
|
3163
|
+
const found = /* @__PURE__ */ new Set();
|
|
3164
|
+
const checked = /* @__PURE__ */ new Set();
|
|
3165
|
+
const walk2 = (current) => {
|
|
3166
|
+
let entries;
|
|
3167
|
+
try {
|
|
3168
|
+
entries = fs4.readdirSync(current, { withFileTypes: true });
|
|
3169
|
+
} catch {
|
|
3170
|
+
return;
|
|
3171
|
+
}
|
|
3172
|
+
for (const entry of entries) {
|
|
3173
|
+
if (entry.name.startsWith(".") && entry.isDirectory()) continue;
|
|
3174
|
+
const file = path4.join(current, entry.name);
|
|
3175
|
+
if (entry.isDirectory()) {
|
|
3176
|
+
if (!CLIENT_PACKAGE_SCAN_SKIP.has(entry.name)) walk2(file);
|
|
3177
|
+
continue;
|
|
3178
|
+
}
|
|
3179
|
+
if (!CLIENT_PACKAGE_SCAN_EXTENSIONS.test(entry.name) || entry.name.endsWith(".d.ts"))
|
|
3180
|
+
continue;
|
|
3181
|
+
const content = readIfExists(file);
|
|
3182
|
+
if (!content) continue;
|
|
3183
|
+
for (const specifier of new Set(getImportSpecifiers(content))) {
|
|
3184
|
+
const name = bareSpecifierPackage(specifier);
|
|
3185
|
+
if (!name || checked.has(name)) continue;
|
|
3186
|
+
checked.add(name);
|
|
3187
|
+
const bundled = findFarmServerBundledPackage(file, name);
|
|
3188
|
+
if (bundled) found.add(bundled);
|
|
3189
|
+
}
|
|
3190
|
+
}
|
|
3191
|
+
};
|
|
3192
|
+
walk2(directory);
|
|
3193
|
+
return [...found].sort();
|
|
3194
|
+
}
|
|
3195
|
+
var clientReachableModules = /* @__PURE__ */ new Map();
|
|
3196
|
+
function invalidateFarmClientReachableModules() {
|
|
3197
|
+
clientReachableModules.clear();
|
|
3198
|
+
}
|
|
3199
|
+
function getFarmClientReachableModules(directory, root) {
|
|
3200
|
+
const key = `${path4.resolve(root)}\0${path4.resolve(directory)}`;
|
|
3201
|
+
const cached = clientReachableModules.get(key);
|
|
3202
|
+
if (cached) return cached;
|
|
3203
|
+
const reachable = /* @__PURE__ */ new Set();
|
|
3204
|
+
const queue = [];
|
|
3205
|
+
const walk2 = (current) => {
|
|
3206
|
+
let entries;
|
|
3207
|
+
try {
|
|
3208
|
+
entries = fs4.readdirSync(current, { withFileTypes: true });
|
|
3209
|
+
} catch {
|
|
3210
|
+
return;
|
|
3211
|
+
}
|
|
3212
|
+
for (const entry of entries) {
|
|
3213
|
+
const file = path4.join(current, entry.name);
|
|
3214
|
+
if (entry.isDirectory()) {
|
|
3215
|
+
if (!entry.name.startsWith(".") && !CLIENT_PACKAGE_SCAN_SKIP.has(entry.name)) walk2(file);
|
|
3216
|
+
} else if (CLIENT_PACKAGE_SCAN_EXTENSIONS.test(entry.name) && !entry.name.endsWith(".d.ts")) {
|
|
3217
|
+
const content = readIfExists(file);
|
|
3218
|
+
if (hasUseClientDirective(content) || hasHydrateExport(content)) queue.push(file);
|
|
3219
|
+
}
|
|
3220
|
+
}
|
|
3221
|
+
};
|
|
3222
|
+
walk2(directory);
|
|
3223
|
+
while (queue.length > 0) {
|
|
3224
|
+
const file = path4.resolve(queue.pop());
|
|
3225
|
+
if (reachable.has(file)) continue;
|
|
3226
|
+
reachable.add(file);
|
|
3227
|
+
for (const specifier of getImportSpecifiers(readIfExists(file), { dynamic: true })) {
|
|
3228
|
+
const imported = resolveImportedModule(file, specifier, root);
|
|
3229
|
+
if (imported.local && imported.path && !reachable.has(path4.resolve(imported.path))) {
|
|
3230
|
+
queue.push(imported.path);
|
|
3231
|
+
}
|
|
3232
|
+
}
|
|
3233
|
+
}
|
|
3234
|
+
clientReachableModules.set(key, reachable);
|
|
3235
|
+
return reachable;
|
|
3236
|
+
}
|
|
3237
|
+
function resolveFarmClientOptimizeDeps(directory, root) {
|
|
3238
|
+
const importer = path4.join(path4.resolve(root), "package.json");
|
|
3239
|
+
const include = /* @__PURE__ */ new Set();
|
|
3240
|
+
const exclude = /* @__PURE__ */ new Set();
|
|
3241
|
+
const imports = scanFarmPackageImports(directory, root);
|
|
3242
|
+
for (const specifier of imports.client) {
|
|
3243
|
+
const manifest = findFarmPackageManifest(importer, specifier);
|
|
3244
|
+
if (manifest && farmReactServerBuildReachesClientModules(importer, specifier, imports.server.has(specifier))) {
|
|
3245
|
+
exclude.add(manifest.name);
|
|
3246
|
+
for (const dependency of manifest.dependencies) {
|
|
3247
|
+
include.add(`${manifest.name} > ${dependency}`);
|
|
3248
|
+
}
|
|
3249
|
+
} else {
|
|
3250
|
+
include.add(specifier);
|
|
3251
|
+
}
|
|
3252
|
+
}
|
|
3253
|
+
for (const name of exclude) {
|
|
3254
|
+
for (const entry of include) {
|
|
3255
|
+
const target = entry.includes(" > ") ? entry.slice(entry.lastIndexOf(" > ") + 3) : entry;
|
|
3256
|
+
if (target === name || target.startsWith(`${name}/`)) include.delete(entry);
|
|
3257
|
+
}
|
|
3258
|
+
}
|
|
3259
|
+
return { include: [...include].sort(), exclude: [...exclude].sort() };
|
|
3260
|
+
}
|
|
3261
|
+
|
|
3262
|
+
// src/environment-vite.ts
|
|
3263
|
+
var ENVIRONMENT_IMPORTS = /* @__PURE__ */ new Set([
|
|
3264
|
+
"@farm.js/core",
|
|
3265
|
+
"@farm.js/core/environment",
|
|
3266
|
+
"@farm.js/core/server"
|
|
3267
|
+
]);
|
|
3268
|
+
var ENVIRONMENT_FUNCTIONS = /* @__PURE__ */ new Set([
|
|
3269
|
+
"createServerOnlyFn",
|
|
3270
|
+
"createClientOnlyFn",
|
|
3271
|
+
"createIsomorphicFn"
|
|
3272
|
+
]);
|
|
3273
|
+
var MODULE_EXTENSION_RE2 = /\.[cm]?[jt]sx?$/;
|
|
3274
|
+
function transformEnvironmentFunctions(options) {
|
|
3275
|
+
if (!isTransformableModule(options.id) || !containsEnvironmentFunction(options.code)) {
|
|
3276
|
+
return null;
|
|
3277
|
+
}
|
|
3278
|
+
let output = options.code;
|
|
3279
|
+
let transformed = false;
|
|
3280
|
+
for (let pass = 0; pass < 20; pass++) {
|
|
3281
|
+
const ast = options.parse(output);
|
|
3282
|
+
const bindings = findEnvironmentFunctionBindings(ast);
|
|
3283
|
+
if (bindings.named.size === 0 && bindings.namespaces.size === 0) break;
|
|
3284
|
+
const calls = findEnvironmentCalls(ast, bindings);
|
|
3285
|
+
if (calls.length === 0) break;
|
|
3286
|
+
const innermostCalls = calls.filter(
|
|
3287
|
+
(call) => !calls.some(
|
|
3288
|
+
(candidate) => candidate !== call && candidate.node.start > call.node.start && candidate.node.end < call.node.end
|
|
3289
|
+
)
|
|
3290
|
+
);
|
|
3291
|
+
const replacements = innermostCalls.map(
|
|
3292
|
+
(call) => createReplacement(output, options.id, options.environment, call)
|
|
3293
|
+
);
|
|
3294
|
+
output = applyReplacements(output, replacements);
|
|
3295
|
+
transformed = true;
|
|
3296
|
+
}
|
|
3297
|
+
if (!transformed) return null;
|
|
3298
|
+
const remainingAst = options.parse(output);
|
|
3299
|
+
const remainingBindings = findEnvironmentFunctionBindings(remainingAst);
|
|
3300
|
+
if (findEnvironmentCalls(remainingAst, remainingBindings).length > 0) {
|
|
3301
|
+
throw transformError(options.id, "environment functions are nested too deeply");
|
|
3302
|
+
}
|
|
3303
|
+
return { code: output };
|
|
3304
|
+
}
|
|
3305
|
+
function farmEnvironmentFunctionsPlugin(options = {}) {
|
|
3306
|
+
let routesFiles = /* @__PURE__ */ new Set();
|
|
3307
|
+
let farmApi;
|
|
3308
|
+
let isBuild = false;
|
|
3309
|
+
let projectRoot = process.cwd();
|
|
3310
|
+
let sources;
|
|
3311
|
+
const routeSourceFiles = () => {
|
|
3312
|
+
const clientRoutes = farmApi?.getProgrammaticClientRoutes();
|
|
3313
|
+
if (sources?.for !== clientRoutes || !sources) {
|
|
3314
|
+
sources = {
|
|
3315
|
+
for: clientRoutes,
|
|
3316
|
+
files: /* @__PURE__ */ new Set([
|
|
3317
|
+
...routesFiles,
|
|
3318
|
+
...[...clientRoutes?.routeSourceFiles ?? []].map(resolvedFile)
|
|
3319
|
+
])
|
|
3320
|
+
};
|
|
3321
|
+
}
|
|
3322
|
+
return sources.files;
|
|
3323
|
+
};
|
|
3324
|
+
const routeSourceError = (file, importers = []) => `[Farm.js] ${file} defines programmatic routes, but the browser bundle imports it` + (importers.length > 0 ? ` (from ${importers.join(", ")})` : "") + ". Routes files and the modules that define routes carry server-only guards, data hooks, and API handlers, so they never reach the browser. Import the component, server function, or helper from its own module instead.";
|
|
3325
|
+
return {
|
|
3326
|
+
name: "farm:environment-functions",
|
|
3327
|
+
enforce: "post",
|
|
3328
|
+
configResolved(config) {
|
|
3329
|
+
isBuild = config.command === "build";
|
|
3330
|
+
projectRoot = config.root;
|
|
3331
|
+
farmApi = config.plugins.find((plugin) => plugin.name === "farm")?.api;
|
|
3332
|
+
sources = void 0;
|
|
3333
|
+
routesFiles = new Set(
|
|
3334
|
+
getFarmSourceRoots({ ...options, root: options.root ?? config.root }).flatMap(
|
|
3335
|
+
(source) => PROGRAMMATIC_ROUTE_FILE_NAMES.map(
|
|
3336
|
+
(name) => resolvedFile(path5.resolve(source.root, source.srcDir, name))
|
|
3337
|
+
)
|
|
3338
|
+
)
|
|
3339
|
+
);
|
|
3340
|
+
},
|
|
3341
|
+
transform(code, id, transformOptions) {
|
|
3342
|
+
const environment = resolveBuildEnvironment(
|
|
3343
|
+
this,
|
|
3344
|
+
transformOptions?.ssr
|
|
3345
|
+
);
|
|
3346
|
+
const parse2 = (source) => this.parse(source);
|
|
3347
|
+
const result = transformEnvironmentFunctions({ code, id, environment, parse: parse2 });
|
|
3348
|
+
if (environment === "client" && !isBuild && !parseProgrammaticRouteModuleId(id) && routeSourceFiles().has(moduleFile(id)) && !isProgrammaticRouteActionProxy(code)) {
|
|
3349
|
+
this.error(routeSourceError(moduleFile(id)));
|
|
3350
|
+
}
|
|
3351
|
+
if (environment === "server" && resolveFarmServerComponentsMode(options.experimental?.serverComponents) === "islands" && isApplicationScript(id)) {
|
|
3352
|
+
const file = id.split("?", 1)[0];
|
|
3353
|
+
const root = realpathSync(options.root ?? projectRoot);
|
|
3354
|
+
const clientCode = getFarmClientReachableModules(
|
|
3355
|
+
path5.resolve(root, options.srcDir || "src"),
|
|
3356
|
+
root
|
|
3357
|
+
).has(path5.resolve(file));
|
|
3358
|
+
const reached = clientCode ? null : findFarmClientOnlyImport(code, file);
|
|
3359
|
+
if (reached) {
|
|
3360
|
+
const chain = reached.chain.map((step) => path5.relative(root, step)).join(" -> ");
|
|
3361
|
+
this.error(
|
|
3362
|
+
`[Farm.js] ${path5.relative(root, file)} is server code, but its import of "${reached.specifier}" reaches "client-only" (${chain}), so that package can only run in the browser. Add "use client" to this module, or import the package from a "use client" module.`
|
|
3363
|
+
);
|
|
3364
|
+
}
|
|
3365
|
+
}
|
|
3366
|
+
return result ? { code: result.code, map: null } : null;
|
|
3367
|
+
},
|
|
3368
|
+
generateBundle() {
|
|
3369
|
+
const context = this;
|
|
3370
|
+
if (resolveBuildEnvironment(context, false) !== "client") return;
|
|
3371
|
+
const forbidden = routeSourceFiles();
|
|
3372
|
+
for (const id of this.getModuleIds()) {
|
|
3373
|
+
if (parseProgrammaticRouteModuleId(id)) {
|
|
3374
|
+
const chain = findClientNodeBuiltinChain(id, (moduleId) => {
|
|
3375
|
+
return this.getModuleInfo(moduleId)?.importedIds;
|
|
3376
|
+
});
|
|
3377
|
+
if (chain) {
|
|
3378
|
+
this.error(
|
|
3379
|
+
`[Farm.js] The browser bundle reaches the server-only module "${chain.at(-1)}" through the programmatic route module ${moduleFile(id)}: ${chain.map(moduleFile).join(" -> ")}. Keep server-only imports in the routes file or in modules only its guard, data, and API handlers use.`
|
|
3380
|
+
);
|
|
3381
|
+
}
|
|
3382
|
+
continue;
|
|
3383
|
+
}
|
|
3384
|
+
if (!forbidden.has(moduleFile(id))) continue;
|
|
3385
|
+
const info = this.getModuleInfo(id);
|
|
3386
|
+
if (isProgrammaticRouteActionProxy(info?.code)) continue;
|
|
3387
|
+
this.error(routeSourceError(moduleFile(id), info?.importers.map(moduleFile)));
|
|
3388
|
+
}
|
|
3389
|
+
}
|
|
3390
|
+
};
|
|
3391
|
+
}
|
|
3392
|
+
function isApplicationScript(id) {
|
|
3393
|
+
return !id.startsWith("\0") && !id.includes("/node_modules/") && !id.includes("/.farm/") && /\.[cm]?[jt]sx?(?:$|\?)/.test(id);
|
|
3394
|
+
}
|
|
3395
|
+
function moduleFile(id) {
|
|
3396
|
+
return id.split("?", 1)[0].replace(/\\/g, "/");
|
|
3397
|
+
}
|
|
3398
|
+
function resolvedFile(filePath) {
|
|
3399
|
+
try {
|
|
3400
|
+
return moduleFile(realpathSync(filePath));
|
|
3401
|
+
} catch {
|
|
3402
|
+
return moduleFile(filePath);
|
|
3403
|
+
}
|
|
3404
|
+
}
|
|
3405
|
+
function resolveBuildEnvironment(context, ssr) {
|
|
3406
|
+
if (context.environment?.name === "client") return "client";
|
|
3407
|
+
if (context.environment?.name === "rsc" || context.environment?.name === "ssr") {
|
|
3408
|
+
return "server";
|
|
3409
|
+
}
|
|
3410
|
+
return ssr ? "server" : "client";
|
|
3411
|
+
}
|
|
3412
|
+
function findEnvironmentFunctionBindings(ast) {
|
|
3413
|
+
const named = /* @__PURE__ */ new Map();
|
|
3414
|
+
const namespaces = /* @__PURE__ */ new Set();
|
|
3415
|
+
const body = Array.isArray(ast.body) ? ast.body : [];
|
|
3416
|
+
for (const statement of body) {
|
|
3417
|
+
if (!isAstNode(statement) || statement.type !== "ImportDeclaration") continue;
|
|
3418
|
+
const source = isAstNode(statement.source) ? statement.source.value : void 0;
|
|
3419
|
+
if (typeof source !== "string" || !ENVIRONMENT_IMPORTS.has(source)) continue;
|
|
3420
|
+
const specifiers = Array.isArray(statement.specifiers) ? statement.specifiers : [];
|
|
3421
|
+
for (const specifier of specifiers) {
|
|
3422
|
+
if (!isAstNode(specifier) || !isAstNode(specifier.local)) continue;
|
|
3423
|
+
const localName = specifier.local.name;
|
|
3424
|
+
if (typeof localName !== "string") continue;
|
|
3425
|
+
if (specifier.type === "ImportNamespaceSpecifier") {
|
|
3426
|
+
namespaces.add(localName);
|
|
3427
|
+
continue;
|
|
3428
|
+
}
|
|
3429
|
+
if (specifier.type !== "ImportSpecifier" || !isAstNode(specifier.imported)) continue;
|
|
3430
|
+
const importedName = specifier.imported.name ?? specifier.imported.value;
|
|
3431
|
+
if (isEnvironmentFunctionKind(importedName)) {
|
|
3432
|
+
named.set(localName, importedName);
|
|
3433
|
+
}
|
|
3434
|
+
}
|
|
3435
|
+
}
|
|
3436
|
+
return { named, namespaces };
|
|
3437
|
+
}
|
|
3438
|
+
function findEnvironmentCalls(ast, bindings) {
|
|
3439
|
+
const calls = [];
|
|
3440
|
+
walkAst(ast, (node, ancestors) => {
|
|
3441
|
+
if (node.type !== "CallExpression" || !isAstNode(node.callee)) return;
|
|
3442
|
+
if (node.callee.type === "Identifier" && typeof node.callee.name === "string") {
|
|
3443
|
+
const kind = bindings.named.get(node.callee.name);
|
|
3444
|
+
if (kind && !isNameShadowed(node.callee.name, ancestors)) calls.push({ node, kind });
|
|
3445
|
+
return;
|
|
3446
|
+
}
|
|
3447
|
+
if (node.callee.type !== "MemberExpression" || node.callee.computed === true || !isAstNode(node.callee.object) || !isAstNode(node.callee.property) || node.callee.object.type !== "Identifier" || node.callee.property.type !== "Identifier" || typeof node.callee.object.name !== "string" || typeof node.callee.property.name !== "string" || !bindings.namespaces.has(node.callee.object.name) || isNameShadowed(node.callee.object.name, ancestors) || !isEnvironmentFunctionKind(node.callee.property.name)) {
|
|
3448
|
+
return;
|
|
3449
|
+
}
|
|
3450
|
+
calls.push({ node, kind: node.callee.property.name });
|
|
3451
|
+
});
|
|
3452
|
+
return calls;
|
|
3453
|
+
}
|
|
3454
|
+
function createReplacement(code, id, environment, call) {
|
|
3455
|
+
const args = Array.isArray(call.node.arguments) ? call.node.arguments : [];
|
|
3456
|
+
if (args.length !== 1 || !isAstNode(args[0]) || args[0].type === "SpreadElement") {
|
|
3457
|
+
throw transformError(id, `${call.kind}() requires exactly one static argument`);
|
|
3458
|
+
}
|
|
3459
|
+
let replacement;
|
|
3460
|
+
if (call.kind === "createIsomorphicFn") {
|
|
3461
|
+
replacement = selectIsomorphicImplementation(code, id, environment, args[0]);
|
|
3462
|
+
} else {
|
|
3463
|
+
const expected = call.kind === "createServerOnlyFn" ? "server" : "client";
|
|
3464
|
+
replacement = environment === expected ? readNode(code, args[0]) : `(0, ${readNode(code, call.node.callee)})(undefined, ${JSON.stringify(environment)})`;
|
|
3465
|
+
}
|
|
3466
|
+
return {
|
|
3467
|
+
start: call.node.start,
|
|
3468
|
+
end: call.node.end,
|
|
3469
|
+
code: `(${replacement})`
|
|
3470
|
+
};
|
|
3471
|
+
}
|
|
3472
|
+
function selectIsomorphicImplementation(code, id, environment, optionsNode) {
|
|
3473
|
+
if (optionsNode.type !== "ObjectExpression") {
|
|
3474
|
+
throw transformError(id, "createIsomorphicFn() requires an inline options object");
|
|
3475
|
+
}
|
|
3476
|
+
const properties = Array.isArray(optionsNode.properties) ? optionsNode.properties : [];
|
|
3477
|
+
if (properties.some((property) => isAstNode(property) && property.type === "SpreadElement")) {
|
|
3478
|
+
throw transformError(id, "createIsomorphicFn() does not support spread properties");
|
|
3479
|
+
}
|
|
3480
|
+
let selectedProperty;
|
|
3481
|
+
for (const property of properties) {
|
|
3482
|
+
if (!isAstNode(property) || property.type !== "Property" || property.computed === true) {
|
|
3483
|
+
continue;
|
|
3484
|
+
}
|
|
3485
|
+
const key = readPropertyName(property.key);
|
|
3486
|
+
if (key === environment) selectedProperty = property;
|
|
3487
|
+
}
|
|
3488
|
+
if (!selectedProperty || !isAstNode(selectedProperty.value)) {
|
|
3489
|
+
throw transformError(id, `createIsomorphicFn() requires a ${environment} implementation`);
|
|
3490
|
+
}
|
|
3491
|
+
if (selectedProperty.kind !== void 0 && selectedProperty.kind !== "init") {
|
|
3492
|
+
throw transformError(id, "createIsomorphicFn() does not support getters or setters");
|
|
3493
|
+
}
|
|
3494
|
+
return selectedProperty.method === true ? renderObjectMethod(code, id, selectedProperty.value) : readNode(code, selectedProperty.value);
|
|
3495
|
+
}
|
|
3496
|
+
function renderObjectMethod(code, id, functionNode) {
|
|
3497
|
+
if (!isAstNode(functionNode.body) || !Array.isArray(functionNode.params)) {
|
|
3498
|
+
throw transformError(id, "createIsomorphicFn() received an unsupported method");
|
|
3499
|
+
}
|
|
3500
|
+
const params = functionNode.params.map((param) => {
|
|
3501
|
+
if (!isAstNode(param)) {
|
|
3502
|
+
throw transformError(id, "createIsomorphicFn() received an unsupported parameter");
|
|
3503
|
+
}
|
|
3504
|
+
return readNode(code, param);
|
|
3505
|
+
});
|
|
3506
|
+
const asyncPrefix = functionNode.async === true ? "async " : "";
|
|
3507
|
+
const generatorMarker = functionNode.generator === true ? "*" : "";
|
|
3508
|
+
return `${asyncPrefix}function${generatorMarker}(${params.join(", ")}) ${readNode(code, functionNode.body)}`;
|
|
3509
|
+
}
|
|
3510
|
+
function applyReplacements(code, replacements) {
|
|
3511
|
+
let output = code;
|
|
3512
|
+
for (const replacement of replacements.sort((left, right) => right.start - left.start)) {
|
|
3513
|
+
output = output.slice(0, replacement.start) + replacement.code + output.slice(replacement.end);
|
|
3514
|
+
}
|
|
3515
|
+
return output;
|
|
3516
|
+
}
|
|
3517
|
+
function walkAst(node, visit, ancestors = []) {
|
|
3518
|
+
visit(node, ancestors);
|
|
3519
|
+
const childAncestors = [...ancestors, node];
|
|
3520
|
+
for (const [key, value] of Object.entries(node)) {
|
|
3521
|
+
if (key === "start" || key === "end" || key === "loc" || key === "range") continue;
|
|
3522
|
+
if (isAstNode(value)) {
|
|
3523
|
+
walkAst(value, visit, childAncestors);
|
|
3524
|
+
} else if (Array.isArray(value)) {
|
|
3525
|
+
for (const item of value) {
|
|
3526
|
+
if (isAstNode(item)) walkAst(item, visit, childAncestors);
|
|
3527
|
+
}
|
|
3528
|
+
}
|
|
3529
|
+
}
|
|
3530
|
+
}
|
|
3531
|
+
function isNameShadowed(name, ancestors) {
|
|
3532
|
+
for (const [index, ancestor] of ancestors.entries()) {
|
|
3533
|
+
if (isFunctionNode(ancestor)) {
|
|
3534
|
+
const params = Array.isArray(ancestor.params) ? ancestor.params : [];
|
|
3535
|
+
if (params.some((param) => patternContainsName(param, name))) return true;
|
|
3536
|
+
if (patternContainsName(ancestor.id, name)) return true;
|
|
3537
|
+
if (isAstNode(ancestor.body) && ancestors.slice(index + 1).includes(ancestor.body) && functionBodyDeclaresVarName(ancestor.body, name)) {
|
|
3538
|
+
return true;
|
|
3539
|
+
}
|
|
3540
|
+
}
|
|
3541
|
+
if (ancestor.type === "CatchClause" && patternContainsName(ancestor.param, name)) {
|
|
3542
|
+
return true;
|
|
3543
|
+
}
|
|
3544
|
+
if ((ancestor.type === "BlockStatement" || ancestor.type === "StaticBlock") && blockDeclaresName(ancestor, name)) {
|
|
3545
|
+
return true;
|
|
3546
|
+
}
|
|
3547
|
+
if (loopDeclaresName(ancestor, name)) return true;
|
|
3548
|
+
if (ancestor.type === "SwitchStatement" && ancestors.slice(index + 1).some((candidate) => candidate.type === "SwitchCase") && switchDeclaresName(ancestor, name)) {
|
|
3549
|
+
return true;
|
|
3550
|
+
}
|
|
3551
|
+
if (ancestor.type === "ClassExpression" && patternContainsName(ancestor.id, name) && ancestors.slice(index + 1).some((candidate) => candidate.type === "ClassBody")) {
|
|
3552
|
+
return true;
|
|
3553
|
+
}
|
|
3554
|
+
}
|
|
3555
|
+
return false;
|
|
3556
|
+
}
|
|
3557
|
+
function functionBodyDeclaresVarName(body, name) {
|
|
3558
|
+
if (body.type === "VariableDeclaration" && body.kind === "var") {
|
|
3559
|
+
const declarations = Array.isArray(body.declarations) ? body.declarations : [];
|
|
3560
|
+
if (declarations.some(
|
|
3561
|
+
(declaration) => isAstNode(declaration) && patternContainsName(declaration.id, name)
|
|
3562
|
+
)) {
|
|
3563
|
+
return true;
|
|
3564
|
+
}
|
|
3565
|
+
}
|
|
3566
|
+
for (const [key, value] of Object.entries(body)) {
|
|
3567
|
+
if (key === "start" || key === "end" || key === "loc" || key === "range") continue;
|
|
3568
|
+
if (isAstNode(value)) {
|
|
3569
|
+
if (isNestedVarScope(value)) continue;
|
|
3570
|
+
if (functionBodyDeclaresVarName(value, name)) return true;
|
|
3571
|
+
} else if (Array.isArray(value)) {
|
|
3572
|
+
for (const item of value) {
|
|
3573
|
+
if (!isAstNode(item) || isNestedVarScope(item)) continue;
|
|
3574
|
+
if (functionBodyDeclaresVarName(item, name)) return true;
|
|
3575
|
+
}
|
|
3576
|
+
}
|
|
3577
|
+
}
|
|
3578
|
+
return false;
|
|
3579
|
+
}
|
|
3580
|
+
function isNestedVarScope(node) {
|
|
3581
|
+
return isFunctionNode(node) || node.type === "ClassDeclaration" || node.type === "ClassExpression";
|
|
3582
|
+
}
|
|
3583
|
+
function loopDeclaresName(node, name) {
|
|
3584
|
+
const declaration = node.type === "ForStatement" ? node.init : node.type === "ForInStatement" || node.type === "ForOfStatement" ? node.left : void 0;
|
|
3585
|
+
if (!isAstNode(declaration) || declaration.type !== "VariableDeclaration") return false;
|
|
3586
|
+
const declarations = Array.isArray(declaration.declarations) ? declaration.declarations : [];
|
|
3587
|
+
return declarations.some((item) => isAstNode(item) && patternContainsName(item.id, name));
|
|
3588
|
+
}
|
|
3589
|
+
function switchDeclaresName(node, name) {
|
|
3590
|
+
const cases = Array.isArray(node.cases) ? node.cases : [];
|
|
3591
|
+
return cases.some((switchCase) => {
|
|
3592
|
+
if (!isAstNode(switchCase) || !Array.isArray(switchCase.consequent)) return false;
|
|
3593
|
+
return switchCase.consequent.some((statement) => {
|
|
3594
|
+
if (!isAstNode(statement)) return false;
|
|
3595
|
+
if ((statement.type === "FunctionDeclaration" || statement.type === "ClassDeclaration") && patternContainsName(statement.id, name)) {
|
|
3596
|
+
return true;
|
|
3597
|
+
}
|
|
3598
|
+
if (statement.type !== "VariableDeclaration" || statement.kind === "var") return false;
|
|
3599
|
+
const declarations = Array.isArray(statement.declarations) ? statement.declarations : [];
|
|
3600
|
+
return declarations.some(
|
|
3601
|
+
(declaration) => isAstNode(declaration) && patternContainsName(declaration.id, name)
|
|
3602
|
+
);
|
|
3603
|
+
});
|
|
3604
|
+
});
|
|
3605
|
+
}
|
|
3606
|
+
function blockDeclaresName(block, name) {
|
|
3607
|
+
const statements = Array.isArray(block.body) ? block.body : [];
|
|
3608
|
+
for (const statement of statements) {
|
|
3609
|
+
if (!isAstNode(statement)) continue;
|
|
3610
|
+
if ((statement.type === "FunctionDeclaration" || statement.type === "ClassDeclaration") && patternContainsName(statement.id, name)) {
|
|
3611
|
+
return true;
|
|
3612
|
+
}
|
|
3613
|
+
if (statement.type !== "VariableDeclaration" || !Array.isArray(statement.declarations)) {
|
|
3614
|
+
continue;
|
|
3615
|
+
}
|
|
3616
|
+
if (statement.declarations.some(
|
|
3617
|
+
(declaration) => isAstNode(declaration) && patternContainsName(declaration.id, name)
|
|
3618
|
+
)) {
|
|
3619
|
+
return true;
|
|
3620
|
+
}
|
|
3621
|
+
}
|
|
3622
|
+
return false;
|
|
3623
|
+
}
|
|
3624
|
+
function patternContainsName(value, name) {
|
|
3625
|
+
if (!isAstNode(value)) return false;
|
|
3626
|
+
if (value.type === "Identifier") return value.name === name;
|
|
3627
|
+
if (value.type === "RestElement") return patternContainsName(value.argument, name);
|
|
3628
|
+
if (value.type === "AssignmentPattern") return patternContainsName(value.left, name);
|
|
3629
|
+
if (value.type === "Property") return patternContainsName(value.value, name);
|
|
3630
|
+
const elements = Array.isArray(value.elements) ? value.elements : Array.isArray(value.properties) ? value.properties : [];
|
|
3631
|
+
return elements.some((element) => patternContainsName(element, name));
|
|
3632
|
+
}
|
|
3633
|
+
function isFunctionNode(node) {
|
|
3634
|
+
return node.type === "FunctionDeclaration" || node.type === "FunctionExpression" || node.type === "ArrowFunctionExpression";
|
|
3635
|
+
}
|
|
3636
|
+
function readPropertyName(value) {
|
|
3637
|
+
if (!isAstNode(value)) return void 0;
|
|
3638
|
+
if (value.type === "Identifier" && typeof value.name === "string") return value.name;
|
|
3639
|
+
if (value.type === "Literal" && typeof value.value === "string") return value.value;
|
|
3640
|
+
return void 0;
|
|
3641
|
+
}
|
|
3642
|
+
function readNode(code, node) {
|
|
3643
|
+
return code.slice(node.start, node.end);
|
|
3644
|
+
}
|
|
3645
|
+
function isAstNode(value) {
|
|
3646
|
+
return !!value && typeof value === "object" && typeof value.type === "string" && typeof value.start === "number" && typeof value.end === "number";
|
|
3647
|
+
}
|
|
3648
|
+
function isEnvironmentFunctionKind(value) {
|
|
3649
|
+
return typeof value === "string" && ENVIRONMENT_FUNCTIONS.has(value);
|
|
3650
|
+
}
|
|
3651
|
+
function containsEnvironmentFunction(code) {
|
|
3652
|
+
return Array.from(ENVIRONMENT_FUNCTIONS).some((name) => code.includes(name));
|
|
3653
|
+
}
|
|
3654
|
+
function isTransformableModule(id) {
|
|
3655
|
+
const cleanId = id.split("?", 1)[0];
|
|
3656
|
+
return MODULE_EXTENSION_RE2.test(cleanId) && !/\.d\.[cm]?ts$/.test(cleanId);
|
|
3657
|
+
}
|
|
3658
|
+
function transformError(id, message) {
|
|
3659
|
+
return new Error(`[Farm environment functions] ${message} in ${id.split("?", 1)[0]}`);
|
|
3660
|
+
}
|
|
3661
|
+
|
|
3662
|
+
export {
|
|
3663
|
+
resolveFarmBrowserBuiltin,
|
|
3664
|
+
loadFarmBrowserBuiltin,
|
|
3665
|
+
farmBrowserBuiltinsOptimizerPlugin,
|
|
3666
|
+
programmaticClientRouteKey,
|
|
3667
|
+
resolveProgrammaticClientRoutes,
|
|
3668
|
+
createEvaluatedRouteGraph,
|
|
3669
|
+
mergeProgrammaticClientRoutes,
|
|
3670
|
+
generateProgrammaticClientRouteModule,
|
|
3671
|
+
rewriteFarmReactServerImports,
|
|
3672
|
+
invalidateFarmClientOnlyScan,
|
|
3673
|
+
farmRelativeImportFiles,
|
|
3674
|
+
FARM_CLIENT_REFERENCE_PRAGMA,
|
|
3675
|
+
FARM_CLIENT_REFERENCE_DIRECTORY,
|
|
3676
|
+
ensureFarmPackageClientReference,
|
|
3677
|
+
rewriteFarmPackageClientImports,
|
|
3678
|
+
withPackageClientBoundaryCache,
|
|
3679
|
+
usePackageClientBoundaryCacheFile,
|
|
3680
|
+
resolveModuleSourcePath,
|
|
3681
|
+
getFarmClientHydrationPlanOptions,
|
|
3682
|
+
describeSuppressedAsyncHydration,
|
|
3683
|
+
resolveFarmIsolatedClientHydrationMode,
|
|
3684
|
+
hasUseClientDirective,
|
|
3685
|
+
getIslandStrategyExport,
|
|
3686
|
+
stripUseClientDirective,
|
|
3687
|
+
collectFarmRenderedClientModules,
|
|
3688
|
+
collectFarmServerStylesheets,
|
|
3689
|
+
getClientModuleMetadata,
|
|
3690
|
+
getClientModuleHydrationPlan,
|
|
3691
|
+
usesFarmServerTree,
|
|
3692
|
+
createMarkdownPageHydrationPlanner,
|
|
3693
|
+
enforceFarmIsolatedHydrationRouteBudget,
|
|
3694
|
+
isIsolatableClientBoundarySource,
|
|
3695
|
+
resolveImportedModule,
|
|
3696
|
+
isFarmPackageClientBoundary,
|
|
3697
|
+
collectFarmClientPackageImports,
|
|
3698
|
+
collectFarmServerBundledPackages,
|
|
3699
|
+
invalidateFarmClientReachableModules,
|
|
3700
|
+
getFarmClientReachableModules,
|
|
3701
|
+
resolveFarmClientOptimizeDeps,
|
|
3702
|
+
transformEnvironmentFunctions,
|
|
3703
|
+
farmEnvironmentFunctionsPlugin
|
|
3704
|
+
};
|