🎩 You're Invited:Meet the Socket team at Black Hat in Las Vegas, August 3-6.RSVP
Sign In

@prisma-next/framework-components

Package Overview
Dependencies
Maintainers
4
Versions
479
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@prisma-next/framework-components - npm Package Compare versions

Comparing version
0.14.0-dev.60
to
0.14.0-dev.61
+504
dist/framework-authoring-Bz_vaNZw.mjs
import { n as runtimeError } from "./runtime-error-B2gWOtgH.mjs";
import { blindCast } from "@prisma-next/utils/casts";
import { isColumnDefaultLiteralInputValue, isExecutionMutationDefaultValue } from "@prisma-next/contract/types";
import { ifDefined } from "@prisma-next/utils/defined";
//#region src/shared/framework-authoring.ts
/**
* Classifies an `enum` block's members (before codec decoding, which needs
* the codec chosen first) into which default codec an omitted `@@type`
* should resolve to:
*
* - every member is `bare`, or a `value` whose raw JSON is a string → `'text'`
* - every member is a `value` whose raw JSON is an integer → `'int'`
* - anything else (float, bigint, boolean, mixed, or a `ref`/`option`/`list`
* parameter) → `null`, meaning the caller must require an explicit `@@type`.
*/
function classifyEnumMemberType(block) {
let sawText = false;
let sawInt = false;
for (const paramValue of Object.values(block.parameters)) {
if (paramValue.kind === "bare") {
sawText = true;
continue;
}
if (paramValue.kind !== "value") return null;
let jsonValue;
try {
jsonValue = JSON.parse(paramValue.raw);
} catch {
return null;
}
if (typeof jsonValue === "string") sawText = true;
else if (typeof jsonValue === "number" && Number.isInteger(jsonValue)) sawInt = true;
else return null;
}
if (sawText && sawInt) return null;
if (sawText) return "text";
if (sawInt) return "int";
return null;
}
/**
* Resolves the codec id for an `enum` block. When `@@type` is absent, the codec
* is inferred from the members via {@link classifyEnumMemberType}; otherwise the
* explicit `@@type("codec")` argument is parsed. Pushes the appropriate
* diagnostic and returns `undefined` when neither yields a codec. `codecSpan` is
* the span downstream codec-validation diagnostics should anchor to. Shared by
* every family's enum factory so inference and the explicit path stay identical.
*/
function resolveEnumCodecId(block, ctx) {
const sourceId = ctx.sourceId ?? "unknown";
const typeAttr = block.blockAttributes.find((a) => a.name === "type");
if (typeAttr === void 0) {
const inferredKind = classifyEnumMemberType(block);
if (inferredKind === null || ctx.enumInferenceCodecs === void 0) {
ctx.diagnostics?.push({
code: "PSL_ENUM_CANNOT_INFER_TYPE",
message: `cannot infer @@type for enum "${block.name}"; add an explicit @@type(...)`,
sourceId,
span: block.span
});
return;
}
return {
codecId: ctx.enumInferenceCodecs[inferredKind],
codecSpan: block.span
};
}
const rawCodecArg = typeAttr.args[0]?.value;
const codecId = rawCodecArg?.startsWith("\"") && rawCodecArg.endsWith("\"") && rawCodecArg.length >= 2 ? rawCodecArg.slice(1, -1) : void 0;
if (codecId === void 0) {
ctx.diagnostics?.push({
code: "PSL_ENUM_MISSING_TYPE",
message: `enum "${block.name}" @@type attribute must have a quoted codec id argument`,
sourceId,
span: typeAttr.span
});
return;
}
return {
codecId,
codecSpan: typeAttr.args[0]?.span ?? typeAttr.span
};
}
function isAuthoringArgRef(value) {
if (typeof value !== "object" || value === null || value.kind !== "arg") return false;
const { index, path } = value;
if (typeof index !== "number" || !Number.isInteger(index) || index < 0) return false;
if (path !== void 0 && (!Array.isArray(path) || path.some((s) => typeof s !== "string"))) return false;
return true;
}
function isAuthoringTemplateRecord(value) {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
function isAuthoringTypeConstructorDescriptor(value) {
return "kind" in value && value.kind === "typeConstructor";
}
function isAuthoringFieldPresetDescriptor(value) {
return "kind" in value && value.kind === "fieldPreset";
}
function isAuthoringEntityTypeDescriptor(value) {
return "kind" in value && value.kind === "entity";
}
function isAuthoringPslBlockDescriptor(value) {
return "kind" in value && value.kind === "pslBlock";
}
function isAuthoringModelAttributeDescriptor(value) {
return "kind" in value && value.kind === "modelAttribute";
}
/**
* Returns true when `namespace` is a non-leaf key in `contributions.field`.
*
* `AuthoringFieldNamespace` permits a leaf descriptor at any depth — including
* the root — so a top-level `field: { Foo: { kind: 'fieldPreset', ... } }`
* registration must NOT be treated as a "namespace" with sub-paths. Callers
* use this predicate to gate dot-namespaced lookups (e.g. PSL `@Foo.bar`).
*/
function hasRegisteredFieldNamespace(contributions, namespace) {
if (contributions?.field === void 0 || !Object.hasOwn(contributions.field, namespace)) return false;
const value = contributions.field[namespace];
return value !== void 0 && !isAuthoringFieldPresetDescriptor(value);
}
function isCopyableNamespaceObject(value) {
if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
const proto = Object.getPrototypeOf(value);
return proto === Object.prototype || proto === null;
}
/**
* Deep structural check run only at the composition boundary (the merge and
* collect walkers) to classify a raw namespace-tree node as a leaf descriptor.
* A node counts as a leaf iff its `kind` matches `descriptorKind` AND it
* carries that kind's required fields.
*
* This is boundary validation over `unknown`, NOT a type-predicate: the four
* exported `isAuthoring*Descriptor` predicates deliberately narrow on `kind`
* alone and trust the static types. The walkers, by contrast, also receive
* type-bypassing packs (`as unknown as never` in tests, untyped JS at runtime)
* whose descriptor-shaped-but-incomplete nodes must be rejected rather than
* silently treated as sub-namespaces — so the well-formedness check lives here.
*/
function isWellFormedDescriptor(value, descriptorKind) {
if (typeof value !== "object" || value === null) return false;
if (!("kind" in value) || value.kind !== descriptorKind) return false;
switch (descriptorKind) {
case "typeConstructor":
case "fieldPreset": {
if (!("output" in value)) return false;
const output = value.output;
return typeof output === "object" && output !== null;
}
case "entity": {
if (!("discriminator" in value) || typeof value.discriminator !== "string") return false;
if (value.discriminator.length === 0) return false;
if (!("output" in value)) return false;
const output = value.output;
if (typeof output !== "object" || output === null) return false;
const factory = "factory" in output ? output.factory : void 0;
const template = "template" in output ? output.template : void 0;
return typeof factory === "function" || template !== void 0;
}
case "pslBlock": {
if (!("keyword" in value) || typeof value.keyword !== "string" || value.keyword.length === 0) return false;
if (!("discriminator" in value) || typeof value.discriminator !== "string" || value.discriminator.length === 0) return false;
if (!("name" in value)) return false;
const name = value.name;
if (typeof name !== "object" || name === null) return false;
if (!("required" in name) || typeof name.required !== "boolean") return false;
if (!("parameters" in value)) return false;
const parameters = value.parameters;
return typeof parameters === "object" && parameters !== null && !Array.isArray(parameters);
}
case "modelAttribute":
if (!("attribute" in value) || typeof value.attribute !== "string" || value.attribute.length === 0) return false;
if (!("spec" in value)) return false;
return "lower" in value && typeof value.lower === "function";
default: return false;
}
}
function deepCopyNamespace(source, descriptorKind) {
const copy = {};
for (const [key, value] of Object.entries(source)) copy[key] = isCopyableNamespaceObject(value) && !isWellFormedDescriptor(value, descriptorKind) ? deepCopyNamespace(value, descriptorKind) : value;
return copy;
}
/**
* Merges `source` into `target` recursively at the descriptor-namespace
* level. `descriptorKind` is the `kind` value ('typeConstructor',
* 'fieldPreset', 'entity', or 'pslBlock') that identifies a descriptor
* (terminal merge point; same-path registrations across components are
* reported as duplicates) as opposed to a sub-namespace (recursion target).
*
* Path segments are validated against prototype-pollution names
* (`__proto__`, `constructor`, `prototype`). A value that is neither a
* recognized leaf nor a plain object — e.g. a malformed descriptor
* where the canonical leaf guard rejected it for missing `output` —
* is reported as an invalid contribution rather than recursed into,
* which would either silently mangle state or infinite-loop on
* primitive properties.
*
* Within-registry duplicate detection is this walker's job;
* cross-registry detection runs separately via
* `assertNoCrossRegistryCollisions` after merging completes.
*/
function mergeAuthoringNamespaces(target, source, path, descriptorKind, label) {
const assertSafePath = (currentPath) => {
const blockedSegment = currentPath.find((segment) => segment === "__proto__" || segment === "constructor" || segment === "prototype");
if (blockedSegment) throw new Error(`Invalid authoring ${label} helper "${currentPath.join(".")}". Helper path segments must not use "${blockedSegment}".`);
};
for (const [key, sourceValue] of Object.entries(source)) {
const currentPath = [...path, key];
assertSafePath(currentPath);
const hasExistingValue = Object.hasOwn(target, key);
const existingValue = hasExistingValue ? target[key] : void 0;
if (!hasExistingValue) {
target[key] = isCopyableNamespaceObject(sourceValue) && !isWellFormedDescriptor(sourceValue, descriptorKind) ? deepCopyNamespace(sourceValue, descriptorKind) : sourceValue;
continue;
}
const existingIsLeaf = isWellFormedDescriptor(existingValue, descriptorKind);
const sourceIsLeaf = isWellFormedDescriptor(sourceValue, descriptorKind);
if (existingIsLeaf || sourceIsLeaf) throw new Error(`Duplicate authoring ${label} helper "${currentPath.join(".")}". Helper names must be unique across composed packs.`);
if (!isCopyableNamespaceObject(existingValue) || !isCopyableNamespaceObject(sourceValue)) throw new Error(`Invalid authoring ${label} helper "${currentPath.join(".")}". Expected a sub-namespace object or a recognized descriptor; received a malformed value.`);
mergeAuthoringNamespaces(existingValue, sourceValue, currentPath, descriptorKind, label);
}
}
function collectDescriptorPaths(namespace, isLeaf, path = []) {
const paths = [];
for (const [key, value] of Object.entries(namespace)) {
const currentPath = [...path, key];
if (isLeaf(value)) {
paths.push(currentPath.join("."));
continue;
}
if (typeof value === "object" && value !== null && !Array.isArray(value)) paths.push(...collectDescriptorPaths(value, isLeaf, currentPath));
}
return paths;
}
function collectDescriptorEntries(namespace, isLeaf, descriptorKind, label, path = []) {
const entries = [];
for (const [key, value] of Object.entries(namespace)) {
const currentPath = [...path, key];
if (isLeaf(value)) {
if (!isWellFormedDescriptor(value, descriptorKind)) throw new Error(`Malformed authoring ${label} contribution at "${currentPath.join(".")}". The value carries descriptor keys (kind/keyword/discriminator) but does not satisfy the ${label} descriptor shape. Fix the contribution so it is a complete descriptor, or remove the stray keys if it was meant to be a sub-namespace.`);
if (value.discriminator.length > 0) entries.push({
path: currentPath.join("."),
discriminator: value.discriminator
});
continue;
}
if (typeof value === "object" && value !== null && !Array.isArray(value)) {
const record = blindCast(value);
if ((record["kind"] !== void 0 || record["keyword"] !== void 0 || record["discriminator"] !== void 0) && !isLeaf(value)) {
const hasKind = record["kind"] === "pslBlock";
const hasKeyword = typeof record["keyword"] === "string";
const hasDiscriminator = typeof record["discriminator"] === "string";
if (hasKind || hasKeyword && hasDiscriminator) throw new Error(`Malformed authoring ${label} contribution at "${currentPath.join(".")}". The value carries descriptor keys (kind/keyword/discriminator) but does not satisfy the ${label} descriptor shape. Fix the contribution so it is a complete descriptor, or remove the stray keys if it was meant to be a sub-namespace.`);
}
entries.push(...collectDescriptorEntries(value, isLeaf, descriptorKind, label, currentPath));
}
}
return entries;
}
/**
* Throws when two or more entries in the same namespace share a key. A
* duplicate key makes dispatch ambiguous — the caller's lookup dispatches by
* this key, so one entry would silently shadow the other. Catch duplicates
* before building any dispatch map.
*
* `label` (e.g. `'pslBlock'`, `'entityType'`) names which namespace the
* duplicate was found in and is carried in the structured error metadata;
* the key itself is always called `key` in both the message and the
* metadata, since what it semantically represents (a discriminator for
* `entityType`, the parser's dispatch keyword for `pslBlock`) is the
* caller's concern, not this function's.
*/
function assertUniqueDiscriminators(entries, label) {
const seen = /* @__PURE__ */ new Map();
for (const { path, discriminator: key } of entries) {
const existing = seen.get(key);
if (existing !== void 0) throw runtimeError("RUNTIME.DUPLICATE_AUTHORING_DISCRIMINATOR", `Duplicate ${label} key "${key}" registered at both "${existing}" and "${path}". Each ${label} contribution must use a unique key.`, {
label,
key,
existingPath: existing,
path
});
seen.set(key, path);
}
}
function collectPslBlockDescriptorEntries(namespace, path = []) {
const entries = [];
for (const [key, value] of Object.entries(namespace)) {
const currentPath = [...path, key];
if (isAuthoringPslBlockDescriptor(value)) {
if (!isWellFormedDescriptor(value, "pslBlock")) throw new Error(`Malformed authoring pslBlock contribution at "${currentPath.join(".")}". The value carries descriptor keys (kind/keyword/discriminator) but does not satisfy the pslBlock descriptor shape. Fix the contribution so it is a complete descriptor, or remove the stray keys if it was meant to be a sub-namespace.`);
entries.push({
path: currentPath.join("."),
discriminator: value.discriminator,
keyword: value.keyword
});
continue;
}
if (typeof value === "object" && value !== null && !Array.isArray(value)) {
const record = blindCast(value);
const hasKind = record["kind"] === "pslBlock";
const hasKeyword = typeof record["keyword"] === "string";
const hasDiscriminator = typeof record["discriminator"] === "string";
if (hasKind || hasKeyword && hasDiscriminator) throw new Error(`Malformed authoring pslBlock contribution at "${currentPath.join(".")}". The value carries descriptor keys (kind/keyword/discriminator) but does not satisfy the pslBlock descriptor shape. Fix the contribution so it is a complete descriptor, or remove the stray keys if it was meant to be a sub-namespace.`);
entries.push(...collectPslBlockDescriptorEntries(value, currentPath));
}
}
return entries;
}
/**
* Every `pslBlockDescriptors` entry requires a matching `entityTypes` factory
* with the same discriminator. An `entityTypes` factory may stand alone (e.g.
* `enum`, reachable from the TypeScript builder without any PSL block).
*
* Uniqueness for pslBlock entries is keyed on **keyword**, not discriminator:
* several keywords (e.g. `policy_select`/`policy_insert`) may legitimately
* share one discriminator, routing to the same `entityTypes` factory and the
* same `entries[discriminator]` slot — that N:1 shape is exactly what lets
* one entity kind be authored through several PSL keywords. What must stay
* unique is the keyword itself, since that's what the parser dispatches on.
*/
function assertPslBlocksHaveFactories(entityTypeNamespace, pslBlockNamespace) {
const blockEntries = collectPslBlockDescriptorEntries(pslBlockNamespace);
const entityEntries = collectDescriptorEntries(entityTypeNamespace, isAuthoringEntityTypeDescriptor, "entity", "entityType");
assertUniqueDiscriminators(blockEntries.map((entry) => ({
path: entry.path,
discriminator: entry.keyword
})), "pslBlock");
assertUniqueDiscriminators(entityEntries, "entityType");
const entityDiscriminators = new Set(entityEntries.map((entry) => entry.discriminator));
for (const block of blockEntries) if (!entityDiscriminators.has(block.discriminator)) throw new Error(`Incomplete extension contribution: pslBlock helper "${block.path}" registers discriminator "${block.discriminator}" but no entityType contribution shares that discriminator. An extension-contributed PSL block requires a matching entityType factory so the parsed AST node can lower to an IR class instance; add an entityType helper with discriminator "${block.discriminator}".`);
}
function collectModelAttributeEntries(namespace, path = []) {
const entries = [];
for (const [key, value] of Object.entries(namespace)) {
const currentPath = [...path, key];
if (isAuthoringModelAttributeDescriptor(value)) {
if (!isWellFormedDescriptor(value, "modelAttribute")) throw new Error(`Malformed authoring modelAttribute contribution at "${currentPath.join(".")}". The value carries descriptor keys (kind/attribute) but does not satisfy the modelAttribute descriptor shape. Fix the contribution so it is a complete descriptor, or remove the stray keys if it was meant to be a sub-namespace.`);
entries.push({
path: currentPath.join("."),
discriminator: value.attribute
});
continue;
}
if (typeof value === "object" && value !== null && !Array.isArray(value)) {
const record = blindCast(value);
if (typeof record["attribute"] === "string" && "spec" in record) throw new Error(`Malformed authoring modelAttribute contribution at "${currentPath.join(".")}". The value carries descriptor keys (kind/attribute) but does not satisfy the modelAttribute descriptor shape. Fix the contribution so it is a complete descriptor, or remove the stray keys if it was meant to be a sub-namespace.`);
entries.push(...collectModelAttributeEntries(value, currentPath));
}
}
return entries;
}
/**
* Throws when two modelAttribute contributions — at any paths, even
* different ones — claim the same bare `@@` attribute name. The family
* interpreter dispatches by attribute name, not by registration path, so
* two descriptors claiming the same name would have one silently shadow
* the other.
*/
function assertUniqueModelAttributeNames(entries) {
const seen = /* @__PURE__ */ new Map();
for (const { path, discriminator: attribute } of entries) {
const existing = seen.get(attribute);
if (existing !== void 0) throw new Error(`Duplicate modelAttribute "${attribute}" registered at both "${existing}" and "${path}". Each modelAttribute contribution must claim a unique attribute name.`);
seen.set(attribute, path);
}
}
function assertNoCrossRegistryCollisions(typeNamespace, fieldNamespace, entityTypeNamespace = {}, pslBlockNamespace = {}, modelAttributeNamespace = {}) {
const typePaths = new Set(collectDescriptorPaths(typeNamespace, isAuthoringTypeConstructorDescriptor));
const fieldPaths = new Set(collectDescriptorPaths(fieldNamespace, isAuthoringFieldPresetDescriptor));
const entityPaths = new Set(collectDescriptorPaths(entityTypeNamespace, isAuthoringEntityTypeDescriptor));
const ambiguityHint = "Register each path in only one of authoringContributions.field / authoringContributions.type / authoringContributions.entityTypes.";
for (const fieldPath of fieldPaths) if (typePaths.has(fieldPath)) throw new Error(`Ambiguous authoring registry path "${fieldPath}". The same path is registered as both a type constructor and a field preset; PSL resolution would be ambiguous. ${ambiguityHint}`);
for (const entityPath of entityPaths) if (typePaths.has(entityPath) || fieldPaths.has(entityPath)) throw new Error(`Ambiguous authoring registry path "${entityPath}". The same path is registered as an entity contribution AND as a type constructor or field preset; PSL resolution would be ambiguous. ${ambiguityHint}`);
assertPslBlocksHaveFactories(entityTypeNamespace, pslBlockNamespace);
assertUniqueModelAttributeNames(collectModelAttributeEntries(modelAttributeNamespace));
}
function resolveAuthoringTemplateValue(template, args) {
if (template === void 0) return;
if (isAuthoringArgRef(template)) {
let value = args[template.index];
for (const segment of template.path ?? []) {
if (!isAuthoringTemplateRecord(value) || !Object.hasOwn(value, segment)) {
value = void 0;
break;
}
value = value[segment];
}
if (value === void 0 && template.default !== void 0) return resolveAuthoringTemplateValue(template.default, args);
return value;
}
if (Array.isArray(template)) return template.map((value) => resolveAuthoringTemplateValue(value, args));
if (typeof template === "object" && template !== null) {
const resolved = {};
for (const [key, value] of Object.entries(template)) {
const resolvedValue = resolveAuthoringTemplateValue(value, args);
if (resolvedValue !== void 0) resolved[key] = resolvedValue;
}
return resolved;
}
return template;
}
function validateAuthoringArgument(descriptor, value, path) {
if (value === void 0) {
if (descriptor.optional) return;
throw new Error(`Missing required authoring helper argument at ${path}`);
}
if (descriptor.kind === "string") {
if (typeof value !== "string") throw new Error(`Authoring helper argument at ${path} must be a string`);
return;
}
if (descriptor.kind === "boolean") {
if (typeof value !== "boolean") throw new Error(`Authoring helper argument at ${path} must be a boolean`);
return;
}
if (descriptor.kind === "stringArray") {
if (!Array.isArray(value)) throw new Error(`Authoring helper argument at ${path} must be an array of strings`);
for (const entry of value) if (typeof entry !== "string") throw new Error(`Authoring helper argument at ${path} must be an array of strings`);
return;
}
if (descriptor.kind === "object") {
if (typeof value !== "object" || value === null || Array.isArray(value)) throw new Error(`Authoring helper argument at ${path} must be an object`);
const input = value;
const expectedKeys = new Set(Object.keys(descriptor.properties));
for (const key of Object.keys(input)) if (!expectedKeys.has(key)) throw new Error(`Authoring helper argument at ${path} contains unknown property "${key}"`);
for (const [key, propertyDescriptor] of Object.entries(descriptor.properties)) validateAuthoringArgument(propertyDescriptor, input[key], `${path}.${key}`);
return;
}
if (typeof value !== "number" || Number.isNaN(value)) throw new Error(`Authoring helper argument at ${path} must be a number`);
if (descriptor.integer && !Number.isInteger(value)) throw new Error(`Authoring helper argument at ${path} must be an integer`);
if (descriptor.minimum !== void 0 && value < descriptor.minimum) throw new Error(`Authoring helper argument at ${path} must be >= ${descriptor.minimum}, received ${value}`);
if (descriptor.maximum !== void 0 && value > descriptor.maximum) throw new Error(`Authoring helper argument at ${path} must be <= ${descriptor.maximum}, received ${value}`);
}
function validateAuthoringHelperArguments(helperPath, descriptors, args) {
const expected = descriptors ?? [];
const minimumArgs = expected.reduce((count, descriptor, index) => descriptor.optional ? count : index + 1, 0);
if (args.length < minimumArgs || args.length > expected.length) throw new Error(`${helperPath} expects ${minimumArgs === expected.length ? expected.length : `${minimumArgs}-${expected.length}`} argument(s), received ${args.length}`);
expected.forEach((descriptor, index) => {
validateAuthoringArgument(descriptor, args[index], `${helperPath}[${index}]`);
});
}
function resolveAuthoringStorageTypeTemplate(template, args) {
const nativeType = resolveAuthoringTemplateValue(template.nativeType, args);
if (typeof nativeType !== "string") throw new Error(`Resolved authoring nativeType must be a string for codec "${template.codecId}", received ${String(nativeType)}`);
const typeParams = template.typeParams === void 0 ? void 0 : resolveAuthoringTemplateValue(template.typeParams, args);
if (typeParams !== void 0 && !isAuthoringTemplateRecord(typeParams)) throw new Error(`Resolved authoring typeParams must be an object for codec "${template.codecId}", received ${String(typeParams)}`);
return {
codecId: template.codecId,
nativeType,
...ifDefined("typeParams", typeParams)
};
}
function resolveAuthoringColumnDefaultTemplate(template, args) {
if (template.kind === "literal") {
const value = resolveAuthoringTemplateValue(template.value, args);
if (value === void 0) throw new Error("Resolved authoring literal default must not be undefined");
if (!isColumnDefaultLiteralInputValue(value)) throw new Error(`Resolved authoring literal default must be a JSON-serializable value or Date, received ${String(value)}`);
return {
kind: "literal",
value
};
}
const expression = resolveAuthoringTemplateValue(template.expression, args);
if (expression === void 0 || typeof expression === "object" && expression !== null) throw new Error(`Resolved authoring function default expression must resolve to a primitive, received ${String(expression)}`);
return {
kind: "function",
expression: String(expression)
};
}
function resolveExecutionMutationDefaultPhase(phase, template, args) {
const value = resolveAuthoringTemplateValue(template, args);
if (!isExecutionMutationDefaultValue(value)) throw new Error(`Authoring preset executionDefaults.${phase} did not resolve to a valid generator descriptor (kind: 'generator', id: string).`);
return value;
}
function resolveAuthoringExecutionDefaultsTemplate(template, args) {
return {
...ifDefined("onCreate", template.onCreate !== void 0 ? resolveExecutionMutationDefaultPhase("onCreate", template.onCreate, args) : void 0),
...ifDefined("onUpdate", template.onUpdate !== void 0 ? resolveExecutionMutationDefaultPhase("onUpdate", template.onUpdate, args) : void 0)
};
}
function instantiateAuthoringTypeConstructor(descriptor, args) {
return resolveAuthoringStorageTypeTemplate(descriptor.output, args);
}
function instantiateAuthoringEntityType(helperPath, descriptor, args, ctx) {
if ("factory" in descriptor.output) {
const input = args[0];
return blindCast(descriptor.output.factory)(input, ctx);
}
validateAuthoringHelperArguments(helperPath, descriptor.args, args);
return blindCast(resolveAuthoringTemplateValue(descriptor.output.template, args));
}
function instantiateAuthoringFieldPreset(descriptor, args) {
return {
descriptor: resolveAuthoringStorageTypeTemplate(descriptor.output, args),
nullable: descriptor.output.nullable ?? false,
...ifDefined("default", descriptor.output.default !== void 0 ? resolveAuthoringColumnDefaultTemplate(descriptor.output.default, args) : void 0),
...ifDefined("executionDefaults", descriptor.output.executionDefaults !== void 0 ? resolveAuthoringExecutionDefaultsTemplate(descriptor.output.executionDefaults, args) : void 0),
id: descriptor.output.id ?? false,
unique: descriptor.output.unique ?? false
};
}
//#endregion
export { instantiateAuthoringFieldPreset as a, isAuthoringEntityTypeDescriptor as c, isAuthoringPslBlockDescriptor as d, isAuthoringTypeConstructorDescriptor as f, validateAuthoringHelperArguments as g, resolveEnumCodecId as h, instantiateAuthoringEntityType as i, isAuthoringFieldPresetDescriptor as l, resolveAuthoringTemplateValue as m, classifyEnumMemberType as n, instantiateAuthoringTypeConstructor as o, mergeAuthoringNamespaces as p, hasRegisteredFieldNamespace as r, isAuthoringArgRef as s, assertNoCrossRegistryCollisions as t, isAuthoringModelAttributeDescriptor as u };
//# sourceMappingURL=framework-authoring-Bz_vaNZw.mjs.map

Sorry, the diff of this file is too big to display

import { r as CodecLookup } from "./codec-types-BH2f2dg1.mjs";
import { ColumnDefault, ExecutionMutationDefaultPhases } from "@prisma-next/contract/types";
import { Type } from "arktype";
//#region src/shared/psl-extension-block.d.ts
/**
* Shape-only types for the PSL source-position primitives, diagnostic
* codes, extension-block descriptor vocabulary, and the uniform
* extension-block AST node base.
*
* These live in the shared plane so an extension's authoring descriptor
* (`AuthoringPslBlockDescriptor` in `framework-authoring`) can reference
* them without crossing the shared → migration-plane boundary. The
* migration-plane `psl-ast.ts` re-exports everything here for consumers
* that import PSL AST types from the control entrypoint.
*/
interface PslPosition {
readonly offset: number;
readonly line: number;
readonly column: number;
}
interface PslSpan {
readonly start: PslPosition;
readonly end: PslPosition;
}
type PslDiagnosticCode = 'PSL_UNTERMINATED_BLOCK' | 'PSL_UNSUPPORTED_TOP_LEVEL_BLOCK' | 'PSL_INVALID_NAMESPACE_BLOCK' | 'PSL_INVALID_ATTRIBUTE_SYNTAX' | 'PSL_INVALID_MODEL_MEMBER' | 'PSL_UNSUPPORTED_MODEL_ATTRIBUTE' | 'PSL_UNSUPPORTED_FIELD_ATTRIBUTE' | 'PSL_INVALID_RELATION_ATTRIBUTE' | 'PSL_INVALID_REFERENTIAL_ACTION' | 'PSL_INVALID_DEFAULT_VALUE' | 'PSL_INVALID_ENUM_MEMBER' | 'PSL_INVALID_TYPES_MEMBER' | 'PSL_INVALID_QUALIFIED_TYPE'
/**
* A qualified name (e.g. a dotted type or attribute reference) is structurally
* invalid, such as an over-qualified or trailing-separator name.
*/
| 'PSL_INVALID_QUALIFIED_NAME'
/**
* A reserved declaration keyword (`model`/`enum`/`namespace`/`type`) that
* committed the declaration kind on the keyword alone but is missing its name
* and/or opening brace. The recursive-descent parser produces a best-effort
* typed node for the malformed header and reports this code rather than
* `PSL_UNSUPPORTED_TOP_LEVEL_BLOCK`, which is reserved for a genuinely unknown
* top-level keyword.
*/
| 'PSL_INVALID_DECLARATION'
/**
* A malformed line inside an extension-contributed top-level block body, or
* a structurally invalid element inside a `list` parameter value.
*
* Replaces the overloaded `PSL_UNSUPPORTED_TOP_LEVEL_BLOCK` code that the
* generic framework parser previously used for these two parse-error sites
* inside extension blocks — keeping `PSL_UNSUPPORTED_TOP_LEVEL_BLOCK` for
* its original meaning (an unknown keyword at the top level) and giving
* extension-block parse errors their own code.
*/
| 'PSL_INVALID_EXTENSION_BLOCK_MEMBER'
/**
* A malformed JS-like object literal `{ key: value, … }` in value/argument
* position — a field missing its `:`, a field missing its value, or an
* unterminated `{`. The recursive-descent parser still produces a best-effort
* `ObjectLiteralExpr` node (preserving the lossless round-trip) and reports
* this code anchored on the offending token.
*/
| 'PSL_INVALID_OBJECT_LITERAL'
/**
* A string literal with no closing quote — the tokenizer stops the literal at
* a newline or at EOF when no terminating `"` is found, and the
* recursive-descent parser still consumes the token (preserving the lossless
* round-trip) but reports this code anchored on the string token's span.
*/
| 'PSL_UNTERMINATED_STRING'
/**
* An unknown parameter key in an extension-contributed block — a key present
* in the source block but absent from the descriptor's `parameters` map.
*/
| 'PSL_EXTENSION_UNKNOWN_PARAMETER'
/**
* A required parameter declared in the descriptor is absent from the parsed block.
*/
| 'PSL_EXTENSION_MISSING_REQUIRED_PARAMETER'
/**
* An `option`-kind parameter value is not one of the allowed tokens listed
* in the descriptor's `values` array.
*/
| 'PSL_EXTENSION_OPTION_OUT_OF_SET'
/**
* A `value`-kind parameter's raw text is not a valid JSON literal, or the
* parsed JSON value was rejected by the codec's `decodeJson` method, or the
* codec id is not registered in the lookup.
*/
| 'PSL_EXTENSION_INVALID_VALUE'
/**
* A `ref`-kind parameter identifier does not resolve to a declared entity of
* the required `refKind` within the declared scope.
*/
| 'PSL_EXTENSION_UNRESOLVED_REF'
/**
* A parameter key appears more than once in an extension block body.
* The first occurrence is kept; subsequent occurrences emit this diagnostic.
*/
| 'PSL_EXTENSION_DUPLICATE_PARAMETER'
/**
* A `@@`-prefixed block-attribute line inside an extension block has invalid syntax.
*/
| 'PSL_INVALID_EXTENSION_BLOCK_ATTRIBUTE'
/**
* Duplicate scopes are top level, namespace body, or block fields; diagnostics
* are first-wins and anchored on later name spans.
*/
| 'PSL_DUPLICATE_DECLARATION';
/**
* Descriptor vocabulary for a single parameter on a declared block.
*
* Four kinds:
* - `ref` — the parameter value is an identifier that must resolve to a
* declared entity of `refKind` within the declared `scope`.
* - `value` — the parameter value is a PSL literal parsed and printed
* through the codec identified by `codecId`.
* - `option` — the parameter value is one of the literal tokens in `values`.
* Not a codec; not persisted data. A closed authoring-time constraint only.
* - `list` — a bracketed list whose elements each match the `of` descriptor.
*/
type PslBlockParam = PslBlockParamRef | PslBlockParamValue | PslBlockParamOption | PslBlockParamList;
interface PslBlockParamRef {
readonly kind: 'ref';
readonly refKind: string;
readonly scope: 'same-namespace' | 'same-space' | 'cross-space';
readonly required?: boolean;
}
interface PslBlockParamValue {
readonly kind: 'value';
readonly codecId: string;
readonly required?: boolean;
}
interface PslBlockParamOption {
readonly kind: 'option';
readonly values: readonly string[];
readonly required?: boolean;
}
interface PslBlockParamList {
readonly kind: 'list';
readonly of: PslBlockParam;
readonly required?: boolean;
}
/**
* The parsed representation of a single parameter value on a uniform
* extension-block AST node. Mirrors the `PslBlockParam` descriptor
* vocabulary, plus `bare` for keyonly entries:
*
* - `ref` → `PslExtensionBlockParamRef` — a raw identifier string
* (resolution runs in the validator, not the parser).
* - `value` → `PslExtensionBlockParamScalarValue` — a raw PSL literal string
* (codec validation runs in the validator).
* - `option` → `PslExtensionBlockParamOption` — the chosen token.
* - `list` → `PslExtensionBlockParamList` — ordered list of the above.
* - `bare` → `PslExtensionBlockParamBare` — a bare identifier line with no
* `= value` (e.g. `Low` in an enum block). The name is the key in
* `parameters`; the interpreting consumer decides the default value.
*
* These shapes are intentionally minimal. The validator and lowering refine
* and consume them; the generic framework parser produces them.
*/
type PslExtensionBlockParamValue = PslExtensionBlockParamRef | PslExtensionBlockParamScalarValue | PslExtensionBlockParamOption | PslExtensionBlockParamList | PslExtensionBlockParamBare;
interface PslExtensionBlockParamRef {
readonly kind: 'ref';
readonly identifier: string;
readonly span: PslSpan;
}
interface PslExtensionBlockParamScalarValue {
readonly kind: 'value';
readonly raw: string;
readonly span: PslSpan;
}
interface PslExtensionBlockParamOption {
readonly kind: 'option';
readonly token: string;
readonly span: PslSpan;
}
interface PslExtensionBlockParamList {
readonly kind: 'list';
readonly items: readonly PslExtensionBlockParamValue[];
readonly span: PslSpan;
}
/**
* A bare identifier line inside an extension block — a key with no `= value`.
* Emitted when a line matches `/^[A-Za-z_]\w*$/` with no assignment. The
* consumer decides what default value (if any) to apply.
*/
interface PslExtensionBlockParamBare {
readonly kind: 'bare';
readonly span: PslSpan;
}
/**
* A positional argument on a block attribute, e.g. the `"pg/text@1"` in
* `@@type("pg/text@1")`.
*/
interface PslExtensionBlockAttributeArg {
readonly kind: 'positional';
readonly value: string;
readonly span: PslSpan;
}
/**
* A `@@`-prefixed block-level attribute parsed inside an extension block,
* e.g. `@@type("pg/text@1")`. Block attributes are captured generically
* — the parser does not validate attribute names or argument shapes; that
* is a concern of the block's interpreter.
*/
interface PslExtensionBlockAttribute {
readonly name: string;
readonly args: readonly PslExtensionBlockAttributeArg[];
readonly span: PslSpan;
}
/**
* Base shape for a uniform extension-contributed top-level PSL block
* node, as produced by the generic framework parser and consumed by the
* validator, printer, and lowering factory.
*
* - `kind` is the routing discriminant, equal to the descriptor's
* `discriminator`. The framework parser sets this to
* `descriptor.discriminator` for every block it parses. Several keywords
* may share one discriminator (e.g. `policy_select`/`policy_insert` both
* route to `kind: 'policy'`) — `kind` identifies the entity/storage kind,
* not the source syntax.
* - `keyword` is the source PSL keyword the block was declared with
* (`policy_select`, `policy_insert`, …) — the parse-dispatch identity.
* Distinct from `kind` precisely when a discriminator is shared by more
* than one keyword; a lowering factory that contributes several keywords
* under one discriminator reads `keyword` to tell its blocks apart, and
* the printer re-emits each block under its own `keyword` regardless of
* how many other keywords share its `kind`.
* - `name` is the block's declared name (the identifier after the keyword).
* - `parameters` is the descriptor-driven parameter map. Keys are
* parameter names from the descriptor; values are the parsed parameter
* representations. Only parameters present in the source are included
* — absence of a required parameter is a validator concern, not a
* parser concern. Insertion order is preserved; the first occurrence of a
* duplicate key is retained and subsequent occurrences emit
* `PSL_EXTENSION_DUPLICATE_PARAMETER`.
* - `blockAttributes` are `@@`-prefixed attribute lines inside the block, in
* declaration order. Captured generically — names and args are not validated
* by the parser.
* - `span` covers the full block from keyword to closing brace.
*/
interface PslExtensionBlock {
readonly kind: string;
/**
* The block's parse identity — the source PSL keyword it was declared
* with. `kind`/`discriminator` is its storage identity; several keywords
* can share one. E.g. the five `policy_*` keywords all lower to the
* `policy` entity kind.
*/
readonly keyword: string;
readonly name: string;
readonly parameters: Record<string, PslExtensionBlockParamValue>;
readonly blockAttributes: readonly PslExtensionBlockAttribute[];
readonly span: PslSpan;
}
//#endregion
//#region src/shared/framework-authoring.d.ts
type AuthoringArgRef = {
readonly kind: 'arg';
readonly index: number;
readonly path?: readonly string[];
readonly default?: AuthoringTemplateValue;
};
type AuthoringTemplateValue = string | number | boolean | null | AuthoringArgRef | readonly AuthoringTemplateValue[] | {
readonly [key: string]: AuthoringTemplateValue;
};
interface AuthoringArgumentDescriptorCommon {
readonly name?: string;
readonly optional?: boolean;
}
type AuthoringArgumentDescriptor = AuthoringArgumentDescriptorCommon & ({
readonly kind: 'string';
} | {
readonly kind: 'boolean';
} | {
readonly kind: 'number';
readonly integer?: boolean;
readonly minimum?: number;
readonly maximum?: number;
} | {
readonly kind: 'stringArray';
} | {
readonly kind: 'object';
readonly properties: Record<string, AuthoringArgumentDescriptor>;
});
interface AuthoringStorageTypeTemplate {
readonly codecId: string;
/**
* Optional so a type constructor whose {@link AuthoringTypeConstructorDescriptor.entityRefArg}
* names another entity can omit this template entirely — its output for
* that case is derived by the codec at `codecId`, not by resolving a
* literal here. Every other consumer of this shape (field presets, plain
* type constructors) always supplies it.
*/
readonly nativeType?: AuthoringTemplateValue;
readonly typeParams?: Record<string, AuthoringTemplateValue>;
}
/**
* Declares that one positional argument of a
* {@link AuthoringTypeConstructorDescriptor} call names another entity
* parsed from the same document, rather than carrying a literal value (e.g.
* `pg.enum(AalLevel)` naming a `native_enum` entity). `index` is the
* argument's position in the call; `entityKind` is the entries-slot
* discriminator the interpreter looks the named entity up under (the same
* shape {@link AuthoringEntityTypeFactoryOutput.factory} output is collected
* into, keyed by discriminator then block name).
*
* The interpreter resolves the named argument to the entity instance
* generically, driven only by this declaration — it has no target-specific
* knowledge of which type constructors carry one. Converting the resolved
* entity into the constructor's params is a separate, codec-owned concern:
* the codec descriptor registered for `output.codecId` supplies that
* conversion, not this framework type.
*/
interface AuthoringTypeConstructorEntityRef {
readonly index: number;
readonly entityKind: string;
}
interface AuthoringTypeConstructorDescriptor {
readonly kind: 'typeConstructor';
readonly args?: readonly AuthoringArgumentDescriptor[];
readonly output: AuthoringStorageTypeTemplate;
/** Present when one of this constructor's positional arguments names another document-local entity instead of carrying a literal value. Absent for ordinary literal-argument constructors. */
readonly entityRefArg?: AuthoringTypeConstructorEntityRef;
}
interface AuthoringColumnDefaultTemplateLiteral {
readonly kind: 'literal';
readonly value: AuthoringTemplateValue;
}
interface AuthoringColumnDefaultTemplateFunction {
readonly kind: 'function';
readonly expression: AuthoringTemplateValue;
}
type AuthoringColumnDefaultTemplate = AuthoringColumnDefaultTemplateLiteral | AuthoringColumnDefaultTemplateFunction;
interface AuthoringExecutionDefaultsTemplate {
readonly onCreate?: AuthoringTemplateValue;
readonly onUpdate?: AuthoringTemplateValue;
}
interface AuthoringFieldPresetOutput extends AuthoringStorageTypeTemplate {
readonly nullable?: boolean;
readonly default?: AuthoringColumnDefaultTemplate;
readonly executionDefaults?: AuthoringExecutionDefaultsTemplate;
readonly id?: boolean;
readonly unique?: boolean;
}
interface AuthoringFieldPresetDescriptor {
readonly kind: 'fieldPreset';
readonly args?: readonly AuthoringArgumentDescriptor[];
readonly output: AuthoringFieldPresetOutput;
}
type AuthoringTypeNamespace = {
readonly [name: string]: AuthoringTypeConstructorDescriptor | AuthoringTypeNamespace;
};
type AuthoringFieldNamespace = {
readonly [name: string]: AuthoringFieldPresetDescriptor | AuthoringFieldNamespace;
};
/**
* Context surfaced to entity-type factories at call time. Currently a
* placeholder — sharpened as concrete consumers (enum, namespace, …)
* discover what the factory actually needs to read (codec lookup,
* namespace registry, …).
*/
/**
* A write-only sink that a factory may push authoring-time diagnostics into.
* The concrete type pushed must be structurally compatible with whatever the
* consumer accumulates (typically `ContractSourceDiagnostic[]`); the framework
* layer deliberately does not depend on that concrete type.
*/
interface AuthoringDiagnosticSink {
push(d: {
readonly code: string;
readonly message: string;
readonly sourceId: string;
readonly span?: unknown;
}): void;
}
interface AuthoringEntityContext {
readonly family: string;
readonly target: string;
/** Codec registry available to factories that need to validate or decode values. */
readonly codecLookup?: CodecLookup;
/** Source file identifier threaded into diagnostics emitted by the factory. */
readonly sourceId?: string;
/** Push channel for authoring-time diagnostics emitted by the factory. */
readonly diagnostics?: AuthoringDiagnosticSink;
/**
* The target's default codec ids for an `enum` block that omits `@@type`.
* `text` is used when every member is a bare name or a string value;
* `int` is used when every member is an integer value. Every target pack
* populates this so `@@type` omission can be inferred consistently.
*/
readonly enumInferenceCodecs?: {
readonly text: string;
readonly int: string;
};
}
/**
* Classifies an `enum` block's members (before codec decoding, which needs
* the codec chosen first) into which default codec an omitted `@@type`
* should resolve to:
*
* - every member is `bare`, or a `value` whose raw JSON is a string → `'text'`
* - every member is a `value` whose raw JSON is an integer → `'int'`
* - anything else (float, bigint, boolean, mixed, or a `ref`/`option`/`list`
* parameter) → `null`, meaning the caller must require an explicit `@@type`.
*/
declare function classifyEnumMemberType(block: PslExtensionBlock): 'text' | 'int' | null;
/**
* Resolves the codec id for an `enum` block. When `@@type` is absent, the codec
* is inferred from the members via {@link classifyEnumMemberType}; otherwise the
* explicit `@@type("codec")` argument is parsed. Pushes the appropriate
* diagnostic and returns `undefined` when neither yields a codec. `codecSpan` is
* the span downstream codec-validation diagnostics should anchor to. Shared by
* every family's enum factory so inference and the explicit path stay identical.
*/
declare function resolveEnumCodecId(block: PslExtensionBlock, ctx: AuthoringEntityContext): {
readonly codecId: string;
readonly codecSpan: PslSpan;
} | undefined;
interface AuthoringEntityTypeTemplateOutput {
readonly template: AuthoringTemplateValue;
}
/**
* Default `Input = never` is load-bearing for pack-bag-driven type
* narrowing. Factory parameter positions are contravariant, so a pack
* literal declaring `factory: (input: DemoEntityInput) => DemoEntity`
* is only assignable to the base descriptor's factory shape if the
* base's input is `never` (the bottom of the contravariant position).
* The concrete input/output types are recovered at the helper-derivation
* site via `EntityHelperFunction<Descriptor>`'s conditional inference,
* which reads them from the pack's `as const` literal factory signature
* — the base widening does not erase the literal because `satisfies`
* does not widen the declared type.
*/
interface AuthoringEntityTypeFactoryOutput<Input = never, Output = unknown> {
readonly factory: (input: Input, ctx: AuthoringEntityContext) => Output;
}
interface AuthoringEntityTypeDescriptor<Input = never, Output = unknown> {
readonly kind: 'entity';
readonly discriminator: string;
readonly args?: readonly AuthoringArgumentDescriptor[];
readonly output: AuthoringEntityTypeTemplateOutput | AuthoringEntityTypeFactoryOutput<Input, Output>;
/**
* arktype schema fragment for one entry whose envelope `kind` matches
* this descriptor's {@link discriminator}. The family validator composes
* contributed fragments into the per-namespace entry schema at
* validator construction time so the structural check covers
* pack-introduced kinds without the family core hard-coding the schema.
*
* Hydration uses {@link AuthoringEntityTypeFactoryOutput.factory}
* directly — the wire shape conforms structurally to the factory's
* `Input` after `validatorSchema` validates it.
*/
readonly validatorSchema?: Type<unknown>;
}
type AuthoringEntityTypeNamespace = {
readonly [name: string]: AuthoringEntityTypeDescriptor | AuthoringEntityTypeNamespace;
};
/**
* Declarative descriptor for an extension-contributed top-level PSL block.
*
* An extension registers one of these per keyword it contributes. The
* framework owns the generic parser, validator, and printer — no
* parsing or printing code runs from the extension.
*
* - `keyword` is the PSL top-level identifier this descriptor claims
* (`policy_select`, `role`, …).
* - `discriminator` is the routing key used by the printer dispatch and
* the `entityTypes` lowering factory lookup. Convention:
* `<target-or-family>-<kind>` (`postgres-policy-select`).
* - `name.required` declares whether the block must have a name token
* after the keyword. Currently always `true` — anonymous blocks are
* not part of the closed-grammar premise — but the field is explicit
* so the type can evolve without a breaking change.
* - `parameters` maps parameter names to their value-kind descriptors
* (`ref` / `value` / `option` / `list`). The generic parser and
* validator interpret these; the extension supplies no parser or
* printer function.
*/
interface AuthoringPslBlockDescriptor {
readonly kind: 'pslBlock';
readonly keyword: string;
readonly discriminator: string;
readonly name: {
readonly required: boolean;
};
readonly parameters: Record<string, PslBlockParam>;
/**
* When `true`, the block body accepts a variadic tail of parameters beyond
* the declared set. The block body may contain: fields (model-style),
* `key = value` parameters, and `@@` attributes. With `variadicParameters`,
* bare identifiers (keys without a `= value`) and undeclared `key = value`
* pairs flow into the variadic tail — their semantics belong to the
* lowering, not the parser.
*
* A key that IS declared in `parameters` must still be supplied as
* `key = value`; a bare occurrence of a declared key is a diagnostic.
*
* When `false` (default), the validator emits `PSL_EXTENSION_UNKNOWN_PARAMETER`
* for keys absent from `parameters`.
*/
readonly variadicParameters?: boolean;
/**
* Declares that the model named by the block's ref parameter `parameter`
* must carry the bare `@@` model attribute `attribute`. The family
* interpreter enforces this generically over the whole parsed document —
* declaration order of the block and the model does not matter — and
* emits `PSL_EXTENSION_TARGET_MODEL_MISSING_ATTRIBUTE` naming the block
* and the model when the attribute is absent. A parameter that is
* missing or does not resolve to a model is not this rule's concern
* (missing-parameter and unresolved-ref diagnostics own those cases).
*/
readonly requiresModelAttribute?: {
readonly parameter: string;
readonly attribute: string;
};
}
type AuthoringPslBlockDescriptorNamespace = {
readonly [name: string]: AuthoringPslBlockDescriptor | AuthoringPslBlockDescriptorNamespace;
};
/**
* Context surfaced to a model-attribute lowering at call time: the entity
* context shared with entity-type factories, plus the declaring model's
* name, its mapped storage name (the name of the storage object the model
* maps to; which kind of object that is belongs to the family, not the
* framework), and the namespace id the lowered entity should be filed
* under.
*/
interface AuthoringModelAttributeContext extends AuthoringEntityContext {
readonly modelName: string;
readonly storageName: string;
readonly namespaceId: string;
}
/**
* What a model-attribute lowering returns when it produces an entity: `key`
* is the identity the entity is stored under within its `entries` slot
* (`entries[attribute][key]`); `entity` is the value stored there. A
* lowering that instead pushed a diagnostic through
* {@link AuthoringModelAttributeContext.diagnostics} returns `undefined` —
* the same convention {@link AuthoringEntityTypeFactoryOutput} uses.
*/
interface AuthoringModelAttributeLoweringOutput {
readonly key: string;
readonly entity: unknown;
}
/**
* Declarative descriptor for an extension-contributed `@@` model attribute.
*
* An extension registers one of these per bare attribute name it
* contributes. The framework owns the generic consult in the interpreter's
* model-attribute loop; the contribution supplies only `spec` and `lower`.
*
* - `attribute` is the bare `@@` attribute name this descriptor claims and,
* by the one-string rule, the `entries` slot its lowered entities are
* grouped under (`entries[attribute][key]`).
* - `spec` is opaque to the framework core: an ADR-231 attribute-spec kit
* `AttributeSpec<Out>` value (`modelAttribute(name, {...})` from
* `@prisma-next/psl-parser`). Framework core does not depend on
* psl-parser and never inspects this field; the family interpreter,
* which does depend on psl-parser, parses the attribute's arguments
* against it.
* - `lower` receives the parsed arguments and the declaring model's
* context, and returns the entity to file into `entries`, or `undefined`
* after pushing a diagnostic via `ctx.diagnostics`.
*
* `Out` defaults to `never` — not `unknown` — for the same contravariance
* reason documented on {@link AuthoringEntityTypeFactoryOutput}: a concrete
* pack literal's narrower `lower(parsed: ConcreteOut, ctx)` is only
* assignable to this base shape when the base parameter is the bottom type.
*/
interface AuthoringModelAttributeDescriptor<Out = never> {
readonly kind: 'modelAttribute';
readonly attribute: string;
readonly spec: unknown;
readonly lower: (parsed: Out, ctx: AuthoringModelAttributeContext) => AuthoringModelAttributeLoweringOutput | undefined;
}
type AuthoringModelAttributeDescriptorNamespace = {
readonly [name: string]: AuthoringModelAttributeDescriptor | AuthoringModelAttributeDescriptorNamespace;
};
interface AuthoringContributions {
readonly type?: AuthoringTypeNamespace;
readonly field?: AuthoringFieldNamespace;
readonly entityTypes?: AuthoringEntityTypeNamespace;
/**
* Registry of declarative block descriptors this contribution registers,
* keyed by arbitrary path segments. Each leaf is an
* {@link AuthoringPslBlockDescriptor} that claims a PSL top-level keyword.
* The framework owns the generic parser, validator, and printer; the
* contribution supplies only these declarative descriptors.
*
* Contrast with the parsed block nodes themselves, which live in a
* namespace's `entries` under their discriminator key; this field holds the
* registry of descriptors that teach the parser how to read those blocks.
*/
readonly pslBlockDescriptors?: AuthoringPslBlockDescriptorNamespace;
/**
* Registry of declarative `@@` model attribute descriptors this
* contribution registers, keyed by arbitrary path segments. Each leaf is
* an {@link AuthoringModelAttributeDescriptor} that claims a bare model
* attribute name. The framework owns the generic consult in the family
* interpreter's model-attribute loop; the contribution supplies only the
* declarative spec and the lowering.
*/
readonly modelAttributes?: AuthoringModelAttributeDescriptorNamespace;
}
declare function isAuthoringArgRef(value: unknown): value is AuthoringArgRef;
declare function isAuthoringTypeConstructorDescriptor(value: AuthoringTypeConstructorDescriptor | AuthoringTypeNamespace): value is AuthoringTypeConstructorDescriptor;
declare function isAuthoringFieldPresetDescriptor(value: AuthoringFieldPresetDescriptor | AuthoringFieldNamespace): value is AuthoringFieldPresetDescriptor;
declare function isAuthoringEntityTypeDescriptor(value: AuthoringEntityTypeDescriptor | AuthoringEntityTypeNamespace): value is AuthoringEntityTypeDescriptor;
declare function isAuthoringPslBlockDescriptor(value: AuthoringPslBlockDescriptor | AuthoringPslBlockDescriptorNamespace): value is AuthoringPslBlockDescriptor;
declare function isAuthoringModelAttributeDescriptor(value: AuthoringModelAttributeDescriptor | AuthoringModelAttributeDescriptorNamespace): value is AuthoringModelAttributeDescriptor;
/**
* Returns true when `namespace` is a non-leaf key in `contributions.field`.
*
* `AuthoringFieldNamespace` permits a leaf descriptor at any depth — including
* the root — so a top-level `field: { Foo: { kind: 'fieldPreset', ... } }`
* registration must NOT be treated as a "namespace" with sub-paths. Callers
* use this predicate to gate dot-namespaced lookups (e.g. PSL `@Foo.bar`).
*/
declare function hasRegisteredFieldNamespace(contributions: AuthoringContributions | undefined, namespace: string): boolean;
/**
* Merges `source` into `target` recursively at the descriptor-namespace
* level. `descriptorKind` is the `kind` value ('typeConstructor',
* 'fieldPreset', 'entity', or 'pslBlock') that identifies a descriptor
* (terminal merge point; same-path registrations across components are
* reported as duplicates) as opposed to a sub-namespace (recursion target).
*
* Path segments are validated against prototype-pollution names
* (`__proto__`, `constructor`, `prototype`). A value that is neither a
* recognized leaf nor a plain object — e.g. a malformed descriptor
* where the canonical leaf guard rejected it for missing `output` —
* is reported as an invalid contribution rather than recursed into,
* which would either silently mangle state or infinite-loop on
* primitive properties.
*
* Within-registry duplicate detection is this walker's job;
* cross-registry detection runs separately via
* `assertNoCrossRegistryCollisions` after merging completes.
*/
declare function mergeAuthoringNamespaces(target: Record<string, unknown>, source: Record<string, unknown>, path: readonly string[], descriptorKind: string, label: string): void;
declare function assertNoCrossRegistryCollisions(typeNamespace: AuthoringTypeNamespace, fieldNamespace: AuthoringFieldNamespace, entityTypeNamespace?: AuthoringEntityTypeNamespace, pslBlockNamespace?: AuthoringPslBlockDescriptorNamespace, modelAttributeNamespace?: AuthoringModelAttributeDescriptorNamespace): void;
declare function resolveAuthoringTemplateValue(template: AuthoringTemplateValue | undefined, args: readonly unknown[]): unknown;
declare function validateAuthoringHelperArguments(helperPath: string, descriptors: readonly AuthoringArgumentDescriptor[] | undefined, args: readonly unknown[]): void;
declare function instantiateAuthoringTypeConstructor(descriptor: AuthoringTypeConstructorDescriptor, args: readonly unknown[]): {
readonly codecId: string;
readonly nativeType: string;
readonly typeParams?: Record<string, unknown>;
};
declare function instantiateAuthoringEntityType<TOutput = unknown>(helperPath: string, descriptor: AuthoringEntityTypeDescriptor, args: readonly unknown[], ctx: AuthoringEntityContext): TOutput;
declare function instantiateAuthoringFieldPreset(descriptor: AuthoringFieldPresetDescriptor, args: readonly unknown[]): {
readonly descriptor: {
readonly codecId: string;
readonly nativeType: string;
readonly typeParams?: Record<string, unknown>;
};
readonly nullable: boolean;
readonly default?: ColumnDefault;
readonly executionDefaults?: ExecutionMutationDefaultPhases;
readonly id: boolean;
readonly unique: boolean;
};
//#endregion
export { PslExtensionBlockParamRef as $, instantiateAuthoringTypeConstructor as A, validateAuthoringHelperArguments as B, AuthoringTypeConstructorEntityRef as C, hasRegisteredFieldNamespace as D, classifyEnumMemberType as E, isAuthoringPslBlockDescriptor as F, PslBlockParamValue as G, PslBlockParamList as H, isAuthoringTypeConstructorDescriptor as I, PslExtensionBlockAttribute as J, PslDiagnosticCode as K, mergeAuthoringNamespaces as L, isAuthoringEntityTypeDescriptor as M, isAuthoringFieldPresetDescriptor as N, instantiateAuthoringEntityType as O, isAuthoringModelAttributeDescriptor as P, PslExtensionBlockParamOption as Q, resolveAuthoringTemplateValue as R, AuthoringTypeConstructorDescriptor as S, assertNoCrossRegistryCollisions as T, PslBlockParamOption as U, PslBlockParam as V, PslBlockParamRef as W, PslExtensionBlockParamBare as X, PslExtensionBlockAttributeArg as Y, PslExtensionBlockParamList as Z, AuthoringModelAttributeLoweringOutput as _, AuthoringDiagnosticSink as a, AuthoringStorageTypeTemplate as b, AuthoringEntityTypeFactoryOutput as c, AuthoringFieldNamespace as d, PslExtensionBlockParamScalarValue as et, AuthoringFieldPresetDescriptor as f, AuthoringModelAttributeDescriptorNamespace as g, AuthoringModelAttributeDescriptor as h, AuthoringContributions as i, isAuthoringArgRef as j, instantiateAuthoringFieldPreset as k, AuthoringEntityTypeNamespace as l, AuthoringModelAttributeContext as m, AuthoringArgumentDescriptor as n, PslPosition as nt, AuthoringEntityContext as o, AuthoringFieldPresetOutput as p, PslExtensionBlock as q, AuthoringColumnDefaultTemplate as r, PslSpan as rt, AuthoringEntityTypeDescriptor as s, AuthoringArgRef as t, PslExtensionBlockParamValue as tt, AuthoringEntityTypeTemplateOutput as u, AuthoringPslBlockDescriptor as v, AuthoringTypeNamespace as w, AuthoringTemplateValue as x, AuthoringPslBlockDescriptorNamespace as y, resolveEnumCodecId as z };
//# sourceMappingURL=framework-authoring-CEbpeygb.d.mts.map
{"version":3,"file":"framework-authoring-CEbpeygb.d.mts","names":[],"sources":["../src/shared/psl-extension-block.ts","../src/shared/framework-authoring.ts"],"mappings":";;;;;;;;;;AAYA;;;;;;UAAiB,WAAA;EAAA,SACN,MAAA;EAAA,SACA,IAAA;EAAA,SACA,MAAA;AAAA;AAAA,UAGM,OAAA;EAAA,SACN,KAAA,EAAO,WAAA;EAAA,SACP,GAAA,EAAK,WAAW;AAAA;AAAA,KAGf,iBAAA;;;AAHe;AAG3B;;;;AAA6B;AA0G7B;;;;;;;;;;;;;;AAIqB;AAErB;;;;;;;;;;AAOA;;;;;;AAAA;;AAGmB;AAGnB;;;;;;;;AAGmB;AAGnB;;;;;;;;;AAGmB;AAqBnB;;;AArBmB;;;;;;;;;;;;;AA0BW;;;;;;;;;;AAKN;AAGxB;;;KA9DY,aAAA,GACR,gBAAA,GACA,kBAAA,GACA,mBAAA,GACA,iBAAA;AAAA,UAEa,gBAAA;EAAA,SACN,IAAA;EAAA,SACA,OAAA;EAAA,SACA,KAAA;EAAA,SACA,QAAA;AAAA;AAAA,UAGM,kBAAA;EAAA,SACN,IAAA;EAAA,SACA,OAAA;EAAA,SACA,QAAA;AAAA;AAAA,UAGM,mBAAA;EAAA,SACN,IAAA;EAAA,SACA,MAAA;EAAA,SACA,QAAA;AAAA;AAAA,UAGM,iBAAA;EAAA,SACN,IAAA;EAAA,SACA,EAAA,EAAI,aAAa;EAAA,SACjB,QAAA;AAAA;;;;;;AAiDa;AAQxB;;;;;;;;AAEwB;AAOxB;;;KA7CY,2BAAA,GACR,yBAAA,GACA,iCAAA,GACA,4BAAA,GACA,0BAAA,GACA,0BAAA;AAAA,UAEa,yBAAA;EAAA,SACN,IAAA;EAAA,SACA,UAAA;EAAA,SACA,IAAA,EAAM,OAAO;AAAA;AAAA,UAGP,iCAAA;EAAA,SACN,IAAA;EAAA,SACA,GAAA;EAAA,SACA,IAAA,EAAM,OAAO;AAAA;AAAA,UAGP,4BAAA;EAAA,SACN,IAAA;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AenF;;;iBAsXgB,2BAAA,CACd,aAAA,EAAe,sBAAsB,cACrC,SAAA;;;;;;;;AAlXC;AAGH;;;;;;;;;;;iBAuegB,wBAAA,CACd,MAAA,EAAQ,MAAA,mBACR,MAAA,EAAQ,MAAM,mBACd,IAAA,qBACA,cAAA,UACA,KAAA;AAAA,iBA6Tc,+BAAA,CACd,aAAA,EAAe,sBAAA,EACf,cAAA,EAAgB,uBAAA,EAChB,mBAAA,GAAqB,4BAAA,EACrB,iBAAA,GAAmB,oCAAA,EACnB,uBAAA,GAAyB,0CAAA;AAAA,iBAqCX,6BAAA,CACd,QAAA,EAAU,sBAAsB,cAChC,IAAA;AAAA,iBAoHc,gCAAA,CACd,UAAA,UACA,WAAA,WAAsB,2BAA2B,gBACjD,IAAA;AAAA,iBAmHc,mCAAA,CACd,UAAA,EAAY,kCAAA,EACZ,IAAA;EAAA,SAES,OAAA;EAAA,SACA,UAAA;EAAA,SACA,UAAA,GAAa,MAAM;AAAA;AAAA,iBAKd,8BAAA,oBACd,UAAA,UACA,UAAA,EAAY,6BAAA,EACZ,IAAA,sBACA,GAAA,EAAK,sBAAA,GACJ,OAAA;AAAA,iBA2Ba,+BAAA,CACd,UAAA,EAAY,8BAAA,EACZ,IAAA;EAAA,SAES,UAAA;IAAA,SACE,OAAA;IAAA,SACA,UAAA;IAAA,SACA,UAAA,GAAa,MAAA;EAAA;EAAA,SAEf,QAAA;EAAA,SACA,OAAA,GAAU,aAAA;EAAA,SACV,iBAAA,GAAoB,8BAAA;EAAA,SACpB,EAAA;EAAA,SACA,MAAA;AAAA"}
import { f as AnyCodecDescriptor } from "./codec-types-BH2f2dg1.mjs";
import { i as AuthoringContributions } from "./framework-authoring-CEbpeygb.mjs";
import { t as TypesImportSpec } from "./types-import-spec-DRKzrJ20.mjs";
import { ColumnDefault, ExecutionMutationDefaultPhases, ExecutionMutationDefaultValue } from "@prisma-next/contract/types";
//#region src/shared/mutation-default-types.d.ts
interface SourcePosition {
readonly offset: number;
readonly line: number;
readonly column: number;
}
interface SourceSpan {
readonly start: SourcePosition;
readonly end: SourcePosition;
}
interface SourceDiagnostic {
readonly code: string;
readonly message: string;
readonly sourceId?: string;
readonly span?: SourceSpan;
readonly data?: Readonly<Record<string, unknown>>;
}
interface DefaultFunctionArgument {
readonly raw: string;
readonly span: SourceSpan;
}
interface ParsedDefaultFunctionCall {
readonly name: string;
readonly raw: string;
readonly args: readonly DefaultFunctionArgument[];
readonly span: SourceSpan;
}
interface DefaultFunctionLoweringContext {
readonly sourceId: string;
readonly modelName: string;
readonly fieldName: string;
readonly columnCodecId?: string;
}
type LoweredDefaultValue = {
readonly kind: 'storage';
readonly defaultValue: ColumnDefault;
} | {
readonly kind: 'execution';
readonly generated: ExecutionMutationDefaultValue;
};
type LoweredDefaultResult = {
readonly ok: true;
readonly value: LoweredDefaultValue;
} | {
readonly ok: false;
readonly diagnostic: SourceDiagnostic;
};
type DefaultFunctionLoweringHandler = (input: {
readonly call: ParsedDefaultFunctionCall;
readonly context: DefaultFunctionLoweringContext;
}) => LoweredDefaultResult;
interface DefaultFunctionRegistryEntry {
readonly lower: DefaultFunctionLoweringHandler;
readonly usageSignatures?: readonly string[];
}
type DefaultFunctionRegistry = ReadonlyMap<string, DefaultFunctionRegistryEntry>;
interface MutationDefaultGeneratorDescriptor {
readonly id: string;
/**
* Codec ids the generator is compatible with when the codec choice
* and the generator choice are made independently by the contract
* author. Set when the registry-coherence check is meaningful
* (the codec and the generator can be paired arbitrarily by the
* caller); omitted when the generator is only reachable through a
* descriptor that co-registers a fixed codec, so coherence is
* structural and the list would be tautological.
*/
readonly applicableCodecIds?: readonly string[];
readonly resolveGeneratedColumnDescriptor?: (input: {
readonly generated: ExecutionMutationDefaultValue;
}) => {
readonly codecId: string;
readonly nativeType: string;
readonly typeRef?: string;
readonly typeParams?: Record<string, unknown>;
} | undefined;
/**
* Construct the `onCreate`/`onUpdate` phases value owned by this
* generator. Authoring layers (PSL `temporal.updatedAt()`, TS field presets) call
* this instead of building the literal inline so PSL/TS-authored
* contracts stay byte-equivalent for any future params-bearing generator.
*/
readonly buildPhases?: (args?: Record<string, unknown>) => ExecutionMutationDefaultPhases;
}
interface ControlMutationDefaultEntry {
readonly lower: (input: {
readonly call: ParsedDefaultFunctionCall;
readonly context: DefaultFunctionLoweringContext;
}) => LoweredDefaultResult;
readonly usageSignatures?: readonly string[];
}
type ControlMutationDefaultRegistry = ReadonlyMap<string, ControlMutationDefaultEntry>;
interface ControlMutationDefaults {
readonly defaultFunctionRegistry: ControlMutationDefaultRegistry;
readonly generatorDescriptors: readonly MutationDefaultGeneratorDescriptor[];
}
//#endregion
//#region src/shared/framework-components.d.ts
/**
* Declarative fields that describe component metadata.
*/
interface ComponentMetadata {
/** Component version (semver) */
readonly version: string;
/**
* Capabilities this component provides.
*
* For adapters, capabilities must be declared on the adapter descriptor (so they are emitted into the contract) and also exposed in runtime adapter code (e.g. `adapter.profile.capabilities`); keep these declarations in sync. Targets are identifiers/descriptors and typically do not declare capabilities.
*/
readonly capabilities?: Record<string, unknown>;
/** Type imports for contract.d.ts generation */
readonly types?: {
readonly codecTypes?: {
/**
* Base codec types import spec. Optional: adapters typically provide this, extensions usually don't.
*/
readonly import?: TypesImportSpec;
/**
* Additional type-only imports for parameterized codec branded types.
*
* These imports are included in generated `contract.d.ts` but are NOT treated as codec type maps (i.e., they should not be intersected into `export type CodecTypes = ...`).
*
* Example: `Vector<N>` for pgvector codecs that emit `Vector<1536>`
*/
readonly typeImports?: ReadonlyArray<TypesImportSpec>;
/**
* Optional control-plane hooks keyed by codecId. Used by family-specific planners/verifiers to handle storage types.
*/
readonly controlPlaneHooks?: Record<string, unknown>;
/**
* Codec descriptors contributed by this component. Source of truth for codec-id-keyed metadata (`traits`, `targetTypes`, `meta`, `renderOutputType`) consumed by `extractCodecLookup`, and used to materialize representative `Codec` instances for codec-dispatched type rendering during emission.
*/
readonly codecDescriptors?: ReadonlyArray<AnyCodecDescriptor>;
};
readonly queryOperationTypes?: {
readonly import: TypesImportSpec;
};
readonly storage?: ReadonlyArray<{
readonly typeId: string;
readonly familyId: string;
readonly targetId: string;
readonly nativeType?: string;
}>;
};
/**
* Optional pure-data authoring contributions exposed by this component.
*
* These contributions are safe to include on pack refs and descriptors because they contain only declarative metadata. Higher-level authoring packages may project them into concrete helper functions for TS-first workflows.
*/
readonly authoring?: AuthoringContributions;
/**
* Scalar type name to codec ID mapping contributed by this component. Assembled by `createControlStack` with duplicate detection.
*/
readonly scalarTypeDescriptors?: ReadonlyMap<string, string>;
/**
* Mutation default function handlers and generator descriptors contributed by this component. Assembled by `createControlStack` with duplicate detection.
*/
readonly controlMutationDefaults?: ControlMutationDefaults;
}
/**
* Base descriptor for any framework component.
*
* All component descriptors share these fundamental properties that identify the component and provide its metadata. This interface is extended by specific descriptor types (FamilyDescriptor, TargetDescriptor, etc.).
*
* @template Kind - Discriminator literal identifying the component type. Built-in kinds are 'family', 'target', 'adapter', 'driver', 'extension', but the type accepts any string to allow ecosystem extensions.
*
* @example
* ```ts
* // All descriptors have these properties
* descriptor.kind // The Kind type parameter (e.g., 'family', 'target', or custom kinds)
* descriptor.id // Unique string identifier (e.g., 'sql', 'postgres')
* descriptor.version // Component version (semver)
* ```
*/
interface ComponentDescriptor<Kind extends string> extends ComponentMetadata {
/** Discriminator identifying the component type */
readonly kind: Kind;
/** Unique identifier for this component (e.g., 'sql', 'postgres', 'pgvector') */
readonly id: string;
}
interface ContractComponentRequirementsCheckInput {
readonly contract: {
readonly target: string;
readonly targetFamily?: string | undefined;
readonly extensionPacks?: Record<string, unknown> | undefined;
};
readonly expectedTargetFamily?: string | undefined;
readonly expectedTargetId?: string | undefined;
readonly providedComponentIds: Iterable<string>;
}
interface ContractComponentRequirementsCheckResult {
readonly familyMismatch?: {
readonly expected: string;
readonly actual: string;
} | undefined;
readonly targetMismatch?: {
readonly expected: string;
readonly actual: string;
} | undefined;
readonly missingExtensionPackIds: readonly string[];
}
declare function checkContractComponentRequirements(input: ContractComponentRequirementsCheckInput): ContractComponentRequirementsCheckResult;
/**
* Descriptor for a family component.
*
* A "family" represents a category of data sources with shared semantics (e.g., SQL databases, document stores). Families define:
* - Query semantics and operations (SELECT, INSERT, find, aggregate, etc.)
* - Contract structure (tables vs collections, columns vs fields)
* - Type system and codecs
*
* Families are the top-level grouping. Each family contains multiple targets (e.g., SQL family contains Postgres, MySQL, SQLite targets).
*
* Extended by plane-specific descriptors:
* - `ControlFamilyDescriptor` - adds `emission` for CLI/tooling operations
* - `RuntimeFamilyDescriptor` - adds runtime-specific factory methods
*
* @template TFamilyId - Literal type for the family identifier (e.g., 'sql', 'document')
*
* @example
* ```ts
* import sql from '@prisma-next/family-sql/control';
*
* sql.kind // 'family'
* sql.familyId // 'sql'
* sql.id // 'sql'
* ```
*/
interface FamilyDescriptor<TFamilyId extends string> extends ComponentDescriptor<'family'> {
/** The family identifier (e.g., 'sql', 'document') */
readonly familyId: TFamilyId;
}
/**
* Descriptor for a target component.
*
* A "target" represents a specific database or data store within a family (e.g., Postgres, MySQL, MongoDB). Targets define:
* - Native type mappings (e.g., Postgres int4 → TypeScript number)
* - Target-specific capabilities (e.g., RETURNING, LATERAL joins)
*
* Targets are bound to a family and provide the target-specific implementation details that adapters and drivers use.
*
* Extended by plane-specific descriptors:
* - `ControlTargetDescriptor` - adds optional `migrations` capability
* - `RuntimeTargetDescriptor` - adds runtime factory method
*
* @template TFamilyId - Literal type for the family identifier
* @template TTargetId - Literal type for the target identifier (e.g., 'postgres', 'mysql')
*
* @example
* ```ts
* import postgres from '@prisma-next/target-postgres/control';
*
* postgres.kind // 'target'
* postgres.familyId // 'sql'
* postgres.targetId // 'postgres'
* ```
*/
interface TargetDescriptor<TFamilyId extends string, TTargetId extends string> extends ComponentDescriptor<'target'> {
/** The family this target belongs to */
readonly familyId: TFamilyId;
/** The target identifier (e.g., 'postgres', 'mysql', 'mongodb') */
readonly targetId: TTargetId;
}
/**
* Base shape for any pack reference. Pack refs are pure JSON-friendly objects safe to import in authoring flows.
*/
interface PackRefBase<Kind extends string, TFamilyId extends string> extends ComponentMetadata {
readonly kind: Kind;
readonly id: string;
readonly familyId: TFamilyId;
readonly targetId?: string;
readonly authoring?: AuthoringContributions;
}
type FamilyPackRef<TFamilyId extends string = string> = PackRefBase<'family', TFamilyId>;
type TargetPackRef<TFamilyId extends string = string, TTargetId extends string = string> = PackRefBase<'target', TFamilyId> & {
readonly targetId: TTargetId; /** The namespace a bare (un-namespaced) entity name resolves to for this target (e.g. Postgres `'public'`). */
readonly defaultNamespaceId: string;
};
type AdapterPackRef<TFamilyId extends string = string, TTargetId extends string = string> = PackRefBase<'adapter', TFamilyId> & {
readonly targetId: TTargetId;
};
type ExtensionPackRef<TFamilyId extends string = string, TTargetId extends string = string> = PackRefBase<'extension', TFamilyId> & {
readonly targetId: TTargetId;
};
type DriverPackRef<TFamilyId extends string = string, TTargetId extends string = string> = PackRefBase<'driver', TFamilyId> & {
readonly targetId: TTargetId;
};
/**
* Descriptor for an adapter component.
*
* An "adapter" provides the protocol and dialect implementation for a target. Adapters handle:
* - SQL/query generation (lowering AST to target-specific syntax)
* - Codec registration (encoding/decoding between JS and wire types)
* - Type mappings and coercions
*
* Adapters are bound to a specific family+target combination and work with any compatible driver for that target.
*
* Extended by plane-specific descriptors:
* - `ControlAdapterDescriptor` - control-plane factory
* - `RuntimeAdapterDescriptor` - runtime factory
*
* @template TFamilyId - Literal type for the family identifier
* @template TTargetId - Literal type for the target identifier
*
* @example
* ```ts
* import postgresAdapter from '@prisma-next/adapter-postgres/control';
*
* postgresAdapter.kind // 'adapter'
* postgresAdapter.familyId // 'sql'
* postgresAdapter.targetId // 'postgres'
* ```
*/
interface AdapterDescriptor<TFamilyId extends string, TTargetId extends string> extends ComponentDescriptor<'adapter'> {
/** The family this adapter belongs to */
readonly familyId: TFamilyId;
/** The target this adapter is designed for */
readonly targetId: TTargetId;
}
/**
* Descriptor for a driver component.
*
* A "driver" provides the connection and execution layer for a target. Drivers handle:
* - Connection management (pooling, timeouts, retries)
* - Query execution (sending SQL/commands, receiving results)
* - Transaction management
* - Wire protocol communication
*
* Drivers are bound to a specific family+target and work with any compatible adapter. Multiple drivers can exist for the same target (e.g., node-postgres vs postgres.js for Postgres).
*
* Extended by plane-specific descriptors:
* - `ControlDriverDescriptor` - creates driver from connection URL
* - `RuntimeDriverDescriptor` - creates driver with runtime options
*
* @template TFamilyId - Literal type for the family identifier
* @template TTargetId - Literal type for the target identifier
*
* @example
* ```ts
* import postgresDriver from '@prisma-next/driver-postgres/control';
*
* postgresDriver.kind // 'driver'
* postgresDriver.familyId // 'sql'
* postgresDriver.targetId // 'postgres'
* ```
*/
interface DriverDescriptor<TFamilyId extends string, TTargetId extends string> extends ComponentDescriptor<'driver'> {
/** The family this driver belongs to */
readonly familyId: TFamilyId;
/** The target this driver connects to */
readonly targetId: TTargetId;
}
/**
* Descriptor for an extension component.
*
* An "extension" adds optional capabilities to a target. Extensions can provide:
* - Additional operations (e.g., vector similarity search with pgvector)
* - Custom types and codecs (e.g., vector type)
* - Extended query capabilities
*
* Extensions are bound to a specific family+target and are registered in the config alongside the core components. Multiple extensions can be used together.
*
* Extended by plane-specific descriptors:
* - `ControlExtensionDescriptor` - control-plane extension factory
* - `RuntimeExtensionDescriptor` - runtime extension factory
*
* @template TFamilyId - Literal type for the family identifier
* @template TTargetId - Literal type for the target identifier
*
* @example
* ```ts
* import pgvector from '@prisma-next/extension-pgvector/control';
*
* pgvector.kind // 'extension'
* pgvector.familyId // 'sql'
* pgvector.targetId // 'postgres'
* ```
*/
interface ExtensionDescriptor<TFamilyId extends string, TTargetId extends string> extends ComponentDescriptor<'extension'> {
/** The family this extension belongs to */
readonly familyId: TFamilyId;
/** The target this extension is designed for */
readonly targetId: TTargetId;
}
/** Components bound to a specific family+target combination. */
type TargetBoundComponentDescriptor<TFamilyId extends string, TTargetId extends string> = TargetDescriptor<TFamilyId, TTargetId> | AdapterDescriptor<TFamilyId, TTargetId> | DriverDescriptor<TFamilyId, TTargetId> | ExtensionDescriptor<TFamilyId, TTargetId>;
interface FamilyInstance<TFamilyId extends string> {
readonly familyId: TFamilyId;
}
interface TargetInstance<TFamilyId extends string, TTargetId extends string> {
readonly familyId: TFamilyId;
readonly targetId: TTargetId;
}
interface AdapterInstance<TFamilyId extends string, TTargetId extends string> {
readonly familyId: TFamilyId;
readonly targetId: TTargetId;
}
interface DriverInstance<TFamilyId extends string, TTargetId extends string> {
readonly familyId: TFamilyId;
readonly targetId: TTargetId;
}
interface ExtensionInstance<TFamilyId extends string, TTargetId extends string> {
readonly familyId: TFamilyId;
readonly targetId: TTargetId;
}
//#endregion
export { LoweredDefaultResult as A, ControlMutationDefaultEntry as C, DefaultFunctionLoweringHandler as D, DefaultFunctionLoweringContext as E, SourceSpan as F, MutationDefaultGeneratorDescriptor as M, ParsedDefaultFunctionCall as N, DefaultFunctionRegistry as O, SourceDiagnostic as P, checkContractComponentRequirements as S, ControlMutationDefaults as T, PackRefBase as _, ComponentMetadata as a, TargetInstance as b, DriverDescriptor as c, ExtensionDescriptor as d, ExtensionInstance as f, FamilyPackRef as g, FamilyInstance as h, ComponentDescriptor as i, LoweredDefaultValue as j, DefaultFunctionRegistryEntry as k, DriverInstance as l, FamilyDescriptor as m, AdapterInstance as n, ContractComponentRequirementsCheckInput as o, ExtensionPackRef as p, AdapterPackRef as r, ContractComponentRequirementsCheckResult as s, AdapterDescriptor as t, DriverPackRef as u, TargetBoundComponentDescriptor as v, ControlMutationDefaultRegistry as w, TargetPackRef as x, TargetDescriptor as y };
//# sourceMappingURL=framework-components-BuDe2aFH.d.mts.map
{"version":3,"file":"framework-components-BuDe2aFH.d.mts","names":[],"sources":["../src/shared/mutation-default-types.ts","../src/shared/framework-components.ts"],"mappings":";;;;;;UAMU,cAAA;EAAA,SACC,MAAA;EAAA,SACA,IAAA;EAAA,SACA,MAAA;AAAA;AAAA,UAGM,UAAA;EAAA,SACN,KAAA,EAAO,cAAA;EAAA,SACP,GAAA,EAAK,cAAc;AAAA;AAAA,UAG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,SAmPF,QAAA,EAAU,SAAA;AAAA;;;;;;;;;;;;;;AA3NuC;AAkB5D;;;;;;;;;;AAKa;AAGb;;UA+NiB,gBAAA,6DACP,mBAAA;EAxN+B;EAAA,SA0N9B,QAAA,EAAU,SAAA;EAhOR;EAAA,SAmOF,QAAA,EAAU,SAAA;AAAA;;;;;;;AA7NoB;AAGzC;;;;;;;;;;;;AAGkC;AAGlC;;;;;;UAiPiB,mBAAA,6DACP,mBAAA;EAhPiC;EAAA,SAkPhC,QAAA,EAAU,SAAA;EAvLJ;EAAA,SA0LN,QAAA,EAAU,SAAA;AAAA;;KAIT,8BAAA,uDACR,gBAAA,CAAiB,SAAA,EAAW,SAAA,IAC5B,iBAAA,CAAkB,SAAA,EAAW,SAAA,IAC7B,gBAAA,CAAiB,SAAA,EAAW,SAAA,IAC5B,mBAAA,CAAoB,SAAA,EAAW,SAAA;AAAA,UAElB,cAAA;EAAA,SACN,QAAA,EAAU,SAAS;AAAA;AAAA,UAGb,cAAA;EAAA,SACN,QAAA,EAAU,SAAA;EAAA,SACV,QAAA,EAAU,SAAS;AAAA;AAAA,UAGb,eAAA;EAAA,SACN,QAAA,EAAU,SAAA;EAAA,SACV,QAAA,EAAU,SAAS;AAAA;AAAA,UAGb,cAAA;EAAA,SACN,QAAA,EAAU,SAAA;EAAA,SACV,QAAA,EAAU,SAAS;AAAA;AAAA,UAGb,iBAAA;EAAA,SACN,QAAA,EAAU,SAAA;EAAA,SACV,QAAA,EAAU,SAAS;AAAA"}
import { r as CodecLookup } from "./codec-types-BH2f2dg1.mjs";
import { K as PslDiagnosticCode, q as PslExtensionBlock, rt as PslSpan, y as AuthoringPslBlockDescriptorNamespace } from "./framework-authoring-CEbpeygb.mjs";
//#region src/control/psl-ast.d.ts
interface PslDiagnostic {
readonly code: PslDiagnosticCode;
readonly message: string;
readonly sourceId: string;
readonly span: PslSpan;
}
interface PslDefaultFunctionValue {
readonly kind: 'function';
readonly name: 'autoincrement' | 'now';
}
interface PslDefaultLiteralValue {
readonly kind: 'literal';
readonly value: string | number | boolean;
}
type PslDefaultValue = PslDefaultFunctionValue | PslDefaultLiteralValue;
type PslAttributeTarget = 'field' | 'model' | 'enum' | 'namedType';
interface PslAttributePositionalArgument {
readonly kind: 'positional';
readonly value: string;
readonly span: PslSpan;
}
interface PslAttributeNamedArgument {
readonly kind: 'named';
readonly name: string;
readonly value: string;
readonly span: PslSpan;
}
type PslAttributeArgument = PslAttributePositionalArgument | PslAttributeNamedArgument;
interface PslTypeConstructorCall {
readonly kind: 'typeConstructor';
readonly path: readonly string[];
readonly args: readonly PslAttributeArgument[];
readonly span: PslSpan;
}
interface PslAttribute {
readonly kind: 'attribute';
readonly target: PslAttributeTarget;
readonly name: string;
readonly args: readonly PslAttributeArgument[];
readonly span: PslSpan;
}
type PslReferentialAction = string;
type PslFieldAttribute = PslAttribute;
interface PslField {
readonly kind: 'field';
readonly name: string;
/** Unqualified type name, e.g. `"User"` for both `User`, `auth.User`, and `supabase:auth.User`. */
readonly typeName: string;
/** Namespace qualifier from a dot-qualified type reference, e.g. `"auth"` for `auth.User` or `supabase:auth.User`. Absent for unqualified types. */
readonly typeNamespaceId?: string;
/**
* Contract-space qualifier from a colon-prefix type reference, e.g. `"supabase"` for
* `supabase:auth.User` or `supabase:User`. Absent for local (same-space) type references.
*
* When present, the field references a model from a different contract space. The namespace
* (`typeNamespaceId`) and model name (`typeName`) identify the target within that space.
* Physical table resolution against the extension contract is deferred to the aggregate stage (M3).
*/
readonly typeContractSpaceId?: string;
readonly typeConstructor?: PslTypeConstructorCall;
readonly optional: boolean;
readonly list: boolean;
readonly typeRef?: string;
readonly attributes: readonly PslFieldAttribute[];
readonly span: PslSpan;
}
interface PslUniqueConstraint {
readonly kind: 'unique';
readonly fields: readonly string[];
readonly span: PslSpan;
}
interface PslIndexConstraint {
readonly kind: 'index';
readonly fields: readonly string[];
readonly span: PslSpan;
}
type PslModelAttribute = PslAttribute;
interface PslModel {
readonly kind: 'model';
readonly name: string;
readonly fields: readonly PslField[];
readonly attributes: readonly PslModelAttribute[];
readonly span: PslSpan;
/**
* Optional leading comment line emitted above the `model` keyword by the
* printer. Producers (e.g. `sqlSchemaIrToPslAst`) attach introspection
* advisories such as "// WARNING: This table has no primary key in the
* database" here. The parser leaves this field unset; round-tripping a
* parsed schema does not re-attach comments.
*/
readonly comment?: string;
}
/**
* A reusable group of fields embedded in a model (a `type Name { … }` block) —
* e.g. a MongoDB embedded document or a Postgres composite type. Unlike
* {@link PslModel} it has no storage or identity of its own.
*/
interface PslCompositeType {
readonly kind: 'compositeType';
readonly name: string;
readonly fields: readonly PslField[];
readonly attributes: readonly PslAttribute[];
readonly span: PslSpan;
}
interface PslNamedTypeDeclaration {
readonly kind: 'namedType';
readonly name: string;
/**
* Parser invariant: exactly one of `baseType` and `typeConstructor` is set.
* Expressing this as a discriminated union trips TypeScript narrowing when
* the declaration flows through helpers that accept the full union.
*/
readonly baseType?: string;
readonly typeConstructor?: PslTypeConstructorCall;
readonly attributes: readonly PslAttribute[];
readonly span: PslSpan;
}
interface PslTypesBlock {
readonly kind: 'types';
readonly declarations: readonly PslNamedTypeDeclaration[];
readonly span: PslSpan;
}
/**
* Name of the synthesised namespace bucket the framework parser uses for
* top-level declarations that appear outside any `namespace { … }` block.
* The double-underscore decoration signals that the identifier is parser-
* synthesised and never appears in user-authored PSL source — writing
* `namespace __unspecified__ { … }` is a parse error.
*
* Distinct from the IR sentinel `__unbound__`: the PSL bucket describes
* syntactic absence at the parser layer; the IR sentinel describes a late-
* bound storage slot at the IR layer. Per-target interpreters decide how
* (or whether) to map the PSL bucket to the IR sentinel.
*/
declare const UNSPECIFIED_PSL_NAMESPACE_ID = "__unspecified__";
/** A value in {@link PslNamespace.entries}: a built-in entity node or an extension-contributed {@link PslExtensionBlock}. */
type PslNamespaceEntry = PslModel | PslCompositeType | PslExtensionBlock;
/**
* A namespace block, or the parser's synthesised `__unspecified__` bucket for
* declarations outside any `namespace { … }`. Same-name blocks reopen-merge;
* `span` points at the first opening.
*
* Entities are stored canonically (ADR 224) in `entries[kind][name]`, where
* `kind` is the PSL keyword for built-ins or the block discriminator for
* extension kinds, e.g. `entries['policy']['ReadPosts']` (the discriminator,
* not the PSL keyword — a `policy_select` block lands under `'policy'` per
* ADR 225).
*/
interface PslNamespace {
readonly kind: 'namespace';
readonly name: string;
/** Canonical store: a frozen container of frozen per-kind maps. The accessors below derive from it. */
readonly entries: Readonly<Record<string, Readonly<Record<string, PslNamespaceEntry>>>>;
/** Built-in models, from `entries['model']`. Extension kinds: {@link namespacePslExtensionBlocks}. */
readonly models: readonly PslModel[];
/** Built-in composite types, from `entries['compositeType']`. */
readonly compositeTypes: readonly PslCompositeType[];
readonly span: PslSpan;
}
/** Constructs a {@link PslNamespace}. Use this, never a namespace literal — the accessors must derive from `entries`. */
declare function makePslNamespace(init: {
readonly kind: 'namespace';
readonly name: string;
readonly entries: Readonly<Record<string, Readonly<Record<string, PslNamespaceEntry>>>>;
readonly span: PslSpan;
}): PslNamespace;
/**
* Builds the frozen `entries[kind][name]` container from per-kind arrays.
* Built-ins key on their PSL keyword; extension blocks key on their `kind`
* discriminator. Call this rather than hand-building the literal.
*/
declare function makePslNamespaceEntries(models: readonly PslModel[], compositeTypes: readonly PslCompositeType[], extensionBlocks: readonly PslExtensionBlock[]): Readonly<Record<string, Readonly<Record<string, PslNamespaceEntry>>>>;
interface PslDocumentAst {
readonly kind: 'document';
readonly sourceId: string;
readonly namespaces: readonly PslNamespace[];
readonly types?: PslTypesBlock;
readonly span: PslSpan;
}
/**
* Returns all models from every namespace in document order. Convenience
* for consumers that don't (yet) need namespace-awareness.
*/
declare function flatPslModels(ast: PslDocumentAst): readonly PslModel[];
/**
* Returns all composite types from every namespace in document order.
*/
declare function flatPslCompositeTypes(ast: PslDocumentAst): readonly PslCompositeType[];
/**
* The set of `entries` kind keys that the framework parser reserves for
* built-in PSL entity kinds. Any own-enumerable key on `PslNamespace.entries`
* that is **not** in this set was contributed by an extension-block descriptor.
*
* Built-in keys match the PSL keyword used on each block type:
* `'model'`, `'compositeType'`. The `'enum'` keyword is claimed by the
* extension-block grammar via a registered descriptor, so `entries['enum']`
* holds `PslExtensionBlock` nodes and is returned by `namespacePslExtensionBlocks`.
*/
declare const BUILTIN_PSL_KIND_KEYS: ReadonlySet<string>;
/**
* Returns all extension-contributed blocks in the given namespace, in
* insertion order (the order the parser encountered them in the source).
*
* Reads from `namespace.entries`, skipping the built-in kind keys
* (`'model'`, `'compositeType'`). All remaining kind maps contain
* only `PslExtensionBlock` nodes by construction (see `makePslNamespaceEntries`).
*/
declare function namespacePslExtensionBlocks(ns: PslNamespace): readonly PslExtensionBlock[];
interface ParsePslDocumentInput {
readonly schema: string;
readonly sourceId: string;
/**
* Registry of declarative block descriptors, keyed by arbitrary path
* segments with {@link AuthoringPslBlockDescriptor} leaves. The registry
* teaches the parser which top-level keywords belong to extension
* contributions: when the parser encounters an unknown keyword, it looks
* it up here and, when found, reads the block generically into a
* {@link PslExtensionBlock} node. Absent or undefined means no extension
* blocks are registered and any unknown keyword yields
* `PSL_UNSUPPORTED_TOP_LEVEL_BLOCK`.
*
* Contrast with the parsed block nodes themselves, which live in
* {@link PslNamespace.entries} under their discriminator key (read them with
* {@link namespacePslExtensionBlocks}); this field holds the registry of
* descriptors that teach the parser how to read those blocks.
*/
readonly pslBlockDescriptors?: AuthoringPslBlockDescriptorNamespace;
/**
* Codec lookup for validating `value`-kind extension block parameters.
* When provided alongside `pslBlockDescriptors`, the generic validator runs
* over every parsed extension block after the full AST is assembled,
* appending any diagnostics to the parse result. Absent or undefined means
* no codec validation runs; `ref` resolution still runs when namespace
* context is available (built from the assembled namespaces).
*/
readonly codecLookup?: CodecLookup;
}
interface ParsePslDocumentResult {
readonly ast: PslDocumentAst;
readonly diagnostics: readonly PslDiagnostic[];
readonly ok: boolean;
}
//#endregion
export { makePslNamespace as A, PslReferentialAction as C, UNSPECIFIED_PSL_NAMESPACE_ID as D, PslUniqueConstraint as E, namespacePslExtensionBlocks as M, flatPslCompositeTypes as O, PslNamespaceEntry as S, PslTypesBlock as T, PslIndexConstraint as _, PslAttributeArgument as a, PslNamedTypeDeclaration as b, PslAttributeTarget as c, PslDefaultLiteralValue as d, PslDefaultValue as f, PslFieldAttribute as g, PslField as h, PslAttribute as i, makePslNamespaceEntries as j, flatPslModels as k, PslCompositeType as l, PslDocumentAst as m, ParsePslDocumentInput as n, PslAttributeNamedArgument as o, PslDiagnostic as p, ParsePslDocumentResult as r, PslAttributePositionalArgument as s, BUILTIN_PSL_KIND_KEYS as t, PslDefaultFunctionValue as u, PslModel as v, PslTypeConstructorCall as w, PslNamespace as x, PslModelAttribute as y };
//# sourceMappingURL=psl-ast-BEdlyUwY.d.mts.map
{"version":3,"file":"psl-ast-BEdlyUwY.d.mts","names":[],"sources":["../src/control/psl-ast.ts"],"mappings":";;;;UA0BiB,aAAA;EAAA,SACN,IAAA,EAAM,iBAAA;EAAA,SACN,OAAA;EAAA,SACA,QAAA;EAAA,SACA,IAAA,EAAM,OAAO;AAAA;AAAA,UAGP,uBAAA;EAAA,SACN,IAAA;EAAA,SACA,IAAI;AAAA;AAAA,UAGE,sBAAA;EAAA,SACN,IAAA;EAAA,SACA,KAAK;AAAA;AAAA,KAGJ,eAAA,GAAkB,uBAAA,GAA0B,sBAAsB;AAAA,KAElE,kBAAA;AAAA,UAEK,8BAAA;EAAA,SACN,IAAA;EAAA,SACA,KAAA;EAAA,SACA,IAAA,EAAM,OAAO;AAAA;AAAA,UAGP,yBAAA;EAAA,SACN,IAAA;EAAA,SACA,IAAA;EAAA,SACA,KAAA;EAAA,SACA,IAAA,EAAM,OAAO;AAAA;AAAA,KAGZ,oBAAA,GAAuB,8BAAA,GAAiC,yBAAyB;AAAA,UAE5E,sBAAA;EAAA,SACN,IAAA;EAAA,SACA,IAAA;EAAA,SACA,IAAA,WAAe,oBAAA;EAAA,SACf,IAAA,EAAM,OAAO;AAAA;AAAA,UAGP,YAAA;EAAA,SACN,IAAA;EAAA,SACA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;AAAA,UAgBxE,qBAAA;EAAA,SACN,MAAA;EAAA,SACA,QAAA;EAzMa;AAAA;AAexB;;;;AAAyC;AAGzC;;;;;;;;EAlBwB,SAyNb,mBAAA,GAAsB,oCAAA;EAvMU;;;AAAoC;AAa/E;;;;EAb2C,SAgNhC,WAAA,GAAc,WAAW;AAAA;AAAA,UAGnB,sBAAA;EAAA,SACN,GAAA,EAAK,cAAA;EAAA,SACL,WAAA,WAAsB,aAAa;EAAA,SACnC,EAAA;AAAA"}
+1
-1

@@ -1,2 +0,2 @@

import { $ as PslExtensionBlockParamRef, A as instantiateAuthoringTypeConstructor, B as validateAuthoringHelperArguments, C as AuthoringTypeConstructorEntityRef, D as hasRegisteredFieldNamespace, E as classifyEnumMemberType, F as isAuthoringPslBlockDescriptor, G as PslBlockParamValue, H as PslBlockParamList, I as isAuthoringTypeConstructorDescriptor, L as mergeAuthoringNamespaces, M as isAuthoringEntityTypeDescriptor, N as isAuthoringFieldPresetDescriptor, O as instantiateAuthoringEntityType, P as isAuthoringModelAttributeDescriptor, Q as PslExtensionBlockParamOption, R as resolveAuthoringTemplateValue, S as AuthoringTypeConstructorDescriptor, T as assertNoCrossRegistryCollisions, U as PslBlockParamOption, V as PslBlockParam, W as PslBlockParamRef, Z as PslExtensionBlockParamList, _ as AuthoringModelAttributeLoweringOutput, a as AuthoringDiagnosticSink, b as AuthoringStorageTypeTemplate, c as AuthoringEntityTypeFactoryOutput, d as AuthoringFieldNamespace, et as PslExtensionBlockParamScalarValue, f as AuthoringFieldPresetDescriptor, g as AuthoringModelAttributeDescriptorNamespace, h as AuthoringModelAttributeDescriptor, i as AuthoringContributions, j as isAuthoringArgRef, k as instantiateAuthoringFieldPreset, l as AuthoringEntityTypeNamespace, m as AuthoringModelAttributeContext, n as AuthoringArgumentDescriptor, o as AuthoringEntityContext, p as AuthoringFieldPresetOutput, q as PslExtensionBlock, r as AuthoringColumnDefaultTemplate, s as AuthoringEntityTypeDescriptor, t as AuthoringArgRef, tt as PslExtensionBlockParamValue, u as AuthoringEntityTypeTemplateOutput, v as AuthoringPslBlockDescriptor, w as AuthoringTypeNamespace, x as AuthoringTemplateValue, y as AuthoringPslBlockDescriptorNamespace, z as resolveEnumCodecId } from "./framework-authoring-jIw3xcfy.mjs";
import { $ as PslExtensionBlockParamRef, A as instantiateAuthoringTypeConstructor, B as validateAuthoringHelperArguments, C as AuthoringTypeConstructorEntityRef, D as hasRegisteredFieldNamespace, E as classifyEnumMemberType, F as isAuthoringPslBlockDescriptor, G as PslBlockParamValue, H as PslBlockParamList, I as isAuthoringTypeConstructorDescriptor, L as mergeAuthoringNamespaces, M as isAuthoringEntityTypeDescriptor, N as isAuthoringFieldPresetDescriptor, O as instantiateAuthoringEntityType, P as isAuthoringModelAttributeDescriptor, Q as PslExtensionBlockParamOption, R as resolveAuthoringTemplateValue, S as AuthoringTypeConstructorDescriptor, T as assertNoCrossRegistryCollisions, U as PslBlockParamOption, V as PslBlockParam, W as PslBlockParamRef, Z as PslExtensionBlockParamList, _ as AuthoringModelAttributeLoweringOutput, a as AuthoringDiagnosticSink, b as AuthoringStorageTypeTemplate, c as AuthoringEntityTypeFactoryOutput, d as AuthoringFieldNamespace, et as PslExtensionBlockParamScalarValue, f as AuthoringFieldPresetDescriptor, g as AuthoringModelAttributeDescriptorNamespace, h as AuthoringModelAttributeDescriptor, i as AuthoringContributions, j as isAuthoringArgRef, k as instantiateAuthoringFieldPreset, l as AuthoringEntityTypeNamespace, m as AuthoringModelAttributeContext, n as AuthoringArgumentDescriptor, o as AuthoringEntityContext, p as AuthoringFieldPresetOutput, q as PslExtensionBlock, r as AuthoringColumnDefaultTemplate, s as AuthoringEntityTypeDescriptor, t as AuthoringArgRef, tt as PslExtensionBlockParamValue, u as AuthoringEntityTypeTemplateOutput, v as AuthoringPslBlockDescriptor, w as AuthoringTypeNamespace, x as AuthoringTemplateValue, y as AuthoringPslBlockDescriptorNamespace, z as resolveEnumCodecId } from "./framework-authoring-CEbpeygb.mjs";
export { type AuthoringArgRef, type AuthoringArgumentDescriptor, type AuthoringColumnDefaultTemplate, type AuthoringContributions, type AuthoringDiagnosticSink, type AuthoringEntityContext, type AuthoringEntityTypeDescriptor, type AuthoringEntityTypeFactoryOutput, type AuthoringEntityTypeNamespace, type AuthoringEntityTypeTemplateOutput, type AuthoringFieldNamespace, type AuthoringFieldPresetDescriptor, type AuthoringFieldPresetOutput, type AuthoringModelAttributeContext, type AuthoringModelAttributeDescriptor, type AuthoringModelAttributeDescriptorNamespace, type AuthoringModelAttributeLoweringOutput, type AuthoringPslBlockDescriptor, type AuthoringPslBlockDescriptorNamespace, type AuthoringStorageTypeTemplate, type AuthoringTemplateValue, type AuthoringTypeConstructorDescriptor, type AuthoringTypeConstructorEntityRef, type AuthoringTypeNamespace, type PslBlockParam, type PslBlockParamList, type PslBlockParamOption, type PslBlockParamRef, type PslBlockParamValue, type PslExtensionBlock, type PslExtensionBlockParamList, type PslExtensionBlockParamOption, type PslExtensionBlockParamRef, type PslExtensionBlockParamScalarValue, type PslExtensionBlockParamValue, assertNoCrossRegistryCollisions, classifyEnumMemberType, hasRegisteredFieldNamespace, instantiateAuthoringEntityType, instantiateAuthoringFieldPreset, instantiateAuthoringTypeConstructor, isAuthoringArgRef, isAuthoringEntityTypeDescriptor, isAuthoringFieldPresetDescriptor, isAuthoringModelAttributeDescriptor, isAuthoringPslBlockDescriptor, isAuthoringTypeConstructorDescriptor, mergeAuthoringNamespaces, resolveAuthoringTemplateValue, resolveEnumCodecId, validateAuthoringHelperArguments };

@@ -1,2 +0,2 @@

import { a as instantiateAuthoringFieldPreset, c as isAuthoringEntityTypeDescriptor, d as isAuthoringPslBlockDescriptor, f as isAuthoringTypeConstructorDescriptor, g as validateAuthoringHelperArguments, h as resolveEnumCodecId, i as instantiateAuthoringEntityType, l as isAuthoringFieldPresetDescriptor, m as resolveAuthoringTemplateValue, n as classifyEnumMemberType, o as instantiateAuthoringTypeConstructor, p as mergeAuthoringNamespaces, r as hasRegisteredFieldNamespace, s as isAuthoringArgRef, t as assertNoCrossRegistryCollisions, u as isAuthoringModelAttributeDescriptor } from "./framework-authoring-DsAScNbB.mjs";
import { a as instantiateAuthoringFieldPreset, c as isAuthoringEntityTypeDescriptor, d as isAuthoringPslBlockDescriptor, f as isAuthoringTypeConstructorDescriptor, g as validateAuthoringHelperArguments, h as resolveEnumCodecId, i as instantiateAuthoringEntityType, l as isAuthoringFieldPresetDescriptor, m as resolveAuthoringTemplateValue, n as classifyEnumMemberType, o as instantiateAuthoringTypeConstructor, p as mergeAuthoringNamespaces, r as hasRegisteredFieldNamespace, s as isAuthoringArgRef, t as assertNoCrossRegistryCollisions, u as isAuthoringModelAttributeDescriptor } from "./framework-authoring-Bz_vaNZw.mjs";
export { assertNoCrossRegistryCollisions, classifyEnumMemberType, hasRegisteredFieldNamespace, instantiateAuthoringEntityType, instantiateAuthoringFieldPreset, instantiateAuthoringTypeConstructor, isAuthoringArgRef, isAuthoringEntityTypeDescriptor, isAuthoringFieldPresetDescriptor, isAuthoringModelAttributeDescriptor, isAuthoringPslBlockDescriptor, isAuthoringTypeConstructorDescriptor, mergeAuthoringNamespaces, resolveAuthoringTemplateValue, resolveEnumCodecId, validateAuthoringHelperArguments };
import { n as mergeCapabilityMatrices, t as CapabilityMatrix } from "./capabilities-Cupq4-1-.mjs";
import { S as checkContractComponentRequirements, _ as PackRefBase, a as ComponentMetadata, b as TargetInstance, c as DriverDescriptor, d as ExtensionDescriptor, f as ExtensionInstance, g as FamilyPackRef, h as FamilyInstance, i as ComponentDescriptor, l as DriverInstance, m as FamilyDescriptor, n as AdapterInstance, o as ContractComponentRequirementsCheckInput, p as ExtensionPackRef, r as AdapterPackRef, s as ContractComponentRequirementsCheckResult, t as AdapterDescriptor, u as DriverPackRef, v as TargetBoundComponentDescriptor, x as TargetPackRef, y as TargetDescriptor } from "./framework-components-7p9S3MZ0.mjs";
import { S as checkContractComponentRequirements, _ as PackRefBase, a as ComponentMetadata, b as TargetInstance, c as DriverDescriptor, d as ExtensionDescriptor, f as ExtensionInstance, g as FamilyPackRef, h as FamilyInstance, i as ComponentDescriptor, l as DriverInstance, m as FamilyDescriptor, n as AdapterInstance, o as ContractComponentRequirementsCheckInput, p as ExtensionPackRef, r as AdapterPackRef, s as ContractComponentRequirementsCheckResult, t as AdapterDescriptor, u as DriverPackRef, v as TargetBoundComponentDescriptor, x as TargetPackRef, y as TargetDescriptor } from "./framework-components-BuDe2aFH.mjs";
export { type AdapterDescriptor, type AdapterInstance, type AdapterPackRef, type CapabilityMatrix, type ComponentDescriptor, type ComponentMetadata, type ContractComponentRequirementsCheckInput, type ContractComponentRequirementsCheckResult, type DriverDescriptor, type DriverInstance, type DriverPackRef, type ExtensionDescriptor, type ExtensionInstance, type ExtensionPackRef, type FamilyDescriptor, type FamilyInstance, type FamilyPackRef, type PackRefBase, type TargetBoundComponentDescriptor, type TargetDescriptor, type TargetInstance, type TargetPackRef, checkContractComponentRequirements, mergeCapabilityMatrices };
import { o as CodecRegistry } from "./codec-types-BH2f2dg1.mjs";
import { d as AuthoringFieldNamespace, g as AuthoringModelAttributeDescriptorNamespace, i as AuthoringContributions, l as AuthoringEntityTypeNamespace, w as AuthoringTypeNamespace, y as AuthoringPslBlockDescriptorNamespace } from "./framework-authoring-jIw3xcfy.mjs";
import { d as AuthoringFieldNamespace, g as AuthoringModelAttributeDescriptorNamespace, i as AuthoringContributions, l as AuthoringEntityTypeNamespace, w as AuthoringTypeNamespace, y as AuthoringPslBlockDescriptorNamespace } from "./framework-authoring-CEbpeygb.mjs";
import { t as CapabilityMatrix } from "./capabilities-Cupq4-1-.mjs";
import { A as LoweredDefaultResult, C as ControlMutationDefaultEntry, D as DefaultFunctionLoweringHandler, E as DefaultFunctionLoweringContext, F as SourceSpan, M as MutationDefaultGeneratorDescriptor, N as ParsedDefaultFunctionCall, O as DefaultFunctionRegistry, P as SourceDiagnostic, T as ControlMutationDefaults, a as ComponentMetadata, b as TargetInstance, c as DriverDescriptor, d as ExtensionDescriptor, f as ExtensionInstance, h as FamilyInstance, j as LoweredDefaultValue, k as DefaultFunctionRegistryEntry, l as DriverInstance, m as FamilyDescriptor, n as AdapterInstance, t as AdapterDescriptor, v as TargetBoundComponentDescriptor, w as ControlMutationDefaultRegistry, y as TargetDescriptor } from "./framework-components-7p9S3MZ0.mjs";
import { A as LoweredDefaultResult, C as ControlMutationDefaultEntry, D as DefaultFunctionLoweringHandler, E as DefaultFunctionLoweringContext, F as SourceSpan, M as MutationDefaultGeneratorDescriptor, N as ParsedDefaultFunctionCall, O as DefaultFunctionRegistry, P as SourceDiagnostic, T as ControlMutationDefaults, a as ComponentMetadata, b as TargetInstance, c as DriverDescriptor, d as ExtensionDescriptor, f as ExtensionInstance, h as FamilyInstance, j as LoweredDefaultValue, k as DefaultFunctionRegistryEntry, l as DriverInstance, m as FamilyDescriptor, n as AdapterInstance, t as AdapterDescriptor, v as TargetBoundComponentDescriptor, w as ControlMutationDefaultRegistry, y as TargetDescriptor } from "./framework-components-BuDe2aFH.mjs";
import { t as TypesImportSpec } from "./types-import-spec-DRKzrJ20.mjs";
import { t as EmissionSpi } from "./emission-types-BryrMZg9.mjs";
import { m as PslDocumentAst } from "./psl-ast-BRRUqpAN.mjs";
import { m as PslDocumentAst } from "./psl-ast-BEdlyUwY.mjs";
import { Contract, ContractMarkerRecord, ControlPolicy, LedgerEntryRecord } from "@prisma-next/contract/types";

@@ -1094,5 +1094,5 @@ import { ImportRequirement, ImportRequirement as ImportRequirement$1 } from "@prisma-next/ts-render";

* - `auxiliary`: a secondary part of an entity (an index, a default, a key).
* - `structural`: a cross-cutting object (an access policy, a role, a tree
* root) that is the owning space's own concern, never a sibling's
* unclaimed entity.
* - `structural`: a cross-cutting object (an access policy, a tree root) that
* is the owning space's own concern, never a sibling's unclaimed entity —
* its extras fail verify in both modes.
*/

@@ -1099,0 +1099,0 @@ type DiffSubjectGranularity = 'namespace' | 'entity' | 'field' | 'auxiliary' | 'structural';

import { n as materializeCodec, r as resolveCodecDescriptorOrThrow, t as CONTRACT_CODEC_DESCRIPTOR_MISSING } from "./resolve-codec-D8EPZosv.mjs";
import { t as mergeCapabilityMatrices } from "./capabilities-BnRAFKP5.mjs";
import { p as mergeAuthoringNamespaces, t as assertNoCrossRegistryCollisions } from "./framework-authoring-DsAScNbB.mjs";
import { p as mergeAuthoringNamespaces, t as assertNoCrossRegistryCollisions } from "./framework-authoring-Bz_vaNZw.mjs";
import { blindCast } from "@prisma-next/utils/casts";

@@ -5,0 +5,0 @@ //#region src/control/control-capabilities.ts

@@ -1,1 +0,1 @@

{"version":3,"file":"control.mjs","names":[],"sources":["../src/control/control-capabilities.ts","../src/control/control-operation-results.ts","../src/control/control-schema-view.ts","../src/control/control-spaces.ts","../src/control/control-stack.ts","../src/control/schema-diff.ts","../src/control/verifier-disposition.ts"],"sourcesContent":["import type { ControlTargetDescriptor } from './control-descriptors';\nimport type { ControlFamilyInstance } from './control-instances';\nimport type { MigrationPlanOperation, TargetMigrationsCapability } from './control-migration-types';\nimport type { OperationPreview } from './control-operation-preview';\nimport type { CoreSchemaView } from './control-schema-view';\nimport type { PslDocumentAst } from './psl-ast';\nimport type { SchemaDiffIssue } from './schema-diff';\n\nexport interface MigratableTargetDescriptor<\n TFamilyId extends string,\n TTargetId extends string,\n TFamilyInstance extends ControlFamilyInstance<TFamilyId, unknown> = ControlFamilyInstance<\n TFamilyId,\n unknown\n >,\n> extends ControlTargetDescriptor<TFamilyId, TTargetId> {\n readonly migrations: TargetMigrationsCapability<TFamilyId, TTargetId, TFamilyInstance>;\n}\n\nexport function hasMigrations<TFamilyId extends string, TTargetId extends string>(\n target: ControlTargetDescriptor<TFamilyId, TTargetId>,\n): target is MigratableTargetDescriptor<TFamilyId, TTargetId> {\n return 'migrations' in target && !!(target as Record<string, unknown>)['migrations'];\n}\n\nexport interface SchemaViewCapable<TSchemaIR = unknown> {\n toSchemaView(schema: TSchemaIR): CoreSchemaView;\n}\n\nexport function hasSchemaView<TFamilyId extends string, TSchemaIR>(\n instance: ControlFamilyInstance<TFamilyId, TSchemaIR>,\n): instance is ControlFamilyInstance<TFamilyId, TSchemaIR> & SchemaViewCapable<TSchemaIR> {\n return (\n 'toSchemaView' in instance &&\n typeof (instance as Record<string, unknown>)['toSchemaView'] === 'function'\n );\n}\n\n/**\n * Capability declaring that a family can infer a PSL contract AST from its\n * opaque introspected schema IR. Consumed by `prisma-next contract infer`.\n */\nexport interface PslContractInferCapable<TSchemaIR = unknown> {\n inferPslContract(schemaIR: TSchemaIR): PslDocumentAst;\n}\n\nexport function hasPslContractInfer<TFamilyId extends string, TSchemaIR>(\n instance: ControlFamilyInstance<TFamilyId, TSchemaIR>,\n): instance is ControlFamilyInstance<TFamilyId, TSchemaIR> & PslContractInferCapable<TSchemaIR> {\n return (\n 'inferPslContract' in instance &&\n typeof (instance as Record<string, unknown>)['inferPslContract'] === 'function'\n );\n}\n\n/**\n * Capability declaring that a family can render a textual preview of migration\n * operations for the CLI's \"DDL preview\" output. SQL families emit\n * `language: 'sql'` statements; Mongo families emit `language: 'mongodb-shell'`.\n */\nexport interface OperationPreviewCapable {\n toOperationPreview(operations: readonly MigrationPlanOperation[]): OperationPreview;\n}\n\nexport function hasOperationPreview<TFamilyId extends string, TSchemaIR>(\n instance: ControlFamilyInstance<TFamilyId, TSchemaIR>,\n): instance is ControlFamilyInstance<TFamilyId, TSchemaIR> & OperationPreviewCapable {\n return (\n 'toOperationPreview' in instance &&\n typeof (instance as Record<string, unknown>)['toOperationPreview'] === 'function'\n );\n}\n\n/**\n * The granularity of a {@link SchemaDiffIssue}'s subject, resolved on demand\n * from the issue's node `nodeKind` — never stamped on the issue or the node.\n *\n * - `namespace`: a whole namespace.\n * - `entity`: a whole top-level entity (the thing a namespace contains).\n * - `field`: a field of an entity.\n * - `auxiliary`: a secondary part of an entity (an index, a default, a key).\n * - `structural`: a cross-cutting object (an access policy, a role, a tree\n * root) that is the owning space's own concern, never a sibling's\n * unclaimed entity.\n */\nexport type DiffSubjectGranularity = 'namespace' | 'entity' | 'field' | 'auxiliary' | 'structural';\n\n/**\n * Capability declaring that a family can classify a {@link SchemaDiffIssue}'s\n * subject granularity, and separately its storage `entityKind`, on demand —\n * both resolved from its node's `nodeKind` through the family/target\n * vocabulary it owns. Consumed by framework code that spans contract spaces\n * (the migration aggregate's unclaimed-elements sweep) and cannot itself read\n * family/target node vocabulary, so it asks this capability instead of\n * hardcoding a family entity kind. `undefined` when the issue's node kind is\n * unrecognized, or when the family injects no classifier at all — callers\n * fall back to path shape in that case.\n *\n * `classifyEntityKind` returns the same per-family vocabulary as the contract\n * storage's `entries` dictionary keys (the vocabulary\n * {@link import('../ir/storage').elementCoordinates} walks) — never a\n * granularity word, and never a word this framework layer names itself.\n */\nexport interface SchemaSubjectClassifierCapable {\n classifySubjectGranularity(issue: SchemaDiffIssue): DiffSubjectGranularity | undefined;\n classifyEntityKind(issue: SchemaDiffIssue): string | undefined;\n}\n\nexport function hasSchemaSubjectClassifier<TFamilyId extends string, TSchemaIR>(\n instance: ControlFamilyInstance<TFamilyId, TSchemaIR>,\n): instance is ControlFamilyInstance<TFamilyId, TSchemaIR> & SchemaSubjectClassifierCapable {\n return (\n 'classifySubjectGranularity' in instance &&\n typeof (instance as Record<string, unknown>)['classifySubjectGranularity'] === 'function' &&\n 'classifyEntityKind' in instance &&\n typeof (instance as Record<string, unknown>)['classifyEntityKind'] === 'function'\n );\n}\n","import type { SchemaDiffIssue } from './schema-diff';\n\nexport const VERIFY_CODE_MARKER_MISSING = 'PN-RUN-3001';\nexport const VERIFY_CODE_HASH_MISMATCH = 'PN-RUN-3002';\nexport const VERIFY_CODE_TARGET_MISMATCH = 'PN-RUN-3003';\nexport const VERIFY_CODE_SCHEMA_FAILURE = 'PN-RUN-3010';\n\nexport interface OperationContext {\n readonly contractPath?: string;\n readonly configPath?: string;\n readonly meta?: Readonly<Record<string, unknown>>;\n}\n\nexport interface VerifyDatabaseResult {\n readonly ok: boolean;\n readonly code?: string;\n readonly summary: string;\n readonly contract: {\n readonly storageHash: string;\n readonly profileHash?: string;\n };\n readonly marker?: {\n readonly storageHash?: string;\n readonly profileHash?: string;\n };\n readonly target: {\n readonly expected: string;\n readonly actual?: string;\n };\n readonly missingCodecs?: readonly string[];\n readonly codecCoverageSkipped?: boolean;\n readonly meta?: {\n readonly configPath?: string;\n readonly contractPath: string;\n };\n readonly timings: {\n readonly total: number;\n };\n}\n\n/**\n * The three ways an actual state can fail an expectation: it contains a node\n * that was not expected, lacks a node that was expected, or holds a node that\n * is not equal to the expected one. Expected is the desired side and actual the\n * current side of whatever comparison produced the issue — contract-vs-database,\n * or contract-vs-contract in an offline plan — so the vocabulary is\n * comparison-relative and never ambiguous about a base.\n *\n * The failure reason is a structural characteristic carried as a declared\n * field: consumers filter on `reason`, never by enumerating kind strings or\n * family-invented node codes.\n */\nexport type ExpectationFailureReason = 'not-expected' | 'not-found' | 'not-equal';\n\n/**\n * The issue-based schema-verify result. `ok` derives from the FAILURE list\n * only: a verify passes exactly when `schema.issues` is empty, post\n * strict-gating and control-policy disposition.\n *\n * `schema.warnings` carries warn-graded issues (an `observed`-policy\n * subject's drift, and any other `warn` disposition) in the same shape.\n * Warnings are informational — they never affect `ok` — but they MUST be\n * surfaced: an `observed` table that drifted yields `ok: true` with a\n * non-empty warnings channel, which is what distinguishes \"watch without\n * failing\" from full suppression.\n */\nexport interface VerifyDatabaseSchemaResult {\n readonly ok: boolean;\n readonly code?: string;\n readonly summary: string;\n readonly contract: {\n readonly storageHash: string;\n readonly profileHash?: string;\n };\n readonly target: {\n readonly expected: string;\n readonly actual?: string;\n };\n readonly schema: {\n readonly issues: readonly SchemaDiffIssue[];\n readonly warnings?: {\n readonly issues: readonly SchemaDiffIssue[];\n };\n };\n readonly meta?: {\n readonly configPath?: string;\n readonly contractPath?: string;\n readonly strict: boolean;\n };\n readonly timings: {\n readonly total: number;\n };\n}\n\nexport interface EmitContractResult {\n readonly contractJson: string;\n readonly contractDts: string;\n readonly storageHash: string;\n readonly executionHash?: string;\n readonly profileHash: string;\n}\n\nexport interface IntrospectSchemaResult<TSchemaIR> {\n readonly ok: true;\n readonly summary: string;\n readonly target: {\n readonly familyId: string;\n readonly id: string;\n };\n readonly schema: TSchemaIR;\n readonly meta?: {\n readonly configPath?: string;\n readonly dbUrl?: string;\n };\n readonly timings: {\n readonly total: number;\n };\n}\n\nexport interface SignDatabaseResult {\n readonly ok: boolean;\n readonly summary: string;\n readonly contract: {\n readonly storageHash: string;\n readonly profileHash?: string;\n };\n readonly target: {\n readonly expected: string;\n readonly actual?: string;\n };\n readonly marker: {\n readonly created: boolean;\n readonly updated: boolean;\n readonly previous?: {\n readonly storageHash?: string;\n readonly profileHash?: string;\n };\n };\n readonly meta?: {\n readonly configPath?: string;\n readonly contractPath: string;\n };\n readonly timings: {\n readonly total: number;\n };\n}\n","/**\n * Core schema view types for family-agnostic schema visualization.\n *\n * These types provide a minimal, generic, tree-shaped representation of schemas\n * across families, designed for CLI visualization and lightweight tooling.\n *\n * Families can optionally project their family-specific Schema IR into this\n * core view via the `toSchemaView` method on `FamilyInstance`.\n */\n\nexport type SchemaViewNodeKind =\n | 'root'\n | 'namespace'\n | 'collection'\n | 'entity'\n | 'field'\n | 'index'\n | 'dependency';\n\nexport interface SchemaTreeVisitor<R> {\n visit(node: SchemaTreeNode): R;\n}\n\nexport interface SchemaTreeNodeOptions {\n readonly kind: SchemaViewNodeKind;\n readonly id: string;\n readonly label: string;\n readonly meta?: Record<string, unknown>;\n readonly children?: readonly SchemaTreeNode[];\n}\n\nexport class SchemaTreeNode {\n readonly kind: SchemaViewNodeKind;\n readonly id: string;\n readonly label: string;\n readonly meta?: Record<string, unknown>;\n readonly children?: readonly SchemaTreeNode[];\n\n constructor(options: SchemaTreeNodeOptions) {\n this.kind = options.kind;\n this.id = options.id;\n this.label = options.label;\n if (options.meta !== undefined) this.meta = options.meta;\n if (options.children !== undefined) this.children = options.children;\n Object.freeze(this);\n }\n\n accept<R>(visitor: SchemaTreeVisitor<R>): R {\n return visitor.visit(this);\n }\n}\n\n/**\n * Core schema view providing a family-agnostic tree representation of a schema.\n * Used by CLI and cross-family tooling for visualization.\n */\nexport interface CoreSchemaView {\n readonly root: SchemaTreeNode;\n}\n","import type { Contract } from '@prisma-next/contract/types';\nimport type { MigrationMetadata, MigrationPlanOperation } from './control-migration-types';\n\n/**\n * Canonical control-plane identifiers for contract spaces.\n *\n * A contract space is the disjoint `(contract.json, migration-graph)` unit\n * the per-space planner / runner / verifier (project: extension contract\n * spaces, TML-2397) operates on. The application owns one well-known\n * space — the value below — and each loaded extension that contributes\n * schema owns a uniquely-named space.\n *\n * Lives in `framework-components/control` so every layer that has to\n * reason about space identity (the migration tooling, the SQL runtime's\n * marker reader, target-side statement builders, target-side adapters)\n * can import a single value rather than duplicating the literal. Raw\n * `'app'` string literals in framework / target / runtime / adapter\n * source code are forbidden and policed by\n * `scripts/lint-app-space-id.mjs` (wired into `pnpm lint:deps`).\n *\n * @see specs/framework-mechanism.spec.md § 3 — Layout convention (γ).\n */\nexport const APP_SPACE_ID = 'app' as const;\n\n/**\n * Head ref for a contract space — the `(hash, invariants)` tuple\n * a runner targets when applying that space's migration graph. Identical\n * in shape to the on-disk `migrations/<space-id>/refs/head.json` the\n * framework writes per loaded extension, and to the app-space\n * `<projectRoot>/refs/head.json`. Family-agnostic: SQL, Mongo, and any\n * future family share the same head-ref shape.\n *\n * @see specs/framework-mechanism.spec.md § 1.\n */\nexport interface ContractSpaceHeadRef {\n readonly hash: string;\n readonly invariants: readonly string[];\n}\n\n/**\n * Canonical structural shape of a migration package — the unit a planner\n * produces and a runner consumes: a directory name, the metadata\n * envelope, and the operation list.\n *\n * In-memory by default. Readers in `@prisma-next/migration-tools`\n * (`readMigrationPackage` / `readMigrationsDir`) return the augmented\n * {@link import('@prisma-next/migration-tools/package').OnDiskMigrationPackage}\n * variant which adds `dirPath`; everything else operates against the\n * canonical shape so the same value flows through pre-emission\n * authoring, on-disk loading, and runner execution without conversion.\n *\n * @see specs/framework-mechanism.spec.md § 1.\n */\nexport interface MigrationPackage {\n readonly dirName: string;\n readonly metadata: MigrationMetadata;\n readonly ops: readonly MigrationPlanOperation[];\n}\n\n/**\n * Canonical structural shape of a contract space — one disjoint\n * `(contractJson, migration-graph)` unit the per-space planner / runner\n * / verifier operates on. The application owns one well-known space\n * ({@link APP_SPACE_ID}); each loaded extension that contributes schema\n * owns a uniquely-named space. Whether a value is the app's space or an\n * extension's space is a control-plane concern; the type carries no\n * such distinction.\n *\n * Generic over the contract so each family pins a typed contract value\n * at consumption time. The SQL family specialises to\n * `ContractSpace<Contract<SqlStorage>>` at the descriptor surface;\n * Mongo's symmetrical `ContractSpace<Contract<MongoStorage>>` will land\n * with that family.\n *\n * @see specs/framework-mechanism.spec.md § 1.\n */\nexport interface ContractSpace<TContract extends Contract = Contract> {\n readonly contractJson: TContract;\n readonly migrations: readonly MigrationPackage[];\n readonly headRef: ContractSpaceHeadRef;\n}\n","import type { JsonValue } from '@prisma-next/contract/types';\nimport { blindCast } from '@prisma-next/utils/casts';\nimport type { CapabilityMatrix } from '../shared/capabilities';\nimport { mergeCapabilityMatrices } from '../shared/capabilities';\nimport type { Codec } from '../shared/codec';\nimport type { AnyCodecDescriptor } from '../shared/codec-descriptor';\nimport type { CodecLookup, CodecMeta, CodecRef, CodecRegistry } from '../shared/codec-types';\nimport type {\n AuthoringContributions,\n AuthoringEntityTypeNamespace,\n AuthoringFieldNamespace,\n AuthoringModelAttributeDescriptorNamespace,\n AuthoringPslBlockDescriptorNamespace,\n AuthoringTypeNamespace,\n} from '../shared/framework-authoring';\nimport {\n assertNoCrossRegistryCollisions,\n mergeAuthoringNamespaces,\n} from '../shared/framework-authoring';\nimport type { ComponentMetadata } from '../shared/framework-components';\nimport type {\n ControlMutationDefaultEntry,\n ControlMutationDefaults,\n MutationDefaultGeneratorDescriptor,\n} from '../shared/mutation-default-types';\nimport {\n CONTRACT_CODEC_DESCRIPTOR_MISSING,\n materializeCodec,\n resolveCodecDescriptorOrThrow,\n} from '../shared/resolve-codec';\nimport type { TypesImportSpec } from '../shared/types-import-spec';\nimport type {\n ControlAdapterDescriptor,\n ControlDriverDescriptor,\n ControlExtensionDescriptor,\n ControlFamilyDescriptor,\n ControlTargetDescriptor,\n} from './control-descriptors';\n\nexport interface AssembledAuthoringContributions {\n readonly field: AuthoringFieldNamespace;\n readonly type: AuthoringTypeNamespace;\n readonly entityTypes: AuthoringEntityTypeNamespace;\n readonly pslBlockDescriptors: AuthoringPslBlockDescriptorNamespace;\n readonly modelAttributes: AuthoringModelAttributeDescriptorNamespace;\n}\n\nexport interface ControlStack<\n TFamilyId extends string = string,\n TTargetId extends string = string,\n> {\n readonly family: ControlFamilyDescriptor<TFamilyId>;\n readonly target: ControlTargetDescriptor<TFamilyId, TTargetId>;\n readonly adapter?: ControlAdapterDescriptor<TFamilyId, TTargetId> | undefined;\n readonly driver?: ControlDriverDescriptor<TFamilyId, TTargetId> | undefined;\n readonly extensionPacks: readonly ControlExtensionDescriptor<TFamilyId, TTargetId>[];\n\n readonly codecTypeImports: ReadonlyArray<TypesImportSpec>;\n readonly queryOperationTypeImports: ReadonlyArray<TypesImportSpec>;\n readonly extensionIds: ReadonlyArray<string>;\n readonly codecLookup: CodecRegistry;\n readonly authoringContributions: AssembledAuthoringContributions;\n readonly scalarTypeDescriptors: ReadonlyMap<string, string>;\n readonly controlMutationDefaults: ControlMutationDefaults;\n readonly capabilities: CapabilityMatrix;\n}\n\nexport interface CreateControlStackInput<\n TFamilyId extends string = string,\n TTargetId extends string = string,\n> {\n readonly family: ControlFamilyDescriptor<TFamilyId>;\n readonly target: ControlTargetDescriptor<TFamilyId, TTargetId>;\n readonly adapter?: ControlAdapterDescriptor<TFamilyId, TTargetId> | undefined;\n readonly driver?: ControlDriverDescriptor<TFamilyId, TTargetId> | undefined;\n readonly extensionPacks?:\n | ReadonlyArray<ControlExtensionDescriptor<TFamilyId, TTargetId>>\n | undefined;\n}\n\nfunction addUniqueId(ids: string[], seen: Set<string>, id: string): void {\n if (!seen.has(id)) {\n ids.push(id);\n seen.add(id);\n }\n}\n\nexport function assertUniqueCodecOwner(options: {\n readonly codecId: string;\n readonly owners: Map<string, string>;\n readonly descriptorId: string;\n readonly entityLabel: string;\n readonly entityOwnershipLabel: string;\n}): void {\n const existingOwner = options.owners.get(options.codecId);\n if (existingOwner !== undefined) {\n throw new Error(\n `Duplicate ${options.entityLabel} for codecId \"${options.codecId}\". ` +\n `Descriptor \"${options.descriptorId}\" conflicts with \"${existingOwner}\". ` +\n `Each codecId can only have one ${options.entityOwnershipLabel}.`,\n );\n }\n}\n\nexport function extractCodecTypeImports(\n descriptors: ReadonlyArray<Pick<ComponentMetadata, 'types'>>,\n): ReadonlyArray<TypesImportSpec> {\n const imports: TypesImportSpec[] = [];\n\n for (const descriptor of descriptors) {\n const codecTypes = descriptor.types?.codecTypes;\n if (codecTypes?.import) {\n imports.push(codecTypes.import);\n }\n if (codecTypes?.typeImports) {\n imports.push(...codecTypes.typeImports);\n }\n }\n\n return imports;\n}\n\nexport function extractQueryOperationTypeImports(\n descriptors: ReadonlyArray<Pick<ComponentMetadata, 'types'>>,\n): ReadonlyArray<TypesImportSpec> {\n const imports: TypesImportSpec[] = [];\n\n for (const descriptor of descriptors) {\n const queryOperationTypes = descriptor.types?.queryOperationTypes;\n if (queryOperationTypes?.import) {\n imports.push(queryOperationTypes.import);\n }\n }\n\n return imports;\n}\n\nexport function extractComponentIds(\n family: { readonly id: string },\n target: { readonly id: string },\n adapter: { readonly id: string } | undefined,\n extensions: ReadonlyArray<{ readonly id: string }>,\n): ReadonlyArray<string> {\n const ids: string[] = [];\n const seen = new Set<string>();\n\n addUniqueId(ids, seen, family.id);\n addUniqueId(ids, seen, target.id);\n if (adapter) {\n addUniqueId(ids, seen, adapter.id);\n }\n\n for (const ext of extensions) {\n addUniqueId(ids, seen, ext.id);\n }\n\n return ids;\n}\n\nexport function assembleAuthoringContributions(\n descriptors: ReadonlyArray<{ readonly authoring?: AuthoringContributions }>,\n): AssembledAuthoringContributions {\n const field = {} as Record<string, unknown>;\n const type = {} as Record<string, unknown>;\n const entityTypes = {} as Record<string, unknown>;\n const pslBlockDescriptors: Record<string, unknown> = {};\n const modelAttributes: Record<string, unknown> = {};\n\n for (const descriptor of descriptors) {\n if (descriptor.authoring?.field) {\n mergeAuthoringNamespaces(field, descriptor.authoring.field, [], 'fieldPreset', 'field');\n }\n if (descriptor.authoring?.type) {\n mergeAuthoringNamespaces(type, descriptor.authoring.type, [], 'typeConstructor', 'type');\n }\n if (descriptor.authoring?.entityTypes) {\n mergeAuthoringNamespaces(\n entityTypes,\n descriptor.authoring.entityTypes,\n [],\n 'entity',\n 'entity',\n );\n }\n if (descriptor.authoring?.pslBlockDescriptors) {\n mergeAuthoringNamespaces(\n pslBlockDescriptors,\n descriptor.authoring.pslBlockDescriptors,\n [],\n 'pslBlock',\n 'pslBlock',\n );\n }\n if (descriptor.authoring?.modelAttributes) {\n mergeAuthoringNamespaces(\n modelAttributes,\n descriptor.authoring.modelAttributes,\n [],\n 'modelAttribute',\n 'modelAttribute',\n );\n }\n }\n\n const fieldNamespace = field as AuthoringFieldNamespace;\n const typeNamespace = type as AuthoringTypeNamespace;\n const entityTypeNamespace = entityTypes as AuthoringEntityTypeNamespace;\n const pslBlockDescriptorNamespace = blindCast<\n AuthoringPslBlockDescriptorNamespace,\n 'merge target accumulator narrows to typed namespace post-merge'\n >(pslBlockDescriptors);\n const modelAttributeNamespace = blindCast<\n AuthoringModelAttributeDescriptorNamespace,\n 'merge target accumulator narrows to typed namespace post-merge'\n >(modelAttributes);\n assertNoCrossRegistryCollisions(\n typeNamespace,\n fieldNamespace,\n entityTypeNamespace,\n pslBlockDescriptorNamespace,\n modelAttributeNamespace,\n );\n\n return {\n field: fieldNamespace,\n type: typeNamespace,\n entityTypes: entityTypeNamespace,\n pslBlockDescriptors: pslBlockDescriptorNamespace,\n modelAttributes: modelAttributeNamespace,\n };\n}\n\nexport function assembleScalarTypeDescriptors(\n descriptors: ReadonlyArray<\n Pick<ComponentMetadata, 'scalarTypeDescriptors'> & { readonly id?: string }\n >,\n): ReadonlyMap<string, string> {\n const result = new Map<string, string>();\n const owners = new Map<string, string>();\n\n for (const descriptor of descriptors) {\n const descriptorMap = descriptor.scalarTypeDescriptors;\n if (!descriptorMap) continue;\n const descriptorId = descriptor.id ?? '<unknown>';\n for (const [typeName, codecId] of descriptorMap) {\n const existingOwner = owners.get(typeName);\n if (existingOwner !== undefined) {\n throw new Error(\n `Duplicate scalar type descriptor \"${typeName}\". ` +\n `Descriptor \"${descriptorId}\" conflicts with \"${existingOwner}\".`,\n );\n }\n result.set(typeName, codecId);\n owners.set(typeName, descriptorId);\n }\n }\n\n return result;\n}\n\nexport function assembleControlMutationDefaults(\n descriptors: ReadonlyArray<\n Pick<ComponentMetadata, 'controlMutationDefaults'> & { readonly id?: string }\n >,\n): ControlMutationDefaults {\n const defaultFunctionRegistry = new Map<string, ControlMutationDefaultEntry>();\n const functionOwners = new Map<string, string>();\n const generatorMap = new Map<string, MutationDefaultGeneratorDescriptor>();\n const generatorOwners = new Map<string, string>();\n\n for (const descriptor of descriptors) {\n const contributions = descriptor.controlMutationDefaults;\n if (!contributions) continue;\n const descriptorId = descriptor.id ?? '<unknown>';\n\n for (const generatorDescriptor of contributions.generatorDescriptors) {\n const existingOwner = generatorOwners.get(generatorDescriptor.id);\n if (existingOwner !== undefined) {\n throw new Error(\n `Duplicate mutation default generator id \"${generatorDescriptor.id}\". ` +\n `Descriptor \"${descriptorId}\" conflicts with \"${existingOwner}\".`,\n );\n }\n generatorMap.set(generatorDescriptor.id, generatorDescriptor);\n generatorOwners.set(generatorDescriptor.id, descriptorId);\n }\n\n for (const [functionName, handler] of contributions.defaultFunctionRegistry) {\n const existingOwner = functionOwners.get(functionName);\n if (existingOwner !== undefined) {\n throw new Error(\n `Duplicate mutation default function \"${functionName}\". ` +\n `Descriptor \"${descriptorId}\" conflicts with \"${existingOwner}\".`,\n );\n }\n defaultFunctionRegistry.set(functionName, handler);\n functionOwners.set(functionName, descriptorId);\n }\n }\n\n return {\n defaultFunctionRegistry,\n generatorDescriptors: Array.from(generatorMap.values()),\n };\n}\n\nexport function extractCodecLookup(\n descriptors: ReadonlyArray<Pick<ComponentMetadata & { id: string }, 'types' | 'id'>>,\n): CodecRegistry {\n const byId = new Map<string, Codec>();\n const descriptorsById = new Map<string, AnyCodecDescriptor>();\n const targetTypesById = new Map<string, readonly string[]>();\n const metaById = new Map<string, CodecMeta>();\n const metaRenderersById = new Map<\n string,\n (params: Record<string, unknown> | JsonValue) => CodecMeta | undefined\n >();\n const renderersById = new Map<string, (params: Record<string, unknown>) => string | undefined>();\n const inputRenderersById = new Map<\n string,\n (params: Record<string, unknown>) => string | undefined\n >();\n const valueLiteralRenderersById = new Map<\n string,\n (value: JsonValue, side: 'output' | 'input') => string | undefined\n >();\n const owners = new Map<string, string>();\n for (const descriptor of descriptors) {\n const codecTypes = descriptor.types?.codecTypes;\n const descriptorId = descriptor.id;\n // Descriptor-side metadata is the single source of truth for `targetTypes` / `meta` / `renderOutputType`. A component contributes its codecs by listing `codecDescriptors` on `types.codecTypes`; each codecId has exactly one contributor across the stack.\n for (const codecDescriptor of codecTypes?.codecDescriptors ?? []) {\n assertUniqueCodecOwner({\n codecId: codecDescriptor.codecId,\n owners,\n descriptorId,\n entityLabel: 'codec descriptor',\n entityOwnershipLabel: 'codec descriptor provider',\n });\n owners.set(codecDescriptor.codecId, descriptorId);\n descriptorsById.set(codecDescriptor.codecId, codecDescriptor);\n if (Array.isArray(codecDescriptor.targetTypes)) {\n targetTypesById.set(codecDescriptor.codecId, codecDescriptor.targetTypes);\n }\n if (codecDescriptor.meta !== undefined) {\n metaById.set(codecDescriptor.codecId, codecDescriptor.meta);\n }\n if (typeof codecDescriptor.metaFor === 'function') {\n metaRenderersById.set(codecDescriptor.codecId, codecDescriptor.metaFor);\n }\n if (typeof codecDescriptor.renderOutputType === 'function') {\n renderersById.set(codecDescriptor.codecId, codecDescriptor.renderOutputType);\n }\n if (typeof codecDescriptor.renderInputType === 'function') {\n inputRenderersById.set(codecDescriptor.codecId, codecDescriptor.renderInputType);\n }\n if (typeof codecDescriptor.renderValueLiteral === 'function') {\n valueLiteralRenderersById.set(codecDescriptor.codecId, codecDescriptor.renderValueLiteral);\n }\n // Materialize a representative `Codec` instance for `byId.get()` so consumers reading the lookup's instance side (e.g. SQL renderer's cast-policy lookup, or the contract emitter's literal-default `encodeJson` resolver) keep finding the codec.\n //\n // Two cohorts:\n // - Non-parameterized descriptors: factory must succeed; any throw is a real bug and we let it propagate (no silent try/catch).\n // - Parameterized descriptors: try with empty params. Many parameterized codecs treat params as advisory (e.g. `pg/timestamptz@1` whose precision is rendered into the `nativeType` only and never read by the runtime codec), so an empty-params construction yields a usable representative for id-keyed lookups (e.g. emit-time literal-default encoding). Codecs whose factory genuinely requires params (e.g. `pg/vector@1` threading `length` into the runtime codec) will throw; for those, per-column instances are materialized at runtime by `buildContractCodecRegistry` and the id-keyed lookup miss is correct (the column-aware path resolves them).\n if (!byId.has(codecDescriptor.codecId)) {\n if (codecDescriptor.isParameterized) {\n try {\n const representative = codecDescriptor.factory({} as never)({\n name: `<lookup:${codecDescriptor.codecId}>`,\n } as Parameters<ReturnType<typeof codecDescriptor.factory>>[0]);\n byId.set(codecDescriptor.codecId, representative);\n } catch {\n // Factory requires concrete params; skip representative materialization. Per-column instances are built at runtime; id-keyed lookup miss is the correct outcome here.\n }\n } else {\n const representative = codecDescriptor.factory(undefined as never)({\n name: `<lookup:${codecDescriptor.codecId}>`,\n } as Parameters<ReturnType<typeof codecDescriptor.factory>>[0]);\n byId.set(codecDescriptor.codecId, representative);\n }\n }\n }\n }\n return {\n get: (id) => byId.get(id),\n forCodecRef(ref: CodecRef) {\n const d = resolveCodecDescriptorOrThrow(\n (id) => descriptorsById.get(id),\n ref,\n CONTRACT_CODEC_DESCRIPTOR_MISSING,\n );\n return materializeCodec(d, ref, { name: `<ref:${ref.codecId}>` });\n },\n forColumn: () => undefined,\n targetTypesFor: (id) => targetTypesById.get(id),\n metaFor: (id, typeParams) => {\n if (typeParams !== undefined) {\n const paramsAware = metaRenderersById.get(id)?.(typeParams);\n if (paramsAware !== undefined) return paramsAware;\n }\n return metaById.get(id);\n },\n renderOutputTypeFor: (id, params) => renderersById.get(id)?.(params),\n renderInputTypeFor: (id, params) => inputRenderersById.get(id)?.(params),\n renderValueLiteralFor: (id, value, side) => valueLiteralRenderersById.get(id)?.(value, side),\n descriptorFor: (id) => descriptorsById.get(id),\n };\n}\n\nexport function validateScalarTypeCodecIds(\n scalarTypeDescriptors: ReadonlyMap<string, string>,\n codecLookup: CodecLookup,\n): string[] {\n const errors: string[] = [];\n for (const [typeName, codecId] of scalarTypeDescriptors) {\n if (!codecLookup.get(codecId)) {\n errors.push(\n `Scalar type \"${typeName}\" references codec \"${codecId}\" which is not registered by any component.`,\n );\n }\n }\n return errors;\n}\n\ninterface DependencyDeclaringDescriptor {\n readonly id: string;\n readonly contractSpace?: {\n readonly contractJson?: {\n readonly extensionPacks?: Readonly<Record<string, unknown>>;\n };\n };\n}\n\nfunction readDeclaredDependencyIds(descriptor: DependencyDeclaringDescriptor): readonly string[] {\n const packs = descriptor.contractSpace?.contractJson?.extensionPacks;\n if (packs === null || typeof packs !== 'object') return [];\n return Object.keys(packs);\n}\n\n/**\n * Builds a dependency-respecting load order for the given extension descriptors\n * using Kahn's topological sort algorithm. Dependencies (packs declared in\n * `contractSpace.contractJson.extensionPacks`) are placed before the extensions\n * that depend on them.\n *\n * Throws if the dependency graph contains a cycle, with an error message that\n * names every extension involved in the cycle.\n *\n * Throws if any extension declares a dependency on a pack ID that is not present\n * in the provided list — add the missing pack to the `extensionPacks` list to\n * resolve the error.\n */\n\nexport function buildExtensionLoadOrder(\n extensions: ReadonlyArray<DependencyDeclaringDescriptor>,\n): readonly string[] {\n if (extensions.length === 0) return [];\n\n const idSet = new Set(extensions.map((e) => e.id));\n const inDegree = new Map<string, number>();\n const dependents = new Map<string, string[]>();\n\n for (const ext of extensions) {\n if (!inDegree.has(ext.id)) inDegree.set(ext.id, 0);\n if (!dependents.has(ext.id)) dependents.set(ext.id, []);\n }\n\n for (const ext of extensions) {\n for (const depId of readDeclaredDependencyIds(ext)) {\n if (!idSet.has(depId)) {\n throw new Error(\n `Extension \"${ext.id}\" declares a dependency on \"${depId}\", but \"${depId}\" is not in the provided extension set. Add the missing space to extensionPacks.`,\n );\n }\n inDegree.set(ext.id, (inDegree.get(ext.id) ?? 0) + 1);\n const list = dependents.get(depId);\n if (list !== undefined) list.push(ext.id);\n }\n }\n\n const queue: string[] = [];\n for (const [id, deg] of inDegree) {\n if (deg === 0) queue.push(id);\n }\n queue.sort();\n\n const result: string[] = [];\n while (queue.length > 0) {\n const id = queue.shift();\n if (id === undefined) break;\n result.push(id);\n const children = dependents.get(id) ?? [];\n children.sort();\n for (const childId of children) {\n const newDeg = (inDegree.get(childId) ?? 1) - 1;\n inDegree.set(childId, newDeg);\n if (newDeg === 0) queue.push(childId);\n }\n }\n\n if (result.length < extensions.length) {\n const cycleMembers = extensions\n .map((e) => e.id)\n .filter((id) => !result.includes(id))\n .sort();\n throw new Error(\n `Extension dependency cycle detected. Cycle members: ${cycleMembers.map((id) => `\"${id}\"`).join(', ')}.`,\n );\n }\n\n return result;\n}\n\nexport function createControlStack<TFamilyId extends string, TTargetId extends string>(\n input: CreateControlStackInput<TFamilyId, TTargetId>,\n): ControlStack<TFamilyId, TTargetId> {\n const { family, target, adapter, driver, extensionPacks = [] } = input;\n\n const orderedIds = buildExtensionLoadOrder(extensionPacks);\n const extensionById = new Map(extensionPacks.map((ext) => [ext.id, ext]));\n const orderedExtensionPacks = orderedIds\n .map((id) => extensionById.get(id))\n .filter((ext): ext is ControlExtensionDescriptor<TFamilyId, TTargetId> => ext !== undefined);\n\n const allDescriptors = [family, target, ...(adapter ? [adapter] : []), ...orderedExtensionPacks];\n\n const codecLookup = extractCodecLookup(allDescriptors);\n const scalarTypeDescriptors = assembleScalarTypeDescriptors(allDescriptors);\n\n return {\n family,\n target,\n adapter,\n driver,\n extensionPacks: orderedExtensionPacks,\n\n codecTypeImports: extractCodecTypeImports(allDescriptors),\n queryOperationTypeImports: extractQueryOperationTypeImports(allDescriptors),\n extensionIds: extractComponentIds(family, target, adapter, orderedExtensionPacks),\n codecLookup,\n authoringContributions: assembleAuthoringContributions(allDescriptors),\n scalarTypeDescriptors,\n controlMutationDefaults: assembleControlMutationDefaults(allDescriptors),\n capabilities: mergeCapabilityMatrices({}, [\n target,\n ...(adapter ? [adapter] : []),\n ...orderedExtensionPacks,\n ]),\n };\n}\n","import type { ExpectationFailureReason } from './control-operation-results';\n\nexport interface SchemaDiffIssue<TNode extends DiffableNode = DiffableNode> {\n /** Path from the root node down to the diffed node, as a sequence of local keys. */\n readonly path: readonly string[];\n /** Why the actual state fails the expectation. Consumers filter on this field. */\n readonly reason: ExpectationFailureReason;\n /** The expected (desired-side) node, when available. Absent for `not-expected` issues. */\n readonly expected?: TNode;\n /** The actual (current-side) node, when available. Absent for `not-found` issues. */\n readonly actual?: TNode;\n}\n\n/**\n * A node in the schema tree. Every node in the tree implements this interface.\n *\n * The differ pairs siblings by the combination of `nodeKind` and `id`, not by\n * `id` alone: `id` needs only be unique among siblings of the same\n * `nodeKind` at the same level, not globally unique at that level. Two\n * distinct kinds of child in distinct slots (e.g. a role and a namespace) may\n * legitimately share a name — they are never paired against each other, so\n * the collision is harmless. A node never folds its kind into its id string\n * to route around this; `nodeKind` is the discriminant that does that job.\n * A same-`nodeKind`/same-`id` collision among siblings is a genuine\n * duplicate and is enforced by a throw. The differ accumulates ids (not\n * nodeKind) into a path that stamps every emitted issue.\n */\nexport interface DiffableNode {\n readonly id: string;\n readonly nodeKind: string;\n isEqualTo(other: DiffableNode): boolean;\n children(): readonly DiffableNode[];\n}\n\n/** Delimiter joining `nodeKind` and `id` into one sibling-map key. Every `nodeKind` is a code-defined literal (kebab-case-style), so a null character can never appear in one. */\nconst SIBLING_KEY_DELIMITER = '\\u0000';\n\nfunction siblingKey(node: DiffableNode): string {\n return `${node.nodeKind}${SIBLING_KEY_DELIMITER}${node.id}`;\n}\n\nfunction insertNode(map: Map<string, DiffableNode>, node: DiffableNode): void {\n const key = siblingKey(node);\n if (map.has(key)) {\n throw new Error(`diffSchemas: duplicate id among siblings: ${node.nodeKind}/${node.id}`);\n }\n map.set(key, node);\n}\n\nfunction emitMissingSubtree(node: DiffableNode, parentPath: readonly string[]): SchemaDiffIssue[] {\n const path = [...parentPath, node.id];\n return [\n {\n path,\n reason: 'not-found',\n expected: node,\n },\n ...node.children().flatMap((c) => emitMissingSubtree(c, path)),\n ];\n}\n\nfunction emitExtraSubtree(node: DiffableNode, parentPath: readonly string[]): SchemaDiffIssue[] {\n const path = [...parentPath, node.id];\n return [\n {\n path,\n reason: 'not-expected',\n actual: node,\n },\n ...node.children().flatMap((c) => emitExtraSubtree(c, path)),\n ];\n}\n\n/**\n * Diff two schema trees starting from their roots.\n *\n * The differ is **total**: every node-level difference is reported. An unmatched\n * non-leaf node emits its own issue and descends, emitting an issue for every\n * node in the missing/extra subtree. Coalescing a parent change over its\n * children is the planner's responsibility. Ownership filtering (dropping `extra`\n * issues in namespaces a contract doesn't own) is the caller's responsibility.\n */\nexport function diffSchemas(\n expected: DiffableNode,\n actual: DiffableNode,\n): readonly SchemaDiffIssue[] {\n return diffPair(expected, actual, []);\n}\n\nfunction diffPair(\n expected: DiffableNode,\n actual: DiffableNode,\n parentPath: readonly string[],\n): readonly SchemaDiffIssue[] {\n const path = [...parentPath, expected.id];\n const issues: SchemaDiffIssue[] = [];\n if (!expected.isEqualTo(actual)) {\n issues.push({\n path,\n reason: 'not-equal',\n expected,\n actual,\n });\n }\n issues.push(...diffChildren(expected.children(), actual.children(), path));\n return issues;\n}\n\n/**\n * Align one level of nodes by `(nodeKind, id)`; emit issues in input order\n * and recurse.\n *\n * A missing node emits one issue for itself and one for every node in its\n * subtree (total descent). Same for extra nodes. A matched pair recurses via\n * `diffPair`.\n */\nfunction diffChildren(\n expected: readonly DiffableNode[],\n actual: readonly DiffableNode[],\n parentPath: readonly string[],\n): readonly SchemaDiffIssue[] {\n const expectedMap = new Map<string, DiffableNode>();\n for (const node of expected) {\n insertNode(expectedMap, node);\n }\n\n const actualMap = new Map<string, DiffableNode>();\n for (const node of actual) {\n insertNode(actualMap, node);\n }\n\n const issues: SchemaDiffIssue[] = [];\n\n for (const [key, expectedNode] of expectedMap) {\n const actualNode = actualMap.get(key);\n if (actualNode === undefined) {\n issues.push(...emitMissingSubtree(expectedNode, parentPath));\n } else {\n issues.push(...diffPair(expectedNode, actualNode, parentPath));\n }\n }\n\n for (const [key, actualNode] of actualMap) {\n if (!expectedMap.has(key)) {\n issues.push(...emitExtraSubtree(actualNode, parentPath));\n }\n }\n\n return issues;\n}\n\n/**\n * The result of diffing a contract's expected schema against the introspected\n * actual schema: one node-typed issue list. Carries no verdict, verification\n * tree, or counts — those are the verifier's own presentation, built from the\n * same underlying comparison.\n *\n * `TNode` is the concrete schema-IR node the issues carry; it defaults to\n * `DiffableNode`, so this is purely additive — a caller that wants the\n * concrete node opts in (the Postgres planner uses the concrete node type),\n * everyone else keeps the default unchanged.\n */\nexport class SchemaDiff<TNode extends DiffableNode = DiffableNode> {\n readonly issues: readonly SchemaDiffIssue<TNode>[];\n\n constructor(issues: readonly SchemaDiffIssue<TNode>[]) {\n this.issues = issues;\n }\n\n /** Returns a new `SchemaDiff` narrowed to the issues `keep` returns true for. */\n filter(keep: (issue: SchemaDiffIssue<TNode>) => boolean): SchemaDiff<TNode> {\n return new SchemaDiff(this.issues.filter(keep));\n }\n}\n","import type { ControlPolicy } from '@prisma-next/contract/types';\n\nexport type VerificationStatus = 'pass' | 'warn' | 'fail';\n\nexport type VerifierOutcome = VerificationStatus | 'suppress';\n\n/**\n * Target-neutral classification of a verifier finding, abstracted away from any\n * one storage model's vocabulary. Each family classifies its own concrete issue\n * kinds into these categories; the framework only grades the category against a\n * control policy.\n *\n * - `declaredMissing` — a declared object/element is absent from the database.\n * - `declaredIncompatible` — a declared object/element exists but its shape diverges.\n * - `valueDrift` — the value set of an existing type drifted (e.g. enum values).\n * - `extraNestedElement` — an undeclared element nested inside a declared object\n * (a SQL column, a document field).\n * - `extraAuxiliary` — an undeclared auxiliary attached to a declared object\n * (a SQL constraint/index, a Mongo index/validator).\n * - `extraTopLevelObject` — an undeclared top-level object (a SQL table, a\n * Mongo collection).\n */\nexport type VerifierIssueCategory =\n | 'declaredMissing'\n | 'declaredIncompatible'\n | 'valueDrift'\n | 'extraNestedElement'\n | 'extraAuxiliary'\n | 'extraTopLevelObject';\n\n/**\n * Grades a target-neutral issue category against a control policy.\n *\n * - `observed` warns on everything.\n * - `tolerated` suppresses only an extra nested element (everything else fails).\n * - `external` suppresses every extra category and value drift (existence and\n * declared-shape divergences still fail).\n * - `managed` (and any other) fails.\n */\nexport function dispositionForCategory(\n controlPolicy: ControlPolicy,\n category: VerifierIssueCategory,\n): VerifierOutcome {\n if (controlPolicy === 'observed') {\n return 'warn';\n }\n if (controlPolicy === 'tolerated' && category === 'extraNestedElement') {\n return 'suppress';\n }\n if (controlPolicy === 'external') {\n if (\n category === 'extraNestedElement' ||\n category === 'extraAuxiliary' ||\n category === 'extraTopLevelObject' ||\n category === 'valueDrift'\n ) {\n return 'suppress';\n }\n }\n return 'fail';\n}\n"],"mappings":";;;;;AAmBA,SAAgB,cACd,QAC4D;CAC5D,OAAO,gBAAgB,UAAU,CAAC,CAAE,OAAmC;AACzE;AAMA,SAAgB,cACd,UACwF;CACxF,OACE,kBAAkB,YAClB,OAAQ,SAAqC,oBAAoB;AAErE;AAUA,SAAgB,oBACd,UAC8F;CAC9F,OACE,sBAAsB,YACtB,OAAQ,SAAqC,wBAAwB;AAEzE;AAWA,SAAgB,oBACd,UACmF;CACnF,OACE,wBAAwB,YACxB,OAAQ,SAAqC,0BAA0B;AAE3E;AAqCA,SAAgB,2BACd,UAC0F;CAC1F,OACE,gCAAgC,YAChC,OAAQ,SAAqC,kCAAkC,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AC4B;CAC5B,MAAM,8BAAc,IAAI,IAA0B;CAClD,KAAK,MAAM,QAAQ,UACjB,WAAW,aAAa,IAAI;CAG9B,MAAM,4BAAY,IAAI,IAA0B;CAChD,KAAK,MAAM,QAAQ,QACjB,WAAW,WAAW,IAAI;CAG5B,MAAM,SAA4B,CAAC;CAEnC,KAAK,MAAM,CAAC,KAAK,iBAAiB,aAAa;EAC7C,MAAM,aAAa,UAAU,IAAI,GAAG;EACpC,IAAI,eAAe,KAAA,GACjB,OAAO,KAAK,GAAG,mBAAmB,cAAc,UAAU,CAAC;OAE3D,OAAO,KAAK,GAAG,SAAS,cAAc,YAAY,UAAU,CAAC;CAEjE;CAEA,KAAK,MAAM,CAAC,KAAK,eAAe,WAC9B,IAAI,CAAC,YAAY,IAAI,GAAG,GACtB,OAAO,KAAK,GAAG,iBAAiB,YAAY,UAAU,CAAC;CAI3D,OAAO;AACT;;;;;;;;;;;;AAaA,IAAa,aAAb,MAAa,WAAsD;CACjE;CAEA,YAAY,QAA2C;EACrD,KAAK,SAAS;CAChB;;CAGA,OAAO,MAAqE;EAC1E,OAAO,IAAI,WAAW,KAAK,OAAO,OAAO,IAAI,CAAC;CAChD;AACF;;;;;;;;;;;;ACtIA,SAAgB,uBACd,eACA,UACiB;CACjB,IAAI,kBAAkB,YACpB,OAAO;CAET,IAAI,kBAAkB,eAAe,aAAa,sBAChD,OAAO;CAET,IAAI,kBAAkB;MAElB,aAAa,wBACb,aAAa,oBACb,aAAa,yBACb,aAAa,cAEb,OAAO;CAAA;CAGX,OAAO;AACT"}
{"version":3,"file":"control.mjs","names":[],"sources":["../src/control/control-capabilities.ts","../src/control/control-operation-results.ts","../src/control/control-schema-view.ts","../src/control/control-spaces.ts","../src/control/control-stack.ts","../src/control/schema-diff.ts","../src/control/verifier-disposition.ts"],"sourcesContent":["import type { ControlTargetDescriptor } from './control-descriptors';\nimport type { ControlFamilyInstance } from './control-instances';\nimport type { MigrationPlanOperation, TargetMigrationsCapability } from './control-migration-types';\nimport type { OperationPreview } from './control-operation-preview';\nimport type { CoreSchemaView } from './control-schema-view';\nimport type { PslDocumentAst } from './psl-ast';\nimport type { SchemaDiffIssue } from './schema-diff';\n\nexport interface MigratableTargetDescriptor<\n TFamilyId extends string,\n TTargetId extends string,\n TFamilyInstance extends ControlFamilyInstance<TFamilyId, unknown> = ControlFamilyInstance<\n TFamilyId,\n unknown\n >,\n> extends ControlTargetDescriptor<TFamilyId, TTargetId> {\n readonly migrations: TargetMigrationsCapability<TFamilyId, TTargetId, TFamilyInstance>;\n}\n\nexport function hasMigrations<TFamilyId extends string, TTargetId extends string>(\n target: ControlTargetDescriptor<TFamilyId, TTargetId>,\n): target is MigratableTargetDescriptor<TFamilyId, TTargetId> {\n return 'migrations' in target && !!(target as Record<string, unknown>)['migrations'];\n}\n\nexport interface SchemaViewCapable<TSchemaIR = unknown> {\n toSchemaView(schema: TSchemaIR): CoreSchemaView;\n}\n\nexport function hasSchemaView<TFamilyId extends string, TSchemaIR>(\n instance: ControlFamilyInstance<TFamilyId, TSchemaIR>,\n): instance is ControlFamilyInstance<TFamilyId, TSchemaIR> & SchemaViewCapable<TSchemaIR> {\n return (\n 'toSchemaView' in instance &&\n typeof (instance as Record<string, unknown>)['toSchemaView'] === 'function'\n );\n}\n\n/**\n * Capability declaring that a family can infer a PSL contract AST from its\n * opaque introspected schema IR. Consumed by `prisma-next contract infer`.\n */\nexport interface PslContractInferCapable<TSchemaIR = unknown> {\n inferPslContract(schemaIR: TSchemaIR): PslDocumentAst;\n}\n\nexport function hasPslContractInfer<TFamilyId extends string, TSchemaIR>(\n instance: ControlFamilyInstance<TFamilyId, TSchemaIR>,\n): instance is ControlFamilyInstance<TFamilyId, TSchemaIR> & PslContractInferCapable<TSchemaIR> {\n return (\n 'inferPslContract' in instance &&\n typeof (instance as Record<string, unknown>)['inferPslContract'] === 'function'\n );\n}\n\n/**\n * Capability declaring that a family can render a textual preview of migration\n * operations for the CLI's \"DDL preview\" output. SQL families emit\n * `language: 'sql'` statements; Mongo families emit `language: 'mongodb-shell'`.\n */\nexport interface OperationPreviewCapable {\n toOperationPreview(operations: readonly MigrationPlanOperation[]): OperationPreview;\n}\n\nexport function hasOperationPreview<TFamilyId extends string, TSchemaIR>(\n instance: ControlFamilyInstance<TFamilyId, TSchemaIR>,\n): instance is ControlFamilyInstance<TFamilyId, TSchemaIR> & OperationPreviewCapable {\n return (\n 'toOperationPreview' in instance &&\n typeof (instance as Record<string, unknown>)['toOperationPreview'] === 'function'\n );\n}\n\n/**\n * The granularity of a {@link SchemaDiffIssue}'s subject, resolved on demand\n * from the issue's node `nodeKind` — never stamped on the issue or the node.\n *\n * - `namespace`: a whole namespace.\n * - `entity`: a whole top-level entity (the thing a namespace contains).\n * - `field`: a field of an entity.\n * - `auxiliary`: a secondary part of an entity (an index, a default, a key).\n * - `structural`: a cross-cutting object (an access policy, a tree root) that\n * is the owning space's own concern, never a sibling's unclaimed entity —\n * its extras fail verify in both modes.\n */\nexport type DiffSubjectGranularity = 'namespace' | 'entity' | 'field' | 'auxiliary' | 'structural';\n\n/**\n * Capability declaring that a family can classify a {@link SchemaDiffIssue}'s\n * subject granularity, and separately its storage `entityKind`, on demand —\n * both resolved from its node's `nodeKind` through the family/target\n * vocabulary it owns. Consumed by framework code that spans contract spaces\n * (the migration aggregate's unclaimed-elements sweep) and cannot itself read\n * family/target node vocabulary, so it asks this capability instead of\n * hardcoding a family entity kind. `undefined` when the issue's node kind is\n * unrecognized, or when the family injects no classifier at all — callers\n * fall back to path shape in that case.\n *\n * `classifyEntityKind` returns the same per-family vocabulary as the contract\n * storage's `entries` dictionary keys (the vocabulary\n * {@link import('../ir/storage').elementCoordinates} walks) — never a\n * granularity word, and never a word this framework layer names itself.\n */\nexport interface SchemaSubjectClassifierCapable {\n classifySubjectGranularity(issue: SchemaDiffIssue): DiffSubjectGranularity | undefined;\n classifyEntityKind(issue: SchemaDiffIssue): string | undefined;\n}\n\nexport function hasSchemaSubjectClassifier<TFamilyId extends string, TSchemaIR>(\n instance: ControlFamilyInstance<TFamilyId, TSchemaIR>,\n): instance is ControlFamilyInstance<TFamilyId, TSchemaIR> & SchemaSubjectClassifierCapable {\n return (\n 'classifySubjectGranularity' in instance &&\n typeof (instance as Record<string, unknown>)['classifySubjectGranularity'] === 'function' &&\n 'classifyEntityKind' in instance &&\n typeof (instance as Record<string, unknown>)['classifyEntityKind'] === 'function'\n );\n}\n","import type { SchemaDiffIssue } from './schema-diff';\n\nexport const VERIFY_CODE_MARKER_MISSING = 'PN-RUN-3001';\nexport const VERIFY_CODE_HASH_MISMATCH = 'PN-RUN-3002';\nexport const VERIFY_CODE_TARGET_MISMATCH = 'PN-RUN-3003';\nexport const VERIFY_CODE_SCHEMA_FAILURE = 'PN-RUN-3010';\n\nexport interface OperationContext {\n readonly contractPath?: string;\n readonly configPath?: string;\n readonly meta?: Readonly<Record<string, unknown>>;\n}\n\nexport interface VerifyDatabaseResult {\n readonly ok: boolean;\n readonly code?: string;\n readonly summary: string;\n readonly contract: {\n readonly storageHash: string;\n readonly profileHash?: string;\n };\n readonly marker?: {\n readonly storageHash?: string;\n readonly profileHash?: string;\n };\n readonly target: {\n readonly expected: string;\n readonly actual?: string;\n };\n readonly missingCodecs?: readonly string[];\n readonly codecCoverageSkipped?: boolean;\n readonly meta?: {\n readonly configPath?: string;\n readonly contractPath: string;\n };\n readonly timings: {\n readonly total: number;\n };\n}\n\n/**\n * The three ways an actual state can fail an expectation: it contains a node\n * that was not expected, lacks a node that was expected, or holds a node that\n * is not equal to the expected one. Expected is the desired side and actual the\n * current side of whatever comparison produced the issue — contract-vs-database,\n * or contract-vs-contract in an offline plan — so the vocabulary is\n * comparison-relative and never ambiguous about a base.\n *\n * The failure reason is a structural characteristic carried as a declared\n * field: consumers filter on `reason`, never by enumerating kind strings or\n * family-invented node codes.\n */\nexport type ExpectationFailureReason = 'not-expected' | 'not-found' | 'not-equal';\n\n/**\n * The issue-based schema-verify result. `ok` derives from the FAILURE list\n * only: a verify passes exactly when `schema.issues` is empty, post\n * strict-gating and control-policy disposition.\n *\n * `schema.warnings` carries warn-graded issues (an `observed`-policy\n * subject's drift, and any other `warn` disposition) in the same shape.\n * Warnings are informational — they never affect `ok` — but they MUST be\n * surfaced: an `observed` table that drifted yields `ok: true` with a\n * non-empty warnings channel, which is what distinguishes \"watch without\n * failing\" from full suppression.\n */\nexport interface VerifyDatabaseSchemaResult {\n readonly ok: boolean;\n readonly code?: string;\n readonly summary: string;\n readonly contract: {\n readonly storageHash: string;\n readonly profileHash?: string;\n };\n readonly target: {\n readonly expected: string;\n readonly actual?: string;\n };\n readonly schema: {\n readonly issues: readonly SchemaDiffIssue[];\n readonly warnings?: {\n readonly issues: readonly SchemaDiffIssue[];\n };\n };\n readonly meta?: {\n readonly configPath?: string;\n readonly contractPath?: string;\n readonly strict: boolean;\n };\n readonly timings: {\n readonly total: number;\n };\n}\n\nexport interface EmitContractResult {\n readonly contractJson: string;\n readonly contractDts: string;\n readonly storageHash: string;\n readonly executionHash?: string;\n readonly profileHash: string;\n}\n\nexport interface IntrospectSchemaResult<TSchemaIR> {\n readonly ok: true;\n readonly summary: string;\n readonly target: {\n readonly familyId: string;\n readonly id: string;\n };\n readonly schema: TSchemaIR;\n readonly meta?: {\n readonly configPath?: string;\n readonly dbUrl?: string;\n };\n readonly timings: {\n readonly total: number;\n };\n}\n\nexport interface SignDatabaseResult {\n readonly ok: boolean;\n readonly summary: string;\n readonly contract: {\n readonly storageHash: string;\n readonly profileHash?: string;\n };\n readonly target: {\n readonly expected: string;\n readonly actual?: string;\n };\n readonly marker: {\n readonly created: boolean;\n readonly updated: boolean;\n readonly previous?: {\n readonly storageHash?: string;\n readonly profileHash?: string;\n };\n };\n readonly meta?: {\n readonly configPath?: string;\n readonly contractPath: string;\n };\n readonly timings: {\n readonly total: number;\n };\n}\n","/**\n * Core schema view types for family-agnostic schema visualization.\n *\n * These types provide a minimal, generic, tree-shaped representation of schemas\n * across families, designed for CLI visualization and lightweight tooling.\n *\n * Families can optionally project their family-specific Schema IR into this\n * core view via the `toSchemaView` method on `FamilyInstance`.\n */\n\nexport type SchemaViewNodeKind =\n | 'root'\n | 'namespace'\n | 'collection'\n | 'entity'\n | 'field'\n | 'index'\n | 'dependency';\n\nexport interface SchemaTreeVisitor<R> {\n visit(node: SchemaTreeNode): R;\n}\n\nexport interface SchemaTreeNodeOptions {\n readonly kind: SchemaViewNodeKind;\n readonly id: string;\n readonly label: string;\n readonly meta?: Record<string, unknown>;\n readonly children?: readonly SchemaTreeNode[];\n}\n\nexport class SchemaTreeNode {\n readonly kind: SchemaViewNodeKind;\n readonly id: string;\n readonly label: string;\n readonly meta?: Record<string, unknown>;\n readonly children?: readonly SchemaTreeNode[];\n\n constructor(options: SchemaTreeNodeOptions) {\n this.kind = options.kind;\n this.id = options.id;\n this.label = options.label;\n if (options.meta !== undefined) this.meta = options.meta;\n if (options.children !== undefined) this.children = options.children;\n Object.freeze(this);\n }\n\n accept<R>(visitor: SchemaTreeVisitor<R>): R {\n return visitor.visit(this);\n }\n}\n\n/**\n * Core schema view providing a family-agnostic tree representation of a schema.\n * Used by CLI and cross-family tooling for visualization.\n */\nexport interface CoreSchemaView {\n readonly root: SchemaTreeNode;\n}\n","import type { Contract } from '@prisma-next/contract/types';\nimport type { MigrationMetadata, MigrationPlanOperation } from './control-migration-types';\n\n/**\n * Canonical control-plane identifiers for contract spaces.\n *\n * A contract space is the disjoint `(contract.json, migration-graph)` unit\n * the per-space planner / runner / verifier (project: extension contract\n * spaces, TML-2397) operates on. The application owns one well-known\n * space — the value below — and each loaded extension that contributes\n * schema owns a uniquely-named space.\n *\n * Lives in `framework-components/control` so every layer that has to\n * reason about space identity (the migration tooling, the SQL runtime's\n * marker reader, target-side statement builders, target-side adapters)\n * can import a single value rather than duplicating the literal. Raw\n * `'app'` string literals in framework / target / runtime / adapter\n * source code are forbidden and policed by\n * `scripts/lint-app-space-id.mjs` (wired into `pnpm lint:deps`).\n *\n * @see specs/framework-mechanism.spec.md § 3 — Layout convention (γ).\n */\nexport const APP_SPACE_ID = 'app' as const;\n\n/**\n * Head ref for a contract space — the `(hash, invariants)` tuple\n * a runner targets when applying that space's migration graph. Identical\n * in shape to the on-disk `migrations/<space-id>/refs/head.json` the\n * framework writes per loaded extension, and to the app-space\n * `<projectRoot>/refs/head.json`. Family-agnostic: SQL, Mongo, and any\n * future family share the same head-ref shape.\n *\n * @see specs/framework-mechanism.spec.md § 1.\n */\nexport interface ContractSpaceHeadRef {\n readonly hash: string;\n readonly invariants: readonly string[];\n}\n\n/**\n * Canonical structural shape of a migration package — the unit a planner\n * produces and a runner consumes: a directory name, the metadata\n * envelope, and the operation list.\n *\n * In-memory by default. Readers in `@prisma-next/migration-tools`\n * (`readMigrationPackage` / `readMigrationsDir`) return the augmented\n * {@link import('@prisma-next/migration-tools/package').OnDiskMigrationPackage}\n * variant which adds `dirPath`; everything else operates against the\n * canonical shape so the same value flows through pre-emission\n * authoring, on-disk loading, and runner execution without conversion.\n *\n * @see specs/framework-mechanism.spec.md § 1.\n */\nexport interface MigrationPackage {\n readonly dirName: string;\n readonly metadata: MigrationMetadata;\n readonly ops: readonly MigrationPlanOperation[];\n}\n\n/**\n * Canonical structural shape of a contract space — one disjoint\n * `(contractJson, migration-graph)` unit the per-space planner / runner\n * / verifier operates on. The application owns one well-known space\n * ({@link APP_SPACE_ID}); each loaded extension that contributes schema\n * owns a uniquely-named space. Whether a value is the app's space or an\n * extension's space is a control-plane concern; the type carries no\n * such distinction.\n *\n * Generic over the contract so each family pins a typed contract value\n * at consumption time. The SQL family specialises to\n * `ContractSpace<Contract<SqlStorage>>` at the descriptor surface;\n * Mongo's symmetrical `ContractSpace<Contract<MongoStorage>>` will land\n * with that family.\n *\n * @see specs/framework-mechanism.spec.md § 1.\n */\nexport interface ContractSpace<TContract extends Contract = Contract> {\n readonly contractJson: TContract;\n readonly migrations: readonly MigrationPackage[];\n readonly headRef: ContractSpaceHeadRef;\n}\n","import type { JsonValue } from '@prisma-next/contract/types';\nimport { blindCast } from '@prisma-next/utils/casts';\nimport type { CapabilityMatrix } from '../shared/capabilities';\nimport { mergeCapabilityMatrices } from '../shared/capabilities';\nimport type { Codec } from '../shared/codec';\nimport type { AnyCodecDescriptor } from '../shared/codec-descriptor';\nimport type { CodecLookup, CodecMeta, CodecRef, CodecRegistry } from '../shared/codec-types';\nimport type {\n AuthoringContributions,\n AuthoringEntityTypeNamespace,\n AuthoringFieldNamespace,\n AuthoringModelAttributeDescriptorNamespace,\n AuthoringPslBlockDescriptorNamespace,\n AuthoringTypeNamespace,\n} from '../shared/framework-authoring';\nimport {\n assertNoCrossRegistryCollisions,\n mergeAuthoringNamespaces,\n} from '../shared/framework-authoring';\nimport type { ComponentMetadata } from '../shared/framework-components';\nimport type {\n ControlMutationDefaultEntry,\n ControlMutationDefaults,\n MutationDefaultGeneratorDescriptor,\n} from '../shared/mutation-default-types';\nimport {\n CONTRACT_CODEC_DESCRIPTOR_MISSING,\n materializeCodec,\n resolveCodecDescriptorOrThrow,\n} from '../shared/resolve-codec';\nimport type { TypesImportSpec } from '../shared/types-import-spec';\nimport type {\n ControlAdapterDescriptor,\n ControlDriverDescriptor,\n ControlExtensionDescriptor,\n ControlFamilyDescriptor,\n ControlTargetDescriptor,\n} from './control-descriptors';\n\nexport interface AssembledAuthoringContributions {\n readonly field: AuthoringFieldNamespace;\n readonly type: AuthoringTypeNamespace;\n readonly entityTypes: AuthoringEntityTypeNamespace;\n readonly pslBlockDescriptors: AuthoringPslBlockDescriptorNamespace;\n readonly modelAttributes: AuthoringModelAttributeDescriptorNamespace;\n}\n\nexport interface ControlStack<\n TFamilyId extends string = string,\n TTargetId extends string = string,\n> {\n readonly family: ControlFamilyDescriptor<TFamilyId>;\n readonly target: ControlTargetDescriptor<TFamilyId, TTargetId>;\n readonly adapter?: ControlAdapterDescriptor<TFamilyId, TTargetId> | undefined;\n readonly driver?: ControlDriverDescriptor<TFamilyId, TTargetId> | undefined;\n readonly extensionPacks: readonly ControlExtensionDescriptor<TFamilyId, TTargetId>[];\n\n readonly codecTypeImports: ReadonlyArray<TypesImportSpec>;\n readonly queryOperationTypeImports: ReadonlyArray<TypesImportSpec>;\n readonly extensionIds: ReadonlyArray<string>;\n readonly codecLookup: CodecRegistry;\n readonly authoringContributions: AssembledAuthoringContributions;\n readonly scalarTypeDescriptors: ReadonlyMap<string, string>;\n readonly controlMutationDefaults: ControlMutationDefaults;\n readonly capabilities: CapabilityMatrix;\n}\n\nexport interface CreateControlStackInput<\n TFamilyId extends string = string,\n TTargetId extends string = string,\n> {\n readonly family: ControlFamilyDescriptor<TFamilyId>;\n readonly target: ControlTargetDescriptor<TFamilyId, TTargetId>;\n readonly adapter?: ControlAdapterDescriptor<TFamilyId, TTargetId> | undefined;\n readonly driver?: ControlDriverDescriptor<TFamilyId, TTargetId> | undefined;\n readonly extensionPacks?:\n | ReadonlyArray<ControlExtensionDescriptor<TFamilyId, TTargetId>>\n | undefined;\n}\n\nfunction addUniqueId(ids: string[], seen: Set<string>, id: string): void {\n if (!seen.has(id)) {\n ids.push(id);\n seen.add(id);\n }\n}\n\nexport function assertUniqueCodecOwner(options: {\n readonly codecId: string;\n readonly owners: Map<string, string>;\n readonly descriptorId: string;\n readonly entityLabel: string;\n readonly entityOwnershipLabel: string;\n}): void {\n const existingOwner = options.owners.get(options.codecId);\n if (existingOwner !== undefined) {\n throw new Error(\n `Duplicate ${options.entityLabel} for codecId \"${options.codecId}\". ` +\n `Descriptor \"${options.descriptorId}\" conflicts with \"${existingOwner}\". ` +\n `Each codecId can only have one ${options.entityOwnershipLabel}.`,\n );\n }\n}\n\nexport function extractCodecTypeImports(\n descriptors: ReadonlyArray<Pick<ComponentMetadata, 'types'>>,\n): ReadonlyArray<TypesImportSpec> {\n const imports: TypesImportSpec[] = [];\n\n for (const descriptor of descriptors) {\n const codecTypes = descriptor.types?.codecTypes;\n if (codecTypes?.import) {\n imports.push(codecTypes.import);\n }\n if (codecTypes?.typeImports) {\n imports.push(...codecTypes.typeImports);\n }\n }\n\n return imports;\n}\n\nexport function extractQueryOperationTypeImports(\n descriptors: ReadonlyArray<Pick<ComponentMetadata, 'types'>>,\n): ReadonlyArray<TypesImportSpec> {\n const imports: TypesImportSpec[] = [];\n\n for (const descriptor of descriptors) {\n const queryOperationTypes = descriptor.types?.queryOperationTypes;\n if (queryOperationTypes?.import) {\n imports.push(queryOperationTypes.import);\n }\n }\n\n return imports;\n}\n\nexport function extractComponentIds(\n family: { readonly id: string },\n target: { readonly id: string },\n adapter: { readonly id: string } | undefined,\n extensions: ReadonlyArray<{ readonly id: string }>,\n): ReadonlyArray<string> {\n const ids: string[] = [];\n const seen = new Set<string>();\n\n addUniqueId(ids, seen, family.id);\n addUniqueId(ids, seen, target.id);\n if (adapter) {\n addUniqueId(ids, seen, adapter.id);\n }\n\n for (const ext of extensions) {\n addUniqueId(ids, seen, ext.id);\n }\n\n return ids;\n}\n\nexport function assembleAuthoringContributions(\n descriptors: ReadonlyArray<{ readonly authoring?: AuthoringContributions }>,\n): AssembledAuthoringContributions {\n const field = {} as Record<string, unknown>;\n const type = {} as Record<string, unknown>;\n const entityTypes = {} as Record<string, unknown>;\n const pslBlockDescriptors: Record<string, unknown> = {};\n const modelAttributes: Record<string, unknown> = {};\n\n for (const descriptor of descriptors) {\n if (descriptor.authoring?.field) {\n mergeAuthoringNamespaces(field, descriptor.authoring.field, [], 'fieldPreset', 'field');\n }\n if (descriptor.authoring?.type) {\n mergeAuthoringNamespaces(type, descriptor.authoring.type, [], 'typeConstructor', 'type');\n }\n if (descriptor.authoring?.entityTypes) {\n mergeAuthoringNamespaces(\n entityTypes,\n descriptor.authoring.entityTypes,\n [],\n 'entity',\n 'entity',\n );\n }\n if (descriptor.authoring?.pslBlockDescriptors) {\n mergeAuthoringNamespaces(\n pslBlockDescriptors,\n descriptor.authoring.pslBlockDescriptors,\n [],\n 'pslBlock',\n 'pslBlock',\n );\n }\n if (descriptor.authoring?.modelAttributes) {\n mergeAuthoringNamespaces(\n modelAttributes,\n descriptor.authoring.modelAttributes,\n [],\n 'modelAttribute',\n 'modelAttribute',\n );\n }\n }\n\n const fieldNamespace = field as AuthoringFieldNamespace;\n const typeNamespace = type as AuthoringTypeNamespace;\n const entityTypeNamespace = entityTypes as AuthoringEntityTypeNamespace;\n const pslBlockDescriptorNamespace = blindCast<\n AuthoringPslBlockDescriptorNamespace,\n 'merge target accumulator narrows to typed namespace post-merge'\n >(pslBlockDescriptors);\n const modelAttributeNamespace = blindCast<\n AuthoringModelAttributeDescriptorNamespace,\n 'merge target accumulator narrows to typed namespace post-merge'\n >(modelAttributes);\n assertNoCrossRegistryCollisions(\n typeNamespace,\n fieldNamespace,\n entityTypeNamespace,\n pslBlockDescriptorNamespace,\n modelAttributeNamespace,\n );\n\n return {\n field: fieldNamespace,\n type: typeNamespace,\n entityTypes: entityTypeNamespace,\n pslBlockDescriptors: pslBlockDescriptorNamespace,\n modelAttributes: modelAttributeNamespace,\n };\n}\n\nexport function assembleScalarTypeDescriptors(\n descriptors: ReadonlyArray<\n Pick<ComponentMetadata, 'scalarTypeDescriptors'> & { readonly id?: string }\n >,\n): ReadonlyMap<string, string> {\n const result = new Map<string, string>();\n const owners = new Map<string, string>();\n\n for (const descriptor of descriptors) {\n const descriptorMap = descriptor.scalarTypeDescriptors;\n if (!descriptorMap) continue;\n const descriptorId = descriptor.id ?? '<unknown>';\n for (const [typeName, codecId] of descriptorMap) {\n const existingOwner = owners.get(typeName);\n if (existingOwner !== undefined) {\n throw new Error(\n `Duplicate scalar type descriptor \"${typeName}\". ` +\n `Descriptor \"${descriptorId}\" conflicts with \"${existingOwner}\".`,\n );\n }\n result.set(typeName, codecId);\n owners.set(typeName, descriptorId);\n }\n }\n\n return result;\n}\n\nexport function assembleControlMutationDefaults(\n descriptors: ReadonlyArray<\n Pick<ComponentMetadata, 'controlMutationDefaults'> & { readonly id?: string }\n >,\n): ControlMutationDefaults {\n const defaultFunctionRegistry = new Map<string, ControlMutationDefaultEntry>();\n const functionOwners = new Map<string, string>();\n const generatorMap = new Map<string, MutationDefaultGeneratorDescriptor>();\n const generatorOwners = new Map<string, string>();\n\n for (const descriptor of descriptors) {\n const contributions = descriptor.controlMutationDefaults;\n if (!contributions) continue;\n const descriptorId = descriptor.id ?? '<unknown>';\n\n for (const generatorDescriptor of contributions.generatorDescriptors) {\n const existingOwner = generatorOwners.get(generatorDescriptor.id);\n if (existingOwner !== undefined) {\n throw new Error(\n `Duplicate mutation default generator id \"${generatorDescriptor.id}\". ` +\n `Descriptor \"${descriptorId}\" conflicts with \"${existingOwner}\".`,\n );\n }\n generatorMap.set(generatorDescriptor.id, generatorDescriptor);\n generatorOwners.set(generatorDescriptor.id, descriptorId);\n }\n\n for (const [functionName, handler] of contributions.defaultFunctionRegistry) {\n const existingOwner = functionOwners.get(functionName);\n if (existingOwner !== undefined) {\n throw new Error(\n `Duplicate mutation default function \"${functionName}\". ` +\n `Descriptor \"${descriptorId}\" conflicts with \"${existingOwner}\".`,\n );\n }\n defaultFunctionRegistry.set(functionName, handler);\n functionOwners.set(functionName, descriptorId);\n }\n }\n\n return {\n defaultFunctionRegistry,\n generatorDescriptors: Array.from(generatorMap.values()),\n };\n}\n\nexport function extractCodecLookup(\n descriptors: ReadonlyArray<Pick<ComponentMetadata & { id: string }, 'types' | 'id'>>,\n): CodecRegistry {\n const byId = new Map<string, Codec>();\n const descriptorsById = new Map<string, AnyCodecDescriptor>();\n const targetTypesById = new Map<string, readonly string[]>();\n const metaById = new Map<string, CodecMeta>();\n const metaRenderersById = new Map<\n string,\n (params: Record<string, unknown> | JsonValue) => CodecMeta | undefined\n >();\n const renderersById = new Map<string, (params: Record<string, unknown>) => string | undefined>();\n const inputRenderersById = new Map<\n string,\n (params: Record<string, unknown>) => string | undefined\n >();\n const valueLiteralRenderersById = new Map<\n string,\n (value: JsonValue, side: 'output' | 'input') => string | undefined\n >();\n const owners = new Map<string, string>();\n for (const descriptor of descriptors) {\n const codecTypes = descriptor.types?.codecTypes;\n const descriptorId = descriptor.id;\n // Descriptor-side metadata is the single source of truth for `targetTypes` / `meta` / `renderOutputType`. A component contributes its codecs by listing `codecDescriptors` on `types.codecTypes`; each codecId has exactly one contributor across the stack.\n for (const codecDescriptor of codecTypes?.codecDescriptors ?? []) {\n assertUniqueCodecOwner({\n codecId: codecDescriptor.codecId,\n owners,\n descriptorId,\n entityLabel: 'codec descriptor',\n entityOwnershipLabel: 'codec descriptor provider',\n });\n owners.set(codecDescriptor.codecId, descriptorId);\n descriptorsById.set(codecDescriptor.codecId, codecDescriptor);\n if (Array.isArray(codecDescriptor.targetTypes)) {\n targetTypesById.set(codecDescriptor.codecId, codecDescriptor.targetTypes);\n }\n if (codecDescriptor.meta !== undefined) {\n metaById.set(codecDescriptor.codecId, codecDescriptor.meta);\n }\n if (typeof codecDescriptor.metaFor === 'function') {\n metaRenderersById.set(codecDescriptor.codecId, codecDescriptor.metaFor);\n }\n if (typeof codecDescriptor.renderOutputType === 'function') {\n renderersById.set(codecDescriptor.codecId, codecDescriptor.renderOutputType);\n }\n if (typeof codecDescriptor.renderInputType === 'function') {\n inputRenderersById.set(codecDescriptor.codecId, codecDescriptor.renderInputType);\n }\n if (typeof codecDescriptor.renderValueLiteral === 'function') {\n valueLiteralRenderersById.set(codecDescriptor.codecId, codecDescriptor.renderValueLiteral);\n }\n // Materialize a representative `Codec` instance for `byId.get()` so consumers reading the lookup's instance side (e.g. SQL renderer's cast-policy lookup, or the contract emitter's literal-default `encodeJson` resolver) keep finding the codec.\n //\n // Two cohorts:\n // - Non-parameterized descriptors: factory must succeed; any throw is a real bug and we let it propagate (no silent try/catch).\n // - Parameterized descriptors: try with empty params. Many parameterized codecs treat params as advisory (e.g. `pg/timestamptz@1` whose precision is rendered into the `nativeType` only and never read by the runtime codec), so an empty-params construction yields a usable representative for id-keyed lookups (e.g. emit-time literal-default encoding). Codecs whose factory genuinely requires params (e.g. `pg/vector@1` threading `length` into the runtime codec) will throw; for those, per-column instances are materialized at runtime by `buildContractCodecRegistry` and the id-keyed lookup miss is correct (the column-aware path resolves them).\n if (!byId.has(codecDescriptor.codecId)) {\n if (codecDescriptor.isParameterized) {\n try {\n const representative = codecDescriptor.factory({} as never)({\n name: `<lookup:${codecDescriptor.codecId}>`,\n } as Parameters<ReturnType<typeof codecDescriptor.factory>>[0]);\n byId.set(codecDescriptor.codecId, representative);\n } catch {\n // Factory requires concrete params; skip representative materialization. Per-column instances are built at runtime; id-keyed lookup miss is the correct outcome here.\n }\n } else {\n const representative = codecDescriptor.factory(undefined as never)({\n name: `<lookup:${codecDescriptor.codecId}>`,\n } as Parameters<ReturnType<typeof codecDescriptor.factory>>[0]);\n byId.set(codecDescriptor.codecId, representative);\n }\n }\n }\n }\n return {\n get: (id) => byId.get(id),\n forCodecRef(ref: CodecRef) {\n const d = resolveCodecDescriptorOrThrow(\n (id) => descriptorsById.get(id),\n ref,\n CONTRACT_CODEC_DESCRIPTOR_MISSING,\n );\n return materializeCodec(d, ref, { name: `<ref:${ref.codecId}>` });\n },\n forColumn: () => undefined,\n targetTypesFor: (id) => targetTypesById.get(id),\n metaFor: (id, typeParams) => {\n if (typeParams !== undefined) {\n const paramsAware = metaRenderersById.get(id)?.(typeParams);\n if (paramsAware !== undefined) return paramsAware;\n }\n return metaById.get(id);\n },\n renderOutputTypeFor: (id, params) => renderersById.get(id)?.(params),\n renderInputTypeFor: (id, params) => inputRenderersById.get(id)?.(params),\n renderValueLiteralFor: (id, value, side) => valueLiteralRenderersById.get(id)?.(value, side),\n descriptorFor: (id) => descriptorsById.get(id),\n };\n}\n\nexport function validateScalarTypeCodecIds(\n scalarTypeDescriptors: ReadonlyMap<string, string>,\n codecLookup: CodecLookup,\n): string[] {\n const errors: string[] = [];\n for (const [typeName, codecId] of scalarTypeDescriptors) {\n if (!codecLookup.get(codecId)) {\n errors.push(\n `Scalar type \"${typeName}\" references codec \"${codecId}\" which is not registered by any component.`,\n );\n }\n }\n return errors;\n}\n\ninterface DependencyDeclaringDescriptor {\n readonly id: string;\n readonly contractSpace?: {\n readonly contractJson?: {\n readonly extensionPacks?: Readonly<Record<string, unknown>>;\n };\n };\n}\n\nfunction readDeclaredDependencyIds(descriptor: DependencyDeclaringDescriptor): readonly string[] {\n const packs = descriptor.contractSpace?.contractJson?.extensionPacks;\n if (packs === null || typeof packs !== 'object') return [];\n return Object.keys(packs);\n}\n\n/**\n * Builds a dependency-respecting load order for the given extension descriptors\n * using Kahn's topological sort algorithm. Dependencies (packs declared in\n * `contractSpace.contractJson.extensionPacks`) are placed before the extensions\n * that depend on them.\n *\n * Throws if the dependency graph contains a cycle, with an error message that\n * names every extension involved in the cycle.\n *\n * Throws if any extension declares a dependency on a pack ID that is not present\n * in the provided list — add the missing pack to the `extensionPacks` list to\n * resolve the error.\n */\n\nexport function buildExtensionLoadOrder(\n extensions: ReadonlyArray<DependencyDeclaringDescriptor>,\n): readonly string[] {\n if (extensions.length === 0) return [];\n\n const idSet = new Set(extensions.map((e) => e.id));\n const inDegree = new Map<string, number>();\n const dependents = new Map<string, string[]>();\n\n for (const ext of extensions) {\n if (!inDegree.has(ext.id)) inDegree.set(ext.id, 0);\n if (!dependents.has(ext.id)) dependents.set(ext.id, []);\n }\n\n for (const ext of extensions) {\n for (const depId of readDeclaredDependencyIds(ext)) {\n if (!idSet.has(depId)) {\n throw new Error(\n `Extension \"${ext.id}\" declares a dependency on \"${depId}\", but \"${depId}\" is not in the provided extension set. Add the missing space to extensionPacks.`,\n );\n }\n inDegree.set(ext.id, (inDegree.get(ext.id) ?? 0) + 1);\n const list = dependents.get(depId);\n if (list !== undefined) list.push(ext.id);\n }\n }\n\n const queue: string[] = [];\n for (const [id, deg] of inDegree) {\n if (deg === 0) queue.push(id);\n }\n queue.sort();\n\n const result: string[] = [];\n while (queue.length > 0) {\n const id = queue.shift();\n if (id === undefined) break;\n result.push(id);\n const children = dependents.get(id) ?? [];\n children.sort();\n for (const childId of children) {\n const newDeg = (inDegree.get(childId) ?? 1) - 1;\n inDegree.set(childId, newDeg);\n if (newDeg === 0) queue.push(childId);\n }\n }\n\n if (result.length < extensions.length) {\n const cycleMembers = extensions\n .map((e) => e.id)\n .filter((id) => !result.includes(id))\n .sort();\n throw new Error(\n `Extension dependency cycle detected. Cycle members: ${cycleMembers.map((id) => `\"${id}\"`).join(', ')}.`,\n );\n }\n\n return result;\n}\n\nexport function createControlStack<TFamilyId extends string, TTargetId extends string>(\n input: CreateControlStackInput<TFamilyId, TTargetId>,\n): ControlStack<TFamilyId, TTargetId> {\n const { family, target, adapter, driver, extensionPacks = [] } = input;\n\n const orderedIds = buildExtensionLoadOrder(extensionPacks);\n const extensionById = new Map(extensionPacks.map((ext) => [ext.id, ext]));\n const orderedExtensionPacks = orderedIds\n .map((id) => extensionById.get(id))\n .filter((ext): ext is ControlExtensionDescriptor<TFamilyId, TTargetId> => ext !== undefined);\n\n const allDescriptors = [family, target, ...(adapter ? [adapter] : []), ...orderedExtensionPacks];\n\n const codecLookup = extractCodecLookup(allDescriptors);\n const scalarTypeDescriptors = assembleScalarTypeDescriptors(allDescriptors);\n\n return {\n family,\n target,\n adapter,\n driver,\n extensionPacks: orderedExtensionPacks,\n\n codecTypeImports: extractCodecTypeImports(allDescriptors),\n queryOperationTypeImports: extractQueryOperationTypeImports(allDescriptors),\n extensionIds: extractComponentIds(family, target, adapter, orderedExtensionPacks),\n codecLookup,\n authoringContributions: assembleAuthoringContributions(allDescriptors),\n scalarTypeDescriptors,\n controlMutationDefaults: assembleControlMutationDefaults(allDescriptors),\n capabilities: mergeCapabilityMatrices({}, [\n target,\n ...(adapter ? [adapter] : []),\n ...orderedExtensionPacks,\n ]),\n };\n}\n","import type { ExpectationFailureReason } from './control-operation-results';\n\nexport interface SchemaDiffIssue<TNode extends DiffableNode = DiffableNode> {\n /** Path from the root node down to the diffed node, as a sequence of local keys. */\n readonly path: readonly string[];\n /** Why the actual state fails the expectation. Consumers filter on this field. */\n readonly reason: ExpectationFailureReason;\n /** The expected (desired-side) node, when available. Absent for `not-expected` issues. */\n readonly expected?: TNode;\n /** The actual (current-side) node, when available. Absent for `not-found` issues. */\n readonly actual?: TNode;\n}\n\n/**\n * A node in the schema tree. Every node in the tree implements this interface.\n *\n * The differ pairs siblings by the combination of `nodeKind` and `id`, not by\n * `id` alone: `id` needs only be unique among siblings of the same\n * `nodeKind` at the same level, not globally unique at that level. Two\n * distinct kinds of child in distinct slots (e.g. a role and a namespace) may\n * legitimately share a name — they are never paired against each other, so\n * the collision is harmless. A node never folds its kind into its id string\n * to route around this; `nodeKind` is the discriminant that does that job.\n * A same-`nodeKind`/same-`id` collision among siblings is a genuine\n * duplicate and is enforced by a throw. The differ accumulates ids (not\n * nodeKind) into a path that stamps every emitted issue.\n */\nexport interface DiffableNode {\n readonly id: string;\n readonly nodeKind: string;\n isEqualTo(other: DiffableNode): boolean;\n children(): readonly DiffableNode[];\n}\n\n/** Delimiter joining `nodeKind` and `id` into one sibling-map key. Every `nodeKind` is a code-defined literal (kebab-case-style), so a null character can never appear in one. */\nconst SIBLING_KEY_DELIMITER = '\\u0000';\n\nfunction siblingKey(node: DiffableNode): string {\n return `${node.nodeKind}${SIBLING_KEY_DELIMITER}${node.id}`;\n}\n\nfunction insertNode(map: Map<string, DiffableNode>, node: DiffableNode): void {\n const key = siblingKey(node);\n if (map.has(key)) {\n throw new Error(`diffSchemas: duplicate id among siblings: ${node.nodeKind}/${node.id}`);\n }\n map.set(key, node);\n}\n\nfunction emitMissingSubtree(node: DiffableNode, parentPath: readonly string[]): SchemaDiffIssue[] {\n const path = [...parentPath, node.id];\n return [\n {\n path,\n reason: 'not-found',\n expected: node,\n },\n ...node.children().flatMap((c) => emitMissingSubtree(c, path)),\n ];\n}\n\nfunction emitExtraSubtree(node: DiffableNode, parentPath: readonly string[]): SchemaDiffIssue[] {\n const path = [...parentPath, node.id];\n return [\n {\n path,\n reason: 'not-expected',\n actual: node,\n },\n ...node.children().flatMap((c) => emitExtraSubtree(c, path)),\n ];\n}\n\n/**\n * Diff two schema trees starting from their roots.\n *\n * The differ is **total**: every node-level difference is reported. An unmatched\n * non-leaf node emits its own issue and descends, emitting an issue for every\n * node in the missing/extra subtree. Coalescing a parent change over its\n * children is the planner's responsibility. Ownership filtering (dropping `extra`\n * issues in namespaces a contract doesn't own) is the caller's responsibility.\n */\nexport function diffSchemas(\n expected: DiffableNode,\n actual: DiffableNode,\n): readonly SchemaDiffIssue[] {\n return diffPair(expected, actual, []);\n}\n\nfunction diffPair(\n expected: DiffableNode,\n actual: DiffableNode,\n parentPath: readonly string[],\n): readonly SchemaDiffIssue[] {\n const path = [...parentPath, expected.id];\n const issues: SchemaDiffIssue[] = [];\n if (!expected.isEqualTo(actual)) {\n issues.push({\n path,\n reason: 'not-equal',\n expected,\n actual,\n });\n }\n issues.push(...diffChildren(expected.children(), actual.children(), path));\n return issues;\n}\n\n/**\n * Align one level of nodes by `(nodeKind, id)`; emit issues in input order\n * and recurse.\n *\n * A missing node emits one issue for itself and one for every node in its\n * subtree (total descent). Same for extra nodes. A matched pair recurses via\n * `diffPair`.\n */\nfunction diffChildren(\n expected: readonly DiffableNode[],\n actual: readonly DiffableNode[],\n parentPath: readonly string[],\n): readonly SchemaDiffIssue[] {\n const expectedMap = new Map<string, DiffableNode>();\n for (const node of expected) {\n insertNode(expectedMap, node);\n }\n\n const actualMap = new Map<string, DiffableNode>();\n for (const node of actual) {\n insertNode(actualMap, node);\n }\n\n const issues: SchemaDiffIssue[] = [];\n\n for (const [key, expectedNode] of expectedMap) {\n const actualNode = actualMap.get(key);\n if (actualNode === undefined) {\n issues.push(...emitMissingSubtree(expectedNode, parentPath));\n } else {\n issues.push(...diffPair(expectedNode, actualNode, parentPath));\n }\n }\n\n for (const [key, actualNode] of actualMap) {\n if (!expectedMap.has(key)) {\n issues.push(...emitExtraSubtree(actualNode, parentPath));\n }\n }\n\n return issues;\n}\n\n/**\n * The result of diffing a contract's expected schema against the introspected\n * actual schema: one node-typed issue list. Carries no verdict, verification\n * tree, or counts — those are the verifier's own presentation, built from the\n * same underlying comparison.\n *\n * `TNode` is the concrete schema-IR node the issues carry; it defaults to\n * `DiffableNode`, so this is purely additive — a caller that wants the\n * concrete node opts in (the Postgres planner uses the concrete node type),\n * everyone else keeps the default unchanged.\n */\nexport class SchemaDiff<TNode extends DiffableNode = DiffableNode> {\n readonly issues: readonly SchemaDiffIssue<TNode>[];\n\n constructor(issues: readonly SchemaDiffIssue<TNode>[]) {\n this.issues = issues;\n }\n\n /** Returns a new `SchemaDiff` narrowed to the issues `keep` returns true for. */\n filter(keep: (issue: SchemaDiffIssue<TNode>) => boolean): SchemaDiff<TNode> {\n return new SchemaDiff(this.issues.filter(keep));\n }\n}\n","import type { ControlPolicy } from '@prisma-next/contract/types';\n\nexport type VerificationStatus = 'pass' | 'warn' | 'fail';\n\nexport type VerifierOutcome = VerificationStatus | 'suppress';\n\n/**\n * Target-neutral classification of a verifier finding, abstracted away from any\n * one storage model's vocabulary. Each family classifies its own concrete issue\n * kinds into these categories; the framework only grades the category against a\n * control policy.\n *\n * - `declaredMissing` — a declared object/element is absent from the database.\n * - `declaredIncompatible` — a declared object/element exists but its shape diverges.\n * - `valueDrift` — the value set of an existing type drifted (e.g. enum values).\n * - `extraNestedElement` — an undeclared element nested inside a declared object\n * (a SQL column, a document field).\n * - `extraAuxiliary` — an undeclared auxiliary attached to a declared object\n * (a SQL constraint/index, a Mongo index/validator).\n * - `extraTopLevelObject` — an undeclared top-level object (a SQL table, a\n * Mongo collection).\n */\nexport type VerifierIssueCategory =\n | 'declaredMissing'\n | 'declaredIncompatible'\n | 'valueDrift'\n | 'extraNestedElement'\n | 'extraAuxiliary'\n | 'extraTopLevelObject';\n\n/**\n * Grades a target-neutral issue category against a control policy.\n *\n * - `observed` warns on everything.\n * - `tolerated` suppresses only an extra nested element (everything else fails).\n * - `external` suppresses every extra category and value drift (existence and\n * declared-shape divergences still fail).\n * - `managed` (and any other) fails.\n */\nexport function dispositionForCategory(\n controlPolicy: ControlPolicy,\n category: VerifierIssueCategory,\n): VerifierOutcome {\n if (controlPolicy === 'observed') {\n return 'warn';\n }\n if (controlPolicy === 'tolerated' && category === 'extraNestedElement') {\n return 'suppress';\n }\n if (controlPolicy === 'external') {\n if (\n category === 'extraNestedElement' ||\n category === 'extraAuxiliary' ||\n category === 'extraTopLevelObject' ||\n category === 'valueDrift'\n ) {\n return 'suppress';\n }\n }\n return 'fail';\n}\n"],"mappings":";;;;;AAmBA,SAAgB,cACd,QAC4D;CAC5D,OAAO,gBAAgB,UAAU,CAAC,CAAE,OAAmC;AACzE;AAMA,SAAgB,cACd,UACwF;CACxF,OACE,kBAAkB,YAClB,OAAQ,SAAqC,oBAAoB;AAErE;AAUA,SAAgB,oBACd,UAC8F;CAC9F,OACE,sBAAsB,YACtB,OAAQ,SAAqC,wBAAwB;AAEzE;AAWA,SAAgB,oBACd,UACmF;CACnF,OACE,wBAAwB,YACxB,OAAQ,SAAqC,0BAA0B;AAE3E;AAqCA,SAAgB,2BACd,UAC0F;CAC1F,OACE,gCAAgC,YAChC,OAAQ,SAAqC,kCAAkC,cAC/E,wBAAwB,YACxB,OAAQ,SAAqC,0BAA0B;AAE3E;;;ACnHA,MAAa,6BAA6B;AAC1C,MAAa,4BAA4B;AACzC,MAAa,8BAA8B;AAC3C,MAAa,6BAA6B;;;AC0B1C,IAAa,iBAAb,MAA4B;CAC1B;CACA;CACA;CACA;CACA;CAEA,YAAY,SAAgC;EAC1C,KAAK,OAAO,QAAQ;EACpB,KAAK,KAAK,QAAQ;EAClB,KAAK,QAAQ,QAAQ;EACrB,IAAI,QAAQ,SAAS,KAAA,GAAW,KAAK,OAAO,QAAQ;EACpD,IAAI,QAAQ,aAAa,KAAA,GAAW,KAAK,WAAW,QAAQ;EAC5D,OAAO,OAAO,IAAI;CACpB;CAEA,OAAU,SAAkC;EAC1C,OAAO,QAAQ,MAAM,IAAI;CAC3B;AACF;;;;;;;;;;;;;;;;;;;;;;AC5BA,MAAa,eAAe;;;AC0D5B,SAAS,YAAY,KAAe,MAAmB,IAAkB;CACvE,IAA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AsD;CACjE;CAEA,YAAY,QAA2C;EACrD,KAAK,SAAS;CAChB;;CAGA,OAAO,MAAqE;EAC1E,OAAO,IAAI,WAAW,KAAK,OAAO,OAAO,IAAI,CAAC;CAChD;AACF;;;;;;;;;;;;ACtIA,SAAgB,uBACd,eACA,UACiB;CACjB,IAAI,kBAAkB,YACpB,OAAO;CAET,IAAI,kBAAkB,eAAe,aAAa,sBAChD,OAAO;CAET,IAAI,kBAAkB;MAElB,aAAa,wBACb,aAAa,oBACb,aAAa,yBACb,aAAa,cAEb,OAAO;CAAA;CAGX,OAAO;AACT"}

@@ -1,2 +0,2 @@

import { b as TargetInstance, c as DriverDescriptor, d as ExtensionDescriptor, f as ExtensionInstance, h as FamilyInstance, l as DriverInstance, m as FamilyDescriptor, n as AdapterInstance, t as AdapterDescriptor, y as TargetDescriptor } from "./framework-components-7p9S3MZ0.mjs";
import { b as TargetInstance, c as DriverDescriptor, d as ExtensionDescriptor, f as ExtensionInstance, h as FamilyInstance, l as DriverInstance, m as FamilyDescriptor, n as AdapterInstance, t as AdapterDescriptor, y as TargetDescriptor } from "./framework-components-BuDe2aFH.mjs";

@@ -3,0 +3,0 @@ //#region src/execution/execution-instances.d.ts

import { r as CodecLookup } from "./codec-types-BH2f2dg1.mjs";
import { $ as PslExtensionBlockParamRef, G as PslBlockParamValue, H as PslBlockParamList, J as PslExtensionBlockAttribute, K as PslDiagnosticCode, Q as PslExtensionBlockParamOption, U as PslBlockParamOption, V as PslBlockParam, W as PslBlockParamRef, X as PslExtensionBlockParamBare, Y as PslExtensionBlockAttributeArg, Z as PslExtensionBlockParamList, et as PslExtensionBlockParamScalarValue, nt as PslPosition, q as PslExtensionBlock, rt as PslSpan, tt as PslExtensionBlockParamValue, v as AuthoringPslBlockDescriptor, y as AuthoringPslBlockDescriptorNamespace } from "./framework-authoring-jIw3xcfy.mjs";
import { A as makePslNamespace, C as PslReferentialAction, D as UNSPECIFIED_PSL_NAMESPACE_ID, E as PslUniqueConstraint, M as namespacePslExtensionBlocks, O as flatPslCompositeTypes, S as PslNamespaceEntry, T as PslTypesBlock, _ as PslIndexConstraint, a as PslAttributeArgument, b as PslNamedTypeDeclaration, c as PslAttributeTarget, d as PslDefaultLiteralValue, f as PslDefaultValue, g as PslFieldAttribute, h as PslField, i as PslAttribute, j as makePslNamespaceEntries, k as flatPslModels, l as PslCompositeType, m as PslDocumentAst, n as ParsePslDocumentInput, o as PslAttributeNamedArgument, p as PslDiagnostic, r as ParsePslDocumentResult, s as PslAttributePositionalArgument, t as BUILTIN_PSL_KIND_KEYS, u as PslDefaultFunctionValue, v as PslModel, w as PslTypeConstructorCall, x as PslNamespace, y as PslModelAttribute } from "./psl-ast-BRRUqpAN.mjs";
import { $ as PslExtensionBlockParamRef, G as PslBlockParamValue, H as PslBlockParamList, J as PslExtensionBlockAttribute, K as PslDiagnosticCode, Q as PslExtensionBlockParamOption, U as PslBlockParamOption, V as PslBlockParam, W as PslBlockParamRef, X as PslExtensionBlockParamBare, Y as PslExtensionBlockAttributeArg, Z as PslExtensionBlockParamList, et as PslExtensionBlockParamScalarValue, nt as PslPosition, q as PslExtensionBlock, rt as PslSpan, tt as PslExtensionBlockParamValue, v as AuthoringPslBlockDescriptor, y as AuthoringPslBlockDescriptorNamespace } from "./framework-authoring-CEbpeygb.mjs";
import { A as makePslNamespace, C as PslReferentialAction, D as UNSPECIFIED_PSL_NAMESPACE_ID, E as PslUniqueConstraint, M as namespacePslExtensionBlocks, O as flatPslCompositeTypes, S as PslNamespaceEntry, T as PslTypesBlock, _ as PslIndexConstraint, a as PslAttributeArgument, b as PslNamedTypeDeclaration, c as PslAttributeTarget, d as PslDefaultLiteralValue, f as PslDefaultValue, g as PslFieldAttribute, h as PslField, i as PslAttribute, j as makePslNamespaceEntries, k as flatPslModels, l as PslCompositeType, m as PslDocumentAst, n as ParsePslDocumentInput, o as PslAttributeNamedArgument, p as PslDiagnostic, r as ParsePslDocumentResult, s as PslAttributePositionalArgument, t as BUILTIN_PSL_KIND_KEYS, u as PslDefaultFunctionValue, v as PslModel, w as PslTypeConstructorCall, x as PslNamespace, y as PslModelAttribute } from "./psl-ast-BEdlyUwY.mjs";

@@ -5,0 +5,0 @@ //#region src/control/psl-extension-block-validator.d.ts

{
"name": "@prisma-next/framework-components",
"version": "0.14.0-dev.60",
"version": "0.14.0-dev.61",
"license": "Apache-2.0",

@@ -9,6 +9,6 @@ "type": "module",

"dependencies": {
"@prisma-next/contract": "0.14.0-dev.60",
"@prisma-next/operations": "0.14.0-dev.60",
"@prisma-next/ts-render": "0.14.0-dev.60",
"@prisma-next/utils": "0.14.0-dev.60",
"@prisma-next/contract": "0.14.0-dev.61",
"@prisma-next/operations": "0.14.0-dev.61",
"@prisma-next/ts-render": "0.14.0-dev.61",
"@prisma-next/utils": "0.14.0-dev.61",
"@standard-schema/spec": "^1.1.0",

@@ -18,4 +18,4 @@ "arktype": "^2.2.0"

"devDependencies": {
"@prisma-next/tsconfig": "0.14.0-dev.60",
"@prisma-next/tsdown": "0.14.0-dev.60",
"@prisma-next/tsconfig": "0.14.0-dev.61",
"@prisma-next/tsdown": "0.14.0-dev.61",
"tsdown": "0.22.1",

@@ -22,0 +22,0 @@ "typescript": "5.9.3",

@@ -82,5 +82,5 @@ import type { ControlTargetDescriptor } from './control-descriptors';

* - `auxiliary`: a secondary part of an entity (an index, a default, a key).
* - `structural`: a cross-cutting object (an access policy, a role, a tree
* root) that is the owning space's own concern, never a sibling's
* unclaimed entity.
* - `structural`: a cross-cutting object (an access policy, a tree root) that
* is the owning space's own concern, never a sibling's unclaimed entity —
* its extras fail verify in both modes.
*/

@@ -87,0 +87,0 @@ export type DiffSubjectGranularity = 'namespace' | 'entity' | 'field' | 'auxiliary' | 'structural';

@@ -15,2 +15,3 @@ import type {

import type { PslBlockParam, PslExtensionBlock, PslSpan } from './psl-extension-block';
import { runtimeError } from './runtime-error';

@@ -799,25 +800,38 @@ export type EnumInferredMemberType = 'text' | 'int';

/**
* Throws when two or more entries in the same namespace share a discriminator.
* Duplicate discriminators within a namespace make dispatch ambiguous — the
* lowering factory lookup dispatches by discriminator, so one would silently
* shadow the other. Catch duplicates before building any dispatch map.
* Throws when two or more entries in the same namespace share a key. A
* duplicate key makes dispatch ambiguous — the caller's lookup dispatches by
* this key, so one entry would silently shadow the other. Catch duplicates
* before building any dispatch map.
*
* `label` (e.g. `'pslBlock'`, `'entityType'`) names which namespace the
* duplicate was found in and is carried in the structured error metadata;
* the key itself is always called `key` in both the message and the
* metadata, since what it semantically represents (a discriminator for
* `entityType`, the parser's dispatch keyword for `pslBlock`) is the
* caller's concern, not this function's.
*/
function assertUniqueDiscriminators(entries: readonly DescriptorEntry[], label: string): void {
const seen = new Map<string, string>();
for (const { path, discriminator } of entries) {
const existing = seen.get(discriminator);
for (const { path, discriminator: key } of entries) {
const existing = seen.get(key);
if (existing !== undefined) {
throw new Error(
`Duplicate ${label} discriminator "${discriminator}" registered at both "${existing}" and "${path}". Each ${label} contribution must use a unique discriminator.`,
throw runtimeError(
'RUNTIME.DUPLICATE_AUTHORING_DISCRIMINATOR',
`Duplicate ${label} key "${key}" registered at both "${existing}" and "${path}". Each ${label} contribution must use a unique key.`,
{ label, key, existingPath: existing, path },
);
}
seen.set(discriminator, path);
seen.set(key, path);
}
}
interface PslBlockDescriptorEntry extends DescriptorEntry {
readonly keyword: string;
}
function collectPslBlockDescriptorEntries(
namespace: AuthoringPslBlockDescriptorNamespace,
path: readonly string[] = [],
): DescriptorEntry[] {
const entries: DescriptorEntry[] = [];
): PslBlockDescriptorEntry[] {
const entries: PslBlockDescriptorEntry[] = [];
for (const [key, value] of Object.entries(namespace)) {

@@ -836,2 +850,3 @@ const currentPath = [...path, key];

discriminator: value.discriminator,
keyword: value.keyword,
});

@@ -863,2 +878,9 @@ continue;

* `enum`, reachable from the TypeScript builder without any PSL block).
*
* Uniqueness for pslBlock entries is keyed on **keyword**, not discriminator:
* several keywords (e.g. `policy_select`/`policy_insert`) may legitimately
* share one discriminator, routing to the same `entityTypes` factory and the
* same `entries[discriminator]` slot — that N:1 shape is exactly what lets
* one entity kind be authored through several PSL keywords. What must stay
* unique is the keyword itself, since that's what the parser dispatches on.
*/

@@ -877,3 +899,6 @@ function assertPslBlocksHaveFactories(

assertUniqueDiscriminators(blockEntries, 'pslBlock');
assertUniqueDiscriminators(
blockEntries.map((entry) => ({ path: entry.path, discriminator: entry.keyword })),
'pslBlock',
);
assertUniqueDiscriminators(entityEntries, 'entityType');

@@ -880,0 +905,0 @@

@@ -245,7 +245,17 @@ /**

* node, as produced by the generic framework parser and consumed by the
* validator and lowering factory.
* validator, printer, and lowering factory.
*
* - `kind` is the routing discriminant, equal to the descriptor's
* `discriminator`. The framework parser sets this to
* `descriptor.discriminator` for every block it parses.
* `descriptor.discriminator` for every block it parses. Several keywords
* may share one discriminator (e.g. `policy_select`/`policy_insert` both
* route to `kind: 'policy'`) — `kind` identifies the entity/storage kind,
* not the source syntax.
* - `keyword` is the source PSL keyword the block was declared with
* (`policy_select`, `policy_insert`, …) — the parse-dispatch identity.
* Distinct from `kind` precisely when a discriminator is shared by more
* than one keyword; a lowering factory that contributes several keywords
* under one discriminator reads `keyword` to tell its blocks apart, and
* the printer re-emits each block under its own `keyword` regardless of
* how many other keywords share its `kind`.
* - `name` is the block's declared name (the identifier after the keyword).

@@ -266,2 +276,9 @@ * - `parameters` is the descriptor-driven parameter map. Keys are

readonly kind: string;
/**
* The block's parse identity — the source PSL keyword it was declared
* with. `kind`/`discriminator` is its storage identity; several keywords
* can share one. E.g. the five `policy_*` keywords all lower to the
* `policy` entity kind.
*/
readonly keyword: string;
readonly name: string;

@@ -268,0 +285,0 @@ readonly parameters: Record<string, PslExtensionBlockParamValue>;

import { blindCast } from "@prisma-next/utils/casts";
import { isColumnDefaultLiteralInputValue, isExecutionMutationDefaultValue } from "@prisma-next/contract/types";
import { ifDefined } from "@prisma-next/utils/defined";
//#region src/shared/framework-authoring.ts
/**
* Classifies an `enum` block's members (before codec decoding, which needs
* the codec chosen first) into which default codec an omitted `@@type`
* should resolve to:
*
* - every member is `bare`, or a `value` whose raw JSON is a string → `'text'`
* - every member is a `value` whose raw JSON is an integer → `'int'`
* - anything else (float, bigint, boolean, mixed, or a `ref`/`option`/`list`
* parameter) → `null`, meaning the caller must require an explicit `@@type`.
*/
function classifyEnumMemberType(block) {
let sawText = false;
let sawInt = false;
for (const paramValue of Object.values(block.parameters)) {
if (paramValue.kind === "bare") {
sawText = true;
continue;
}
if (paramValue.kind !== "value") return null;
let jsonValue;
try {
jsonValue = JSON.parse(paramValue.raw);
} catch {
return null;
}
if (typeof jsonValue === "string") sawText = true;
else if (typeof jsonValue === "number" && Number.isInteger(jsonValue)) sawInt = true;
else return null;
}
if (sawText && sawInt) return null;
if (sawText) return "text";
if (sawInt) return "int";
return null;
}
/**
* Resolves the codec id for an `enum` block. When `@@type` is absent, the codec
* is inferred from the members via {@link classifyEnumMemberType}; otherwise the
* explicit `@@type("codec")` argument is parsed. Pushes the appropriate
* diagnostic and returns `undefined` when neither yields a codec. `codecSpan` is
* the span downstream codec-validation diagnostics should anchor to. Shared by
* every family's enum factory so inference and the explicit path stay identical.
*/
function resolveEnumCodecId(block, ctx) {
const sourceId = ctx.sourceId ?? "unknown";
const typeAttr = block.blockAttributes.find((a) => a.name === "type");
if (typeAttr === void 0) {
const inferredKind = classifyEnumMemberType(block);
if (inferredKind === null || ctx.enumInferenceCodecs === void 0) {
ctx.diagnostics?.push({
code: "PSL_ENUM_CANNOT_INFER_TYPE",
message: `cannot infer @@type for enum "${block.name}"; add an explicit @@type(...)`,
sourceId,
span: block.span
});
return;
}
return {
codecId: ctx.enumInferenceCodecs[inferredKind],
codecSpan: block.span
};
}
const rawCodecArg = typeAttr.args[0]?.value;
const codecId = rawCodecArg?.startsWith("\"") && rawCodecArg.endsWith("\"") && rawCodecArg.length >= 2 ? rawCodecArg.slice(1, -1) : void 0;
if (codecId === void 0) {
ctx.diagnostics?.push({
code: "PSL_ENUM_MISSING_TYPE",
message: `enum "${block.name}" @@type attribute must have a quoted codec id argument`,
sourceId,
span: typeAttr.span
});
return;
}
return {
codecId,
codecSpan: typeAttr.args[0]?.span ?? typeAttr.span
};
}
function isAuthoringArgRef(value) {
if (typeof value !== "object" || value === null || value.kind !== "arg") return false;
const { index, path } = value;
if (typeof index !== "number" || !Number.isInteger(index) || index < 0) return false;
if (path !== void 0 && (!Array.isArray(path) || path.some((s) => typeof s !== "string"))) return false;
return true;
}
function isAuthoringTemplateRecord(value) {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
function isAuthoringTypeConstructorDescriptor(value) {
return "kind" in value && value.kind === "typeConstructor";
}
function isAuthoringFieldPresetDescriptor(value) {
return "kind" in value && value.kind === "fieldPreset";
}
function isAuthoringEntityTypeDescriptor(value) {
return "kind" in value && value.kind === "entity";
}
function isAuthoringPslBlockDescriptor(value) {
return "kind" in value && value.kind === "pslBlock";
}
function isAuthoringModelAttributeDescriptor(value) {
return "kind" in value && value.kind === "modelAttribute";
}
/**
* Returns true when `namespace` is a non-leaf key in `contributions.field`.
*
* `AuthoringFieldNamespace` permits a leaf descriptor at any depth — including
* the root — so a top-level `field: { Foo: { kind: 'fieldPreset', ... } }`
* registration must NOT be treated as a "namespace" with sub-paths. Callers
* use this predicate to gate dot-namespaced lookups (e.g. PSL `@Foo.bar`).
*/
function hasRegisteredFieldNamespace(contributions, namespace) {
if (contributions?.field === void 0 || !Object.hasOwn(contributions.field, namespace)) return false;
const value = contributions.field[namespace];
return value !== void 0 && !isAuthoringFieldPresetDescriptor(value);
}
function isCopyableNamespaceObject(value) {
if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
const proto = Object.getPrototypeOf(value);
return proto === Object.prototype || proto === null;
}
/**
* Deep structural check run only at the composition boundary (the merge and
* collect walkers) to classify a raw namespace-tree node as a leaf descriptor.
* A node counts as a leaf iff its `kind` matches `descriptorKind` AND it
* carries that kind's required fields.
*
* This is boundary validation over `unknown`, NOT a type-predicate: the four
* exported `isAuthoring*Descriptor` predicates deliberately narrow on `kind`
* alone and trust the static types. The walkers, by contrast, also receive
* type-bypassing packs (`as unknown as never` in tests, untyped JS at runtime)
* whose descriptor-shaped-but-incomplete nodes must be rejected rather than
* silently treated as sub-namespaces — so the well-formedness check lives here.
*/
function isWellFormedDescriptor(value, descriptorKind) {
if (typeof value !== "object" || value === null) return false;
if (!("kind" in value) || value.kind !== descriptorKind) return false;
switch (descriptorKind) {
case "typeConstructor":
case "fieldPreset": {
if (!("output" in value)) return false;
const output = value.output;
return typeof output === "object" && output !== null;
}
case "entity": {
if (!("discriminator" in value) || typeof value.discriminator !== "string") return false;
if (value.discriminator.length === 0) return false;
if (!("output" in value)) return false;
const output = value.output;
if (typeof output !== "object" || output === null) return false;
const factory = "factory" in output ? output.factory : void 0;
const template = "template" in output ? output.template : void 0;
return typeof factory === "function" || template !== void 0;
}
case "pslBlock": {
if (!("keyword" in value) || typeof value.keyword !== "string" || value.keyword.length === 0) return false;
if (!("discriminator" in value) || typeof value.discriminator !== "string" || value.discriminator.length === 0) return false;
if (!("name" in value)) return false;
const name = value.name;
if (typeof name !== "object" || name === null) return false;
if (!("required" in name) || typeof name.required !== "boolean") return false;
if (!("parameters" in value)) return false;
const parameters = value.parameters;
return typeof parameters === "object" && parameters !== null && !Array.isArray(parameters);
}
case "modelAttribute":
if (!("attribute" in value) || typeof value.attribute !== "string" || value.attribute.length === 0) return false;
if (!("spec" in value)) return false;
return "lower" in value && typeof value.lower === "function";
default: return false;
}
}
function deepCopyNamespace(source, descriptorKind) {
const copy = {};
for (const [key, value] of Object.entries(source)) copy[key] = isCopyableNamespaceObject(value) && !isWellFormedDescriptor(value, descriptorKind) ? deepCopyNamespace(value, descriptorKind) : value;
return copy;
}
/**
* Merges `source` into `target` recursively at the descriptor-namespace
* level. `descriptorKind` is the `kind` value ('typeConstructor',
* 'fieldPreset', 'entity', or 'pslBlock') that identifies a descriptor
* (terminal merge point; same-path registrations across components are
* reported as duplicates) as opposed to a sub-namespace (recursion target).
*
* Path segments are validated against prototype-pollution names
* (`__proto__`, `constructor`, `prototype`). A value that is neither a
* recognized leaf nor a plain object — e.g. a malformed descriptor
* where the canonical leaf guard rejected it for missing `output` —
* is reported as an invalid contribution rather than recursed into,
* which would either silently mangle state or infinite-loop on
* primitive properties.
*
* Within-registry duplicate detection is this walker's job;
* cross-registry detection runs separately via
* `assertNoCrossRegistryCollisions` after merging completes.
*/
function mergeAuthoringNamespaces(target, source, path, descriptorKind, label) {
const assertSafePath = (currentPath) => {
const blockedSegment = currentPath.find((segment) => segment === "__proto__" || segment === "constructor" || segment === "prototype");
if (blockedSegment) throw new Error(`Invalid authoring ${label} helper "${currentPath.join(".")}". Helper path segments must not use "${blockedSegment}".`);
};
for (const [key, sourceValue] of Object.entries(source)) {
const currentPath = [...path, key];
assertSafePath(currentPath);
const hasExistingValue = Object.hasOwn(target, key);
const existingValue = hasExistingValue ? target[key] : void 0;
if (!hasExistingValue) {
target[key] = isCopyableNamespaceObject(sourceValue) && !isWellFormedDescriptor(sourceValue, descriptorKind) ? deepCopyNamespace(sourceValue, descriptorKind) : sourceValue;
continue;
}
const existingIsLeaf = isWellFormedDescriptor(existingValue, descriptorKind);
const sourceIsLeaf = isWellFormedDescriptor(sourceValue, descriptorKind);
if (existingIsLeaf || sourceIsLeaf) throw new Error(`Duplicate authoring ${label} helper "${currentPath.join(".")}". Helper names must be unique across composed packs.`);
if (!isCopyableNamespaceObject(existingValue) || !isCopyableNamespaceObject(sourceValue)) throw new Error(`Invalid authoring ${label} helper "${currentPath.join(".")}". Expected a sub-namespace object or a recognized descriptor; received a malformed value.`);
mergeAuthoringNamespaces(existingValue, sourceValue, currentPath, descriptorKind, label);
}
}
function collectDescriptorPaths(namespace, isLeaf, path = []) {
const paths = [];
for (const [key, value] of Object.entries(namespace)) {
const currentPath = [...path, key];
if (isLeaf(value)) {
paths.push(currentPath.join("."));
continue;
}
if (typeof value === "object" && value !== null && !Array.isArray(value)) paths.push(...collectDescriptorPaths(value, isLeaf, currentPath));
}
return paths;
}
function collectDescriptorEntries(namespace, isLeaf, descriptorKind, label, path = []) {
const entries = [];
for (const [key, value] of Object.entries(namespace)) {
const currentPath = [...path, key];
if (isLeaf(value)) {
if (!isWellFormedDescriptor(value, descriptorKind)) throw new Error(`Malformed authoring ${label} contribution at "${currentPath.join(".")}". The value carries descriptor keys (kind/keyword/discriminator) but does not satisfy the ${label} descriptor shape. Fix the contribution so it is a complete descriptor, or remove the stray keys if it was meant to be a sub-namespace.`);
if (value.discriminator.length > 0) entries.push({
path: currentPath.join("."),
discriminator: value.discriminator
});
continue;
}
if (typeof value === "object" && value !== null && !Array.isArray(value)) {
const record = blindCast(value);
if ((record["kind"] !== void 0 || record["keyword"] !== void 0 || record["discriminator"] !== void 0) && !isLeaf(value)) {
const hasKind = record["kind"] === "pslBlock";
const hasKeyword = typeof record["keyword"] === "string";
const hasDiscriminator = typeof record["discriminator"] === "string";
if (hasKind || hasKeyword && hasDiscriminator) throw new Error(`Malformed authoring ${label} contribution at "${currentPath.join(".")}". The value carries descriptor keys (kind/keyword/discriminator) but does not satisfy the ${label} descriptor shape. Fix the contribution so it is a complete descriptor, or remove the stray keys if it was meant to be a sub-namespace.`);
}
entries.push(...collectDescriptorEntries(value, isLeaf, descriptorKind, label, currentPath));
}
}
return entries;
}
/**
* Throws when two or more entries in the same namespace share a discriminator.
* Duplicate discriminators within a namespace make dispatch ambiguous — the
* lowering factory lookup dispatches by discriminator, so one would silently
* shadow the other. Catch duplicates before building any dispatch map.
*/
function assertUniqueDiscriminators(entries, label) {
const seen = /* @__PURE__ */ new Map();
for (const { path, discriminator } of entries) {
const existing = seen.get(discriminator);
if (existing !== void 0) throw new Error(`Duplicate ${label} discriminator "${discriminator}" registered at both "${existing}" and "${path}". Each ${label} contribution must use a unique discriminator.`);
seen.set(discriminator, path);
}
}
function collectPslBlockDescriptorEntries(namespace, path = []) {
const entries = [];
for (const [key, value] of Object.entries(namespace)) {
const currentPath = [...path, key];
if (isAuthoringPslBlockDescriptor(value)) {
if (!isWellFormedDescriptor(value, "pslBlock")) throw new Error(`Malformed authoring pslBlock contribution at "${currentPath.join(".")}". The value carries descriptor keys (kind/keyword/discriminator) but does not satisfy the pslBlock descriptor shape. Fix the contribution so it is a complete descriptor, or remove the stray keys if it was meant to be a sub-namespace.`);
entries.push({
path: currentPath.join("."),
discriminator: value.discriminator
});
continue;
}
if (typeof value === "object" && value !== null && !Array.isArray(value)) {
const record = blindCast(value);
const hasKind = record["kind"] === "pslBlock";
const hasKeyword = typeof record["keyword"] === "string";
const hasDiscriminator = typeof record["discriminator"] === "string";
if (hasKind || hasKeyword && hasDiscriminator) throw new Error(`Malformed authoring pslBlock contribution at "${currentPath.join(".")}". The value carries descriptor keys (kind/keyword/discriminator) but does not satisfy the pslBlock descriptor shape. Fix the contribution so it is a complete descriptor, or remove the stray keys if it was meant to be a sub-namespace.`);
entries.push(...collectPslBlockDescriptorEntries(value, currentPath));
}
}
return entries;
}
/**
* Every `pslBlockDescriptors` entry requires a matching `entityTypes` factory
* with the same discriminator. An `entityTypes` factory may stand alone (e.g.
* `enum`, reachable from the TypeScript builder without any PSL block).
*/
function assertPslBlocksHaveFactories(entityTypeNamespace, pslBlockNamespace) {
const blockEntries = collectPslBlockDescriptorEntries(pslBlockNamespace);
const entityEntries = collectDescriptorEntries(entityTypeNamespace, isAuthoringEntityTypeDescriptor, "entity", "entityType");
assertUniqueDiscriminators(blockEntries, "pslBlock");
assertUniqueDiscriminators(entityEntries, "entityType");
const entityDiscriminators = new Set(entityEntries.map((entry) => entry.discriminator));
for (const block of blockEntries) if (!entityDiscriminators.has(block.discriminator)) throw new Error(`Incomplete extension contribution: pslBlock helper "${block.path}" registers discriminator "${block.discriminator}" but no entityType contribution shares that discriminator. An extension-contributed PSL block requires a matching entityType factory so the parsed AST node can lower to an IR class instance; add an entityType helper with discriminator "${block.discriminator}".`);
}
function collectModelAttributeEntries(namespace, path = []) {
const entries = [];
for (const [key, value] of Object.entries(namespace)) {
const currentPath = [...path, key];
if (isAuthoringModelAttributeDescriptor(value)) {
if (!isWellFormedDescriptor(value, "modelAttribute")) throw new Error(`Malformed authoring modelAttribute contribution at "${currentPath.join(".")}". The value carries descriptor keys (kind/attribute) but does not satisfy the modelAttribute descriptor shape. Fix the contribution so it is a complete descriptor, or remove the stray keys if it was meant to be a sub-namespace.`);
entries.push({
path: currentPath.join("."),
discriminator: value.attribute
});
continue;
}
if (typeof value === "object" && value !== null && !Array.isArray(value)) {
const record = blindCast(value);
if (typeof record["attribute"] === "string" && "spec" in record) throw new Error(`Malformed authoring modelAttribute contribution at "${currentPath.join(".")}". The value carries descriptor keys (kind/attribute) but does not satisfy the modelAttribute descriptor shape. Fix the contribution so it is a complete descriptor, or remove the stray keys if it was meant to be a sub-namespace.`);
entries.push(...collectModelAttributeEntries(value, currentPath));
}
}
return entries;
}
/**
* Throws when two modelAttribute contributions — at any paths, even
* different ones — claim the same bare `@@` attribute name. The family
* interpreter dispatches by attribute name, not by registration path, so
* two descriptors claiming the same name would have one silently shadow
* the other.
*/
function assertUniqueModelAttributeNames(entries) {
const seen = /* @__PURE__ */ new Map();
for (const { path, discriminator: attribute } of entries) {
const existing = seen.get(attribute);
if (existing !== void 0) throw new Error(`Duplicate modelAttribute "${attribute}" registered at both "${existing}" and "${path}". Each modelAttribute contribution must claim a unique attribute name.`);
seen.set(attribute, path);
}
}
function assertNoCrossRegistryCollisions(typeNamespace, fieldNamespace, entityTypeNamespace = {}, pslBlockNamespace = {}, modelAttributeNamespace = {}) {
const typePaths = new Set(collectDescriptorPaths(typeNamespace, isAuthoringTypeConstructorDescriptor));
const fieldPaths = new Set(collectDescriptorPaths(fieldNamespace, isAuthoringFieldPresetDescriptor));
const entityPaths = new Set(collectDescriptorPaths(entityTypeNamespace, isAuthoringEntityTypeDescriptor));
const ambiguityHint = "Register each path in only one of authoringContributions.field / authoringContributions.type / authoringContributions.entityTypes.";
for (const fieldPath of fieldPaths) if (typePaths.has(fieldPath)) throw new Error(`Ambiguous authoring registry path "${fieldPath}". The same path is registered as both a type constructor and a field preset; PSL resolution would be ambiguous. ${ambiguityHint}`);
for (const entityPath of entityPaths) if (typePaths.has(entityPath) || fieldPaths.has(entityPath)) throw new Error(`Ambiguous authoring registry path "${entityPath}". The same path is registered as an entity contribution AND as a type constructor or field preset; PSL resolution would be ambiguous. ${ambiguityHint}`);
assertPslBlocksHaveFactories(entityTypeNamespace, pslBlockNamespace);
assertUniqueModelAttributeNames(collectModelAttributeEntries(modelAttributeNamespace));
}
function resolveAuthoringTemplateValue(template, args) {
if (template === void 0) return;
if (isAuthoringArgRef(template)) {
let value = args[template.index];
for (const segment of template.path ?? []) {
if (!isAuthoringTemplateRecord(value) || !Object.hasOwn(value, segment)) {
value = void 0;
break;
}
value = value[segment];
}
if (value === void 0 && template.default !== void 0) return resolveAuthoringTemplateValue(template.default, args);
return value;
}
if (Array.isArray(template)) return template.map((value) => resolveAuthoringTemplateValue(value, args));
if (typeof template === "object" && template !== null) {
const resolved = {};
for (const [key, value] of Object.entries(template)) {
const resolvedValue = resolveAuthoringTemplateValue(value, args);
if (resolvedValue !== void 0) resolved[key] = resolvedValue;
}
return resolved;
}
return template;
}
function validateAuthoringArgument(descriptor, value, path) {
if (value === void 0) {
if (descriptor.optional) return;
throw new Error(`Missing required authoring helper argument at ${path}`);
}
if (descriptor.kind === "string") {
if (typeof value !== "string") throw new Error(`Authoring helper argument at ${path} must be a string`);
return;
}
if (descriptor.kind === "boolean") {
if (typeof value !== "boolean") throw new Error(`Authoring helper argument at ${path} must be a boolean`);
return;
}
if (descriptor.kind === "stringArray") {
if (!Array.isArray(value)) throw new Error(`Authoring helper argument at ${path} must be an array of strings`);
for (const entry of value) if (typeof entry !== "string") throw new Error(`Authoring helper argument at ${path} must be an array of strings`);
return;
}
if (descriptor.kind === "object") {
if (typeof value !== "object" || value === null || Array.isArray(value)) throw new Error(`Authoring helper argument at ${path} must be an object`);
const input = value;
const expectedKeys = new Set(Object.keys(descriptor.properties));
for (const key of Object.keys(input)) if (!expectedKeys.has(key)) throw new Error(`Authoring helper argument at ${path} contains unknown property "${key}"`);
for (const [key, propertyDescriptor] of Object.entries(descriptor.properties)) validateAuthoringArgument(propertyDescriptor, input[key], `${path}.${key}`);
return;
}
if (typeof value !== "number" || Number.isNaN(value)) throw new Error(`Authoring helper argument at ${path} must be a number`);
if (descriptor.integer && !Number.isInteger(value)) throw new Error(`Authoring helper argument at ${path} must be an integer`);
if (descriptor.minimum !== void 0 && value < descriptor.minimum) throw new Error(`Authoring helper argument at ${path} must be >= ${descriptor.minimum}, received ${value}`);
if (descriptor.maximum !== void 0 && value > descriptor.maximum) throw new Error(`Authoring helper argument at ${path} must be <= ${descriptor.maximum}, received ${value}`);
}
function validateAuthoringHelperArguments(helperPath, descriptors, args) {
const expected = descriptors ?? [];
const minimumArgs = expected.reduce((count, descriptor, index) => descriptor.optional ? count : index + 1, 0);
if (args.length < minimumArgs || args.length > expected.length) throw new Error(`${helperPath} expects ${minimumArgs === expected.length ? expected.length : `${minimumArgs}-${expected.length}`} argument(s), received ${args.length}`);
expected.forEach((descriptor, index) => {
validateAuthoringArgument(descriptor, args[index], `${helperPath}[${index}]`);
});
}
function resolveAuthoringStorageTypeTemplate(template, args) {
const nativeType = resolveAuthoringTemplateValue(template.nativeType, args);
if (typeof nativeType !== "string") throw new Error(`Resolved authoring nativeType must be a string for codec "${template.codecId}", received ${String(nativeType)}`);
const typeParams = template.typeParams === void 0 ? void 0 : resolveAuthoringTemplateValue(template.typeParams, args);
if (typeParams !== void 0 && !isAuthoringTemplateRecord(typeParams)) throw new Error(`Resolved authoring typeParams must be an object for codec "${template.codecId}", received ${String(typeParams)}`);
return {
codecId: template.codecId,
nativeType,
...ifDefined("typeParams", typeParams)
};
}
function resolveAuthoringColumnDefaultTemplate(template, args) {
if (template.kind === "literal") {
const value = resolveAuthoringTemplateValue(template.value, args);
if (value === void 0) throw new Error("Resolved authoring literal default must not be undefined");
if (!isColumnDefaultLiteralInputValue(value)) throw new Error(`Resolved authoring literal default must be a JSON-serializable value or Date, received ${String(value)}`);
return {
kind: "literal",
value
};
}
const expression = resolveAuthoringTemplateValue(template.expression, args);
if (expression === void 0 || typeof expression === "object" && expression !== null) throw new Error(`Resolved authoring function default expression must resolve to a primitive, received ${String(expression)}`);
return {
kind: "function",
expression: String(expression)
};
}
function resolveExecutionMutationDefaultPhase(phase, template, args) {
const value = resolveAuthoringTemplateValue(template, args);
if (!isExecutionMutationDefaultValue(value)) throw new Error(`Authoring preset executionDefaults.${phase} did not resolve to a valid generator descriptor (kind: 'generator', id: string).`);
return value;
}
function resolveAuthoringExecutionDefaultsTemplate(template, args) {
return {
...ifDefined("onCreate", template.onCreate !== void 0 ? resolveExecutionMutationDefaultPhase("onCreate", template.onCreate, args) : void 0),
...ifDefined("onUpdate", template.onUpdate !== void 0 ? resolveExecutionMutationDefaultPhase("onUpdate", template.onUpdate, args) : void 0)
};
}
function instantiateAuthoringTypeConstructor(descriptor, args) {
return resolveAuthoringStorageTypeTemplate(descriptor.output, args);
}
function instantiateAuthoringEntityType(helperPath, descriptor, args, ctx) {
if ("factory" in descriptor.output) {
const input = args[0];
return blindCast(descriptor.output.factory)(input, ctx);
}
validateAuthoringHelperArguments(helperPath, descriptor.args, args);
return blindCast(resolveAuthoringTemplateValue(descriptor.output.template, args));
}
function instantiateAuthoringFieldPreset(descriptor, args) {
return {
descriptor: resolveAuthoringStorageTypeTemplate(descriptor.output, args),
nullable: descriptor.output.nullable ?? false,
...ifDefined("default", descriptor.output.default !== void 0 ? resolveAuthoringColumnDefaultTemplate(descriptor.output.default, args) : void 0),
...ifDefined("executionDefaults", descriptor.output.executionDefaults !== void 0 ? resolveAuthoringExecutionDefaultsTemplate(descriptor.output.executionDefaults, args) : void 0),
id: descriptor.output.id ?? false,
unique: descriptor.output.unique ?? false
};
}
//#endregion
export { instantiateAuthoringFieldPreset as a, isAuthoringEntityTypeDescriptor as c, isAuthoringPslBlockDescriptor as d, isAuthoringTypeConstructorDescriptor as f, validateAuthoringHelperArguments as g, resolveEnumCodecId as h, instantiateAuthoringEntityType as i, isAuthoringFieldPresetDescriptor as l, resolveAuthoringTemplateValue as m, classifyEnumMemberType as n, instantiateAuthoringTypeConstructor as o, mergeAuthoringNamespaces as p, hasRegisteredFieldNamespace as r, isAuthoringArgRef as s, assertNoCrossRegistryCollisions as t, isAuthoringModelAttributeDescriptor as u };
//# sourceMappingURL=framework-authoring-DsAScNbB.mjs.map

Sorry, the diff of this file is too big to display

import { r as CodecLookup } from "./codec-types-BH2f2dg1.mjs";
import { ColumnDefault, ExecutionMutationDefaultPhases } from "@prisma-next/contract/types";
import { Type } from "arktype";
//#region src/shared/psl-extension-block.d.ts
/**
* Shape-only types for the PSL source-position primitives, diagnostic
* codes, extension-block descriptor vocabulary, and the uniform
* extension-block AST node base.
*
* These live in the shared plane so an extension's authoring descriptor
* (`AuthoringPslBlockDescriptor` in `framework-authoring`) can reference
* them without crossing the shared → migration-plane boundary. The
* migration-plane `psl-ast.ts` re-exports everything here for consumers
* that import PSL AST types from the control entrypoint.
*/
interface PslPosition {
readonly offset: number;
readonly line: number;
readonly column: number;
}
interface PslSpan {
readonly start: PslPosition;
readonly end: PslPosition;
}
type PslDiagnosticCode = 'PSL_UNTERMINATED_BLOCK' | 'PSL_UNSUPPORTED_TOP_LEVEL_BLOCK' | 'PSL_INVALID_NAMESPACE_BLOCK' | 'PSL_INVALID_ATTRIBUTE_SYNTAX' | 'PSL_INVALID_MODEL_MEMBER' | 'PSL_UNSUPPORTED_MODEL_ATTRIBUTE' | 'PSL_UNSUPPORTED_FIELD_ATTRIBUTE' | 'PSL_INVALID_RELATION_ATTRIBUTE' | 'PSL_INVALID_REFERENTIAL_ACTION' | 'PSL_INVALID_DEFAULT_VALUE' | 'PSL_INVALID_ENUM_MEMBER' | 'PSL_INVALID_TYPES_MEMBER' | 'PSL_INVALID_QUALIFIED_TYPE'
/**
* A qualified name (e.g. a dotted type or attribute reference) is structurally
* invalid, such as an over-qualified or trailing-separator name.
*/
| 'PSL_INVALID_QUALIFIED_NAME'
/**
* A reserved declaration keyword (`model`/`enum`/`namespace`/`type`) that
* committed the declaration kind on the keyword alone but is missing its name
* and/or opening brace. The recursive-descent parser produces a best-effort
* typed node for the malformed header and reports this code rather than
* `PSL_UNSUPPORTED_TOP_LEVEL_BLOCK`, which is reserved for a genuinely unknown
* top-level keyword.
*/
| 'PSL_INVALID_DECLARATION'
/**
* A malformed line inside an extension-contributed top-level block body, or
* a structurally invalid element inside a `list` parameter value.
*
* Replaces the overloaded `PSL_UNSUPPORTED_TOP_LEVEL_BLOCK` code that the
* generic framework parser previously used for these two parse-error sites
* inside extension blocks — keeping `PSL_UNSUPPORTED_TOP_LEVEL_BLOCK` for
* its original meaning (an unknown keyword at the top level) and giving
* extension-block parse errors their own code.
*/
| 'PSL_INVALID_EXTENSION_BLOCK_MEMBER'
/**
* A malformed JS-like object literal `{ key: value, … }` in value/argument
* position — a field missing its `:`, a field missing its value, or an
* unterminated `{`. The recursive-descent parser still produces a best-effort
* `ObjectLiteralExpr` node (preserving the lossless round-trip) and reports
* this code anchored on the offending token.
*/
| 'PSL_INVALID_OBJECT_LITERAL'
/**
* A string literal with no closing quote — the tokenizer stops the literal at
* a newline or at EOF when no terminating `"` is found, and the
* recursive-descent parser still consumes the token (preserving the lossless
* round-trip) but reports this code anchored on the string token's span.
*/
| 'PSL_UNTERMINATED_STRING'
/**
* An unknown parameter key in an extension-contributed block — a key present
* in the source block but absent from the descriptor's `parameters` map.
*/
| 'PSL_EXTENSION_UNKNOWN_PARAMETER'
/**
* A required parameter declared in the descriptor is absent from the parsed block.
*/
| 'PSL_EXTENSION_MISSING_REQUIRED_PARAMETER'
/**
* An `option`-kind parameter value is not one of the allowed tokens listed
* in the descriptor's `values` array.
*/
| 'PSL_EXTENSION_OPTION_OUT_OF_SET'
/**
* A `value`-kind parameter's raw text is not a valid JSON literal, or the
* parsed JSON value was rejected by the codec's `decodeJson` method, or the
* codec id is not registered in the lookup.
*/
| 'PSL_EXTENSION_INVALID_VALUE'
/**
* A `ref`-kind parameter identifier does not resolve to a declared entity of
* the required `refKind` within the declared scope.
*/
| 'PSL_EXTENSION_UNRESOLVED_REF'
/**
* A parameter key appears more than once in an extension block body.
* The first occurrence is kept; subsequent occurrences emit this diagnostic.
*/
| 'PSL_EXTENSION_DUPLICATE_PARAMETER'
/**
* A `@@`-prefixed block-attribute line inside an extension block has invalid syntax.
*/
| 'PSL_INVALID_EXTENSION_BLOCK_ATTRIBUTE'
/**
* Duplicate scopes are top level, namespace body, or block fields; diagnostics
* are first-wins and anchored on later name spans.
*/
| 'PSL_DUPLICATE_DECLARATION';
/**
* Descriptor vocabulary for a single parameter on a declared block.
*
* Four kinds:
* - `ref` — the parameter value is an identifier that must resolve to a
* declared entity of `refKind` within the declared `scope`.
* - `value` — the parameter value is a PSL literal parsed and printed
* through the codec identified by `codecId`.
* - `option` — the parameter value is one of the literal tokens in `values`.
* Not a codec; not persisted data. A closed authoring-time constraint only.
* - `list` — a bracketed list whose elements each match the `of` descriptor.
*/
type PslBlockParam = PslBlockParamRef | PslBlockParamValue | PslBlockParamOption | PslBlockParamList;
interface PslBlockParamRef {
readonly kind: 'ref';
readonly refKind: string;
readonly scope: 'same-namespace' | 'same-space' | 'cross-space';
readonly required?: boolean;
}
interface PslBlockParamValue {
readonly kind: 'value';
readonly codecId: string;
readonly required?: boolean;
}
interface PslBlockParamOption {
readonly kind: 'option';
readonly values: readonly string[];
readonly required?: boolean;
}
interface PslBlockParamList {
readonly kind: 'list';
readonly of: PslBlockParam;
readonly required?: boolean;
}
/**
* The parsed representation of a single parameter value on a uniform
* extension-block AST node. Mirrors the `PslBlockParam` descriptor
* vocabulary, plus `bare` for keyonly entries:
*
* - `ref` → `PslExtensionBlockParamRef` — a raw identifier string
* (resolution runs in the validator, not the parser).
* - `value` → `PslExtensionBlockParamScalarValue` — a raw PSL literal string
* (codec validation runs in the validator).
* - `option` → `PslExtensionBlockParamOption` — the chosen token.
* - `list` → `PslExtensionBlockParamList` — ordered list of the above.
* - `bare` → `PslExtensionBlockParamBare` — a bare identifier line with no
* `= value` (e.g. `Low` in an enum block). The name is the key in
* `parameters`; the interpreting consumer decides the default value.
*
* These shapes are intentionally minimal. The validator and lowering refine
* and consume them; the generic framework parser produces them.
*/
type PslExtensionBlockParamValue = PslExtensionBlockParamRef | PslExtensionBlockParamScalarValue | PslExtensionBlockParamOption | PslExtensionBlockParamList | PslExtensionBlockParamBare;
interface PslExtensionBlockParamRef {
readonly kind: 'ref';
readonly identifier: string;
readonly span: PslSpan;
}
interface PslExtensionBlockParamScalarValue {
readonly kind: 'value';
readonly raw: string;
readonly span: PslSpan;
}
interface PslExtensionBlockParamOption {
readonly kind: 'option';
readonly token: string;
readonly span: PslSpan;
}
interface PslExtensionBlockParamList {
readonly kind: 'list';
readonly items: readonly PslExtensionBlockParamValue[];
readonly span: PslSpan;
}
/**
* A bare identifier line inside an extension block — a key with no `= value`.
* Emitted when a line matches `/^[A-Za-z_]\w*$/` with no assignment. The
* consumer decides what default value (if any) to apply.
*/
interface PslExtensionBlockParamBare {
readonly kind: 'bare';
readonly span: PslSpan;
}
/**
* A positional argument on a block attribute, e.g. the `"pg/text@1"` in
* `@@type("pg/text@1")`.
*/
interface PslExtensionBlockAttributeArg {
readonly kind: 'positional';
readonly value: string;
readonly span: PslSpan;
}
/**
* A `@@`-prefixed block-level attribute parsed inside an extension block,
* e.g. `@@type("pg/text@1")`. Block attributes are captured generically
* — the parser does not validate attribute names or argument shapes; that
* is a concern of the block's interpreter.
*/
interface PslExtensionBlockAttribute {
readonly name: string;
readonly args: readonly PslExtensionBlockAttributeArg[];
readonly span: PslSpan;
}
/**
* Base shape for a uniform extension-contributed top-level PSL block
* node, as produced by the generic framework parser and consumed by the
* validator and lowering factory.
*
* - `kind` is the routing discriminant, equal to the descriptor's
* `discriminator`. The framework parser sets this to
* `descriptor.discriminator` for every block it parses.
* - `name` is the block's declared name (the identifier after the keyword).
* - `parameters` is the descriptor-driven parameter map. Keys are
* parameter names from the descriptor; values are the parsed parameter
* representations. Only parameters present in the source are included
* — absence of a required parameter is a validator concern, not a
* parser concern. Insertion order is preserved; the first occurrence of a
* duplicate key is retained and subsequent occurrences emit
* `PSL_EXTENSION_DUPLICATE_PARAMETER`.
* - `blockAttributes` are `@@`-prefixed attribute lines inside the block, in
* declaration order. Captured generically — names and args are not validated
* by the parser.
* - `span` covers the full block from keyword to closing brace.
*/
interface PslExtensionBlock {
readonly kind: string;
readonly name: string;
readonly parameters: Record<string, PslExtensionBlockParamValue>;
readonly blockAttributes: readonly PslExtensionBlockAttribute[];
readonly span: PslSpan;
}
//#endregion
//#region src/shared/framework-authoring.d.ts
type AuthoringArgRef = {
readonly kind: 'arg';
readonly index: number;
readonly path?: readonly string[];
readonly default?: AuthoringTemplateValue;
};
type AuthoringTemplateValue = string | number | boolean | null | AuthoringArgRef | readonly AuthoringTemplateValue[] | {
readonly [key: string]: AuthoringTemplateValue;
};
interface AuthoringArgumentDescriptorCommon {
readonly name?: string;
readonly optional?: boolean;
}
type AuthoringArgumentDescriptor = AuthoringArgumentDescriptorCommon & ({
readonly kind: 'string';
} | {
readonly kind: 'boolean';
} | {
readonly kind: 'number';
readonly integer?: boolean;
readonly minimum?: number;
readonly maximum?: number;
} | {
readonly kind: 'stringArray';
} | {
readonly kind: 'object';
readonly properties: Record<string, AuthoringArgumentDescriptor>;
});
interface AuthoringStorageTypeTemplate {
readonly codecId: string;
/**
* Optional so a type constructor whose {@link AuthoringTypeConstructorDescriptor.entityRefArg}
* names another entity can omit this template entirely — its output for
* that case is derived by the codec at `codecId`, not by resolving a
* literal here. Every other consumer of this shape (field presets, plain
* type constructors) always supplies it.
*/
readonly nativeType?: AuthoringTemplateValue;
readonly typeParams?: Record<string, AuthoringTemplateValue>;
}
/**
* Declares that one positional argument of a
* {@link AuthoringTypeConstructorDescriptor} call names another entity
* parsed from the same document, rather than carrying a literal value (e.g.
* `pg.enum(AalLevel)` naming a `native_enum` entity). `index` is the
* argument's position in the call; `entityKind` is the entries-slot
* discriminator the interpreter looks the named entity up under (the same
* shape {@link AuthoringEntityTypeFactoryOutput.factory} output is collected
* into, keyed by discriminator then block name).
*
* The interpreter resolves the named argument to the entity instance
* generically, driven only by this declaration — it has no target-specific
* knowledge of which type constructors carry one. Converting the resolved
* entity into the constructor's params is a separate, codec-owned concern:
* the codec descriptor registered for `output.codecId` supplies that
* conversion, not this framework type.
*/
interface AuthoringTypeConstructorEntityRef {
readonly index: number;
readonly entityKind: string;
}
interface AuthoringTypeConstructorDescriptor {
readonly kind: 'typeConstructor';
readonly args?: readonly AuthoringArgumentDescriptor[];
readonly output: AuthoringStorageTypeTemplate;
/** Present when one of this constructor's positional arguments names another document-local entity instead of carrying a literal value. Absent for ordinary literal-argument constructors. */
readonly entityRefArg?: AuthoringTypeConstructorEntityRef;
}
interface AuthoringColumnDefaultTemplateLiteral {
readonly kind: 'literal';
readonly value: AuthoringTemplateValue;
}
interface AuthoringColumnDefaultTemplateFunction {
readonly kind: 'function';
readonly expression: AuthoringTemplateValue;
}
type AuthoringColumnDefaultTemplate = AuthoringColumnDefaultTemplateLiteral | AuthoringColumnDefaultTemplateFunction;
interface AuthoringExecutionDefaultsTemplate {
readonly onCreate?: AuthoringTemplateValue;
readonly onUpdate?: AuthoringTemplateValue;
}
interface AuthoringFieldPresetOutput extends AuthoringStorageTypeTemplate {
readonly nullable?: boolean;
readonly default?: AuthoringColumnDefaultTemplate;
readonly executionDefaults?: AuthoringExecutionDefaultsTemplate;
readonly id?: boolean;
readonly unique?: boolean;
}
interface AuthoringFieldPresetDescriptor {
readonly kind: 'fieldPreset';
readonly args?: readonly AuthoringArgumentDescriptor[];
readonly output: AuthoringFieldPresetOutput;
}
type AuthoringTypeNamespace = {
readonly [name: string]: AuthoringTypeConstructorDescriptor | AuthoringTypeNamespace;
};
type AuthoringFieldNamespace = {
readonly [name: string]: AuthoringFieldPresetDescriptor | AuthoringFieldNamespace;
};
/**
* Context surfaced to entity-type factories at call time. Currently a
* placeholder — sharpened as concrete consumers (enum, namespace, …)
* discover what the factory actually needs to read (codec lookup,
* namespace registry, …).
*/
/**
* A write-only sink that a factory may push authoring-time diagnostics into.
* The concrete type pushed must be structurally compatible with whatever the
* consumer accumulates (typically `ContractSourceDiagnostic[]`); the framework
* layer deliberately does not depend on that concrete type.
*/
interface AuthoringDiagnosticSink {
push(d: {
readonly code: string;
readonly message: string;
readonly sourceId: string;
readonly span?: unknown;
}): void;
}
interface AuthoringEntityContext {
readonly family: string;
readonly target: string;
/** Codec registry available to factories that need to validate or decode values. */
readonly codecLookup?: CodecLookup;
/** Source file identifier threaded into diagnostics emitted by the factory. */
readonly sourceId?: string;
/** Push channel for authoring-time diagnostics emitted by the factory. */
readonly diagnostics?: AuthoringDiagnosticSink;
/**
* The target's default codec ids for an `enum` block that omits `@@type`.
* `text` is used when every member is a bare name or a string value;
* `int` is used when every member is an integer value. Every target pack
* populates this so `@@type` omission can be inferred consistently.
*/
readonly enumInferenceCodecs?: {
readonly text: string;
readonly int: string;
};
}
/**
* Classifies an `enum` block's members (before codec decoding, which needs
* the codec chosen first) into which default codec an omitted `@@type`
* should resolve to:
*
* - every member is `bare`, or a `value` whose raw JSON is a string → `'text'`
* - every member is a `value` whose raw JSON is an integer → `'int'`
* - anything else (float, bigint, boolean, mixed, or a `ref`/`option`/`list`
* parameter) → `null`, meaning the caller must require an explicit `@@type`.
*/
declare function classifyEnumMemberType(block: PslExtensionBlock): 'text' | 'int' | null;
/**
* Resolves the codec id for an `enum` block. When `@@type` is absent, the codec
* is inferred from the members via {@link classifyEnumMemberType}; otherwise the
* explicit `@@type("codec")` argument is parsed. Pushes the appropriate
* diagnostic and returns `undefined` when neither yields a codec. `codecSpan` is
* the span downstream codec-validation diagnostics should anchor to. Shared by
* every family's enum factory so inference and the explicit path stay identical.
*/
declare function resolveEnumCodecId(block: PslExtensionBlock, ctx: AuthoringEntityContext): {
readonly codecId: string;
readonly codecSpan: PslSpan;
} | undefined;
interface AuthoringEntityTypeTemplateOutput {
readonly template: AuthoringTemplateValue;
}
/**
* Default `Input = never` is load-bearing for pack-bag-driven type
* narrowing. Factory parameter positions are contravariant, so a pack
* literal declaring `factory: (input: DemoEntityInput) => DemoEntity`
* is only assignable to the base descriptor's factory shape if the
* base's input is `never` (the bottom of the contravariant position).
* The concrete input/output types are recovered at the helper-derivation
* site via `EntityHelperFunction<Descriptor>`'s conditional inference,
* which reads them from the pack's `as const` literal factory signature
* — the base widening does not erase the literal because `satisfies`
* does not widen the declared type.
*/
interface AuthoringEntityTypeFactoryOutput<Input = never, Output = unknown> {
readonly factory: (input: Input, ctx: AuthoringEntityContext) => Output;
}
interface AuthoringEntityTypeDescriptor<Input = never, Output = unknown> {
readonly kind: 'entity';
readonly discriminator: string;
readonly args?: readonly AuthoringArgumentDescriptor[];
readonly output: AuthoringEntityTypeTemplateOutput | AuthoringEntityTypeFactoryOutput<Input, Output>;
/**
* arktype schema fragment for one entry whose envelope `kind` matches
* this descriptor's {@link discriminator}. The family validator composes
* contributed fragments into the per-namespace entry schema at
* validator construction time so the structural check covers
* pack-introduced kinds without the family core hard-coding the schema.
*
* Hydration uses {@link AuthoringEntityTypeFactoryOutput.factory}
* directly — the wire shape conforms structurally to the factory's
* `Input` after `validatorSchema` validates it.
*/
readonly validatorSchema?: Type<unknown>;
}
type AuthoringEntityTypeNamespace = {
readonly [name: string]: AuthoringEntityTypeDescriptor | AuthoringEntityTypeNamespace;
};
/**
* Declarative descriptor for an extension-contributed top-level PSL block.
*
* An extension registers one of these per keyword it contributes. The
* framework owns the generic parser, validator, and printer — no
* parsing or printing code runs from the extension.
*
* - `keyword` is the PSL top-level identifier this descriptor claims
* (`policy_select`, `role`, …).
* - `discriminator` is the routing key used by the printer dispatch and
* the `entityTypes` lowering factory lookup. Convention:
* `<target-or-family>-<kind>` (`postgres-policy-select`).
* - `name.required` declares whether the block must have a name token
* after the keyword. Currently always `true` — anonymous blocks are
* not part of the closed-grammar premise — but the field is explicit
* so the type can evolve without a breaking change.
* - `parameters` maps parameter names to their value-kind descriptors
* (`ref` / `value` / `option` / `list`). The generic parser and
* validator interpret these; the extension supplies no parser or
* printer function.
*/
interface AuthoringPslBlockDescriptor {
readonly kind: 'pslBlock';
readonly keyword: string;
readonly discriminator: string;
readonly name: {
readonly required: boolean;
};
readonly parameters: Record<string, PslBlockParam>;
/**
* When `true`, the block body accepts a variadic tail of parameters beyond
* the declared set. The block body may contain: fields (model-style),
* `key = value` parameters, and `@@` attributes. With `variadicParameters`,
* bare identifiers (keys without a `= value`) and undeclared `key = value`
* pairs flow into the variadic tail — their semantics belong to the
* lowering, not the parser.
*
* A key that IS declared in `parameters` must still be supplied as
* `key = value`; a bare occurrence of a declared key is a diagnostic.
*
* When `false` (default), the validator emits `PSL_EXTENSION_UNKNOWN_PARAMETER`
* for keys absent from `parameters`.
*/
readonly variadicParameters?: boolean;
/**
* Declares that the model named by the block's ref parameter `parameter`
* must carry the bare `@@` model attribute `attribute`. The family
* interpreter enforces this generically over the whole parsed document —
* declaration order of the block and the model does not matter — and
* emits `PSL_EXTENSION_TARGET_MODEL_MISSING_ATTRIBUTE` naming the block
* and the model when the attribute is absent. A parameter that is
* missing or does not resolve to a model is not this rule's concern
* (missing-parameter and unresolved-ref diagnostics own those cases).
*/
readonly requiresModelAttribute?: {
readonly parameter: string;
readonly attribute: string;
};
}
type AuthoringPslBlockDescriptorNamespace = {
readonly [name: string]: AuthoringPslBlockDescriptor | AuthoringPslBlockDescriptorNamespace;
};
/**
* Context surfaced to a model-attribute lowering at call time: the entity
* context shared with entity-type factories, plus the declaring model's
* name, its mapped storage name (the name of the storage object the model
* maps to; which kind of object that is belongs to the family, not the
* framework), and the namespace id the lowered entity should be filed
* under.
*/
interface AuthoringModelAttributeContext extends AuthoringEntityContext {
readonly modelName: string;
readonly storageName: string;
readonly namespaceId: string;
}
/**
* What a model-attribute lowering returns when it produces an entity: `key`
* is the identity the entity is stored under within its `entries` slot
* (`entries[attribute][key]`); `entity` is the value stored there. A
* lowering that instead pushed a diagnostic through
* {@link AuthoringModelAttributeContext.diagnostics} returns `undefined` —
* the same convention {@link AuthoringEntityTypeFactoryOutput} uses.
*/
interface AuthoringModelAttributeLoweringOutput {
readonly key: string;
readonly entity: unknown;
}
/**
* Declarative descriptor for an extension-contributed `@@` model attribute.
*
* An extension registers one of these per bare attribute name it
* contributes. The framework owns the generic consult in the interpreter's
* model-attribute loop; the contribution supplies only `spec` and `lower`.
*
* - `attribute` is the bare `@@` attribute name this descriptor claims and,
* by the one-string rule, the `entries` slot its lowered entities are
* grouped under (`entries[attribute][key]`).
* - `spec` is opaque to the framework core: an ADR-231 attribute-spec kit
* `AttributeSpec<Out>` value (`modelAttribute(name, {...})` from
* `@prisma-next/psl-parser`). Framework core does not depend on
* psl-parser and never inspects this field; the family interpreter,
* which does depend on psl-parser, parses the attribute's arguments
* against it.
* - `lower` receives the parsed arguments and the declaring model's
* context, and returns the entity to file into `entries`, or `undefined`
* after pushing a diagnostic via `ctx.diagnostics`.
*
* `Out` defaults to `never` — not `unknown` — for the same contravariance
* reason documented on {@link AuthoringEntityTypeFactoryOutput}: a concrete
* pack literal's narrower `lower(parsed: ConcreteOut, ctx)` is only
* assignable to this base shape when the base parameter is the bottom type.
*/
interface AuthoringModelAttributeDescriptor<Out = never> {
readonly kind: 'modelAttribute';
readonly attribute: string;
readonly spec: unknown;
readonly lower: (parsed: Out, ctx: AuthoringModelAttributeContext) => AuthoringModelAttributeLoweringOutput | undefined;
}
type AuthoringModelAttributeDescriptorNamespace = {
readonly [name: string]: AuthoringModelAttributeDescriptor | AuthoringModelAttributeDescriptorNamespace;
};
interface AuthoringContributions {
readonly type?: AuthoringTypeNamespace;
readonly field?: AuthoringFieldNamespace;
readonly entityTypes?: AuthoringEntityTypeNamespace;
/**
* Registry of declarative block descriptors this contribution registers,
* keyed by arbitrary path segments. Each leaf is an
* {@link AuthoringPslBlockDescriptor} that claims a PSL top-level keyword.
* The framework owns the generic parser, validator, and printer; the
* contribution supplies only these declarative descriptors.
*
* Contrast with the parsed block nodes themselves, which live in a
* namespace's `entries` under their discriminator key; this field holds the
* registry of descriptors that teach the parser how to read those blocks.
*/
readonly pslBlockDescriptors?: AuthoringPslBlockDescriptorNamespace;
/**
* Registry of declarative `@@` model attribute descriptors this
* contribution registers, keyed by arbitrary path segments. Each leaf is
* an {@link AuthoringModelAttributeDescriptor} that claims a bare model
* attribute name. The framework owns the generic consult in the family
* interpreter's model-attribute loop; the contribution supplies only the
* declarative spec and the lowering.
*/
readonly modelAttributes?: AuthoringModelAttributeDescriptorNamespace;
}
declare function isAuthoringArgRef(value: unknown): value is AuthoringArgRef;
declare function isAuthoringTypeConstructorDescriptor(value: AuthoringTypeConstructorDescriptor | AuthoringTypeNamespace): value is AuthoringTypeConstructorDescriptor;
declare function isAuthoringFieldPresetDescriptor(value: AuthoringFieldPresetDescriptor | AuthoringFieldNamespace): value is AuthoringFieldPresetDescriptor;
declare function isAuthoringEntityTypeDescriptor(value: AuthoringEntityTypeDescriptor | AuthoringEntityTypeNamespace): value is AuthoringEntityTypeDescriptor;
declare function isAuthoringPslBlockDescriptor(value: AuthoringPslBlockDescriptor | AuthoringPslBlockDescriptorNamespace): value is AuthoringPslBlockDescriptor;
declare function isAuthoringModelAttributeDescriptor(value: AuthoringModelAttributeDescriptor | AuthoringModelAttributeDescriptorNamespace): value is AuthoringModelAttributeDescriptor;
/**
* Returns true when `namespace` is a non-leaf key in `contributions.field`.
*
* `AuthoringFieldNamespace` permits a leaf descriptor at any depth — including
* the root — so a top-level `field: { Foo: { kind: 'fieldPreset', ... } }`
* registration must NOT be treated as a "namespace" with sub-paths. Callers
* use this predicate to gate dot-namespaced lookups (e.g. PSL `@Foo.bar`).
*/
declare function hasRegisteredFieldNamespace(contributions: AuthoringContributions | undefined, namespace: string): boolean;
/**
* Merges `source` into `target` recursively at the descriptor-namespace
* level. `descriptorKind` is the `kind` value ('typeConstructor',
* 'fieldPreset', 'entity', or 'pslBlock') that identifies a descriptor
* (terminal merge point; same-path registrations across components are
* reported as duplicates) as opposed to a sub-namespace (recursion target).
*
* Path segments are validated against prototype-pollution names
* (`__proto__`, `constructor`, `prototype`). A value that is neither a
* recognized leaf nor a plain object — e.g. a malformed descriptor
* where the canonical leaf guard rejected it for missing `output` —
* is reported as an invalid contribution rather than recursed into,
* which would either silently mangle state or infinite-loop on
* primitive properties.
*
* Within-registry duplicate detection is this walker's job;
* cross-registry detection runs separately via
* `assertNoCrossRegistryCollisions` after merging completes.
*/
declare function mergeAuthoringNamespaces(target: Record<string, unknown>, source: Record<string, unknown>, path: readonly string[], descriptorKind: string, label: string): void;
declare function assertNoCrossRegistryCollisions(typeNamespace: AuthoringTypeNamespace, fieldNamespace: AuthoringFieldNamespace, entityTypeNamespace?: AuthoringEntityTypeNamespace, pslBlockNamespace?: AuthoringPslBlockDescriptorNamespace, modelAttributeNamespace?: AuthoringModelAttributeDescriptorNamespace): void;
declare function resolveAuthoringTemplateValue(template: AuthoringTemplateValue | undefined, args: readonly unknown[]): unknown;
declare function validateAuthoringHelperArguments(helperPath: string, descriptors: readonly AuthoringArgumentDescriptor[] | undefined, args: readonly unknown[]): void;
declare function instantiateAuthoringTypeConstructor(descriptor: AuthoringTypeConstructorDescriptor, args: readonly unknown[]): {
readonly codecId: string;
readonly nativeType: string;
readonly typeParams?: Record<string, unknown>;
};
declare function instantiateAuthoringEntityType<TOutput = unknown>(helperPath: string, descriptor: AuthoringEntityTypeDescriptor, args: readonly unknown[], ctx: AuthoringEntityContext): TOutput;
declare function instantiateAuthoringFieldPreset(descriptor: AuthoringFieldPresetDescriptor, args: readonly unknown[]): {
readonly descriptor: {
readonly codecId: string;
readonly nativeType: string;
readonly typeParams?: Record<string, unknown>;
};
readonly nullable: boolean;
readonly default?: ColumnDefault;
readonly executionDefaults?: ExecutionMutationDefaultPhases;
readonly id: boolean;
readonly unique: boolean;
};
//#endregion
export { PslExtensionBlockParamRef as $, instantiateAuthoringTypeConstructor as A, validateAuthoringHelperArguments as B, AuthoringTypeConstructorEntityRef as C, hasRegisteredFieldNamespace as D, classifyEnumMemberType as E, isAuthoringPslBlockDescriptor as F, PslBlockParamValue as G, PslBlockParamList as H, isAuthoringTypeConstructorDescriptor as I, PslExtensionBlockAttribute as J, PslDiagnosticCode as K, mergeAuthoringNamespaces as L, isAuthoringEntityTypeDescriptor as M, isAuthoringFieldPresetDescriptor as N, instantiateAuthoringEntityType as O, isAuthoringModelAttributeDescriptor as P, PslExtensionBlockParamOption as Q, resolveAuthoringTemplateValue as R, AuthoringTypeConstructorDescriptor as S, assertNoCrossRegistryCollisions as T, PslBlockParamOption as U, PslBlockParam as V, PslBlockParamRef as W, PslExtensionBlockParamBare as X, PslExtensionBlockAttributeArg as Y, PslExtensionBlockParamList as Z, AuthoringModelAttributeLoweringOutput as _, AuthoringDiagnosticSink as a, AuthoringStorageTypeTemplate as b, AuthoringEntityTypeFactoryOutput as c, AuthoringFieldNamespace as d, PslExtensionBlockParamScalarValue as et, AuthoringFieldPresetDescriptor as f, AuthoringModelAttributeDescriptorNamespace as g, AuthoringModelAttributeDescriptor as h, AuthoringContributions as i, isAuthoringArgRef as j, instantiateAuthoringFieldPreset as k, AuthoringEntityTypeNamespace as l, AuthoringModelAttributeContext as m, AuthoringArgumentDescriptor as n, PslPosition as nt, AuthoringEntityContext as o, AuthoringFieldPresetOutput as p, PslExtensionBlock as q, AuthoringColumnDefaultTemplate as r, PslSpan as rt, AuthoringEntityTypeDescriptor as s, AuthoringArgRef as t, PslExtensionBlockParamValue as tt, AuthoringEntityTypeTemplateOutput as u, AuthoringPslBlockDescriptor as v, AuthoringTypeNamespace as w, AuthoringTemplateValue as x, AuthoringPslBlockDescriptorNamespace as y, resolveEnumCodecId as z };
//# sourceMappingURL=framework-authoring-jIw3xcfy.d.mts.map
{"version":3,"file":"framework-authoring-jIw3xcfy.d.mts","names":[],"sources":["../src/shared/psl-extension-block.ts","../src/shared/framework-authoring.ts"],"mappings":";;;;;;;;;;AAYA;;;;;;UAAiB,W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qSc,+BAAA,CACd,aAAA,EAAe,sBAAA,EACf,cAAA,EAAgB,uBAAA,EAChB,mBAAA,GAAqB,4BAAA,EACrB,iBAAA,GAAmB,oCAAA,EACnB,uBAAA,GAAyB,0CAAA;AAAA,iBAqCX,6BAAA,CACd,QAAA,EAAU,sBAAsB,cAChC,IAAA;AAAA,iBAoHc,gCAAA,CACd,UAAA,UACA,WAAA,WAAsB,2BAA2B,gBACjD,IAAA;AAAA,iBAmHc,mCAAA,CACd,UAAA,EAAY,kCAAA,EACZ,IAAA;EAAA,SAES,OAAA;EAAA,SACA,UAAA;EAAA,SACA,UAAA,GAAa,MAAM;AAAA;AAAA,iBAKd,8BAAA,oBACd,UAAA,UACA,UAAA,EAAY,6BAAA,EACZ,IAAA,sBACA,GAAA,EAAK,sBAAA,GACJ,OAAA;AAAA,iBA2Ba,+BAAA,CACd,UAAA,EAAY,8BAAA,EACZ,IAAA;EAAA,SAES,UAAA;IAAA,SACE,OAAA;IAAA,SACA,UAAA;IAAA,SACA,UAAA,GAAa,MAAA;EAAA;EAAA,SAEf,QAAA;EAAA,SACA,OAAA,GAAU,aAAA;EAAA,SACV,iBAAA,GAAoB,8BAAA;EAAA,SACpB,EAAA;EAAA,SACA,MAAA;AAAA"}
import { f as AnyCodecDescriptor } from "./codec-types-BH2f2dg1.mjs";
import { i as AuthoringContributions } from "./framework-authoring-jIw3xcfy.mjs";
import { t as TypesImportSpec } from "./types-import-spec-DRKzrJ20.mjs";
import { ColumnDefault, ExecutionMutationDefaultPhases, ExecutionMutationDefaultValue } from "@prisma-next/contract/types";
//#region src/shared/mutation-default-types.d.ts
interface SourcePosition {
readonly offset: number;
readonly line: number;
readonly column: number;
}
interface SourceSpan {
readonly start: SourcePosition;
readonly end: SourcePosition;
}
interface SourceDiagnostic {
readonly code: string;
readonly message: string;
readonly sourceId?: string;
readonly span?: SourceSpan;
readonly data?: Readonly<Record<string, unknown>>;
}
interface DefaultFunctionArgument {
readonly raw: string;
readonly span: SourceSpan;
}
interface ParsedDefaultFunctionCall {
readonly name: string;
readonly raw: string;
readonly args: readonly DefaultFunctionArgument[];
readonly span: SourceSpan;
}
interface DefaultFunctionLoweringContext {
readonly sourceId: string;
readonly modelName: string;
readonly fieldName: string;
readonly columnCodecId?: string;
}
type LoweredDefaultValue = {
readonly kind: 'storage';
readonly defaultValue: ColumnDefault;
} | {
readonly kind: 'execution';
readonly generated: ExecutionMutationDefaultValue;
};
type LoweredDefaultResult = {
readonly ok: true;
readonly value: LoweredDefaultValue;
} | {
readonly ok: false;
readonly diagnostic: SourceDiagnostic;
};
type DefaultFunctionLoweringHandler = (input: {
readonly call: ParsedDefaultFunctionCall;
readonly context: DefaultFunctionLoweringContext;
}) => LoweredDefaultResult;
interface DefaultFunctionRegistryEntry {
readonly lower: DefaultFunctionLoweringHandler;
readonly usageSignatures?: readonly string[];
}
type DefaultFunctionRegistry = ReadonlyMap<string, DefaultFunctionRegistryEntry>;
interface MutationDefaultGeneratorDescriptor {
readonly id: string;
/**
* Codec ids the generator is compatible with when the codec choice
* and the generator choice are made independently by the contract
* author. Set when the registry-coherence check is meaningful
* (the codec and the generator can be paired arbitrarily by the
* caller); omitted when the generator is only reachable through a
* descriptor that co-registers a fixed codec, so coherence is
* structural and the list would be tautological.
*/
readonly applicableCodecIds?: readonly string[];
readonly resolveGeneratedColumnDescriptor?: (input: {
readonly generated: ExecutionMutationDefaultValue;
}) => {
readonly codecId: string;
readonly nativeType: string;
readonly typeRef?: string;
readonly typeParams?: Record<string, unknown>;
} | undefined;
/**
* Construct the `onCreate`/`onUpdate` phases value owned by this
* generator. Authoring layers (PSL `temporal.updatedAt()`, TS field presets) call
* this instead of building the literal inline so PSL/TS-authored
* contracts stay byte-equivalent for any future params-bearing generator.
*/
readonly buildPhases?: (args?: Record<string, unknown>) => ExecutionMutationDefaultPhases;
}
interface ControlMutationDefaultEntry {
readonly lower: (input: {
readonly call: ParsedDefaultFunctionCall;
readonly context: DefaultFunctionLoweringContext;
}) => LoweredDefaultResult;
readonly usageSignatures?: readonly string[];
}
type ControlMutationDefaultRegistry = ReadonlyMap<string, ControlMutationDefaultEntry>;
interface ControlMutationDefaults {
readonly defaultFunctionRegistry: ControlMutationDefaultRegistry;
readonly generatorDescriptors: readonly MutationDefaultGeneratorDescriptor[];
}
//#endregion
//#region src/shared/framework-components.d.ts
/**
* Declarative fields that describe component metadata.
*/
interface ComponentMetadata {
/** Component version (semver) */
readonly version: string;
/**
* Capabilities this component provides.
*
* For adapters, capabilities must be declared on the adapter descriptor (so they are emitted into the contract) and also exposed in runtime adapter code (e.g. `adapter.profile.capabilities`); keep these declarations in sync. Targets are identifiers/descriptors and typically do not declare capabilities.
*/
readonly capabilities?: Record<string, unknown>;
/** Type imports for contract.d.ts generation */
readonly types?: {
readonly codecTypes?: {
/**
* Base codec types import spec. Optional: adapters typically provide this, extensions usually don't.
*/
readonly import?: TypesImportSpec;
/**
* Additional type-only imports for parameterized codec branded types.
*
* These imports are included in generated `contract.d.ts` but are NOT treated as codec type maps (i.e., they should not be intersected into `export type CodecTypes = ...`).
*
* Example: `Vector<N>` for pgvector codecs that emit `Vector<1536>`
*/
readonly typeImports?: ReadonlyArray<TypesImportSpec>;
/**
* Optional control-plane hooks keyed by codecId. Used by family-specific planners/verifiers to handle storage types.
*/
readonly controlPlaneHooks?: Record<string, unknown>;
/**
* Codec descriptors contributed by this component. Source of truth for codec-id-keyed metadata (`traits`, `targetTypes`, `meta`, `renderOutputType`) consumed by `extractCodecLookup`, and used to materialize representative `Codec` instances for codec-dispatched type rendering during emission.
*/
readonly codecDescriptors?: ReadonlyArray<AnyCodecDescriptor>;
};
readonly queryOperationTypes?: {
readonly import: TypesImportSpec;
};
readonly storage?: ReadonlyArray<{
readonly typeId: string;
readonly familyId: string;
readonly targetId: string;
readonly nativeType?: string;
}>;
};
/**
* Optional pure-data authoring contributions exposed by this component.
*
* These contributions are safe to include on pack refs and descriptors because they contain only declarative metadata. Higher-level authoring packages may project them into concrete helper functions for TS-first workflows.
*/
readonly authoring?: AuthoringContributions;
/**
* Scalar type name to codec ID mapping contributed by this component. Assembled by `createControlStack` with duplicate detection.
*/
readonly scalarTypeDescriptors?: ReadonlyMap<string, string>;
/**
* Mutation default function handlers and generator descriptors contributed by this component. Assembled by `createControlStack` with duplicate detection.
*/
readonly controlMutationDefaults?: ControlMutationDefaults;
}
/**
* Base descriptor for any framework component.
*
* All component descriptors share these fundamental properties that identify the component and provide its metadata. This interface is extended by specific descriptor types (FamilyDescriptor, TargetDescriptor, etc.).
*
* @template Kind - Discriminator literal identifying the component type. Built-in kinds are 'family', 'target', 'adapter', 'driver', 'extension', but the type accepts any string to allow ecosystem extensions.
*
* @example
* ```ts
* // All descriptors have these properties
* descriptor.kind // The Kind type parameter (e.g., 'family', 'target', or custom kinds)
* descriptor.id // Unique string identifier (e.g., 'sql', 'postgres')
* descriptor.version // Component version (semver)
* ```
*/
interface ComponentDescriptor<Kind extends string> extends ComponentMetadata {
/** Discriminator identifying the component type */
readonly kind: Kind;
/** Unique identifier for this component (e.g., 'sql', 'postgres', 'pgvector') */
readonly id: string;
}
interface ContractComponentRequirementsCheckInput {
readonly contract: {
readonly target: string;
readonly targetFamily?: string | undefined;
readonly extensionPacks?: Record<string, unknown> | undefined;
};
readonly expectedTargetFamily?: string | undefined;
readonly expectedTargetId?: string | undefined;
readonly providedComponentIds: Iterable<string>;
}
interface ContractComponentRequirementsCheckResult {
readonly familyMismatch?: {
readonly expected: string;
readonly actual: string;
} | undefined;
readonly targetMismatch?: {
readonly expected: string;
readonly actual: string;
} | undefined;
readonly missingExtensionPackIds: readonly string[];
}
declare function checkContractComponentRequirements(input: ContractComponentRequirementsCheckInput): ContractComponentRequirementsCheckResult;
/**
* Descriptor for a family component.
*
* A "family" represents a category of data sources with shared semantics (e.g., SQL databases, document stores). Families define:
* - Query semantics and operations (SELECT, INSERT, find, aggregate, etc.)
* - Contract structure (tables vs collections, columns vs fields)
* - Type system and codecs
*
* Families are the top-level grouping. Each family contains multiple targets (e.g., SQL family contains Postgres, MySQL, SQLite targets).
*
* Extended by plane-specific descriptors:
* - `ControlFamilyDescriptor` - adds `emission` for CLI/tooling operations
* - `RuntimeFamilyDescriptor` - adds runtime-specific factory methods
*
* @template TFamilyId - Literal type for the family identifier (e.g., 'sql', 'document')
*
* @example
* ```ts
* import sql from '@prisma-next/family-sql/control';
*
* sql.kind // 'family'
* sql.familyId // 'sql'
* sql.id // 'sql'
* ```
*/
interface FamilyDescriptor<TFamilyId extends string> extends ComponentDescriptor<'family'> {
/** The family identifier (e.g., 'sql', 'document') */
readonly familyId: TFamilyId;
}
/**
* Descriptor for a target component.
*
* A "target" represents a specific database or data store within a family (e.g., Postgres, MySQL, MongoDB). Targets define:
* - Native type mappings (e.g., Postgres int4 → TypeScript number)
* - Target-specific capabilities (e.g., RETURNING, LATERAL joins)
*
* Targets are bound to a family and provide the target-specific implementation details that adapters and drivers use.
*
* Extended by plane-specific descriptors:
* - `ControlTargetDescriptor` - adds optional `migrations` capability
* - `RuntimeTargetDescriptor` - adds runtime factory method
*
* @template TFamilyId - Literal type for the family identifier
* @template TTargetId - Literal type for the target identifier (e.g., 'postgres', 'mysql')
*
* @example
* ```ts
* import postgres from '@prisma-next/target-postgres/control';
*
* postgres.kind // 'target'
* postgres.familyId // 'sql'
* postgres.targetId // 'postgres'
* ```
*/
interface TargetDescriptor<TFamilyId extends string, TTargetId extends string> extends ComponentDescriptor<'target'> {
/** The family this target belongs to */
readonly familyId: TFamilyId;
/** The target identifier (e.g., 'postgres', 'mysql', 'mongodb') */
readonly targetId: TTargetId;
}
/**
* Base shape for any pack reference. Pack refs are pure JSON-friendly objects safe to import in authoring flows.
*/
interface PackRefBase<Kind extends string, TFamilyId extends string> extends ComponentMetadata {
readonly kind: Kind;
readonly id: string;
readonly familyId: TFamilyId;
readonly targetId?: string;
readonly authoring?: AuthoringContributions;
}
type FamilyPackRef<TFamilyId extends string = string> = PackRefBase<'family', TFamilyId>;
type TargetPackRef<TFamilyId extends string = string, TTargetId extends string = string> = PackRefBase<'target', TFamilyId> & {
readonly targetId: TTargetId; /** The namespace a bare (un-namespaced) entity name resolves to for this target (e.g. Postgres `'public'`). */
readonly defaultNamespaceId: string;
};
type AdapterPackRef<TFamilyId extends string = string, TTargetId extends string = string> = PackRefBase<'adapter', TFamilyId> & {
readonly targetId: TTargetId;
};
type ExtensionPackRef<TFamilyId extends string = string, TTargetId extends string = string> = PackRefBase<'extension', TFamilyId> & {
readonly targetId: TTargetId;
};
type DriverPackRef<TFamilyId extends string = string, TTargetId extends string = string> = PackRefBase<'driver', TFamilyId> & {
readonly targetId: TTargetId;
};
/**
* Descriptor for an adapter component.
*
* An "adapter" provides the protocol and dialect implementation for a target. Adapters handle:
* - SQL/query generation (lowering AST to target-specific syntax)
* - Codec registration (encoding/decoding between JS and wire types)
* - Type mappings and coercions
*
* Adapters are bound to a specific family+target combination and work with any compatible driver for that target.
*
* Extended by plane-specific descriptors:
* - `ControlAdapterDescriptor` - control-plane factory
* - `RuntimeAdapterDescriptor` - runtime factory
*
* @template TFamilyId - Literal type for the family identifier
* @template TTargetId - Literal type for the target identifier
*
* @example
* ```ts
* import postgresAdapter from '@prisma-next/adapter-postgres/control';
*
* postgresAdapter.kind // 'adapter'
* postgresAdapter.familyId // 'sql'
* postgresAdapter.targetId // 'postgres'
* ```
*/
interface AdapterDescriptor<TFamilyId extends string, TTargetId extends string> extends ComponentDescriptor<'adapter'> {
/** The family this adapter belongs to */
readonly familyId: TFamilyId;
/** The target this adapter is designed for */
readonly targetId: TTargetId;
}
/**
* Descriptor for a driver component.
*
* A "driver" provides the connection and execution layer for a target. Drivers handle:
* - Connection management (pooling, timeouts, retries)
* - Query execution (sending SQL/commands, receiving results)
* - Transaction management
* - Wire protocol communication
*
* Drivers are bound to a specific family+target and work with any compatible adapter. Multiple drivers can exist for the same target (e.g., node-postgres vs postgres.js for Postgres).
*
* Extended by plane-specific descriptors:
* - `ControlDriverDescriptor` - creates driver from connection URL
* - `RuntimeDriverDescriptor` - creates driver with runtime options
*
* @template TFamilyId - Literal type for the family identifier
* @template TTargetId - Literal type for the target identifier
*
* @example
* ```ts
* import postgresDriver from '@prisma-next/driver-postgres/control';
*
* postgresDriver.kind // 'driver'
* postgresDriver.familyId // 'sql'
* postgresDriver.targetId // 'postgres'
* ```
*/
interface DriverDescriptor<TFamilyId extends string, TTargetId extends string> extends ComponentDescriptor<'driver'> {
/** The family this driver belongs to */
readonly familyId: TFamilyId;
/** The target this driver connects to */
readonly targetId: TTargetId;
}
/**
* Descriptor for an extension component.
*
* An "extension" adds optional capabilities to a target. Extensions can provide:
* - Additional operations (e.g., vector similarity search with pgvector)
* - Custom types and codecs (e.g., vector type)
* - Extended query capabilities
*
* Extensions are bound to a specific family+target and are registered in the config alongside the core components. Multiple extensions can be used together.
*
* Extended by plane-specific descriptors:
* - `ControlExtensionDescriptor` - control-plane extension factory
* - `RuntimeExtensionDescriptor` - runtime extension factory
*
* @template TFamilyId - Literal type for the family identifier
* @template TTargetId - Literal type for the target identifier
*
* @example
* ```ts
* import pgvector from '@prisma-next/extension-pgvector/control';
*
* pgvector.kind // 'extension'
* pgvector.familyId // 'sql'
* pgvector.targetId // 'postgres'
* ```
*/
interface ExtensionDescriptor<TFamilyId extends string, TTargetId extends string> extends ComponentDescriptor<'extension'> {
/** The family this extension belongs to */
readonly familyId: TFamilyId;
/** The target this extension is designed for */
readonly targetId: TTargetId;
}
/** Components bound to a specific family+target combination. */
type TargetBoundComponentDescriptor<TFamilyId extends string, TTargetId extends string> = TargetDescriptor<TFamilyId, TTargetId> | AdapterDescriptor<TFamilyId, TTargetId> | DriverDescriptor<TFamilyId, TTargetId> | ExtensionDescriptor<TFamilyId, TTargetId>;
interface FamilyInstance<TFamilyId extends string> {
readonly familyId: TFamilyId;
}
interface TargetInstance<TFamilyId extends string, TTargetId extends string> {
readonly familyId: TFamilyId;
readonly targetId: TTargetId;
}
interface AdapterInstance<TFamilyId extends string, TTargetId extends string> {
readonly familyId: TFamilyId;
readonly targetId: TTargetId;
}
interface DriverInstance<TFamilyId extends string, TTargetId extends string> {
readonly familyId: TFamilyId;
readonly targetId: TTargetId;
}
interface ExtensionInstance<TFamilyId extends string, TTargetId extends string> {
readonly familyId: TFamilyId;
readonly targetId: TTargetId;
}
//#endregion
export { LoweredDefaultResult as A, ControlMutationDefaultEntry as C, DefaultFunctionLoweringHandler as D, DefaultFunctionLoweringContext as E, SourceSpan as F, MutationDefaultGeneratorDescriptor as M, ParsedDefaultFunctionCall as N, DefaultFunctionRegistry as O, SourceDiagnostic as P, checkContractComponentRequirements as S, ControlMutationDefaults as T, PackRefBase as _, ComponentMetadata as a, TargetInstance as b, DriverDescriptor as c, ExtensionDescriptor as d, ExtensionInstance as f, FamilyPackRef as g, FamilyInstance as h, ComponentDescriptor as i, LoweredDefaultValue as j, DefaultFunctionRegistryEntry as k, DriverInstance as l, FamilyDescriptor as m, AdapterInstance as n, ContractComponentRequirementsCheckInput as o, ExtensionPackRef as p, AdapterPackRef as r, ContractComponentRequirementsCheckResult as s, AdapterDescriptor as t, DriverPackRef as u, TargetBoundComponentDescriptor as v, ControlMutationDefaultRegistry as w, TargetPackRef as x, TargetDescriptor as y };
//# sourceMappingURL=framework-components-7p9S3MZ0.d.mts.map
{"version":3,"file":"framework-components-7p9S3MZ0.d.mts","names":[],"sources":["../src/shared/mutation-default-types.ts","../src/shared/framework-components.ts"],"mappings":";;;;;;UAMU,cAAA;EAAA,SACC,MAAA;EAAA,SACA,IAAA;EAAA,SACA,MAAA;AAAA;AAAA,UAGM,UAAA;EAAA,SACN,KAAA,EAAO,cAAA;EAAA,SACP,GAAA,EAAK,cAAc;AAAA;AAAA,UAGb,gBAAA;EAAA,SACN,IAAA;EAAA,SACA,OAAA;EAAA,SACA,QAAA;EAAA,SACA,IAAA,GAAO,UAAA;EAAA,SACP,IAAA,GAAO,QAAA,CAAS,MAAA;AAAA;AAAA,UAGjB,uBAAA;EAAA,SACC,GAAA;EAAA,SACA,IAAA,EAAM,UAAU;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;;;;;;;AA7NoB;AAGzC;;;;;;;;;;;;AAGkC;AAGlC;;;;;;UAiPiB,mBAAA,6DACP,mBAAA;EAhPiC;EAAA,SAkPhC,QAAA,EAAU,SAAA;EAvLJ;EAAA,SA0LN,QAAA,EAAU,SAAA;AAAA;;KAIT,8BAAA,uDACR,gBAAA,CAAiB,SAAA,EAAW,SAAA,IAC5B,iBAAA,CAAkB,SAAA,EAAW,SAAA,IAC7B,gBAAA,CAAiB,SAAA,EAAW,SAAA,IAC5B,mBAAA,CAAoB,SAAA,EAAW,SAAA;AAAA,UAElB,cAAA;EAAA,SACN,QAAA,EAAU,SAAS;AAAA;AAAA,UAGb,cAAA;EAAA,SACN,QAAA,EAAU,SAAA;EAAA,SACV,QAAA,EAAU,SAAS;AAAA;AAAA,UAGb,eAAA;EAAA,SACN,QAAA,EAAU,SAAA;EAAA,SACV,QAAA,EAAU,SAAS;AAAA;AAAA,UAGb,cAAA;EAAA,SACN,QAAA,EAAU,SAAA;EAAA,SACV,QAAA,EAAU,SAAS;AAAA;AAAA,UAGb,iBAAA;EAAA,SACN,QAAA,EAAU,SAAA;EAAA,SACV,QAAA,EAAU,SAAS;AAAA"}
import { r as CodecLookup } from "./codec-types-BH2f2dg1.mjs";
import { K as PslDiagnosticCode, q as PslExtensionBlock, rt as PslSpan, y as AuthoringPslBlockDescriptorNamespace } from "./framework-authoring-jIw3xcfy.mjs";
//#region src/control/psl-ast.d.ts
interface PslDiagnostic {
readonly code: PslDiagnosticCode;
readonly message: string;
readonly sourceId: string;
readonly span: PslSpan;
}
interface PslDefaultFunctionValue {
readonly kind: 'function';
readonly name: 'autoincrement' | 'now';
}
interface PslDefaultLiteralValue {
readonly kind: 'literal';
readonly value: string | number | boolean;
}
type PslDefaultValue = PslDefaultFunctionValue | PslDefaultLiteralValue;
type PslAttributeTarget = 'field' | 'model' | 'enum' | 'namedType';
interface PslAttributePositionalArgument {
readonly kind: 'positional';
readonly value: string;
readonly span: PslSpan;
}
interface PslAttributeNamedArgument {
readonly kind: 'named';
readonly name: string;
readonly value: string;
readonly span: PslSpan;
}
type PslAttributeArgument = PslAttributePositionalArgument | PslAttributeNamedArgument;
interface PslTypeConstructorCall {
readonly kind: 'typeConstructor';
readonly path: readonly string[];
readonly args: readonly PslAttributeArgument[];
readonly span: PslSpan;
}
interface PslAttribute {
readonly kind: 'attribute';
readonly target: PslAttributeTarget;
readonly name: string;
readonly args: readonly PslAttributeArgument[];
readonly span: PslSpan;
}
type PslReferentialAction = string;
type PslFieldAttribute = PslAttribute;
interface PslField {
readonly kind: 'field';
readonly name: string;
/** Unqualified type name, e.g. `"User"` for both `User`, `auth.User`, and `supabase:auth.User`. */
readonly typeName: string;
/** Namespace qualifier from a dot-qualified type reference, e.g. `"auth"` for `auth.User` or `supabase:auth.User`. Absent for unqualified types. */
readonly typeNamespaceId?: string;
/**
* Contract-space qualifier from a colon-prefix type reference, e.g. `"supabase"` for
* `supabase:auth.User` or `supabase:User`. Absent for local (same-space) type references.
*
* When present, the field references a model from a different contract space. The namespace
* (`typeNamespaceId`) and model name (`typeName`) identify the target within that space.
* Physical table resolution against the extension contract is deferred to the aggregate stage (M3).
*/
readonly typeContractSpaceId?: string;
readonly typeConstructor?: PslTypeConstructorCall;
readonly optional: boolean;
readonly list: boolean;
readonly typeRef?: string;
readonly attributes: readonly PslFieldAttribute[];
readonly span: PslSpan;
}
interface PslUniqueConstraint {
readonly kind: 'unique';
readonly fields: readonly string[];
readonly span: PslSpan;
}
interface PslIndexConstraint {
readonly kind: 'index';
readonly fields: readonly string[];
readonly span: PslSpan;
}
type PslModelAttribute = PslAttribute;
interface PslModel {
readonly kind: 'model';
readonly name: string;
readonly fields: readonly PslField[];
readonly attributes: readonly PslModelAttribute[];
readonly span: PslSpan;
/**
* Optional leading comment line emitted above the `model` keyword by the
* printer. Producers (e.g. `sqlSchemaIrToPslAst`) attach introspection
* advisories such as "// WARNING: This table has no primary key in the
* database" here. The parser leaves this field unset; round-tripping a
* parsed schema does not re-attach comments.
*/
readonly comment?: string;
}
/**
* A reusable group of fields embedded in a model (a `type Name { … }` block) —
* e.g. a MongoDB embedded document or a Postgres composite type. Unlike
* {@link PslModel} it has no storage or identity of its own.
*/
interface PslCompositeType {
readonly kind: 'compositeType';
readonly name: string;
readonly fields: readonly PslField[];
readonly attributes: readonly PslAttribute[];
readonly span: PslSpan;
}
interface PslNamedTypeDeclaration {
readonly kind: 'namedType';
readonly name: string;
/**
* Parser invariant: exactly one of `baseType` and `typeConstructor` is set.
* Expressing this as a discriminated union trips TypeScript narrowing when
* the declaration flows through helpers that accept the full union.
*/
readonly baseType?: string;
readonly typeConstructor?: PslTypeConstructorCall;
readonly attributes: readonly PslAttribute[];
readonly span: PslSpan;
}
interface PslTypesBlock {
readonly kind: 'types';
readonly declarations: readonly PslNamedTypeDeclaration[];
readonly span: PslSpan;
}
/**
* Name of the synthesised namespace bucket the framework parser uses for
* top-level declarations that appear outside any `namespace { … }` block.
* The double-underscore decoration signals that the identifier is parser-
* synthesised and never appears in user-authored PSL source — writing
* `namespace __unspecified__ { … }` is a parse error.
*
* Distinct from the IR sentinel `__unbound__`: the PSL bucket describes
* syntactic absence at the parser layer; the IR sentinel describes a late-
* bound storage slot at the IR layer. Per-target interpreters decide how
* (or whether) to map the PSL bucket to the IR sentinel.
*/
declare const UNSPECIFIED_PSL_NAMESPACE_ID = "__unspecified__";
/** A value in {@link PslNamespace.entries}: a built-in entity node or an extension-contributed {@link PslExtensionBlock}. */
type PslNamespaceEntry = PslModel | PslCompositeType | PslExtensionBlock;
/**
* A namespace block, or the parser's synthesised `__unspecified__` bucket for
* declarations outside any `namespace { … }`. Same-name blocks reopen-merge;
* `span` points at the first opening.
*
* Entities are stored canonically (ADR 224) in `entries[kind][name]`, where
* `kind` is the PSL keyword for built-ins or the block discriminator for
* extension kinds, e.g. `entries['policy']['ReadPosts']` (the discriminator,
* not the PSL keyword — a `policy_select` block lands under `'policy'` per
* ADR 225).
*/
interface PslNamespace {
readonly kind: 'namespace';
readonly name: string;
/** Canonical store: a frozen container of frozen per-kind maps. The accessors below derive from it. */
readonly entries: Readonly<Record<string, Readonly<Record<string, PslNamespaceEntry>>>>;
/** Built-in models, from `entries['model']`. Extension kinds: {@link namespacePslExtensionBlocks}. */
readonly models: readonly PslModel[];
/** Built-in composite types, from `entries['compositeType']`. */
readonly compositeTypes: readonly PslCompositeType[];
readonly span: PslSpan;
}
/** Constructs a {@link PslNamespace}. Use this, never a namespace literal — the accessors must derive from `entries`. */
declare function makePslNamespace(init: {
readonly kind: 'namespace';
readonly name: string;
readonly entries: Readonly<Record<string, Readonly<Record<string, PslNamespaceEntry>>>>;
readonly span: PslSpan;
}): PslNamespace;
/**
* Builds the frozen `entries[kind][name]` container from per-kind arrays.
* Built-ins key on their PSL keyword; extension blocks key on their `kind`
* discriminator. Call this rather than hand-building the literal.
*/
declare function makePslNamespaceEntries(models: readonly PslModel[], compositeTypes: readonly PslCompositeType[], extensionBlocks: readonly PslExtensionBlock[]): Readonly<Record<string, Readonly<Record<string, PslNamespaceEntry>>>>;
interface PslDocumentAst {
readonly kind: 'document';
readonly sourceId: string;
readonly namespaces: readonly PslNamespace[];
readonly types?: PslTypesBlock;
readonly span: PslSpan;
}
/**
* Returns all models from every namespace in document order. Convenience
* for consumers that don't (yet) need namespace-awareness.
*/
declare function flatPslModels(ast: PslDocumentAst): readonly PslModel[];
/**
* Returns all composite types from every namespace in document order.
*/
declare function flatPslCompositeTypes(ast: PslDocumentAst): readonly PslCompositeType[];
/**
* The set of `entries` kind keys that the framework parser reserves for
* built-in PSL entity kinds. Any own-enumerable key on `PslNamespace.entries`
* that is **not** in this set was contributed by an extension-block descriptor.
*
* Built-in keys match the PSL keyword used on each block type:
* `'model'`, `'compositeType'`. The `'enum'` keyword is claimed by the
* extension-block grammar via a registered descriptor, so `entries['enum']`
* holds `PslExtensionBlock` nodes and is returned by `namespacePslExtensionBlocks`.
*/
declare const BUILTIN_PSL_KIND_KEYS: ReadonlySet<string>;
/**
* Returns all extension-contributed blocks in the given namespace, in
* insertion order (the order the parser encountered them in the source).
*
* Reads from `namespace.entries`, skipping the built-in kind keys
* (`'model'`, `'compositeType'`). All remaining kind maps contain
* only `PslExtensionBlock` nodes by construction (see `makePslNamespaceEntries`).
*/
declare function namespacePslExtensionBlocks(ns: PslNamespace): readonly PslExtensionBlock[];
interface ParsePslDocumentInput {
readonly schema: string;
readonly sourceId: string;
/**
* Registry of declarative block descriptors, keyed by arbitrary path
* segments with {@link AuthoringPslBlockDescriptor} leaves. The registry
* teaches the parser which top-level keywords belong to extension
* contributions: when the parser encounters an unknown keyword, it looks
* it up here and, when found, reads the block generically into a
* {@link PslExtensionBlock} node. Absent or undefined means no extension
* blocks are registered and any unknown keyword yields
* `PSL_UNSUPPORTED_TOP_LEVEL_BLOCK`.
*
* Contrast with the parsed block nodes themselves, which live in
* {@link PslNamespace.entries} under their discriminator key (read them with
* {@link namespacePslExtensionBlocks}); this field holds the registry of
* descriptors that teach the parser how to read those blocks.
*/
readonly pslBlockDescriptors?: AuthoringPslBlockDescriptorNamespace;
/**
* Codec lookup for validating `value`-kind extension block parameters.
* When provided alongside `pslBlockDescriptors`, the generic validator runs
* over every parsed extension block after the full AST is assembled,
* appending any diagnostics to the parse result. Absent or undefined means
* no codec validation runs; `ref` resolution still runs when namespace
* context is available (built from the assembled namespaces).
*/
readonly codecLookup?: CodecLookup;
}
interface ParsePslDocumentResult {
readonly ast: PslDocumentAst;
readonly diagnostics: readonly PslDiagnostic[];
readonly ok: boolean;
}
//#endregion
export { makePslNamespace as A, PslReferentialAction as C, UNSPECIFIED_PSL_NAMESPACE_ID as D, PslUniqueConstraint as E, namespacePslExtensionBlocks as M, flatPslCompositeTypes as O, PslNamespaceEntry as S, PslTypesBlock as T, PslIndexConstraint as _, PslAttributeArgument as a, PslNamedTypeDeclaration as b, PslAttributeTarget as c, PslDefaultLiteralValue as d, PslDefaultValue as f, PslFieldAttribute as g, PslField as h, PslAttribute as i, makePslNamespaceEntries as j, flatPslModels as k, PslCompositeType as l, PslDocumentAst as m, ParsePslDocumentInput as n, PslAttributeNamedArgument as o, PslDiagnostic as p, ParsePslDocumentResult as r, PslAttributePositionalArgument as s, BUILTIN_PSL_KIND_KEYS as t, PslDefaultFunctionValue as u, PslModel as v, PslTypeConstructorCall as w, PslNamespace as x, PslModelAttribute as y };
//# sourceMappingURL=psl-ast-BRRUqpAN.d.mts.map
{"version":3,"file":"psl-ast-BRRUqpAN.d.mts","names":[],"sources":["../src/control/psl-ast.ts"],"mappings":";;;;UA0BiB,aAAA;EAAA,SACN,IAAA,EAAM,iBAAA;EAAA,SACN,OAAA;EAAA,SACA,QAAA;EAAA,SACA,IAAA,EAAM,OAAO;AAAA;AAAA,UAGP,uBAAA;EAAA,SACN,IAAA;EAAA,SACA,IAAI;AAAA;AAAA,UAGE,sBAAA;EAAA,SACN,IAAA;EAAA,SACA,KAAK;AAAA;AAAA,KAGJ,eAAA,GAAkB,uBAAA,GAA0B,sBAAsB;AAAA,KAElE,kBAAA;AAAA,UAEK,8BAAA;EAAA,SACN,IAAA;EAAA,SACA,KAAA;EAAA,SACA,IAAA,EAAM,OAAO;AAAA;AAAA,UAGP,yBAAA;EAAA,SACN,IAAA;EAAA,SACA,IAAA;EAAA,SACA,KAAA;EAAA,SACA,IAAA,EAAM,OAAO;AAAA;AAAA,KAGZ,oBAAA,GAAuB,8BAAA,GAAiC,yBAAyB;AAAA,UAE5E,sBAAA;EAAA,SACN,IAAA;EAAA,SACA,IAAA;EAAA,SACA,IAAA,WAAe,oBAAA;EAAA,SACf,IAAA,EAAM,OAAO;AAAA;AAAA,UAGP,YAAA;EAAA,SACN,IAAA;EAAA,SACA,MAAA,EAAQ,kBAAA;EAAA,SACR,IAAA;EAAA,SACA,IAAA,WAAe,oBAAA;EAAA,SACf,IAAA,EAAM,OAAA;AAAA;AAAA,KAGL,oBAAA;AAAA,KAEA,iBAAA,GAAoB,YAAY;AAAA,UAE3B,QAAA;EAAA,SACN,IAAA;EAAA,SACA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