@vercel/microfrontends 0.14.0 → 0.15.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 (121) hide show
  1. package/dist/bin/cli.cjs +377 -1626
  2. package/dist/config.cjs +460 -1004
  3. package/dist/config.cjs.map +1 -1
  4. package/dist/config.d.ts +4 -25
  5. package/dist/config.js +456 -983
  6. package/dist/config.js.map +1 -1
  7. package/dist/{v2/microfrontends → microfrontends}/server.cjs +63 -143
  8. package/dist/microfrontends/server.cjs.map +1 -0
  9. package/dist/{v2/microfrontends → microfrontends}/server.d.ts +4 -4
  10. package/dist/{v2/microfrontends → microfrontends}/server.js +63 -143
  11. package/dist/microfrontends/server.js.map +1 -0
  12. package/dist/{v2/microfrontends.cjs → microfrontends.cjs} +21 -21
  13. package/dist/microfrontends.cjs.map +1 -0
  14. package/dist/{v2/microfrontends.d.ts → microfrontends.d.ts} +4 -4
  15. package/dist/{v2/microfrontends.js → microfrontends.js} +20 -20
  16. package/dist/microfrontends.js.map +1 -0
  17. package/dist/next/client.cjs +1 -1
  18. package/dist/next/client.cjs.map +1 -1
  19. package/dist/next/client.js +1 -1
  20. package/dist/next/client.js.map +1 -1
  21. package/dist/next/config.cjs +1323 -1024
  22. package/dist/next/config.cjs.map +1 -1
  23. package/dist/next/config.d.ts +1 -1
  24. package/dist/next/config.js +1327 -1028
  25. package/dist/next/config.js.map +1 -1
  26. package/dist/next/endpoints.cjs +77 -18
  27. package/dist/next/endpoints.cjs.map +1 -1
  28. package/dist/next/endpoints.d.ts +13 -2
  29. package/dist/next/endpoints.js +77 -18
  30. package/dist/next/endpoints.js.map +1 -1
  31. package/dist/next/middleware.cjs +745 -396
  32. package/dist/next/middleware.cjs.map +1 -1
  33. package/dist/next/middleware.d.ts +10 -5
  34. package/dist/next/middleware.js +745 -396
  35. package/dist/next/middleware.js.map +1 -1
  36. package/dist/next/testing.cjs +595 -1032
  37. package/dist/next/testing.cjs.map +1 -1
  38. package/dist/next/testing.d.ts +14 -12
  39. package/dist/next/testing.js +589 -1016
  40. package/dist/next/testing.js.map +1 -1
  41. package/dist/overrides.cjs +40 -108
  42. package/dist/overrides.cjs.map +1 -1
  43. package/dist/overrides.d.ts +24 -2
  44. package/dist/overrides.js +36 -106
  45. package/dist/overrides.js.map +1 -1
  46. package/dist/{v2/routing.cjs → routing.cjs} +3 -3
  47. package/dist/routing.cjs.map +1 -0
  48. package/dist/{v2/schema.cjs → schema.cjs} +1 -1
  49. package/dist/schema.cjs.map +1 -0
  50. package/dist/schema.d.ts +1 -0
  51. package/dist/utils/mfe-port.cjs +211 -1333
  52. package/dist/utils/mfe-port.cjs.map +1 -1
  53. package/dist/utils/mfe-port.js +204 -1326
  54. package/dist/utils/mfe-port.js.map +1 -1
  55. package/dist/validation.cjs +31 -361
  56. package/dist/validation.cjs.map +1 -1
  57. package/dist/validation.d.ts +3 -146
  58. package/dist/validation.js +30 -359
  59. package/dist/validation.js.map +1 -1
  60. package/package.json +29 -92
  61. package/schema/schema.json +174 -244
  62. package/dist/config/client.cjs +0 -54
  63. package/dist/config/client.cjs.map +0 -1
  64. package/dist/config/client.d.ts +0 -23
  65. package/dist/config/client.js +0 -28
  66. package/dist/config/client.js.map +0 -1
  67. package/dist/config/edge.cjs +0 -508
  68. package/dist/config/edge.cjs.map +0 -1
  69. package/dist/config/edge.d.ts +0 -20
  70. package/dist/config/edge.js +0 -481
  71. package/dist/config/edge.js.map +0 -1
  72. package/dist/microfrontend-config-983a5139.d.ts +0 -154
  73. package/dist/schema-2922d49e.d.ts +0 -182
  74. package/dist/v2/config.cjs +0 -709
  75. package/dist/v2/config.cjs.map +0 -1
  76. package/dist/v2/config.d.ts +0 -4
  77. package/dist/v2/config.js +0 -684
  78. package/dist/v2/config.js.map +0 -1
  79. package/dist/v2/microfrontends/server.cjs.map +0 -1
  80. package/dist/v2/microfrontends/server.js.map +0 -1
  81. package/dist/v2/microfrontends.cjs.map +0 -1
  82. package/dist/v2/microfrontends.js.map +0 -1
  83. package/dist/v2/next/client.cjs +0 -3
  84. package/dist/v2/next/client.cjs.map +0 -1
  85. package/dist/v2/next/client.d.ts +0 -45
  86. package/dist/v2/next/client.js +0 -3
  87. package/dist/v2/next/client.js.map +0 -1
  88. package/dist/v2/next/config.cjs +0 -2178
  89. package/dist/v2/next/config.cjs.map +0 -1
  90. package/dist/v2/next/config.d.ts +0 -22
  91. package/dist/v2/next/config.js +0 -2143
  92. package/dist/v2/next/config.js.map +0 -1
  93. package/dist/v2/next/endpoints.cjs +0 -141
  94. package/dist/v2/next/endpoints.cjs.map +0 -1
  95. package/dist/v2/next/endpoints.d.ts +0 -26
  96. package/dist/v2/next/endpoints.js +0 -116
  97. package/dist/v2/next/endpoints.js.map +0 -1
  98. package/dist/v2/next/middleware.cjs +0 -1099
  99. package/dist/v2/next/middleware.cjs.map +0 -1
  100. package/dist/v2/next/middleware.d.ts +0 -34
  101. package/dist/v2/next/middleware.js +0 -1071
  102. package/dist/v2/next/middleware.js.map +0 -1
  103. package/dist/v2/next/testing.cjs +0 -992
  104. package/dist/v2/next/testing.cjs.map +0 -1
  105. package/dist/v2/next/testing.d.ts +0 -55
  106. package/dist/v2/next/testing.js +0 -961
  107. package/dist/v2/next/testing.js.map +0 -1
  108. package/dist/v2/overrides.cjs +0 -75
  109. package/dist/v2/overrides.cjs.map +0 -1
  110. package/dist/v2/overrides.d.ts +0 -24
  111. package/dist/v2/overrides.js +0 -45
  112. package/dist/v2/overrides.js.map +0 -1
  113. package/dist/v2/routing.cjs.map +0 -1
  114. package/dist/v2/schema.cjs.map +0 -1
  115. package/dist/v2/schema.d.ts +0 -1
  116. package/schema/schema-v2.json +0 -266
  117. /package/dist/{v2/routing.d.ts → routing.d.ts} +0 -0
  118. /package/dist/{v2/routing.js → routing.js} +0 -0
  119. /package/dist/{v2/routing.js.map → routing.js.map} +0 -0
  120. /package/dist/{v2/schema.js → schema.js} +0 -0
  121. /package/dist/{v2/schema.js.map → schema.js.map} +0 -0
@@ -1,2178 +0,0 @@
1
- "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __export = (target, all) => {
9
- for (var name in all)
10
- __defProp(target, name, { get: all[name], enumerable: true });
11
- };
12
- var __copyProps = (to, from, except, desc) => {
13
- if (from && typeof from === "object" || typeof from === "function") {
14
- for (let key of __getOwnPropNames(from))
15
- if (!__hasOwnProp.call(to, key) && key !== except)
16
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
- }
18
- return to;
19
- };
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
- // If the importer is in node compatibility mode or this is not an ESM
22
- // file that has been converted to a CommonJS file using a Babel-
23
- // compatible transform (i.e. "__esModule" has not been set), then set
24
- // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
- mod
27
- ));
28
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
-
30
- // src/next-v2/config/index.ts
31
- var config_exports = {};
32
- __export(config_exports, {
33
- withMicrofrontends: () => withMicrofrontends
34
- });
35
- module.exports = __toCommonJS(config_exports);
36
- var import_node_fs8 = __toESM(require("fs"), 1);
37
-
38
- // src/config-v2/microfrontends/server/index.ts
39
- var import_node_fs7 = __toESM(require("fs"), 1);
40
- var import_node_path8 = require("path");
41
-
42
- // src/config-v2/overrides/constants.ts
43
- var OVERRIDES_COOKIE_PREFIX = "vercel-micro-frontends-override";
44
- var OVERRIDES_ENV_COOKIE_PREFIX = `${OVERRIDES_COOKIE_PREFIX}:env:`;
45
-
46
- // src/config-v2/overrides/is-override-cookie.ts
47
- function isOverrideCookie(cookie) {
48
- var _a;
49
- return Boolean((_a = cookie.name) == null ? void 0 : _a.startsWith(OVERRIDES_COOKIE_PREFIX));
50
- }
51
-
52
- // src/config-v2/overrides/get-override-from-cookie.ts
53
- function getOverrideFromCookie(cookie) {
54
- if (!isOverrideCookie(cookie) || !cookie.value)
55
- return;
56
- return {
57
- application: cookie.name.replace(OVERRIDES_ENV_COOKIE_PREFIX, ""),
58
- host: cookie.value
59
- };
60
- }
61
-
62
- // src/config-v2/overrides/parse-overrides.ts
63
- function parseOverrides(cookies) {
64
- const overridesConfig = { applications: {} };
65
- cookies.forEach((cookie) => {
66
- const override = getOverrideFromCookie(cookie);
67
- if (!override)
68
- return;
69
- overridesConfig.applications[override.application] = {
70
- environment: { host: override.host }
71
- };
72
- });
73
- return overridesConfig;
74
- }
75
-
76
- // src/config-v2/errors.ts
77
- var MicrofrontendError = class extends Error {
78
- constructor(message, opts) {
79
- super(message);
80
- this.name = "MicrofrontendsError";
81
- this.source = (opts == null ? void 0 : opts.source) ?? "@vercel/microfrontends";
82
- this.type = (opts == null ? void 0 : opts.type) ?? "unknown";
83
- this.subtype = opts == null ? void 0 : opts.subtype;
84
- Error.captureStackTrace(this, MicrofrontendError);
85
- }
86
- isKnown() {
87
- return this.type !== "unknown";
88
- }
89
- isUnknown() {
90
- return !this.isKnown();
91
- }
92
- /**
93
- * Converts an error to a MicrofrontendsError.
94
- * @param original - The original error to convert.
95
- * @returns The converted MicrofrontendsError.
96
- */
97
- static convert(original, opts) {
98
- if (opts == null ? void 0 : opts.fileName) {
99
- const err = MicrofrontendError.convertFSError(original, opts.fileName);
100
- if (err) {
101
- return err;
102
- }
103
- }
104
- if (original.message.includes(
105
- "Code generation from strings disallowed for this context"
106
- )) {
107
- return new MicrofrontendError(original.message, {
108
- type: "config",
109
- subtype: "unsupported_validation_env",
110
- source: "ajv"
111
- });
112
- }
113
- return new MicrofrontendError(original.message);
114
- }
115
- static convertFSError(original, fileName) {
116
- if (original instanceof Error && "code" in original) {
117
- if (original.code === "ENOENT") {
118
- return new MicrofrontendError(`Could not find "${fileName}"`, {
119
- type: "config",
120
- subtype: "unable_to_read_file",
121
- source: "fs"
122
- });
123
- }
124
- if (original.code === "EACCES") {
125
- return new MicrofrontendError(
126
- `Permission denied while accessing "${fileName}"`,
127
- {
128
- type: "config",
129
- subtype: "invalid_permissions",
130
- source: "fs"
131
- }
132
- );
133
- }
134
- }
135
- if (original instanceof SyntaxError) {
136
- return new MicrofrontendError(
137
- `Failed to parse "${fileName}": Invalid JSON format.`,
138
- {
139
- type: "config",
140
- subtype: "invalid_syntax",
141
- source: "fs"
142
- }
143
- );
144
- }
145
- return null;
146
- }
147
- /**
148
- * Handles an unknown error and returns a MicrofrontendsError instance.
149
- * @param err - The error to handle.
150
- * @returns A MicrofrontendsError instance.
151
- */
152
- static handle(err, opts) {
153
- if (err instanceof MicrofrontendError) {
154
- return err;
155
- }
156
- if (err instanceof Error) {
157
- return MicrofrontendError.convert(err, opts);
158
- }
159
- if (typeof err === "object" && err !== null) {
160
- if ("message" in err && typeof err.message === "string") {
161
- return MicrofrontendError.convert(new Error(err.message), opts);
162
- }
163
- }
164
- return new MicrofrontendError("An unknown error occurred");
165
- }
166
- };
167
-
168
- // src/config-v2/microfrontends-config/utils/get-config-from-env.ts
169
- function getConfigStringFromEnv() {
170
- const config = process.env.MFE_CONFIG;
171
- if (!config) {
172
- throw new MicrofrontendError(`Missing "MFE_CONFIG" in environment.`, {
173
- type: "config",
174
- subtype: "not_found_in_env"
175
- });
176
- }
177
- return config;
178
- }
179
-
180
- // src/config-v2/microfrontends-config/isomorphic/index.ts
181
- var import_jsonc_parser = require("jsonc-parser");
182
-
183
- // src/config-v2/schema/utils/is-main-config.ts
184
- function isMainConfig(c) {
185
- return !("partOf" in c);
186
- }
187
-
188
- // src/config-v2/schema/utils/is-default-app.ts
189
- function isDefaultApp(a) {
190
- return !("routing" in a);
191
- }
192
-
193
- // src/config-v2/microfrontends-config/client/index.ts
194
- var import_path_to_regexp = require("path-to-regexp");
195
- var MicrofrontendConfigClient = class {
196
- constructor(config, opts) {
197
- this.pathCache = {};
198
- this.serialized = config;
199
- if (opts == null ? void 0 : opts.removeFlaggedPaths) {
200
- for (const app of Object.values(config.applications)) {
201
- if (app.routing) {
202
- app.routing = app.routing.filter((match) => !match.flag);
203
- }
204
- }
205
- }
206
- this.applications = config.applications;
207
- }
208
- /**
209
- * Create a new `MicrofrontendConfigClient` from a JSON string.
210
- * Config must be passed in to remain framework agnostic
211
- */
212
- static fromEnv(config, opts) {
213
- if (!config) {
214
- throw new Error("No microfrontends configuration found");
215
- }
216
- return new MicrofrontendConfigClient(
217
- JSON.parse(config),
218
- opts
219
- );
220
- }
221
- isEqual(other) {
222
- return JSON.stringify(this.applications) === JSON.stringify(other.applications);
223
- }
224
- getApplicationNameForPath(path5) {
225
- if (!path5.startsWith("/")) {
226
- throw new Error(`Path must start with a /`);
227
- }
228
- if (this.pathCache[path5]) {
229
- return this.pathCache[path5];
230
- }
231
- const pathname = new URL(path5, "https://example.com").pathname;
232
- for (const [name, application] of Object.entries(this.applications)) {
233
- if (application.routing) {
234
- for (const group of application.routing) {
235
- for (const childPath of group.paths) {
236
- const regexp = (0, import_path_to_regexp.pathToRegexp)(childPath);
237
- if (regexp.test(pathname)) {
238
- this.pathCache[path5] = name;
239
- return name;
240
- }
241
- }
242
- }
243
- }
244
- }
245
- const defaultApplication = Object.entries(this.applications).find(
246
- ([, application]) => application.default
247
- );
248
- if (!defaultApplication) {
249
- return null;
250
- }
251
- this.pathCache[path5] = defaultApplication[0];
252
- return defaultApplication[0];
253
- }
254
- serialize() {
255
- return this.serialized;
256
- }
257
- };
258
-
259
- // src/config-v2/microfrontends-config/isomorphic/validation.ts
260
- var import_path_to_regexp2 = require("path-to-regexp");
261
- var SUPPORTED_VERSIONS = ["2"];
262
- var validateConfigVersion = (version) => {
263
- if (!SUPPORTED_VERSIONS.includes(version)) {
264
- throw new MicrofrontendError(
265
- `Unsupported version: ${version}. Supported versions are: ${SUPPORTED_VERSIONS.join(
266
- ", "
267
- )}`,
268
- { type: "config", subtype: "unsupported_version" }
269
- );
270
- }
271
- };
272
- var validateConfigPaths = (applicationConfigsById) => {
273
- if (!applicationConfigsById) {
274
- return;
275
- }
276
- const pathsByApplicationId = /* @__PURE__ */ new Map();
277
- const errors = [];
278
- for (const [id, app] of Object.entries(applicationConfigsById)) {
279
- if (isDefaultApp(app)) {
280
- continue;
281
- }
282
- for (const pathMatch of app.routing) {
283
- for (const path5 of pathMatch.paths) {
284
- const tokens = (0, import_path_to_regexp2.parse)(path5);
285
- for (const token of tokens.slice(0, -1)) {
286
- if (typeof token !== "string") {
287
- errors.push(
288
- `Path ${path5} may only have a :wildcard in the last path component`
289
- );
290
- }
291
- }
292
- const existing = pathsByApplicationId.get(path5);
293
- if (existing) {
294
- existing.applications.push(id);
295
- } else {
296
- pathsByApplicationId.set(path5, {
297
- applications: [id],
298
- matcher: (0, import_path_to_regexp2.pathToRegexp)(path5),
299
- applicationId: id
300
- });
301
- }
302
- }
303
- }
304
- }
305
- const entries = Array.from(pathsByApplicationId.entries());
306
- entries.forEach(([path5, { applications: ids, matcher, applicationId }]) => {
307
- if (ids.length > 1) {
308
- errors.push(
309
- `Duplicate path "${path5}" for applications "${ids.join(", ")}"`
310
- );
311
- }
312
- entries.forEach(
313
- ([
314
- matchPath,
315
- { applications: matchIds, applicationId: matchApplicationId }
316
- ]) => {
317
- if (path5 === matchPath) {
318
- return;
319
- }
320
- if (applicationId === matchApplicationId) {
321
- return;
322
- }
323
- if (matcher.test(matchPath)) {
324
- const source = `"${path5}" of application${ids.length > 0 ? "s" : ""} ${ids.join(", ")}`;
325
- const destination = `"${matchPath}" of application${matchIds.length > 0 ? "s" : ""} ${matchIds.join(", ")}`;
326
- errors.push(
327
- `Overlapping path detected between ${source} and ${destination}`
328
- );
329
- }
330
- }
331
- );
332
- });
333
- if (errors.length) {
334
- throw new MicrofrontendError(`Invalid paths: ${errors.join(", ")}`, {
335
- type: "config",
336
- subtype: "conflicting_paths"
337
- });
338
- }
339
- };
340
- var validateAppPaths = (name, app) => {
341
- for (const group of app.routing) {
342
- for (const p of group.paths) {
343
- if (p === "/") {
344
- continue;
345
- }
346
- if (p.endsWith("/")) {
347
- throw new MicrofrontendError(
348
- `Invalid path for application "${name}". ${p} must not end with a slash.`,
349
- { type: "application", subtype: "invalid_path" }
350
- );
351
- }
352
- if (!p.startsWith("/")) {
353
- throw new MicrofrontendError(
354
- `Invalid path for application "${name}". ${p} must start with a slash.`,
355
- { type: "application", subtype: "invalid_path" }
356
- );
357
- }
358
- }
359
- }
360
- };
361
- var validateConfigDefaultApplication = (applicationConfigsById) => {
362
- if (!applicationConfigsById) {
363
- return;
364
- }
365
- const applicationsWithRouting = Object.entries(applicationConfigsById).filter(
366
- ([, app]) => !isDefaultApp(app)
367
- );
368
- const applicationsWithRoutingNames = applicationsWithRouting.map(
369
- ([key]) => key
370
- );
371
- const numApplications = Object.keys(applicationConfigsById).length;
372
- const numApplicationsWithRouting = applicationsWithRoutingNames.length;
373
- const numApplicationsWithoutRouting = numApplications - numApplicationsWithRouting;
374
- if (numApplicationsWithoutRouting === 0) {
375
- throw new MicrofrontendError(
376
- `No default application found. At least one application needs to be the default by omitting routing.`,
377
- { type: "config", subtype: "no_default_application" }
378
- );
379
- }
380
- if (numApplicationsWithoutRouting > 1) {
381
- throw new MicrofrontendError(
382
- `Only one application can omit "routing". Found ${applicationsWithRoutingNames.length - Object.keys(applicationConfigsById).length > 1}.`,
383
- { type: "config", subtype: "multiple_default_applications" }
384
- );
385
- }
386
- };
387
-
388
- // src/config-v2/microfrontends-config/isomorphic/utils/generate-asset-prefix.ts
389
- var PREFIX = "vc-ap";
390
- function generateAssetPrefixFromName({
391
- name
392
- }) {
393
- if (!name) {
394
- throw new Error("Name is required to generate an asset prefix");
395
- }
396
- return `${PREFIX}-${name}`;
397
- }
398
-
399
- // src/config-v2/microfrontends-config/isomorphic/utils/generate-port.ts
400
- function generatePortFromName({
401
- name,
402
- minPort = 3e3,
403
- maxPort = 8e3
404
- }) {
405
- if (!name) {
406
- throw new Error("Name is required to generate a port");
407
- }
408
- let hash = 0;
409
- for (let i = 0; i < name.length; i++) {
410
- hash = (hash << 5) - hash + name.charCodeAt(i);
411
- hash |= 0;
412
- }
413
- hash = Math.abs(hash);
414
- const range = maxPort - minPort;
415
- const port = minPort + hash % range;
416
- return port;
417
- }
418
-
419
- // src/config-v2/microfrontends-config/isomorphic/host.ts
420
- var Host = class {
421
- constructor(hostConfig, options) {
422
- const { protocol = "https", host, port } = hostConfig;
423
- this.protocol = protocol;
424
- this.host = host;
425
- this.port = Host.getPort({ port, protocol: this.protocol });
426
- this.local = options == null ? void 0 : options.isLocal;
427
- }
428
- isLocal() {
429
- return this.local || this.host === "localhost" || this.host === "127.0.0.1";
430
- }
431
- static getPort({
432
- protocol,
433
- port
434
- }) {
435
- if (!port) {
436
- if (protocol === "http") {
437
- return 80;
438
- }
439
- return 443;
440
- }
441
- return port;
442
- }
443
- isDefaultPort() {
444
- return this.port === Host.getPort({ protocol: this.protocol });
445
- }
446
- toString(opts = {}) {
447
- const url = this.toUrl(opts);
448
- return url.toString().replace(/\/$/, "");
449
- }
450
- toUrl(opts = {}) {
451
- const { includeDefaultPort } = opts;
452
- const url = `${this.protocol}://${this.host}${this.isDefaultPort() && !includeDefaultPort ? "" : `:${this.port}`}`;
453
- return new URL(url);
454
- }
455
- };
456
- var LocalHost = class extends Host {
457
- constructor({
458
- appName,
459
- ...hostConfig
460
- }) {
461
- const host = hostConfig.host ?? "localhost";
462
- const port = hostConfig.port ?? generatePortFromName({ name: appName });
463
- const protocol = hostConfig.protocol ?? "http";
464
- super({ protocol, host, port });
465
- }
466
- };
467
-
468
- // src/config-v2/microfrontends-config/isomorphic/application.ts
469
- var Application = class {
470
- constructor(name, {
471
- app,
472
- overrides,
473
- isDefault
474
- }) {
475
- var _a, _b;
476
- this.name = name;
477
- this.development = {
478
- local: new LocalHost({
479
- appName: name,
480
- ...(_a = app.development) == null ? void 0 : _a.local
481
- }),
482
- fallback: ((_b = app.development) == null ? void 0 : _b.fallback) ? new Host(app.development.fallback) : void 0
483
- };
484
- this.production = app.production ? new Host(app.production) : void 0;
485
- this.vercel = app.vercel;
486
- this.overrides = (overrides == null ? void 0 : overrides.environment) ? {
487
- environment: new Host(overrides.environment)
488
- } : void 0;
489
- this.default = isDefault ?? false;
490
- this.serialized = app;
491
- }
492
- isDefault() {
493
- return this.default;
494
- }
495
- getAssetPrefix() {
496
- return generateAssetPrefixFromName({ name: this.name });
497
- }
498
- serialize() {
499
- return this.serialized;
500
- }
501
- };
502
- var DefaultApplication = class extends Application {
503
- constructor(name, {
504
- app,
505
- overrides
506
- }) {
507
- super(name, {
508
- app,
509
- overrides,
510
- isDefault: true
511
- });
512
- this.default = true;
513
- this.production = new Host(app.production);
514
- }
515
- getAssetPrefix() {
516
- return "";
517
- }
518
- };
519
- var ChildApplication = class extends Application {
520
- constructor(name, {
521
- app,
522
- overrides
523
- }) {
524
- ChildApplication.validate(name, app);
525
- super(name, {
526
- app,
527
- overrides,
528
- isDefault: false
529
- });
530
- this.default = false;
531
- this.routing = app.routing;
532
- }
533
- static validate(name, app) {
534
- validateAppPaths(name, app);
535
- }
536
- };
537
-
538
- // src/config-v2/microfrontends-config/isomorphic/constants.ts
539
- var DEFAULT_LOCAL_PROXY_PORT = 3024;
540
-
541
- // src/config-v2/microfrontends-config/isomorphic/index.ts
542
- var MicrofrontendConfigIsomorphic = class {
543
- constructor({
544
- config,
545
- overrides,
546
- meta
547
- }) {
548
- this.childApplications = {};
549
- var _a, _b, _c, _d;
550
- MicrofrontendConfigIsomorphic.validate(config);
551
- const disableOverrides = ((_b = (_a = config.options) == null ? void 0 : _a.vercel) == null ? void 0 : _b.disableOverrides) ?? false;
552
- this.overrides = overrides && !disableOverrides ? overrides : void 0;
553
- this.isMainConfig = isMainConfig(config);
554
- if (isMainConfig(config)) {
555
- for (const [appId, appConfig] of Object.entries(config.applications)) {
556
- const appOverrides = !disableOverrides ? (_c = this.overrides) == null ? void 0 : _c.applications[appId] : void 0;
557
- if (isDefaultApp(appConfig)) {
558
- this.defaultApplication = new DefaultApplication(appId, {
559
- app: appConfig,
560
- overrides: appOverrides
561
- });
562
- } else {
563
- this.childApplications[appId] = new ChildApplication(appId, {
564
- app: appConfig,
565
- overrides: appOverrides
566
- });
567
- }
568
- }
569
- } else {
570
- this.partOf = config.partOf;
571
- const appOverrides = !disableOverrides ? (_d = this.overrides) == null ? void 0 : _d.applications[meta.fromApp] : void 0;
572
- this.childApplications[meta.fromApp] = new ChildApplication(
573
- meta.fromApp,
574
- {
575
- // we don't know routing because we're not in the main config
576
- app: { routing: [] },
577
- overrides: appOverrides
578
- }
579
- );
580
- }
581
- if (isMainConfig(config) && !this.defaultApplication) {
582
- throw new MicrofrontendError(
583
- `Could not find default application in microfrontends configuration`,
584
- {
585
- type: "application",
586
- subtype: "not_found"
587
- }
588
- );
589
- }
590
- this.config = config;
591
- this.options = config.options;
592
- this.serialized = {
593
- config,
594
- overrides,
595
- meta
596
- };
597
- }
598
- static validate(config) {
599
- const c = typeof config === "string" ? (0, import_jsonc_parser.parse)(config) : config;
600
- if (isMainConfig(c)) {
601
- validateConfigVersion(c.version);
602
- validateConfigPaths(c.applications);
603
- validateConfigDefaultApplication(c.applications);
604
- }
605
- return c;
606
- }
607
- static fromEnv({
608
- meta,
609
- cookies
610
- }) {
611
- return new MicrofrontendConfigIsomorphic({
612
- config: (0, import_jsonc_parser.parse)(getConfigStringFromEnv()),
613
- overrides: parseOverrides(cookies ?? []),
614
- meta
615
- });
616
- }
617
- isOverridesDisabled() {
618
- var _a, _b;
619
- return ((_b = (_a = this.options) == null ? void 0 : _a.vercel) == null ? void 0 : _b.disableOverrides) ?? false;
620
- }
621
- getConfig() {
622
- return this.config;
623
- }
624
- getApplicationsByType() {
625
- return {
626
- defaultApplication: this.defaultApplication,
627
- applications: Object.values(this.childApplications)
628
- };
629
- }
630
- getChildApplications() {
631
- return Object.values(this.childApplications);
632
- }
633
- getAllApplications() {
634
- return [
635
- this.defaultApplication,
636
- ...Object.values(this.childApplications)
637
- ].filter(Boolean);
638
- }
639
- getApplication(name) {
640
- var _a;
641
- if (((_a = this.defaultApplication) == null ? void 0 : _a.name) === name) {
642
- return this.defaultApplication;
643
- }
644
- const app = this.childApplications[name];
645
- if (!app) {
646
- throw new MicrofrontendError(
647
- `Could not find microfrontends configuration for application "${name}"`,
648
- {
649
- type: "application",
650
- subtype: "not_found"
651
- }
652
- );
653
- }
654
- return app;
655
- }
656
- getApplicationByProjectId(projectId) {
657
- var _a, _b;
658
- if (((_b = (_a = this.defaultApplication) == null ? void 0 : _a.vercel) == null ? void 0 : _b.projectId) === projectId) {
659
- return this.defaultApplication;
660
- }
661
- return Object.values(this.childApplications).find(
662
- (app) => {
663
- var _a2;
664
- return ((_a2 = app.vercel) == null ? void 0 : _a2.projectId) === projectId;
665
- }
666
- );
667
- }
668
- /**
669
- * Returns the default application. This can throw if the default application
670
- * is undefined ( )
671
- */
672
- getDefaultApplication() {
673
- if (!this.defaultApplication) {
674
- throw new MicrofrontendError(
675
- `Could not find default application in microfrontends configuration`,
676
- {
677
- type: "application",
678
- subtype: "not_found"
679
- }
680
- );
681
- }
682
- return this.defaultApplication;
683
- }
684
- /**
685
- * Returns the configured port for the local proxy
686
- */
687
- getLocalProxyPort() {
688
- var _a, _b;
689
- return ((_b = (_a = this.config.options) == null ? void 0 : _a.localProxy) == null ? void 0 : _b.port) ?? DEFAULT_LOCAL_PROXY_PORT;
690
- }
691
- /**
692
- * Serializes the class back to the Schema type.
693
- *
694
- * NOTE: This is used when writing the config to disk and must always match the input Schema
695
- */
696
- toSchemaJson() {
697
- return this.serialized.config;
698
- }
699
- toClientConfig() {
700
- const applications = Object.fromEntries(
701
- Object.entries(this.childApplications).map(([name, application]) => [
702
- name,
703
- {
704
- default: false,
705
- routing: application.routing
706
- }
707
- ])
708
- );
709
- if (this.defaultApplication) {
710
- applications[this.defaultApplication.name] = {
711
- default: true
712
- };
713
- }
714
- return new MicrofrontendConfigClient({
715
- applications
716
- });
717
- }
718
- serialize() {
719
- return this.serialized;
720
- }
721
- };
722
-
723
- // src/config-v2/microfrontends-config/isomorphic/child.ts
724
- var MicrofrontendChildConfig = class extends MicrofrontendConfigIsomorphic {
725
- constructor({
726
- config,
727
- overrides,
728
- meta
729
- }) {
730
- super({ config, overrides, meta });
731
- this.isMainConfig = false;
732
- this.partOf = config.partOf;
733
- }
734
- };
735
-
736
- // src/config-v2/microfrontends-config/isomorphic/main.ts
737
- var MicrofrontendMainConfig = class extends MicrofrontendConfigIsomorphic {
738
- constructor({
739
- config,
740
- overrides,
741
- meta
742
- }) {
743
- var _a, _b, _c;
744
- super({ config, overrides, meta });
745
- this.isMainConfig = true;
746
- const disableOverrides = ((_b = (_a = config.options) == null ? void 0 : _a.vercel) == null ? void 0 : _b.disableOverrides) ?? false;
747
- let defaultApplication;
748
- for (const [appId, appConfig] of Object.entries(config.applications)) {
749
- const appOverrides = !disableOverrides ? (_c = this.overrides) == null ? void 0 : _c.applications[appId] : void 0;
750
- if (isDefaultApp(appConfig)) {
751
- defaultApplication = new DefaultApplication(appId, {
752
- app: appConfig,
753
- overrides: appOverrides
754
- });
755
- } else {
756
- this.childApplications[appId] = new ChildApplication(appId, {
757
- app: appConfig,
758
- overrides: appOverrides
759
- });
760
- }
761
- }
762
- if (!defaultApplication) {
763
- throw new MicrofrontendError(
764
- `Could not find default application in microfrontends configuration`,
765
- {
766
- type: "application",
767
- subtype: "not_found"
768
- }
769
- );
770
- }
771
- this.defaultApplication = defaultApplication;
772
- }
773
- };
774
-
775
- // src/config-v2/microfrontends/isomorphic/index.ts
776
- var Microfrontends = class {
777
- constructor({
778
- config,
779
- overrides,
780
- meta
781
- }) {
782
- if (isMainConfig(config)) {
783
- this.config = new MicrofrontendMainConfig({ config, overrides, meta });
784
- } else {
785
- this.config = new MicrofrontendChildConfig({ config, overrides, meta });
786
- }
787
- }
788
- isChildConfig() {
789
- return this.config instanceof MicrofrontendChildConfig;
790
- }
791
- static fromEnv({
792
- cookies,
793
- meta
794
- }) {
795
- const config = MicrofrontendConfigIsomorphic.fromEnv({
796
- cookies,
797
- meta
798
- });
799
- return new Microfrontends(config.serialize());
800
- }
801
- };
802
-
803
- // src/config-v2/microfrontends/utils/find-repository-root.ts
804
- var import_node_fs = __toESM(require("fs"), 1);
805
- var import_node_path = __toESM(require("path"), 1);
806
- var GIT_DIRECTORY = ".git";
807
- function findRepositoryRoot(startDir) {
808
- let currentDir = startDir || process.cwd();
809
- while (currentDir !== import_node_path.default.parse(currentDir).root) {
810
- const gitPath = import_node_path.default.join(currentDir, GIT_DIRECTORY);
811
- if (import_node_fs.default.existsSync(gitPath) && import_node_fs.default.statSync(gitPath).isDirectory()) {
812
- return currentDir;
813
- }
814
- currentDir = import_node_path.default.dirname(currentDir);
815
- }
816
- throw new Error(
817
- "Repository root not found. Specify the root of the repository with the `repository.root` option."
818
- );
819
- }
820
-
821
- // src/config-v2/microfrontends/utils/find-package-path.ts
822
- var import_node_path2 = require("path");
823
- var import_node_fs2 = require("fs");
824
- var import_fast_glob = __toESM(require("fast-glob"), 1);
825
- var configCache = {};
826
- function findPackagePathWithGlob({
827
- repositoryRoot,
828
- name
829
- }) {
830
- try {
831
- const packageJsonPaths = import_fast_glob.default.globSync("**/package.json", {
832
- cwd: repositoryRoot,
833
- absolute: true,
834
- onlyFiles: true,
835
- followSymbolicLinks: false,
836
- ignore: ["**/node_modules/**", "**/.git/**"]
837
- });
838
- const matchingPaths = [];
839
- for (const packageJsonPath2 of packageJsonPaths) {
840
- const packageJsonContent = (0, import_node_fs2.readFileSync)(packageJsonPath2, "utf-8");
841
- const packageJson = JSON.parse(packageJsonContent);
842
- if (packageJson.name === name) {
843
- matchingPaths.push(packageJsonPath2);
844
- }
845
- }
846
- if (matchingPaths.length > 1) {
847
- throw new Error(
848
- `Found multiple packages with the name "${name}" in the repository: ${matchingPaths.join(", ")}`
849
- );
850
- }
851
- if (matchingPaths.length === 0) {
852
- throw new Error(
853
- `Could not find package with the name "${name}" in the repository`
854
- );
855
- }
856
- const [packageJsonPath] = matchingPaths;
857
- return (0, import_node_path2.dirname)(packageJsonPath);
858
- } catch (error) {
859
- return null;
860
- }
861
- }
862
- function findPackagePath(opts) {
863
- const cacheKey = `${opts.repositoryRoot}-${opts.name}`;
864
- if (configCache[cacheKey]) {
865
- return configCache[cacheKey];
866
- }
867
- const result = findPackagePathWithGlob(opts);
868
- if (!result) {
869
- throw new Error(
870
- `Could not find package with the name "${opts.name}" in the repository`
871
- );
872
- }
873
- configCache[cacheKey] = result;
874
- return result;
875
- }
876
-
877
- // src/config-v2/microfrontends/utils/find-default-package.ts
878
- var import_node_path3 = require("path");
879
- var import_node_fs3 = require("fs");
880
- var import_jsonc_parser2 = require("jsonc-parser");
881
- var import_fast_glob2 = __toESM(require("fast-glob"), 1);
882
-
883
- // src/config-v2/constants.ts
884
- var CONFIGURATION_FILENAMES = [
885
- "microfrontends.jsonc",
886
- "microfrontends.json"
887
- ];
888
-
889
- // src/config-v2/microfrontends/utils/find-default-package.ts
890
- var configCache2 = {};
891
- function findDefaultMicrofrontendsPackages({
892
- repositoryRoot,
893
- applicationName
894
- }) {
895
- try {
896
- const microfrontendsJsonPaths = import_fast_glob2.default.globSync(
897
- `**/{${CONFIGURATION_FILENAMES.join(",")}}`,
898
- {
899
- cwd: repositoryRoot,
900
- absolute: true,
901
- onlyFiles: true,
902
- followSymbolicLinks: false,
903
- ignore: ["**/node_modules/**", "**/.git/**"]
904
- }
905
- );
906
- const matchingPaths = [];
907
- for (const microfrontendsJsonPath of microfrontendsJsonPaths) {
908
- const microfrontendsJsonContent = (0, import_node_fs3.readFileSync)(
909
- microfrontendsJsonPath,
910
- "utf-8"
911
- );
912
- const microfrontendsJson = (0, import_jsonc_parser2.parse)(microfrontendsJsonContent);
913
- if (isMainConfig(microfrontendsJson) && microfrontendsJson.applications[applicationName]) {
914
- matchingPaths.push(microfrontendsJsonPath);
915
- }
916
- }
917
- if (matchingPaths.length > 1) {
918
- throw new Error(
919
- `Found multiple default applications referencing "${applicationName}" in the repository, this is not yet supported.
920
- ${matchingPaths.join("\n \u2022 ")}`
921
- );
922
- }
923
- if (matchingPaths.length === 0) {
924
- throw new Error(
925
- `Could not find default application with "applications.${applicationName}"`
926
- );
927
- }
928
- const [packageJsonPath] = matchingPaths;
929
- return (0, import_node_path3.dirname)(packageJsonPath);
930
- } catch (error) {
931
- return null;
932
- }
933
- }
934
- function findDefaultMicrofrontendsPackage(opts) {
935
- const cacheKey = `${opts.repositoryRoot}-${opts.applicationName}`;
936
- if (configCache2[cacheKey]) {
937
- return configCache2[cacheKey];
938
- }
939
- const result = findDefaultMicrofrontendsPackages(opts);
940
- if (!result) {
941
- throw new Error(
942
- `Error trying to resolve the main microfrontends configuration`
943
- );
944
- }
945
- configCache2[cacheKey] = result;
946
- return result;
947
- }
948
-
949
- // src/config-v2/microfrontends/utils/is-monorepo.ts
950
- var import_node_fs4 = __toESM(require("fs"), 1);
951
- var import_node_path4 = __toESM(require("path"), 1);
952
- function isMonorepo({
953
- repositoryRoot
954
- }) {
955
- try {
956
- if (import_node_fs4.default.existsSync(import_node_path4.default.join(repositoryRoot, "pnpm-workspace.yaml"))) {
957
- return true;
958
- }
959
- if (import_node_fs4.default.existsSync(import_node_path4.default.join(repositoryRoot, "vlt-workspaces.json"))) {
960
- return true;
961
- }
962
- const packageJsonPath = import_node_path4.default.join(repositoryRoot, "package.json");
963
- if (!import_node_fs4.default.existsSync(packageJsonPath)) {
964
- return false;
965
- }
966
- const packageJson = JSON.parse(
967
- import_node_fs4.default.readFileSync(packageJsonPath, "utf-8")
968
- );
969
- return packageJson.workspaces !== void 0;
970
- } catch (error) {
971
- console.error("Error determining if repository is a monorepo", error);
972
- return false;
973
- }
974
- }
975
-
976
- // src/config-v2/microfrontends/utils/find-package-root.ts
977
- var import_node_fs5 = __toESM(require("fs"), 1);
978
- var import_node_path5 = __toESM(require("path"), 1);
979
- var PACKAGE_JSON = "package.json";
980
- function findPackageRoot(startDir) {
981
- let currentDir = startDir || process.cwd();
982
- while (currentDir !== import_node_path5.default.parse(currentDir).root) {
983
- const pkgJsonPath = import_node_path5.default.join(currentDir, PACKAGE_JSON);
984
- if (import_node_fs5.default.existsSync(pkgJsonPath)) {
985
- return currentDir;
986
- }
987
- currentDir = import_node_path5.default.dirname(currentDir);
988
- }
989
- throw new Error(
990
- "Package root not found. Specify the root of the package with the `package.root` option."
991
- );
992
- }
993
-
994
- // src/config-v2/microfrontends/utils/find-config.ts
995
- var import_node_fs6 = __toESM(require("fs"), 1);
996
- var import_node_path6 = require("path");
997
- function findConfig({ dir }) {
998
- for (const filename of CONFIGURATION_FILENAMES) {
999
- const maybeConfig = (0, import_node_path6.join)(dir, filename);
1000
- if (import_node_fs6.default.existsSync(maybeConfig)) {
1001
- return maybeConfig;
1002
- }
1003
- }
1004
- return null;
1005
- }
1006
-
1007
- // src/config-v2/microfrontends/server/utils/get-output-file-path.ts
1008
- var import_node_path7 = __toESM(require("path"), 1);
1009
-
1010
- // src/config-v2/microfrontends/server/constants.ts
1011
- var MFE_CONFIG_DEFAULT_FILE_PATH = "microfrontends";
1012
- var MFE_CONFIG_DEFAULT_FILE_NAME = "microfrontends.json";
1013
-
1014
- // src/utils/is-vercel.ts
1015
- function isVercel() {
1016
- return process.env.VERCEL === "1";
1017
- }
1018
-
1019
- // src/config-v2/microfrontends/server/utils/get-output-file-path.ts
1020
- function getOutputFilePath() {
1021
- if (isVercel()) {
1022
- return import_node_path7.default.join(
1023
- ".vercel",
1024
- MFE_CONFIG_DEFAULT_FILE_PATH,
1025
- MFE_CONFIG_DEFAULT_FILE_NAME
1026
- );
1027
- }
1028
- return import_node_path7.default.join(MFE_CONFIG_DEFAULT_FILE_PATH, MFE_CONFIG_DEFAULT_FILE_NAME);
1029
- }
1030
-
1031
- // src/config-v2/microfrontends/server/validation.ts
1032
- var import_jsonc_parser3 = require("jsonc-parser");
1033
- var import_ajv = require("ajv");
1034
-
1035
- // src/config/errors.ts
1036
- var MicrofrontendError2 = class extends Error {
1037
- constructor(message, opts) {
1038
- super(message);
1039
- this.name = "MicrofrontendsError";
1040
- this.source = (opts == null ? void 0 : opts.source) ?? "@vercel/microfrontends";
1041
- this.type = (opts == null ? void 0 : opts.type) ?? "unknown";
1042
- this.subtype = opts == null ? void 0 : opts.subtype;
1043
- Error.captureStackTrace(this, MicrofrontendError2);
1044
- }
1045
- isKnown() {
1046
- return this.type !== "unknown";
1047
- }
1048
- isUnknown() {
1049
- return !this.isKnown();
1050
- }
1051
- /**
1052
- * Converts an error to a MicrofrontendsError.
1053
- * @param original - The original error to convert.
1054
- * @returns The converted MicrofrontendsError.
1055
- */
1056
- static convert(original, opts) {
1057
- if (opts == null ? void 0 : opts.fileName) {
1058
- const err = MicrofrontendError2.convertFSError(original, opts.fileName);
1059
- if (err) {
1060
- return err;
1061
- }
1062
- }
1063
- if (original.message.includes(
1064
- "Code generation from strings disallowed for this context"
1065
- )) {
1066
- return new MicrofrontendError2(original.message, {
1067
- type: "config",
1068
- subtype: "unsupported_validation_env",
1069
- source: "ajv"
1070
- });
1071
- }
1072
- return new MicrofrontendError2(original.message);
1073
- }
1074
- static convertFSError(original, fileName) {
1075
- if (original instanceof Error && "code" in original) {
1076
- if (original.code === "ENOENT") {
1077
- return new MicrofrontendError2(`Could not find "${fileName}"`, {
1078
- type: "config",
1079
- subtype: "unable_to_read_file",
1080
- source: "fs"
1081
- });
1082
- }
1083
- if (original.code === "EACCES") {
1084
- return new MicrofrontendError2(
1085
- `Permission denied while accessing "${fileName}"`,
1086
- {
1087
- type: "config",
1088
- subtype: "invalid_permissions",
1089
- source: "fs"
1090
- }
1091
- );
1092
- }
1093
- }
1094
- if (original instanceof SyntaxError) {
1095
- return new MicrofrontendError2(
1096
- `Failed to parse "${fileName}": Invalid JSON format.`,
1097
- {
1098
- type: "config",
1099
- subtype: "invalid_syntax",
1100
- source: "fs"
1101
- }
1102
- );
1103
- }
1104
- return null;
1105
- }
1106
- /**
1107
- * Handles an unknown error and returns a MicrofrontendsError instance.
1108
- * @param err - The error to handle.
1109
- * @returns A MicrofrontendsError instance.
1110
- */
1111
- static handle(err, opts) {
1112
- if (err instanceof MicrofrontendError2) {
1113
- return err;
1114
- }
1115
- if (err instanceof Error) {
1116
- return MicrofrontendError2.convert(err, opts);
1117
- }
1118
- if (typeof err === "object" && err !== null) {
1119
- if ("message" in err && typeof err.message === "string") {
1120
- return MicrofrontendError2.convert(new Error(err.message), opts);
1121
- }
1122
- }
1123
- return new MicrofrontendError2("An unknown error occurred");
1124
- }
1125
- };
1126
-
1127
- // schema/schema-v2.json
1128
- var schema_v2_default = {
1129
- $schema: "http://json-schema.org/draft-07/schema#",
1130
- $ref: "#/definitions/Config",
1131
- definitions: {
1132
- Config: {
1133
- anyOf: [
1134
- {
1135
- $ref: "#/definitions/MainConfig"
1136
- },
1137
- {
1138
- $ref: "#/definitions/ChildConfig"
1139
- }
1140
- ]
1141
- },
1142
- MainConfig: {
1143
- type: "object",
1144
- properties: {
1145
- $schema: {
1146
- type: "string"
1147
- },
1148
- version: {
1149
- type: "string",
1150
- const: "2"
1151
- },
1152
- options: {
1153
- $ref: "#/definitions/Options"
1154
- },
1155
- remotes: {
1156
- type: "object",
1157
- additionalProperties: {
1158
- $ref: "#/definitions/Application"
1159
- },
1160
- description: "Applications that only serve a subset of the microfrontend routes only need to reference the name of the primary application that owns the full microfrontends configuration."
1161
- },
1162
- applications: {
1163
- $ref: "#/definitions/ApplicationRouting",
1164
- description: "Mapping of application names to the routes that they host. Only needs to be defined in the application that owns the primary microfrontend domain"
1165
- }
1166
- },
1167
- required: ["applications", "version"]
1168
- },
1169
- Options: {
1170
- type: "object",
1171
- properties: {
1172
- vercel: {
1173
- $ref: "#/definitions/VercelOptions",
1174
- description: "Micro-Frontends wide options for Vercel."
1175
- },
1176
- localProxy: {
1177
- $ref: "#/definitions/LocalProxyOptions",
1178
- description: "Options for local proxy."
1179
- }
1180
- }
1181
- },
1182
- VercelOptions: {
1183
- type: "object",
1184
- properties: {
1185
- teamSlug: {
1186
- type: "string",
1187
- description: "Team slug for the Vercel team"
1188
- },
1189
- disableOverrides: {
1190
- type: "boolean",
1191
- description: "If you want to disable the overrides for the site. For example, if you are managing rewrites between applications externally, you may wish to disable the overrides on the toolbar as they will have no effect."
1192
- }
1193
- }
1194
- },
1195
- LocalProxyOptions: {
1196
- type: "object",
1197
- properties: {
1198
- port: {
1199
- type: "number",
1200
- description: "The port number used by the local proxy server.\n\nThe default is `3024`."
1201
- }
1202
- }
1203
- },
1204
- Application: {
1205
- anyOf: [
1206
- {
1207
- $ref: "#/definitions/DefaultApplication"
1208
- },
1209
- {
1210
- $ref: "#/definitions/ChildApplication"
1211
- }
1212
- ]
1213
- },
1214
- DefaultApplication: {
1215
- type: "object",
1216
- properties: {
1217
- vercel: {
1218
- $ref: "#/definitions/Vercel"
1219
- },
1220
- development: {
1221
- $ref: "#/definitions/Development"
1222
- },
1223
- production: {
1224
- $ref: "#/definitions/HostConfig"
1225
- }
1226
- },
1227
- required: ["production"]
1228
- },
1229
- Vercel: {
1230
- type: "object",
1231
- properties: {
1232
- projectId: {
1233
- type: "string",
1234
- description: "Vercel project ID"
1235
- }
1236
- },
1237
- required: ["projectId"]
1238
- },
1239
- Development: {
1240
- type: "object",
1241
- properties: {
1242
- local: {
1243
- $ref: "#/definitions/LocalHostConfig"
1244
- },
1245
- fallback: {
1246
- $ref: "#/definitions/HostConfig",
1247
- description: "Fallback for local development, could be a host config that points to any environment. If this is not provided, or the application is not running - requests to the application in local development will error."
1248
- },
1249
- task: {
1250
- type: "string",
1251
- description: "Optional task to run when starting the development server. Should reference a script in the package.json of the application."
1252
- }
1253
- }
1254
- },
1255
- LocalHostConfig: {
1256
- type: "object",
1257
- properties: {
1258
- host: {
1259
- type: "string",
1260
- description: "The hostname or IP address of the server. This can be a domain name (e.g., `example.com`) or an IP address (e.g., `192.168.1.1`)."
1261
- },
1262
- protocol: {
1263
- type: "string",
1264
- enum: ["http", "https"],
1265
- description: 'The protocol to be used for the connection.\n- `http`: Hypertext Transfer Protocol (HTTP).\n- `https`: Secure Hypertext Transfer Protocol (HTTPS).\n\n* @defaultValue "http" for local development, "https" for otherwise'
1266
- },
1267
- port: {
1268
- type: "number",
1269
- description: "The port number to be used for the connection. Common values include `80` for HTTP and `443` for HTTPS."
1270
- }
1271
- }
1272
- },
1273
- HostConfig: {
1274
- type: "object",
1275
- properties: {
1276
- protocol: {
1277
- type: "string",
1278
- enum: ["http", "https"],
1279
- description: 'The protocol to be used for the connection.\n- `http`: Hypertext Transfer Protocol (HTTP).\n- `https`: Secure Hypertext Transfer Protocol (HTTPS).\n\n* @defaultValue "http" for local development, "https" for otherwise'
1280
- },
1281
- host: {
1282
- type: "string",
1283
- description: "The hostname or IP address of the server. This can be a domain name (e.g., `example.com`) or an IP address (e.g., `192.168.1.1`)."
1284
- },
1285
- port: {
1286
- type: "number",
1287
- description: "The port number to be used for the connection. Common values include `80` for HTTP and `443` for HTTPS."
1288
- }
1289
- },
1290
- required: ["host"]
1291
- },
1292
- ChildApplication: {
1293
- type: "object",
1294
- properties: {
1295
- vercel: {
1296
- $ref: "#/definitions/Vercel"
1297
- },
1298
- development: {
1299
- $ref: "#/definitions/Development"
1300
- },
1301
- routing: {
1302
- $ref: "#/definitions/Routing",
1303
- description: "Groups of path expressions that are routed to this application."
1304
- },
1305
- production: {
1306
- $ref: "#/definitions/HostConfig"
1307
- }
1308
- },
1309
- required: ["routing"]
1310
- },
1311
- Routing: {
1312
- type: "array",
1313
- items: {
1314
- $ref: "#/definitions/PathGroup"
1315
- }
1316
- },
1317
- PathGroup: {
1318
- type: "object",
1319
- properties: {
1320
- group: {
1321
- type: "string",
1322
- description: "Optional group name for the paths"
1323
- },
1324
- flag: {
1325
- type: "string",
1326
- description: "flag name that can be used to enable/disable all paths in the group"
1327
- },
1328
- paths: {
1329
- type: "array",
1330
- items: {
1331
- type: "string"
1332
- }
1333
- }
1334
- },
1335
- required: ["paths"]
1336
- },
1337
- ApplicationRouting: {
1338
- type: "object",
1339
- additionalProperties: {
1340
- $ref: "#/definitions/Application"
1341
- }
1342
- },
1343
- ChildConfig: {
1344
- type: "object",
1345
- properties: {
1346
- $schema: {
1347
- type: "string"
1348
- },
1349
- version: {
1350
- type: "string",
1351
- const: "2"
1352
- },
1353
- options: {
1354
- $ref: "#/definitions/Options"
1355
- },
1356
- remotes: {
1357
- type: "object",
1358
- additionalProperties: {
1359
- $ref: "#/definitions/Application"
1360
- },
1361
- description: "Applications that only serve a subset of the microfrontend routes only need to reference the name of the primary application that owns the full microfrontends configuration."
1362
- },
1363
- partOf: {
1364
- type: "string",
1365
- description: "Applications that only serve a subset of the microfrontend routes only need to reference the name of the primary application that owns the full microfrontends configuration."
1366
- }
1367
- },
1368
- required: ["partOf", "version"]
1369
- }
1370
- }
1371
- };
1372
-
1373
- // src/config-v2/schema/utils/load.ts
1374
- var SCHEMA = schema_v2_default;
1375
-
1376
- // src/config-v2/microfrontends/server/validation.ts
1377
- function validateSchema(configString) {
1378
- const parsedConfig = (0, import_jsonc_parser3.parse)(configString);
1379
- const ajv = new import_ajv.Ajv();
1380
- const validate = ajv.compile(SCHEMA);
1381
- const isValid = validate(parsedConfig);
1382
- if (!isValid) {
1383
- throw new MicrofrontendError2(
1384
- `Invalid config: ${ajv.errorsText(validate.errors)}`,
1385
- { type: "config", subtype: "does_not_match_schema" }
1386
- );
1387
- }
1388
- return parsedConfig;
1389
- }
1390
-
1391
- // src/config-v2/microfrontends/server/index.ts
1392
- var MicrofrontendsServer = class extends Microfrontends {
1393
- /**
1394
- * Writes the configuration to a file.
1395
- */
1396
- writeConfig(opts = {
1397
- pretty: true
1398
- }) {
1399
- const outputPath = getOutputFilePath();
1400
- import_node_fs7.default.mkdirSync((0, import_node_path8.dirname)(outputPath), { recursive: true });
1401
- import_node_fs7.default.writeFileSync(
1402
- outputPath,
1403
- JSON.stringify(
1404
- this.config.toSchemaJson(),
1405
- null,
1406
- opts.pretty ?? true ? 2 : void 0
1407
- )
1408
- );
1409
- }
1410
- // --------- Static Methods ---------
1411
- /**
1412
- * Generates a MicrofrontendsServer instance from an unknown object.
1413
- */
1414
- static fromUnknown({
1415
- config,
1416
- cookies,
1417
- meta
1418
- }) {
1419
- const overrides = cookies ? parseOverrides(cookies) : void 0;
1420
- if (typeof config === "string") {
1421
- return new MicrofrontendsServer({
1422
- config: MicrofrontendsServer.validate(config),
1423
- overrides,
1424
- meta
1425
- });
1426
- }
1427
- if (typeof config === "object") {
1428
- return new MicrofrontendsServer({
1429
- config,
1430
- overrides,
1431
- meta
1432
- });
1433
- }
1434
- throw new MicrofrontendError(
1435
- "Invalid config: must be a string or an object",
1436
- { type: "config", subtype: "does_not_match_schema" }
1437
- );
1438
- }
1439
- /**
1440
- * Generates a MicrofrontendsServer instance from the environment.
1441
- * Uses additional validation that is only available when in a node runtime
1442
- */
1443
- static fromEnv({
1444
- cookies,
1445
- meta
1446
- }) {
1447
- return new MicrofrontendsServer({
1448
- config: MicrofrontendsServer.validate(getConfigStringFromEnv()),
1449
- overrides: parseOverrides(cookies),
1450
- meta
1451
- });
1452
- }
1453
- /**
1454
- * Validates the configuration against the JSON schema
1455
- */
1456
- static validate(config) {
1457
- if (typeof config === "string") {
1458
- const c = validateSchema(config);
1459
- return c;
1460
- }
1461
- return config;
1462
- }
1463
- /**
1464
- * Looks up the configuration by inferring the package root and looking for a microfrontends config file. If a file is not found,
1465
- * it will look for a package in the repository with a microfrontends file that contains the current application
1466
- * and use that configuration.
1467
- *
1468
- * This can return either a Child or Main configuration.
1469
- */
1470
- static infer({
1471
- directory,
1472
- filePath,
1473
- meta,
1474
- cookies,
1475
- options
1476
- } = {}) {
1477
- if (filePath && meta) {
1478
- return MicrofrontendsServer.fromFile({
1479
- filePath,
1480
- cookies,
1481
- meta,
1482
- options
1483
- });
1484
- }
1485
- try {
1486
- const packageRoot = findPackageRoot(directory);
1487
- const packageJsonPath = (0, import_node_path8.join)(packageRoot, "package.json");
1488
- const packageJson = JSON.parse(
1489
- import_node_fs7.default.readFileSync(packageJsonPath, "utf-8")
1490
- );
1491
- if (!packageJson.name) {
1492
- throw new Error(`No name found in package.json at ${packageJsonPath}`);
1493
- }
1494
- const configMeta = meta ?? { fromApp: packageJson.name };
1495
- const maybeConfig = findConfig({ dir: packageRoot });
1496
- if (maybeConfig) {
1497
- return MicrofrontendsServer.fromFile({
1498
- filePath: maybeConfig,
1499
- cookies,
1500
- meta: configMeta,
1501
- options
1502
- });
1503
- }
1504
- const repositoryRoot = findRepositoryRoot();
1505
- const isMonorepo2 = isMonorepo({ repositoryRoot });
1506
- if (isMonorepo2) {
1507
- const defaultPackage = findDefaultMicrofrontendsPackage({
1508
- repositoryRoot,
1509
- applicationName: packageJson.name
1510
- });
1511
- const maybeConfigFromDefault = findConfig({ dir: defaultPackage });
1512
- if (maybeConfigFromDefault) {
1513
- return MicrofrontendsServer.fromFile({
1514
- filePath: maybeConfigFromDefault,
1515
- cookies,
1516
- meta: configMeta,
1517
- options
1518
- });
1519
- }
1520
- }
1521
- throw new Error("Unable to infer");
1522
- } catch (e) {
1523
- throw new MicrofrontendError(
1524
- "Unable to infer microfrontends configuration",
1525
- { type: "config", subtype: "inference_failed" }
1526
- );
1527
- }
1528
- }
1529
- /*
1530
- * Generates a MicrofrontendsServer instance from a file.
1531
- */
1532
- static fromFile({
1533
- filePath,
1534
- cookies,
1535
- meta,
1536
- options
1537
- }) {
1538
- try {
1539
- const configJson = import_node_fs7.default.readFileSync(filePath, "utf-8");
1540
- const config = MicrofrontendsServer.validate(configJson);
1541
- if (!isMainConfig(config) && (options == null ? void 0 : options.resolveMainConfig)) {
1542
- const repositoryRoot = findRepositoryRoot();
1543
- const isMonorepo2 = isMonorepo({ repositoryRoot });
1544
- if (isMonorepo2) {
1545
- const packagePath = findPackagePath({
1546
- repositoryRoot,
1547
- name: config.partOf
1548
- });
1549
- if (!packagePath) {
1550
- throw new MicrofrontendError(
1551
- `Could not find default application "${config.partOf}" in the repository`,
1552
- { type: "config", subtype: "not_found" }
1553
- );
1554
- }
1555
- const maybeConfig = findConfig({ dir: packagePath });
1556
- if (!maybeConfig) {
1557
- throw new MicrofrontendError(
1558
- `Could not find microfrontends configuration in ${packagePath}`,
1559
- { type: "config", subtype: "not_found" }
1560
- );
1561
- }
1562
- return MicrofrontendsServer.fromMainConfigFile({
1563
- filePath: maybeConfig,
1564
- overrides: cookies ? parseOverrides(cookies) : void 0
1565
- });
1566
- }
1567
- }
1568
- return new MicrofrontendsServer({
1569
- config,
1570
- overrides: cookies ? parseOverrides(cookies) : void 0,
1571
- meta
1572
- });
1573
- } catch (e) {
1574
- throw MicrofrontendError.handle(e, {
1575
- fileName: filePath
1576
- });
1577
- }
1578
- }
1579
- /*
1580
- * Generates a MicrofrontendMainConfig instance from a file.
1581
- */
1582
- static fromMainConfigFile({
1583
- filePath,
1584
- overrides
1585
- }) {
1586
- try {
1587
- const config = import_node_fs7.default.readFileSync(filePath, "utf-8");
1588
- const validatedConfig = MicrofrontendsServer.validate(config);
1589
- if (!isMainConfig(validatedConfig)) {
1590
- throw new MicrofrontendError(
1591
- `${filePath} is not a main microfrontend config`,
1592
- {
1593
- type: "config",
1594
- subtype: "invalid_main_path"
1595
- }
1596
- );
1597
- }
1598
- const [defaultApplication] = Object.entries(validatedConfig.applications).filter(([, app]) => isDefaultApp(app)).map(([name]) => name);
1599
- if (!defaultApplication) {
1600
- throw new MicrofrontendError(
1601
- `No default application found. At least one application needs to be the default by omitting routing.`,
1602
- { type: "config", subtype: "no_default_application" }
1603
- );
1604
- }
1605
- return new MicrofrontendsServer({
1606
- config: validatedConfig,
1607
- overrides,
1608
- meta: { fromApp: defaultApplication }
1609
- });
1610
- } catch (e) {
1611
- throw MicrofrontendError.handle(e, {
1612
- fileName: filePath
1613
- });
1614
- }
1615
- }
1616
- };
1617
-
1618
- // src/next-v2/utils/check-proxy.ts
1619
- function displayLocalProxyInfo(port) {
1620
- const { MFE_PROXY_MESSAGE_PRINTED, TURBO_TASK_HAS_MFE_PROXY } = process.env;
1621
- if (TURBO_TASK_HAS_MFE_PROXY === "true" && MFE_PROXY_MESSAGE_PRINTED !== "true") {
1622
- process.env.MFE_PROXY_MESSAGE_PRINTED = "true";
1623
- console.log(`Microfrontends Proxy running on http://localhost:${port}`);
1624
- }
1625
- }
1626
-
1627
- // src/next-v2/config/transforms/asset-prefix.ts
1628
- function transform(args) {
1629
- const { next, app } = args;
1630
- if (app.isDefault()) {
1631
- return {
1632
- next
1633
- };
1634
- }
1635
- if (next.assetPrefix !== void 0 && next.assetPrefix !== app.getAssetPrefix()) {
1636
- console.log(
1637
- `"assetPrefix" already set. This route must be manually configured in your microfrontend.json file.`
1638
- );
1639
- } else {
1640
- next.assetPrefix = `/${app.getAssetPrefix()}`;
1641
- }
1642
- return {
1643
- next
1644
- };
1645
- }
1646
-
1647
- // src/next-v2/config/transforms/draft-mode.ts
1648
- function transform2(args) {
1649
- var _a;
1650
- const { next } = args;
1651
- if (((_a = next.experimental) == null ? void 0 : _a.multiZoneDraftMode) !== void 0) {
1652
- return {
1653
- next
1654
- };
1655
- }
1656
- next.experimental = next.experimental || {};
1657
- next.experimental.multiZoneDraftMode = true;
1658
- return {
1659
- next
1660
- };
1661
- }
1662
-
1663
- // src/next-v2/config/transforms/headers.ts
1664
- function transform3(args) {
1665
- const { next, app } = args;
1666
- if (app.isDefault()) {
1667
- return {
1668
- next
1669
- };
1670
- }
1671
- const headersToAdd = [
1672
- {
1673
- source: "/:path*",
1674
- headers: [
1675
- {
1676
- key: "X-Vercel-Zone",
1677
- value: app.name
1678
- },
1679
- {
1680
- key: "X-Vercel-MFE-App",
1681
- value: app.name
1682
- }
1683
- ]
1684
- },
1685
- {
1686
- source: "/:path*",
1687
- has: [
1688
- {
1689
- type: "host",
1690
- value: "(?<host>.*)"
1691
- }
1692
- ],
1693
- headers: [
1694
- {
1695
- // TODO: we may want to revisit before launch whether we want to expose this
1696
- // value on all responses publicly since users may not want to reveal this host
1697
- // (maybe just in preview? or when the user is logged in to the toolbar?)
1698
- key: "X-Vercel-Host",
1699
- value: ":host"
1700
- }
1701
- ]
1702
- }
1703
- ];
1704
- if (next.headers && typeof next.headers === "function") {
1705
- const originalHeadersFn = next.headers;
1706
- next.headers = async () => {
1707
- const originalHeaders = await originalHeadersFn();
1708
- return [...originalHeaders, ...headersToAdd];
1709
- };
1710
- } else {
1711
- next.headers = () => {
1712
- return Promise.resolve(headersToAdd);
1713
- };
1714
- }
1715
- return {
1716
- next
1717
- };
1718
- }
1719
-
1720
- // src/routing-v2/get-domain-from-environment.ts
1721
- function getDomainFromEnvironment({
1722
- app,
1723
- target
1724
- }) {
1725
- var _a;
1726
- const mfeProjects = JSON.parse(
1727
- process.env.VERCEL_MICROFRONTENDS_PROJECTS ?? "[]"
1728
- );
1729
- if (mfeProjects.length === 0) {
1730
- throw new Error("Missing related microfrontends project information");
1731
- }
1732
- if (!((_a = app.vercel) == null ? void 0 : _a.projectId)) {
1733
- throw new Error(`Missing applications[${app.name}].vercel.projectId`);
1734
- }
1735
- const vercelProject = mfeProjects.find(
1736
- (p) => {
1737
- var _a2;
1738
- return p.project.id === ((_a2 = app.vercel) == null ? void 0 : _a2.projectId);
1739
- }
1740
- );
1741
- if (!vercelProject) {
1742
- throw new Error(
1743
- `Missing related microfrontends project information for application "${app.name}"`
1744
- );
1745
- }
1746
- const domain = target === "preview" && vercelProject.preview.branch ? vercelProject.preview.branch : vercelProject.production.alias ?? vercelProject.production.url;
1747
- if (!domain) {
1748
- throw new Error(
1749
- `Missing domain for target "${target}" in application "${app.name}"`
1750
- );
1751
- }
1752
- return domain.startsWith("https://") ? domain : `https://${domain}`;
1753
- }
1754
-
1755
- // src/routing-v2/get-domain-for-current-environment.ts
1756
- function debugDomains(zone, env, domain) {
1757
- if (process.env.MFE_DEBUG === "true") {
1758
- const indent = " ".repeat(4);
1759
- const header = "domains (zone (env) -> domain)";
1760
- const separator = "\u23AF".repeat(header.length);
1761
- const line = `${indent} 1. ${zone} (${env}) -> ${domain}`;
1762
- console.log(`${indent}${header}
1763
- ${indent}${separator}
1764
- ${line}
1765
- `);
1766
- }
1767
- }
1768
- function getCurrentEnvironment() {
1769
- const isDevelopment = !process.env.VERCEL_ENV || process.env.VERCEL_ENV === "development";
1770
- const isPreview = process.env.VERCEL_ENV === "preview";
1771
- const isProduction2 = process.env.VERCEL_ENV === "production";
1772
- if (isDevelopment) {
1773
- return { group: "development" };
1774
- } else if (isProduction2) {
1775
- return { group: "production" };
1776
- } else if (isPreview) {
1777
- return { group: "preview" };
1778
- }
1779
- return { group: "custom", name: process.env.VERCEL_ENV };
1780
- }
1781
- function getDomainForCurrentEnvironment(config, appName, opts = {}) {
1782
- var _a;
1783
- const app = config.getApplication(appName);
1784
- if (!opts.ignoreOverride && ((_a = app.overrides) == null ? void 0 : _a.environment)) {
1785
- return app.overrides.environment.toString();
1786
- }
1787
- const { group } = getCurrentEnvironment();
1788
- const productionHost = config.getDefaultApplication().production.toString();
1789
- switch (group) {
1790
- case "development": {
1791
- const domain = ["test", "development"].includes(process.env.NODE_ENV) ? app.development.local.toString() : productionHost;
1792
- debugDomains(appName, "development", domain);
1793
- return domain;
1794
- }
1795
- case "preview": {
1796
- return getDomainFromEnvironment({ app, target: "preview" });
1797
- }
1798
- case "production": {
1799
- return getDomainFromEnvironment({ app, target: "production" });
1800
- }
1801
- case "custom":
1802
- console.warn(
1803
- `Custom environments are not supported in getDomainForCurrentEnvironment`
1804
- );
1805
- return productionHost;
1806
- }
1807
- }
1808
-
1809
- // src/next-v2/config/transforms/rewrites.ts
1810
- function debugRewrites(rewrites) {
1811
- if (process.env.MFE_DEBUG === "true") {
1812
- const indent = " ".repeat(4);
1813
- const header = "rewrites (source \u2192 destination)";
1814
- const separator = "\u23AF".repeat(header.length);
1815
- const maxSourceLength = Math.max(
1816
- ...rewrites.map((key) => key.source.length)
1817
- );
1818
- const table = rewrites.map((route, idx) => {
1819
- const paddedSource = route.source.padEnd(maxSourceLength);
1820
- return `${indent} ${idx + 1}. ${paddedSource} \u2192 ${route.destination}`;
1821
- }).join("\n");
1822
- console.log(`${indent}${header}
1823
- ${indent}${separator}
1824
- ${table}
1825
- `);
1826
- }
1827
- }
1828
- function pathToRewrites(path5) {
1829
- var _a;
1830
- const regex = /(?<base>^.+)\/:.+\*$/;
1831
- const match = regex.exec(path5);
1832
- const paths = [path5];
1833
- if ((_a = match == null ? void 0 : match.groups) == null ? void 0 : _a.base) {
1834
- paths.unshift(match.groups.base);
1835
- }
1836
- return paths;
1837
- }
1838
- function rewritesMapToArr(rewrites) {
1839
- return Array.from(rewrites.entries()).flatMap(([source, rewrite]) => {
1840
- const destination = `${rewrite.destination.domain || ""}${rewrite.destination.pathname}`;
1841
- if (source === destination)
1842
- return [];
1843
- return [
1844
- {
1845
- source,
1846
- destination,
1847
- missing: [
1848
- // if this header is present, the proxy has performed the rewrite.
1849
- // once the proxy routing is fully rolled out, this package should
1850
- // be updated to not perform any rewrites when deployed.
1851
- {
1852
- type: "header",
1853
- key: "x-vercel-mfe-host"
1854
- }
1855
- ]
1856
- }
1857
- ];
1858
- });
1859
- }
1860
- function transform4(args) {
1861
- const { next, microfrontend, app } = args;
1862
- const buildBeforeFiles = () => {
1863
- const rewrites = /* @__PURE__ */ new Map();
1864
- if (!app.isDefault()) {
1865
- rewrites.set(`/${app.getAssetPrefix()}/_next/:path+`, {
1866
- destination: {
1867
- pathname: `/_next/:path+`
1868
- }
1869
- });
1870
- rewrites.set(`/${app.getAssetPrefix()}/.well-known/vercel/flags`, {
1871
- destination: {
1872
- pathname: `/.well-known/vercel/flags`
1873
- }
1874
- });
1875
- if (process.env.VERCEL_MICROFRONTENDS_CONSOLIDATE_SPEED_INSIGHTS === "1") {
1876
- rewrites.set(`/${app.getAssetPrefix()}/_vercel/:path*`, {
1877
- destination: { pathname: "/_vercel/:path*" }
1878
- });
1879
- }
1880
- } else if (microfrontend instanceof MicrofrontendMainConfig) {
1881
- for (const [_, a] of Object.entries(
1882
- microfrontend.getChildApplications()
1883
- )) {
1884
- const { routing } = a;
1885
- const domain = getDomainForCurrentEnvironment(microfrontend, a.name);
1886
- rewrites.set(`/${a.getAssetPrefix()}/:path+`, {
1887
- destination: {
1888
- domain,
1889
- pathname: `/${a.getAssetPrefix()}/:path+`
1890
- }
1891
- });
1892
- for (const group of routing) {
1893
- if (group.flag) {
1894
- continue;
1895
- } else {
1896
- for (const source of group.paths) {
1897
- const paths = pathToRewrites(source);
1898
- for (const p of paths) {
1899
- rewrites.set(p, {
1900
- destination: { domain, pathname: p }
1901
- });
1902
- }
1903
- }
1904
- }
1905
- }
1906
- }
1907
- }
1908
- return rewritesMapToArr(rewrites);
1909
- };
1910
- const newBeforeFiles = buildBeforeFiles();
1911
- if (next.rewrites && typeof next.rewrites === "function") {
1912
- const originalRewritesFn = next.rewrites;
1913
- next.rewrites = async () => {
1914
- const originalRewrites = await originalRewritesFn();
1915
- if (typeof originalRewrites === "object" && !Array.isArray(originalRewrites)) {
1916
- const { beforeFiles = [] } = originalRewrites;
1917
- return {
1918
- beforeFiles: [...newBeforeFiles, ...beforeFiles],
1919
- afterFiles: originalRewrites.afterFiles,
1920
- fallback: originalRewrites.fallback
1921
- };
1922
- }
1923
- return {
1924
- beforeFiles: newBeforeFiles,
1925
- afterFiles: originalRewrites,
1926
- fallback: []
1927
- };
1928
- };
1929
- } else {
1930
- next.rewrites = async () => ({
1931
- beforeFiles: newBeforeFiles,
1932
- afterFiles: [],
1933
- fallback: []
1934
- });
1935
- }
1936
- debugRewrites(newBeforeFiles);
1937
- return {
1938
- next
1939
- };
1940
- }
1941
-
1942
- // src/next-v2/config/transforms/server-actions.ts
1943
- function debugRewrites2(allowedOrigins) {
1944
- if (process.env.MFE_DEBUG === "true" && allowedOrigins) {
1945
- const indent = " ".repeat(4);
1946
- const header = "server actions allowed origins";
1947
- const separator = "\u23AF".repeat(header.length);
1948
- const maxSourceLength = Math.max(
1949
- ...allowedOrigins.map((key) => key.length)
1950
- );
1951
- const table = allowedOrigins.map((origin, idx) => {
1952
- const paddedSource = origin.padEnd(maxSourceLength);
1953
- return `${indent} ${idx + 1}. ${paddedSource}`;
1954
- }).join("\n");
1955
- console.log(`${indent}${header}
1956
- ${indent}${separator}
1957
- ${table}
1958
- `);
1959
- }
1960
- }
1961
- var formatDomainForServerAction = (domain) => domain.replace(/https?:\/\//, "");
1962
- function transform5(args) {
1963
- var _a, _b;
1964
- const { next, app, microfrontend } = args;
1965
- if (microfrontend instanceof MicrofrontendChildConfig) {
1966
- console.warn(
1967
- "server actions transform requires the full config - skipping"
1968
- );
1969
- return {
1970
- next
1971
- };
1972
- }
1973
- const defaultApplication = microfrontend.getDefaultApplication();
1974
- const appsToAllow = [
1975
- // this zone - this is included by default unless allowedOrigins is overridden (which we are)
1976
- // so we re-add it here.
1977
- app,
1978
- // this is the default zone for the microfrontend. Allow child zones to call server actions
1979
- // that are in the default zone.
1980
- defaultApplication
1981
- ];
1982
- const existingServerActionConfig = (_a = next.experimental) == null ? void 0 : _a.serverActions;
1983
- next.experimental = {
1984
- ...next.experimental,
1985
- serverActions: {
1986
- ...existingServerActionConfig,
1987
- allowedOrigins: Array.from(
1988
- /* @__PURE__ */ new Set([
1989
- // existing
1990
- ...(existingServerActionConfig == null ? void 0 : existingServerActionConfig.allowedOrigins) ?? [],
1991
- // this deployments host
1992
- ...process.env.VERCEL_URL ? [formatDomainForServerAction(process.env.VERCEL_URL)] : [],
1993
- // default application host
1994
- formatDomainForServerAction(defaultApplication.production.toString()),
1995
- // environment specific microfrontend hosts
1996
- ...appsToAllow.flatMap((a) => [
1997
- formatDomainForServerAction(
1998
- getDomainForCurrentEnvironment(microfrontend, a.name)
1999
- )
2000
- ])
2001
- ])
2002
- )
2003
- }
2004
- };
2005
- debugRewrites2((_b = next.experimental.serverActions) == null ? void 0 : _b.allowedOrigins);
2006
- return {
2007
- next
2008
- };
2009
- }
2010
-
2011
- // src/next-v2/config/transforms/webpack.ts
2012
- function transform6(args) {
2013
- const { next, microfrontend } = args;
2014
- const configWithWebpack = {
2015
- ...next,
2016
- webpack(cfg, context) {
2017
- const config = typeof next.webpack === "function" ? next.webpack(cfg, context) : cfg;
2018
- const { isServer, nextRuntime, webpack: wpFromNext } = context;
2019
- if (isServer || nextRuntime === "edge") {
2020
- config.plugins.push(
2021
- new wpFromNext.EnvironmentPlugin({
2022
- MFE_CONFIG: JSON.stringify(microfrontend.serialize())
2023
- })
2024
- );
2025
- }
2026
- config.plugins.push(
2027
- // Remove node: from import specifiers, because Next.js does not yet support node: scheme
2028
- // https://github.com/vercel/next.js/issues/28774
2029
- new wpFromNext.NormalModuleReplacementPlugin(
2030
- /^node:/,
2031
- (resource) => {
2032
- resource.request = resource.request.replace(/^node:/, "");
2033
- }
2034
- )
2035
- );
2036
- if (!isServer) {
2037
- config.resolve.fallback = {
2038
- fs: false,
2039
- path: false,
2040
- crypto: false,
2041
- ...config.resolve.fallback
2042
- };
2043
- }
2044
- return config;
2045
- }
2046
- };
2047
- return {
2048
- next: configWithWebpack
2049
- };
2050
- }
2051
-
2052
- // src/next-v2/config/transforms/index.ts
2053
- var transforms = {
2054
- assetPrefix: transform,
2055
- draftMode: transform2,
2056
- headers: transform3,
2057
- rewrites: transform4,
2058
- serverActions: transform5,
2059
- webpack: transform6
2060
- };
2061
-
2062
- // src/next-v2/config/env.ts
2063
- function debugEnv(env) {
2064
- if (process.env.MFE_DEBUG === "true") {
2065
- const indent = " ".repeat(4);
2066
- const header = "env (key \u2192 val)";
2067
- const separator = "\u23AF".repeat(header.length);
2068
- const maxKeyLength = Math.max(...Object.keys(env).map((key) => key.length));
2069
- const table = Object.keys(env).map((key, idx) => {
2070
- const paddedKey = key.padEnd(maxKeyLength);
2071
- return `${indent} ${idx + 1}. ${paddedKey} = ${env[key]}`;
2072
- }).join("\n");
2073
- console.log(`${indent}${header}
2074
- ${indent}${separator}
2075
- ${table}
2076
- `);
2077
- }
2078
- }
2079
- function setEnvironment({
2080
- app,
2081
- microfrontends
2082
- }) {
2083
- const clientEnvs = {
2084
- NEXT_PUBLIC_MFE_CURRENT_APPLICATION: app.name,
2085
- NEXT_PUBLIC_MFE_CLIENT_CONFIG: JSON.stringify(
2086
- microfrontends.config.toClientConfig().serialize()
2087
- )
2088
- };
2089
- const serverEnvs = {
2090
- MFE_CURRENT_APPLICATION: app.name,
2091
- MFE_CONFIG: JSON.stringify(microfrontends.config.getConfig())
2092
- };
2093
- const allEnvs = { ...clientEnvs, ...serverEnvs };
2094
- for (const [key, value] of Object.entries(allEnvs)) {
2095
- process.env[key] = value;
2096
- }
2097
- debugEnv(allEnvs);
2098
- }
2099
-
2100
- // src/next-v2/config/index.ts
2101
- function typedEntries(obj) {
2102
- return Object.entries(obj);
2103
- }
2104
- function isProduction(opts) {
2105
- if (opts == null ? void 0 : opts.isProduction) {
2106
- return opts.isProduction();
2107
- }
2108
- return process.env.VERCEL_ENV === "production";
2109
- }
2110
- function getApplicationContext(opts) {
2111
- if (opts == null ? void 0 : opts.appName) {
2112
- return { name: opts.appName };
2113
- }
2114
- try {
2115
- const packageJsonString = import_node_fs8.default.readFileSync("./package.json", "utf-8");
2116
- const packageJson = JSON.parse(packageJsonString);
2117
- if (!packageJson.name) {
2118
- throw new MicrofrontendError(
2119
- `package.json file missing required field "name"`,
2120
- {
2121
- type: "packageJson",
2122
- subtype: "missing_field_name",
2123
- source: "@vercel/microfrontends/next"
2124
- }
2125
- );
2126
- }
2127
- return { name: packageJson.name };
2128
- } catch (err) {
2129
- throw MicrofrontendError.handle(err, {
2130
- fileName: "package.json"
2131
- });
2132
- }
2133
- }
2134
- function withMicrofrontends(nextConfig, opts) {
2135
- var _a;
2136
- if (opts == null ? void 0 : opts.debug) {
2137
- process.env.MFE_DEBUG = "true";
2138
- }
2139
- const { name: fromApp } = getApplicationContext(opts);
2140
- const microfrontends = MicrofrontendsServer.infer({
2141
- filePath: opts == null ? void 0 : opts.configPath,
2142
- meta: {
2143
- fromApp
2144
- }
2145
- });
2146
- const app = microfrontends.config.getApplication(fromApp);
2147
- setEnvironment({ app, microfrontends });
2148
- let next = { ...nextConfig };
2149
- for (const [key, transform7] of typedEntries(transforms)) {
2150
- if ((_a = opts == null ? void 0 : opts.skipTransforms) == null ? void 0 : _a.includes(key)) {
2151
- console.log(`Skipping ${key} transform`);
2152
- continue;
2153
- }
2154
- try {
2155
- const transformedConfig = transform7({
2156
- app,
2157
- next,
2158
- microfrontend: microfrontends.config,
2159
- opts: {
2160
- isProduction: isProduction(opts)
2161
- }
2162
- });
2163
- next = transformedConfig.next;
2164
- } catch (e) {
2165
- console.error("Error transforming next config", e);
2166
- }
2167
- }
2168
- displayLocalProxyInfo(microfrontends.config.getLocalProxyPort());
2169
- if (isVercel()) {
2170
- microfrontends.writeConfig();
2171
- }
2172
- return next;
2173
- }
2174
- // Annotate the CommonJS export names for ESM import in node:
2175
- 0 && (module.exports = {
2176
- withMicrofrontends
2177
- });
2178
- //# sourceMappingURL=config.cjs.map