@xfe-repo/web-app 1.6.4 → 2.0.0-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/README.md +118 -1
  2. package/client.d.ts +1 -0
  3. package/deploy/.drone.yml +13 -4
  4. package/deploy/Dockerfile +15 -6
  5. package/deploy/helm/templates/deployment.yaml +5 -18
  6. package/deploy/helm/templates/svc.yaml +1 -1
  7. package/dist/cli.js +577 -416
  8. package/dist/cli.mjs +562 -256
  9. package/dist/config.d.mts +30 -6
  10. package/dist/config.d.ts +30 -6
  11. package/dist/config.js +142 -298
  12. package/dist/config.mjs +124 -2
  13. package/dist/framework.d.mts +10 -0
  14. package/dist/framework.d.ts +10 -0
  15. package/dist/framework.js +220 -0
  16. package/dist/framework.mjs +182 -0
  17. package/dist/node-dev.d.mts +2 -0
  18. package/dist/node-dev.d.ts +2 -0
  19. package/dist/node-dev.js +358 -0
  20. package/dist/node-dev.mjs +332 -0
  21. package/dist/node.d.mts +27 -0
  22. package/dist/node.d.ts +27 -0
  23. package/dist/node.js +381 -0
  24. package/dist/node.mjs +343 -0
  25. package/dist/react-router-config.d.mts +11 -0
  26. package/dist/react-router-config.d.ts +11 -0
  27. package/dist/react-router-config.js +111 -0
  28. package/dist/react-router-config.mjs +77 -0
  29. package/dist/root.d.mts +17 -0
  30. package/dist/root.d.ts +17 -0
  31. package/dist/root.js +61 -0
  32. package/dist/root.mjs +34 -0
  33. package/dist/serve.d.mts +10 -0
  34. package/dist/serve.d.ts +10 -0
  35. package/dist/serve.js +71 -0
  36. package/dist/serve.mjs +36 -0
  37. package/dist/vite.d.mts +10 -0
  38. package/dist/vite.d.ts +10 -0
  39. package/dist/vite.js +182 -0
  40. package/dist/vite.mjs +146 -0
  41. package/package.json +27 -72
  42. package/tsconfig.json +4 -1
  43. package/config/env.js +0 -104
  44. package/config/getHttpsConfig.js +0 -66
  45. package/config/jest/babelTransform.js +0 -29
  46. package/config/jest/cssTransform.js +0 -14
  47. package/config/jest/fileTransform.js +0 -40
  48. package/config/modules.js +0 -133
  49. package/config/paths.js +0 -65
  50. package/config/webpack/persistentCache/createEnvironmentHash.js +0 -9
  51. package/config/webpack/webpack.config.js +0 -737
  52. package/config/webpack/webpackDevServer.config.js +0 -122
  53. package/deploy/nginx.conf +0 -62
  54. package/dist/chunk-75BJNL7E.mjs +0 -239
  55. package/scripts/build.js +0 -217
  56. package/scripts/dev.js +0 -162
package/dist/cli.mjs CHANGED
@@ -1,271 +1,577 @@
1
- function _array_like_to_array(arr, len) {
2
- if (len == null || len > arr.length) len = arr.length;
3
- for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
4
- return arr2;
5
- }
6
- function _array_with_holes(arr) {
7
- if (Array.isArray(arr)) return arr;
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropNames = Object.getOwnPropertyNames;
3
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
4
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
5
+ }) : x)(function(x) {
6
+ if (typeof require !== "undefined") return require.apply(this, arguments);
7
+ throw Error('Dynamic require of "' + x + '" is not supported');
8
+ });
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
+ };
16
+
17
+ // src/config.ts
18
+ import fs from "fs";
19
+ import path from "path";
20
+ import { fileURLToPath } from "url";
21
+ import yaml from "yaml";
22
+ var DEFAULT_BUILD_DIRECTORY, BUILD_DIRECTORY_ARGUMENT, protectedDirectories, configDirectory, 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
+ configDirectory = typeof __dirname === "string" ? __dirname : path.dirname(fileURLToPath(import.meta.url));
30
+ loadXfeConfig = (root = process.cwd()) => {
31
+ const xfeConfigPath = path.join(root, "xfe.json");
32
+ if (!fs.existsSync(xfeConfigPath)) {
33
+ 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");
34
+ }
35
+ const xfeConfigContent = fs.readFileSync(xfeConfigPath, "utf8");
36
+ const config = JSON.parse(xfeConfigContent);
37
+ const renderMode = config.webapp?.renderMode;
38
+ if (renderMode !== void 0 && renderMode !== "client" && renderMode !== "server") {
39
+ throw new Error("xfe.json.webapp.renderMode \u53EA\u80FD\u4E3A client \u6216 server");
40
+ }
41
+ getBuildDirectory(root, config.webapp);
42
+ getServerEntry(root, config.webapp);
43
+ return config;
44
+ };
45
+ getBuildDirectory = (projectRoot, webapp = {}) => {
46
+ const configured = webapp?.buildDirectory === void 0 ? DEFAULT_BUILD_DIRECTORY : webapp.buildDirectory;
47
+ if (typeof configured !== "string" || !configured.trim() || /[\0\r\n]/.test(configured)) {
48
+ throw new Error("xfe.json.webapp.buildDirectory \u5FC5\u987B\u662F\u975E\u7A7A\u7684\u5355\u884C\u5B57\u7B26\u4E32");
49
+ }
50
+ const directory = configured.trim().replaceAll("\\", "/");
51
+ const root = path.resolve(projectRoot);
52
+ const output = path.resolve(root, directory);
53
+ const relative = path.relative(root, output);
54
+ const [firstDirectory = ""] = relative.split(path.sep);
55
+ const escapesProject = path.isAbsolute(directory) || Boolean(path.win32.parse(directory).root) || firstDirectory === "..";
56
+ const overwritesInput = !relative || protectedDirectories.has(firstDirectory.toLowerCase());
57
+ if (escapesProject || overwritesInput) {
58
+ 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");
59
+ }
60
+ let currentDirectory = root;
61
+ for (const segment of relative.split(path.sep)) {
62
+ currentDirectory = path.join(currentDirectory, segment);
63
+ if (fs.lstatSync(currentDirectory, { throwIfNoEntry: false })?.isSymbolicLink()) {
64
+ throw new Error("xfe.json.webapp.buildDirectory \u4E0D\u80FD\u7ECF\u8FC7\u7B26\u53F7\u94FE\u63A5\uFF0C\u4EE5\u514D\u6E05\u7406\u5176\u4ED6\u76EE\u5F55");
65
+ }
66
+ }
67
+ return output;
68
+ };
69
+ getServerEntry = (projectRoot, webapp = {}) => {
70
+ const entry = webapp?.serverEntry;
71
+ if (entry === void 0) return;
72
+ if (typeof entry !== "string" || !entry.trim() || /[\0\r\n]/.test(entry)) {
73
+ throw new Error("xfe.json.webapp.serverEntry \u5FC5\u987B\u662F\u9879\u76EE\u5185\u7684 TypeScript / JavaScript \u76F8\u5BF9\u8DEF\u5F84");
74
+ }
75
+ const normalized = entry.trim().replaceAll("\\", "/");
76
+ const absolute = path.resolve(projectRoot, normalized);
77
+ const relative = path.relative(path.resolve(projectRoot), absolute);
78
+ const outside = Boolean(path.win32.parse(normalized).root) || relative.split(path.sep)[0] === "..";
79
+ if (outside || !/\.(?:[jt]sx?|m[jt]s)$/.test(relative)) {
80
+ throw new Error("xfe.json.webapp.serverEntry \u5FC5\u987B\u662F\u9879\u76EE\u5185\u7684 TypeScript / JavaScript \u76F8\u5BF9\u8DEF\u5F84");
81
+ }
82
+ return absolute;
83
+ };
84
+ configDeploy = () => {
85
+ const xfeConfig = loadXfeConfig();
86
+ if (!xfeConfig?.deploy) return;
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
+ };
138
+ }
139
+ });
140
+
141
+ // src/framework.ts
142
+ import fs2 from "fs";
143
+ import { createRequire } from "module";
144
+ import path2 from "path";
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))}
172
+ ` : "";
173
+ return `import { createElement, type ReactNode } from 'react'
174
+ import { Outlet } from 'react-router'
175
+ import { Document, PageError, PageLoading } from '@xfe-repo/web-app/dist/root.mjs'
176
+ ${layoutImport}
177
+ export const meta = () => [{ title: ${JSON.stringify(webapp.title || "XFE App")} }]
178
+ export const Layout = ({ children }: { children: ReactNode }) => createElement(Document, { children, lang: ${JSON.stringify(webapp.lang || "zh-CN")}, themeColor: ${JSON.stringify(webapp.themeColor)} })
179
+ export default function Root() { return ${layoutSource ? "createElement(AppLayout, { children: createElement(Outlet) })" : "createElement(Outlet)"} }
180
+ export function ErrorBoundary() { return createElement(PageError, { ${hasErrorView ? "view: ErrorView" : ""} }) }
181
+ export function HydrateFallback() { return createElement(PageLoading) }
182
+ `;
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)}
205
+ ` : "";
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))}
208
+ ` : "";
209
+ writeGenerated(
210
+ rootTarget,
211
+ rootSource ? `export * from ${JSON.stringify(rootImport)}
212
+ export { default } from ${JSON.stringify(rootImport)}
213
+ ${namedExports}${errorBoundaryExport}${middlewareExport}` : `${defaultRootSource(projectRoot, appDirectory)}${middlewareExport}`
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'
224
+ export default collectPageRoutes(${JSON.stringify(appDirectory)})
225
+ `
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")))}
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
+ });
8
291
  }
9
- function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
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 () => {
10
308
  try {
11
- var info = gen[key](arg);
12
- var value = info.value;
309
+ await close();
13
310
  } catch (error) {
14
- reject(error);
15
- return;
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);
16
316
  }
17
- if (info.done) {
18
- resolve(value);
19
- } else {
20
- Promise.resolve(value).then(_next, _throw);
21
- }
22
- }
23
- function _async_to_generator(fn) {
24
- return function() {
25
- var self = this, args = arguments;
26
- return new Promise(function(resolve, reject) {
27
- var gen = fn.apply(self, args);
28
- function _next(value) {
29
- asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
30
- }
31
- function _throw(err) {
32
- asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
33
- }
34
- _next(undefined);
35
- });
36
- };
37
- }
38
- function _define_property(obj, key, value) {
39
- if (key in obj) {
40
- Object.defineProperty(obj, key, {
41
- value: value,
42
- enumerable: true,
43
- configurable: true,
44
- writable: true
45
- });
46
- } else {
47
- obj[key] = value;
48
- }
49
- return obj;
50
- }
51
- function _iterable_to_array_limit(arr, i) {
52
- var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];
53
- if (_i == null) return;
54
- var _arr = [];
55
- var _n = true;
56
- var _d = false;
57
- var _s, _e;
58
- try {
59
- for(_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true){
60
- _arr.push(_s.value);
61
- if (i && _arr.length === i) break;
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;
62
336
  }
63
- } catch (err) {
64
- _d = true;
65
- _e = err;
66
- } finally{
67
- try {
68
- if (!_n && _i["return"] != null) _i["return"]();
69
- } finally{
70
- if (_d) throw _e;
71
- }
72
- }
73
- return _arr;
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
+ }
74
355
  }
75
- function _non_iterable_rest() {
76
- throw new TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
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)) })
363
+ );
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
+ }
77
378
  }
78
- function _object_spread(target) {
79
- for(var i = 1; i < arguments.length; i++){
80
- var source = arguments[i] != null ? arguments[i] : {};
81
- var ownKeys = Object.keys(source);
82
- if (typeof Object.getOwnPropertySymbols === "function") {
83
- ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {
84
- return Object.getOwnPropertyDescriptor(source, sym).enumerable;
85
- }));
86
- }
87
- ownKeys.forEach(function(key) {
88
- _define_property(target, key, source[key]);
89
- });
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;
90
399
  }
91
- return target;
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" }));
92
404
  }
93
- function _sliced_to_array(arr, i) {
94
- return _array_with_holes(arr) || _iterable_to_array_limit(arr, i) || _unsupported_iterable_to_array(arr, i) || _non_iterable_rest();
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
411
+ );
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
+ }
95
423
  }
96
- function _unsupported_iterable_to_array(o, minLen) {
97
- if (!o) return;
98
- if (typeof o === "string") return _array_like_to_array(o, minLen);
99
- var n = Object.prototype.toString.call(o).slice(8, -1);
100
- if (n === "Object" && o.constructor) n = o.constructor.name;
101
- if (n === "Map" || n === "Set") return Array.from(n);
102
- if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen);
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";
443
+
444
+ // src/serve.ts
445
+ import { existsSync } from "fs";
446
+ import path3 from "path";
447
+ import express from "express";
448
+ var serveClient = ({
449
+ directory,
450
+ host,
451
+ port,
452
+ basename = "/"
453
+ }) => {
454
+ const indexFile = path3.join(directory, "index.html");
455
+ if (!existsSync(indexFile)) throw new Error(`\u672A\u627E\u5230 SPA \u5165\u53E3 ${indexFile}\uFF0C\u8BF7\u5148\u6267\u884C xfe-web build`);
456
+ const app = express().disable("x-powered-by");
457
+ const router = express.Router();
458
+ app.use((_request, response, next) => {
459
+ response.setHeader("Access-Control-Allow-Origin", "*");
460
+ next();
461
+ });
462
+ app.use(
463
+ "/assets",
464
+ express.static(path3.join(directory, "assets"), { immutable: true, maxAge: "1y" }),
465
+ (_request, response) => response.status(404).end()
466
+ );
467
+ app.use(express.static(directory));
468
+ router.get("/{*path}", (_request, response) => response.sendFile(indexFile));
469
+ app.use(basename, router);
470
+ const server = app.listen(port, host);
471
+ server.once("listening", () => {
472
+ const address = server.address();
473
+ console.log(`[xfe-web] SPA http://${host}:${typeof address === "object" && address ? address.port : port}${basename}`);
474
+ });
475
+ return server;
476
+ };
477
+
478
+ // src/cli.ts
479
+ var [command, ...args] = process.argv.slice(2);
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
+ }
103
500
  }
104
- function _ts_generator(thisArg, body) {
105
- var f, y, t, _ = {
106
- label: 0,
107
- sent: function() {
108
- if (t[0] & 1) throw t[1];
109
- return t[1];
110
- },
111
- trys: [],
112
- ops: []
113
- }, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype), d = Object.defineProperty;
114
- return d(g, "next", {
115
- value: verb(0)
116
- }), d(g, "throw", {
117
- value: verb(1)
118
- }), d(g, "return", {
119
- value: verb(2)
120
- }), typeof Symbol === "function" && d(g, Symbol.iterator, {
121
- value: function() {
122
- return this;
123
- }
124
- }), g;
125
- function verb(n) {
126
- return function(v) {
127
- return step([
128
- n,
129
- v
130
- ]);
131
- };
501
+ async function main() {
502
+ const projectRoot = process.cwd();
503
+ if (command === "config") return configDeploy();
504
+ if (command === "start") {
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 });
132
512
  }
133
- function step(op) {
134
- if (f) throw new TypeError("Generator is already executing.");
135
- while(g && (g = 0, op[0] && (_ = 0)), _)try {
136
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
137
- if (y = 0, t) op = [
138
- op[0] & 2,
139
- t.value
140
- ];
141
- switch(op[0]){
142
- case 0:
143
- case 1:
144
- t = op;
145
- break;
146
- case 4:
147
- _.label++;
148
- return {
149
- value: op[1],
150
- done: false
151
- };
152
- case 5:
153
- _.label++;
154
- y = op[1];
155
- op = [
156
- 0
157
- ];
158
- continue;
159
- case 7:
160
- op = _.ops.pop();
161
- _.trys.pop();
162
- continue;
163
- default:
164
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
165
- _ = 0;
166
- continue;
167
- }
168
- if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
169
- _.label = op[1];
170
- break;
171
- }
172
- if (op[0] === 6 && _.label < t[1]) {
173
- _.label = t[1];
174
- t = op;
175
- break;
176
- }
177
- if (t && _.label < t[2]) {
178
- _.label = t[2];
179
- _.ops.push(op);
180
- break;
181
- }
182
- if (t[2]) _.ops.pop();
183
- _.trys.pop();
184
- continue;
185
- }
186
- op = body.call(thisArg, _);
187
- } catch (e) {
188
- op = [
189
- 6,
190
- e
191
- ];
192
- y = 0;
193
- } finally{
194
- f = t = 0;
195
- }
196
- if (op[0] & 5) throw op[1];
197
- return {
198
- value: op[0] ? op[1] : void 0,
199
- done: true
200
- };
513
+ if (webapp2.renderMode === "client") {
514
+ serveClient({
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
519
+ });
520
+ return;
201
521
  }
522
+ const rootDirectory = getFrameworkRoot(projectRoot);
523
+ mkdirSync(rootDirectory, { recursive: true });
524
+ return run({
525
+ packageName: "@react-router/serve",
526
+ args: [path5.join(buildDirectory, "server/index.js"), ...args],
527
+ cwd: rootDirectory,
528
+ env: { ...process.env, ...await getJwtEnv() }
529
+ });
530
+ }
531
+ if (!command || !["dev", "build", "typegen", "typecheck"].includes(command)) {
532
+ throw new Error(`\u4E0D\u652F\u6301\u7684\u547D\u4EE4: ${command || "undefined"}\uFF0C\u53EF\u7528\u547D\u4EE4: dev\u3001build\u3001typegen\u3001typecheck\u3001start\u3001config`);
533
+ }
534
+ const framework = prepareFramework(projectRoot);
535
+ const env = { ...process.env, XFE_WEB_ROOT: projectRoot };
536
+ const options = { cwd: framework.rootDirectory, env };
537
+ if (command === "typegen" || command === "typecheck") {
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] });
540
+ return;
541
+ }
542
+ Object.assign(env, await getJwtEnv());
543
+ if (command === "build") delete env.XFE_JWT_PRIVATE_KEY;
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
+ }
202
573
  }
203
- import { configDeploy, getJwtEnv } from "./chunk-75BJNL7E.mjs";
204
- // src/cli.ts
205
- import minimist from "minimist";
206
- import { execSync } from "child_process";
207
- import path from "path";
208
- var argv = minimist(process.argv.slice(2));
209
- var commands = argv._;
210
- var _commands = _sliced_to_array(commands, 1), command = _commands[0];
211
- var appPackageRoot = path.resolve(__dirname, "../");
212
- function main() {
213
- return _async_to_generator(function() {
214
- var jwtEnv, jwtEnv1;
215
- return _ts_generator(this, function(_state) {
216
- switch(_state.label){
217
- case 0:
218
- if (!(command === "dev")) return [
219
- 3,
220
- 2
221
- ];
222
- return [
223
- 4,
224
- getJwtEnv()
225
- ];
226
- case 1:
227
- jwtEnv = _state.sent();
228
- execSync("node ".concat(path.join(appPackageRoot, "scripts/dev.js")), {
229
- stdio: "inherit",
230
- env: _object_spread({}, process.env, jwtEnv)
231
- });
232
- return [
233
- 3,
234
- 5
235
- ];
236
- case 2:
237
- if (!(command === "build")) return [
238
- 3,
239
- 4
240
- ];
241
- return [
242
- 4,
243
- getJwtEnv()
244
- ];
245
- case 3:
246
- jwtEnv1 = _state.sent();
247
- execSync("node ".concat(path.join(appPackageRoot, "scripts/build.js")), {
248
- stdio: "inherit",
249
- env: _object_spread({}, process.env, jwtEnv1)
250
- });
251
- return [
252
- 3,
253
- 5
254
- ];
255
- case 4:
256
- if (command === "config") {
257
- configDeploy();
258
- }
259
- _state.label = 5;
260
- case 5:
261
- return [
262
- 2
263
- ];
264
- }
265
- });
266
- })();
267
- }
268
- main().catch(function(err) {
269
- console.error("XFE Web CLI \u6267\u884C\u51FA\u9519:", err);
270
- process.exit(1);
574
+ main().catch((err) => {
575
+ console.error("XFE Web CLI \u6267\u884C\u51FA\u9519:", err);
576
+ process.exit(1);
271
577
  });