@xfe-repo/web-app 2.0.0-beta.1 → 2.0.0-beta.3

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/cli.mjs CHANGED
@@ -1,108 +1,176 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropNames = Object.getOwnPropertyNames;
1
3
  var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
2
4
  get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
3
5
  }) : x)(function(x) {
4
6
  if (typeof require !== "undefined") return require.apply(this, arguments);
5
7
  throw Error('Dynamic require of "' + x + '" is not supported');
6
8
  });
7
-
8
- // src/cli.ts
9
- import { spawnSync } from "child_process";
10
- import { mkdirSync } from "fs";
11
- import path4 from "path";
9
+ var __esm = (fn, res) => function __init() {
10
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
11
+ };
12
+ var __export = (target, all) => {
13
+ for (var name in all)
14
+ __defProp(target, name, { get: all[name], enumerable: true });
15
+ };
12
16
 
13
17
  // src/config.ts
14
- import path from "path";
15
18
  import fs from "fs";
19
+ import path from "path";
20
+ import { fileURLToPath } from "url";
16
21
  import yaml from "yaml";
17
- var loadXfeConfig = (root = process.cwd()) => {
18
- const xfeConfigPath = path.join(root, "xfe.json");
19
- if (!fs.existsSync(xfeConfigPath)) {
20
- throw new Error("xfe.json \u914D\u7F6E\u6587\u4EF6\u4E0D\u5B58\u5728\uFF0C\u8BF7\u5728\u9879\u76EE\u6839\u76EE\u5F55\u4E0B\u521B\u5EFA\u8BE5\u6587\u4EF6\u3002");
22
+ var DEFAULT_BUILD_DIRECTORY, BUILD_DIRECTORY_ARGUMENT, protectedDirectories, loadXfeConfig, getBuildDirectory, getServerEntry, configDeploy, getJwtEnv;
23
+ var init_config = __esm({
24
+ "src/config.ts"() {
25
+ "use strict";
26
+ DEFAULT_BUILD_DIRECTORY = "dist";
27
+ BUILD_DIRECTORY_ARGUMENT = "XFE_BUILD_DIRECTORY";
28
+ protectedDirectories = /* @__PURE__ */ new Set(["src", "types", "public", "node_modules", ".git"]);
29
+ loadXfeConfig = (root = process.cwd()) => {
30
+ const xfeConfigPath = path.join(root, "xfe.json");
31
+ if (!fs.existsSync(xfeConfigPath)) {
32
+ throw new Error("xfe.json \u914D\u7F6E\u6587\u4EF6\u4E0D\u5B58\u5728\uFF0C\u8BF7\u5728\u9879\u76EE\u6839\u76EE\u5F55\u4E0B\u521B\u5EFA\u8BE5\u6587\u4EF6\u3002");
33
+ }
34
+ const xfeConfigContent = fs.readFileSync(xfeConfigPath, "utf8");
35
+ const config = JSON.parse(xfeConfigContent);
36
+ const renderMode = config.webapp?.renderMode;
37
+ if (renderMode !== void 0 && renderMode !== "client" && renderMode !== "server") {
38
+ throw new Error("xfe.json.webapp.renderMode \u53EA\u80FD\u4E3A client \u6216 server");
39
+ }
40
+ getBuildDirectory(root, config.webapp);
41
+ getServerEntry(root, config.webapp);
42
+ return config;
43
+ };
44
+ getBuildDirectory = (projectRoot, webapp = {}) => {
45
+ const configured = webapp?.buildDirectory === void 0 ? DEFAULT_BUILD_DIRECTORY : webapp.buildDirectory;
46
+ if (typeof configured !== "string" || !configured.trim() || /[\0\r\n]/.test(configured)) {
47
+ throw new Error("xfe.json.webapp.buildDirectory \u5FC5\u987B\u662F\u975E\u7A7A\u7684\u5355\u884C\u5B57\u7B26\u4E32");
48
+ }
49
+ const directory = configured.trim().replaceAll("\\", "/");
50
+ const root = path.resolve(projectRoot);
51
+ const output = path.resolve(root, directory);
52
+ const relative = path.relative(root, output);
53
+ const [firstDirectory = ""] = relative.split(path.sep);
54
+ const escapesProject = path.isAbsolute(directory) || Boolean(path.win32.parse(directory).root) || firstDirectory === "..";
55
+ const overwritesInput = !relative || protectedDirectories.has(firstDirectory.toLowerCase());
56
+ if (escapesProject || overwritesInput) {
57
+ throw new Error("xfe.json.webapp.buildDirectory \u5FC5\u987B\u662F\u9879\u76EE\u5185\u72EC\u7ACB\u7684\u8F93\u51FA\u76EE\u5F55\uFF0C\u4E0D\u80FD\u8986\u76D6\u9879\u76EE\u3001\u6E90\u7801\u6216\u4F9D\u8D56");
58
+ }
59
+ let currentDirectory = root;
60
+ for (const segment of relative.split(path.sep)) {
61
+ currentDirectory = path.join(currentDirectory, segment);
62
+ if (fs.lstatSync(currentDirectory, { throwIfNoEntry: false })?.isSymbolicLink()) {
63
+ throw new Error("xfe.json.webapp.buildDirectory \u4E0D\u80FD\u7ECF\u8FC7\u7B26\u53F7\u94FE\u63A5\uFF0C\u4EE5\u514D\u6E05\u7406\u5176\u4ED6\u76EE\u5F55");
64
+ }
65
+ }
66
+ return output;
67
+ };
68
+ getServerEntry = (projectRoot, webapp = {}) => {
69
+ const entry = webapp?.serverEntry;
70
+ if (entry === void 0) return;
71
+ if (typeof entry !== "string" || !entry.trim() || /[\0\r\n]/.test(entry)) {
72
+ throw new Error("xfe.json.webapp.serverEntry \u5FC5\u987B\u662F\u9879\u76EE\u5185\u7684 TypeScript / JavaScript \u76F8\u5BF9\u8DEF\u5F84");
73
+ }
74
+ const normalized = entry.trim().replaceAll("\\", "/");
75
+ const absolute = path.resolve(projectRoot, normalized);
76
+ const relative = path.relative(path.resolve(projectRoot), absolute);
77
+ const outside = Boolean(path.win32.parse(normalized).root) || relative.split(path.sep)[0] === "..";
78
+ if (outside || !/\.(?:[jt]sx?|m[jt]s)$/.test(relative)) {
79
+ throw new Error("xfe.json.webapp.serverEntry \u5FC5\u987B\u662F\u9879\u76EE\u5185\u7684 TypeScript / JavaScript \u76F8\u5BF9\u8DEF\u5F84");
80
+ }
81
+ return absolute;
82
+ };
83
+ configDeploy = () => {
84
+ const xfeConfig = loadXfeConfig();
85
+ if (!xfeConfig?.deploy) return;
86
+ const configDirectory = typeof __dirname === "string" ? __dirname : path.dirname(fileURLToPath(import.meta.url));
87
+ const projectRoot = process.cwd();
88
+ const buildDirectory = path.relative(projectRoot, getBuildDirectory(projectRoot, xfeConfig.webapp)).replaceAll(path.sep, "/");
89
+ const droneConfigFilePath = path.resolve(configDirectory, "../deploy/.drone.yml");
90
+ const droneTarget = path.resolve(projectRoot, xfeConfig.deploy.droneConfigPath || "./.drone.yml");
91
+ const defaultArgument = JSON.stringify(`${BUILD_DIRECTORY_ARGUMENT}=${DEFAULT_BUILD_DIRECTORY}`);
92
+ const configuredArgument = JSON.stringify(`${BUILD_DIRECTORY_ARGUMENT}=${buildDirectory}`);
93
+ const droneConfig = fs.readFileSync(droneConfigFilePath, "utf8").replace(defaultArgument, configuredArgument);
94
+ fs.mkdirSync(path.dirname(droneTarget), { recursive: true });
95
+ fs.writeFileSync(droneTarget, droneConfig);
96
+ const valuesYamlFilePath = path.resolve(configDirectory, "../deploy/helm/values.yaml");
97
+ const valuesYamlFile = fs.readFileSync(valuesYamlFilePath, "utf8");
98
+ const valuesYaml = yaml.parse(valuesYamlFile);
99
+ if (!valuesYaml.virtualService) valuesYaml.virtualService = {};
100
+ if (!valuesYaml.virtualService.hosts) valuesYaml.virtualService.hosts = { test: [], stage: [], prod: [] };
101
+ const {
102
+ virtualServiceEnabled = true,
103
+ hostsProd = [],
104
+ hostsStage = [],
105
+ hostsTest = [],
106
+ gateways = ["common-gateway-eshetang"]
107
+ } = xfeConfig.deploy;
108
+ const { targetK8s = "saas", targetNamespace = "" } = xfeConfig.deploy;
109
+ valuesYaml.virtualService.enabled = virtualServiceEnabled;
110
+ valuesYaml.virtualService.gateways = gateways;
111
+ valuesYaml.virtualService.hosts.prod = hostsProd;
112
+ valuesYaml.virtualService.hosts.stage = hostsStage;
113
+ valuesYaml.virtualService.hosts.test = hostsTest;
114
+ valuesYaml.targetK8s = targetK8s;
115
+ valuesYaml.namespace = targetNamespace;
116
+ const valuesYamlStr = yaml.stringify(valuesYaml, { defaultStringType: "QUOTE_SINGLE", defaultKeyType: "PLAIN" });
117
+ fs.writeFileSync(valuesYamlFilePath, valuesYamlStr, "utf8");
118
+ };
119
+ getJwtEnv = async () => {
120
+ const xfeConfig = loadXfeConfig();
121
+ if (!xfeConfig?.jwt) return {};
122
+ const { aud = "" } = xfeConfig.jwt;
123
+ if (!aud) throw new Error("xfe.json \u4E2D\u7684 jwt \u914D\u7F6E\u4E0D\u5B8C\u6574\uFF0C\u8BF7\u786E\u4FDD\u5305\u542B aud \u5B57\u6BB5\u3002");
124
+ const jwkRes = await fetch(`https://app.eshetang.com/jwk?appId=${aud}`);
125
+ if (!jwkRes.ok) {
126
+ throw new Error(`\u8FDC\u7A0B\u83B7\u53D6\u5BC6\u94A5\u5931\u8D25: ${jwkRes.status} ${jwkRes.statusText}`);
127
+ }
128
+ let JwkResponseJson;
129
+ try {
130
+ JwkResponseJson = await jwkRes.json();
131
+ } catch (err) {
132
+ throw new Error(`\u8FDC\u7A0B\u83B7\u53D6\u5BC6\u94A5\u5931\u8D25\uFF0C\u54CD\u5E94\u89E3\u6790\u9519\u8BEF: ${err.message}, response text: ${await jwkRes.text()}`);
133
+ }
134
+ const { keyId, privateKeyPkcs8 } = JwkResponseJson?.data || {};
135
+ if (!keyId || !privateKeyPkcs8) throw new Error(`\u672A\u83B7\u53D6\u5230\u9879\u76EE\u7B7E\u540D\u5BC6\u94A5, \u8BF7\u68C0\u67E5aud\u662F\u5426\u6B63\u786E: ${aud}`);
136
+ return { XFE_JWT_AUD: aud, XFE_JWT_KEY_ID: keyId, XFE_JWT_PRIVATE_KEY: privateKeyPkcs8 };
137
+ };
21
138
  }
22
- const xfeConfigContent = fs.readFileSync(xfeConfigPath, "utf8");
23
- const config = JSON.parse(xfeConfigContent);
24
- const renderMode = config.webapp?.renderMode;
25
- if (renderMode !== void 0 && renderMode !== "client" && renderMode !== "server") {
26
- throw new Error("xfe.json.webapp.renderMode \u53EA\u80FD\u4E3A client \u6216 server");
27
- }
28
- return config;
29
- };
30
- var configDeploy = () => {
31
- const xfeConfig = loadXfeConfig();
32
- if (!xfeConfig?.deploy) return;
33
- const droneConfigFilePath = path.resolve(__dirname, "../deploy/.drone.yml");
34
- fs.cpSync(droneConfigFilePath, xfeConfig.deploy.droneConfigPath || "./.drone.yml");
35
- const valuesYamlFilePath = path.resolve(__dirname, "../deploy/helm/values.yaml");
36
- const valuesYamlFile = fs.readFileSync(valuesYamlFilePath, "utf8");
37
- const valuesYaml = yaml.parse(valuesYamlFile);
38
- if (!valuesYaml.virtualService) valuesYaml.virtualService = {};
39
- if (!valuesYaml.virtualService.hosts) valuesYaml.virtualService.hosts = { test: [], stage: [], prod: [] };
40
- const {
41
- virtualServiceEnabled = true,
42
- hostsProd = [],
43
- hostsStage = [],
44
- hostsTest = [],
45
- gateways = ["common-gateway-eshetang"]
46
- } = xfeConfig.deploy;
47
- const { targetK8s = "saas", targetNamespace = "" } = xfeConfig.deploy;
48
- valuesYaml.virtualService.enabled = virtualServiceEnabled;
49
- valuesYaml.virtualService.gateways = gateways;
50
- valuesYaml.virtualService.hosts.prod = hostsProd;
51
- valuesYaml.virtualService.hosts.stage = hostsStage;
52
- valuesYaml.virtualService.hosts.test = hostsTest;
53
- valuesYaml.targetK8s = targetK8s;
54
- valuesYaml.namespace = targetNamespace;
55
- const valuesYamlStr = yaml.stringify(valuesYaml, { defaultStringType: "QUOTE_SINGLE", defaultKeyType: "PLAIN" });
56
- fs.writeFileSync(valuesYamlFilePath, valuesYamlStr, "utf8");
57
- };
58
- var getJwtEnv = async () => {
59
- const xfeConfig = loadXfeConfig();
60
- if (!xfeConfig?.jwt) return {};
61
- const { aud = "" } = xfeConfig.jwt;
62
- if (!aud) throw new Error("xfe.json \u4E2D\u7684 jwt \u914D\u7F6E\u4E0D\u5B8C\u6574\uFF0C\u8BF7\u786E\u4FDD\u5305\u542B aud \u5B57\u6BB5\u3002");
63
- const jwkRes = await fetch(`https://app.eshetang.com/jwk?appId=${aud}`);
64
- if (!jwkRes.ok) {
65
- throw new Error(`\u8FDC\u7A0B\u83B7\u53D6\u5BC6\u94A5\u5931\u8D25: ${jwkRes.status} ${jwkRes.statusText}`);
66
- }
67
- let JwkResponseJson;
68
- try {
69
- JwkResponseJson = await jwkRes.json();
70
- } catch (err) {
71
- throw new Error(`\u8FDC\u7A0B\u83B7\u53D6\u5BC6\u94A5\u5931\u8D25\uFF0C\u54CD\u5E94\u89E3\u6790\u9519\u8BEF: ${err.message}, response text: ${await jwkRes.text()}`);
72
- }
73
- const { keyId, privateKeyPkcs8 } = JwkResponseJson?.data || {};
74
- if (!keyId || !privateKeyPkcs8) throw new Error(`\u672A\u83B7\u53D6\u5230\u9879\u76EE\u7B7E\u540D\u5BC6\u94A5, \u8BF7\u68C0\u67E5aud\u662F\u5426\u6B63\u786E: ${aud}`);
75
- return { XFE_JWT_AUD: aud, XFE_JWT_KEY_ID: keyId, XFE_JWT_PRIVATE_KEY: privateKeyPkcs8 };
76
- };
139
+ });
77
140
 
78
141
  // src/framework.ts
79
142
  import fs2 from "fs";
80
143
  import { createRequire } from "module";
81
144
  import path2 from "path";
82
- import { fileURLToPath } from "url";
83
- var frameworkDirectory = typeof __dirname === "string" ? __dirname : path2.dirname(fileURLToPath(import.meta.url));
84
- var requireFromFramework = createRequire(path2.join(frameworkDirectory, "framework.js"));
85
- var extensions = [".tsx", ".ts", ".jsx", ".js"];
86
- var findSource = (directory, name) => extensions.map((extension) => path2.join(directory, `${name}${extension}`)).find(fs2.existsSync);
87
- var findValueExports = (file) => [...fs2.readFileSync(file, "utf8").matchAll(/^\s*export\s+(?:async\s+)?(?:const|let|var|function|class)\s+([A-Za-z_$][\w$]*)/gm)].map(
88
- ([, name]) => name
89
- );
90
- var importPath = (from, target) => {
91
- const relative = path2.relative(from, target).replace(path2.extname(target), "").replaceAll(path2.sep, "/");
92
- return relative.startsWith(".") ? relative : `./${relative}`;
93
- };
94
- var writeGenerated = (file, content) => {
95
- if (fs2.existsSync(file) && fs2.readFileSync(file, "utf8") === content) return;
96
- fs2.writeFileSync(file, content);
97
- };
98
- var defaultRootSource = (projectRoot, appDirectory) => {
99
- const { webapp = {} } = loadXfeConfig(projectRoot);
100
- const layoutSource = findSource(path2.join(projectRoot, "src"), "layout");
101
- const layoutExports = layoutSource ? findValueExports(layoutSource) : [];
102
- const hasErrorView = layoutExports.includes("ErrorView");
103
- const layoutImport = layoutSource ? `import AppLayout${hasErrorView ? ", { ErrorView }" : ""} from ${JSON.stringify(importPath(appDirectory, layoutSource))}
145
+ import { fileURLToPath as fileURLToPath2 } from "url";
146
+ var frameworkDirectory, requireFromFramework, extensions, findSource, findValueExports, importPath, writeGenerated, defaultRootSource, getFrameworkRoot, prepareFramework;
147
+ var init_framework = __esm({
148
+ "src/framework.ts"() {
149
+ "use strict";
150
+ init_config();
151
+ frameworkDirectory = typeof __dirname === "string" ? __dirname : path2.dirname(fileURLToPath2(import.meta.url));
152
+ requireFromFramework = createRequire(path2.join(frameworkDirectory, "framework.js"));
153
+ extensions = [".tsx", ".ts", ".jsx", ".js"];
154
+ findSource = (directory, name) => extensions.map((extension) => path2.join(directory, `${name}${extension}`)).find(fs2.existsSync);
155
+ findValueExports = (file) => [...fs2.readFileSync(file, "utf8").matchAll(/^\s*export\s+(?:async\s+)?(?:const|let|var|function|class)\s+([A-Za-z_$][\w$]*)/gm)].map(
156
+ ([, name]) => name
157
+ );
158
+ importPath = (from, target) => {
159
+ const relative = path2.relative(from, target).replace(path2.extname(target), "").replaceAll(path2.sep, "/");
160
+ return relative.startsWith(".") ? relative : `./${relative}`;
161
+ };
162
+ writeGenerated = (file, content) => {
163
+ if (fs2.existsSync(file) && fs2.readFileSync(file, "utf8") === content) return;
164
+ fs2.writeFileSync(file, content);
165
+ };
166
+ defaultRootSource = (projectRoot, appDirectory) => {
167
+ const { webapp = {} } = loadXfeConfig(projectRoot);
168
+ const layoutSource = findSource(path2.join(projectRoot, "src"), "layout");
169
+ const layoutExports = layoutSource ? findValueExports(layoutSource) : [];
170
+ const hasErrorView = layoutExports.includes("ErrorView");
171
+ const layoutImport = layoutSource ? `import AppLayout${hasErrorView ? ", { ErrorView }" : ""} from ${JSON.stringify(importPath(appDirectory, layoutSource))}
104
172
  ` : "";
105
- return `import { createElement, type ReactNode } from 'react'
173
+ return `import { createElement, type ReactNode } from 'react'
106
174
  import { Outlet } from 'react-router'
107
175
  import { Document, PageError, PageLoading } from '@xfe-repo/web-app/dist/root.mjs'
108
176
  ${layoutImport}
@@ -112,82 +180,266 @@ export default function Root() { return ${layoutSource ? "createElement(AppLayou
112
180
  export function ErrorBoundary() { return createElement(PageError, { ${hasErrorView ? "view: ErrorView" : ""} }) }
113
181
  export function HydrateFallback() { return createElement(PageLoading) }
114
182
  `;
115
- };
116
- var getFrameworkRoot = (projectRoot) => path2.join(projectRoot, "node_modules/.cache/xfe-web/react-router");
117
- var prepareFramework = (projectRoot = process.cwd()) => {
118
- const sourceDirectory = path2.join(projectRoot, "src");
119
- const rootSource = findSource(sourceDirectory, "root");
120
- const appServerSource = findSource(sourceDirectory, "app.server");
121
- const pagesSource = path2.join(sourceDirectory, "pages");
122
- if (!fs2.existsSync(pagesSource)) throw new Error("\u672A\u627E\u5230 src/pages");
123
- const rootDirectory = getFrameworkRoot(projectRoot);
124
- const appDirectory = path2.join(rootDirectory, "app");
125
- fs2.mkdirSync(appDirectory, { recursive: true });
126
- const routerDirectory = path2.dirname(requireFromFramework.resolve("react-router/package.json"));
127
- const routerLink = path2.join(rootDirectory, "node_modules/react-router");
128
- fs2.mkdirSync(path2.dirname(routerLink), { recursive: true });
129
- if (!fs2.lstatSync(routerLink, { throwIfNoEntry: false })?.isSymbolicLink() || fs2.readlinkSync(routerLink) !== routerDirectory) {
130
- fs2.rmSync(routerLink, { force: true });
131
- fs2.symlinkSync(routerDirectory, routerLink, "junction");
132
- }
133
- const rootTarget = path2.join(appDirectory, "root.tsx");
134
- const rootImport = rootSource ? importPath(appDirectory, rootSource) : "";
135
- const rootExports = rootSource ? findValueExports(rootSource).filter((name) => name !== "middleware" || !appServerSource) : [];
136
- const namedExports = rootExports.length ? `export { ${rootExports.join(", ")} } from ${JSON.stringify(rootImport)}
183
+ };
184
+ getFrameworkRoot = (projectRoot) => path2.join(projectRoot, "node_modules/.cache/xfe-web/react-router");
185
+ prepareFramework = (projectRoot = process.cwd()) => {
186
+ const sourceDirectory = path2.join(projectRoot, "src");
187
+ const rootSource = findSource(sourceDirectory, "root");
188
+ const appServerSource = findSource(sourceDirectory, "app.server");
189
+ const pagesSource = path2.join(sourceDirectory, "pages");
190
+ if (!fs2.existsSync(pagesSource)) throw new Error("\u672A\u627E\u5230 src/pages");
191
+ const rootDirectory = getFrameworkRoot(projectRoot);
192
+ const appDirectory = path2.join(rootDirectory, "app");
193
+ fs2.mkdirSync(appDirectory, { recursive: true });
194
+ const routerDirectory = path2.dirname(requireFromFramework.resolve("react-router/package.json"));
195
+ const routerLink = path2.join(rootDirectory, "node_modules/react-router");
196
+ fs2.mkdirSync(path2.dirname(routerLink), { recursive: true });
197
+ if (!fs2.lstatSync(routerLink, { throwIfNoEntry: false })?.isSymbolicLink() || fs2.readlinkSync(routerLink) !== routerDirectory) {
198
+ fs2.rmSync(routerLink, { force: true });
199
+ fs2.symlinkSync(routerDirectory, routerLink, "junction");
200
+ }
201
+ const rootTarget = path2.join(appDirectory, "root.tsx");
202
+ const rootImport = rootSource ? importPath(appDirectory, rootSource) : "";
203
+ const rootExports = rootSource ? findValueExports(rootSource).filter((name) => name !== "middleware" || !appServerSource) : [];
204
+ const namedExports = rootExports.length ? `export { ${rootExports.join(", ")} } from ${JSON.stringify(rootImport)}
137
205
  ` : "";
138
- const errorBoundaryExport = rootExports.includes("ErrorBoundary") ? "" : "export { DefaultErrorBoundary as ErrorBoundary } from '@xfe-repo/web-router/errors'\n";
139
- const middlewareExport = appServerSource ? `export { middleware } from ${JSON.stringify(importPath(appDirectory, appServerSource))}
206
+ const errorBoundaryExport = rootExports.includes("ErrorBoundary") ? "" : "export { DefaultErrorBoundary as ErrorBoundary } from '@xfe-repo/web-router/errors'\n";
207
+ const middlewareExport = appServerSource ? `export { middleware } from ${JSON.stringify(importPath(appDirectory, appServerSource))}
140
208
  ` : "";
141
- writeGenerated(
142
- rootTarget,
143
- rootSource ? `export * from ${JSON.stringify(rootImport)}
209
+ writeGenerated(
210
+ rootTarget,
211
+ rootSource ? `export * from ${JSON.stringify(rootImport)}
144
212
  export { default } from ${JSON.stringify(rootImport)}
145
213
  ${namedExports}${errorBoundaryExport}${middlewareExport}` : `${defaultRootSource(projectRoot, appDirectory)}${middlewareExport}`
146
- );
147
- const pagesLink = path2.join(appDirectory, "pages");
148
- if (!fs2.existsSync(pagesLink)) fs2.symlinkSync(path2.relative(appDirectory, pagesSource), pagesLink, "dir");
149
- writeGenerated(
150
- path2.join(rootDirectory, "react-router.config.js"),
151
- "export { default } from '@xfe-repo/web-app/dist/react-router-config.mjs'\n"
152
- );
153
- writeGenerated(
154
- path2.join(appDirectory, "routes.js"),
155
- `import { collectPageRoutes } from '@xfe-repo/web-router/routes'
214
+ );
215
+ const pagesLink = path2.join(appDirectory, "pages");
216
+ if (!fs2.existsSync(pagesLink)) fs2.symlinkSync(path2.relative(appDirectory, pagesSource), pagesLink, "dir");
217
+ writeGenerated(
218
+ path2.join(rootDirectory, "react-router.config.js"),
219
+ "export { default } from '@xfe-repo/web-app/dist/react-router-config.mjs'\n"
220
+ );
221
+ writeGenerated(
222
+ path2.join(appDirectory, "routes.js"),
223
+ `import { collectPageRoutes } from '@xfe-repo/web-router/routes'
156
224
  export default collectPageRoutes(${JSON.stringify(appDirectory)})
157
225
  `
158
- );
159
- const defaultsDirectory = path2.join(path2.dirname(requireFromFramework.resolve("@react-router/dev/package.json")), "dist/config/defaults");
160
- writeGenerated(
161
- path2.join(appDirectory, "entry.server.tsx"),
162
- `export { default, streamTimeout } from ${JSON.stringify(importPath(appDirectory, path2.join(defaultsDirectory, "entry.server.web.tsx")))}
226
+ );
227
+ const defaultsDirectory = path2.join(path2.dirname(requireFromFramework.resolve("@react-router/dev/package.json")), "dist/config/defaults");
228
+ writeGenerated(
229
+ path2.join(appDirectory, "entry.server.tsx"),
230
+ `export { default, streamTimeout } from ${JSON.stringify(importPath(appDirectory, path2.join(defaultsDirectory, "entry.server.web.tsx")))}
163
231
  `
232
+ );
233
+ const typeScriptConfig = path2.join(rootDirectory, "tsconfig.json");
234
+ writeGenerated(
235
+ typeScriptConfig,
236
+ JSON.stringify(
237
+ {
238
+ extends: path2.join(projectRoot, "tsconfig.json"),
239
+ compilerOptions: { rootDirs: [projectRoot, rootDirectory, path2.join(rootDirectory, ".react-router/types")] },
240
+ include: [
241
+ path2.join(sourceDirectory, "**/*"),
242
+ path2.join(projectRoot, "types/**/*"),
243
+ path2.join(appDirectory, "*.tsx"),
244
+ path2.join(rootDirectory, ".react-router/types/**/*")
245
+ ],
246
+ exclude: []
247
+ },
248
+ null,
249
+ 2
250
+ )
251
+ );
252
+ return {
253
+ appDirectory,
254
+ rootDirectory,
255
+ viteConfig: path2.resolve(frameworkDirectory, "vite.mjs"),
256
+ typeScriptConfig
257
+ };
258
+ };
259
+ }
260
+ });
261
+
262
+ // src/node.ts
263
+ var node_exports = {};
264
+ __export(node_exports, {
265
+ buildNode: () => buildNode,
266
+ runNode: () => runNode
267
+ });
268
+ import { once } from "events";
269
+ import { rm } from "fs/promises";
270
+ import { Server } from "http";
271
+ import path4 from "path";
272
+ import { pathToFileURL } from "url";
273
+ import express2 from "express";
274
+ async function buildNode({ projectRoot, webapp }) {
275
+ const { build } = await import("esbuild");
276
+ const entry = getServerEntry(projectRoot, webapp);
277
+ if (!entry) throw new Error("\u7F3A\u5C11 xfe.json.webapp.serverEntry");
278
+ if (webapp.renderMode === "client") await rm(path4.join(getBuildDirectory(projectRoot, webapp), "server"), { recursive: true, force: true });
279
+ await build({
280
+ absWorkingDir: projectRoot,
281
+ entryPoints: [entry],
282
+ outfile: path4.join(getBuildDirectory(projectRoot, webapp), NODE_OUTPUT),
283
+ tsconfig: path4.join(projectRoot, "tsconfig.json"),
284
+ bundle: true,
285
+ packages: "external",
286
+ platform: "node",
287
+ format: "esm",
288
+ target: "node22.22",
289
+ sourcemap: true
290
+ });
291
+ }
292
+ async function runNode({ projectRoot, webapp, development }) {
293
+ const entry = development ? getServerEntry(projectRoot, webapp) : path4.join(getBuildDirectory(projectRoot, webapp), NODE_OUTPUT);
294
+ if (!entry) throw new Error("\u7F3A\u5C11 xfe.json.webapp.serverEntry");
295
+ if (development) {
296
+ const { loadEnv } = await import("vite");
297
+ Object.assign(process.env, { ...loadEnv("development", projectRoot, ""), ...process.env });
298
+ } else process.env.NODE_ENV ??= "production";
299
+ const module = await import(pathToFileURL(entry).href);
300
+ if (typeof module.default !== "function") throw new Error("serverEntry \u5FC5\u987B\u9ED8\u8BA4\u5BFC\u51FA Node \u670D\u52A1\u5DE5\u5382\u51FD\u6570");
301
+ const frontend = express2().disable("x-powered-by");
302
+ const application = await module.default({ frontend, mode: development ? "development" : "production" });
303
+ const upgrades = /* @__PURE__ */ new Set();
304
+ let vite;
305
+ let closing;
306
+ const close = () => closing ??= disposeApplication(application, { vite, upgrades });
307
+ const onSignal = async () => {
308
+ try {
309
+ await close();
310
+ } catch (error) {
311
+ console.error("XFE Node \u5173\u95ED\u5931\u8D25:", error);
312
+ process.exit(1);
313
+ } finally {
314
+ process.off("SIGINT", onSignal);
315
+ process.off("SIGTERM", onSignal);
316
+ }
317
+ };
318
+ try {
319
+ const server = application?.server;
320
+ if (!(server instanceof Server) || server.listening) throw new Error("Node \u5DE5\u5382\u5FC5\u987B\u8FD4\u56DE\u5C1A\u672A listen \u7684 http.Server");
321
+ if (server.listenerCount("upgrade")) throw new Error("\u8BF7\u901A\u8FC7\u5DE5\u5382\u8FD4\u56DE\u7684 upgrade \u5904\u7406\u5347\u7EA7\uFF0C\u4E0D\u8981\u76F4\u63A5\u6CE8\u518C server \u7684 upgrade \u4E8B\u4EF6");
322
+ const hmrPath = path4.posix.join(webapp.basename || "/", HMR_PATH);
323
+ server.on(
324
+ "upgrade",
325
+ /** HMR 与业务互斥分流,升级连接由关闭流程统一回收。 */
326
+ (request, socket, head) => {
327
+ upgrades.add(socket);
328
+ socket.once(
329
+ "close",
330
+ /** 不保留已经断开的升级连接。 */
331
+ () => upgrades.delete(socket)
332
+ );
333
+ if (development && request.url?.split("?")[0] === hmrPath) {
334
+ if (!["vite-hmr", "vite-ping"].includes(String(request.headers["sec-websocket-protocol"]))) socket.destroy();
335
+ return;
336
+ }
337
+ if (application.upgrade) application.upgrade(request, socket, head);
338
+ else socket.destroy();
339
+ }
340
+ );
341
+ if (development) vite = await createDevelopmentServer(server, projectRoot);
342
+ await mountFrontend(frontend, { projectRoot, webapp, vite });
343
+ const listening = once(server, "listening");
344
+ const host = process.env.HOST || webapp.host || "0.0.0.0";
345
+ const port = Number(process.env.PORT ?? webapp.port ?? 3e3);
346
+ server.listen(port, host);
347
+ await listening;
348
+ console.info(`XFE Node: http://${host}:${port}`);
349
+ process.on("SIGINT", onSignal);
350
+ process.on("SIGTERM", onSignal);
351
+ } catch (error) {
352
+ await close();
353
+ throw error;
354
+ }
355
+ }
356
+ async function createDevelopmentServer(server, projectRoot) {
357
+ const { createServer } = await import("vite");
358
+ const framework = prepareFramework(projectRoot);
359
+ const events = [[process, "SIGINT"], [process, "SIGTERM"], [process.stdin, "end"]];
360
+ const snapshots = events.map(
361
+ /** 只记录当前监听,恢复时保留宿主和业务原有的处理器。 */
362
+ ([source, event]) => ({ source, event, listeners: new Set(source.listeners(event)) })
164
363
  );
165
- const typeScriptConfig = path2.join(rootDirectory, "tsconfig.json");
166
- writeGenerated(
167
- typeScriptConfig,
168
- JSON.stringify(
169
- {
170
- extends: path2.join(projectRoot, "tsconfig.json"),
171
- compilerOptions: { rootDirs: [projectRoot, rootDirectory, path2.join(rootDirectory, ".react-router/types")] },
172
- include: [
173
- path2.join(sourceDirectory, "**/*"),
174
- path2.join(projectRoot, "types/**/*"),
175
- path2.join(appDirectory, "*.tsx"),
176
- path2.join(rootDirectory, ".react-router/types/**/*")
177
- ],
178
- exclude: []
179
- },
180
- null,
181
- 2
182
- )
364
+ try {
365
+ return await createServer({
366
+ root: framework.rootDirectory,
367
+ configFile: framework.viteConfig,
368
+ server: { middlewareMode: true, ws: { server, path: HMR_PATH } },
369
+ appType: "custom"
370
+ });
371
+ } finally {
372
+ for (const { source, event, listeners } of snapshots) {
373
+ for (const listener of source.listeners(event)) {
374
+ if (!listeners.has(listener)) source.removeListener(event, listener);
375
+ }
376
+ }
377
+ }
378
+ }
379
+ async function mountFrontend(frontend, { projectRoot, webapp, vite }) {
380
+ let build;
381
+ if (vite) {
382
+ const { isRunnableDevEnvironment } = await import("vite");
383
+ const environment = vite.environments.ssr;
384
+ if (!isRunnableDevEnvironment(environment)) throw new Error("React Router \u5F00\u53D1\u73AF\u5883\u672A\u5C31\u7EEA");
385
+ frontend.use(vite.middlewares);
386
+ build = async () => environment.runner.import("virtual:react-router/server-build");
387
+ } else {
388
+ const directory = getBuildDirectory(projectRoot, webapp);
389
+ const basename = webapp.basename || "/";
390
+ frontend.use(path4.posix.join(basename, "assets"), express2.static(path4.join(directory, "client/assets"), { immutable: true, maxAge: "1y", fallthrough: false }));
391
+ frontend.use(basename, express2.static(path4.join(directory, "client")));
392
+ if (webapp.renderMode === "client") {
393
+ frontend.get(
394
+ path4.posix.join(basename, "{*path}"),
395
+ /** SPA 深链接始终返回构建后的首页。 */
396
+ (_request, response) => response.sendFile(path4.join(directory, "client/index.html"))
397
+ );
398
+ return;
399
+ }
400
+ build = await import(pathToFileURL(path4.join(directory, "server/index.js")).href);
401
+ }
402
+ const { createRequestHandler } = await import("@react-router/express");
403
+ frontend.use(createRequestHandler({ build, mode: vite ? "development" : "production" }));
404
+ }
405
+ async function disposeApplication(application, { vite, upgrades }) {
406
+ const server = application?.server instanceof Server ? application.server : void 0;
407
+ const forced = setTimeout(
408
+ /** 生产关闭时中断超过等待上限的普通 HTTP 请求。 */
409
+ () => server?.closeAllConnections(),
410
+ SHUTDOWN_TIMEOUT
183
411
  );
184
- return {
185
- appDirectory,
186
- rootDirectory,
187
- viteConfig: path2.resolve(frameworkDirectory, "vite.mjs"),
188
- typeScriptConfig
189
- };
190
- };
412
+ forced.unref();
413
+ try {
414
+ const drained = server?.listening ? server[Symbol.asyncDispose]() : void 0;
415
+ for (const socket of upgrades) socket.destroy();
416
+ const results = await Promise.allSettled([drained, vite?.close()]);
417
+ await application?.close?.();
418
+ const failure = results.find((result) => result.status === "rejected");
419
+ if (failure?.status === "rejected") throw failure.reason;
420
+ } finally {
421
+ clearTimeout(forced);
422
+ }
423
+ }
424
+ var NODE_OUTPUT, HMR_PATH, SHUTDOWN_TIMEOUT;
425
+ var init_node = __esm({
426
+ "src/node.ts"() {
427
+ "use strict";
428
+ init_config();
429
+ init_framework();
430
+ NODE_OUTPUT = "server/node.mjs";
431
+ HMR_PATH = "/_xfe/hmr";
432
+ SHUTDOWN_TIMEOUT = 3e4;
433
+ }
434
+ });
435
+
436
+ // src/cli.ts
437
+ init_config();
438
+ init_framework();
439
+ import { spawn } from "child_process";
440
+ import { once as once2 } from "events";
441
+ import { mkdirSync } from "fs";
442
+ import path5 from "path";
191
443
 
192
444
  // src/serve.ts
193
445
  import { existsSync } from "fs";
@@ -225,33 +477,53 @@ var serveClient = ({
225
477
 
226
478
  // src/cli.ts
227
479
  var [command, ...args] = process.argv.slice(2);
228
- var resolveBin = (packageName) => path4.join(path4.dirname(__require.resolve(`${packageName}/package.json`)), packageName === "typescript" ? "lib/tsc.js" : "bin.cjs");
229
- var run = (packageName, commandArgs, options = {}) => {
230
- const result = spawnSync(process.execPath, [resolveBin(packageName), ...commandArgs], {
231
- stdio: "inherit",
232
- env: options.env,
233
- cwd: options.cwd
234
- });
235
- if (result.error) throw result.error;
236
- if (result.status !== 0) process.exit(result.status ?? 1);
237
- };
480
+ var binaries = { typescript: "lib/tsc.js", tsx: "dist/cli.mjs" };
481
+ var resolveBin = (packageName) => path5.join(path5.dirname(__require.resolve(`${packageName}/package.json`)), binaries[packageName] || "bin.cjs");
482
+ async function run(options) {
483
+ const { packageName, args: args2, cwd, env } = options;
484
+ const child = spawn(process.execPath, [resolveBin(packageName), ...args2], { stdio: "inherit", env, cwd });
485
+ let stopping = false;
486
+ const forward = (signal) => {
487
+ if (stopping) return;
488
+ stopping = true;
489
+ child.kill(signal);
490
+ };
491
+ process.on("SIGINT", forward);
492
+ process.on("SIGTERM", forward);
493
+ try {
494
+ const [code] = await once2(child, "exit");
495
+ if (code !== 0 && !stopping) throw new Error(`${packageName} ${args2[0]} \u5931\u8D25\uFF0C\u9000\u51FA\u7801 ${code ?? 1}`);
496
+ } finally {
497
+ process.off("SIGINT", forward);
498
+ process.off("SIGTERM", forward);
499
+ }
500
+ }
238
501
  async function main() {
239
502
  const projectRoot = process.cwd();
240
503
  if (command === "config") return configDeploy();
241
504
  if (command === "start") {
242
- const { webapp = {} } = loadXfeConfig(projectRoot);
243
- if (webapp.renderMode === "client") {
505
+ const { webapp: webapp2 = {} } = loadXfeConfig(projectRoot);
506
+ const buildDirectory = getBuildDirectory(projectRoot, webapp2);
507
+ if (webapp2.serverEntry) {
508
+ if (args.length) throw new Error("\u81EA\u5B9A\u4E49 Node \u670D\u52A1\u8BF7\u901A\u8FC7 HOST / PORT \u6216 xfe.json \u914D\u7F6E\u542F\u52A8\u5730\u5740");
509
+ Object.assign(process.env, await getJwtEnv());
510
+ const { runNode: runNode2 } = await Promise.resolve().then(() => (init_node(), node_exports));
511
+ return runNode2({ projectRoot, webapp: webapp2 });
512
+ }
513
+ if (webapp2.renderMode === "client") {
244
514
  serveClient({
245
- directory: path4.join(projectRoot, "build/client"),
246
- host: process.env.HOST || webapp.host || "0.0.0.0",
247
- port: Number(process.env.PORT ?? webapp.port ?? 3e3),
248
- basename: webapp.basename
515
+ directory: path5.join(buildDirectory, "client"),
516
+ host: process.env.HOST || webapp2.host || "0.0.0.0",
517
+ port: Number(process.env.PORT ?? webapp2.port ?? 3e3),
518
+ basename: webapp2.basename
249
519
  });
250
520
  return;
251
521
  }
252
522
  const rootDirectory = getFrameworkRoot(projectRoot);
253
523
  mkdirSync(rootDirectory, { recursive: true });
254
- return run("@react-router/serve", [path4.join(projectRoot, "build/server/index.js"), ...args], {
524
+ return run({
525
+ packageName: "@react-router/serve",
526
+ args: [path5.join(buildDirectory, "server/index.js"), ...args],
255
527
  cwd: rootDirectory,
256
528
  env: { ...process.env, ...await getJwtEnv() }
257
529
  });
@@ -263,13 +535,41 @@ async function main() {
263
535
  const env = { ...process.env, XFE_WEB_ROOT: projectRoot };
264
536
  const options = { cwd: framework.rootDirectory, env };
265
537
  if (command === "typegen" || command === "typecheck") {
266
- run("@react-router/dev", ["typegen", ...command === "typegen" ? args : []], options);
267
- if (command === "typecheck") run("typescript", ["--noEmit", "--project", framework.typeScriptConfig, ...args]);
538
+ await run({ packageName: "@react-router/dev", args: ["typegen", ...command === "typegen" ? args : []], ...options });
539
+ if (command === "typecheck") await run({ packageName: "typescript", args: ["--noEmit", "--project", framework.typeScriptConfig, ...args] });
268
540
  return;
269
541
  }
270
542
  Object.assign(env, await getJwtEnv());
271
543
  if (command === "build") delete env.XFE_JWT_PRIVATE_KEY;
272
- run("@react-router/dev", [command, framework.rootDirectory, "--config", framework.viteConfig, ...args], options);
544
+ const { webapp = {} } = loadXfeConfig(projectRoot);
545
+ if (command === "dev" && webapp.serverEntry) {
546
+ if (args.length) throw new Error("\u81EA\u5B9A\u4E49 Node \u670D\u52A1\u8BF7\u901A\u8FC7 HOST / PORT \u6216 xfe.json \u914D\u7F6E\u542F\u52A8\u5730\u5740");
547
+ return run({
548
+ packageName: "tsx",
549
+ args: [
550
+ "watch",
551
+ "--clear-screen=false",
552
+ "--exclude",
553
+ "**/node_modules/**",
554
+ "--exclude",
555
+ path5.resolve(__dirname, "../node_modules/**"),
556
+ "--exclude",
557
+ path5.resolve(__dirname, "../node_modules/.vite-temp/**"),
558
+ "--exclude",
559
+ path5.join(projectRoot, "src/pages/**"),
560
+ "--include",
561
+ webapp.serverEntry,
562
+ path5.join(__dirname, "node-dev.js")
563
+ ],
564
+ cwd: projectRoot,
565
+ env
566
+ });
567
+ }
568
+ await run({ packageName: "@react-router/dev", args: [command, framework.rootDirectory, "--config", framework.viteConfig, ...args], ...options });
569
+ if (webapp.serverEntry) {
570
+ const { buildNode: buildNode2 } = await Promise.resolve().then(() => (init_node(), node_exports));
571
+ await buildNode2({ projectRoot, webapp });
572
+ }
273
573
  }
274
574
  main().catch((err) => {
275
575
  console.error("XFE Web CLI \u6267\u884C\u51FA\u9519:", err);