every-plugin 3.0.0-rc.3 → 3.0.0-rc.5
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/build/ui/generated-config.cjs +4 -0
- package/dist/build/ui/generated-config.cjs.map +1 -1
- package/dist/build/ui/generated-config.d.cts.map +1 -1
- package/dist/build/ui/generated-config.d.mts.map +1 -1
- package/dist/build/ui/generated-config.mjs +4 -1
- package/dist/build/ui/generated-config.mjs.map +1 -1
- package/dist/client.cjs +69 -0
- package/dist/client.cjs.map +1 -0
- package/dist/client.d.cts +15 -0
- package/dist/client.d.cts.map +1 -0
- package/dist/client.d.mts +15 -0
- package/dist/client.d.mts.map +1 -0
- package/dist/client.mjs +68 -0
- package/dist/client.mjs.map +1 -0
- package/dist/dev/host.cjs +149 -0
- package/dist/dev/host.cjs.map +1 -0
- package/dist/dev/host.d.cts +32 -0
- package/dist/dev/host.d.cts.map +1 -0
- package/dist/dev/host.d.mts +32 -0
- package/dist/dev/host.d.mts.map +1 -0
- package/dist/dev/host.mjs +148 -0
- package/dist/dev/host.mjs.map +1 -0
- package/dist/dev/serve.cjs +16 -111
- package/dist/dev/serve.cjs.map +1 -1
- package/dist/dev/serve.d.cts.map +1 -1
- package/dist/dev/serve.d.mts.map +1 -1
- package/dist/dev/serve.mjs +17 -112
- package/dist/dev/serve.mjs.map +1 -1
- package/dist/index.cjs +2 -0
- package/dist/index.d.cts +3 -2
- package/dist/index.d.mts +3 -2
- package/dist/index.mjs +2 -1
- package/dist/plugin.d.cts +1 -1
- package/dist/remote-entry.cjs +0 -1
- package/dist/remote-entry.cjs.map +1 -1
- package/dist/remote-entry.d.cts +1 -2
- package/dist/remote-entry.d.cts.map +1 -1
- package/dist/remote-entry.d.mts +1 -2
- package/dist/remote-entry.d.mts.map +1 -1
- package/dist/remote-entry.mjs +1 -1
- package/dist/remote-entry.mjs.map +1 -1
- package/dist/runtime/mf-config.cjs +1 -1
- package/dist/runtime/mf-config.mjs +1 -1
- package/dist/runtime/services/plugin-loader.service.d.cts +2 -2
- package/dist/types.d.cts +23 -2
- package/dist/types.d.cts.map +1 -1
- package/dist/types.d.mts +22 -1
- package/dist/types.d.mts.map +1 -1
- package/package.json +19 -2
- package/src/build/ui/generated-config.ts +4 -0
- package/src/client.ts +111 -0
- package/src/dev/host.ts +235 -0
- package/src/dev/serve.ts +22 -140
- package/src/index.ts +9 -0
- package/src/remote-entry.ts +1 -2
- package/src/types.ts +36 -2
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
import { createServer } from "node:http";
|
|
2
|
+
|
|
3
|
+
//#region src/dev/host.ts
|
|
4
|
+
const corsHeaders = {
|
|
5
|
+
"Access-Control-Allow-Origin": "*",
|
|
6
|
+
"Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, PATCH, OPTIONS",
|
|
7
|
+
"Access-Control-Allow-Headers": "X-Requested-With, content-type, Authorization"
|
|
8
|
+
};
|
|
9
|
+
const applyCorsHeaders = (res) => {
|
|
10
|
+
Object.entries(corsHeaders).forEach(([key, value]) => {
|
|
11
|
+
res.setHeader(key, value);
|
|
12
|
+
});
|
|
13
|
+
};
|
|
14
|
+
const sendJson = (res, status, body) => {
|
|
15
|
+
res.statusCode = status;
|
|
16
|
+
res.setHeader("content-type", "application/json; charset=utf-8");
|
|
17
|
+
res.end(JSON.stringify(body));
|
|
18
|
+
};
|
|
19
|
+
const sendText = (res, status, text) => {
|
|
20
|
+
res.statusCode = status;
|
|
21
|
+
res.setHeader("content-type", "text/plain; charset=utf-8");
|
|
22
|
+
res.end(text);
|
|
23
|
+
};
|
|
24
|
+
const pathnameOf = (req) => ((req.url ?? "/").split("?")[0] ?? "/").replace(/\/+$/, "") || "/";
|
|
25
|
+
const toWebRequest = (req, port) => {
|
|
26
|
+
const url = `http://localhost:${port}${req.url}`;
|
|
27
|
+
return new Request(url, {
|
|
28
|
+
method: req.method,
|
|
29
|
+
headers: req.headers,
|
|
30
|
+
body: req.method !== "GET" && req.method !== "HEAD" ? req : void 0,
|
|
31
|
+
duplex: req.method !== "GET" && req.method !== "HEAD" ? "half" : void 0
|
|
32
|
+
});
|
|
33
|
+
};
|
|
34
|
+
const buildHostContext = (effectContext, webRequest, cachedRawBodyRef) => {
|
|
35
|
+
const rawClone = webRequest.method === "GET" || webRequest.method === "HEAD" ? null : webRequest.clone();
|
|
36
|
+
return {
|
|
37
|
+
reqHeaders: webRequest.headers,
|
|
38
|
+
"effect/context": effectContext,
|
|
39
|
+
getRawBody: async () => {
|
|
40
|
+
if (cachedRawBodyRef.value !== null) return cachedRawBodyRef.value;
|
|
41
|
+
if (!rawClone) {
|
|
42
|
+
cachedRawBodyRef.value = "";
|
|
43
|
+
return cachedRawBodyRef.value;
|
|
44
|
+
}
|
|
45
|
+
cachedRawBodyRef.value = await rawClone.text();
|
|
46
|
+
return cachedRawBodyRef.value;
|
|
47
|
+
}
|
|
48
|
+
};
|
|
49
|
+
};
|
|
50
|
+
const handleOrpc = async (req, res, handler, prefix, errorLabel, effectContext, port) => {
|
|
51
|
+
try {
|
|
52
|
+
const webRequest = toWebRequest(req, port);
|
|
53
|
+
const result = await handler.handle(webRequest, {
|
|
54
|
+
prefix,
|
|
55
|
+
context: buildHostContext(effectContext, webRequest, { value: null })
|
|
56
|
+
});
|
|
57
|
+
if (result.response) {
|
|
58
|
+
res.statusCode = result.response.status;
|
|
59
|
+
result.response.headers.forEach((value, key) => {
|
|
60
|
+
res.setHeader(key, value);
|
|
61
|
+
});
|
|
62
|
+
const text = await result.response.text();
|
|
63
|
+
if (!res.getHeader("content-length")) res.setHeader("content-length", Buffer.byteLength(text).toString());
|
|
64
|
+
res.end(text);
|
|
65
|
+
} else sendText(res, 404, "Not Found");
|
|
66
|
+
} catch (error) {
|
|
67
|
+
console.error(`${errorLabel} error:`, error);
|
|
68
|
+
sendJson(res, 500, { error: error.message });
|
|
69
|
+
}
|
|
70
|
+
};
|
|
71
|
+
async function startDirectModuleHost(options) {
|
|
72
|
+
const port = options.port ?? 0;
|
|
73
|
+
let resolvedPort = port;
|
|
74
|
+
const rpcPrefix = options.rpcPrefix ?? "/api/rpc";
|
|
75
|
+
const apiPrefix = options.apiPrefix ?? "/api";
|
|
76
|
+
const staticHandler = options.staticHandler ?? null;
|
|
77
|
+
const resolveEffectContext = typeof options.effectContext === "function" ? options.effectContext : () => options.effectContext;
|
|
78
|
+
const server = createServer((req, res) => {
|
|
79
|
+
applyCorsHeaders(res);
|
|
80
|
+
const pathname = pathnameOf(req);
|
|
81
|
+
if (req.method === "OPTIONS") {
|
|
82
|
+
res.statusCode = 200;
|
|
83
|
+
res.end();
|
|
84
|
+
return;
|
|
85
|
+
}
|
|
86
|
+
if (pathname === "/" && (req.method === "GET" || req.method === "HEAD")) {
|
|
87
|
+
sendJson(res, 200, {
|
|
88
|
+
ok: true,
|
|
89
|
+
module: options.name,
|
|
90
|
+
version: options.version,
|
|
91
|
+
status: options.handlers.rpc ? "ready" : "loading",
|
|
92
|
+
endpoints: {
|
|
93
|
+
health: "/health",
|
|
94
|
+
docs: apiPrefix,
|
|
95
|
+
rpc: rpcPrefix
|
|
96
|
+
}
|
|
97
|
+
});
|
|
98
|
+
return;
|
|
99
|
+
}
|
|
100
|
+
if (pathname === "/health" && (req.method === "GET" || req.method === "HEAD")) {
|
|
101
|
+
sendText(res, 200, "OK");
|
|
102
|
+
return;
|
|
103
|
+
}
|
|
104
|
+
if (pathname.startsWith(`${rpcPrefix}/`)) {
|
|
105
|
+
if (!options.handlers.rpc) {
|
|
106
|
+
sendJson(res, 503, { error: "Plugin still loading..." });
|
|
107
|
+
return;
|
|
108
|
+
}
|
|
109
|
+
handleOrpc(req, res, options.handlers.rpc, rpcPrefix, "RPC", resolveEffectContext(), resolvedPort).catch(() => {});
|
|
110
|
+
return;
|
|
111
|
+
}
|
|
112
|
+
if (pathname === apiPrefix || pathname.startsWith(`${apiPrefix}/`)) {
|
|
113
|
+
if (!options.handlers.api) {
|
|
114
|
+
sendJson(res, 503, { error: "Plugin still loading..." });
|
|
115
|
+
return;
|
|
116
|
+
}
|
|
117
|
+
handleOrpc(req, res, options.handlers.api, apiPrefix, "OpenAPI", resolveEffectContext(), resolvedPort).catch(() => {});
|
|
118
|
+
return;
|
|
119
|
+
}
|
|
120
|
+
if (staticHandler) {
|
|
121
|
+
staticHandler(req, res, () => {
|
|
122
|
+
sendText(res, 404, "Not Found");
|
|
123
|
+
});
|
|
124
|
+
return;
|
|
125
|
+
}
|
|
126
|
+
sendText(res, 404, "Not Found");
|
|
127
|
+
});
|
|
128
|
+
await new Promise((resolve, reject) => {
|
|
129
|
+
server.once("error", reject);
|
|
130
|
+
server.listen(port, () => resolve());
|
|
131
|
+
});
|
|
132
|
+
const address = server.address();
|
|
133
|
+
if (!address || typeof address === "string") {
|
|
134
|
+
await new Promise((resolve) => server.close(() => resolve()));
|
|
135
|
+
throw new Error("Failed to resolve host port");
|
|
136
|
+
}
|
|
137
|
+
resolvedPort = address.port;
|
|
138
|
+
return {
|
|
139
|
+
port: resolvedPort,
|
|
140
|
+
close: async () => {
|
|
141
|
+
await new Promise((resolve) => server.close(() => resolve()));
|
|
142
|
+
}
|
|
143
|
+
};
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
//#endregion
|
|
147
|
+
export { startDirectModuleHost };
|
|
148
|
+
//# sourceMappingURL=host.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"host.mjs","names":[],"sources":["../../src/dev/host.ts"],"sourcesContent":["import type http from \"node:http\";\nimport { createServer } from \"node:http\";\n\nconst corsHeaders = {\n \"Access-Control-Allow-Origin\": \"*\",\n \"Access-Control-Allow-Methods\": \"GET, POST, PUT, DELETE, PATCH, OPTIONS\",\n \"Access-Control-Allow-Headers\": \"X-Requested-With, content-type, Authorization\",\n};\n\nconst applyCorsHeaders = (res: http.ServerResponse) => {\n Object.entries(corsHeaders).forEach(([key, value]) => {\n res.setHeader(key, value);\n });\n};\n\nconst sendJson = (res: http.ServerResponse, status: number, body: unknown) => {\n res.statusCode = status;\n res.setHeader(\"content-type\", \"application/json; charset=utf-8\");\n res.end(JSON.stringify(body));\n};\n\nconst sendText = (res: http.ServerResponse, status: number, text: string) => {\n res.statusCode = status;\n res.setHeader(\"content-type\", \"text/plain; charset=utf-8\");\n res.end(text);\n};\n\nconst pathnameOf = (req: http.IncomingMessage): string =>\n ((req.url ?? \"/\").split(\"?\")[0] ?? \"/\").replace(/\\/+$/, \"\") || \"/\";\n\nconst toWebRequest = (req: http.IncomingMessage, port: number): Request => {\n const url = `http://localhost:${port}${req.url}`;\n return new Request(url, {\n method: req.method,\n headers: req.headers,\n body: req.method !== \"GET\" && req.method !== \"HEAD\" ? req : undefined,\n duplex: req.method !== \"GET\" && req.method !== \"HEAD\" ? \"half\" : undefined,\n } as RequestInit);\n};\n\nconst buildHostContext = (\n effectContext: unknown,\n webRequest: Request,\n cachedRawBodyRef: { value: string | null },\n) => {\n const rawClone =\n webRequest.method === \"GET\" || webRequest.method === \"HEAD\" ? null : webRequest.clone();\n\n return {\n reqHeaders: webRequest.headers,\n \"effect/context\": effectContext,\n getRawBody: async (): Promise<string> => {\n if (cachedRawBodyRef.value !== null) return cachedRawBodyRef.value;\n if (!rawClone) {\n cachedRawBodyRef.value = \"\";\n return cachedRawBodyRef.value;\n }\n cachedRawBodyRef.value = await rawClone.text();\n return cachedRawBodyRef.value;\n },\n };\n};\n\nexport interface DirectModuleHostHandler {\n handle(\n request: Request,\n options: { prefix: string; context: unknown },\n ): Promise<{ response?: Response }>;\n}\n\nconst handleOrpc = async (\n req: http.IncomingMessage,\n res: http.ServerResponse,\n handler: DirectModuleHostHandler,\n prefix: string,\n errorLabel: string,\n effectContext: unknown,\n port: number,\n) => {\n try {\n const webRequest = toWebRequest(req, port);\n const cachedRawBodyRef = { value: null as string | null };\n const result = await handler.handle(webRequest, {\n prefix,\n context: buildHostContext(effectContext, webRequest, cachedRawBodyRef),\n });\n\n if (result.response) {\n res.statusCode = result.response.status;\n result.response.headers.forEach((value: string, key: string) => {\n res.setHeader(key, value);\n });\n const text = await result.response.text();\n if (!res.getHeader(\"content-length\")) {\n res.setHeader(\"content-length\", Buffer.byteLength(text).toString());\n }\n res.end(text);\n } else {\n sendText(res, 404, \"Not Found\");\n }\n } catch (error) {\n console.error(`${errorLabel} error:`, error);\n sendJson(res, 500, { error: (error as Error).message });\n }\n};\n\nexport interface DirectModuleHostHandlers {\n rpc: DirectModuleHostHandler | null;\n api: DirectModuleHostHandler | null;\n}\n\nexport interface DirectModuleHostOptions {\n name: string;\n handlers: DirectModuleHostHandlers;\n effectContext: unknown;\n port?: number;\n version?: string;\n rpcPrefix?: `/${string}`;\n apiPrefix?: `/${string}`;\n staticHandler?:\n | ((req: http.IncomingMessage, res: http.ServerResponse, next: () => void) => void)\n | null;\n}\n\nexport interface DirectModuleHostHandle {\n port: number;\n close: () => Promise<void>;\n}\n\nexport async function startDirectModuleHost(\n options: DirectModuleHostOptions,\n): Promise<DirectModuleHostHandle> {\n const port = options.port ?? 0;\n let resolvedPort = port;\n const rpcPrefix = options.rpcPrefix ?? \"/api/rpc\";\n const apiPrefix = options.apiPrefix ?? \"/api\";\n const staticHandler = options.staticHandler ?? null;\n const resolveEffectContext: () => unknown =\n typeof options.effectContext === \"function\"\n ? (options.effectContext as () => unknown)\n : () => options.effectContext;\n\n const server = createServer((req, res) => {\n applyCorsHeaders(res);\n const pathname = pathnameOf(req);\n\n if (req.method === \"OPTIONS\") {\n res.statusCode = 200;\n res.end();\n return;\n }\n\n if (pathname === \"/\" && (req.method === \"GET\" || req.method === \"HEAD\")) {\n sendJson(res, 200, {\n ok: true,\n module: options.name,\n version: options.version,\n status: options.handlers.rpc ? \"ready\" : \"loading\",\n endpoints: {\n health: \"/health\",\n docs: apiPrefix,\n rpc: rpcPrefix,\n },\n });\n return;\n }\n\n if (pathname === \"/health\" && (req.method === \"GET\" || req.method === \"HEAD\")) {\n sendText(res, 200, \"OK\");\n return;\n }\n\n if (pathname.startsWith(`${rpcPrefix}/`)) {\n if (!options.handlers.rpc) {\n sendJson(res, 503, { error: \"Plugin still loading...\" });\n return;\n }\n handleOrpc(\n req,\n res,\n options.handlers.rpc,\n rpcPrefix,\n \"RPC\",\n resolveEffectContext(),\n resolvedPort,\n ).catch(() => {});\n return;\n }\n\n if (pathname === apiPrefix || pathname.startsWith(`${apiPrefix}/`)) {\n if (!options.handlers.api) {\n sendJson(res, 503, { error: \"Plugin still loading...\" });\n return;\n }\n handleOrpc(\n req,\n res,\n options.handlers.api,\n apiPrefix,\n \"OpenAPI\",\n resolveEffectContext(),\n resolvedPort,\n ).catch(() => {});\n return;\n }\n\n if (staticHandler) {\n staticHandler(req, res, () => {\n sendText(res, 404, \"Not Found\");\n });\n return;\n }\n\n sendText(res, 404, \"Not Found\");\n });\n\n await new Promise<void>((resolve, reject) => {\n server.once(\"error\", reject);\n server.listen(port, () => resolve());\n });\n\n const address = server.address();\n if (!address || typeof address === \"string\") {\n await new Promise<void>((resolve) => server.close(() => resolve()));\n throw new Error(\"Failed to resolve host port\");\n }\n resolvedPort = address.port;\n\n return {\n port: resolvedPort,\n close: async () => {\n await new Promise<void>((resolve) => server.close(() => resolve()));\n },\n };\n}\n"],"mappings":";;;AAGA,MAAM,cAAc;CAClB,+BAA+B;CAC/B,gCAAgC;CAChC,gCAAgC;AAClC;AAEA,MAAM,oBAAoB,QAA6B;CACrD,OAAO,QAAQ,WAAW,CAAC,CAAC,SAAS,CAAC,KAAK,WAAW;EACpD,IAAI,UAAU,KAAK,KAAK;CAC1B,CAAC;AACH;AAEA,MAAM,YAAY,KAA0B,QAAgB,SAAkB;CAC5E,IAAI,aAAa;CACjB,IAAI,UAAU,gBAAgB,iCAAiC;CAC/D,IAAI,IAAI,KAAK,UAAU,IAAI,CAAC;AAC9B;AAEA,MAAM,YAAY,KAA0B,QAAgB,SAAiB;CAC3E,IAAI,aAAa;CACjB,IAAI,UAAU,gBAAgB,2BAA2B;CACzD,IAAI,IAAI,IAAI;AACd;AAEA,MAAM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F;EAEA,IAAI,aAAa,aAAa,SAAS,WAAW,GAAG,UAAU,EAAE,GAAG;GAClE,IAAI,CAAC,QAAQ,SAAS,KAAK;IACzB,SAAS,KAAK,KAAK,EAAE,OAAO,0BAA0B,CAAC;IACvD;GACF;GACA,WACE,KACA,KACA,QAAQ,SAAS,KACjB,WACA,WACA,qBAAqB,GACrB,YACF,CAAC,CAAC,YAAY,CAAC,CAAC;GAChB;EACF;EAEA,IAAI,eAAe;GACjB,cAAc,KAAK,WAAW;IAC5B,SAAS,KAAK,KAAK,WAAW;GAChC,CAAC;GACD;EACF;EAEA,SAAS,KAAK,KAAK,WAAW;CAChC,CAAC;CAED,MAAM,IAAI,SAAe,SAAS,WAAW;EAC3C,OAAO,KAAK,SAAS,MAAM;EAC3B,OAAO,OAAO,YAAY,QAAQ,CAAC;CACrC,CAAC;CAED,MAAM,UAAU,OAAO,QAAQ;CAC/B,IAAI,CAAC,WAAW,OAAO,YAAY,UAAU;EAC3C,MAAM,IAAI,SAAe,YAAY,OAAO,YAAY,QAAQ,CAAC,CAAC;EAClE,MAAM,IAAI,MAAM,6BAA6B;CAC/C;CACA,eAAe,QAAQ;CAEvB,OAAO;EACL,MAAM;EACN,OAAO,YAAY;GACjB,MAAM,IAAI,SAAe,YAAY,OAAO,YAAY,QAAQ,CAAC,CAAC;EACpE;CACF;AACF"}
|
package/dist/dev/serve.cjs
CHANGED
|
@@ -5,6 +5,7 @@ const require_build_artifact_names = require('../build/artifact-names.cjs');
|
|
|
5
5
|
const require_remote_entry = require('../remote-entry.cjs');
|
|
6
6
|
const require_utils = require('../build/rspack/utils.cjs');
|
|
7
7
|
const require_generated_config = require('../build/ui/generated-config.cjs');
|
|
8
|
+
const require_dev_host = require('./host.cjs');
|
|
8
9
|
const require_generated_config$1 = require('../build/rspack/generated-config.cjs');
|
|
9
10
|
const require_watch_kill = require('./watch-kill.cjs');
|
|
10
11
|
let effect = require("effect");
|
|
@@ -70,11 +71,6 @@ const loadPluginWithRetry = (runtime, pluginId, remoteUrl, options = {
|
|
|
70
71
|
load: () => runtime.usePlugin(pluginId, options, pluginsMap),
|
|
71
72
|
timeoutMs
|
|
72
73
|
}));
|
|
73
|
-
const sendJson = (res, status, body) => {
|
|
74
|
-
res.statusCode = status;
|
|
75
|
-
res.setHeader("content-type", "application/json; charset=utf-8");
|
|
76
|
-
res.end(JSON.stringify(body));
|
|
77
|
-
};
|
|
78
74
|
const sendText = (res, status, text) => {
|
|
79
75
|
res.statusCode = status;
|
|
80
76
|
res.setHeader("content-type", "text/plain; charset=utf-8");
|
|
@@ -98,7 +94,6 @@ async function startPluginDevServer(options = {}) {
|
|
|
98
94
|
const compositionKey = require_generated_config.pluginLayoutKey(cwd) ?? pluginId;
|
|
99
95
|
const port = options.port ?? (Number(process.env.PORT) || devConfig?.port || 3999);
|
|
100
96
|
const rpcPrefix = normalizePrefix(devConfig?.prefix);
|
|
101
|
-
const rpcBase = `/api/rpc${rpcPrefix}`;
|
|
102
97
|
const distDir = node_path.default.join(cwd, "dist");
|
|
103
98
|
const serveStatic = (0, sirv.default)(distDir, { dev: true });
|
|
104
99
|
const noWatch = options.watch === false || process.env.BOS_NO_WATCH === "1";
|
|
@@ -148,8 +143,8 @@ async function startPluginDevServer(options = {}) {
|
|
|
148
143
|
"--config",
|
|
149
144
|
uiConfig
|
|
150
145
|
]);
|
|
151
|
-
const uiDistDir =
|
|
152
|
-
if (!node_fs.default.existsSync(node_path.default.join(uiDistDir, "remoteEntry.js")))
|
|
146
|
+
const uiDistDir = require_generated_config.uiDistDirFor(cwd);
|
|
147
|
+
if (!node_fs.default.existsSync(node_path.default.join(uiDistDir, "remoteEntry.js"))) throw new Error(`❌ UI dist is missing at ${uiDistDir} after the rsbuild one-shot — build output layout mismatch?`);
|
|
153
148
|
const serveUiStatic = (0, sirv.default)(uiDistDir, { dev: true });
|
|
154
149
|
uiStaticServer = node_http.default.createServer((req, res) => {
|
|
155
150
|
applyCorsHeaders(res);
|
|
@@ -186,108 +181,18 @@ async function startPluginDevServer(options = {}) {
|
|
|
186
181
|
};
|
|
187
182
|
const effectContextHolder = { context: null };
|
|
188
183
|
let runtime = null;
|
|
189
|
-
const
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
getRawBody: async () => {
|
|
197
|
-
if (cachedRawBody !== null) return cachedRawBody;
|
|
198
|
-
if (!rawClone) {
|
|
199
|
-
cachedRawBody = "";
|
|
200
|
-
return cachedRawBody;
|
|
201
|
-
}
|
|
202
|
-
cachedRawBody = await rawClone.text();
|
|
203
|
-
return cachedRawBody;
|
|
204
|
-
}
|
|
205
|
-
};
|
|
206
|
-
};
|
|
207
|
-
const toWebRequest = (req) => {
|
|
208
|
-
const url = `http://localhost:${port}${req.url}`;
|
|
209
|
-
return new Request(url, {
|
|
210
|
-
method: req.method,
|
|
211
|
-
headers: req.headers,
|
|
212
|
-
body: req.method !== "GET" && req.method !== "HEAD" ? req : void 0,
|
|
213
|
-
duplex: req.method !== "GET" && req.method !== "HEAD" ? "half" : void 0
|
|
214
|
-
});
|
|
215
|
-
};
|
|
216
|
-
const handleOrpc = async (req, res, handler, prefix, errorLabel) => {
|
|
217
|
-
try {
|
|
218
|
-
const webRequest = toWebRequest(req);
|
|
219
|
-
const result = await handler.handle(webRequest, {
|
|
220
|
-
prefix,
|
|
221
|
-
context: buildDevContext(req, webRequest)
|
|
222
|
-
});
|
|
223
|
-
if (result.response) {
|
|
224
|
-
res.statusCode = result.response.status;
|
|
225
|
-
result.response.headers.forEach((value, key) => {
|
|
226
|
-
res.setHeader(key, value);
|
|
227
|
-
});
|
|
228
|
-
const text = await result.response.text();
|
|
229
|
-
if (!res.getHeader("content-length")) res.setHeader("content-length", Buffer.byteLength(text).toString());
|
|
230
|
-
res.end(text);
|
|
231
|
-
} else sendText(res, 404, "Not Found");
|
|
232
|
-
} catch (error) {
|
|
233
|
-
console.error(`${errorLabel} error:`, error);
|
|
234
|
-
sendJson(res, 500, { error: error.message });
|
|
235
|
-
}
|
|
236
|
-
};
|
|
237
|
-
const server = node_http.default.createServer((req, res) => {
|
|
238
|
-
applyCorsHeaders(res);
|
|
239
|
-
const pathname = pathnameOf(req);
|
|
240
|
-
if (req.method === "OPTIONS") {
|
|
241
|
-
res.statusCode = 200;
|
|
242
|
-
res.end();
|
|
243
|
-
return;
|
|
244
|
-
}
|
|
245
|
-
if (pathname === "/" && (req.method === "GET" || req.method === "HEAD")) {
|
|
246
|
-
sendJson(res, 200, {
|
|
247
|
-
ok: true,
|
|
248
|
-
plugin: pluginInfo.normalizedName,
|
|
249
|
-
version: pluginInfo.version,
|
|
250
|
-
status: handlers.rpc ? "ready" : "loading",
|
|
251
|
-
endpoints: {
|
|
252
|
-
health: "/",
|
|
253
|
-
docs: "/api",
|
|
254
|
-
rpc: rpcBase
|
|
255
|
-
}
|
|
256
|
-
});
|
|
257
|
-
return;
|
|
258
|
-
}
|
|
259
|
-
if (pathname === "/health" && (req.method === "GET" || req.method === "HEAD")) {
|
|
260
|
-
sendText(res, 200, "OK");
|
|
261
|
-
return;
|
|
262
|
-
}
|
|
263
|
-
if (pathname.startsWith(`${rpcBase}/`)) {
|
|
264
|
-
if (!handlers.rpc) {
|
|
265
|
-
sendJson(res, 503, { error: "Plugin still loading..." });
|
|
266
|
-
return;
|
|
267
|
-
}
|
|
268
|
-
handleOrpc(req, res, handlers.rpc, rpcBase, "RPC").catch(() => {});
|
|
269
|
-
return;
|
|
270
|
-
}
|
|
271
|
-
if (pathname === "/api" || pathname.startsWith("/api/")) {
|
|
272
|
-
if (!handlers.api) {
|
|
273
|
-
sendJson(res, 503, { error: "Plugin still loading..." });
|
|
274
|
-
return;
|
|
275
|
-
}
|
|
276
|
-
handleOrpc(req, res, handlers.api, "/api", "OpenAPI").catch(() => {});
|
|
277
|
-
return;
|
|
278
|
-
}
|
|
279
|
-
serveStatic(req, res, () => {
|
|
280
|
-
sendText(res, 404, "Not Found");
|
|
281
|
-
});
|
|
282
|
-
});
|
|
283
|
-
await new Promise((resolve, reject) => {
|
|
284
|
-
server.once("error", reject);
|
|
285
|
-
server.listen(port, () => resolve());
|
|
184
|
+
const host = await require_dev_host.startDirectModuleHost({
|
|
185
|
+
name: pluginInfo.normalizedName,
|
|
186
|
+
version: pluginInfo.version,
|
|
187
|
+
handlers,
|
|
188
|
+
effectContext: () => effectContextHolder.context,
|
|
189
|
+
port,
|
|
190
|
+
staticHandler: serveStatic
|
|
286
191
|
});
|
|
287
|
-
console.log(`🚀 ${pluginInfo.name} dev server listening on port ${port}`);
|
|
288
|
-
console.log(`├─ 📡 RPC: http://localhost:${port}/api/rpc${rpcPrefix}`);
|
|
289
|
-
console.log(`├─ 📖 Docs: http://localhost:${port}/api`);
|
|
290
|
-
console.log(`└─ 💚 Health: http://localhost:${port}/`);
|
|
192
|
+
console.log(`🚀 ${pluginInfo.name} dev server listening on port ${host.port}`);
|
|
193
|
+
console.log(`├─ 📡 RPC: http://localhost:${host.port}/api/rpc${rpcPrefix}`);
|
|
194
|
+
console.log(`├─ 📖 Docs: http://localhost:${host.port}/api`);
|
|
195
|
+
console.log(`└─ 💚 Health: http://localhost:${host.port}/`);
|
|
291
196
|
const load = async () => {
|
|
292
197
|
try {
|
|
293
198
|
const { createPluginRuntime } = await Promise.resolve().then(() => require("../runtime/index.cjs"));
|
|
@@ -302,7 +207,7 @@ async function startPluginDevServer(options = {}) {
|
|
|
302
207
|
const { siblings, dependsOn } = collectSiblingRemotes(runtimeConfig, compositionKey);
|
|
303
208
|
if (dependsOn.length > 0) console.log(`🔗 Loading sibling plugin(s): ${dependsOn.join(", ")}`);
|
|
304
209
|
const registry = {
|
|
305
|
-
[pluginId]: { remote: `http://localhost:${port}/${require_build_artifact_names.DEV_ENTRY_FILENAME}` },
|
|
210
|
+
[pluginId]: { remote: `http://localhost:${host.port}/${require_build_artifact_names.DEV_ENTRY_FILENAME}` },
|
|
306
211
|
...siblings
|
|
307
212
|
};
|
|
308
213
|
const mfRuntime = createPluginRuntime({ registry });
|
|
@@ -353,8 +258,8 @@ async function startPluginDevServer(options = {}) {
|
|
|
353
258
|
effectContextHolder.context = null;
|
|
354
259
|
for (const child of [watcher, uiWatcher]) if (child) await require_watch_kill.killChildEscalating(child);
|
|
355
260
|
if (uiStaticServer) await new Promise((resolve) => uiStaticServer.close(() => resolve()));
|
|
261
|
+
await host.close();
|
|
356
262
|
if (runtime) await runtime.shutdown().catch(() => {});
|
|
357
|
-
await new Promise((resolve) => server.close(() => resolve()));
|
|
358
263
|
};
|
|
359
264
|
process.once("SIGINT", async () => {
|
|
360
265
|
const timeout = setTimeout(() => process.exit(0), 3e3);
|
package/dist/dev/serve.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"serve.cjs","names":["DEV_ENTRY_FILENAME","Effect","loadRemoteWithRetry","getPluginInfo","loadDevConfig","path","pluginLayoutKey","spawn","ensureGeneratedRspackConfig","ensureGeneratedUiRsbuildConfig","fs","http","PLUGIN_ERROR_STATUS_MAP","killChildEscalating"],"sources":["../../src/dev/serve.ts"],"sourcesContent":["import { spawn } from \"node:child_process\";\nimport fs from \"node:fs\";\nimport http from \"node:http\";\nimport path from \"node:path\";\nimport { Effect } from \"effect\";\nimport sirv from \"sirv\";\nimport { DEV_ENTRY_FILENAME } from \"../build/artifact-names\";\nimport { ensureGeneratedRspackConfig } from \"../build/rspack/generated-config\";\nimport { getPluginInfo, loadDevConfig } from \"../build/rspack/utils\";\nimport { ensureGeneratedUiRsbuildConfig, pluginLayoutKey } from \"../build/ui/generated-config\";\nimport { PLUGIN_ERROR_STATUS_MAP } from \"../errors\";\nimport { loadRemoteWithRetry } from \"../remote-entry\";\nimport { killChildEscalating, watchParentDeath } from \"./watch-kill\";\n\nconst corsHeaders = {\n \"Access-Control-Allow-Origin\": \"*\",\n \"Access-Control-Allow-Methods\": \"GET, POST, PUT, DELETE, PATCH, OPTIONS\",\n \"Access-Control-Allow-Headers\": \"X-Requested-With, content-type, Authorization\",\n};\n\nconst applyCorsHeaders = (res: http.ServerResponse) => {\n Object.entries(corsHeaders).forEach(([key, value]) => {\n res.setHeader(key, value);\n });\n};\n\nconst normalizePrefix = (prefix?: string): string => {\n if (!prefix) return \"\";\n const cleaned = prefix.replace(/^\\/+|\\/+$/g, \"\");\n return cleaned ? `/${cleaned}` : \"\";\n};\n\nconst readRuntimeConfigFromEnv = (): any => {\n const raw = process.env.BOS_RUNTIME_CONFIG;\n if (!raw) return null;\n try {\n return JSON.parse(raw);\n } catch {\n return null;\n }\n};\n\nconst collectSiblingRemotes = (runtimeConfig: any, pluginId: string) => {\n const siblings: Record<string, { remote: string }> = {};\n\n const isApi = pluginId === \"api\" || runtimeConfig?.api?.name === pluginId;\n\n const ownKey = runtimeConfig?.plugins?.[pluginId] ? pluginId : null;\n let dependsOn: string[] = [];\n if (ownKey) {\n dependsOn = runtimeConfig.plugins[ownKey].dependsOn ?? [];\n } else if (isApi) {\n dependsOn = runtimeConfig?.api?.dependsOn ?? [];\n }\n\n for (const depId of dependsOn) {\n const dep = runtimeConfig?.plugins?.[depId];\n if (!dep || dep.source !== \"local\" || !dep.url) continue;\n if (depId === pluginId) continue;\n const base = dep.url.replace(/\\/$/, \"\");\n siblings[depId] = { remote: `${base}/${DEV_ENTRY_FILENAME}` };\n }\n\n return { siblings, dependsOn };\n};\n\nconst loadPluginWithRetry = (\n runtime: any,\n pluginId: string,\n remoteUrl: string,\n options: Record<string, unknown> = { variables: {}, secrets: {} },\n pluginsMap?: Record<string, unknown>,\n timeoutMs = 90000,\n): Promise<any> =>\n Effect.runPromise(\n loadRemoteWithRetry({\n label: pluginId,\n remoteUrl,\n load: () => runtime.usePlugin(pluginId, options, pluginsMap),\n timeoutMs,\n }),\n );\n\nconst sendJson = (res: http.ServerResponse, status: number, body: unknown) => {\n res.statusCode = status;\n res.setHeader(\"content-type\", \"application/json; charset=utf-8\");\n res.end(JSON.stringify(body));\n};\n\nconst sendText = (res: http.ServerResponse, status: number, text: string) => {\n res.statusCode = status;\n res.setHeader(\"content-type\", \"text/plain; charset=utf-8\");\n res.end(text);\n};\n\nexport interface PluginDevServeOptions {\n cwd?: string;\n port?: number;\n watch?: boolean;\n}\n\nexport interface PluginDevServerHandle {\n port: number;\n close: () => Promise<void>;\n}\n\n/**\n * The dev server's plugin id — the workspace's npm package name, the same\n * value the host passes as `runtimeId`. Both initialize sites must agree:\n * `registerRemote` derives the MF remote name from it, and the plugin's\n * database layer derives its migration slug from it, so a pre-normalized\n * remote name here would migrate into a different schema than the host\n * expects. plugin.dev.ts no longer carries a pluginId field.\n */\nexport const resolveDevPluginId = (cwd: string): string => getPluginInfo(cwd).name;\n\nexport async function startPluginDevServer(\n options: PluginDevServeOptions = {},\n): Promise<PluginDevServerHandle> {\n process.env.BOS_DEV_SERVER = \"1\";\n const cwd = options.cwd ?? process.cwd();\n const pluginInfo = getPluginInfo(cwd);\n const devConfig = loadDevConfig(path.join(cwd, \"plugin.dev.ts\"));\n const pluginId = resolveDevPluginId(cwd);\n const compositionKey = pluginLayoutKey(cwd) ?? pluginId;\n const port = options.port ?? (Number(process.env.PORT) || devConfig?.port || 3999);\n const rpcPrefix = normalizePrefix(devConfig?.prefix);\n const rpcBase = `/api/rpc${rpcPrefix}`;\n\n const distDir = path.join(cwd, \"dist\");\n const serveStatic = sirv(distDir, { dev: true });\n\n // No-watch mode (BOS_NO_WATCH=1): build once, serve the built output.\n // Regression/CI stacks need no hot reload — watchers are the stack's\n // heaviest processes and stall runs freeze under their accumulated\n // footprint. One-shot builds exit; steady state is small static servers.\n const noWatch = options.watch === false || process.env.BOS_NO_WATCH === \"1\";\n\n const runOnce = (cmd: string, args: string[]) =>\n new Promise<void>((resolve, reject) => {\n const child = spawn(cmd, args, { cwd, stdio: \"inherit\", env: process.env });\n child.on(\"error\", reject);\n child.on(\"exit\", (code) => {\n if (code === 0) resolve();\n else reject(new Error(`❌ ${cmd} ${args.join(\" \")} exited with ${code}`));\n });\n });\n\n let watcher: ReturnType<typeof spawn> | null = null;\n if (noWatch) {\n const generatedConfig = ensureGeneratedRspackConfig(cwd);\n await runOnce(\"rspack\", generatedConfig ? [\"build\", \"--config\", generatedConfig] : [\"build\"]);\n } else if (options.watch !== false) {\n const generatedConfig = ensureGeneratedRspackConfig(cwd);\n watcher = spawn(\n \"rspack\",\n generatedConfig ? [\"build\", \"--watch\", \"--config\", generatedConfig] : [\"build\", \"--watch\"],\n {\n cwd,\n stdio: \"inherit\",\n env: process.env,\n },\n );\n watcher.on(\"error\", (error) => {\n console.error(`❌ Failed to spawn rspack build --watch: ${error.message}`);\n });\n }\n\n let uiWatcher: ReturnType<typeof spawn> | null = null;\n let uiStaticServer: http.Server | null = null;\n const uiPort = process.env.BOS_UI_PORT;\n const uiConfig = ensureGeneratedUiRsbuildConfig(cwd);\n if (uiConfig && noWatch && uiPort) {\n // Folder-form ui: one-shot build, then serve the ui source root's dist\n // (the factory's absolute distPath target) statically on the ui port.\n await runOnce(\"rsbuild\", [\"build\", \"--config\", uiConfig]);\n const uiDistDir =\n path.basename(cwd) === \"ui\" ? path.join(cwd, \"dist\") : path.join(cwd, \"ui\", \"dist\");\n if (!fs.existsSync(path.join(uiDistDir, DEV_ENTRY_FILENAME))) {\n console.error(\n `❌ UI dist is missing at ${uiDistDir} — the ui static server would serve 404s for every asset (build output layout mismatch?)`,\n );\n }\n const serveUiStatic = sirv(uiDistDir, { dev: true });\n uiStaticServer = http.createServer((req, res) => {\n applyCorsHeaders(res);\n serveUiStatic(req, res, () => {\n sendText(res, 404, \"Not Found\");\n });\n });\n await new Promise<void>((resolve, reject) => {\n uiStaticServer!.once(\"error\", reject);\n uiStaticServer!.listen(Number(uiPort), () => resolve());\n });\n console.log(`├─ 🎨 UI: http://localhost:${uiPort} (built, no watch)`);\n } else if (uiConfig) {\n uiWatcher = spawn(\"rsbuild\", [\"dev\", \"--config\", uiConfig], {\n cwd,\n stdio: \"inherit\",\n env: uiPort ? { ...process.env, PORT: uiPort } : process.env,\n });\n uiWatcher.on(\"error\", (error) => {\n console.error(`❌ Failed to spawn rsbuild ui dev: ${error.message}`);\n });\n console.log(`├─ 🎨 UI: ${uiPort ? `http://localhost:${uiPort}` : \"(rsbuild auto port)\"}`);\n }\n\n const handlers: { rpc: any; api: any } = { rpc: null, api: null };\n const effectContextHolder: { context: unknown } = { context: null };\n let runtime: { shutdown: () => Promise<void> } | null = null;\n\n const pathnameOf = (req: http.IncomingMessage): string =>\n ((req.url ?? \"/\").split(\"?\")[0] ?? \"/\").replace(/\\/+$/, \"\") || \"/\";\n\n const buildDevContext = (_req: http.IncomingMessage, webRequest: Request) => {\n const rawClone =\n webRequest.method === \"GET\" || webRequest.method === \"HEAD\" ? null : webRequest.clone();\n let cachedRawBody: string | null = null;\n return {\n reqHeaders: webRequest.headers,\n \"effect/context\": effectContextHolder.context,\n getRawBody: async (): Promise<string> => {\n if (cachedRawBody !== null) return cachedRawBody;\n if (!rawClone) {\n cachedRawBody = \"\";\n return cachedRawBody;\n }\n cachedRawBody = await rawClone.text();\n return cachedRawBody;\n },\n };\n };\n\n const toWebRequest = (req: http.IncomingMessage): Request => {\n const url = `http://localhost:${port}${req.url}`;\n return new Request(url, {\n method: req.method,\n headers: req.headers,\n body: req.method !== \"GET\" && req.method !== \"HEAD\" ? req : undefined,\n duplex: req.method !== \"GET\" && req.method !== \"HEAD\" ? \"half\" : undefined,\n } as RequestInit);\n };\n\n const handleOrpc = async (\n req: http.IncomingMessage,\n res: http.ServerResponse,\n handler: any,\n prefix: string,\n errorLabel: string,\n ) => {\n try {\n const webRequest = toWebRequest(req);\n const result = await handler.handle(webRequest, {\n prefix,\n context: buildDevContext(req, webRequest),\n });\n\n if (result.response) {\n res.statusCode = result.response.status;\n result.response.headers.forEach((value: string, key: string) => {\n res.setHeader(key, value);\n });\n const text = await result.response.text();\n if (!res.getHeader(\"content-length\")) {\n res.setHeader(\"content-length\", Buffer.byteLength(text).toString());\n }\n res.end(text);\n } else {\n sendText(res, 404, \"Not Found\");\n }\n } catch (error) {\n console.error(`${errorLabel} error:`, error);\n sendJson(res, 500, { error: (error as Error).message });\n }\n };\n\n const server = http.createServer((req, res) => {\n applyCorsHeaders(res);\n const pathname = pathnameOf(req);\n\n if (req.method === \"OPTIONS\") {\n res.statusCode = 200;\n res.end();\n return;\n }\n\n if (pathname === \"/\" && (req.method === \"GET\" || req.method === \"HEAD\")) {\n sendJson(res, 200, {\n ok: true,\n plugin: pluginInfo.normalizedName,\n version: pluginInfo.version,\n status: handlers.rpc ? \"ready\" : \"loading\",\n endpoints: {\n health: \"/\",\n docs: \"/api\",\n rpc: rpcBase,\n },\n });\n return;\n }\n\n if (pathname === \"/health\" && (req.method === \"GET\" || req.method === \"HEAD\")) {\n sendText(res, 200, \"OK\");\n return;\n }\n\n if (pathname.startsWith(`${rpcBase}/`)) {\n if (!handlers.rpc) {\n sendJson(res, 503, { error: \"Plugin still loading...\" });\n return;\n }\n handleOrpc(req, res, handlers.rpc, rpcBase, \"RPC\").catch(() => {});\n return;\n }\n\n if (pathname === \"/api\" || pathname.startsWith(\"/api/\")) {\n if (!handlers.api) {\n sendJson(res, 503, { error: \"Plugin still loading...\" });\n return;\n }\n handleOrpc(req, res, handlers.api, \"/api\", \"OpenAPI\").catch(() => {});\n return;\n }\n\n serveStatic(req, res, () => {\n sendText(res, 404, \"Not Found\");\n });\n });\n\n await new Promise<void>((resolve, reject) => {\n server.once(\"error\", reject);\n server.listen(port, () => resolve());\n });\n\n console.log(`🚀 ${pluginInfo.name} dev server listening on port ${port}`);\n console.log(`├─ 📡 RPC: http://localhost:${port}/api/rpc${rpcPrefix}`);\n console.log(`├─ 📖 Docs: http://localhost:${port}/api`);\n console.log(`└─ 💚 Health: http://localhost:${port}/`);\n\n const load = async () => {\n try {\n // Import framework internals directly. A package self-import can resolve\n // the published entry while this source-first dev server is running,\n // which leaves the runtime exports unavailable on Windows.\n const { createPluginRuntime } = await import(\"../runtime\");\n const { RPCHandler } = await import(\"@orpc/server/fetch\");\n const { OpenAPIHandler } = await import(\"@orpc/openapi/fetch\");\n const { OpenAPIGenerator } = await import(\"@orpc/openapi\");\n const { OpenAPIReferenceHandlerPlugin } = await import(\"@orpc/openapi/plugins\");\n const { ZodToJsonSchemaConverter } = await import(\"@orpc/zod\");\n const { onError } = await import(\"@orpc/server\");\n const { formatORPCError } = await import(\"../errors\");\n\n const runtimeConfig = readRuntimeConfigFromEnv();\n const { siblings, dependsOn } = collectSiblingRemotes(runtimeConfig, compositionKey);\n\n if (dependsOn.length > 0) {\n console.log(`🔗 Loading sibling plugin(s): ${dependsOn.join(\", \")}`);\n }\n\n const registry: Record<string, { remote: string }> = {\n [pluginId]: {\n remote: `http://localhost:${port}/${DEV_ENTRY_FILENAME}`,\n },\n ...siblings,\n };\n\n const mfRuntime = createPluginRuntime({ registry });\n runtime = mfRuntime;\n\n const pluginsMap: Record<string, unknown> = {};\n const siblingEffectContexts: unknown[] = [];\n for (const depId of Object.keys(siblings)) {\n const dep = await loadPluginWithRetry(mfRuntime, depId, siblings[depId]!.remote);\n pluginsMap[depId] = { client: dep.createClient, router: dep.router };\n if (dep.initialized?.effectContext) {\n siblingEffectContexts.push(dep.initialized.effectContext);\n }\n console.log(`✅ Loaded dependency plugin: ${depId}`);\n }\n\n const loaded: any = await loadPluginWithRetry(\n mfRuntime,\n pluginId,\n registry[pluginId]!.remote,\n (devConfig?.config ?? { variables: {}, secrets: {} }) as Record<string, unknown>,\n Object.keys(pluginsMap).length > 0 ? pluginsMap : undefined,\n );\n\n const { Context } = await import(\"effect\");\n effectContextHolder.context = [loaded.initialized?.effectContext, ...siblingEffectContexts]\n .filter(Boolean)\n .reduce((acc: any, ctx: any) => Context.merge(acc, ctx), Context.empty());\n\n handlers.rpc = new RPCHandler(loaded.router, {\n errorStatusMap: PLUGIN_ERROR_STATUS_MAP,\n interceptors: [\n onError((error: any) => {\n const formatted = formatORPCError(error);\n if (formatted) console.error(formatted);\n }),\n ],\n });\n\n const generator = new OpenAPIGenerator({ converters: [new ZodToJsonSchemaConverter()] });\n\n handlers.api = new OpenAPIHandler(loaded.router, {\n errorStatusMap: PLUGIN_ERROR_STATUS_MAP,\n plugins: [\n new OpenAPIReferenceHandlerPlugin({\n spec: () => generator.generate(loaded.router, { version: \"3.1.1\" }),\n }),\n ],\n interceptors: [\n onError((error: any) => {\n const formatted = formatORPCError(error);\n if (formatted) console.error(formatted);\n }),\n ],\n });\n\n console.log(`✅ Plugin ready: ${pluginId}`);\n } catch (error) {\n console.error(`❌ Failed to load plugin ${pluginId}:`, error);\n console.error(\" Server stays up; fix the build and retry via rebuild.\");\n }\n };\n\n void load();\n\n const close = async () => {\n handlers.rpc = null;\n handlers.api = null;\n effectContextHolder.context = null;\n for (const child of [watcher, uiWatcher]) {\n if (child) {\n await killChildEscalating(child);\n }\n }\n if (uiStaticServer) {\n await new Promise<void>((resolve) => uiStaticServer.close(() => resolve()));\n }\n if (runtime) await runtime.shutdown().catch(() => {});\n await new Promise<void>((resolve) => server.close(() => resolve()));\n };\n\n process.once(\"SIGINT\", async () => {\n const timeout = setTimeout(() => process.exit(0), 3000);\n await close();\n clearTimeout(timeout);\n process.exit(0);\n });\n process.once(\"SIGTERM\", async () => {\n const timeout = setTimeout(() => process.exit(0), 3000);\n await close();\n clearTimeout(timeout);\n process.exit(0);\n });\n\n watchParentDeath(async () => {\n const timeout = setTimeout(() => process.exit(0), 3000);\n await close();\n clearTimeout(timeout);\n process.exit(0);\n });\n\n return { port, close };\n}\n\nconst invokedAsCli = import.meta.main || (process.argv[1] ?? \"\").includes(\"every-plugin-serve\");\n\nif (invokedAsCli) {\n startPluginDevServer().catch((error) => {\n console.error(\"❌ Plugin dev server fatal error:\", error);\n process.exit(1);\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAcA,MAAM,cAAc;CAClB,+BAA+B;CAC/B,gCAAgC;CAChC,gCAAgC;AAClC;AAEA,MAAM,oBAAoB,QAA6B;CACrD,OAAO,QAAQ,WAAW,CAAC,CAAC,SAAS,CAAC,KAA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tC,QAAQ,MAAM,oCAAoC,KAAK;CACvD,QAAQ,KAAK,CAAC;AAChB,CAAC"}
|
|
1
|
+
{"version":3,"file":"serve.cjs","names":["DEV_ENTRY_FILENAME","Effect","loadRemoteWithRetry","getPluginInfo","loadDevConfig","path","pluginLayoutKey","spawn","ensureGeneratedRspackConfig","ensureGeneratedUiRsbuildConfig","uiDistDirFor","fs","http","startDirectModuleHost","PLUGIN_ERROR_STATUS_MAP","killChildEscalating"],"sources":["../../src/dev/serve.ts"],"sourcesContent":["import { spawn } from \"node:child_process\";\nimport fs from \"node:fs\";\nimport http from \"node:http\";\nimport path from \"node:path\";\nimport { Effect } from \"effect\";\nimport sirv from \"sirv\";\nimport { DEV_ENTRY_FILENAME } from \"../build/artifact-names\";\nimport { ensureGeneratedRspackConfig } from \"../build/rspack/generated-config\";\nimport { getPluginInfo, loadDevConfig } from \"../build/rspack/utils\";\nimport {\n ensureGeneratedUiRsbuildConfig,\n pluginLayoutKey,\n uiDistDirFor,\n} from \"../build/ui/generated-config\";\nimport { PLUGIN_ERROR_STATUS_MAP } from \"../errors\";\nimport { loadRemoteWithRetry } from \"../remote-entry\";\nimport { startDirectModuleHost } from \"./host\";\nimport { killChildEscalating, watchParentDeath } from \"./watch-kill\";\n\nconst corsHeaders = {\n \"Access-Control-Allow-Origin\": \"*\",\n \"Access-Control-Allow-Methods\": \"GET, POST, PUT, DELETE, PATCH, OPTIONS\",\n \"Access-Control-Allow-Headers\": \"X-Requested-With, content-type, Authorization\",\n};\n\nconst applyCorsHeaders = (res: http.ServerResponse) => {\n Object.entries(corsHeaders).forEach(([key, value]) => {\n res.setHeader(key, value);\n });\n};\n\nconst normalizePrefix = (prefix?: string): string => {\n if (!prefix) return \"\";\n const cleaned = prefix.replace(/^\\/+|\\/+$/g, \"\");\n return cleaned ? `/${cleaned}` : \"\";\n};\n\nconst readRuntimeConfigFromEnv = (): any => {\n const raw = process.env.BOS_RUNTIME_CONFIG;\n if (!raw) return null;\n try {\n return JSON.parse(raw);\n } catch {\n return null;\n }\n};\n\nconst collectSiblingRemotes = (runtimeConfig: any, pluginId: string) => {\n const siblings: Record<string, { remote: string }> = {};\n\n const isApi = pluginId === \"api\" || runtimeConfig?.api?.name === pluginId;\n\n const ownKey = runtimeConfig?.plugins?.[pluginId] ? pluginId : null;\n let dependsOn: string[] = [];\n if (ownKey) {\n dependsOn = runtimeConfig.plugins[ownKey].dependsOn ?? [];\n } else if (isApi) {\n dependsOn = runtimeConfig?.api?.dependsOn ?? [];\n }\n\n for (const depId of dependsOn) {\n const dep = runtimeConfig?.plugins?.[depId];\n if (!dep || dep.source !== \"local\" || !dep.url) continue;\n if (depId === pluginId) continue;\n const base = dep.url.replace(/\\/$/, \"\");\n siblings[depId] = { remote: `${base}/${DEV_ENTRY_FILENAME}` };\n }\n\n return { siblings, dependsOn };\n};\n\nconst loadPluginWithRetry = (\n runtime: any,\n pluginId: string,\n remoteUrl: string,\n options: Record<string, unknown> = { variables: {}, secrets: {} },\n pluginsMap?: Record<string, unknown>,\n timeoutMs = 90000,\n): Promise<any> =>\n Effect.runPromise(\n loadRemoteWithRetry({\n label: pluginId,\n remoteUrl,\n load: () => runtime.usePlugin(pluginId, options, pluginsMap),\n timeoutMs,\n }),\n );\n\nconst sendText = (res: http.ServerResponse, status: number, text: string) => {\n res.statusCode = status;\n res.setHeader(\"content-type\", \"text/plain; charset=utf-8\");\n res.end(text);\n};\n\nexport interface PluginDevServeOptions {\n cwd?: string;\n port?: number;\n watch?: boolean;\n}\n\nexport interface PluginDevServerHandle {\n port: number;\n close: () => Promise<void>;\n}\n\n/**\n * The dev server's plugin id — the workspace's npm package name, the same\n * value the host passes as `runtimeId`. Both initialize sites must agree:\n * `registerRemote` derives the MF remote name from it, and the plugin's\n * database layer derives its migration slug from it, so a pre-normalized\n * remote name here would migrate into a different schema than the host\n * expects. plugin.dev.ts no longer carries a pluginId field.\n */\nexport const resolveDevPluginId = (cwd: string): string => getPluginInfo(cwd).name;\n\nexport async function startPluginDevServer(\n options: PluginDevServeOptions = {},\n): Promise<PluginDevServerHandle> {\n process.env.BOS_DEV_SERVER = \"1\";\n const cwd = options.cwd ?? process.cwd();\n const pluginInfo = getPluginInfo(cwd);\n const devConfig = loadDevConfig(path.join(cwd, \"plugin.dev.ts\"));\n const pluginId = resolveDevPluginId(cwd);\n const compositionKey = pluginLayoutKey(cwd) ?? pluginId;\n const port = options.port ?? (Number(process.env.PORT) || devConfig?.port || 3999);\n const rpcPrefix = normalizePrefix(devConfig?.prefix);\n\n const distDir = path.join(cwd, \"dist\");\n const serveStatic = sirv(distDir, { dev: true });\n\n // No-watch mode (BOS_NO_WATCH=1): build once, serve the built output.\n // Regression/CI stacks need no hot reload — watchers are the stack's\n // heaviest processes and stall runs freeze under their accumulated\n // footprint. One-shot builds exit; steady state is small static servers.\n const noWatch = options.watch === false || process.env.BOS_NO_WATCH === \"1\";\n\n const runOnce = (cmd: string, args: string[]) =>\n new Promise<void>((resolve, reject) => {\n const child = spawn(cmd, args, { cwd, stdio: \"inherit\", env: process.env });\n child.on(\"error\", reject);\n child.on(\"exit\", (code) => {\n if (code === 0) resolve();\n else reject(new Error(`❌ ${cmd} ${args.join(\" \")} exited with ${code}`));\n });\n });\n\n let watcher: ReturnType<typeof spawn> | null = null;\n if (noWatch) {\n const generatedConfig = ensureGeneratedRspackConfig(cwd);\n await runOnce(\"rspack\", generatedConfig ? [\"build\", \"--config\", generatedConfig] : [\"build\"]);\n } else if (options.watch !== false) {\n const generatedConfig = ensureGeneratedRspackConfig(cwd);\n watcher = spawn(\n \"rspack\",\n generatedConfig ? [\"build\", \"--watch\", \"--config\", generatedConfig] : [\"build\", \"--watch\"],\n {\n cwd,\n stdio: \"inherit\",\n env: process.env,\n },\n );\n watcher.on(\"error\", (error) => {\n console.error(`❌ Failed to spawn rspack build --watch: ${error.message}`);\n });\n }\n\n let uiWatcher: ReturnType<typeof spawn> | null = null;\n let uiStaticServer: http.Server | null = null;\n const uiPort = process.env.BOS_UI_PORT;\n const uiConfig = ensureGeneratedUiRsbuildConfig(cwd);\n if (uiConfig && noWatch && uiPort) {\n // Folder-form ui: one-shot build, then serve the ui source root's dist\n // (the factory's absolute distPath target) statically on the ui port.\n await runOnce(\"rsbuild\", [\"build\", \"--config\", uiConfig]);\n const uiDistDir = uiDistDirFor(cwd);\n if (!fs.existsSync(path.join(uiDistDir, DEV_ENTRY_FILENAME))) {\n throw new Error(\n `❌ UI dist is missing at ${uiDistDir} after the rsbuild one-shot — build output layout mismatch?`,\n );\n }\n const serveUiStatic = sirv(uiDistDir, { dev: true });\n uiStaticServer = http.createServer((req, res) => {\n applyCorsHeaders(res);\n serveUiStatic(req, res, () => {\n sendText(res, 404, \"Not Found\");\n });\n });\n await new Promise<void>((resolve, reject) => {\n uiStaticServer!.once(\"error\", reject);\n uiStaticServer!.listen(Number(uiPort), () => resolve());\n });\n console.log(`├─ 🎨 UI: http://localhost:${uiPort} (built, no watch)`);\n } else if (uiConfig) {\n uiWatcher = spawn(\"rsbuild\", [\"dev\", \"--config\", uiConfig], {\n cwd,\n stdio: \"inherit\",\n env: uiPort ? { ...process.env, PORT: uiPort } : process.env,\n });\n uiWatcher.on(\"error\", (error) => {\n console.error(`❌ Failed to spawn rsbuild ui dev: ${error.message}`);\n });\n console.log(`├─ 🎨 UI: ${uiPort ? `http://localhost:${uiPort}` : \"(rsbuild auto port)\"}`);\n }\n\n const handlers: { rpc: any; api: any } = { rpc: null, api: null };\n const effectContextHolder: { context: unknown } = { context: null };\n let runtime: { shutdown: () => Promise<void> } | null = null;\n const host = await startDirectModuleHost({\n name: pluginInfo.normalizedName,\n version: pluginInfo.version,\n handlers,\n effectContext: () => effectContextHolder.context,\n port,\n staticHandler: serveStatic,\n });\n\n console.log(`🚀 ${pluginInfo.name} dev server listening on port ${host.port}`);\n console.log(`├─ 📡 RPC: http://localhost:${host.port}/api/rpc${rpcPrefix}`);\n console.log(`├─ 📖 Docs: http://localhost:${host.port}/api`);\n console.log(`└─ 💚 Health: http://localhost:${host.port}/`);\n\n const load = async () => {\n try {\n // Import framework internals directly. A package self-import can resolve\n // the published entry while this source-first dev server is running,\n // which leaves the runtime exports unavailable on Windows.\n const { createPluginRuntime } = await import(\"../runtime\");\n const { RPCHandler } = await import(\"@orpc/server/fetch\");\n const { OpenAPIHandler } = await import(\"@orpc/openapi/fetch\");\n const { OpenAPIGenerator } = await import(\"@orpc/openapi\");\n const { OpenAPIReferenceHandlerPlugin } = await import(\"@orpc/openapi/plugins\");\n const { ZodToJsonSchemaConverter } = await import(\"@orpc/zod\");\n const { onError } = await import(\"@orpc/server\");\n const { formatORPCError } = await import(\"../errors\");\n\n const runtimeConfig = readRuntimeConfigFromEnv();\n const { siblings, dependsOn } = collectSiblingRemotes(runtimeConfig, compositionKey);\n\n if (dependsOn.length > 0) {\n console.log(`🔗 Loading sibling plugin(s): ${dependsOn.join(\", \")}`);\n }\n\n const registry: Record<string, { remote: string }> = {\n [pluginId]: {\n remote: `http://localhost:${host.port}/${DEV_ENTRY_FILENAME}`,\n },\n ...siblings,\n };\n\n const mfRuntime = createPluginRuntime({ registry });\n runtime = mfRuntime;\n\n const pluginsMap: Record<string, unknown> = {};\n const siblingEffectContexts: unknown[] = [];\n for (const depId of Object.keys(siblings)) {\n const dep = await loadPluginWithRetry(mfRuntime, depId, siblings[depId]!.remote);\n pluginsMap[depId] = { client: dep.createClient, router: dep.router };\n if (dep.initialized?.effectContext) {\n siblingEffectContexts.push(dep.initialized.effectContext);\n }\n console.log(`✅ Loaded dependency plugin: ${depId}`);\n }\n\n const loaded: any = await loadPluginWithRetry(\n mfRuntime,\n pluginId,\n registry[pluginId]!.remote,\n (devConfig?.config ?? { variables: {}, secrets: {} }) as Record<string, unknown>,\n Object.keys(pluginsMap).length > 0 ? pluginsMap : undefined,\n );\n\n const { Context } = await import(\"effect\");\n effectContextHolder.context = [loaded.initialized?.effectContext, ...siblingEffectContexts]\n .filter(Boolean)\n .reduce((acc: any, ctx: any) => Context.merge(acc, ctx), Context.empty());\n\n handlers.rpc = new RPCHandler(loaded.router, {\n errorStatusMap: PLUGIN_ERROR_STATUS_MAP,\n interceptors: [\n onError((error: any) => {\n const formatted = formatORPCError(error);\n if (formatted) console.error(formatted);\n }),\n ],\n });\n\n const generator = new OpenAPIGenerator({ converters: [new ZodToJsonSchemaConverter()] });\n\n handlers.api = new OpenAPIHandler(loaded.router, {\n errorStatusMap: PLUGIN_ERROR_STATUS_MAP,\n plugins: [\n new OpenAPIReferenceHandlerPlugin({\n spec: () => generator.generate(loaded.router, { version: \"3.1.1\" }),\n }),\n ],\n interceptors: [\n onError((error: any) => {\n const formatted = formatORPCError(error);\n if (formatted) console.error(formatted);\n }),\n ],\n });\n\n console.log(`✅ Plugin ready: ${pluginId}`);\n } catch (error) {\n console.error(`❌ Failed to load plugin ${pluginId}:`, error);\n console.error(\" Server stays up; fix the build and retry via rebuild.\");\n }\n };\n\n void load();\n\n const close = async () => {\n handlers.rpc = null;\n handlers.api = null;\n effectContextHolder.context = null;\n for (const child of [watcher, uiWatcher]) {\n if (child) {\n await killChildEscalating(child);\n }\n }\n if (uiStaticServer) {\n await new Promise<void>((resolve) => uiStaticServer.close(() => resolve()));\n }\n await host.close();\n if (runtime) await runtime.shutdown().catch(() => {});\n };\n\n process.once(\"SIGINT\", async () => {\n const timeout = setTimeout(() => process.exit(0), 3000);\n await close();\n clearTimeout(timeout);\n process.exit(0);\n });\n process.once(\"SIGTERM\", async () => {\n const timeout = setTimeout(() => process.exit(0), 3000);\n await close();\n clearTimeout(timeout);\n process.exit(0);\n });\n\n watchParentDeath(async () => {\n const timeout = setTimeout(() => process.exit(0), 3000);\n await close();\n clearTimeout(timeout);\n process.exit(0);\n });\n\n return { port, close };\n}\n\nconst invokedAsCli = import.meta.main || (process.argv[1] ?? \"\").includes(\"every-plugin-serve\");\n\nif (invokedAsCli) {\n startPluginDevServer().catch((error) => {\n console.error(\"❌ Plugin dev server fatal error:\", error);\n process.exit(1);\n });\n}\n"],"mappings":";;;;;;;;;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K,CAAC;AAChB,CAAC"}
|
package/dist/dev/serve.d.cts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"serve.d.cts","names":[],"sources":["../../src/dev/serve.ts"],"mappings":";
|
|
1
|
+
{"version":3,"file":"serve.d.cts","names":[],"sources":["../../src/dev/serve.ts"],"mappings":";UA8FiB;EACf;EACA;EACA;;UAGe;EACf;EACA,aAAa;;;;;;;;;;cAWF,qBAAkB;iBAET,qBACpB,UAAS,wBACR,QAAQ"}
|
package/dist/dev/serve.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"serve.d.mts","names":[],"sources":["../../src/dev/serve.ts"],"mappings":";
|
|
1
|
+
{"version":3,"file":"serve.d.mts","names":[],"sources":["../../src/dev/serve.ts"],"mappings":";UA8FiB;EACf;EACA;EACA;;UAGe;EACf;EACA,aAAa;;;;;;;;;;cAWF,qBAAkB;iBAET,qBACpB,UAAS,wBACR,QAAQ"}
|
package/dist/dev/serve.mjs
CHANGED
|
@@ -3,7 +3,8 @@ import { PLUGIN_ERROR_STATUS_MAP } from "../errors.mjs";
|
|
|
3
3
|
import { DEV_ENTRY_FILENAME } from "../build/artifact-names.mjs";
|
|
4
4
|
import { loadRemoteWithRetry } from "../remote-entry.mjs";
|
|
5
5
|
import { getPluginInfo, loadDevConfig } from "../build/rspack/utils.mjs";
|
|
6
|
-
import { ensureGeneratedUiRsbuildConfig, pluginLayoutKey } from "../build/ui/generated-config.mjs";
|
|
6
|
+
import { ensureGeneratedUiRsbuildConfig, pluginLayoutKey, uiDistDirFor } from "../build/ui/generated-config.mjs";
|
|
7
|
+
import { startDirectModuleHost } from "./host.mjs";
|
|
7
8
|
import { ensureGeneratedRspackConfig } from "../build/rspack/generated-config.mjs";
|
|
8
9
|
import { killChildEscalating, watchParentDeath } from "./watch-kill.mjs";
|
|
9
10
|
import { Effect } from "effect";
|
|
@@ -65,11 +66,6 @@ const loadPluginWithRetry = (runtime, pluginId, remoteUrl, options = {
|
|
|
65
66
|
load: () => runtime.usePlugin(pluginId, options, pluginsMap),
|
|
66
67
|
timeoutMs
|
|
67
68
|
}));
|
|
68
|
-
const sendJson = (res, status, body) => {
|
|
69
|
-
res.statusCode = status;
|
|
70
|
-
res.setHeader("content-type", "application/json; charset=utf-8");
|
|
71
|
-
res.end(JSON.stringify(body));
|
|
72
|
-
};
|
|
73
69
|
const sendText = (res, status, text) => {
|
|
74
70
|
res.statusCode = status;
|
|
75
71
|
res.setHeader("content-type", "text/plain; charset=utf-8");
|
|
@@ -93,7 +89,6 @@ async function startPluginDevServer(options = {}) {
|
|
|
93
89
|
const compositionKey = pluginLayoutKey(cwd) ?? pluginId;
|
|
94
90
|
const port = options.port ?? (Number(process.env.PORT) || devConfig?.port || 3999);
|
|
95
91
|
const rpcPrefix = normalizePrefix(devConfig?.prefix);
|
|
96
|
-
const rpcBase = `/api/rpc${rpcPrefix}`;
|
|
97
92
|
const distDir = path.join(cwd, "dist");
|
|
98
93
|
const serveStatic = sirv(distDir, { dev: true });
|
|
99
94
|
const noWatch = options.watch === false || process.env.BOS_NO_WATCH === "1";
|
|
@@ -143,8 +138,8 @@ async function startPluginDevServer(options = {}) {
|
|
|
143
138
|
"--config",
|
|
144
139
|
uiConfig
|
|
145
140
|
]);
|
|
146
|
-
const uiDistDir =
|
|
147
|
-
if (!fs.existsSync(path.join(uiDistDir, "remoteEntry.js")))
|
|
141
|
+
const uiDistDir = uiDistDirFor(cwd);
|
|
142
|
+
if (!fs.existsSync(path.join(uiDistDir, "remoteEntry.js"))) throw new Error(`❌ UI dist is missing at ${uiDistDir} after the rsbuild one-shot — build output layout mismatch?`);
|
|
148
143
|
const serveUiStatic = sirv(uiDistDir, { dev: true });
|
|
149
144
|
uiStaticServer = http.createServer((req, res) => {
|
|
150
145
|
applyCorsHeaders(res);
|
|
@@ -181,108 +176,18 @@ async function startPluginDevServer(options = {}) {
|
|
|
181
176
|
};
|
|
182
177
|
const effectContextHolder = { context: null };
|
|
183
178
|
let runtime = null;
|
|
184
|
-
const
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
getRawBody: async () => {
|
|
192
|
-
if (cachedRawBody !== null) return cachedRawBody;
|
|
193
|
-
if (!rawClone) {
|
|
194
|
-
cachedRawBody = "";
|
|
195
|
-
return cachedRawBody;
|
|
196
|
-
}
|
|
197
|
-
cachedRawBody = await rawClone.text();
|
|
198
|
-
return cachedRawBody;
|
|
199
|
-
}
|
|
200
|
-
};
|
|
201
|
-
};
|
|
202
|
-
const toWebRequest = (req) => {
|
|
203
|
-
const url = `http://localhost:${port}${req.url}`;
|
|
204
|
-
return new Request(url, {
|
|
205
|
-
method: req.method,
|
|
206
|
-
headers: req.headers,
|
|
207
|
-
body: req.method !== "GET" && req.method !== "HEAD" ? req : void 0,
|
|
208
|
-
duplex: req.method !== "GET" && req.method !== "HEAD" ? "half" : void 0
|
|
209
|
-
});
|
|
210
|
-
};
|
|
211
|
-
const handleOrpc = async (req, res, handler, prefix, errorLabel) => {
|
|
212
|
-
try {
|
|
213
|
-
const webRequest = toWebRequest(req);
|
|
214
|
-
const result = await handler.handle(webRequest, {
|
|
215
|
-
prefix,
|
|
216
|
-
context: buildDevContext(req, webRequest)
|
|
217
|
-
});
|
|
218
|
-
if (result.response) {
|
|
219
|
-
res.statusCode = result.response.status;
|
|
220
|
-
result.response.headers.forEach((value, key) => {
|
|
221
|
-
res.setHeader(key, value);
|
|
222
|
-
});
|
|
223
|
-
const text = await result.response.text();
|
|
224
|
-
if (!res.getHeader("content-length")) res.setHeader("content-length", Buffer.byteLength(text).toString());
|
|
225
|
-
res.end(text);
|
|
226
|
-
} else sendText(res, 404, "Not Found");
|
|
227
|
-
} catch (error) {
|
|
228
|
-
console.error(`${errorLabel} error:`, error);
|
|
229
|
-
sendJson(res, 500, { error: error.message });
|
|
230
|
-
}
|
|
231
|
-
};
|
|
232
|
-
const server = http.createServer((req, res) => {
|
|
233
|
-
applyCorsHeaders(res);
|
|
234
|
-
const pathname = pathnameOf(req);
|
|
235
|
-
if (req.method === "OPTIONS") {
|
|
236
|
-
res.statusCode = 200;
|
|
237
|
-
res.end();
|
|
238
|
-
return;
|
|
239
|
-
}
|
|
240
|
-
if (pathname === "/" && (req.method === "GET" || req.method === "HEAD")) {
|
|
241
|
-
sendJson(res, 200, {
|
|
242
|
-
ok: true,
|
|
243
|
-
plugin: pluginInfo.normalizedName,
|
|
244
|
-
version: pluginInfo.version,
|
|
245
|
-
status: handlers.rpc ? "ready" : "loading",
|
|
246
|
-
endpoints: {
|
|
247
|
-
health: "/",
|
|
248
|
-
docs: "/api",
|
|
249
|
-
rpc: rpcBase
|
|
250
|
-
}
|
|
251
|
-
});
|
|
252
|
-
return;
|
|
253
|
-
}
|
|
254
|
-
if (pathname === "/health" && (req.method === "GET" || req.method === "HEAD")) {
|
|
255
|
-
sendText(res, 200, "OK");
|
|
256
|
-
return;
|
|
257
|
-
}
|
|
258
|
-
if (pathname.startsWith(`${rpcBase}/`)) {
|
|
259
|
-
if (!handlers.rpc) {
|
|
260
|
-
sendJson(res, 503, { error: "Plugin still loading..." });
|
|
261
|
-
return;
|
|
262
|
-
}
|
|
263
|
-
handleOrpc(req, res, handlers.rpc, rpcBase, "RPC").catch(() => {});
|
|
264
|
-
return;
|
|
265
|
-
}
|
|
266
|
-
if (pathname === "/api" || pathname.startsWith("/api/")) {
|
|
267
|
-
if (!handlers.api) {
|
|
268
|
-
sendJson(res, 503, { error: "Plugin still loading..." });
|
|
269
|
-
return;
|
|
270
|
-
}
|
|
271
|
-
handleOrpc(req, res, handlers.api, "/api", "OpenAPI").catch(() => {});
|
|
272
|
-
return;
|
|
273
|
-
}
|
|
274
|
-
serveStatic(req, res, () => {
|
|
275
|
-
sendText(res, 404, "Not Found");
|
|
276
|
-
});
|
|
277
|
-
});
|
|
278
|
-
await new Promise((resolve, reject) => {
|
|
279
|
-
server.once("error", reject);
|
|
280
|
-
server.listen(port, () => resolve());
|
|
179
|
+
const host = await startDirectModuleHost({
|
|
180
|
+
name: pluginInfo.normalizedName,
|
|
181
|
+
version: pluginInfo.version,
|
|
182
|
+
handlers,
|
|
183
|
+
effectContext: () => effectContextHolder.context,
|
|
184
|
+
port,
|
|
185
|
+
staticHandler: serveStatic
|
|
281
186
|
});
|
|
282
|
-
console.log(`🚀 ${pluginInfo.name} dev server listening on port ${port}`);
|
|
283
|
-
console.log(`├─ 📡 RPC: http://localhost:${port}/api/rpc${rpcPrefix}`);
|
|
284
|
-
console.log(`├─ 📖 Docs: http://localhost:${port}/api`);
|
|
285
|
-
console.log(`└─ 💚 Health: http://localhost:${port}/`);
|
|
187
|
+
console.log(`🚀 ${pluginInfo.name} dev server listening on port ${host.port}`);
|
|
188
|
+
console.log(`├─ 📡 RPC: http://localhost:${host.port}/api/rpc${rpcPrefix}`);
|
|
189
|
+
console.log(`├─ 📖 Docs: http://localhost:${host.port}/api`);
|
|
190
|
+
console.log(`└─ 💚 Health: http://localhost:${host.port}/`);
|
|
286
191
|
const load = async () => {
|
|
287
192
|
try {
|
|
288
193
|
const { createPluginRuntime } = await import("../runtime/index.mjs");
|
|
@@ -297,7 +202,7 @@ async function startPluginDevServer(options = {}) {
|
|
|
297
202
|
const { siblings, dependsOn } = collectSiblingRemotes(runtimeConfig, compositionKey);
|
|
298
203
|
if (dependsOn.length > 0) console.log(`🔗 Loading sibling plugin(s): ${dependsOn.join(", ")}`);
|
|
299
204
|
const registry = {
|
|
300
|
-
[pluginId]: { remote: `http://localhost:${port}/${DEV_ENTRY_FILENAME}` },
|
|
205
|
+
[pluginId]: { remote: `http://localhost:${host.port}/${DEV_ENTRY_FILENAME}` },
|
|
301
206
|
...siblings
|
|
302
207
|
};
|
|
303
208
|
const mfRuntime = createPluginRuntime({ registry });
|
|
@@ -348,8 +253,8 @@ async function startPluginDevServer(options = {}) {
|
|
|
348
253
|
effectContextHolder.context = null;
|
|
349
254
|
for (const child of [watcher, uiWatcher]) if (child) await killChildEscalating(child);
|
|
350
255
|
if (uiStaticServer) await new Promise((resolve) => uiStaticServer.close(() => resolve()));
|
|
256
|
+
await host.close();
|
|
351
257
|
if (runtime) await runtime.shutdown().catch(() => {});
|
|
352
|
-
await new Promise((resolve) => server.close(() => resolve()));
|
|
353
258
|
};
|
|
354
259
|
process.once("SIGINT", async () => {
|
|
355
260
|
const timeout = setTimeout(() => process.exit(0), 3e3);
|