UNPKG

@vercel/microfrontends

Version:

Defines configuration and utilities for microfrontends development

387 lines (380 loc) 16.5 kB
"use strict"; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; 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 __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/schema/validation.ts var validation_exports = {}; __export(validation_exports, { validateSchema: () => validateSchema }); module.exports = __toCommonJS(validation_exports); // src/config/microfrontends/server/validation.ts var import_jsonc_parser = require("jsonc-parser"); var import_ajv = require("ajv"); // 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"); } }; // 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/microfrontends/configuration#application-naming." }, development: { $ref: "#/definitions/ChildDevelopment", description: "Development configuration for the child application." }, routing: { $ref: "#/definitions/Routing", description: "Groups of path expressions that are routed to this application.\n\nSee https://vercel.com/docs/microfrontends/path-routing." }, assetPrefix: { type: "string", description: "The name of the asset prefix to use instead of the auto-generated name.\n\nThe asset prefix is used to prefix all paths to static assets, such as JS, CSS, or images that are served by a specific application. It is necessary to ensure there are no conflicts with other applications on the same domain.\n\nAn auto-generated asset prefix of the form `vc-ap-<hash>` is used when this field is not provided.\n\nWhen this field is provided, `/${assetPrefix}/:path*` must also be added to the list of paths in the `routing` field. Changing the asset prefix after a microfrontend application has already been deployed is not a forwards and backwards compatible change, and the asset prefix should be added to the `routing` field and deployed before setting the `assetPrefix` field.\n\nThe default value is the auto-generated asset prefix of the form `vc-ap-<hash>`.\n\nSee https://vercel.com/docs/microfrontends/path-routing#asset-prefix." } }, required: [ "routing" ], additionalProperties: false }, ChildDevelopment: { 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. If not provided for child apps, the fallback of the default app will be used.\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." } }, additionalProperties: false }, Routing: { type: "array", items: { $ref: "#/definitions/PathGroup" }, description: "A list of path groups that are routed to this application." }, PathGroup: { type: "object", properties: { group: { type: "string", description: "Group name for the paths." }, flag: { type: "string", description: "The name of the feature flag that controls routing for this group of paths. See https://vercel.com/docs/microfrontends/path-routing#routing-changes-safely-with-flags." }, paths: { type: "array", items: { type: "string" }, description: "A list of path expressions that are routed to this application. See https://vercel.com/docs/microfrontends/path-routing#supported-path-expressions." } }, required: [ "paths" ], additionalProperties: false, description: "A group of paths that is routed to this application." }, Options: { type: "object", properties: { disableOverrides: { type: "boolean", 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.\n\nSee https://vercel.com/docs/microfrontends/managing-microfrontends/vercel-toolbar#routing-overrides." }, localProxyPort: { type: "number", description: "The port number used by the local proxy server.\n\nThe default value is 3024.\n\nSee https://vercel.com/docs/microfrontends/local-development." } }, additionalProperties: false } } }; // src/config/schema/utils/load.ts var SCHEMA = schema_default; // src/config/microfrontends/server/validation.ts var LIST_FORMATTER = new Intl.ListFormat("en", { style: "long", type: "disjunction" }); function formatAjvErrors(errors) { if (!errors) { return []; } const errorMessages = []; for (const error of errors) { if (error.instancePath === "" && (error.keyword === "anyOf" || error.keyword === "required" && error.params.missingProperty === "partOf")) { continue; } const instancePath = error.instancePath.slice(1); const formattedInstancePath = instancePath === "" ? "at the root" : `in field ${instancePath}`; if (error.keyword === "required" && error.params.missingProperty === "routing" && instancePath.split("/").length === 2) { errorMessages.push( `Unable to infer if ${instancePath} is the default app or a child app. This usually means that there is another error in the configuration.` ); } else if (error.keyword === "anyOf" && instancePath.split("/").length > 2) { const anyOfErrors = errors.filter( (e) => e.instancePath === error.instancePath && e.keyword !== "anyOf" ); if (anyOfErrors.every((e) => e.keyword === "type")) { const allowedTypes = LIST_FORMATTER.format( anyOfErrors.map((e) => { return e.keyword === "type" ? String(e.params.type) : "unknown"; }) ); errorMessages.push( `Incorrect type for ${instancePath}. Must be one of ${allowedTypes}` ); } else { errorMessages.push( `Invalid field for ${instancePath}. Possible error messages are ${LIST_FORMATTER.format(anyOfErrors.map((e) => e.message ?? ""))}` ); } } else if (error.keyword === "additionalProperties" && !(error.params.additionalProperty === "routing" && instancePath.split("/").length === 2)) { errorMessages.push( `Property '${error.params.additionalProperty}' is not allowed ${formattedInstancePath}` ); } else if (error.keyword === "required") { errorMessages.push( `Property '${error.params.missingProperty}' is required ${formattedInstancePath}` ); } } return errorMessages; } function validateSchema(configString) { const parsedConfig = (0, import_jsonc_parser.parse)(configString); const ajv = new import_ajv.Ajv({ allowUnionTypes: true }); const validate = ajv.compile(SCHEMA); const isValid = validate(parsedConfig); if (!isValid) { throw new MicrofrontendError( `Invalid microfrontends config:${formatAjvErrors(validate.errors).map((error) => ` - ${error}`).join( "" )} See https://openapi.vercel.sh/microfrontends.json for the schema.`, { type: "config", subtype: "does_not_match_schema" } ); } return parsedConfig; } // Annotate the CommonJS export names for ESM import in node: 0 && (module.exports = { validateSchema }); //# sourceMappingURL=validation.cjs.map