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