@module-federation/dts-plugin 0.0.0-chore-bump-node-22-20260710161714

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.
@@ -0,0 +1,113 @@
1
+ import { _ as retrieveMfTypesPath, b as ModuleFederationDevServer, g as retrieveTypesZipPath, h as retrieveHostConfig, i as retrieveRemoteConfig, n as RpcGMCallTypes, o as getDTSManagerConstructor, t as exposeRpc, y as createHttpServer } from "./expose-rpc-CDdqA9PX.mjs";
2
+ import { o as UpdateMode, r as DEFAULT_TAR_NAME } from "./Action-DNNg2YDh.mjs";
3
+ import { n as UpdateKind, o as getIPV4, s as fileLog } from "./Broker-Cmbh_XVO.mjs";
4
+ import "./consumeTypes-3S4eCiRK.mjs";
5
+ import "./core.mjs";
6
+ import { t as getIpFromEntry } from "./utils-CkPvDGOy.mjs";
7
+ import { decodeName } from "@module-federation/sdk";
8
+
9
+ //#region src/dev-worker/handleWorkerMessage.ts
10
+ function handleDevWorkerMessage(message, options = {}) {
11
+ const { moduleServer, processExit = process.exit, pid = process.pid, log = () => void 0 } = options;
12
+ log(`ChildProcess(${pid}), message: ${JSON.stringify(message)} `, "forkDevWorker", "info");
13
+ if (message.type === RpcGMCallTypes.EXIT) {
14
+ log(`ChildProcess(${pid}) SIGTERM, Federation DevServer will exit...`, "forkDevWorker", "error");
15
+ moduleServer?.exit();
16
+ processExit(0);
17
+ }
18
+ }
19
+
20
+ //#endregion
21
+ //#region src/dev-worker/forkDevWorker.ts
22
+ let typesManager, serverAddress, moduleServer, cacheOptions;
23
+ function getLocalRemoteNames(options, encodeNameIdentifier) {
24
+ if (!options) return [];
25
+ let hostConfig;
26
+ try {
27
+ hostConfig = retrieveHostConfig(options);
28
+ } catch (e) {
29
+ fileLog(`getLocalRemoteNames: retrieveHostConfig failed: ${e.message}`, "forkDevWorker", "warn");
30
+ return [];
31
+ }
32
+ const { mapRemotesToDownload } = hostConfig;
33
+ return Object.keys(mapRemotesToDownload).reduce((sum, remoteModuleName) => {
34
+ const remoteInfo = mapRemotesToDownload[remoteModuleName];
35
+ const name = encodeNameIdentifier ? decodeName(remoteInfo.name, encodeNameIdentifier) : remoteInfo.name;
36
+ const ip = getIpFromEntry(remoteInfo.url, getIPV4());
37
+ if (!ip) return sum;
38
+ sum.push({
39
+ name,
40
+ entry: remoteInfo.url,
41
+ ip
42
+ });
43
+ return sum;
44
+ }, []);
45
+ }
46
+ async function updateCallback({ updateMode, name, remoteTypeTarPath, remoteInfo, once }) {
47
+ const { disableHotTypesReload, disableLiveReload } = cacheOptions || {};
48
+ fileLog(`sync remote module ${name}, types to ${cacheOptions?.name},typesManager.updateTypes run`, "forkDevWorker", "info");
49
+ if (!disableLiveReload && moduleServer) moduleServer.update({
50
+ updateKind: UpdateKind.RELOAD_PAGE,
51
+ updateMode: UpdateMode.PASSIVE
52
+ });
53
+ if (!disableHotTypesReload && typesManager) await typesManager.updateTypes({
54
+ updateMode,
55
+ remoteName: name,
56
+ remoteTarPath: remoteTypeTarPath,
57
+ remoteInfo,
58
+ once
59
+ });
60
+ }
61
+ async function forkDevWorker(options, action) {
62
+ if (!typesManager) {
63
+ const { name, remote, host, extraOptions } = options;
64
+ typesManager = new (getDTSManagerConstructor(remote?.implementation))({
65
+ remote,
66
+ host,
67
+ extraOptions
68
+ });
69
+ if (!options.disableHotTypesReload && remote) {
70
+ const { remoteOptions, tsConfig } = retrieveRemoteConfig(remote);
71
+ const mfTypesZipPath = retrieveTypesZipPath(retrieveMfTypesPath(tsConfig, remoteOptions), remoteOptions);
72
+ await Promise.all([createHttpServer({ typeTarPath: mfTypesZipPath }).then((res) => {
73
+ serverAddress = res.serverAddress;
74
+ }), typesManager.generateTypes()]).catch((err) => {
75
+ fileLog(`${name} module generateTypes done, localServerAddress: ${JSON.stringify(err)}`, "forkDevWorker", "error");
76
+ });
77
+ fileLog(`${name} module generateTypes done, localServerAddress: ${serverAddress}`, "forkDevWorker", "info");
78
+ }
79
+ moduleServer = new ModuleFederationDevServer({
80
+ name,
81
+ remotes: getLocalRemoteNames(host, extraOptions?.["encodeNameIdentifier"]),
82
+ updateCallback,
83
+ remoteTypeTarPath: `${serverAddress}/${DEFAULT_TAR_NAME}`
84
+ });
85
+ cacheOptions = options;
86
+ }
87
+ if (action === "update" && cacheOptions) {
88
+ fileLog(`remoteModule ${cacheOptions.name} receive devWorker update, start typesManager.updateTypes `, "forkDevWorker", "info");
89
+ if (!cacheOptions.disableLiveReload) moduleServer?.update({
90
+ updateKind: UpdateKind.RELOAD_PAGE,
91
+ updateMode: UpdateMode.POSITIVE
92
+ });
93
+ if (!cacheOptions.disableHotTypesReload) typesManager?.updateTypes({
94
+ updateMode: UpdateMode.POSITIVE,
95
+ remoteName: cacheOptions.name
96
+ }).then(() => {
97
+ moduleServer?.update({
98
+ updateKind: UpdateKind.UPDATE_TYPE,
99
+ updateMode: UpdateMode.POSITIVE
100
+ });
101
+ });
102
+ }
103
+ }
104
+ process.on("message", (message) => {
105
+ handleDevWorkerMessage(message, {
106
+ moduleServer,
107
+ log: fileLog
108
+ });
109
+ });
110
+ exposeRpc(forkDevWorker);
111
+
112
+ //#endregion
113
+ export { forkDevWorker };
@@ -0,0 +1,14 @@
1
+ import { n as RpcGMCallTypes, r as generateTypes, t as exposeRpc } from "./expose-rpc-CDdqA9PX.mjs";
2
+ import "./Broker-Cmbh_XVO.mjs";
3
+
4
+ //#region src/core/lib/forkGenerateDts.ts
5
+ async function forkGenerateDts(options) {
6
+ return generateTypes(options);
7
+ }
8
+ process.on("message", (message) => {
9
+ if (message.type === RpcGMCallTypes.EXIT) process.exit(0);
10
+ });
11
+ exposeRpc(forkGenerateDts);
12
+
13
+ //#endregion
14
+ export { forkGenerateDts };
@@ -0,0 +1,509 @@
1
+ import { a as cloneDeepOptions, c as isTSProject, l as retrieveTypesAssetsInfo, n as RpcGMCallTypes, r as generateTypes, u as validateOptions } from "./expose-rpc-CDdqA9PX.mjs";
2
+ import { s as WEB_CLIENT_OPTIONS_IDENTIFIER } from "./Action-DNNg2YDh.mjs";
3
+ import { c as logger$1, o as getIPV4 } from "./Broker-Cmbh_XVO.mjs";
4
+ import { a as createRpcWorker, n as generateTypesInChildProcess, t as consumeTypes } from "./consumeTypes-3S4eCiRK.mjs";
5
+ import "./core.mjs";
6
+ import fs from "fs";
7
+ import { fileURLToPath } from "url";
8
+ import * as path$1 from "path";
9
+ import path from "path";
10
+ import { rm } from "fs/promises";
11
+ import { TEMP_DIR, infrastructureLogger, logger, normalizeOptions } from "@module-federation/sdk";
12
+
13
+ //#region src/dev-worker/DevWorker.ts
14
+ const __filename$1 = fileURLToPath(import.meta.url);
15
+ const __dirname$1 = path.dirname(__filename$1);
16
+ var DevWorker = class {
17
+ constructor(options) {
18
+ this._options = cloneDeepOptions(options);
19
+ this.removeUnSerializationOptions();
20
+ this._rpcWorker = createRpcWorker(path.resolve(__dirname$1, "./fork-dev-worker.js"), {}, void 0, false);
21
+ this._res = this._rpcWorker.connect(this._options);
22
+ }
23
+ removeUnSerializationOptions() {
24
+ delete this._options.host?.moduleFederationConfig?.manifest;
25
+ delete this._options.remote?.moduleFederationConfig?.manifest;
26
+ }
27
+ get controlledPromise() {
28
+ return this._res;
29
+ }
30
+ update() {
31
+ this._rpcWorker.process?.send?.({
32
+ type: RpcGMCallTypes.CALL,
33
+ id: this._rpcWorker.id,
34
+ args: [void 0, "update"]
35
+ });
36
+ }
37
+ exit() {
38
+ this._rpcWorker?.terminate();
39
+ }
40
+ };
41
+
42
+ //#endregion
43
+ //#region src/dev-worker/createDevWorker.ts
44
+ async function removeLogFile() {
45
+ try {
46
+ await rm(path$1.resolve(process.cwd(), ".mf/typesGenerate.log"), {
47
+ force: true,
48
+ recursive: true
49
+ });
50
+ } catch (err) {
51
+ console.error("removeLogFile error", "forkDevWorker", err);
52
+ }
53
+ }
54
+ function createDevWorker(options) {
55
+ removeLogFile();
56
+ return new DevWorker({ ...options });
57
+ }
58
+
59
+ //#endregion
60
+ //#region src/plugins/utils.ts
61
+ function isDev() {
62
+ return process.env["NODE_ENV"] === "development";
63
+ }
64
+ function isPrd() {
65
+ return process.env["NODE_ENV"] === "production";
66
+ }
67
+ function getCompilerOutputDir(compiler) {
68
+ try {
69
+ return path.relative(compiler.context, compiler.outputPath || compiler.options.output.path);
70
+ } catch (err) {
71
+ return "";
72
+ }
73
+ }
74
+
75
+ //#endregion
76
+ //#region src/plugins/DevPlugin.ts
77
+ const __filename = fileURLToPath(import.meta.url);
78
+ const __dirname = path.dirname(__filename);
79
+ var PROCESS_EXIT_CODE = /* @__PURE__ */ function(PROCESS_EXIT_CODE) {
80
+ PROCESS_EXIT_CODE[PROCESS_EXIT_CODE["SUCCESS"] = 0] = "SUCCESS";
81
+ PROCESS_EXIT_CODE[PROCESS_EXIT_CODE["FAILURE"] = 1] = "FAILURE";
82
+ return PROCESS_EXIT_CODE;
83
+ }(PROCESS_EXIT_CODE || {});
84
+ function ensureTempDir(filePath) {
85
+ try {
86
+ const dir = path.dirname(filePath);
87
+ fs.mkdirSync(dir, { recursive: true });
88
+ } catch (_err) {}
89
+ }
90
+ var DevPlugin = class DevPlugin {
91
+ constructor(options, dtsOptions, generateTypesPromise, fetchRemoteTypeUrlsPromise) {
92
+ this.name = "MFDevPlugin";
93
+ this._options = options;
94
+ this.generateTypesPromise = generateTypesPromise;
95
+ this.dtsOptions = dtsOptions;
96
+ this.fetchRemoteTypeUrlsPromise = fetchRemoteTypeUrlsPromise;
97
+ }
98
+ static ensureLiveReloadEntry(options, filePath) {
99
+ ensureTempDir(filePath);
100
+ const liveReloadEntryWithOptions = fs.readFileSync(path.join(__dirname, "./iife/launch-web-client.iife.js")).toString("utf-8").replace(WEB_CLIENT_OPTIONS_IDENTIFIER, JSON.stringify(options));
101
+ fs.writeFileSync(filePath, liveReloadEntryWithOptions);
102
+ }
103
+ _stopWhenSIGTERMOrSIGINT() {
104
+ process.on("SIGTERM", () => {
105
+ logger$1.info(`${this._options.name} Process(${process.pid}) SIGTERM, mf server will exit...`);
106
+ this._exit(PROCESS_EXIT_CODE.SUCCESS);
107
+ });
108
+ process.on("SIGINT", () => {
109
+ logger$1.info(`${this._options.name} Process(${process.pid}) SIGINT, mf server will exit...`);
110
+ this._exit(PROCESS_EXIT_CODE.SUCCESS);
111
+ });
112
+ }
113
+ _handleUnexpectedExit() {
114
+ process.on("unhandledRejection", (error) => {
115
+ logger$1.error(error);
116
+ logger$1.error(`Process(${process.pid}) unhandledRejection, mf server will exit...`);
117
+ this._exit(PROCESS_EXIT_CODE.FAILURE);
118
+ });
119
+ process.on("uncaughtException", (error) => {
120
+ logger$1.error(error);
121
+ logger$1.error(`Process(${process.pid}) uncaughtException, mf server will exit...`);
122
+ this._exit(PROCESS_EXIT_CODE.FAILURE);
123
+ });
124
+ }
125
+ _exit(exitCode = 0) {
126
+ this._devWorker?.exit();
127
+ process.exit(exitCode);
128
+ }
129
+ _afterEmit() {
130
+ this._devWorker?.update();
131
+ }
132
+ apply(compiler) {
133
+ const { _options: { name, dev, dts } } = this;
134
+ const normalizedDev = normalizeOptions(true, {
135
+ disableLiveReload: true,
136
+ disableHotTypesReload: false,
137
+ disableDynamicRemoteTypeHints: false
138
+ }, "mfOptions.dev")(dev);
139
+ if (!isDev() || normalizedDev === false) return;
140
+ new compiler.webpack.DefinePlugin({ FEDERATION_IPV4: JSON.stringify(getIPV4()) }).apply(compiler);
141
+ if (normalizedDev.disableHotTypesReload && normalizedDev.disableLiveReload && normalizedDev.disableDynamicRemoteTypeHints) return;
142
+ if (!name) throw new Error("name is required if you want to enable dev server!");
143
+ if (!normalizedDev.disableDynamicRemoteTypeHints) {
144
+ if (!this._options.runtimePlugins) this._options.runtimePlugins = [];
145
+ this._options.runtimePlugins.push(path.resolve(__dirname, "dynamic-remote-type-hints-plugin.js"));
146
+ }
147
+ if (!normalizedDev.disableLiveReload) {
148
+ const TEMP_DIR$1 = path.join(`${process.cwd()}/node_modules`, TEMP_DIR);
149
+ const filepath = path.join(TEMP_DIR$1, `live-reload.js`);
150
+ if (typeof compiler.options.entry === "object") {
151
+ DevPlugin.ensureLiveReloadEntry({ name }, filepath);
152
+ Object.keys(compiler.options.entry).forEach((entry) => {
153
+ const normalizedEntry = compiler.options.entry[entry];
154
+ if (typeof normalizedEntry === "object" && Array.isArray(normalizedEntry.import)) normalizedEntry.import.unshift(filepath);
155
+ });
156
+ }
157
+ }
158
+ const defaultGenerateTypes = { compileInChildProcess: true };
159
+ const defaultConsumeTypes = { consumeAPITypes: true };
160
+ const normalizedDtsOptions = normalizeOptions(isTSProject(dts, compiler.context), {
161
+ generateTypes: defaultGenerateTypes,
162
+ consumeTypes: defaultConsumeTypes,
163
+ extraOptions: {},
164
+ displayErrorInTerminal: this.dtsOptions?.displayErrorInTerminal
165
+ }, "mfOptions.dts")(dts);
166
+ const normalizedGenerateTypes = normalizeOptions(Boolean(normalizedDtsOptions), defaultGenerateTypes, "mfOptions.dts.generateTypes")(normalizedDtsOptions === false ? void 0 : normalizedDtsOptions.generateTypes);
167
+ const remote = normalizedGenerateTypes === false ? void 0 : {
168
+ implementation: normalizedDtsOptions === false ? void 0 : normalizedDtsOptions.implementation,
169
+ context: compiler.context,
170
+ outputDir: getCompilerOutputDir(compiler),
171
+ moduleFederationConfig: { ...this._options },
172
+ hostRemoteTypesFolder: normalizedGenerateTypes.typesFolder || "@mf-types",
173
+ ...normalizedGenerateTypes,
174
+ typesFolder: `.dev-server`
175
+ };
176
+ const normalizedConsumeTypes = normalizeOptions(Boolean(normalizedDtsOptions), defaultConsumeTypes, "mfOptions.dts.consumeTypes")(normalizedDtsOptions === false ? void 0 : normalizedDtsOptions.consumeTypes);
177
+ const host = normalizedConsumeTypes === false ? void 0 : {
178
+ implementation: normalizedDtsOptions === false ? void 0 : normalizedDtsOptions.implementation,
179
+ context: compiler.context,
180
+ moduleFederationConfig: this._options,
181
+ typesFolder: normalizedConsumeTypes.typesFolder || "@mf-types",
182
+ abortOnError: false,
183
+ ...normalizedConsumeTypes
184
+ };
185
+ const extraOptions = normalizedDtsOptions ? normalizedDtsOptions.extraOptions || {} : {};
186
+ if (!remote && !host && normalizedDev.disableLiveReload) return;
187
+ if (remote && !remote?.tsConfigPath && typeof normalizedDtsOptions === "object" && normalizedDtsOptions.tsConfigPath) remote.tsConfigPath = normalizedDtsOptions.tsConfigPath;
188
+ Promise.all([this.generateTypesPromise, this.fetchRemoteTypeUrlsPromise]).then(([_, remoteTypeUrls]) => {
189
+ this._devWorker = createDevWorker({
190
+ name,
191
+ remote,
192
+ host: {
193
+ moduleFederationConfig: {},
194
+ ...host,
195
+ remoteTypeUrls
196
+ },
197
+ extraOptions,
198
+ disableLiveReload: normalizedDev.disableHotTypesReload,
199
+ disableHotTypesReload: normalizedDev.disableHotTypesReload
200
+ });
201
+ });
202
+ this._stopWhenSIGTERMOrSIGINT();
203
+ this._handleUnexpectedExit();
204
+ compiler.hooks.afterEmit.tap(this.name, this._afterEmit.bind(this));
205
+ }
206
+ };
207
+
208
+ //#endregion
209
+ //#region src/plugins/ConsumeTypesPlugin.ts
210
+ const DEFAULT_CONSUME_TYPES = {
211
+ abortOnError: false,
212
+ consumeAPITypes: true,
213
+ typesOnBuild: false
214
+ };
215
+ const normalizeConsumeTypesOptions = ({ context, dtsOptions, pluginOptions }) => {
216
+ const normalizedConsumeTypes = normalizeOptions(true, DEFAULT_CONSUME_TYPES, "mfOptions.dts.consumeTypes")(dtsOptions.consumeTypes);
217
+ if (!normalizedConsumeTypes) return;
218
+ const dtsManagerOptions = {
219
+ host: {
220
+ implementation: dtsOptions.implementation,
221
+ context,
222
+ moduleFederationConfig: pluginOptions,
223
+ ...normalizedConsumeTypes
224
+ },
225
+ extraOptions: dtsOptions.extraOptions || {},
226
+ displayErrorInTerminal: dtsOptions.displayErrorInTerminal
227
+ };
228
+ validateOptions(dtsManagerOptions.host);
229
+ return dtsManagerOptions;
230
+ };
231
+ const consumeTypesAPI = async (dtsManagerOptions, cb) => {
232
+ return (typeof dtsManagerOptions.host.remoteTypeUrls === "function" ? dtsManagerOptions.host.remoteTypeUrls() : Promise.resolve(dtsManagerOptions.host.remoteTypeUrls)).then((remoteTypeUrls) => {
233
+ consumeTypes({
234
+ ...dtsManagerOptions,
235
+ host: {
236
+ ...dtsManagerOptions.host,
237
+ remoteTypeUrls
238
+ }
239
+ }).then(() => {
240
+ typeof cb === "function" && cb(remoteTypeUrls);
241
+ }).catch(() => {
242
+ typeof cb === "function" && cb(remoteTypeUrls);
243
+ });
244
+ });
245
+ };
246
+ var ConsumeTypesPlugin = class {
247
+ constructor(pluginOptions, dtsOptions, fetchRemoteTypeUrlsResolve) {
248
+ this.pluginOptions = pluginOptions;
249
+ this.dtsOptions = dtsOptions;
250
+ this.fetchRemoteTypeUrlsResolve = fetchRemoteTypeUrlsResolve;
251
+ }
252
+ apply(compiler) {
253
+ const { dtsOptions, pluginOptions, fetchRemoteTypeUrlsResolve } = this;
254
+ const dtsManagerOptions = normalizeConsumeTypesOptions({
255
+ context: compiler.context,
256
+ dtsOptions,
257
+ pluginOptions
258
+ });
259
+ if (!dtsManagerOptions) {
260
+ fetchRemoteTypeUrlsResolve(void 0);
261
+ return;
262
+ }
263
+ if (isPrd() && !dtsManagerOptions.host.typesOnBuild) {
264
+ fetchRemoteTypeUrlsResolve(void 0);
265
+ return;
266
+ }
267
+ infrastructureLogger.debug("start fetching remote types...");
268
+ const promise = consumeTypesAPI(dtsManagerOptions, fetchRemoteTypeUrlsResolve);
269
+ compiler.hooks.thisCompilation.tap("mf:generateTypes", (compilation) => {
270
+ compilation.hooks.processAssets.tapPromise({
271
+ name: "mf:generateTypes",
272
+ stage: compilation.constructor.PROCESS_ASSETS_STAGE_OPTIMIZE_TRANSFER - 1
273
+ }, async () => {
274
+ await promise;
275
+ infrastructureLogger.debug("fetch remote types success!");
276
+ });
277
+ });
278
+ }
279
+ };
280
+
281
+ //#endregion
282
+ //#region src/plugins/GenerateTypesPlugin.ts
283
+ const DEFAULT_GENERATE_TYPES = {
284
+ generateAPITypes: true,
285
+ compileInChildProcess: true,
286
+ abortOnError: false,
287
+ extractThirdParty: false,
288
+ extractRemoteTypes: false
289
+ };
290
+ const normalizeGenerateTypesOptions = ({ context, outputDir, dtsOptions, pluginOptions }) => {
291
+ const normalizedGenerateTypes = normalizeOptions(true, DEFAULT_GENERATE_TYPES, "mfOptions.dts.generateTypes")(dtsOptions.generateTypes);
292
+ if (!normalizedGenerateTypes) return;
293
+ const normalizedConsumeTypes = normalizeOptions(true, {}, "mfOptions.dts.consumeTypes")(dtsOptions.consumeTypes);
294
+ const finalOptions = {
295
+ remote: {
296
+ implementation: dtsOptions.implementation,
297
+ context,
298
+ outputDir,
299
+ moduleFederationConfig: pluginOptions,
300
+ ...normalizedGenerateTypes
301
+ },
302
+ host: normalizedConsumeTypes === false ? void 0 : {
303
+ context,
304
+ moduleFederationConfig: pluginOptions,
305
+ ...normalizedConsumeTypes,
306
+ remoteTypeUrls: typeof normalizedConsumeTypes?.remoteTypeUrls === "object" ? normalizedConsumeTypes?.remoteTypeUrls : void 0
307
+ },
308
+ extraOptions: dtsOptions.extraOptions || {},
309
+ displayErrorInTerminal: dtsOptions.displayErrorInTerminal
310
+ };
311
+ if (dtsOptions.tsConfigPath && !finalOptions.remote.tsConfigPath) finalOptions.remote.tsConfigPath = dtsOptions.tsConfigPath;
312
+ validateOptions(finalOptions.remote);
313
+ return finalOptions;
314
+ };
315
+ const getGenerateTypesFn = (dtsManagerOptions) => {
316
+ let fn = generateTypes;
317
+ if (dtsManagerOptions.remote.compileInChildProcess) fn = generateTypesInChildProcess;
318
+ return fn;
319
+ };
320
+ const generateTypesAPI = ({ dtsManagerOptions }) => {
321
+ return getGenerateTypesFn(dtsManagerOptions)(dtsManagerOptions).then(async () => {
322
+ await callAfterGenerateHook({
323
+ dtsManagerOptions,
324
+ generatedTypes: retrieveTypesAssetsInfo(dtsManagerOptions.remote)
325
+ });
326
+ });
327
+ };
328
+ const callAfterGenerateHook = async ({ dtsManagerOptions, generatedTypes }) => {
329
+ const afterGenerate = dtsManagerOptions.remote.afterGenerate;
330
+ if (!afterGenerate) return;
331
+ try {
332
+ await afterGenerate(generatedTypes);
333
+ } catch (error) {
334
+ if (dtsManagerOptions.remote.abortOnError === false) {
335
+ if (dtsManagerOptions.displayErrorInTerminal) logger.error(error);
336
+ return;
337
+ }
338
+ throw error;
339
+ }
340
+ };
341
+ const WINDOWS_ABSOLUTE_PATH_REGEXP = /^[a-zA-Z]:[\\/]/;
342
+ const isSafeRelativePath = (relativePath) => {
343
+ return Boolean(relativePath) && !relativePath.startsWith("..") && !path.isAbsolute(relativePath) && !WINDOWS_ABSOLUTE_PATH_REGEXP.test(relativePath);
344
+ };
345
+ const resolveEmitAssetName = ({ compilerOutputPath, assetPath, fallbackName }) => {
346
+ if (!assetPath) return fallbackName;
347
+ const relativePath = path.relative(compilerOutputPath, assetPath);
348
+ return isSafeRelativePath(relativePath) ? relativePath : fallbackName;
349
+ };
350
+ var GenerateTypesPlugin = class {
351
+ constructor(pluginOptions, dtsOptions, fetchRemoteTypeUrlsPromise, callback) {
352
+ this.pluginOptions = pluginOptions;
353
+ this.dtsOptions = dtsOptions;
354
+ this.fetchRemoteTypeUrlsPromise = fetchRemoteTypeUrlsPromise;
355
+ this.callback = callback;
356
+ }
357
+ apply(compiler) {
358
+ const { dtsOptions, pluginOptions, fetchRemoteTypeUrlsPromise, callback } = this;
359
+ const outputDir = getCompilerOutputDir(compiler);
360
+ const context = compiler.context;
361
+ const dtsManagerOptions = normalizeGenerateTypesOptions({
362
+ context,
363
+ outputDir,
364
+ dtsOptions,
365
+ pluginOptions
366
+ });
367
+ if (!dtsManagerOptions) {
368
+ callback();
369
+ return;
370
+ }
371
+ const isProd = !isDev();
372
+ const compilerOutputPath = path.resolve(context, outputDir);
373
+ const emitTypesFiles = async (compilation) => {
374
+ try {
375
+ const { zipTypesPath, apiTypesPath, zipName, apiFileName } = retrieveTypesAssetsInfo(dtsManagerOptions.remote);
376
+ const emitZipName = resolveEmitAssetName({
377
+ compilerOutputPath,
378
+ assetPath: zipTypesPath,
379
+ fallbackName: zipName
380
+ });
381
+ const emitApiFileName = resolveEmitAssetName({
382
+ compilerOutputPath,
383
+ assetPath: apiTypesPath,
384
+ fallbackName: apiFileName
385
+ });
386
+ if (isProd && emitZipName && compilation.getAsset(emitZipName)) {
387
+ callback();
388
+ return;
389
+ }
390
+ logger.debug("start generating types...");
391
+ await generateTypesAPI({ dtsManagerOptions });
392
+ logger.debug("generate types success!");
393
+ if (isProd) {
394
+ if (zipTypesPath && !compilation.getAsset(emitZipName) && fs.existsSync(zipTypesPath)) compilation.emitAsset(emitZipName, new compiler.webpack.sources.RawSource(fs.readFileSync(zipTypesPath)));
395
+ if (apiTypesPath && !compilation.getAsset(emitApiFileName) && fs.existsSync(apiTypesPath)) compilation.emitAsset(emitApiFileName, new compiler.webpack.sources.RawSource(fs.readFileSync(apiTypesPath)));
396
+ callback();
397
+ } else {
398
+ const isEEXIST = (err) => {
399
+ return err.code == "EEXIST";
400
+ };
401
+ if (zipTypesPath && fs.existsSync(zipTypesPath)) {
402
+ const zipContent = fs.readFileSync(zipTypesPath);
403
+ const zipOutputPath = path.join(compiler.outputPath, emitZipName);
404
+ await new Promise((resolve, reject) => {
405
+ compiler.outputFileSystem.mkdir(path.dirname(zipOutputPath), { recursive: true }, (err) => {
406
+ if (err && !isEEXIST(err)) reject(err);
407
+ else compiler.outputFileSystem.writeFile(zipOutputPath, zipContent, (writeErr) => {
408
+ if (writeErr && !isEEXIST(writeErr)) reject(writeErr);
409
+ else resolve();
410
+ });
411
+ });
412
+ });
413
+ }
414
+ if (apiTypesPath && fs.existsSync(apiTypesPath)) {
415
+ const apiContent = fs.readFileSync(apiTypesPath);
416
+ const apiOutputPath = path.join(compiler.outputPath, emitApiFileName);
417
+ await new Promise((resolve, reject) => {
418
+ compiler.outputFileSystem.mkdir(path.dirname(apiOutputPath), { recursive: true }, (err) => {
419
+ if (err && !isEEXIST(err)) reject(err);
420
+ else compiler.outputFileSystem.writeFile(apiOutputPath, apiContent, (writeErr) => {
421
+ if (writeErr && !isEEXIST(writeErr)) reject(writeErr);
422
+ else resolve();
423
+ });
424
+ });
425
+ });
426
+ }
427
+ callback();
428
+ }
429
+ } catch (err) {
430
+ callback();
431
+ if (dtsManagerOptions.displayErrorInTerminal) console.error(err);
432
+ logger.debug("generate types fail!");
433
+ }
434
+ };
435
+ compiler.hooks.thisCompilation.tap("mf:generateTypes", (compilation) => {
436
+ compilation.hooks.processAssets.tapPromise({
437
+ name: "mf:generateTypes",
438
+ stage: compilation.constructor.PROCESS_ASSETS_STAGE_OPTIMIZE_TRANSFER
439
+ }, async () => {
440
+ await fetchRemoteTypeUrlsPromise;
441
+ const emitTypesFilesPromise = emitTypesFiles(compilation);
442
+ if (isProd) await emitTypesFilesPromise;
443
+ });
444
+ });
445
+ }
446
+ };
447
+
448
+ //#endregion
449
+ //#region src/plugins/DtsPlugin.ts
450
+ const normalizeDtsOptions = (options, context, defaultOptions) => {
451
+ return normalizeOptions(isTSProject(options.dts, context), {
452
+ generateTypes: defaultOptions?.defaultGenerateOptions || DEFAULT_GENERATE_TYPES,
453
+ consumeTypes: defaultOptions?.defaultConsumeOptions || DEFAULT_CONSUME_TYPES,
454
+ extraOptions: {},
455
+ displayErrorInTerminal: true
456
+ }, "mfOptions.dts")(options.dts);
457
+ };
458
+ const excludeDts = (filepath) => {
459
+ if (typeof filepath !== "string") return false;
460
+ const [_p, query] = filepath.split("?");
461
+ if (query && query.startsWith("exclude-mf-dts")) return true;
462
+ return false;
463
+ };
464
+ var DtsPlugin = class {
465
+ constructor(options) {
466
+ this.options = options;
467
+ this.clonedOptions = { ...options };
468
+ }
469
+ apply(compiler) {
470
+ const { options, clonedOptions } = this;
471
+ if (options.exposes && typeof options.exposes === "object") {
472
+ const cleanedExposes = {};
473
+ Object.entries(options.exposes).forEach(([key, value]) => {
474
+ if (typeof value === "string") {
475
+ const [filepath, _query] = value.split("?");
476
+ if (excludeDts(value)) return;
477
+ cleanedExposes[key] = filepath;
478
+ } else {
479
+ if (typeof value === "object" && Array.isArray(value.import) && value.import.some((v) => excludeDts(v))) return;
480
+ cleanedExposes[key] = value;
481
+ }
482
+ });
483
+ clonedOptions.exposes = cleanedExposes;
484
+ }
485
+ const normalizedDtsOptions = normalizeDtsOptions(clonedOptions, compiler.context);
486
+ if (typeof normalizedDtsOptions !== "object") return;
487
+ let fetchRemoteTypeUrlsResolve;
488
+ const fetchRemoteTypeUrlsPromise = new Promise((resolve) => {
489
+ fetchRemoteTypeUrlsResolve = resolve;
490
+ });
491
+ let generateTypesPromiseResolve;
492
+ new DevPlugin(clonedOptions, normalizedDtsOptions, new Promise((resolve) => {
493
+ generateTypesPromiseResolve = resolve;
494
+ }), fetchRemoteTypeUrlsPromise).apply(compiler);
495
+ new GenerateTypesPlugin(clonedOptions, normalizedDtsOptions, fetchRemoteTypeUrlsPromise, generateTypesPromiseResolve).apply(compiler);
496
+ new ConsumeTypesPlugin(clonedOptions, normalizedDtsOptions, fetchRemoteTypeUrlsResolve).apply(compiler);
497
+ }
498
+ addRuntimePlugins() {
499
+ const { options, clonedOptions } = this;
500
+ if (!clonedOptions.runtimePlugins) return;
501
+ if (!options.runtimePlugins) options.runtimePlugins = [];
502
+ clonedOptions.runtimePlugins.forEach((plugin) => {
503
+ options.runtimePlugins.includes(plugin) || options.runtimePlugins.push(plugin);
504
+ });
505
+ }
506
+ };
507
+
508
+ //#endregion
509
+ export { DtsPlugin, consumeTypesAPI, generateTypesAPI, isTSProject, normalizeConsumeTypesOptions, normalizeDtsOptions, normalizeGenerateTypesOptions };
@@ -0,0 +1,22 @@
1
+ import { s as fileLog, t as Broker } from "./Broker-Cmbh_XVO.mjs";
2
+
3
+ //#region src/server/broker/startBroker.ts
4
+ let broker;
5
+ function getBroker() {
6
+ return broker;
7
+ }
8
+ async function startBroker() {
9
+ if (getBroker()) return;
10
+ broker = new Broker();
11
+ await broker.start();
12
+ process.send?.("ready");
13
+ }
14
+ process.on("message", (message) => {
15
+ if (message === "start") {
16
+ fileLog(`startBroker... ${process.pid}`, "StartBroker", "info");
17
+ startBroker();
18
+ }
19
+ });
20
+
21
+ //#endregion
22
+ export { getBroker };
@@ -0,0 +1,13 @@
1
+ //#region src/dev-worker/utils.ts
2
+ const DEFAULT_LOCAL_IPS = ["localhost", "127.0.0.1"];
3
+ function getIpFromEntry(entry, ipv4) {
4
+ let ip;
5
+ entry.replace(/https?:\/\/([0-9|.]+|localhost):/, (str, matched) => {
6
+ ip = matched;
7
+ return str;
8
+ });
9
+ if (ip) return DEFAULT_LOCAL_IPS.includes(ip) ? ipv4 : ip;
10
+ }
11
+
12
+ //#endregion
13
+ export { getIpFromEntry as t };