cvx-kit 0.1.16 → 0.1.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,25 +1,26 @@
1
1
  import { ManagedBudgets, ManagedQueryContext, ManagedSecurityConfig } from "./querying/security.mjs";
2
2
  import { IndexCondition, NativePagination } from "./querying/filters.mjs";
3
- import { RelationDeclarations, RelationFilterSelection, RelationFilters, RelationRegistry, RelationRow, RelationSelection, RelationTables } from "./relations.mjs";
3
+ import { RelationDeclarations, RelationFilterSelection, RelationFilters, RelationQueryRow, RelationRegistry, RelationSelection, RelationTables } from "./relations.mjs";
4
4
  import { CursorCodecConfig } from "./querying/cursors.mjs";
5
5
  import { DataModelFromSchemaDefinition, GenericSchema, PaginationResult, SchemaDefinition } from "convex/server";
6
6
  import { GenericId } from "convex/values";
7
7
  //#region src/querying.d.ts
8
- type FullMask<S> = { [K in keyof S]-?: NonNullable<S[K]> extends true ? true : FullMask<NonNullable<S[K]>>; };
8
+ type FullMask<S> = { [K in keyof S]-?: NonNullable<S[K]> extends true ? true : FullMask<Exclude<NonNullable<S[K]>, true>>; };
9
9
  type Paths<D extends RelationDeclarations, T extends string, L extends readonly 1[] = [1, 1, 1, 1]> = L extends readonly [1, ...infer Rest extends 1[]] ? { [K in keyof D[T] & string]: (D[T][K]['cardinality'] extends 'many' ? K : never) | `${K}.${Paths<D, D[T][K]['target'], Rest>}`; }[keyof D[T] & string] : never;
10
10
  type PathTarget<D extends RelationDeclarations, T extends string, P extends string> = P extends `${infer Head}.${infer Rest}` ? PathTarget<D, D[T][Head]['target'], Rest> : D[T][P]['target'];
11
+ type PathScope<D extends RelationDeclarations, T extends string, P extends string> = P extends `${infer Head}.${infer Rest}` ? PathScope<D, D[T][Head]['target'], Rest> : Extract<NonNullable<D[T][P]['targetGuard']>['tag'], string>;
11
12
  type RemainingDepth<P extends string, L extends readonly 1[]> = L extends readonly [1, ...infer Rest extends 1[]] ? P extends `${string}.${infer Tail}` ? RemainingDepth<Tail, Rest> : Rest : [];
12
13
  type EngineArgs<Tables extends RelationTables, D extends RelationDeclarations, T extends keyof Tables> = NativePagination & {
13
14
  filters?: RelationFilters<Tables, D, T, FullMask<RelationFilterSelection<Tables, D, T>>>;
14
15
  order?: 'asc' | 'desc';
15
16
  };
16
17
  /** Typed declarative chain returned by the engine; named for consumer declaration emission. */
17
- export interface TableQuery<Tables extends RelationTables, D extends RelationDeclarations, T extends keyof Tables, S = {}, L extends readonly 1[] = [1, 1, 1, 1]> {
18
- when(value: IndexCondition['value'], index: string): TableQuery<Tables, D, T, S, L>;
19
- where(spec: NonNullable<EngineArgs<Tables, D, T>['filters']>): TableQuery<Tables, D, T, S, L>;
20
- with<const Selection extends RelationSelection<Tables, D, T, L>>(selection: Selection & { [K in keyof Selection]: K extends keyof RelationSelection<Tables, D, T, L> ? Selection[K] : never; }): TableQuery<Tables, D, T, Selection, L>;
21
- relation<const P extends Paths<D, Extract<T, string>>>(parent: GenericId<Tables[T]['tableName']>, path: P): Omit<TableQuery<Tables, D, Extract<PathTarget<D, Extract<T, string>, P>, keyof Tables>, {}, RemainingDepth<P, L>>, 'relation'>;
22
- paginate(args: EngineArgs<Tables, D, T>): Promise<PaginationResult<RelationRow<Tables, D, T, S>>>;
18
+ export interface TableQuery<Tables extends RelationTables, D extends RelationDeclarations, T extends keyof Tables, S = {}, L extends readonly 1[] = [1, 1, 1, 1], Scope extends string = never> {
19
+ when(value: IndexCondition['value'], index: string): TableQuery<Tables, D, T, S, L, Scope>;
20
+ where(spec: NonNullable<EngineArgs<Tables, D, T>['filters']>): TableQuery<Tables, D, T, S, L, Scope>;
21
+ with<const Selection extends RelationSelection<Tables, D, T, L>>(selection: Selection & { [K in keyof Selection]: K extends keyof RelationSelection<Tables, D, T, L> ? Selection[K] : never; }): TableQuery<Tables, D, T, Selection, L, Scope>;
22
+ relation<const P extends Paths<D, Extract<T, string>>>(parent: GenericId<Tables[T]['tableName']>, path: P): Omit<TableQuery<Tables, D, Extract<PathTarget<D, Extract<T, string>, P>, keyof Tables>, {}, RemainingDepth<P, L>, PathScope<D, Extract<T, string>, P>>, 'relation'>;
23
+ paginate(args: EngineArgs<Tables, D, T>): Promise<PaginationResult<RelationQueryRow<Tables, D, T, S, Scope>>>;
23
24
  }
24
25
  export interface QueryEngineDeclaration<Schema extends SchemaDefinition<GenericSchema, boolean>, Tables extends RelationTables, D extends RelationDeclarations> {
25
26
  schema: Schema;
@@ -1 +1 @@
1
- {"version":3,"file":"querying.mjs","names":["executorRequest","createQueryEngine","config","settings","options","planner","createPlanner","schema","relations","cursorCodec","createCursorCodec","maxPageSize","engineVersion","policyVersion","registryDigest","security","createManagedSecurity","querying","request","ctx","tableQuery","table","conditions","constraints","selection","route","spec","selected","path","declaredPath","target","name","edge","codec","createEnvironmentCursorCodec","pageSchema","assertRelationshipDepth","plan","input","byte","binding","executor","relationshipExecutor","result","executeQuery","permitted","row"],"sources":["../src/querying.ts"],"sourcesContent":["import type {\n\tGenericSchema,\n\tSchemaDefinition,\n\tDataModelFromSchemaDefinition,\n\tPaginationResult,\n} from 'convex/server'\nimport type { GenericId } from 'convex/values'\nimport type {\n\tRelationTables,\n\tRelationDeclarations,\n\tRelationRegistry,\n\tRelationRow,\n\tRelationSelection,\n\tRelationFilters,\n\tRelationFilterSelection,\n} from './relations'\nimport { createPlanner, type QueryInput, type StoredConstraint } from './querying/planner'\nimport { executeQuery, type ExecutionRequest } from './querying/execution'\nimport {\n\trelationshipExecutor,\n\tassertRelationshipDepth,\n\ttype OutputSelection,\n\ttype RelationDocument,\n} from './querying/relationships'\nimport {\n\tcreateCursorCodec,\n\tcreateEnvironmentCursorCodec,\n\ttype CursorCodecConfig,\n\ttype CursorBinding,\n} from './querying/cursors'\nimport {\n\tcreateManagedSecurity,\n\ttype ManagedSecurityConfig,\n\ttype ManagedQueryContext,\n\ttype ManagedBudgets,\n} from './querying/security'\nimport type { IndexCondition, NativePagination } from './querying/filters'\n\ntype FullMask<S> = {\n\t[K in keyof S]-?: NonNullable<S[K]> extends true ? true : FullMask<NonNullable<S[K]>>\n}\ntype Paths<\n\tD extends RelationDeclarations,\n\tT extends string,\n\tL extends readonly 1[] = [1, 1, 1, 1],\n> = L extends readonly [1, ...infer Rest extends 1[]]\n\t? {\n\t\t\t[K in keyof D[T] & string]:\n\t\t\t\t| (D[T][K]['cardinality'] extends 'many' ? K : never)\n\t\t\t\t| `${K}.${Paths<D, D[T][K]['target'], Rest>}`\n\t\t}[keyof D[T] & string]\n\t: never\ntype PathTarget<\n\tD extends RelationDeclarations,\n\tT extends string,\n\tP extends string,\n> = P extends `${infer Head}.${infer Rest}`\n\t? PathTarget<D, D[T][Head]['target'], Rest>\n\t: D[T][P]['target']\ntype RemainingDepth<P extends string, L extends readonly 1[]> = L extends readonly [\n\t1,\n\t...infer Rest extends 1[],\n]\n\t? P extends `${string}.${infer Tail}`\n\t\t? RemainingDepth<Tail, Rest>\n\t\t: Rest\n\t: []\ntype EngineArgs<\n\tTables extends RelationTables,\n\tD extends RelationDeclarations,\n\tT extends keyof Tables,\n> = NativePagination & {\n\tfilters?: RelationFilters<Tables, D, T, FullMask<RelationFilterSelection<Tables, D, T>>>\n\torder?: 'asc' | 'desc'\n}\n/** Typed declarative chain returned by the engine; named for consumer declaration emission. */\nexport interface TableQuery<\n\tTables extends RelationTables,\n\tD extends RelationDeclarations,\n\tT extends keyof Tables,\n\tS = {},\n\tL extends readonly 1[] = [1, 1, 1, 1],\n> {\n\twhen(value: IndexCondition['value'], index: string): TableQuery<Tables, D, T, S, L>\n\twhere(spec: NonNullable<EngineArgs<Tables, D, T>['filters']>): TableQuery<Tables, D, T, S, L>\n\twith<const Selection extends RelationSelection<Tables, D, T, L>>(\n\t\tselection: Selection & {\n\t\t\t[K in keyof Selection]: K extends keyof RelationSelection<Tables, D, T, L>\n\t\t\t\t? Selection[K]\n\t\t\t\t: never\n\t\t},\n\t): TableQuery<Tables, D, T, Selection, L>\n\trelation<const P extends Paths<D, Extract<T, string>>>(\n\t\tparent: GenericId<Tables[T]['tableName']>,\n\t\tpath: P,\n\t): Omit<\n\t\tTableQuery<\n\t\t\tTables,\n\t\t\tD,\n\t\t\tExtract<PathTarget<D, Extract<T, string>, P>, keyof Tables>,\n\t\t\t{},\n\t\t\tRemainingDepth<P, L>\n\t\t>,\n\t\t'relation'\n\t>\n\tpaginate(args: EngineArgs<Tables, D, T>): Promise<PaginationResult<RelationRow<Tables, D, T, S>>>\n}\nexport interface QueryEngineDeclaration<\n\tSchema extends SchemaDefinition<GenericSchema, boolean>,\n\tTables extends RelationTables,\n\tD extends RelationDeclarations,\n> {\n\tschema: Schema\n\trelations: RelationRegistry<Tables, D>\n}\n/** Advanced server configuration, separate from the normal schema/relations declaration. */\nexport interface QueryEngineOptions<Schema extends SchemaDefinition<GenericSchema, boolean>> {\n\t/** Explicit codecs validate at creation. Otherwise environment keys load at first paginate. */\n\tcursor?: CursorCodecConfig\n\tbudgets?: Partial<ManagedBudgets>\n\tmaxPageSize?: number\n\tpolicyVersion?: string\n\tengineVersion?: string\n\ttrustedAdapter?: ManagedSecurityConfig<DataModelFromSchemaDefinition<Schema>>['trustedAdapter']\n}\n\n/** @deprecated Use QueryEngineDeclaration and optional QueryEngineOptions separately. */\nexport interface QueryEngineConfig<\n\tSchema extends SchemaDefinition<GenericSchema, boolean>,\n\tTables extends RelationTables,\n\tD extends RelationDeclarations,\n>\n\textends QueryEngineDeclaration<Schema, Tables, D>, QueryEngineOptions<Schema> {\n\tcursor: CursorCodecConfig\n}\n\ntype QueryEngine<\n\tSchema extends SchemaDefinition<GenericSchema, boolean>,\n\tTables extends RelationTables,\n\tD extends RelationDeclarations,\n> = {\n\t(ctx: ManagedQueryContext<DataModelFromSchemaDefinition<Schema>>): {\n\t\t[T in keyof Tables]: TableQuery<Tables, D, T>\n\t}\n\ttables: RelationRegistry<Tables, D>['tables']\n}\n\n/** Central facade. Endpoint chains carry declarative constraints and explicit relationships. */\nexport function createQueryEngine<\n\tSchema extends SchemaDefinition<GenericSchema, boolean>,\n\tconst Tables extends RelationTables,\n\tconst D extends RelationDeclarations,\n>(\n\tconfig: QueryEngineDeclaration<Schema, Tables, D>,\n\toptions?: QueryEngineOptions<Schema>,\n): QueryEngine<Schema, Tables, D>\n/** @deprecated Pass advanced fields in the optional second argument. */\nexport function createQueryEngine<\n\tSchema extends SchemaDefinition<GenericSchema, boolean>,\n\tconst Tables extends RelationTables,\n\tconst D extends RelationDeclarations,\n>(\n\tconfig: QueryEngineDeclaration<Schema, Tables, D> &\n\t\tQueryEngineOptions<Schema> & { cursor: CursorCodecConfig },\n): QueryEngine<Schema, Tables, D>\nexport function createQueryEngine<\n\tSchema extends SchemaDefinition<GenericSchema, boolean>,\n\tconst Tables extends RelationTables,\n\tconst D extends RelationDeclarations,\n>(\n\tconfig: QueryEngineDeclaration<Schema, Tables, D> & QueryEngineOptions<Schema>,\n\toptions?: QueryEngineOptions<Schema>,\n) {\n\tconst { schema, relations } = config\n\t// Retain released one-argument calls; a second argument overrides legacy fields.\n\tconst settings = { ...config, ...options }\n\tconst planner = createPlanner(schema, relations)\n\tlet cursorCodec = settings.cursor === undefined ? undefined : createCursorCodec(settings.cursor)\n\tconst maxPageSize = settings.maxPageSize ?? 100\n\tif (!Number.isSafeInteger(maxPageSize) || maxPageSize <= 0 || maxPageSize > 100)\n\t\tthrow new Error('Invalid central page size')\n\tconst engineVersion = settings.engineVersion ?? 'scalar-1'\n\tconst policyVersion = settings.policyVersion ?? '1'\n\t// Bind the full immutable identity through a collision-resistant digest so\n\t// real application registries fit the codec's bounded AAD. Live guards still\n\t// inspect current schemas; this caches only the immutable version identity.\n\tlet registryDigest: string | undefined\n\tconst security = createManagedSecurity<DataModelFromSchemaDefinition<Schema>>({\n\t\ttables: Object.keys(relations.tables),\n\t\tpolicyVersion,\n\t\tbudgets: settings.budgets,\n\t\ttrustedAdapter: settings.trustedAdapter,\n\t})\n\tfunction querying(ctx: ManagedQueryContext<DataModelFromSchemaDefinition<Schema>>) {\n\t\tplanner.assertUnchanged()\n\t\tconst request = security(ctx)\n\t\tfunction tableQuery(\n\t\t\ttable: string,\n\t\t\tconditions: readonly IndexCondition[] = [],\n\t\t\tconstraints: readonly StoredConstraint[] = [],\n\t\t\tselection: OutputSelection = {},\n\t\t\troute?: { table: string; parent: string; path: string[] },\n\t\t) {\n\t\t\treturn Object.freeze({\n\t\t\t\twhen: (value: IndexCondition['value'], index: string) =>\n\t\t\t\t\ttableQuery(table, [...conditions, { value, index }], constraints, selection, route),\n\t\t\t\twhere: (spec: StoredConstraint) =>\n\t\t\t\t\ttableQuery(table, conditions, [...constraints, spec], selection, route),\n\t\t\t\twith: (selected: OutputSelection) =>\n\t\t\t\t\ttableQuery(table, conditions, constraints, selected, route),\n\t\t\t\trelation: (parent: string, declaredPath: string) => {\n\t\t\t\t\tconst path = declaredPath.split('.')\n\t\t\t\t\tif (!path.length || path.length > 4) throw new Error('INVALID_RELATION')\n\t\t\t\t\tlet target = table\n\t\t\t\t\tfor (const name of path) {\n\t\t\t\t\t\tconst edge = planner.metadata.declarations[target]?.[name]\n\t\t\t\t\t\tif (!edge) throw new Error('INVALID_RELATION')\n\t\t\t\t\t\ttarget = edge.target\n\t\t\t\t\t}\n\t\t\t\t\treturn tableQuery(target, conditions, constraints, {}, { table, parent, path })\n\t\t\t\t},\n\t\t\t\tasync paginate(input: QueryInput) {\n\t\t\t\t\t// Resolve once per global engine, before any native query or policy reads.\n\t\t\t\t\tconst codec = (cursorCodec ??= createEnvironmentCursorCodec())\n\t\t\t\t\tplanner.assertUnchanged()\n\t\t\t\t\tconst pageSchema = planner.page(table, selection)\n\t\t\t\t\tassertRelationshipDepth(selection, route?.path.length ?? 0)\n\t\t\t\t\tconst plan = planner.plan(table, input, route ? [] : conditions, constraints)\n\t\t\t\t\tif (plan.args.numItems > maxPageSize) throw new Error('Page size exceeds central ceiling')\n\t\t\t\t\t// Native root limits stay native; lowering those limits cannot raise\n\t\t\t\t\t// the independent shared request meter.\n\t\t\t\t\tplan.args.maximumRowsRead = Math.min(\n\t\t\t\t\t\tplan.args.maximumRowsRead ?? request.budgets.rawCandidates,\n\t\t\t\t\t\trequest.budgets.rawCandidates,\n\t\t\t\t\t)\n\t\t\t\t\tplan.args.maximumBytesRead = Math.min(\n\t\t\t\t\t\tplan.args.maximumBytesRead ?? request.budgets.documentBytes,\n\t\t\t\t\t\trequest.budgets.documentBytes,\n\t\t\t\t\t)\n\t\t\t\t\tregistryDigest ??= Array.from(\n\t\t\t\t\t\tnew Uint8Array(\n\t\t\t\t\t\t\tawait crypto.subtle.digest('SHA-256', new TextEncoder().encode(relations.identity)),\n\t\t\t\t\t\t),\n\t\t\t\t\t\t(byte) => byte.toString(16).padStart(2, '0'),\n\t\t\t\t\t).join('')\n\t\t\t\t\t// The digest await is a boundary too: mutation must be detected\n\t\t\t\t\t// before authenticated cursor validation or native query construction.\n\t\t\t\t\tplanner.assertUnchanged()\n\t\t\t\t\t// SAFETY: selection has passed the registry page validator before binding.\n\t\t\t\t\tconst binding: CursorBinding = {\n\t\t\t\t\t\ttable: route?.table ?? table,\n\t\t\t\t\t\tindex: plan.index?.name ?? 'by_creation_time',\n\t\t\t\t\t\torder: plan.args.order ?? 'asc',\n\t\t\t\t\t\tclientFilters: plan.clientIdentity,\n\t\t\t\t\t\t// Include output selection and the complete immutable scope in trusted identity.\n\t\t\t\t\t\tserverFilters: {\n\t\t\t\t\t\t\tpredicates: plan.serverIdentity,\n\t\t\t\t\t\t\tselection: selection as import('convex/values').Value,\n\t\t\t\t\t\t\tscope: { ...request.scope },\n\t\t\t\t\t\t},\n\t\t\t\t\t\trelationPath: [],\n\t\t\t\t\t\tprincipal: JSON.stringify(request.scope),\n\t\t\t\t\t\ttenant: request.scope.tenant,\n\t\t\t\t\t\tpolicyVersion,\n\t\t\t\t\t\tengineVersion,\n\t\t\t\t\t\tregistryVersion: registryDigest,\n\t\t\t\t\t}\n\t\t\t\t\t// The executor accepts registry-selected native tables, rather than a static DM key.\n\t\t\t\t\tconst executorRequest: unknown = request\n\t\t\t\t\t// SAFETY: only native DM types are erased at this private executor boundary.\n\t\t\t\t\tconst executor = relationshipExecutor(\n\t\t\t\t\t\tschema,\n\t\t\t\t\t\texecutorRequest as ExecutionRequest,\n\t\t\t\t\t\tplanner,\n\t\t\t\t\t\tcodec,\n\t\t\t\t\t\tbinding,\n\t\t\t\t\t)\n\t\t\t\t\tif (route)\n\t\t\t\t\t\treturn executor.continuation(\n\t\t\t\t\t\t\troute.table,\n\t\t\t\t\t\t\troute.parent,\n\t\t\t\t\t\t\troute.path,\n\t\t\t\t\t\t\tselection,\n\t\t\t\t\t\t\tplan.args,\n\t\t\t\t\t\t\tconditions,\n\t\t\t\t\t\t\tconstraints,\n\t\t\t\t\t\t)\n\t\t\t\t\tconst result = await executeQuery(\n\t\t\t\t\t\tschema,\n\t\t\t\t\t\trequest,\n\t\t\t\t\t\ttable,\n\t\t\t\t\t\tplan,\n\t\t\t\t\t\tplanner,\n\t\t\t\t\t\tcodec,\n\t\t\t\t\t\tbinding,\n\t\t\t\t\t\tasync (row, permitted) => {\n\t\t\t\t\t\t\t// SAFETY: metered native stream rows contain the validated system fields.\n\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\t!permitted ||\n\t\t\t\t\t\t\t\t!(await executor.matches(table, row as RelationDocument, plan.residual))\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\treturn null\n\t\t\t\t\t\t\t// SAFETY: the same native row is authorized and matches the declared predicates.\n\t\t\t\t\t\t\treturn executor.output(table, row as RelationDocument, selection, plan.args)\n\t\t\t\t\t\t},\n\t\t\t\t\t)\n\t\t\t\t\tplanner.assertUnchanged()\n\t\t\t\t\treturn pageSchema.parse(result)\n\t\t\t\t},\n\t\t\t})\n\t\t}\n\t\t// SAFETY: each key comes from the exact validated registry; the planner\n\t\t// validates all input and projection while mapped types retain table brands.\n\t\treturn Object.freeze(\n\t\t\tObject.fromEntries(Object.keys(relations.tables).map((table) => [table, tableQuery(table)])),\n\t\t) as { [T in keyof Tables]: TableQuery<Tables, D, T> }\n\t}\n\treturn Object.assign(querying, { tables: relations.tables })\n}\n"],"mappings":"6WAqKA,SAAgBC,EAKf,EACA,EACC,CACD,GAAM,CAAE,SAAQ,aAAcC,EAExBC,EAAW,CAAE,GAAGD,EAAQ,GAAGE,CAAQ,EACnCC,EAAUC,EAAcC,EAAQC,CAAS,EAC3CC,EAAcN,EAAS,SAAW,IAAA,GAAY,IAAA,GAAYO,EAAkBP,EAAS,MAAM,EACzFQ,EAAcR,EAAS,aAAe,IAC5C,GAAI,CAAC,OAAO,cAAcQ,CAAW,GAAKA,GAAe,GAAKA,EAAc,IAC3E,MAAU,MAAM,2BAA2B,EAC5C,IAAMC,EAAgBT,EAAS,eAAiB,WAC1CU,EAAgBV,EAAS,eAAiB,IAI5CW,EACEC,EAAWC,EAA6D,CAC7E,OAAQ,OAAO,KAAKR,EAAU,MAAM,EACpC,gBACA,QAASL,EAAS,QAClB,eAAgBA,EAAS,cAC1B,CAAC,EACD,SAASc,EAAS,EAAiE,CAClFZ,EAAQ,gBAAgB,EACxB,IAAMa,EAAUH,EAASI,CAAG,EAC5B,SAASC,EACR,EACA,EAAwC,CAAC,EACzC,EAA2C,CAAC,EAC5C,EAA6B,CAAC,EAC9B,EACC,CACD,OAAO,OAAO,OAAO,CACpB,MAAO,EAAgC,IACtCA,EAAWC,EAAO,CAAC,GAAGC,EAAY,CAAE,QAAO,OAAM,CAAC,EAAGC,EAAaC,EAAWC,CAAK,EACnF,MAAQ,GACPL,EAAWC,EAAOC,EAAY,CAAC,GAAGC,EAAaG,CAAI,EAAGF,EAAWC,CAAK,EACvE,KAAO,GACNL,EAAWC,EAAOC,EAAYC,EAAaI,EAAUF,CAAK,EAC3D,UAAW,EAAgB,IAAyB,CACnD,IAAMG,EAAOC,EAAa,MAAM,GAAG,EACnC,GAAI,CAACD,EAAK,QAAUA,EAAK,OAAS,EAAG,MAAU,MAAM,kBAAkB,EACvE,IAAIE,EAAST,EACb,IAAK,IAAMU,KAAQH,EAAM,CACxB,IAAMI,EAAO3B,EAAQ,SAAS,aAAayB,EAAO,GAAGC,GACrD,GAAI,CAACC,EAAM,MAAU,MAAM,kBAAkB,EAC7C,EAASA,EAAK,MACf,CACA,OAAOZ,EAAWU,EAAQR,EAAYC,EAAa,CAAC,EAAG,CAAE,QAAO,SAAQ,MAAK,CAAC,CAC/E,EACA,MAAM,SAAS,EAAmB,CAEjC,IAAMU,EAAS,IAAgBC,EAA6B,EAC5D7B,EAAQ,gBAAgB,EACxB,IAAM8B,EAAa9B,EAAQ,KAAKgB,EAAOG,CAAS,EAChDY,EAAwBZ,EAAWC,GAAO,KAAK,QAAU,CAAC,EAC1D,IAAMY,EAAOhC,EAAQ,KAAKgB,EAAOiB,EAAOb,EAAQ,CAAC,EAAIH,EAAYC,CAAW,EAC5E,GAAIc,EAAK,KAAK,SAAW1B,EAAa,MAAU,MAAM,mCAAmC,EAGzF,EAAK,KAAK,gBAAkB,KAAK,IAChC0B,EAAK,KAAK,iBAAmBnB,EAAQ,QAAQ,cAC7CA,EAAQ,QAAQ,aACjB,EACA,EAAK,KAAK,iBAAmB,KAAK,IACjCmB,EAAK,KAAK,kBAAoBnB,EAAQ,QAAQ,cAC9CA,EAAQ,QAAQ,aACjB,EACA,IAAmB,MAAM,KACxB,IAAI,WACH,MAAM,OAAO,OAAO,OAAO,UAAW,IAAI,YAAY,CAAC,CAAC,OAAOV,EAAU,QAAQ,CAAC,CACnF,EACC,GAAS+B,EAAK,SAAS,EAAE,CAAC,CAAC,SAAS,EAAG,GAAG,CAC5C,CAAC,CAAC,KAAK,EAAE,EAGTlC,EAAQ,gBAAgB,EAExB,IAAMmC,EAAyB,CAC9B,MAAOf,GAAO,OAASJ,EACvB,MAAOgB,EAAK,OAAO,MAAQ,mBAC3B,MAAOA,EAAK,KAAK,OAAS,MAC1B,cAAeA,EAAK,eAEpB,cAAe,CACd,WAAYA,EAAK,eACN,YACX,MAAO,CAAE,GAAGnB,EAAQ,KAAM,CAC3B,EACA,aAAc,CAAC,EACf,UAAW,KAAK,UAAUA,EAAQ,KAAK,EACvC,OAAQA,EAAQ,MAAM,OACtB,gBACA,gBACA,gBAAiBJ,CAClB,EAIM2B,EAAWC,EAChBnC,EACAP,EACAK,EACA4B,EACAO,CACD,EACA,GAAIf,EACH,OAAOgB,EAAS,aACfhB,EAAM,MACNA,EAAM,OACNA,EAAM,KACND,EACAa,EAAK,KACLf,EACAC,CACD,EACD,IAAMoB,EAAS,MAAMC,EACpBrC,EACAW,EACAG,EACAgB,EACAhC,EACA4B,EACAO,EACA,MAAO,EAAK,IAGV,CAACK,GACD,CAAE,MAAMJ,EAAS,QAAQpB,EAAOyB,EAAyBT,EAAK,QAAQ,EAE/D,KAEDI,EAAS,OAAOpB,EAAOyB,EAAyBtB,EAAWa,EAAK,IAAI,CAE7E,EAEA,OADAhC,EAAQ,gBAAgB,EACjB8B,EAAW,MAAMQ,CAAM,CAC/B,CACD,CAAC,CACF,CAGA,OAAO,OAAO,OACb,OAAO,YAAY,OAAO,KAAKnC,EAAU,MAAM,CAAC,CAAC,IAAK,GAAU,CAACa,EAAOD,EAAWC,CAAK,CAAC,CAAC,CAAC,CAC5F,CACD,CACA,OAAO,OAAO,OAAOJ,EAAU,CAAE,OAAQT,EAAU,MAAO,CAAC,CAC5D"}
1
+ {"version":3,"file":"querying.mjs","names":["executorRequest","createQueryEngine","config","settings","options","planner","createPlanner","schema","relations","cursorCodec","createCursorCodec","maxPageSize","engineVersion","policyVersion","registryDigest","security","createManagedSecurity","querying","request","ctx","tableQuery","table","conditions","constraints","selection","route","spec","selected","path","declaredPath","target","name","edge","codec","createEnvironmentCursorCodec","pageSchema","assertRelationshipDepth","plan","input","byte","binding","executor","relationshipExecutor","result","executeQuery","permitted","row"],"sources":["../src/querying.ts"],"sourcesContent":["import type {\n\tGenericSchema,\n\tSchemaDefinition,\n\tDataModelFromSchemaDefinition,\n\tPaginationResult,\n} from 'convex/server'\nimport type { GenericId } from 'convex/values'\nimport type {\n\tRelationTables,\n\tRelationDeclarations,\n\tRelationRegistry,\n\tRelationQueryRow,\n\tRelationSelection,\n\tRelationFilters,\n\tRelationFilterSelection,\n} from './relations'\nimport { createPlanner, type QueryInput, type StoredConstraint } from './querying/planner'\nimport { executeQuery, type ExecutionRequest } from './querying/execution'\nimport {\n\trelationshipExecutor,\n\tassertRelationshipDepth,\n\ttype OutputSelection,\n\ttype RelationDocument,\n} from './querying/relationships'\nimport {\n\tcreateCursorCodec,\n\tcreateEnvironmentCursorCodec,\n\ttype CursorCodecConfig,\n\ttype CursorBinding,\n} from './querying/cursors'\nimport {\n\tcreateManagedSecurity,\n\ttype ManagedSecurityConfig,\n\ttype ManagedQueryContext,\n\ttype ManagedBudgets,\n} from './querying/security'\nimport type { IndexCondition, NativePagination } from './querying/filters'\n\ntype FullMask<S> = {\n\t[K in keyof S]-?: NonNullable<S[K]> extends true\n\t\t? true\n\t\t: FullMask<Exclude<NonNullable<S[K]>, true>>\n}\ntype Paths<\n\tD extends RelationDeclarations,\n\tT extends string,\n\tL extends readonly 1[] = [1, 1, 1, 1],\n> = L extends readonly [1, ...infer Rest extends 1[]]\n\t? {\n\t\t\t[K in keyof D[T] & string]:\n\t\t\t\t| (D[T][K]['cardinality'] extends 'many' ? K : never)\n\t\t\t\t| `${K}.${Paths<D, D[T][K]['target'], Rest>}`\n\t\t}[keyof D[T] & string]\n\t: never\ntype PathTarget<\n\tD extends RelationDeclarations,\n\tT extends string,\n\tP extends string,\n> = P extends `${infer Head}.${infer Rest}`\n\t? PathTarget<D, D[T][Head]['target'], Rest>\n\t: D[T][P]['target']\ntype PathScope<\n\tD extends RelationDeclarations,\n\tT extends string,\n\tP extends string,\n> = P extends `${infer Head}.${infer Rest}`\n\t? PathScope<D, D[T][Head]['target'], Rest>\n\t: Extract<NonNullable<D[T][P]['targetGuard']>['tag'], string>\ntype RemainingDepth<P extends string, L extends readonly 1[]> = L extends readonly [\n\t1,\n\t...infer Rest extends 1[],\n]\n\t? P extends `${string}.${infer Tail}`\n\t\t? RemainingDepth<Tail, Rest>\n\t\t: Rest\n\t: []\ntype EngineArgs<\n\tTables extends RelationTables,\n\tD extends RelationDeclarations,\n\tT extends keyof Tables,\n> = NativePagination & {\n\tfilters?: RelationFilters<Tables, D, T, FullMask<RelationFilterSelection<Tables, D, T>>>\n\torder?: 'asc' | 'desc'\n}\n/** Typed declarative chain returned by the engine; named for consumer declaration emission. */\nexport interface TableQuery<\n\tTables extends RelationTables,\n\tD extends RelationDeclarations,\n\tT extends keyof Tables,\n\tS = {},\n\tL extends readonly 1[] = [1, 1, 1, 1],\n\tScope extends string = never,\n> {\n\twhen(value: IndexCondition['value'], index: string): TableQuery<Tables, D, T, S, L, Scope>\n\twhere(\n\t\tspec: NonNullable<EngineArgs<Tables, D, T>['filters']>,\n\t): TableQuery<Tables, D, T, S, L, Scope>\n\twith<const Selection extends RelationSelection<Tables, D, T, L>>(\n\t\tselection: Selection & {\n\t\t\t[K in keyof Selection]: K extends keyof RelationSelection<Tables, D, T, L>\n\t\t\t\t? Selection[K]\n\t\t\t\t: never\n\t\t},\n\t): TableQuery<Tables, D, T, Selection, L, Scope>\n\trelation<const P extends Paths<D, Extract<T, string>>>(\n\t\tparent: GenericId<Tables[T]['tableName']>,\n\t\tpath: P,\n\t): Omit<\n\t\tTableQuery<\n\t\t\tTables,\n\t\t\tD,\n\t\t\tExtract<PathTarget<D, Extract<T, string>, P>, keyof Tables>,\n\t\t\t{},\n\t\t\tRemainingDepth<P, L>,\n\t\t\tPathScope<D, Extract<T, string>, P>\n\t\t>,\n\t\t'relation'\n\t>\n\tpaginate(\n\t\targs: EngineArgs<Tables, D, T>,\n\t): Promise<PaginationResult<RelationQueryRow<Tables, D, T, S, Scope>>>\n}\nexport interface QueryEngineDeclaration<\n\tSchema extends SchemaDefinition<GenericSchema, boolean>,\n\tTables extends RelationTables,\n\tD extends RelationDeclarations,\n> {\n\tschema: Schema\n\trelations: RelationRegistry<Tables, D>\n}\n/** Advanced server configuration, separate from the normal schema/relations declaration. */\nexport interface QueryEngineOptions<Schema extends SchemaDefinition<GenericSchema, boolean>> {\n\t/** Explicit codecs validate at creation. Otherwise environment keys load at first paginate. */\n\tcursor?: CursorCodecConfig\n\tbudgets?: Partial<ManagedBudgets>\n\tmaxPageSize?: number\n\tpolicyVersion?: string\n\tengineVersion?: string\n\ttrustedAdapter?: ManagedSecurityConfig<DataModelFromSchemaDefinition<Schema>>['trustedAdapter']\n}\n\n/** @deprecated Use QueryEngineDeclaration and optional QueryEngineOptions separately. */\nexport interface QueryEngineConfig<\n\tSchema extends SchemaDefinition<GenericSchema, boolean>,\n\tTables extends RelationTables,\n\tD extends RelationDeclarations,\n>\n\textends QueryEngineDeclaration<Schema, Tables, D>, QueryEngineOptions<Schema> {\n\tcursor: CursorCodecConfig\n}\n\ntype QueryEngine<\n\tSchema extends SchemaDefinition<GenericSchema, boolean>,\n\tTables extends RelationTables,\n\tD extends RelationDeclarations,\n> = {\n\t(ctx: ManagedQueryContext<DataModelFromSchemaDefinition<Schema>>): {\n\t\t[T in keyof Tables]: TableQuery<Tables, D, T>\n\t}\n\ttables: RelationRegistry<Tables, D>['tables']\n}\n\n/** Central facade. Endpoint chains carry declarative constraints and explicit relationships. */\nexport function createQueryEngine<\n\tSchema extends SchemaDefinition<GenericSchema, boolean>,\n\tconst Tables extends RelationTables,\n\tconst D extends RelationDeclarations,\n>(\n\tconfig: QueryEngineDeclaration<Schema, Tables, D>,\n\toptions?: QueryEngineOptions<Schema>,\n): QueryEngine<Schema, Tables, D>\n/** @deprecated Pass advanced fields in the optional second argument. */\nexport function createQueryEngine<\n\tSchema extends SchemaDefinition<GenericSchema, boolean>,\n\tconst Tables extends RelationTables,\n\tconst D extends RelationDeclarations,\n>(\n\tconfig: QueryEngineDeclaration<Schema, Tables, D> &\n\t\tQueryEngineOptions<Schema> & { cursor: CursorCodecConfig },\n): QueryEngine<Schema, Tables, D>\nexport function createQueryEngine<\n\tSchema extends SchemaDefinition<GenericSchema, boolean>,\n\tconst Tables extends RelationTables,\n\tconst D extends RelationDeclarations,\n>(\n\tconfig: QueryEngineDeclaration<Schema, Tables, D> & QueryEngineOptions<Schema>,\n\toptions?: QueryEngineOptions<Schema>,\n) {\n\tconst { schema, relations } = config\n\t// Retain released one-argument calls; a second argument overrides legacy fields.\n\tconst settings = { ...config, ...options }\n\tconst planner = createPlanner(schema, relations)\n\tlet cursorCodec = settings.cursor === undefined ? undefined : createCursorCodec(settings.cursor)\n\tconst maxPageSize = settings.maxPageSize ?? 100\n\tif (!Number.isSafeInteger(maxPageSize) || maxPageSize <= 0 || maxPageSize > 100)\n\t\tthrow new Error('Invalid central page size')\n\tconst engineVersion = settings.engineVersion ?? 'scalar-1'\n\tconst policyVersion = settings.policyVersion ?? '1'\n\t// Bind the full immutable identity through a collision-resistant digest so\n\t// real application registries fit the codec's bounded AAD. Live guards still\n\t// inspect current schemas; this caches only the immutable version identity.\n\tlet registryDigest: string | undefined\n\tconst security = createManagedSecurity<DataModelFromSchemaDefinition<Schema>>({\n\t\ttables: Object.keys(relations.tables),\n\t\tpolicyVersion,\n\t\tbudgets: settings.budgets,\n\t\ttrustedAdapter: settings.trustedAdapter,\n\t})\n\tfunction querying(ctx: ManagedQueryContext<DataModelFromSchemaDefinition<Schema>>) {\n\t\tplanner.assertUnchanged()\n\t\tconst request = security(ctx)\n\t\tfunction tableQuery(\n\t\t\ttable: string,\n\t\t\tconditions: readonly IndexCondition[] = [],\n\t\t\tconstraints: readonly StoredConstraint[] = [],\n\t\t\tselection: OutputSelection = {},\n\t\t\troute?: { table: string; parent: string; path: string[] },\n\t\t) {\n\t\t\treturn Object.freeze({\n\t\t\t\twhen: (value: IndexCondition['value'], index: string) =>\n\t\t\t\t\ttableQuery(table, [...conditions, { value, index }], constraints, selection, route),\n\t\t\t\twhere: (spec: StoredConstraint) =>\n\t\t\t\t\ttableQuery(table, conditions, [...constraints, spec], selection, route),\n\t\t\t\twith: (selected: OutputSelection) =>\n\t\t\t\t\ttableQuery(table, conditions, constraints, selected, route),\n\t\t\t\trelation: (parent: string, declaredPath: string) => {\n\t\t\t\t\tconst path = declaredPath.split('.')\n\t\t\t\t\tif (!path.length || path.length > 4) throw new Error('INVALID_RELATION')\n\t\t\t\t\tlet target = table\n\t\t\t\t\tfor (const name of path) {\n\t\t\t\t\t\tconst edge = planner.metadata.declarations[target]?.[name]\n\t\t\t\t\t\tif (!edge) throw new Error('INVALID_RELATION')\n\t\t\t\t\t\ttarget = edge.target\n\t\t\t\t\t}\n\t\t\t\t\treturn tableQuery(target, conditions, constraints, {}, { table, parent, path })\n\t\t\t\t},\n\t\t\t\tasync paginate(input: QueryInput) {\n\t\t\t\t\t// Resolve once per global engine, before any native query or policy reads.\n\t\t\t\t\tconst codec = (cursorCodec ??= createEnvironmentCursorCodec())\n\t\t\t\t\tplanner.assertUnchanged()\n\t\t\t\t\tconst pageSchema = planner.page(table, selection)\n\t\t\t\t\tassertRelationshipDepth(selection, route?.path.length ?? 0)\n\t\t\t\t\tconst plan = planner.plan(table, input, route ? [] : conditions, constraints)\n\t\t\t\t\tif (plan.args.numItems > maxPageSize) throw new Error('Page size exceeds central ceiling')\n\t\t\t\t\t// Native root limits stay native; lowering those limits cannot raise\n\t\t\t\t\t// the independent shared request meter.\n\t\t\t\t\tplan.args.maximumRowsRead = Math.min(\n\t\t\t\t\t\tplan.args.maximumRowsRead ?? request.budgets.rawCandidates,\n\t\t\t\t\t\trequest.budgets.rawCandidates,\n\t\t\t\t\t)\n\t\t\t\t\tplan.args.maximumBytesRead = Math.min(\n\t\t\t\t\t\tplan.args.maximumBytesRead ?? request.budgets.documentBytes,\n\t\t\t\t\t\trequest.budgets.documentBytes,\n\t\t\t\t\t)\n\t\t\t\t\tregistryDigest ??= Array.from(\n\t\t\t\t\t\tnew Uint8Array(\n\t\t\t\t\t\t\tawait crypto.subtle.digest('SHA-256', new TextEncoder().encode(relations.identity)),\n\t\t\t\t\t\t),\n\t\t\t\t\t\t(byte) => byte.toString(16).padStart(2, '0'),\n\t\t\t\t\t).join('')\n\t\t\t\t\t// The digest await is a boundary too: mutation must be detected\n\t\t\t\t\t// before authenticated cursor validation or native query construction.\n\t\t\t\t\tplanner.assertUnchanged()\n\t\t\t\t\t// SAFETY: selection has passed the registry page validator before binding.\n\t\t\t\t\tconst binding: CursorBinding = {\n\t\t\t\t\t\ttable: route?.table ?? table,\n\t\t\t\t\t\tindex: plan.index?.name ?? 'by_creation_time',\n\t\t\t\t\t\torder: plan.args.order ?? 'asc',\n\t\t\t\t\t\tclientFilters: plan.clientIdentity,\n\t\t\t\t\t\t// Include output selection and the complete immutable scope in trusted identity.\n\t\t\t\t\t\tserverFilters: {\n\t\t\t\t\t\t\tpredicates: plan.serverIdentity,\n\t\t\t\t\t\t\tselection: selection as import('convex/values').Value,\n\t\t\t\t\t\t\tscope: { ...request.scope },\n\t\t\t\t\t\t},\n\t\t\t\t\t\trelationPath: [],\n\t\t\t\t\t\tprincipal: JSON.stringify(request.scope),\n\t\t\t\t\t\ttenant: request.scope.tenant,\n\t\t\t\t\t\tpolicyVersion,\n\t\t\t\t\t\tengineVersion,\n\t\t\t\t\t\tregistryVersion: registryDigest,\n\t\t\t\t\t}\n\t\t\t\t\t// The executor accepts registry-selected native tables, rather than a static DM key.\n\t\t\t\t\tconst executorRequest: unknown = request\n\t\t\t\t\t// SAFETY: only native DM types are erased at this private executor boundary.\n\t\t\t\t\tconst executor = relationshipExecutor(\n\t\t\t\t\t\tschema,\n\t\t\t\t\t\texecutorRequest as ExecutionRequest,\n\t\t\t\t\t\tplanner,\n\t\t\t\t\t\tcodec,\n\t\t\t\t\t\tbinding,\n\t\t\t\t\t)\n\t\t\t\t\tif (route)\n\t\t\t\t\t\treturn executor.continuation(\n\t\t\t\t\t\t\troute.table,\n\t\t\t\t\t\t\troute.parent,\n\t\t\t\t\t\t\troute.path,\n\t\t\t\t\t\t\tselection,\n\t\t\t\t\t\t\tplan.args,\n\t\t\t\t\t\t\tconditions,\n\t\t\t\t\t\t\tconstraints,\n\t\t\t\t\t\t)\n\t\t\t\t\tconst result = await executeQuery(\n\t\t\t\t\t\tschema,\n\t\t\t\t\t\trequest,\n\t\t\t\t\t\ttable,\n\t\t\t\t\t\tplan,\n\t\t\t\t\t\tplanner,\n\t\t\t\t\t\tcodec,\n\t\t\t\t\t\tbinding,\n\t\t\t\t\t\tasync (row, permitted) => {\n\t\t\t\t\t\t\t// SAFETY: metered native stream rows contain the validated system fields.\n\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\t!permitted ||\n\t\t\t\t\t\t\t\t!(await executor.matches(table, row as RelationDocument, plan.residual))\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\treturn null\n\t\t\t\t\t\t\t// SAFETY: the same native row is authorized and matches the declared predicates.\n\t\t\t\t\t\t\treturn executor.output(table, row as RelationDocument, selection, plan.args)\n\t\t\t\t\t\t},\n\t\t\t\t\t)\n\t\t\t\t\tplanner.assertUnchanged()\n\t\t\t\t\treturn pageSchema.parse(result)\n\t\t\t\t},\n\t\t\t})\n\t\t}\n\t\t// SAFETY: each key comes from the exact validated registry; the planner\n\t\t// validates all input and projection while mapped types retain table brands.\n\t\treturn Object.freeze(\n\t\t\tObject.fromEntries(Object.keys(relations.tables).map((table) => [table, tableQuery(table)])),\n\t\t) as { [T in keyof Tables]: TableQuery<Tables, D, T> }\n\t}\n\treturn Object.assign(querying, { tables: relations.tables })\n}\n"],"mappings":"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"}
@@ -1,2 +1,2 @@
1
- import { FieldReference, RelationBuilder, RelationDeclarations, RelationEdge, RelationFilterSelection, RelationFilters, RelationRegistry, RelationRegistryIdentity, RelationRow, RelationSelection, RelationTable, RelationTableHelpers, RelationTables, ThroughReference, defineRelations } from "./relations.mjs";
2
- export { type FieldReference, type RelationBuilder, type RelationDeclarations, type RelationEdge, type RelationFilterSelection, type RelationFilters, type RelationRegistry, type RelationRegistryIdentity, type RelationRow, type RelationSelection, type RelationTable, type RelationTableHelpers, type RelationTables, type ThroughReference, defineRelations };
1
+ import { BranchBuilder, FieldReference, RelationBuilder, RelationDeclarations, RelationEdge, RelationFilterSelection, RelationFilters, RelationRegistry, RelationRegistryIdentity, RelationRow, RelationSelection, RelationTable, RelationTableHelpers, RelationTables, ThroughReference, defineRelations } from "./relations.mjs";
2
+ export { type BranchBuilder, type FieldReference, type RelationBuilder, type RelationDeclarations, type RelationEdge, type RelationFilterSelection, type RelationFilters, type RelationRegistry, type RelationRegistryIdentity, type RelationRow, type RelationSelection, type RelationTable, type RelationTableHelpers, type RelationTables, type ThroughReference, defineRelations };
@@ -1,14 +1,14 @@
1
- import { PaginationOptionsSchema, ScalarPredicate, ScalarSelection } from "./querying/filters.mjs";
1
+ import { FieldSchemas, PaginationOptionsSchema, ScalarPredicate, ScalarSelection } from "./querying/filters.mjs";
2
2
  import { ConvexValidatorFromZod } from "convex-helpers/server/zod4";
3
3
  import { PaginationResult, TableDefinition } from "convex/server";
4
4
  import { z } from "zod";
5
- import { GenericId, ValidatorJSON } from "convex/values";
5
+ import { GenericId, GenericValidator, ValidatorJSON } from "convex/values";
6
6
  //#region src/relations.d.ts
7
- /** Object table boundaries only. Runtime metadata comes from native validators/export. */
7
+ /** Generated object or discriminated-union boundaries. */
8
8
  export interface RelationTable {
9
9
  tableName: string;
10
- schema: z.ZodObject;
11
- publicDto: z.ZodObject;
10
+ schema: z.ZodObject | z.ZodDiscriminatedUnion<any, string>;
11
+ publicDto: z.ZodObject | z.ZodDiscriminatedUnion<any, string>;
12
12
  table: TableDefinition;
13
13
  dto(includeId: true): z.ZodType;
14
14
  }
@@ -17,29 +17,54 @@ export type RelationTables = Record<string, RelationTable>;
17
17
  export interface SelectionMask {
18
18
  [key: string]: true | SelectionMask;
19
19
  }
20
- type Fields<T extends RelationTable> = T['schema']['shape'];
20
+ type DocumentFields<S> = S extends z.ZodObject<infer F> ? F : S extends z.ZodDiscriminatedUnion<infer O, string> ? O[number] extends (infer B) ? B extends z.ZodObject<infer F> ? F : never : never : never;
21
+ type AllKeys<F> = F extends unknown ? keyof F : never;
22
+ type FieldAt<F, K extends PropertyKey> = F extends unknown ? K extends keyof F ? F[K] : never : never;
23
+ type NativeDomain<V> = V extends {
24
+ kind: 'union';
25
+ members: infer M extends GenericValidator[];
26
+ } ? NativeDomain<M[number]> : V extends {
27
+ kind: 'null';
28
+ } ? never : V extends {
29
+ kind: infer K;
30
+ type: infer Value;
31
+ } ? readonly [K, Exclude<Value, undefined>] : never;
32
+ type DomainAt<F, K extends PropertyKey> = F extends unknown ? K extends keyof F ? F[K] extends z.ZodType ? NativeDomain<ConvexValidatorFromZod<F[K], 'required'>> : never : never : never;
33
+ type CompatibleBranches<F, K extends keyof F, Domain = DomainAt<F, K>> = F extends unknown ? Same<DomainAt<F, K>, Domain> : never;
34
+ type Discriminator<T extends RelationTable> = T['schema'] extends z.ZodDiscriminatedUnion<any, string> ? T['schema']['_zod']['def']['discriminator'] : never;
35
+ type Fields<T extends RelationTable, F = DocumentFields<T['schema']>> = string extends T['tableName'] ? FieldSchemas : T['schema'] extends z.ZodObject<infer ObjectFields> ? { [K in keyof ObjectFields]: Extract<ObjectFields[K], z.ZodType>; } : { [K in Extract<keyof F, string> as K extends Discriminator<T> ? K : false extends CompatibleBranches<F, K> ? never : K]: Extract<FieldAt<F, K>, z.ZodType>; };
36
+ type BranchFields<T extends RelationTable, Tag extends string> = DocumentFields<T['schema']> extends (infer F) ? F extends Record<Discriminator<T>, z.ZodType> ? Tag extends z.output<F[Discriminator<T>]> ? F : never : never : never;
37
+ type Tags<T extends RelationTable> = T['schema'] extends z.ZodDiscriminatedUnion<any, string> ? Extract<z.output<T['schema']>[Discriminator<T>], string> : never;
21
38
  type Native<T extends RelationTable, K extends keyof Fields<T>> = ConvexValidatorFromZod<Fields<T>[K], 'required'>['type'];
22
39
  declare const fieldBrand: unique symbol;
23
40
  declare const edgeBrand: unique symbol;
24
41
  type Comparable<Value> = Exclude<Value, null | undefined>;
25
42
  type Same<A, B> = [Comparable<A> | Comparable<B>] extends [never] ? false : [Comparable<A>] extends [Comparable<B>] ? [Comparable<B>] extends [Comparable<A>] ? true : false : false;
26
- export interface FieldReference<Table extends string, Field extends string, Value> {
43
+ export interface FieldReference<Table extends string, Field extends string, Value, Scope extends string = never> {
44
+ readonly guard?: RelationGuard<Scope>;
27
45
  readonly [fieldBrand]: Value;
28
46
  readonly table: Table;
29
47
  readonly field: Field;
30
- through<J extends AnyField>(junction: J & (Same<Value, J[typeof fieldBrand]> extends true ? {} : never)): ThroughReference<Table, Field, Value, J>;
48
+ through<J extends AnyField>(junction: J & (Same<Value, J[typeof fieldBrand]> extends true ? {} : never)): ThroughReference<Table, Field, Value, J, Scope>;
31
49
  }
32
- type AnyField = FieldReference<string, string, any>;
33
- export interface ThroughReference<Table extends string, Field extends string, Value, Junction extends AnyField> {
34
- readonly base: FieldReference<Table, Field, Value>;
50
+ export interface RelationGuard<Tag extends string = string> {
51
+ readonly discriminator: string;
52
+ readonly tag: Tag;
53
+ }
54
+ type AnyField = FieldReference<string, string, any, any>;
55
+ export interface ThroughReference<Table extends string, Field extends string, Value, Junction extends AnyField, Scope extends string = never> {
56
+ readonly base: FieldReference<Table, Field, Value, Scope>;
35
57
  readonly junction: Junction;
36
58
  }
37
- type AnyThrough = ThroughReference<string, string, any, AnyField>;
59
+ type AnyThrough = ThroughReference<string, string, any, AnyField, any>;
38
60
  type Leg = AnyField | AnyThrough;
39
61
  type Base<L extends Leg> = L extends AnyThrough ? L['base'] : L;
40
62
  type JunctionTable<L extends Leg> = L extends AnyThrough ? L['junction']['table'] : never;
41
63
  type CompatibleLegs<F extends Leg, T extends Leg> = F extends AnyThrough ? T extends AnyThrough ? Same<JunctionTable<F>, JunctionTable<T>> extends true ? {} : never : never : T extends AnyThrough ? never : Same<Base<F>[typeof fieldBrand], Base<T>[typeof fieldBrand]> extends true ? {} : never;
42
- export interface RelationEdge<Source extends string, Target extends string, Cardinality extends 'one' | 'many'> {
64
+ export interface RelationEdge<Source extends string, Target extends string, Cardinality extends 'one' | 'many', SourceScope extends string = never, TargetScope extends string = never> {
65
+ readonly sourceGuard?: RelationGuard<SourceScope>;
66
+ readonly targetGuard?: RelationGuard<TargetScope>;
67
+ readonly junctionGuard?: RelationGuard;
43
68
  readonly [edgeBrand]: true;
44
69
  readonly source: Source;
45
70
  readonly target: Target;
@@ -47,43 +72,62 @@ export interface RelationEdge<Source extends string, Target extends string, Card
47
72
  readonly from: Leg;
48
73
  readonly to: Leg;
49
74
  }
50
- type AnyEdge = RelationEdge<string, string, 'one' | 'many'>;
75
+ type AnyEdge = RelationEdge<string, string, 'one' | 'many', any, any>;
51
76
  type FieldReferences<Tables extends RelationTables> = { [T in keyof Tables]: { [K in Extract<keyof Fields<Tables[T]>, string>]: FieldReference<Extract<T, string>, K, Native<Tables[T], K>>; }; };
77
+ export type BranchBuilder<Tables extends RelationTables> = <const T extends keyof Tables & string, const Tag extends Tags<Tables[T]>>(table: T, tag: Tag) => { [K in keyof BranchFields<Tables[T], Tag> & string]: FieldReference<T, K, ConvexValidatorFromZod<Extract<BranchFields<Tables[T], Tag>[K], z.ZodType>, 'required'>['type'], Tag>; };
78
+ type Scope<L extends Leg> = NonNullable<Base<L>['guard']>['tag'];
52
79
  type AllReferences<Tables extends RelationTables> = { [T in keyof Tables]: FieldReferences<Tables>[T][Extract<keyof FieldReferences<Tables>[T], string>]; }[keyof Tables];
53
- type Builders<Tables extends RelationTables, C extends 'one' | 'many'> = { [T in keyof Tables]: <F extends AllReferences<Tables> | AnyThrough, To extends FieldReferences<Tables>[T][Extract<keyof FieldReferences<Tables>[T], string>] | AnyThrough>(spec: {
80
+ type Builders<Tables extends RelationTables, C extends 'one' | 'many'> = { [T in keyof Tables]: <F extends AllReferences<Tables> | AnyField | AnyThrough, To extends FieldReferences<Tables>[T][Extract<keyof FieldReferences<Tables>[T], string>] | AnyField | AnyThrough>(spec: {
54
81
  from: F;
55
82
  to: To;
56
- } & CompatibleLegs<F, To> & (Base<To>['table'] extends T ? {} : never)) => RelationEdge<Base<F>['table'], Extract<T, string>, C>; };
83
+ } & CompatibleLegs<F, To> & (Base<To>['table'] extends T ? {} : never)) => RelationEdge<Base<F>['table'], Extract<T, string>, C, Scope<F>, Scope<To>>; };
57
84
  export type RelationBuilder<Tables extends RelationTables> = FieldReferences<Tables> & {
58
85
  one: Builders<Tables, 'one'>;
59
86
  many: Builders<Tables, 'many'>;
60
87
  };
61
88
  export type RelationDeclarations = Record<string, Record<string, AnyEdge>>;
62
- type ExactDeclarations<Tables extends RelationTables, D extends RelationDeclarations> = { [T in keyof D]: T extends keyof Tables ? { [K in keyof D[T]]: K extends keyof Fields<Tables[T]> | 'and' | 'or' | 'not' | 'fields' | 'then' | '__proto__' | 'constructor' | 'prototype' ? never : D[T][K]['source'] extends T ? D[T][K] : never; } : never; };
89
+ type ExactDeclarations<Tables extends RelationTables, D extends RelationDeclarations> = { [T in keyof D]: T extends keyof Tables ? { [K in keyof D[T]]: K extends AllKeys<DocumentFields<Tables[T]['schema']>> | 'and' | 'or' | 'not' | 'fields' | 'then' | ([Tags<Tables[T]>] extends [never] ? never : 'variant' | 'variants') | '__proto__' | 'constructor' | 'prototype' ? never : D[T][K]['source'] extends T ? D[T][K] : never; } : never; };
63
90
  type Depth = readonly [1, 1, 1, 1];
64
91
  type Tail<D extends readonly 1[]> = D extends readonly [1, ...infer R extends 1[]] ? R : [];
65
92
  type Edges<D, T> = T extends keyof D ? D[T] : {};
66
93
  type Target<E> = E extends AnyEdge ? E['target'] : never;
67
94
  export type RelationSelection<Tables extends RelationTables, D extends RelationDeclarations, T extends keyof Tables, Level extends readonly 1[] = Depth> = Level extends readonly [] ? Record<string, never> : { [K in keyof Edges<D, T>]?: true | RelationSelection<Tables, D, Extract<Target<Edges<D, T>[K]>, keyof Tables>, Tail<Level>>; };
68
- export type RelationFilterSelection<Tables extends RelationTables, D extends RelationDeclarations, T extends keyof Tables, Level extends readonly 1[] = Depth> = ScalarSelection<Fields<Tables[T]>> & (Level extends readonly [] ? {} : { [K in keyof Edges<D, T>]?: RelationFilterSelection<Tables, D, Extract<Target<Edges<D, T>[K]>, keyof Tables>, Tail<Level>>; });
95
+ type BranchTables<Tables extends RelationTables, T extends keyof Tables, Tag extends string> = { [K in keyof Tables]: K extends T ? Omit<Tables[K], 'schema'> & {
96
+ schema: z.ZodObject<BranchFields<Tables[T], Tag>>;
97
+ } : Tables[K]; };
98
+ type VariantSelections<Tables extends RelationTables, D extends RelationDeclarations, T extends keyof Tables, Level extends readonly 1[]> = { [Tag in Tags<Tables[T]>]?: RelationFilterSelection<BranchTables<Tables, T, Tag>, D, T, Level>; };
99
+ export type RelationFilterSelection<Tables extends RelationTables, D extends RelationDeclarations, T extends keyof Tables, Level extends readonly 1[] = Depth> = ([Tags<Tables[T]>] extends [never] ? ScalarSelection<Fields<Tables[T]>> : Omit<ScalarSelection<Fields<Tables[T]>>, 'variants'> & {
100
+ variants?: ('variants' extends keyof ScalarSelection<Fields<Tables[T]>> ? true : never) | VariantSelections<Tables, D, T, Level>;
101
+ }) & (Level extends readonly [] ? {} : { [K in keyof Edges<D, T>]?: RelationFilterSelection<Tables, D, Extract<Target<Edges<D, T>[K]>, keyof Tables>, Tail<Level>>; });
69
102
  type ExactOutputMask<Tables extends RelationTables, D extends RelationDeclarations, T extends keyof Tables, S, L extends readonly 1[] = Depth> = S & { [K in keyof S]: L extends readonly [] ? never : K extends keyof Edges<D, T> ? S[K] extends true ? true : ExactOutputMask<Tables, D, Extract<Target<Edges<D, T>[K]>, keyof Tables>, S[K], Tail<L>> : never; };
70
- type ExactFilterMask<Tables extends RelationTables, D extends RelationDeclarations, T extends keyof Tables, S, L extends readonly 1[] = Depth> = S & { [K in keyof S]: K extends keyof ScalarSelection<Fields<Tables[T]>> ? S[K] extends true ? true : never : L extends readonly [] ? never : K extends keyof Edges<D, T> ? S[K] extends true ? never : ExactFilterMask<Tables, D, Extract<Target<Edges<D, T>[K]>, keyof Tables>, S[K], Tail<L>> : never; };
103
+ type ExactFilterMask<Tables extends RelationTables, D extends RelationDeclarations, T extends keyof Tables, S, L extends readonly 1[] = Depth> = S & { [K in keyof S]: K extends ([Tags<Tables[T]>] extends [never] ? never : 'variants') ? S[K] extends true ? K extends keyof ScalarSelection<Fields<Tables[T]>> ? true : never : S[K] & { [Tag in keyof S[K]]: Tag extends Tags<Tables[T]> ? ExactFilterMask<BranchTables<Tables, T, Extract<Tag, string>>, D, T, S[K][Tag], Tail<L>> : never; } : K extends keyof ScalarSelection<Fields<Tables[T]>> ? S[K] extends true ? true : never : L extends readonly [] ? never : K extends keyof Edges<D, T> ? S[K] extends true ? never : ExactFilterMask<Tables, D, Extract<Target<Edges<D, T>[K]>, keyof Tables>, S[K], Tail<L>> : never; };
71
104
  type ScalarValues<T extends RelationTable, S, Side extends 'input' | 'output'> = { [K in Extract<keyof S, keyof Fields<T>>]?: ScalarPredicate<Fields<T>[K], Side>; };
72
- export type RelationFilters<Tables extends RelationTables, D extends RelationDeclarations, T extends keyof Tables, S, Side extends 'input' | 'output' = 'output', Level extends readonly 1[] = Depth> = Omit<ScalarValues<Tables[T], S, Side>, 'and' | 'or' | 'not' | 'fields'> & {
105
+ export type RelationFilters<Tables extends RelationTables, D extends RelationDeclarations, T extends keyof Tables, S, Side extends 'input' | 'output' = 'output', Level extends readonly 1[] = Depth> = Omit<ScalarValues<Tables[T], S, Side>, 'and' | 'or' | 'not' | 'fields' | ([Tags<Tables[T]>] extends [never] ? never : 'variant')> & {
73
106
  fields?: ScalarValues<Tables[T], S, Side>;
74
- } & (Level extends readonly [] ? {} : { [K in Extract<keyof S, keyof Edges<D, T>>]?: Edges<D, T>[K] extends RelationEdge<string, infer Target, infer C> ? C extends 'one' ? RelationFilters<Tables, D, Extract<Target, keyof Tables>, S[K], Side, Tail<Level>> | null : {
107
+ } & VariantFilters<Tables, D, T, S, Side, Level> & (Level extends readonly [] ? {} : { [K in Extract<keyof S, keyof Edges<D, T>>]?: Edges<D, T>[K] extends RelationEdge<string, infer Target, infer C, any, any> ? C extends 'one' ? RelationFilters<Tables, D, Extract<Target, keyof Tables>, S[K], Side, Tail<Level>> | null : {
75
108
  some: RelationFilters<Tables, D, Extract<Target, keyof Tables>, S[K], Side, Tail<Level>>;
76
109
  } | {
77
110
  none: RelationFilters<Tables, D, Extract<Target, keyof Tables>, S[K], Side, Tail<Level>>;
78
111
  } : never; } & {
79
- and?: RelationFilters<Tables, D, T, S, Side, Tail<Level>>[];
80
- or?: RelationFilters<Tables, D, T, S, Side, Tail<Level>>[];
112
+ and?: readonly RelationFilters<Tables, D, T, S, Side, Tail<Level>>[];
113
+ or?: readonly RelationFilters<Tables, D, T, S, Side, Tail<Level>>[];
81
114
  not?: RelationFilters<Tables, D, T, S, Side, Tail<Level>>;
82
115
  });
116
+ type VariantFilters<Tables extends RelationTables, D extends RelationDeclarations, T extends keyof Tables, S, Side extends 'input' | 'output', L extends readonly 1[]> = L extends readonly [] ? {} : S extends {
117
+ variants: infer V;
118
+ } ? V extends true ? {} : {
119
+ variant?: { [Tag in keyof V]: Tag extends Tags<Tables[T]> ? {
120
+ tag: Tag;
121
+ filters: RelationFilters<BranchTables<Tables, T, Extract<Tag, string>>, D, T, V[Tag] & Omit<S, 'variants'>, Side, Tail<L>>;
122
+ } : never; }[keyof V];
123
+ } : {};
83
124
  type PublicRow<T extends RelationTable> = z.output<T['publicDto']> & {
84
125
  _id: GenericId<T['tableName']>;
85
126
  };
86
- export type RelationRow<Tables extends RelationTables, D extends RelationDeclarations, T extends keyof Tables, S, Level extends readonly 1[] = Depth> = PublicRow<Tables[T]> & (Level extends readonly [] ? {} : { [K in keyof S]: K extends keyof Edges<D, T> ? Edges<D, T>[K] extends RelationEdge<string, infer Target, infer C> ? C extends 'one' ? RelationRow<Tables, D, Extract<Target, keyof Tables>, S[K] extends true ? {} : S[K], Tail<Level>> | null : PaginationResult<RelationRow<Tables, D, Extract<Target, keyof Tables>, S[K] extends true ? {} : S[K], Tail<Level>>> : never : never; });
127
+ export type ScopedRelationRow<Row, Scope extends string, Key extends PropertyKey> = [Scope] extends [never] ? Row : Extract<Row, Record<Key, Scope>>;
128
+ type ComposeRelationRow<Tables extends RelationTables, D extends RelationDeclarations, T extends keyof Tables, S, Level extends readonly 1[], Row> = Row extends unknown ? Row & (Level extends readonly [] ? {} : { [K in keyof S]: K extends keyof Edges<D, T> ? Edges<D, T>[K] extends RelationEdge<string, infer Target, infer C, infer SourceScope, infer TargetScope> ? C extends 'one' ? ([SourceScope] extends [never] ? true : Row extends ScopedRelationRow<Row, SourceScope, Discriminator<Tables[T]>> ? true : false) extends true ? ScopedRelationRow<RelationRow<Tables, D, Extract<Target, keyof Tables>, S[K] extends true ? {} : S[K], Tail<Level>>, TargetScope, Discriminator<Tables[Extract<Target, keyof Tables>]>> | null : null : PaginationResult<ScopedRelationRow<RelationRow<Tables, D, Extract<Target, keyof Tables>, S[K] extends true ? {} : S[K], Tail<Level>>, TargetScope, Discriminator<Tables[Extract<Target, keyof Tables>]>>> : never : never; }) : never;
129
+ export type RelationRow<Tables extends RelationTables, D extends RelationDeclarations, T extends keyof Tables, S, Level extends readonly 1[] = Depth> = ComposeRelationRow<Tables, D, T, S, Level, PublicRow<Tables[T]>>;
130
+ export type RelationQueryRow<Tables extends RelationTables, D extends RelationDeclarations, T extends keyof Tables, S, Scope extends string = never> = ScopedRelationRow<RelationRow<Tables, D, T, S>, Scope, Discriminator<Tables[T]>>;
87
131
  export interface RelationTableHelpers<Tables extends RelationTables, D extends RelationDeclarations, T extends keyof Tables> {
88
132
  paginationOpts<const S extends RelationFilterSelection<Tables, D, T>>(selection: ExactFilterMask<Tables, D, T, S>): PaginationOptionsSchema<RelationFilters<Tables, D, T, S>, RelationFilters<Tables, D, T, S, 'input'>>;
89
133
  pageDto<const S extends RelationSelection<Tables, D, T>>(selection: ExactOutputMask<Tables, D, T, S>): z.ZodType<PaginationResult<RelationRow<Tables, D, T, S>>>;
@@ -106,6 +150,10 @@ export interface RelationFieldMetadata {
106
150
  }
107
151
  export interface RelationTableMetadata {
108
152
  readonly fields: Readonly<Record<string, RelationFieldMetadata>>;
153
+ readonly variant?: {
154
+ readonly discriminator: string;
155
+ readonly tags: readonly string[];
156
+ };
109
157
  readonly indexes: readonly {
110
158
  readonly name: string;
111
159
  readonly fields: readonly string[];
@@ -116,12 +164,13 @@ export interface RelationMetadata {
116
164
  readonly declarations: Readonly<Record<string, Readonly<Record<string, AnyEdge>>>>;
117
165
  }
118
166
  /** No ID-field inference and no readers: this registry owns declarations/schema helpers only. */
119
- export declare function defineRelations<const Tables extends RelationTables, const D extends RelationDeclarations>(tables: Tables, declare: (r: RelationBuilder<Tables>) => D & ExactDeclarations<Tables, D>): RelationRegistry<Tables, D>;
167
+ export declare function defineRelations<const Tables extends RelationTables, const D extends RelationDeclarations>(tables: Tables, declare: (r: RelationBuilder<Tables>, branch: BranchBuilder<Tables>) => D & ExactDeclarations<Tables, D>): RelationRegistry<Tables, D>;
120
168
  /** Internal owned executor bridge. Not an advertised root API. Every operation
121
169
  * rechecks the live registry, including cached plans and individual projections.
122
170
  */
123
171
  export declare function getRelationExecutor(registry: RelationRegistryIdentity): Readonly<{
124
172
  assertUnchanged: () => void;
173
+ validateDocument: (table: string, row: Record<string, import('convex/values').Value>) => void;
125
174
  assertNativeTable: (table: string, definition: TableDefinition) => void;
126
175
  assertSchema: (tables: Readonly<Record<string, TableDefinition>>) => void;
127
176
  pagination(table: string): z.ZodObject<{
@@ -1,2 +1,2 @@
1
- import{nativePagination as e,relationFilterSchema as t,scalarPredicateSchema as n}from"./querying/filters.mjs";import{paginated as r}from"./zod-table.mjs";import{zodToConvex as i}from"convex-helpers/server/zod4";import{z as a}from"zod";import{v as o}from"convex/values";const s=Symbol(`relationField`),c=Symbol(`relationEdge`),l=/* @__PURE__ */ new WeakMap,u=/* @__PURE__ */ new WeakMap,d=/* @__PURE__ */ new WeakMap,f=/* @__PURE__ */ new WeakSet,p=/* @__PURE__ */ new WeakSet,m=a.object({indexes:a.array(a.object({indexDescriptor:a.string(),fields:a.array(a.string())}))});function h(n,o){let c={},h=/* @__PURE__ */ new Set,g={},_={},v={};for(let[e,t]of Object.entries(n)){if(t.schema instanceof a.ZodUnion)throw Error(`Variant tables are not supported by relations or the query engine`);if(t.tableName!==e||[`one`,`many`,`__proto__`,`constructor`,`prototype`].includes(e))throw Error(`Invalid relation table "${e}"`);let n=t.dto(!0);if(!(n instanceof a.ZodObject))throw Error(`Expected object DTO`);let r=I(n),o=i(t.schema),l=k(t.table);M(l.documentType),N(e,o.fields,l.documentType);let u=m.parse(l).indexes.map(e=>({name:e.indexDescriptor,fields:[...e.fields]})).sort((e,t)=>e.name.localeCompare(t.name));M(A(i(n))),c[e]={fields:o.fields,indexes:u,dto:n,assertUnchanged:r};let p=Object.create(null);for(let[t,n]of Object.entries(o.fields)){let r={[s]:void 0,table:e,field:t,through(e){let t=d.get(e);if(!h.has(e)||!t||!S(n,t))throw Error(`Invalid junction field or registry`);let i=Object.freeze({base:r,junction:e});return f.add(i),i}};d.set(r,n),h.add(r),p[t]=Object.freeze(r)}g[e]=Object.freeze(p),_[e]=t=>x(e,`one`,t,h),v[e]=t=>x(e,`many`,t,h)}let C=o(Object.freeze({...g,one:Object.freeze(_),many:Object.freeze(v)})),T=Object.fromEntries(Object.entries(C).map(([e,t])=>[e,Object.freeze({...t})]));Object.freeze(T);for(let[e,t]of Object.entries(T)){if(!Object.hasOwn(n,e))throw Error(`Unknown source table "${e}"`);for(let[n,r]of Object.entries(t)){if(Object.hasOwn(c[e].fields,n)||[`and`,`or`,`not`,`fields`,`then`,`__proto__`,`constructor`,`prototype`].includes(n))throw Error(`Relation name collision "${n}"`);if(!p.has(r)||!h.has(b(r.from))||!h.has(b(r.to))||r.source!==e)throw Error(`Relation source bucket mismatch`);w(r,c)}}let P={metadata:c,declarations:T},F={};for(let i of Object.keys(n))F[i]={paginationOpts(n){return B(P),y(n),H(e.extend({filters:t(D(P,i,n)).optional(),order:a.enum([`asc`,`desc`]).optional()}),()=>B(P))},pageDto(e){return B(P),y(e),H(r(O(P,i,e)).result,()=>B(P))}};let L=JSON.stringify([1,Object.entries(c).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,Object.entries(t.fields).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,t.isOptional,A(t)]),t.indexes,j(A(i(t.dto)))]),Object.entries(T).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,Object.entries(t).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,t.cardinality,t.target,E(t.from),E(t.to)])])]),R=Object.freeze({identity:L,version:1,tables:Object.freeze(F)});l.set(R,U(P));let V=Object.freeze({...n}),W=Object.fromEntries(Object.entries(V).map(([e,t])=>{let n=z(t.schema,`stored`),r=JSON.stringify(k(t.table));return[e,()=>{if(n(),JSON.stringify(k(t.table))!==r)throw Error(`Native schema mutated after registry construction: ${e}`)}]}));return u.set(R,{internal:P,tables:V,assertStoredUnchanged:()=>{for(let e of Object.values(W))e()},assertNativeTable(e,t){if(!Object.hasOwn(V,e)||V[e].table!==t)throw Error(`Native schema/table ownership disagrees with relation registry`);W[e]()}}),R}function g(i){let o=u.get(i);if(!o)throw Error(`Unknown relation registry`);let s=()=>{B(o.internal),o.assertStoredUnchanged()},c=e=>{s();let t=Object.keys(o.tables);if(t.length!==Object.keys(e).length||t.some(t=>e[t]!==o.tables[t].table))throw Error(`Native schema/table ownership disagrees with relation registry`)};return s(),Object.freeze({assertUnchanged:s,assertNativeTable:o.assertNativeTable,assertSchema:c,pagination(r){s();let i=o.internal,c=/* @__PURE__ */ new Map;function l(e,t){let r=i.metadata[e];if(!r)throw Error(`Unknown query table`);let a=c.get(e);if(!a){a={};for(let[e,t]of Object.entries(r.fields))v(t)&&(a[e]=n(t).optional());c.set(e,a)}return{fields:a,relations:t>=4?{}:Object.fromEntries(Object.entries(i.declarations[e]??{}).map(([e,n])=>[e,{cardinality:n.cardinality,target:l(n.target,t+1)}]))}}return e.extend({filters:t(l(r,0)).optional(),order:a.enum([`asc`,`desc`]).optional()})},page(e,t){return s(),y(t),r(O(o.internal,e,t)).result},project(e,t,n,r){if(c(e),!r())return null;let i=o.internal.metadata[t]?.dto;if(!i)throw Error(`Unknown query table`);return i.parse(Object.fromEntries(Object.keys(i.shape).filter(e=>Object.hasOwn(n,e)).map(e=>[e,n[e]])))}})}function _(e){let t=l.get(e);if(!t)throw Error(`Unknown relation registry`);return t}function v(e){return[`id`,`string`,`float64`,`int64`,`boolean`,`null`,`literal`].includes(e.kind)||e.kind===`union`&&e.members.every(v)}function y(e){let t=[{value:e,depth:0,ancestors:[]}],n=0;for(;t.length;){let{value:e,depth:r,ancestors:i}=t.pop();if(++n>256||r>4||i.includes(e))throw Error(`Selection cycle or depth/node budget exceeded`);let a=Object.getPrototypeOf(e);if(a!==Object.prototype&&a!==null)throw Error(`Invalid selection`);let o=Reflect.ownKeys(e);if(o.length+n+t.length>256)throw Error(`Selection node budget exceeded`);for(let a of o){let o=Object.getOwnPropertyDescriptor(e,a);if(!o.enumerable||!(`value`in o)||String(a)!==a)throw Error(`Invalid selection property`);if(o.value!==!0)t.push({value:o.value,depth:r+1,ancestors:[...i,e]});else if(++n>256)throw Error(`Selection node budget exceeded`)}}}function b(e){return`base`in e?e.base:e}function x(e,t,n,r){for(let e of[n.from,n.to])if(!r.has(b(e))||`base`in e&&(!f.has(e)||!r.has(e.junction)))throw Error(`Foreign registry or invalid field reference`);if(b(n.to).table!==e)throw Error(`Wrong relation target table`);let i=Object.freeze({[c]:!0,source:b(n.from).table,target:e,cardinality:t,from:n.from,to:n.to});return p.add(i),i}function S(e,t){let n=C(e);return n.length>0&&JSON.stringify(n)===JSON.stringify(C(t))}function C(e){if(e.kind===`union`)return[...new Set(e.members.flatMap(C))].sort();if(e.kind===`null`)return[];if(![`id`,`string`,`float64`,`int64`,`boolean`,`literal`].includes(e.kind))throw Error(`Unsupported relation field kind`);return[JSON.stringify(A(e))]}function w(e,t){let n=e.from,r=e.to;if(`base`in n!=`base`in r)throw Error(`Both relation legs must use through`);if(`base`in n&&`base`in r){if(n.junction.table!==r.junction.table)throw Error(`Different junction tables`);T(t,n.junction.table,n.junction.field),T(t,e.target,r.base.field);return}if(!S(d.get(b(n)),d.get(b(r))))throw Error(`Incompatible relation field types`);T(t,e.target,b(r).field)}function T(e,t,n){if(n!==`_id`&&!e[t].indexes.some(e=>e.fields[0]===n))throw Error(`No active index begins with "${t}.${n}"`)}function E(e){return`base`in e?[e.base.table,e.base.field,e.junction.table,e.junction.field]:[e.table,e.field]}function D(e,t,r,i=0){let a={},o={};for(let[s,c]of Object.entries(r)){let r=e.metadata[t].fields[s],l=e.declarations[t]?.[s];if(c===!0&&r)a[s]=n(r).optional();else if(c!==!0&&l&&i<4)o[s]={cardinality:l.cardinality,target:D(e,l.target,c,i+1)};else throw Error(`Invalid relation filter selection "${t}.${s}"`)}return{fields:a,relations:o}}function O(e,t,n,i=0){let o={};for(let[a,s]of Object.entries(n)){let n=e.declarations[t]?.[a];if(!n||i>=4)throw Error(`Unknown or too deep relation "${t}.${a}"`);let c=s===!0?e.metadata[n.target].dto:O(e,n.target,s,i+1);o[a]=n.cardinality===`one`?c.nullable():r(c).result}let s=e.metadata[t].dto;if(!(s instanceof a.ZodObject))throw Error(`Expected object DTO`);return H(s.extend(o).strict(),()=>B(e))}function k(e){return e.export()}function A(e){return e.json}function j(e){if(Array.isArray(e))return`[${e.map(j).join(`,`)}]`;if(e!==null&&Object(e)===e){let t=e;return`{${Object.keys(t).sort().map(e=>`${JSON.stringify(e)}:${j(t[e])}`).join(`,`)}}`}return JSON.stringify(e)}function M(e){if(e===null||Object(e)!==e)return;let t=e;if(t.type===`any`)throw Error(`Unsupported native validation form`);for(let e of Object.values(t))M(e)}function N(e,t,n){let{_id:r,_creationTime:i,...a}=t;if(!r||!i||j(A(r))!==j(A(o.id(e)))||j(A(i))!==j(A(o.number()))||r.isOptional!==`required`||i.isOptional!==`required`||j(n)!==j(A(o.object(a))))throw Error(`Native stored document disagrees with boundary "${e}"`)}const P=a.object({field:a.string()}),F=new Set([P,P.pick({field:!0}),P.omit({field:!0}),P.extend({other:a.string()}),P.safeExtend({other:a.string()}),P.merge(a.object({other:a.string()})),P.partial(),P.required()].flatMap(e=>{let t=Object.getOwnPropertyDescriptor(e._zod.def,`shape`)?.get;return t?[Function.prototype.toString.call(t)]:[]}));function I(e){return z(e,`dto`)}const L=Function.prototype.toString.call(Object.getOwnPropertyDescriptor(a.string().default(``)._zod.def,`defaultValue`).get),R=Function.prototype.toString.call(Object.getOwnPropertyDescriptor(a.string().prefault(``)._zod.def,`defaultValue`).get);function z(e,t){let n=[],r=/* @__PURE__ */ new Set,i=[],o=/* @__PURE__ */ new Set,s=/* @__PURE__ */ new Set,c=[];function l(e,u){if(s.has(e))throw Error(`Unsupported cyclic DTO schema`);if(!o.has(e)){if(u>32||n.length>=4096)throw Error(`DTO schema graph budget exceeded`);o.add(e),s.add(e);try{if(e instanceof RegExp&&i.push({expression:e,source:e.source,flags:e.flags}),e instanceof a.core.$ZodCheck&&`check`in e._zod.def){if(t===`dto`&&e._zod.def.check===`overwrite`)throw Error(`Unsupported DTO overwrite check`);l(e._zod.def,u+1),n.push({object:e._zod,exactKeys:!1,keys:[`def`,`check`],values:[`def`,`check`].map(t=>Object.getOwnPropertyDescriptor(e._zod,t))});return}if(e instanceof a.core.$ZodType){let i=e._zod.def;if(t===`dto`&&(![`object`,`array`,`optional`,`nullable`,`nonoptional`,`union`,`intersection`,`tuple`,`record`,`string`,`number`,`boolean`,`bigint`,`null`,`never`,`literal`,`enum`].includes(i.type)||`coerce`in i&&i.coerce))throw Error(`Unsupported DTO schema "${i.type}"`);if(t===`stored`&&(i.type==="default"||i.type===`prefault`)){let e=Object.getOwnPropertyDescriptor(i,`defaultValue`);if(e?.get){if(e.set||Function.prototype.toString.call(e.get)!==(i.type==="default"?L:R))throw Error(`Unsupported stored schema accessor`);r.add(i)}}if(i.type===`object`){let t=Object.getOwnPropertyDescriptor(i,`shape`);if(t?.get){if(t.set||!F.has(Function.prototype.toString.call(t.get)))throw Error(`Unsupported DTO schema accessor`);let e=i.shape;l(e,u+1),Object.getOwnPropertyDescriptor(i,`shape`)?.get&&c.push({definition:i,fields:e})}if(e instanceof a.ZodObject){let t=Object.getOwnPropertyDescriptor(e,`shape`);if(t&&!(`value`in t))throw Error(`Unsupported DTO schema accessor`);l(e.shape,u+1)}}l(i,u+1),n.push({object:e._zod,exactKeys:!1,keys:[`def`],values:[Object.getOwnPropertyDescriptor(e._zod,`def`)]});return}let o=Reflect.ownKeys(e),s=o.map(t=>Object.getOwnPropertyDescriptor(e,t));if(s.some((t,n)=>!(`value`in t)&&!c.some(({definition:t})=>t===e&&o[n]===`shape`)&&!(r.has(e)&&o[n]===`defaultValue`)))throw Error(`Unsupported DTO schema accessor`);n.push({object:e,exactKeys:!0,keys:o,values:s});for(let e of s)e.value!==null&&Object(e.value)===e.value&&!(e.value instanceof Function)&&l(e.value,u+1)}finally{s.delete(e)}}}return l(e,0),()=>{for(let e of i)if(e.expression.source!==e.source||e.expression.flags!==e.flags)throw Error(`DTO schema mutated after registry construction`);for(let e of n){let t=e.keys;if(e.exactKeys&&Reflect.ownKeys(e.object).length!==t.length)throw Error(`DTO schema mutated after registry construction`);for(let n=0;n<t.length;n++){if(e.object instanceof RegExp&&t[n]===`lastIndex`)continue;let r=Object.getOwnPropertyDescriptor(e.object,t[n]),i=e.values[n];if(!r||r.value!==i.value||r.get!==i.get||r.set!==i.set||r.enumerable!==i.enumerable)throw Error(`DTO schema mutated after registry construction`)}}for(let{definition:e,fields:t}of c){let n=e.shape,r=Reflect.ownKeys(t);if(Reflect.ownKeys(n).length!==r.length||r.some(e=>Object.getOwnPropertyDescriptor(n,e)?.value!==Object.getOwnPropertyDescriptor(t,e)?.value))throw Error(`DTO schema mutated after registry construction`)}}}function B(e){for(let t of Object.values(e.metadata))t.assertUnchanged()}const V=a.core.$constructor(`GuardedDtoObject`,(e,t)=>{let n=t;a.ZodObject.init(e,t),e._zod.deferred??=[],e._zod.deferred.push(()=>{let t=e._zod.run;e._zod.run=(e,r)=>{try{n.assertUnchanged()}catch{return e.issues.push({code:`custom`,input:e.value,message:`DTO schema mutated after registry construction`}),e}return t(e,r)}})});function H(e,t){let n=e.shape,r={...e._zod.def,assertUnchanged:t};return Object.defineProperty(r,"shape",{enumerable:!0,configurable:!0,get:()=>(t(),n)}),new V(r)}function U(e){let t={};for(let[n,r]of Object.entries(e.metadata)){let e={};for(let[t,n]of Object.entries(r.fields))e[t]=Object.freeze({kind:n.kind,optional:n.isOptional===`optional`,nullable:W(n),idTables:Object.freeze(G(n)),native:K(A(n))});t[n]=Object.freeze({fields:Object.freeze(e),indexes:Object.freeze(r.indexes.map(e=>Object.freeze({name:e.name,fields:Object.freeze([...e.fields])})))})}return Object.freeze({tables:Object.freeze(t),declarations:e.declarations})}function W(e){return e.kind===`null`||e.kind===`union`&&e.members.some(W)}function G(e){return e.kind===`id`?[e.tableName]:e.kind===`union`?[...new Set(e.members.flatMap(G))].sort():[]}function K(e){let t=structuredClone(e),n=[t];for(;n.length;){let e=n.pop();if(Object(e)!==e)continue;let t=e;Object.freeze(t),n.push(...Object.values(t))}return t}export{h as defineRelations,g as getRelationExecutor,_ as getRelationMetadata};
1
+ import{nativePagination as e,relationFilterSchema as t,scalarPredicateSchema as n}from"./querying/filters.mjs";import{paginated as r}from"./zod-table.mjs";import{convexToZod as i,zodToConvex as a}from"convex-helpers/server/zod4";import{z as o}from"zod";import{v as s}from"convex/values";const c=Symbol(`relationField`),l=Symbol(`relationEdge`),u=/* @__PURE__ */ new WeakMap,d=/* @__PURE__ */ new WeakMap,f=/* @__PURE__ */ new WeakMap,p=/* @__PURE__ */ new WeakSet,m=/* @__PURE__ */ new WeakSet,h=o.object({indexes:o.array(o.object({indexDescriptor:o.string(),fields:o.array(o.string())}))});function g(n,i){let s={},l=/* @__PURE__ */ new Set,g=/* @__PURE__ */ new Map,_={},v={},y={};for(let[e,t]of Object.entries(n)){if(t.tableName!==e||[`one`,`many`,`__proto__`,`constructor`,`prototype`].includes(e))throw Error(`Invalid relation table "${e}"`);let n=t.dto(!0);if(!(n instanceof o.ZodObject)&&!(n instanceof o.ZodDiscriminatedUnion))throw Error(`Expected object or discriminated union DTO`);let r=B(n),i=N(t.table);I(i.documentType);let u=j(e,t.schema,n,i.documentType),d=h.parse(i).indexes.map(e=>({name:e.indexDescriptor,fields:[...e.fields]})).sort((e,t)=>e.name.localeCompare(t.name));I(P(a(n))),s[e]={...u,indexes:d,dto:n,assertUnchanged:r};let m=(t,n)=>{let r=Object.create(null);for(let[i,a]of Object.entries(t)){let t={[c]:void 0,table:e,field:i,guard:n,through(e){let n=f.get(e);if(!l.has(e)||!n||!w(a,n))throw Error(`Invalid junction field or registry`);let r=Object.freeze({base:t,junction:e});return p.add(r),r}};f.set(t,a),l.add(t),r[i]=Object.freeze(t)}return Object.freeze(r)};if(_[e]=m(u.fields),u.branches)for(let[t,n]of Object.entries(u.branches.options))g.set(JSON.stringify([e,t]),m(n.fields,Object.freeze({discriminator:u.branches.discriminator,tag:t})));v[e]=t=>S(e,`one`,t,l),y[e]=t=>S(e,`many`,t,l)}let C=i(Object.freeze({..._,one:Object.freeze(v),many:Object.freeze(y)}),((e,t)=>{let n=g.get(JSON.stringify([e,t]));if(!n)throw Error(`Unknown variant scope "${e}.${t}"`);return n})),T=Object.fromEntries(Object.entries(C).map(([e,t])=>[e,Object.freeze({...t})]));Object.freeze(T);for(let[e,t]of Object.entries(T)){if(!Object.hasOwn(n,e))throw Error(`Unknown source table "${e}"`);for(let[n,r]of Object.entries(t)){if(s[e].allFields.has(n)||s[e].branches&&[`variant`,`variants`].includes(n)||[`and`,`or`,`not`,`fields`,`then`,`__proto__`,`constructor`,`prototype`].includes(n))throw Error(`Relation name collision "${n}"`);if(!m.has(r)||!l.has(x(r.from))||!l.has(x(r.to))||r.source!==e)throw Error(`Relation source bucket mismatch`);E(r,s)}}let D={metadata:s,declarations:T},M={};for(let i of Object.keys(n))M[i]={paginationOpts(n){return W(D),b(n),K(e.extend({filters:t(k(D,i,n)).optional(),order:o.enum([`asc`,`desc`]).optional()}),()=>W(D))},pageDto(e){return W(D),b(e),K(r(A(D,i,e)).result,()=>W(D))}};let L=JSON.stringify([2,Object.entries(s).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,Object.entries(t.fields).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,t.isOptional,P(t)]),t.branches?[t.branches.discriminator,Object.entries(t.branches.options).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,Object.entries(t.fields).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,t.isOptional,P(t)])])]:null,t.indexes,F(P(a(t.dto)))]),Object.entries(T).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,Object.entries(t).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,t.cardinality,t.target,O(t.from),O(t.to)])])]),R=Object.freeze({identity:L,version:1,tables:Object.freeze(M)});u.set(R,Y(D));let z=Object.freeze({...n}),V=Object.fromEntries(Object.entries(z).map(([e,t])=>{let n=U(t.schema,`stored`),r=U(t.publicDto,`dto`),i=t.table.validator,a=i.isOptional,o=JSON.stringify(N(t.table));return[e,()=>{if(n(),r(),t.table.validator!==i||i.isOptional!==a||JSON.stringify(N(t.table))!==o)throw Error(`Native schema mutated after registry construction: ${e}`)}]}));for(let[e,t]of Object.entries(s)){if(!t.branches)continue;let n=t.assertUnchanged;t.assertUnchanged=()=>{n(),V[e]()}}return d.set(R,{internal:D,tables:z,assertStoredUnchanged:()=>{for(let e of Object.values(V))e()},assertNativeTable(e,t){if(!Object.hasOwn(z,e)||z[e].table!==t)throw Error(`Native schema/table ownership disagrees with relation registry`);V[e]()}}),R}function _(a){let c=d.get(a);if(!c)throw Error(`Unknown relation registry`);let l=()=>{W(c.internal),c.assertStoredUnchanged()},u=e=>{l();let t=Object.keys(c.tables);if(t.length!==Object.keys(e).length||t.some(t=>e[t]!==c.tables[t].table))throw Error(`Native schema/table ownership disagrees with relation registry`)};l();let f=/* @__PURE__ */ new WeakMap;function p(e,t){l();let n=c.internal.metadata[e];if(!n)throw Error(`Unknown query table`);if(!n.branches)return;let r=o.string().safeParse(t[n.branches.discriminator]),a=r.success&&Object.hasOwn(n.branches.options,r.data)?n.branches.options[r.data]:void 0;if(!a)throw Error(`Invalid variant document`);let u=Object.fromEntries(Object.keys(a.fields).filter(e=>Object.hasOwn(t,e)).map(e=>[e,t[e]])),d=f.get(a);d||(d=i(s.object(a.fields)),f.set(a,d)),d.parse(u)}return Object.freeze({assertUnchanged:l,validateDocument:p,assertNativeTable:c.assertNativeTable,assertSchema:u,pagination(r){l();let i=c.internal,a=/* @__PURE__ */ new Map;function s(e,t,r){let o=i.metadata[e];if(!o)throw Error(`Unknown query table`);let c=JSON.stringify([e,r??null]),l=a.get(c);if(!l){l={};for(let[e,t]of Object.entries(r===void 0?o.fields:o.branches.options[r].fields))y(t)&&(l[e]=n(t).optional());a.set(c,l)}return{fields:l,variants:o.branches&&r===void 0&&t<4?{discriminator:o.branches.discriminator,options:Object.fromEntries(Object.keys(o.branches.options).map(n=>[n,s(e,t+1,n)]))}:void 0,relations:t>=4?{}:Object.fromEntries(Object.entries(i.declarations[e]??{}).map(([e,n])=>[e,{cardinality:n.cardinality,target:s(n.target,t+1)}]))}}return e.extend({filters:t(s(r,0)).optional(),order:o.enum([`asc`,`desc`]).optional()})},page(e,t){return l(),b(t),r(A(c.internal,e,t)).result},project(e,t,n,r){if(u(e),!r())return null;let i=c.internal.metadata[t];if(!i)throw Error(`Unknown query table`);let a=i.branches?i.branches.options[String(n[i.branches.discriminator])]:void 0;if(i.branches&&!a)throw Error(`Invalid variant document`);let s=a?.dto??i.dto;if(!(s instanceof o.ZodObject))throw Error(`Invalid variant DTO`);return p(t,n),s.parse(Object.fromEntries(Object.keys(s.shape).filter(e=>Object.hasOwn(n,e)).map(e=>[e,n[e]])))}})}function v(e){let t=u.get(e);if(!t)throw Error(`Unknown relation registry`);return t}function y(e){return[`id`,`string`,`float64`,`int64`,`boolean`,`null`,`literal`].includes(e.kind)||e.kind===`union`&&e.members.every(y)}function b(e){let t=[{value:e,depth:0,ancestors:[]}],n=0;for(;t.length;){let{value:e,depth:r,ancestors:i}=t.pop();if(++n>256||r>4||i.includes(e))throw Error(`Selection cycle or depth/node budget exceeded`);let a=Object.getPrototypeOf(e);if(a!==Object.prototype&&a!==null)throw Error(`Invalid selection`);let o=Reflect.ownKeys(e);if(o.length+n+t.length>256)throw Error(`Selection node budget exceeded`);for(let a of o){let o=Object.getOwnPropertyDescriptor(e,a);if(!o.enumerable||!(`value`in o)||String(a)!==a)throw Error(`Invalid selection property`);if(o.value!==!0)t.push({value:o.value,depth:r+1,ancestors:[...i,e]});else if(++n>256)throw Error(`Selection node budget exceeded`)}}}function x(e){return`base`in e?e.base:e}function S(e,t,n,r){for(let e of[n.from,n.to])if(!r.has(x(e))||`base`in e&&(!p.has(e)||!r.has(e.junction)))throw Error(`Foreign registry or invalid field reference`);if(x(n.to).table!==e)throw Error(`Wrong relation target table`);let i=Object.freeze({[l]:!0,source:x(n.from).table,target:e,cardinality:t,from:n.from,to:n.to,sourceGuard:x(n.from).guard,targetGuard:x(n.to).guard,junctionGuard:C(n.from,n.to)});return m.add(i),i}function C(e,t){let n=`base`in e?e.junction.guard:void 0,r=`base`in t?t.junction.guard:void 0;if(n&&r&&(n.discriminator!==r.discriminator||n.tag!==r.tag))throw Error(`Contradictory junction scopes`);return n??r}function w(e,t){let n=T(e);return n.length>0&&JSON.stringify(n)===JSON.stringify(T(t))}function T(e){if(e.kind===`union`)return[...new Set(e.members.flatMap(T))].sort();if(e.kind===`null`)return[];if(![`id`,`string`,`float64`,`int64`,`boolean`,`literal`].includes(e.kind))throw Error(`Unsupported relation field kind`);return[JSON.stringify(P(e))]}function E(e,t){let n=e.from,r=e.to;if(`base`in n!=`base`in r)throw Error(`Both relation legs must use through`);if(`base`in n&&`base`in r){if(n.junction.table!==r.junction.table)throw Error(`Different junction tables`);D(t,n.junction.table,n.junction.field,e.junctionGuard),D(t,e.target,r.base.field,e.targetGuard);return}if(!w(f.get(x(n)),f.get(x(r))))throw Error(`Incompatible relation field types`);D(t,e.target,x(r).field,e.targetGuard)}function D(e,t,n,r){if(n!==`_id`&&!e[t].indexes.some(e=>{let t=e.fields.indexOf(n);return t>=0&&e.fields.slice(0,t).every(e=>e===r?.discriminator)}))throw Error(`No active index begins with or has a guarded prefix for "${t}.${n}"`)}function O(e){return`base`in e?[e.base.table,e.base.field,e.base.guard??null,e.junction.table,e.junction.field,e.junction.guard??null]:[e.table,e.field,e.guard??null]}function k(e,t,r,i=0,a){let o={},s={},c=e.metadata[t],l={};for(let[u,d]of Object.entries(r)){if(u===`variants`&&d!==!0&&c.branches&&a===void 0){if(i>=4)throw Error(`Invalid variant selection`);for(let[n,a]of Object.entries(d)){if(!Object.hasOwn(c.branches.options,n)||a===!0)throw Error(`Unknown variant filter selection`);l[n]=k(e,t,{...Object.fromEntries(Object.entries(r).filter(([e])=>e!==`variants`)),...a},i+1,n)}continue}let f=(a===void 0?c.fields:c.branches.options[a].fields)[u],p=e.declarations[t]?.[u];if(d===!0&&f)o[u]=n(f).optional();else if(d!==!0&&p&&i<4)s[u]={cardinality:p.cardinality,target:k(e,p.target,d,i+1)};else throw Error(`Invalid relation filter selection "${t}.${u}"`)}return{fields:o,relations:s,variants:c.branches&&a===void 0?{discriminator:c.branches.discriminator,options:l}:void 0}}function A(e,t,n,i=0){let a={};for(let[s,c]of Object.entries(n)){let n=e.declarations[t]?.[s];if(!n||i>=4)throw Error(`Unknown or too deep relation "${t}.${s}"`);let l=c===!0?e.metadata[n.target].dto:A(e,n.target,c,i+1);if(n.targetGuard){if(!(l instanceof o.ZodDiscriminatedUnion))throw Error(`Invalid target scope`);l=l.options.find(e=>e.shape[n.targetGuard.discriminator]instanceof o.ZodLiteral&&e.shape[n.targetGuard.discriminator].value===n.targetGuard.tag)}a[s]=n.cardinality===`one`?l.nullable():r(l).result}let s=e.metadata[t];function c(n,r){let i={...a};for(let n of Object.keys(i)){let a=e.declarations[t][n];a.sourceGuard&&r!==a.sourceGuard.tag&&a.cardinality===`one`&&(i[n]=o.null())}return K(n.extend(i).strict(),()=>W(e))}if(s.branches){let t=Object.entries(s.branches.options).map(([e,t])=>c(t.dto,e));return J(o.discriminatedUnion(s.branches.discriminator,[t[0],...t.slice(1)]),()=>W(e))}if(!(s.dto instanceof o.ZodObject))throw Error(`Expected object DTO`);return c(s.dto)}function j(e,t,n,r){if(t instanceof o.ZodObject&&n instanceof o.ZodObject){let n=a(t).fields;return L(e,n,r),{fields:n,allFields:new Set(Object.keys(n))}}if(!(t instanceof o.ZodDiscriminatedUnion)||!(n instanceof o.ZodDiscriminatedUnion))throw Error(`Expected matching discriminated union boundaries "${e}"`);let i=t._zod.def.discriminator;if(n._zod.def.discriminator!==i)throw Error(`DTO discriminator mismatch`);function c(e){let t=Object.create(null);for(let n of e.options){if(!(n instanceof o.ZodObject))throw Error(`Variant branches must be objects`);let e=n.shape[i];if(!(e instanceof o.ZodLiteral)||e.values.size!==1)throw Error(`Variant tags must be unique required string literals`);let r=o.string().safeParse(e.value);if(!r.success||Object.hasOwn(t,r.data))throw Error(`Variant tags must be unique required string literals`);t[r.data]=n}if(Object.keys(t).length===0)throw Error(`Expected at least one variant branch`);return t}let l=c(t),u=c(n);if(Object.keys(l).sort().join(`\0`)!==Object.keys(u).sort().join(`\0`))throw Error(`DTO variant tags mismatch`);let d={discriminator:i,options:Object.create(null)},f=[];for(let[t,n]of Object.entries(l)){let r=a(n).fields,{_id:i,_creationTime:o,...c}=r;L(e,r,P(s.object(c))),f.push(s.object(c)),d.options[t]={fields:r,dto:u[t]}}if(F(r)!==F(P(s.union(...f))))throw Error(`Native stored document disagrees with boundary "${e}"`);let p=Object.values(d.options).map(e=>e.fields),m={};for(let e of Object.keys(p[0])){if(!p.every(t=>Object.hasOwn(t,e))||e!==i&&!p.every(t=>M(t[e],p[0][e])))continue;let t=p.map(t=>t[e]),n=s.union(...t);m[e]=t.some(e=>e.isOptional===`optional`)?s.optional(n):n}return{fields:m,branches:d,allFields:new Set(p.flatMap(e=>Object.keys(e)))}}function M(e,t){try{return w(e,t)}catch{return F(P(e))===F(P(t))}}function N(e){return e.export()}function P(e){return e.json}function F(e){if(Array.isArray(e))return`[${e.map(F).join(`,`)}]`;if(e!==null&&Object(e)===e){let t=e;return`{${Object.keys(t).sort().map(e=>`${JSON.stringify(e)}:${F(t[e])}`).join(`,`)}}`}return JSON.stringify(e)}function I(e){if(e===null||Object(e)!==e)return;let t=e;if(t.type===`any`)throw Error(`Unsupported native validation form`);for(let e of Object.values(t))I(e)}function L(e,t,n){let{_id:r,_creationTime:i,...a}=t;if(!r||!i||F(P(r))!==F(P(s.id(e)))||F(P(i))!==F(P(s.number()))||r.isOptional!==`required`||i.isOptional!==`required`||F(n)!==F(P(s.object(a))))throw Error(`Native stored document disagrees with boundary "${e}"`)}const R=o.object({field:o.string()}),z=new Set([R,R.pick({field:!0}),R.omit({field:!0}),R.extend({other:o.string()}),R.safeExtend({other:o.string()}),R.merge(o.object({other:o.string()})),R.partial(),R.required()].flatMap(e=>{let t=Object.getOwnPropertyDescriptor(e._zod.def,`shape`)?.get;return t?[Function.prototype.toString.call(t)]:[]}));function B(e){return U(e,`dto`)}const V=Function.prototype.toString.call(Object.getOwnPropertyDescriptor(o.string().default(``)._zod.def,`defaultValue`).get),H=Function.prototype.toString.call(Object.getOwnPropertyDescriptor(o.string().prefault(``)._zod.def,`defaultValue`).get);function U(e,t){let n=[],r=/* @__PURE__ */ new Set,i=[],a=/* @__PURE__ */ new Set,s=/* @__PURE__ */ new Set,c=[];function l(e,u){if(s.has(e))throw Error(`Unsupported cyclic DTO schema`);if(!a.has(e)){if(u>32||n.length>=4096)throw Error(`DTO schema graph budget exceeded`);a.add(e),s.add(e);try{if(e instanceof RegExp&&i.push({expression:e,source:e.source,flags:e.flags}),e instanceof o.core.$ZodCheck&&`check`in e._zod.def){if(t===`dto`&&e._zod.def.check===`overwrite`)throw Error(`Unsupported DTO overwrite check`);l(e._zod.def,u+1),n.push({object:e._zod,exactKeys:!1,keys:[`def`,`check`],values:[`def`,`check`].map(t=>Object.getOwnPropertyDescriptor(e._zod,t))});return}if(e instanceof o.core.$ZodType){let i=e._zod.def;if(t===`dto`&&(![`object`,`array`,`optional`,`nullable`,`nonoptional`,`union`,`intersection`,`tuple`,`record`,`string`,`number`,`boolean`,`bigint`,`null`,`never`,`literal`,`enum`].includes(i.type)||`coerce`in i&&i.coerce))throw Error(`Unsupported DTO schema "${i.type}"`);if(t===`stored`&&(i.type==="default"||i.type===`prefault`)){let e=Object.getOwnPropertyDescriptor(i,`defaultValue`);if(e?.get){if(e.set||Function.prototype.toString.call(e.get)!==(i.type==="default"?V:H))throw Error(`Unsupported stored schema accessor`);r.add(i)}}if(e instanceof o.ZodUnion&&(l(e.options,u+1),n.push({object:e,exactKeys:!1,keys:[`options`],values:[Object.getOwnPropertyDescriptor(e,`options`)]})),i.type===`object`){let t=Object.getOwnPropertyDescriptor(i,`shape`);if(t?.get){if(t.set||!z.has(Function.prototype.toString.call(t.get)))throw Error(`Unsupported DTO schema accessor`);let e=i.shape;l(e,u+1),Object.getOwnPropertyDescriptor(i,`shape`)?.get&&c.push({definition:i,fields:e})}if(e instanceof o.ZodObject){let t=Object.getOwnPropertyDescriptor(e,`shape`);if(t&&!(`value`in t))throw Error(`Unsupported DTO schema accessor`);l(e.shape,u+1)}}l(i,u+1),n.push({object:e._zod,exactKeys:!1,keys:[`def`],values:[Object.getOwnPropertyDescriptor(e._zod,`def`)]});return}let a=Reflect.ownKeys(e),s=a.map(t=>Object.getOwnPropertyDescriptor(e,t));if(s.some((t,n)=>!(`value`in t)&&!c.some(({definition:t})=>t===e&&a[n]===`shape`)&&!(r.has(e)&&a[n]===`defaultValue`)))throw Error(`Unsupported DTO schema accessor`);n.push({object:e,exactKeys:!0,keys:a,values:s});for(let e of s)e.value!==null&&Object(e.value)===e.value&&!(e.value instanceof Function)&&l(e.value,u+1)}finally{s.delete(e)}}}return l(e,0),()=>{for(let e of i)if(e.expression.source!==e.source||e.expression.flags!==e.flags)throw Error(`DTO schema mutated after registry construction`);for(let e of n){let t=e.keys;if(e.exactKeys&&Reflect.ownKeys(e.object).length!==t.length)throw Error(`DTO schema mutated after registry construction`);for(let n=0;n<t.length;n++){if(e.object instanceof RegExp&&t[n]===`lastIndex`)continue;let r=Object.getOwnPropertyDescriptor(e.object,t[n]),i=e.values[n];if(!r||r.value!==i.value||r.get!==i.get||r.set!==i.set||r.enumerable!==i.enumerable)throw Error(`DTO schema mutated after registry construction`)}}for(let{definition:e,fields:t}of c){let n=e.shape,r=Reflect.ownKeys(t);if(Reflect.ownKeys(n).length!==r.length||r.some(e=>Object.getOwnPropertyDescriptor(n,e)?.value!==Object.getOwnPropertyDescriptor(t,e)?.value))throw Error(`DTO schema mutated after registry construction`)}}}function W(e){for(let t of Object.values(e.metadata))t.assertUnchanged()}const G=o.core.$constructor(`GuardedDtoObject`,(e,t)=>{let n=t;o.ZodObject.init(e,t),e._zod.deferred??=[],e._zod.deferred.push(()=>{let t=e._zod.run;e._zod.run=(e,r)=>{try{n.assertUnchanged()}catch{return e.issues.push({code:`custom`,input:e.value,message:`DTO schema mutated after registry construction`}),e}return t(e,r)}})});function K(e,t){let n=e.shape,r={...e._zod.def,assertUnchanged:t};return Object.defineProperty(r,"shape",{enumerable:!0,configurable:!0,get:()=>(t(),n)}),new G(r)}const q=o.core.$constructor(`GuardedDtoUnion`,(e,t)=>{let n=t;o.ZodDiscriminatedUnion.init(e,t),e._zod.deferred??=[],e._zod.deferred.push(()=>{let t=e._zod.run;e._zod.run=(e,r)=>{try{n.assertUnchanged()}catch{return e.issues.push({code:`custom`,input:e.value,message:`DTO schema mutated after registry construction`}),e}return t(e,r)}})});function J(e,t){let n=e.options,r={...e._zod.def,assertUnchanged:t};return Object.defineProperty(r,"options",{enumerable:!0,configurable:!0,get:()=>(t(),n)}),new q(r)}function Y(e){let t={};for(let[n,r]of Object.entries(e.metadata)){let e={};for(let[t,n]of Object.entries(r.fields))e[t]=Object.freeze({kind:n.kind,optional:n.isOptional===`optional`,nullable:X(n),idTables:Object.freeze(Z(n)),native:Q(P(n))});t[n]=Object.freeze({fields:Object.freeze(e),variant:r.branches?Object.freeze({discriminator:r.branches.discriminator,tags:Object.freeze(Object.keys(r.branches.options))}):void 0,indexes:Object.freeze(r.indexes.map(e=>Object.freeze({name:e.name,fields:Object.freeze([...e.fields])})))})}return Object.freeze({tables:Object.freeze(t),declarations:e.declarations})}function X(e){return e.kind===`null`||e.kind===`union`&&e.members.some(X)}function Z(e){return e.kind===`id`?[e.tableName]:e.kind===`union`?[...new Set(e.members.flatMap(Z))].sort():[]}function Q(e){let t=structuredClone(e),n=[t];for(;n.length;){let e=n.pop();if(Object(e)!==e)continue;let t=e;Object.freeze(t),n.push(...Object.values(t))}return t}export{g as defineRelations,_ as getRelationExecutor,v as getRelationMetadata};
2
2
  //# sourceMappingURL=relations.mjs.map