@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,1082 @@
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/micro-frontends";
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 micro-frontends 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-microfrontends-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
+ };
492
+ var ChildApplication = class extends Application {
493
+ constructor(name, {
494
+ app,
495
+ overrides
496
+ }) {
497
+ ChildApplication.validate(name, app);
498
+ super(name, {
499
+ app,
500
+ overrides,
501
+ isDefault: false
502
+ });
503
+ this.default = false;
504
+ this.routing = app.routing;
505
+ }
506
+ static validate(name, app) {
507
+ validateAppPaths(name, app);
508
+ }
509
+ };
510
+
511
+ // src/config-v2/microfrontends-config/isomorphic/constants.ts
512
+ var DEFAULT_LOCAL_PROXY_PORT = 3024;
513
+
514
+ // src/config-v2/microfrontends-config/isomorphic/index.ts
515
+ var MicroFrontendConfigIsomorphic = class {
516
+ constructor({
517
+ config,
518
+ overrides,
519
+ meta
520
+ }) {
521
+ this.childApplications = {};
522
+ var _a, _b, _c, _d;
523
+ MicroFrontendConfigIsomorphic.validate(config);
524
+ const disableOverrides = ((_b = (_a = config.options) == null ? void 0 : _a.vercel) == null ? void 0 : _b.disableOverrides) ?? false;
525
+ this.overrides = overrides && !disableOverrides ? overrides : void 0;
526
+ this.isMainConfig = isMainConfig(config);
527
+ if (isMainConfig(config)) {
528
+ for (const [appId, appConfig] of Object.entries(config.applications)) {
529
+ const appOverrides = !disableOverrides ? (_c = this.overrides) == null ? void 0 : _c.applications[appId] : void 0;
530
+ if (isDefaultApp(appConfig)) {
531
+ this.defaultApplication = new DefaultApplication(appId, {
532
+ app: appConfig,
533
+ overrides: appOverrides
534
+ });
535
+ } else {
536
+ this.childApplications[appId] = new ChildApplication(appId, {
537
+ app: appConfig,
538
+ overrides: appOverrides
539
+ });
540
+ }
541
+ }
542
+ } else {
543
+ this.partOf = config.partOf;
544
+ const appOverrides = !disableOverrides ? (_d = this.overrides) == null ? void 0 : _d.applications[meta.fromApp] : void 0;
545
+ this.childApplications[meta.fromApp] = new ChildApplication(
546
+ meta.fromApp,
547
+ {
548
+ // we don't know routing because we're not in the main config
549
+ app: { routing: [] },
550
+ overrides: appOverrides
551
+ }
552
+ );
553
+ }
554
+ if (isMainConfig(config) && !this.defaultApplication) {
555
+ throw new MicroFrontendError(
556
+ `Could not find default application in microfrontends configuration`,
557
+ {
558
+ type: "application",
559
+ subtype: "not_found"
560
+ }
561
+ );
562
+ }
563
+ this.config = config;
564
+ this.options = config.options;
565
+ this.serialized = {
566
+ config,
567
+ overrides,
568
+ meta
569
+ };
570
+ }
571
+ static validate(config) {
572
+ const c = typeof config === "string" ? parse(config) : config;
573
+ if (isMainConfig(c)) {
574
+ validateConfigVersion(c.version);
575
+ validateConfigPaths(c.applications);
576
+ validateConfigDefaultApplication(c.applications);
577
+ }
578
+ validateConfigOptions(c.options);
579
+ return c;
580
+ }
581
+ static fromEnv({
582
+ meta,
583
+ cookies
584
+ }) {
585
+ return new MicroFrontendConfigIsomorphic({
586
+ config: parse(getConfigStringFromEnv()),
587
+ overrides: parseOverrides(cookies ?? []),
588
+ meta
589
+ });
590
+ }
591
+ isOverridesDisabled() {
592
+ var _a, _b;
593
+ return ((_b = (_a = this.options) == null ? void 0 : _a.vercel) == null ? void 0 : _b.disableOverrides) ?? false;
594
+ }
595
+ getConfig() {
596
+ return this.config;
597
+ }
598
+ getApplicationsByType() {
599
+ return {
600
+ defaultApplication: this.defaultApplication,
601
+ applications: Object.values(this.childApplications)
602
+ };
603
+ }
604
+ getChildApplications() {
605
+ return Object.values(this.childApplications);
606
+ }
607
+ getAllApplications() {
608
+ return [
609
+ this.defaultApplication,
610
+ ...Object.values(this.childApplications)
611
+ ].filter(Boolean);
612
+ }
613
+ getApplication(name) {
614
+ var _a;
615
+ if (((_a = this.defaultApplication) == null ? void 0 : _a.name) === name) {
616
+ return this.defaultApplication;
617
+ }
618
+ const app = this.childApplications[name];
619
+ if (!app) {
620
+ throw new MicroFrontendError(
621
+ `Could not find microfrontends configuration for application "${name}"`,
622
+ {
623
+ type: "application",
624
+ subtype: "not_found"
625
+ }
626
+ );
627
+ }
628
+ return app;
629
+ }
630
+ getApplicationByProjectId(projectId) {
631
+ var _a, _b;
632
+ if (((_b = (_a = this.defaultApplication) == null ? void 0 : _a.vercel) == null ? void 0 : _b.projectId) === projectId) {
633
+ return this.defaultApplication;
634
+ }
635
+ return Object.values(this.childApplications).find(
636
+ (app) => {
637
+ var _a2;
638
+ return ((_a2 = app.vercel) == null ? void 0 : _a2.projectId) === projectId;
639
+ }
640
+ );
641
+ }
642
+ /**
643
+ * Returns the default application. This can throw if the default application
644
+ * is undefined ( )
645
+ */
646
+ getDefaultApplication() {
647
+ if (!this.defaultApplication) {
648
+ throw new MicroFrontendError(
649
+ `Could not find default application in microfrontends configuration`,
650
+ {
651
+ type: "application",
652
+ subtype: "not_found"
653
+ }
654
+ );
655
+ }
656
+ return this.defaultApplication;
657
+ }
658
+ /**
659
+ * Returns the configured port for the local proxy
660
+ */
661
+ getLocalProxyPort() {
662
+ var _a, _b;
663
+ return ((_b = (_a = this.config.options) == null ? void 0 : _a.localProxy) == null ? void 0 : _b.port) ?? DEFAULT_LOCAL_PROXY_PORT;
664
+ }
665
+ /**
666
+ * Serializes the class back to the Schema type.
667
+ *
668
+ * NOTE: This is used when writing the config to disk and must always match the input Schema
669
+ */
670
+ toSchemaJson() {
671
+ return this.serialized.config;
672
+ }
673
+ toClientConfig() {
674
+ const applications = Object.fromEntries(
675
+ Object.entries(this.childApplications).map(([name, application]) => [
676
+ name,
677
+ {
678
+ default: false,
679
+ routing: application.routing
680
+ }
681
+ ])
682
+ );
683
+ if (this.defaultApplication) {
684
+ applications[this.defaultApplication.name] = {
685
+ default: true
686
+ };
687
+ }
688
+ return new MicroFrontendConfigClient({
689
+ applications
690
+ });
691
+ }
692
+ serialize() {
693
+ return this.serialized;
694
+ }
695
+ };
696
+
697
+ // src/config-v2/microfrontends-config/isomorphic/child.ts
698
+ var MicroFrontendChildConfig = class extends MicroFrontendConfigIsomorphic {
699
+ constructor({
700
+ config,
701
+ overrides,
702
+ meta
703
+ }) {
704
+ super({ config, overrides, meta });
705
+ this.isMainConfig = false;
706
+ this.partOf = config.partOf;
707
+ }
708
+ };
709
+
710
+ // src/config-v2/microfrontends-config/isomorphic/main.ts
711
+ var MicroFrontendMainConfig = class extends MicroFrontendConfigIsomorphic {
712
+ constructor({
713
+ config,
714
+ overrides,
715
+ meta
716
+ }) {
717
+ var _a, _b, _c;
718
+ super({ config, overrides, meta });
719
+ this.isMainConfig = true;
720
+ this.provider = config.provider;
721
+ const disableOverrides = ((_b = (_a = config.options) == null ? void 0 : _a.vercel) == null ? void 0 : _b.disableOverrides) ?? false;
722
+ let defaultApplication;
723
+ for (const [appId, appConfig] of Object.entries(config.applications)) {
724
+ const appOverrides = !disableOverrides ? (_c = this.overrides) == null ? void 0 : _c.applications[appId] : void 0;
725
+ if (isDefaultApp(appConfig)) {
726
+ defaultApplication = new DefaultApplication(appId, {
727
+ app: appConfig,
728
+ overrides: appOverrides
729
+ });
730
+ } else {
731
+ this.childApplications[appId] = new ChildApplication(appId, {
732
+ app: appConfig,
733
+ overrides: appOverrides
734
+ });
735
+ }
736
+ }
737
+ if (!defaultApplication) {
738
+ throw new MicroFrontendError(
739
+ `Could not find default application in microfrontends configuration`,
740
+ {
741
+ type: "application",
742
+ subtype: "not_found"
743
+ }
744
+ );
745
+ }
746
+ this.defaultApplication = defaultApplication;
747
+ }
748
+ };
749
+
750
+ // src/config-v2/microfrontends/isomorphic/index.ts
751
+ var Microfrontends = class {
752
+ constructor({
753
+ config,
754
+ overrides,
755
+ meta
756
+ }) {
757
+ if (isMainConfig(config)) {
758
+ this.config = new MicroFrontendMainConfig({ config, overrides, meta });
759
+ } else {
760
+ this.config = new MicroFrontendChildConfig({ config, overrides, meta });
761
+ }
762
+ }
763
+ isChildConfig() {
764
+ return this.config instanceof MicroFrontendChildConfig;
765
+ }
766
+ static fromEnv({
767
+ cookies,
768
+ meta
769
+ }) {
770
+ const config = MicroFrontendConfigIsomorphic.fromEnv({
771
+ cookies,
772
+ meta
773
+ });
774
+ return new Microfrontends(config.serialize());
775
+ }
776
+ };
777
+
778
+ // src/routing-v2/get-domain-from-environment.ts
779
+ function getDomainFromEnvironment({
780
+ app,
781
+ target
782
+ }) {
783
+ const projects = JSON.parse(
784
+ process.env.VERCEL_RELATED_PROJECTS ?? "[]"
785
+ );
786
+ if (projects.length === 0) {
787
+ throw new Error("Missing related vercel project information");
788
+ }
789
+ const vercelProject = projects.find(
790
+ (project) => {
791
+ var _a;
792
+ return project.projectId === ((_a = app.vercel) == null ? void 0 : _a.projectId) || project.appName === app.name;
793
+ }
794
+ );
795
+ if (!vercelProject) {
796
+ throw new Error(
797
+ `Missing related vercel project information for application "${app.name}"`
798
+ );
799
+ }
800
+ return vercelProject.aliases[target];
801
+ }
802
+
803
+ // src/routing-v2/get-domain-for-current-environment.ts
804
+ function debugDomains(zone, env, domain) {
805
+ if (process.env.MFE_DEBUG === "true") {
806
+ const indent = " ".repeat(4);
807
+ const header = "domains (zone (env) -> domain)";
808
+ const separator = "\u23AF".repeat(header.length);
809
+ const line = `${indent} 1. ${zone} (${env}) -> ${domain}`;
810
+ console.log(`${indent}${header}
811
+ ${indent}${separator}
812
+ ${line}
813
+ `);
814
+ }
815
+ }
816
+ function getCurrentEnvironment() {
817
+ const isDevelopment = !process.env.VERCEL_ENV || process.env.VERCEL_ENV === "development";
818
+ const isPreview = process.env.VERCEL_ENV === "preview";
819
+ const isProduction = process.env.VERCEL_ENV === "production";
820
+ if (isDevelopment) {
821
+ return { group: "development" };
822
+ } else if (isProduction) {
823
+ return { group: "production" };
824
+ } else if (isPreview) {
825
+ return { group: "preview" };
826
+ }
827
+ return { group: "custom", name: process.env.VERCEL_ENV };
828
+ }
829
+ function getDomainForCurrentEnvironment(config, appName) {
830
+ var _a;
831
+ const app = config.getApplication(appName);
832
+ if ((_a = app.overrides) == null ? void 0 : _a.environment) {
833
+ return app.overrides.environment.toString();
834
+ }
835
+ const { group } = getCurrentEnvironment();
836
+ const productionHost = config.getDefaultApplication().production.toString();
837
+ switch (group) {
838
+ case "development": {
839
+ const domain = process.env.NODE_ENV === "test" ? app.development.local.toString() : productionHost;
840
+ debugDomains(appName, "development", domain);
841
+ return domain;
842
+ }
843
+ case "preview": {
844
+ return getDomainFromEnvironment({ app, target: "branch" });
845
+ }
846
+ case "production": {
847
+ return getDomainFromEnvironment({ app, target: "production" });
848
+ }
849
+ case "custom":
850
+ console.warn(
851
+ `Custom environments are not supported in getDomainForCurrentEnvironment`
852
+ );
853
+ return productionHost;
854
+ }
855
+ }
856
+
857
+ // src/next-v2/middleware/middleware.ts
858
+ async function verifyPreviewDomain(req, rewriteDomain) {
859
+ var _a;
860
+ const jwtCookie = (_a = req.cookies.get("_vercel_jwt")) == null ? void 0 : _a.value;
861
+ const deploymentProtectionBypassHeader = req.headers.get(
862
+ "x-vercel-protection-bypass"
863
+ );
864
+ const previewResponse = await fetch(rewriteDomain, {
865
+ method: "HEAD",
866
+ headers: {
867
+ "x-vercel-micro-frontends-check": "1",
868
+ ...jwtCookie ? { cookie: `_vercel_jwt=${jwtCookie}` } : {},
869
+ ...deploymentProtectionBypassHeader ? {
870
+ "x-vercel-protection-bypass": deploymentProtectionBypassHeader
871
+ } : {}
872
+ }
873
+ });
874
+ const vercelError = previewResponse.headers.get("x-vercel-error");
875
+ return !(previewResponse.status === 404 && (vercelError === "DEPLOYMENT_NOT_FOUND" || vercelError === "NOT_FOUND"));
876
+ }
877
+ function microFrontendInternalRoutingHandler({
878
+ config,
879
+ production
880
+ }) {
881
+ return async (req) => {
882
+ const payload = Object.fromEntries(
883
+ await Promise.all(
884
+ config.getAllApplications().map(async (application) => {
885
+ let rewriteDomain = getDomainForCurrentEnvironment(
886
+ config,
887
+ application.name
888
+ );
889
+ const isPreviewDomainAvailable = await verifyPreviewDomain(
890
+ req,
891
+ rewriteDomain
892
+ );
893
+ if (!isPreviewDomainAvailable) {
894
+ rewriteDomain = production.toString();
895
+ }
896
+ return [
897
+ application.name,
898
+ { routing: { host: rewriteDomain } }
899
+ ];
900
+ })
901
+ )
902
+ );
903
+ return NextResponse.json(payload);
904
+ };
905
+ }
906
+ function getHandler({
907
+ config,
908
+ application,
909
+ flagFn,
910
+ pattern,
911
+ production
912
+ }) {
913
+ return async (req) => {
914
+ var _a, _b;
915
+ const pathname = req.nextUrl.pathname;
916
+ const search = req.nextUrl.search;
917
+ let rewriteDomain = getDomainForCurrentEnvironment(
918
+ config,
919
+ application.name
920
+ );
921
+ const patchedHeaders = new Headers(req.headers);
922
+ const responseCallbacks = [];
923
+ const onRewrite = (response) => {
924
+ for (const callback of responseCallbacks) {
925
+ callback(response);
926
+ }
927
+ return response;
928
+ };
929
+ if (process.env.VERCEL_ENV === "preview" && rewriteDomain) {
930
+ const zoneFallbackCookieName = `__zone_${application.name}_production_fallback`;
931
+ const assetPrefix = application.getAssetPrefix();
932
+ if (assetPrefix && pathname.startsWith(`/${assetPrefix}`) && ((_a = req.cookies.get(zoneFallbackCookieName)) == null ? void 0 : _a.value) === "1") {
933
+ rewriteDomain = production.toString();
934
+ } else {
935
+ try {
936
+ let deploymentFound;
937
+ if (req.headers.get("x-vercel-skip-deployment-existence-check")) {
938
+ deploymentFound = true;
939
+ } else {
940
+ deploymentFound = await verifyPreviewDomain(req, rewriteDomain);
941
+ }
942
+ if (!deploymentFound) {
943
+ rewriteDomain = production.toString();
944
+ responseCallbacks.push((response) => {
945
+ response.cookies.set(zoneFallbackCookieName, "1", {
946
+ httpOnly: true,
947
+ sameSite: "lax",
948
+ secure: true,
949
+ maxAge: 60
950
+ // 1 minute
951
+ });
952
+ });
953
+ try {
954
+ const existingCookie = patchedHeaders.get("cookie");
955
+ if (!(existingCookie == null ? void 0 : existingCookie.includes("__vercel_toolbar"))) {
956
+ patchedHeaders.set(
957
+ "cookie",
958
+ [`__vercel_toolbar=1`, existingCookie].join("; ")
959
+ );
960
+ responseCallbacks.push((response) => {
961
+ response.cookies.set("__vercel_toolbar", "1", {
962
+ httpOnly: false,
963
+ sameSite: "lax",
964
+ secure: true,
965
+ maxAge: 29030400
966
+ });
967
+ });
968
+ }
969
+ } catch (error) {
970
+ }
971
+ } else if (((_b = req.cookies.get(zoneFallbackCookieName)) == null ? void 0 : _b.value) === "1") {
972
+ responseCallbacks.push((response) => {
973
+ response.cookies.set(zoneFallbackCookieName, "", {
974
+ httpOnly: true,
975
+ sameSite: "lax",
976
+ secure: true,
977
+ maxAge: 0
978
+ });
979
+ });
980
+ }
981
+ } catch {
982
+ }
983
+ }
984
+ }
985
+ const isFlagEnabled = async () => flagFn ? flagFn() : true;
986
+ if (pattern.test(pathname) && await isFlagEnabled()) {
987
+ return onRewrite(
988
+ NextResponse.rewrite(`${rewriteDomain}${pathname}${search}`, {
989
+ request: {
990
+ headers: patchedHeaders
991
+ }
992
+ })
993
+ );
994
+ }
995
+ };
996
+ }
997
+ function getMicroFrontendsMiddleware({
998
+ request,
999
+ flagValues
1000
+ }) {
1001
+ const microfrontends = Microfrontends.fromEnv({
1002
+ cookies: request.cookies.getAll(),
1003
+ meta: {
1004
+ fromApp: "vercel-site"
1005
+ }
1006
+ });
1007
+ const middlewares = [];
1008
+ if (microfrontends.config instanceof MicroFrontendChildConfig) {
1009
+ return middlewares;
1010
+ }
1011
+ const config = microfrontends.config;
1012
+ const production = config.defaultApplication.production;
1013
+ middlewares.push({
1014
+ src: "/.well-known/vercel/microfrontend-routing",
1015
+ fn: microFrontendInternalRoutingHandler({ config, production })
1016
+ });
1017
+ for (const application of config.getChildApplications()) {
1018
+ if (application.name === process.env.NEXT_PUBLIC_MFE_CURRENT_APPLICATION) {
1019
+ continue;
1020
+ }
1021
+ if (process.env.VERCEL_ENV === "preview") {
1022
+ const pattern = pathToRegexp3(`/${application.getAssetPrefix()}/:path+`);
1023
+ middlewares.push({
1024
+ src: pattern,
1025
+ fn: getHandler({
1026
+ config,
1027
+ application,
1028
+ pattern,
1029
+ production
1030
+ })
1031
+ });
1032
+ }
1033
+ for (const pathGroup of application.routing) {
1034
+ if (process.env.VERCEL_ENV === "preview" || pathGroup.flag || pathGroup.routeToDefaultApplication) {
1035
+ const flagName = pathGroup.flag;
1036
+ let flagFn;
1037
+ if (flagName) {
1038
+ flagFn = flagValues == null ? void 0 : flagValues[flagName];
1039
+ if (!flagFn) {
1040
+ throw new Error(
1041
+ `Flag "${flagName}" was specified to control routing for path group "${pathGroup.group}" in application ${application.name} but not found in provided flag values.`
1042
+ );
1043
+ }
1044
+ }
1045
+ for (const path of pathGroup.paths) {
1046
+ const pattern = pathToRegexp3(path);
1047
+ middlewares.push({
1048
+ src: pattern,
1049
+ fn: getHandler({
1050
+ config,
1051
+ application,
1052
+ flagFn,
1053
+ pattern,
1054
+ production
1055
+ })
1056
+ });
1057
+ }
1058
+ }
1059
+ }
1060
+ }
1061
+ return middlewares;
1062
+ }
1063
+ async function runMicroFrontendsMiddleware(request, flagValues) {
1064
+ const pathname = request.nextUrl.pathname;
1065
+ const middlewares = getMicroFrontendsMiddleware({
1066
+ request,
1067
+ flagValues
1068
+ });
1069
+ for (const mware of middlewares) {
1070
+ if (typeof mware.src === "string" ? pathname === mware.src : mware.src.test(pathname)) {
1071
+ const response = await mware.fn(request);
1072
+ if (response) {
1073
+ return response;
1074
+ }
1075
+ }
1076
+ }
1077
+ }
1078
+ export {
1079
+ getMicroFrontendsMiddleware,
1080
+ runMicroFrontendsMiddleware
1081
+ };
1082
+ //# sourceMappingURL=middleware.js.map