/** * External contract package consumer boundary (§4). * * This repository does not own OpenAPI/AsyncAPI source, operation semantics, * Problem Details meaning or event payload schemas. It owns only the normalized * descriptor interface, the runtime validator protocol, and the bounds it * applies before a contribution may be composed. */ import { isOperationId } from "./operation-id.ts"; import { INSTALLED_REST_AUTH_PROFILES, type InstalledRestAuthProfiles, } from "./rest-profiles.ts"; import { defineTrafficBudget, TRAFFIC_BUDGET_KEYS, type TrafficBudget, } from "../platform/traffic/traffic-budget.ts"; import { createReadOnlyRegistry, type ReadOnlyRegistry, } from "./read-only-registry.ts"; import { exactOwnDataSnapshot, snapshotExactArray } from "./exact-snapshot.ts"; /** §7.3 hard ceilings. A contribution may lower these, never raise them. */ export const HTTP_EXECUTION_CEILINGS = Object.freeze({ defaultRequestBytes: 262_144, hardRequestBytes: 1_048_576, defaultResponseBytes: 1_048_576, hardResponseBytes: 8_388_608, problemResponseBytes: 65_536, pathTemplateBytes: 512, encodedQueryBytes: 8_192, examinedHeaderValueBytes: 8_192, defaultTotalDeadlineMs: 10_000, hardTotalDeadlineMs: 60_000, hardRetryCount: 2, finalUrlBytes: 16_384, }); /* * D-15. The validator protocol below is the canonical shape; * `RuntimeSchemaCodec` (`schema-registry.ts`) adapts over it. `MappingResult` * below is the contract-package side of a mapping result. Feature mappers and * the HTTP binding return `BoundaryMappingResult` (`boundary-mapper.ts`) * instead, whose failure code is a closed set; `toContractMappingResult` * converts one into this shape (07-01). */ export type RuntimeValidationIssue = Readonly<{ path: readonly (string | number)[]; code: string; }>; export type RuntimeValidationResult = | Readonly<{ success: true; data: T }> | Readonly<{ success: false; issues: readonly RuntimeValidationIssue[] }>; export interface RuntimeValidator { readonly schemaId: string; /** * 1101/07-03. Absent on a validator that checks its input. `"NONE"` marks * one made by `unvalidatedPayload` (`unvalidated-payload.ts`), which * accepts any value as `T`; `listUnvalidatedPayloads` lists it. * Composition, on the boot path, does not read the marker. A hand-written * validator that checks nothing and omits the marker is not detected. */ readonly validation?: "NONE"; /** Why validation is skipped. `unvalidatedPayload` requires one. */ readonly unvalidatedReason?: string; safeParse(value: unknown): RuntimeValidationResult; } /** * A validator invocation never escapes as a native throw. `THROWN` is the * `CONTRACT_RUNTIME_FAILURE` signal; `false` success is the ordinary * `CONTRACT_VALUE_INVALID` signal. */ export type ValidatorInvocation = | Readonly<{ outcome: "VALID"; value: T }> | Readonly<{ outcome: "INVALID"; issues: readonly RuntimeValidationIssue[] }> | Readonly<{ outcome: "THROWN" }>; export function invokeValidator( validator: RuntimeValidator, value: unknown, ): ValidatorInvocation { // 07-06. Reading the result stays inside the try: a hand-written validator // may return any shape, including throwing getters. try { const result: unknown = validator.safeParse(value); if (!result || typeof result !== "object") throw new TypeError(); const candidate = result as Readonly>; if (candidate.success === true) { return Object.freeze({ outcome: "VALID" as const, value: candidate.data as T, }); } const issues = candidate.issues; if (candidate.success !== false || !Array.isArray(issues)) { throw new TypeError(); } return Object.freeze({ outcome: "INVALID" as const, issues: Object.freeze([...(issues as RuntimeValidationIssue[])]), }); } catch { return Object.freeze({ outcome: "THROWN" as const }); } } export type MappingResult = | Readonly<{ ok: true; value: T }> | Readonly<{ ok: false; error: Readonly<{ kind: "MAPPING_CONTRACT_VIOLATION"; code: string }>; }>; export function mappingViolation(code: string): MappingResult { return Object.freeze({ ok: false as const, error: Object.freeze({ kind: "MAPPING_CONTRACT_VIOLATION" as const, code, }), }); } export type CommandRecoveryDescriptor = Readonly<{ mode: "IDEMPOTENCY_REPLAY" | "INSPECT_OPERATION"; operationIdentityField: string; inspectOperationId?: string; }>; export type CommandEffectClassification = | "NOT_APPLIED" | "APPLIED_CONFIRMED" | "MAYBE_APPLIED"; export interface CommandEffectDescriptor { readonly successEffect: "APPLIED_CONFIRMED"; classifyProblem( input: Readonly<{ status: number; problem: Problem }>, ): CommandEffectClassification; /** * D-2. 401, 403 and 429 are admitted by status before any problem body is * read. Declare `NOT_APPLIED` only when the server contract guarantees the * command was rejected untouched. Without this, they stay `MAYBE_APPLIED`. */ classifyStatus?(status: 401 | 403 | 429): "NOT_APPLIED" | "MAYBE_APPLIED"; } export type HttpMethod = | "GET" | "HEAD" | "POST" | "PUT" | "PATCH" | "DELETE"; export type RetrySemantics = "SAFE" | "IDEMPOTENT" | "KEYED" | "NEVER"; export type ResponseEnvelope = "NONE" | "ENVELOPE_V1"; export interface HttpExecutionPolicy { readonly policyId: string; readonly requestByteLimit: number; readonly responseByteLimit: number; readonly totalDeadlineMs: number; readonly retryBudget: 0 | 1 | 2; readonly authProfileId: string; readonly diagnosticsOperation: string; /** * scale-architecture.md §11. Optional operation-owned interaction traffic policy. When a * caller supplies no interaction `ExecutionContext`, the executor creates one * from this policy (or the bounded platform default), so every logical * execution carries finite request/retry/concurrency budgets. */ readonly traffic?: TrafficBudget; } export interface InstalledHttpContract { readonly contract: Readonly<{ operationId: string; method: HttpMethod; pathTemplate: string; inputValidator: RuntimeValidator; outputValidator: RuntimeValidator; problemValidator: RuntimeValidator; acceptedStatuses: readonly number[]; emptyBodyStatuses: readonly number[]; retrySemantics: RetrySemantics; requestBody: "NONE" | "JSON"; responseBody: "REQUIRED_JSON" | "OPTIONAL_JSON" | "NONE"; /** * 1101 README 14.3. How the server frames a JSON body. Absent or `"NONE"`: * the body is the DTO, and a failure body is the problem. `"ENVELOPE_V1"`: * the paired backend's `{ success, data | error, meta }` * (clean-architecture-backend-template docs/web/http-contract.md §1). * `outputValidator` then sees `data` (`null` when the key is absent) and * `problemValidator` sees `error`. Whether a 400, 409, 422 or 503 * `IDEMPOTENCY_UNAVAILABLE` applied comes from the backend's own table * (`src/adapters/http/backend-envelope.ts`, the frontend contract's 6.1), * not from `commandEffect.classifyProblem`, which decides every other * status. A body that is empty by `emptyBodyStatuses` has no Envelope. */ responseEnvelope?: ResponseEnvelope; commandRecovery: CommandRecoveryDescriptor | null; commandEffect: CommandEffectDescriptor | null; /** * Descriptor-owned projection from canonical application input to the wire * request. The frontend never re-derives method, path or query semantics. */ projectRequest(input: Input): HttpRequestProjection; }>; readonly frontend: HttpExecutionPolicy; } export type HttpRequestProjection = Readonly<{ /** Ordered path placeholder values keyed by descriptor placeholder name. */ pathValues: Readonly>; /** Descriptor-generated query entry order; array encoding is descriptor-owned. */ queryEntries: readonly (readonly [string, string])[]; /** Canonical JSON body value, or `null` when `requestBody` is `NONE`. */ body: unknown; }>; export interface InstalledEventContract { readonly eventType: string; readonly envelopeValidator: RuntimeValidator; readonly payloadValidator: RuntimeValidator; } export interface InstalledContractPackageIdentity { readonly packageId: string; readonly version: string; readonly digest: `sha256:${string}`; readonly runtimeProtocolVersion: 1; readonly sourceRevision: string; } export type ContractContributionSource = | Readonly<{ kind: "EXTERNAL_PACKAGE"; package: InstalledContractPackageIdentity; }> | Readonly<{ kind: "TEMPLATE_FIXTURE"; fixtureId: "REFERENCE_FEATURE_V1"; revision: 1; }>; export interface InstalledContractContribution { readonly contributionId: string; readonly featureId: string; readonly source: ContractContributionSource; readonly http: readonly InstalledHttpContract[]; readonly events: readonly InstalledEventContract[]; } export type ContractCompositionFailureCode = | "CONTRACT_CONTRIBUTION_INVALID" | "CONTRACT_RUNTIME_PROTOCOL_UNSUPPORTED"; export class ContractContributionError extends Error { readonly code: ContractCompositionFailureCode; readonly reason: string; constructor(reason: string, code: ContractCompositionFailureCode = "CONTRACT_CONTRIBUTION_INVALID") { super("Installed contract contribution is not composable"); this.name = "ContractContributionError"; this.code = code; this.reason = reason; } } // §4.9 exact validation vocabulary. const FEATURE_ID = /^[a-z][a-z0-9-]{0,63}$/; const CONTRIBUTION_ID = /^[a-z][a-z0-9._-]{0,127}$/; const PACKAGE_ID = /^@[a-z0-9][a-z0-9._-]{0,62}\/[a-z0-9][a-z0-9._-]{0,62}$/; const SEM_VER = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*)(?:\.(?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*))*))?(?:\+([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?$/; const DIGEST = /^sha256:[0-9a-f]{64}$/; const SOURCE_REVISION = /^[0-9a-f]{7,64}$/; /** Whitespace and C0/C1 control characters are rejected in an event type. */ function hasControlOrSpace(value: string): boolean { for (const character of value) { const code = character.codePointAt(0) ?? 0; if (code <= 0x20 || (code >= 0x7f && code <= 0x9f)) return true; } return false; } const encoder = new TextEncoder(); function utf8Bytes(value: string): number { return encoder.encode(value).byteLength; } function fail(reason: string): never { throw new ContractContributionError(reason); } function assertPackageIdentity( identity: InstalledContractPackageIdentity, featureId: string, ): void { if (!identity || typeof identity !== "object") { fail(`${featureId}: package identity`); } if (identity.runtimeProtocolVersion !== 1) { throw new ContractContributionError( `${featureId}: runtime protocol version must be exactly 1`, "CONTRACT_RUNTIME_PROTOCOL_UNSUPPORTED", ); } if (!PACKAGE_ID.test(identity.packageId)) fail(`${featureId}: packageId`); if ( typeof identity.version !== "string" || identity.version !== identity.version.trim() || identity.version.startsWith("v") || !SEM_VER.test(identity.version) ) { fail(`${featureId}: package version must be exact SemVer`); } if (!DIGEST.test(identity.digest)) fail(`${featureId}: package digest`); if (!SOURCE_REVISION.test(identity.sourceRevision)) { fail(`${featureId}: package sourceRevision`); } } function assertValidator( validator: RuntimeValidator, label: string, ): void { if ( !validator || typeof validator.safeParse !== "function" || typeof validator.schemaId !== "string" || validator.schemaId.length === 0 ) { fail(`${label}: runtime validator with non-empty schemaId is required`); } } function assertStatuses( statuses: readonly number[], label: string, ): void { if (!Array.isArray(statuses)) fail(`${label}: status array required`); if (statuses.length < 1 || statuses.length > 32) { fail(`${label}: 1..32 statuses required`); } for (let index = 0; index < statuses.length; index += 1) { const status = statuses[index] as number; if (!Number.isInteger(status) || status < 100 || status > 599) { fail(`${label}: status out of range`); } const previous = statuses[index - 1]; if (index > 0 && previous !== undefined && status <= previous) { fail(`${label}: statuses must be sorted and unique`); } } } function assertExecutionPolicy( policy: HttpExecutionPolicy, label: string, authProfiles: InstalledRestAuthProfiles, ): void { const ceilings = HTTP_EXECUTION_CEILINGS; if ( !policy || typeof policy.policyId !== "string" || policy.policyId.length === 0 || typeof policy.authProfileId !== "string" || policy.authProfileId.length === 0 || typeof policy.diagnosticsOperation !== "string" || policy.diagnosticsOperation.length === 0 ) { fail(`${label}: frontend execution policy identity`); } // §7.7 / VD-23. A declared profile that the installed registry does not own // is a composition failure; the executor must never resolve it at runtime. if (!authProfiles.has(policy.authProfileId)) { fail(`${label}: unknown authProfileId ${policy.authProfileId}`); } if ( !Number.isSafeInteger(policy.requestByteLimit) || policy.requestByteLimit < 0 || policy.requestByteLimit > ceilings.hardRequestBytes ) { fail(`${label}: requestByteLimit exceeds the hard ceiling`); } if ( !Number.isSafeInteger(policy.responseByteLimit) || policy.responseByteLimit < 1 || policy.responseByteLimit > ceilings.hardResponseBytes ) { fail(`${label}: responseByteLimit exceeds the hard ceiling`); } if ( !Number.isSafeInteger(policy.totalDeadlineMs) || policy.totalDeadlineMs < 1 || policy.totalDeadlineMs > ceilings.hardTotalDeadlineMs ) { fail(`${label}: totalDeadlineMs exceeds the hard ceiling`); } if ( policy.retryBudget !== 0 && policy.retryBudget !== 1 && policy.retryBudget !== 2 ) { fail(`${label}: retryBudget must be 0, 1 or 2`); } if (policy.traffic !== undefined) { try { defineTrafficBudget(policy.traffic); } catch (error) { fail( `${label}: traffic policy ${error instanceof Error ? error.message : "invalid"}`, ); } } } function assertHttpContract( installed: InstalledHttpContract, featureId: string, authProfiles: InstalledRestAuthProfiles, ): void { const contract = installed?.contract; if (!contract || typeof contract !== "object") { fail(`${featureId}: http contract descriptor missing`); } const label = `${featureId}/${String(contract.operationId)}`; if (!isOperationId(contract.operationId)) { fail(`${label}: operationId`); } if ( contract.method !== "GET" && contract.method !== "HEAD" && contract.method !== "POST" && contract.method !== "PUT" && contract.method !== "PATCH" && contract.method !== "DELETE" ) { fail(`${label}: method`); } if ( typeof contract.pathTemplate !== "string" || !contract.pathTemplate.startsWith("/") || utf8Bytes(contract.pathTemplate) > HTTP_EXECUTION_CEILINGS.pathTemplateBytes || contract.pathTemplate.includes("?") || contract.pathTemplate.includes("#") ) { fail(`${label}: pathTemplate`); } assertValidator(contract.inputValidator, `${label}.input`); assertValidator(contract.outputValidator, `${label}.output`); assertValidator(contract.problemValidator, `${label}.problem`); if (typeof contract.projectRequest !== "function") { fail(`${label}: descriptor request projection is required`); } if ( contract.retrySemantics !== "SAFE" && contract.retrySemantics !== "IDEMPOTENT" && contract.retrySemantics !== "KEYED" && contract.retrySemantics !== "NEVER" ) { fail(`${label}: retrySemantics`); } if (contract.requestBody !== "NONE" && contract.requestBody !== "JSON") { fail(`${label}: requestBody`); } if ( contract.responseBody !== "REQUIRED_JSON" && contract.responseBody !== "OPTIONAL_JSON" && contract.responseBody !== "NONE" ) { fail(`${label}: responseBody`); } if ( contract.responseEnvelope !== undefined && contract.responseEnvelope !== "NONE" && contract.responseEnvelope !== "ENVELOPE_V1" ) { fail(`${label}: responseEnvelope`); } assertStatuses(contract.acceptedStatuses, `${label}.acceptedStatuses`); if (contract.emptyBodyStatuses.length > 0) { assertStatuses(contract.emptyBodyStatuses, `${label}.emptyBodyStatuses`); const accepted = new Set(contract.acceptedStatuses); for (const status of contract.emptyBodyStatuses) { if (!accepted.has(status)) { fail(`${label}: empty-body status must be an accepted status`); } } } const isRead = contract.method === "GET" || contract.method === "HEAD"; if (isRead) { if (contract.commandEffect !== null || contract.commandRecovery !== null) { fail(`${label}: read operations carry no command descriptors`); } if (contract.requestBody !== "NONE") { fail(`${label}: read operations carry no request body`); } // 1103/07-01 (c). The executor runs a read as a read whatever it is // declared; KEYED or NEVER here only looks like a decision the executor // never makes. A realtime snapshot binding reads the same pair. if ( contract.retrySemantics !== "SAFE" && contract.retrySemantics !== "IDEMPOTENT" ) { fail( `${label}: ${contract.method} is a read; its retrySemantics is SAFE or IDEMPOTENT, not ${contract.retrySemantics}`, ); } } else { if (!contract.commandEffect) { fail(`${label}: command operations require a command effect descriptor`); } if (contract.commandEffect.successEffect !== "APPLIED_CONFIRMED") { fail(`${label}: command success effect`); } if (typeof contract.commandEffect.classifyProblem !== "function") { fail(`${label}: command effect classifier is required`); } if ( contract.commandEffect.classifyStatus !== undefined && typeof contract.commandEffect.classifyStatus !== "function" ) { fail(`${label}: command status classifier must be a function`); } if (contract.retrySemantics === "KEYED" && !contract.commandRecovery) { fail(`${label}: KEYED commands require a recovery descriptor`); } } if (contract.commandRecovery) { const recovery = contract.commandRecovery; if ( (recovery.mode !== "IDEMPOTENCY_REPLAY" && recovery.mode !== "INSPECT_OPERATION") || !recovery.operationIdentityField || (recovery.mode === "INSPECT_OPERATION" && !recovery.inspectOperationId) ) { fail(`${label}: command recovery descriptor`); } } assertExecutionPolicy(installed.frontend, label, authProfiles); // A browser attaches an ambient cookie to any site's request, so a // cookie-authenticated write needs a header only the page can set. const profile = authProfiles.get(installed.frontend.authProfileId); if ( !isRead && profile?.transport === "SAME_ORIGIN_COOKIE" && !profile.requiredCredentialHeaders.some( (header) => header === "x-csrf-token" || header === "x-xsrf-token", ) ) { fail( `${label}: ${contract.method} with cookie profile ${profile.authProfileId} must require x-csrf-token or x-xsrf-token`, ); } if ( installed.frontend.retryBudget > 0 && contract.retrySemantics === "NEVER" ) { fail(`${label}: retry budget contradicts NEVER retry semantics`); } } function assertEventContract( event: InstalledEventContract, featureId: string, ): void { const label = `${featureId}/${String(event?.eventType)}`; if ( typeof event?.eventType !== "string" || event.eventType.length === 0 || utf8Bytes(event.eventType) > 160 || hasControlOrSpace(event.eventType) ) { fail(`${label}: eventType`); } assertValidator(event.envelopeValidator, `${label}.envelope`); assertValidator(event.payloadValidator, `${label}.payload`); } export type ComposedContractContributions = Readonly<{ contributions: readonly InstalledContractContribution[]; /** * LIVE-03. Read facades over private stores. The executor resolves an * operation on every request, so an exported `Map` would let any holder of * the composed singleton delete or replace a validated row after boot. */ httpByOperationId: ReadOnlyRegistry< string, InstalledHttpContract >; eventByType: ReadOnlyRegistry< string, InstalledEventContract >; externalPackages: readonly InstalledContractPackageIdentity[]; }>; const EXECUTION_POLICY_KEYS = [ "policyId", "requestByteLimit", "responseByteLimit", "totalDeadlineMs", "retryBudget", "authProfileId", "diagnosticsOperation", ] as const; const EXECUTION_POLICY_ALLOWED_KEYS = [ ...EXECUTION_POLICY_KEYS, "traffic", ] as const; const HTTP_CONTRACT_KEYS = [ "operationId", "method", "pathTemplate", "inputValidator", "outputValidator", "problemValidator", "acceptedStatuses", "emptyBodyStatuses", "retrySemantics", "requestBody", "responseBody", "commandRecovery", "commandEffect", "projectRequest", ] as const; const HTTP_CONTRACT_ALLOWED_KEYS = [ ...HTTP_CONTRACT_KEYS, "responseEnvelope", ] as const; const COMMAND_RECOVERY_KEYS = [ "mode", "operationIdentityField", "inspectOperationId", ] as const; /** * LIVE-03. Composition is the last point at which a contribution row is * trusted, so the registry keeps an exact own-data copy rather than the * caller's object. A later mutation of the source — including one that swaps a * deadline or a credential policy — cannot reach what the executor reads. * * Validators and the descriptor-owned `projectRequest` stay by reference: they * are behaviour the contribution owns, not data this repository re-derives. */ function snapshotHttpContract( installed: InstalledHttpContract, label: string, ): InstalledHttpContract { const reject = (detail: string): never => fail(`${label}: ${detail}`); // NS-02. The outer row is snapshotted first, so every nested read below comes // from an owned object rather than from the caller's, which could answer // differently on a second read. const row = exactOwnDataSnapshot< InstalledHttpContract >(installed, ["contract", "frontend"], ["contract", "frontend"], reject); const policy = exactOwnDataSnapshot( row.frontend, EXECUTION_POLICY_ALLOWED_KEYS, EXECUTION_POLICY_KEYS, reject, ); const frontend: HttpExecutionPolicy = policy.traffic === undefined ? policy : Object.freeze({ ...policy, traffic: exactOwnDataSnapshot( policy.traffic, TRAFFIC_BUDGET_KEYS, TRAFFIC_BUDGET_KEYS, (detail) => reject(`traffic policy ${detail}`), ), }); const source = exactOwnDataSnapshot< InstalledHttpContract["contract"] >(row.contract, HTTP_CONTRACT_ALLOWED_KEYS, HTTP_CONTRACT_KEYS, reject); const contract = Object.freeze({ ...source, acceptedStatuses: statusArray(source.acceptedStatuses, reject), emptyBodyStatuses: statusArray(source.emptyBodyStatuses, reject), commandRecovery: source.commandRecovery === null ? null : exactOwnDataSnapshot( source.commandRecovery, COMMAND_RECOVERY_KEYS, ["mode", "operationIdentityField"], reject, ), }); return Object.freeze({ contract, frontend }); } /** * Q-6.7-6. Arrays are copied by index, never through their iterator, so an own * `Symbol.iterator` cannot hand composition a different list than `length` * and the indices describe. */ function statusArray( value: readonly number[], reject: (detail: string) => never, ): readonly number[] { return (snapshotExactArray(value, 32) as readonly number[] | null) ?? reject("status array"); } function snapshotEventContract( event: InstalledEventContract, label: string, ): InstalledEventContract { return exactOwnDataSnapshot>( event, ["eventType", "envelopeValidator", "payloadValidator"], ["eventType", "envelopeValidator", "payloadValidator"], (detail) => fail(`${label}: ${detail}`), ); } /** * §4.8–§4.9. The only place installed contributions become a runtime registry. * Every bound is checked before composition; a violation stops the boot rather * than degrading into an assumed meaning. */ export function composeContractContributions( contributions: readonly InstalledContractContribution[], /** * Q-6.7-9. The registry the executor will resolve against. Pass the same * one the executor receives; the default is the shared installed registry. */ authProfiles: InstalledRestAuthProfiles = INSTALLED_REST_AUTH_PROFILES, ): ComposedContractContributions { const rows = snapshotExactArray(contributions) ?? fail("contributions: array required"); const httpByOperationId = new Map< string, InstalledHttpContract >(); const eventByType = new Map< string, InstalledEventContract >(); const packagesById = new Map(); const contributionIds = new Set(); const installedContributions: InstalledContractContribution[] = []; let fixtureInstalled = false; for (const raw of rows) { if (!raw || typeof raw !== "object") { fail("contribution: object required"); } // NS-02. Snapshot first, then validate the snapshot, then install exactly // what was validated. Validating the caller's object and reading it again // to copy it let a stateful answer pass the ceiling check and still install // a different deadline, retry budget or auth profile. const contribution = exactOwnDataSnapshot( raw, ["contributionId", "featureId", "source", "http", "events"], ["contributionId", "featureId", "source", "http", "events"], (detail) => fail(`contribution: ${detail}`), ); const contributionId = contribution.contributionId; if ( typeof contributionId !== "string" || !CONTRIBUTION_ID.test(contributionId) ) { fail(`contributionId: ${String(contributionId)}`); } if (contributionIds.has(contributionId)) { fail(`duplicate contributionId: ${contributionId}`); } contributionIds.add(contributionId); const featureId = contribution?.featureId; if (typeof featureId !== "string" || !FEATURE_ID.test(featureId)) { fail(`featureId: ${String(featureId)}`); } const rawSource = contribution.source; if (!rawSource || typeof rawSource !== "object" || !("kind" in rawSource)) { fail(`${featureId}: source`); } const httpRows = snapshotExactArray(contribution.http); const eventRows = snapshotExactArray(contribution.events); if (!httpRows || !eventRows) fail(`${featureId}: contribution arrays`); const rejectSource = (detail: string): never => fail(`${featureId}: source ${detail}`); let source: ContractContributionSource; if (rawSource.kind === "EXTERNAL_PACKAGE") { const outer = exactOwnDataSnapshot< Readonly<{ kind: "EXTERNAL_PACKAGE"; package: unknown }> >(rawSource, ["kind", "package"], ["kind", "package"], rejectSource); const identity = exactOwnDataSnapshot( outer.package, [ "packageId", "version", "digest", "runtimeProtocolVersion", "sourceRevision", ], [ "packageId", "version", "digest", "runtimeProtocolVersion", "sourceRevision", ], rejectSource, ); assertPackageIdentity(identity, featureId); source = Object.freeze({ kind: "EXTERNAL_PACKAGE" as const, package: identity, }); const existing = packagesById.get(identity.packageId); if ( existing && (existing.version !== identity.version || existing.digest !== identity.digest || existing.sourceRevision !== identity.sourceRevision) ) { fail( `${featureId}: package ${identity.packageId} has conflicting identities`, ); } packagesById.set(identity.packageId, identity); } else if (rawSource.kind === "TEMPLATE_FIXTURE") { const fixture = exactOwnDataSnapshot< Readonly<{ kind: "TEMPLATE_FIXTURE"; fixtureId: "REFERENCE_FEATURE_V1"; revision: 1; }> >( rawSource, ["kind", "fixtureId", "revision"], ["kind", "fixtureId", "revision"], rejectSource, ); if ( fixture.kind !== "TEMPLATE_FIXTURE" || fixture.fixtureId !== "REFERENCE_FEATURE_V1" || fixture.revision !== 1 ) { fail(`${featureId}: template fixture identity`); } // §4.8, §24.5 (07-04). The fixture is the sample vertical's test data, // not a product contract: it never joins the contract set, so a fixture // copied into a product feature would drop that API from the release // check without a word. Only the feature the fixture is named after may // install it; every other feature pins an EXTERNAL_PACKAGE. // The owner is derived from the fixture id (upper snake case feature id // plus `_V`) instead of being written out, because // test:sample-removal rejects the sample feature's id anywhere in src/ // once the sample is gone. const fixtureOwner = fixture.fixtureId .slice(0, -`_V${fixture.revision}`.length) .toLowerCase() .replaceAll("_", "-"); if (featureId !== fixtureOwner) { fail( `${featureId}: TEMPLATE_FIXTURE ${fixture.fixtureId} belongs to ${fixtureOwner} only; pin an EXTERNAL_PACKAGE`, ); } if (fixtureInstalled) { fail(`${featureId}: only one TEMPLATE_FIXTURE contribution is allowed`); } fixtureInstalled = true; if (eventRows.length !== 0) { fail(`${featureId}: template fixture must not contribute events`); } source = fixture; } else { fail(`${featureId}: unknown contribution source kind`); } const installedHttp: InstalledHttpContract[] = []; for (const installed of httpRows) { const snapshot = snapshotHttpContract( installed as InstalledHttpContract, featureId, ); assertHttpContract(snapshot, featureId, authProfiles); const operationId = snapshot.contract.operationId; const previous = httpByOperationId.get(operationId); if (previous) fail(`duplicate operation: ${operationId}`); httpByOperationId.set(operationId, snapshot); installedHttp.push(snapshot); } const installedEvents: InstalledEventContract[] = []; for (const event of eventRows) { const snapshot = snapshotEventContract( event as InstalledEventContract, featureId, ); assertEventContract(snapshot, featureId); if (eventByType.has(snapshot.eventType)) { fail(`duplicate event type: ${snapshot.eventType}`); } eventByType.set(snapshot.eventType, snapshot); installedEvents.push(snapshot); } // Everything published downstream is the validated snapshot, so no consumer // can be handed the caller's still-live object. installedContributions.push( Object.freeze({ contributionId, featureId, source, http: Object.freeze(installedHttp), events: Object.freeze(installedEvents), }), ); } const externalPackages = [...packagesById.values()].map((identity) => Object.freeze({ ...identity }), ); return Object.freeze({ contributions: Object.freeze(installedContributions), httpByOperationId: createReadOnlyRegistry(httpByOperationId), eventByType: createReadOnlyRegistry(eventByType), externalPackages: Object.freeze(externalPackages), }); }