import { Option, Predicate, Result, Schema } from "effect"; import { stampVersion } from "./internal/version.js"; import type { SchemaLayout, SchemaVersion } from "./SchemaVersioning.js"; import { SchemaVersioning } from "./SchemaVersioning.js"; /** The host SchemaStore-hosted documents declare in `$id`. @public */ export const SCHEMASTORE_ID_BASE = "https://json.schemastore.org"; /** The host SchemaStore's `catalog.json` points `url` at. @public */ export const SCHEMASTORE_CATALOG_BASE = "https://www.schemastore.org"; const RAW_GITHUB_BASE = "https://raw.githubusercontent.com"; const trimSlashes = (url: string): string => { let end = url.length; while (end > 0 && url.charCodeAt(end - 1) === 47) { end -= 1; } return url.slice(0, end); }; // A base must be a directory a file name can be joined under: an https URL // with no query, fragment or credentials — each of which would survive the // join and make `/` name something other than a child path. const describeDirectoryUrl = (raw: string): string | undefined => { let url: URL; try { url = new URL(raw); } catch { return 'expected "schemastore" or an https:// URL'; } if (url.protocol !== "https:" || url.host.length === 0) { return 'expected "schemastore" or an https:// URL'; } if (url.search.length > 0 || raw.endsWith("?")) { return "a base URL cannot carry a query"; } if (url.hash.length > 0 || raw.endsWith("#")) { return "a base URL cannot carry a fragment"; } if (url.username.length > 0 || url.password.length > 0) { return "a base URL cannot carry credentials"; } return undefined; }; // `owner/repo`, exactly two non-empty path segments with no whitespace. const isOwnerRepo = (repo: string): boolean => /^[^/\s]+\/[^/\s]+$/.test(repo); // Where a document is hosted decides both of its bases and its layout. interface Hosting { readonly idBase: string; readonly catalogBase: string; readonly layout: SchemaLayout; readonly appendVersion: boolean; } // Every label, deduplicated under Order (`1.2` / `1.2.0` are one label), plus // which one is current: the explicit label, else the newest. interface Versions { readonly versions: ReadonlyArray; readonly current: SchemaVersion | undefined; } interface Resolved { readonly hosting: Hosting; readonly versions: Versions; } interface Fields { readonly name: string; readonly baseUrl: string; readonly versions?: ReadonlyArray; readonly current?: string; readonly layout?: SchemaLayout; readonly appendVersion?: boolean; } // One walk over the raw fields answering either the resolved identity or the // first reason it is invalid — the same walk backs the class check and every // derived getter, so what the check admits is exactly what the getters read. // Messages are predicates with no subject; the class check prefixes them // with `schema ""`, the same subject `defineConfig` uses, so a // hand-spelled entry and a `hosted` one fail with one wording. const resolve = (fields: Fields): Result.Result => { if (!SchemaVersioning.isSimpleName(fields.name)) { return Result.fail(`must be keyed by a simple file base name (no separators, no whitespace)`); } const appendVersion = fields.appendVersion ?? true; let hosting: Hosting; if (fields.baseUrl === "schemastore") { if (fields.layout !== undefined) { return Result.fail( `declares layout "${fields.layout}" under baseUrl "schemastore", which serves only the flat layout`, ); } hosting = { idBase: SCHEMASTORE_ID_BASE, catalogBase: SCHEMASTORE_CATALOG_BASE, layout: "flat", appendVersion }; } else { const problem = describeDirectoryUrl(fields.baseUrl); if (problem !== undefined) { return Result.fail(`has baseUrl "${fields.baseUrl}"; ${problem}`); } hosting = { idBase: fields.baseUrl, catalogBase: fields.baseUrl, layout: fields.layout ?? "versioned", appendVersion, }; } if (!appendVersion && hosting.layout !== "versioned") { return Result.fail( `declares appendVersion: false under the "${hosting.layout}" layout, where every version would share one file name; only the "versioned" layout can drop the suffix`, ); } if (fields.versions === undefined) { if (fields.current !== undefined) { return Result.fail(`declares current "${fields.current}" without versions`); } return Result.succeed({ hosting, versions: { versions: [], current: undefined } }); } if (fields.versions.length === 0) { return Result.fail(`declares versions as an empty array; omit versions for an unversioned schema`); } const versions: Array = []; for (const label of fields.versions) { const parsed = SchemaVersioning.parseResult(label); if (Result.isFailure(parsed)) { return Result.fail(`has an invalid version label "${label}": ${parsed.failure.message}`); } const duplicate = versions.find((v) => SchemaVersioning.Order(v, parsed.success) === 0); if (duplicate !== undefined) { return Result.fail(`declares the same version twice, as "${duplicate}" and "${parsed.success}"`); } versions.push(parsed.success); } if (fields.current === undefined) { // Non-empty by the guard above, so `latest` is always `some`. return Result.succeed({ hosting, versions: { versions, current: Option.getOrThrow(SchemaVersioning.latest(versions)) }, }); } const current = SchemaVersioning.parseResult(fields.current); if (Result.isFailure(current)) { return Result.fail(`has an invalid version label "${fields.current}": ${current.failure.message}`); } const match = versions.find((v) => SchemaVersioning.Order(v, current.success) === 0); if (match === undefined) { return Result.fail(`declares current "${fields.current}" which is not one of its versions`); } return Result.succeed({ hosting, versions: { versions, current: match } }); }; const HostedSchemaFields = Schema.Struct({ name: Schema.String, baseUrl: Schema.String, versions: Schema.optionalKey(Schema.Array(Schema.String)), current: Schema.optionalKey(Schema.String), layout: Schema.optionalKey(Schema.Literals(["flat", "versioned"])), appendVersion: Schema.optionalKey(Schema.Boolean), }).check( Schema.makeFilter((fields) => { const resolved = resolve(fields); return Result.isFailure(resolved) ? `schema "${fields.name}" ${resolved.failure}` : undefined; }), ); /** * The identity every hosted document derives from: `versions` and `current` * as `defineConfig` accepts them, minus the host, which each constructor * supplies. * * @public */ export interface HostedSchemaVersionsInput { /** The schema's file base name — the key it takes in `defineConfig`'s `schemas`. */ readonly name: string; /** Every version label the schema advertises; omit for an unversioned schema. */ readonly versions?: ReadonlyArray; /** Which of `versions` is current. Defaults to the newest under {@link SchemaVersioning.Order}. */ readonly current?: string; /** * Whether a versioned file name carries the `-` suffix * (`/-.json`, SchemaStore's own convention, the * default) or the version directory alone names it * (`/.json`). `false` requires the `"versioned"` layout * and is rejected under `"flat"`, including SchemaStore hosting. */ readonly appendVersion?: boolean; } /** Input to {@link HostedSchema.github}. @public */ export interface GitHubHostedSchemaInput extends HostedSchemaVersionsInput { /** The repository, as `owner/repo`. */ readonly repo: string; /** The branch (or tag) the files are served from. Defaults to `"main"`. */ readonly branch?: string; /** The directory under the repository root the files live in, e.g. `"schemas"`. Defaults to the root. */ readonly path?: string; /** How a versioned file nests under `path`. Defaults to `"versioned"`. */ readonly layout?: SchemaLayout; } /** Input to {@link HostedSchema.custom}. @public */ export interface CustomHostedSchemaInput extends HostedSchemaVersionsInput { /** The `https://` directory URL the files are served under; a trailing slash is trimmed. */ readonly baseUrl: string | URL; /** How a versioned file nests under `baseUrl`. Defaults to `"versioned"`. */ readonly layout?: SchemaLayout; } // Module functions, not `private` members: a private member makes the class // nominal, and `@effected/plugin` inlines a second declaration copy of it, so a // HostedSchema from an installed schemastore would never type-check against the // plugin's config surface. The class must stay structural; the runtime brand // below is what tells copies apart. const resolvedOf = (fields: Fields): Resolved => // Admitted by the class check, so the walk cannot fail here. Result.getOrThrow(resolve(fields)); const parseLabel = (name: string, version: string | undefined): SchemaVersion | undefined => { if (version === undefined) { return undefined; } return Result.getOrThrowWith( SchemaVersioning.parseResult(version), (error) => new Error(`HostedSchema "${name}": invalid version label "${version}": ${error.message}`), ); }; /** * Where a JSON Schema document is hosted and which version of it is current * — the one value an application derives its `$schema` URL from and hands * to `defineConfig`, so the URL the code emits and the `$id` the CLI writes * cannot disagree. * * @remarks * Build one with {@link HostedSchema.github}, * {@link HostedSchema.schemastore} or * {@link HostedSchema.custom}; each validates the identity and * throws a plain `Error` naming the reason. The derivation is * {@link SchemaVersioning.schemaUrl}'s: `/.json` unversioned, * `/-.json` under the `"flat"` layout and * `//-.json` under `"versioned"` (or * `//.json` with `appendVersion: false`, when the * version directory alone should name the file). The raw fields are what * `defineConfig` accepts by hand (`baseUrl`, `versions`, `current`, * `layout`, `appendVersion`); the getters are the resolved identity. * * @example * ```ts * import { HostedSchema } from "@effected/schemastore"; * import { Schema } from "effect"; * * export const OutputSchema = HostedSchema.github({ * repo: "savvy-web/silk-release-action", * path: "schemas", * name: "silk-release-action.output", * versions: ["5.2"], * }); * * // In the application: every payload names the schema it was written against. * const Output = Schema.Struct({ $schema: Schema.Literal(OutputSchema.$id) }); * * // In schemastore.config.ts: the same value, so nothing is re-derived. * // schemas: { [OutputSchema.name]: { schema: Output, hosted: OutputSchema } } * ``` * * @public */ export class HostedSchema extends Schema.Class("HostedSchema")(HostedSchemaFields) { /** A schema served raw from a GitHub repository. */ static github(input: GitHubHostedSchemaInput): HostedSchema { const { repo, branch, path, ...rest } = input; if (!isOwnerRepo(repo)) { throw new Error(`schema "${input.name}" has repo "${repo}"; expected owner/repo`); } const segments = [RAW_GITHUB_BASE, repo, branch ?? "main", ...(path === undefined ? [] : [path])]; return construct({ ...rest, baseUrl: trimSlashes(segments.join("/")) }); } /** A schema published to SchemaStore: `$id` on {@link SCHEMASTORE_ID_BASE}, catalog URL on {@link SCHEMASTORE_CATALOG_BASE}, flat layout. */ static schemastore(input: HostedSchemaVersionsInput): HostedSchema { return construct({ ...input, baseUrl: "schemastore" }); } /** A schema served from any `https://` directory. */ static custom(input: CustomHostedSchemaInput): HostedSchema { const { baseUrl, ...rest } = input; return construct({ ...rest, baseUrl: trimSlashes(typeof baseUrl === "string" ? baseUrl : baseUrl.href) }); } /** The base `$id` is derived from: {@link SCHEMASTORE_ID_BASE} under SchemaStore, else `baseUrl`. */ get idBase(): string { return resolvedOf(this).hosting.idBase; } /** The base the catalog URL is derived from: {@link SCHEMASTORE_CATALOG_BASE} under SchemaStore, else `baseUrl`. */ get catalogBase(): string { return resolvedOf(this).hosting.catalogBase; } /** The effective layout: `"flat"` under SchemaStore, else `layout` defaulting to `"versioned"`. */ get resolvedLayout(): SchemaLayout { return resolvedOf(this).hosting.layout; } /** Whether versioned file names carry the `-` suffix: `appendVersion` defaulting to `true`. */ get resolvedAppendVersion(): boolean { return resolvedOf(this).hosting.appendVersion; } /** Every advertised version, parsed; empty for an unversioned schema. */ get resolvedVersions(): ReadonlyArray { return resolvedOf(this).versions.versions; } /** * The current version — `current`, else the newest of `versions`; * `Option.none()` for an unversioned schema. * * @remarks * An `Option` because this is a derived lookup that can miss, and the * kit's lookups return `Option`. The argument side is a different * contract: {@link HostedSchema.idFor}, {@link HostedSchema.urlFor} and * {@link HostedSchema.fileNameFor} still take an omitted `version` to mean * the unversioned document, so `Option.getOrUndefined(hosted.resolvedCurrent)` * feeds them directly. */ get resolvedCurrent(): Option.Option { return Option.fromUndefinedOr(resolvedOf(this).versions.current); } /** The `$id` of the current document — what an application writes as `$schema`. */ get $id(): string { return this.idFor(resolvedOf(this).versions.current); } /** The catalog URL of the current document; equals {@link HostedSchema.$id} except under SchemaStore. */ get url(): string { return this.urlFor(resolvedOf(this).versions.current); } /** The current document's file name relative to the output directory. */ get fileName(): string { return this.fileNameFor(resolvedOf(this).versions.current); } /** The `$id` of the document at `version` (or the unversioned document). */ idFor(version?: string): string { return SchemaVersioning.schemaUrl( this.idBase, this.name, parseLabel(this.name, version), this.resolvedLayout, this.resolvedAppendVersion, ); } /** The catalog URL of the document at `version` (or the unversioned document). */ urlFor(version?: string): string { return SchemaVersioning.schemaUrl( this.catalogBase, this.name, parseLabel(this.name, version), this.resolvedLayout, this.resolvedAppendVersion, ); } /** The file name of the document at `version` (or the unversioned document), relative to the output directory. */ fileNameFor(version?: string): string { return SchemaVersioning.fileName( this.name, parseLabel(this.name, version), this.resolvedLayout, this.resolvedAppendVersion, ); } } // A prototype property, so neither of these reaches an instance's own keys: // structural equality and `Schema` encoding never see them. The brand is what // `defineConfig` recognizes, because `instanceof` fails across two copies of // this package. const HostedSchemaBrand: unique symbol = Symbol.for("@effected/schemastore/HostedSchema"); Object.defineProperty(HostedSchema.prototype, HostedSchemaBrand, { value: true }); stampVersion(HostedSchema.prototype); /** * Whether a value is a `HostedSchema` from any copy of this package. * * @internal */ export const isHostedSchema = (value: unknown): value is HostedSchema => Predicate.hasProperty(value, HostedSchemaBrand) && value[HostedSchemaBrand] === true; // The one validating path every named constructor takes: a decode, so the // class check's message reaches the thrown Error (`make` buries it in `cause`). const construct = (fields: Fields): HostedSchema => Result.getOrThrowWith(Schema.decodeUnknownResult(HostedSchema)(fields), (error) => new Error(error.message));