@meethive/vite 0.0.1

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 (72) hide show
  1. package/dist/index.d.ts +4 -0
  2. package/dist/index.d.ts.map +1 -0
  3. package/dist/index.js +2118 -0
  4. package/dist/index.mjs +2096 -0
  5. package/dist/src/federation/src/dev/expose-development.d.ts +5 -0
  6. package/dist/src/federation/src/dev/expose-development.d.ts.map +1 -0
  7. package/dist/src/federation/src/dev/remote-development.d.ts +5 -0
  8. package/dist/src/federation/src/dev/remote-development.d.ts.map +1 -0
  9. package/dist/src/federation/src/dev/shared-development.d.ts +5 -0
  10. package/dist/src/federation/src/dev/shared-development.d.ts.map +1 -0
  11. package/dist/src/federation/src/index.d.ts +7 -0
  12. package/dist/src/federation/src/index.d.ts.map +1 -0
  13. package/dist/src/federation/src/prod/expose-production.d.ts +5 -0
  14. package/dist/src/federation/src/prod/expose-production.d.ts.map +1 -0
  15. package/dist/src/federation/src/prod/remote-production.d.ts +7 -0
  16. package/dist/src/federation/src/prod/remote-production.d.ts.map +1 -0
  17. package/dist/src/federation/src/prod/shared-production.d.ts +5 -0
  18. package/dist/src/federation/src/prod/shared-production.d.ts.map +1 -0
  19. package/dist/src/federation/src/public.d.ts +40 -0
  20. package/dist/src/federation/src/public.d.ts.map +1 -0
  21. package/dist/src/federation/src/runtime/dynamic-remote.d.ts +79 -0
  22. package/dist/src/federation/src/runtime/dynamic-remote.d.ts.map +1 -0
  23. package/dist/src/federation/src/utils/html.d.ts +12 -0
  24. package/dist/src/federation/src/utils/html.d.ts.map +1 -0
  25. package/dist/src/federation/src/utils/index.d.ts +29 -0
  26. package/dist/src/federation/src/utils/index.d.ts.map +1 -0
  27. package/dist/src/federation/src/utils/semver/compare.d.ts +10 -0
  28. package/dist/src/federation/src/utils/semver/compare.d.ts.map +1 -0
  29. package/dist/src/federation/src/utils/semver/constants.d.ts +11 -0
  30. package/dist/src/federation/src/utils/semver/constants.d.ts.map +1 -0
  31. package/dist/src/federation/src/utils/semver/parser.d.ts +10 -0
  32. package/dist/src/federation/src/utils/semver/parser.d.ts.map +1 -0
  33. package/dist/src/federation/src/utils/semver/satisfy.d.ts +2 -0
  34. package/dist/src/federation/src/utils/semver/satisfy.d.ts.map +1 -0
  35. package/dist/src/federation/src/utils/semver/utils.d.ts +12 -0
  36. package/dist/src/federation/src/utils/semver/utils.d.ts.map +1 -0
  37. package/dist/src/monaco-editor/index.d.ts +35 -0
  38. package/dist/src/monaco-editor/index.d.ts.map +1 -0
  39. package/dist/src/monaco-editor/languageWork.d.ts +10 -0
  40. package/dist/src/monaco-editor/languageWork.d.ts.map +1 -0
  41. package/dist/src/monaco-editor/workerMiddleware.d.ts +9 -0
  42. package/dist/src/monaco-editor/workerMiddleware.d.ts.map +1 -0
  43. package/dist/src/sharp/index.d.ts +12 -0
  44. package/dist/src/sharp/index.d.ts.map +1 -0
  45. package/index.ts +3 -0
  46. package/package.json +48 -0
  47. package/src/federation/src/dev/expose-development.ts +29 -0
  48. package/src/federation/src/dev/remote-development.ts +435 -0
  49. package/src/federation/src/dev/shared-development.ts +29 -0
  50. package/src/federation/src/index.ts +242 -0
  51. package/src/federation/src/prod/expose-production.ts +333 -0
  52. package/src/federation/src/prod/federation_fn_import.js +75 -0
  53. package/src/federation/src/prod/remote-production.ts +658 -0
  54. package/src/federation/src/prod/shared-production.ts +268 -0
  55. package/src/federation/src/public.ts +54 -0
  56. package/src/federation/src/runtime/dynamic-remote.ts +247 -0
  57. package/src/federation/src/utils/html.ts +165 -0
  58. package/src/federation/src/utils/index.ts +255 -0
  59. package/src/federation/src/utils/semver/compare.ts +131 -0
  60. package/src/federation/src/utils/semver/constants.ts +46 -0
  61. package/src/federation/src/utils/semver/parser.ts +253 -0
  62. package/src/federation/src/utils/semver/satisfy.ts +151 -0
  63. package/src/federation/src/utils/semver/utils.ts +93 -0
  64. package/src/federation/types/dynamic-remote.d.ts +105 -0
  65. package/src/federation/types/index.d.ts +344 -0
  66. package/src/federation/types/pluginHooks.d.ts +4 -0
  67. package/src/federation/types/virtual-modules.d.ts +48 -0
  68. package/src/federation/types/viteDevServer.d.ts +22 -0
  69. package/src/monaco-editor/index.ts +205 -0
  70. package/src/monaco-editor/languageWork.ts +36 -0
  71. package/src/monaco-editor/workerMiddleware.ts +78 -0
  72. package/src/sharp/index.ts +93 -0
package/dist/index.mjs ADDED
@@ -0,0 +1,2096 @@
1
+ import virtual from "@rollup/plugin-virtual";
2
+ import path, { posix, resolve, basename, join, extname, parse, relative, dirname, isAbsolute } from "path";
3
+ import { walk } from "estree-walker";
4
+ import MagicString from "magic-string";
5
+ import path$1 from "node:path";
6
+ import { readFileSync, statSync, readdirSync, existsSync, rmSync } from "fs";
7
+ import "crypto";
8
+ import { buildSync } from "esbuild";
9
+ const EXPOSES_MAP = /* @__PURE__ */ new Map();
10
+ const EXPOSES_KEY_MAP = /* @__PURE__ */ new Map();
11
+ const SHARED = "shared";
12
+ const DYNAMIC_LOADING_CSS = "dynamicLoadingCss";
13
+ const DYNAMIC_LOADING_CSS_PREFIX = "__v__css__";
14
+ const DEFAULT_ENTRY_FILENAME = "remoteEntry.js";
15
+ const builderInfo = {
16
+ builder: "rollup",
17
+ assetsDir: "",
18
+ isHost: false,
19
+ isRemote: false,
20
+ isShared: false
21
+ };
22
+ const parsedOptions = {
23
+ prodExpose: [],
24
+ prodRemote: [],
25
+ prodShared: [],
26
+ devShared: [],
27
+ devExpose: [],
28
+ devRemote: []
29
+ };
30
+ const devRemotes = [];
31
+ const prodRemotes = [];
32
+ const viteConfigResolved = {
33
+ config: void 0
34
+ };
35
+ const unaryTags = /* @__PURE__ */ new Set(["link", "meta", "base"]);
36
+ function serializeTag({ tag, attrs, children }, indent = "") {
37
+ if (unaryTags.has(tag)) {
38
+ return `<${tag}${serializeAttrs(attrs)}>`;
39
+ } else {
40
+ return `<${tag}${serializeAttrs(attrs)}>${serializeTags(
41
+ children,
42
+ incrementIndent(indent)
43
+ )}</${tag}>`;
44
+ }
45
+ }
46
+ function serializeTags(tags, indent = "") {
47
+ if (typeof tags === "string") {
48
+ return tags;
49
+ } else if (tags && tags.length) {
50
+ return tags.map((tag) => `${indent}${serializeTag(tag, indent)}
51
+ `).join("");
52
+ }
53
+ return "";
54
+ }
55
+ function serializeAttrs(attrs) {
56
+ let res = "";
57
+ for (const key in attrs) {
58
+ if (typeof attrs[key] === "boolean") {
59
+ res += attrs[key] ? ` ${key}` : ``;
60
+ } else {
61
+ res += ` ${key}="${escapeHtml(attrs[key])}"`;
62
+ }
63
+ }
64
+ return res;
65
+ }
66
+ function incrementIndent(indent = "") {
67
+ return `${indent}${indent[0] === " " ? " " : " "}`;
68
+ }
69
+ const matchHtmlRegExp = /["'&<>]/;
70
+ function escapeHtml(string) {
71
+ const str = "" + string;
72
+ const match = matchHtmlRegExp.exec(str);
73
+ if (!match) {
74
+ return str;
75
+ }
76
+ let escape;
77
+ let html = "";
78
+ let index = 0;
79
+ let lastIndex = 0;
80
+ for (index = match.index; index < str.length; index++) {
81
+ switch (str.charCodeAt(index)) {
82
+ case 34:
83
+ escape = "&quot;";
84
+ break;
85
+ case 38:
86
+ escape = "&amp;";
87
+ break;
88
+ case 39:
89
+ escape = "&#39;";
90
+ break;
91
+ case 60:
92
+ escape = "&lt;";
93
+ break;
94
+ case 62:
95
+ escape = "&gt;";
96
+ break;
97
+ default:
98
+ continue;
99
+ }
100
+ if (lastIndex !== index) {
101
+ html += str.substring(lastIndex, index);
102
+ }
103
+ lastIndex = index + 1;
104
+ html += escape;
105
+ }
106
+ return lastIndex !== index ? html + str.substring(lastIndex, index) : html;
107
+ }
108
+ const headInjectRE = /([ \t]*)<\/head>/i;
109
+ const headPrependInjectRE = /([ \t]*)<head[^>]*>/i;
110
+ const htmlPrependInjectRE = /([ \t]*)<html[^>]*>/i;
111
+ const bodyPrependInjectRE = /([ \t]*)<body[^>]*>/i;
112
+ const doctypePrependInjectRE = /<!doctype html>/i;
113
+ const toPreloadTag = (href) => ({
114
+ tag: "link",
115
+ attrs: {
116
+ rel: "modulepreload",
117
+ crossorigin: true,
118
+ href
119
+ }
120
+ });
121
+ function injectToHead(html, tags, prepend = false) {
122
+ if (tags.length === 0) return html;
123
+ if (prepend) {
124
+ if (headPrependInjectRE.test(html)) {
125
+ return html.replace(
126
+ headPrependInjectRE,
127
+ (match, p1) => `${match}
128
+ ${serializeTags(tags, incrementIndent(p1))}`
129
+ );
130
+ }
131
+ } else {
132
+ if (headInjectRE.test(html)) {
133
+ return html.replace(
134
+ headInjectRE,
135
+ (match, p1) => `${serializeTags(tags, incrementIndent(p1))}${match}`
136
+ );
137
+ }
138
+ if (bodyPrependInjectRE.test(html)) {
139
+ return html.replace(
140
+ bodyPrependInjectRE,
141
+ (match, p1) => `${serializeTags(tags, p1)}
142
+ ${match}`
143
+ );
144
+ }
145
+ }
146
+ return prependInjectFallback(html, tags);
147
+ }
148
+ function prependInjectFallback(html, tags) {
149
+ if (htmlPrependInjectRE.test(html)) {
150
+ return html.replace(htmlPrependInjectRE, `$&
151
+ ${serializeTags(tags)}`);
152
+ }
153
+ if (doctypePrependInjectRE.test(html)) {
154
+ return html.replace(doctypePrependInjectRE, `$&
155
+ ${serializeTags(tags)}`);
156
+ }
157
+ return serializeTags(tags) + html;
158
+ }
159
+ function parseSharedOptions(options) {
160
+ return parseOptions(
161
+ options.shared || {},
162
+ (value, key) => ({
163
+ import: true,
164
+ shareScope: "default",
165
+ packagePath: key,
166
+ // Whether the path is set manually
167
+ manuallyPackagePathSetting: false,
168
+ generate: true,
169
+ modulePreload: false
170
+ }),
171
+ (value, key) => {
172
+ value.import = value.import ?? true;
173
+ value.shareScope = value.shareScope || "default";
174
+ value.packagePath = value.packagePath || key;
175
+ value.manuallyPackagePathSetting = value.packagePath !== key;
176
+ value.generate = value.generate ?? true;
177
+ value.modulePreload = value.modulePreload ?? false;
178
+ return value;
179
+ }
180
+ );
181
+ }
182
+ function parseExposeOptions(options) {
183
+ return parseOptions(
184
+ options.exposes,
185
+ (item) => {
186
+ return {
187
+ import: item,
188
+ name: void 0,
189
+ dontAppendStylesToHead: false
190
+ };
191
+ },
192
+ (item) => ({
193
+ import: item.import,
194
+ name: item.name || void 0,
195
+ dontAppendStylesToHead: item.dontAppendStylesToHead || false
196
+ })
197
+ );
198
+ }
199
+ function parseRemoteOptions(options) {
200
+ return parseOptions(
201
+ options.remotes ? options.remotes : {},
202
+ (item) => ({
203
+ external: Array.isArray(item) ? item : [item],
204
+ shareScope: options.shareScope || "default",
205
+ format: "esm",
206
+ from: "vite",
207
+ externalType: "url"
208
+ }),
209
+ (item) => ({
210
+ external: Array.isArray(item.external) ? item.external : [item.external],
211
+ shareScope: item.shareScope || options.shareScope || "default",
212
+ format: item.format || "esm",
213
+ from: item.from ?? "vite",
214
+ externalType: item.externalType || "url"
215
+ })
216
+ );
217
+ }
218
+ function parseOptions(options, normalizeSimple, normalizeOptions) {
219
+ if (!options) {
220
+ return [];
221
+ }
222
+ const list = [];
223
+ const array = (items) => {
224
+ for (const item of items) {
225
+ if (typeof item === "string") {
226
+ list.push([item, normalizeSimple(item, item)]);
227
+ } else if (item && typeof item === "object") {
228
+ object(item);
229
+ } else {
230
+ throw new Error("Unexpected options format");
231
+ }
232
+ }
233
+ };
234
+ const object = (obj) => {
235
+ for (const [key, value] of Object.entries(obj)) {
236
+ if (typeof value === "string" || Array.isArray(value)) {
237
+ list.push([key, normalizeSimple(value, key)]);
238
+ } else {
239
+ list.push([key, normalizeOptions(value, key)]);
240
+ }
241
+ }
242
+ };
243
+ if (Array.isArray(options)) {
244
+ array(options);
245
+ } else if (typeof options === "object") {
246
+ object(options);
247
+ } else {
248
+ throw new Error("Unexpected options format");
249
+ }
250
+ return list;
251
+ }
252
+ const letterReg = new RegExp("[0-9a-zA-Z]+");
253
+ function removeNonRegLetter(str, reg = letterReg) {
254
+ let needUpperCase = false;
255
+ let ret = "";
256
+ for (const c of str) {
257
+ if (reg.test(c)) {
258
+ ret += needUpperCase ? c.toUpperCase() : c;
259
+ needUpperCase = false;
260
+ } else {
261
+ needUpperCase = true;
262
+ }
263
+ }
264
+ return ret;
265
+ }
266
+ function getModuleMarker(value, type) {
267
+ return type ? `__rf_${type}__${value}` : `__rf_placeholder__${value}`;
268
+ }
269
+ function normalizePath(id) {
270
+ return posix.normalize(id.replace(/\\/g, "/"));
271
+ }
272
+ function createRemotesMap(remotes) {
273
+ const createUrl = (remote) => {
274
+ const external = remote.config.external[0];
275
+ const externalType = remote.config.externalType;
276
+ if (externalType === "promise") {
277
+ return `()=>${external}`;
278
+ } else {
279
+ return `'${external}'`;
280
+ }
281
+ };
282
+ return `const remotesMap = {
283
+ ${remotes.map(
284
+ (remote) => `'${remote.id}':{url:${createUrl(remote)},format:'${remote.config.format}',from:'${remote.config.from}'}`
285
+ ).join(",\n ")}
286
+ };`;
287
+ }
288
+ function getFileExtname(url) {
289
+ const fileNameAndParamArr = normalizePath(url).split("/");
290
+ const fileNameAndParam = fileNameAndParamArr[fileNameAndParamArr.length - 1];
291
+ const fileName = fileNameAndParam.split("?")[0];
292
+ return path.extname(fileName);
293
+ }
294
+ const REMOTE_FROM_PARAMETER = "remoteFrom";
295
+ const NAME_CHAR_REG = new RegExp("[0-9a-zA-Z@_-]+");
296
+ function joinUrlSegments(a, b) {
297
+ if (!a || !b) {
298
+ return a || b || "";
299
+ }
300
+ if (a[a.length - 1] === "/") {
301
+ a = a.substring(0, a.length - 1);
302
+ }
303
+ if (b[0] !== "/") {
304
+ b = "/" + b;
305
+ }
306
+ return a + b;
307
+ }
308
+ function toOutputFilePathWithoutRuntime(filename, type, hostId, hostType, config, toRelative) {
309
+ const { renderBuiltUrl } = config.experimental;
310
+ let relative2 = config.base === "" || config.base === "./";
311
+ if (renderBuiltUrl) {
312
+ const result = renderBuiltUrl(filename, {
313
+ hostId,
314
+ hostType,
315
+ type,
316
+ ssr: !!config.build.ssr
317
+ });
318
+ if (typeof result === "object") {
319
+ if (result.runtime) {
320
+ throw new Error(
321
+ `{ runtime: "${result.runtime}" } is not supported for assets in ${hostType} files: ${filename}`
322
+ );
323
+ }
324
+ if (typeof result.relative === "boolean") {
325
+ relative2 = result.relative;
326
+ }
327
+ } else if (result) {
328
+ return result;
329
+ }
330
+ }
331
+ if (relative2 && !config.build.ssr) {
332
+ return toRelative(filename, hostId);
333
+ } else {
334
+ return joinUrlSegments(config.base, filename);
335
+ }
336
+ }
337
+ function prodRemotePlugin(options) {
338
+ parsedOptions.prodRemote = parseRemoteOptions(options);
339
+ for (const item of parsedOptions.prodRemote) {
340
+ prodRemotes.push({
341
+ id: item[0],
342
+ regexp: new RegExp(`^${item[0]}/.+?`),
343
+ config: item[1]
344
+ });
345
+ }
346
+ const shareScope = options.shareScope || "default";
347
+ let resolvedConfig;
348
+ return {
349
+ name: "originjs:remote-production",
350
+ virtualFile: options.remotes || options.enableDynamicRemotes ? {
351
+ // language=JS
352
+ __federation__: `
353
+ ${createRemotesMap(prodRemotes)}
354
+ const currentImports = {}
355
+ const loadJS = async (url, fn) => {
356
+ const resolvedUrl = typeof url === 'function' ? await url() : url;
357
+ const script = document.createElement('script')
358
+ script.type = 'text/javascript';
359
+ script.onload = fn;
360
+ script.src = resolvedUrl;
361
+ document.getElementsByTagName('head')[0].appendChild(script);
362
+ }
363
+
364
+ function get(name, ${REMOTE_FROM_PARAMETER}) {
365
+ return __federation_import(name).then(module => () => {
366
+ if (${REMOTE_FROM_PARAMETER} === 'webpack') {
367
+ return Object.prototype.toString.call(module).indexOf('Module') > -1 && module.default ? module.default : module
368
+ }
369
+ return module
370
+ })
371
+ }
372
+
373
+ function merge(obj1, obj2) {
374
+ const mergedObj = Object.assign(obj1, obj2);
375
+ for (const key of Object.keys(mergedObj)) {
376
+ if (typeof mergedObj[key] === 'object' && typeof obj2[key] === 'object') {
377
+ mergedObj[key] = merge(mergedObj[key], obj2[key]);
378
+ }
379
+ }
380
+ return mergedObj;
381
+ }
382
+
383
+ const wrapShareModule = ${REMOTE_FROM_PARAMETER} => {
384
+ return merge({
385
+ ${getModuleMarker("shareScope")}
386
+ }, (globalThis.__federation_shared__ || {})['${shareScope}'] || {});
387
+ }
388
+
389
+ async function __federation_import(name) {
390
+ currentImports[name] ??= import(name)
391
+ return currentImports[name]
392
+ }
393
+
394
+ const initMap = Object.create(null);
395
+
396
+ async function __federation_method_ensure(remoteId) {
397
+ const remote = remotesMap[remoteId];
398
+ if (!remote.inited) {
399
+ if ('var' === remote.format) {
400
+ // loading js with script tag
401
+ return new Promise(resolve => {
402
+ const callback = () => {
403
+ if (!remote.inited) {
404
+ remote.lib = window[remoteId];
405
+ remote.lib.init(wrapShareModule(remote.from))
406
+ remote.inited = true;
407
+ }
408
+ resolve(remote.lib);
409
+ }
410
+ return loadJS(remote.url, callback);
411
+ });
412
+ } else if (['esm', 'systemjs'].includes(remote.format)) {
413
+ // loading js with import(...)
414
+ return new Promise((resolve, reject) => {
415
+ const getUrl = typeof remote.url === 'function' ? remote.url : () => Promise.resolve(remote.url);
416
+ getUrl().then(url => {
417
+ import(/* @vite-ignore */ url).then(lib => {
418
+ if (!remote.inited) {
419
+ const shareScope = wrapShareModule(remote.from);
420
+ lib.init(shareScope);
421
+ remote.lib = lib;
422
+ remote.lib.init(shareScope);
423
+ remote.inited = true;
424
+ }
425
+ resolve(remote.lib);
426
+ }).catch(reject)
427
+ })
428
+ })
429
+ }
430
+ } else {
431
+ return remote.lib;
432
+ }
433
+ }
434
+
435
+ function __federation_method_unwrapDefault(module) {
436
+ return (module?.__esModule || module?.[Symbol.toStringTag] === 'Module') ? module.default : module
437
+ }
438
+
439
+ function __federation_method_wrapDefault(module, need) {
440
+ if (!module?.default && need) {
441
+ let obj = Object.create(null);
442
+ obj.default = module;
443
+ obj.__esModule = true;
444
+ return obj;
445
+ }
446
+ return module;
447
+ }
448
+
449
+ function __federation_method_getRemote(remoteName, componentName) {
450
+ return __federation_method_ensure(remoteName).then((remote) => remote.get(componentName).then(factory => factory()));
451
+ }
452
+
453
+ function __federation_method_setRemote(remoteName, remoteConfig) {
454
+ remotesMap[remoteName] = remoteConfig;
455
+ }
456
+
457
+ async function __federation_method_add_origin_setRemote(remoteName, remoteUrl, options) {
458
+ const _options = options || {}
459
+ const _item = {
460
+ external: Array.isArray(_options.external) ? _options.external : [_options.external],
461
+ shareScope: _options.shareScope || 'default',
462
+ format: _options.format || 'esm',
463
+ from: _options.from ?? 'vite',
464
+ externalType: _options.externalType || 'url'
465
+ }
466
+
467
+ __federation_method_setRemote(remoteName, {
468
+ url: remoteUrl,
469
+ format: _item.format,
470
+ from: _item.from
471
+ })
472
+ }
473
+
474
+ export {
475
+ __federation_method_ensure,
476
+ __federation_method_getRemote,
477
+ __federation_method_setRemote,
478
+ __federation_method_add_origin_setRemote,
479
+ __federation_method_unwrapDefault,
480
+ __federation_method_wrapDefault
481
+ }
482
+ `
483
+ } : { __federation__: "" },
484
+ configResolved(config) {
485
+ resolvedConfig = config;
486
+ },
487
+ async transform(code, id) {
488
+ if (builderInfo.isShared) {
489
+ for (const sharedInfo of parsedOptions.prodShared) {
490
+ if (!sharedInfo[1].emitFile) {
491
+ sharedInfo[1].emitFile = this.emitFile({
492
+ type: "chunk",
493
+ id: sharedInfo[1].id ?? sharedInfo[1].packagePath,
494
+ preserveSignature: "strict",
495
+ name: `__federation_shared_${sharedInfo[0]}`
496
+ });
497
+ }
498
+ }
499
+ if (id === "\0virtual:__federation_fn_import") {
500
+ const moduleMapCode = parsedOptions.prodShared.filter((shareInfo) => shareInfo[1].generate).map(
501
+ (sharedInfo) => `'${sharedInfo[0]}':{get:()=>()=>__federation_import(import.meta.ROLLUP_FILE_URL_${sharedInfo[1].emitFile}),import:${sharedInfo[1].import}${sharedInfo[1].requiredVersion ? `,requiredVersion:'${sharedInfo[1].requiredVersion}'` : ""}}`
502
+ ).join(",");
503
+ return code.replace(
504
+ getModuleMarker("moduleMap", "var"),
505
+ `{${moduleMapCode}}`
506
+ );
507
+ }
508
+ }
509
+ if (builderInfo.isRemote) {
510
+ for (const expose of parsedOptions.prodExpose) {
511
+ if (!expose[1].emitFile) {
512
+ expose[1].emitFile = this.emitFile({
513
+ type: "chunk",
514
+ id: expose[1].id ?? expose[1].import,
515
+ name: EXPOSES_KEY_MAP.get(expose[0]),
516
+ preserveSignature: "allow-extension"
517
+ });
518
+ }
519
+ }
520
+ }
521
+ if (builderInfo.isHost) {
522
+ if (id === "\0virtual:__federation__") {
523
+ const res = [];
524
+ parsedOptions.prodShared.forEach((arr) => {
525
+ const obj = arr[1];
526
+ let str = "";
527
+ if (typeof obj === "object") {
528
+ const fileUrl = `import.meta.ROLLUP_FILE_URL_${obj.emitFile}`;
529
+ str += `get:()=>get(${fileUrl}, ${REMOTE_FROM_PARAMETER}), loaded:1`;
530
+ res.push(`'${arr[0]}':{'${obj.version}':{${str}}}`);
531
+ }
532
+ });
533
+ return code.replace(getModuleMarker("shareScope"), res.join(","));
534
+ }
535
+ } else {
536
+ if (id === "\0virtual:__federation__") {
537
+ return code.replace(getModuleMarker("shareScope"), "");
538
+ }
539
+ }
540
+ if (builderInfo.isHost || builderInfo.isShared) {
541
+ let ast = null;
542
+ try {
543
+ ast = this.parse(code);
544
+ } catch (err) {
545
+ console.error(err);
546
+ }
547
+ if (!ast) {
548
+ return null;
549
+ }
550
+ const magicString = new MagicString(code);
551
+ const hasStaticImported = /* @__PURE__ */ new Map();
552
+ let requiresRuntime = false;
553
+ let hasImportShared = false;
554
+ let modify = false;
555
+ let manualRequired = null;
556
+ walk(ast, {
557
+ enter(node) {
558
+ if (node.type === "ImportDeclaration") {
559
+ const moduleName = node.source.value;
560
+ if (parsedOptions.prodShared.some(
561
+ (sharedInfo) => sharedInfo[0] === moduleName
562
+ )) {
563
+ const namedImportDeclaration = [];
564
+ let defaultImportDeclaration = null;
565
+ if (!node.specifiers?.length) {
566
+ magicString.remove(node.start, node.end);
567
+ modify = true;
568
+ } else {
569
+ node.specifiers.forEach((specify) => {
570
+ if (specify.imported?.name) {
571
+ namedImportDeclaration.push(
572
+ `${specify.imported.name === specify.local.name ? specify.imported.name : `${specify.imported.name}:${specify.local.name}`}`
573
+ );
574
+ } else {
575
+ defaultImportDeclaration = specify.local.name;
576
+ }
577
+ });
578
+ hasImportShared = true;
579
+ if (defaultImportDeclaration && namedImportDeclaration.length) {
580
+ const imports = namedImportDeclaration.join(",");
581
+ const line = `const ${defaultImportDeclaration} = await importShared('${moduleName}');
582
+ const {${imports}} = ${defaultImportDeclaration};
583
+ `;
584
+ magicString.overwrite(node.start, node.end, line);
585
+ } else if (defaultImportDeclaration) {
586
+ magicString.overwrite(
587
+ node.start,
588
+ node.end,
589
+ `const ${defaultImportDeclaration} = await importShared('${moduleName}');
590
+ `
591
+ );
592
+ } else if (namedImportDeclaration.length) {
593
+ magicString.overwrite(
594
+ node.start,
595
+ node.end,
596
+ `const {${namedImportDeclaration.join(
597
+ ","
598
+ )}} = await importShared('${moduleName}');
599
+ `
600
+ );
601
+ }
602
+ }
603
+ }
604
+ }
605
+ if (node.type === "ImportDeclaration" && node.source?.value === "virtual:__federation__") {
606
+ manualRequired = node;
607
+ }
608
+ if ((node.type === "ImportExpression" || node.type === "ImportDeclaration" || node.type === "ExportNamedDeclaration") && node.source?.value?.indexOf("/") > -1) {
609
+ const moduleId = node.source.value;
610
+ const remote = prodRemotes.find((r) => r.regexp.test(moduleId));
611
+ const needWrap = remote?.config.from === "vite";
612
+ if (remote) {
613
+ requiresRuntime = true;
614
+ const modName = `.${moduleId.slice(remote.id.length)}`;
615
+ switch (node.type) {
616
+ case "ImportExpression": {
617
+ magicString.overwrite(
618
+ node.start,
619
+ node.end,
620
+ `__federation_method_getRemote(${JSON.stringify(
621
+ remote.id
622
+ )} , ${JSON.stringify(
623
+ modName
624
+ )}).then(module=>__federation_method_wrapDefault(module, ${needWrap}))`
625
+ );
626
+ break;
627
+ }
628
+ case "ImportDeclaration": {
629
+ if (node.specifiers?.length) {
630
+ const afterImportName = `__federation_var_${moduleId.replace(
631
+ /[@/\\.-]/g,
632
+ ""
633
+ )}`;
634
+ if (!hasStaticImported.has(moduleId)) {
635
+ hasStaticImported.set(moduleId, afterImportName);
636
+ magicString.overwrite(
637
+ node.start,
638
+ node.end,
639
+ `const ${afterImportName} = await __federation_method_getRemote(${JSON.stringify(
640
+ remote.id
641
+ )} , ${JSON.stringify(modName)});`
642
+ );
643
+ }
644
+ let deconstructStr = "";
645
+ node.specifiers.forEach((spec) => {
646
+ if (spec.type === "ImportDefaultSpecifier") {
647
+ magicString.appendRight(
648
+ node.end,
649
+ `
650
+ let ${spec.local.name} = __federation_method_unwrapDefault(${afterImportName}) `
651
+ );
652
+ } else if (spec.type === "ImportSpecifier") {
653
+ const importedName = spec.imported.name;
654
+ const localName = spec.local.name;
655
+ deconstructStr += `${importedName === localName ? localName : `${importedName} : ${localName}`},`;
656
+ } else if (spec.type === "ImportNamespaceSpecifier") {
657
+ magicString.appendRight(
658
+ node.end,
659
+ `let {${spec.local.name}} = ${afterImportName}`
660
+ );
661
+ }
662
+ });
663
+ if (deconstructStr.length > 0) {
664
+ magicString.appendRight(
665
+ node.end,
666
+ `
667
+ let {${deconstructStr.slice(
668
+ 0,
669
+ -1
670
+ )}} = ${afterImportName}`
671
+ );
672
+ }
673
+ }
674
+ break;
675
+ }
676
+ case "ExportNamedDeclaration": {
677
+ const afterImportName = `__federation_var_${moduleId.replace(
678
+ /[@/\\.-]/g,
679
+ ""
680
+ )}`;
681
+ if (!hasStaticImported.has(moduleId)) {
682
+ hasStaticImported.set(moduleId, afterImportName);
683
+ magicString.overwrite(
684
+ node.start,
685
+ node.end,
686
+ `const ${afterImportName} = await __federation_method_getRemote(${JSON.stringify(
687
+ remote.id
688
+ )} , ${JSON.stringify(modName)});`
689
+ );
690
+ }
691
+ if (node.specifiers.length > 0) {
692
+ const specifiers = node.specifiers;
693
+ let exportContent = "";
694
+ let deconstructContent = "";
695
+ specifiers.forEach((spec) => {
696
+ const localName = spec.local.name;
697
+ const exportName = spec.exported.name;
698
+ const variableName = `${afterImportName}_${localName}`;
699
+ deconstructContent = deconstructContent.concat(
700
+ `${localName}:${variableName},`
701
+ );
702
+ exportContent = exportContent.concat(
703
+ `${variableName} as ${exportName},`
704
+ );
705
+ });
706
+ magicString.append(
707
+ `
708
+ const {${deconstructContent.slice(
709
+ 0,
710
+ deconstructContent.length - 1
711
+ )}} = ${afterImportName};
712
+ `
713
+ );
714
+ magicString.append(
715
+ `
716
+ export {${exportContent.slice(
717
+ 0,
718
+ exportContent.length - 1
719
+ )}}; `
720
+ );
721
+ }
722
+ break;
723
+ }
724
+ }
725
+ }
726
+ }
727
+ }
728
+ });
729
+ if (requiresRuntime) {
730
+ let requiresCode = `import {__federation_method_ensure, __federation_method_getRemote , __federation_method_wrapDefault , __federation_method_unwrapDefault, __federation_method_add_origin_setRemote} from '__federation__';
731
+
732
+ `;
733
+ if (manualRequired) {
734
+ requiresCode = `import {__federation_method_setRemote, __federation_method_ensure, __federation_method_getRemote , __federation_method_wrapDefault , __federation_method_unwrapDefault, __federation_method_add_origin_setRemote} from '__federation__';
735
+
736
+ `;
737
+ magicString.overwrite(manualRequired.start, manualRequired.end, ``);
738
+ }
739
+ magicString.prepend(requiresCode);
740
+ }
741
+ if (hasImportShared) {
742
+ magicString.prepend(
743
+ `import {importShared} from '\0virtual:__federation_fn_import';
744
+ `
745
+ );
746
+ }
747
+ if (requiresRuntime || hasImportShared || modify) {
748
+ return {
749
+ code: magicString.toString(),
750
+ map: magicString.generateMap({ hires: true })
751
+ };
752
+ }
753
+ }
754
+ },
755
+ generateBundle(options2, bundle) {
756
+ const preloadSharedReg = parsedOptions.prodShared.filter((shareInfo) => shareInfo[1].modulePreload).map(
757
+ (item) => new RegExp(`__federation_shared_${item[0]}-.{8}.js`, "g")
758
+ );
759
+ const getImportedChunks = (chunk, satisfy, seen = /* @__PURE__ */ new Set()) => {
760
+ const chunks = [];
761
+ chunk.imports.forEach((file) => {
762
+ const importee = bundle[file];
763
+ if (importee) {
764
+ if (importee.type === "chunk" && !seen.has(file)) {
765
+ if (satisfy(importee)) {
766
+ seen.add(file);
767
+ chunks.push(...getImportedChunks(importee, satisfy, seen));
768
+ chunks.push(importee);
769
+ }
770
+ }
771
+ }
772
+ });
773
+ return chunks;
774
+ };
775
+ const sharedFiles = [];
776
+ const entryChunk = {};
777
+ for (const fileName in bundle) {
778
+ const file = bundle[fileName];
779
+ if (file.type === "asset") {
780
+ if (fileName.endsWith(".html")) {
781
+ entryChunk[fileName] = file;
782
+ }
783
+ } else {
784
+ if (preloadSharedReg.some((item) => item.test(fileName))) {
785
+ sharedFiles.push(fileName);
786
+ }
787
+ }
788
+ }
789
+ if (!sharedFiles.length) return;
790
+ Object.keys(entryChunk).forEach((fileName) => {
791
+ let html = entryChunk[fileName].source;
792
+ const htmlPath = entryChunk[fileName].fileName;
793
+ const basePath = resolvedConfig.base === "./" || resolvedConfig.base === "" ? path$1.posix.join(
794
+ path$1.posix.relative(entryChunk[fileName].fileName, "").slice(0, -2),
795
+ "./"
796
+ ) : resolvedConfig.base;
797
+ const toOutputFilePath = (filename) => toOutputFilePathWithoutRuntime(
798
+ filename,
799
+ "asset",
800
+ htmlPath,
801
+ "html",
802
+ resolvedConfig,
803
+ (filename2) => basePath + filename2
804
+ );
805
+ const importFiles = sharedFiles.filter((item) => {
806
+ return !html.includes(toOutputFilePath(item));
807
+ }).flatMap((item) => {
808
+ const filepath = item;
809
+ const importFiles2 = getImportedChunks(
810
+ bundle[item],
811
+ (chunk) => !html.includes(toOutputFilePath(chunk.fileName))
812
+ ).map((item2) => item2.fileName);
813
+ return [filepath, ...importFiles2].map(
814
+ (item2) => toOutputFilePath(item2)
815
+ );
816
+ });
817
+ html = injectToHead(
818
+ html,
819
+ [...new Set(importFiles)].map((item) => toPreloadTag(item))
820
+ );
821
+ entryChunk[fileName].source = html;
822
+ });
823
+ }
824
+ };
825
+ }
826
+ const federation_fn_import = "import { satisfy } from '__federation_fn_satisfy'\r\n\r\nconst currentImports = {}\r\n\r\n// eslint-disable-next-line no-undef\r\nconst moduleMap = __rf_var__moduleMap\r\nconst moduleCache = Object.create(null)\r\nasync function importShared(name, shareScope = 'default') {\r\n return moduleCache[name]\r\n ? new Promise((r) => r(moduleCache[name]))\r\n : (await getSharedFromRuntime(name, shareScope)) || getSharedFromLocal(name)\r\n}\r\n// eslint-disable-next-line\r\nasync function __federation_import(name) {\r\n currentImports[name] ??= import(name)\r\n return currentImports[name]\r\n}\r\nasync function getSharedFromRuntime(name, shareScope) {\r\n let module = null\r\n if (globalThis?.__federation_shared__?.[shareScope]?.[name]) {\r\n const versionObj = globalThis.__federation_shared__[shareScope][name]\r\n const requiredVersion = moduleMap[name]?.requiredVersion\r\n const hasRequiredVersion = !!requiredVersion\r\n if (hasRequiredVersion) {\r\n const versionKey = Object.keys(versionObj).find((version) =>\r\n satisfy(version, requiredVersion)\r\n )\r\n if (versionKey) {\r\n const versionValue = versionObj[versionKey]\r\n module = await (await versionValue.get())()\r\n } else {\r\n console.log(\r\n `provider support ${name}(${versionKey}) is not satisfied requiredVersion(\\${moduleMap[name].requiredVersion})`\r\n )\r\n }\r\n } else {\r\n const versionKey = Object.keys(versionObj)[0]\r\n const versionValue = versionObj[versionKey]\r\n module = await (await versionValue.get())()\r\n }\r\n }\r\n if (module) {\r\n return flattenModule(module, name)\r\n }\r\n}\r\nasync function getSharedFromLocal(name) {\r\n if (moduleMap[name]?.import) {\r\n let module = await (await moduleMap[name].get())()\r\n return flattenModule(module, name)\r\n } else {\r\n console.error(\r\n `consumer config import=false,so cant use callback shared module`\r\n )\r\n }\r\n}\r\nfunction flattenModule(module, name) {\r\n // use a shared module which export default a function will getting error 'TypeError: xxx is not a function'\r\n if (typeof module.default === 'function') {\r\n Object.keys(module).forEach((key) => {\r\n if (key !== 'default') {\r\n module.default[key] = module[key]\r\n }\r\n })\r\n moduleCache[name] = module.default\r\n return module.default\r\n }\r\n if (module.default) module = Object.assign({}, module.default, module)\r\n moduleCache[name] = module\r\n return module\r\n}\r\nexport {\r\n importShared,\r\n getSharedFromRuntime as importSharedRuntime,\r\n getSharedFromLocal as importSharedLocal\r\n}\r\n";
827
+ const sharedFilePathReg = /__federation_shared_(.+)-.{8}\.js$/;
828
+ function prodSharedPlugin(options) {
829
+ parsedOptions.prodShared = parseSharedOptions(options);
830
+ const shareName2Prop = /* @__PURE__ */ new Map();
831
+ parsedOptions.prodShared.forEach(
832
+ (value) => shareName2Prop.set(removeNonRegLetter(value[0], NAME_CHAR_REG), value[1])
833
+ );
834
+ let isHost;
835
+ let isRemote;
836
+ const id2Prop = /* @__PURE__ */ new Map();
837
+ function negotiateManualChunksCompatibility(inputOptions) {
838
+ if (!inputOptions.output) return;
839
+ const outputs = Array.isArray(inputOptions.output) ? inputOptions.output : [inputOptions.output];
840
+ outputs.forEach((output) => {
841
+ if (!output.manualChunks) return;
842
+ const sharedModuleNames = [...shareName2Prop.keys()];
843
+ const conflictModules = /* @__PURE__ */ new Set();
844
+ if (typeof output.manualChunks === "object") {
845
+ Object.values(output.manualChunks).flat().forEach((mod) => {
846
+ if (sharedModuleNames.some((shared) => mod.includes(shared) || mod === shared)) {
847
+ conflictModules.add(mod);
848
+ }
849
+ });
850
+ }
851
+ if (conflictModules.size > 0) {
852
+ console.info(
853
+ `[Federation] 检测到模块 [${Array.from(conflictModules).join(", ")}] 同时配置在 shared 和 manualChunks 中,启用协商共存模式`
854
+ );
855
+ adaptSharedToManualChunks(conflictModules);
856
+ }
857
+ });
858
+ }
859
+ function adaptSharedToManualChunks(conflictModules) {
860
+ parsedOptions.prodShared.forEach((sharedItem, index) => {
861
+ const [moduleName, config] = sharedItem;
862
+ if (conflictModules.has(moduleName)) {
863
+ config.manualChunkCompat = true;
864
+ config.chunkLoading = "defer";
865
+ console.info(
866
+ `[Federation] 模块 "${moduleName}" 设置为兼容模式:manualChunks 负责分块,federation 负责运行时共享`
867
+ );
868
+ }
869
+ });
870
+ }
871
+ return {
872
+ name: "originjs:shared-production",
873
+ virtualFile: {
874
+ __federation_fn_import: federation_fn_import
875
+ },
876
+ options(inputOptions) {
877
+ isRemote = !!parsedOptions.prodExpose.length;
878
+ isHost = options.isHost;
879
+ if (shareName2Prop.size) {
880
+ inputOptions.external = inputOptions.external?.filter((item) => {
881
+ if (item instanceof RegExp)
882
+ return ![...shareName2Prop.keys()].some((key) => item.test(key));
883
+ return !shareName2Prop.has(removeNonRegLetter(item, NAME_CHAR_REG));
884
+ });
885
+ }
886
+ negotiateManualChunksCompatibility(inputOptions);
887
+ return inputOptions;
888
+ },
889
+ async buildStart() {
890
+ if (parsedOptions.prodShared.length && isRemote) {
891
+ this.emitFile({
892
+ name: "__federation_fn_import",
893
+ type: "chunk",
894
+ id: "__federation_fn_import",
895
+ preserveSignature: "strict"
896
+ });
897
+ }
898
+ const collectDirFn = (filePath, collect) => {
899
+ const files = readdirSync(filePath);
900
+ files.forEach((name) => {
901
+ const tempPath = join(filePath, name);
902
+ const isDir = statSync(tempPath).isDirectory();
903
+ if (isDir) {
904
+ collect.push(tempPath);
905
+ collectDirFn(tempPath, collect);
906
+ }
907
+ });
908
+ };
909
+ const monoRepos = [];
910
+ const dirPaths = [];
911
+ const currentDir = resolve();
912
+ for (const arr of parsedOptions.prodShared) {
913
+ if (isHost && !arr[1].version && !arr[1].manuallyPackagePathSetting) {
914
+ const packageJsonPath = (await this.resolve(`${arr[1].packagePath}/package.json`))?.id;
915
+ if (packageJsonPath) {
916
+ const packageJson = JSON.parse(
917
+ readFileSync(packageJsonPath, { encoding: "utf-8" })
918
+ );
919
+ arr[1].version = packageJson.version;
920
+ } else {
921
+ arr[1].removed = true;
922
+ const dir = join(currentDir, "node_modules", arr[0]);
923
+ const dirStat = statSync(dir);
924
+ if (dirStat.isDirectory()) {
925
+ collectDirFn(dir, dirPaths);
926
+ } else {
927
+ this.error(`cant resolve "${arr[1].packagePath}"`);
928
+ }
929
+ if (dirPaths.length > 0) {
930
+ monoRepos.push({ arr: dirPaths, root: arr });
931
+ }
932
+ }
933
+ if (!arr[1].removed && !arr[1].version) {
934
+ this.error(
935
+ `No description file or no version in description file (usually package.json) of ${arr[0]}. Add version to description file, or manually specify version in shared config.`
936
+ );
937
+ }
938
+ }
939
+ }
940
+ parsedOptions.prodShared = parsedOptions.prodShared.filter(
941
+ (item) => !item[1].removed
942
+ );
943
+ if (monoRepos.length > 0) {
944
+ for (const monoRepo of monoRepos) {
945
+ for (const id of monoRepo.arr) {
946
+ try {
947
+ const idResolve = await this.resolve(id);
948
+ if (idResolve?.id) {
949
+ parsedOptions.prodShared.push([
950
+ `${monoRepo.root[0]}/${basename(id)}`,
951
+ {
952
+ id: idResolve?.id,
953
+ import: monoRepo.root[1].import,
954
+ shareScope: monoRepo.root[1].shareScope,
955
+ root: monoRepo.root
956
+ }
957
+ ]);
958
+ }
959
+ } catch (e) {
960
+ }
961
+ }
962
+ }
963
+ }
964
+ if (parsedOptions.prodShared.length && isRemote) {
965
+ for (const prod of parsedOptions.prodShared) {
966
+ id2Prop.set(prod[1].id, prod[1]);
967
+ }
968
+ }
969
+ },
970
+ outputOptions: function(outputOption) {
971
+ outputOption.hoistTransitiveImports = false;
972
+ const manualChunkFunc = (id) => {
973
+ const find = parsedOptions.prodShared.find(
974
+ (arr) => arr[1].dependencies?.has(id)
975
+ );
976
+ return find ? find[0] : void 0;
977
+ };
978
+ if (typeof outputOption.manualChunks === "function") {
979
+ outputOption.manualChunks = new Proxy(outputOption.manualChunks, {
980
+ apply(target, thisArg, argArray) {
981
+ const result = manualChunkFunc(argArray[0]);
982
+ return result ? result : target(argArray[0], argArray[1]);
983
+ }
984
+ });
985
+ }
986
+ if (outputOption.manualChunks === void 0) {
987
+ outputOption.manualChunks = manualChunkFunc;
988
+ }
989
+ return outputOption;
990
+ },
991
+ generateBundle(options2, bundle) {
992
+ if (!isRemote) {
993
+ return;
994
+ }
995
+ const needRemoveShared = /* @__PURE__ */ new Set();
996
+ for (const key in bundle) {
997
+ const chunk = bundle[key];
998
+ if (chunk.type === "chunk") {
999
+ if (!isHost) {
1000
+ const regRst = sharedFilePathReg.exec(chunk.fileName);
1001
+ if (regRst && shareName2Prop.get(removeNonRegLetter(regRst[1], NAME_CHAR_REG))?.generate === false) {
1002
+ needRemoveShared.add(key);
1003
+ }
1004
+ }
1005
+ }
1006
+ }
1007
+ if (needRemoveShared.size !== 0) {
1008
+ for (const key of needRemoveShared) {
1009
+ delete bundle[key];
1010
+ }
1011
+ }
1012
+ }
1013
+ };
1014
+ }
1015
+ function prodExposePlugin(options) {
1016
+ let moduleMap = "";
1017
+ const hasOptions = parsedOptions.prodExpose.some((expose) => {
1018
+ return expose[0] === parseExposeOptions(options)[0]?.[0];
1019
+ });
1020
+ if (!hasOptions) {
1021
+ parsedOptions.prodExpose = Array.prototype.concat(
1022
+ parsedOptions.prodExpose,
1023
+ parseExposeOptions(options)
1024
+ );
1025
+ }
1026
+ for (const item of parseExposeOptions(options)) {
1027
+ getModuleMarker(`\${${item[0]}}`, SHARED);
1028
+ const exposeFilepath = normalizePath(resolve(item[1].import));
1029
+ EXPOSES_MAP.set(item[0], exposeFilepath);
1030
+ EXPOSES_KEY_MAP.set(
1031
+ item[0],
1032
+ `__federation_expose_${removeNonRegLetter(item[0], NAME_CHAR_REG)}`
1033
+ );
1034
+ moduleMap += `
1035
+ "${item[0]}":()=>{
1036
+ ${DYNAMIC_LOADING_CSS}('${DYNAMIC_LOADING_CSS_PREFIX}${exposeFilepath}', ${item[1].dontAppendStylesToHead}, '${item[0]}')
1037
+ return __federation_import('\${__federation_expose_${item[0]}}').then(module =>Object.keys(module).every(item => exportSet.has(item)) ? () => module.default : () => module)},`;
1038
+ }
1039
+ return {
1040
+ name: "originjs:expose-production",
1041
+ virtualFile: {
1042
+ // code generated for remote
1043
+ // language=JS
1044
+ [`__remoteEntryHelper__${options.filename}`]: `
1045
+ const currentImports = {}
1046
+ const exportSet = new Set(['Module', '__esModule', 'default', '_export_sfc']);
1047
+ let moduleMap = {${moduleMap}}
1048
+ const seen = {}
1049
+ export const ${DYNAMIC_LOADING_CSS} = (cssFilePaths, dontAppendStylesToHead, exposeItemName) => {
1050
+ const metaUrl = import.meta.url;
1051
+ if (typeof metaUrl === 'undefined') {
1052
+ console.warn('The remote style takes effect only when the build.target option in the vite.config.ts file is higher than that of "es2020".');
1053
+ return;
1054
+ }
1055
+
1056
+ const curUrl = metaUrl.substring(0, metaUrl.lastIndexOf('${options.filename}'));
1057
+ const base = __VITE_BASE_PLACEHOLDER__;
1058
+ const assetsDir = __VITE_ASSETS_DIR_PLACEHOLDER__;
1059
+
1060
+ cssFilePaths.forEach(cssPath => {
1061
+ let href = '';
1062
+ const baseUrl = base || curUrl;
1063
+ if (baseUrl) {
1064
+ const trimmer = {
1065
+ trailing: (path) => (path.endsWith('/') ? path.slice(0, -1) : path),
1066
+ leading: (path) => (path.startsWith('/') ? path.slice(1) : path)
1067
+ }
1068
+ const isAbsoluteUrl = (url) => url.startsWith('http') || url.startsWith('//');
1069
+
1070
+ const cleanBaseUrl = trimmer.trailing(baseUrl).replace('.', '');
1071
+ const cleanAssetsDir = trimmer.leading(assetsDir);
1072
+ const cleanCssPath = trimmer.leading(cssPath);
1073
+ const cleanCurUrl = trimmer.trailing(curUrl);
1074
+
1075
+ if (isAbsoluteUrl(baseUrl)) {
1076
+ href = [cleanBaseUrl, cleanAssetsDir, cleanCssPath].filter(Boolean).join('/');
1077
+ } else {
1078
+ // 当remoteEntry.js和CSS都在assets目录下时,使用相对路径
1079
+ const remoteEntryInAssets = cleanCurUrl.endsWith('/assets/') || cleanCurUrl.endsWith('/assets');
1080
+
1081
+ if (remoteEntryInAssets) {
1082
+ // 都在assets目录下,直接使用CSS文件名
1083
+ href = [cleanCurUrl, cleanCssPath].filter(Boolean).join('/');
1084
+ } else if (cleanCurUrl.includes(cleanBaseUrl)) {
1085
+ href = [cleanCurUrl, cleanAssetsDir, cleanCssPath].filter(Boolean).join('/');
1086
+ } else {
1087
+ href = [cleanCurUrl + cleanBaseUrl, cleanAssetsDir, cleanCssPath].filter(Boolean).join('/');
1088
+ }
1089
+ }
1090
+ } else {
1091
+ href = cssPath;
1092
+ }
1093
+
1094
+ if (dontAppendStylesToHead) {
1095
+ const key = 'css__${options.name}__' + exposeItemName;
1096
+ window[key] = window[key] || [];
1097
+ window[key].push(href);
1098
+ return;
1099
+ }
1100
+
1101
+ if (href in seen) return;
1102
+ seen[href] = true;
1103
+
1104
+ const element = document.createElement('link');
1105
+ element.rel = 'stylesheet';
1106
+ element.href = href;
1107
+ document.head.appendChild(element);
1108
+ });
1109
+ };
1110
+ async function __federation_import(name) {
1111
+ currentImports[name] ??= import(name)
1112
+ return currentImports[name]
1113
+ };
1114
+ export const get =(module) => {
1115
+ if(!moduleMap[module]) throw new Error('Can not find remote module ' + module)
1116
+ return moduleMap[module]();
1117
+ };
1118
+ export const init =(shareScope) => {
1119
+ globalThis.__federation_shared__= globalThis.__federation_shared__|| {};
1120
+ Object.entries(shareScope).forEach(([key, value]) => {
1121
+ for (const [versionKey, versionValue] of Object.entries(value)) {
1122
+ const scope = versionValue.scope || 'default'
1123
+ globalThis.__federation_shared__[scope] = globalThis.__federation_shared__[scope] || {};
1124
+ const shared= globalThis.__federation_shared__[scope];
1125
+ (shared[key] = shared[key]||{})[versionKey] = versionValue;
1126
+ }
1127
+ });
1128
+ }`
1129
+ },
1130
+ configResolved(config) {
1131
+ if (config) {
1132
+ viteConfigResolved.config = config;
1133
+ }
1134
+ },
1135
+ buildStart() {
1136
+ if (parsedOptions.prodExpose.length > 0) {
1137
+ const assetsDir = builderInfo.assetsDir;
1138
+ this.emitFile({
1139
+ fileName: assetsDir ? `${assetsDir}/${options.filename}` : options.filename,
1140
+ type: "chunk",
1141
+ id: `__remoteEntryHelper__${options.filename}`,
1142
+ preserveSignature: "strict"
1143
+ });
1144
+ }
1145
+ },
1146
+ generateBundle(_options, bundle) {
1147
+ let remoteEntryChunk;
1148
+ for (const file in bundle) {
1149
+ const chunk = bundle[file];
1150
+ if (chunk?.facadeModuleId === `\0virtual:__remoteEntryHelper__${options.filename}`) {
1151
+ remoteEntryChunk = chunk;
1152
+ break;
1153
+ }
1154
+ }
1155
+ if (remoteEntryChunk) {
1156
+ remoteEntryChunk.code = remoteEntryChunk.code.replace(
1157
+ "__VITE_BASE_PLACEHOLDER__",
1158
+ `'${viteConfigResolved.config?.base || ""}'`
1159
+ ).replace(
1160
+ "__VITE_ASSETS_DIR_PLACEHOLDER__",
1161
+ `'${builderInfo.assetsDir || ""}'`
1162
+ );
1163
+ const filepathMap = /* @__PURE__ */ new Map();
1164
+ const getFilename = (name) => parse(parse(name).name).name;
1165
+ const cssBundlesMap = Object.keys(bundle).filter((name) => extname(name) === ".css").reduce((res, name) => {
1166
+ const filename = getFilename(name);
1167
+ res.set(filename, bundle[name]);
1168
+ return res;
1169
+ }, /* @__PURE__ */ new Map());
1170
+ remoteEntryChunk.code = remoteEntryChunk.code.replace(
1171
+ new RegExp(`(["'])${DYNAMIC_LOADING_CSS_PREFIX}.*?\\1`, "g"),
1172
+ (str) => {
1173
+ if (viteConfigResolved.config && !viteConfigResolved.config.build.cssCodeSplit) {
1174
+ if (cssBundlesMap.size) {
1175
+ return `[${[...cssBundlesMap.values()].map(
1176
+ (cssBundle) => JSON.stringify(basename(cssBundle.fileName))
1177
+ ).join(",")}]`;
1178
+ } else {
1179
+ return "[]";
1180
+ }
1181
+ }
1182
+ const filepath = str.slice(
1183
+ (`'` + DYNAMIC_LOADING_CSS_PREFIX).length,
1184
+ -1
1185
+ );
1186
+ if (!filepath || !filepath.length) return str;
1187
+ let fileBundle = filepathMap.get(filepath);
1188
+ if (!fileBundle) {
1189
+ fileBundle = Object.values(bundle).find(
1190
+ (b) => "facadeModuleId" in b && b.facadeModuleId === filepath
1191
+ );
1192
+ if (fileBundle) filepathMap.set(filepath, fileBundle);
1193
+ else return str;
1194
+ }
1195
+ const depCssFiles = /* @__PURE__ */ new Set();
1196
+ const addDepCss = (bundleName) => {
1197
+ const theBundle = bundle[bundleName];
1198
+ if (theBundle && theBundle.viteMetadata) {
1199
+ for (const cssFileName of theBundle.viteMetadata.importedCss.values()) {
1200
+ const cssBundle = cssBundlesMap.get(getFilename(cssFileName));
1201
+ if (cssBundle) {
1202
+ depCssFiles.add(cssBundle.fileName);
1203
+ }
1204
+ }
1205
+ }
1206
+ if (theBundle && theBundle.imports && theBundle.imports.length) {
1207
+ theBundle.imports.forEach((name) => addDepCss(name));
1208
+ }
1209
+ };
1210
+ [fileBundle.fileName, ...fileBundle.imports].forEach(addDepCss);
1211
+ return `[${[...depCssFiles].map((d) => JSON.stringify(basename(d))).join(",")}]`;
1212
+ }
1213
+ );
1214
+ for (const expose of parseExposeOptions(options)) {
1215
+ const module = Object.keys(bundle).find((module2) => {
1216
+ const chunk = bundle[module2];
1217
+ return chunk.name === EXPOSES_KEY_MAP.get(expose[0]);
1218
+ });
1219
+ if (module) {
1220
+ const chunk = bundle[module];
1221
+ const fileRelativePath = relative(
1222
+ dirname(remoteEntryChunk.fileName),
1223
+ chunk.fileName
1224
+ );
1225
+ const slashPath = fileRelativePath.replace(/\\/g, "/");
1226
+ remoteEntryChunk.code = remoteEntryChunk.code.replace(
1227
+ `\${__federation_expose_${expose[0]}}`,
1228
+ viteConfigResolved.config?.base?.replace(/\/+$/, "") ? [
1229
+ viteConfigResolved.config.base.replace(/\/+$/, ""),
1230
+ slashPath
1231
+ ].filter(Boolean).join("/") : `./${slashPath}`
1232
+ );
1233
+ }
1234
+ }
1235
+ let ast = null;
1236
+ try {
1237
+ ast = this.parse(remoteEntryChunk.code);
1238
+ } catch (err) {
1239
+ console.error(err);
1240
+ }
1241
+ if (!ast) {
1242
+ return;
1243
+ }
1244
+ const magicString = new MagicString(remoteEntryChunk.code);
1245
+ walk(ast, {
1246
+ enter(node) {
1247
+ if (node && node.type === "CallExpression" && typeof node.arguments[0]?.value === "string" && node.arguments[0]?.value.indexOf(
1248
+ `${DYNAMIC_LOADING_CSS_PREFIX}`
1249
+ ) > -1) {
1250
+ magicString.remove(node.start, node.end + 1);
1251
+ }
1252
+ }
1253
+ });
1254
+ remoteEntryChunk.code = magicString.toString();
1255
+ }
1256
+ }
1257
+ };
1258
+ }
1259
+ function devSharedPlugin(options) {
1260
+ parsedOptions.devShared = parseSharedOptions(options);
1261
+ return {
1262
+ name: "originjs:shared-development"
1263
+ };
1264
+ }
1265
+ function devRemotePlugin(options) {
1266
+ parsedOptions.devRemote = parseRemoteOptions(options);
1267
+ for (const item of parsedOptions.devRemote) {
1268
+ devRemotes.push({
1269
+ id: item[0],
1270
+ regexp: new RegExp(`^${item[0]}/.+?`),
1271
+ config: item[1]
1272
+ });
1273
+ }
1274
+ const needHandleFileType = [
1275
+ ".js",
1276
+ ".ts",
1277
+ ".jsx",
1278
+ ".tsx",
1279
+ ".mjs",
1280
+ ".cjs",
1281
+ ".vue",
1282
+ ".svelte"
1283
+ ];
1284
+ options.transformFileTypes = (options.transformFileTypes ?? []).concat(needHandleFileType).map((item) => item.toLowerCase());
1285
+ const transformFileTypeSet = new Set(options.transformFileTypes);
1286
+ let viteDevServer;
1287
+ return {
1288
+ name: "originjs:remote-development",
1289
+ virtualFile: options.remotes || options.enableDynamicRemotes ? {
1290
+ __federation__: `
1291
+ ${createRemotesMap(devRemotes)}
1292
+ const loadJS = async (url, fn) => {
1293
+ const resolvedUrl = typeof url === 'function' ? await url() : url;
1294
+ const script = document.createElement('script')
1295
+ script.type = 'text/javascript';
1296
+ script.onload = fn;
1297
+ script.src = resolvedUrl;
1298
+ document.getElementsByTagName('head')[0].appendChild(script);
1299
+ }
1300
+ function get(name, ${REMOTE_FROM_PARAMETER}){
1301
+ return import(/* @vite-ignore */ name).then(module => ()=> {
1302
+ if (${REMOTE_FROM_PARAMETER} === 'webpack') {
1303
+ return Object.prototype.toString.call(module).indexOf('Module') > -1 && module.default ? module.default : module
1304
+ }
1305
+ return module
1306
+ })
1307
+ }
1308
+ const wrapShareScope = ${REMOTE_FROM_PARAMETER} => {
1309
+ return {
1310
+ ${getModuleMarker("shareScope")}
1311
+ }
1312
+ }
1313
+
1314
+ const initMap = Object.create(null);
1315
+ async function __federation_method_ensure(remoteId) {
1316
+ const remote = remotesMap[remoteId];
1317
+ if (!remote.inited) {
1318
+ if ('var' === remote.format) {
1319
+ // loading js with script tag
1320
+ return new Promise(resolve => {
1321
+ const callback = () => {
1322
+ if (!remote.inited) {
1323
+ remote.lib = window[remoteId];
1324
+ remote.lib.init(wrapShareScope(remote.from))
1325
+ remote.inited = true;
1326
+ }
1327
+ resolve(remote.lib);
1328
+ }
1329
+ return loadJS(remote.url, callback);
1330
+ });
1331
+ } else if (['esm', 'systemjs'].includes(remote.format)) {
1332
+ // loading js with import(...)
1333
+ return new Promise((resolve, reject) => {
1334
+ const getUrl = typeof remote.url === 'function' ? remote.url : () => Promise.resolve(remote.url);
1335
+ getUrl().then(url => {
1336
+ import(/* @vite-ignore */ url).then(lib => {
1337
+ if (!remote.inited) {
1338
+ const shareScope = wrapShareScope(remote.from)
1339
+ lib.init(shareScope);
1340
+ remote.lib = lib;
1341
+ remote.lib.init(shareScope);
1342
+ remote.inited = true;
1343
+ }
1344
+ resolve(remote.lib);
1345
+ }).catch(reject)
1346
+ })
1347
+ })
1348
+ }
1349
+ } else {
1350
+ return remote.lib;
1351
+ }
1352
+ }
1353
+
1354
+ function __federation_method_unwrapDefault(module) {
1355
+ return (module?.__esModule || module?.[Symbol.toStringTag] === 'Module')?module.default:module
1356
+ }
1357
+
1358
+ function __federation_method_wrapDefault(module ,need){
1359
+ if (!module?.default && need) {
1360
+ let obj = Object.create(null);
1361
+ obj.default = module;
1362
+ obj.__esModule = true;
1363
+ return obj;
1364
+ }
1365
+ return module;
1366
+ }
1367
+
1368
+ function __federation_method_getRemote(remoteName, componentName){
1369
+ return __federation_method_ensure(remoteName).then((remote) => remote.get(componentName).then(factory => factory()));
1370
+ }
1371
+
1372
+ function __federation_method_setRemote(remoteName, remoteConfig) {
1373
+ remotesMap[remoteName] = remoteConfig;
1374
+ }
1375
+
1376
+ async function __federation_method_add_origin_setRemote(remoteName, remoteUrl, options) {
1377
+ const _options = options || {}
1378
+ const _item = {
1379
+ external: Array.isArray(_options.external) ? _options.external : [_options.external],
1380
+ shareScope: _options.shareScope || 'default',
1381
+ format: _options.format || 'esm',
1382
+ from: _options.from ?? 'vite',
1383
+ externalType: _options.externalType || 'url'
1384
+ }
1385
+
1386
+ __federation_method_setRemote(remoteName, {
1387
+ url: remoteUrl,
1388
+ format: _item.format,
1389
+ from: _item.from
1390
+ })
1391
+ }
1392
+
1393
+ export {__federation_method_ensure, __federation_method_getRemote , __federation_method_setRemote , __federation_method_unwrapDefault , __federation_method_wrapDefault, __federation_method_add_origin_setRemote}
1394
+ ;`
1395
+ } : { __federation__: "" },
1396
+ config(config) {
1397
+ if (parsedOptions.devRemote.length) {
1398
+ const excludeRemotes = [];
1399
+ parsedOptions.devRemote.forEach((item) => excludeRemotes.push(item[0]));
1400
+ let optimizeDeps = config.optimizeDeps;
1401
+ if (!optimizeDeps) {
1402
+ optimizeDeps = config.optimizeDeps = {};
1403
+ }
1404
+ if (!optimizeDeps.exclude) {
1405
+ optimizeDeps.exclude = [];
1406
+ }
1407
+ optimizeDeps.exclude = optimizeDeps.exclude.concat(excludeRemotes);
1408
+ }
1409
+ },
1410
+ configureServer(server) {
1411
+ viteDevServer = server;
1412
+ },
1413
+ async transform(code, id) {
1414
+ if (builderInfo.isHost && !builderInfo.isRemote) {
1415
+ for (const arr of parsedOptions.devShared) {
1416
+ if (!arr[1].version && !arr[1].manuallyPackagePathSetting) {
1417
+ const packageJsonPath = (await this.resolve(`${arr[0]}/package.json`))?.id;
1418
+ if (!packageJsonPath) {
1419
+ this.error(
1420
+ `No description file or no version in description file (usually package.json) of ${arr[0]}(${packageJsonPath}). Add version to description file, or manually specify version in shared config.`
1421
+ );
1422
+ } else {
1423
+ const json = JSON.parse(
1424
+ readFileSync(packageJsonPath, { encoding: "utf-8" })
1425
+ );
1426
+ arr[1].version = json.version;
1427
+ }
1428
+ }
1429
+ }
1430
+ }
1431
+ if (id === "\0virtual:__federation__") {
1432
+ const scopeCode = await devSharedScopeCode.call(
1433
+ this,
1434
+ parsedOptions.devShared
1435
+ );
1436
+ return code.replace(getModuleMarker("shareScope"), scopeCode.join(","));
1437
+ }
1438
+ const fileExtname = getFileExtname(id);
1439
+ if (!transformFileTypeSet.has((fileExtname ?? "").toLowerCase())) {
1440
+ return;
1441
+ }
1442
+ let ast = null;
1443
+ try {
1444
+ ast = this.parse(code);
1445
+ } catch (err) {
1446
+ console.error(err);
1447
+ }
1448
+ if (!ast) {
1449
+ return null;
1450
+ }
1451
+ const magicString = new MagicString(code);
1452
+ const hasStaticImported = /* @__PURE__ */ new Map();
1453
+ let requiresRuntime = false;
1454
+ let manualRequired = null;
1455
+ walk(ast, {
1456
+ enter(node) {
1457
+ if (node.type === "ImportDeclaration" && node.source?.value === "virtual:__federation__") {
1458
+ manualRequired = node;
1459
+ }
1460
+ if ((node.type === "ImportExpression" || node.type === "ImportDeclaration" || node.type === "ExportNamedDeclaration") && node.source?.value?.indexOf("/") > -1) {
1461
+ const moduleId = node.source.value;
1462
+ const remote = devRemotes.find((r) => r.regexp.test(moduleId));
1463
+ const needWrap = remote?.config.from === "vite";
1464
+ if (remote) {
1465
+ requiresRuntime = true;
1466
+ const modName = `.${moduleId.slice(remote.id.length)}`;
1467
+ switch (node.type) {
1468
+ case "ImportExpression": {
1469
+ magicString.overwrite(
1470
+ node.start,
1471
+ node.end,
1472
+ `__federation_method_getRemote(${JSON.stringify(
1473
+ remote.id
1474
+ )} , ${JSON.stringify(
1475
+ modName
1476
+ )}).then(module=>__federation_method_wrapDefault(module, ${needWrap}))`
1477
+ );
1478
+ break;
1479
+ }
1480
+ case "ImportDeclaration": {
1481
+ if (node.specifiers?.length) {
1482
+ const afterImportName = `__federation_var_${moduleId.replace(
1483
+ /[@/\\.-]/g,
1484
+ ""
1485
+ )}`;
1486
+ if (!hasStaticImported.has(moduleId)) {
1487
+ magicString.overwrite(
1488
+ node.start,
1489
+ node.end,
1490
+ `const ${afterImportName} = await __federation_method_getRemote(${JSON.stringify(
1491
+ remote.id
1492
+ )} , ${JSON.stringify(modName)});`
1493
+ );
1494
+ hasStaticImported.set(moduleId, afterImportName);
1495
+ }
1496
+ let deconstructStr = "";
1497
+ node.specifiers.forEach((spec) => {
1498
+ if (spec.type === "ImportDefaultSpecifier") {
1499
+ magicString.appendRight(
1500
+ node.end,
1501
+ `
1502
+ let ${spec.local.name} = __federation_method_unwrapDefault(${afterImportName}) `
1503
+ );
1504
+ } else if (spec.type === "ImportSpecifier") {
1505
+ const importedName = spec.imported.name;
1506
+ const localName = spec.local.name;
1507
+ deconstructStr += `${importedName === localName ? localName : `${importedName} : ${localName}`},`;
1508
+ } else if (spec.type === "ImportNamespaceSpecifier") {
1509
+ magicString.appendRight(
1510
+ node.end,
1511
+ `let {${spec.local.name}} = ${afterImportName}`
1512
+ );
1513
+ }
1514
+ });
1515
+ if (deconstructStr.length > 0) {
1516
+ magicString.appendRight(
1517
+ node.end,
1518
+ `
1519
+ let {${deconstructStr.slice(
1520
+ 0,
1521
+ -1
1522
+ )}} = ${afterImportName}`
1523
+ );
1524
+ }
1525
+ }
1526
+ break;
1527
+ }
1528
+ case "ExportNamedDeclaration": {
1529
+ const afterImportName = `__federation_var_${moduleId.replace(
1530
+ /[@/\\.-]/g,
1531
+ ""
1532
+ )}`;
1533
+ if (!hasStaticImported.has(moduleId)) {
1534
+ hasStaticImported.set(moduleId, afterImportName);
1535
+ magicString.overwrite(
1536
+ node.start,
1537
+ node.end,
1538
+ `const ${afterImportName} = await __federation_method_getRemote(${JSON.stringify(
1539
+ remote.id
1540
+ )} , ${JSON.stringify(modName)});`
1541
+ );
1542
+ }
1543
+ if (node.specifiers.length > 0) {
1544
+ const specifiers = node.specifiers;
1545
+ let exportContent = "";
1546
+ let deconstructContent = "";
1547
+ specifiers.forEach((spec) => {
1548
+ const localName = spec.local.name;
1549
+ const exportName = spec.exported.name;
1550
+ const variableName = `${afterImportName}_${localName}`;
1551
+ deconstructContent = deconstructContent.concat(
1552
+ `${localName}:${variableName},`
1553
+ );
1554
+ exportContent = exportContent.concat(
1555
+ `${variableName} as ${exportName},`
1556
+ );
1557
+ });
1558
+ magicString.append(
1559
+ `
1560
+ const {${deconstructContent.slice(
1561
+ 0,
1562
+ deconstructContent.length - 1
1563
+ )}} = ${afterImportName};
1564
+ `
1565
+ );
1566
+ magicString.append(
1567
+ `
1568
+ export {${exportContent.slice(
1569
+ 0,
1570
+ exportContent.length - 1
1571
+ )}}; `
1572
+ );
1573
+ }
1574
+ break;
1575
+ }
1576
+ }
1577
+ }
1578
+ }
1579
+ }
1580
+ });
1581
+ if (requiresRuntime) {
1582
+ let requiresCode = `import {__federation_method_ensure, __federation_method_getRemote , __federation_method_wrapDefault , __federation_method_unwrapDefault, __federation_method_add_origin_setRemote} from '__federation__';
1583
+
1584
+ `;
1585
+ if (manualRequired) {
1586
+ requiresCode = `import {__federation_method_setRemote, __federation_method_ensure, __federation_method_getRemote , __federation_method_wrapDefault , __federation_method_unwrapDefault, __federation_method_add_origin_setRemote} from '__federation__';
1587
+
1588
+ `;
1589
+ magicString.overwrite(manualRequired.start, manualRequired.end, ``);
1590
+ }
1591
+ magicString.prepend(requiresCode);
1592
+ }
1593
+ return magicString.toString();
1594
+ }
1595
+ };
1596
+ async function devSharedScopeCode(shared) {
1597
+ const res = [];
1598
+ if (shared.length) {
1599
+ const serverConfiguration = viteDevServer.config.server;
1600
+ const base = viteDevServer.config.base;
1601
+ const cwdPath = normalizePath(process.cwd());
1602
+ for (const item of shared) {
1603
+ const moduleInfo = await this.resolve(item[1].packagePath, void 0, {
1604
+ skipSelf: true
1605
+ });
1606
+ if (!moduleInfo) continue;
1607
+ const moduleFilePath = normalizePath(moduleInfo.id);
1608
+ const idx = moduleFilePath.indexOf(cwdPath);
1609
+ const relativePath = idx === 0 ? posix.join(base, moduleFilePath.slice(cwdPath.length)) : null;
1610
+ const sharedName = item[0];
1611
+ const obj = item[1];
1612
+ let str = "";
1613
+ if (typeof obj === "object") {
1614
+ const origin = serverConfiguration.origin;
1615
+ const pathname = relativePath ?? `/@fs/${moduleInfo.id}`;
1616
+ const url = origin ? `'${origin}${pathname}'` : `window.location.origin+'${pathname}'`;
1617
+ str += `get:()=> get(${url}, ${REMOTE_FROM_PARAMETER})`;
1618
+ res.push(`'${sharedName}':{'${obj.version}':{${str}}}`);
1619
+ }
1620
+ }
1621
+ }
1622
+ return res;
1623
+ }
1624
+ }
1625
+ function devExposePlugin(options) {
1626
+ parsedOptions.devExpose = parseExposeOptions(options);
1627
+ return {
1628
+ name: "originjs:expose-development"
1629
+ };
1630
+ }
1631
+ function isVueAvailable() {
1632
+ try {
1633
+ return typeof ref !== "undefined" && typeof onMounted !== "undefined";
1634
+ } catch {
1635
+ return false;
1636
+ }
1637
+ }
1638
+ let ref, onMounted, readonly;
1639
+ if (isVueAvailable()) {
1640
+ try {
1641
+ import("vue").then((vue) => {
1642
+ ref = vue.ref;
1643
+ onMounted = vue.onMounted;
1644
+ readonly = vue.readonly;
1645
+ }).catch(() => {
1646
+ console.warn("Vue not available for dynamic import");
1647
+ });
1648
+ } catch {
1649
+ }
1650
+ }
1651
+ const normalizeAssetsDir = (config) => {
1652
+ const configured = config?.build?.assetsDir ?? "assets";
1653
+ if (!configured) return "";
1654
+ if (!isAbsolute(configured)) return configured;
1655
+ const root = config?.root ? resolve(config.root) : process.cwd();
1656
+ const resolvedOutDir = config?.build?.outDir ? isAbsolute(config.build.outDir) ? config.build.outDir : resolve(root, config.build.outDir) : resolve(root, "dist");
1657
+ const normalized = relative(resolvedOutDir, configured).replace(/\\/g, "/");
1658
+ return normalized.startsWith("..") ? "" : normalized || "assets";
1659
+ };
1660
+ function federation(options) {
1661
+ options.filename = options.filename ? options.filename : DEFAULT_ENTRY_FILENAME;
1662
+ let pluginList = [];
1663
+ let virtualMod;
1664
+ let registerCount = 0;
1665
+ function registerPlugins(mode, command) {
1666
+ if (mode === "production" || command === "build") {
1667
+ pluginList = [
1668
+ prodSharedPlugin(options),
1669
+ prodExposePlugin(options),
1670
+ prodRemotePlugin(options)
1671
+ ];
1672
+ } else if (mode === "development" || command === "serve") {
1673
+ pluginList = [
1674
+ devSharedPlugin(options),
1675
+ devExposePlugin(options),
1676
+ devRemotePlugin(options)
1677
+ ];
1678
+ } else {
1679
+ pluginList = [];
1680
+ }
1681
+ builderInfo.isHost = options.isHost || !!(parsedOptions.prodRemote.length || parsedOptions.devRemote.length);
1682
+ builderInfo.isRemote = !!(parsedOptions.prodExpose.length || parsedOptions.devExpose.length);
1683
+ builderInfo.isShared = !!(parsedOptions.prodShared.length || parsedOptions.devShared.length);
1684
+ let virtualFiles = {};
1685
+ pluginList.forEach((plugin) => {
1686
+ if (plugin.virtualFile) {
1687
+ virtualFiles = Object.assign(virtualFiles, plugin.virtualFile);
1688
+ }
1689
+ });
1690
+ virtualMod = virtual(virtualFiles);
1691
+ }
1692
+ return {
1693
+ name: "originjs:federation",
1694
+ // for scenario vite.config.js build.cssCodeSplit: false
1695
+ // vite:css-post plugin will summarize all the styles in the style.xxxxxx.css file
1696
+ // so, this plugin need run after vite:css-post in post plugin list
1697
+ enforce: "post",
1698
+ // apply:'build',
1699
+ options(_options) {
1700
+ if (!registerCount++) {
1701
+ registerPlugins(options.mode = options.mode ?? "production", "");
1702
+ }
1703
+ if (typeof _options.input === "string") {
1704
+ _options.input = { index: _options.input };
1705
+ }
1706
+ _options.external = _options.external || [];
1707
+ if (!Array.isArray(_options.external)) {
1708
+ _options.external = [_options.external];
1709
+ }
1710
+ for (const pluginHook of pluginList) {
1711
+ pluginHook.options?.call(this, _options);
1712
+ }
1713
+ return _options;
1714
+ },
1715
+ config(config, env) {
1716
+ options.mode = options.mode ?? env.mode;
1717
+ registerPlugins(options.mode, env.command);
1718
+ registerCount++;
1719
+ for (const pluginHook of pluginList) {
1720
+ pluginHook.config?.call(this, config, env);
1721
+ }
1722
+ builderInfo.builder = "vite";
1723
+ builderInfo.assetsDir = normalizeAssetsDir(config) ?? "assets";
1724
+ },
1725
+ configureServer(server) {
1726
+ for (const pluginHook of pluginList) {
1727
+ pluginHook.configureServer?.call(this, server);
1728
+ }
1729
+ },
1730
+ configResolved(config) {
1731
+ for (const pluginHook of pluginList) {
1732
+ pluginHook.configResolved?.call(this, config);
1733
+ }
1734
+ },
1735
+ buildStart(inputOptions) {
1736
+ for (const pluginHook of pluginList) {
1737
+ pluginHook.buildStart?.call(this, inputOptions);
1738
+ }
1739
+ },
1740
+ async resolveId(...args) {
1741
+ const v = virtualMod.resolveId.call(this, ...args);
1742
+ if (v) {
1743
+ return v;
1744
+ }
1745
+ if (args[0] === "\0virtual:__federation_fn_import") {
1746
+ return {
1747
+ id: "\0virtual:__federation_fn_import",
1748
+ moduleSideEffects: true
1749
+ };
1750
+ }
1751
+ if (args[0] === "__federation_fn_satisfy") {
1752
+ const federationId = (await this.resolve("@meethive/vite"))?.id;
1753
+ if (federationId) {
1754
+ return await this.resolve(`${dirname(federationId)}/satisfy.mjs`);
1755
+ }
1756
+ return null;
1757
+ }
1758
+ if (args[0] === "virtual:__federation__") {
1759
+ return {
1760
+ id: "\0virtual:__federation__",
1761
+ moduleSideEffects: true
1762
+ };
1763
+ }
1764
+ return null;
1765
+ },
1766
+ load(...args) {
1767
+ const v = virtualMod.load.call(this, ...args);
1768
+ if (v) {
1769
+ return v;
1770
+ }
1771
+ return null;
1772
+ },
1773
+ transform(code, id) {
1774
+ for (const pluginHook of pluginList) {
1775
+ const result = pluginHook.transform?.call(this, code, id);
1776
+ if (result) {
1777
+ return result;
1778
+ }
1779
+ }
1780
+ return code;
1781
+ },
1782
+ moduleParsed(moduleInfo) {
1783
+ for (const pluginHook of pluginList) {
1784
+ pluginHook.moduleParsed?.call(this, moduleInfo);
1785
+ }
1786
+ },
1787
+ outputOptions(outputOptions) {
1788
+ for (const pluginHook of pluginList) {
1789
+ pluginHook.outputOptions?.call(this, outputOptions);
1790
+ }
1791
+ return outputOptions;
1792
+ },
1793
+ renderChunk(code, chunkInfo, _options) {
1794
+ for (const pluginHook of pluginList) {
1795
+ const result = pluginHook.renderChunk?.call(
1796
+ this,
1797
+ code,
1798
+ chunkInfo,
1799
+ _options
1800
+ );
1801
+ if (result) {
1802
+ return result;
1803
+ }
1804
+ }
1805
+ return null;
1806
+ },
1807
+ generateBundle: function(_options, bundle, isWrite) {
1808
+ for (const pluginHook of pluginList) {
1809
+ pluginHook.generateBundle?.call(this, _options, bundle, isWrite);
1810
+ }
1811
+ }
1812
+ };
1813
+ }
1814
+ const languageWorkAttr = [
1815
+ {
1816
+ label: "editorWorkerService",
1817
+ entry: "monaco-editor/esm/vs/editor/editor.worker"
1818
+ },
1819
+ {
1820
+ label: "css",
1821
+ entry: "monaco-editor/esm/vs/language/css/css.worker"
1822
+ },
1823
+ {
1824
+ label: "html",
1825
+ entry: "monaco-editor/esm/vs/language/html/html.worker"
1826
+ },
1827
+ {
1828
+ label: "json",
1829
+ entry: "monaco-editor/esm/vs/language/json/json.worker"
1830
+ },
1831
+ {
1832
+ label: "typescript",
1833
+ entry: "monaco-editor/esm/vs/language/typescript/ts.worker"
1834
+ }
1835
+ ];
1836
+ const languageWorksByLabel = {};
1837
+ languageWorkAttr.forEach(
1838
+ (languageWork) => languageWorksByLabel[languageWork.label] = languageWork
1839
+ );
1840
+ function getFilenameByEntry(entry) {
1841
+ entry = basename(entry, "js");
1842
+ return entry + ".bundle.js";
1843
+ }
1844
+ const cacheDir = "node_modules/.monaco/";
1845
+ function getWorkPath(works, options, config) {
1846
+ const workerPaths = {};
1847
+ for (const work of works) {
1848
+ if (isCDN(options.publicPath)) {
1849
+ workerPaths[work.label] = options.publicPath + "/" + getFilenameByEntry(work.entry);
1850
+ } else {
1851
+ workerPaths[work.label] = config.base + options.publicPath + "/" + getFilenameByEntry(work.entry);
1852
+ }
1853
+ }
1854
+ if (workerPaths["typescript"]) {
1855
+ workerPaths["javascript"] = workerPaths["typescript"];
1856
+ }
1857
+ if (workerPaths["css"]) {
1858
+ workerPaths["less"] = workerPaths["css"];
1859
+ workerPaths["scss"] = workerPaths["css"];
1860
+ }
1861
+ if (workerPaths["html"]) {
1862
+ workerPaths["handlebars"] = workerPaths["html"];
1863
+ workerPaths["razor"] = workerPaths["html"];
1864
+ }
1865
+ return workerPaths;
1866
+ }
1867
+ function workerMiddleware(middlewares, config, options) {
1868
+ const works = getWorks(options);
1869
+ if (existsSync(cacheDir)) {
1870
+ rmSync(cacheDir, { recursive: true, force: true });
1871
+ }
1872
+ for (const work of works) {
1873
+ middlewares.use(
1874
+ config.base + options.publicPath + "/" + getFilenameByEntry(work.entry),
1875
+ function(req, res, next) {
1876
+ if (!existsSync(cacheDir + getFilenameByEntry(work.entry))) {
1877
+ buildSync({
1878
+ entryPoints: [resolveMonacoPath(work.entry)],
1879
+ bundle: true,
1880
+ outfile: cacheDir + getFilenameByEntry(work.entry)
1881
+ });
1882
+ }
1883
+ const contentBuffer = readFileSync(cacheDir + getFilenameByEntry(work.entry));
1884
+ res.setHeader("Content-Type", "text/javascript");
1885
+ res.end(contentBuffer);
1886
+ }
1887
+ );
1888
+ }
1889
+ }
1890
+ function resolveMonacoPath(filePath) {
1891
+ try {
1892
+ return resolve(join(process.cwd(), "node_modules", filePath));
1893
+ } catch (err) {
1894
+ return resolve(filePath);
1895
+ }
1896
+ }
1897
+ function getWorks(options) {
1898
+ let works = options.languageWorkers.map(
1899
+ (work) => languageWorksByLabel[work]
1900
+ );
1901
+ works.push(...options.customWorkers);
1902
+ return works;
1903
+ }
1904
+ const getFS = async () => {
1905
+ if (typeof process !== "undefined" && process.versions?.node) {
1906
+ const fs = await import("fs");
1907
+ return {
1908
+ existsSync: fs.existsSync,
1909
+ mkdirSync: fs.mkdirSync,
1910
+ readFileSync: fs.readFileSync,
1911
+ writeFileSync: fs.writeFileSync
1912
+ };
1913
+ }
1914
+ return null;
1915
+ };
1916
+ function monacoEditorPlugin(options) {
1917
+ const languageWorkers = options.languageWorkers || Object.keys(languageWorksByLabel);
1918
+ const publicPath = options.publicPath || "monacoeditorwork";
1919
+ const globalAPI = options.globalAPI || false;
1920
+ const customWorkers = options.customWorkers || [];
1921
+ const forceBuildCDN = options.forceBuildCDN || false;
1922
+ options = {
1923
+ ...options,
1924
+ languageWorkers,
1925
+ publicPath,
1926
+ globalAPI,
1927
+ customWorkers,
1928
+ forceBuildCDN
1929
+ };
1930
+ let resolvedConfig;
1931
+ return {
1932
+ name: "vite-plugin-monaco-editor",
1933
+ configResolved(getResolvedConfig) {
1934
+ resolvedConfig = getResolvedConfig;
1935
+ },
1936
+ configureServer(server) {
1937
+ if (isCDN(publicPath)) {
1938
+ return;
1939
+ }
1940
+ workerMiddleware(server.middlewares, resolvedConfig, options);
1941
+ },
1942
+ transformIndexHtml(html) {
1943
+ const works = getWorks(options);
1944
+ const workerPaths = getWorkPath(works, options, resolvedConfig);
1945
+ const globals = {
1946
+ MonacoEnvironment: `(function (paths) {
1947
+ return {
1948
+ globalAPI: ${globalAPI},
1949
+ getWorkerUrl : function (moduleId, label) {
1950
+ var result = paths[label];
1951
+ var _location = window.__MICRO_APP_ENVIRONMENT__ ? window.rawWindow.location : window.location;
1952
+ var currentUrl = String(_location);
1953
+ var currentOrigin = currentUrl.substr(0, currentUrl.length - _location.hash.length - _location.search.length - _location.pathname.length);
1954
+
1955
+ if (window.__MICRO_APP_ENVIRONMENT__) {
1956
+ result = currentOrigin + result.replace('./', '/')
1957
+ }
1958
+
1959
+ if (/^((http:)|(https:)|(file:)|(\\/\\/))/.test(result)) {
1960
+ if (result.substring(0, currentOrigin.length) !== currentOrigin) {
1961
+ var js = '/*' + label + '*/importScripts("' + result + '");';
1962
+ var blob = new Blob([js], { type: 'application/javascript' });
1963
+ return URL.createObjectURL(blob);
1964
+ }
1965
+ }
1966
+ console.log('result',result);
1967
+ return result;
1968
+ }
1969
+ };
1970
+ })(${JSON.stringify(workerPaths, null, 2)})`
1971
+ };
1972
+ const descriptor = [
1973
+ {
1974
+ tag: "script",
1975
+ children: Object.keys(globals).map((key) => `self[${JSON.stringify(key)}] = ${globals[key]};`).join("\n"),
1976
+ injectTo: "head-prepend"
1977
+ }
1978
+ ];
1979
+ return descriptor;
1980
+ },
1981
+ async writeBundle() {
1982
+ if (isCDN(publicPath) && !forceBuildCDN) {
1983
+ return;
1984
+ }
1985
+ const fs = await getFS();
1986
+ if (!fs) {
1987
+ this.warn("File system operations not available in this environment");
1988
+ return;
1989
+ }
1990
+ const works = getWorks(options);
1991
+ const distPath = options.customDistPath ? options.customDistPath(
1992
+ resolvedConfig.root,
1993
+ resolvedConfig.build.outDir,
1994
+ resolvedConfig.base
1995
+ ) : join(
1996
+ resolvedConfig.root,
1997
+ resolvedConfig.build.outDir,
1998
+ resolvedConfig.base,
1999
+ options.publicPath
2000
+ );
2001
+ if (!fs.existsSync(distPath)) {
2002
+ fs.mkdirSync(distPath, {
2003
+ recursive: true
2004
+ });
2005
+ }
2006
+ for (const work of works) {
2007
+ if (!fs.existsSync(cacheDir + getFilenameByEntry(work.entry))) {
2008
+ buildSync({
2009
+ entryPoints: [resolveMonacoPath(work.entry)],
2010
+ bundle: true,
2011
+ outfile: cacheDir + getFilenameByEntry(work.entry)
2012
+ });
2013
+ }
2014
+ const contentBuffer = fs.readFileSync(cacheDir + getFilenameByEntry(work.entry));
2015
+ const workDistPath = resolve(distPath, getFilenameByEntry(work.entry));
2016
+ fs.writeFileSync(workDistPath, contentBuffer);
2017
+ }
2018
+ }
2019
+ };
2020
+ }
2021
+ function isCDN(publicPath) {
2022
+ if (/^((http:)|(https:)|(file:)|(\/\/))/.test(publicPath)) {
2023
+ return true;
2024
+ }
2025
+ return false;
2026
+ }
2027
+ function matches(filename, patterns) {
2028
+ if (!patterns || patterns.length === 0) return true;
2029
+ return patterns.some(
2030
+ (p) => typeof p === "string" ? filename.includes(p) : p.test(filename)
2031
+ );
2032
+ }
2033
+ function sharpOptimize(options = {}) {
2034
+ const {
2035
+ include,
2036
+ exclude,
2037
+ jpegQuality = 75,
2038
+ pngQuality = 75,
2039
+ webpQuality = 75,
2040
+ avifQuality = 50
2041
+ } = options;
2042
+ let _sharp = null;
2043
+ const getSharp = async () => {
2044
+ if (!_sharp) {
2045
+ const sharpModule = await import("sharp");
2046
+ _sharp = sharpModule.default ?? sharpModule;
2047
+ }
2048
+ return _sharp;
2049
+ };
2050
+ const imageExts = /* @__PURE__ */ new Set([".png", ".jpg", ".jpeg", ".webp", ".avif"]);
2051
+ return {
2052
+ name: "jetlinks-sharp-optimize",
2053
+ apply: "build",
2054
+ enforce: "post",
2055
+ async generateBundle(_opts, bundle) {
2056
+ for (const [fileName, asset] of Object.entries(bundle)) {
2057
+ if (asset.type !== "asset") continue;
2058
+ const ext = path$1.extname(fileName).toLowerCase();
2059
+ if (!imageExts.has(ext)) continue;
2060
+ if (exclude && matches(fileName, exclude)) continue;
2061
+ if (include && !matches(fileName, include)) continue;
2062
+ try {
2063
+ const sourceBuffer = Buffer.isBuffer(asset.source) ? asset.source : Buffer.from(String(asset.source));
2064
+ const sharp = await getSharp();
2065
+ let instance = sharp(sourceBuffer);
2066
+ switch (ext) {
2067
+ case ".jpg":
2068
+ case ".jpeg":
2069
+ instance = instance.jpeg({ quality: jpegQuality, mozjpeg: true });
2070
+ break;
2071
+ case ".png":
2072
+ instance = instance.png({ quality: pngQuality, compressionLevel: 9 });
2073
+ break;
2074
+ case ".webp":
2075
+ instance = instance.webp({ quality: webpQuality });
2076
+ break;
2077
+ case ".avif":
2078
+ instance = instance.avif({ quality: avifQuality });
2079
+ break;
2080
+ default:
2081
+ break;
2082
+ }
2083
+ const optimized = await instance.toBuffer();
2084
+ asset.source = optimized;
2085
+ } catch (err) {
2086
+ this.warn(`sharp optimize failed for ${fileName}: ${String(err)}`);
2087
+ }
2088
+ }
2089
+ }
2090
+ };
2091
+ }
2092
+ export {
2093
+ federation,
2094
+ monacoEditorPlugin,
2095
+ sharpOptimize
2096
+ };