@vercel/microfrontends 0.13.0 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (120) hide show
  1. package/README.md +3 -3
  2. package/dist/bin/cli.cjs +403 -1627
  3. package/dist/config.cjs +460 -1004
  4. package/dist/config.cjs.map +1 -1
  5. package/dist/config.d.ts +4 -25
  6. package/dist/config.js +456 -983
  7. package/dist/config.js.map +1 -1
  8. package/dist/{index-83133f2d.d.ts → index-bf67a461.d.ts} +3 -10
  9. package/dist/{v2/microfrontends → microfrontends}/server.cjs +128 -194
  10. package/dist/microfrontends/server.cjs.map +1 -0
  11. package/dist/{v2/microfrontends → microfrontends}/server.d.ts +6 -5
  12. package/dist/{v2/microfrontends → microfrontends}/server.js +125 -191
  13. package/dist/microfrontends/server.js.map +1 -0
  14. package/dist/{v2/microfrontends.cjs → microfrontends.cjs} +21 -35
  15. package/dist/microfrontends.cjs.map +1 -0
  16. package/dist/{v2/microfrontends.d.ts → microfrontends.d.ts} +4 -3
  17. package/dist/{v2/microfrontends.js → microfrontends.js} +20 -34
  18. package/dist/microfrontends.js.map +1 -0
  19. package/dist/next/client.cjs +1 -1
  20. package/dist/next/client.cjs.map +1 -1
  21. package/dist/next/client.js +1 -1
  22. package/dist/next/client.js.map +1 -1
  23. package/dist/next/config.cjs +1323 -1024
  24. package/dist/next/config.cjs.map +1 -1
  25. package/dist/next/config.d.ts +1 -1
  26. package/dist/next/config.js +1327 -1028
  27. package/dist/next/config.js.map +1 -1
  28. package/dist/next/endpoints.cjs +77 -18
  29. package/dist/next/endpoints.cjs.map +1 -1
  30. package/dist/next/endpoints.d.ts +14 -3
  31. package/dist/next/endpoints.js +77 -18
  32. package/dist/next/endpoints.js.map +1 -1
  33. package/dist/next/middleware.cjs +745 -425
  34. package/dist/next/middleware.cjs.map +1 -1
  35. package/dist/next/middleware.d.ts +10 -5
  36. package/dist/next/middleware.js +745 -425
  37. package/dist/next/middleware.js.map +1 -1
  38. package/dist/next/testing.cjs +595 -1032
  39. package/dist/next/testing.cjs.map +1 -1
  40. package/dist/next/testing.d.ts +14 -12
  41. package/dist/next/testing.js +589 -1016
  42. package/dist/next/testing.js.map +1 -1
  43. package/dist/overrides.cjs +40 -108
  44. package/dist/overrides.cjs.map +1 -1
  45. package/dist/overrides.d.ts +24 -2
  46. package/dist/overrides.js +36 -106
  47. package/dist/overrides.js.map +1 -1
  48. package/dist/routing.cjs +19 -0
  49. package/dist/routing.cjs.map +1 -0
  50. package/dist/routing.d.ts +26 -0
  51. package/dist/routing.js +1 -0
  52. package/dist/{v2/schema.cjs → schema.cjs} +1 -1
  53. package/dist/schema.cjs.map +1 -0
  54. package/dist/schema.d.ts +1 -0
  55. package/dist/schema.js.map +1 -0
  56. package/dist/{types-a995174e.d.ts → types-a29d224a.d.ts} +1 -7
  57. package/dist/{types-15b7f215.d.ts → types-cfe3308b.d.ts} +1 -1
  58. package/dist/types-fc30696d.d.ts +11 -0
  59. package/dist/utils/mfe-port.cjs +254 -1362
  60. package/dist/utils/mfe-port.cjs.map +1 -1
  61. package/dist/utils/mfe-port.js +250 -1358
  62. package/dist/utils/mfe-port.js.map +1 -1
  63. package/dist/validation.cjs +31 -365
  64. package/dist/validation.cjs.map +1 -1
  65. package/dist/validation.d.ts +3 -152
  66. package/dist/validation.js +30 -363
  67. package/dist/validation.js.map +1 -1
  68. package/package.json +32 -80
  69. package/schema/schema.json +174 -244
  70. package/dist/config/client.cjs +0 -54
  71. package/dist/config/client.cjs.map +0 -1
  72. package/dist/config/client.d.ts +0 -23
  73. package/dist/config/client.js +0 -28
  74. package/dist/config/client.js.map +0 -1
  75. package/dist/config/edge.cjs +0 -508
  76. package/dist/config/edge.cjs.map +0 -1
  77. package/dist/config/edge.d.ts +0 -20
  78. package/dist/config/edge.js +0 -481
  79. package/dist/config/edge.js.map +0 -1
  80. package/dist/microfrontend-config-983a5139.d.ts +0 -154
  81. package/dist/schema-2922d49e.d.ts +0 -182
  82. package/dist/v2/config.cjs +0 -723
  83. package/dist/v2/config.cjs.map +0 -1
  84. package/dist/v2/config.d.ts +0 -3
  85. package/dist/v2/config.js +0 -698
  86. package/dist/v2/config.js.map +0 -1
  87. package/dist/v2/microfrontends/server.cjs.map +0 -1
  88. package/dist/v2/microfrontends/server.js.map +0 -1
  89. package/dist/v2/microfrontends.cjs.map +0 -1
  90. package/dist/v2/microfrontends.js.map +0 -1
  91. package/dist/v2/next/client.cjs +0 -3
  92. package/dist/v2/next/client.cjs.map +0 -1
  93. package/dist/v2/next/client.d.ts +0 -45
  94. package/dist/v2/next/client.js +0 -3
  95. package/dist/v2/next/client.js.map +0 -1
  96. package/dist/v2/next/config.cjs +0 -2132
  97. package/dist/v2/next/config.cjs.map +0 -1
  98. package/dist/v2/next/config.d.ts +0 -22
  99. package/dist/v2/next/config.js +0 -2097
  100. package/dist/v2/next/config.js.map +0 -1
  101. package/dist/v2/next/endpoints.cjs +0 -141
  102. package/dist/v2/next/endpoints.cjs.map +0 -1
  103. package/dist/v2/next/endpoints.d.ts +0 -15
  104. package/dist/v2/next/endpoints.js +0 -116
  105. package/dist/v2/next/endpoints.js.map +0 -1
  106. package/dist/v2/next/middleware.cjs +0 -1143
  107. package/dist/v2/next/middleware.cjs.map +0 -1
  108. package/dist/v2/next/middleware.d.ts +0 -29
  109. package/dist/v2/next/middleware.js +0 -1115
  110. package/dist/v2/next/middleware.js.map +0 -1
  111. package/dist/v2/overrides.cjs +0 -75
  112. package/dist/v2/overrides.cjs.map +0 -1
  113. package/dist/v2/overrides.d.ts +0 -24
  114. package/dist/v2/overrides.js +0 -45
  115. package/dist/v2/overrides.js.map +0 -1
  116. package/dist/v2/schema.cjs.map +0 -1
  117. package/dist/v2/schema.d.ts +0 -1
  118. package/schema/schema-v2.json +0 -270
  119. /package/dist/{v2/schema.js.map → routing.js.map} +0 -0
  120. /package/dist/{v2/schema.js → schema.js} +0 -0
@@ -1,1115 +0,0 @@
1
- // src/next-v2/middleware/middleware.ts
2
- import { NextResponse } from "next/server";
3
- import { pathToRegexp as pathToRegexp3 } from "path-to-regexp";
4
-
5
- // src/config-v2/microfrontends-config/isomorphic/index.ts
6
- import { parse } from "jsonc-parser";
7
-
8
- // src/config-v2/errors.ts
9
- var MicrofrontendError = class extends Error {
10
- constructor(message, opts) {
11
- super(message);
12
- this.name = "MicrofrontendsError";
13
- this.source = (opts == null ? void 0 : opts.source) ?? "@vercel/microfrontends";
14
- this.type = (opts == null ? void 0 : opts.type) ?? "unknown";
15
- this.subtype = opts == null ? void 0 : opts.subtype;
16
- Error.captureStackTrace(this, MicrofrontendError);
17
- }
18
- isKnown() {
19
- return this.type !== "unknown";
20
- }
21
- isUnknown() {
22
- return !this.isKnown();
23
- }
24
- /**
25
- * Converts an error to a MicrofrontendsError.
26
- * @param original - The original error to convert.
27
- * @returns The converted MicrofrontendsError.
28
- */
29
- static convert(original, opts) {
30
- if (opts == null ? void 0 : opts.fileName) {
31
- const err = MicrofrontendError.convertFSError(original, opts.fileName);
32
- if (err) {
33
- return err;
34
- }
35
- }
36
- if (original.message.includes(
37
- "Code generation from strings disallowed for this context"
38
- )) {
39
- return new MicrofrontendError(original.message, {
40
- type: "config",
41
- subtype: "unsupported_validation_env",
42
- source: "ajv"
43
- });
44
- }
45
- return new MicrofrontendError(original.message);
46
- }
47
- static convertFSError(original, fileName) {
48
- if (original instanceof Error && "code" in original) {
49
- if (original.code === "ENOENT") {
50
- return new MicrofrontendError(`Could not find "${fileName}"`, {
51
- type: "config",
52
- subtype: "unable_to_read_file",
53
- source: "fs"
54
- });
55
- }
56
- if (original.code === "EACCES") {
57
- return new MicrofrontendError(
58
- `Permission denied while accessing "${fileName}"`,
59
- {
60
- type: "config",
61
- subtype: "invalid_permissions",
62
- source: "fs"
63
- }
64
- );
65
- }
66
- }
67
- if (original instanceof SyntaxError) {
68
- return new MicrofrontendError(
69
- `Failed to parse "${fileName}": Invalid JSON format.`,
70
- {
71
- type: "config",
72
- subtype: "invalid_syntax",
73
- source: "fs"
74
- }
75
- );
76
- }
77
- return null;
78
- }
79
- /**
80
- * Handles an unknown error and returns a MicrofrontendsError instance.
81
- * @param err - The error to handle.
82
- * @returns A MicrofrontendsError instance.
83
- */
84
- static handle(err, opts) {
85
- if (err instanceof MicrofrontendError) {
86
- return err;
87
- }
88
- if (err instanceof Error) {
89
- return MicrofrontendError.convert(err, opts);
90
- }
91
- if (typeof err === "object" && err !== null) {
92
- if ("message" in err && typeof err.message === "string") {
93
- return MicrofrontendError.convert(new Error(err.message), opts);
94
- }
95
- }
96
- return new MicrofrontendError("An unknown error occurred");
97
- }
98
- };
99
-
100
- // src/config-v2/microfrontends-config/utils/get-config-from-env.ts
101
- function getConfigStringFromEnv() {
102
- const config = process.env.MFE_CONFIG;
103
- if (!config) {
104
- throw new MicrofrontendError(`Missing "MFE_CONFIG" in environment.`, {
105
- type: "config",
106
- subtype: "not_found_in_env"
107
- });
108
- }
109
- return config;
110
- }
111
-
112
- // src/config-v2/schema/utils/is-main-config.ts
113
- function isMainConfig(c) {
114
- return !("partOf" in c);
115
- }
116
-
117
- // src/config-v2/schema/utils/is-default-app.ts
118
- function isDefaultApp(a) {
119
- return !("routing" in a);
120
- }
121
-
122
- // src/config-v2/microfrontends-config/client/index.ts
123
- import { pathToRegexp } from "path-to-regexp";
124
- var MicrofrontendConfigClient = class {
125
- constructor(config, opts) {
126
- this.pathCache = {};
127
- this.serialized = config;
128
- if (opts == null ? void 0 : opts.removeFlaggedPaths) {
129
- for (const app of Object.values(config.applications)) {
130
- if (app.routing) {
131
- app.routing = app.routing.filter((match) => !match.flag);
132
- }
133
- }
134
- }
135
- this.applications = config.applications;
136
- }
137
- /**
138
- * Create a new `MicrofrontendConfigClient` from a JSON string.
139
- * Config must be passed in to remain framework agnostic
140
- */
141
- static fromEnv(config, opts) {
142
- if (!config) {
143
- throw new Error("No microfrontends configuration found");
144
- }
145
- return new MicrofrontendConfigClient(
146
- JSON.parse(config),
147
- opts
148
- );
149
- }
150
- isEqual(other) {
151
- return JSON.stringify(this.applications) === JSON.stringify(other.applications);
152
- }
153
- getApplicationNameForPath(path) {
154
- if (!path.startsWith("/")) {
155
- throw new Error(`Path must start with a /`);
156
- }
157
- if (this.pathCache[path]) {
158
- return this.pathCache[path];
159
- }
160
- const pathname = new URL(path, "https://example.com").pathname;
161
- for (const [name, application] of Object.entries(this.applications)) {
162
- if (application.routing) {
163
- for (const group of application.routing) {
164
- for (const childPath of group.paths) {
165
- const regexp = pathToRegexp(childPath);
166
- if (regexp.test(pathname)) {
167
- this.pathCache[path] = name;
168
- return name;
169
- }
170
- }
171
- }
172
- }
173
- }
174
- const defaultApplication = Object.entries(this.applications).find(
175
- ([, application]) => application.default
176
- );
177
- if (!defaultApplication) {
178
- return null;
179
- }
180
- this.pathCache[path] = defaultApplication[0];
181
- return defaultApplication[0];
182
- }
183
- serialize() {
184
- return this.serialized;
185
- }
186
- };
187
-
188
- // src/config-v2/overrides/constants.ts
189
- var OVERRIDES_COOKIE_PREFIX = "vercel-micro-frontends-override";
190
- var OVERRIDES_ENV_COOKIE_PREFIX = `${OVERRIDES_COOKIE_PREFIX}:env:`;
191
-
192
- // src/config-v2/overrides/is-override-cookie.ts
193
- function isOverrideCookie(cookie) {
194
- var _a;
195
- return Boolean((_a = cookie.name) == null ? void 0 : _a.startsWith(OVERRIDES_COOKIE_PREFIX));
196
- }
197
-
198
- // src/config-v2/overrides/get-override-from-cookie.ts
199
- function getOverrideFromCookie(cookie) {
200
- if (!isOverrideCookie(cookie) || !cookie.value)
201
- return;
202
- return {
203
- application: cookie.name.replace(OVERRIDES_ENV_COOKIE_PREFIX, ""),
204
- host: cookie.value
205
- };
206
- }
207
-
208
- // src/config-v2/overrides/parse-overrides.ts
209
- function parseOverrides(cookies) {
210
- const overridesConfig = { applications: {} };
211
- cookies.forEach((cookie) => {
212
- const override = getOverrideFromCookie(cookie);
213
- if (!override)
214
- return;
215
- overridesConfig.applications[override.application] = {
216
- environment: { host: override.host }
217
- };
218
- });
219
- return overridesConfig;
220
- }
221
-
222
- // src/config-v2/microfrontends-config/isomorphic/validation.ts
223
- import { pathToRegexp as pathToRegexp2, parse as parsePathRegexp } from "path-to-regexp";
224
- var SUPPORTED_VERSIONS = ["2"];
225
- var validateConfigVersion = (version) => {
226
- if (!SUPPORTED_VERSIONS.includes(version)) {
227
- throw new MicrofrontendError(
228
- `Unsupported version: ${version}. Supported versions are: ${SUPPORTED_VERSIONS.join(
229
- ", "
230
- )}`,
231
- { type: "config", subtype: "unsupported_version" }
232
- );
233
- }
234
- };
235
- var validateConfigPaths = (applicationConfigsById) => {
236
- if (!applicationConfigsById) {
237
- return;
238
- }
239
- const pathsByApplicationId = /* @__PURE__ */ new Map();
240
- const errors = [];
241
- for (const [id, app] of Object.entries(applicationConfigsById)) {
242
- if (isDefaultApp(app)) {
243
- continue;
244
- }
245
- for (const pathMatch of app.routing) {
246
- for (const path of pathMatch.paths) {
247
- const tokens = parsePathRegexp(path);
248
- for (const token of tokens.slice(0, -1)) {
249
- if (typeof token !== "string") {
250
- errors.push(
251
- `Path ${path} may only have a :wildcard in the last path component`
252
- );
253
- }
254
- }
255
- const existing = pathsByApplicationId.get(path);
256
- if (existing) {
257
- existing.applications.push(id);
258
- } else {
259
- pathsByApplicationId.set(path, {
260
- applications: [id],
261
- matcher: pathToRegexp2(path),
262
- applicationId: id
263
- });
264
- }
265
- }
266
- }
267
- }
268
- const entries = Array.from(pathsByApplicationId.entries());
269
- entries.forEach(([path, { applications: ids, matcher, applicationId }]) => {
270
- if (ids.length > 1) {
271
- errors.push(
272
- `Duplicate path "${path}" for applications "${ids.join(", ")}"`
273
- );
274
- }
275
- entries.forEach(
276
- ([
277
- matchPath,
278
- { applications: matchIds, applicationId: matchApplicationId }
279
- ]) => {
280
- if (path === matchPath) {
281
- return;
282
- }
283
- if (applicationId === matchApplicationId) {
284
- return;
285
- }
286
- if (matcher.test(matchPath)) {
287
- const source = `"${path}" of application${ids.length > 0 ? "s" : ""} ${ids.join(", ")}`;
288
- const destination = `"${matchPath}" of application${matchIds.length > 0 ? "s" : ""} ${matchIds.join(", ")}`;
289
- errors.push(
290
- `Overlapping path detected between ${source} and ${destination}`
291
- );
292
- }
293
- }
294
- );
295
- });
296
- if (errors.length) {
297
- throw new MicrofrontendError(`Invalid paths: ${errors.join(", ")}`, {
298
- type: "config",
299
- subtype: "conflicting_paths"
300
- });
301
- }
302
- };
303
- var validateAppPaths = (name, app) => {
304
- for (const group of app.routing) {
305
- for (const p of group.paths) {
306
- if (p === "/") {
307
- continue;
308
- }
309
- if (p.endsWith("/")) {
310
- throw new MicrofrontendError(
311
- `Invalid path for application "${name}". ${p} must not end with a slash.`,
312
- { type: "application", subtype: "invalid_path" }
313
- );
314
- }
315
- if (!p.startsWith("/")) {
316
- throw new MicrofrontendError(
317
- `Invalid path for application "${name}". ${p} must start with a slash.`,
318
- { type: "application", subtype: "invalid_path" }
319
- );
320
- }
321
- }
322
- }
323
- };
324
- var validateConfigDefaultApplication = (applicationConfigsById) => {
325
- if (!applicationConfigsById) {
326
- return;
327
- }
328
- const applicationsWithRouting = Object.entries(applicationConfigsById).filter(
329
- ([, app]) => !isDefaultApp(app)
330
- );
331
- const applicationsWithRoutingNames = applicationsWithRouting.map(
332
- ([key]) => key
333
- );
334
- const numApplications = Object.keys(applicationConfigsById).length;
335
- const numApplicationsWithRouting = applicationsWithRoutingNames.length;
336
- const numApplicationsWithoutRouting = numApplications - numApplicationsWithRouting;
337
- if (numApplicationsWithoutRouting === 0) {
338
- throw new MicrofrontendError(
339
- `No default application found. At least one application needs to be the default by omitting routing.`,
340
- { type: "config", subtype: "no_default_application" }
341
- );
342
- }
343
- if (numApplicationsWithoutRouting > 1) {
344
- throw new MicrofrontendError(
345
- `Only one application can omit "routing". Found ${applicationsWithRoutingNames.length - Object.keys(applicationConfigsById).length > 1}.`,
346
- { type: "config", subtype: "multiple_default_applications" }
347
- );
348
- }
349
- };
350
- var validateConfigOptions = (options) => {
351
- var _a;
352
- if ((_a = options == null ? void 0 : options.vercel) == null ? void 0 : _a.previewDeploymentSuffix) {
353
- if (!/^[a-zA-Z]{2,}\.[a-zA-Z]{2,}$/.test(
354
- options.vercel.previewDeploymentSuffix
355
- )) {
356
- throw new MicrofrontendError(
357
- `Invalid preview deployment suffix: ${options.vercel.previewDeploymentSuffix}. Should have be formatted like "vercel.app".`,
358
- { type: "config", subtype: "invalid_preview_deployment_suffix" }
359
- );
360
- }
361
- }
362
- };
363
-
364
- // src/config-v2/microfrontends-config/isomorphic/utils/generate-asset-prefix.ts
365
- var PREFIX = "vc-ap";
366
- function generateAssetPrefixFromName({
367
- name
368
- }) {
369
- if (!name) {
370
- throw new Error("Name is required to generate an asset prefix");
371
- }
372
- return `${PREFIX}-${name}`;
373
- }
374
-
375
- // src/config-v2/microfrontends-config/isomorphic/utils/generate-port.ts
376
- function generatePortFromName({
377
- name,
378
- minPort = 3e3,
379
- maxPort = 8e3
380
- }) {
381
- if (!name) {
382
- throw new Error("Name is required to generate a port");
383
- }
384
- let hash = 0;
385
- for (let i = 0; i < name.length; i++) {
386
- hash = (hash << 5) - hash + name.charCodeAt(i);
387
- hash |= 0;
388
- }
389
- hash = Math.abs(hash);
390
- const range = maxPort - minPort;
391
- const port = minPort + hash % range;
392
- return port;
393
- }
394
-
395
- // src/config-v2/microfrontends-config/isomorphic/host.ts
396
- var Host = class {
397
- constructor(hostConfig, options) {
398
- const { protocol = "https", host, port } = hostConfig;
399
- this.protocol = protocol;
400
- this.host = host;
401
- this.port = Host.getPort({ port, protocol: this.protocol });
402
- this.local = options == null ? void 0 : options.isLocal;
403
- }
404
- isLocal() {
405
- return this.local || this.host === "localhost" || this.host === "127.0.0.1";
406
- }
407
- static getPort({
408
- protocol,
409
- port
410
- }) {
411
- if (!port) {
412
- if (protocol === "http") {
413
- return 80;
414
- }
415
- return 443;
416
- }
417
- return port;
418
- }
419
- isDefaultPort() {
420
- return this.port === Host.getPort({ protocol: this.protocol });
421
- }
422
- toString(opts = {}) {
423
- const url = this.toUrl(opts);
424
- return url.toString().replace(/\/$/, "");
425
- }
426
- toUrl(opts = {}) {
427
- const { includeDefaultPort } = opts;
428
- const url = `${this.protocol}://${this.host}${this.isDefaultPort() && !includeDefaultPort ? "" : `:${this.port}`}`;
429
- return new URL(url);
430
- }
431
- };
432
- var LocalHost = class extends Host {
433
- constructor({
434
- appName,
435
- ...hostConfig
436
- }) {
437
- const host = hostConfig.host ?? "localhost";
438
- const port = hostConfig.port ?? generatePortFromName({ name: appName });
439
- const protocol = hostConfig.protocol ?? "http";
440
- super({ protocol, host, port });
441
- }
442
- };
443
-
444
- // src/config-v2/microfrontends-config/isomorphic/application.ts
445
- var Application = class {
446
- constructor(name, {
447
- app,
448
- overrides,
449
- isDefault
450
- }) {
451
- var _a, _b;
452
- this.name = name;
453
- this.development = {
454
- local: new LocalHost({
455
- appName: name,
456
- ...(_a = app.development) == null ? void 0 : _a.local
457
- }),
458
- fallback: ((_b = app.development) == null ? void 0 : _b.fallback) ? new Host(app.development.fallback) : void 0
459
- };
460
- this.production = app.production ? new Host(app.production) : void 0;
461
- this.vercel = app.vercel;
462
- this.overrides = (overrides == null ? void 0 : overrides.environment) ? {
463
- environment: new Host(overrides.environment)
464
- } : void 0;
465
- this.default = isDefault ?? false;
466
- this.serialized = app;
467
- }
468
- isDefault() {
469
- return this.default;
470
- }
471
- getAssetPrefix() {
472
- return generateAssetPrefixFromName({ name: this.name });
473
- }
474
- serialize() {
475
- return this.serialized;
476
- }
477
- };
478
- var DefaultApplication = class extends Application {
479
- constructor(name, {
480
- app,
481
- overrides
482
- }) {
483
- super(name, {
484
- app,
485
- overrides,
486
- isDefault: true
487
- });
488
- this.default = true;
489
- this.production = new Host(app.production);
490
- }
491
- getAssetPrefix() {
492
- return "";
493
- }
494
- };
495
- var ChildApplication = class extends Application {
496
- constructor(name, {
497
- app,
498
- overrides
499
- }) {
500
- ChildApplication.validate(name, app);
501
- super(name, {
502
- app,
503
- overrides,
504
- isDefault: false
505
- });
506
- this.default = false;
507
- this.routing = app.routing;
508
- }
509
- static validate(name, app) {
510
- validateAppPaths(name, app);
511
- }
512
- };
513
-
514
- // src/config-v2/microfrontends-config/isomorphic/constants.ts
515
- var DEFAULT_LOCAL_PROXY_PORT = 3024;
516
-
517
- // src/config-v2/microfrontends-config/isomorphic/index.ts
518
- var MicrofrontendConfigIsomorphic = class {
519
- constructor({
520
- config,
521
- overrides,
522
- meta
523
- }) {
524
- this.childApplications = {};
525
- var _a, _b, _c, _d;
526
- MicrofrontendConfigIsomorphic.validate(config);
527
- const disableOverrides = ((_b = (_a = config.options) == null ? void 0 : _a.vercel) == null ? void 0 : _b.disableOverrides) ?? false;
528
- this.overrides = overrides && !disableOverrides ? overrides : void 0;
529
- this.isMainConfig = isMainConfig(config);
530
- if (isMainConfig(config)) {
531
- for (const [appId, appConfig] of Object.entries(config.applications)) {
532
- const appOverrides = !disableOverrides ? (_c = this.overrides) == null ? void 0 : _c.applications[appId] : void 0;
533
- if (isDefaultApp(appConfig)) {
534
- this.defaultApplication = new DefaultApplication(appId, {
535
- app: appConfig,
536
- overrides: appOverrides
537
- });
538
- } else {
539
- this.childApplications[appId] = new ChildApplication(appId, {
540
- app: appConfig,
541
- overrides: appOverrides
542
- });
543
- }
544
- }
545
- } else {
546
- this.partOf = config.partOf;
547
- const appOverrides = !disableOverrides ? (_d = this.overrides) == null ? void 0 : _d.applications[meta.fromApp] : void 0;
548
- this.childApplications[meta.fromApp] = new ChildApplication(
549
- meta.fromApp,
550
- {
551
- // we don't know routing because we're not in the main config
552
- app: { routing: [] },
553
- overrides: appOverrides
554
- }
555
- );
556
- }
557
- if (isMainConfig(config) && !this.defaultApplication) {
558
- throw new MicrofrontendError(
559
- `Could not find default application in microfrontends configuration`,
560
- {
561
- type: "application",
562
- subtype: "not_found"
563
- }
564
- );
565
- }
566
- this.config = config;
567
- this.options = config.options;
568
- this.serialized = {
569
- config,
570
- overrides,
571
- meta
572
- };
573
- }
574
- static validate(config) {
575
- const c = typeof config === "string" ? parse(config) : config;
576
- if (isMainConfig(c)) {
577
- validateConfigVersion(c.version);
578
- validateConfigPaths(c.applications);
579
- validateConfigDefaultApplication(c.applications);
580
- }
581
- validateConfigOptions(c.options);
582
- return c;
583
- }
584
- static fromEnv({
585
- meta,
586
- cookies
587
- }) {
588
- return new MicrofrontendConfigIsomorphic({
589
- config: parse(getConfigStringFromEnv()),
590
- overrides: parseOverrides(cookies ?? []),
591
- meta
592
- });
593
- }
594
- isOverridesDisabled() {
595
- var _a, _b;
596
- return ((_b = (_a = this.options) == null ? void 0 : _a.vercel) == null ? void 0 : _b.disableOverrides) ?? false;
597
- }
598
- getConfig() {
599
- return this.config;
600
- }
601
- getApplicationsByType() {
602
- return {
603
- defaultApplication: this.defaultApplication,
604
- applications: Object.values(this.childApplications)
605
- };
606
- }
607
- getChildApplications() {
608
- return Object.values(this.childApplications);
609
- }
610
- getAllApplications() {
611
- return [
612
- this.defaultApplication,
613
- ...Object.values(this.childApplications)
614
- ].filter(Boolean);
615
- }
616
- getApplication(name) {
617
- var _a;
618
- if (((_a = this.defaultApplication) == null ? void 0 : _a.name) === name) {
619
- return this.defaultApplication;
620
- }
621
- const app = this.childApplications[name];
622
- if (!app) {
623
- throw new MicrofrontendError(
624
- `Could not find microfrontends configuration for application "${name}"`,
625
- {
626
- type: "application",
627
- subtype: "not_found"
628
- }
629
- );
630
- }
631
- return app;
632
- }
633
- getApplicationByProjectId(projectId) {
634
- var _a, _b;
635
- if (((_b = (_a = this.defaultApplication) == null ? void 0 : _a.vercel) == null ? void 0 : _b.projectId) === projectId) {
636
- return this.defaultApplication;
637
- }
638
- return Object.values(this.childApplications).find(
639
- (app) => {
640
- var _a2;
641
- return ((_a2 = app.vercel) == null ? void 0 : _a2.projectId) === projectId;
642
- }
643
- );
644
- }
645
- /**
646
- * Returns the default application. This can throw if the default application
647
- * is undefined ( )
648
- */
649
- getDefaultApplication() {
650
- if (!this.defaultApplication) {
651
- throw new MicrofrontendError(
652
- `Could not find default application in microfrontends configuration`,
653
- {
654
- type: "application",
655
- subtype: "not_found"
656
- }
657
- );
658
- }
659
- return this.defaultApplication;
660
- }
661
- /**
662
- * Returns the configured port for the local proxy
663
- */
664
- getLocalProxyPort() {
665
- var _a, _b;
666
- return ((_b = (_a = this.config.options) == null ? void 0 : _a.localProxy) == null ? void 0 : _b.port) ?? DEFAULT_LOCAL_PROXY_PORT;
667
- }
668
- /**
669
- * Serializes the class back to the Schema type.
670
- *
671
- * NOTE: This is used when writing the config to disk and must always match the input Schema
672
- */
673
- toSchemaJson() {
674
- return this.serialized.config;
675
- }
676
- toClientConfig() {
677
- const applications = Object.fromEntries(
678
- Object.entries(this.childApplications).map(([name, application]) => [
679
- name,
680
- {
681
- default: false,
682
- routing: application.routing
683
- }
684
- ])
685
- );
686
- if (this.defaultApplication) {
687
- applications[this.defaultApplication.name] = {
688
- default: true
689
- };
690
- }
691
- return new MicrofrontendConfigClient({
692
- applications
693
- });
694
- }
695
- serialize() {
696
- return this.serialized;
697
- }
698
- };
699
-
700
- // src/config-v2/microfrontends-config/isomorphic/child.ts
701
- var MicrofrontendChildConfig = class extends MicrofrontendConfigIsomorphic {
702
- constructor({
703
- config,
704
- overrides,
705
- meta
706
- }) {
707
- super({ config, overrides, meta });
708
- this.isMainConfig = false;
709
- this.partOf = config.partOf;
710
- }
711
- };
712
-
713
- // src/config-v2/microfrontends-config/isomorphic/main.ts
714
- var MicrofrontendMainConfig = class extends MicrofrontendConfigIsomorphic {
715
- constructor({
716
- config,
717
- overrides,
718
- meta
719
- }) {
720
- var _a, _b, _c;
721
- super({ config, overrides, meta });
722
- this.isMainConfig = true;
723
- const disableOverrides = ((_b = (_a = config.options) == null ? void 0 : _a.vercel) == null ? void 0 : _b.disableOverrides) ?? false;
724
- let defaultApplication;
725
- for (const [appId, appConfig] of Object.entries(config.applications)) {
726
- const appOverrides = !disableOverrides ? (_c = this.overrides) == null ? void 0 : _c.applications[appId] : void 0;
727
- if (isDefaultApp(appConfig)) {
728
- defaultApplication = new DefaultApplication(appId, {
729
- app: appConfig,
730
- overrides: appOverrides
731
- });
732
- } else {
733
- this.childApplications[appId] = new ChildApplication(appId, {
734
- app: appConfig,
735
- overrides: appOverrides
736
- });
737
- }
738
- }
739
- if (!defaultApplication) {
740
- throw new MicrofrontendError(
741
- `Could not find default application in microfrontends configuration`,
742
- {
743
- type: "application",
744
- subtype: "not_found"
745
- }
746
- );
747
- }
748
- this.defaultApplication = defaultApplication;
749
- }
750
- };
751
-
752
- // src/config-v2/microfrontends/isomorphic/index.ts
753
- var Microfrontends = class {
754
- constructor({
755
- config,
756
- overrides,
757
- meta
758
- }) {
759
- if (isMainConfig(config)) {
760
- this.config = new MicrofrontendMainConfig({ config, overrides, meta });
761
- } else {
762
- this.config = new MicrofrontendChildConfig({ config, overrides, meta });
763
- }
764
- }
765
- isChildConfig() {
766
- return this.config instanceof MicrofrontendChildConfig;
767
- }
768
- static fromEnv({
769
- cookies,
770
- meta
771
- }) {
772
- const config = MicrofrontendConfigIsomorphic.fromEnv({
773
- cookies,
774
- meta
775
- });
776
- return new Microfrontends(config.serialize());
777
- }
778
- };
779
-
780
- // src/routing-v2/get-domain-from-environment.ts
781
- function getDomainFromEnvironment({
782
- app,
783
- target
784
- }) {
785
- var _a;
786
- const mfeProjects = JSON.parse(
787
- process.env.VERCEL_MICROFRONTENDS_PROJECTS ?? "[]"
788
- );
789
- if (mfeProjects.length === 0) {
790
- throw new Error("Missing related microfrontends project information");
791
- }
792
- if (!((_a = app.vercel) == null ? void 0 : _a.projectId)) {
793
- throw new Error(`Missing applications[${app.name}].vercel.projectId`);
794
- }
795
- const vercelProject = mfeProjects.find(
796
- (p) => {
797
- var _a2;
798
- return p.project.id === ((_a2 = app.vercel) == null ? void 0 : _a2.projectId);
799
- }
800
- );
801
- if (!vercelProject) {
802
- throw new Error(
803
- `Missing related microfrontends project information for application "${app.name}"`
804
- );
805
- }
806
- const domain = target === "preview" && vercelProject.preview.branch ? vercelProject.preview.branch : vercelProject.production.alias ?? vercelProject.production.url;
807
- if (!domain) {
808
- throw new Error(
809
- `Missing domain for target "${target}" in application "${app.name}"`
810
- );
811
- }
812
- return domain.startsWith("https://") ? domain : `https://${domain}`;
813
- }
814
-
815
- // src/routing-v2/get-domain-for-current-environment.ts
816
- function debugDomains(zone, env, domain) {
817
- if (process.env.MFE_DEBUG === "true") {
818
- const indent = " ".repeat(4);
819
- const header = "domains (zone (env) -> domain)";
820
- const separator = "\u23AF".repeat(header.length);
821
- const line = `${indent} 1. ${zone} (${env}) -> ${domain}`;
822
- console.log(`${indent}${header}
823
- ${indent}${separator}
824
- ${line}
825
- `);
826
- }
827
- }
828
- function getCurrentEnvironment() {
829
- const isDevelopment = !process.env.VERCEL_ENV || process.env.VERCEL_ENV === "development";
830
- const isPreview = process.env.VERCEL_ENV === "preview";
831
- const isProduction = process.env.VERCEL_ENV === "production";
832
- if (isDevelopment) {
833
- return { group: "development" };
834
- } else if (isProduction) {
835
- return { group: "production" };
836
- } else if (isPreview) {
837
- return { group: "preview" };
838
- }
839
- return { group: "custom", name: process.env.VERCEL_ENV };
840
- }
841
- function getDomainForCurrentEnvironment(config, appName, opts = {}) {
842
- var _a;
843
- const app = config.getApplication(appName);
844
- if (!opts.ignoreOverride && ((_a = app.overrides) == null ? void 0 : _a.environment)) {
845
- return app.overrides.environment.toString();
846
- }
847
- const { group } = getCurrentEnvironment();
848
- const productionHost = config.getDefaultApplication().production.toString();
849
- switch (group) {
850
- case "development": {
851
- const domain = ["test", "development"].includes(process.env.NODE_ENV) ? app.development.local.toString() : productionHost;
852
- debugDomains(appName, "development", domain);
853
- return domain;
854
- }
855
- case "preview": {
856
- return getDomainFromEnvironment({ app, target: "preview" });
857
- }
858
- case "production": {
859
- return getDomainFromEnvironment({ app, target: "production" });
860
- }
861
- case "custom":
862
- console.warn(
863
- `Custom environments are not supported in getDomainForCurrentEnvironment`
864
- );
865
- return productionHost;
866
- }
867
- }
868
-
869
- // src/next-v2/middleware/middleware.ts
870
- async function verifyPreviewDomain(req, rewriteDomain) {
871
- var _a;
872
- const jwtCookie = (_a = req.cookies.get("_vercel_jwt")) == null ? void 0 : _a.value;
873
- const deploymentProtectionBypassHeader = req.headers.get(
874
- "x-vercel-protection-bypass"
875
- );
876
- const previewResponse = await fetch(rewriteDomain, {
877
- method: "HEAD",
878
- headers: {
879
- "x-vercel-micro-frontends-check": "1",
880
- ...jwtCookie ? { cookie: `_vercel_jwt=${jwtCookie}` } : {},
881
- ...deploymentProtectionBypassHeader ? {
882
- "x-vercel-protection-bypass": deploymentProtectionBypassHeader
883
- } : {}
884
- }
885
- });
886
- const vercelError = previewResponse.headers.get("x-vercel-error");
887
- return !(previewResponse.status === 404 && (vercelError === "DEPLOYMENT_NOT_FOUND" || vercelError === "NOT_FOUND"));
888
- }
889
- function microfrontendInternalRoutingHandler({
890
- config,
891
- production
892
- }) {
893
- return async (req) => {
894
- const payload = Object.fromEntries(
895
- await Promise.all(
896
- config.getAllApplications().map(async (application) => {
897
- let rewriteDomain = getDomainForCurrentEnvironment(
898
- config,
899
- application.name,
900
- {
901
- ignoreOverride: true
902
- }
903
- );
904
- const isPreviewDomainAvailable = await verifyPreviewDomain(
905
- req,
906
- rewriteDomain
907
- );
908
- if (!isPreviewDomainAvailable) {
909
- rewriteDomain = production.toString();
910
- }
911
- return [
912
- application.name,
913
- { routing: { host: rewriteDomain } }
914
- ];
915
- })
916
- )
917
- );
918
- return NextResponse.json(payload);
919
- };
920
- }
921
- function getHandler({
922
- config,
923
- application,
924
- flagFn,
925
- pattern,
926
- production
927
- }) {
928
- return async (req) => {
929
- var _a, _b;
930
- try {
931
- const pathname = req.nextUrl.pathname;
932
- const search = req.nextUrl.search;
933
- const proxyRouting = req.headers.get("X-Vercel-Mfe-Proxy") === "1";
934
- let rewriteDomain = proxyRouting ? null : getDomainForCurrentEnvironment(config, application.name);
935
- const patchedHeaders = new Headers(req.headers);
936
- const responseCallbacks = [];
937
- const onRewrite = (response) => {
938
- for (const callback of responseCallbacks) {
939
- callback(response);
940
- }
941
- return response;
942
- };
943
- if (process.env.VERCEL_ENV === "preview" && rewriteDomain) {
944
- const zoneFallbackCookieName = `__zone_${application.name}_production_fallback`;
945
- const assetPrefix = application.getAssetPrefix();
946
- if (assetPrefix && pathname.startsWith(`/${assetPrefix}`) && ((_a = req.cookies.get(zoneFallbackCookieName)) == null ? void 0 : _a.value) === "1") {
947
- rewriteDomain = production.toString();
948
- } else {
949
- try {
950
- let deploymentFound;
951
- if (req.headers.get("x-vercel-skip-deployment-existence-check")) {
952
- deploymentFound = true;
953
- } else {
954
- deploymentFound = await verifyPreviewDomain(req, rewriteDomain);
955
- }
956
- if (!deploymentFound) {
957
- rewriteDomain = production.toString();
958
- responseCallbacks.push((response) => {
959
- response.cookies.set(zoneFallbackCookieName, "1", {
960
- httpOnly: true,
961
- sameSite: "lax",
962
- secure: true,
963
- maxAge: 60
964
- // 1 minute
965
- });
966
- });
967
- try {
968
- const existingCookie = patchedHeaders.get("cookie");
969
- if (!(existingCookie == null ? void 0 : existingCookie.includes("__vercel_toolbar"))) {
970
- patchedHeaders.set(
971
- "cookie",
972
- [`__vercel_toolbar=1`, existingCookie].join("; ")
973
- );
974
- responseCallbacks.push((response) => {
975
- response.cookies.set("__vercel_toolbar", "1", {
976
- httpOnly: false,
977
- sameSite: "lax",
978
- secure: true,
979
- maxAge: 29030400
980
- });
981
- });
982
- }
983
- } catch (error) {
984
- }
985
- } else if (((_b = req.cookies.get(zoneFallbackCookieName)) == null ? void 0 : _b.value) === "1") {
986
- responseCallbacks.push((response) => {
987
- response.cookies.set(zoneFallbackCookieName, "", {
988
- httpOnly: true,
989
- sameSite: "lax",
990
- secure: true,
991
- maxAge: 0
992
- });
993
- });
994
- }
995
- } catch {
996
- }
997
- }
998
- }
999
- const isFlagEnabled = async () => flagFn ? flagFn() : true;
1000
- if (pattern.test(pathname) && await isFlagEnabled()) {
1001
- if (proxyRouting) {
1002
- const headers = new Headers(req.headers);
1003
- headers.set("x-vercel-mfe-zone", application.name);
1004
- return onRewrite(
1005
- NextResponse.next({
1006
- request: {
1007
- headers
1008
- },
1009
- headers: {
1010
- // temporary, can delete when proxyRouting flag is removed
1011
- "x-vercel-mfe-middleware-sent-proxy": application.name
1012
- }
1013
- })
1014
- );
1015
- }
1016
- return onRewrite(
1017
- NextResponse.rewrite(`${rewriteDomain}${pathname}${search}`, {
1018
- request: {
1019
- headers: patchedHeaders
1020
- }
1021
- })
1022
- );
1023
- }
1024
- } catch (e) {
1025
- console.error("An error occured in the microfrontends middleware:", e);
1026
- throw e;
1027
- }
1028
- };
1029
- }
1030
- function getMicrofrontendsMiddleware({
1031
- request,
1032
- flagValues
1033
- }) {
1034
- const microfrontends = Microfrontends.fromEnv({
1035
- cookies: request.cookies.getAll(),
1036
- meta: {
1037
- fromApp: "vercel-site"
1038
- }
1039
- });
1040
- const middlewares = [];
1041
- if (microfrontends.config instanceof MicrofrontendChildConfig) {
1042
- return middlewares;
1043
- }
1044
- const config = microfrontends.config;
1045
- const production = config.defaultApplication.production;
1046
- middlewares.push({
1047
- src: "/.well-known/vercel/microfrontend-routing",
1048
- fn: microfrontendInternalRoutingHandler({ config, production })
1049
- });
1050
- for (const application of config.getChildApplications()) {
1051
- if (application.name === process.env.NEXT_PUBLIC_MFE_CURRENT_APPLICATION) {
1052
- continue;
1053
- }
1054
- if (process.env.VERCEL_ENV === "preview") {
1055
- const pattern = pathToRegexp3(`/${application.getAssetPrefix()}/:path+`);
1056
- middlewares.push({
1057
- src: pattern,
1058
- fn: getHandler({
1059
- config,
1060
- application,
1061
- pattern,
1062
- production
1063
- })
1064
- });
1065
- }
1066
- for (const pathGroup of application.routing) {
1067
- if (process.env.VERCEL_ENV === "preview" || pathGroup.flag) {
1068
- const flagName = pathGroup.flag;
1069
- let flagFn;
1070
- if (flagName) {
1071
- flagFn = flagValues == null ? void 0 : flagValues[flagName];
1072
- if (!flagFn) {
1073
- throw new Error(
1074
- `Flag "${flagName}" was specified to control routing for path group "${pathGroup.group}" in application ${application.name} but not found in provided flag values.`
1075
- );
1076
- }
1077
- }
1078
- for (const path of pathGroup.paths) {
1079
- const pattern = pathToRegexp3(path);
1080
- middlewares.push({
1081
- src: pattern,
1082
- fn: getHandler({
1083
- config,
1084
- application,
1085
- flagFn,
1086
- pattern,
1087
- production
1088
- })
1089
- });
1090
- }
1091
- }
1092
- }
1093
- }
1094
- return middlewares;
1095
- }
1096
- async function runMicrofrontendsMiddleware(request, flagValues) {
1097
- const pathname = request.nextUrl.pathname;
1098
- const middlewares = getMicrofrontendsMiddleware({
1099
- request,
1100
- flagValues
1101
- });
1102
- for (const mware of middlewares) {
1103
- if (typeof mware.src === "string" ? pathname === mware.src : mware.src.test(pathname)) {
1104
- const response = await mware.fn(request);
1105
- if (response) {
1106
- return response;
1107
- }
1108
- }
1109
- }
1110
- }
1111
- export {
1112
- getMicrofrontendsMiddleware,
1113
- runMicrofrontendsMiddleware
1114
- };
1115
- //# sourceMappingURL=middleware.js.map