{"version":3,"file":"planner.mjs","names":["createPlanner","owned","getRelationExecutor","relations","schema","metadata","getRelationMetadata","inputs","versions","registryVersion","tables","scope","edges","walk","edge","table","name","select","nested","selection","target","group","groups","filter","ast","child","key","version","digest","document","permitted","scalarMatches","residual","validator","where","constraints","parseFilterPlan","input","traversal","ordering","conditions","compiled","client","server","empty","clientIdentity","serverIdentity","evaluateFilter","text","byte"],"sources":["../../src/querying/planner.ts"],"sourcesContent":["import { evaluateFilter } from './shared/evaluate'\nimport type { z } from 'zod'\nimport type { SchemaDefinition, GenericSchema } from 'convex/server'\nimport { type Value } from 'convex/values'\nimport {\n\tgetRelationExecutor,\n\tgetRelationMetadata,\n\ttype RelationRegistryIdentity,\n} from '../relations'\nimport { parseFilterPlan, type FilterAst, type IndexCondition } from './filters'\n\ninterface SelectionTree {\n\t[name: string]: true | SelectionTree\n}\ninterface GroupTree {\n\trelations: Record<string, GroupTree>\n}\n/** What one cursor binding can depend on: a root, the path to its table and what it reads there. */\nexport interface RegistryScope {\n\treadonly root: string\n\treadonly path: readonly string[]\n\treadonly selection: SelectionTree\n\treadonly groups: GroupTree\n\treadonly filters: readonly FilterAst[]\n}\n\nexport type QueryInput = z.input<ReturnType<ReturnType<typeof getRelationExecutor>['pagination']>>\nexport type StoredConstraint = NonNullable<QueryInput['filters']>\n\nexport function createPlanner(\n\tschema: SchemaDefinition<GenericSchema, boolean>,\n\trelations: RelationRegistryIdentity,\n) {\n\tconst owned = getRelationExecutor(relations)\n\towned.assertSchema(schema.tables)\n\tconst metadata = getRelationMetadata(relations)\n\t// Build each immutable filter grammar only when that table is queried. Engine\n\t// declarations also load in mutations, which never need pagination validators.\n\tconst inputs = new Map<string, ReturnType<typeof owned.pagination>>()\n\t// Digests per used scope; a scope is a few sorted names, so the cap only bounds abuse.\n\tconst versions = new Map<string, Promise<string>>()\n\t/**\n\t * The registry version a cursor binds: a digest of the identity of every table\n\t * and edge the query can read. That is its table, the path edges to it, and\n\t * every edge its selection, field groups and relation filters walk, with the\n\t * tables those edges touch. Nothing else can change what such a cursor means.\n\t */\n\tfunction registryVersion(scope: RegistryScope): Promise<string> {\n\t\tconst tables = new Set([scope.root])\n\t\tconst edges = new Map<string, readonly [string, string]>()\n\t\tfunction walk(table: string, name: string): string {\n\t\t\tconst edge = metadata.declarations[table]?.[name]\n\t\t\tif (!edge) throw new Error('INVALID_RELATION')\n\t\t\tedges.set(JSON.stringify([table, name]), [table, name])\n\t\t\treturn edge.target\n\t\t}\n\t\tfunction select(table: string, selection: SelectionTree): void {\n\t\t\tfor (const [name, nested] of Object.entries(selection)) {\n\t\t\t\tconst target = walk(table, name)\n\t\t\t\tif (nested !== true) select(target, nested)\n\t\t\t}\n\t\t}\n\t\tfunction group(table: string, groups: GroupTree): void {\n\t\t\tfor (const [name, nested] of Object.entries(groups.relations))\n\t\t\t\tgroup(walk(table, name), nested)\n\t\t}\n\t\tfunction filter(table: string, ast: FilterAst): void {\n\t\t\tif (ast.kind === 'and' || ast.kind === 'or')\n\t\t\t\tfor (const child of ast.children) filter(table, child)\n\t\t\telse if (ast.kind === 'not' || ast.kind === 'variant') filter(table, ast.child)\n\t\t\telse if (ast.kind === 'relation') {\n\t\t\t\tconst target = walk(table, ast.name)\n\t\t\t\tif (ast.predicate) filter(target, ast.predicate)\n\t\t\t}\n\t\t}\n\t\tlet table = scope.root\n\t\tfor (const name of scope.path) table = walk(table, name)\n\t\ttables.add(table)\n\t\tselect(table, scope.selection)\n\t\tgroup(table, scope.groups)\n\t\tfor (const ast of scope.filters) filter(table, ast)\n\t\tconst key = JSON.stringify([[...tables].sort(), [...edges.keys()].sort()])\n\t\tlet version = versions.get(key)\n\t\tif (!version) {\n\t\t\tversion = digest(owned.scopedIdentity([...tables], [...edges.values()]))\n\t\t\tif (versions.size >= 256) versions.clear()\n\t\t\tversions.set(key, version)\n\t\t}\n\t\treturn version\n\t}\n\treturn {\n\t\tmetadata,\n\t\tselect: owned.select,\n\t\tgroups: owned.groups,\n\t\tvalidateDocument: owned.validateDocument,\n\t\tstreamSchema: owned.streamSchema,\n\t\tregistryVersion,\n\t\tbeforeLeaf(table: string) {\n\t\t\tif (!Object.hasOwn(metadata.tables, table)) throw new Error('Unknown query table')\n\t\t},\n\t\tcomplete(\n\t\t\ttable: string,\n\t\t\tdocument: Record<string, Value>,\n\t\t\tpermitted: boolean,\n\t\t\tresidual: FilterAst,\n\t\t\tgroups: readonly string[] = [],\n\t\t) {\n\t\t\treturn owned.project(\n\t\t\t\ttable,\n\t\t\t\tdocument,\n\t\t\t\t() => permitted && scalarMatches(residual, document),\n\t\t\t\tgroups,\n\t\t\t)\n\t\t},\n\t\tplan(\n\t\t\ttable: string,\n\t\t\tinput: QueryInput,\n\t\t\tconditions: readonly IndexCondition[],\n\t\t\tconstraints: readonly StoredConstraint[],\n\t\t\tordering?: string,\n\t\t\ttraversal: 'root' | 'relation' = 'root',\n\t\t) {\n\t\t\tif (!Object.hasOwn(metadata.tables, table)) throw new Error('Unknown query table')\n\t\t\tlet validator = inputs.get(table)\n\t\t\tif (!validator) {\n\t\t\t\tvalidator = owned.pagination(table)\n\t\t\t\tinputs.set(table, validator)\n\t\t\t}\n\t\t\t// Server constraints are independently validated against stored fields,\n\t\t\t// not the endpoint's public input/filter mask. Client values cannot replace them.\n\t\t\tconst where =\n\t\t\t\tconstraints.length === 1\n\t\t\t\t\t? constraints[0]\n\t\t\t\t\t: constraints.length\n\t\t\t\t\t\t? { and: constraints }\n\t\t\t\t\t\t: undefined\n\t\t\tconst { args, compiled } = parseFilterPlan(\n\t\t\t\tvalidator,\n\t\t\t\tinput,\n\t\t\t\ttraversal === 'relation' && ordering === undefined ? [] : metadata.tables[table].indexes,\n\t\t\t\tconditions,\n\t\t\t\twhere,\n\t\t\t\tordering,\n\t\t\t)\n\t\t\tif (compiled.residual.kind !== 'and') throw new Error('Invalid compiled filter root')\n\t\t\tconst [client, server] = compiled.residual.children\n\t\t\tconst empty: FilterAst = { kind: 'and', children: [] }\n\t\t\tconst clientIdentity = { kind: 'and', children: [client, empty] }\n\t\t\tconst serverIdentity = compiled.sets.size\n\t\t\t\t? {\n\t\t\t\t\t\tkind: 'and',\n\t\t\t\t\t\tchildren: [server, empty],\n\t\t\t\t\t\ttraversal: { version: 2, expansion: compiled.expansion },\n\t\t\t\t\t}\n\t\t\t\t: { kind: 'and', children: [server, empty] }\n\t\t\t// SAFETY: normalized AST nodes contain only validated native scalar Values.\n\t\t\treturn {\n\t\t\t\t...compiled,\n\t\t\t\targs,\n\t\t\t\tclientIdentity: clientIdentity as Value,\n\t\t\t\tserverIdentity: serverIdentity as Value,\n\t\t\t}\n\t\t},\n\t}\n}\n\nexport function scalarMatches(\n\tast: FilterAst,\n\tdocument: Record<string, Value | undefined>,\n): boolean {\n\treturn evaluateFilter(ast, document) === true\n}\n\n/** Lowercase hex SHA-256 of the UTF-8 text. */\nexport async function digest(text: string): Promise<string> {\n\treturn Array.from(\n\t\tnew Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(text))),\n\t\t(byte) => byte.toString(16).padStart(2, '0'),\n\t).join('')\n}\n"],"mappings":"6MA6BA,SAAgBA,EACf,EACA,EACC,CACD,IAAMC,EAAQC,EAAoBC,CAAS,EAC3CF,EAAM,aAAaG,EAAO,MAAM,EAChC,IAAMC,EAAWC,EAAoBH,CAAS,EAGxCI,kBAAS,IAAI,IAEbC,kBAAW,IAAI,IAOrB,SAASC,EAAgB,EAAuC,CAC/D,IAAMC,kBAAS,IAAI,IAAI,CAACC,EAAM,IAAI,CAAC,EAC7BC,kBAAQ,IAAI,IAClB,SAASC,EAAK,EAAe,EAAsB,CAClD,IAAMC,EAAOT,EAAS,aAAaU,EAAM,GAAGC,GAC5C,GAAI,CAACF,EAAM,MAAU,MAAM,kBAAkB,EAE7C,OADAF,EAAM,IAAI,KAAK,UAAU,CAACG,EAAOC,CAAI,CAAC,EAAG,CAACD,EAAOC,CAAI,CAAC,EAC/CF,EAAK,MACb,CACA,SAASG,EAAO,EAAe,EAAgC,C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