@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,1389 @@
1
+ // src/next/testing/index.ts
2
+ import { readFileSync } from "node:fs";
3
+ import {
4
+ NextRequest
5
+ } from "next/server";
6
+ import { match } from "path-to-regexp";
7
+ import { parse as parse2 } from "jsonc-parser";
8
+ import { matchHas } from "next/dist/shared/lib/router/utils/prepare-destination";
9
+ import { NextRequestHint } from "next/dist/server/web/adapter";
10
+ import { WebNextRequest } from "next/dist/server/base-http/web";
11
+
12
+ // src/config/types.ts
13
+ var isDefaultApplicationConfig = (app) => app.default && typeof app.routing === "undefined";
14
+
15
+ // src/config/micro-frontend-config.ts
16
+ import fs2 from "node:fs";
17
+
18
+ // src/config-v2/microfrontends/server/utils/get-output-file-path.ts
19
+ import path from "node:path";
20
+
21
+ // src/config-v2/microfrontends/server/constants.ts
22
+ var MFE_CONFIG_DEFAULT_FILE_PATH = "microfrontends";
23
+ var MFE_CONFIG_DEFAULT_FILE_NAME = "microfrontends.json";
24
+
25
+ // src/utils/is-vercel.ts
26
+ function isVercel() {
27
+ return process.env.VERCEL === "1";
28
+ }
29
+
30
+ // src/config-v2/microfrontends/server/utils/get-output-file-path.ts
31
+ function getOutputFilePath() {
32
+ if (isVercel()) {
33
+ return path.join(
34
+ ".vercel",
35
+ MFE_CONFIG_DEFAULT_FILE_PATH,
36
+ MFE_CONFIG_DEFAULT_FILE_NAME
37
+ );
38
+ }
39
+ return path.join(MFE_CONFIG_DEFAULT_FILE_PATH, MFE_CONFIG_DEFAULT_FILE_NAME);
40
+ }
41
+
42
+ // src/config/errors.ts
43
+ var MicroFrontendError = class extends Error {
44
+ constructor(message, opts) {
45
+ super(message);
46
+ this.name = "MicroFrontendsError";
47
+ this.source = (opts == null ? void 0 : opts.source) ?? "@vercel/micro-frontends";
48
+ this.type = (opts == null ? void 0 : opts.type) ?? "unknown";
49
+ this.subtype = opts == null ? void 0 : opts.subtype;
50
+ Error.captureStackTrace(this, MicroFrontendError);
51
+ }
52
+ isKnown() {
53
+ return this.type !== "unknown";
54
+ }
55
+ isUnknown() {
56
+ return !this.isKnown();
57
+ }
58
+ /**
59
+ * Converts an error to a MicroFrontendsError.
60
+ * @param original - The original error to convert.
61
+ * @returns The converted MicroFrontendsError.
62
+ */
63
+ static convert(original, opts) {
64
+ if (opts == null ? void 0 : opts.fileName) {
65
+ const err = MicroFrontendError.convertFSError(original, opts.fileName);
66
+ if (err) {
67
+ return err;
68
+ }
69
+ }
70
+ if (original.message.includes(
71
+ "Code generation from strings disallowed for this context"
72
+ )) {
73
+ return new MicroFrontendError(original.message, {
74
+ type: "config",
75
+ subtype: "unsupported_validation_env",
76
+ source: "ajv"
77
+ });
78
+ }
79
+ return new MicroFrontendError(original.message);
80
+ }
81
+ static convertFSError(original, fileName) {
82
+ if (original instanceof Error && "code" in original) {
83
+ if (original.code === "ENOENT") {
84
+ return new MicroFrontendError(`Could not find "${fileName}"`, {
85
+ type: "config",
86
+ subtype: "unable_to_read_file",
87
+ source: "fs"
88
+ });
89
+ }
90
+ if (original.code === "EACCES") {
91
+ return new MicroFrontendError(
92
+ `Permission denied while accessing "${fileName}"`,
93
+ {
94
+ type: "config",
95
+ subtype: "invalid_permissions",
96
+ source: "fs"
97
+ }
98
+ );
99
+ }
100
+ }
101
+ if (original instanceof SyntaxError) {
102
+ return new MicroFrontendError(
103
+ `Failed to parse "${fileName}": Invalid JSON format.`,
104
+ {
105
+ type: "config",
106
+ subtype: "invalid_syntax",
107
+ source: "fs"
108
+ }
109
+ );
110
+ }
111
+ return null;
112
+ }
113
+ /**
114
+ * Handles an unknown error and returns a MicroFrontendsError instance.
115
+ * @param err - The error to handle.
116
+ * @returns A MicroFrontendsError instance.
117
+ */
118
+ static handle(err, opts) {
119
+ if (err instanceof MicroFrontendError) {
120
+ return err;
121
+ }
122
+ if (err instanceof Error) {
123
+ return MicroFrontendError.convert(err, opts);
124
+ }
125
+ if (typeof err === "object" && err !== null) {
126
+ if ("message" in err && typeof err.message === "string") {
127
+ return MicroFrontendError.convert(new Error(err.message), opts);
128
+ }
129
+ }
130
+ return new MicroFrontendError("An unknown error occurred");
131
+ }
132
+ };
133
+
134
+ // src/routing/url.ts
135
+ function buildUrlSafeString(givenOpts = {}) {
136
+ const options = {
137
+ joinString: "-",
138
+ lowercaseOnly: true,
139
+ maxLen: 100,
140
+ regexRemovePattern: /(?:(?!(?:[a-z0-9])).)/gi,
141
+ trimWhitespace: true,
142
+ ...givenOpts
143
+ };
144
+ return {
145
+ generate: (...args) => {
146
+ const reJoinString = new RegExp(`${options.joinString}+`, "g");
147
+ let tag;
148
+ if (args.length === 0) {
149
+ throw new Error("generate method must be passed at least one argument");
150
+ }
151
+ for (let i = 0; i < args.length; i++) {
152
+ const arg = args[i];
153
+ if (typeof arg !== "string")
154
+ throw new Error("all supplied arguments must be Strings");
155
+ if (options.trimWhitespace) {
156
+ args[i] = arg.trim();
157
+ }
158
+ }
159
+ tag = args.join(options.joinString);
160
+ tag = tag.replace(/\s/g, options.joinString);
161
+ if (options.lowercaseOnly)
162
+ tag = tag.toLowerCase();
163
+ tag = tag.replace(options.regexRemovePattern, (match2) => {
164
+ if (match2 === options.joinString)
165
+ return match2;
166
+ return "";
167
+ });
168
+ if (tag.length > options.maxLen)
169
+ tag = tag.substring(0, options.maxLen);
170
+ tag = tag.replace(reJoinString, options.joinString);
171
+ return tag;
172
+ }
173
+ };
174
+ }
175
+ var urlSafeString = buildUrlSafeString().generate;
176
+ function makeUrlSafe(name) {
177
+ return urlSafeString(name.replace(/\//g, "-")).replace(/^-*/g, "").replace(/-*$/g, "");
178
+ }
179
+
180
+ // src/config/overrides/config.ts
181
+ var OVERRIDES_COOKIE_PREFIX = "vercel-micro-frontends-override";
182
+ var _Overrides = class {
183
+ constructor(config) {
184
+ this.config = config;
185
+ }
186
+ static getAppEnvOverrideCookieName(zone) {
187
+ return `${_Overrides.overrideEnvCookiePrefix}${zone}`;
188
+ }
189
+ static isOverrideCookie(cookie) {
190
+ var _a;
191
+ return Boolean((_a = cookie.name) == null ? void 0 : _a.startsWith(OVERRIDES_COOKIE_PREFIX));
192
+ }
193
+ static getOverrideFromCookie(cookie) {
194
+ if (!_Overrides.isOverrideCookie(cookie) || !cookie.value)
195
+ return;
196
+ return {
197
+ zone: cookie.name.replace(_Overrides.overrideEnvCookiePrefix, ""),
198
+ host: cookie.value
199
+ };
200
+ }
201
+ static parseOverrides(cookies) {
202
+ const overridesConfig = { applications: {} };
203
+ cookies.forEach((cookie) => {
204
+ const override = _Overrides.getOverrideFromCookie(cookie);
205
+ if (!override)
206
+ return;
207
+ overridesConfig.applications[override.zone] = {
208
+ environment: { host: override.host }
209
+ };
210
+ });
211
+ return overridesConfig;
212
+ }
213
+ static validOverrideDomainsForZone(microFrontendConfig, zone) {
214
+ var _a, _b, _c, _d, _e;
215
+ const projectName = (_a = microFrontendConfig.getZone(zone).vercel) == null ? void 0 : _a.projectName;
216
+ if (!projectName) {
217
+ return [microFrontendConfig.getZone(zone).production.host];
218
+ }
219
+ const parsedProjectName = makeUrlSafe(projectName);
220
+ const previewDeploymentSuffix = (_c = (_b = microFrontendConfig.options) == null ? void 0 : _b.vercel) == null ? void 0 : _c.previewDeploymentSuffix;
221
+ const teamSlug = (_e = (_d = microFrontendConfig.options) == null ? void 0 : _d.vercel) == null ? void 0 : _e.teamSlug;
222
+ if (!teamSlug && !previewDeploymentSuffix) {
223
+ return [microFrontendConfig.getZone(zone).production.host];
224
+ }
225
+ const suffix = previewDeploymentSuffix ? `.${previewDeploymentSuffix}` : `-${teamSlug}.vercel.app`;
226
+ return [
227
+ `${parsedProjectName}-git-([a-zA-Z0-9-]+)${suffix}`,
228
+ microFrontendConfig.getZone(zone).production.host
229
+ ];
230
+ }
231
+ static validateOverrideDomain(microFrontendConfig, zone, domain) {
232
+ return new RegExp(
233
+ `^${_Overrides.validOverrideDomainsForZone(microFrontendConfig, zone).join(
234
+ "|"
235
+ )}$`
236
+ ).test(domain);
237
+ }
238
+ serialize() {
239
+ return this.config;
240
+ }
241
+ };
242
+ var Overrides = _Overrides;
243
+ Overrides.overrideEnvCookiePrefix = `${OVERRIDES_COOKIE_PREFIX}:env:`;
244
+
245
+ // src/config/common/host.ts
246
+ var Host = class {
247
+ constructor({ protocol, host, port }) {
248
+ this.protocol = protocol || "https";
249
+ this.host = host;
250
+ this.port = Host.getPort({ port, protocol: this.protocol });
251
+ this.serialized = {
252
+ protocol,
253
+ host,
254
+ ...port ? { port } : void 0
255
+ };
256
+ }
257
+ isLocal() {
258
+ return this.host === "localhost" || this.host === "127.0.0.1";
259
+ }
260
+ static getPort({
261
+ protocol,
262
+ port
263
+ }) {
264
+ if (!port) {
265
+ if (protocol === "http") {
266
+ return 80;
267
+ }
268
+ return 443;
269
+ }
270
+ return port;
271
+ }
272
+ isDefaultPort() {
273
+ return this.port === Host.getPort({ protocol: this.protocol });
274
+ }
275
+ toString(opts = {}) {
276
+ const url = this.toUrl(opts);
277
+ return url.toString().replace(/\/$/, "");
278
+ }
279
+ toUrl(opts = {}) {
280
+ const { includeDefaultPort } = opts;
281
+ const url = `${this.protocol}://${this.host}${this.isDefaultPort() && !includeDefaultPort ? "" : `:${this.port}`}`;
282
+ return new URL(url);
283
+ }
284
+ serialize() {
285
+ return this.serialized;
286
+ }
287
+ };
288
+
289
+ // src/config/common/application.ts
290
+ var Application = class {
291
+ constructor(name, {
292
+ app,
293
+ overrides
294
+ }) {
295
+ Application.validate(name, app);
296
+ this.name = name;
297
+ this.default = app.default;
298
+ this.routing = app.routing;
299
+ this.development = {
300
+ local: new Host(app.development.local),
301
+ fallback: app.development.fallback ? new Host(app.development.fallback) : void 0
302
+ };
303
+ this.production = new Host(app.production);
304
+ this.vercel = app.vercel;
305
+ this.overrides = (overrides == null ? void 0 : overrides.environment) ? {
306
+ environment: new Host(overrides.environment)
307
+ } : void 0;
308
+ }
309
+ isDefault() {
310
+ return this.default;
311
+ }
312
+ static validate(name, app) {
313
+ var _a, _b, _c, _d, _e;
314
+ 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("/"))) {
315
+ throw new MicroFrontendError(
316
+ `Invalid assetPrefix for application "${name}". Must not start or end with a slash.`,
317
+ { type: "zone", subtype: "invalid_asset_prefix" }
318
+ );
319
+ }
320
+ for (const group of ((_e = app.routing) == null ? void 0 : _e.matches) ?? []) {
321
+ for (const p of group.paths) {
322
+ if (p === "/") {
323
+ continue;
324
+ }
325
+ if (p.endsWith("/")) {
326
+ throw new MicroFrontendError(
327
+ `Invalid path for application "${name}". ${p} must not end with a slash.`,
328
+ { type: "zone", subtype: "invalid_path" }
329
+ );
330
+ }
331
+ if (!p.startsWith("/")) {
332
+ throw new MicroFrontendError(
333
+ `Invalid path for application "${name}". ${p} must start with a slash.`,
334
+ { type: "zone", subtype: "invalid_path" }
335
+ );
336
+ }
337
+ }
338
+ }
339
+ }
340
+ serialize() {
341
+ var _a, _b;
342
+ if (this.routing === void 0 || this.default) {
343
+ return {
344
+ default: true,
345
+ development: {
346
+ local: this.development.local.serialize(),
347
+ fallback: (_a = this.development.fallback) == null ? void 0 : _a.serialize()
348
+ },
349
+ production: this.production.serialize(),
350
+ vercel: this.vercel
351
+ };
352
+ }
353
+ return {
354
+ default: false,
355
+ routing: this.routing,
356
+ development: {
357
+ local: this.development.local.serialize(),
358
+ fallback: (_b = this.development.fallback) == null ? void 0 : _b.serialize()
359
+ },
360
+ production: this.production.serialize(),
361
+ vercel: this.vercel
362
+ };
363
+ }
364
+ };
365
+
366
+ // src/config/common/micro-frontend-config.ts
367
+ var SUPPORTED_VERSIONS = ["1"];
368
+ var DEFAULT_LOCAL_PROXY_PORT = 3024;
369
+ var MicroFrontendConfigCommon = class {
370
+ constructor({
371
+ config,
372
+ overrides
373
+ }) {
374
+ this.zones = {};
375
+ var _a, _b, _c;
376
+ if (!SUPPORTED_VERSIONS.includes(config.version)) {
377
+ throw new MicroFrontendError(
378
+ `Unsupported version: ${config.version}. Supported versions are: ${SUPPORTED_VERSIONS.join(
379
+ ", "
380
+ )}`,
381
+ { type: "config", subtype: "unsupported_version" }
382
+ );
383
+ }
384
+ const disableOverrides = ((_b = (_a = config.options) == null ? void 0 : _a.vercel) == null ? void 0 : _b.disableOverrides) ?? false;
385
+ this.overrides = overrides && !disableOverrides ? new Overrides(overrides) : void 0;
386
+ for (const [zoneName, zoneConfig] of Object.entries(config.applications)) {
387
+ this.zones[zoneName] = new Application(zoneName, {
388
+ app: zoneConfig,
389
+ overrides: !disableOverrides ? (_c = this.overrides) == null ? void 0 : _c.config.applications[zoneName] : void 0
390
+ });
391
+ }
392
+ this.config = config;
393
+ this.name = config.name;
394
+ this.version = config.version;
395
+ this.options = config.options;
396
+ this.$schema = config.$schema;
397
+ }
398
+ isOverridesDisabled() {
399
+ var _a, _b;
400
+ return ((_b = (_a = this.options) == null ? void 0 : _a.vercel) == null ? void 0 : _b.disableOverrides) ?? false;
401
+ }
402
+ static getConfigFromEnv() {
403
+ const config = process.env.MFE_CONFIG;
404
+ if (!config) {
405
+ throw new MicroFrontendError(`Missing "MFE_CONFIG" in environment.`, {
406
+ type: "config",
407
+ subtype: "not_found_in_env"
408
+ });
409
+ }
410
+ return config;
411
+ }
412
+ static fromEnv(_) {
413
+ throw new Error("Not implemented");
414
+ }
415
+ getConfig() {
416
+ return this.config;
417
+ }
418
+ getAllApplications() {
419
+ return Object.values(this.zones);
420
+ }
421
+ getZone(name) {
422
+ const zone = this.zones[name];
423
+ if (!zone) {
424
+ throw new MicroFrontendError(
425
+ `Could not find micro-frontends configuration for application "${name}"`,
426
+ {
427
+ type: "zone",
428
+ subtype: "not_found"
429
+ }
430
+ );
431
+ }
432
+ return zone;
433
+ }
434
+ getApplicationByProjectId(projectId) {
435
+ return Object.values(this.zones).find(
436
+ (zone) => {
437
+ var _a;
438
+ return ((_a = zone.vercel) == null ? void 0 : _a.projectId) === projectId;
439
+ }
440
+ );
441
+ }
442
+ getDefaultZone() {
443
+ const zone = Object.values(this.zones).find((z) => z.default);
444
+ if (!zone) {
445
+ throw new MicroFrontendError(
446
+ `Could not find default zone in micro-frontends configuration`,
447
+ {
448
+ type: "zone",
449
+ subtype: "not_found"
450
+ }
451
+ );
452
+ }
453
+ return zone;
454
+ }
455
+ /**
456
+ * Returns the configured port for the local proxy
457
+ */
458
+ getLocalProxyPort() {
459
+ var _a, _b;
460
+ return ((_b = (_a = this.config.options) == null ? void 0 : _a.localProxy) == null ? void 0 : _b.port) ?? DEFAULT_LOCAL_PROXY_PORT;
461
+ }
462
+ /**
463
+ * Serializes the class back to the Schema type.
464
+ *
465
+ * NOTE: This is used when writing the config to disk and must always match the input Schema
466
+ */
467
+ toSchemaJson() {
468
+ const applications = {};
469
+ for (const [name, zone] of Object.entries(this.zones)) {
470
+ applications[name] = zone.serialize();
471
+ }
472
+ return {
473
+ $schema: this.$schema,
474
+ name: this.name,
475
+ version: this.version,
476
+ options: this.options,
477
+ applications
478
+ };
479
+ }
480
+ serialize() {
481
+ var _a;
482
+ const applications = {};
483
+ for (const [name, zone] of Object.entries(this.zones)) {
484
+ applications[name] = zone.serialize();
485
+ }
486
+ return {
487
+ config: {
488
+ name: this.name,
489
+ version: this.version,
490
+ applications,
491
+ options: this.options,
492
+ $schema: this.$schema
493
+ },
494
+ overrides: (_a = this.overrides) == null ? void 0 : _a.serialize()
495
+ };
496
+ }
497
+ write(_) {
498
+ throw new MicroFrontendError(
499
+ `Writing to file to disk requires using an instance of "MicroFrontendConfig".`,
500
+ { type: "config", subtype: "unsupported_operation" }
501
+ );
502
+ }
503
+ };
504
+
505
+ // src/config/utils/get-output-file-path.ts
506
+ import path2 from "node:path";
507
+
508
+ // src/config/constants.ts
509
+ var MFE_CONFIG_DEFAULT_FILE_PATH2 = "micro-frontends";
510
+ var MFE_CONFIG_DEFAULT_FILE_NAME2 = "micro-frontends.config.json";
511
+
512
+ // src/config/utils/get-output-file-path.ts
513
+ function getOutputFilePath2() {
514
+ if (isVercel()) {
515
+ return path2.join(
516
+ ".vercel",
517
+ MFE_CONFIG_DEFAULT_FILE_PATH2,
518
+ MFE_CONFIG_DEFAULT_FILE_NAME2
519
+ );
520
+ }
521
+ return path2.join(MFE_CONFIG_DEFAULT_FILE_PATH2, MFE_CONFIG_DEFAULT_FILE_NAME2);
522
+ }
523
+
524
+ // src/config/validation.ts
525
+ import { parse } from "jsonc-parser";
526
+ import { pathToRegexp, parse as parsePathRegexp } from "path-to-regexp";
527
+ import { Ajv } from "ajv";
528
+
529
+ // schema/schema.json
530
+ var schema_default = {
531
+ $schema: "http://json-schema.org/draft-07/schema#",
532
+ $ref: "#/definitions/Config",
533
+ definitions: {
534
+ Config: {
535
+ type: "object",
536
+ properties: {
537
+ version: {
538
+ type: "string"
539
+ },
540
+ $schema: {
541
+ type: "string"
542
+ },
543
+ name: {
544
+ type: "string",
545
+ description: 'Name for the micro-frontend site (eg. "vercel.com", "vercel-site" etc.).'
546
+ },
547
+ applications: {
548
+ $ref: "#/definitions/ApplicationConfigsById"
549
+ },
550
+ options: {
551
+ $ref: "#/definitions/Options",
552
+ description: "Optional configuration for the entire micro-frontends setup."
553
+ }
554
+ },
555
+ required: ["version", "applications"],
556
+ description: "Configuration for micro-frontend applications\n\nTODO: Add proxy configuration"
557
+ },
558
+ ApplicationConfigsById: {
559
+ type: "object",
560
+ additionalProperties: {
561
+ $ref: "#/definitions/ApplicationConfig"
562
+ }
563
+ },
564
+ ApplicationConfig: {
565
+ anyOf: [
566
+ {
567
+ $ref: "#/definitions/DefaultApplicationConfig"
568
+ },
569
+ {
570
+ $ref: "#/definitions/CommonApplicationConfig"
571
+ }
572
+ ],
573
+ description: "A Micro-Frontend Deployment Target"
574
+ },
575
+ DefaultApplicationConfig: {
576
+ type: "object",
577
+ properties: {
578
+ default: {
579
+ type: "boolean",
580
+ const: true,
581
+ description: "The default application is used no other application is matched via the routing config"
582
+ },
583
+ routing: {
584
+ $ref: "#/definitions/Routing"
585
+ },
586
+ development: {
587
+ type: "object",
588
+ properties: {
589
+ local: {
590
+ $ref: "#/definitions/HostConfig"
591
+ },
592
+ fallback: {
593
+ $ref: "#/definitions/HostConfig",
594
+ 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."
595
+ },
596
+ task: {
597
+ type: "string",
598
+ description: "Optional task to run when starting the development server. Should reference a script in the package.json of the application."
599
+ }
600
+ },
601
+ required: ["local"]
602
+ },
603
+ production: {
604
+ $ref: "#/definitions/HostConfig"
605
+ },
606
+ metadata: {
607
+ type: "object",
608
+ additionalProperties: {
609
+ type: "string"
610
+ }
611
+ },
612
+ federation: {
613
+ type: "object",
614
+ properties: {
615
+ exposes: {
616
+ type: "array",
617
+ items: {
618
+ type: "object",
619
+ properties: {
620
+ name: {
621
+ type: "string",
622
+ description: "The name of the module - should be used when importing the module from another application"
623
+ },
624
+ path: {
625
+ type: "string",
626
+ description: "Relative path to the module within its `application`"
627
+ }
628
+ },
629
+ required: ["name", "path"]
630
+ },
631
+ description: "Modules that are exposed by this application"
632
+ },
633
+ uses: {
634
+ type: "array",
635
+ items: {
636
+ type: "string"
637
+ },
638
+ description: "Modules that are used by this application. Only the name of the module is required."
639
+ }
640
+ }
641
+ },
642
+ vercel: {
643
+ $ref: "#/definitions/Vercel"
644
+ }
645
+ },
646
+ required: ["default", "development", "production"]
647
+ },
648
+ Routing: {
649
+ type: "object",
650
+ properties: {
651
+ assetPrefix: {
652
+ type: "string",
653
+ description: "[assetPrefix] for the application"
654
+ },
655
+ matches: {
656
+ type: "array",
657
+ items: {
658
+ $ref: "#/definitions/PathGroup"
659
+ },
660
+ description: "Path expressions that are routed to this application."
661
+ }
662
+ },
663
+ required: ["matches"]
664
+ },
665
+ PathGroup: {
666
+ type: "object",
667
+ properties: {
668
+ group: {
669
+ type: "string",
670
+ description: "Optional group name for the paths"
671
+ },
672
+ options: {
673
+ type: "object",
674
+ properties: {
675
+ flag: {
676
+ type: "string",
677
+ description: "flag name that can be used to enable/disable all paths in the group"
678
+ },
679
+ routeToDefaultApplication: {
680
+ type: "boolean",
681
+ 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."
682
+ }
683
+ }
684
+ },
685
+ paths: {
686
+ type: "array",
687
+ items: {
688
+ type: "string"
689
+ }
690
+ }
691
+ },
692
+ required: ["paths"]
693
+ },
694
+ HostConfig: {
695
+ type: "object",
696
+ properties: {
697
+ protocol: {
698
+ type: "string",
699
+ enum: ["http", "https"],
700
+ 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"'
701
+ },
702
+ host: {
703
+ type: "string",
704
+ 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`)."
705
+ },
706
+ port: {
707
+ type: "number",
708
+ 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"
709
+ }
710
+ },
711
+ required: ["host"]
712
+ },
713
+ Vercel: {
714
+ type: "object",
715
+ properties: {
716
+ projectId: {
717
+ type: "string",
718
+ description: "Vercel project ID"
719
+ },
720
+ projectName: {
721
+ type: "string",
722
+ description: "Vercel project name (temporary until we can use project ID)"
723
+ },
724
+ defaultRoute: {
725
+ type: "string",
726
+ description: "The default route for the application. Used to render screenshots, favicons, and provide direct zone links"
727
+ },
728
+ routeSpeedInsightsToDefaultZone: {
729
+ type: "boolean",
730
+ description: "Whether to route Speed Insights to the default zone or each individual microfrontend."
731
+ }
732
+ },
733
+ required: ["projectId"]
734
+ },
735
+ CommonApplicationConfig: {
736
+ type: "object",
737
+ properties: {
738
+ default: {
739
+ type: "boolean",
740
+ const: false,
741
+ description: "The default application is used no other application is matched via the routing config"
742
+ },
743
+ routing: {
744
+ $ref: "#/definitions/Routing"
745
+ },
746
+ development: {
747
+ type: "object",
748
+ properties: {
749
+ local: {
750
+ $ref: "#/definitions/HostConfig"
751
+ },
752
+ fallback: {
753
+ $ref: "#/definitions/HostConfig",
754
+ 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."
755
+ },
756
+ task: {
757
+ type: "string",
758
+ description: "Optional task to run when starting the development server. Should reference a script in the package.json of the application."
759
+ }
760
+ },
761
+ required: ["local"]
762
+ },
763
+ production: {
764
+ $ref: "#/definitions/HostConfig"
765
+ },
766
+ metadata: {
767
+ type: "object",
768
+ additionalProperties: {
769
+ type: "string"
770
+ }
771
+ },
772
+ federation: {
773
+ type: "object",
774
+ properties: {
775
+ exposes: {
776
+ type: "array",
777
+ items: {
778
+ type: "object",
779
+ properties: {
780
+ name: {
781
+ type: "string",
782
+ description: "The name of the module - should be used when importing the module from another application"
783
+ },
784
+ path: {
785
+ type: "string",
786
+ description: "Relative path to the module within its `application`"
787
+ }
788
+ },
789
+ required: ["name", "path"]
790
+ },
791
+ description: "Modules that are exposed by this application"
792
+ },
793
+ uses: {
794
+ type: "array",
795
+ items: {
796
+ type: "string"
797
+ },
798
+ description: "Modules that are used by this application. Only the name of the module is required."
799
+ }
800
+ }
801
+ },
802
+ vercel: {
803
+ $ref: "#/definitions/Vercel"
804
+ }
805
+ },
806
+ required: ["default", "development", "production", "routing"]
807
+ },
808
+ Options: {
809
+ type: "object",
810
+ properties: {
811
+ vercel: {
812
+ $ref: "#/definitions/VercelOptions",
813
+ description: "Micro-Frontends wide options for Vercel."
814
+ },
815
+ localProxy: {
816
+ $ref: "#/definitions/LocalProxyOptions",
817
+ description: "Options for local proxy."
818
+ }
819
+ }
820
+ },
821
+ VercelOptions: {
822
+ type: "object",
823
+ properties: {
824
+ previewDeploymentSuffix: {
825
+ type: "string",
826
+ 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`."
827
+ },
828
+ teamSlug: {
829
+ type: "string",
830
+ description: "Team slug for the Vercel team"
831
+ },
832
+ disableOverrides: {
833
+ type: "boolean",
834
+ 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."
835
+ }
836
+ }
837
+ },
838
+ LocalProxyOptions: {
839
+ type: "object",
840
+ properties: {
841
+ port: {
842
+ type: "number",
843
+ description: "The port number used by the local proxy server.\n\nThe default is `3024`."
844
+ }
845
+ }
846
+ }
847
+ }
848
+ };
849
+
850
+ // src/config/utils/load-schema.ts
851
+ var SCHEMA = schema_default;
852
+
853
+ // src/config/validation.ts
854
+ var validateSchema = (configString) => {
855
+ const parsedConfig = parse(configString);
856
+ const ajv = new Ajv();
857
+ const validate = ajv.compile(SCHEMA);
858
+ const isValid = validate(parsedConfig);
859
+ if (!isValid) {
860
+ throw new MicroFrontendError(
861
+ `Invalid config: ${ajv.errorsText(validate.errors)}`,
862
+ { type: "config", subtype: "does_not_match_schema" }
863
+ );
864
+ }
865
+ return parsedConfig;
866
+ };
867
+ var SUPPORTED_VERSIONS2 = ["1"];
868
+ var validateVersion = (version) => {
869
+ if (!SUPPORTED_VERSIONS2.includes(version)) {
870
+ throw new MicroFrontendError(
871
+ `Unsupported version: ${version}. Supported versions are: ${SUPPORTED_VERSIONS2.join(
872
+ ", "
873
+ )}`,
874
+ { type: "config", subtype: "unsupported_version" }
875
+ );
876
+ }
877
+ };
878
+ function validateMainPath(applicationConfigsById) {
879
+ for (const [id, app] of Object.entries(applicationConfigsById)) {
880
+ const { defaultRoute } = app.vercel ?? {};
881
+ if (!defaultRoute) {
882
+ continue;
883
+ }
884
+ if (isDefaultApplicationConfig(app)) {
885
+ const pathsWithApp = [];
886
+ for (const [otherId, otherApp] of Object.entries(
887
+ applicationConfigsById
888
+ )) {
889
+ if (isDefaultApplicationConfig(otherApp)) {
890
+ continue;
891
+ }
892
+ pathsWithApp.push({
893
+ id: otherId,
894
+ paths: otherApp.routing.matches.flatMap((match2) => match2.paths)
895
+ });
896
+ }
897
+ for (const { id: otherId, paths } of pathsWithApp) {
898
+ const isValid = paths.every((path3) => {
899
+ const matcher = pathToRegexp(path3);
900
+ return !matcher.test(defaultRoute);
901
+ });
902
+ if (!isValid) {
903
+ throw new MicroFrontendError(
904
+ `default route "${defaultRoute}" cannot be used for "${id}" because it is matched by "${otherId}"`,
905
+ { type: "config", subtype: "invalid_main_path" }
906
+ );
907
+ }
908
+ }
909
+ } else {
910
+ const allPaths = app.routing.matches.flatMap((match2) => match2.paths);
911
+ const isValid = allPaths.some((path3) => {
912
+ const matcher = pathToRegexp(path3);
913
+ return matcher.test(defaultRoute);
914
+ });
915
+ if (!isValid) {
916
+ throw new MicroFrontendError(
917
+ `default route "${defaultRoute}" is not included by the routing config for application "${id}"`,
918
+ { type: "config", subtype: "invalid_main_path" }
919
+ );
920
+ }
921
+ }
922
+ }
923
+ }
924
+ var validatePaths = (applicationConfigsById) => {
925
+ const pathsByApplicationId = /* @__PURE__ */ new Map();
926
+ const errors = [];
927
+ for (const [id, app] of Object.entries(applicationConfigsById)) {
928
+ if (isDefaultApplicationConfig(app)) {
929
+ continue;
930
+ }
931
+ for (const pathMatch of app.routing.matches) {
932
+ for (const path3 of pathMatch.paths) {
933
+ const maybeError = validatePathExpression(path3);
934
+ if (maybeError) {
935
+ errors.push(maybeError);
936
+ }
937
+ const existing = pathsByApplicationId.get(path3);
938
+ if (existing) {
939
+ existing.applications.push(id);
940
+ } else {
941
+ pathsByApplicationId.set(path3, {
942
+ applications: [id],
943
+ matcher: pathToRegexp(path3),
944
+ applicationId: id
945
+ });
946
+ }
947
+ }
948
+ }
949
+ }
950
+ const entries = Array.from(pathsByApplicationId.entries());
951
+ entries.forEach(([path3, { applications: ids, matcher, applicationId }]) => {
952
+ if (ids.length > 1) {
953
+ errors.push(
954
+ `Duplicate path "${path3}" for applications "${ids.join(", ")}"`
955
+ );
956
+ }
957
+ entries.forEach(
958
+ ([
959
+ matchPath,
960
+ { applications: matchIds, applicationId: matchApplicationId }
961
+ ]) => {
962
+ if (path3 === matchPath) {
963
+ return;
964
+ }
965
+ if (applicationId === matchApplicationId) {
966
+ return;
967
+ }
968
+ if (matcher.test(matchPath)) {
969
+ const source = `"${path3}" of application${ids.length > 0 ? "s" : ""} ${ids.join(", ")}`;
970
+ const destination = `"${matchPath}" of application${matchIds.length > 0 ? "s" : ""} ${matchIds.join(", ")}`;
971
+ errors.push(
972
+ `Overlapping path detected between ${source} and ${destination}`
973
+ );
974
+ }
975
+ }
976
+ );
977
+ });
978
+ if (errors.length) {
979
+ throw new MicroFrontendError(`Invalid paths: ${errors.join(", ")}`, {
980
+ type: "config",
981
+ subtype: "conflicting_paths"
982
+ });
983
+ }
984
+ };
985
+ var PATH_DEFAULT_PATTERN = "[^\\/#\\?]+?";
986
+ function validatePathExpression(path3) {
987
+ const tokens = parsePathRegexp(path3);
988
+ for (let i = 0; i < tokens.length; i++) {
989
+ const token = tokens[i];
990
+ if (token === void 0) {
991
+ return `token ${i} in ${path3} is undefined, this shouldn't happen`;
992
+ }
993
+ if (typeof token !== "string") {
994
+ if (token.pattern !== PATH_DEFAULT_PATTERN) {
995
+ return `Path ${path3} cannot use a regular expression wildcard`;
996
+ }
997
+ if (token.prefix !== "/") {
998
+ return `Wildcard :${token.name} must be immediately after a / in ${path3}`;
999
+ }
1000
+ if (token.suffix) {
1001
+ return `Wildcard suffix on :${token.name} is not allowed. Suffixes are not supported`;
1002
+ }
1003
+ if (token.modifier && i !== tokens.length - 1) {
1004
+ return `Modifier ${token.modifier} is not allowed on wildcard :${token.name} in ${path3}. Modifiers are only allowed in the last path component`;
1005
+ }
1006
+ }
1007
+ }
1008
+ return void 0;
1009
+ }
1010
+ var validateDefaults = (applicationConfigsById) => {
1011
+ const defaultApplicationIds = Object.entries(applicationConfigsById).reduce((acc, [id, app]) => app.default ? [...acc, id] : acc, []);
1012
+ if (defaultApplicationIds.length === 0) {
1013
+ throw new MicroFrontendError(
1014
+ `No default application found. At least one application must be marked as default.`,
1015
+ { type: "config", subtype: "no_default_application" }
1016
+ );
1017
+ }
1018
+ if (defaultApplicationIds.length > 1) {
1019
+ throw new MicroFrontendError(
1020
+ `Only one default application is allowed. Found ${defaultApplicationIds.join(", ")}.`,
1021
+ { type: "config", subtype: "multiple_default_applications" }
1022
+ );
1023
+ }
1024
+ };
1025
+ var validateOptions = (options) => {
1026
+ var _a;
1027
+ if ((_a = options == null ? void 0 : options.vercel) == null ? void 0 : _a.previewDeploymentSuffix) {
1028
+ if (!/^[a-zA-Z]{2,}\.[a-zA-Z]{2,}$/.test(
1029
+ options.vercel.previewDeploymentSuffix
1030
+ )) {
1031
+ throw new MicroFrontendError(
1032
+ `Invalid preview deployment suffix: ${options.vercel.previewDeploymentSuffix}. Should have be formatted like "vercel.app".`,
1033
+ { type: "config", subtype: "invalid_preview_deployment_suffix" }
1034
+ );
1035
+ }
1036
+ }
1037
+ };
1038
+
1039
+ // src/config/utils/convert.ts
1040
+ function convertV1RoutingToV2Routing(routing) {
1041
+ return routing.matches.map((group) => {
1042
+ var _a, _b;
1043
+ return {
1044
+ group: group.group,
1045
+ flag: (_a = group.options) == null ? void 0 : _a.flag,
1046
+ routeToDefaultApplication: (_b = group.options) == null ? void 0 : _b.routeToDefaultApplication,
1047
+ paths: group.paths
1048
+ };
1049
+ });
1050
+ }
1051
+ function convertV1ApplicationToV2Application(application) {
1052
+ const common = {
1053
+ production: application.production,
1054
+ development: application.development,
1055
+ vercel: application.vercel
1056
+ };
1057
+ if (application.default) {
1058
+ return common;
1059
+ }
1060
+ return {
1061
+ ...common,
1062
+ routing: convertV1RoutingToV2Routing(application.routing)
1063
+ };
1064
+ }
1065
+ function convertV1ConfigToV2Config(config, fromApp) {
1066
+ if (!config.applications[fromApp]) {
1067
+ throw new Error(`Application "${fromApp}" not found in the config`);
1068
+ }
1069
+ const common = {
1070
+ version: "2",
1071
+ options: config.options
1072
+ };
1073
+ if (config.applications[fromApp].default) {
1074
+ return {
1075
+ ...common,
1076
+ // this is assumed for now, and by the time this is released we won't need this conversion
1077
+ provider: "vercel",
1078
+ applications: Object.fromEntries(
1079
+ Object.entries(config.applications).map(([id, application]) => [
1080
+ id,
1081
+ convertV1ApplicationToV2Application(application)
1082
+ ])
1083
+ )
1084
+ };
1085
+ }
1086
+ return {
1087
+ ...common,
1088
+ partOf: fromApp
1089
+ };
1090
+ }
1091
+
1092
+ // src/config/utils/write-file.ts
1093
+ import fs from "node:fs";
1094
+ import { dirname } from "node:path";
1095
+ function writeFile(outputPath, config, prettify) {
1096
+ fs.mkdirSync(dirname(outputPath), { recursive: true });
1097
+ fs.writeFileSync(
1098
+ outputPath,
1099
+ JSON.stringify(config, null, prettify ? 2 : void 0)
1100
+ );
1101
+ }
1102
+
1103
+ // src/config/micro-frontend-config.ts
1104
+ var MicroFrontendConfig = class extends MicroFrontendConfigCommon {
1105
+ static validate(configString) {
1106
+ const config = validateSchema(configString);
1107
+ validateVersion(config.version);
1108
+ validatePaths(config.applications);
1109
+ validateMainPath(config.applications);
1110
+ validateDefaults(config.applications);
1111
+ validateOptions(config.options);
1112
+ return config;
1113
+ }
1114
+ static fromEnv({
1115
+ cookies
1116
+ }) {
1117
+ return new MicroFrontendConfigCommon({
1118
+ config: MicroFrontendConfig.validate(
1119
+ MicroFrontendConfigCommon.getConfigFromEnv()
1120
+ ),
1121
+ overrides: Overrides.parseOverrides(cookies)
1122
+ });
1123
+ }
1124
+ static fromFile({
1125
+ filePath
1126
+ }) {
1127
+ try {
1128
+ const config = fs2.readFileSync(filePath, "utf-8");
1129
+ return new MicroFrontendConfig({
1130
+ config: MicroFrontendConfig.validate(config)
1131
+ });
1132
+ } catch (e) {
1133
+ throw MicroFrontendError.handle(e, {
1134
+ fileName: filePath
1135
+ });
1136
+ }
1137
+ }
1138
+ /**
1139
+ * Writes the configuration to a file.
1140
+ */
1141
+ write(fromApp, opts = {}) {
1142
+ const { pretty = true, versions = ["v1", "v2"] } = opts;
1143
+ const config = this.toSchemaJson();
1144
+ if (versions.includes("v1")) {
1145
+ const outputPath = getOutputFilePath2();
1146
+ writeFile(outputPath, config, pretty);
1147
+ }
1148
+ if (versions.includes("v2")) {
1149
+ const outputPath = getOutputFilePath();
1150
+ const v2Config = convertV1ConfigToV2Config(config, fromApp);
1151
+ writeFile(outputPath, v2Config, pretty);
1152
+ }
1153
+ }
1154
+ };
1155
+
1156
+ // src/next/testing/index.ts
1157
+ function expandWildcards(path3) {
1158
+ if (path3.includes("/:path*") || path3.includes("/:slug*")) {
1159
+ return [
1160
+ path3 === "/:path*" || path3 === "/:slug*" ? "/" : path3.replace("/:path*", "").replace("/:slug*", ""),
1161
+ path3.replace("/:path*", "/foo").replace("/:slug*", "/foo"),
1162
+ path3.replace("/:path*", "/foo/bar").replace("/:slug*", "/foo/bar")
1163
+ ];
1164
+ }
1165
+ if (path3.includes("/:path+") || path3.includes("/:slug+")) {
1166
+ return [
1167
+ path3.replace("/:path+", "/foo").replace("/:slug+", "/foo"),
1168
+ path3.replace("/:path+", "/foo/bar").replace("/:slug+", "/foo/bar")
1169
+ ];
1170
+ }
1171
+ if (path3.includes("/:path") || path3.includes("/:slug")) {
1172
+ return [path3.replace("/:path", "/foo").replace("/:slug", "/foo")];
1173
+ }
1174
+ return [path3];
1175
+ }
1176
+ function loadMicrofrontendConfigForEdge(path3) {
1177
+ const rawMfConfig = parse2(readFileSync(path3, "utf-8"));
1178
+ return new MicroFrontendConfig({ config: rawMfConfig });
1179
+ }
1180
+ function getAllZoneNames(mfConfig) {
1181
+ return mfConfig.getAllApplications().filter((app) => !app.default).map((app) => app.name);
1182
+ }
1183
+ function getLaunchedPathsForZone(mfConfig, zoneName) {
1184
+ var _a, _b;
1185
+ const zone = mfConfig.getZone(zoneName);
1186
+ return [
1187
+ ...((_a = zone.routing) == null ? void 0 : _a.assetPrefix) ? [`/${zone.routing.assetPrefix}/_next/static`] : [],
1188
+ ...((_b = zone.routing) == null ? void 0 : _b.matches.filter((group) => {
1189
+ var _a2;
1190
+ return !((_a2 = group.options) == null ? void 0 : _a2.flag);
1191
+ }).flatMap((group) => group.paths.flatMap(expandWildcards))) ?? []
1192
+ ];
1193
+ }
1194
+ function getFlaggedPathsForZone(mfConfig, zoneName) {
1195
+ var _a;
1196
+ const zone = mfConfig.getZone(zoneName);
1197
+ return ((_a = zone.routing) == null ? void 0 : _a.matches.filter((group) => {
1198
+ var _a2;
1199
+ return Boolean((_a2 = group.options) == null ? void 0 : _a2.flag);
1200
+ }).flatMap((group) => group.paths.flatMap(expandWildcards))) ?? [];
1201
+ }
1202
+ function getExpectedDomainForZone(mfConfig, zoneName, env) {
1203
+ const zone = mfConfig.getZone(zoneName);
1204
+ return env === "development" ? zone.development.local.toString() : zone.production.toString();
1205
+ }
1206
+ function getAllMultiZonesPaths(mfConfig) {
1207
+ return mfConfig.getAllApplications().flatMap((app) => {
1208
+ var _a;
1209
+ return ((_a = app.routing) == null ? void 0 : _a.matches.flatMap(
1210
+ (group) => group.paths.flatMap(expandWildcards)
1211
+ )) ?? [];
1212
+ });
1213
+ }
1214
+ function urlMatches(middlewareConfig, path3, host) {
1215
+ if (!middlewareConfig.matcher) {
1216
+ return false;
1217
+ }
1218
+ const matchers = Array.isArray(middlewareConfig.matcher) ? middlewareConfig.matcher : [middlewareConfig.matcher];
1219
+ for (let matcher of matchers) {
1220
+ matcher = typeof matcher === "string" ? { source: matcher } : matcher;
1221
+ if (match(matcher.source)(path3)) {
1222
+ if (matchHas(
1223
+ new WebNextRequest(
1224
+ new NextRequestHint({
1225
+ init: { headers: { host } },
1226
+ input: `https://${host}${path3}`,
1227
+ page: "unused_placeholder"
1228
+ })
1229
+ ),
1230
+ {},
1231
+ matcher.has,
1232
+ matcher.missing
1233
+ )) {
1234
+ return true;
1235
+ }
1236
+ }
1237
+ }
1238
+ return false;
1239
+ }
1240
+ function validateMiddlewareConfig(middlewareConfig, microFrontendConfigOrPath, extraProductionMatches) {
1241
+ var _a, _b;
1242
+ const microFrontendConfig = typeof microFrontendConfigOrPath === "string" ? loadMicrofrontendConfigForEdge(microFrontendConfigOrPath) : microFrontendConfigOrPath;
1243
+ const errors = [];
1244
+ const usedExtraProductionMatches = /* @__PURE__ */ new Set();
1245
+ for (const application of microFrontendConfig.getAllApplications()) {
1246
+ if ((_a = application.routing) == null ? void 0 : _a.matches) {
1247
+ const matches = [...application.routing.matches];
1248
+ if (application.routing.assetPrefix) {
1249
+ matches.push({
1250
+ paths: [`/${application.routing.assetPrefix}/_next/:path+`]
1251
+ });
1252
+ }
1253
+ for (const aMatch of matches) {
1254
+ const isFlagged = Boolean((_b = aMatch.options) == null ? void 0 : _b.flag);
1255
+ for (const path3 of aMatch.paths) {
1256
+ const pathsToTest = expandWildcards(path3);
1257
+ for (const testPath of pathsToTest) {
1258
+ const pathForDisplay = `${testPath}${path3 === testPath ? "" : ` (synthesized from ${path3})`}`;
1259
+ if (!urlMatches(middlewareConfig, testPath, "test.nonproduction.host")) {
1260
+ errors.push(
1261
+ `Matcher misconfigured for ${pathForDisplay}. This path should have matched the middleware config on a non-production host, but did not. Microfrontends require a middleware config matcher that matches on this host everywhere but in production. That can be configured with a configuration like this:
1262
+ ${getSampleMatcher(path3, microFrontendConfig.getDefaultZone().production.host)}`
1263
+ );
1264
+ break;
1265
+ }
1266
+ const productionUrlMatches = urlMatches(
1267
+ middlewareConfig,
1268
+ testPath,
1269
+ microFrontendConfig.getDefaultZone().production.host
1270
+ );
1271
+ if (isFlagged) {
1272
+ if (!productionUrlMatches) {
1273
+ errors.push(
1274
+ `Matcher misconfigured for ${pathForDisplay}. Middleware config matchers for flagged paths should ALWAYS match.`
1275
+ );
1276
+ break;
1277
+ }
1278
+ } else if (productionUrlMatches) {
1279
+ if (extraProductionMatches == null ? void 0 : extraProductionMatches.includes(path3)) {
1280
+ usedExtraProductionMatches.add(path3);
1281
+ } else {
1282
+ errors.push(
1283
+ `Matcher misconfigured for ${pathForDisplay}. This path matched the middleware config on a production host, but should not have. Microfrontends require a middleware config matcher that matches on this host everywhere but in production. If this is desired, you can add the path the to extraProductionMatches parameter. Otherwise, you can set up a configuration like this:
1284
+ ${getSampleMatcher(path3, microFrontendConfig.getDefaultZone().production.host)}`
1285
+ );
1286
+ }
1287
+ break;
1288
+ }
1289
+ }
1290
+ }
1291
+ }
1292
+ }
1293
+ }
1294
+ const unusedExtraProductionMatches = extraProductionMatches == null ? void 0 : extraProductionMatches.filter(
1295
+ (x) => !usedExtraProductionMatches.has(x)
1296
+ );
1297
+ if (unusedExtraProductionMatches == null ? void 0 : unusedExtraProductionMatches.length) {
1298
+ errors.push(
1299
+ `The following paths were passed to the extraProductionMatches parameter but were unused. You probably want to remove them from the extraProductionMatches parameter: ${unusedExtraProductionMatches.join(", ")}`
1300
+ );
1301
+ }
1302
+ if (errors.length > 0) {
1303
+ const message = `Found the following inconsistencies between your microfrontend config ${typeof microFrontendConfigOrPath === "string" ? `(at ${microFrontendConfigOrPath}) ` : ""}and middleware config:
1304
+
1305
+ - `;
1306
+ throw new Error(message + errors.join("\n\n- "));
1307
+ }
1308
+ }
1309
+ function getSampleMatcher(path3, host) {
1310
+ return ` {
1311
+ source: '${path3}', // This can also be a broader regular expression.
1312
+ missing: [
1313
+ type: 'header',
1314
+ key: 'host',
1315
+ value '${host}',
1316
+ ],
1317
+ }`;
1318
+ }
1319
+ async function validateMiddlewareOnFlaggedPaths(microFrontendConfigOrPath, middleware) {
1320
+ const initialEnv = process.env.VERCEL_ENV;
1321
+ const initialMfePreviewDomains = process.env.MFE_PREVIEW_DOMAINS;
1322
+ try {
1323
+ const microFrontendConfig = typeof microFrontendConfigOrPath === "string" ? loadMicrofrontendConfigForEdge(microFrontendConfigOrPath) : microFrontendConfigOrPath;
1324
+ const fakePreviewDomains = createFakePreviewDomains(microFrontendConfig);
1325
+ process.env.MFE_PREVIEW_DOMAINS = JSON.stringify(fakePreviewDomains);
1326
+ const allZoneNames = getAllZoneNames(microFrontendConfig);
1327
+ const errors = [];
1328
+ for (const zoneName of allZoneNames) {
1329
+ const flaggedPaths = getFlaggedPathsForZone(
1330
+ microFrontendConfig,
1331
+ zoneName
1332
+ );
1333
+ if (flaggedPaths.length) {
1334
+ for (const env of ["preview", "production"]) {
1335
+ process.env.VERCEL_ENV = env;
1336
+ for (const path3 of flaggedPaths) {
1337
+ const expectedHost = env === "preview" ? fakePreviewDomains[zoneName] : getExpectedDomainForZone(microFrontendConfig, zoneName, env);
1338
+ const requestPath = `https://${microFrontendConfig.getDefaultZone().production.host}${path3}`;
1339
+ const request = new NextRequest(requestPath, {
1340
+ headers: { "x-vercel-skip-deployment-existence-check": "1" }
1341
+ });
1342
+ const response = await middleware(
1343
+ request,
1344
+ {}
1345
+ );
1346
+ const expectedUrl = `${expectedHost}${path3}`;
1347
+ if (!response) {
1348
+ errors.push(
1349
+ `middleware did not action for ${requestPath} in ${env}. Expected a rewrite to ${expectedUrl}`
1350
+ );
1351
+ } else if (response.status !== 200) {
1352
+ errors.push(
1353
+ `expected 200 status for ${requestPath} in ${env} but got ${response.status}`
1354
+ );
1355
+ } else if (response.headers.get("x-middleware-rewrite") !== expectedUrl) {
1356
+ errors.push(
1357
+ `expected rewrite from ${requestPath} to ${expectedUrl} in ${env}, but got ${response.headers.get("x-middleware-rewrite")}`
1358
+ );
1359
+ }
1360
+ }
1361
+ }
1362
+ }
1363
+ }
1364
+ if (errors.length) {
1365
+ throw new Error(errors.join("\n"));
1366
+ }
1367
+ } finally {
1368
+ process.env.VERCEL_ENV = initialEnv;
1369
+ process.env.MFE_PREVIEW_DOMAINS = initialMfePreviewDomains;
1370
+ }
1371
+ }
1372
+ function createFakePreviewDomains(config) {
1373
+ return config.getAllApplications().reduce((result, application) => {
1374
+ result[application.name] = `https://preview-for-middleware-test-only.${application.production.host}`;
1375
+ return result;
1376
+ }, {});
1377
+ }
1378
+ export {
1379
+ expandWildcards,
1380
+ getAllMultiZonesPaths,
1381
+ getAllZoneNames,
1382
+ getExpectedDomainForZone,
1383
+ getFlaggedPathsForZone,
1384
+ getLaunchedPathsForZone,
1385
+ loadMicrofrontendConfigForEdge,
1386
+ validateMiddlewareConfig,
1387
+ validateMiddlewareOnFlaggedPaths
1388
+ };
1389
+ //# sourceMappingURL=testing.js.map