@module-federation/dts-plugin 2.0.0 → 2.1.0

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