UNPKG

@vercel/microfrontends

Version:

Defines configuration and utilities for microfrontends development

1,524 lines (1,482 loc) 98.5 kB
#!/usr/bin/env node "use strict"; var __create = Object.create; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( // If the importer is in node compatibility mode or this is not an ESM // file that has been converted to a CommonJS file using a Babel- // compatible transform (i.e. "__esModule" has not been set), then set // "default" to the CommonJS "module.exports" for node compatibility. isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod )); // src/bin/index.ts var import_commander = require("commander"); var import_env = require("@next/env"); // package.json var package_default = { name: "@vercel/microfrontends", version: "2.2.1", private: false, description: "Defines configuration and utilities for microfrontends development", keywords: [ "microfrontends", "micro-frontends", "micro frontends", "microservices", "Vercel", "Next.js", "React" ], homepage: "https://vercel.com/docs/microfrontends", repository: { type: "git", url: "https://github.com/vercel/microfrontends.git", directory: "packages/microfrontends" }, sideEffects: false, type: "module", exports: { "./schema.json": "./schema/schema.json", "./validation": { import: "./dist/validation.js", require: "./dist/validation.cjs" }, "./config": { import: "./dist/config.js", require: "./dist/config.cjs" }, "./experimental/sveltekit": { import: "./dist/experimental/sveltekit.js", require: "./dist/experimental/sveltekit.cjs" }, "./experimental/vite": { import: "./dist/experimental/vite.js", require: "./dist/experimental/vite.cjs" }, "./overrides": { import: "./dist/overrides.js", require: "./dist/overrides.cjs" }, "./microfrontends/server": { import: "./dist/microfrontends/server.js", require: "./dist/microfrontends/server.cjs" }, "./microfrontends/utils": { import: "./dist/microfrontends/utils.js", require: "./dist/microfrontends/utils.cjs" }, "./schema": { import: "./dist/schema.js", require: "./dist/schema.cjs" }, "./next/config": { import: "./dist/next/config.js", require: "./dist/next/config.cjs" }, "./next/middleware": { import: "./dist/next/middleware.js", require: "./dist/next/middleware.cjs" }, "./next/testing": { import: "./dist/next/testing.js", require: "./dist/next/testing.cjs" }, "./next/client": { import: "./dist/next/client.js", require: "./dist/next/client.cjs" }, "./utils/mfe-port": { import: "./dist/utils/mfe-port.js", require: "./dist/utils/mfe-port.cjs" } }, typesVersions: { "*": { validation: [ "./dist/validation.d.ts" ], config: [ "./dist/config.d.ts" ], "experimental/sveltekit": [ "./dist/experimental/sveltekit.d.ts" ], "experimental/vite": [ "./dist/experimental/vite.d.ts" ], overrides: [ "./dist/overrides.d.ts" ], "microfrontends/server": [ "./dist/microfrontends/server.d.ts" ], "microfrontends/utils": [ "./dist/microfrontends/utils.d.ts" ], schema: [ "./dist/schema.d.ts" ], "next/config": [ "./dist/next/config.d.ts" ], "next/middleware": [ "./dist/next/middleware.d.ts" ], "next/testing": [ "./dist/next/testing.d.ts" ], "next/client": [ "./dist/next/client.d.ts" ], "utils/mfe-port": [ "./dist/utils/mfe-port.d.ts" ] } }, bin: { microfrontends: "./cli/index.cjs" }, files: [ "dist", "schema", "CHANGELOG.md" ], scripts: { build: "tsup", postbuild: "pnpm generate:exports", "generate:exports": "tsx scripts/generate-exports/index.ts", "generate:schema": "tsx scripts/generate-json-schema.ts", lint: "eslint .", "lint-fix": "eslint . --fix", prepublishOnly: "pnpm build && pnpm generate:exports && pnpm generate:schema", proxy: "tsx src/proxy/index.ts", test: "cross-env TZ=UTC jest", typecheck: "tsc --noEmit" }, dependencies: { "@next/env": "15.5.4", "@types/md5": "^2.3.5", ajv: "^8.17.1", commander: "^12.1.0", cookie: "1.0.2", "fast-glob": "^3.3.2", "http-proxy": "^1.18.1", "jsonc-parser": "^3.3.1", md5: "^2.3.0", nanoid: "^3.3.9", "path-to-regexp": "6.2.1", semver: "^7.7.2" }, devDependencies: { "@edge-runtime/jest-environment": "^4.0.0", "@edge-runtime/types": "^3.0.2", "@sveltejs/kit": "2.17.2", "@testing-library/react": "^15.0.7", "@types/cookie": "0.5.1", "@types/http-proxy": "^1.17.15", "@types/jest": "^29.2.0", "@types/json-schema": "^7.0.15", "@types/node": "20.11.30", "@types/react": "18.3.1", "@types/react-dom": "18.3.0", "@types/semver": "^7.7.0", "eslint-config-custom": "workspace:*", jest: "^29.7.0", "jest-environment-jsdom": "29.2.2", next: "15.5.4", react: "19.0.0", "react-dom": "19.0.0", "ts-config": "workspace:*", "ts-json-schema-generator": "^1.1.2", "ts-node": "~10.9.2", tsup: "^6.6.2", tsx: "^4.6.2", typescript: "5.7.3", vite: "5.4.11", webpack: "5" }, peerDependencies: { "@sveltejs/kit": ">=1", "@vercel/analytics": ">=1.5.0", "@vercel/speed-insights": ">=1.2.0", next: ">=13", react: ">=17.0.0", "react-dom": ">=17.0.0", vite: ">=5" }, peerDependenciesMeta: { "@sveltejs/kit": { optional: true }, "@vercel/analytics": { optional: true }, "@vercel/speed-insights": { optional: true }, next: { optional: true }, react: { optional: true }, "react-dom": { optional: true }, vite: { optional: true } } }; // src/bin/local-proxy.ts var http = __toESM(require("http"), 1); var https = __toESM(require("https"), 1); var import_node_url = require("url"); var import_cookie = require("cookie"); var import_path_to_regexp3 = require("path-to-regexp"); var import_http_proxy = __toESM(require("http-proxy"), 1); // src/config/microfrontends-config/isomorphic/index.ts var import_jsonc_parser = require("jsonc-parser"); // src/config/errors.ts var MicrofrontendError = class extends Error { constructor(message, opts) { super(message, { cause: opts?.cause }); this.name = "MicrofrontendsError"; this.source = opts?.source ?? "@vercel/microfrontends"; this.type = opts?.type ?? "unknown"; this.subtype = opts?.subtype; Error.captureStackTrace(this, MicrofrontendError); } isKnown() { return this.type !== "unknown"; } isUnknown() { return !this.isKnown(); } /** * Converts an error to a MicrofrontendsError. * @param original - The original error to convert. * @returns The converted MicrofrontendsError. */ static convert(original, opts) { if (opts?.fileName) { const err = MicrofrontendError.convertFSError(original, opts.fileName); if (err) { return err; } } if (original.message.includes( "Code generation from strings disallowed for this context" )) { return new MicrofrontendError(original.message, { type: "config", subtype: "unsupported_validation_env", source: "ajv" }); } return new MicrofrontendError(original.message); } static convertFSError(original, fileName) { if (original instanceof Error && "code" in original) { if (original.code === "ENOENT") { return new MicrofrontendError(`Could not find "${fileName}"`, { type: "config", subtype: "unable_to_read_file", source: "fs" }); } if (original.code === "EACCES") { return new MicrofrontendError( `Permission denied while accessing "${fileName}"`, { type: "config", subtype: "invalid_permissions", source: "fs" } ); } } if (original instanceof SyntaxError) { return new MicrofrontendError( `Failed to parse "${fileName}": Invalid JSON format.`, { type: "config", subtype: "invalid_syntax", source: "fs" } ); } return null; } /** * Handles an unknown error and returns a MicrofrontendsError instance. * @param err - The error to handle. * @returns A MicrofrontendsError instance. */ static handle(err, opts) { if (err instanceof MicrofrontendError) { return err; } if (err instanceof Error) { return MicrofrontendError.convert(err, opts); } if (typeof err === "object" && err !== null) { if ("message" in err && typeof err.message === "string") { return MicrofrontendError.convert(new Error(err.message), opts); } } return new MicrofrontendError("An unknown error occurred"); } }; // src/config/microfrontends-config/utils/get-config-from-env.ts function getConfigStringFromEnv() { const config = process.env.MFE_CONFIG; if (!config) { throw new MicrofrontendError(`Missing "MFE_CONFIG" in environment.`, { type: "config", subtype: "not_found_in_env" }); } return config; } // src/config/schema/utils/is-default-app.ts function isDefaultApp(a) { return !("routing" in a); } // src/config/overrides/constants.ts var OVERRIDES_COOKIE_PREFIX = "vercel-micro-frontends-override"; var OVERRIDES_ENV_COOKIE_PREFIX = `${OVERRIDES_COOKIE_PREFIX}:env:`; // src/config/overrides/is-override-cookie.ts function isOverrideCookie(cookie) { return Boolean(cookie.name?.startsWith(OVERRIDES_COOKIE_PREFIX)); } // src/config/overrides/get-override-from-cookie.ts function getOverrideFromCookie(cookie) { if (!isOverrideCookie(cookie) || !cookie.value) return; return { application: cookie.name.replace(OVERRIDES_ENV_COOKIE_PREFIX, ""), host: cookie.value }; } // src/config/overrides/parse-overrides.ts function parseOverrides(cookies) { const overridesConfig = { applications: {} }; cookies.forEach((cookie) => { const override = getOverrideFromCookie(cookie); if (!override) return; overridesConfig.applications[override.application] = { environment: { host: override.host } }; }); return overridesConfig; } // src/config/overrides/get-app-env-override-cookie-name.ts function getAppEnvOverrideCookieName(application) { return `${OVERRIDES_ENV_COOKIE_PREFIX}${application}`; } // src/config/microfrontends-config/client/index.ts var import_path_to_regexp = require("path-to-regexp"); var regexpCache = /* @__PURE__ */ new Map(); var getRegexp = (path7) => { const existing = regexpCache.get(path7); if (existing) { return existing; } const regexp = (0, import_path_to_regexp.pathToRegexp)(path7); regexpCache.set(path7, regexp); return regexp; }; var MicrofrontendConfigClient = class { constructor(config, opts) { this.pathCache = {}; this.hasFlaggedPaths = config.hasFlaggedPaths ?? false; for (const app of Object.values(config.applications)) { if (app.routing) { if (app.routing.some((match) => match.flag)) { this.hasFlaggedPaths = true; } const newRouting = []; const pathsWithoutFlags = []; for (const group of app.routing) { if (group.flag) { if (opts?.removeFlaggedPaths) { continue; } if (group.group) { delete group.group; } newRouting.push(group); } else { pathsWithoutFlags.push(...group.paths); } } if (pathsWithoutFlags.length > 0) { newRouting.push({ paths: pathsWithoutFlags }); } app.routing = newRouting; } } this.serialized = config; if (this.hasFlaggedPaths) { this.serialized.hasFlaggedPaths = this.hasFlaggedPaths; } this.applications = config.applications; } /** * Create a new `MicrofrontendConfigClient` from a JSON string. * Config must be passed in to remain framework agnostic */ static fromEnv(config) { if (!config) { throw new Error( "Could not construct MicrofrontendConfigClient: configuration is empty or undefined. Did you set up your application with `withMicrofrontends`? Is the local proxy running and this application is being accessed via the proxy port? See https://vercel.com/docs/microfrontends/local-development#setting-up-microfrontends-proxy" ); } return new MicrofrontendConfigClient(JSON.parse(config)); } isEqual(other) { return this === other || JSON.stringify(this.applications) === JSON.stringify(other.applications); } getApplicationNameForPath(path7) { if (!path7.startsWith("/")) { throw new Error(`Path must start with a /`); } if (this.pathCache[path7]) { return this.pathCache[path7]; } const pathname = new URL(path7, "https://example.com").pathname; for (const [name, application] of Object.entries(this.applications)) { if (application.routing) { for (const group of application.routing) { for (const childPath of group.paths) { const regexp = getRegexp(childPath); if (regexp.test(pathname)) { this.pathCache[path7] = name; return name; } } } } } const defaultApplication = Object.entries(this.applications).find( ([, application]) => application.default ); if (!defaultApplication) { return null; } this.pathCache[path7] = defaultApplication[0]; return defaultApplication[0]; } serialize() { return this.serialized; } }; // src/config/microfrontends-config/isomorphic/validation.ts var import_path_to_regexp2 = require("path-to-regexp"); var LIST_FORMATTER = new Intl.ListFormat("en", { style: "long", type: "conjunction" }); var VALID_ASSET_PREFIX_REGEXP = /^[a-z](?:[a-z0-9-]*[a-z0-9])?$/; var validateConfigPaths = (applicationConfigsById) => { if (!applicationConfigsById) { return; } const pathsByApplicationId = /* @__PURE__ */ new Map(); const errors = []; for (const [id, app] of Object.entries(applicationConfigsById)) { if (isDefaultApp(app)) { continue; } for (const pathMatch of app.routing) { for (const path7 of pathMatch.paths) { const maybeError = validatePathExpression(path7); if (maybeError) { errors.push(maybeError); } else { const existing = pathsByApplicationId.get(path7); if (existing) { existing.applications.push(id); } else { pathsByApplicationId.set(path7, { applications: [id], matcher: (0, import_path_to_regexp2.pathToRegexp)(path7), applicationId: id }); } } } } } const entries = Array.from(pathsByApplicationId.entries()); for (const [path7, { applications: ids, matcher, applicationId }] of entries) { if (ids.length > 1) { errors.push( `Duplicate path "${path7}" for applications "${ids.join(", ")}"` ); } for (const [ matchPath, { applications: matchIds, applicationId: matchApplicationId } ] of entries) { if (path7 === matchPath) { continue; } if (applicationId === matchApplicationId) { continue; } if (matcher.test(matchPath)) { const source = `"${path7}" of application${ids.length > 0 ? "s" : ""} ${ids.join(", ")}`; const destination = `"${matchPath}" of application${matchIds.length > 0 ? "s" : ""} ${matchIds.join(", ")}`; errors.push( `Overlapping path detected between ${source} and ${destination}` ); } } } if (errors.length) { throw new MicrofrontendError( `Invalid paths: ${errors.join(", ")}. See supported paths in the documentation https://vercel.com/docs/microfrontends/path-routing#supported-path-expressions.`, { type: "config", subtype: "conflicting_paths" } ); } }; var PATH_DEFAULT_PATTERN = "[^\\/#\\?]+?"; function validatePathExpression(path7) { try { const tokens = (0, import_path_to_regexp2.parse)(path7); if (/(?<!\\)\{/.test(path7)) { return `Optional paths are not supported: ${path7}`; } if (/(?<!\\|\()\?/.test(path7)) { return `Optional paths are not supported: ${path7}`; } if (/\/[^/]*(?<!\\):[^/]*(?<!\\):[^/]*/.test(path7)) { return `Only one wildcard is allowed per path segment: ${path7}`; } for (let i = 0; i < tokens.length; i++) { const token = tokens[i]; if (token === void 0) { return `token ${i} in ${path7} is undefined, this shouldn't happen`; } if (typeof token !== "string") { if (!token.name) { return `Only named wildcards are allowed: ${path7} (hint: add ":path" to the wildcard)`; } if (token.pattern !== PATH_DEFAULT_PATTERN && // Allows (a|b|c) and ((?!a|b|c).*) regex // Only limited regex is supported for now, due to performance considerations // Allows all letters, numbers, and hyphens. Other characters must be escaped. !/^(?<allowed>[\w-~]+(?:\|[^:|()]+)+)$|^\(\?!(?<disallowed>[\w-~]+(?:\|[^:|()]+)*)\)\.\*$/.test( token.pattern.replace(/\\./g, "") )) { return `Path ${path7} cannot use unsupported regular expression wildcard. If the path includes special characters, they must be escaped with backslash (e.g. '\\(')`; } if (token.modifier && i !== tokens.length - 1) { return `Modifier ${token.modifier} is not allowed on wildcard :${token.name} in ${path7}. Modifiers are only allowed in the last path component`; } } } } catch (e) { const message = e instanceof Error ? e.message : String(e); return `Path ${path7} could not be parsed into regexp: ${message}`; } return void 0; } var validateAppPaths = (name, app) => { for (const group of app.routing) { for (const p of group.paths) { if (p === "/") { continue; } if (p.endsWith("/")) { throw new MicrofrontendError( `Invalid path for application "${name}". ${p} must not end with a slash.`, { type: "application", subtype: "invalid_path" } ); } if (!p.startsWith("/")) { throw new MicrofrontendError( `Invalid path for application "${name}". ${p} must start with a slash.`, { type: "application", subtype: "invalid_path" } ); } } } if (app.assetPrefix) { if (!VALID_ASSET_PREFIX_REGEXP.test(app.assetPrefix)) { throw new MicrofrontendError( `Invalid asset prefix for application "${name}". ${app.assetPrefix} must start with a lowercase letter and contain only lowercase letters, numbers, and hyphens.`, { type: "application", subtype: "invalid_asset_prefix" } ); } if (app.assetPrefix !== `vc-ap-${name}` && !app.routing.some( (group) => group.paths.includes(`/${app.assetPrefix}/:path*`) && !group.flag )) { throw new MicrofrontendError( `When \`assetPrefix\` is specified, \`/${app.assetPrefix}/:path*\` must be added the routing paths for the application. Changing the asset prefix is not a forwards and backwards compatible change, and the custom asset prefix should be added to \`paths\` and deployed before setting the \`assetPrefix\` field.`, { type: "application", subtype: "invalid_asset_prefix" } ); } } }; var validateConfigDefaultApplication = (applicationConfigsById) => { if (!applicationConfigsById) { return; } const applicationsWithoutRouting = Object.entries( applicationConfigsById ).filter(([, app]) => isDefaultApp(app)); const numApplicationsWithoutRouting = applicationsWithoutRouting.reduce( (acc) => { return acc + 1; }, 0 ); if (numApplicationsWithoutRouting === 0) { throw new MicrofrontendError( "No default application found. At least one application needs to be the default by omitting routing.", { type: "config", subtype: "no_default_application" } ); } if (numApplicationsWithoutRouting > 1) { const applicationNamesMissingRouting = applicationsWithoutRouting.map( ([name]) => name ); throw new MicrofrontendError( `All applications except for the default app must contain the "routing" field. Applications that are missing routing: ${LIST_FORMATTER.format(applicationNamesMissingRouting)}.`, { type: "config", subtype: "multiple_default_applications" } ); } }; // src/config/microfrontends-config/isomorphic/utils/hash-application-name.ts var import_md5 = __toESM(require("md5"), 1); function hashApplicationName(name) { if (!name) { throw new Error("Application name is required to generate hash"); } return (0, import_md5.default)(name).substring(0, 6).padStart(6, "0"); } // src/config/microfrontends-config/isomorphic/utils/generate-asset-prefix.ts var PREFIX = "vc-ap"; function generateAssetPrefixFromName({ name }) { if (!name) { throw new Error("Name is required to generate an asset prefix"); } return `${PREFIX}-${hashApplicationName(name)}`; } // src/config/microfrontends-config/isomorphic/utils/generate-port.ts function generatePortFromName({ name, minPort = 3e3, maxPort = 8e3 }) { if (!name) { throw new Error("Name is required to generate a port"); } let hash = 0; for (let i = 0; i < name.length; i++) { hash = (hash << 5) - hash + name.charCodeAt(i); hash |= 0; } hash = Math.abs(hash); const range = maxPort - minPort; const port = minPort + hash % range; return port; } // src/config/microfrontends-config/isomorphic/host.ts var Host = class { constructor(hostConfig, options) { if (typeof hostConfig === "string") { ({ protocol: this.protocol, host: this.host, port: this.port } = Host.parseUrl(hostConfig)); } else { const { protocol = "https", host, port } = hostConfig; this.protocol = protocol; this.host = host; this.port = port; } this.local = options?.isLocal; } static parseUrl(url, defaultProtocol = "https") { let hostToParse = url; if (!/^https?:\/\//.exec(hostToParse)) { hostToParse = `${defaultProtocol}://${hostToParse}`; } const parsed = new URL(hostToParse); if (!parsed.hostname) { throw new Error(Host.getMicrofrontendsError(url, "requires a host")); } if (parsed.hash) { throw new Error( Host.getMicrofrontendsError(url, "cannot have a fragment") ); } if (parsed.username || parsed.password) { throw new Error( Host.getMicrofrontendsError( url, "cannot have authentication credentials (username and/or password)" ) ); } if (parsed.pathname !== "/") { throw new Error(Host.getMicrofrontendsError(url, "cannot have a path")); } if (parsed.search) { throw new Error( Host.getMicrofrontendsError(url, "cannot have query parameters") ); } const protocol = parsed.protocol.slice(0, -1); return { protocol, host: parsed.hostname, port: parsed.port ? Number.parseInt(parsed.port) : void 0 }; } static getMicrofrontendsError(url, message) { return `Microfrontends configuration error: the URL ${url} in your microfrontends.json ${message}.`; } isLocal() { return this.local || this.host === "localhost" || this.host === "127.0.0.1"; } toString() { const url = this.toUrl(); return url.toString().replace(/\/$/, ""); } toUrl() { const url = `${this.protocol}://${this.host}${this.port ? `:${this.port}` : ""}`; return new URL(url); } }; var LocalHost = class extends Host { constructor({ appName, local }) { let protocol; let host; let port; if (typeof local === "number") { port = local; } else if (typeof local === "string") { if (/^\d+$/.test(local)) { port = Number.parseInt(local); } else { const parsed = Host.parseUrl(local, "http"); protocol = parsed.protocol; host = parsed.host; port = parsed.port; } } else if (local) { protocol = local.protocol; host = local.host; port = local.port; } super({ protocol: protocol ?? "http", host: host ?? "localhost", port: port ?? generatePortFromName({ name: appName }) }); } }; // src/config/microfrontends-config/isomorphic/utils/generate-automation-bypass-env-var-name.ts function generateAutomationBypassEnvVarName({ name }) { return `AUTOMATION_BYPASS_${name.toUpperCase().replace(/[^a-zA-Z0-9]/g, "_")}`; } // src/config/microfrontends-config/isomorphic/application.ts var Application = class { constructor(name, { app, overrides, isDefault }) { this.name = name; this.development = { local: new LocalHost({ appName: name, local: app.development?.local }), fallback: app.development?.fallback ? new Host(app.development.fallback) : void 0 }; if (app.development?.fallback) { this.fallback = new Host(app.development.fallback); } this.packageName = app.packageName; this.overrides = overrides?.environment ? { environment: new Host(overrides.environment) } : void 0; this.default = isDefault ?? false; this.serialized = app; } isDefault() { return this.default; } getAssetPrefix() { const generatedAssetPrefix = generateAssetPrefixFromName({ name: this.name }); if ("assetPrefix" in this.serialized) { return this.serialized.assetPrefix ?? generatedAssetPrefix; } return generatedAssetPrefix; } getAutomationBypassEnvVarName() { return generateAutomationBypassEnvVarName({ name: this.name }); } serialize() { return this.serialized; } }; var DefaultApplication = class extends Application { constructor(name, { app, overrides }) { super(name, { app, overrides, isDefault: true }); this.default = true; this.fallback = new Host(app.development.fallback); } getAssetPrefix() { return ""; } }; var ChildApplication = class extends Application { constructor(name, { app, overrides }) { ChildApplication.validate(name, app); super(name, { app, overrides, isDefault: false }); this.default = false; this.routing = app.routing; } static validate(name, app) { validateAppPaths(name, app); } }; // src/config/microfrontends-config/isomorphic/constants.ts var DEFAULT_LOCAL_PROXY_PORT = 3024; // src/config/microfrontends-config/isomorphic/index.ts var MicrofrontendConfigIsomorphic = class { constructor({ config, overrides }) { this.childApplications = {}; MicrofrontendConfigIsomorphic.validate(config); const disableOverrides = config.options?.disableOverrides ?? false; this.overrides = overrides && !disableOverrides ? overrides : void 0; let defaultApplication; for (const [appId, appConfig] of Object.entries(config.applications)) { const appOverrides = !disableOverrides ? this.overrides?.applications[appId] : void 0; if (isDefaultApp(appConfig)) { defaultApplication = new DefaultApplication(appId, { app: appConfig, overrides: appOverrides }); } else { this.childApplications[appId] = new ChildApplication(appId, { app: appConfig, overrides: appOverrides }); } } if (!defaultApplication) { throw new MicrofrontendError( "Could not find default application in microfrontends configuration", { type: "application", subtype: "not_found" } ); } this.defaultApplication = defaultApplication; this.config = config; this.options = config.options; this.serialized = { config, overrides }; } static validate(config) { const c = typeof config === "string" ? (0, import_jsonc_parser.parse)(config) : config; validateConfigPaths(c.applications); validateConfigDefaultApplication(c.applications); return c; } static fromEnv({ cookies }) { return new MicrofrontendConfigIsomorphic({ config: (0, import_jsonc_parser.parse)(getConfigStringFromEnv()), overrides: parseOverrides(cookies ?? []) }); } isOverridesDisabled() { return this.options?.disableOverrides ?? false; } getConfig() { return this.config; } getApplicationsByType() { return { defaultApplication: this.defaultApplication, applications: Object.values(this.childApplications) }; } getChildApplications() { return Object.values(this.childApplications); } getAllApplications() { return [ this.defaultApplication, ...Object.values(this.childApplications) ].filter(Boolean); } getApplication(name) { if (this.defaultApplication.name === name || this.defaultApplication.packageName === name) { return this.defaultApplication; } const app = this.childApplications[name] || Object.values(this.childApplications).find( (child) => child.packageName === name ); if (!app) { throw new MicrofrontendError( `Could not find microfrontends configuration for application "${name}". If the name in package.json differs from your Vercel Project name, set the \`packageName\` field for the application in \`microfrontends.json\` to ensure that the configuration can be found locally.`, { type: "application", subtype: "not_found" } ); } return app; } hasApplication(name) { try { this.getApplication(name); return true; } catch { return false; } } getApplicationByProjectName(projectName) { if (this.defaultApplication.name === projectName) { return this.defaultApplication; } return Object.values(this.childApplications).find( (app) => app.name === projectName ); } /** * Returns the default application. */ getDefaultApplication() { return this.defaultApplication; } /** * Returns the configured port for the local proxy */ getLocalProxyPort() { return this.config.options?.localProxyPort ?? DEFAULT_LOCAL_PROXY_PORT; } toClientConfig(options) { const applications = Object.fromEntries( Object.entries(this.childApplications).map(([name, application]) => [ hashApplicationName(name), { default: false, routing: application.routing } ]) ); applications[hashApplicationName(this.defaultApplication.name)] = { default: true }; return new MicrofrontendConfigClient( { applications }, { removeFlaggedPaths: options?.removeFlaggedPaths } ); } /** * Serializes the class back to the Schema type. * * NOTE: This is used when writing the config to disk and must always match the input Schema */ toSchemaJson() { return this.serialized.config; } serialize() { return this.serialized; } }; // src/config/microfrontends/server/index.ts var import_node_fs7 = __toESM(require("fs"), 1); var import_node_path8 = require("path"); // src/config/microfrontends/utils/find-repository-root.ts var import_node_fs = __toESM(require("fs"), 1); var import_node_path = __toESM(require("path"), 1); var GIT_DIRECTORY = ".git"; function hasGitDirectory(dir) { const gitPath = import_node_path.default.join(dir, GIT_DIRECTORY); return import_node_fs.default.existsSync(gitPath) && import_node_fs.default.statSync(gitPath).isDirectory(); } function hasPnpmWorkspaces(dir) { return import_node_fs.default.existsSync(import_node_path.default.join(dir, "pnpm-workspace.yaml")); } function hasPackageJson(dir) { return import_node_fs.default.existsSync(import_node_path.default.join(dir, "package.json")); } function findRepositoryRoot(startDir) { if (process.env.NX_WORKSPACE_ROOT) { return process.env.NX_WORKSPACE_ROOT; } let currentDir = startDir || process.cwd(); let lastPackageJsonDir = null; while (currentDir !== import_node_path.default.parse(currentDir).root) { if (hasGitDirectory(currentDir) || hasPnpmWorkspaces(currentDir)) { return currentDir; } if (hasPackageJson(currentDir)) { lastPackageJsonDir = currentDir; } currentDir = import_node_path.default.dirname(currentDir); } if (lastPackageJsonDir) { return lastPackageJsonDir; } throw new Error( `Could not find the root of the repository for ${startDir}. Please ensure that the directory is part of a Git repository. If you suspect that this should work, please file an issue to the Vercel team.` ); } // src/config/microfrontends/utils/infer-microfrontends-location.ts var import_node_path2 = require("path"); var import_node_fs2 = require("fs"); var import_jsonc_parser2 = require("jsonc-parser"); var import_fast_glob = __toESM(require("fast-glob"), 1); // src/bin/logger.ts function debug(...args) { if (process.env.MFE_DEBUG) { console.log(...args); } } function info(...args) { console.log(...args); } function warn(...args) { console.warn(...args); } function error(...args) { console.error(...args); } var logger = { debug, info, warn, error }; // src/config/microfrontends/utils/get-config-file-name.ts var DEFAULT_CONFIGURATION_FILENAMES = [ "microfrontends.json", "microfrontends.jsonc" ]; function getPossibleConfigurationFilenames({ customConfigFilename }) { if (customConfigFilename) { if (!customConfigFilename.endsWith(".json") && !customConfigFilename.endsWith(".jsonc")) { throw new Error( `Found VC_MICROFRONTENDS_CONFIG_FILE_NAME but the name is invalid. Received: ${customConfigFilename}. The file name must end with '.json' or '.jsonc'. It's also possible for the env var to include the path, eg microfrontends-dev.json or /path/to/microfrontends-dev.json.` ); } return Array.from( /* @__PURE__ */ new Set([customConfigFilename, ...DEFAULT_CONFIGURATION_FILENAMES]) ); } return DEFAULT_CONFIGURATION_FILENAMES; } // src/config/microfrontends/utils/infer-microfrontends-location.ts var configCache = {}; function findPackageWithMicrofrontendsConfig({ repositoryRoot, applicationContext, customConfigFilename }) { const applicationName = applicationContext.name; logger.debug( "[MFE Config] Searching repository for configs containing application:", applicationName ); try { const microfrontendsJsonPaths = import_fast_glob.default.globSync( `**/{${getPossibleConfigurationFilenames({ customConfigFilename }).join(",")}}`, { cwd: repositoryRoot, absolute: true, onlyFiles: true, followSymbolicLinks: false, ignore: ["**/node_modules/**", "**/.git/**"] } ); logger.debug( "[MFE Config] Found", microfrontendsJsonPaths.length, "config file(s) in repository" ); const matchingPaths = []; for (const microfrontendsJsonPath of microfrontendsJsonPaths) { try { const microfrontendsJsonContent = (0, import_node_fs2.readFileSync)( microfrontendsJsonPath, "utf-8" ); const microfrontendsJson = (0, import_jsonc_parser2.parse)(microfrontendsJsonContent); if (microfrontendsJson.applications[applicationName]) { logger.debug( "[MFE Config] Found application in config:", microfrontendsJsonPath ); matchingPaths.push(microfrontendsJsonPath); } else { for (const [_, app] of Object.entries( microfrontendsJson.applications )) { if (app.packageName === applicationName) { logger.debug( "[MFE Config] Found application via packageName in config:", microfrontendsJsonPath ); matchingPaths.push(microfrontendsJsonPath); } } } } catch (error2) { } } logger.debug( "[MFE Config] Total matching config files:", matchingPaths.length ); if (matchingPaths.length > 1) { throw new MicrofrontendError( `Found multiple \`microfrontends.json\` files in the repository referencing the application "${applicationName}", but only one is allowed. ${matchingPaths.join("\n \u2022 ")}`, { type: "config", subtype: "inference_failed" } ); } if (matchingPaths.length === 0) { let additionalErrorMessage = ""; if (microfrontendsJsonPaths.length > 0) { if (!applicationContext.projectName) { additionalErrorMessage = ` If the name in package.json (${applicationContext.packageJsonName}) differs from your Vercel Project name, set the \`packageName\` field for the application in \`microfrontends.json\` to ensure that the configuration can be found locally.`; } else { additionalErrorMessage = ` Names of applications in \`microfrontends.json\` must match the Vercel Project name (${applicationContext.projectName}).`; } } throw new MicrofrontendError( `Could not find a \`microfrontends.json\` file in the repository that contains the "${applicationName}" application.${additionalErrorMessage} If your Vercel Microfrontends configuration is not in this repository, you can use the Vercel CLI to pull the Vercel Microfrontends configuration using the "vercel microfrontends pull" command, or you can specify the path manually using the VC_MICROFRONTENDS_CONFIG environment variable. If your Vercel Microfrontends configuration has a custom name, ensure the VC_MICROFRONTENDS_CONFIG_FILE_NAME environment variable is set, you can pull the vercel project environment variables using the "vercel env pull" command. If you suspect this is thrown in error, please reach out to the Vercel team.`, { type: "config", subtype: "inference_failed" } ); } const [packageJsonPath] = matchingPaths; return (0, import_node_path2.dirname)(packageJsonPath); } catch (error2) { if (error2 instanceof MicrofrontendError) { throw error2; } return null; } } function inferMicrofrontendsLocation(opts) { const cacheKey = `${opts.repositoryRoot}-${opts.applicationContext.name}${opts.customConfigFilename ? `-${opts.customConfigFilename}` : ""}`; if (configCache[cacheKey]) { return configCache[cacheKey]; } const result = findPackageWithMicrofrontendsConfig(opts); if (!result) { throw new MicrofrontendError( `Could not infer the location of the \`microfrontends.json\` file for application "${opts.applicationContext.name}" starting in directory "${opts.repositoryRoot}".`, { type: "config", subtype: "inference_failed" } ); } configCache[cacheKey] = result; return result; } // src/config/microfrontends/utils/is-monorepo.ts var import_node_fs3 = __toESM(require("fs"), 1); var import_node_path3 = __toESM(require("path"), 1); function isMonorepo({ repositoryRoot }) { try { if (import_node_fs3.default.existsSync(import_node_path3.default.join(repositoryRoot, "pnpm-workspace.yaml"))) { return true; } if (import_node_fs3.default.existsSync(import_node_path3.default.join(repositoryRoot, "vlt-workspaces.json"))) { return true; } if (process.env.NX_WORKSPACE_ROOT === import_node_path3.default.resolve(repositoryRoot)) { return true; } const packageJsonPath = import_node_path3.default.join(repositoryRoot, "package.json"); if (!import_node_fs3.default.existsSync(packageJsonPath)) { return false; } const packageJson = JSON.parse( import_node_fs3.default.readFileSync(packageJsonPath, "utf-8") ); return packageJson.workspaces !== void 0; } catch (error2) { logger.error("Error determining if repository is a monorepo", error2); return false; } } // src/config/microfrontends/utils/find-package-root.ts var import_node_fs4 = __toESM(require("fs"), 1); var import_node_path4 = __toESM(require("path"), 1); var PACKAGE_JSON = "package.json"; function findPackageRoot(startDir) { let currentDir = startDir || process.cwd(); while (currentDir !== import_node_path4.default.parse(currentDir).root) { const pkgJsonPath = import_node_path4.default.join(currentDir, PACKAGE_JSON); if (import_node_fs4.default.existsSync(pkgJsonPath)) { return currentDir; } currentDir = import_node_path4.default.dirname(currentDir); } throw new Error( `The root of the package that contains the \`package.json\` file for the \`${startDir}\` directory could not be found.` ); } // src/config/microfrontends/utils/find-config.ts var import_node_fs5 = __toESM(require("fs"), 1); var import_node_path5 = require("path"); function findConfig({ dir, customConfigFilename }) { for (const filename of getPossibleConfigurationFilenames({ customConfigFilename })) { const maybeConfig = (0, import_node_path5.join)(dir, filename); if (import_node_fs5.default.existsSync(maybeConfig)) { return maybeConfig; } } return null; } // src/config/microfrontends/utils/get-application-context.ts var import_node_fs6 = __toESM(require("fs"), 1); var import_node_path6 = __toESM(require("path"), 1); function getApplicationContext(opts) { if (opts?.appName) { logger.debug("[MFE Config] Application name from appName parameter:", opts.appName); return { name: opts.appName }; } if (process.env.VERCEL_PROJECT_NAME) { logger.debug("[MFE Config] Application name from VERCEL_PROJECT_NAME:", process.env.VERCEL_PROJECT_NAME); return { name: process.env.VERCEL_PROJECT_NAME, projectName: process.env.VERCEL_PROJECT_NAME }; } if (process.env.NX_TASK_TARGET_PROJECT) { logger.debug("[MFE Config] Application name from NX_TASK_TARGET_PROJECT:", process.env.NX_TASK_TARGET_PROJECT); return { name: process.env.NX_TASK_TARGET_PROJECT, packageJsonName: process.env.NX_TASK_TARGET_PROJECT }; } try { const vercelProjectJsonPath = import_node_fs6.default.readFileSync( import_node_path6.default.join(opts?.packageRoot || ".", ".vercel", "project.json"), "utf-8" ); const projectJson = JSON.parse(vercelProjectJsonPath); if (projectJson.projectName) { logger.debug("[MFE Config] Application name from .vercel/project.json:", projectJson.projectName); return { name: projectJson.projectName, projectName: projectJson.projectName }; } } catch (_) { } try { const packageJsonString = import_node_fs6.default.readFileSync( import_node_path6.default.join(opts?.packageRoot || ".", "package.json"), "utf-8" ); const packageJson = JSON.parse(packageJsonString); if (!packageJson.name) { throw new MicrofrontendError( `package.json file missing required field "name"`, { type: "packageJson", subtype: "missing_field_name", source: "@vercel/microfrontends/next" } ); } logger.debug("[MFE Config] Application name from package.json:", packageJson.name); return { name: packageJson.name, packageJsonName: packageJson.name }; } catch (err) { throw MicrofrontendError.handle(err, { fileName: "package.json" }); } } // src/config/microfrontends/server/utils/get-output-file-path.ts var import_node_path7 = __toESM(require("path"), 1); // src/config/microfrontends/server/constants.ts var MFE_CONFIG_DEFAULT_FILE_PATH = "microfrontends"; var MFE_CONFIG_DEFAULT_FILE_NAME = "microfrontends.json"; // src/config/microfrontends/server/utils/get-output-file-path.ts function getOutputFilePath() { return import_node_path7.default.join(MFE_CONFIG_DEFAULT_FILE_PATH, MFE_CONFIG_DEFAULT_FILE_NAME); } // src/config/microfrontends/server/validation.ts var import_jsonc_parser3 = require("jsonc-parser"); var import_ajv = require("ajv"); // schema/schema.json var schema_default = { $schema: "http://json-schema.org/draft-07/schema#", $ref: "#/definitions/Config", definitions: { Config: { type: "object", properties: { $schema: { type: "string", description: "See https://openapi.vercel.sh/microfrontends.json." }, version: { type: "string", const: "1", description: "The version of the microfrontends config schema." }, applications: { $ref: "#/definitions/ApplicationRouting", description: "Mapping of Vercel project names to their microfrontend configurations." }, options: { $ref: "#/definitions/Options", description: "Optional configuration options for the microfrontend." } }, required: [ "applications" ], additionalProperties: false, description: "The microfrontends configuration schema. See https://vercel.com/docs/microfrontends/configuration." }, ApplicationRouting: { type: "object", additionalProperties: { $ref: "#/definitions/Application" }, propertyNames: { description: "The Vercel project name of the microfrontend application.\n\nNote: If this name does not also match the name `name` from the `package.json`, set `packageName` with the name used in `package.json`.\n\nSee https://vercel.com/docs/microfrontends/configuration#application-naming." }, description: "Mapping of Vercel project names to their microfrontend configurations." }, Application: { anyOf: [ { $ref: "#/definitions/DefaultApplication" }, { $ref: "#/definitions/ChildApplication" } ], description: "The configuration for a microfrontend application. There must always be one default application." }, DefaultApplication: { type: "object", properties: { packageName: { type: "string", description: "The name used to run the application, e.g. the `name` field in the `package.json`.\n\nThis is used by the local proxy to map the application config to the locally running app.\n\nThis is only necessary when the application name does not match the `name` used in `package.json`.\n\nSee https://vercel.com/docs/microfrontends/configuration#application-naming." }, development: { $ref: "#/definitions/DefaultDevelopment", description: "Development configuration for the default application." } }, required: [ "development" ], additionalProperties: false }, DefaultDevelopment: { type: "object", properties: { local: { type: [ "number", "string" ], description: "A local port number or host that this application runs on when it is running locally. If passing a string, include the protocol (optional), host (required) and port (optional).\n\nExamples of valid values: 8080, my.localhost.me, my.localhost.me:8080, https://my.localhost.me, https://my.localhost.me:8080.\n\nThe default value is http://localhost:<port> where port is a stable, unique port number (based on the application name).\n\nSee https://vercel.com/docs/microfrontends/local-development." }, task: { type: "string", description: 'The task to run when starting the development server. Should reference a script in the package.json of the application.\n\nThe default value is "dev".\n\nSee https://vercel.com/docs/microfrontends/local-development.' }, fallback: { type: "string", description: "Fallback for local development, could point to any environment. This is required for the default app. This value is used as the fallback for child apps as well if they do not have a fallback.\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.\n\nSee https://vercel.com/docs/microfrontends/local-development." } }, required: [ "fallback" ], additionalProperties: false }, ChildApplication: { type: "object", properties: { packageName: { type: "string", description: "The name used to run the application, e.g. the `name` field in the `package.json`.\n\nThis is used by the local proxy to map the application config to the locally running app.\n\nThis is only necessary when the application name does not match the `name` used in `package.json`.\n\nSee https://vercel.com/docs/microfronte