@vercel/microfrontends 1.0.1-canary.0 → 1.0.1-canary.2

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 (44) hide show
  1. package/dist/bin/cli.cjs +143 -44
  2. package/dist/config.cjs +39 -26
  3. package/dist/config.cjs.map +1 -1
  4. package/dist/config.js +39 -26
  5. package/dist/config.js.map +1 -1
  6. package/dist/{sveltekit.cjs → experimental/sveltekit.cjs} +39 -26
  7. package/dist/experimental/sveltekit.cjs.map +1 -0
  8. package/dist/{sveltekit.js → experimental/sveltekit.js} +39 -26
  9. package/dist/experimental/sveltekit.js.map +1 -0
  10. package/dist/experimental/vite.cjs +1758 -0
  11. package/dist/experimental/vite.cjs.map +1 -0
  12. package/dist/experimental/vite.d.ts +29 -0
  13. package/dist/experimental/vite.js +1723 -0
  14. package/dist/experimental/vite.js.map +1 -0
  15. package/dist/microfrontends/server.cjs +39 -26
  16. package/dist/microfrontends/server.cjs.map +1 -1
  17. package/dist/microfrontends/server.js +39 -26
  18. package/dist/microfrontends/server.js.map +1 -1
  19. package/dist/microfrontends.cjs +39 -26
  20. package/dist/microfrontends.cjs.map +1 -1
  21. package/dist/microfrontends.js +39 -26
  22. package/dist/microfrontends.js.map +1 -1
  23. package/dist/next/config.cjs +220 -135
  24. package/dist/next/config.cjs.map +1 -1
  25. package/dist/next/config.d.ts +7 -1
  26. package/dist/next/config.js +220 -135
  27. package/dist/next/config.js.map +1 -1
  28. package/dist/next/middleware.cjs +69 -31
  29. package/dist/next/middleware.cjs.map +1 -1
  30. package/dist/next/middleware.js +69 -31
  31. package/dist/next/middleware.js.map +1 -1
  32. package/dist/next/testing.cjs +39 -26
  33. package/dist/next/testing.cjs.map +1 -1
  34. package/dist/next/testing.d.ts +1 -1
  35. package/dist/next/testing.js +40 -27
  36. package/dist/next/testing.js.map +1 -1
  37. package/dist/utils/mfe-port.cjs +39 -26
  38. package/dist/utils/mfe-port.cjs.map +1 -1
  39. package/dist/utils/mfe-port.js +39 -26
  40. package/dist/utils/mfe-port.js.map +1 -1
  41. package/package.json +22 -9
  42. package/dist/sveltekit.cjs.map +0 -1
  43. package/dist/sveltekit.js.map +0 -1
  44. /package/dist/{sveltekit.d.ts → experimental/sveltekit.d.ts} +0 -0
@@ -0,0 +1,1723 @@
1
+ // src/vite/index.ts
2
+ import { existsSync } from "node:fs";
3
+ import { join as join3 } from "node:path";
4
+ import { cwd } from "node:process";
5
+
6
+ // src/config/microfrontends/server/index.ts
7
+ import fs5 from "node:fs";
8
+ import { dirname as dirname3, join as join2 } from "node:path";
9
+
10
+ // src/config/overrides/constants.ts
11
+ var OVERRIDES_COOKIE_PREFIX = "vercel-micro-frontends-override";
12
+ var OVERRIDES_ENV_COOKIE_PREFIX = `${OVERRIDES_COOKIE_PREFIX}:env:`;
13
+
14
+ // src/config/overrides/is-override-cookie.ts
15
+ function isOverrideCookie(cookie) {
16
+ return Boolean(cookie.name?.startsWith(OVERRIDES_COOKIE_PREFIX));
17
+ }
18
+
19
+ // src/config/overrides/get-override-from-cookie.ts
20
+ function getOverrideFromCookie(cookie) {
21
+ if (!isOverrideCookie(cookie) || !cookie.value)
22
+ return;
23
+ return {
24
+ application: cookie.name.replace(OVERRIDES_ENV_COOKIE_PREFIX, ""),
25
+ host: cookie.value
26
+ };
27
+ }
28
+
29
+ // src/config/overrides/parse-overrides.ts
30
+ function parseOverrides(cookies) {
31
+ const overridesConfig = { applications: {} };
32
+ cookies.forEach((cookie) => {
33
+ const override = getOverrideFromCookie(cookie);
34
+ if (!override)
35
+ return;
36
+ overridesConfig.applications[override.application] = {
37
+ environment: { host: override.host }
38
+ };
39
+ });
40
+ return overridesConfig;
41
+ }
42
+
43
+ // src/config/errors.ts
44
+ var MicrofrontendError = class extends Error {
45
+ constructor(message, opts) {
46
+ super(message, { cause: opts?.cause });
47
+ this.name = "MicrofrontendsError";
48
+ this.source = opts?.source ?? "@vercel/microfrontends";
49
+ this.type = opts?.type ?? "unknown";
50
+ this.subtype = opts?.subtype;
51
+ Error.captureStackTrace(this, MicrofrontendError);
52
+ }
53
+ isKnown() {
54
+ return this.type !== "unknown";
55
+ }
56
+ isUnknown() {
57
+ return !this.isKnown();
58
+ }
59
+ /**
60
+ * Converts an error to a MicrofrontendsError.
61
+ * @param original - The original error to convert.
62
+ * @returns The converted MicrofrontendsError.
63
+ */
64
+ static convert(original, opts) {
65
+ if (opts?.fileName) {
66
+ const err = MicrofrontendError.convertFSError(original, opts.fileName);
67
+ if (err) {
68
+ return err;
69
+ }
70
+ }
71
+ if (original.message.includes(
72
+ "Code generation from strings disallowed for this context"
73
+ )) {
74
+ return new MicrofrontendError(original.message, {
75
+ type: "config",
76
+ subtype: "unsupported_validation_env",
77
+ source: "ajv"
78
+ });
79
+ }
80
+ return new MicrofrontendError(original.message);
81
+ }
82
+ static convertFSError(original, fileName) {
83
+ if (original instanceof Error && "code" in original) {
84
+ if (original.code === "ENOENT") {
85
+ return new MicrofrontendError(`Could not find "${fileName}"`, {
86
+ type: "config",
87
+ subtype: "unable_to_read_file",
88
+ source: "fs"
89
+ });
90
+ }
91
+ if (original.code === "EACCES") {
92
+ return new MicrofrontendError(
93
+ `Permission denied while accessing "${fileName}"`,
94
+ {
95
+ type: "config",
96
+ subtype: "invalid_permissions",
97
+ source: "fs"
98
+ }
99
+ );
100
+ }
101
+ }
102
+ if (original instanceof SyntaxError) {
103
+ return new MicrofrontendError(
104
+ `Failed to parse "${fileName}": Invalid JSON format.`,
105
+ {
106
+ type: "config",
107
+ subtype: "invalid_syntax",
108
+ source: "fs"
109
+ }
110
+ );
111
+ }
112
+ return null;
113
+ }
114
+ /**
115
+ * Handles an unknown error and returns a MicrofrontendsError instance.
116
+ * @param err - The error to handle.
117
+ * @returns A MicrofrontendsError instance.
118
+ */
119
+ static handle(err, opts) {
120
+ if (err instanceof MicrofrontendError) {
121
+ return err;
122
+ }
123
+ if (err instanceof Error) {
124
+ return MicrofrontendError.convert(err, opts);
125
+ }
126
+ if (typeof err === "object" && err !== null) {
127
+ if ("message" in err && typeof err.message === "string") {
128
+ return MicrofrontendError.convert(new Error(err.message), opts);
129
+ }
130
+ }
131
+ return new MicrofrontendError("An unknown error occurred");
132
+ }
133
+ };
134
+
135
+ // src/config/microfrontends-config/utils/get-config-from-env.ts
136
+ function getConfigStringFromEnv() {
137
+ const config = process.env.MFE_CONFIG;
138
+ if (!config) {
139
+ throw new MicrofrontendError(`Missing "MFE_CONFIG" in environment.`, {
140
+ type: "config",
141
+ subtype: "not_found_in_env"
142
+ });
143
+ }
144
+ return config;
145
+ }
146
+
147
+ // src/config/microfrontends-config/isomorphic/index.ts
148
+ import { parse } from "jsonc-parser";
149
+
150
+ // src/config/schema/utils/is-main-config.ts
151
+ function isMainConfig(c) {
152
+ return !("partOf" in c);
153
+ }
154
+
155
+ // src/config/schema/utils/is-default-app.ts
156
+ function isDefaultApp(a) {
157
+ return !("routing" in a);
158
+ }
159
+
160
+ // src/config/microfrontends-config/client/index.ts
161
+ import { pathToRegexp } from "path-to-regexp";
162
+ var MicrofrontendConfigClient = class {
163
+ constructor(config, opts) {
164
+ this.pathCache = {};
165
+ this.serialized = config;
166
+ if (opts?.removeFlaggedPaths) {
167
+ for (const app of Object.values(config.applications)) {
168
+ if (app.routing) {
169
+ app.routing = app.routing.filter((match) => !match.flag);
170
+ }
171
+ }
172
+ }
173
+ this.applications = config.applications;
174
+ }
175
+ /**
176
+ * Create a new `MicrofrontendConfigClient` from a JSON string.
177
+ * Config must be passed in to remain framework agnostic
178
+ */
179
+ static fromEnv(config, opts) {
180
+ if (!config) {
181
+ throw new Error("No microfrontends configuration found");
182
+ }
183
+ return new MicrofrontendConfigClient(
184
+ JSON.parse(config),
185
+ opts
186
+ );
187
+ }
188
+ isEqual(other) {
189
+ return JSON.stringify(this.applications) === JSON.stringify(other.applications);
190
+ }
191
+ getApplicationNameForPath(path5) {
192
+ if (!path5.startsWith("/")) {
193
+ throw new Error(`Path must start with a /`);
194
+ }
195
+ if (this.pathCache[path5]) {
196
+ return this.pathCache[path5];
197
+ }
198
+ const pathname = new URL(path5, "https://example.com").pathname;
199
+ for (const [name, application] of Object.entries(this.applications)) {
200
+ if (application.routing) {
201
+ for (const group of application.routing) {
202
+ for (const childPath of group.paths) {
203
+ const regexp = pathToRegexp(childPath);
204
+ if (regexp.test(pathname)) {
205
+ this.pathCache[path5] = name;
206
+ return name;
207
+ }
208
+ }
209
+ }
210
+ }
211
+ }
212
+ const defaultApplication = Object.entries(this.applications).find(
213
+ ([, application]) => application.default
214
+ );
215
+ if (!defaultApplication) {
216
+ return null;
217
+ }
218
+ this.pathCache[path5] = defaultApplication[0];
219
+ return defaultApplication[0];
220
+ }
221
+ serialize() {
222
+ return this.serialized;
223
+ }
224
+ };
225
+
226
+ // src/config/microfrontends-config/isomorphic/validation.ts
227
+ import { pathToRegexp as pathToRegexp2, parse as parsePathRegexp } from "path-to-regexp";
228
+ var validateConfigPaths = (applicationConfigsById) => {
229
+ if (!applicationConfigsById) {
230
+ return;
231
+ }
232
+ const pathsByApplicationId = /* @__PURE__ */ new Map();
233
+ const errors = [];
234
+ for (const [id, app] of Object.entries(applicationConfigsById)) {
235
+ if (isDefaultApp(app)) {
236
+ continue;
237
+ }
238
+ const childApp = app;
239
+ for (const pathMatch of childApp.routing) {
240
+ for (const path5 of pathMatch.paths) {
241
+ const maybeError = validatePathExpression(path5);
242
+ if (maybeError) {
243
+ errors.push(maybeError);
244
+ } else {
245
+ const existing = pathsByApplicationId.get(path5);
246
+ if (existing) {
247
+ existing.applications.push(id);
248
+ } else {
249
+ pathsByApplicationId.set(path5, {
250
+ applications: [id],
251
+ matcher: pathToRegexp2(path5),
252
+ applicationId: id
253
+ });
254
+ }
255
+ }
256
+ }
257
+ }
258
+ }
259
+ const entries = Array.from(pathsByApplicationId.entries());
260
+ for (const [path5, { applications: ids, matcher, applicationId }] of entries) {
261
+ if (ids.length > 1) {
262
+ errors.push(
263
+ `Duplicate path "${path5}" for applications "${ids.join(", ")}"`
264
+ );
265
+ }
266
+ for (const [
267
+ matchPath,
268
+ { applications: matchIds, applicationId: matchApplicationId }
269
+ ] of entries) {
270
+ if (path5 === matchPath) {
271
+ continue;
272
+ }
273
+ if (applicationId === matchApplicationId) {
274
+ continue;
275
+ }
276
+ if (matcher.test(matchPath)) {
277
+ const source = `"${path5}" of application${ids.length > 0 ? "s" : ""} ${ids.join(", ")}`;
278
+ const destination = `"${matchPath}" of application${matchIds.length > 0 ? "s" : ""} ${matchIds.join(", ")}`;
279
+ errors.push(
280
+ `Overlapping path detected between ${source} and ${destination}`
281
+ );
282
+ }
283
+ }
284
+ }
285
+ if (errors.length) {
286
+ throw new MicrofrontendError(`Invalid paths: ${errors.join(", ")}`, {
287
+ type: "config",
288
+ subtype: "conflicting_paths"
289
+ });
290
+ }
291
+ };
292
+ var PATH_DEFAULT_PATTERN = "[^\\/#\\?]+?";
293
+ function validatePathExpression(path5) {
294
+ try {
295
+ const tokens = parsePathRegexp(path5);
296
+ if (/(?<!\\)\{/.test(path5)) {
297
+ return `Optional paths are not supported: ${path5}`;
298
+ }
299
+ if (/(?<!\\|\()\?/.test(path5)) {
300
+ return `Optional paths are not supported: ${path5}`;
301
+ }
302
+ if (/\/[^/]*(?<!\\):[^/]*(?<!\\):[^/]*/.test(path5)) {
303
+ return `Only one wildcard is allowed per path segment: ${path5}`;
304
+ }
305
+ for (let i = 0; i < tokens.length; i++) {
306
+ const token = tokens[i];
307
+ if (token === void 0) {
308
+ return `token ${i} in ${path5} is undefined, this shouldn't happen`;
309
+ }
310
+ if (typeof token !== "string") {
311
+ if (token.pattern !== PATH_DEFAULT_PATTERN && // Allows (a|b|c) and ((?!a|b|c).*) regex
312
+ // Only limited regex is supported for now, due to performance considerations
313
+ !/^(?<allowed>[\w]+(?:\|[^|()]+)+)$|^\(\?!(?<disallowed>[\w]+(?:\|[^|()]+)+)\)\.\*$/.test(
314
+ token.pattern
315
+ )) {
316
+ return `Path ${path5} cannot use unsupported regular expression wildcard`;
317
+ }
318
+ if (token.modifier && i !== tokens.length - 1) {
319
+ return `Modifier ${token.modifier} is not allowed on wildcard :${token.name} in ${path5}. Modifiers are only allowed in the last path component`;
320
+ }
321
+ }
322
+ }
323
+ } catch (e) {
324
+ const message = e instanceof Error ? e.message : String(e);
325
+ return `Path ${path5} could not be parsed into regexp: ${message}`;
326
+ }
327
+ return void 0;
328
+ }
329
+ var validateAppPaths = (name, app) => {
330
+ for (const group of app.routing) {
331
+ for (const p of group.paths) {
332
+ if (p === "/") {
333
+ continue;
334
+ }
335
+ if (p.endsWith("/")) {
336
+ throw new MicrofrontendError(
337
+ `Invalid path for application "${name}". ${p} must not end with a slash.`,
338
+ { type: "application", subtype: "invalid_path" }
339
+ );
340
+ }
341
+ if (!p.startsWith("/")) {
342
+ throw new MicrofrontendError(
343
+ `Invalid path for application "${name}". ${p} must start with a slash.`,
344
+ { type: "application", subtype: "invalid_path" }
345
+ );
346
+ }
347
+ }
348
+ }
349
+ };
350
+ var validateConfigDefaultApplication = (applicationConfigsById) => {
351
+ if (!applicationConfigsById) {
352
+ return;
353
+ }
354
+ const applicationsWithRouting = Object.entries(applicationConfigsById).filter(
355
+ ([, app]) => !isDefaultApp(app)
356
+ );
357
+ const applicationsWithRoutingNames = applicationsWithRouting.map(
358
+ ([key]) => key
359
+ );
360
+ const numApplications = Object.keys(applicationConfigsById).length;
361
+ const numApplicationsWithRouting = applicationsWithRoutingNames.length;
362
+ const numApplicationsWithoutRouting = numApplications - numApplicationsWithRouting;
363
+ if (numApplicationsWithoutRouting === 0) {
364
+ throw new MicrofrontendError(
365
+ "No default application found. At least one application needs to be the default by omitting routing.",
366
+ { type: "config", subtype: "no_default_application" }
367
+ );
368
+ }
369
+ if (numApplicationsWithoutRouting > 1) {
370
+ throw new MicrofrontendError(
371
+ `Only one application can omit "routing". Found ${applicationsWithRoutingNames.length - Object.keys(applicationConfigsById).length > 1}.`,
372
+ { type: "config", subtype: "multiple_default_applications" }
373
+ );
374
+ }
375
+ };
376
+ var validateDeprecatedFields = (config) => {
377
+ const errors = [];
378
+ if (config.options?.vercel) {
379
+ errors.push(
380
+ `Configuration cannot contain deprecated field 'options.vercel'. Use 'options.disableOverrides' instead.`
381
+ );
382
+ }
383
+ if (config.options?.localProxy) {
384
+ errors.push(
385
+ `Configuration cannot contain deprecated field 'options.localProxy'. Use 'options.localProxyPort' instead.`
386
+ );
387
+ }
388
+ for (const [applicationId, application] of Object.entries(
389
+ config.applications
390
+ )) {
391
+ if (application.vercel) {
392
+ errors.push(
393
+ `Application '${applicationId}' cannot contain deprecated field 'vercel'. Use 'projectId' instead.`
394
+ );
395
+ }
396
+ if (application.production) {
397
+ errors.push(
398
+ `Application '${applicationId}' cannot contain deprecated field 'production'. Use 'development.fallback' instead.`
399
+ );
400
+ }
401
+ if (application.development?.local) {
402
+ errors.push(
403
+ `Application '${applicationId}' cannot contain deprecated field 'development.local'. Use 'developement.localPort' instead.`
404
+ );
405
+ }
406
+ }
407
+ if (errors.length) {
408
+ throw new MicrofrontendError(
409
+ `Microfrontends configuration file errors:
410
+ - ${errors.join("\n- ")}`,
411
+ {
412
+ type: "config",
413
+ subtype: "depcrecated_field"
414
+ }
415
+ );
416
+ }
417
+ };
418
+
419
+ // src/config/microfrontends-config/isomorphic/utils/generate-asset-prefix.ts
420
+ var PREFIX = "vc-ap";
421
+ function generateAssetPrefixFromName({
422
+ name
423
+ }) {
424
+ if (!name) {
425
+ throw new Error("Name is required to generate an asset prefix");
426
+ }
427
+ return `${PREFIX}-${name}`;
428
+ }
429
+
430
+ // src/config/microfrontends-config/isomorphic/utils/generate-port.ts
431
+ function generatePortFromName({
432
+ name,
433
+ minPort = 3e3,
434
+ maxPort = 8e3
435
+ }) {
436
+ if (!name) {
437
+ throw new Error("Name is required to generate a port");
438
+ }
439
+ let hash = 0;
440
+ for (let i = 0; i < name.length; i++) {
441
+ hash = (hash << 5) - hash + name.charCodeAt(i);
442
+ hash |= 0;
443
+ }
444
+ hash = Math.abs(hash);
445
+ const range = maxPort - minPort;
446
+ const port = minPort + hash % range;
447
+ return port;
448
+ }
449
+
450
+ // src/config/microfrontends-config/isomorphic/host.ts
451
+ var Host = class {
452
+ constructor(hostConfig, options) {
453
+ if (typeof hostConfig === "string") {
454
+ ({
455
+ protocol: this.protocol,
456
+ host: this.host,
457
+ port: this.port
458
+ } = Host.parseUrl(hostConfig));
459
+ } else {
460
+ const { protocol = "https", host, port } = hostConfig;
461
+ this.protocol = protocol;
462
+ this.host = host;
463
+ this.port = port;
464
+ }
465
+ this.local = options?.isLocal;
466
+ }
467
+ static parseUrl(url) {
468
+ let hostToParse = url;
469
+ if (!/^https?:\/\//.exec(hostToParse)) {
470
+ hostToParse = `https://${hostToParse}`;
471
+ }
472
+ const parsed = new URL(hostToParse);
473
+ if (!parsed.hostname) {
474
+ throw new Error(Host.getMicrofrontendsError(url, "requires a host"));
475
+ }
476
+ if (parsed.hash) {
477
+ throw new Error(
478
+ Host.getMicrofrontendsError(url, "cannot have a fragment")
479
+ );
480
+ }
481
+ if (parsed.username || parsed.password) {
482
+ throw new Error(
483
+ Host.getMicrofrontendsError(
484
+ url,
485
+ "cannot have authentication credentials (username and/or password)"
486
+ )
487
+ );
488
+ }
489
+ if (parsed.pathname !== "/") {
490
+ throw new Error(Host.getMicrofrontendsError(url, "cannot have a path"));
491
+ }
492
+ if (parsed.search) {
493
+ throw new Error(
494
+ Host.getMicrofrontendsError(url, "cannot have query parameters")
495
+ );
496
+ }
497
+ const protocol = parsed.protocol.slice(0, -1);
498
+ return {
499
+ protocol,
500
+ host: parsed.hostname,
501
+ port: parsed.port ? Number.parseInt(parsed.port) : void 0
502
+ };
503
+ }
504
+ static getMicrofrontendsError(url, message) {
505
+ return `Microfrontends configuration error: the URL ${url} in your microfrontends.json ${message}.`;
506
+ }
507
+ isLocal() {
508
+ return this.local || this.host === "localhost" || this.host === "127.0.0.1";
509
+ }
510
+ toString() {
511
+ const url = this.toUrl();
512
+ return url.toString().replace(/\/$/, "");
513
+ }
514
+ toUrl() {
515
+ const url = `${this.protocol}://${this.host}${this.port ? `:${this.port}` : ""}`;
516
+ return new URL(url);
517
+ }
518
+ };
519
+ var LocalHost = class extends Host {
520
+ constructor({
521
+ appName,
522
+ localPort,
523
+ ...hostConfig
524
+ }) {
525
+ const host = hostConfig.host ?? "localhost";
526
+ const port = localPort ?? hostConfig.port ?? generatePortFromName({ name: appName });
527
+ const protocol = hostConfig.protocol ?? "http";
528
+ super({ protocol, host, port });
529
+ }
530
+ };
531
+
532
+ // src/config/microfrontends-config/isomorphic/application.ts
533
+ var Application = class {
534
+ constructor(name, {
535
+ app,
536
+ overrides,
537
+ isDefault
538
+ }) {
539
+ this.name = name;
540
+ this.development = {
541
+ local: new LocalHost({
542
+ appName: name,
543
+ localPort: app.development?.localPort,
544
+ ...app.development?.local
545
+ }),
546
+ fallback: app.development?.fallback ? new Host(app.development.fallback) : void 0
547
+ };
548
+ if (app.development?.fallback) {
549
+ this.fallback = new Host(app.development.fallback);
550
+ } else if (app.production) {
551
+ this.fallback = new Host(app.production);
552
+ }
553
+ this.projectId = app.projectId ?? app.vercel?.projectId;
554
+ this.overrides = overrides?.environment ? {
555
+ environment: new Host(overrides.environment)
556
+ } : void 0;
557
+ this.default = isDefault ?? false;
558
+ this.serialized = app;
559
+ }
560
+ isDefault() {
561
+ return this.default;
562
+ }
563
+ getAssetPrefix() {
564
+ return generateAssetPrefixFromName({ name: this.name });
565
+ }
566
+ serialize() {
567
+ return this.serialized;
568
+ }
569
+ };
570
+ var DefaultApplication = class extends Application {
571
+ constructor(name, {
572
+ app,
573
+ overrides
574
+ }) {
575
+ super(name, {
576
+ app,
577
+ overrides,
578
+ isDefault: true
579
+ });
580
+ this.default = true;
581
+ const fallbackHost = app.development?.fallback ?? app.production;
582
+ if (fallbackHost === void 0) {
583
+ throw new Error(
584
+ "`app.production` or `app.development.fallback` must be set in the default application in microfrontends.json."
585
+ );
586
+ }
587
+ this.fallback = new Host(fallbackHost);
588
+ if (app.production) {
589
+ this.production = new Host(app.production);
590
+ }
591
+ }
592
+ getAssetPrefix() {
593
+ return "";
594
+ }
595
+ };
596
+ var ChildApplication = class extends Application {
597
+ constructor(name, {
598
+ app,
599
+ overrides
600
+ }) {
601
+ ChildApplication.validate(name, app);
602
+ super(name, {
603
+ app,
604
+ overrides,
605
+ isDefault: false
606
+ });
607
+ this.default = false;
608
+ this.routing = app.routing;
609
+ }
610
+ static validate(name, app) {
611
+ validateAppPaths(name, app);
612
+ }
613
+ };
614
+
615
+ // src/config/microfrontends-config/isomorphic/constants.ts
616
+ var DEFAULT_LOCAL_PROXY_PORT = 3024;
617
+
618
+ // src/config/microfrontends-config/isomorphic/index.ts
619
+ var MicrofrontendConfigIsomorphic = class {
620
+ constructor({
621
+ config,
622
+ overrides,
623
+ meta,
624
+ opts
625
+ }) {
626
+ this.childApplications = {};
627
+ MicrofrontendConfigIsomorphic.validate(config, opts);
628
+ const disableOverrides = config.options?.disableOverrides ?? config.options?.vercel?.disableOverrides ?? false;
629
+ this.overrides = overrides && !disableOverrides ? overrides : void 0;
630
+ this.isMainConfig = isMainConfig(config);
631
+ if (isMainConfig(config)) {
632
+ for (const [appId, appConfig] of Object.entries(config.applications)) {
633
+ const appOverrides = !disableOverrides ? this.overrides?.applications[appId] : void 0;
634
+ if (isDefaultApp(appConfig)) {
635
+ this.defaultApplication = new DefaultApplication(appId, {
636
+ app: appConfig,
637
+ overrides: appOverrides
638
+ });
639
+ } else {
640
+ this.childApplications[appId] = new ChildApplication(appId, {
641
+ app: appConfig,
642
+ overrides: appOverrides
643
+ });
644
+ }
645
+ }
646
+ } else {
647
+ this.partOf = config.partOf;
648
+ const appOverrides = !disableOverrides ? this.overrides?.applications[meta.fromApp] : void 0;
649
+ this.childApplications[meta.fromApp] = new ChildApplication(
650
+ meta.fromApp,
651
+ {
652
+ // we don't know routing because we're not in the main config
653
+ app: { routing: [] },
654
+ overrides: appOverrides
655
+ }
656
+ );
657
+ }
658
+ if (isMainConfig(config) && !this.defaultApplication) {
659
+ throw new MicrofrontendError(
660
+ "Could not find default application in microfrontends configuration",
661
+ {
662
+ type: "application",
663
+ subtype: "not_found"
664
+ }
665
+ );
666
+ }
667
+ this.config = config;
668
+ this.options = config.options;
669
+ this.serialized = {
670
+ config,
671
+ overrides,
672
+ meta
673
+ };
674
+ }
675
+ static validate(config, opts) {
676
+ const skipValidation = opts?.skipValidation ?? [];
677
+ const c = typeof config === "string" ? parse(config) : config;
678
+ if (isMainConfig(c)) {
679
+ if (!skipValidation.includes("paths")) {
680
+ validateConfigPaths(c.applications);
681
+ }
682
+ if (!skipValidation.includes("defaultApplication")) {
683
+ validateConfigDefaultApplication(c.applications);
684
+ }
685
+ if (!skipValidation.includes("deprecatedFields")) {
686
+ validateDeprecatedFields(c);
687
+ }
688
+ }
689
+ return c;
690
+ }
691
+ static fromEnv({
692
+ meta,
693
+ cookies
694
+ }) {
695
+ return new MicrofrontendConfigIsomorphic({
696
+ config: parse(getConfigStringFromEnv()),
697
+ overrides: parseOverrides(cookies ?? []),
698
+ meta
699
+ });
700
+ }
701
+ isOverridesDisabled() {
702
+ return this.options?.vercel?.disableOverrides ?? false;
703
+ }
704
+ getConfig() {
705
+ return this.config;
706
+ }
707
+ getApplicationsByType() {
708
+ return {
709
+ defaultApplication: this.defaultApplication,
710
+ applications: Object.values(this.childApplications)
711
+ };
712
+ }
713
+ getChildApplications() {
714
+ return Object.values(this.childApplications);
715
+ }
716
+ getAllApplications() {
717
+ return [
718
+ this.defaultApplication,
719
+ ...Object.values(this.childApplications)
720
+ ].filter(Boolean);
721
+ }
722
+ getApplication(name) {
723
+ if (this.defaultApplication?.name === name) {
724
+ return this.defaultApplication;
725
+ }
726
+ const app = this.childApplications[name];
727
+ if (!app) {
728
+ throw new MicrofrontendError(
729
+ `Could not find microfrontends configuration for application "${name}"`,
730
+ {
731
+ type: "application",
732
+ subtype: "not_found"
733
+ }
734
+ );
735
+ }
736
+ return app;
737
+ }
738
+ getApplicationByProjectId(projectId) {
739
+ if (this.defaultApplication?.projectId === projectId) {
740
+ return this.defaultApplication;
741
+ }
742
+ return Object.values(this.childApplications).find(
743
+ (app) => app.projectId === projectId
744
+ );
745
+ }
746
+ /**
747
+ * Returns the default application. This can throw if the default application
748
+ * is undefined ( )
749
+ */
750
+ getDefaultApplication() {
751
+ if (!this.defaultApplication) {
752
+ throw new MicrofrontendError(
753
+ "Could not find default application in microfrontends configuration",
754
+ {
755
+ type: "application",
756
+ subtype: "not_found"
757
+ }
758
+ );
759
+ }
760
+ return this.defaultApplication;
761
+ }
762
+ /**
763
+ * Returns the configured port for the local proxy
764
+ */
765
+ getLocalProxyPort() {
766
+ return this.config.options?.localProxyPort ?? this.config.options?.localProxy?.port ?? DEFAULT_LOCAL_PROXY_PORT;
767
+ }
768
+ /**
769
+ * Serializes the class back to the Schema type.
770
+ *
771
+ * NOTE: This is used when writing the config to disk and must always match the input Schema
772
+ */
773
+ toSchemaJson() {
774
+ return this.serialized.config;
775
+ }
776
+ toClientConfig() {
777
+ const applications = Object.fromEntries(
778
+ Object.entries(this.childApplications).map(([name, application]) => [
779
+ name,
780
+ {
781
+ default: false,
782
+ routing: application.routing
783
+ }
784
+ ])
785
+ );
786
+ if (this.defaultApplication) {
787
+ applications[this.defaultApplication.name] = {
788
+ default: true
789
+ };
790
+ }
791
+ return new MicrofrontendConfigClient({
792
+ applications
793
+ });
794
+ }
795
+ serialize() {
796
+ return this.serialized;
797
+ }
798
+ };
799
+
800
+ // src/config/microfrontends-config/isomorphic/child.ts
801
+ var MicrofrontendChildConfig = class extends MicrofrontendConfigIsomorphic {
802
+ constructor({
803
+ config,
804
+ overrides,
805
+ meta
806
+ }) {
807
+ super({ config, overrides, meta });
808
+ this.isMainConfig = false;
809
+ this.partOf = config.partOf;
810
+ }
811
+ };
812
+
813
+ // src/config/microfrontends-config/isomorphic/main.ts
814
+ var MicrofrontendMainConfig = class extends MicrofrontendConfigIsomorphic {
815
+ constructor({
816
+ config,
817
+ overrides,
818
+ meta
819
+ }) {
820
+ super({ config, overrides, meta });
821
+ this.isMainConfig = true;
822
+ const disableOverrides = config.options?.disableOverrides ?? config.options?.vercel?.disableOverrides ?? false;
823
+ let defaultApplication;
824
+ for (const [appId, appConfig] of Object.entries(config.applications)) {
825
+ const appOverrides = !disableOverrides ? this.overrides?.applications[appId] : void 0;
826
+ if (isDefaultApp(appConfig)) {
827
+ defaultApplication = new DefaultApplication(appId, {
828
+ app: appConfig,
829
+ overrides: appOverrides
830
+ });
831
+ } else {
832
+ this.childApplications[appId] = new ChildApplication(appId, {
833
+ app: appConfig,
834
+ overrides: appOverrides
835
+ });
836
+ }
837
+ }
838
+ if (!defaultApplication) {
839
+ throw new MicrofrontendError(
840
+ "Could not find default application in microfrontends configuration",
841
+ {
842
+ type: "application",
843
+ subtype: "not_found"
844
+ }
845
+ );
846
+ }
847
+ this.defaultApplication = defaultApplication;
848
+ }
849
+ };
850
+
851
+ // src/config/microfrontends/isomorphic/index.ts
852
+ var Microfrontends = class {
853
+ constructor({
854
+ config,
855
+ overrides,
856
+ meta
857
+ }) {
858
+ if (isMainConfig(config)) {
859
+ this.config = new MicrofrontendMainConfig({ config, overrides, meta });
860
+ } else {
861
+ this.config = new MicrofrontendChildConfig({ config, overrides, meta });
862
+ }
863
+ }
864
+ isChildConfig() {
865
+ return this.config instanceof MicrofrontendChildConfig;
866
+ }
867
+ static fromEnv({
868
+ cookies,
869
+ meta
870
+ }) {
871
+ const config = MicrofrontendConfigIsomorphic.fromEnv({
872
+ cookies,
873
+ meta
874
+ });
875
+ return new Microfrontends(config.serialize());
876
+ }
877
+ };
878
+
879
+ // src/config/microfrontends/utils/find-repository-root.ts
880
+ import fs from "node:fs";
881
+ import path from "node:path";
882
+ var GIT_DIRECTORY = ".git";
883
+ function findRepositoryRoot(startDir) {
884
+ let currentDir = startDir || process.cwd();
885
+ while (currentDir !== path.parse(currentDir).root) {
886
+ const gitPath = path.join(currentDir, GIT_DIRECTORY);
887
+ if (fs.existsSync(gitPath) && fs.statSync(gitPath).isDirectory()) {
888
+ return currentDir;
889
+ }
890
+ currentDir = path.dirname(currentDir);
891
+ }
892
+ throw new Error(
893
+ "Repository root not found. Specify the root of the repository with the `repository.root` option."
894
+ );
895
+ }
896
+
897
+ // src/config/microfrontends/utils/find-package-path.ts
898
+ import { dirname } from "node:path";
899
+ import { readFileSync } from "node:fs";
900
+ import fg from "fast-glob";
901
+ var configCache = {};
902
+ function findPackagePathWithGlob({
903
+ repositoryRoot,
904
+ name
905
+ }) {
906
+ try {
907
+ const packageJsonPaths = fg.globSync("**/package.json", {
908
+ cwd: repositoryRoot,
909
+ absolute: true,
910
+ onlyFiles: true,
911
+ followSymbolicLinks: false,
912
+ ignore: ["**/node_modules/**", "**/.git/**"]
913
+ });
914
+ const matchingPaths = [];
915
+ for (const packageJsonPath2 of packageJsonPaths) {
916
+ const packageJsonContent = readFileSync(packageJsonPath2, "utf-8");
917
+ const packageJson = JSON.parse(packageJsonContent);
918
+ if (packageJson.name === name) {
919
+ matchingPaths.push(packageJsonPath2);
920
+ }
921
+ }
922
+ if (matchingPaths.length > 1) {
923
+ throw new Error(
924
+ `Found multiple packages with the name "${name}" in the repository: ${matchingPaths.join(", ")}`
925
+ );
926
+ }
927
+ if (matchingPaths.length === 0) {
928
+ throw new Error(
929
+ `Could not find package with the name "${name}" in the repository`
930
+ );
931
+ }
932
+ const [packageJsonPath] = matchingPaths;
933
+ return dirname(packageJsonPath);
934
+ } catch (error) {
935
+ return null;
936
+ }
937
+ }
938
+ function findPackagePath(opts) {
939
+ const cacheKey = `${opts.repositoryRoot}-${opts.name}`;
940
+ if (configCache[cacheKey]) {
941
+ return configCache[cacheKey];
942
+ }
943
+ const result = findPackagePathWithGlob(opts);
944
+ if (!result) {
945
+ throw new Error(
946
+ `Could not find package with the name "${opts.name}" in the repository`
947
+ );
948
+ }
949
+ configCache[cacheKey] = result;
950
+ return result;
951
+ }
952
+
953
+ // src/config/microfrontends/utils/find-default-package.ts
954
+ import { dirname as dirname2 } from "node:path";
955
+ import { readFileSync as readFileSync2 } from "node:fs";
956
+ import { parse as parse2 } from "jsonc-parser";
957
+ import fg2 from "fast-glob";
958
+
959
+ // src/config/constants.ts
960
+ var CONFIGURATION_FILENAMES = [
961
+ "microfrontends.jsonc",
962
+ "microfrontends.json"
963
+ ];
964
+
965
+ // src/config/microfrontends/utils/find-default-package.ts
966
+ var configCache2 = {};
967
+ function findDefaultMicrofrontendsPackages({
968
+ repositoryRoot,
969
+ applicationName
970
+ }) {
971
+ try {
972
+ const microfrontendsJsonPaths = fg2.globSync(
973
+ `**/{${CONFIGURATION_FILENAMES.join(",")}}`,
974
+ {
975
+ cwd: repositoryRoot,
976
+ absolute: true,
977
+ onlyFiles: true,
978
+ followSymbolicLinks: false,
979
+ ignore: ["**/node_modules/**", "**/.git/**"]
980
+ }
981
+ );
982
+ const matchingPaths = [];
983
+ for (const microfrontendsJsonPath of microfrontendsJsonPaths) {
984
+ try {
985
+ const microfrontendsJsonContent = readFileSync2(
986
+ microfrontendsJsonPath,
987
+ "utf-8"
988
+ );
989
+ const microfrontendsJson = parse2(microfrontendsJsonContent);
990
+ if (isMainConfig(microfrontendsJson) && microfrontendsJson.applications[applicationName]) {
991
+ matchingPaths.push(microfrontendsJsonPath);
992
+ }
993
+ } catch (error) {
994
+ }
995
+ }
996
+ if (matchingPaths.length > 1) {
997
+ throw new Error(
998
+ `Found multiple default applications referencing "${applicationName}" in the repository, this is not yet supported.
999
+ ${matchingPaths.join("\n \u2022 ")}`
1000
+ );
1001
+ }
1002
+ if (matchingPaths.length === 0) {
1003
+ throw new Error(
1004
+ `Could not find default application with "applications.${applicationName}"`
1005
+ );
1006
+ }
1007
+ const [packageJsonPath] = matchingPaths;
1008
+ return dirname2(packageJsonPath);
1009
+ } catch (error) {
1010
+ return null;
1011
+ }
1012
+ }
1013
+ function findDefaultMicrofrontendsPackage(opts) {
1014
+ const cacheKey = `${opts.repositoryRoot}-${opts.applicationName}`;
1015
+ if (configCache2[cacheKey]) {
1016
+ return configCache2[cacheKey];
1017
+ }
1018
+ const result = findDefaultMicrofrontendsPackages(opts);
1019
+ if (!result) {
1020
+ throw new Error(
1021
+ "Error trying to resolve the main microfrontends configuration"
1022
+ );
1023
+ }
1024
+ configCache2[cacheKey] = result;
1025
+ return result;
1026
+ }
1027
+
1028
+ // src/config/microfrontends/utils/is-monorepo.ts
1029
+ import fs2 from "node:fs";
1030
+ import path2 from "node:path";
1031
+ function isMonorepo({
1032
+ repositoryRoot
1033
+ }) {
1034
+ try {
1035
+ if (fs2.existsSync(path2.join(repositoryRoot, "pnpm-workspace.yaml"))) {
1036
+ return true;
1037
+ }
1038
+ if (fs2.existsSync(path2.join(repositoryRoot, "vlt-workspaces.json"))) {
1039
+ return true;
1040
+ }
1041
+ const packageJsonPath = path2.join(repositoryRoot, "package.json");
1042
+ if (!fs2.existsSync(packageJsonPath)) {
1043
+ return false;
1044
+ }
1045
+ const packageJson = JSON.parse(
1046
+ fs2.readFileSync(packageJsonPath, "utf-8")
1047
+ );
1048
+ return packageJson.workspaces !== void 0;
1049
+ } catch (error) {
1050
+ console.error("Error determining if repository is a monorepo", error);
1051
+ return false;
1052
+ }
1053
+ }
1054
+
1055
+ // src/config/microfrontends/utils/find-package-root.ts
1056
+ import fs3 from "node:fs";
1057
+ import path3 from "node:path";
1058
+ var PACKAGE_JSON = "package.json";
1059
+ function findPackageRoot(startDir) {
1060
+ let currentDir = startDir || process.cwd();
1061
+ while (currentDir !== path3.parse(currentDir).root) {
1062
+ const pkgJsonPath = path3.join(currentDir, PACKAGE_JSON);
1063
+ if (fs3.existsSync(pkgJsonPath)) {
1064
+ return currentDir;
1065
+ }
1066
+ currentDir = path3.dirname(currentDir);
1067
+ }
1068
+ throw new Error(
1069
+ "Package root not found. Specify the root of the package with the `package.root` option."
1070
+ );
1071
+ }
1072
+
1073
+ // src/config/microfrontends/utils/find-config.ts
1074
+ import fs4 from "node:fs";
1075
+ import { join } from "node:path";
1076
+ function findConfig({ dir }) {
1077
+ for (const filename of CONFIGURATION_FILENAMES) {
1078
+ const maybeConfig = join(dir, filename);
1079
+ if (fs4.existsSync(maybeConfig)) {
1080
+ return maybeConfig;
1081
+ }
1082
+ }
1083
+ return null;
1084
+ }
1085
+
1086
+ // src/config/microfrontends/server/utils/get-output-file-path.ts
1087
+ import path4 from "node:path";
1088
+
1089
+ // src/config/microfrontends/server/constants.ts
1090
+ var MFE_CONFIG_DEFAULT_FILE_PATH = "microfrontends";
1091
+ var MFE_CONFIG_DEFAULT_FILE_NAME = "microfrontends.json";
1092
+
1093
+ // src/config/microfrontends/server/utils/get-output-file-path.ts
1094
+ function getOutputFilePath() {
1095
+ return path4.join(MFE_CONFIG_DEFAULT_FILE_PATH, MFE_CONFIG_DEFAULT_FILE_NAME);
1096
+ }
1097
+
1098
+ // src/config/microfrontends/server/validation.ts
1099
+ import { parse as parse3 } from "jsonc-parser";
1100
+ import { Ajv } from "ajv";
1101
+
1102
+ // schema/schema.json
1103
+ var schema_default = {
1104
+ $schema: "http://json-schema.org/draft-07/schema#",
1105
+ $ref: "#/definitions/Config",
1106
+ definitions: {
1107
+ Config: {
1108
+ anyOf: [
1109
+ {
1110
+ $ref: "#/definitions/MainConfig"
1111
+ },
1112
+ {
1113
+ $ref: "#/definitions/ChildConfig"
1114
+ }
1115
+ ]
1116
+ },
1117
+ MainConfig: {
1118
+ type: "object",
1119
+ properties: {
1120
+ $schema: {
1121
+ type: "string"
1122
+ },
1123
+ version: {
1124
+ type: "string",
1125
+ const: "1"
1126
+ },
1127
+ options: {
1128
+ $ref: "#/definitions/Options"
1129
+ },
1130
+ applications: {
1131
+ $ref: "#/definitions/ApplicationRouting",
1132
+ description: "Mapping of application names to the routes that they host. Only needs to be defined in the application that owns the primary microfrontend domain"
1133
+ }
1134
+ },
1135
+ required: [
1136
+ "applications"
1137
+ ],
1138
+ additionalProperties: false
1139
+ },
1140
+ Options: {
1141
+ type: "object",
1142
+ properties: {
1143
+ vercel: {
1144
+ $ref: "#/definitions/VercelOptions",
1145
+ description: "Microfrontends wide options for Vercel.",
1146
+ deprecated: "This is being replaced by the `disableOverrides` field below."
1147
+ },
1148
+ disableOverrides: {
1149
+ type: "boolean",
1150
+ description: "If you want to disable the overrides for the site. For example, if you are managing rewrites between applications externally, you may wish to disable the overrides on the toolbar as they will have no effect."
1151
+ },
1152
+ localProxy: {
1153
+ $ref: "#/definitions/LocalProxyOptions",
1154
+ description: "Options for local proxy.",
1155
+ deprecated: "This is being replaced by the `localProxyPort` field below."
1156
+ },
1157
+ localProxyPort: {
1158
+ type: "number",
1159
+ description: "The port number used by the local proxy server.\n\nThe default is `3024`."
1160
+ }
1161
+ },
1162
+ additionalProperties: false
1163
+ },
1164
+ VercelOptions: {
1165
+ type: "object",
1166
+ properties: {
1167
+ disableOverrides: {
1168
+ type: "boolean",
1169
+ description: "If you want to disable the overrides for the site. For example, if you are managing rewrites between applications externally, you may wish to disable the overrides on the toolbar as they will have no effect."
1170
+ }
1171
+ },
1172
+ additionalProperties: false
1173
+ },
1174
+ LocalProxyOptions: {
1175
+ type: "object",
1176
+ properties: {
1177
+ port: {
1178
+ type: "number",
1179
+ description: "The port number used by the local proxy server.\n\nThe default is `3024`."
1180
+ }
1181
+ },
1182
+ additionalProperties: false
1183
+ },
1184
+ ApplicationRouting: {
1185
+ type: "object",
1186
+ additionalProperties: {
1187
+ $ref: "#/definitions/Application"
1188
+ },
1189
+ propertyNames: {
1190
+ description: "The unique identifier for a Microfrontend Application. Must match the `name` field of the application's `package.json`."
1191
+ }
1192
+ },
1193
+ Application: {
1194
+ anyOf: [
1195
+ {
1196
+ $ref: "#/definitions/DefaultApplication"
1197
+ },
1198
+ {
1199
+ $ref: "#/definitions/ChildApplication"
1200
+ }
1201
+ ]
1202
+ },
1203
+ DefaultApplication: {
1204
+ type: "object",
1205
+ properties: {
1206
+ vercel: {
1207
+ $ref: "#/definitions/Vercel",
1208
+ deprecated: "This is being replaced by the `projectId` field below."
1209
+ },
1210
+ projectId: {
1211
+ type: "string",
1212
+ description: "Vercel project ID"
1213
+ },
1214
+ production: {
1215
+ $ref: "#/definitions/HostConfig",
1216
+ deprecated: "This is a duplicate of the `development.fallback` field and this will be removed soon."
1217
+ },
1218
+ development: {
1219
+ $ref: "#/definitions/Development"
1220
+ }
1221
+ },
1222
+ additionalProperties: false
1223
+ },
1224
+ Vercel: {
1225
+ type: "object",
1226
+ properties: {
1227
+ projectId: {
1228
+ type: "string",
1229
+ description: "Vercel project ID"
1230
+ }
1231
+ },
1232
+ required: [
1233
+ "projectId"
1234
+ ],
1235
+ additionalProperties: false
1236
+ },
1237
+ HostConfig: {
1238
+ type: "object",
1239
+ properties: {
1240
+ protocol: {
1241
+ type: "string",
1242
+ enum: [
1243
+ "http",
1244
+ "https"
1245
+ ],
1246
+ description: "The protocol to be used for the connection.\n- `http`: Hypertext Transfer Protocol (HTTP).\n- `https`: Secure Hypertext Transfer Protocol (HTTPS).\n\n*"
1247
+ },
1248
+ host: {
1249
+ type: "string",
1250
+ description: "The hostname or IP address of the server. This can be a domain name (e.g., `example.com`) or an IP address (e.g., `192.168.1.1`)."
1251
+ },
1252
+ port: {
1253
+ type: "number",
1254
+ description: "The port number to be used for the connection. Common values include `80` for HTTP and `443` for HTTPS."
1255
+ }
1256
+ },
1257
+ required: [
1258
+ "host"
1259
+ ],
1260
+ additionalProperties: false
1261
+ },
1262
+ Development: {
1263
+ type: "object",
1264
+ properties: {
1265
+ local: {
1266
+ $ref: "#/definitions/LocalHostConfig",
1267
+ deprecated: "This is being replaced by the `localPort` field below."
1268
+ },
1269
+ localPort: {
1270
+ type: "number",
1271
+ description: "The local port number that this application runs on when it is running locally. Common values include `80` for HTTP and `443` for HTTPS."
1272
+ },
1273
+ fallback: {
1274
+ anyOf: [
1275
+ {
1276
+ $ref: "#/definitions/HostConfig"
1277
+ },
1278
+ {
1279
+ type: "string"
1280
+ }
1281
+ ],
1282
+ description: "Fallback for local development, could be a host config that points to any environment. If this is not provided, or the application is not running - requests to the application in local development will error.\n\nIf passing a string, include the protocol (optional), host (required) and port (optional). For example: `https://this.ismyhost:8080`. If omitted, the protocol defaults to HTTPS. If omitted, the port defaults to `80` for HTTP and `443` for HTTPS."
1283
+ },
1284
+ task: {
1285
+ type: "string",
1286
+ description: "Optional task to run when starting the development server. Should reference a script in the package.json of the application."
1287
+ }
1288
+ },
1289
+ additionalProperties: false
1290
+ },
1291
+ LocalHostConfig: {
1292
+ type: "object",
1293
+ additionalProperties: false,
1294
+ properties: {
1295
+ host: {
1296
+ type: "string",
1297
+ description: "The hostname or IP address of the server. This can be a domain name (e.g., `example.com`) or an IP address (e.g., `192.168.1.1`)."
1298
+ },
1299
+ protocol: {
1300
+ type: "string",
1301
+ enum: [
1302
+ "http",
1303
+ "https"
1304
+ ],
1305
+ description: "The protocol to be used for the connection.\n- `http`: Hypertext Transfer Protocol (HTTP).\n- `https`: Secure Hypertext Transfer Protocol (HTTPS).\n\n*"
1306
+ },
1307
+ port: {
1308
+ type: "number",
1309
+ description: "The port number to be used for the connection. Common values include `80` for HTTP and `443` for HTTPS."
1310
+ }
1311
+ }
1312
+ },
1313
+ ChildApplication: {
1314
+ type: "object",
1315
+ properties: {
1316
+ vercel: {
1317
+ $ref: "#/definitions/Vercel",
1318
+ deprecated: "This is being replaced by the `projectId` field below."
1319
+ },
1320
+ projectId: {
1321
+ type: "string",
1322
+ description: "Vercel project ID"
1323
+ },
1324
+ production: {
1325
+ $ref: "#/definitions/HostConfig",
1326
+ deprecated: "This is a duplicate of the `development.fallback` field and this will be removed soon."
1327
+ },
1328
+ development: {
1329
+ $ref: "#/definitions/Development"
1330
+ },
1331
+ routing: {
1332
+ $ref: "#/definitions/Routing",
1333
+ description: "Groups of path expressions that are routed to this application."
1334
+ }
1335
+ },
1336
+ required: [
1337
+ "routing"
1338
+ ],
1339
+ additionalProperties: false
1340
+ },
1341
+ Routing: {
1342
+ type: "array",
1343
+ items: {
1344
+ $ref: "#/definitions/PathGroup"
1345
+ }
1346
+ },
1347
+ PathGroup: {
1348
+ type: "object",
1349
+ properties: {
1350
+ group: {
1351
+ type: "string",
1352
+ description: "Optional group name for the paths"
1353
+ },
1354
+ flag: {
1355
+ type: "string",
1356
+ description: "flag name that can be used to enable/disable all paths in the group"
1357
+ },
1358
+ paths: {
1359
+ type: "array",
1360
+ items: {
1361
+ type: "string"
1362
+ }
1363
+ }
1364
+ },
1365
+ required: [
1366
+ "paths"
1367
+ ],
1368
+ additionalProperties: false
1369
+ },
1370
+ ChildConfig: {
1371
+ type: "object",
1372
+ properties: {
1373
+ $schema: {
1374
+ type: "string"
1375
+ },
1376
+ version: {
1377
+ type: "string",
1378
+ const: "1"
1379
+ },
1380
+ options: {
1381
+ $ref: "#/definitions/Options"
1382
+ },
1383
+ partOf: {
1384
+ type: "string",
1385
+ description: "Applications that only serve a subset of the microfrontend routes only need to reference the name of the primary application that owns the full microfrontends configuration."
1386
+ }
1387
+ },
1388
+ required: [
1389
+ "partOf"
1390
+ ],
1391
+ additionalProperties: false
1392
+ }
1393
+ }
1394
+ };
1395
+
1396
+ // src/config/schema/utils/load.ts
1397
+ var SCHEMA = schema_default;
1398
+
1399
+ // src/config/microfrontends/server/validation.ts
1400
+ function filterAjvErrors(errors) {
1401
+ if (!errors) {
1402
+ return [];
1403
+ }
1404
+ return errors.filter((error) => {
1405
+ return error.keyword === "additionalProperties" || error.keyword === "required";
1406
+ });
1407
+ }
1408
+ function validateSchema(configString) {
1409
+ const parsedConfig = parse3(configString);
1410
+ const ajv = new Ajv();
1411
+ const validate = ajv.compile(SCHEMA);
1412
+ const isValid = validate(parsedConfig);
1413
+ if (!isValid) {
1414
+ throw new MicrofrontendError(
1415
+ `Invalid microfrontends config:
1416
+ - ${ajv.errorsText(filterAjvErrors(validate.errors), { separator: "\n - " })}
1417
+
1418
+ See https://openapi.vercel.sh/microfrontends.json for the schema.`,
1419
+ { type: "config", subtype: "does_not_match_schema" }
1420
+ );
1421
+ }
1422
+ return parsedConfig;
1423
+ }
1424
+
1425
+ // src/config/microfrontends/server/index.ts
1426
+ var MicrofrontendsServer = class extends Microfrontends {
1427
+ /**
1428
+ * Writes the configuration to a file.
1429
+ */
1430
+ writeConfig(opts = {
1431
+ pretty: true
1432
+ }) {
1433
+ const outputPath = getOutputFilePath();
1434
+ fs5.mkdirSync(dirname3(outputPath), { recursive: true });
1435
+ fs5.writeFileSync(
1436
+ outputPath,
1437
+ JSON.stringify(
1438
+ this.config.toSchemaJson(),
1439
+ null,
1440
+ opts.pretty ?? true ? 2 : void 0
1441
+ )
1442
+ );
1443
+ }
1444
+ // --------- Static Methods ---------
1445
+ /**
1446
+ * Generates a MicrofrontendsServer instance from an unknown object.
1447
+ */
1448
+ static fromUnknown({
1449
+ config,
1450
+ cookies,
1451
+ meta
1452
+ }) {
1453
+ const overrides = cookies ? parseOverrides(cookies) : void 0;
1454
+ if (typeof config === "string") {
1455
+ return new MicrofrontendsServer({
1456
+ config: MicrofrontendsServer.validate(config),
1457
+ overrides,
1458
+ meta
1459
+ });
1460
+ }
1461
+ if (typeof config === "object") {
1462
+ return new MicrofrontendsServer({
1463
+ config,
1464
+ overrides,
1465
+ meta
1466
+ });
1467
+ }
1468
+ throw new MicrofrontendError(
1469
+ "Invalid config: must be a string or an object",
1470
+ { type: "config", subtype: "does_not_match_schema" }
1471
+ );
1472
+ }
1473
+ /**
1474
+ * Generates a MicrofrontendsServer instance from the environment.
1475
+ * Uses additional validation that is only available when in a node runtime
1476
+ */
1477
+ static fromEnv({
1478
+ cookies,
1479
+ meta
1480
+ }) {
1481
+ return new MicrofrontendsServer({
1482
+ config: MicrofrontendsServer.validate(getConfigStringFromEnv()),
1483
+ overrides: parseOverrides(cookies),
1484
+ meta
1485
+ });
1486
+ }
1487
+ /**
1488
+ * Validates the configuration against the JSON schema
1489
+ */
1490
+ static validate(config) {
1491
+ if (typeof config === "string") {
1492
+ const c = validateSchema(config);
1493
+ return c;
1494
+ }
1495
+ return config;
1496
+ }
1497
+ /**
1498
+ * Looks up the configuration by inferring the package root and looking for a microfrontends config file. If a file is not found,
1499
+ * it will look for a package in the repository with a microfrontends file that contains the current application
1500
+ * and use that configuration.
1501
+ *
1502
+ * This can return either a Child or Main configuration.
1503
+ */
1504
+ static infer({
1505
+ directory,
1506
+ filePath,
1507
+ meta,
1508
+ cookies,
1509
+ options
1510
+ } = {}) {
1511
+ if (filePath && meta) {
1512
+ return MicrofrontendsServer.fromFile({
1513
+ filePath,
1514
+ cookies,
1515
+ meta,
1516
+ options
1517
+ });
1518
+ }
1519
+ try {
1520
+ const packageRoot = findPackageRoot(directory);
1521
+ const packageJsonPath = join2(packageRoot, "package.json");
1522
+ const packageJson = JSON.parse(
1523
+ fs5.readFileSync(packageJsonPath, "utf-8")
1524
+ );
1525
+ if (!packageJson.name) {
1526
+ throw new Error(`No name found in package.json at ${packageJsonPath}`);
1527
+ }
1528
+ const configMeta = meta ?? { fromApp: packageJson.name };
1529
+ const maybeConfig = findConfig({ dir: packageRoot });
1530
+ if (maybeConfig) {
1531
+ return MicrofrontendsServer.fromFile({
1532
+ filePath: maybeConfig,
1533
+ cookies,
1534
+ meta: configMeta,
1535
+ options
1536
+ });
1537
+ }
1538
+ const repositoryRoot = findRepositoryRoot();
1539
+ const isMonorepo2 = isMonorepo({ repositoryRoot });
1540
+ if (isMonorepo2) {
1541
+ const defaultPackage = findDefaultMicrofrontendsPackage({
1542
+ repositoryRoot,
1543
+ applicationName: packageJson.name
1544
+ });
1545
+ const maybeConfigFromDefault = findConfig({ dir: defaultPackage });
1546
+ if (maybeConfigFromDefault) {
1547
+ return MicrofrontendsServer.fromFile({
1548
+ filePath: maybeConfigFromDefault,
1549
+ cookies,
1550
+ meta: configMeta,
1551
+ options
1552
+ });
1553
+ }
1554
+ }
1555
+ throw new Error("Unable to infer");
1556
+ } catch (e) {
1557
+ throw new MicrofrontendError(
1558
+ "Unable to locate and parse microfrontends configuration",
1559
+ { cause: e, type: "config", subtype: "inference_failed" }
1560
+ );
1561
+ }
1562
+ }
1563
+ /*
1564
+ * Generates a MicrofrontendsServer instance from a file.
1565
+ */
1566
+ static fromFile({
1567
+ filePath,
1568
+ cookies,
1569
+ meta,
1570
+ options
1571
+ }) {
1572
+ try {
1573
+ const configJson = fs5.readFileSync(filePath, "utf-8");
1574
+ const config = MicrofrontendsServer.validate(configJson);
1575
+ if (!isMainConfig(config) && options?.resolveMainConfig) {
1576
+ const repositoryRoot = findRepositoryRoot();
1577
+ const isMonorepo2 = isMonorepo({ repositoryRoot });
1578
+ if (isMonorepo2) {
1579
+ const packagePath = findPackagePath({
1580
+ repositoryRoot,
1581
+ name: config.partOf
1582
+ });
1583
+ if (!packagePath) {
1584
+ throw new MicrofrontendError(
1585
+ `Could not find default application "${config.partOf}" in the repository`,
1586
+ { type: "config", subtype: "not_found" }
1587
+ );
1588
+ }
1589
+ const maybeConfig = findConfig({ dir: packagePath });
1590
+ if (!maybeConfig) {
1591
+ throw new MicrofrontendError(
1592
+ `Could not find microfrontends configuration in ${packagePath}`,
1593
+ { type: "config", subtype: "not_found" }
1594
+ );
1595
+ }
1596
+ return MicrofrontendsServer.fromMainConfigFile({
1597
+ filePath: maybeConfig,
1598
+ overrides: cookies ? parseOverrides(cookies) : void 0
1599
+ });
1600
+ }
1601
+ }
1602
+ return new MicrofrontendsServer({
1603
+ config,
1604
+ overrides: cookies ? parseOverrides(cookies) : void 0,
1605
+ meta
1606
+ });
1607
+ } catch (e) {
1608
+ throw MicrofrontendError.handle(e, {
1609
+ fileName: filePath
1610
+ });
1611
+ }
1612
+ }
1613
+ /*
1614
+ * Generates a MicrofrontendMainConfig instance from a file.
1615
+ */
1616
+ static fromMainConfigFile({
1617
+ filePath,
1618
+ overrides
1619
+ }) {
1620
+ try {
1621
+ const config = fs5.readFileSync(filePath, "utf-8");
1622
+ const validatedConfig = MicrofrontendsServer.validate(config);
1623
+ if (!isMainConfig(validatedConfig)) {
1624
+ throw new MicrofrontendError(
1625
+ `${filePath} is not a main microfrontend config`,
1626
+ {
1627
+ type: "config",
1628
+ subtype: "invalid_main_path"
1629
+ }
1630
+ );
1631
+ }
1632
+ const [defaultApplication] = Object.entries(validatedConfig.applications).filter(([, app]) => isDefaultApp(app)).map(([name]) => name);
1633
+ if (!defaultApplication) {
1634
+ throw new MicrofrontendError(
1635
+ "No default application found. At least one application needs to be the default by omitting routing.",
1636
+ { type: "config", subtype: "no_default_application" }
1637
+ );
1638
+ }
1639
+ return new MicrofrontendsServer({
1640
+ config: validatedConfig,
1641
+ overrides,
1642
+ meta: { fromApp: defaultApplication }
1643
+ });
1644
+ } catch (e) {
1645
+ throw MicrofrontendError.handle(e, {
1646
+ fileName: filePath
1647
+ });
1648
+ }
1649
+ }
1650
+ };
1651
+
1652
+ // src/config/microfrontends/utils/get-application-context.ts
1653
+ import fs6 from "node:fs";
1654
+ function getApplicationContext(opts) {
1655
+ if (opts?.appName) {
1656
+ return { name: opts.appName };
1657
+ }
1658
+ try {
1659
+ const packageJsonString = fs6.readFileSync("./package.json", "utf-8");
1660
+ const packageJson = JSON.parse(packageJsonString);
1661
+ if (!packageJson.name) {
1662
+ throw new MicrofrontendError(
1663
+ `package.json file missing required field "name"`,
1664
+ {
1665
+ type: "packageJson",
1666
+ subtype: "missing_field_name",
1667
+ source: "@vercel/microfrontends/next"
1668
+ }
1669
+ );
1670
+ }
1671
+ return { name: packageJson.name };
1672
+ } catch (err) {
1673
+ throw MicrofrontendError.handle(err, {
1674
+ fileName: "package.json"
1675
+ });
1676
+ }
1677
+ }
1678
+
1679
+ // src/vite/index.ts
1680
+ function microfrontends(opts) {
1681
+ const { name: fromApp } = getApplicationContext();
1682
+ const microfrontendsObj = MicrofrontendsServer.infer({
1683
+ meta: {
1684
+ fromApp
1685
+ }
1686
+ });
1687
+ const app = microfrontendsObj.config.getApplication(fromApp);
1688
+ const additionalConfigOptions = {};
1689
+ if (!app.isDefault()) {
1690
+ if (opts?.basePath) {
1691
+ additionalConfigOptions.base = `/${opts.basePath}`;
1692
+ } else {
1693
+ const isSvelteKit = existsSync(join3(cwd(), "svelte.config.js"));
1694
+ if (!isSvelteKit) {
1695
+ additionalConfigOptions.experimental = {
1696
+ renderBuiltUrl(filename, { type }) {
1697
+ if (type === "asset") {
1698
+ return `/${app.getAssetPrefix()}/${filename}`;
1699
+ }
1700
+ }
1701
+ };
1702
+ }
1703
+ }
1704
+ }
1705
+ return {
1706
+ name: "vite-plugin-vercel-microfrontends",
1707
+ config: () => {
1708
+ return {
1709
+ ...additionalConfigOptions,
1710
+ define: {
1711
+ "import.meta.env.MFE_CURRENT_APPLICATION": JSON.stringify(app.name),
1712
+ "import.meta.env.MFE_CONFIG": JSON.stringify(
1713
+ microfrontendsObj.config.getConfig()
1714
+ )
1715
+ }
1716
+ };
1717
+ }
1718
+ };
1719
+ }
1720
+ export {
1721
+ microfrontends
1722
+ };
1723
+ //# sourceMappingURL=vite.js.map