@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
@@ -0,0 +1,332 @@
1
+ // src/config.ts
2
+ import fs from "fs";
3
+ import path from "path";
4
+ import { fileURLToPath } from "url";
5
+ import yaml from "yaml";
6
+ var DEFAULT_BUILD_DIRECTORY = "dist";
7
+ var protectedDirectories = /* @__PURE__ */ new Set(["src", "types", "public", "node_modules", ".git"]);
8
+ var configDirectory = typeof __dirname === "string" ? __dirname : path.dirname(fileURLToPath(import.meta.url));
9
+ var loadXfeConfig = (root = process.cwd()) => {
10
+ const xfeConfigPath = path.join(root, "xfe.json");
11
+ if (!fs.existsSync(xfeConfigPath)) {
12
+ 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");
13
+ }
14
+ const xfeConfigContent = fs.readFileSync(xfeConfigPath, "utf8");
15
+ const config = JSON.parse(xfeConfigContent);
16
+ const renderMode = config.webapp?.renderMode;
17
+ if (renderMode !== void 0 && renderMode !== "client" && renderMode !== "server") {
18
+ throw new Error("xfe.json.webapp.renderMode \u53EA\u80FD\u4E3A client \u6216 server");
19
+ }
20
+ getBuildDirectory(root, config.webapp);
21
+ getServerEntry(root, config.webapp);
22
+ return config;
23
+ };
24
+ var getBuildDirectory = (projectRoot2, webapp2 = {}) => {
25
+ const configured = webapp2?.buildDirectory === void 0 ? DEFAULT_BUILD_DIRECTORY : webapp2.buildDirectory;
26
+ if (typeof configured !== "string" || !configured.trim() || /[\0\r\n]/.test(configured)) {
27
+ throw new Error("xfe.json.webapp.buildDirectory \u5FC5\u987B\u662F\u975E\u7A7A\u7684\u5355\u884C\u5B57\u7B26\u4E32");
28
+ }
29
+ const directory = configured.trim().replaceAll("\\", "/");
30
+ const root = path.resolve(projectRoot2);
31
+ const output = path.resolve(root, directory);
32
+ const relative = path.relative(root, output);
33
+ const [firstDirectory = ""] = relative.split(path.sep);
34
+ const escapesProject = path.isAbsolute(directory) || Boolean(path.win32.parse(directory).root) || firstDirectory === "..";
35
+ const overwritesInput = !relative || protectedDirectories.has(firstDirectory.toLowerCase());
36
+ if (escapesProject || overwritesInput) {
37
+ 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");
38
+ }
39
+ let currentDirectory = root;
40
+ for (const segment of relative.split(path.sep)) {
41
+ currentDirectory = path.join(currentDirectory, segment);
42
+ if (fs.lstatSync(currentDirectory, { throwIfNoEntry: false })?.isSymbolicLink()) {
43
+ throw new Error("xfe.json.webapp.buildDirectory \u4E0D\u80FD\u7ECF\u8FC7\u7B26\u53F7\u94FE\u63A5\uFF0C\u4EE5\u514D\u6E05\u7406\u5176\u4ED6\u76EE\u5F55");
44
+ }
45
+ }
46
+ return output;
47
+ };
48
+ var getServerEntry = (projectRoot2, webapp2 = {}) => {
49
+ const entry = webapp2?.serverEntry;
50
+ if (entry === void 0) return;
51
+ if (typeof entry !== "string" || !entry.trim() || /[\0\r\n]/.test(entry)) {
52
+ throw new Error("xfe.json.webapp.serverEntry \u5FC5\u987B\u662F\u9879\u76EE\u5185\u7684 TypeScript / JavaScript \u76F8\u5BF9\u8DEF\u5F84");
53
+ }
54
+ const normalized = entry.trim().replaceAll("\\", "/");
55
+ const absolute = path.resolve(projectRoot2, normalized);
56
+ const relative = path.relative(path.resolve(projectRoot2), absolute);
57
+ const outside = Boolean(path.win32.parse(normalized).root) || relative.split(path.sep)[0] === "..";
58
+ if (outside || !/\.(?:[jt]sx?|m[jt]s)$/.test(relative)) {
59
+ throw new Error("xfe.json.webapp.serverEntry \u5FC5\u987B\u662F\u9879\u76EE\u5185\u7684 TypeScript / JavaScript \u76F8\u5BF9\u8DEF\u5F84");
60
+ }
61
+ return absolute;
62
+ };
63
+
64
+ // src/node.ts
65
+ import { once } from "events";
66
+ import { rm } from "fs/promises";
67
+ import { Server } from "http";
68
+ import path3 from "path";
69
+ import { pathToFileURL } from "url";
70
+ import express from "express";
71
+
72
+ // src/framework.ts
73
+ import fs2 from "fs";
74
+ import { createRequire } from "module";
75
+ import path2 from "path";
76
+ import { fileURLToPath as fileURLToPath2 } from "url";
77
+ var frameworkDirectory = typeof __dirname === "string" ? __dirname : path2.dirname(fileURLToPath2(import.meta.url));
78
+ var requireFromFramework = createRequire(path2.join(frameworkDirectory, "framework.js"));
79
+ var extensions = [".tsx", ".ts", ".jsx", ".js"];
80
+ var findSource = (directory, name) => extensions.map((extension) => path2.join(directory, `${name}${extension}`)).find(fs2.existsSync);
81
+ 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(
82
+ ([, name]) => name
83
+ );
84
+ var importPath = (from, target) => {
85
+ const relative = path2.relative(from, target).replace(path2.extname(target), "").replaceAll(path2.sep, "/");
86
+ return relative.startsWith(".") ? relative : `./${relative}`;
87
+ };
88
+ var writeGenerated = (file, content) => {
89
+ if (fs2.existsSync(file) && fs2.readFileSync(file, "utf8") === content) return;
90
+ fs2.writeFileSync(file, content);
91
+ };
92
+ var defaultRootSource = (projectRoot2, appDirectory) => {
93
+ const { webapp: webapp2 = {} } = loadXfeConfig(projectRoot2);
94
+ const layoutSource = findSource(path2.join(projectRoot2, "src"), "layout");
95
+ const layoutExports = layoutSource ? findValueExports(layoutSource) : [];
96
+ const hasErrorView = layoutExports.includes("ErrorView");
97
+ const layoutImport = layoutSource ? `import AppLayout${hasErrorView ? ", { ErrorView }" : ""} from ${JSON.stringify(importPath(appDirectory, layoutSource))}
98
+ ` : "";
99
+ return `import { createElement, type ReactNode } from 'react'
100
+ import { Outlet } from 'react-router'
101
+ import { Document, PageError, PageLoading } from '@xfe-repo/web-app/dist/root.mjs'
102
+ ${layoutImport}
103
+ export const meta = () => [{ title: ${JSON.stringify(webapp2.title || "XFE App")} }]
104
+ export const Layout = ({ children }: { children: ReactNode }) => createElement(Document, { children, lang: ${JSON.stringify(webapp2.lang || "zh-CN")}, themeColor: ${JSON.stringify(webapp2.themeColor)} })
105
+ export default function Root() { return ${layoutSource ? "createElement(AppLayout, { children: createElement(Outlet) })" : "createElement(Outlet)"} }
106
+ export function ErrorBoundary() { return createElement(PageError, { ${hasErrorView ? "view: ErrorView" : ""} }) }
107
+ export function HydrateFallback() { return createElement(PageLoading) }
108
+ `;
109
+ };
110
+ var getFrameworkRoot = (projectRoot2) => path2.join(projectRoot2, "node_modules/.cache/xfe-web/react-router");
111
+ var prepareFramework = (projectRoot2 = process.cwd()) => {
112
+ const sourceDirectory = path2.join(projectRoot2, "src");
113
+ const rootSource = findSource(sourceDirectory, "root");
114
+ const appServerSource = findSource(sourceDirectory, "app.server");
115
+ const pagesSource = path2.join(sourceDirectory, "pages");
116
+ if (!fs2.existsSync(pagesSource)) throw new Error("\u672A\u627E\u5230 src/pages");
117
+ const rootDirectory = getFrameworkRoot(projectRoot2);
118
+ const appDirectory = path2.join(rootDirectory, "app");
119
+ fs2.mkdirSync(appDirectory, { recursive: true });
120
+ const routerDirectory = path2.dirname(requireFromFramework.resolve("react-router/package.json"));
121
+ const routerLink = path2.join(rootDirectory, "node_modules/react-router");
122
+ fs2.mkdirSync(path2.dirname(routerLink), { recursive: true });
123
+ if (!fs2.lstatSync(routerLink, { throwIfNoEntry: false })?.isSymbolicLink() || fs2.readlinkSync(routerLink) !== routerDirectory) {
124
+ fs2.rmSync(routerLink, { force: true });
125
+ fs2.symlinkSync(routerDirectory, routerLink, "junction");
126
+ }
127
+ const rootTarget = path2.join(appDirectory, "root.tsx");
128
+ const rootImport = rootSource ? importPath(appDirectory, rootSource) : "";
129
+ const rootExports = rootSource ? findValueExports(rootSource).filter((name) => name !== "middleware" || !appServerSource) : [];
130
+ const namedExports = rootExports.length ? `export { ${rootExports.join(", ")} } from ${JSON.stringify(rootImport)}
131
+ ` : "";
132
+ const errorBoundaryExport = rootExports.includes("ErrorBoundary") ? "" : "export { DefaultErrorBoundary as ErrorBoundary } from '@xfe-repo/web-router/errors'\n";
133
+ const middlewareExport = appServerSource ? `export { middleware } from ${JSON.stringify(importPath(appDirectory, appServerSource))}
134
+ ` : "";
135
+ writeGenerated(
136
+ rootTarget,
137
+ rootSource ? `export * from ${JSON.stringify(rootImport)}
138
+ export { default } from ${JSON.stringify(rootImport)}
139
+ ${namedExports}${errorBoundaryExport}${middlewareExport}` : `${defaultRootSource(projectRoot2, appDirectory)}${middlewareExport}`
140
+ );
141
+ const pagesLink = path2.join(appDirectory, "pages");
142
+ if (!fs2.existsSync(pagesLink)) fs2.symlinkSync(path2.relative(appDirectory, pagesSource), pagesLink, "dir");
143
+ writeGenerated(
144
+ path2.join(rootDirectory, "react-router.config.js"),
145
+ "export { default } from '@xfe-repo/web-app/dist/react-router-config.mjs'\n"
146
+ );
147
+ writeGenerated(
148
+ path2.join(appDirectory, "routes.js"),
149
+ `import { collectPageRoutes } from '@xfe-repo/web-router/routes'
150
+ export default collectPageRoutes(${JSON.stringify(appDirectory)})
151
+ `
152
+ );
153
+ const defaultsDirectory = path2.join(path2.dirname(requireFromFramework.resolve("@react-router/dev/package.json")), "dist/config/defaults");
154
+ writeGenerated(
155
+ path2.join(appDirectory, "entry.server.tsx"),
156
+ `export { default, streamTimeout } from ${JSON.stringify(importPath(appDirectory, path2.join(defaultsDirectory, "entry.server.web.tsx")))}
157
+ `
158
+ );
159
+ const typeScriptConfig = path2.join(rootDirectory, "tsconfig.json");
160
+ writeGenerated(
161
+ typeScriptConfig,
162
+ JSON.stringify(
163
+ {
164
+ extends: path2.join(projectRoot2, "tsconfig.json"),
165
+ compilerOptions: { rootDirs: [projectRoot2, rootDirectory, path2.join(rootDirectory, ".react-router/types")] },
166
+ include: [
167
+ path2.join(sourceDirectory, "**/*"),
168
+ path2.join(projectRoot2, "types/**/*"),
169
+ path2.join(appDirectory, "*.tsx"),
170
+ path2.join(rootDirectory, ".react-router/types/**/*")
171
+ ],
172
+ exclude: []
173
+ },
174
+ null,
175
+ 2
176
+ )
177
+ );
178
+ return {
179
+ appDirectory,
180
+ rootDirectory,
181
+ viteConfig: path2.resolve(frameworkDirectory, "vite.mjs"),
182
+ typeScriptConfig
183
+ };
184
+ };
185
+
186
+ // src/node.ts
187
+ var NODE_OUTPUT = "server/node.mjs";
188
+ var HMR_PATH = "/_xfe/hmr";
189
+ var SHUTDOWN_TIMEOUT = 3e4;
190
+ async function runNode({ projectRoot: projectRoot2, webapp: webapp2, development }) {
191
+ const entry = development ? getServerEntry(projectRoot2, webapp2) : path3.join(getBuildDirectory(projectRoot2, webapp2), NODE_OUTPUT);
192
+ if (!entry) throw new Error("\u7F3A\u5C11 xfe.json.webapp.serverEntry");
193
+ if (development) {
194
+ const { loadEnv } = await import("vite");
195
+ Object.assign(process.env, { ...loadEnv("development", projectRoot2, ""), ...process.env });
196
+ } else process.env.NODE_ENV ??= "production";
197
+ const module = await import(pathToFileURL(entry).href);
198
+ if (typeof module.default !== "function") throw new Error("serverEntry \u5FC5\u987B\u9ED8\u8BA4\u5BFC\u51FA Node \u670D\u52A1\u5DE5\u5382\u51FD\u6570");
199
+ const frontend = express().disable("x-powered-by");
200
+ const application = await module.default({ frontend, mode: development ? "development" : "production" });
201
+ const upgrades = /* @__PURE__ */ new Set();
202
+ let vite;
203
+ let closing;
204
+ const close = () => closing ??= disposeApplication(application, { vite, upgrades });
205
+ const onSignal = async () => {
206
+ try {
207
+ await close();
208
+ } catch (error) {
209
+ console.error("XFE Node \u5173\u95ED\u5931\u8D25:", error);
210
+ process.exit(1);
211
+ } finally {
212
+ process.off("SIGINT", onSignal);
213
+ process.off("SIGTERM", onSignal);
214
+ }
215
+ };
216
+ try {
217
+ const server = application?.server;
218
+ if (!(server instanceof Server) || server.listening) throw new Error("Node \u5DE5\u5382\u5FC5\u987B\u8FD4\u56DE\u5C1A\u672A listen \u7684 http.Server");
219
+ 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");
220
+ const hmrPath = path3.posix.join(webapp2.basename || "/", HMR_PATH);
221
+ server.on(
222
+ "upgrade",
223
+ /** HMR 与业务互斥分流,升级连接由关闭流程统一回收。 */
224
+ (request, socket, head) => {
225
+ upgrades.add(socket);
226
+ socket.once(
227
+ "close",
228
+ /** 不保留已经断开的升级连接。 */
229
+ () => upgrades.delete(socket)
230
+ );
231
+ if (development && request.url?.split("?")[0] === hmrPath) {
232
+ if (!["vite-hmr", "vite-ping"].includes(String(request.headers["sec-websocket-protocol"]))) socket.destroy();
233
+ return;
234
+ }
235
+ if (application.upgrade) application.upgrade(request, socket, head);
236
+ else socket.destroy();
237
+ }
238
+ );
239
+ if (development) vite = await createDevelopmentServer(server, projectRoot2);
240
+ await mountFrontend(frontend, { projectRoot: projectRoot2, webapp: webapp2, vite });
241
+ const listening = once(server, "listening");
242
+ const host = process.env.HOST || webapp2.host || "0.0.0.0";
243
+ const port = Number(process.env.PORT ?? webapp2.port ?? 3e3);
244
+ server.listen(port, host);
245
+ await listening;
246
+ console.info(`XFE Node: http://${host}:${port}`);
247
+ process.on("SIGINT", onSignal);
248
+ process.on("SIGTERM", onSignal);
249
+ } catch (error) {
250
+ await close();
251
+ throw error;
252
+ }
253
+ }
254
+ async function createDevelopmentServer(server, projectRoot2) {
255
+ const { createServer } = await import("vite");
256
+ const framework = prepareFramework(projectRoot2);
257
+ const events = [[process, "SIGINT"], [process, "SIGTERM"], [process.stdin, "end"]];
258
+ const snapshots = events.map(
259
+ /** 只记录当前监听,恢复时保留宿主和业务原有的处理器。 */
260
+ ([source, event]) => ({ source, event, listeners: new Set(source.listeners(event)) })
261
+ );
262
+ try {
263
+ return await createServer({
264
+ root: framework.rootDirectory,
265
+ configFile: framework.viteConfig,
266
+ server: { middlewareMode: true, ws: { server, path: HMR_PATH } },
267
+ appType: "custom"
268
+ });
269
+ } finally {
270
+ for (const { source, event, listeners } of snapshots) {
271
+ for (const listener of source.listeners(event)) {
272
+ if (!listeners.has(listener)) source.removeListener(event, listener);
273
+ }
274
+ }
275
+ }
276
+ }
277
+ async function mountFrontend(frontend, { projectRoot: projectRoot2, webapp: webapp2, vite }) {
278
+ let build;
279
+ if (vite) {
280
+ const { isRunnableDevEnvironment } = await import("vite");
281
+ const environment = vite.environments.ssr;
282
+ if (!isRunnableDevEnvironment(environment)) throw new Error("React Router \u5F00\u53D1\u73AF\u5883\u672A\u5C31\u7EEA");
283
+ frontend.use(vite.middlewares);
284
+ build = async () => environment.runner.import("virtual:react-router/server-build");
285
+ } else {
286
+ const directory = getBuildDirectory(projectRoot2, webapp2);
287
+ const basename = webapp2.basename || "/";
288
+ frontend.use(path3.posix.join(basename, "assets"), express.static(path3.join(directory, "client/assets"), { immutable: true, maxAge: "1y", fallthrough: false }));
289
+ frontend.use(basename, express.static(path3.join(directory, "client")));
290
+ if (webapp2.renderMode === "client") {
291
+ frontend.get(
292
+ path3.posix.join(basename, "{*path}"),
293
+ /** SPA 深链接始终返回构建后的首页。 */
294
+ (_request, response) => response.sendFile(path3.join(directory, "client/index.html"))
295
+ );
296
+ return;
297
+ }
298
+ build = await import(pathToFileURL(path3.join(directory, "server/index.js")).href);
299
+ }
300
+ const { createRequestHandler } = await import("@react-router/express");
301
+ frontend.use(createRequestHandler({ build, mode: vite ? "development" : "production" }));
302
+ }
303
+ async function disposeApplication(application, { vite, upgrades }) {
304
+ const server = application?.server instanceof Server ? application.server : void 0;
305
+ const forced = setTimeout(
306
+ /** 生产关闭时中断超过等待上限的普通 HTTP 请求。 */
307
+ () => server?.closeAllConnections(),
308
+ SHUTDOWN_TIMEOUT
309
+ );
310
+ forced.unref();
311
+ try {
312
+ const drained = server?.listening ? server[Symbol.asyncDispose]() : void 0;
313
+ for (const socket of upgrades) socket.destroy();
314
+ const results = await Promise.allSettled([drained, vite?.close()]);
315
+ await application?.close?.();
316
+ const failure = results.find((result) => result.status === "rejected");
317
+ if (failure?.status === "rejected") throw failure.reason;
318
+ } finally {
319
+ clearTimeout(forced);
320
+ }
321
+ }
322
+
323
+ // src/node-dev.ts
324
+ var projectRoot = process.cwd();
325
+ var { webapp = {} } = loadXfeConfig(projectRoot);
326
+ void runNode({ projectRoot, webapp, development: true }).catch(
327
+ /** 开发失败报告给监听器,源码修复后由 tsx 重新启动。 */
328
+ (error) => {
329
+ console.error("XFE Node \u542F\u52A8\u5931\u8D25:", error);
330
+ process.exit(1);
331
+ }
332
+ );
@@ -0,0 +1,27 @@
1
+ import { Server, IncomingMessage, RequestListener } from 'node:http';
2
+ import { Duplex } from 'node:stream';
3
+ import { WebAppConfig } from './config.mjs';
4
+
5
+ interface NodeServerContext {
6
+ readonly frontend: RequestListener;
7
+ readonly mode: 'development' | 'production';
8
+ }
9
+ interface NodeServerApplication {
10
+ readonly server: Server;
11
+ /** 只处理业务升级;开发 HMR 的升级由框架分流。 */
12
+ readonly upgrade?: (request: IncomingMessage, socket: Duplex, head: Buffer) => void;
13
+ /** HTTP 排空及升级连接断开后,释放数据库等业务资源。 */
14
+ readonly close?: () => void | Promise<void>;
15
+ }
16
+ type NodeServerFactory = (context: NodeServerContext) => NodeServerApplication | Promise<NodeServerApplication>;
17
+ type NodeOptions = {
18
+ projectRoot: string;
19
+ webapp: WebAppConfig;
20
+ development?: boolean;
21
+ };
22
+ /** 前端构建结束后编译独立 Node 工厂,外部依赖由 Node 原生加载。 */
23
+ declare function buildNode({ projectRoot, webapp }: NodeOptions): Promise<void>;
24
+ /** 只编排工厂创建、前端接入和监听;启动失败与退出共用一次清理。 */
25
+ declare function runNode({ projectRoot, webapp, development }: NodeOptions): Promise<void>;
26
+
27
+ export { type NodeServerApplication, type NodeServerContext, type NodeServerFactory, buildNode, runNode };
package/dist/node.d.ts ADDED
@@ -0,0 +1,27 @@
1
+ import { Server, IncomingMessage, RequestListener } from 'node:http';
2
+ import { Duplex } from 'node:stream';
3
+ import { WebAppConfig } from './config.js';
4
+
5
+ interface NodeServerContext {
6
+ readonly frontend: RequestListener;
7
+ readonly mode: 'development' | 'production';
8
+ }
9
+ interface NodeServerApplication {
10
+ readonly server: Server;
11
+ /** 只处理业务升级;开发 HMR 的升级由框架分流。 */
12
+ readonly upgrade?: (request: IncomingMessage, socket: Duplex, head: Buffer) => void;
13
+ /** HTTP 排空及升级连接断开后,释放数据库等业务资源。 */
14
+ readonly close?: () => void | Promise<void>;
15
+ }
16
+ type NodeServerFactory = (context: NodeServerContext) => NodeServerApplication | Promise<NodeServerApplication>;
17
+ type NodeOptions = {
18
+ projectRoot: string;
19
+ webapp: WebAppConfig;
20
+ development?: boolean;
21
+ };
22
+ /** 前端构建结束后编译独立 Node 工厂,外部依赖由 Node 原生加载。 */
23
+ declare function buildNode({ projectRoot, webapp }: NodeOptions): Promise<void>;
24
+ /** 只编排工厂创建、前端接入和监听;启动失败与退出共用一次清理。 */
25
+ declare function runNode({ projectRoot, webapp, development }: NodeOptions): Promise<void>;
26
+
27
+ export { type NodeServerApplication, type NodeServerContext, type NodeServerFactory, buildNode, runNode };