@vercel/microfrontends 0.9.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 (100) hide show
  1. package/README.md +202 -0
  2. package/cli/index.cjs +21 -0
  3. package/dist/bin/cli.cjs +1604 -0
  4. package/dist/config/client.cjs +54 -0
  5. package/dist/config/client.cjs.map +1 -0
  6. package/dist/config/client.d.ts +23 -0
  7. package/dist/config/client.js +28 -0
  8. package/dist/config/client.js.map +1 -0
  9. package/dist/config/edge.cjs +508 -0
  10. package/dist/config/edge.cjs.map +1 -0
  11. package/dist/config/edge.d.ts +20 -0
  12. package/dist/config/edge.js +481 -0
  13. package/dist/config/edge.js.map +1 -0
  14. package/dist/config.cjs +1254 -0
  15. package/dist/config.cjs.map +1 -0
  16. package/dist/config.d.ts +25 -0
  17. package/dist/config.js +1212 -0
  18. package/dist/config.js.map +1 -0
  19. package/dist/index-eff254d8.d.ts +175 -0
  20. package/dist/micro-frontend-config-42886104.d.ts +154 -0
  21. package/dist/next/client.cjs +3 -0
  22. package/dist/next/client.cjs.map +1 -0
  23. package/dist/next/client.d.ts +45 -0
  24. package/dist/next/client.js +3 -0
  25. package/dist/next/client.js.map +1 -0
  26. package/dist/next/config.cjs +1793 -0
  27. package/dist/next/config.cjs.map +1 -0
  28. package/dist/next/config.d.ts +22 -0
  29. package/dist/next/config.js +1758 -0
  30. package/dist/next/config.js.map +1 -0
  31. package/dist/next/endpoints.cjs +82 -0
  32. package/dist/next/endpoints.cjs.map +1 -0
  33. package/dist/next/endpoints.d.ts +15 -0
  34. package/dist/next/endpoints.js +57 -0
  35. package/dist/next/endpoints.js.map +1 -0
  36. package/dist/next/middleware.cjs +763 -0
  37. package/dist/next/middleware.cjs.map +1 -0
  38. package/dist/next/middleware.d.ts +29 -0
  39. package/dist/next/middleware.js +735 -0
  40. package/dist/next/middleware.js.map +1 -0
  41. package/dist/next/testing.cjs +1430 -0
  42. package/dist/next/testing.cjs.map +1 -0
  43. package/dist/next/testing.d.ts +53 -0
  44. package/dist/next/testing.js +1389 -0
  45. package/dist/next/testing.js.map +1 -0
  46. package/dist/overrides.cjs +143 -0
  47. package/dist/overrides.cjs.map +1 -0
  48. package/dist/overrides.d.ts +2 -0
  49. package/dist/overrides.js +115 -0
  50. package/dist/overrides.js.map +1 -0
  51. package/dist/schema-83a75e61.d.ts +188 -0
  52. package/dist/types-4fd1c7c6.d.ts +157 -0
  53. package/dist/v2/config.cjs +720 -0
  54. package/dist/v2/config.cjs.map +1 -0
  55. package/dist/v2/config.d.ts +2 -0
  56. package/dist/v2/config.js +695 -0
  57. package/dist/v2/config.js.map +1 -0
  58. package/dist/v2/microfrontends/server.cjs +1312 -0
  59. package/dist/v2/microfrontends/server.cjs.map +1 -0
  60. package/dist/v2/microfrontends/server.d.ts +48 -0
  61. package/dist/v2/microfrontends/server.js +1277 -0
  62. package/dist/v2/microfrontends/server.js.map +1 -0
  63. package/dist/v2/microfrontends.cjs +803 -0
  64. package/dist/v2/microfrontends.cjs.map +1 -0
  65. package/dist/v2/microfrontends.d.ts +44 -0
  66. package/dist/v2/microfrontends.js +776 -0
  67. package/dist/v2/microfrontends.js.map +1 -0
  68. package/dist/v2/next/client.cjs +3 -0
  69. package/dist/v2/next/client.cjs.map +1 -0
  70. package/dist/v2/next/client.d.ts +45 -0
  71. package/dist/v2/next/client.js +3 -0
  72. package/dist/v2/next/client.js.map +1 -0
  73. package/dist/v2/next/config.cjs +1829 -0
  74. package/dist/v2/next/config.cjs.map +1 -0
  75. package/dist/v2/next/config.d.ts +22 -0
  76. package/dist/v2/next/config.js +1794 -0
  77. package/dist/v2/next/config.js.map +1 -0
  78. package/dist/v2/next/endpoints.cjs +138 -0
  79. package/dist/v2/next/endpoints.cjs.map +1 -0
  80. package/dist/v2/next/endpoints.d.ts +15 -0
  81. package/dist/v2/next/endpoints.js +113 -0
  82. package/dist/v2/next/endpoints.js.map +1 -0
  83. package/dist/v2/next/middleware.cjs +1110 -0
  84. package/dist/v2/next/middleware.cjs.map +1 -0
  85. package/dist/v2/next/middleware.d.ts +29 -0
  86. package/dist/v2/next/middleware.js +1082 -0
  87. package/dist/v2/next/middleware.js.map +1 -0
  88. package/dist/v2/schema.cjs +19 -0
  89. package/dist/v2/schema.cjs.map +1 -0
  90. package/dist/v2/schema.d.ts +1 -0
  91. package/dist/v2/schema.js +1 -0
  92. package/dist/v2/schema.js.map +1 -0
  93. package/dist/validation.cjs +754 -0
  94. package/dist/validation.cjs.map +1 -0
  95. package/dist/validation.d.ts +163 -0
  96. package/dist/validation.js +726 -0
  97. package/dist/validation.js.map +1 -0
  98. package/package.json +204 -0
  99. package/schema/schema-v2.json +288 -0
  100. package/schema/schema.json +352 -0
@@ -0,0 +1,1758 @@
1
+ // src/next/config/index.ts
2
+ import fs3 from "node:fs";
3
+
4
+ // src/config/micro-frontend-config.ts
5
+ import fs2 from "node:fs";
6
+
7
+ // src/config-v2/microfrontends/server/utils/get-output-file-path.ts
8
+ import path from "node:path";
9
+
10
+ // src/config-v2/microfrontends/server/constants.ts
11
+ var MFE_CONFIG_DEFAULT_FILE_PATH = "microfrontends";
12
+ var MFE_CONFIG_DEFAULT_FILE_NAME = "microfrontends.json";
13
+
14
+ // src/utils/is-vercel.ts
15
+ function isVercel() {
16
+ return process.env.VERCEL === "1";
17
+ }
18
+
19
+ // src/config-v2/microfrontends/server/utils/get-output-file-path.ts
20
+ function getOutputFilePath() {
21
+ if (isVercel()) {
22
+ return path.join(
23
+ ".vercel",
24
+ MFE_CONFIG_DEFAULT_FILE_PATH,
25
+ MFE_CONFIG_DEFAULT_FILE_NAME
26
+ );
27
+ }
28
+ return path.join(MFE_CONFIG_DEFAULT_FILE_PATH, MFE_CONFIG_DEFAULT_FILE_NAME);
29
+ }
30
+
31
+ // src/config/errors.ts
32
+ var MicroFrontendError = class extends Error {
33
+ constructor(message, opts) {
34
+ super(message);
35
+ this.name = "MicroFrontendsError";
36
+ this.source = (opts == null ? void 0 : opts.source) ?? "@vercel/micro-frontends";
37
+ this.type = (opts == null ? void 0 : opts.type) ?? "unknown";
38
+ this.subtype = opts == null ? void 0 : opts.subtype;
39
+ Error.captureStackTrace(this, MicroFrontendError);
40
+ }
41
+ isKnown() {
42
+ return this.type !== "unknown";
43
+ }
44
+ isUnknown() {
45
+ return !this.isKnown();
46
+ }
47
+ /**
48
+ * Converts an error to a MicroFrontendsError.
49
+ * @param original - The original error to convert.
50
+ * @returns The converted MicroFrontendsError.
51
+ */
52
+ static convert(original, opts) {
53
+ if (opts == null ? void 0 : opts.fileName) {
54
+ const err = MicroFrontendError.convertFSError(original, opts.fileName);
55
+ if (err) {
56
+ return err;
57
+ }
58
+ }
59
+ if (original.message.includes(
60
+ "Code generation from strings disallowed for this context"
61
+ )) {
62
+ return new MicroFrontendError(original.message, {
63
+ type: "config",
64
+ subtype: "unsupported_validation_env",
65
+ source: "ajv"
66
+ });
67
+ }
68
+ return new MicroFrontendError(original.message);
69
+ }
70
+ static convertFSError(original, fileName) {
71
+ if (original instanceof Error && "code" in original) {
72
+ if (original.code === "ENOENT") {
73
+ return new MicroFrontendError(`Could not find "${fileName}"`, {
74
+ type: "config",
75
+ subtype: "unable_to_read_file",
76
+ source: "fs"
77
+ });
78
+ }
79
+ if (original.code === "EACCES") {
80
+ return new MicroFrontendError(
81
+ `Permission denied while accessing "${fileName}"`,
82
+ {
83
+ type: "config",
84
+ subtype: "invalid_permissions",
85
+ source: "fs"
86
+ }
87
+ );
88
+ }
89
+ }
90
+ if (original instanceof SyntaxError) {
91
+ return new MicroFrontendError(
92
+ `Failed to parse "${fileName}": Invalid JSON format.`,
93
+ {
94
+ type: "config",
95
+ subtype: "invalid_syntax",
96
+ source: "fs"
97
+ }
98
+ );
99
+ }
100
+ return null;
101
+ }
102
+ /**
103
+ * Handles an unknown error and returns a MicroFrontendsError instance.
104
+ * @param err - The error to handle.
105
+ * @returns A MicroFrontendsError instance.
106
+ */
107
+ static handle(err, opts) {
108
+ if (err instanceof MicroFrontendError) {
109
+ return err;
110
+ }
111
+ if (err instanceof Error) {
112
+ return MicroFrontendError.convert(err, opts);
113
+ }
114
+ if (typeof err === "object" && err !== null) {
115
+ if ("message" in err && typeof err.message === "string") {
116
+ return MicroFrontendError.convert(new Error(err.message), opts);
117
+ }
118
+ }
119
+ return new MicroFrontendError("An unknown error occurred");
120
+ }
121
+ };
122
+
123
+ // src/routing/url.ts
124
+ function buildUrlSafeString(givenOpts = {}) {
125
+ const options = {
126
+ joinString: "-",
127
+ lowercaseOnly: true,
128
+ maxLen: 100,
129
+ regexRemovePattern: /(?:(?!(?:[a-z0-9])).)/gi,
130
+ trimWhitespace: true,
131
+ ...givenOpts
132
+ };
133
+ return {
134
+ generate: (...args) => {
135
+ const reJoinString = new RegExp(`${options.joinString}+`, "g");
136
+ let tag;
137
+ if (args.length === 0) {
138
+ throw new Error("generate method must be passed at least one argument");
139
+ }
140
+ for (let i = 0; i < args.length; i++) {
141
+ const arg = args[i];
142
+ if (typeof arg !== "string")
143
+ throw new Error("all supplied arguments must be Strings");
144
+ if (options.trimWhitespace) {
145
+ args[i] = arg.trim();
146
+ }
147
+ }
148
+ tag = args.join(options.joinString);
149
+ tag = tag.replace(/\s/g, options.joinString);
150
+ if (options.lowercaseOnly)
151
+ tag = tag.toLowerCase();
152
+ tag = tag.replace(options.regexRemovePattern, (match) => {
153
+ if (match === options.joinString)
154
+ return match;
155
+ return "";
156
+ });
157
+ if (tag.length > options.maxLen)
158
+ tag = tag.substring(0, options.maxLen);
159
+ tag = tag.replace(reJoinString, options.joinString);
160
+ return tag;
161
+ }
162
+ };
163
+ }
164
+ var urlSafeString = buildUrlSafeString().generate;
165
+ function makeUrlSafe(name) {
166
+ return urlSafeString(name.replace(/\//g, "-")).replace(/^-*/g, "").replace(/-*$/g, "");
167
+ }
168
+
169
+ // src/config/overrides/config.ts
170
+ var OVERRIDES_COOKIE_PREFIX = "vercel-micro-frontends-override";
171
+ var _Overrides = class {
172
+ constructor(config) {
173
+ this.config = config;
174
+ }
175
+ static getAppEnvOverrideCookieName(zone) {
176
+ return `${_Overrides.overrideEnvCookiePrefix}${zone}`;
177
+ }
178
+ static isOverrideCookie(cookie) {
179
+ var _a;
180
+ return Boolean((_a = cookie.name) == null ? void 0 : _a.startsWith(OVERRIDES_COOKIE_PREFIX));
181
+ }
182
+ static getOverrideFromCookie(cookie) {
183
+ if (!_Overrides.isOverrideCookie(cookie) || !cookie.value)
184
+ return;
185
+ return {
186
+ zone: cookie.name.replace(_Overrides.overrideEnvCookiePrefix, ""),
187
+ host: cookie.value
188
+ };
189
+ }
190
+ static parseOverrides(cookies) {
191
+ const overridesConfig = { applications: {} };
192
+ cookies.forEach((cookie) => {
193
+ const override = _Overrides.getOverrideFromCookie(cookie);
194
+ if (!override)
195
+ return;
196
+ overridesConfig.applications[override.zone] = {
197
+ environment: { host: override.host }
198
+ };
199
+ });
200
+ return overridesConfig;
201
+ }
202
+ static validOverrideDomainsForZone(microFrontendConfig, zone) {
203
+ var _a, _b, _c, _d, _e;
204
+ const projectName = (_a = microFrontendConfig.getZone(zone).vercel) == null ? void 0 : _a.projectName;
205
+ if (!projectName) {
206
+ return [microFrontendConfig.getZone(zone).production.host];
207
+ }
208
+ const parsedProjectName = makeUrlSafe(projectName);
209
+ const previewDeploymentSuffix = (_c = (_b = microFrontendConfig.options) == null ? void 0 : _b.vercel) == null ? void 0 : _c.previewDeploymentSuffix;
210
+ const teamSlug = (_e = (_d = microFrontendConfig.options) == null ? void 0 : _d.vercel) == null ? void 0 : _e.teamSlug;
211
+ if (!teamSlug && !previewDeploymentSuffix) {
212
+ return [microFrontendConfig.getZone(zone).production.host];
213
+ }
214
+ const suffix = previewDeploymentSuffix ? `.${previewDeploymentSuffix}` : `-${teamSlug}.vercel.app`;
215
+ return [
216
+ `${parsedProjectName}-git-([a-zA-Z0-9-]+)${suffix}`,
217
+ microFrontendConfig.getZone(zone).production.host
218
+ ];
219
+ }
220
+ static validateOverrideDomain(microFrontendConfig, zone, domain) {
221
+ return new RegExp(
222
+ `^${_Overrides.validOverrideDomainsForZone(microFrontendConfig, zone).join(
223
+ "|"
224
+ )}$`
225
+ ).test(domain);
226
+ }
227
+ serialize() {
228
+ return this.config;
229
+ }
230
+ };
231
+ var Overrides = _Overrides;
232
+ Overrides.overrideEnvCookiePrefix = `${OVERRIDES_COOKIE_PREFIX}:env:`;
233
+
234
+ // src/config/common/host.ts
235
+ var Host = class {
236
+ constructor({ protocol, host, port }) {
237
+ this.protocol = protocol || "https";
238
+ this.host = host;
239
+ this.port = Host.getPort({ port, protocol: this.protocol });
240
+ this.serialized = {
241
+ protocol,
242
+ host,
243
+ ...port ? { port } : void 0
244
+ };
245
+ }
246
+ isLocal() {
247
+ return this.host === "localhost" || this.host === "127.0.0.1";
248
+ }
249
+ static getPort({
250
+ protocol,
251
+ port
252
+ }) {
253
+ if (!port) {
254
+ if (protocol === "http") {
255
+ return 80;
256
+ }
257
+ return 443;
258
+ }
259
+ return port;
260
+ }
261
+ isDefaultPort() {
262
+ return this.port === Host.getPort({ protocol: this.protocol });
263
+ }
264
+ toString(opts = {}) {
265
+ const url = this.toUrl(opts);
266
+ return url.toString().replace(/\/$/, "");
267
+ }
268
+ toUrl(opts = {}) {
269
+ const { includeDefaultPort } = opts;
270
+ const url = `${this.protocol}://${this.host}${this.isDefaultPort() && !includeDefaultPort ? "" : `:${this.port}`}`;
271
+ return new URL(url);
272
+ }
273
+ serialize() {
274
+ return this.serialized;
275
+ }
276
+ };
277
+
278
+ // src/config/common/application.ts
279
+ var Application = class {
280
+ constructor(name, {
281
+ app,
282
+ overrides
283
+ }) {
284
+ Application.validate(name, app);
285
+ this.name = name;
286
+ this.default = app.default;
287
+ this.routing = app.routing;
288
+ this.development = {
289
+ local: new Host(app.development.local),
290
+ fallback: app.development.fallback ? new Host(app.development.fallback) : void 0
291
+ };
292
+ this.production = new Host(app.production);
293
+ this.vercel = app.vercel;
294
+ this.overrides = (overrides == null ? void 0 : overrides.environment) ? {
295
+ environment: new Host(overrides.environment)
296
+ } : void 0;
297
+ }
298
+ isDefault() {
299
+ return this.default;
300
+ }
301
+ static validate(name, app) {
302
+ var _a, _b, _c, _d, _e;
303
+ if (((_b = (_a = app.routing) == null ? void 0 : _a.assetPrefix) == null ? void 0 : _b.startsWith("/")) || ((_d = (_c = app.routing) == null ? void 0 : _c.assetPrefix) == null ? void 0 : _d.endsWith("/"))) {
304
+ throw new MicroFrontendError(
305
+ `Invalid assetPrefix for application "${name}". Must not start or end with a slash.`,
306
+ { type: "zone", subtype: "invalid_asset_prefix" }
307
+ );
308
+ }
309
+ for (const group of ((_e = app.routing) == null ? void 0 : _e.matches) ?? []) {
310
+ for (const p of group.paths) {
311
+ if (p === "/") {
312
+ continue;
313
+ }
314
+ if (p.endsWith("/")) {
315
+ throw new MicroFrontendError(
316
+ `Invalid path for application "${name}". ${p} must not end with a slash.`,
317
+ { type: "zone", subtype: "invalid_path" }
318
+ );
319
+ }
320
+ if (!p.startsWith("/")) {
321
+ throw new MicroFrontendError(
322
+ `Invalid path for application "${name}". ${p} must start with a slash.`,
323
+ { type: "zone", subtype: "invalid_path" }
324
+ );
325
+ }
326
+ }
327
+ }
328
+ }
329
+ serialize() {
330
+ var _a, _b;
331
+ if (this.routing === void 0 || this.default) {
332
+ return {
333
+ default: true,
334
+ development: {
335
+ local: this.development.local.serialize(),
336
+ fallback: (_a = this.development.fallback) == null ? void 0 : _a.serialize()
337
+ },
338
+ production: this.production.serialize(),
339
+ vercel: this.vercel
340
+ };
341
+ }
342
+ return {
343
+ default: false,
344
+ routing: this.routing,
345
+ development: {
346
+ local: this.development.local.serialize(),
347
+ fallback: (_b = this.development.fallback) == null ? void 0 : _b.serialize()
348
+ },
349
+ production: this.production.serialize(),
350
+ vercel: this.vercel
351
+ };
352
+ }
353
+ };
354
+
355
+ // src/config/common/micro-frontend-config.ts
356
+ var SUPPORTED_VERSIONS = ["1"];
357
+ var DEFAULT_LOCAL_PROXY_PORT = 3024;
358
+ var MicroFrontendConfigCommon = class {
359
+ constructor({
360
+ config,
361
+ overrides
362
+ }) {
363
+ this.zones = {};
364
+ var _a, _b, _c;
365
+ if (!SUPPORTED_VERSIONS.includes(config.version)) {
366
+ throw new MicroFrontendError(
367
+ `Unsupported version: ${config.version}. Supported versions are: ${SUPPORTED_VERSIONS.join(
368
+ ", "
369
+ )}`,
370
+ { type: "config", subtype: "unsupported_version" }
371
+ );
372
+ }
373
+ const disableOverrides = ((_b = (_a = config.options) == null ? void 0 : _a.vercel) == null ? void 0 : _b.disableOverrides) ?? false;
374
+ this.overrides = overrides && !disableOverrides ? new Overrides(overrides) : void 0;
375
+ for (const [zoneName, zoneConfig] of Object.entries(config.applications)) {
376
+ this.zones[zoneName] = new Application(zoneName, {
377
+ app: zoneConfig,
378
+ overrides: !disableOverrides ? (_c = this.overrides) == null ? void 0 : _c.config.applications[zoneName] : void 0
379
+ });
380
+ }
381
+ this.config = config;
382
+ this.name = config.name;
383
+ this.version = config.version;
384
+ this.options = config.options;
385
+ this.$schema = config.$schema;
386
+ }
387
+ isOverridesDisabled() {
388
+ var _a, _b;
389
+ return ((_b = (_a = this.options) == null ? void 0 : _a.vercel) == null ? void 0 : _b.disableOverrides) ?? false;
390
+ }
391
+ static getConfigFromEnv() {
392
+ const config = process.env.MFE_CONFIG;
393
+ if (!config) {
394
+ throw new MicroFrontendError(`Missing "MFE_CONFIG" in environment.`, {
395
+ type: "config",
396
+ subtype: "not_found_in_env"
397
+ });
398
+ }
399
+ return config;
400
+ }
401
+ static fromEnv(_) {
402
+ throw new Error("Not implemented");
403
+ }
404
+ getConfig() {
405
+ return this.config;
406
+ }
407
+ getAllApplications() {
408
+ return Object.values(this.zones);
409
+ }
410
+ getZone(name) {
411
+ const zone = this.zones[name];
412
+ if (!zone) {
413
+ throw new MicroFrontendError(
414
+ `Could not find micro-frontends configuration for application "${name}"`,
415
+ {
416
+ type: "zone",
417
+ subtype: "not_found"
418
+ }
419
+ );
420
+ }
421
+ return zone;
422
+ }
423
+ getApplicationByProjectId(projectId) {
424
+ return Object.values(this.zones).find(
425
+ (zone) => {
426
+ var _a;
427
+ return ((_a = zone.vercel) == null ? void 0 : _a.projectId) === projectId;
428
+ }
429
+ );
430
+ }
431
+ getDefaultZone() {
432
+ const zone = Object.values(this.zones).find((z) => z.default);
433
+ if (!zone) {
434
+ throw new MicroFrontendError(
435
+ `Could not find default zone in micro-frontends configuration`,
436
+ {
437
+ type: "zone",
438
+ subtype: "not_found"
439
+ }
440
+ );
441
+ }
442
+ return zone;
443
+ }
444
+ /**
445
+ * Returns the configured port for the local proxy
446
+ */
447
+ getLocalProxyPort() {
448
+ var _a, _b;
449
+ return ((_b = (_a = this.config.options) == null ? void 0 : _a.localProxy) == null ? void 0 : _b.port) ?? DEFAULT_LOCAL_PROXY_PORT;
450
+ }
451
+ /**
452
+ * Serializes the class back to the Schema type.
453
+ *
454
+ * NOTE: This is used when writing the config to disk and must always match the input Schema
455
+ */
456
+ toSchemaJson() {
457
+ const applications = {};
458
+ for (const [name, zone] of Object.entries(this.zones)) {
459
+ applications[name] = zone.serialize();
460
+ }
461
+ return {
462
+ $schema: this.$schema,
463
+ name: this.name,
464
+ version: this.version,
465
+ options: this.options,
466
+ applications
467
+ };
468
+ }
469
+ serialize() {
470
+ var _a;
471
+ const applications = {};
472
+ for (const [name, zone] of Object.entries(this.zones)) {
473
+ applications[name] = zone.serialize();
474
+ }
475
+ return {
476
+ config: {
477
+ name: this.name,
478
+ version: this.version,
479
+ applications,
480
+ options: this.options,
481
+ $schema: this.$schema
482
+ },
483
+ overrides: (_a = this.overrides) == null ? void 0 : _a.serialize()
484
+ };
485
+ }
486
+ write(_) {
487
+ throw new MicroFrontendError(
488
+ `Writing to file to disk requires using an instance of "MicroFrontendConfig".`,
489
+ { type: "config", subtype: "unsupported_operation" }
490
+ );
491
+ }
492
+ };
493
+
494
+ // src/config/utils/get-output-file-path.ts
495
+ import path2 from "node:path";
496
+
497
+ // src/config/constants.ts
498
+ var MFE_CONFIG_DEFAULT_FILE_PATH2 = "micro-frontends";
499
+ var MFE_CONFIG_DEFAULT_FILE_NAME2 = "micro-frontends.config.json";
500
+
501
+ // src/config/utils/get-output-file-path.ts
502
+ function getOutputFilePath2() {
503
+ if (isVercel()) {
504
+ return path2.join(
505
+ ".vercel",
506
+ MFE_CONFIG_DEFAULT_FILE_PATH2,
507
+ MFE_CONFIG_DEFAULT_FILE_NAME2
508
+ );
509
+ }
510
+ return path2.join(MFE_CONFIG_DEFAULT_FILE_PATH2, MFE_CONFIG_DEFAULT_FILE_NAME2);
511
+ }
512
+
513
+ // src/config/validation.ts
514
+ import { parse } from "jsonc-parser";
515
+ import { pathToRegexp, parse as parsePathRegexp } from "path-to-regexp";
516
+ import { Ajv } from "ajv";
517
+
518
+ // src/config/types.ts
519
+ var isDefaultApplicationConfig = (app) => app.default && typeof app.routing === "undefined";
520
+
521
+ // schema/schema.json
522
+ var schema_default = {
523
+ $schema: "http://json-schema.org/draft-07/schema#",
524
+ $ref: "#/definitions/Config",
525
+ definitions: {
526
+ Config: {
527
+ type: "object",
528
+ properties: {
529
+ version: {
530
+ type: "string"
531
+ },
532
+ $schema: {
533
+ type: "string"
534
+ },
535
+ name: {
536
+ type: "string",
537
+ description: 'Name for the micro-frontend site (eg. "vercel.com", "vercel-site" etc.).'
538
+ },
539
+ applications: {
540
+ $ref: "#/definitions/ApplicationConfigsById"
541
+ },
542
+ options: {
543
+ $ref: "#/definitions/Options",
544
+ description: "Optional configuration for the entire micro-frontends setup."
545
+ }
546
+ },
547
+ required: ["version", "applications"],
548
+ description: "Configuration for micro-frontend applications\n\nTODO: Add proxy configuration"
549
+ },
550
+ ApplicationConfigsById: {
551
+ type: "object",
552
+ additionalProperties: {
553
+ $ref: "#/definitions/ApplicationConfig"
554
+ }
555
+ },
556
+ ApplicationConfig: {
557
+ anyOf: [
558
+ {
559
+ $ref: "#/definitions/DefaultApplicationConfig"
560
+ },
561
+ {
562
+ $ref: "#/definitions/CommonApplicationConfig"
563
+ }
564
+ ],
565
+ description: "A Micro-Frontend Deployment Target"
566
+ },
567
+ DefaultApplicationConfig: {
568
+ type: "object",
569
+ properties: {
570
+ default: {
571
+ type: "boolean",
572
+ const: true,
573
+ description: "The default application is used no other application is matched via the routing config"
574
+ },
575
+ routing: {
576
+ $ref: "#/definitions/Routing"
577
+ },
578
+ development: {
579
+ type: "object",
580
+ properties: {
581
+ local: {
582
+ $ref: "#/definitions/HostConfig"
583
+ },
584
+ fallback: {
585
+ $ref: "#/definitions/HostConfig",
586
+ 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."
587
+ },
588
+ task: {
589
+ type: "string",
590
+ description: "Optional task to run when starting the development server. Should reference a script in the package.json of the application."
591
+ }
592
+ },
593
+ required: ["local"]
594
+ },
595
+ production: {
596
+ $ref: "#/definitions/HostConfig"
597
+ },
598
+ metadata: {
599
+ type: "object",
600
+ additionalProperties: {
601
+ type: "string"
602
+ }
603
+ },
604
+ federation: {
605
+ type: "object",
606
+ properties: {
607
+ exposes: {
608
+ type: "array",
609
+ items: {
610
+ type: "object",
611
+ properties: {
612
+ name: {
613
+ type: "string",
614
+ description: "The name of the module - should be used when importing the module from another application"
615
+ },
616
+ path: {
617
+ type: "string",
618
+ description: "Relative path to the module within its `application`"
619
+ }
620
+ },
621
+ required: ["name", "path"]
622
+ },
623
+ description: "Modules that are exposed by this application"
624
+ },
625
+ uses: {
626
+ type: "array",
627
+ items: {
628
+ type: "string"
629
+ },
630
+ description: "Modules that are used by this application. Only the name of the module is required."
631
+ }
632
+ }
633
+ },
634
+ vercel: {
635
+ $ref: "#/definitions/Vercel"
636
+ }
637
+ },
638
+ required: ["default", "development", "production"]
639
+ },
640
+ Routing: {
641
+ type: "object",
642
+ properties: {
643
+ assetPrefix: {
644
+ type: "string",
645
+ description: "[assetPrefix] for the application"
646
+ },
647
+ matches: {
648
+ type: "array",
649
+ items: {
650
+ $ref: "#/definitions/PathGroup"
651
+ },
652
+ description: "Path expressions that are routed to this application."
653
+ }
654
+ },
655
+ required: ["matches"]
656
+ },
657
+ PathGroup: {
658
+ type: "object",
659
+ properties: {
660
+ group: {
661
+ type: "string",
662
+ description: "Optional group name for the paths"
663
+ },
664
+ options: {
665
+ type: "object",
666
+ properties: {
667
+ flag: {
668
+ type: "string",
669
+ description: "flag name that can be used to enable/disable all paths in the group"
670
+ },
671
+ routeToDefaultApplication: {
672
+ type: "boolean",
673
+ description: "True to route the request to the default application for this micro-frontends set-up. This must be `true` when using `flag` or when you want to use custom logic to make the routing decision for this group of paths."
674
+ }
675
+ }
676
+ },
677
+ paths: {
678
+ type: "array",
679
+ items: {
680
+ type: "string"
681
+ }
682
+ }
683
+ },
684
+ required: ["paths"]
685
+ },
686
+ HostConfig: {
687
+ type: "object",
688
+ properties: {
689
+ protocol: {
690
+ type: "string",
691
+ enum: ["http", "https"],
692
+ 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 "https"'
693
+ },
694
+ host: {
695
+ type: "string",
696
+ 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`)."
697
+ },
698
+ port: {
699
+ type: "number",
700
+ description: "The port number to be used for the connection. Common values include `80` for HTTP and `443` for HTTPS.\n\nThis field is optional and can be omitted if the default ports for the specified protocol are used"
701
+ }
702
+ },
703
+ required: ["host"]
704
+ },
705
+ Vercel: {
706
+ type: "object",
707
+ properties: {
708
+ projectId: {
709
+ type: "string",
710
+ description: "Vercel project ID"
711
+ },
712
+ projectName: {
713
+ type: "string",
714
+ description: "Vercel project name (temporary until we can use project ID)"
715
+ },
716
+ defaultRoute: {
717
+ type: "string",
718
+ description: "The default route for the application. Used to render screenshots, favicons, and provide direct zone links"
719
+ },
720
+ routeSpeedInsightsToDefaultZone: {
721
+ type: "boolean",
722
+ description: "Whether to route Speed Insights to the default zone or each individual microfrontend."
723
+ }
724
+ },
725
+ required: ["projectId"]
726
+ },
727
+ CommonApplicationConfig: {
728
+ type: "object",
729
+ properties: {
730
+ default: {
731
+ type: "boolean",
732
+ const: false,
733
+ description: "The default application is used no other application is matched via the routing config"
734
+ },
735
+ routing: {
736
+ $ref: "#/definitions/Routing"
737
+ },
738
+ development: {
739
+ type: "object",
740
+ properties: {
741
+ local: {
742
+ $ref: "#/definitions/HostConfig"
743
+ },
744
+ fallback: {
745
+ $ref: "#/definitions/HostConfig",
746
+ 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."
747
+ },
748
+ task: {
749
+ type: "string",
750
+ description: "Optional task to run when starting the development server. Should reference a script in the package.json of the application."
751
+ }
752
+ },
753
+ required: ["local"]
754
+ },
755
+ production: {
756
+ $ref: "#/definitions/HostConfig"
757
+ },
758
+ metadata: {
759
+ type: "object",
760
+ additionalProperties: {
761
+ type: "string"
762
+ }
763
+ },
764
+ federation: {
765
+ type: "object",
766
+ properties: {
767
+ exposes: {
768
+ type: "array",
769
+ items: {
770
+ type: "object",
771
+ properties: {
772
+ name: {
773
+ type: "string",
774
+ description: "The name of the module - should be used when importing the module from another application"
775
+ },
776
+ path: {
777
+ type: "string",
778
+ description: "Relative path to the module within its `application`"
779
+ }
780
+ },
781
+ required: ["name", "path"]
782
+ },
783
+ description: "Modules that are exposed by this application"
784
+ },
785
+ uses: {
786
+ type: "array",
787
+ items: {
788
+ type: "string"
789
+ },
790
+ description: "Modules that are used by this application. Only the name of the module is required."
791
+ }
792
+ }
793
+ },
794
+ vercel: {
795
+ $ref: "#/definitions/Vercel"
796
+ }
797
+ },
798
+ required: ["default", "development", "production", "routing"]
799
+ },
800
+ Options: {
801
+ type: "object",
802
+ properties: {
803
+ vercel: {
804
+ $ref: "#/definitions/VercelOptions",
805
+ description: "Micro-Frontends wide options for Vercel."
806
+ },
807
+ localProxy: {
808
+ $ref: "#/definitions/LocalProxyOptions",
809
+ description: "Options for local proxy."
810
+ }
811
+ }
812
+ },
813
+ VercelOptions: {
814
+ type: "object",
815
+ properties: {
816
+ previewDeploymentSuffix: {
817
+ type: "string",
818
+ description: "If your team uses a custom Preview Deployment Suffix, please specify it here. See https://vercel.com/docs/deployments/preview-deployment-suffix. The default is `vercel.app`."
819
+ },
820
+ teamSlug: {
821
+ type: "string",
822
+ description: "Team slug for the Vercel team"
823
+ },
824
+ disableOverrides: {
825
+ type: "boolean",
826
+ 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."
827
+ }
828
+ }
829
+ },
830
+ LocalProxyOptions: {
831
+ type: "object",
832
+ properties: {
833
+ port: {
834
+ type: "number",
835
+ description: "The port number used by the local proxy server.\n\nThe default is `3024`."
836
+ }
837
+ }
838
+ }
839
+ }
840
+ };
841
+
842
+ // src/config/utils/load-schema.ts
843
+ var SCHEMA = schema_default;
844
+
845
+ // src/config/validation.ts
846
+ var validateSchema = (configString) => {
847
+ const parsedConfig = parse(configString);
848
+ const ajv = new Ajv();
849
+ const validate = ajv.compile(SCHEMA);
850
+ const isValid = validate(parsedConfig);
851
+ if (!isValid) {
852
+ throw new MicroFrontendError(
853
+ `Invalid config: ${ajv.errorsText(validate.errors)}`,
854
+ { type: "config", subtype: "does_not_match_schema" }
855
+ );
856
+ }
857
+ return parsedConfig;
858
+ };
859
+ var SUPPORTED_VERSIONS2 = ["1"];
860
+ var validateVersion = (version) => {
861
+ if (!SUPPORTED_VERSIONS2.includes(version)) {
862
+ throw new MicroFrontendError(
863
+ `Unsupported version: ${version}. Supported versions are: ${SUPPORTED_VERSIONS2.join(
864
+ ", "
865
+ )}`,
866
+ { type: "config", subtype: "unsupported_version" }
867
+ );
868
+ }
869
+ };
870
+ function validateMainPath(applicationConfigsById) {
871
+ for (const [id, app] of Object.entries(applicationConfigsById)) {
872
+ const { defaultRoute } = app.vercel ?? {};
873
+ if (!defaultRoute) {
874
+ continue;
875
+ }
876
+ if (isDefaultApplicationConfig(app)) {
877
+ const pathsWithApp = [];
878
+ for (const [otherId, otherApp] of Object.entries(
879
+ applicationConfigsById
880
+ )) {
881
+ if (isDefaultApplicationConfig(otherApp)) {
882
+ continue;
883
+ }
884
+ pathsWithApp.push({
885
+ id: otherId,
886
+ paths: otherApp.routing.matches.flatMap((match) => match.paths)
887
+ });
888
+ }
889
+ for (const { id: otherId, paths } of pathsWithApp) {
890
+ const isValid = paths.every((path3) => {
891
+ const matcher = pathToRegexp(path3);
892
+ return !matcher.test(defaultRoute);
893
+ });
894
+ if (!isValid) {
895
+ throw new MicroFrontendError(
896
+ `default route "${defaultRoute}" cannot be used for "${id}" because it is matched by "${otherId}"`,
897
+ { type: "config", subtype: "invalid_main_path" }
898
+ );
899
+ }
900
+ }
901
+ } else {
902
+ const allPaths = app.routing.matches.flatMap((match) => match.paths);
903
+ const isValid = allPaths.some((path3) => {
904
+ const matcher = pathToRegexp(path3);
905
+ return matcher.test(defaultRoute);
906
+ });
907
+ if (!isValid) {
908
+ throw new MicroFrontendError(
909
+ `default route "${defaultRoute}" is not included by the routing config for application "${id}"`,
910
+ { type: "config", subtype: "invalid_main_path" }
911
+ );
912
+ }
913
+ }
914
+ }
915
+ }
916
+ var validatePaths = (applicationConfigsById) => {
917
+ const pathsByApplicationId = /* @__PURE__ */ new Map();
918
+ const errors = [];
919
+ for (const [id, app] of Object.entries(applicationConfigsById)) {
920
+ if (isDefaultApplicationConfig(app)) {
921
+ continue;
922
+ }
923
+ for (const pathMatch of app.routing.matches) {
924
+ for (const path3 of pathMatch.paths) {
925
+ const maybeError = validatePathExpression(path3);
926
+ if (maybeError) {
927
+ errors.push(maybeError);
928
+ }
929
+ const existing = pathsByApplicationId.get(path3);
930
+ if (existing) {
931
+ existing.applications.push(id);
932
+ } else {
933
+ pathsByApplicationId.set(path3, {
934
+ applications: [id],
935
+ matcher: pathToRegexp(path3),
936
+ applicationId: id
937
+ });
938
+ }
939
+ }
940
+ }
941
+ }
942
+ const entries = Array.from(pathsByApplicationId.entries());
943
+ entries.forEach(([path3, { applications: ids, matcher, applicationId }]) => {
944
+ if (ids.length > 1) {
945
+ errors.push(
946
+ `Duplicate path "${path3}" for applications "${ids.join(", ")}"`
947
+ );
948
+ }
949
+ entries.forEach(
950
+ ([
951
+ matchPath,
952
+ { applications: matchIds, applicationId: matchApplicationId }
953
+ ]) => {
954
+ if (path3 === matchPath) {
955
+ return;
956
+ }
957
+ if (applicationId === matchApplicationId) {
958
+ return;
959
+ }
960
+ if (matcher.test(matchPath)) {
961
+ const source = `"${path3}" of application${ids.length > 0 ? "s" : ""} ${ids.join(", ")}`;
962
+ const destination = `"${matchPath}" of application${matchIds.length > 0 ? "s" : ""} ${matchIds.join(", ")}`;
963
+ errors.push(
964
+ `Overlapping path detected between ${source} and ${destination}`
965
+ );
966
+ }
967
+ }
968
+ );
969
+ });
970
+ if (errors.length) {
971
+ throw new MicroFrontendError(`Invalid paths: ${errors.join(", ")}`, {
972
+ type: "config",
973
+ subtype: "conflicting_paths"
974
+ });
975
+ }
976
+ };
977
+ var PATH_DEFAULT_PATTERN = "[^\\/#\\?]+?";
978
+ function validatePathExpression(path3) {
979
+ const tokens = parsePathRegexp(path3);
980
+ for (let i = 0; i < tokens.length; i++) {
981
+ const token = tokens[i];
982
+ if (token === void 0) {
983
+ return `token ${i} in ${path3} is undefined, this shouldn't happen`;
984
+ }
985
+ if (typeof token !== "string") {
986
+ if (token.pattern !== PATH_DEFAULT_PATTERN) {
987
+ return `Path ${path3} cannot use a regular expression wildcard`;
988
+ }
989
+ if (token.prefix !== "/") {
990
+ return `Wildcard :${token.name} must be immediately after a / in ${path3}`;
991
+ }
992
+ if (token.suffix) {
993
+ return `Wildcard suffix on :${token.name} is not allowed. Suffixes are not supported`;
994
+ }
995
+ if (token.modifier && i !== tokens.length - 1) {
996
+ return `Modifier ${token.modifier} is not allowed on wildcard :${token.name} in ${path3}. Modifiers are only allowed in the last path component`;
997
+ }
998
+ }
999
+ }
1000
+ return void 0;
1001
+ }
1002
+ var validateDefaults = (applicationConfigsById) => {
1003
+ const defaultApplicationIds = Object.entries(applicationConfigsById).reduce((acc, [id, app]) => app.default ? [...acc, id] : acc, []);
1004
+ if (defaultApplicationIds.length === 0) {
1005
+ throw new MicroFrontendError(
1006
+ `No default application found. At least one application must be marked as default.`,
1007
+ { type: "config", subtype: "no_default_application" }
1008
+ );
1009
+ }
1010
+ if (defaultApplicationIds.length > 1) {
1011
+ throw new MicroFrontendError(
1012
+ `Only one default application is allowed. Found ${defaultApplicationIds.join(", ")}.`,
1013
+ { type: "config", subtype: "multiple_default_applications" }
1014
+ );
1015
+ }
1016
+ };
1017
+ var validateOptions = (options) => {
1018
+ var _a;
1019
+ if ((_a = options == null ? void 0 : options.vercel) == null ? void 0 : _a.previewDeploymentSuffix) {
1020
+ if (!/^[a-zA-Z]{2,}\.[a-zA-Z]{2,}$/.test(
1021
+ options.vercel.previewDeploymentSuffix
1022
+ )) {
1023
+ throw new MicroFrontendError(
1024
+ `Invalid preview deployment suffix: ${options.vercel.previewDeploymentSuffix}. Should have be formatted like "vercel.app".`,
1025
+ { type: "config", subtype: "invalid_preview_deployment_suffix" }
1026
+ );
1027
+ }
1028
+ }
1029
+ };
1030
+
1031
+ // src/config/utils/convert.ts
1032
+ function convertV1RoutingToV2Routing(routing) {
1033
+ return routing.matches.map((group) => {
1034
+ var _a, _b;
1035
+ return {
1036
+ group: group.group,
1037
+ flag: (_a = group.options) == null ? void 0 : _a.flag,
1038
+ routeToDefaultApplication: (_b = group.options) == null ? void 0 : _b.routeToDefaultApplication,
1039
+ paths: group.paths
1040
+ };
1041
+ });
1042
+ }
1043
+ function convertV1ApplicationToV2Application(application) {
1044
+ const common = {
1045
+ production: application.production,
1046
+ development: application.development,
1047
+ vercel: application.vercel
1048
+ };
1049
+ if (application.default) {
1050
+ return common;
1051
+ }
1052
+ return {
1053
+ ...common,
1054
+ routing: convertV1RoutingToV2Routing(application.routing)
1055
+ };
1056
+ }
1057
+ function convertV1ConfigToV2Config(config, fromApp) {
1058
+ if (!config.applications[fromApp]) {
1059
+ throw new Error(`Application "${fromApp}" not found in the config`);
1060
+ }
1061
+ const common = {
1062
+ version: "2",
1063
+ options: config.options
1064
+ };
1065
+ if (config.applications[fromApp].default) {
1066
+ return {
1067
+ ...common,
1068
+ // this is assumed for now, and by the time this is released we won't need this conversion
1069
+ provider: "vercel",
1070
+ applications: Object.fromEntries(
1071
+ Object.entries(config.applications).map(([id, application]) => [
1072
+ id,
1073
+ convertV1ApplicationToV2Application(application)
1074
+ ])
1075
+ )
1076
+ };
1077
+ }
1078
+ return {
1079
+ ...common,
1080
+ partOf: fromApp
1081
+ };
1082
+ }
1083
+
1084
+ // src/config/utils/write-file.ts
1085
+ import fs from "node:fs";
1086
+ import { dirname } from "node:path";
1087
+ function writeFile(outputPath, config, prettify) {
1088
+ fs.mkdirSync(dirname(outputPath), { recursive: true });
1089
+ fs.writeFileSync(
1090
+ outputPath,
1091
+ JSON.stringify(config, null, prettify ? 2 : void 0)
1092
+ );
1093
+ }
1094
+
1095
+ // src/config/micro-frontend-config.ts
1096
+ var MicroFrontendConfig = class extends MicroFrontendConfigCommon {
1097
+ static validate(configString) {
1098
+ const config = validateSchema(configString);
1099
+ validateVersion(config.version);
1100
+ validatePaths(config.applications);
1101
+ validateMainPath(config.applications);
1102
+ validateDefaults(config.applications);
1103
+ validateOptions(config.options);
1104
+ return config;
1105
+ }
1106
+ static fromEnv({
1107
+ cookies
1108
+ }) {
1109
+ return new MicroFrontendConfigCommon({
1110
+ config: MicroFrontendConfig.validate(
1111
+ MicroFrontendConfigCommon.getConfigFromEnv()
1112
+ ),
1113
+ overrides: Overrides.parseOverrides(cookies)
1114
+ });
1115
+ }
1116
+ static fromFile({
1117
+ filePath
1118
+ }) {
1119
+ try {
1120
+ const config = fs2.readFileSync(filePath, "utf-8");
1121
+ return new MicroFrontendConfig({
1122
+ config: MicroFrontendConfig.validate(config)
1123
+ });
1124
+ } catch (e) {
1125
+ throw MicroFrontendError.handle(e, {
1126
+ fileName: filePath
1127
+ });
1128
+ }
1129
+ }
1130
+ /**
1131
+ * Writes the configuration to a file.
1132
+ */
1133
+ write(fromApp, opts = {}) {
1134
+ const { pretty = true, versions = ["v1", "v2"] } = opts;
1135
+ const config = this.toSchemaJson();
1136
+ if (versions.includes("v1")) {
1137
+ const outputPath = getOutputFilePath2();
1138
+ writeFile(outputPath, config, pretty);
1139
+ }
1140
+ if (versions.includes("v2")) {
1141
+ const outputPath = getOutputFilePath();
1142
+ const v2Config = convertV1ConfigToV2Config(config, fromApp);
1143
+ writeFile(outputPath, v2Config, pretty);
1144
+ }
1145
+ }
1146
+ };
1147
+
1148
+ // src/next/utils/check-proxy.ts
1149
+ function displayLocalProxyInfo(port) {
1150
+ const { MFE_PROXY_MESSAGE_PRINTED, TURBO_TASK_HAS_MFE_PROXY } = process.env;
1151
+ if (TURBO_TASK_HAS_MFE_PROXY === "true" && MFE_PROXY_MESSAGE_PRINTED !== "true") {
1152
+ process.env.MFE_PROXY_MESSAGE_PRINTED = "true";
1153
+ console.log(`Microfrontends Proxy running on http://localhost:${port}`);
1154
+ }
1155
+ }
1156
+
1157
+ // src/next/config/transforms/asset-prefix.ts
1158
+ function transform(args) {
1159
+ var _a;
1160
+ const { next, zone } = args;
1161
+ if (!((_a = zone.routing) == null ? void 0 : _a.assetPrefix)) {
1162
+ return {
1163
+ next
1164
+ };
1165
+ }
1166
+ if (next.assetPrefix !== void 0 && next.assetPrefix !== zone.routing.assetPrefix) {
1167
+ throw new Error(
1168
+ `"assetPrefix" already set. Overwriting with "${zone.name}"`
1169
+ );
1170
+ }
1171
+ next.assetPrefix = `/${zone.routing.assetPrefix}`;
1172
+ return {
1173
+ next
1174
+ };
1175
+ }
1176
+
1177
+ // src/next/config/transforms/draft-mode.ts
1178
+ function transform2(args) {
1179
+ var _a;
1180
+ const { next } = args;
1181
+ if (((_a = next.experimental) == null ? void 0 : _a.multiZoneDraftMode) !== void 0) {
1182
+ return {
1183
+ next
1184
+ };
1185
+ }
1186
+ next.experimental = next.experimental || {};
1187
+ next.experimental.multiZoneDraftMode = true;
1188
+ return {
1189
+ next
1190
+ };
1191
+ }
1192
+
1193
+ // src/next/config/transforms/headers.ts
1194
+ function transform3(args) {
1195
+ const { next, zone } = args;
1196
+ if (zone.isDefault()) {
1197
+ return {
1198
+ next
1199
+ };
1200
+ }
1201
+ const headersToAdd = [
1202
+ {
1203
+ source: "/:path*",
1204
+ headers: [
1205
+ {
1206
+ key: "X-Vercel-Zone",
1207
+ value: zone.name
1208
+ }
1209
+ ]
1210
+ },
1211
+ {
1212
+ source: "/:path*",
1213
+ has: [
1214
+ {
1215
+ type: "host",
1216
+ value: "(?<host>.*)"
1217
+ }
1218
+ ],
1219
+ headers: [
1220
+ {
1221
+ // TODO: we may want to revisit before launch whether we want to expose this
1222
+ // value on all responses publicly since users may not want to reveal this host
1223
+ // (maybe just in preview? or when the user is logged in to the toolbar?)
1224
+ key: "X-Vercel-Host",
1225
+ value: ":host"
1226
+ }
1227
+ ]
1228
+ }
1229
+ ];
1230
+ if (next.headers && typeof next.headers === "function") {
1231
+ const originalHeadersFn = next.headers;
1232
+ next.headers = async () => {
1233
+ const originalHeaders = await originalHeadersFn();
1234
+ return [...originalHeaders, ...headersToAdd];
1235
+ };
1236
+ } else {
1237
+ next.headers = () => {
1238
+ return Promise.resolve(headersToAdd);
1239
+ };
1240
+ }
1241
+ return {
1242
+ next
1243
+ };
1244
+ }
1245
+
1246
+ // src/routing/get-preview-domain.ts
1247
+ import { createHash } from "node:crypto";
1248
+ var DOMAIN_SIZE = 253;
1249
+ var DOMAIN_LABEL_SIZE = 63;
1250
+ function getMaxLabelLength(domain) {
1251
+ return Math.min(DOMAIN_SIZE - domain.length - 1, DOMAIN_LABEL_SIZE);
1252
+ }
1253
+ function parseBranchUrl(branchUrl) {
1254
+ const branchUrlParts = branchUrl.split(".");
1255
+ if (branchUrlParts.length < 3) {
1256
+ throw new Error(`Could not parse Vercel branch URL "${branchUrl}"`);
1257
+ }
1258
+ const domain = [branchUrlParts[1], branchUrlParts[2]].join(".");
1259
+ return {
1260
+ // biome-ignore lint/style/noNonNullAssertion: Ignored using `--suppress`
1261
+ label: branchUrlParts[0],
1262
+ domain
1263
+ };
1264
+ }
1265
+ function getDomainSuffix(branchUrl, vercelUrl) {
1266
+ const branchLabelParts = parseBranchUrl(branchUrl).label.split("-");
1267
+ const vercelUrlLabelParts = parseBranchUrl(vercelUrl).label.split("-");
1268
+ const suffixParts = [];
1269
+ for (let i = 1; i < branchLabelParts.length; i++) {
1270
+ if (branchLabelParts.at(-1 * i) === vercelUrlLabelParts.at(-1 * i)) {
1271
+ suffixParts.push(branchLabelParts.at(-1 * i) ?? "");
1272
+ }
1273
+ }
1274
+ return suffixParts.reverse().filter(Boolean).join("-");
1275
+ }
1276
+ function getPreviewDomain(zone) {
1277
+ var _a;
1278
+ const targetVercelProjectName = (_a = zone.vercel) == null ? void 0 : _a.projectName;
1279
+ if (!targetVercelProjectName) {
1280
+ throw new Error(
1281
+ `Missing Vercel project configuration for application "${zone.name}"`
1282
+ );
1283
+ }
1284
+ const { VERCEL_GIT_COMMIT_REF, VERCEL_BRANCH_URL, VERCEL_URL } = process.env;
1285
+ if (VERCEL_GIT_COMMIT_REF && VERCEL_BRANCH_URL && VERCEL_URL) {
1286
+ const branchUrlParts = parseBranchUrl(VERCEL_BRANCH_URL);
1287
+ const { domain } = branchUrlParts;
1288
+ const stagingSuffix = domain !== "vercel.sh" ? getDomainSuffix(VERCEL_BRANCH_URL, VERCEL_URL) : "";
1289
+ const gitBranch = `git-${VERCEL_GIT_COMMIT_REF.toLocaleLowerCase()}`;
1290
+ const gitBranchForHash = `git-${VERCEL_GIT_COMMIT_REF}`;
1291
+ const urlSafeBranch = makeUrlSafe(gitBranch);
1292
+ const urlSafeProjectName = makeUrlSafe(targetVercelProjectName);
1293
+ const maxLabelLength = getMaxLabelLength(domain);
1294
+ const label = [urlSafeProjectName, urlSafeBranch, stagingSuffix].filter(Boolean).join("-");
1295
+ if (label.length > maxLabelLength) {
1296
+ let newLabel = makeUrlSafe(stagingSuffix).slice(0, maxLabelLength);
1297
+ const hash = createHash("sha256").update(`${gitBranchForHash}${targetVercelProjectName}`).digest("hex").slice(0, 6);
1298
+ newLabel = [hash, newLabel].filter(Boolean).join("-");
1299
+ const projectNamePart = makeUrlSafe(
1300
+ urlSafeProjectName.slice(0, maxLabelLength - newLabel.length - 1 - 4)
1301
+ );
1302
+ const branchPart = makeUrlSafe(
1303
+ urlSafeBranch.slice(
1304
+ 0,
1305
+ Math.max(
1306
+ 0,
1307
+ maxLabelLength - (newLabel.length + projectNamePart.length) - 2
1308
+ )
1309
+ )
1310
+ );
1311
+ if (branchPart.length >= 3) {
1312
+ newLabel = [branchPart, newLabel].filter(Boolean).join("-");
1313
+ }
1314
+ if (projectNamePart) {
1315
+ newLabel = [projectNamePart, newLabel].filter(Boolean).join("-");
1316
+ }
1317
+ return `https://${newLabel}.${domain}`;
1318
+ }
1319
+ return `https://${label}.${domain}`;
1320
+ }
1321
+ return zone.production.toString();
1322
+ }
1323
+
1324
+ // src/routing/get-domain-for-current-environment.ts
1325
+ function debugDomains(zone, env, domain) {
1326
+ if (process.env.MFE_DEBUG === "true") {
1327
+ const indent = " ".repeat(4);
1328
+ const header = "domains (zone (env) -> domain)";
1329
+ const separator = "\u23AF".repeat(header.length);
1330
+ const line = `${indent} 1. ${zone} (${env}) -> ${domain}`;
1331
+ console.log(`${indent}${header}
1332
+ ${indent}${separator}
1333
+ ${line}
1334
+ `);
1335
+ }
1336
+ }
1337
+ function getDomainForCurrentEnvironment(zone) {
1338
+ var _a;
1339
+ if ((_a = zone.overrides) == null ? void 0 : _a.environment) {
1340
+ return zone.overrides.environment.toString();
1341
+ }
1342
+ const zoneName = zone.name;
1343
+ if (!process.env.VERCEL_ENV || process.env.VERCEL_ENV === "development") {
1344
+ const domain = process.env.NODE_ENV === "test" ? zone.development.local.toString() : zone.production.toString();
1345
+ debugDomains(zoneName, "development", domain);
1346
+ return domain;
1347
+ } else if (process.env.VERCEL_ENV === "production") {
1348
+ const domain = zone.production.toString();
1349
+ debugDomains(zoneName, "production", domain);
1350
+ return domain;
1351
+ } else if (process.env.VERCEL_ENV === "preview") {
1352
+ const MFE_PREVIEW_DOMAINS = JSON.parse(
1353
+ process.env.MFE_PREVIEW_DOMAINS ?? "{}"
1354
+ );
1355
+ if (MFE_PREVIEW_DOMAINS[zoneName]) {
1356
+ debugDomains(zoneName, "preview", MFE_PREVIEW_DOMAINS[zoneName]);
1357
+ return MFE_PREVIEW_DOMAINS[zoneName];
1358
+ }
1359
+ throw new Error(
1360
+ `Could not find preview domain for application "${zoneName}"`
1361
+ );
1362
+ }
1363
+ debugDomains(zoneName, process.env.VERCEL_ENV, zone.production.toString());
1364
+ return zone.production.toString();
1365
+ }
1366
+
1367
+ // src/next/config/transforms/rewrites.ts
1368
+ function debugRewrites(rewrites) {
1369
+ if (process.env.MFE_DEBUG === "true") {
1370
+ const indent = " ".repeat(4);
1371
+ const header = "rewrites (source \u2192 destination)";
1372
+ const separator = "\u23AF".repeat(header.length);
1373
+ const maxSourceLength = Math.max(
1374
+ ...rewrites.map((key) => key.source.length)
1375
+ );
1376
+ const table = rewrites.map((route, idx) => {
1377
+ const paddedSource = route.source.padEnd(maxSourceLength);
1378
+ return `${indent} ${idx + 1}. ${paddedSource} \u2192 ${route.destination}`;
1379
+ }).join("\n");
1380
+ console.log(`${indent}${header}
1381
+ ${indent}${separator}
1382
+ ${table}
1383
+ `);
1384
+ }
1385
+ }
1386
+ function pathToRewrites(path3) {
1387
+ var _a;
1388
+ const regex = /(?<base>^.+)\/:.+\*$/;
1389
+ const match = regex.exec(path3);
1390
+ const paths = [path3];
1391
+ if ((_a = match == null ? void 0 : match.groups) == null ? void 0 : _a.base) {
1392
+ paths.unshift(match.groups.base);
1393
+ }
1394
+ return paths;
1395
+ }
1396
+ function rewritesMapToArr(rewrites) {
1397
+ return Array.from(rewrites.entries()).flatMap(([source, rewrite]) => {
1398
+ const destination = `${rewrite.destination.domain || ""}${rewrite.destination.pathname}`;
1399
+ if (source === destination)
1400
+ return [];
1401
+ return [
1402
+ {
1403
+ source,
1404
+ destination
1405
+ }
1406
+ ];
1407
+ });
1408
+ }
1409
+ function transform4(args) {
1410
+ const { next, microFrontend, zone } = args;
1411
+ const buildBeforeFiles = () => {
1412
+ var _a, _b, _c, _d, _e;
1413
+ const rewrites = /* @__PURE__ */ new Map();
1414
+ if ((_a = zone.routing) == null ? void 0 : _a.assetPrefix) {
1415
+ rewrites.set(`/${zone.routing.assetPrefix}/_next/:path+`, {
1416
+ destination: {
1417
+ pathname: `/_next/:path+`
1418
+ }
1419
+ });
1420
+ if (!((_b = zone.vercel) == null ? void 0 : _b.routeSpeedInsightsToDefaultZone)) {
1421
+ rewrites.set(`/${zone.routing.assetPrefix}/_vercel/:path*`, {
1422
+ destination: { pathname: "/_vercel/:path*" }
1423
+ });
1424
+ }
1425
+ }
1426
+ if (zone.isDefault()) {
1427
+ for (const [_, z] of Object.entries(microFrontend.zones)) {
1428
+ if (zone.name === z.name) {
1429
+ continue;
1430
+ }
1431
+ const { routing } = z;
1432
+ if (!routing) {
1433
+ continue;
1434
+ }
1435
+ const domain = process.env.VERCEL_ENV === "preview" ? getPreviewDomain(z) : getDomainForCurrentEnvironment(z);
1436
+ if ((_c = z.routing) == null ? void 0 : _c.assetPrefix) {
1437
+ rewrites.set(`/${z.routing.assetPrefix}/:path+`, {
1438
+ destination: {
1439
+ domain,
1440
+ pathname: `/${z.routing.assetPrefix}/:path+`
1441
+ }
1442
+ });
1443
+ }
1444
+ for (const group of routing.matches) {
1445
+ if ((_d = group.options) == null ? void 0 : _d.routeToDefaultApplication) {
1446
+ continue;
1447
+ } else if ((_e = group.options) == null ? void 0 : _e.flag) {
1448
+ continue;
1449
+ } else {
1450
+ for (const source of group.paths) {
1451
+ const paths = pathToRewrites(source);
1452
+ for (const p of paths) {
1453
+ rewrites.set(p, {
1454
+ destination: { domain, pathname: p }
1455
+ });
1456
+ }
1457
+ }
1458
+ }
1459
+ }
1460
+ }
1461
+ } else {
1462
+ }
1463
+ return rewritesMapToArr(rewrites);
1464
+ };
1465
+ const newBeforeFiles = buildBeforeFiles();
1466
+ if (next.rewrites && typeof next.rewrites === "function") {
1467
+ const originalRewritesFn = next.rewrites;
1468
+ next.rewrites = async () => {
1469
+ const originalRewrites = await originalRewritesFn();
1470
+ if (typeof originalRewrites === "object" && !Array.isArray(originalRewrites)) {
1471
+ const { beforeFiles = [] } = originalRewrites;
1472
+ return {
1473
+ beforeFiles: [...newBeforeFiles, ...beforeFiles],
1474
+ afterFiles: originalRewrites.afterFiles,
1475
+ fallback: originalRewrites.fallback
1476
+ };
1477
+ }
1478
+ return {
1479
+ beforeFiles: newBeforeFiles,
1480
+ afterFiles: originalRewrites,
1481
+ fallback: []
1482
+ };
1483
+ };
1484
+ } else {
1485
+ next.rewrites = async () => ({
1486
+ beforeFiles: newBeforeFiles,
1487
+ afterFiles: [],
1488
+ fallback: []
1489
+ });
1490
+ }
1491
+ debugRewrites(newBeforeFiles);
1492
+ return {
1493
+ next
1494
+ };
1495
+ }
1496
+
1497
+ // src/next/config/transforms/server-actions.ts
1498
+ var formatDomainForServerAction = (domain) => domain.replace(/https?:\/\//, "");
1499
+ function transform5(args) {
1500
+ var _a;
1501
+ const { next, zone, microFrontend } = args;
1502
+ const zonesToAllow = [
1503
+ // this zone - this is included by default unless allowedOrigins is overridden (which we are)
1504
+ // so we re-add it here.
1505
+ zone,
1506
+ // this is the default zone for the micro-frontend. Allow child zones to call server actions
1507
+ // that are in the default zone.
1508
+ microFrontend.getDefaultZone()
1509
+ ];
1510
+ const existingServerActionConfig = (_a = next.experimental) == null ? void 0 : _a.serverActions;
1511
+ next.experimental = {
1512
+ ...next.experimental,
1513
+ serverActions: {
1514
+ ...existingServerActionConfig,
1515
+ allowedOrigins: Array.from(
1516
+ /* @__PURE__ */ new Set([
1517
+ ...(existingServerActionConfig == null ? void 0 : existingServerActionConfig.allowedOrigins) ?? [],
1518
+ ...zonesToAllow.flatMap((z) => [
1519
+ formatDomainForServerAction(z.production.toString()),
1520
+ formatDomainForServerAction(getDomainForCurrentEnvironment(z))
1521
+ ])
1522
+ ])
1523
+ )
1524
+ }
1525
+ };
1526
+ return {
1527
+ next
1528
+ };
1529
+ }
1530
+
1531
+ // src/next/config/transforms/webpack.ts
1532
+ function transform6(args) {
1533
+ const { next, microFrontend } = args;
1534
+ const previewDomains = process.env.VERCEL_ENV === "preview" ? microFrontend.getAllApplications().reduce(
1535
+ (obj, app) => {
1536
+ obj[app.name] = getPreviewDomain(app);
1537
+ return obj;
1538
+ },
1539
+ // eslint-disable-next-line @typescript-eslint/prefer-reduce-type-parameter -- needed to satisfy TSC
1540
+ {}
1541
+ ) : {};
1542
+ const configWithWebpack = {
1543
+ ...next,
1544
+ webpack(cfg, context) {
1545
+ const config = typeof next.webpack === "function" ? next.webpack(cfg, context) : cfg;
1546
+ const { isServer, nextRuntime, webpack: wpFromNext } = context;
1547
+ if (isServer || nextRuntime === "edge") {
1548
+ config.plugins.push(
1549
+ new wpFromNext.EnvironmentPlugin({
1550
+ MFE_CONFIG: JSON.stringify(microFrontend.serialize()),
1551
+ MFE_PREVIEW_DOMAINS: JSON.stringify(previewDomains)
1552
+ })
1553
+ );
1554
+ }
1555
+ config.plugins.push(
1556
+ // Remove node: from import specifiers, because Next.js does not yet support node: scheme
1557
+ // https://github.com/vercel/next.js/issues/28774
1558
+ new wpFromNext.NormalModuleReplacementPlugin(
1559
+ /^node:/,
1560
+ (resource) => {
1561
+ resource.request = resource.request.replace(/^node:/, "");
1562
+ }
1563
+ )
1564
+ );
1565
+ if (!isServer) {
1566
+ config.resolve.fallback = {
1567
+ fs: false,
1568
+ path: false,
1569
+ crypto: false,
1570
+ ...config.resolve.fallback
1571
+ };
1572
+ }
1573
+ return config;
1574
+ }
1575
+ };
1576
+ return {
1577
+ next: configWithWebpack
1578
+ };
1579
+ }
1580
+
1581
+ // src/next/config/transforms/index.ts
1582
+ var transforms = {
1583
+ assetPrefix: transform,
1584
+ draftMode: transform2,
1585
+ headers: transform3,
1586
+ rewrites: transform4,
1587
+ serverActions: transform5,
1588
+ webpack: transform6
1589
+ };
1590
+
1591
+ // src/config/client/client-config.ts
1592
+ function getConfigForClient(config) {
1593
+ return {
1594
+ applications: Object.fromEntries(
1595
+ Object.entries(config.applications).map(([name, application]) => [
1596
+ name,
1597
+ {
1598
+ default: application.default,
1599
+ routing: application.routing
1600
+ }
1601
+ ])
1602
+ )
1603
+ };
1604
+ }
1605
+
1606
+ // src/next/config/env.ts
1607
+ function debugEnv(env) {
1608
+ if (process.env.MFE_DEBUG === "true") {
1609
+ const indent = " ".repeat(4);
1610
+ const header = "env (key \u2192 val)";
1611
+ const separator = "\u23AF".repeat(header.length);
1612
+ const maxKeyLength = Math.max(...Object.keys(env).map((key) => key.length));
1613
+ const table = Object.keys(env).map((key, idx) => {
1614
+ const paddedKey = key.padEnd(maxKeyLength);
1615
+ return `${indent} ${idx + 1}. ${paddedKey} = ${env[key]}`;
1616
+ }).join("\n");
1617
+ console.log(`${indent}${header}
1618
+ ${indent}${separator}
1619
+ ${table}
1620
+ `);
1621
+ }
1622
+ }
1623
+ function setEnvironment({
1624
+ zone,
1625
+ config
1626
+ }) {
1627
+ var _a, _b, _c, _d;
1628
+ const previewDomains = process.env.VERCEL_ENV === "preview" ? config.getAllApplications().reduce(
1629
+ (obj, app) => {
1630
+ obj[app.name] = getPreviewDomain(app);
1631
+ return obj;
1632
+ },
1633
+ // eslint-disable-next-line @typescript-eslint/prefer-reduce-type-parameter -- needed to satisfy TSC
1634
+ {}
1635
+ ) : {};
1636
+ const clientEnvs = {
1637
+ NEXT_PUBLIC_MFE_CURRENT_APPLICATION: zone.name,
1638
+ NEXT_PUBLIC_MFE_CLIENT_CONFIG: JSON.stringify(
1639
+ getConfigForClient(config.getConfig())
1640
+ ),
1641
+ ...((_a = zone.vercel) == null ? void 0 : _a.routeSpeedInsightsToDefaultZone) && ((_b = zone.routing) == null ? void 0 : _b.assetPrefix) ? {} : {
1642
+ NEXT_PUBLIC_SPEED_INSIGHTS_BASEPATH: (_c = zone.routing) == null ? void 0 : _c.assetPrefix,
1643
+ NEXT_PUBLIC_WEB_ANALYTICS_BASEPATH: (_d = zone.routing) == null ? void 0 : _d.assetPrefix
1644
+ }
1645
+ };
1646
+ const serverEnvs = {
1647
+ MFE_CURRENT_APPLICATION: zone.name,
1648
+ MFE_PREVIEW_DOMAINS: JSON.stringify(previewDomains),
1649
+ MFE_CONFIG: JSON.stringify(config.getConfig())
1650
+ };
1651
+ const allEnvs = { ...clientEnvs, ...serverEnvs };
1652
+ for (const [key, value] of Object.entries(allEnvs)) {
1653
+ process.env[key] = value;
1654
+ }
1655
+ debugEnv(allEnvs);
1656
+ }
1657
+
1658
+ // src/next/config/index.ts
1659
+ function typedEntries(obj) {
1660
+ return Object.entries(obj);
1661
+ }
1662
+ function isProduction(opts) {
1663
+ if (opts == null ? void 0 : opts.isProduction) {
1664
+ return opts.isProduction();
1665
+ }
1666
+ return process.env.VERCEL_ENV === "production";
1667
+ }
1668
+ function getConfigPath(opts) {
1669
+ var _a;
1670
+ if (opts == null ? void 0 : opts.configPath) {
1671
+ return { configPath: opts.configPath };
1672
+ }
1673
+ try {
1674
+ const vercelJsonString = fs3.readFileSync("./vercel.json", "utf-8");
1675
+ const vercelJson = JSON.parse(vercelJsonString);
1676
+ if (!((_a = vercelJson.microFrontends) == null ? void 0 : _a.config)) {
1677
+ throw new MicroFrontendError(
1678
+ `vercel.json file missing required field "microFrontends.config"`,
1679
+ {
1680
+ type: "vercelJson",
1681
+ subtype: "missing_field_microFrontend_config_path",
1682
+ source: "@vercel/micro-frontends/next"
1683
+ }
1684
+ );
1685
+ }
1686
+ return { configPath: vercelJson.microFrontends.config };
1687
+ } catch (err) {
1688
+ throw MicroFrontendError.handle(err, {
1689
+ fileName: "vercel.json"
1690
+ });
1691
+ }
1692
+ }
1693
+ function getApplicationContext(opts) {
1694
+ if (opts == null ? void 0 : opts.appName) {
1695
+ return { name: opts.appName };
1696
+ }
1697
+ try {
1698
+ const packageJsonString = fs3.readFileSync("./package.json", "utf-8");
1699
+ const packageJson = JSON.parse(packageJsonString);
1700
+ if (!packageJson.name) {
1701
+ throw new MicroFrontendError(
1702
+ `package.json file missing required field "name"`,
1703
+ {
1704
+ type: "packageJson",
1705
+ subtype: "missing_field_name",
1706
+ source: "@vercel/micro-frontends/next"
1707
+ }
1708
+ );
1709
+ }
1710
+ return { name: packageJson.name };
1711
+ } catch (err) {
1712
+ throw MicroFrontendError.handle(err, {
1713
+ fileName: "package.json"
1714
+ });
1715
+ }
1716
+ }
1717
+ function withMicroFrontends(nextConfig, opts) {
1718
+ var _a;
1719
+ if (opts == null ? void 0 : opts.debug) {
1720
+ process.env.MFE_DEBUG = "true";
1721
+ }
1722
+ const { name } = getApplicationContext(opts);
1723
+ const { configPath } = getConfigPath(opts);
1724
+ const mfConfig = MicroFrontendConfig.fromFile({
1725
+ filePath: configPath
1726
+ });
1727
+ const zone = mfConfig.getZone(name);
1728
+ setEnvironment({ zone, config: mfConfig });
1729
+ let next = { ...nextConfig };
1730
+ for (const [key, transform7] of typedEntries(transforms)) {
1731
+ if ((_a = opts == null ? void 0 : opts.skipTransforms) == null ? void 0 : _a.includes(key)) {
1732
+ console.log(`Skipping ${key} transform`);
1733
+ continue;
1734
+ }
1735
+ try {
1736
+ const transformedConfig = transform7({
1737
+ zone,
1738
+ next,
1739
+ microFrontend: mfConfig,
1740
+ opts: {
1741
+ isProduction: isProduction(opts)
1742
+ }
1743
+ });
1744
+ next = transformedConfig.next;
1745
+ } catch (e) {
1746
+ console.error("Error transforming next config", e);
1747
+ }
1748
+ }
1749
+ displayLocalProxyInfo(mfConfig.getLocalProxyPort());
1750
+ if (isVercel()) {
1751
+ mfConfig.write(zone.name, { versions: ["v1", "v2"] });
1752
+ }
1753
+ return next;
1754
+ }
1755
+ export {
1756
+ withMicroFrontends
1757
+ };
1758
+ //# sourceMappingURL=config.js.map