@rocicorp/zero 0.19.2025041201 → 0.19.2025041402
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.
- package/out/{chunk-XXFMSZJU.js → chunk-JYQA7DID.js} +2 -2
- package/out/{chunk-WXO6HY3X.js → chunk-KD57S54B.js} +1 -1
- package/out/{chunk-WXO6HY3X.js.map → chunk-KD57S54B.js.map} +2 -2
- package/out/{chunk-UYUOQPYD.js → chunk-QONNL5HY.js} +23 -17
- package/out/{chunk-UYUOQPYD.js.map → chunk-QONNL5HY.js.map} +2 -2
- package/out/{inspector-KHFMOHCD.js → inspector-2LIZBIYB.js} +3 -3
- package/out/react.js +1 -1
- package/out/solid.js +3 -3
- package/out/z2s/src/compiler.d.ts +14 -3
- package/out/z2s/src/compiler.d.ts.map +1 -1
- package/out/z2s/src/compiler.js +34 -23
- package/out/z2s/src/compiler.js.map +1 -1
- package/out/zero-cache/src/server/main.js +1 -1
- package/out/zero-cache/src/server/main.js.map +1 -1
- package/out/zero-cache/src/server/syncer.d.ts.map +1 -1
- package/out/zero-cache/src/server/syncer.js +1 -3
- package/out/zero-cache/src/server/syncer.js.map +1 -1
- package/out/zero-cache/src/services/mutagen/pusher.d.ts +256 -14
- package/out/zero-cache/src/services/mutagen/pusher.d.ts.map +1 -1
- package/out/zero-cache/src/services/mutagen/pusher.js +105 -50
- package/out/zero-cache/src/services/mutagen/pusher.js.map +1 -1
- package/out/zero-cache/src/services/view-syncer/cvr-store.d.ts.map +1 -1
- package/out/zero-cache/src/services/view-syncer/cvr-store.js +2 -1
- package/out/zero-cache/src/services/view-syncer/cvr-store.js.map +1 -1
- package/out/zero-cache/src/services/view-syncer/pipeline-driver.d.ts +6 -2
- package/out/zero-cache/src/services/view-syncer/pipeline-driver.d.ts.map +1 -1
- package/out/zero-cache/src/services/view-syncer/pipeline-driver.js +5 -9
- package/out/zero-cache/src/services/view-syncer/pipeline-driver.js.map +1 -1
- package/out/zero-cache/src/services/view-syncer/view-syncer.d.ts.map +1 -1
- package/out/zero-cache/src/services/view-syncer/view-syncer.js +3 -6
- package/out/zero-cache/src/services/view-syncer/view-syncer.js.map +1 -1
- package/out/zero-cache/src/workers/connection.d.ts +3 -2
- package/out/zero-cache/src/workers/connection.d.ts.map +1 -1
- package/out/zero-cache/src/workers/connection.js +6 -2
- package/out/zero-cache/src/workers/connection.js.map +1 -1
- package/out/zero-cache/src/workers/syncer-ws-message-handler.d.ts +2 -2
- package/out/zero-cache/src/workers/syncer-ws-message-handler.d.ts.map +1 -1
- package/out/zero-cache/src/workers/syncer-ws-message-handler.js +39 -20
- package/out/zero-cache/src/workers/syncer-ws-message-handler.js.map +1 -1
- package/out/zero-cache/src/workers/syncer.d.ts +1 -1
- package/out/zero-cache/src/workers/syncer.d.ts.map +1 -1
- package/out/zero-cache/src/workers/syncer.js +2 -4
- package/out/zero-cache/src/workers/syncer.js.map +1 -1
- package/out/zero-client/src/client/mutation-tracker.d.ts +4 -0
- package/out/zero-client/src/client/mutation-tracker.d.ts.map +1 -1
- package/out/zero-client/src/client/options.d.ts +17 -1
- package/out/zero-client/src/client/options.d.ts.map +1 -1
- package/out/zero-client/src/client/zero.d.ts +1 -1
- package/out/zero-client/src/client/zero.d.ts.map +1 -1
- package/out/zero-pg/src/web.js +1 -1
- package/out/zero-pg/src/web.js.map +1 -1
- package/out/zero-protocol/src/connect.d.ts +10 -0
- package/out/zero-protocol/src/connect.d.ts.map +1 -1
- package/out/zero-protocol/src/connect.js +4 -0
- package/out/zero-protocol/src/connect.js.map +1 -1
- package/out/zero-protocol/src/protocol-version.d.ts +1 -1
- package/out/zero-protocol/src/protocol-version.d.ts.map +1 -1
- package/out/zero-protocol/src/protocol-version.js +2 -1
- package/out/zero-protocol/src/protocol-version.js.map +1 -1
- package/out/zero-protocol/src/up.d.ts +3 -0
- package/out/zero-protocol/src/up.d.ts.map +1 -1
- package/out/zero.js +3 -3
- package/out/zql/src/query/query-impl.d.ts.map +1 -1
- package/out/zql/src/query/query-impl.js.map +1 -1
- package/package.json +1 -1
- /package/out/{chunk-XXFMSZJU.js.map → chunk-JYQA7DID.js.map} +0 -0
- /package/out/{inspector-KHFMOHCD.js.map → inspector-2LIZBIYB.js.map} +0 -0
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../shared/src/valita.ts", "../../zql/src/query/ttl.ts", "../../shared/src/has-own.ts", "../../shared/src/hash.ts", "../../zero-protocol/src/ast.ts", "../../shared/src/arrays.ts", "../../shared/src/json-schema.ts", "../../shared/src/config.ts", "../../shared/src/json.ts", "../../zero-protocol/src/data.ts", "../../zero-schema/src/table-schema.ts", "../../zql/src/query/query-impl.ts", "../../zero-protocol/src/ast-hash.ts", "../../zql/src/ivm/operator.ts", "../../zql/src/ivm/stream.ts", "../../zql/src/ivm/exists.ts", "../../shared/src/iterables.ts", "../../zql/src/ivm/fan-in.ts", "../../zql/src/ivm/fan-out.ts", "../../zql/src/ivm/maybe-split-and-push-edit-change.ts", "../../zql/src/ivm/filter-push.ts", "../../zql/src/ivm/filter.ts", "../../zql/src/ivm/join.ts", "../../zql/src/ivm/skip.ts", "../../zql/src/ivm/take.ts", "../../zql/src/builder/like.ts", "../../zql/src/builder/filter.ts", "../../zql/src/builder/builder.ts", "../../zql/src/ivm/array-view.ts", "../../zql/src/query/expression.ts", "../../zql/src/query/dnf.ts"],
|
|
4
|
-
"sourcesContent": ["import * as v from '@badrap/valita';\n\nexport * from '@badrap/valita';\n\nfunction toDisplay(value: unknown): string {\n switch (typeof value) {\n case 'string':\n case 'number':\n case 'boolean':\n return JSON.stringify(value);\n case 'undefined':\n return 'undefined';\n case 'bigint':\n return value.toString() + 'n';\n default:\n if (value === null) {\n return 'null';\n }\n if (Array.isArray(value)) {\n return 'array';\n }\n return typeof value;\n }\n}\n\ntype Key = string | number;\n\nfunction toDisplayAtPath(v: unknown, path: Key[] | undefined): string {\n if (!path?.length) {\n return toDisplay(v);\n }\n\n let cur = v;\n for (const p of path) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n cur = (cur as any)[p];\n }\n return toDisplay(cur);\n}\n\nfunction displayList<T>(\n word: string,\n expected: T[],\n toDisplay: (x: T) => string | number = x => String(x),\n): string | number {\n if (expected.length === 1) {\n return toDisplay(expected[0]);\n }\n\n const suffix = `${toDisplay(\n expected[expected.length - 2],\n )} ${word} ${toDisplay(expected[expected.length - 1])}`;\n if (expected.length === 2) {\n return suffix;\n }\n return `${expected.slice(0, -2).map(toDisplay).join(', ')}, ${suffix}`;\n}\n\nfunction getMessage(\n err: v.Err | v.ValitaError,\n v: unknown,\n schema: v.Type | v.Optional,\n mode: ParseOptionsMode | undefined,\n): string {\n const firstIssue = err.issues[0];\n const {path} = firstIssue;\n const atPath = path?.length ? ` at ${path.join('.')}` : '';\n\n switch (firstIssue.code) {\n case 'invalid_type':\n return `Expected ${displayList(\n 'or',\n firstIssue.expected,\n )}${atPath}. Got ${toDisplayAtPath(v, path)}`;\n case 'missing_value': {\n const atPath =\n path && path.length > 1 ? ` at ${path.slice(0, -1).join('.')}` : '';\n\n if (firstIssue.path?.length) {\n return `Missing property ${firstIssue.path.at(-1)}${atPath}`;\n }\n return `TODO Unknown missing property${atPath}`;\n }\n\n case 'invalid_literal':\n return `Expected literal value ${displayList(\n 'or',\n firstIssue.expected,\n toDisplay,\n )}${atPath} Got ${toDisplayAtPath(v, path)}`;\n\n case 'invalid_length': {\n return `Expected array with length ${\n firstIssue.minLength === firstIssue.maxLength\n ? firstIssue.minLength\n : `between ${firstIssue.minLength} and ${firstIssue.maxLength}`\n }${atPath}. Got array with length ${(v as {length: number}).length}`;\n }\n\n case 'unrecognized_keys':\n if (firstIssue.keys.length === 1) {\n return `Unexpected property ${firstIssue.keys[0]}${atPath}`;\n }\n return `Unexpected properties ${displayList(\n 'and',\n firstIssue.keys,\n )}${atPath}`;\n\n case 'invalid_union':\n return schema.name === 'union'\n ? getDeepestUnionParseError(v, schema as v.UnionType, mode ?? 'strict')\n : `Invalid union value${atPath}`;\n\n case 'custom_error': {\n const {error} = firstIssue;\n const message = !error\n ? 'unknown'\n : typeof error === 'string'\n ? error\n : (error.message ?? 'unknown');\n return `${message}${atPath}. Got ${toDisplayAtPath(v, path)}`;\n }\n }\n}\n\ntype FailedType = {type: v.Type; err: v.Err};\n\nfunction getDeepestUnionParseError(\n value: unknown,\n schema: v.UnionType,\n mode: ParseOptionsMode,\n): string {\n const failures: FailedType[] = [];\n for (const type of schema.options) {\n const r = type.try(value, {mode});\n if (!r.ok) {\n failures.push({type, err: r});\n }\n }\n if (failures.length) {\n // compare the first and second longest-path errors\n failures.sort(pathCmp);\n if (failures.length === 1 || pathCmp(failures[0], failures[1]) < 0) {\n return getMessage(failures[0].err, value, failures[0].type, mode);\n }\n }\n // paths are equivalent\n try {\n const str = JSON.stringify(value);\n return `Invalid union value: ${str}`;\n } catch (e) {\n // fallback if the value could not be stringified\n return `Invalid union value`;\n }\n}\n\n// Descending-order comparison of Issue paths.\n// * [1, 'a'] sorts before [1]\n// * [1] sorts before [0] (i.e. errors later in the tuple sort before earlier errors)\nfunction pathCmp(a: FailedType, b: FailedType) {\n const aPath = a.err.issues[0].path;\n const bPath = b.err.issues[0].path;\n if (aPath.length !== bPath.length) {\n return bPath.length - aPath.length;\n }\n for (let i = 0; i < aPath.length; i++) {\n if (bPath[i] > aPath[i]) {\n return -1;\n }\n if (bPath[i] < aPath[i]) {\n return 1;\n }\n }\n return 0;\n}\n\n/**\n * 'strip' allows unknown properties and removes unknown properties.\n * 'strict' errors if there are unknown properties.\n * 'passthrough' allows unknown properties.\n */\nexport type ParseOptionsMode = 'passthrough' | 'strict' | 'strip';\n\nexport function parse<T>(\n value: unknown,\n schema: v.Type<T>,\n mode?: ParseOptionsMode,\n): T {\n const res = test(value, schema, mode);\n if (!res.ok) {\n throw new TypeError(res.error);\n }\n return res.value;\n}\n\nexport function is<T>(\n value: unknown,\n schema: v.Type<T>,\n mode?: ParseOptionsMode,\n): value is T {\n return test(value, schema, mode).ok;\n}\n\nexport function assert<T>(\n value: unknown,\n schema: v.Type<T>,\n mode?: ParseOptionsMode,\n): asserts value is T {\n parse(value, schema, mode);\n}\n\ntype Result<T> = {ok: true; value: T} | {ok: false; error: string};\n\nexport function test<T>(\n value: unknown,\n schema: v.Type<T>,\n mode?: ParseOptionsMode,\n): Result<T> {\n const res = schema.try(value, mode ? {mode} : undefined);\n if (!res.ok) {\n return {\n ok: false,\n error: getMessage(res, value, schema, mode),\n };\n }\n return res;\n}\n\n/**\n * Similar to {@link test} but works for AbstractTypes such as Optional.\n * This is for advanced usage. Prefer {@link test} unless you really need\n * to operate directly on an Optional field.\n */\nexport function testOptional<T>(\n value: unknown,\n schema: v.Type<T> | v.Optional<T>,\n mode?: ParseOptionsMode,\n): Result<T | undefined> {\n let flags = 0x1; // FLAG_FORBID_EXTRA_KEYS;\n if (mode === 'passthrough') {\n flags = 0;\n } else if (mode === 'strip') {\n flags = 0x2; // FLAG_STRIP_EXTRA_KEYS;\n }\n const res = schema.func(value, flags);\n if (res === undefined) {\n return {ok: true, value} as Result<T>;\n } else if (res.ok) {\n return res;\n }\n const err = new v.ValitaError(res);\n return {ok: false, error: getMessage(err, value, schema, mode)};\n}\n\n/**\n * Shallowly marks the schema as readonly.\n */\nexport function readonly<T extends v.Type>(t: T): v.Type<Readonly<v.Infer<T>>> {\n return t as v.Type<Readonly<v.Infer<T>>>;\n}\n\nexport function readonlyObject<T extends Record<string, v.Type | v.Optional>>(\n t: T,\n): v.ObjectType<Readonly<T>, undefined> {\n return v.object(t);\n}\n\nexport function readonlyArray<T extends v.Type>(\n t: T,\n): v.Type<readonly v.Infer<T>[]> {\n return v.array(t);\n}\n\nexport function readonlyRecord<T extends v.Type>(\n t: T,\n): v.Type<Readonly<Record<string, v.Infer<T>>>> {\n return v.record(t);\n}\n\n// eslint-disable-next-line @typescript-eslint/naming-convention\nconst AbstractType = Object.getPrototypeOf(\n Object.getPrototypeOf(v.string().optional()),\n).constructor;\n\nexport function instanceOfAbstractType<T = unknown>(\n obj: unknown,\n): obj is v.Type<T> | v.Optional<T> {\n return obj instanceof AbstractType;\n}\n\ntype ObjectShape = Record<string, typeof AbstractType>;\n\n/**\n * Similar to `ObjectType.partial()` except it recurses into nested objects.\n * Rest types are not supported.\n */\nexport function deepPartial<Shape extends ObjectShape>(\n s: v.ObjectType<Shape, undefined>,\n) {\n const shape = {} as Record<string, unknown>;\n for (const [key, type] of Object.entries(s.shape)) {\n if (type.name === 'object') {\n shape[key] = deepPartial(type as v.ObjectType).optional();\n } else {\n shape[key] = type.optional();\n }\n }\n return v.object(shape as {[K in keyof Shape]: v.Optional<v.Infer<Shape[K]>>});\n}\n", "export type TimeUnit = 's' | 'm' | 'h' | 'd' | 'y';\n\n/**\n * Time To Live. This is used for query expiration.\n * - `forever` means the query will never expire.\n * - `none` means the query will expire immediately.\n * - A number means the query will expire after that many milliseconds.\n * - A negative number means the query will never expire, this is same as 'forever'.\n * - A string like `1s` means the query will expire after that many seconds.\n * - A string like `1m` means the query will expire after that many minutes.\n * - A string like `1h` means the query will expire after that many hours.\n * - A string like `1d` means the query will expire after that many days.\n * - A string like `1y` means the query will expire after that many years.\n */\nexport type TTL = `${number}${TimeUnit}` | 'forever' | 'none' | number;\n\nexport const DEFAULT_TTL: TTL = 'none';\n\nconst multiplier = {\n s: 1000,\n m: 60 * 1000,\n h: 60 * 60 * 1000,\n d: 24 * 60 * 60 * 1000,\n y: 365 * 24 * 60 * 60 * 1000,\n} as const;\n\nexport function parseTTL(ttl: TTL): number {\n if (typeof ttl === 'number') {\n return Number.isNaN(ttl) ? 0 : !Number.isFinite(ttl) || ttl < 0 ? -1 : ttl;\n }\n if (ttl === 'none') {\n return 0;\n }\n if (ttl === 'forever') {\n return -1;\n }\n const multi = multiplier[ttl[ttl.length - 1] as TimeUnit];\n return Number(ttl.slice(0, -1)) * multi;\n}\n\nexport function compareTTL(a: TTL, b: TTL): number {\n const ap = parseTTL(a);\n const bp = parseTTL(b);\n if (ap === -1 && bp !== -1) {\n return 1;\n }\n if (ap !== -1 && bp === -1) {\n return -1;\n }\n return ap - bp;\n}\n\nexport function normalizeTTL(ttl: TTL): TTL {\n if (typeof ttl === 'string') {\n return ttl;\n }\n\n if (ttl < 0) {\n return 'forever';\n }\n\n if (ttl === 0) {\n return 'none';\n }\n\n let shortest = ttl.toString();\n const lengthOfNumber = shortest.length;\n for (const unit of ['y', 'd', 'h', 'm', 's'] as const) {\n const multi = multiplier[unit];\n const value = ttl / multi;\n const candidate = `${value}${unit}`;\n if (candidate.length < shortest.length) {\n shortest = candidate;\n }\n }\n\n return (shortest.length < lengthOfNumber ? shortest : ttl) as TTL;\n}\n", "// hasOwn was added in ES2022\nexport const {hasOwn} = Object;\n", "import {xxHash32} from 'js-xxhash';\n\nexport const h32 = (s: string) => xxHash32(s, 0);\nexport const h64 = (s: string) => hash(s, 2);\nexport const h128 = (s: string) => hash(s, 4);\n\n/**\n * xxHash32 only computes 32-bit values. Run it n times with different seeds to\n * get a larger hash with better collision resistance.\n */\nfunction hash(str: string, words: number): bigint {\n let hash = 0n;\n for (let i = 0; i < words; i++) {\n hash = (hash << 32n) + BigInt(xxHash32(str, i));\n }\n return hash;\n}\n", "/**\n * Wire-format representation of the zql AST interface.\n *\n * `v.Type<...>` types are explicitly declared to facilitate Typescript verification\n * that the schemas satisfy the zql type definitions. (Incidentally, explicit types\n * are also required for recursive schema definitions.)\n */\n\nimport {compareUTF8} from 'compare-utf8';\nimport {defined} from '../../shared/src/arrays.ts';\nimport {assert} from '../../shared/src/asserts.ts';\nimport {must} from '../../shared/src/must.ts';\nimport * as v from '../../shared/src/valita.ts';\nimport type {NameMapper} from '../../zero-schema/src/name-mapper.ts';\nimport {rowSchema, type Row} from './data.ts';\n\nexport const selectorSchema = v.string();\nexport const toStaticParam = Symbol();\n\nconst orderingElementSchema = v.readonly(\n v.tuple([selectorSchema, v.union(v.literal('asc'), v.literal('desc'))]),\n);\n\nexport const orderingSchema = v.readonlyArray(orderingElementSchema);\nexport type System = 'permissions' | 'client';\n\nexport const primitiveSchema = v.union(\n v.string(),\n v.number(),\n v.boolean(),\n v.null(),\n);\n\nexport const equalityOpsSchema = v.union(\n v.literal('='),\n v.literal('!='),\n v.literal('IS'),\n v.literal('IS NOT'),\n);\n\nexport const orderOpsSchema = v.union(\n v.literal('<'),\n v.literal('>'),\n v.literal('<='),\n v.literal('>='),\n);\n\nexport const likeOpsSchema = v.union(\n v.literal('LIKE'),\n v.literal('NOT LIKE'),\n v.literal('ILIKE'),\n v.literal('NOT ILIKE'),\n);\n\nexport const inOpsSchema = v.union(v.literal('IN'), v.literal('NOT IN'));\n\nexport const simpleOperatorSchema = v.union(\n equalityOpsSchema,\n orderOpsSchema,\n likeOpsSchema,\n inOpsSchema,\n);\n\nconst literalReferenceSchema: v.Type<LiteralReference> = v.readonlyObject({\n type: v.literal('literal'),\n value: v.union(\n v.string(),\n v.number(),\n v.boolean(),\n v.null(),\n v.readonlyArray(v.union(v.string(), v.number(), v.boolean())),\n ),\n});\nconst columnReferenceSchema: v.Type<ColumnReference> = v.readonlyObject({\n type: v.literal('column'),\n name: v.string(),\n});\n\n/**\n * A parameter is a value that is not known at the time the query is written\n * and is resolved at runtime.\n *\n * Static parameters refer to something provided by the caller.\n * Static parameters are injected when the query pipeline is built from the AST\n * and do not change for the life of that pipeline.\n *\n * An example static parameter is the current authentication data.\n * When a user is authenticated, queries on the server have access\n * to the user's authentication data in order to evaluate authorization rules.\n * Authentication data doesn't change over the life of a query as a change\n * in auth data would represent a log-in / log-out of the user.\n *\n * AncestorParameters refer to rows encountered while running the query.\n * They are used by subqueries to refer to rows emitted by parent queries.\n */\nconst parameterReferenceSchema = v.readonlyObject({\n type: v.literal('static'),\n // The \"namespace\" of the injected parameter.\n // Write authorization will send the value of a row\n // prior to the mutation being run (preMutationRow).\n // Read and write authorization will both send the\n // current authentication data (authData).\n anchor: v.union(v.literal('authData'), v.literal('preMutationRow')),\n field: v.union(v.string(), v.array(v.string())),\n});\n\nconst conditionValueSchema = v.union(\n literalReferenceSchema,\n columnReferenceSchema,\n parameterReferenceSchema,\n);\n\nexport type Parameter = v.Infer<typeof parameterReferenceSchema>;\n\nexport const simpleConditionSchema: v.Type<SimpleCondition> = v.readonlyObject({\n type: v.literal('simple'),\n op: simpleOperatorSchema,\n left: conditionValueSchema,\n right: v.union(parameterReferenceSchema, literalReferenceSchema),\n});\n\ntype ConditionValue = v.Infer<typeof conditionValueSchema>;\n\nexport const correlatedSubqueryConditionOperatorSchema: v.Type<CorrelatedSubqueryConditionOperator> =\n v.union(v.literal('EXISTS'), v.literal('NOT EXISTS'));\n\nexport const correlatedSubqueryConditionSchema: v.Type<CorrelatedSubqueryCondition> =\n v.readonlyObject({\n type: v.literal('correlatedSubquery'),\n related: v.lazy(() => correlatedSubquerySchema),\n op: correlatedSubqueryConditionOperatorSchema,\n });\n\nexport const conditionSchema: v.Type<Condition> = v.union(\n simpleConditionSchema,\n v.lazy(() => conjunctionSchema),\n v.lazy(() => disjunctionSchema),\n correlatedSubqueryConditionSchema,\n);\n\nconst conjunctionSchema: v.Type<Conjunction> = v.readonlyObject({\n type: v.literal('and'),\n conditions: v.readonlyArray(conditionSchema),\n});\n\nconst disjunctionSchema: v.Type<Disjunction> = v.readonlyObject({\n type: v.literal('or'),\n conditions: v.readonlyArray(conditionSchema),\n});\n\nexport type CompoundKey = readonly [string, ...string[]];\n\nfunction mustCompoundKey(field: readonly string[]): CompoundKey {\n assert(Array.isArray(field) && field.length >= 1);\n return field as unknown as CompoundKey;\n}\n\nexport const compoundKeySchema: v.Type<CompoundKey> = v.readonly(\n v.tuple([v.string()]).concat(v.array(v.string())),\n);\n\nconst correlationSchema = v.readonlyObject({\n parentField: compoundKeySchema,\n childField: compoundKeySchema,\n});\n\n// Split out so that its inferred type can be checked against\n// Omit<CorrelatedSubquery, 'correlation'> in ast-type-test.ts.\n// The mutually-recursive reference of the 'other' field to astSchema\n// is the only thing added in v.lazy. The v.lazy is necessary due to the\n// mutually-recursive types, but v.lazy prevents inference of the resulting\n// type.\nexport const correlatedSubquerySchemaOmitSubquery = v.readonlyObject({\n correlation: correlationSchema,\n hidden: v.boolean().optional(),\n system: v.union(v.literal('permissions'), v.literal('client')).optional(),\n});\n\nexport const correlatedSubquerySchema: v.Type<CorrelatedSubquery> =\n correlatedSubquerySchemaOmitSubquery.extend({\n subquery: v.lazy(() => astSchema),\n });\n\nexport const astSchema: v.Type<AST> = v.readonlyObject({\n schema: v.string().optional(),\n table: v.string(),\n alias: v.string().optional(),\n where: conditionSchema.optional(),\n related: v.readonlyArray(correlatedSubquerySchema).optional(),\n limit: v.number().optional(),\n orderBy: orderingSchema.optional(),\n start: v\n .object({\n row: rowSchema,\n exclusive: v.boolean(),\n })\n .optional(),\n});\n\nexport type Bound = {\n row: Row;\n exclusive: boolean;\n};\n\n/**\n * As in SQL you can have multiple orderings. We don't currently\n * support ordering on anything other than the root query.\n */\nexport type OrderPart = readonly [field: string, direction: 'asc' | 'desc'];\nexport type Ordering = readonly OrderPart[];\n\nexport type SimpleOperator = EqualityOps | OrderOps | LikeOps | InOps;\nexport type EqualityOps = '=' | '!=' | 'IS' | 'IS NOT';\nexport type OrderOps = '<' | '>' | '<=' | '>=';\nexport type LikeOps = 'LIKE' | 'NOT LIKE' | 'ILIKE' | 'NOT ILIKE';\nexport type InOps = 'IN' | 'NOT IN';\n\nexport type AST = {\n readonly schema?: string | undefined;\n readonly table: string;\n\n // A query would be aliased if the AST is a subquery.\n // e.g., when two subqueries select from the same table\n // they need an alias to differentiate them.\n // `SELECT\n // [SELECT * FROM issue WHERE issue.id = outer.parentId] AS parent\n // [SELECT * FROM issue WHERE issue.parentId = outer.id] AS children\n // FROM issue as outer`\n readonly alias?: string | undefined;\n\n // `select` is missing given we return all columns for now.\n\n // The PipelineBuilder will pick what to use to correlate\n // a subquery with a parent query. It can choose something from the\n // where conditions or choose the _first_ `related` entry.\n // Choosing the first `related` entry is almost always the best choice if\n // one exists.\n readonly where?: Condition | undefined;\n\n readonly related?: readonly CorrelatedSubquery[] | undefined;\n readonly start?: Bound | undefined;\n readonly limit?: number | undefined;\n readonly orderBy?: Ordering | undefined;\n};\n\nexport type Correlation = {\n readonly parentField: CompoundKey;\n readonly childField: CompoundKey;\n};\n\nexport type CorrelatedSubquery = {\n /**\n * Only equality correlation are supported for now.\n * E.g., direct foreign key relationships.\n */\n readonly correlation: Correlation;\n readonly subquery: AST;\n readonly system?: System | undefined;\n // If a hop in the subquery chain should be hidden from the output view.\n // A common example is junction edges. The query API provides the illusion\n // that they don't exist: `issue.related('labels')` instead of `issue.related('issue_labels').related('labels')`.\n // To maintain this illusion, the junction edge should be hidden.\n // When `hidden` is set to true, this hop will not be included in the output view\n // but its children will be.\n readonly hidden?: boolean | undefined;\n};\n\nexport type ValuePosition = LiteralReference | Parameter | ColumnReference;\n\nexport type ColumnReference = {\n readonly type: 'column';\n /**\n * Not a path yet as we're currently not allowing\n * comparisons across tables. This will need to\n * be a path through the tree in the near future.\n */\n readonly name: string;\n};\n\nexport type LiteralReference = {\n readonly type: 'literal';\n readonly value: LiteralValue;\n};\n\nexport type LiteralValue =\n | string\n | number\n | boolean\n | null\n | ReadonlyArray<string | number | boolean>;\n\n/**\n * Starting only with SimpleCondition for now.\n * ivm1 supports Conjunctions and Disjunctions.\n * We'll support them in the future.\n */\nexport type Condition =\n | SimpleCondition\n | Conjunction\n | Disjunction\n | CorrelatedSubqueryCondition;\n\nexport type SimpleCondition = {\n readonly type: 'simple';\n readonly op: SimpleOperator;\n readonly left: ValuePosition;\n\n /**\n * `null` is absent since we do not have an `IS` or `IS NOT`\n * operator defined and `null != null` in SQL.\n */\n readonly right: Exclude<ValuePosition, ColumnReference>;\n};\n\nexport type Conjunction = {\n type: 'and';\n conditions: readonly Condition[];\n};\n\nexport type Disjunction = {\n type: 'or';\n conditions: readonly Condition[];\n};\n\nexport type CorrelatedSubqueryCondition = {\n type: 'correlatedSubquery';\n related: CorrelatedSubquery;\n op: CorrelatedSubqueryConditionOperator;\n};\n\nexport type CorrelatedSubqueryConditionOperator = 'EXISTS' | 'NOT EXISTS';\n\ninterface ASTTransform {\n tableName(orig: string): string;\n columnName(origTable: string, origColumn: string): string;\n related(subqueries: CorrelatedSubquery[]): readonly CorrelatedSubquery[];\n where(cond: Condition): Condition | undefined;\n // conjunction or disjunction, called when traversing the return value of where()\n conditions(conds: Condition[]): readonly Condition[];\n}\n\nfunction transformAST(ast: AST, transform: ASTTransform): Required<AST> {\n // Name mapping functions (e.g. to server names)\n const {tableName, columnName} = transform;\n const colName = (c: string) => columnName(ast.table, c);\n const key = (table: string, k: CompoundKey) => {\n const serverKey = k.map(col => columnName(table, col));\n return mustCompoundKey(serverKey);\n };\n\n const where = ast.where ? transform.where(ast.where) : undefined;\n const transformed = {\n schema: ast.schema,\n table: tableName(ast.table),\n alias: ast.alias,\n where: where ? transformWhere(where, ast.table, transform) : undefined,\n related: ast.related\n ? transform.related(\n ast.related.map(\n r =>\n ({\n correlation: {\n parentField: key(ast.table, r.correlation.parentField),\n childField: key(r.subquery.table, r.correlation.childField),\n },\n hidden: r.hidden,\n subquery: transformAST(r.subquery, transform),\n system: r.system,\n }) satisfies Required<CorrelatedSubquery>,\n ),\n )\n : undefined,\n start: ast.start\n ? {\n ...ast.start,\n row: Object.fromEntries(\n Object.entries(ast.start.row).map(([col, val]) => [\n colName(col),\n val,\n ]),\n ),\n }\n : undefined,\n limit: ast.limit,\n orderBy: ast.orderBy?.map(([col, dir]) => [colName(col), dir] as const),\n };\n\n return transformed;\n}\n\nfunction transformWhere(\n where: Condition,\n table: string,\n transform: ASTTransform,\n): Condition {\n // Name mapping functions (e.g. to server names)\n const {columnName} = transform;\n const condValue = (c: ConditionValue) =>\n c.type !== 'column' ? c : {...c, name: columnName(table, c.name)};\n const key = (table: string, k: CompoundKey) => {\n const serverKey = k.map(col => columnName(table, col));\n return mustCompoundKey(serverKey);\n };\n\n if (where.type === 'simple') {\n return {...where, left: condValue(where.left)};\n } else if (where.type === 'correlatedSubquery') {\n const {correlation, subquery} = where.related;\n return {\n ...where,\n related: {\n ...where.related,\n correlation: {\n parentField: key(table, correlation.parentField),\n childField: key(subquery.table, correlation.childField),\n },\n subquery: transformAST(subquery, transform),\n },\n };\n }\n\n return {\n type: where.type,\n conditions: transform.conditions(\n where.conditions.map(c => transformWhere(c, table, transform)),\n ),\n };\n}\n\nconst normalizeCache = new WeakMap<AST, Required<AST>>();\n\nconst NORMALIZE_TRANSFORM: ASTTransform = {\n tableName: t => t,\n columnName: (_, c) => c,\n related: sortedRelated,\n where: flattened,\n conditions: c => c.sort(cmpCondition),\n};\n\nexport function normalizeAST(ast: AST): Required<AST> {\n let normalized = normalizeCache.get(ast);\n if (!normalized) {\n normalized = transformAST(ast, NORMALIZE_TRANSFORM);\n normalizeCache.set(ast, normalized);\n }\n return normalized;\n}\n\nexport function mapAST(ast: AST, mapper: NameMapper) {\n return transformAST(ast, {\n tableName: table => mapper.tableName(table),\n columnName: (table, col) => mapper.columnName(table, col),\n related: r => r,\n where: w => w,\n conditions: c => c,\n });\n}\n\nexport function mapCondition(\n cond: Condition,\n table: string,\n mapper: NameMapper,\n) {\n return transformWhere(cond, table, {\n tableName: table => mapper.tableName(table),\n columnName: (table, col) => mapper.columnName(table, col),\n related: r => r,\n where: w => w,\n conditions: c => c,\n });\n}\n\nfunction sortedRelated(\n related: CorrelatedSubquery[],\n): readonly CorrelatedSubquery[] {\n return related.sort(cmpRelated);\n}\n\nfunction cmpCondition(a: Condition, b: Condition): number {\n if (a.type === 'simple') {\n if (b.type !== 'simple') {\n return -1; // Order SimpleConditions first\n }\n\n return (\n compareValuePosition(a.left, b.left) ||\n compareUTF8MaybeNull(a.op, b.op) ||\n compareValuePosition(a.right, b.right)\n );\n }\n\n if (b.type === 'simple') {\n return 1; // Order SimpleConditions first\n }\n\n if (a.type === 'correlatedSubquery') {\n if (b.type !== 'correlatedSubquery') {\n return -1; // Order subquery before conjuctions/disjuctions\n }\n return cmpRelated(a.related, b.related) || compareUTF8MaybeNull(a.op, b.op);\n }\n if (b.type === 'correlatedSubquery') {\n return -1; // Order correlatedSubquery before conjuctions/disjuctions\n }\n\n const val = compareUTF8MaybeNull(a.type, b.type);\n if (val !== 0) {\n return val;\n }\n for (\n let l = 0, r = 0;\n l < a.conditions.length && r < b.conditions.length;\n l++, r++\n ) {\n const val = cmpCondition(a.conditions[l], b.conditions[r]);\n if (val !== 0) {\n return val;\n }\n }\n // prefixes first\n return a.conditions.length - b.conditions.length;\n}\n\nfunction compareValuePosition(a: ValuePosition, b: ValuePosition): number {\n if (a.type !== b.type) {\n return compareUTF8(a.type, b.type);\n }\n switch (a.type) {\n case 'literal':\n assert(b.type === 'literal');\n return compareUTF8(String(a.value), String(b.value));\n case 'column':\n assert(b.type === 'column');\n return compareUTF8(a.name, b.name);\n case 'static':\n throw new Error(\n 'Static parameters should be resolved before normalization',\n );\n }\n}\n\nfunction cmpRelated(a: CorrelatedSubquery, b: CorrelatedSubquery): number {\n return compareUTF8(must(a.subquery.alias), must(b.subquery.alias));\n}\n\n/**\n * Returns a flattened version of the Conditions in which nested Conjunctions with\n * the same operation ('AND' or 'OR') are flattened to the same level. e.g.\n *\n * ```\n * ((a AND b) AND (c AND (d OR (e OR f)))) -> (a AND b AND c AND (d OR e OR f))\n * ```\n *\n * Also flattens singleton Conjunctions regardless of operator, and removes\n * empty Conjunctions.\n */\nfunction flattened(cond: Condition): Condition | undefined {\n if (cond.type === 'simple' || cond.type === 'correlatedSubquery') {\n return cond;\n }\n const conditions = defined(\n cond.conditions.flatMap(c =>\n c.type === cond.type ? c.conditions.map(c => flattened(c)) : flattened(c),\n ),\n );\n\n switch (conditions.length) {\n case 0:\n return undefined;\n case 1:\n return conditions[0];\n default:\n return {\n type: cond.type,\n conditions,\n };\n }\n}\n\nfunction compareUTF8MaybeNull(a: string | null, b: string | null): number {\n if (a !== null && b !== null) {\n return compareUTF8(a, b);\n }\n if (b !== null) {\n return -1;\n }\n if (a !== null) {\n return 1;\n }\n return 0;\n}\n", "import {assert} from './asserts.ts';\n\n/**\n * Returns `arr` as is if none of the elements are `undefined`.\n * Otherwise returns a new array with only defined elements in `arr`.\n */\nexport function defined<T>(arr: (T | undefined)[]): T[] {\n // avoid an array copy if possible\n let i = arr.findIndex(x => x === undefined);\n if (i < 0) {\n return arr as T[];\n }\n const defined: T[] = arr.slice(0, i) as T[];\n for (i++; i < arr.length; i++) {\n const x = arr[i];\n if (x !== undefined) {\n defined.push(x);\n }\n }\n return defined;\n}\n\nexport function areEqual<T>(arr1: readonly T[], arr2: readonly T[]): boolean {\n return arr1.length === arr2.length && arr1.every((e, i) => e === arr2[i]);\n}\n\nexport function zip<T1, T2>(a1: readonly T1[], a2: readonly T2[]): [T1, T2][] {\n assert(a1.length === a2.length);\n const result: [T1, T2][] = [];\n for (let i = 0; i < a1.length; i++) {\n result.push([a1[i], a2[i]]);\n }\n return result;\n}\n\nexport function groupBy<T, K>(\n arr: readonly T[],\n keyFn: (el: T) => K,\n): Map<K, T[]> {\n const groups = new Map<K, T[]>();\n for (const el of arr) {\n const key = keyFn(el);\n let group = groups.get(key);\n if (group === undefined) {\n group = [];\n groups.set(key, group);\n }\n group.push(el);\n }\n return groups;\n}\n", "import * as valita from '@badrap/valita';\nimport {skipAssertJSONValue} from './config.ts';\nimport type {ReadonlyJSONObject, ReadonlyJSONValue} from './json.ts';\nimport {isJSONObject, isJSONValue} from './json.ts';\nimport * as v from './valita.ts';\n\nconst path: (string | number)[] = [];\n\nexport const jsonSchema: valita.Type<ReadonlyJSONValue> = v\n .unknown()\n .chain(v => {\n if (skipAssertJSONValue) {\n return valita.ok(v as ReadonlyJSONValue);\n }\n const rv = isJSONValue(v, path)\n ? valita.ok(v)\n : valita.err({\n message: `Not a JSON value`,\n path: path.slice(),\n });\n path.length = 0;\n return rv;\n });\n\nexport const jsonObjectSchema: valita.Type<ReadonlyJSONObject> = v\n .unknown()\n .chain(v => {\n if (skipAssertJSONValue) {\n return valita.ok(v as ReadonlyJSONObject);\n }\n const rv = isJSONObject(v, path)\n ? valita.ok(v)\n : valita.err({\n message: `Not a JSON object`,\n path: path.slice(),\n });\n path.length = 0;\n return rv;\n });\n", "declare const process: {\n env: {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n NODE_ENV?: string;\n };\n};\n\nexport const isProd = process.env.NODE_ENV === 'production';\n\nexport {isProd as skipAssertJSONValue};\n", "import {assertObject, throwInvalidType} from './asserts.ts';\nimport {skipAssertJSONValue} from './config.ts';\nimport {hasOwn} from './has-own.ts';\n\n/** The values that can be represented in JSON */\nexport type JSONValue =\n | null\n | string\n | boolean\n | number\n | Array<JSONValue>\n | JSONObject;\n\n/**\n * A JSON object. This is a map from strings to JSON values or `undefined`. We\n * allow `undefined` values as a convenience... but beware that the `undefined`\n * values do not round trip to the server. For example:\n *\n * ```\n * // Time t1\n * await tx.set('a', {a: undefined});\n *\n * // time passes, in a new transaction\n * const v = await tx.get('a');\n * console.log(v); // either {a: undefined} or {}\n * ```\n */\nexport type JSONObject = {[key: string]: JSONValue | undefined};\n\n/** Like {@link JSONValue} but deeply readonly */\nexport type ReadonlyJSONValue =\n | null\n | string\n | boolean\n | number\n | ReadonlyArray<ReadonlyJSONValue>\n | ReadonlyJSONObject;\n\n/** Like {@link JSONObject} but deeply readonly */\nexport type ReadonlyJSONObject = {\n readonly [key: string]: ReadonlyJSONValue | undefined;\n};\n\n/**\n * Checks deep equality of two JSON value with (almost) same semantics as\n * `JSON.stringify`. The only difference is that with `JSON.stringify` the\n * ordering of the properties in an object/map/dictionary matters. In\n * {@link deepEqual} the following two values are consider equal, even though the\n * strings JSON.stringify would produce is different:\n *\n * ```js\n * assert(deepEqual(t({a: 1, b: 2}, {b: 2, a: 1}))\n * ```\n */\nexport function deepEqual(\n a: ReadonlyJSONValue | undefined,\n b: ReadonlyJSONValue | undefined,\n): boolean {\n if (a === b) {\n return true;\n }\n\n if (typeof a !== typeof b) {\n return false;\n }\n\n switch (typeof a) {\n case 'boolean':\n case 'number':\n case 'string':\n return false;\n }\n\n // a cannot be undefined here because either a and b are undefined or their\n // types are different.\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n a = a!;\n\n // 'object'\n if (Array.isArray(a)) {\n if (!Array.isArray(b)) {\n return false;\n }\n if (a.length !== b.length) {\n return false;\n }\n for (let i = 0; i < a.length; i++) {\n if (!deepEqual(a[i], b[i])) {\n return false;\n }\n }\n return true;\n }\n\n if (a === null || b === null) {\n return false;\n }\n\n if (Array.isArray(b)) {\n return false;\n }\n\n // We know a and b are objects here but type inference is not smart enough.\n a = a as ReadonlyJSONObject;\n b = b as ReadonlyJSONObject;\n\n // We use for-in loops instead of for of Object.keys() to make sure deepEquals\n // does not allocate any objects.\n\n let aSize = 0;\n for (const key in a) {\n if (hasOwn(a, key)) {\n if (!deepEqual(a[key], b[key])) {\n return false;\n }\n aSize++;\n }\n }\n\n let bSize = 0;\n for (const key in b) {\n if (hasOwn(b, key)) {\n bSize++;\n }\n }\n\n return aSize === bSize;\n}\n\nexport function assertJSONValue(v: unknown): asserts v is JSONValue {\n if (skipAssertJSONValue) {\n return;\n }\n switch (typeof v) {\n case 'boolean':\n case 'number':\n case 'string':\n return;\n case 'object':\n if (v === null) {\n return;\n }\n if (Array.isArray(v)) {\n return assertJSONArray(v);\n }\n return assertObjectIsJSONObject(v as Record<string, unknown>);\n }\n throwInvalidType(v, 'JSON value');\n}\n\nexport function assertJSONObject(v: unknown): asserts v is JSONObject {\n assertObject(v);\n assertObjectIsJSONObject(v);\n}\n\nfunction assertObjectIsJSONObject(\n v: Record<string, unknown>,\n): asserts v is JSONObject {\n for (const k in v) {\n if (hasOwn(v, k)) {\n const value = v[k];\n if (value !== undefined) {\n assertJSONValue(value);\n }\n }\n }\n}\n\nfunction assertJSONArray(v: unknown[]): asserts v is JSONValue[] {\n for (const item of v) {\n assertJSONValue(item);\n }\n}\n\ninterface Path {\n push(key: string | number): void;\n pop(): void;\n}\n\n/**\n * Checks if a value is a JSON value. If there is a value that is not a JSON\n * value, the path parameter is updated to the path of the invalid value.\n */\nexport function isJSONValue(v: unknown, path: Path): v is JSONValue {\n switch (typeof v) {\n case 'boolean':\n case 'number':\n case 'string':\n return true;\n case 'object':\n if (v === null) {\n return true;\n }\n if (Array.isArray(v)) {\n return isJSONArray(v, path);\n }\n return objectIsJSONObject(v as Record<string, unknown>, path);\n }\n return false;\n}\n\nexport function isJSONObject(v: unknown, path: Path): v is JSONObject {\n if (typeof v !== 'object' || v === null) {\n return false;\n }\n return objectIsJSONObject(v as Record<string, unknown>, path);\n}\n\nfunction objectIsJSONObject(\n v: Record<string, unknown>,\n path: Path,\n): v is JSONObject {\n for (const k in v) {\n if (hasOwn(v, k)) {\n path.push(k);\n const value = v[k];\n if (value !== undefined && !isJSONValue(value, path)) {\n return false;\n }\n path.pop();\n }\n }\n return true;\n}\n\nfunction isJSONArray(v: unknown[], path: Path): v is JSONValue[] {\n for (let i = 0; i < v.length; i++) {\n path.push(i);\n if (!isJSONValue(v[i], path)) {\n return false;\n }\n path.pop();\n }\n return true;\n}\n\n/** Basic deep readonly type. It works for {@link JSONValue} types. */\nexport type DeepReadonly<T> = T extends\n | null\n | boolean\n | string\n | number\n | undefined\n ? T\n : {readonly [K in keyof T]: DeepReadonly<T[K]>};\n", "import {jsonSchema} from '../../shared/src/json-schema.ts';\nimport * as v from '../../shared/src/valita.ts';\n\nexport const valueSchema = v.union(jsonSchema, v.undefined());\n\nexport const rowSchema = v.readonlyRecord(valueSchema);\n\n/**\n * The data types that Zero can represent are limited by two things:\n *\n * 1. The underlying Replicache sync layer currently can only represent JSON\n * types. This could possibly be expanded in the future, but we do want to be\n * careful of adding encoding overhead. By using JSON, we are taking\n * advantage of IndexedDB\u2019s fast native JSValue [de]serialization which has\n * historically been a perf advantage for us.\n *\n * 2. IDs in Zero need to be comparable because we use them for sorting and row\n * identity. We could expand the set of allowed value types (to include,\n * i.e., Objects) but we would then need to restrict IDs to only comparable\n * types.\n *\n * These two facts leave us with the following allowed types. Zero's replication\n * layer must convert other types into these for tables to be used with Zero.\n *\n * For developer convenience we also allow `undefined`, which we treat\n * equivalently to `null`.\n */\nexport type Value = v.Infer<typeof valueSchema>;\n\n/**\n * A Row is represented as a JS Object.\n *\n * We do everything in IVM as loosely typed values because these pipelines are\n * going to be constructed at runtime by other code, so type-safety can't buy us\n * anything.\n *\n * Also since the calling code on the client ultimately wants objects to work\n * with we end up with a lot less copies by using objects throughout.\n */\nexport type Row = v.Infer<typeof rowSchema>;\n", "export type {ValueType} from '../../zero-protocol/src/client-schema.ts';\nimport type {ValueType} from '../../zero-protocol/src/client-schema.ts';\nimport type {PrimaryKey} from '../../zero-protocol/src/primary-key.ts';\n\n/**\n * `related` calls need to know what the available relationships are.\n * The `schema` type encodes this information.\n */\nexport type SchemaValue<T = unknown> =\n | {\n type: ValueType;\n serverName?: string | undefined;\n optional?: boolean | undefined;\n }\n | EnumSchemaValue<T>\n | SchemaValueWithCustomType<T>;\n\nexport type SchemaValueWithCustomType<T> = {\n type: ValueType;\n serverName?: string | undefined;\n optional?: boolean;\n customType: T;\n};\n\nexport type EnumSchemaValue<T> = {\n kind: 'enum';\n type: 'string';\n serverName?: string | undefined;\n optional?: boolean;\n customType: T;\n};\n\nexport type TableSchema = {\n readonly name: string;\n readonly serverName?: string | undefined;\n readonly columns: Record<string, SchemaValue>;\n readonly primaryKey: PrimaryKey;\n};\n\nexport type RelationshipsSchema = {\n readonly [name: string]: Relationship;\n};\n\nexport type TypeNameToTypeMap = {\n string: string;\n number: number;\n boolean: boolean;\n null: null;\n\n // In schema-v2, the user will be able to specify the TS type that\n // the JSON should match and `any`` will no\n // longer be used here.\n // ReadOnlyJSONValue is not used as it causes\n // infinite depth errors to pop up for users of our APIs.\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n json: any;\n};\n\nexport type ColumnTypeName<T extends SchemaValue | ValueType> =\n T extends SchemaValue ? T['type'] : T;\n\n/**\n * Given a schema value, return the TypeScript type.\n *\n * This allows us to create the correct return type for a\n * query that has a selection.\n */\nexport type SchemaValueToTSType<T extends SchemaValue | ValueType> =\n T extends ValueType\n ? TypeNameToTypeMap[T]\n : T extends {\n optional: true;\n }\n ?\n | (T extends SchemaValueWithCustomType<infer V>\n ? V\n : TypeNameToTypeMap[ColumnTypeName<T>])\n | null\n : T extends SchemaValueWithCustomType<infer V>\n ? V\n : TypeNameToTypeMap[ColumnTypeName<T>];\n\ntype Connection = {\n readonly sourceField: readonly string[];\n readonly destField: readonly string[];\n readonly destSchema: string;\n readonly cardinality: Cardinality;\n};\n\nexport type Cardinality = 'one' | 'many';\n\nexport type Relationship =\n | readonly [Connection]\n | readonly [Connection, Connection];\n// | readonly [Connection, Connection, Connection];\n\nexport type LastInTuple<T extends Relationship> = T extends readonly [infer L]\n ? L\n : T extends readonly [unknown, infer L]\n ? L\n : T extends readonly [unknown, unknown, infer L]\n ? L\n : never;\n\nexport type AtLeastOne<T> = readonly [T, ...T[]];\n\nexport function atLeastOne<T>(arr: readonly T[]): AtLeastOne<T> {\n if (arr.length === 0) {\n throw new Error('Expected at least one element');\n }\n return arr as AtLeastOne<T>;\n}\n\nexport function isOneHop(r: Relationship): r is readonly [Connection] {\n return r.length === 1;\n}\n\nexport function isTwoHop(\n r: Relationship,\n): r is readonly [Connection, Connection] {\n return r.length === 2;\n}\n\nexport type Opaque<BaseType, BrandType = unknown> = BaseType & {\n readonly [base]: BaseType;\n readonly [brand]: BrandType;\n};\n\ndeclare const base: unique symbol;\ndeclare const brand: unique symbol;\n\nexport type IsOpaque<T> = T extends {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n readonly [brand]: any;\n}\n ? true\n : false;\n\nexport type ExpandRecursiveSkipOpaque<T> =\n IsOpaque<T> extends true\n ? T\n : T extends object\n ? T extends infer O\n ? {[K in keyof O]: ExpandRecursiveSkipOpaque<O[K]>}\n : never\n : T;\n", "/* eslint-disable @typescript-eslint/naming-convention */\n/* eslint-disable @typescript-eslint/no-explicit-any */\nimport {resolver} from '@rocicorp/resolver';\nimport {assert} from '../../../shared/src/asserts.ts';\nimport type {Writable} from '../../../shared/src/writable.ts';\nimport {hashOfAST} from '../../../zero-protocol/src/ast-hash.ts';\nimport type {\n AST,\n CompoundKey,\n Condition,\n Ordering,\n Parameter,\n SimpleOperator,\n System,\n} from '../../../zero-protocol/src/ast.ts';\nimport type {Row as IVMRow} from '../../../zero-protocol/src/data.ts';\nimport type {Schema} from '../../../zero-schema/src/builder/schema-builder.ts';\nimport {\n isOneHop,\n isTwoHop,\n type TableSchema,\n} from '../../../zero-schema/src/table-schema.ts';\nimport {buildPipeline, type BuilderDelegate} from '../builder/builder.ts';\nimport {ArrayView} from '../ivm/array-view.ts';\nimport type {Input} from '../ivm/operator.ts';\nimport type {Format, ViewFactory} from '../ivm/view.ts';\nimport {dnf} from './dnf.ts';\nimport {\n and,\n cmp,\n ExpressionBuilder,\n type ExpressionFactory,\n} from './expression.ts';\nimport {\n type GetFilterType,\n type HumanReadable,\n type PreloadOptions,\n type PullRow,\n type Query,\n} from './query.ts';\nimport {DEFAULT_TTL, type TTL} from './ttl.ts';\nimport type {TypedView} from './typed-view.ts';\n\ntype AnyQuery = Query<Schema, string, any>;\n\nconst astSymbol = Symbol();\n\nexport function ast(query: Query<Schema, string, any>): AST {\n return (query as AbstractQuery<Schema, string>)[astSymbol];\n}\n\nexport function newQuery<\n TSchema extends Schema,\n TTable extends keyof TSchema['tables'] & string,\n>(\n delegate: QueryDelegate,\n schema: TSchema,\n table: TTable,\n): Query<TSchema, TTable> {\n return new QueryImpl(delegate, schema, table, {table}, defaultFormat);\n}\n\nfunction newQueryWithDetails<\n TSchema extends Schema,\n TTable extends keyof TSchema['tables'] & string,\n TReturn,\n>(\n delegate: QueryDelegate,\n schema: TSchema,\n tableName: TTable,\n ast: AST,\n format: Format,\n): QueryImpl<TSchema, TTable, TReturn> {\n return new QueryImpl(delegate, schema, tableName, ast, format);\n}\n\nexport type CommitListener = () => void;\nexport type GotCallback = (got: boolean) => void;\nexport interface QueryDelegate extends BuilderDelegate {\n addServerQuery(\n ast: AST,\n ttl: TTL,\n gotCallback?: GotCallback | undefined,\n ): () => void;\n updateServerQuery(ast: AST, ttl: TTL): void;\n onTransactionCommit(cb: CommitListener): () => void;\n batchViewUpdates<T>(applyViewUpdates: () => T): T;\n onQueryMaterialized(hash: string, ast: AST, duration: number): void;\n}\n\nexport function staticParam(\n anchorClass: 'authData' | 'preMutationRow',\n field: string | string[],\n): Parameter {\n return {\n type: 'static',\n anchor: anchorClass,\n // for backwards compatibility\n field: field.length === 1 ? field[0] : field,\n };\n}\n\nexport const SUBQ_PREFIX = 'zsubq_';\n\nexport const defaultFormat = {singular: false, relationships: {}} as const;\n\nexport abstract class AbstractQuery<\n TSchema extends Schema,\n TTable extends keyof TSchema['tables'] & string,\n TReturn = PullRow<TTable, TSchema>,\n> implements Query<TSchema, TTable, TReturn>\n{\n readonly #schema: TSchema;\n readonly #tableName: TTable;\n readonly #ast: AST;\n readonly format: Format;\n #hash: string = '';\n\n constructor(schema: TSchema, tableName: TTable, ast: AST, format: Format) {\n this.#schema = schema;\n this.#tableName = tableName;\n this.#ast = ast;\n this.format = format;\n }\n\n get [astSymbol](): AST {\n return this.#ast;\n }\n\n hash(): string {\n if (!this.#hash) {\n this.#hash = hashOfAST(this._completeAst());\n }\n return this.#hash;\n }\n\n protected abstract _system: System;\n\n protected abstract _newQuery<\n TSchema extends Schema,\n TTable extends keyof TSchema['tables'] & string,\n TReturn,\n >(\n schema: TSchema,\n table: TTable,\n ast: AST,\n format: Format,\n ): AbstractQuery<TSchema, TTable, TReturn>;\n\n one(): Query<TSchema, TTable, TReturn | undefined> {\n return this._newQuery(\n this.#schema,\n this.#tableName,\n {\n ...this.#ast,\n limit: 1,\n },\n {\n ...this.format,\n singular: true,\n },\n );\n }\n whereExists(\n relationship: string,\n cb?: (q: AnyQuery) => AnyQuery,\n ): Query<TSchema, TTable, TReturn> {\n return this.where(({exists}) => exists(relationship, cb));\n }\n\n related(relationship: string, cb?: (q: AnyQuery) => AnyQuery): AnyQuery {\n if (relationship.startsWith(SUBQ_PREFIX)) {\n throw new Error(\n `Relationship names may not start with \"${SUBQ_PREFIX}\". That is a reserved prefix.`,\n );\n }\n cb = cb ?? (q => q);\n\n const related = this.#schema.relationships[this.#tableName][relationship];\n assert(related, 'Invalid relationship');\n if (isOneHop(related)) {\n const {destSchema, destField, sourceField, cardinality} = related[0];\n let q: AnyQuery = this._newQuery(\n this.#schema,\n destSchema,\n {\n table: destSchema,\n alias: relationship,\n },\n {\n relationships: {},\n singular: cardinality === 'one',\n },\n );\n if (cardinality === 'one') {\n q = q.one();\n }\n const sq = cb(q) as AbstractQuery<Schema, string>;\n assert(\n isCompoundKey(sourceField),\n 'The source of a relationship must specify at last 1 field',\n );\n assert(\n isCompoundKey(destField),\n 'The destination of a relationship must specify at last 1 field',\n );\n assert(\n sourceField.length === destField.length,\n 'The source and destination of a relationship must have the same number of fields',\n );\n\n return this._newQuery(\n this.#schema,\n this.#tableName,\n {\n ...this.#ast,\n related: [\n ...(this.#ast.related ?? []),\n {\n system: this._system,\n correlation: {\n parentField: sourceField,\n childField: destField,\n },\n subquery: addPrimaryKeysToAst(\n this.#schema.tables[destSchema],\n sq.#ast,\n ),\n },\n ],\n },\n {\n ...this.format,\n relationships: {\n ...this.format.relationships,\n [relationship]: sq.format,\n },\n },\n );\n }\n\n if (isTwoHop(related)) {\n const [firstRelation, secondRelation] = related;\n const {destSchema} = secondRelation;\n const junctionSchema = firstRelation.destSchema;\n const sq = cb(\n this._newQuery(\n this.#schema,\n destSchema,\n {\n table: destSchema,\n alias: relationship,\n },\n {\n relationships: {},\n singular: secondRelation.cardinality === 'one',\n },\n ),\n ) as unknown as QueryImpl<Schema, string>;\n\n assert(isCompoundKey(firstRelation.sourceField), 'Invalid relationship');\n assert(isCompoundKey(firstRelation.destField), 'Invalid relationship');\n assert(isCompoundKey(secondRelation.sourceField), 'Invalid relationship');\n assert(isCompoundKey(secondRelation.destField), 'Invalid relationship');\n\n return this._newQuery(\n this.#schema,\n this.#tableName,\n {\n ...this.#ast,\n related: [\n ...(this.#ast.related ?? []),\n {\n system: this._system,\n correlation: {\n parentField: firstRelation.sourceField,\n childField: firstRelation.destField,\n },\n hidden: true,\n subquery: {\n table: junctionSchema,\n alias: relationship,\n orderBy: addPrimaryKeys(\n this.#schema.tables[junctionSchema],\n undefined,\n ),\n related: [\n {\n system: this._system,\n correlation: {\n parentField: secondRelation.sourceField,\n childField: secondRelation.destField,\n },\n subquery: addPrimaryKeysToAst(\n this.#schema.tables[destSchema],\n sq.#ast,\n ),\n },\n ],\n },\n },\n ],\n },\n {\n ...this.format,\n relationships: {\n ...this.format.relationships,\n [relationship]: sq.format,\n },\n },\n );\n }\n\n throw new Error(`Invalid relationship ${relationship}`);\n }\n\n where(\n fieldOrExpressionFactory: string | ExpressionFactory<TSchema, TTable>,\n opOrValue?: SimpleOperator | GetFilterType<any, any, any> | Parameter,\n value?: GetFilterType<any, any, any> | Parameter,\n ): Query<TSchema, TTable, TReturn> {\n let cond: Condition;\n\n if (typeof fieldOrExpressionFactory === 'function') {\n cond = fieldOrExpressionFactory(\n new ExpressionBuilder(this._exists) as ExpressionBuilder<\n TSchema,\n TTable\n >,\n );\n } else {\n assert(opOrValue !== undefined, 'Invalid condition');\n cond = cmp(fieldOrExpressionFactory, opOrValue, value);\n }\n\n const existingWhere = this.#ast.where;\n if (existingWhere) {\n cond = and(existingWhere, cond);\n }\n\n return this._newQuery(\n this.#schema,\n this.#tableName,\n {\n ...this.#ast,\n where: dnf(cond),\n },\n this.format,\n );\n }\n\n start(\n row: Partial<PullRow<TTable, TSchema>>,\n opts?: {inclusive: boolean} | undefined,\n ): Query<TSchema, TTable, TReturn> {\n return this._newQuery(\n this.#schema,\n this.#tableName,\n {\n ...this.#ast,\n start: {\n row,\n exclusive: !opts?.inclusive,\n },\n },\n this.format,\n );\n }\n\n limit(limit: number): Query<TSchema, TTable, TReturn> {\n if (limit < 0) {\n throw new Error('Limit must be non-negative');\n }\n if ((limit | 0) !== limit) {\n throw new Error('Limit must be an integer');\n }\n\n return this._newQuery(\n this.#schema,\n this.#tableName,\n {\n ...this.#ast,\n limit,\n },\n this.format,\n );\n }\n\n orderBy<TSelector extends keyof TSchema['tables'][TTable]['columns']>(\n field: TSelector,\n direction: 'asc' | 'desc',\n ): Query<TSchema, TTable, TReturn> {\n return this._newQuery(\n this.#schema,\n this.#tableName,\n {\n ...this.#ast,\n orderBy: [...(this.#ast.orderBy ?? []), [field as string, direction]],\n },\n this.format,\n );\n }\n\n protected _exists = (\n relationship: string,\n cb: (query: AnyQuery) => AnyQuery = q => q,\n ): Condition => {\n const related = this.#schema.relationships[this.#tableName][relationship];\n assert(related, 'Invalid relationship');\n\n if (isOneHop(related)) {\n const {destSchema, sourceField, destField} = related[0];\n assert(isCompoundKey(sourceField), 'Invalid relationship');\n assert(isCompoundKey(destField), 'Invalid relationship');\n\n const sq = cb(\n this._newQuery(\n this.#schema,\n destSchema,\n {\n table: destSchema,\n alias: `${SUBQ_PREFIX}${relationship}`,\n },\n defaultFormat,\n ),\n ) as unknown as QueryImpl<any, any>;\n return {\n type: 'correlatedSubquery',\n related: {\n system: this._system,\n correlation: {\n parentField: sourceField,\n childField: destField,\n },\n subquery: addPrimaryKeysToAst(\n this.#schema.tables[destSchema],\n sq.#ast,\n ),\n },\n op: 'EXISTS',\n };\n }\n\n if (isTwoHop(related)) {\n const [firstRelation, secondRelation] = related;\n assert(isCompoundKey(firstRelation.sourceField), 'Invalid relationship');\n assert(isCompoundKey(firstRelation.destField), 'Invalid relationship');\n assert(isCompoundKey(secondRelation.sourceField), 'Invalid relationship');\n assert(isCompoundKey(secondRelation.destField), 'Invalid relationship');\n const {destSchema} = secondRelation;\n const junctionSchema = firstRelation.destSchema;\n const queryToDest = cb(\n this._newQuery(\n this.#schema,\n destSchema,\n {\n table: destSchema,\n alias: `${SUBQ_PREFIX}${relationship}`,\n },\n defaultFormat,\n ),\n );\n\n return {\n type: 'correlatedSubquery',\n related: {\n system: this._system,\n correlation: {\n parentField: firstRelation.sourceField,\n childField: firstRelation.destField,\n },\n subquery: {\n table: junctionSchema,\n alias: `${SUBQ_PREFIX}${relationship}`,\n orderBy: addPrimaryKeys(\n this.#schema.tables[junctionSchema],\n undefined,\n ),\n where: {\n type: 'correlatedSubquery',\n related: {\n system: this._system,\n correlation: {\n parentField: secondRelation.sourceField,\n childField: secondRelation.destField,\n },\n\n subquery: addPrimaryKeysToAst(\n this.#schema.tables[destSchema],\n (queryToDest as QueryImpl<any, any>).#ast,\n ),\n },\n op: 'EXISTS',\n },\n },\n },\n op: 'EXISTS',\n };\n }\n\n throw new Error(`Invalid relationship ${relationship}`);\n };\n\n #completedAST: AST | undefined;\n\n protected _completeAst(): AST {\n if (!this.#completedAST) {\n const finalOrderBy = addPrimaryKeys(\n this.#schema.tables[this.#tableName],\n this.#ast.orderBy,\n );\n if (this.#ast.start) {\n const {row} = this.#ast.start;\n const narrowedRow: Writable<IVMRow> = {};\n for (const [field] of finalOrderBy) {\n narrowedRow[field] = row[field];\n }\n this.#completedAST = {\n ...this.#ast,\n start: {\n ...this.#ast.start,\n row: narrowedRow,\n },\n orderBy: finalOrderBy,\n };\n } else {\n this.#completedAST = {\n ...this.#ast,\n orderBy: addPrimaryKeys(\n this.#schema.tables[this.#tableName],\n this.#ast.orderBy,\n ),\n };\n }\n }\n return this.#completedAST;\n }\n\n then<TResult1 = HumanReadable<TReturn>, TResult2 = never>(\n onFulfilled?:\n | ((value: HumanReadable<TReturn>) => TResult1 | PromiseLike<TResult1>)\n | undefined\n | null,\n onRejected?:\n | ((reason: any) => TResult2 | PromiseLike<TResult2>)\n | undefined\n | null,\n ): PromiseLike<TResult1 | TResult2> {\n return this.run().then(onFulfilled, onRejected);\n }\n\n abstract materialize(): TypedView<HumanReadable<TReturn>>;\n abstract materialize<T>(factory: ViewFactory<TSchema, TTable, TReturn, T>): T;\n abstract run(): Promise<HumanReadable<TReturn>>;\n abstract preload(): {\n cleanup: () => void;\n complete: Promise<void>;\n };\n}\n\nconst completedAstSymbol = Symbol();\n\nexport function completedAST(q: Query<Schema, string, any>) {\n return (q as QueryImpl<Schema, string>)[completedAstSymbol];\n}\n\nexport class QueryImpl<\n TSchema extends Schema,\n TTable extends keyof TSchema['tables'] & string,\n TReturn = PullRow<TTable, TSchema>,\n> extends AbstractQuery<TSchema, TTable, TReturn> {\n readonly #delegate: QueryDelegate;\n\n constructor(\n delegate: QueryDelegate,\n schema: TSchema,\n tableName: TTable,\n ast: AST,\n format: Format,\n ) {\n super(schema, tableName, ast, format);\n this.#delegate = delegate;\n }\n\n protected readonly _system = 'client';\n\n get [completedAstSymbol](): AST {\n return this._completeAst();\n }\n\n protected _newQuery<TSchema extends Schema, TTable extends string, TReturn>(\n schema: TSchema,\n tableName: TTable,\n ast: AST,\n format: Format,\n ): QueryImpl<TSchema, TTable, TReturn> {\n return newQueryWithDetails(this.#delegate, schema, tableName, ast, format);\n }\n\n materialize<T>(\n factoryOrTTL?: ViewFactory<TSchema, TTable, TReturn, T> | TTL,\n ttl: TTL = DEFAULT_TTL,\n ): T {\n const t0 = Date.now();\n let factory: ViewFactory<TSchema, TTable, TReturn, T> | undefined;\n if (typeof factoryOrTTL === 'function') {\n factory = factoryOrTTL;\n } else {\n ttl = factoryOrTTL ?? DEFAULT_TTL;\n }\n const ast = this._completeAst();\n const queryCompleteResolver = resolver<true>();\n let queryGot = false;\n const removeServerQuery = this.#delegate.addServerQuery(ast, ttl, got => {\n if (got) {\n const t1 = Date.now();\n this.#delegate.onQueryMaterialized(this.hash(), ast, t1 - t0);\n queryGot = true;\n queryCompleteResolver.resolve(true);\n }\n });\n\n const updateTTL = (newTTL: TTL) => {\n this.#delegate.updateServerQuery(ast, newTTL);\n };\n\n const input = buildPipeline(ast, this.#delegate);\n let removeCommitObserver: (() => void) | undefined;\n\n const onDestroy = () => {\n input.destroy();\n removeCommitObserver?.();\n removeServerQuery();\n };\n\n const view = this.#delegate.batchViewUpdates(() =>\n (factory ?? arrayViewFactory)(\n this,\n input,\n this.format,\n onDestroy,\n cb => {\n removeCommitObserver = this.#delegate.onTransactionCommit(cb);\n },\n queryGot || queryCompleteResolver.promise,\n updateTTL,\n ),\n );\n\n return view as T;\n }\n\n run(): Promise<HumanReadable<TReturn>> {\n const v: TypedView<HumanReadable<TReturn>> = this.materialize();\n const ret = v.data;\n v.destroy();\n return Promise.resolve(ret);\n }\n\n preload(options?: PreloadOptions): {\n cleanup: () => void;\n complete: Promise<void>;\n } {\n const {resolve, promise: complete} = resolver<void>();\n const ast = this._completeAst();\n const unsub = this.#delegate.addServerQuery(\n ast,\n options?.ttl ?? DEFAULT_TTL,\n got => {\n if (got) {\n resolve();\n }\n },\n );\n return {\n cleanup: unsub,\n complete,\n };\n }\n}\n\nfunction addPrimaryKeys(\n schema: TableSchema,\n orderBy: Ordering | undefined,\n): Ordering {\n orderBy = orderBy ?? [];\n const {primaryKey} = schema;\n const primaryKeysToAdd = new Set(primaryKey);\n\n for (const [field] of orderBy) {\n primaryKeysToAdd.delete(field);\n }\n\n if (primaryKeysToAdd.size === 0) {\n return orderBy;\n }\n\n return [\n ...orderBy,\n ...[...primaryKeysToAdd].map(key => [key, 'asc'] as [string, 'asc']),\n ];\n}\n\nfunction addPrimaryKeysToAst(schema: TableSchema, ast: AST): AST {\n return {\n ...ast,\n orderBy: addPrimaryKeys(schema, ast.orderBy),\n };\n}\n\nfunction arrayViewFactory<\n TSchema extends Schema,\n TTable extends string,\n TReturn,\n>(\n _query: AbstractQuery<TSchema, TTable, TReturn>,\n input: Input,\n format: Format,\n onDestroy: () => void,\n onTransactionCommit: (cb: () => void) => void,\n queryComplete: true | Promise<true>,\n updateTTL: (ttl: TTL) => void,\n): TypedView<HumanReadable<TReturn>> {\n const v = new ArrayView<HumanReadable<TReturn>>(\n input,\n format,\n queryComplete,\n updateTTL,\n );\n v.onDestroy = onDestroy;\n onTransactionCommit(() => {\n v.flush();\n });\n return v;\n}\n\nfunction isCompoundKey(field: readonly string[]): field is CompoundKey {\n return Array.isArray(field) && field.length >= 1;\n}\n", "import {h64} from '../../shared/src/hash.ts';\nimport {normalizeAST, type AST} from './ast.ts';\n\nconst hashCache = new WeakMap<AST, string>();\n\nexport function hashOfAST(ast: AST): string {\n const normalized = normalizeAST(ast);\n const cached = hashCache.get(normalized);\n if (cached) {\n return cached;\n }\n const hash = h64(JSON.stringify(normalized)).toString(36);\n hashCache.set(normalized, hash);\n return hash;\n}\n", "import type {JSONValue} from '../../../shared/src/json.ts';\nimport type {Row} from '../../../zero-protocol/src/data.ts';\nimport type {Change} from './change.ts';\nimport type {Constraint} from './constraint.ts';\nimport {type Node} from './data.ts';\nimport type {SourceSchema} from './schema.ts';\nimport type {Stream} from './stream.ts';\n\n/**\n * Input to an operator.\n */\nexport interface Input {\n /** The schema of the data this input returns. */\n getSchema(): SourceSchema;\n\n /**\n * Fetch data. May modify the data in place.\n * Returns nodes sorted in order of `SourceSchema.compareRows`.\n */\n fetch(req: FetchRequest): Stream<Node>;\n\n /**\n * Cleanup maintained state. This is called when `output` will no longer need\n * the data returned by {@linkcode fetch}. The receiving operator should clean up any\n * resources it has allocated to service such requests.\n *\n * This is different from {@linkcode destroy} which means this input will no longer\n * be called at all, for any input.\n *\n * Returns the same thing as {@linkcode fetch}. This allows callers to properly\n * propagate the cleanup message through the graph.\n */\n cleanup(req: FetchRequest): Stream<Node>;\n\n /** Tell the input where to send its output. */\n setOutput(output: Output): void;\n\n /**\n * Completely destroy the input. Destroying an input\n * causes it to call destroy on its upstreams, fully\n * cleaning up a pipeline.\n */\n destroy(): void;\n}\n\nexport type FetchRequest = {\n readonly constraint?: Constraint | undefined;\n /** If supplied, `start.row` must have previously been output by fetch or push. */\n readonly start?: Start | undefined;\n\n /** Whether to fetch in reverse order of the SourceSchema's sort. */\n readonly reverse?: boolean | undefined;\n};\n\nexport type Start = {\n readonly row: Row;\n readonly basis: 'at' | 'after';\n};\n\n/**\n * An output for an operator. Typically another Operator but can also be\n * the code running the pipeline.\n */\nexport interface Output {\n /**\n * Push incremental changes to data previously received with fetch().\n * Consumers must apply all pushed changes or incremental result will\n * be incorrect.\n * Callers must maintain some invariants for correct operation:\n * - Only add rows which do not already exist (by deep equality).\n * - Only remove rows which do exist (by deep equality).\n */\n push(change: Change): void;\n}\n\n/**\n * An implementation of Output that throws if pushed to. It is used as the\n * initial value for for an operator's output before it is set.\n */\nexport const throwOutput: Output = {\n push(_change: Change): void {\n throw new Error('Output not set');\n },\n};\n\n/**\n * Operators are arranged into pipelines.\n * They are stateful.\n * Each operator is an input to the next operator in the chain and an output\n * to the previous.\n */\nexport interface Operator extends Input, Output {}\n\n/**\n * Operators get access to storage that they can store their internal\n * state in.\n */\nexport interface Storage {\n set(key: string, value: JSONValue): void;\n get(key: string, def?: JSONValue): JSONValue | undefined;\n /**\n * If options is not specified, defaults to scanning all entries.\n */\n scan(options?: {prefix: string}): Stream<[string, JSONValue]>;\n del(key: string): void;\n}\n", "/**\n * streams are lazy forward-only iterables.\n * Once a stream reaches the end it can't be restarted.\n * They are iterable, not iterator, so that they can be used in for-each,\n * and so that we know when consumer has stopped iterating the stream. This allows us\n * to clean up resources like sql statements.\n */\nexport type Stream<T> = Iterable<T>;\n\nexport function* take<T>(stream: Stream<T>, limit: number): Stream<T> {\n if (limit < 1) {\n return;\n }\n let count = 0;\n for (const v of stream) {\n yield v;\n if (++count === limit) {\n break;\n }\n }\n}\n\nexport function first<T>(stream: Stream<T>): T | undefined {\n const it = stream[Symbol.iterator]();\n const {value} = it.next();\n it.return?.();\n return value;\n}\n", "import {areEqual} from '../../../shared/src/arrays.ts';\nimport {assert, unreachable} from '../../../shared/src/asserts.ts';\nimport type {CompoundKey} from '../../../zero-protocol/src/ast.ts';\nimport {type Change} from './change.ts';\nimport {\n drainStreams,\n normalizeUndefined,\n type Node,\n type NormalizedValue,\n} from './data.ts';\nimport {\n throwOutput,\n type FetchRequest,\n type Input,\n type Operator,\n type Output,\n type Storage,\n} from './operator.ts';\nimport type {SourceSchema} from './schema.ts';\nimport {first} from './stream.ts';\n\ntype SizeStorageKeyPrefix = `row/${string}/`;\n/**\n * Key is of format\n * `row/${JSON.stringify(parentJoinKeyValues)}/${JSON.stringify(primaryKeyValues)}`\n * This format allows us to look up an existing cached size for a given set of\n * `parentJoinKeyValues` by scanning for prefix\n * `row/${JSON.stringify(parentJoinKeyValues)}/` and using the first result, and\n * to look up the cached size for a specific row by the full key.\n * If the parent join and primary key are the same, then format is changed to\n * `row//${JSON.stringify(primaryKeyValues)}` to shorten the key, since there\n * is no point in looking up an existing cached size by\n * `parentJoinKeyValues` if the specific rows cached size is missing.\n */\ntype SizeStorageKey = `${SizeStorageKeyPrefix}${string}`;\n\ninterface ExistsStorage {\n get(key: SizeStorageKey): number | undefined;\n set(key: SizeStorageKey, value: number): void;\n del(key: SizeStorageKey): void;\n scan({prefix}: {prefix: SizeStorageKeyPrefix}): Iterable<[string, number]>;\n}\n\n/**\n * The Exists operator filters data based on whether or not a relationship is\n * non-empty.\n */\nexport class Exists implements Operator {\n readonly #input: Input;\n readonly #relationshipName: string;\n readonly #storage: ExistsStorage;\n readonly #not: boolean;\n readonly #parentJoinKey: CompoundKey;\n readonly #noSizeReuse: boolean;\n\n #output: Output = throwOutput;\n\n /**\n * This instance variable is `true` when this operator is processing a `push`,\n * and is used to disable reuse of cached sizes across rows with the\n * same parent join key value.\n * This is necessary because during a push relationships can be inconsistent\n * due to push communicating changes (which may change multiple Nodes) one\n * Node at a time.\n */\n #inPush = false;\n\n constructor(\n input: Input,\n storage: Storage,\n relationshipName: string,\n parentJoinKey: CompoundKey,\n type: 'EXISTS' | 'NOT EXISTS',\n ) {\n this.#input = input;\n this.#relationshipName = relationshipName;\n this.#input.setOutput(this);\n this.#storage = storage as ExistsStorage;\n assert(\n this.#input.getSchema().relationships[relationshipName],\n `Input schema missing ${relationshipName}`,\n );\n this.#not = type === 'NOT EXISTS';\n this.#parentJoinKey = parentJoinKey;\n\n // If the parentJoinKey is the primary key, no sense in trying to reuse.\n this.#noSizeReuse = areEqual(\n parentJoinKey,\n this.#input.getSchema().primaryKey,\n );\n }\n\n setOutput(output: Output) {\n this.#output = output;\n }\n\n destroy(): void {\n this.#input.destroy();\n }\n\n getSchema(): SourceSchema {\n return this.#input.getSchema();\n }\n\n *fetch(req: FetchRequest) {\n for (const node of this.#input.fetch(req)) {\n if (this.#filter(node)) {\n yield node;\n }\n }\n }\n\n *cleanup(req: FetchRequest) {\n for (const node of this.#input.cleanup(req)) {\n if (this.#filter(node)) {\n yield node;\n } else {\n drainStreams(node);\n }\n this.#delSize(node);\n }\n }\n\n push(change: Change) {\n this.#inPush = true;\n try {\n switch (change.type) {\n // add, remove and edit cannot change the size of the\n // this.#relationshipName relationship, so simply #pushWithFilter\n case 'add':\n case 'edit': {\n this.#pushWithFilter(change);\n return;\n }\n case 'remove': {\n const size = this.#getSize(change.node);\n // If size is undefined, this operator has not output\n // this row before and so it is unnecessary to output a remove for\n // it.\n if (size === undefined) {\n return;\n }\n this.#pushWithFilter(change, size);\n this.#delSize(change.node);\n return;\n }\n case 'child':\n // Only add and remove child changes for the\n // this.#relationshipName relationship, can change the size\n // of the this.#relationshipName relationship, for other\n // child changes simply #pushWithFilter\n if (\n change.child.relationshipName !== this.#relationshipName ||\n change.child.change.type === 'edit' ||\n change.child.change.type === 'child'\n ) {\n this.#pushWithFilter(change);\n return;\n }\n switch (change.child.change.type) {\n case 'add': {\n let size = this.#getSize(change.node);\n if (size !== undefined) {\n size++;\n this.#setSize(change.node, size);\n } else {\n size = this.#fetchSize(change.node);\n }\n if (size === 1) {\n if (this.#not) {\n // Since the add child change currently being processed is not\n // pushed to output, the added child needs to be excluded from\n // the remove being pushed to output (since the child has\n // never been added to the output).\n this.#output.push({\n type: 'remove',\n node: {\n row: change.node.row,\n relationships: {\n ...change.node.relationships,\n [this.#relationshipName]: () => [],\n },\n },\n });\n } else {\n this.#output.push({\n type: 'add',\n node: change.node,\n });\n }\n } else {\n this.#pushWithFilter(change, size);\n }\n return;\n }\n case 'remove': {\n let size = this.#getSize(change.node);\n if (size !== undefined) {\n assert(size > 0);\n size--;\n this.#setSize(change.node, size);\n } else {\n size = this.#fetchSize(change.node);\n }\n if (size === 0) {\n if (this.#not) {\n this.#output.push({\n type: 'add',\n node: change.node,\n });\n } else {\n // Since the remove child change currently being processed is\n // not pushed to output, the removed child needs to be added to\n // the remove being pushed to output.\n this.#output.push({\n type: 'remove',\n node: {\n row: change.node.row,\n relationships: {\n ...change.node.relationships,\n [this.#relationshipName]: () => [\n change.child.change.node,\n ],\n },\n },\n });\n }\n } else {\n this.#pushWithFilter(change, size);\n }\n return;\n }\n }\n return;\n default:\n unreachable(change);\n }\n } finally {\n this.#inPush = false;\n }\n }\n\n /**\n * Returns whether or not the node's this.#relationshipName\n * relationship passes the exist/not exists filter condition.\n * If the optional `size` is passed it is used.\n * Otherwise, if there is a stored size for the row it is used.\n * Otherwise the size is computed by streaming the node's\n * relationship with this.#relationshipName (this computed size is also\n * stored).\n */\n #filter(node: Node, size?: number): boolean {\n const exists = (size ?? this.#getOrFetchSize(node)) > 0;\n return this.#not ? !exists : exists;\n }\n\n /**\n * Pushes a change if this.#filter is true for its row.\n */\n #pushWithFilter(change: Change, size?: number): void {\n if (this.#filter(change.node, size)) {\n this.#output.push(change);\n }\n }\n\n #getSize(node: Node): number | undefined {\n return this.#storage.get(this.#makeSizeStorageKey(node));\n }\n\n #setSize(node: Node, size: number) {\n this.#storage.set(this.#makeSizeStorageKey(node), size);\n }\n\n #delSize(node: Node) {\n this.#storage.del(this.#makeSizeStorageKey(node));\n }\n\n #getOrFetchSize(node: Node): number {\n const size = this.#getSize(node);\n if (size !== undefined) {\n return size;\n }\n return this.#fetchSize(node);\n }\n\n #fetchSize(node: Node): number {\n if (!this.#noSizeReuse && !this.#inPush) {\n const cachedSizeEntry = first(\n this.#storage.scan({\n prefix: this.#makeSizeStorageKeyPrefix(node),\n }),\n );\n if (cachedSizeEntry !== undefined) {\n this.#setSize(node, cachedSizeEntry[1]);\n return cachedSizeEntry[1];\n }\n }\n\n const relationship = node.relationships[this.#relationshipName];\n assert(relationship);\n let size = 0;\n for (const _relatedNode of relationship()) {\n size++;\n }\n\n this.#setSize(node, size);\n return size;\n }\n\n #makeSizeStorageKeyPrefix(node: Node): SizeStorageKeyPrefix {\n return `row/${\n this.#noSizeReuse\n ? ''\n : JSON.stringify(this.#getKeyValues(node, this.#parentJoinKey))\n }/`;\n }\n\n #makeSizeStorageKey(node: Node): SizeStorageKey {\n return `${this.#makeSizeStorageKeyPrefix(node)}${JSON.stringify(\n this.#getKeyValues(node, this.#input.getSchema().primaryKey),\n )}`;\n }\n\n #getKeyValues(node: Node, def: CompoundKey): NormalizedValue[] {\n const values: NormalizedValue[] = [];\n for (const key of def) {\n values.push(normalizeUndefined(node.row[key]));\n }\n return values;\n }\n}\n", "import {assert} from './asserts.ts';\n\nexport function* joinIterables<T>(...iters: Iterable<T>[]) {\n for (const iter of iters) {\n yield* iter;\n }\n}\n\nfunction* filterIter<T>(\n iter: Iterable<T>,\n p: (t: T, index: number) => boolean,\n): Iterable<T> {\n let index = 0;\n for (const t of iter) {\n if (p(t, index++)) {\n yield t;\n }\n }\n}\n\nfunction* mapIter<T, U>(\n iter: Iterable<T>,\n f: (t: T, index: number) => U,\n): Iterable<U> {\n let index = 0;\n for (const t of iter) {\n yield f(t, index++);\n }\n}\n\nexport function first<T>(stream: Iterable<T>): T | undefined {\n const it = stream[Symbol.iterator]();\n const {value} = it.next();\n it.return?.();\n return value;\n}\n\n// TODO(arv): Use ES2024 Iterable.from when available\n// https://github.com/tc39/proposal-iterator-helpers\n\nclass IterWrapper<T> implements Iterable<T> {\n iter: Iterable<T>;\n constructor(iter: Iterable<T>) {\n this.iter = iter;\n }\n\n [Symbol.iterator]() {\n return this.iter[Symbol.iterator]();\n }\n\n map<U>(f: (t: T, index: number) => U): IterWrapper<U> {\n return new IterWrapper(mapIter(this.iter, f));\n }\n\n filter(p: (t: T, index: number) => boolean): IterWrapper<T> {\n return new IterWrapper(filterIter(this.iter, p));\n }\n}\n\nexport function wrapIterable<T>(iter: Iterable<T>): IterWrapper<T> {\n return new IterWrapper(iter);\n}\n\nexport function* mergeIterables<T>(\n iterables: Iterable<T>[],\n comparator: (l: T, r: T) => number,\n distinct = false,\n): IterableIterator<T> {\n const iterators = iterables.map(i => i[Symbol.iterator]());\n try {\n const current = iterators.map(i => i.next());\n let lastYielded: T | undefined;\n while (current.some(c => !c.done)) {\n const min = current.reduce(\n (acc: [T, number] | undefined, c, i): [T, number] | undefined => {\n if (c.done) {\n return acc;\n }\n if (acc === undefined || comparator(c.value, acc[0]) < 0) {\n return [c.value, i];\n }\n return acc;\n },\n undefined,\n );\n\n assert(min !== undefined, 'min is undefined');\n current[min[1]] = iterators[min[1]].next();\n if (\n lastYielded !== undefined &&\n distinct &&\n comparator(lastYielded, min[0]) === 0\n ) {\n continue;\n }\n lastYielded = min[0];\n yield min[0];\n }\n } finally {\n for (const it of iterators) {\n it.return?.();\n }\n }\n}\n", "import {assert} from '../../../shared/src/asserts.ts';\nimport {mergeIterables} from '../../../shared/src/iterables.ts';\nimport {must} from '../../../shared/src/must.ts';\nimport type {Change} from './change.ts';\nimport type {Node} from './data.ts';\nimport type {FanOut} from './fan-out.ts';\nimport {\n throwOutput,\n type FetchRequest,\n type Input,\n type Operator,\n type Output,\n} from './operator.ts';\nimport type {SourceSchema} from './schema.ts';\nimport type {Stream} from './stream.ts';\n\n/**\n * The FanIn operator merges multiple streams into one.\n * It eliminates duplicates and must be paired with a fan-out operator\n * somewhere upstream of the fan-in.\n *\n * issue\n * |\n * fan-out\n * / \\\n * a b\n * \\ /\n * fan-in\n * |\n */\nexport class FanIn implements Operator {\n readonly #inputs: readonly Input[];\n readonly #schema: SourceSchema;\n #output: Output = throwOutput;\n #accumulatedPushes: Change[];\n\n constructor(fanOut: FanOut, inputs: Input[]) {\n this.#inputs = inputs;\n this.#schema = fanOut.getSchema();\n for (const input of inputs) {\n input.setOutput(this);\n assert(this.#schema === input.getSchema(), `Schema mismatch in fan-in`);\n }\n this.#accumulatedPushes = [];\n }\n\n setOutput(output: Output): void {\n this.#output = output;\n }\n\n destroy(): void {\n for (const input of this.#inputs) {\n input.destroy();\n }\n }\n\n getSchema() {\n return this.#schema;\n }\n\n fetch(req: FetchRequest): Stream<Node> {\n return this.#fetchOrCleanup(input => input.fetch(req));\n }\n\n cleanup(req: FetchRequest): Stream<Node> {\n return this.#fetchOrCleanup(input => input.cleanup(req));\n }\n\n *#fetchOrCleanup(streamProvider: (input: Input) => Stream<Node>) {\n const iterables = this.#inputs.map(input => streamProvider(input));\n yield* mergeIterables(\n iterables,\n (l, r) => must(this.#schema).compareRows(l.row, r.row),\n true,\n );\n }\n\n push(change: Change) {\n this.#accumulatedPushes.push(change);\n }\n\n fanOutDonePushingToAllBranches(fanOutChangeType: Change['type']) {\n if (this.#inputs.length === 0) {\n assert(\n this.#accumulatedPushes.length === 0,\n 'If there are no inputs then fan-in should not receive any pushes.',\n );\n return;\n }\n\n if (this.#accumulatedPushes.length === 0) {\n // It is possible for no forks to pass along the push.\n // E.g., if no filters match in any fork.\n return;\n }\n\n // collapse down to a single change per type\n const candidatesToPush = new Map<Change['type'], Change>();\n for (const change of this.#accumulatedPushes) {\n if (fanOutChangeType === 'child' && change.type !== 'child') {\n assert(\n candidatesToPush.has(change.type) === false,\n () =>\n `Fan-in:child expected at most one ${change.type} when fan-out is of type child`,\n );\n }\n candidatesToPush.set(change.type, change);\n }\n\n this.#accumulatedPushes = [];\n\n const types = [...candidatesToPush.keys()];\n /**\n * Based on the received `fanOutChangeType` only certain output types are valid.\n *\n * - remove must result in all removes\n * - add must result in all adds\n * - edit must result in add or removes or edits\n * - child must result in a single add or single remove or many child changes\n */\n switch (fanOutChangeType) {\n case 'remove':\n assert(\n types.length === 1 && types[0] === 'remove',\n 'Fan-in:remove expected all removes',\n );\n this.#output.push(must(candidatesToPush.get('remove')));\n return;\n case 'add':\n assert(\n types.length === 1 && types[0] === 'add',\n 'Fan-in:add expected all adds',\n );\n this.#output.push(must(candidatesToPush.get('add')));\n return;\n case 'edit': {\n assert(\n types.every(\n type => type === 'add' || type === 'remove' || type === 'edit',\n ),\n 'Fan-in:edit expected all adds, removes, or edits',\n );\n const addChange = candidatesToPush.get('add');\n const removeChange = candidatesToPush.get('remove');\n const editChange = candidatesToPush.get('edit');\n\n // If an `edit` is present, it supersedes `add` and `remove`\n // as it semantically represents both.\n if (editChange) {\n this.#output.push(editChange);\n return;\n }\n\n // If `edit` didn't make it through but both `add` and `remove` did,\n // convert back to an edit.\n //\n // When can this happen?\n //\n // EDIT old: a=1, new: a=2\n // |\n // FanOut\n // / \\\n // a=1 a=2\n // | |\n // remove add\n // \\ /\n // FanIn\n //\n // The left filter converts the edit into a remove.\n // The right filter converts the edit into an add.\n if (addChange && removeChange) {\n this.#output.push({\n type: 'edit',\n node: addChange.node,\n oldNode: removeChange.node,\n } as const);\n return;\n }\n\n this.#output.push(must(addChange ?? removeChange));\n return;\n }\n case 'child': {\n assert(\n types.every(\n type =>\n type === 'add' || // exists can change child to add or remove\n type === 'remove' || // exists can change child to add or remove\n type === 'child', // other operators may preserve the child change\n ),\n 'Fan-in:child expected all adds, removes, or children',\n );\n assert(\n types.length <= 2,\n 'Fan-in:child expected at most 2 types on a child change from fan-out',\n );\n\n // If any branch preserved the original child change, that takes precedence over all other changes.\n const childChange = candidatesToPush.get('child');\n if (childChange) {\n this.#output.push(childChange);\n return;\n }\n\n const addChange = candidatesToPush.get('add');\n const removeChange = candidatesToPush.get('remove');\n\n assert(\n addChange === undefined || removeChange === undefined,\n 'Fan-in:child expected either add or remove, not both',\n );\n\n this.#output.push(must(addChange ?? removeChange));\n return;\n }\n default:\n fanOutChangeType satisfies never;\n }\n }\n}\n", "import {must} from '../../../shared/src/must.ts';\nimport type {Change} from './change.ts';\nimport type {FanIn} from './fan-in.ts';\nimport type {FetchRequest, Input, Operator, Output} from './operator.ts';\n\n/**\n * Forks a stream into multiple streams.\n * Is meant to be paired with a `FanIn` operator which will\n * later merge the forks back together.\n */\nexport class FanOut implements Operator {\n readonly #input: Input;\n readonly #outputs: Output[] = [];\n #fanIn: FanIn | undefined;\n #destroyCount: number = 0;\n\n constructor(input: Input) {\n this.#input = input;\n input.setOutput(this);\n }\n\n setFanIn(fanIn: FanIn) {\n this.#fanIn = fanIn;\n }\n\n setOutput(output: Output): void {\n this.#outputs.push(output);\n }\n\n destroy(): void {\n if (this.#destroyCount < this.#outputs.length) {\n if (this.#destroyCount === 0) {\n this.#input.destroy();\n }\n ++this.#destroyCount;\n } else {\n throw new Error('FanOut already destroyed once for each output');\n }\n }\n\n getSchema() {\n return this.#input.getSchema();\n }\n\n fetch(req: FetchRequest) {\n return this.#input.fetch(req);\n }\n\n cleanup(req: FetchRequest) {\n return this.#input.cleanup(req);\n }\n\n push(change: Change) {\n for (const out of this.#outputs) {\n out.push(change);\n }\n must(\n this.#fanIn,\n 'fan-out must have a corresponding fan-in set!',\n ).fanOutDonePushingToAllBranches(change.type);\n }\n}\n", "import type {Row} from '../../../zero-protocol/src/data.ts';\nimport type {EditChange} from './change.ts';\nimport type {Output} from './operator.ts';\n\n/**\n * This takes an {@linkcode EditChange} and a predicate that determines if a row\n * should be present based on the row's data. It then splits the change and\n * pushes the appropriate changes to the output based on the predicate.\n */\nexport function maybeSplitAndPushEditChange(\n change: EditChange,\n predicate: (row: Row) => boolean,\n output: Output,\n) {\n const oldWasPresent = predicate(change.oldNode.row);\n const newIsPresent = predicate(change.node.row);\n\n if (oldWasPresent && newIsPresent) {\n output.push(change);\n } else if (oldWasPresent && !newIsPresent) {\n output.push({\n type: 'remove',\n node: change.oldNode,\n });\n } else if (!oldWasPresent && newIsPresent) {\n output.push({\n type: 'add',\n node: change.node,\n });\n }\n}\n", "import {unreachable} from '../../../shared/src/asserts.ts';\nimport type {Row} from '../../../zero-protocol/src/data.ts';\nimport type {Change} from './change.ts';\nimport {maybeSplitAndPushEditChange} from './maybe-split-and-push-edit-change.ts';\nimport type {Output} from './operator.ts';\n\nexport function filterPush(\n change: Change,\n output: Output,\n predicate?: ((row: Row) => boolean) | undefined,\n) {\n if (!predicate) {\n output.push(change);\n return;\n }\n switch (change.type) {\n case 'add':\n case 'remove':\n if (predicate(change.node.row)) {\n output.push(change);\n }\n break;\n case 'child':\n if (predicate(change.node.row)) {\n output.push(change);\n }\n break;\n case 'edit':\n maybeSplitAndPushEditChange(change, predicate, output);\n break;\n default:\n unreachable(change);\n }\n}\n", "import type {Row} from '../../../zero-protocol/src/data.ts';\nimport type {Change} from './change.ts';\nimport {drainStreams} from './data.ts';\nimport {filterPush} from './filter-push.ts';\nimport {\n throwOutput,\n type FetchRequest,\n type Input,\n type Operator,\n type Output,\n} from './operator.ts';\nimport type {SourceSchema} from './schema.ts';\n\n/**\n * The Filter operator filters data through a predicate. It is stateless.\n *\n * The predicate must be pure.\n */\nexport class Filter implements Operator {\n readonly #input: Input;\n readonly #predicate: (row: Row) => boolean;\n\n #output: Output = throwOutput;\n\n constructor(input: Input, predicate: (row: Row) => boolean) {\n this.#input = input;\n this.#predicate = predicate;\n input.setOutput(this);\n }\n\n setOutput(output: Output) {\n this.#output = output;\n }\n\n destroy(): void {\n this.#input.destroy();\n }\n\n getSchema(): SourceSchema {\n return this.#input.getSchema();\n }\n\n *fetch(req: FetchRequest) {\n for (const node of this.#input.fetch(req)) {\n if (this.#predicate(node.row)) {\n yield node;\n }\n }\n }\n\n *cleanup(req: FetchRequest) {\n for (const node of this.#input.cleanup(req)) {\n if (this.#predicate(node.row)) {\n yield node;\n } else {\n drainStreams(node);\n }\n }\n }\n\n push(change: Change) {\n filterPush(change, this.#output, this.#predicate);\n }\n}\n", "import {assert, unreachable} from '../../../shared/src/asserts.ts';\nimport type {CompoundKey, System} from '../../../zero-protocol/src/ast.ts';\nimport type {Row, Value} from '../../../zero-protocol/src/data.ts';\nimport type {PrimaryKey} from '../../../zero-protocol/src/primary-key.ts';\nimport type {Change, ChildChange} from './change.ts';\nimport {compareValues, valuesEqual, type Node} from './data.ts';\nimport {\n throwOutput,\n type FetchRequest,\n type Input,\n type Output,\n type Storage,\n} from './operator.ts';\nimport type {SourceSchema} from './schema.ts';\nimport {take, type Stream} from './stream.ts';\n\ntype Args = {\n parent: Input;\n child: Input;\n storage: Storage;\n // The order of the keys does not have to match but the length must match.\n // The nth key in parentKey corresponds to the nth key in childKey.\n parentKey: CompoundKey;\n childKey: CompoundKey;\n\n // TODO: Change parentKey & childKey to a correlation\n\n relationshipName: string;\n hidden: boolean;\n system: System;\n};\n\ntype ChildChangeOverlay = {\n change: Change;\n position: Row | undefined;\n};\n\n/**\n * The Join operator joins the output from two upstream inputs. Zero's join\n * is a little different from SQL's join in that we output hierarchical data,\n * not a flat table. This makes it a lot more useful for UI programming and\n * avoids duplicating tons of data like left join would.\n *\n * The Nodes output from Join have a new relationship added to them, which has\n * the name #relationshipName. The value of the relationship is a stream of\n * child nodes which are the corresponding values from the child source.\n */\nexport class Join implements Input {\n readonly #parent: Input;\n readonly #child: Input;\n readonly #storage: Storage;\n readonly #parentKey: CompoundKey;\n readonly #childKey: CompoundKey;\n readonly #relationshipName: string;\n readonly #schema: SourceSchema;\n\n #output: Output = throwOutput;\n\n #inprogressChildChange: ChildChangeOverlay | undefined;\n\n constructor({\n parent,\n child,\n storage,\n parentKey,\n childKey,\n relationshipName,\n hidden,\n system,\n }: Args) {\n assert(parent !== child, 'Parent and child must be different operators');\n assert(\n parentKey.length === childKey.length,\n 'The parentKey and childKey keys must have same length',\n );\n this.#parent = parent;\n this.#child = child;\n this.#storage = storage;\n this.#parentKey = parentKey;\n this.#childKey = childKey;\n this.#relationshipName = relationshipName;\n\n const parentSchema = parent.getSchema();\n const childSchema = child.getSchema();\n this.#schema = {\n ...parentSchema,\n relationships: {\n ...parentSchema.relationships,\n [relationshipName]: {\n ...childSchema,\n isHidden: hidden,\n system,\n },\n },\n };\n\n parent.setOutput({\n push: (change: Change) => this.#pushParent(change),\n });\n child.setOutput({\n push: (change: Change) => this.#pushChild(change),\n });\n }\n\n destroy(): void {\n this.#parent.destroy();\n this.#child.destroy();\n }\n\n setOutput(output: Output): void {\n this.#output = output;\n }\n\n getSchema(): SourceSchema {\n return this.#schema;\n }\n\n *fetch(req: FetchRequest): Stream<Node> {\n for (const parentNode of this.#parent.fetch(req)) {\n yield this.#processParentNode(\n parentNode.row,\n parentNode.relationships,\n 'fetch',\n );\n }\n }\n\n *cleanup(req: FetchRequest): Stream<Node> {\n for (const parentNode of this.#parent.cleanup(req)) {\n yield this.#processParentNode(\n parentNode.row,\n parentNode.relationships,\n 'cleanup',\n );\n }\n }\n\n #pushParent(change: Change): void {\n switch (change.type) {\n case 'add':\n this.#output.push({\n type: 'add',\n node: this.#processParentNode(\n change.node.row,\n change.node.relationships,\n 'fetch',\n ),\n });\n break;\n case 'remove':\n this.#output.push({\n type: 'remove',\n node: this.#processParentNode(\n change.node.row,\n change.node.relationships,\n 'cleanup',\n ),\n });\n break;\n case 'child':\n this.#output.push({\n type: 'child',\n node: this.#processParentNode(\n change.node.row,\n change.node.relationships,\n 'fetch',\n ),\n child: change.child,\n });\n break;\n case 'edit': {\n // Assert the edit could not change the relationship.\n assert(\n rowEqualsForCompoundKey(\n change.oldNode.row,\n change.node.row,\n this.#parentKey,\n ),\n `Parent edit must not change relationship.`,\n );\n this.#output.push({\n type: 'edit',\n oldNode: this.#processParentNode(\n change.oldNode.row,\n change.oldNode.relationships,\n 'cleanup',\n ),\n node: this.#processParentNode(\n change.node.row,\n change.node.relationships,\n 'fetch',\n ),\n });\n break;\n }\n default:\n unreachable(change);\n }\n }\n\n #pushChild(change: Change): void {\n const pushChildChange = (childRow: Row, change: Change) => {\n this.#inprogressChildChange = {\n change,\n position: undefined,\n };\n try {\n const parentNodes = this.#parent.fetch({\n constraint: Object.fromEntries(\n this.#parentKey.map((key, i) => [key, childRow[this.#childKey[i]]]),\n ),\n });\n\n for (const parentNode of parentNodes) {\n this.#inprogressChildChange.position = parentNode.row;\n const childChange: ChildChange = {\n type: 'child',\n node: this.#processParentNode(\n parentNode.row,\n parentNode.relationships,\n 'fetch',\n ),\n child: {\n relationshipName: this.#relationshipName,\n change,\n },\n };\n this.#output.push(childChange);\n }\n } finally {\n this.#inprogressChildChange = undefined;\n }\n };\n\n switch (change.type) {\n case 'add':\n case 'remove':\n pushChildChange(change.node.row, change);\n break;\n case 'child':\n pushChildChange(change.node.row, change);\n break;\n case 'edit': {\n const childRow = change.node.row;\n const oldChildRow = change.oldNode.row;\n // Assert the edit could not change the relationship.\n assert(\n rowEqualsForCompoundKey(oldChildRow, childRow, this.#childKey),\n 'Child edit must not change relationship.',\n );\n pushChildChange(childRow, change);\n break;\n }\n\n default:\n unreachable(change);\n }\n }\n\n *#generateChildStreamWithOverlay(\n stream: Stream<Node>,\n overlay: Change,\n ): Stream<Node> {\n let applied = false;\n let editOldApplied = false;\n let editNewApplied = false;\n for (const child of stream) {\n let yieldChild = true;\n if (!applied) {\n switch (overlay.type) {\n case 'add': {\n if (\n this.#child\n .getSchema()\n .compareRows(overlay.node.row, child.row) === 0\n ) {\n applied = true;\n yieldChild = false;\n }\n break;\n }\n case 'remove': {\n if (\n this.#child.getSchema().compareRows(overlay.node.row, child.row) <\n 0\n ) {\n applied = true;\n yield overlay.node;\n }\n break;\n }\n case 'edit': {\n if (\n this.#child\n .getSchema()\n .compareRows(overlay.oldNode.row, child.row) < 0\n ) {\n editOldApplied = true;\n if (editNewApplied) {\n applied = true;\n }\n yield overlay.oldNode;\n }\n if (\n this.#child\n .getSchema()\n .compareRows(overlay.node.row, child.row) === 0\n ) {\n editNewApplied = true;\n if (editOldApplied) {\n applied = true;\n }\n yieldChild = false;\n }\n break;\n }\n case 'child': {\n if (\n this.#child\n .getSchema()\n .compareRows(overlay.node.row, child.row) === 0\n ) {\n applied = true;\n yield {\n row: child.row,\n relationships: {\n ...child.relationships,\n [overlay.child.relationshipName]: () =>\n this.#generateChildStreamWithOverlay(\n child.relationships[overlay.child.relationshipName](),\n overlay.child.change,\n ),\n },\n };\n yieldChild = false;\n }\n break;\n }\n }\n }\n if (yieldChild) {\n yield child;\n }\n }\n if (!applied) {\n if (overlay.type === 'remove') {\n applied = true;\n yield overlay.node;\n } else if (overlay.type === 'edit') {\n assert(editNewApplied);\n editOldApplied = true;\n applied = true;\n yield overlay.oldNode;\n }\n }\n\n assert(applied);\n }\n\n #processParentNode(\n parentNodeRow: Row,\n parentNodeRelations: Record<string, () => Stream<Node>>,\n mode: ProcessParentMode,\n ): Node {\n let method: ProcessParentMode = mode;\n let storageUpdated = false;\n const childStream = () => {\n if (!storageUpdated) {\n if (mode === 'cleanup') {\n this.#storage.del(\n makeStorageKey(\n this.#parentKey,\n this.#parent.getSchema().primaryKey,\n parentNodeRow,\n ),\n );\n const empty =\n [\n ...take(\n this.#storage.scan({\n prefix: makeStorageKeyPrefix(parentNodeRow, this.#parentKey),\n }),\n 1,\n ),\n ].length === 0;\n method = empty ? 'cleanup' : 'fetch';\n }\n\n storageUpdated = true;\n // Defer the work to update storage until the child stream\n // is actually accessed\n if (mode === 'fetch') {\n this.#storage.set(\n makeStorageKey(\n this.#parentKey,\n this.#parent.getSchema().primaryKey,\n parentNodeRow,\n ),\n true,\n );\n }\n }\n\n const stream = this.#child[method]({\n constraint: Object.fromEntries(\n this.#childKey.map((key, i) => [\n key,\n parentNodeRow[this.#parentKey[i]],\n ]),\n ),\n });\n\n if (\n this.#inprogressChildChange &&\n this.#isJoinMatch(\n parentNodeRow,\n this.#inprogressChildChange.change.node.row,\n ) &&\n this.#inprogressChildChange.position &&\n this.#schema.compareRows(\n parentNodeRow,\n this.#inprogressChildChange.position,\n ) > 0\n ) {\n return this.#generateChildStreamWithOverlay(\n stream,\n this.#inprogressChildChange.change,\n );\n }\n return stream;\n };\n\n return {\n row: parentNodeRow,\n relationships: {\n ...parentNodeRelations,\n [this.#relationshipName]: childStream,\n },\n };\n }\n\n #isJoinMatch(parent: Row, child: Row) {\n for (let i = 0; i < this.#parentKey.length; i++) {\n if (!valuesEqual(parent[this.#parentKey[i]], child[this.#childKey[i]])) {\n return false;\n }\n }\n return true;\n }\n}\n\ntype ProcessParentMode = 'fetch' | 'cleanup';\n\n/** Exported for testing. */\nexport function makeStorageKeyForValues(values: readonly Value[]): string {\n const json = JSON.stringify(['pKeySet', ...values]);\n return json.substring(1, json.length - 1) + ',';\n}\n\n/** Exported for testing. */\nexport function makeStorageKeyPrefix(row: Row, key: CompoundKey): string {\n return makeStorageKeyForValues(key.map(k => row[k]));\n}\n\n/** Exported for testing.\n * This storage key tracks the primary keys seen for each unique\n * value joined on. This is used to know when to cleanup a child's state.\n */\nexport function makeStorageKey(\n key: CompoundKey,\n primaryKey: PrimaryKey,\n row: Row,\n): string {\n const values: Value[] = key.map(k => row[k]);\n for (const key of primaryKey) {\n values.push(row[key]);\n }\n return makeStorageKeyForValues(values);\n}\n\nfunction rowEqualsForCompoundKey(a: Row, b: Row, key: CompoundKey): boolean {\n for (let i = 0; i < key.length; i++) {\n if (compareValues(a[key[i]], b[key[i]]) !== 0) {\n return false;\n }\n }\n return true;\n}\n", "import type {Row} from '../../../zero-protocol/src/data.ts';\nimport type {AddChange, Change, ChildChange, RemoveChange} from './change.ts';\nimport type {Comparator, Node} from './data.ts';\nimport {maybeSplitAndPushEditChange} from './maybe-split-and-push-edit-change.ts';\nimport {\n throwOutput,\n type FetchRequest,\n type Input,\n type Operator,\n type Output,\n type Start,\n} from './operator.ts';\nimport type {SourceSchema} from './schema.ts';\nimport type {Stream} from './stream.ts';\n\nexport type Bound = {\n row: Row;\n exclusive: boolean;\n};\n\n/**\n * Skip sets the start position for the pipeline. No rows before the bound will\n * be output.\n */\nexport class Skip implements Operator {\n readonly #input: Input;\n readonly #bound: Bound;\n readonly #comparator: Comparator;\n\n #output: Output = throwOutput;\n\n constructor(input: Input, bound: Bound) {\n this.#input = input;\n this.#bound = bound;\n this.#comparator = input.getSchema().compareRows;\n input.setOutput(this);\n }\n\n getSchema(): SourceSchema {\n return this.#input.getSchema();\n }\n\n fetch(req: FetchRequest): Stream<Node> {\n return this.#fetchOrCleanup('fetch', req);\n }\n\n cleanup(req: FetchRequest): Stream<Node> {\n return this.#fetchOrCleanup('fetch', req);\n }\n\n *#fetchOrCleanup(method: 'fetch' | 'cleanup', req: FetchRequest) {\n const start = this.#getStart(req);\n if (start === 'empty') {\n return;\n }\n const nodes = this.#input[method]({...req, start});\n if (!req.reverse) {\n yield* nodes;\n return;\n }\n for (const node of nodes) {\n if (!this.#shouldBePresent(node.row)) {\n return;\n }\n yield node;\n }\n }\n\n setOutput(output: Output): void {\n this.#output = output;\n }\n\n destroy(): void {\n this.#input.destroy();\n }\n\n #shouldBePresent(row: Row): boolean {\n const cmp = this.#comparator(this.#bound.row, row);\n return cmp < 0 || (cmp === 0 && !this.#bound.exclusive);\n }\n\n push(change: Change): void {\n const shouldBePresent = (row: Row) => this.#shouldBePresent(row);\n if (change.type === 'edit') {\n maybeSplitAndPushEditChange(change, shouldBePresent, this.#output);\n return;\n }\n\n change satisfies AddChange | RemoveChange | ChildChange;\n\n if (shouldBePresent(change.node.row)) {\n this.#output.push(change);\n }\n }\n\n #getStart(req: FetchRequest): Start | undefined | 'empty' {\n const boundStart = {\n row: this.#bound.row,\n basis: this.#bound.exclusive ? 'after' : 'at',\n } as const;\n\n if (!req.start) {\n if (req.reverse) {\n return undefined;\n }\n return boundStart;\n }\n\n const cmp = this.#comparator(this.#bound.row, req.start.row);\n\n if (!req.reverse) {\n // The skip bound is after the requested bound. The requested bound cannot\n // be relevant because even if it was basis: 'after', the skip bound is\n // itself after the requested bound. Return the skip bound.\n if (cmp > 0) {\n return boundStart;\n }\n\n // The skip bound and requested bound are equal. If either is exclusive,\n // return that bound with exclusive. Otherwise, return the skip bound.\n if (cmp === 0) {\n if (this.#bound.exclusive || req.start.basis === 'after') {\n return {\n row: this.#bound.row,\n basis: 'after',\n };\n }\n return boundStart;\n }\n\n return req.start;\n }\n\n req.reverse satisfies true;\n\n // bound is after the start, but request is for reverse so results\n // must be empty\n if (cmp > 0) {\n return 'empty';\n }\n\n if (cmp === 0) {\n // if both are inclusive, the result can be the single row at bound\n // return it as start\n if (!this.#bound.exclusive && req.start.basis === 'at') {\n return boundStart;\n }\n // otherwise the results must be empty, one or both are exclusive\n // in opposite directions\n return 'empty';\n }\n\n // bound is before the start, return start\n return req.start;\n }\n}\n", "import {assert, unreachable} from '../../../shared/src/asserts.ts';\nimport {hasOwn} from '../../../shared/src/has-own.ts';\nimport {must} from '../../../shared/src/must.ts';\nimport type {Row, Value} from '../../../zero-protocol/src/data.ts';\nimport type {PrimaryKey} from '../../../zero-protocol/src/primary-key.ts';\nimport {assertOrderingIncludesPK} from '../builder/builder.ts';\nimport {type Change, type EditChange, type RemoveChange} from './change.ts';\nimport type {Constraint} from './constraint.ts';\nimport {compareValues, type Comparator, type Node} from './data.ts';\nimport {\n throwOutput,\n type FetchRequest,\n type Input,\n type Operator,\n type Output,\n type Storage,\n} from './operator.ts';\nimport type {SourceSchema} from './schema.ts';\nimport {first, take, type Stream} from './stream.ts';\n\nconst MAX_BOUND_KEY = 'maxBound';\n\ntype TakeState = {\n size: number;\n bound: Row | undefined;\n};\n\ninterface TakeStorage {\n get(key: typeof MAX_BOUND_KEY): Row | undefined;\n get(key: string): TakeState | undefined;\n set(key: typeof MAX_BOUND_KEY, value: Row): void;\n set(key: string, value: TakeState): void;\n del(key: string): void;\n}\n\nexport type PartitionKey = PrimaryKey;\n\n/**\n * The Take operator is for implementing limit queries. It takes the first n\n * nodes of its input as determined by the input\u2019s comparator. It then keeps\n * a *bound* of the last item it has accepted so that it can evaluate whether\n * new incoming pushes should be accepted or rejected.\n *\n * Take can count rows globally or by unique value of some field.\n *\n * Maintains the invariant that its output size is always <= limit, even\n * mid processing of a push.\n */\nexport class Take implements Operator {\n readonly #input: Input;\n readonly #storage: TakeStorage;\n readonly #limit: number;\n readonly #partitionKey: PartitionKey | undefined;\n readonly #partitionKeyComparator: Comparator | undefined;\n // Fetch overlay needed for some split push cases.\n #rowHiddenFromFetch: Row | undefined;\n\n #output: Output = throwOutput;\n\n constructor(\n input: Input,\n storage: Storage,\n limit: number,\n partitionKey?: PartitionKey | undefined,\n ) {\n assert(limit >= 0);\n assertOrderingIncludesPK(\n input.getSchema().sort,\n input.getSchema().primaryKey,\n );\n input.setOutput(this);\n this.#input = input;\n this.#storage = storage as TakeStorage;\n this.#limit = limit;\n this.#partitionKey = partitionKey;\n this.#partitionKeyComparator =\n partitionKey && makePartitionKeyComparator(partitionKey);\n }\n\n setOutput(output: Output): void {\n this.#output = output;\n }\n\n getSchema(): SourceSchema {\n return this.#input.getSchema();\n }\n\n *fetch(req: FetchRequest): Stream<Node> {\n if (\n !this.#partitionKey ||\n (req.constraint &&\n constraintMatchesPartitionKey(req.constraint, this.#partitionKey))\n ) {\n const takeStateKey = getTakeStateKey(this.#partitionKey, req.constraint);\n const takeState = this.#storage.get(takeStateKey);\n if (!takeState) {\n yield* this.#initialFetch(req);\n return;\n }\n if (takeState.bound === undefined) {\n return;\n }\n for (const inputNode of this.#input.fetch(req)) {\n if (this.getSchema().compareRows(takeState.bound, inputNode.row) < 0) {\n return;\n }\n if (\n this.#rowHiddenFromFetch &&\n this.getSchema().compareRows(\n this.#rowHiddenFromFetch,\n inputNode.row,\n ) === 0\n ) {\n continue;\n }\n yield inputNode;\n }\n return;\n }\n // There is a partition key, but the fetch is not constrained or constrained\n // on a different key. Thus we don't have a single take state to bound by.\n // This currently only happens with nested sub-queries\n // e.g. issues include issuelabels include label. We could remove this\n // case if we added a translation layer (powered by some state) in join.\n // Specifically we need joinKeyValue => parent constraint key\n const maxBound = this.#storage.get(MAX_BOUND_KEY);\n if (maxBound === undefined) {\n return;\n }\n for (const inputNode of this.#input.fetch(req)) {\n if (this.getSchema().compareRows(inputNode.row, maxBound) > 0) {\n return;\n }\n const takeStateKey = getTakeStateKey(this.#partitionKey, inputNode.row);\n const takeState = this.#storage.get(takeStateKey);\n if (\n takeState?.bound !== undefined &&\n this.getSchema().compareRows(takeState.bound, inputNode.row) >= 0\n ) {\n yield inputNode;\n }\n }\n }\n\n *#initialFetch(req: FetchRequest): Stream<Node> {\n assert(req.start === undefined);\n assert(!req.reverse);\n assert(constraintMatchesPartitionKey(req.constraint, this.#partitionKey));\n\n if (this.#limit === 0) {\n return;\n }\n\n const takeStateKey = getTakeStateKey(this.#partitionKey, req.constraint);\n assert(this.#storage.get(takeStateKey) === undefined);\n\n let size = 0;\n let bound: Row | undefined;\n let downstreamEarlyReturn = true;\n let exceptionThrown = false;\n try {\n for (const inputNode of this.#input.fetch(req)) {\n yield inputNode;\n bound = inputNode.row;\n size++;\n if (size === this.#limit) {\n break;\n }\n }\n downstreamEarlyReturn = false;\n } catch (e) {\n exceptionThrown = true;\n throw e;\n } finally {\n if (!exceptionThrown) {\n this.#setTakeState(\n takeStateKey,\n size,\n bound,\n this.#storage.get(MAX_BOUND_KEY),\n );\n // If it becomes necessary to support downstream early return, this\n // assert should be removed, and replaced with code that consumes\n // the input stream until limit is reached or the input stream is\n // exhausted so that takeState is properly hydrated.\n assert(\n !downstreamEarlyReturn,\n 'Unexpected early return prevented full hydration',\n );\n }\n }\n }\n\n *cleanup(req: FetchRequest): Stream<Node> {\n assert(req.start === undefined);\n assert(constraintMatchesPartitionKey(req.constraint, this.#partitionKey));\n const takeStateKey = getTakeStateKey(this.#partitionKey, req.constraint);\n this.#storage.del(takeStateKey);\n let size = 0;\n for (const inputNode of this.#input.cleanup(req)) {\n if (size === this.#limit) {\n return;\n }\n size++;\n yield inputNode;\n }\n }\n\n #getStateAndConstraint(row: Row) {\n const takeStateKey = getTakeStateKey(this.#partitionKey, row);\n const takeState = this.#storage.get(takeStateKey);\n let maxBound: Row | undefined;\n let constraint: Constraint | undefined;\n if (takeState) {\n maxBound = this.#storage.get(MAX_BOUND_KEY);\n constraint =\n this.#partitionKey &&\n Object.fromEntries(\n this.#partitionKey.map(key => [key, row[key]] as const),\n );\n }\n\n return {takeState, takeStateKey, maxBound, constraint} as\n | {\n takeState: undefined;\n takeStateKey: string;\n maxBound: undefined;\n constraint: undefined;\n }\n | {\n takeState: TakeState;\n takeStateKey: string;\n maxBound: Row | undefined;\n constraint: Constraint | undefined;\n };\n }\n\n push(change: Change): void {\n if (change.type === 'edit') {\n this.#pushEditChange(change);\n return;\n }\n\n const {takeState, takeStateKey, maxBound, constraint} =\n this.#getStateAndConstraint(change.node.row);\n if (!takeState) {\n return;\n }\n\n const {compareRows} = this.getSchema();\n\n if (change.type === 'add') {\n if (takeState.size < this.#limit) {\n this.#setTakeState(\n takeStateKey,\n takeState.size + 1,\n takeState.bound === undefined ||\n compareRows(takeState.bound, change.node.row) < 0\n ? change.node.row\n : takeState.bound,\n maxBound,\n );\n this.#output.push(change);\n return;\n }\n // size === limit\n if (\n takeState.bound === undefined ||\n compareRows(change.node.row, takeState.bound) >= 0\n ) {\n return;\n }\n // added row < bound\n let beforeBoundNode: Node | undefined;\n let boundNode: Node;\n if (this.#limit === 1) {\n boundNode = must(\n first(\n this.#input.fetch({\n start: {\n row: takeState.bound,\n basis: 'at',\n },\n constraint,\n }),\n ),\n );\n } else {\n [boundNode, beforeBoundNode] = take(\n this.#input.fetch({\n start: {\n row: takeState.bound,\n basis: 'at',\n },\n constraint,\n reverse: true,\n }),\n 2,\n );\n }\n const removeChange: RemoveChange = {\n type: 'remove',\n node: boundNode,\n };\n // Remove before add to maintain invariant that\n // output size <= limit.\n this.#setTakeState(\n takeStateKey,\n takeState.size,\n beforeBoundNode === undefined ||\n compareRows(change.node.row, beforeBoundNode.row) > 0\n ? change.node.row\n : beforeBoundNode.row,\n maxBound,\n );\n this.#withRowHiddenFromFetch(change.node.row, () => {\n this.#output.push(removeChange);\n });\n this.#output.push(change);\n } else if (change.type === 'remove') {\n if (takeState.bound === undefined) {\n // change is after bound\n return;\n }\n const compToBound = compareRows(change.node.row, takeState.bound);\n if (compToBound > 0) {\n // change is after bound\n return;\n }\n const [beforeBoundNode] = take(\n this.#input.fetch({\n start: {\n row: takeState.bound,\n basis: 'after',\n },\n constraint,\n reverse: true,\n }),\n 1,\n );\n\n let newBound: {node: Node; push: boolean} | undefined;\n if (beforeBoundNode) {\n const push = compareRows(beforeBoundNode.row, takeState.bound) > 0;\n newBound = {\n node: beforeBoundNode,\n push,\n };\n }\n if (!newBound?.push) {\n for (const node of this.#input.fetch({\n start: {\n row: takeState.bound,\n basis: 'at',\n },\n constraint,\n })) {\n const push = compareRows(node.row, takeState.bound) > 0;\n newBound = {\n node,\n push,\n };\n if (push) {\n break;\n }\n }\n }\n\n if (newBound?.push) {\n this.#output.push(change);\n this.#setTakeState(\n takeStateKey,\n takeState.size,\n newBound.node.row,\n maxBound,\n );\n this.#output.push({\n type: 'add',\n node: newBound.node,\n });\n return;\n }\n this.#setTakeState(\n takeStateKey,\n takeState.size - 1,\n newBound?.node.row,\n maxBound,\n );\n this.#output.push(change);\n } else if (change.type === 'child') {\n // A 'child' change should be pushed to output if its row\n // is <= bound.\n if (\n takeState.bound &&\n compareRows(change.node.row, takeState.bound) <= 0\n ) {\n this.#output.push(change);\n }\n }\n }\n\n #pushEditChange(change: EditChange): void {\n assert(\n !this.#partitionKeyComparator ||\n this.#partitionKeyComparator(change.oldNode.row, change.node.row) === 0,\n 'Unexpected change of partition key',\n );\n\n const {takeState, takeStateKey, maxBound, constraint} =\n this.#getStateAndConstraint(change.oldNode.row);\n if (!takeState) {\n return;\n }\n\n assert(takeState.bound, 'Bound should be set');\n const {compareRows} = this.getSchema();\n const oldCmp = compareRows(change.oldNode.row, takeState.bound);\n const newCmp = compareRows(change.node.row, takeState.bound);\n\n const replaceBoundAndForwardChange = () => {\n this.#setTakeState(\n takeStateKey,\n takeState.size,\n change.node.row,\n maxBound,\n );\n this.#output.push(change);\n };\n\n // The bounds row was changed.\n if (oldCmp === 0) {\n // The new row is the new bound.\n if (newCmp === 0) {\n // no need to update the state since we are keeping the bounds\n this.#output.push(change);\n return;\n }\n\n if (newCmp < 0) {\n if (this.#limit === 1) {\n replaceBoundAndForwardChange();\n return;\n }\n\n // New row will be in the result but it might not be the bounds any\n // more. We need to find the row before the bounds to determine the new\n // bounds.\n\n const beforeBoundNode = must(\n first(\n this.#input.fetch({\n start: {\n row: takeState.bound,\n basis: 'after',\n },\n constraint,\n reverse: true,\n }),\n ),\n );\n\n this.#setTakeState(\n takeStateKey,\n takeState.size,\n beforeBoundNode.row,\n maxBound,\n );\n this.#output.push(change);\n return;\n }\n\n assert(newCmp > 0);\n // Find the first item at the old bounds. This will be the new bounds.\n const newBoundNode = must(\n first(\n this.#input.fetch({\n start: {\n row: takeState.bound,\n basis: 'at',\n },\n constraint,\n }),\n ),\n );\n\n // The next row is the new row. We can replace the bounds and keep the\n // edit change.\n if (compareRows(newBoundNode.row, change.node.row) === 0) {\n replaceBoundAndForwardChange();\n return;\n }\n\n // The new row is now outside the bounds, so we need to remove the old\n // row and add the new bounds row.\n this.#setTakeState(\n takeStateKey,\n takeState.size,\n newBoundNode.row,\n maxBound,\n );\n this.#output.push({\n type: 'add',\n node: newBoundNode,\n });\n return;\n }\n\n if (oldCmp > 0) {\n assert(newCmp !== 0, 'Invalid state. Row has duplicate primary key');\n\n // Both old and new outside of bounds\n if (newCmp > 0) {\n return;\n }\n\n // old was outside, new is inside. Pushing out the old bounds\n assert(newCmp < 0);\n\n const [oldBoundNode, newBoundNode] = take(\n this.#input.fetch({\n start: {\n row: takeState.bound,\n basis: 'at',\n },\n constraint,\n reverse: true,\n }),\n 2,\n );\n // Remove before add to maintain invariant that\n // output size <= limit.\n this.#setTakeState(\n takeStateKey,\n takeState.size,\n newBoundNode.row,\n maxBound,\n );\n this.#withRowHiddenFromFetch(change.node.row, () => {\n this.#output.push({\n type: 'remove',\n node: oldBoundNode,\n });\n });\n this.#output.push({\n type: 'add',\n node: change.node,\n });\n\n return;\n }\n\n if (oldCmp < 0) {\n assert(newCmp !== 0, 'Invalid state. Row has duplicate primary key');\n\n // Both old and new inside of bounds\n if (newCmp < 0) {\n this.#output.push(change);\n return;\n }\n\n // old was inside, new is larger than old bound\n\n assert(newCmp > 0);\n\n // at this point we need to find the row after the bound and use that or\n // the newRow as the new bound.\n const afterBoundNode = must(\n first(\n this.#input.fetch({\n start: {\n row: takeState.bound,\n basis: 'after',\n },\n constraint,\n }),\n ),\n );\n\n // The new row is the new bound. Use an edit change.\n if (compareRows(afterBoundNode.row, change.node.row) === 0) {\n replaceBoundAndForwardChange();\n return;\n }\n\n this.#output.push({\n type: 'remove',\n node: change.oldNode,\n });\n this.#setTakeState(\n takeStateKey,\n takeState.size,\n afterBoundNode.row,\n maxBound,\n );\n this.#output.push({\n type: 'add',\n node: afterBoundNode,\n });\n return;\n }\n\n unreachable();\n }\n\n #withRowHiddenFromFetch(row: Row, fn: () => void) {\n this.#rowHiddenFromFetch = row;\n try {\n fn();\n } finally {\n this.#rowHiddenFromFetch = undefined;\n }\n }\n\n #setTakeState(\n takeStateKey: string,\n size: number,\n bound: Row | undefined,\n maxBound: Row | undefined,\n ) {\n this.#storage.set(takeStateKey, {\n size,\n bound,\n });\n if (\n bound !== undefined &&\n (maxBound === undefined ||\n this.getSchema().compareRows(bound, maxBound) > 0)\n ) {\n this.#storage.set(MAX_BOUND_KEY, bound);\n }\n }\n\n destroy(): void {\n this.#input.destroy();\n }\n}\n\nfunction getTakeStateKey(\n partitionKey: PartitionKey | undefined,\n rowOrConstraint: Row | Constraint | undefined,\n): string {\n // The order must be consistent. We always use the order as defined by the\n // partition key.\n const partitionValues: Value[] = [];\n\n if (partitionKey && rowOrConstraint) {\n for (const key of partitionKey) {\n partitionValues.push(rowOrConstraint[key]);\n }\n }\n\n return JSON.stringify(['take', ...partitionValues]);\n}\n\nfunction constraintMatchesPartitionKey(\n constraint: Constraint | undefined,\n partitionKey: PartitionKey | undefined,\n): boolean {\n if (constraint === undefined || partitionKey === undefined) {\n return constraint === partitionKey;\n }\n if (partitionKey.length !== Object.keys(constraint).length) {\n return false;\n }\n for (const key of partitionKey) {\n if (!hasOwn(constraint, key)) {\n return false;\n }\n }\n return true;\n}\n\nfunction makePartitionKeyComparator(partitionKey: PartitionKey): Comparator {\n return (a, b) => {\n for (const key of partitionKey) {\n const cmp = compareValues(a[key], b[key]);\n if (cmp !== 0) {\n return cmp;\n }\n }\n return 0;\n };\n}\n", "import {assertString} from '../../../shared/src/asserts.ts';\nimport type {NonNullValue, SimplePredicateNoNull} from './filter.ts';\n\nexport function getLikePredicate(\n pattern: NonNullValue,\n flags: 'i' | '',\n): SimplePredicateNoNull {\n const op = getLikeOp(String(pattern), flags);\n return (lhs: NonNullValue) => {\n assertString(lhs);\n return op(String(lhs));\n };\n}\n\nfunction getLikeOp(pattern: string, flags: 'i' | ''): (lhs: string) => boolean {\n // if lhs does not contain '%' or '_' then it is a simple string comparison.\n // if it does contain '%' or '_' then it is a regex comparison.\n // '%' is a wildcard for any number of characters\n // '_' is a wildcard for a single character\n // Postgres SQL allows escaping using `\\`.\n\n if (!/_|%|\\\\/.test(pattern)) {\n if (flags === 'i') {\n const rhsLower = pattern.toLowerCase();\n return (lhs: string) => lhs.toLowerCase() === rhsLower;\n }\n return (lhs: string) => lhs === pattern;\n }\n const re = patternToRegExp(pattern, flags);\n return (lhs: string) => re.test(lhs);\n}\n\nconst specialCharsRe = /[$()*+.?[\\]\\\\^{|}]/;\n\nfunction patternToRegExp(source: string, flags: '' | 'i' = ''): RegExp {\n // There are a few cases:\n // % => .*\n // _ => .\n // \\x => \\x for any x except special regexp chars\n // special regexp chars => \\special regexp chars\n let pattern = '^';\n for (let i = 0; i < source.length; i++) {\n let c = source[i];\n switch (c) {\n case '%':\n pattern += '.*';\n break;\n case '_':\n pattern += '.';\n break;\n\n // @ts-expect-error fallthrough\n case '\\\\':\n if (i === source.length - 1) {\n throw new Error('LIKE pattern must not end with escape character');\n }\n i++;\n c = source[i];\n\n // fall through\n default:\n if (specialCharsRe.test(c)) {\n pattern += '\\\\';\n }\n pattern += c;\n\n break;\n }\n }\n return new RegExp(pattern + '$', flags + 'm');\n}\n", "import {assert, unreachable} from '../../../shared/src/asserts.ts';\nimport type {\n Condition,\n SimpleCondition,\n SimpleOperator,\n} from '../../../zero-protocol/src/ast.ts';\nimport type {Row, Value} from '../../../zero-protocol/src/data.ts';\nimport {getLikePredicate} from './like.ts';\n\nexport type NonNullValue = Exclude<Value, null | undefined>;\nexport type SimplePredicate = (rhs: Value) => boolean;\nexport type SimplePredicateNoNull = (rhs: NonNullValue) => boolean;\n\nexport type NoSubqueryCondition =\n | SimpleCondition\n | {\n type: 'and';\n conditions: readonly NoSubqueryCondition[];\n }\n | {\n type: 'or';\n conditions: readonly NoSubqueryCondition[];\n };\n\nexport function createPredicate(\n condition: NoSubqueryCondition,\n): (row: Row) => boolean {\n if (condition.type !== 'simple') {\n const predicates = condition.conditions.map(c => createPredicate(c));\n return condition.type === 'and'\n ? (row: Row) => {\n // and\n for (const predicate of predicates) {\n if (!predicate(row)) {\n return false;\n }\n }\n return true;\n }\n : (row: Row) => {\n // or\n for (const predicate of predicates) {\n if (predicate(row)) {\n return true;\n }\n }\n return false;\n };\n }\n const {left} = condition;\n const {right} = condition;\n assert(\n right.type !== 'static',\n 'static values should be resolved before creating predicates',\n );\n assert(\n left.type !== 'static',\n 'static values should be resolved before creating predicates',\n );\n\n switch (condition.op) {\n case 'IS':\n case 'IS NOT': {\n const impl = createIsPredicate(right.value, condition.op);\n if (left.type === 'literal') {\n const result = impl(left.value);\n return () => result;\n }\n return (row: Row) => impl(row[left.name]);\n }\n }\n\n if (right.value === null || right.value === undefined) {\n return (_row: Row) => false;\n }\n\n const impl = createPredicateImpl(right.value, condition.op);\n if (left.type === 'literal') {\n if (left.value === null || left.value === undefined) {\n return (_row: Row) => false;\n }\n const result = impl(left.value);\n return () => result;\n }\n\n return (row: Row) => {\n const lhs = row[left.name];\n if (lhs === null || lhs === undefined) {\n return false;\n }\n return impl(lhs);\n };\n}\n\nfunction createIsPredicate(\n rhs: Value | readonly Value[],\n operator: 'IS' | 'IS NOT',\n): SimplePredicate {\n switch (operator) {\n case 'IS':\n return lhs => lhs === rhs;\n case 'IS NOT':\n return lhs => lhs !== rhs;\n }\n}\n\nfunction createPredicateImpl(\n rhs: NonNullValue | readonly NonNullValue[],\n operator: Exclude<SimpleOperator, 'IS' | 'IS NOT'>,\n): SimplePredicateNoNull {\n switch (operator) {\n case '=':\n return lhs => lhs === rhs;\n case '!=':\n return lhs => lhs !== rhs;\n case '<':\n return lhs => lhs < rhs;\n case '<=':\n return lhs => lhs <= rhs;\n case '>':\n return lhs => lhs > rhs;\n case '>=':\n return lhs => lhs >= rhs;\n case 'LIKE':\n return getLikePredicate(rhs, '');\n case 'NOT LIKE':\n return not(getLikePredicate(rhs, ''));\n case 'ILIKE':\n return getLikePredicate(rhs, 'i');\n case 'NOT ILIKE':\n return not(getLikePredicate(rhs, 'i'));\n case 'IN': {\n assert(Array.isArray(rhs));\n const set = new Set(rhs);\n return lhs => set.has(lhs);\n }\n case 'NOT IN': {\n assert(Array.isArray(rhs));\n const set = new Set(rhs);\n return lhs => !set.has(lhs);\n }\n default:\n operator satisfies never;\n throw new Error(`Unexpected operator: ${operator}`);\n }\n}\n\nfunction not<T>(f: (lhs: T) => boolean) {\n return (lhs: T) => !f(lhs);\n}\n\n/**\n * If the condition contains any CorrelatedSubqueryConditions, returns a\n * transformed condition which contains no CorrelatedSubqueryCondition(s) but\n * which will filter a subset of the rows that would be filtered by the original\n * condition, or undefined if no such transformation exists.\n *\n * If the condition does not contain any CorrelatedSubqueryConditions\n * returns the condition unmodified and `conditionsRemoved: false`.\n *\n *\n * Assumes Condition is in DNF.\n */\nexport function transformFilters(filters: Condition | undefined): {\n filters: NoSubqueryCondition | undefined;\n conditionsRemoved: boolean;\n} {\n if (!filters) {\n return {filters: undefined, conditionsRemoved: false};\n }\n switch (filters.type) {\n case 'simple':\n return {filters, conditionsRemoved: false};\n case 'correlatedSubquery':\n return {filters: undefined, conditionsRemoved: true};\n case 'and': {\n const transformedConditions = [];\n for (const cond of filters.conditions) {\n assert(cond.type === 'simple' || cond.type === 'correlatedSubquery');\n if (cond.type === 'simple') {\n transformedConditions.push(cond);\n }\n }\n const conditionsRemoved =\n transformedConditions.length !== filters.conditions.length;\n if (transformedConditions.length === 0) {\n return {filters: undefined, conditionsRemoved};\n }\n if (transformedConditions.length === 1) {\n return {\n filters: transformedConditions[0],\n conditionsRemoved,\n };\n }\n return {\n filters: {\n type: 'and',\n conditions: transformedConditions,\n },\n conditionsRemoved,\n };\n }\n case 'or': {\n const transformedConditions: NoSubqueryCondition[] = [];\n let conditionsRemoved = false;\n for (const cond of filters.conditions) {\n assert(cond.type !== 'or');\n const transformed = transformFilters(cond);\n if (transformed.filters === undefined) {\n return {filters: undefined, conditionsRemoved: true};\n }\n conditionsRemoved = conditionsRemoved || transformed.conditionsRemoved;\n transformedConditions.push(transformed.filters);\n }\n return {\n filters: {type: 'or', conditions: transformedConditions},\n conditionsRemoved,\n };\n }\n default:\n unreachable(filters);\n }\n}\n", "import {assert} from '../../../shared/src/asserts.ts';\nimport type {JSONValue} from '../../../shared/src/json.ts';\nimport {must} from '../../../shared/src/must.ts';\nimport type {\n AST,\n ColumnReference,\n CompoundKey,\n Condition,\n Conjunction,\n CorrelatedSubquery,\n CorrelatedSubqueryCondition,\n Disjunction,\n LiteralValue,\n Ordering,\n Parameter,\n SimpleCondition,\n ValuePosition,\n} from '../../../zero-protocol/src/ast.ts';\nimport type {Row} from '../../../zero-protocol/src/data.ts';\nimport type {PrimaryKey} from '../../../zero-protocol/src/primary-key.ts';\nimport {Exists} from '../ivm/exists.ts';\nimport {FanIn} from '../ivm/fan-in.ts';\nimport {FanOut} from '../ivm/fan-out.ts';\nimport {Filter} from '../ivm/filter.ts';\nimport {Join} from '../ivm/join.ts';\nimport type {Input, Storage} from '../ivm/operator.ts';\nimport {Skip} from '../ivm/skip.ts';\nimport type {Source} from '../ivm/source.ts';\nimport {Take} from '../ivm/take.ts';\nimport {createPredicate, type NoSubqueryCondition} from './filter.ts';\n\nexport type StaticQueryParameters = {\n authData: Record<string, JSONValue>;\n preMutationRow?: Row | undefined;\n};\n\n/**\n * Interface required of caller to buildPipeline. Connects to constructed\n * pipeline to delegate environment to provide sources and storage.\n */\nexport interface BuilderDelegate {\n /**\n * Called once for each source needed by the AST.\n * Might be called multiple times with same tableName. It is OK to return\n * same storage instance in that case.\n */\n getSource(tableName: string): Source | undefined;\n\n /**\n * Called once for each operator that requires storage. Should return a new\n * unique storage object for each call.\n */\n createStorage(name: string): Storage;\n\n decorateInput(input: Input, name: string): Input;\n\n /**\n * The AST is mapped on-the-wire between client and server names.\n *\n * There is no \"wire\" for zqlite tests so this function is provided\n * to allow tests to remap the AST.\n */\n mapAst(ast: AST): AST;\n}\n\n/**\n * Builds a pipeline from an AST. Caller must provide a delegate to create source\n * and storage interfaces as necessary.\n *\n * Usage:\n *\n * ```ts\n * class MySink implements Output {\n * readonly #input: Input;\n *\n * constructor(input: Input) {\n * this.#input = input;\n * input.setOutput(this);\n * }\n *\n * push(change: Change, _: Operator) {\n * console.log(change);\n * }\n * }\n *\n * const input = buildPipeline(ast, myDelegate);\n * const sink = new MySink(input);\n * ```\n */\nexport function buildPipeline(ast: AST, delegate: BuilderDelegate): Input {\n return buildPipelineInternal(delegate.mapAst(ast), delegate, '');\n}\n\nexport function bindStaticParameters(\n ast: AST,\n staticQueryParameters: StaticQueryParameters | undefined,\n) {\n const visit = (node: AST): AST => ({\n ...node,\n where: node.where ? bindCondition(node.where) : undefined,\n related: node.related?.map(sq => ({\n ...sq,\n subquery: visit(sq.subquery),\n })),\n });\n\n function bindCondition(condition: Condition): Condition {\n if (condition.type === 'simple') {\n return {\n ...condition,\n left: bindValue(condition.left),\n right: bindValue(condition.right) as Exclude<\n ValuePosition,\n ColumnReference\n >,\n };\n }\n if (condition.type === 'correlatedSubquery') {\n return {\n ...condition,\n related: {\n ...condition.related,\n subquery: visit(condition.related.subquery),\n },\n };\n }\n return {\n ...condition,\n conditions: condition.conditions.map(bindCondition),\n };\n }\n\n const bindValue = (value: ValuePosition): ValuePosition => {\n if (isParameter(value)) {\n const anchor = must(\n staticQueryParameters,\n 'Static query params do not exist',\n )[value.anchor];\n const resolvedValue = resolveField(anchor, value.field);\n return {\n type: 'literal',\n value: resolvedValue as LiteralValue,\n };\n }\n return value;\n };\n\n return visit(ast);\n}\n\nfunction resolveField(\n anchor: Record<string, JSONValue> | Row | undefined,\n field: string | string[],\n): unknown {\n if (anchor === undefined) {\n return null;\n }\n\n if (Array.isArray(field)) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return field.reduce((acc, f) => (acc as any)?.[f], anchor) ?? null;\n }\n\n return anchor[field] ?? null;\n}\n\nfunction isParameter(value: ValuePosition): value is Parameter {\n return value.type === 'static';\n}\n\nfunction buildPipelineInternal(\n ast: AST,\n delegate: BuilderDelegate,\n name: string,\n partitionKey?: CompoundKey | undefined,\n): Input {\n const source = delegate.getSource(ast.table);\n if (!source) {\n throw new Error(`Source not found: ${ast.table}`);\n }\n ast = uniquifyCorrelatedSubqueryConditionAliases(ast);\n\n const csqsFromCondition = gatherCorrelatedSubqueryQueriesFromCondition(\n ast.where,\n );\n const splitEditKeys: Set<string> = partitionKey\n ? new Set(partitionKey)\n : new Set();\n for (const csq of csqsFromCondition) {\n for (const key of csq.correlation.parentField) {\n splitEditKeys.add(key);\n }\n }\n if (ast.related) {\n for (const csq of ast.related) {\n for (const key of csq.correlation.parentField) {\n splitEditKeys.add(key);\n }\n }\n }\n const conn = source.connect(must(ast.orderBy), ast.where, splitEditKeys);\n let end: Input = delegate.decorateInput(conn, `${name}:source(${ast.table})`);\n const {fullyAppliedFilters} = conn;\n\n if (ast.start) {\n end = delegate.decorateInput(new Skip(end, ast.start), `${name}:skip)`);\n }\n\n for (const csq of csqsFromCondition) {\n end = applyCorrelatedSubQuery(csq, delegate, end, name);\n }\n\n if (ast.where && !fullyAppliedFilters) {\n end = applyWhere(end, ast.where, delegate, name);\n }\n\n if (ast.limit !== undefined) {\n const takeName = `${name}:take`;\n end = delegate.decorateInput(\n new Take(end, delegate.createStorage(takeName), ast.limit, partitionKey),\n takeName,\n );\n }\n\n if (ast.related) {\n for (const csq of ast.related) {\n end = applyCorrelatedSubQuery(csq, delegate, end, name);\n }\n }\n\n return end;\n}\n\nfunction applyWhere(\n input: Input,\n condition: Condition,\n delegate: BuilderDelegate,\n name: string,\n): Input {\n switch (condition.type) {\n case 'and':\n return applyAnd(input, condition, delegate, name);\n case 'or':\n return applyOr(input, condition, delegate, name);\n case 'correlatedSubquery':\n return applyCorrelatedSubqueryCondition(input, condition, delegate, name);\n case 'simple':\n return applySimpleCondition(input, condition);\n }\n}\n\nfunction applyAnd(\n input: Input,\n condition: Conjunction,\n delegate: BuilderDelegate,\n name: string,\n) {\n for (const subCondition of condition.conditions) {\n input = applyWhere(input, subCondition, delegate, name);\n }\n return input;\n}\n\nexport function applyOr(\n input: Input,\n condition: Disjunction,\n delegate: BuilderDelegate,\n name: string,\n): Input {\n const [subqueryConditions, otherConditions] =\n groupSubqueryConditions(condition);\n // if there are no subquery conditions, no fan-in / fan-out is needed\n if (subqueryConditions.length === 0) {\n return new Filter(\n input,\n createPredicate({\n type: 'or',\n conditions: otherConditions,\n }),\n );\n }\n\n const fanOut = new FanOut(input);\n const branches = subqueryConditions.map(subCondition =>\n applyWhere(fanOut, subCondition, delegate, name),\n );\n if (otherConditions.length > 0) {\n branches.push(\n new Filter(\n fanOut,\n createPredicate({\n type: 'or',\n conditions: otherConditions,\n }),\n ),\n );\n }\n const ret = new FanIn(fanOut, branches);\n fanOut.setFanIn(ret);\n return ret;\n}\n\nexport function groupSubqueryConditions(condition: Disjunction) {\n const partitioned: [\n subqueryConditions: Condition[],\n otherConditions: NoSubqueryCondition[],\n ] = [[], []];\n for (const subCondition of condition.conditions) {\n if (isNotAndDoesNotContainSubquery(subCondition)) {\n partitioned[1].push(subCondition);\n } else {\n partitioned[0].push(subCondition);\n }\n }\n return partitioned;\n}\n\nexport function isNotAndDoesNotContainSubquery(\n condition: Condition,\n): condition is NoSubqueryCondition {\n if (condition.type === 'correlatedSubquery') {\n return false;\n }\n if (condition.type === 'and') {\n return condition.conditions.every(isNotAndDoesNotContainSubquery);\n }\n assert(condition.type !== 'or', 'where conditions are expected to be in DNF');\n return true;\n}\n\nfunction applySimpleCondition(input: Input, condition: SimpleCondition): Input {\n return new Filter(input, createPredicate(condition));\n}\n\nfunction applyCorrelatedSubQuery(\n sq: CorrelatedSubquery,\n delegate: BuilderDelegate,\n end: Input,\n name: string,\n) {\n assert(sq.subquery.alias, 'Subquery must have an alias');\n const child = buildPipelineInternal(\n sq.subquery,\n delegate,\n `${name}.${sq.subquery.alias}`,\n sq.correlation.childField,\n );\n const joinName = `${name}:join(${sq.subquery.alias})`;\n end = new Join({\n parent: end,\n child,\n storage: delegate.createStorage(joinName),\n parentKey: sq.correlation.parentField,\n childKey: sq.correlation.childField,\n relationshipName: sq.subquery.alias,\n hidden: sq.hidden ?? false,\n system: sq.system ?? 'client',\n });\n return delegate.decorateInput(end, joinName);\n}\n\nfunction applyCorrelatedSubqueryCondition(\n input: Input,\n condition: CorrelatedSubqueryCondition,\n delegate: BuilderDelegate,\n name: string,\n): Input {\n assert(condition.op === 'EXISTS' || condition.op === 'NOT EXISTS');\n const existsName = `${name}:exists(${condition.related.subquery.alias})`;\n return delegate.decorateInput(\n new Exists(\n input,\n delegate.createStorage(existsName),\n must(condition.related.subquery.alias),\n condition.related.correlation.parentField,\n condition.op,\n ),\n existsName,\n );\n}\n\nfunction gatherCorrelatedSubqueryQueriesFromCondition(\n condition: Condition | undefined,\n) {\n const csqs: CorrelatedSubquery[] = [];\n const gather = (condition: Condition) => {\n if (condition.type === 'correlatedSubquery') {\n assert(condition.op === 'EXISTS' || condition.op === 'NOT EXISTS');\n csqs.push({\n ...condition.related,\n subquery: {\n ...condition.related.subquery,\n limit:\n condition.related.system === 'permissions'\n ? PERMISSIONS_EXISTS_LIMIT\n : EXISTS_LIMIT,\n },\n });\n return;\n }\n if (condition.type === 'and' || condition.type === 'or') {\n for (const c of condition.conditions) {\n gather(c);\n }\n return;\n }\n };\n if (condition) {\n gather(condition);\n }\n return csqs;\n}\n\nconst EXISTS_LIMIT = 3;\nconst PERMISSIONS_EXISTS_LIMIT = 1;\n\nexport function assertOrderingIncludesPK(\n ordering: Ordering,\n pk: PrimaryKey,\n): void {\n const orderingFields = ordering.map(([field]) => field);\n const missingFields = pk.filter(pkField => !orderingFields.includes(pkField));\n\n if (missingFields.length > 0) {\n throw new Error(\n `Ordering must include all primary key fields. Missing: ${missingFields.join(\n ', ',\n )}. ZQL automatically appends primary key fields to the ordering if they are missing \n so a common cause of this error is a casing mismatch between Postgres and ZQL.\n E.g., \"userid\" vs \"userID\".\n You may want to add double-quotes around your Postgres column names to prevent Postgres from lower-casing them:\n https://www.postgresql.org/docs/current/sql-syntax-lexical.htm`,\n );\n }\n}\nfunction uniquifyCorrelatedSubqueryConditionAliases(ast: AST): AST {\n if (!ast.where) {\n return ast;\n }\n const {where} = ast;\n if (where.type !== 'and' && where.type !== 'or') {\n return ast;\n }\n let count = 0;\n\n const uniquifyCorrelatedSubquery = (csqc: CorrelatedSubqueryCondition) => ({\n ...csqc,\n related: {\n ...csqc.related,\n subquery: {\n ...csqc.related.subquery,\n alias: (csqc.related.subquery.alias ?? '') + '_' + count++,\n },\n },\n });\n\n const uniquifyAnd = (and: Conjunction) => {\n const conds = [];\n for (const cond of and.conditions) {\n if (cond.type === 'correlatedSubquery') {\n conds.push(uniquifyCorrelatedSubquery(cond));\n } else {\n conds.push(cond);\n }\n }\n return {\n ...and,\n conditions: conds,\n };\n };\n if (where.type === 'and') {\n return {\n ...ast,\n where: uniquifyAnd(where),\n };\n }\n // or\n const conds = [];\n for (const cond of where.conditions) {\n if (cond.type === 'simple') {\n conds.push(cond);\n } else if (cond.type === 'correlatedSubquery') {\n conds.push(uniquifyCorrelatedSubquery(cond));\n } else if (cond.type === 'and') {\n conds.push(uniquifyAnd(cond));\n }\n }\n return {\n ...ast,\n where: {\n ...where,\n conditions: conds,\n },\n };\n}\n", "import {assert} from '../../../shared/src/asserts.ts';\nimport type {Immutable} from '../../../shared/src/immutable.ts';\nimport type {TTL} from '../query/ttl.ts';\nimport type {Listener, TypedView} from '../query/typed-view.ts';\nimport type {Change} from './change.ts';\nimport type {Input, Output} from './operator.ts';\nimport type {SourceSchema} from './schema.ts';\nimport {applyChange} from './view-apply-change.ts';\nimport type {Entry, Format, View} from './view.ts';\n\n/**\n * Implements a materialized view of the output of an operator.\n *\n * It might seem more efficient to use an immutable b-tree for the\n * materialization, but it's not so clear. Inserts in the middle are\n * asymptotically slower in an array, but can often be done with zero\n * allocations, where changes to the b-tree will often require several allocs.\n *\n * Also the plain array view is more convenient for consumers since you can dump\n * it into console to see what it is, rather than having to iterate it.\n */\nexport class ArrayView<V extends View> implements Output, TypedView<V> {\n readonly #input: Input;\n readonly #listeners = new Set<Listener<V>>();\n readonly #schema: SourceSchema;\n readonly #format: Format;\n\n // Synthetic \"root\" entry that has a single \"\" relationship, so that we can\n // treat all changes, including the root change, generically.\n readonly #root: Entry;\n\n onDestroy: (() => void) | undefined;\n\n #dirty = false;\n #complete = false;\n readonly #updateTTL: (ttl: TTL) => void;\n\n constructor(\n input: Input,\n format: Format, // = {singular: false, relationships: {}},\n queryComplete: true | Promise<true>, // = true,\n updateTTL: (ttl: TTL) => void,\n ) {\n this.#input = input;\n this.#schema = input.getSchema();\n this.#format = format;\n this.#updateTTL = updateTTL;\n this.#root = {'': format.singular ? undefined : []};\n input.setOutput(this);\n\n if (queryComplete === true) {\n this.#complete = true;\n } else {\n void queryComplete.then(() => {\n this.#complete = true;\n this.#fireListeners();\n });\n }\n this.#hydrate();\n }\n\n get data() {\n return this.#root[''] as V;\n }\n\n addListener(listener: Listener<V>) {\n assert(!this.#listeners.has(listener), 'Listener already registered');\n this.#listeners.add(listener);\n\n this.#fireListener(listener);\n\n return () => {\n this.#listeners.delete(listener);\n };\n }\n\n #fireListeners() {\n for (const listener of this.#listeners) {\n this.#fireListener(listener);\n }\n }\n\n #fireListener(listener: Listener<V>) {\n listener(\n this.data as Immutable<V>,\n this.#complete ? 'complete' : 'unknown',\n );\n }\n\n destroy() {\n this.onDestroy?.();\n }\n\n #hydrate() {\n this.#dirty = true;\n for (const node of this.#input.fetch({})) {\n applyChange(\n this.#root,\n {type: 'add', node},\n this.#schema,\n '',\n this.#format,\n );\n }\n this.flush();\n }\n\n push(change: Change): void {\n this.#dirty = true;\n applyChange(this.#root, change, this.#schema, '', this.#format);\n }\n\n flush() {\n if (!this.#dirty) {\n return;\n }\n this.#dirty = false;\n this.#fireListeners();\n }\n\n updateTTL(ttl: TTL) {\n this.#updateTTL(ttl);\n }\n}\n", "/* eslint-disable @typescript-eslint/no-explicit-any */\nimport {must} from '../../../shared/src/must.ts';\nimport {\n toStaticParam,\n type Condition,\n type LiteralValue,\n type Parameter,\n type SimpleOperator,\n} from '../../../zero-protocol/src/ast.ts';\nimport type {Schema} from '../../../zero-schema/src/builder/schema-builder.ts';\nimport type {\n AvailableRelationships,\n DestTableName,\n GetFilterType,\n NoJsonSelector,\n PullTableSchema,\n Query,\n} from './query.ts';\n\nexport type ParameterReference = {\n [toStaticParam](): Parameter;\n};\n\n/**\n * A factory function that creates a condition. This is used to create\n * complex conditions that can be passed to the `where` method of a query.\n *\n * @example\n *\n * ```ts\n * const condition: ExpressionFactory<User> = ({and, cmp, or}) =>\n * and(\n * cmp('name', '=', 'Alice'),\n * or(cmp('age', '>', 18), cmp('isStudent', '=', true)),\n * );\n *\n * const query = z.query.user.where(condition);\n * ```\n */\nexport interface ExpressionFactory<\n TSchema extends Schema,\n TTable extends keyof TSchema['tables'] & string,\n> {\n (eb: ExpressionBuilder<TSchema, TTable>): Condition;\n}\n\nexport class ExpressionBuilder<\n TSchema extends Schema,\n TTable extends keyof TSchema['tables'] & string,\n> {\n readonly #exists: (\n relationship: string,\n cb?: (query: Query<TSchema, TTable>) => Query<TSchema, any>,\n ) => Condition;\n\n constructor(\n exists: (\n relationship: string,\n cb?: (query: Query<TSchema, TTable>) => Query<TSchema, any>,\n ) => Condition,\n ) {\n this.#exists = exists;\n this.exists = this.exists.bind(this);\n }\n\n get eb() {\n return this;\n }\n\n cmp<\n TSelector extends NoJsonSelector<PullTableSchema<TTable, TSchema>>,\n TOperator extends SimpleOperator,\n >(\n field: TSelector,\n op: TOperator,\n value:\n | GetFilterType<PullTableSchema<TTable, TSchema>, TSelector, TOperator>\n | ParameterReference,\n ): Condition;\n cmp<TSelector extends NoJsonSelector<PullTableSchema<TTable, TSchema>>>(\n field: TSelector,\n value:\n | GetFilterType<PullTableSchema<TTable, TSchema>, TSelector, '='>\n | ParameterReference,\n ): Condition;\n cmp(\n field: string,\n opOrValue: SimpleOperator | ParameterReference | LiteralValue,\n value?: ParameterReference | LiteralValue,\n ): Condition {\n return cmp(field, opOrValue, value);\n }\n\n cmpLit(\n left: ParameterReference | LiteralValue,\n op: SimpleOperator,\n right: ParameterReference | LiteralValue,\n ): Condition {\n return {\n type: 'simple',\n left: isParameterReference(left)\n ? left[toStaticParam]()\n : {type: 'literal', value: left},\n right: isParameterReference(right)\n ? right[toStaticParam]()\n : {type: 'literal', value: right},\n op,\n };\n }\n\n and = and;\n or = or;\n not = not;\n\n exists = <TRelationship extends AvailableRelationships<TTable, TSchema>>(\n relationship: TRelationship,\n cb?: (\n query: Query<TSchema, DestTableName<TTable, TSchema, TRelationship>>,\n ) => Query<TSchema, any>,\n ): Condition => this.#exists(relationship, cb);\n}\n\nexport function and(...conditions: (Condition | undefined)[]): Condition {\n const expressions = filterTrue(filterUndefined(conditions));\n\n if (expressions.length === 1) {\n return expressions[0];\n }\n\n if (expressions.some(isAlwaysFalse)) {\n return FALSE;\n }\n\n return {type: 'and', conditions: expressions};\n}\n\nexport function or(...conditions: (Condition | undefined)[]): Condition {\n const expressions = filterFalse(filterUndefined(conditions));\n\n if (expressions.length === 1) {\n return expressions[0];\n }\n\n if (expressions.some(isAlwaysTrue)) {\n return TRUE;\n }\n\n return {type: 'or', conditions: expressions};\n}\n\nexport function not(expression: Condition): Condition {\n switch (expression.type) {\n case 'and':\n return {\n type: 'or',\n conditions: expression.conditions.map(not),\n };\n case 'or':\n return {\n type: 'and',\n conditions: expression.conditions.map(not),\n };\n case 'correlatedSubquery':\n return {\n type: 'correlatedSubquery',\n related: expression.related,\n op: negateOperator(expression.op),\n };\n case 'simple':\n return {\n type: 'simple',\n op: negateOperator(expression.op),\n left: expression.left,\n right: expression.right,\n };\n }\n}\n\nexport function cmp(\n field: string,\n opOrValue: SimpleOperator | ParameterReference | LiteralValue,\n value?: ParameterReference | LiteralValue,\n): Condition {\n let op: SimpleOperator;\n if (value === undefined) {\n value = opOrValue;\n op = '=';\n } else {\n op = opOrValue as SimpleOperator;\n }\n\n return {\n type: 'simple',\n left: {type: 'column', name: field},\n right: isParameterReference(value)\n ? value[toStaticParam]()\n : {type: 'literal', value},\n op,\n };\n}\n\nfunction isParameterReference(\n value: ParameterReference | LiteralValue | null,\n): value is ParameterReference {\n return (\n value !== null && typeof value === 'object' && (value as any)[toStaticParam]\n );\n}\n\nexport const TRUE: Condition = {\n type: 'and',\n conditions: [],\n};\n\nconst FALSE: Condition = {\n type: 'or',\n conditions: [],\n};\n\nfunction isAlwaysTrue(condition: Condition): boolean {\n return condition.type === 'and' && condition.conditions.length === 0;\n}\n\nfunction isAlwaysFalse(condition: Condition): boolean {\n return condition.type === 'or' && condition.conditions.length === 0;\n}\n\nexport function flatten(\n type: 'and' | 'or',\n conditions: Condition[],\n): Condition[] {\n const flattened: Condition[] = [];\n for (const c of conditions) {\n if (c.type === type) {\n flattened.push(...c.conditions);\n } else {\n flattened.push(c);\n }\n }\n\n return flattened;\n}\n\nconst negateSimpleOperatorMap = {\n ['=']: '!=',\n ['!=']: '=',\n ['<']: '>=',\n ['>']: '<=',\n ['>=']: '<',\n ['<=']: '>',\n ['IN']: 'NOT IN',\n ['NOT IN']: 'IN',\n ['LIKE']: 'NOT LIKE',\n ['NOT LIKE']: 'LIKE',\n ['ILIKE']: 'NOT ILIKE',\n ['NOT ILIKE']: 'ILIKE',\n ['IS']: 'IS NOT',\n ['IS NOT']: 'IS',\n} as const;\n\nconst negateOperatorMap = {\n ...negateSimpleOperatorMap,\n ['EXISTS']: 'NOT EXISTS',\n ['NOT EXISTS']: 'EXISTS',\n} as const;\n\nexport function negateOperator<OP extends keyof typeof negateOperatorMap>(\n op: OP,\n): (typeof negateOperatorMap)[OP] {\n return must(negateOperatorMap[op]);\n}\n\nfunction filterUndefined<T>(array: (T | undefined)[]): T[] {\n return array.filter(e => e !== undefined);\n}\n\nfunction filterTrue(conditions: Condition[]): Condition[] {\n return conditions.filter(c => !isAlwaysTrue(c));\n}\n\nfunction filterFalse(conditions: Condition[]): Condition[] {\n return conditions.filter(c => !isAlwaysFalse(c));\n}\n", "import {unreachable} from '../../../shared/src/asserts.ts';\nimport type {Condition, Disjunction} from '../../../zero-protocol/src/ast.ts';\nimport {flatten, TRUE} from './expression.ts';\n\n/**\n * DNF (Disjunctive Normal Form) is a way to represent a boolean expression as a\n * series of `or` conditions where each `or` condition is a series of `and`\n * conditions. The `and` conditions are the terms (SimpleCondition) of the\n * expression.\n */\nexport function dnf(condition: Condition): Condition {\n return unwrap(dnfInner(condition));\n}\n\nfunction dnfInner(condition: Condition): Disjunction {\n switch (condition.type) {\n case 'simple':\n case 'correlatedSubquery':\n return {type: 'or', conditions: [condition]};\n\n case 'and':\n return distributeAnd(condition.conditions.map(dnfInner));\n\n case 'or':\n return {\n type: 'or',\n conditions: flatten(\n 'or',\n condition.conditions.map(dnfInner).flatMap(c => c.conditions),\n ),\n };\n\n default:\n unreachable(condition);\n }\n}\n\nfunction distributeAnd(conditions: Disjunction[]): Disjunction {\n if (conditions.length === 0) {\n return {type: 'or', conditions: [TRUE]};\n }\n\n return conditions.reduce((acc, orCondition): Disjunction => {\n const newConditions: Condition[] = [];\n for (const accCondition of acc.conditions) {\n for (const orSubCondition of orCondition.conditions) {\n newConditions.push({\n type: 'and',\n conditions: [accCondition, orSubCondition],\n });\n }\n }\n return {\n type: 'or',\n conditions: flatten('or', newConditions),\n };\n });\n}\n\nexport function unwrap(c: Condition): Condition {\n if (c.type === 'simple' || c.type === 'correlatedSubquery') {\n return c;\n }\n if (c.conditions.length === 1) {\n return unwrap(c.conditions[0]);\n }\n return {type: c.type, conditions: flatten(c.type, c.conditions.map(unwrap))};\n}\n"],
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA,gBAAAA;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAEA;AAFA,YAAY,OAAO;AAEnB,6BAAc;AAEd,SAAS,UAAU,OAAwB;AACzC,UAAQ,OAAO,OAAO;AAAA,IACpB,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AACH,aAAO,KAAK,UAAU,KAAK;AAAA,IAC7B,KAAK;AACH,aAAO;AAAA,IACT,KAAK;AACH,aAAO,MAAM,SAAS,IAAI;AAAA,IAC5B;AACE,UAAI,UAAU,MAAM;AAClB,eAAO;AAAA,MACT;AACA,UAAI,MAAM,QAAQ,KAAK,GAAG;AACxB,eAAO;AAAA,MACT;AACA,aAAO,OAAO;AAAA,EAClB;AACF;AAIA,SAAS,gBAAgBC,IAAYC,OAAiC;AACpE,MAAI,CAACA,OAAM,QAAQ;AACjB,WAAO,UAAUD,EAAC;AAAA,EACpB;AAEA,MAAI,MAAMA;AACV,aAAW,KAAKC,OAAM;AAEpB,UAAO,IAAY,CAAC;AAAA,EACtB;AACA,SAAO,UAAU,GAAG;AACtB;AAEA,SAAS,YACP,MACA,UACAC,aAAuC,OAAK,OAAO,CAAC,GACnC;AACjB,MAAI,SAAS,WAAW,GAAG;AACzB,WAAOA,WAAU,SAAS,CAAC,CAAC;AAAA,EAC9B;AAEA,QAAM,SAAS,GAAGA;AAAA,IAChB,SAAS,SAAS,SAAS,CAAC;AAAA,EAC9B,CAAC,IAAI,IAAI,IAAIA,WAAU,SAA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QAAQ,KAAK,KAAK,MAAM,UAAU;AACjD;",
|
|
4
|
+
"sourcesContent": ["import * as v from '@badrap/valita';\n\nexport * from '@badrap/valita';\n\nfunction toDisplay(value: unknown): string {\n switch (typeof value) {\n case 'string':\n case 'number':\n case 'boolean':\n return JSON.stringify(value);\n case 'undefined':\n return 'undefined';\n case 'bigint':\n return value.toString() + 'n';\n default:\n if (value === null) {\n return 'null';\n }\n if (Array.isArray(value)) {\n return 'array';\n }\n return typeof value;\n }\n}\n\ntype Key = string | number;\n\nfunction toDisplayAtPath(v: unknown, path: Key[] | undefined): string {\n if (!path?.length) {\n return toDisplay(v);\n }\n\n let cur = v;\n for (const p of path) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n cur = (cur as any)[p];\n }\n return toDisplay(cur);\n}\n\nfunction displayList<T>(\n word: string,\n expected: T[],\n toDisplay: (x: T) => string | number = x => String(x),\n): string | number {\n if (expected.length === 1) {\n return toDisplay(expected[0]);\n }\n\n const suffix = `${toDisplay(\n expected[expected.length - 2],\n )} ${word} ${toDisplay(expected[expected.length - 1])}`;\n if (expected.length === 2) {\n return suffix;\n }\n return `${expected.slice(0, -2).map(toDisplay).join(', ')}, ${suffix}`;\n}\n\nfunction getMessage(\n err: v.Err | v.ValitaError,\n v: unknown,\n schema: v.Type | v.Optional,\n mode: ParseOptionsMode | undefined,\n): string {\n const firstIssue = err.issues[0];\n const {path} = firstIssue;\n const atPath = path?.length ? ` at ${path.join('.')}` : '';\n\n switch (firstIssue.code) {\n case 'invalid_type':\n return `Expected ${displayList(\n 'or',\n firstIssue.expected,\n )}${atPath}. Got ${toDisplayAtPath(v, path)}`;\n case 'missing_value': {\n const atPath =\n path && path.length > 1 ? ` at ${path.slice(0, -1).join('.')}` : '';\n\n if (firstIssue.path?.length) {\n return `Missing property ${firstIssue.path.at(-1)}${atPath}`;\n }\n return `TODO Unknown missing property${atPath}`;\n }\n\n case 'invalid_literal':\n return `Expected literal value ${displayList(\n 'or',\n firstIssue.expected,\n toDisplay,\n )}${atPath} Got ${toDisplayAtPath(v, path)}`;\n\n case 'invalid_length': {\n return `Expected array with length ${\n firstIssue.minLength === firstIssue.maxLength\n ? firstIssue.minLength\n : `between ${firstIssue.minLength} and ${firstIssue.maxLength}`\n }${atPath}. Got array with length ${(v as {length: number}).length}`;\n }\n\n case 'unrecognized_keys':\n if (firstIssue.keys.length === 1) {\n return `Unexpected property ${firstIssue.keys[0]}${atPath}`;\n }\n return `Unexpected properties ${displayList(\n 'and',\n firstIssue.keys,\n )}${atPath}`;\n\n case 'invalid_union':\n return schema.name === 'union'\n ? getDeepestUnionParseError(v, schema as v.UnionType, mode ?? 'strict')\n : `Invalid union value${atPath}`;\n\n case 'custom_error': {\n const {error} = firstIssue;\n const message = !error\n ? 'unknown'\n : typeof error === 'string'\n ? error\n : (error.message ?? 'unknown');\n return `${message}${atPath}. Got ${toDisplayAtPath(v, path)}`;\n }\n }\n}\n\ntype FailedType = {type: v.Type; err: v.Err};\n\nfunction getDeepestUnionParseError(\n value: unknown,\n schema: v.UnionType,\n mode: ParseOptionsMode,\n): string {\n const failures: FailedType[] = [];\n for (const type of schema.options) {\n const r = type.try(value, {mode});\n if (!r.ok) {\n failures.push({type, err: r});\n }\n }\n if (failures.length) {\n // compare the first and second longest-path errors\n failures.sort(pathCmp);\n if (failures.length === 1 || pathCmp(failures[0], failures[1]) < 0) {\n return getMessage(failures[0].err, value, failures[0].type, mode);\n }\n }\n // paths are equivalent\n try {\n const str = JSON.stringify(value);\n return `Invalid union value: ${str}`;\n } catch (e) {\n // fallback if the value could not be stringified\n return `Invalid union value`;\n }\n}\n\n// Descending-order comparison of Issue paths.\n// * [1, 'a'] sorts before [1]\n// * [1] sorts before [0] (i.e. errors later in the tuple sort before earlier errors)\nfunction pathCmp(a: FailedType, b: FailedType) {\n const aPath = a.err.issues[0].path;\n const bPath = b.err.issues[0].path;\n if (aPath.length !== bPath.length) {\n return bPath.length - aPath.length;\n }\n for (let i = 0; i < aPath.length; i++) {\n if (bPath[i] > aPath[i]) {\n return -1;\n }\n if (bPath[i] < aPath[i]) {\n return 1;\n }\n }\n return 0;\n}\n\n/**\n * 'strip' allows unknown properties and removes unknown properties.\n * 'strict' errors if there are unknown properties.\n * 'passthrough' allows unknown properties.\n */\nexport type ParseOptionsMode = 'passthrough' | 'strict' | 'strip';\n\nexport function parse<T>(\n value: unknown,\n schema: v.Type<T>,\n mode?: ParseOptionsMode,\n): T {\n const res = test(value, schema, mode);\n if (!res.ok) {\n throw new TypeError(res.error);\n }\n return res.value;\n}\n\nexport function is<T>(\n value: unknown,\n schema: v.Type<T>,\n mode?: ParseOptionsMode,\n): value is T {\n return test(value, schema, mode).ok;\n}\n\nexport function assert<T>(\n value: unknown,\n schema: v.Type<T>,\n mode?: ParseOptionsMode,\n): asserts value is T {\n parse(value, schema, mode);\n}\n\ntype Result<T> = {ok: true; value: T} | {ok: false; error: string};\n\nexport function test<T>(\n value: unknown,\n schema: v.Type<T>,\n mode?: ParseOptionsMode,\n): Result<T> {\n const res = schema.try(value, mode ? {mode} : undefined);\n if (!res.ok) {\n return {\n ok: false,\n error: getMessage(res, value, schema, mode),\n };\n }\n return res;\n}\n\n/**\n * Similar to {@link test} but works for AbstractTypes such as Optional.\n * This is for advanced usage. Prefer {@link test} unless you really need\n * to operate directly on an Optional field.\n */\nexport function testOptional<T>(\n value: unknown,\n schema: v.Type<T> | v.Optional<T>,\n mode?: ParseOptionsMode,\n): Result<T | undefined> {\n let flags = 0x1; // FLAG_FORBID_EXTRA_KEYS;\n if (mode === 'passthrough') {\n flags = 0;\n } else if (mode === 'strip') {\n flags = 0x2; // FLAG_STRIP_EXTRA_KEYS;\n }\n const res = schema.func(value, flags);\n if (res === undefined) {\n return {ok: true, value} as Result<T>;\n } else if (res.ok) {\n return res;\n }\n const err = new v.ValitaError(res);\n return {ok: false, error: getMessage(err, value, schema, mode)};\n}\n\n/**\n * Shallowly marks the schema as readonly.\n */\nexport function readonly<T extends v.Type>(t: T): v.Type<Readonly<v.Infer<T>>> {\n return t as v.Type<Readonly<v.Infer<T>>>;\n}\n\nexport function readonlyObject<T extends Record<string, v.Type | v.Optional>>(\n t: T,\n): v.ObjectType<Readonly<T>, undefined> {\n return v.object(t);\n}\n\nexport function readonlyArray<T extends v.Type>(\n t: T,\n): v.Type<readonly v.Infer<T>[]> {\n return v.array(t);\n}\n\nexport function readonlyRecord<T extends v.Type>(\n t: T,\n): v.Type<Readonly<Record<string, v.Infer<T>>>> {\n return v.record(t);\n}\n\n// eslint-disable-next-line @typescript-eslint/naming-convention\nconst AbstractType = Object.getPrototypeOf(\n Object.getPrototypeOf(v.string().optional()),\n).constructor;\n\nexport function instanceOfAbstractType<T = unknown>(\n obj: unknown,\n): obj is v.Type<T> | v.Optional<T> {\n return obj instanceof AbstractType;\n}\n\ntype ObjectShape = Record<string, typeof AbstractType>;\n\n/**\n * Similar to `ObjectType.partial()` except it recurses into nested objects.\n * Rest types are not supported.\n */\nexport function deepPartial<Shape extends ObjectShape>(\n s: v.ObjectType<Shape, undefined>,\n) {\n const shape = {} as Record<string, unknown>;\n for (const [key, type] of Object.entries(s.shape)) {\n if (type.name === 'object') {\n shape[key] = deepPartial(type as v.ObjectType).optional();\n } else {\n shape[key] = type.optional();\n }\n }\n return v.object(shape as {[K in keyof Shape]: v.Optional<v.Infer<Shape[K]>>});\n}\n", "export type TimeUnit = 's' | 'm' | 'h' | 'd' | 'y';\n\n/**\n * Time To Live. This is used for query expiration.\n * - `forever` means the query will never expire.\n * - `none` means the query will expire immediately.\n * - A number means the query will expire after that many milliseconds.\n * - A negative number means the query will never expire, this is same as 'forever'.\n * - A string like `1s` means the query will expire after that many seconds.\n * - A string like `1m` means the query will expire after that many minutes.\n * - A string like `1h` means the query will expire after that many hours.\n * - A string like `1d` means the query will expire after that many days.\n * - A string like `1y` means the query will expire after that many years.\n */\nexport type TTL = `${number}${TimeUnit}` | 'forever' | 'none' | number;\n\nexport const DEFAULT_TTL: TTL = 'none';\n\nconst multiplier = {\n s: 1000,\n m: 60 * 1000,\n h: 60 * 60 * 1000,\n d: 24 * 60 * 60 * 1000,\n y: 365 * 24 * 60 * 60 * 1000,\n} as const;\n\nexport function parseTTL(ttl: TTL): number {\n if (typeof ttl === 'number') {\n return Number.isNaN(ttl) ? 0 : !Number.isFinite(ttl) || ttl < 0 ? -1 : ttl;\n }\n if (ttl === 'none') {\n return 0;\n }\n if (ttl === 'forever') {\n return -1;\n }\n const multi = multiplier[ttl[ttl.length - 1] as TimeUnit];\n return Number(ttl.slice(0, -1)) * multi;\n}\n\nexport function compareTTL(a: TTL, b: TTL): number {\n const ap = parseTTL(a);\n const bp = parseTTL(b);\n if (ap === -1 && bp !== -1) {\n return 1;\n }\n if (ap !== -1 && bp === -1) {\n return -1;\n }\n return ap - bp;\n}\n\nexport function normalizeTTL(ttl: TTL): TTL {\n if (typeof ttl === 'string') {\n return ttl;\n }\n\n if (ttl < 0) {\n return 'forever';\n }\n\n if (ttl === 0) {\n return 'none';\n }\n\n let shortest = ttl.toString();\n const lengthOfNumber = shortest.length;\n for (const unit of ['y', 'd', 'h', 'm', 's'] as const) {\n const multi = multiplier[unit];\n const value = ttl / multi;\n const candidate = `${value}${unit}`;\n if (candidate.length < shortest.length) {\n shortest = candidate;\n }\n }\n\n return (shortest.length < lengthOfNumber ? shortest : ttl) as TTL;\n}\n", "// hasOwn was added in ES2022\nexport const {hasOwn} = Object;\n", "import {xxHash32} from 'js-xxhash';\n\nexport const h32 = (s: string) => xxHash32(s, 0);\nexport const h64 = (s: string) => hash(s, 2);\nexport const h128 = (s: string) => hash(s, 4);\n\n/**\n * xxHash32 only computes 32-bit values. Run it n times with different seeds to\n * get a larger hash with better collision resistance.\n */\nfunction hash(str: string, words: number): bigint {\n let hash = 0n;\n for (let i = 0; i < words; i++) {\n hash = (hash << 32n) + BigInt(xxHash32(str, i));\n }\n return hash;\n}\n", "/**\n * Wire-format representation of the zql AST interface.\n *\n * `v.Type<...>` types are explicitly declared to facilitate Typescript verification\n * that the schemas satisfy the zql type definitions. (Incidentally, explicit types\n * are also required for recursive schema definitions.)\n */\n\nimport {compareUTF8} from 'compare-utf8';\nimport {defined} from '../../shared/src/arrays.ts';\nimport {assert} from '../../shared/src/asserts.ts';\nimport {must} from '../../shared/src/must.ts';\nimport * as v from '../../shared/src/valita.ts';\nimport type {NameMapper} from '../../zero-schema/src/name-mapper.ts';\nimport {rowSchema, type Row} from './data.ts';\n\nexport const selectorSchema = v.string();\nexport const toStaticParam = Symbol();\n\nconst orderingElementSchema = v.readonly(\n v.tuple([selectorSchema, v.union(v.literal('asc'), v.literal('desc'))]),\n);\n\nexport const orderingSchema = v.readonlyArray(orderingElementSchema);\nexport type System = 'permissions' | 'client';\n\nexport const primitiveSchema = v.union(\n v.string(),\n v.number(),\n v.boolean(),\n v.null(),\n);\n\nexport const equalityOpsSchema = v.union(\n v.literal('='),\n v.literal('!='),\n v.literal('IS'),\n v.literal('IS NOT'),\n);\n\nexport const orderOpsSchema = v.union(\n v.literal('<'),\n v.literal('>'),\n v.literal('<='),\n v.literal('>='),\n);\n\nexport const likeOpsSchema = v.union(\n v.literal('LIKE'),\n v.literal('NOT LIKE'),\n v.literal('ILIKE'),\n v.literal('NOT ILIKE'),\n);\n\nexport const inOpsSchema = v.union(v.literal('IN'), v.literal('NOT IN'));\n\nexport const simpleOperatorSchema = v.union(\n equalityOpsSchema,\n orderOpsSchema,\n likeOpsSchema,\n inOpsSchema,\n);\n\nconst literalReferenceSchema: v.Type<LiteralReference> = v.readonlyObject({\n type: v.literal('literal'),\n value: v.union(\n v.string(),\n v.number(),\n v.boolean(),\n v.null(),\n v.readonlyArray(v.union(v.string(), v.number(), v.boolean())),\n ),\n});\nconst columnReferenceSchema: v.Type<ColumnReference> = v.readonlyObject({\n type: v.literal('column'),\n name: v.string(),\n});\n\n/**\n * A parameter is a value that is not known at the time the query is written\n * and is resolved at runtime.\n *\n * Static parameters refer to something provided by the caller.\n * Static parameters are injected when the query pipeline is built from the AST\n * and do not change for the life of that pipeline.\n *\n * An example static parameter is the current authentication data.\n * When a user is authenticated, queries on the server have access\n * to the user's authentication data in order to evaluate authorization rules.\n * Authentication data doesn't change over the life of a query as a change\n * in auth data would represent a log-in / log-out of the user.\n *\n * AncestorParameters refer to rows encountered while running the query.\n * They are used by subqueries to refer to rows emitted by parent queries.\n */\nconst parameterReferenceSchema = v.readonlyObject({\n type: v.literal('static'),\n // The \"namespace\" of the injected parameter.\n // Write authorization will send the value of a row\n // prior to the mutation being run (preMutationRow).\n // Read and write authorization will both send the\n // current authentication data (authData).\n anchor: v.union(v.literal('authData'), v.literal('preMutationRow')),\n field: v.union(v.string(), v.array(v.string())),\n});\n\nconst conditionValueSchema = v.union(\n literalReferenceSchema,\n columnReferenceSchema,\n parameterReferenceSchema,\n);\n\nexport type Parameter = v.Infer<typeof parameterReferenceSchema>;\n\nexport const simpleConditionSchema: v.Type<SimpleCondition> = v.readonlyObject({\n type: v.literal('simple'),\n op: simpleOperatorSchema,\n left: conditionValueSchema,\n right: v.union(parameterReferenceSchema, literalReferenceSchema),\n});\n\ntype ConditionValue = v.Infer<typeof conditionValueSchema>;\n\nexport const correlatedSubqueryConditionOperatorSchema: v.Type<CorrelatedSubqueryConditionOperator> =\n v.union(v.literal('EXISTS'), v.literal('NOT EXISTS'));\n\nexport const correlatedSubqueryConditionSchema: v.Type<CorrelatedSubqueryCondition> =\n v.readonlyObject({\n type: v.literal('correlatedSubquery'),\n related: v.lazy(() => correlatedSubquerySchema),\n op: correlatedSubqueryConditionOperatorSchema,\n });\n\nexport const conditionSchema: v.Type<Condition> = v.union(\n simpleConditionSchema,\n v.lazy(() => conjunctionSchema),\n v.lazy(() => disjunctionSchema),\n correlatedSubqueryConditionSchema,\n);\n\nconst conjunctionSchema: v.Type<Conjunction> = v.readonlyObject({\n type: v.literal('and'),\n conditions: v.readonlyArray(conditionSchema),\n});\n\nconst disjunctionSchema: v.Type<Disjunction> = v.readonlyObject({\n type: v.literal('or'),\n conditions: v.readonlyArray(conditionSchema),\n});\n\nexport type CompoundKey = readonly [string, ...string[]];\n\nfunction mustCompoundKey(field: readonly string[]): CompoundKey {\n assert(Array.isArray(field) && field.length >= 1);\n return field as unknown as CompoundKey;\n}\n\nexport const compoundKeySchema: v.Type<CompoundKey> = v.readonly(\n v.tuple([v.string()]).concat(v.array(v.string())),\n);\n\nconst correlationSchema = v.readonlyObject({\n parentField: compoundKeySchema,\n childField: compoundKeySchema,\n});\n\n// Split out so that its inferred type can be checked against\n// Omit<CorrelatedSubquery, 'correlation'> in ast-type-test.ts.\n// The mutually-recursive reference of the 'other' field to astSchema\n// is the only thing added in v.lazy. The v.lazy is necessary due to the\n// mutually-recursive types, but v.lazy prevents inference of the resulting\n// type.\nexport const correlatedSubquerySchemaOmitSubquery = v.readonlyObject({\n correlation: correlationSchema,\n hidden: v.boolean().optional(),\n system: v.union(v.literal('permissions'), v.literal('client')).optional(),\n});\n\nexport const correlatedSubquerySchema: v.Type<CorrelatedSubquery> =\n correlatedSubquerySchemaOmitSubquery.extend({\n subquery: v.lazy(() => astSchema),\n });\n\nexport const astSchema: v.Type<AST> = v.readonlyObject({\n schema: v.string().optional(),\n table: v.string(),\n alias: v.string().optional(),\n where: conditionSchema.optional(),\n related: v.readonlyArray(correlatedSubquerySchema).optional(),\n limit: v.number().optional(),\n orderBy: orderingSchema.optional(),\n start: v\n .object({\n row: rowSchema,\n exclusive: v.boolean(),\n })\n .optional(),\n});\n\nexport type Bound = {\n row: Row;\n exclusive: boolean;\n};\n\n/**\n * As in SQL you can have multiple orderings. We don't currently\n * support ordering on anything other than the root query.\n */\nexport type OrderPart = readonly [field: string, direction: 'asc' | 'desc'];\nexport type Ordering = readonly OrderPart[];\n\nexport type SimpleOperator = EqualityOps | OrderOps | LikeOps | InOps;\nexport type EqualityOps = '=' | '!=' | 'IS' | 'IS NOT';\nexport type OrderOps = '<' | '>' | '<=' | '>=';\nexport type LikeOps = 'LIKE' | 'NOT LIKE' | 'ILIKE' | 'NOT ILIKE';\nexport type InOps = 'IN' | 'NOT IN';\n\nexport type AST = {\n readonly schema?: string | undefined;\n readonly table: string;\n\n // A query would be aliased if the AST is a subquery.\n // e.g., when two subqueries select from the same table\n // they need an alias to differentiate them.\n // `SELECT\n // [SELECT * FROM issue WHERE issue.id = outer.parentId] AS parent\n // [SELECT * FROM issue WHERE issue.parentId = outer.id] AS children\n // FROM issue as outer`\n readonly alias?: string | undefined;\n\n // `select` is missing given we return all columns for now.\n\n // The PipelineBuilder will pick what to use to correlate\n // a subquery with a parent query. It can choose something from the\n // where conditions or choose the _first_ `related` entry.\n // Choosing the first `related` entry is almost always the best choice if\n // one exists.\n readonly where?: Condition | undefined;\n\n readonly related?: readonly CorrelatedSubquery[] | undefined;\n readonly start?: Bound | undefined;\n readonly limit?: number | undefined;\n readonly orderBy?: Ordering | undefined;\n};\n\nexport type Correlation = {\n readonly parentField: CompoundKey;\n readonly childField: CompoundKey;\n};\n\nexport type CorrelatedSubquery = {\n /**\n * Only equality correlation are supported for now.\n * E.g., direct foreign key relationships.\n */\n readonly correlation: Correlation;\n readonly subquery: AST;\n readonly system?: System | undefined;\n // If a hop in the subquery chain should be hidden from the output view.\n // A common example is junction edges. The query API provides the illusion\n // that they don't exist: `issue.related('labels')` instead of `issue.related('issue_labels').related('labels')`.\n // To maintain this illusion, the junction edge should be hidden.\n // When `hidden` is set to true, this hop will not be included in the output view\n // but its children will be.\n readonly hidden?: boolean | undefined;\n};\n\nexport type ValuePosition = LiteralReference | Parameter | ColumnReference;\n\nexport type ColumnReference = {\n readonly type: 'column';\n /**\n * Not a path yet as we're currently not allowing\n * comparisons across tables. This will need to\n * be a path through the tree in the near future.\n */\n readonly name: string;\n};\n\nexport type LiteralReference = {\n readonly type: 'literal';\n readonly value: LiteralValue;\n};\n\nexport type LiteralValue =\n | string\n | number\n | boolean\n | null\n | ReadonlyArray<string | number | boolean>;\n\n/**\n * Starting only with SimpleCondition for now.\n * ivm1 supports Conjunctions and Disjunctions.\n * We'll support them in the future.\n */\nexport type Condition =\n | SimpleCondition\n | Conjunction\n | Disjunction\n | CorrelatedSubqueryCondition;\n\nexport type SimpleCondition = {\n readonly type: 'simple';\n readonly op: SimpleOperator;\n readonly left: ValuePosition;\n\n /**\n * `null` is absent since we do not have an `IS` or `IS NOT`\n * operator defined and `null != null` in SQL.\n */\n readonly right: Exclude<ValuePosition, ColumnReference>;\n};\n\nexport type Conjunction = {\n type: 'and';\n conditions: readonly Condition[];\n};\n\nexport type Disjunction = {\n type: 'or';\n conditions: readonly Condition[];\n};\n\nexport type CorrelatedSubqueryCondition = {\n type: 'correlatedSubquery';\n related: CorrelatedSubquery;\n op: CorrelatedSubqueryConditionOperator;\n};\n\nexport type CorrelatedSubqueryConditionOperator = 'EXISTS' | 'NOT EXISTS';\n\ninterface ASTTransform {\n tableName(orig: string): string;\n columnName(origTable: string, origColumn: string): string;\n related(subqueries: CorrelatedSubquery[]): readonly CorrelatedSubquery[];\n where(cond: Condition): Condition | undefined;\n // conjunction or disjunction, called when traversing the return value of where()\n conditions(conds: Condition[]): readonly Condition[];\n}\n\nfunction transformAST(ast: AST, transform: ASTTransform): Required<AST> {\n // Name mapping functions (e.g. to server names)\n const {tableName, columnName} = transform;\n const colName = (c: string) => columnName(ast.table, c);\n const key = (table: string, k: CompoundKey) => {\n const serverKey = k.map(col => columnName(table, col));\n return mustCompoundKey(serverKey);\n };\n\n const where = ast.where ? transform.where(ast.where) : undefined;\n const transformed = {\n schema: ast.schema,\n table: tableName(ast.table),\n alias: ast.alias,\n where: where ? transformWhere(where, ast.table, transform) : undefined,\n related: ast.related\n ? transform.related(\n ast.related.map(\n r =>\n ({\n correlation: {\n parentField: key(ast.table, r.correlation.parentField),\n childField: key(r.subquery.table, r.correlation.childField),\n },\n hidden: r.hidden,\n subquery: transformAST(r.subquery, transform),\n system: r.system,\n }) satisfies Required<CorrelatedSubquery>,\n ),\n )\n : undefined,\n start: ast.start\n ? {\n ...ast.start,\n row: Object.fromEntries(\n Object.entries(ast.start.row).map(([col, val]) => [\n colName(col),\n val,\n ]),\n ),\n }\n : undefined,\n limit: ast.limit,\n orderBy: ast.orderBy?.map(([col, dir]) => [colName(col), dir] as const),\n };\n\n return transformed;\n}\n\nfunction transformWhere(\n where: Condition,\n table: string,\n transform: ASTTransform,\n): Condition {\n // Name mapping functions (e.g. to server names)\n const {columnName} = transform;\n const condValue = (c: ConditionValue) =>\n c.type !== 'column' ? c : {...c, name: columnName(table, c.name)};\n const key = (table: string, k: CompoundKey) => {\n const serverKey = k.map(col => columnName(table, col));\n return mustCompoundKey(serverKey);\n };\n\n if (where.type === 'simple') {\n return {...where, left: condValue(where.left)};\n } else if (where.type === 'correlatedSubquery') {\n const {correlation, subquery} = where.related;\n return {\n ...where,\n related: {\n ...where.related,\n correlation: {\n parentField: key(table, correlation.parentField),\n childField: key(subquery.table, correlation.childField),\n },\n subquery: transformAST(subquery, transform),\n },\n };\n }\n\n return {\n type: where.type,\n conditions: transform.conditions(\n where.conditions.map(c => transformWhere(c, table, transform)),\n ),\n };\n}\n\nconst normalizeCache = new WeakMap<AST, Required<AST>>();\n\nconst NORMALIZE_TRANSFORM: ASTTransform = {\n tableName: t => t,\n columnName: (_, c) => c,\n related: sortedRelated,\n where: flattened,\n conditions: c => c.sort(cmpCondition),\n};\n\nexport function normalizeAST(ast: AST): Required<AST> {\n let normalized = normalizeCache.get(ast);\n if (!normalized) {\n normalized = transformAST(ast, NORMALIZE_TRANSFORM);\n normalizeCache.set(ast, normalized);\n }\n return normalized;\n}\n\nexport function mapAST(ast: AST, mapper: NameMapper) {\n return transformAST(ast, {\n tableName: table => mapper.tableName(table),\n columnName: (table, col) => mapper.columnName(table, col),\n related: r => r,\n where: w => w,\n conditions: c => c,\n });\n}\n\nexport function mapCondition(\n cond: Condition,\n table: string,\n mapper: NameMapper,\n) {\n return transformWhere(cond, table, {\n tableName: table => mapper.tableName(table),\n columnName: (table, col) => mapper.columnName(table, col),\n related: r => r,\n where: w => w,\n conditions: c => c,\n });\n}\n\nfunction sortedRelated(\n related: CorrelatedSubquery[],\n): readonly CorrelatedSubquery[] {\n return related.sort(cmpRelated);\n}\n\nfunction cmpCondition(a: Condition, b: Condition): number {\n if (a.type === 'simple') {\n if (b.type !== 'simple') {\n return -1; // Order SimpleConditions first\n }\n\n return (\n compareValuePosition(a.left, b.left) ||\n compareUTF8MaybeNull(a.op, b.op) ||\n compareValuePosition(a.right, b.right)\n );\n }\n\n if (b.type === 'simple') {\n return 1; // Order SimpleConditions first\n }\n\n if (a.type === 'correlatedSubquery') {\n if (b.type !== 'correlatedSubquery') {\n return -1; // Order subquery before conjuctions/disjuctions\n }\n return cmpRelated(a.related, b.related) || compareUTF8MaybeNull(a.op, b.op);\n }\n if (b.type === 'correlatedSubquery') {\n return -1; // Order correlatedSubquery before conjuctions/disjuctions\n }\n\n const val = compareUTF8MaybeNull(a.type, b.type);\n if (val !== 0) {\n return val;\n }\n for (\n let l = 0, r = 0;\n l < a.conditions.length && r < b.conditions.length;\n l++, r++\n ) {\n const val = cmpCondition(a.conditions[l], b.conditions[r]);\n if (val !== 0) {\n return val;\n }\n }\n // prefixes first\n return a.conditions.length - b.conditions.length;\n}\n\nfunction compareValuePosition(a: ValuePosition, b: ValuePosition): number {\n if (a.type !== b.type) {\n return compareUTF8(a.type, b.type);\n }\n switch (a.type) {\n case 'literal':\n assert(b.type === 'literal');\n return compareUTF8(String(a.value), String(b.value));\n case 'column':\n assert(b.type === 'column');\n return compareUTF8(a.name, b.name);\n case 'static':\n throw new Error(\n 'Static parameters should be resolved before normalization',\n );\n }\n}\n\nfunction cmpRelated(a: CorrelatedSubquery, b: CorrelatedSubquery): number {\n return compareUTF8(must(a.subquery.alias), must(b.subquery.alias));\n}\n\n/**\n * Returns a flattened version of the Conditions in which nested Conjunctions with\n * the same operation ('AND' or 'OR') are flattened to the same level. e.g.\n *\n * ```\n * ((a AND b) AND (c AND (d OR (e OR f)))) -> (a AND b AND c AND (d OR e OR f))\n * ```\n *\n * Also flattens singleton Conjunctions regardless of operator, and removes\n * empty Conjunctions.\n */\nfunction flattened(cond: Condition): Condition | undefined {\n if (cond.type === 'simple' || cond.type === 'correlatedSubquery') {\n return cond;\n }\n const conditions = defined(\n cond.conditions.flatMap(c =>\n c.type === cond.type ? c.conditions.map(c => flattened(c)) : flattened(c),\n ),\n );\n\n switch (conditions.length) {\n case 0:\n return undefined;\n case 1:\n return conditions[0];\n default:\n return {\n type: cond.type,\n conditions,\n };\n }\n}\n\nfunction compareUTF8MaybeNull(a: string | null, b: string | null): number {\n if (a !== null && b !== null) {\n return compareUTF8(a, b);\n }\n if (b !== null) {\n return -1;\n }\n if (a !== null) {\n return 1;\n }\n return 0;\n}\n", "import {assert} from './asserts.ts';\n\n/**\n * Returns `arr` as is if none of the elements are `undefined`.\n * Otherwise returns a new array with only defined elements in `arr`.\n */\nexport function defined<T>(arr: (T | undefined)[]): T[] {\n // avoid an array copy if possible\n let i = arr.findIndex(x => x === undefined);\n if (i < 0) {\n return arr as T[];\n }\n const defined: T[] = arr.slice(0, i) as T[];\n for (i++; i < arr.length; i++) {\n const x = arr[i];\n if (x !== undefined) {\n defined.push(x);\n }\n }\n return defined;\n}\n\nexport function areEqual<T>(arr1: readonly T[], arr2: readonly T[]): boolean {\n return arr1.length === arr2.length && arr1.every((e, i) => e === arr2[i]);\n}\n\nexport function zip<T1, T2>(a1: readonly T1[], a2: readonly T2[]): [T1, T2][] {\n assert(a1.length === a2.length);\n const result: [T1, T2][] = [];\n for (let i = 0; i < a1.length; i++) {\n result.push([a1[i], a2[i]]);\n }\n return result;\n}\n\nexport function groupBy<T, K>(\n arr: readonly T[],\n keyFn: (el: T) => K,\n): Map<K, T[]> {\n const groups = new Map<K, T[]>();\n for (const el of arr) {\n const key = keyFn(el);\n let group = groups.get(key);\n if (group === undefined) {\n group = [];\n groups.set(key, group);\n }\n group.push(el);\n }\n return groups;\n}\n", "import * as valita from '@badrap/valita';\nimport {skipAssertJSONValue} from './config.ts';\nimport type {ReadonlyJSONObject, ReadonlyJSONValue} from './json.ts';\nimport {isJSONObject, isJSONValue} from './json.ts';\nimport * as v from './valita.ts';\n\nconst path: (string | number)[] = [];\n\nexport const jsonSchema: valita.Type<ReadonlyJSONValue> = v\n .unknown()\n .chain(v => {\n if (skipAssertJSONValue) {\n return valita.ok(v as ReadonlyJSONValue);\n }\n const rv = isJSONValue(v, path)\n ? valita.ok(v)\n : valita.err({\n message: `Not a JSON value`,\n path: path.slice(),\n });\n path.length = 0;\n return rv;\n });\n\nexport const jsonObjectSchema: valita.Type<ReadonlyJSONObject> = v\n .unknown()\n .chain(v => {\n if (skipAssertJSONValue) {\n return valita.ok(v as ReadonlyJSONObject);\n }\n const rv = isJSONObject(v, path)\n ? valita.ok(v)\n : valita.err({\n message: `Not a JSON object`,\n path: path.slice(),\n });\n path.length = 0;\n return rv;\n });\n", "declare const process: {\n env: {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n NODE_ENV?: string;\n };\n};\n\nexport const isProd = process.env.NODE_ENV === 'production';\n\nexport {isProd as skipAssertJSONValue};\n", "import {assertObject, throwInvalidType} from './asserts.ts';\nimport {skipAssertJSONValue} from './config.ts';\nimport {hasOwn} from './has-own.ts';\n\n/** The values that can be represented in JSON */\nexport type JSONValue =\n | null\n | string\n | boolean\n | number\n | Array<JSONValue>\n | JSONObject;\n\n/**\n * A JSON object. This is a map from strings to JSON values or `undefined`. We\n * allow `undefined` values as a convenience... but beware that the `undefined`\n * values do not round trip to the server. For example:\n *\n * ```\n * // Time t1\n * await tx.set('a', {a: undefined});\n *\n * // time passes, in a new transaction\n * const v = await tx.get('a');\n * console.log(v); // either {a: undefined} or {}\n * ```\n */\nexport type JSONObject = {[key: string]: JSONValue | undefined};\n\n/** Like {@link JSONValue} but deeply readonly */\nexport type ReadonlyJSONValue =\n | null\n | string\n | boolean\n | number\n | ReadonlyArray<ReadonlyJSONValue>\n | ReadonlyJSONObject;\n\n/** Like {@link JSONObject} but deeply readonly */\nexport type ReadonlyJSONObject = {\n readonly [key: string]: ReadonlyJSONValue | undefined;\n};\n\n/**\n * Checks deep equality of two JSON value with (almost) same semantics as\n * `JSON.stringify`. The only difference is that with `JSON.stringify` the\n * ordering of the properties in an object/map/dictionary matters. In\n * {@link deepEqual} the following two values are consider equal, even though the\n * strings JSON.stringify would produce is different:\n *\n * ```js\n * assert(deepEqual(t({a: 1, b: 2}, {b: 2, a: 1}))\n * ```\n */\nexport function deepEqual(\n a: ReadonlyJSONValue | undefined,\n b: ReadonlyJSONValue | undefined,\n): boolean {\n if (a === b) {\n return true;\n }\n\n if (typeof a !== typeof b) {\n return false;\n }\n\n switch (typeof a) {\n case 'boolean':\n case 'number':\n case 'string':\n return false;\n }\n\n // a cannot be undefined here because either a and b are undefined or their\n // types are different.\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n a = a!;\n\n // 'object'\n if (Array.isArray(a)) {\n if (!Array.isArray(b)) {\n return false;\n }\n if (a.length !== b.length) {\n return false;\n }\n for (let i = 0; i < a.length; i++) {\n if (!deepEqual(a[i], b[i])) {\n return false;\n }\n }\n return true;\n }\n\n if (a === null || b === null) {\n return false;\n }\n\n if (Array.isArray(b)) {\n return false;\n }\n\n // We know a and b are objects here but type inference is not smart enough.\n a = a as ReadonlyJSONObject;\n b = b as ReadonlyJSONObject;\n\n // We use for-in loops instead of for of Object.keys() to make sure deepEquals\n // does not allocate any objects.\n\n let aSize = 0;\n for (const key in a) {\n if (hasOwn(a, key)) {\n if (!deepEqual(a[key], b[key])) {\n return false;\n }\n aSize++;\n }\n }\n\n let bSize = 0;\n for (const key in b) {\n if (hasOwn(b, key)) {\n bSize++;\n }\n }\n\n return aSize === bSize;\n}\n\nexport function assertJSONValue(v: unknown): asserts v is JSONValue {\n if (skipAssertJSONValue) {\n return;\n }\n switch (typeof v) {\n case 'boolean':\n case 'number':\n case 'string':\n return;\n case 'object':\n if (v === null) {\n return;\n }\n if (Array.isArray(v)) {\n return assertJSONArray(v);\n }\n return assertObjectIsJSONObject(v as Record<string, unknown>);\n }\n throwInvalidType(v, 'JSON value');\n}\n\nexport function assertJSONObject(v: unknown): asserts v is JSONObject {\n assertObject(v);\n assertObjectIsJSONObject(v);\n}\n\nfunction assertObjectIsJSONObject(\n v: Record<string, unknown>,\n): asserts v is JSONObject {\n for (const k in v) {\n if (hasOwn(v, k)) {\n const value = v[k];\n if (value !== undefined) {\n assertJSONValue(value);\n }\n }\n }\n}\n\nfunction assertJSONArray(v: unknown[]): asserts v is JSONValue[] {\n for (const item of v) {\n assertJSONValue(item);\n }\n}\n\ninterface Path {\n push(key: string | number): void;\n pop(): void;\n}\n\n/**\n * Checks if a value is a JSON value. If there is a value that is not a JSON\n * value, the path parameter is updated to the path of the invalid value.\n */\nexport function isJSONValue(v: unknown, path: Path): v is JSONValue {\n switch (typeof v) {\n case 'boolean':\n case 'number':\n case 'string':\n return true;\n case 'object':\n if (v === null) {\n return true;\n }\n if (Array.isArray(v)) {\n return isJSONArray(v, path);\n }\n return objectIsJSONObject(v as Record<string, unknown>, path);\n }\n return false;\n}\n\nexport function isJSONObject(v: unknown, path: Path): v is JSONObject {\n if (typeof v !== 'object' || v === null) {\n return false;\n }\n return objectIsJSONObject(v as Record<string, unknown>, path);\n}\n\nfunction objectIsJSONObject(\n v: Record<string, unknown>,\n path: Path,\n): v is JSONObject {\n for (const k in v) {\n if (hasOwn(v, k)) {\n path.push(k);\n const value = v[k];\n if (value !== undefined && !isJSONValue(value, path)) {\n return false;\n }\n path.pop();\n }\n }\n return true;\n}\n\nfunction isJSONArray(v: unknown[], path: Path): v is JSONValue[] {\n for (let i = 0; i < v.length; i++) {\n path.push(i);\n if (!isJSONValue(v[i], path)) {\n return false;\n }\n path.pop();\n }\n return true;\n}\n\n/** Basic deep readonly type. It works for {@link JSONValue} types. */\nexport type DeepReadonly<T> = T extends\n | null\n | boolean\n | string\n | number\n | undefined\n ? T\n : {readonly [K in keyof T]: DeepReadonly<T[K]>};\n", "import {jsonSchema} from '../../shared/src/json-schema.ts';\nimport * as v from '../../shared/src/valita.ts';\n\nexport const valueSchema = v.union(jsonSchema, v.undefined());\n\nexport const rowSchema = v.readonlyRecord(valueSchema);\n\n/**\n * The data types that Zero can represent are limited by two things:\n *\n * 1. The underlying Replicache sync layer currently can only represent JSON\n * types. This could possibly be expanded in the future, but we do want to be\n * careful of adding encoding overhead. By using JSON, we are taking\n * advantage of IndexedDB\u2019s fast native JSValue [de]serialization which has\n * historically been a perf advantage for us.\n *\n * 2. IDs in Zero need to be comparable because we use them for sorting and row\n * identity. We could expand the set of allowed value types (to include,\n * i.e., Objects) but we would then need to restrict IDs to only comparable\n * types.\n *\n * These two facts leave us with the following allowed types. Zero's replication\n * layer must convert other types into these for tables to be used with Zero.\n *\n * For developer convenience we also allow `undefined`, which we treat\n * equivalently to `null`.\n */\nexport type Value = v.Infer<typeof valueSchema>;\n\n/**\n * A Row is represented as a JS Object.\n *\n * We do everything in IVM as loosely typed values because these pipelines are\n * going to be constructed at runtime by other code, so type-safety can't buy us\n * anything.\n *\n * Also since the calling code on the client ultimately wants objects to work\n * with we end up with a lot less copies by using objects throughout.\n */\nexport type Row = v.Infer<typeof rowSchema>;\n", "export type {ValueType} from '../../zero-protocol/src/client-schema.ts';\nimport type {ValueType} from '../../zero-protocol/src/client-schema.ts';\nimport type {PrimaryKey} from '../../zero-protocol/src/primary-key.ts';\n\n/**\n * `related` calls need to know what the available relationships are.\n * The `schema` type encodes this information.\n */\nexport type SchemaValue<T = unknown> =\n | {\n type: ValueType;\n serverName?: string | undefined;\n optional?: boolean | undefined;\n }\n | EnumSchemaValue<T>\n | SchemaValueWithCustomType<T>;\n\nexport type SchemaValueWithCustomType<T> = {\n type: ValueType;\n serverName?: string | undefined;\n optional?: boolean;\n customType: T;\n};\n\nexport type EnumSchemaValue<T> = {\n kind: 'enum';\n type: 'string';\n serverName?: string | undefined;\n optional?: boolean;\n customType: T;\n};\n\nexport type TableSchema = {\n readonly name: string;\n readonly serverName?: string | undefined;\n readonly columns: Record<string, SchemaValue>;\n readonly primaryKey: PrimaryKey;\n};\n\nexport type RelationshipsSchema = {\n readonly [name: string]: Relationship;\n};\n\nexport type TypeNameToTypeMap = {\n string: string;\n number: number;\n boolean: boolean;\n null: null;\n\n // In schema-v2, the user will be able to specify the TS type that\n // the JSON should match and `any`` will no\n // longer be used here.\n // ReadOnlyJSONValue is not used as it causes\n // infinite depth errors to pop up for users of our APIs.\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n json: any;\n};\n\nexport type ColumnTypeName<T extends SchemaValue | ValueType> =\n T extends SchemaValue ? T['type'] : T;\n\n/**\n * Given a schema value, return the TypeScript type.\n *\n * This allows us to create the correct return type for a\n * query that has a selection.\n */\nexport type SchemaValueToTSType<T extends SchemaValue | ValueType> =\n T extends ValueType\n ? TypeNameToTypeMap[T]\n : T extends {\n optional: true;\n }\n ?\n | (T extends SchemaValueWithCustomType<infer V>\n ? V\n : TypeNameToTypeMap[ColumnTypeName<T>])\n | null\n : T extends SchemaValueWithCustomType<infer V>\n ? V\n : TypeNameToTypeMap[ColumnTypeName<T>];\n\ntype Connection = {\n readonly sourceField: readonly string[];\n readonly destField: readonly string[];\n readonly destSchema: string;\n readonly cardinality: Cardinality;\n};\n\nexport type Cardinality = 'one' | 'many';\n\nexport type Relationship =\n | readonly [Connection]\n | readonly [Connection, Connection];\n// | readonly [Connection, Connection, Connection];\n\nexport type LastInTuple<T extends Relationship> = T extends readonly [infer L]\n ? L\n : T extends readonly [unknown, infer L]\n ? L\n : T extends readonly [unknown, unknown, infer L]\n ? L\n : never;\n\nexport type AtLeastOne<T> = readonly [T, ...T[]];\n\nexport function atLeastOne<T>(arr: readonly T[]): AtLeastOne<T> {\n if (arr.length === 0) {\n throw new Error('Expected at least one element');\n }\n return arr as AtLeastOne<T>;\n}\n\nexport function isOneHop(r: Relationship): r is readonly [Connection] {\n return r.length === 1;\n}\n\nexport function isTwoHop(\n r: Relationship,\n): r is readonly [Connection, Connection] {\n return r.length === 2;\n}\n\nexport type Opaque<BaseType, BrandType = unknown> = BaseType & {\n readonly [base]: BaseType;\n readonly [brand]: BrandType;\n};\n\ndeclare const base: unique symbol;\ndeclare const brand: unique symbol;\n\nexport type IsOpaque<T> = T extends {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n readonly [brand]: any;\n}\n ? true\n : false;\n\nexport type ExpandRecursiveSkipOpaque<T> =\n IsOpaque<T> extends true\n ? T\n : T extends object\n ? T extends infer O\n ? {[K in keyof O]: ExpandRecursiveSkipOpaque<O[K]>}\n : never\n : T;\n", "/* eslint-disable @typescript-eslint/naming-convention */\n/* eslint-disable @typescript-eslint/no-explicit-any */\nimport {resolver} from '@rocicorp/resolver';\nimport {assert} from '../../../shared/src/asserts.ts';\nimport type {Writable} from '../../../shared/src/writable.ts';\nimport {hashOfAST} from '../../../zero-protocol/src/ast-hash.ts';\nimport type {\n AST,\n CompoundKey,\n Condition,\n Ordering,\n Parameter,\n SimpleOperator,\n System,\n} from '../../../zero-protocol/src/ast.ts';\nimport type {Row as IVMRow} from '../../../zero-protocol/src/data.ts';\nimport type {Schema} from '../../../zero-schema/src/builder/schema-builder.ts';\nimport {\n isOneHop,\n isTwoHop,\n type TableSchema,\n} from '../../../zero-schema/src/table-schema.ts';\nimport {buildPipeline, type BuilderDelegate} from '../builder/builder.ts';\nimport {ArrayView} from '../ivm/array-view.ts';\nimport type {Input} from '../ivm/operator.ts';\nimport type {Format, ViewFactory} from '../ivm/view.ts';\nimport {dnf} from './dnf.ts';\nimport {\n and,\n cmp,\n ExpressionBuilder,\n type ExpressionFactory,\n} from './expression.ts';\nimport {\n type GetFilterType,\n type HumanReadable,\n type PreloadOptions,\n type PullRow,\n type Query,\n} from './query.ts';\nimport {DEFAULT_TTL, type TTL} from './ttl.ts';\nimport type {TypedView} from './typed-view.ts';\n\ntype AnyQuery = Query<Schema, string, any>;\n\nconst astSymbol = Symbol();\n\nexport function ast(query: Query<Schema, string, any>): AST {\n return (query as AbstractQuery<Schema, string>)[astSymbol];\n}\n\nexport function newQuery<\n TSchema extends Schema,\n TTable extends keyof TSchema['tables'] & string,\n>(\n delegate: QueryDelegate,\n schema: TSchema,\n table: TTable,\n): Query<TSchema, TTable> {\n return new QueryImpl(delegate, schema, table, {table}, defaultFormat);\n}\n\nfunction newQueryWithDetails<\n TSchema extends Schema,\n TTable extends keyof TSchema['tables'] & string,\n TReturn,\n>(\n delegate: QueryDelegate,\n schema: TSchema,\n tableName: TTable,\n ast: AST,\n format: Format,\n): QueryImpl<TSchema, TTable, TReturn> {\n return new QueryImpl(delegate, schema, tableName, ast, format);\n}\n\nexport type CommitListener = () => void;\nexport type GotCallback = (got: boolean) => void;\nexport interface QueryDelegate extends BuilderDelegate {\n addServerQuery(\n ast: AST,\n ttl: TTL,\n gotCallback?: GotCallback | undefined,\n ): () => void;\n updateServerQuery(ast: AST, ttl: TTL): void;\n onTransactionCommit(cb: CommitListener): () => void;\n batchViewUpdates<T>(applyViewUpdates: () => T): T;\n onQueryMaterialized(hash: string, ast: AST, duration: number): void;\n}\n\nexport function staticParam(\n anchorClass: 'authData' | 'preMutationRow',\n field: string | string[],\n): Parameter {\n return {\n type: 'static',\n anchor: anchorClass,\n // for backwards compatibility\n field: field.length === 1 ? field[0] : field,\n };\n}\n\nexport const SUBQ_PREFIX = 'zsubq_';\n\nexport const defaultFormat = {singular: false, relationships: {}} as const;\n\nexport abstract class AbstractQuery<\n TSchema extends Schema,\n TTable extends keyof TSchema['tables'] & string,\n TReturn = PullRow<TTable, TSchema>,\n> implements Query<TSchema, TTable, TReturn>\n{\n readonly #schema: TSchema;\n readonly #tableName: TTable;\n readonly #ast: AST;\n readonly format: Format;\n #hash: string = '';\n\n constructor(schema: TSchema, tableName: TTable, ast: AST, format: Format) {\n this.#schema = schema;\n this.#tableName = tableName;\n this.#ast = ast;\n this.format = format;\n }\n\n get [astSymbol](): AST {\n return this.#ast;\n }\n\n hash(): string {\n if (!this.#hash) {\n this.#hash = hashOfAST(this._completeAst());\n }\n return this.#hash;\n }\n\n protected abstract _system: System;\n\n protected abstract _newQuery<\n TSchema extends Schema,\n TTable extends keyof TSchema['tables'] & string,\n TReturn,\n >(\n schema: TSchema,\n table: TTable,\n ast: AST,\n format: Format,\n ): AbstractQuery<TSchema, TTable, TReturn>;\n\n one(): Query<TSchema, TTable, TReturn | undefined> {\n return this._newQuery(\n this.#schema,\n this.#tableName,\n {\n ...this.#ast,\n limit: 1,\n },\n {\n ...this.format,\n singular: true,\n },\n );\n }\n whereExists(\n relationship: string,\n cb?: (q: AnyQuery) => AnyQuery,\n ): Query<TSchema, TTable, TReturn> {\n return this.where(({exists}) => exists(relationship, cb));\n }\n\n related(relationship: string, cb?: (q: AnyQuery) => AnyQuery): AnyQuery {\n if (relationship.startsWith(SUBQ_PREFIX)) {\n throw new Error(\n `Relationship names may not start with \"${SUBQ_PREFIX}\". That is a reserved prefix.`,\n );\n }\n cb = cb ?? (q => q);\n\n const related = this.#schema.relationships[this.#tableName][relationship];\n assert(related, 'Invalid relationship');\n if (isOneHop(related)) {\n const {destSchema, destField, sourceField, cardinality} = related[0];\n let q: AnyQuery = this._newQuery(\n this.#schema,\n destSchema,\n {\n table: destSchema,\n alias: relationship,\n },\n {\n relationships: {},\n singular: cardinality === 'one',\n },\n );\n if (cardinality === 'one') {\n q = q.one();\n }\n const sq = cb(q) as AbstractQuery<Schema, string>;\n assert(\n isCompoundKey(sourceField),\n 'The source of a relationship must specify at last 1 field',\n );\n assert(\n isCompoundKey(destField),\n 'The destination of a relationship must specify at last 1 field',\n );\n assert(\n sourceField.length === destField.length,\n 'The source and destination of a relationship must have the same number of fields',\n );\n\n return this._newQuery(\n this.#schema,\n this.#tableName,\n {\n ...this.#ast,\n related: [\n ...(this.#ast.related ?? []),\n {\n system: this._system,\n correlation: {\n parentField: sourceField,\n childField: destField,\n },\n subquery: addPrimaryKeysToAst(\n this.#schema.tables[destSchema],\n sq.#ast,\n ),\n },\n ],\n },\n {\n ...this.format,\n relationships: {\n ...this.format.relationships,\n [relationship]: sq.format,\n },\n },\n );\n }\n\n if (isTwoHop(related)) {\n const [firstRelation, secondRelation] = related;\n const {destSchema} = secondRelation;\n const junctionSchema = firstRelation.destSchema;\n const sq = cb(\n this._newQuery(\n this.#schema,\n destSchema,\n {\n table: destSchema,\n alias: relationship,\n },\n {\n relationships: {},\n singular: secondRelation.cardinality === 'one',\n },\n ),\n ) as unknown as QueryImpl<Schema, string>;\n\n assert(isCompoundKey(firstRelation.sourceField), 'Invalid relationship');\n assert(isCompoundKey(firstRelation.destField), 'Invalid relationship');\n assert(isCompoundKey(secondRelation.sourceField), 'Invalid relationship');\n assert(isCompoundKey(secondRelation.destField), 'Invalid relationship');\n\n return this._newQuery(\n this.#schema,\n this.#tableName,\n {\n ...this.#ast,\n related: [\n ...(this.#ast.related ?? []),\n {\n system: this._system,\n correlation: {\n parentField: firstRelation.sourceField,\n childField: firstRelation.destField,\n },\n hidden: true,\n subquery: {\n table: junctionSchema,\n alias: relationship,\n orderBy: addPrimaryKeys(\n this.#schema.tables[junctionSchema],\n undefined,\n ),\n related: [\n {\n system: this._system,\n correlation: {\n parentField: secondRelation.sourceField,\n childField: secondRelation.destField,\n },\n subquery: addPrimaryKeysToAst(\n this.#schema.tables[destSchema],\n sq.#ast,\n ),\n },\n ],\n },\n },\n ],\n },\n {\n ...this.format,\n relationships: {\n ...this.format.relationships,\n [relationship]: sq.format,\n },\n },\n );\n }\n\n throw new Error(`Invalid relationship ${relationship}`);\n }\n\n where(\n fieldOrExpressionFactory: string | ExpressionFactory<TSchema, TTable>,\n opOrValue?: SimpleOperator | GetFilterType<any, any, any> | Parameter,\n value?: GetFilterType<any, any, any> | Parameter,\n ): Query<TSchema, TTable, TReturn> {\n let cond: Condition;\n\n if (typeof fieldOrExpressionFactory === 'function') {\n cond = fieldOrExpressionFactory(\n new ExpressionBuilder(this._exists) as ExpressionBuilder<\n TSchema,\n TTable\n >,\n );\n } else {\n assert(opOrValue !== undefined, 'Invalid condition');\n cond = cmp(fieldOrExpressionFactory, opOrValue, value);\n }\n\n const existingWhere = this.#ast.where;\n if (existingWhere) {\n cond = and(existingWhere, cond);\n }\n\n return this._newQuery(\n this.#schema,\n this.#tableName,\n {\n ...this.#ast,\n where: dnf(cond),\n },\n this.format,\n );\n }\n\n start(\n row: Partial<PullRow<TTable, TSchema>>,\n opts?: {inclusive: boolean} | undefined,\n ): Query<TSchema, TTable, TReturn> {\n return this._newQuery(\n this.#schema,\n this.#tableName,\n {\n ...this.#ast,\n start: {\n row,\n exclusive: !opts?.inclusive,\n },\n },\n this.format,\n );\n }\n\n limit(limit: number): Query<TSchema, TTable, TReturn> {\n if (limit < 0) {\n throw new Error('Limit must be non-negative');\n }\n if ((limit | 0) !== limit) {\n throw new Error('Limit must be an integer');\n }\n\n return this._newQuery(\n this.#schema,\n this.#tableName,\n {\n ...this.#ast,\n limit,\n },\n this.format,\n );\n }\n\n orderBy<TSelector extends keyof TSchema['tables'][TTable]['columns']>(\n field: TSelector,\n direction: 'asc' | 'desc',\n ): Query<TSchema, TTable, TReturn> {\n return this._newQuery(\n this.#schema,\n this.#tableName,\n {\n ...this.#ast,\n orderBy: [...(this.#ast.orderBy ?? []), [field as string, direction]],\n },\n this.format,\n );\n }\n\n protected _exists = (\n relationship: string,\n cb: (query: AnyQuery) => AnyQuery = q => q,\n ): Condition => {\n const related = this.#schema.relationships[this.#tableName][relationship];\n assert(related, 'Invalid relationship');\n\n if (isOneHop(related)) {\n const {destSchema, sourceField, destField} = related[0];\n assert(isCompoundKey(sourceField), 'Invalid relationship');\n assert(isCompoundKey(destField), 'Invalid relationship');\n\n const sq = cb(\n this._newQuery(\n this.#schema,\n destSchema,\n {\n table: destSchema,\n alias: `${SUBQ_PREFIX}${relationship}`,\n },\n defaultFormat,\n ),\n ) as unknown as QueryImpl<any, any>;\n return {\n type: 'correlatedSubquery',\n related: {\n system: this._system,\n correlation: {\n parentField: sourceField,\n childField: destField,\n },\n subquery: addPrimaryKeysToAst(\n this.#schema.tables[destSchema],\n sq.#ast,\n ),\n },\n op: 'EXISTS',\n };\n }\n\n if (isTwoHop(related)) {\n const [firstRelation, secondRelation] = related;\n assert(isCompoundKey(firstRelation.sourceField), 'Invalid relationship');\n assert(isCompoundKey(firstRelation.destField), 'Invalid relationship');\n assert(isCompoundKey(secondRelation.sourceField), 'Invalid relationship');\n assert(isCompoundKey(secondRelation.destField), 'Invalid relationship');\n const {destSchema} = secondRelation;\n const junctionSchema = firstRelation.destSchema;\n const queryToDest = cb(\n this._newQuery(\n this.#schema,\n destSchema,\n {\n table: destSchema,\n alias: `${SUBQ_PREFIX}${relationship}`,\n },\n defaultFormat,\n ),\n );\n\n return {\n type: 'correlatedSubquery',\n related: {\n system: this._system,\n correlation: {\n parentField: firstRelation.sourceField,\n childField: firstRelation.destField,\n },\n subquery: {\n table: junctionSchema,\n alias: `${SUBQ_PREFIX}${relationship}`,\n orderBy: addPrimaryKeys(\n this.#schema.tables[junctionSchema],\n undefined,\n ),\n where: {\n type: 'correlatedSubquery',\n related: {\n system: this._system,\n correlation: {\n parentField: secondRelation.sourceField,\n childField: secondRelation.destField,\n },\n\n subquery: addPrimaryKeysToAst(\n this.#schema.tables[destSchema],\n (queryToDest as QueryImpl<any, any>).#ast,\n ),\n },\n op: 'EXISTS',\n },\n },\n },\n op: 'EXISTS',\n };\n }\n\n throw new Error(`Invalid relationship ${relationship}`);\n };\n\n #completedAST: AST | undefined;\n\n protected _completeAst(): AST {\n if (!this.#completedAST) {\n const finalOrderBy = addPrimaryKeys(\n this.#schema.tables[this.#tableName],\n this.#ast.orderBy,\n );\n if (this.#ast.start) {\n const {row} = this.#ast.start;\n const narrowedRow: Writable<IVMRow> = {};\n for (const [field] of finalOrderBy) {\n narrowedRow[field] = row[field];\n }\n this.#completedAST = {\n ...this.#ast,\n start: {\n ...this.#ast.start,\n row: narrowedRow,\n },\n orderBy: finalOrderBy,\n };\n } else {\n this.#completedAST = {\n ...this.#ast,\n orderBy: addPrimaryKeys(\n this.#schema.tables[this.#tableName],\n this.#ast.orderBy,\n ),\n };\n }\n }\n return this.#completedAST;\n }\n\n then<TResult1 = HumanReadable<TReturn>, TResult2 = never>(\n onFulfilled?:\n | ((value: HumanReadable<TReturn>) => TResult1 | PromiseLike<TResult1>)\n | undefined\n | null,\n onRejected?:\n | ((reason: any) => TResult2 | PromiseLike<TResult2>)\n | undefined\n | null,\n ): PromiseLike<TResult1 | TResult2> {\n return this.run().then(onFulfilled, onRejected);\n }\n\n abstract materialize(): TypedView<HumanReadable<TReturn>>;\n abstract materialize<T>(factory: ViewFactory<TSchema, TTable, TReturn, T>): T;\n\n abstract run(): Promise<HumanReadable<TReturn>>;\n\n abstract preload(): {\n cleanup: () => void;\n complete: Promise<void>;\n };\n}\n\nconst completedAstSymbol = Symbol();\n\nexport function completedAST(q: Query<Schema, string, any>) {\n return (q as QueryImpl<Schema, string>)[completedAstSymbol];\n}\n\nexport class QueryImpl<\n TSchema extends Schema,\n TTable extends keyof TSchema['tables'] & string,\n TReturn = PullRow<TTable, TSchema>,\n> extends AbstractQuery<TSchema, TTable, TReturn> {\n readonly #delegate: QueryDelegate;\n\n constructor(\n delegate: QueryDelegate,\n schema: TSchema,\n tableName: TTable,\n ast: AST,\n format: Format,\n ) {\n super(schema, tableName, ast, format);\n this.#delegate = delegate;\n }\n\n protected readonly _system = 'client';\n\n get [completedAstSymbol](): AST {\n return this._completeAst();\n }\n\n protected _newQuery<TSchema extends Schema, TTable extends string, TReturn>(\n schema: TSchema,\n tableName: TTable,\n ast: AST,\n format: Format,\n ): QueryImpl<TSchema, TTable, TReturn> {\n return newQueryWithDetails(this.#delegate, schema, tableName, ast, format);\n }\n\n materialize<T>(\n factoryOrTTL?: ViewFactory<TSchema, TTable, TReturn, T> | TTL,\n ttl: TTL = DEFAULT_TTL,\n ): T {\n const t0 = Date.now();\n let factory: ViewFactory<TSchema, TTable, TReturn, T> | undefined;\n if (typeof factoryOrTTL === 'function') {\n factory = factoryOrTTL;\n } else {\n ttl = factoryOrTTL ?? DEFAULT_TTL;\n }\n const ast = this._completeAst();\n const queryCompleteResolver = resolver<true>();\n let queryGot = false;\n const removeServerQuery = this.#delegate.addServerQuery(ast, ttl, got => {\n if (got) {\n const t1 = Date.now();\n this.#delegate.onQueryMaterialized(this.hash(), ast, t1 - t0);\n queryGot = true;\n queryCompleteResolver.resolve(true);\n }\n });\n\n const updateTTL = (newTTL: TTL) => {\n this.#delegate.updateServerQuery(ast, newTTL);\n };\n\n const input = buildPipeline(ast, this.#delegate);\n let removeCommitObserver: (() => void) | undefined;\n\n const onDestroy = () => {\n input.destroy();\n removeCommitObserver?.();\n removeServerQuery();\n };\n\n const view = this.#delegate.batchViewUpdates(() =>\n (factory ?? arrayViewFactory)(\n this,\n input,\n this.format,\n onDestroy,\n cb => {\n removeCommitObserver = this.#delegate.onTransactionCommit(cb);\n },\n queryGot || queryCompleteResolver.promise,\n updateTTL,\n ),\n );\n\n return view as T;\n }\n\n run(): Promise<HumanReadable<TReturn>> {\n const v: TypedView<HumanReadable<TReturn>> = this.materialize();\n const ret = v.data;\n v.destroy();\n return Promise.resolve(ret);\n }\n\n preload(options?: PreloadOptions): {\n cleanup: () => void;\n complete: Promise<void>;\n } {\n const {resolve, promise: complete} = resolver<void>();\n const ast = this._completeAst();\n const unsub = this.#delegate.addServerQuery(\n ast,\n options?.ttl ?? DEFAULT_TTL,\n got => {\n if (got) {\n resolve();\n }\n },\n );\n return {\n cleanup: unsub,\n complete,\n };\n }\n}\n\nfunction addPrimaryKeys(\n schema: TableSchema,\n orderBy: Ordering | undefined,\n): Ordering {\n orderBy = orderBy ?? [];\n const {primaryKey} = schema;\n const primaryKeysToAdd = new Set(primaryKey);\n\n for (const [field] of orderBy) {\n primaryKeysToAdd.delete(field);\n }\n\n if (primaryKeysToAdd.size === 0) {\n return orderBy;\n }\n\n return [\n ...orderBy,\n ...[...primaryKeysToAdd].map(key => [key, 'asc'] as [string, 'asc']),\n ];\n}\n\nfunction addPrimaryKeysToAst(schema: TableSchema, ast: AST): AST {\n return {\n ...ast,\n orderBy: addPrimaryKeys(schema, ast.orderBy),\n };\n}\n\nfunction arrayViewFactory<\n TSchema extends Schema,\n TTable extends string,\n TReturn,\n>(\n _query: AbstractQuery<TSchema, TTable, TReturn>,\n input: Input,\n format: Format,\n onDestroy: () => void,\n onTransactionCommit: (cb: () => void) => void,\n queryComplete: true | Promise<true>,\n updateTTL: (ttl: TTL) => void,\n): TypedView<HumanReadable<TReturn>> {\n const v = new ArrayView<HumanReadable<TReturn>>(\n input,\n format,\n queryComplete,\n updateTTL,\n );\n v.onDestroy = onDestroy;\n onTransactionCommit(() => {\n v.flush();\n });\n return v;\n}\n\nfunction isCompoundKey(field: readonly string[]): field is CompoundKey {\n return Array.isArray(field) && field.length >= 1;\n}\n", "import {h64} from '../../shared/src/hash.ts';\nimport {normalizeAST, type AST} from './ast.ts';\n\nconst hashCache = new WeakMap<AST, string>();\n\nexport function hashOfAST(ast: AST): string {\n const normalized = normalizeAST(ast);\n const cached = hashCache.get(normalized);\n if (cached) {\n return cached;\n }\n const hash = h64(JSON.stringify(normalized)).toString(36);\n hashCache.set(normalized, hash);\n return hash;\n}\n", "import type {JSONValue} from '../../../shared/src/json.ts';\nimport type {Row} from '../../../zero-protocol/src/data.ts';\nimport type {Change} from './change.ts';\nimport type {Constraint} from './constraint.ts';\nimport {type Node} from './data.ts';\nimport type {SourceSchema} from './schema.ts';\nimport type {Stream} from './stream.ts';\n\n/**\n * Input to an operator.\n */\nexport interface Input {\n /** The schema of the data this input returns. */\n getSchema(): SourceSchema;\n\n /**\n * Fetch data. May modify the data in place.\n * Returns nodes sorted in order of `SourceSchema.compareRows`.\n */\n fetch(req: FetchRequest): Stream<Node>;\n\n /**\n * Cleanup maintained state. This is called when `output` will no longer need\n * the data returned by {@linkcode fetch}. The receiving operator should clean up any\n * resources it has allocated to service such requests.\n *\n * This is different from {@linkcode destroy} which means this input will no longer\n * be called at all, for any input.\n *\n * Returns the same thing as {@linkcode fetch}. This allows callers to properly\n * propagate the cleanup message through the graph.\n */\n cleanup(req: FetchRequest): Stream<Node>;\n\n /** Tell the input where to send its output. */\n setOutput(output: Output): void;\n\n /**\n * Completely destroy the input. Destroying an input\n * causes it to call destroy on its upstreams, fully\n * cleaning up a pipeline.\n */\n destroy(): void;\n}\n\nexport type FetchRequest = {\n readonly constraint?: Constraint | undefined;\n /** If supplied, `start.row` must have previously been output by fetch or push. */\n readonly start?: Start | undefined;\n\n /** Whether to fetch in reverse order of the SourceSchema's sort. */\n readonly reverse?: boolean | undefined;\n};\n\nexport type Start = {\n readonly row: Row;\n readonly basis: 'at' | 'after';\n};\n\n/**\n * An output for an operator. Typically another Operator but can also be\n * the code running the pipeline.\n */\nexport interface Output {\n /**\n * Push incremental changes to data previously received with fetch().\n * Consumers must apply all pushed changes or incremental result will\n * be incorrect.\n * Callers must maintain some invariants for correct operation:\n * - Only add rows which do not already exist (by deep equality).\n * - Only remove rows which do exist (by deep equality).\n */\n push(change: Change): void;\n}\n\n/**\n * An implementation of Output that throws if pushed to. It is used as the\n * initial value for for an operator's output before it is set.\n */\nexport const throwOutput: Output = {\n push(_change: Change): void {\n throw new Error('Output not set');\n },\n};\n\n/**\n * Operators are arranged into pipelines.\n * They are stateful.\n * Each operator is an input to the next operator in the chain and an output\n * to the previous.\n */\nexport interface Operator extends Input, Output {}\n\n/**\n * Operators get access to storage that they can store their internal\n * state in.\n */\nexport interface Storage {\n set(key: string, value: JSONValue): void;\n get(key: string, def?: JSONValue): JSONValue | undefined;\n /**\n * If options is not specified, defaults to scanning all entries.\n */\n scan(options?: {prefix: string}): Stream<[string, JSONValue]>;\n del(key: string): void;\n}\n", "/**\n * streams are lazy forward-only iterables.\n * Once a stream reaches the end it can't be restarted.\n * They are iterable, not iterator, so that they can be used in for-each,\n * and so that we know when consumer has stopped iterating the stream. This allows us\n * to clean up resources like sql statements.\n */\nexport type Stream<T> = Iterable<T>;\n\nexport function* take<T>(stream: Stream<T>, limit: number): Stream<T> {\n if (limit < 1) {\n return;\n }\n let count = 0;\n for (const v of stream) {\n yield v;\n if (++count === limit) {\n break;\n }\n }\n}\n\nexport function first<T>(stream: Stream<T>): T | undefined {\n const it = stream[Symbol.iterator]();\n const {value} = it.next();\n it.return?.();\n return value;\n}\n", "import {areEqual} from '../../../shared/src/arrays.ts';\nimport {assert, unreachable} from '../../../shared/src/asserts.ts';\nimport type {CompoundKey} from '../../../zero-protocol/src/ast.ts';\nimport {type Change} from './change.ts';\nimport {\n drainStreams,\n normalizeUndefined,\n type Node,\n type NormalizedValue,\n} from './data.ts';\nimport {\n throwOutput,\n type FetchRequest,\n type Input,\n type Operator,\n type Output,\n type Storage,\n} from './operator.ts';\nimport type {SourceSchema} from './schema.ts';\nimport {first} from './stream.ts';\n\ntype SizeStorageKeyPrefix = `row/${string}/`;\n/**\n * Key is of format\n * `row/${JSON.stringify(parentJoinKeyValues)}/${JSON.stringify(primaryKeyValues)}`\n * This format allows us to look up an existing cached size for a given set of\n * `parentJoinKeyValues` by scanning for prefix\n * `row/${JSON.stringify(parentJoinKeyValues)}/` and using the first result, and\n * to look up the cached size for a specific row by the full key.\n * If the parent join and primary key are the same, then format is changed to\n * `row//${JSON.stringify(primaryKeyValues)}` to shorten the key, since there\n * is no point in looking up an existing cached size by\n * `parentJoinKeyValues` if the specific rows cached size is missing.\n */\ntype SizeStorageKey = `${SizeStorageKeyPrefix}${string}`;\n\ninterface ExistsStorage {\n get(key: SizeStorageKey): number | undefined;\n set(key: SizeStorageKey, value: number): void;\n del(key: SizeStorageKey): void;\n scan({prefix}: {prefix: SizeStorageKeyPrefix}): Iterable<[string, number]>;\n}\n\n/**\n * The Exists operator filters data based on whether or not a relationship is\n * non-empty.\n */\nexport class Exists implements Operator {\n readonly #input: Input;\n readonly #relationshipName: string;\n readonly #storage: ExistsStorage;\n readonly #not: boolean;\n readonly #parentJoinKey: CompoundKey;\n readonly #noSizeReuse: boolean;\n\n #output: Output = throwOutput;\n\n /**\n * This instance variable is `true` when this operator is processing a `push`,\n * and is used to disable reuse of cached sizes across rows with the\n * same parent join key value.\n * This is necessary because during a push relationships can be inconsistent\n * due to push communicating changes (which may change multiple Nodes) one\n * Node at a time.\n */\n #inPush = false;\n\n constructor(\n input: Input,\n storage: Storage,\n relationshipName: string,\n parentJoinKey: CompoundKey,\n type: 'EXISTS' | 'NOT EXISTS',\n ) {\n this.#input = input;\n this.#relationshipName = relationshipName;\n this.#input.setOutput(this);\n this.#storage = storage as ExistsStorage;\n assert(\n this.#input.getSchema().relationships[relationshipName],\n `Input schema missing ${relationshipName}`,\n );\n this.#not = type === 'NOT EXISTS';\n this.#parentJoinKey = parentJoinKey;\n\n // If the parentJoinKey is the primary key, no sense in trying to reuse.\n this.#noSizeReuse = areEqual(\n parentJoinKey,\n this.#input.getSchema().primaryKey,\n );\n }\n\n setOutput(output: Output) {\n this.#output = output;\n }\n\n destroy(): void {\n this.#input.destroy();\n }\n\n getSchema(): SourceSchema {\n return this.#input.getSchema();\n }\n\n *fetch(req: FetchRequest) {\n for (const node of this.#input.fetch(req)) {\n if (this.#filter(node)) {\n yield node;\n }\n }\n }\n\n *cleanup(req: FetchRequest) {\n for (const node of this.#input.cleanup(req)) {\n if (this.#filter(node)) {\n yield node;\n } else {\n drainStreams(node);\n }\n this.#delSize(node);\n }\n }\n\n push(change: Change) {\n this.#inPush = true;\n try {\n switch (change.type) {\n // add, remove and edit cannot change the size of the\n // this.#relationshipName relationship, so simply #pushWithFilter\n case 'add':\n case 'edit': {\n this.#pushWithFilter(change);\n return;\n }\n case 'remove': {\n const size = this.#getSize(change.node);\n // If size is undefined, this operator has not output\n // this row before and so it is unnecessary to output a remove for\n // it.\n if (size === undefined) {\n return;\n }\n this.#pushWithFilter(change, size);\n this.#delSize(change.node);\n return;\n }\n case 'child':\n // Only add and remove child changes for the\n // this.#relationshipName relationship, can change the size\n // of the this.#relationshipName relationship, for other\n // child changes simply #pushWithFilter\n if (\n change.child.relationshipName !== this.#relationshipName ||\n change.child.change.type === 'edit' ||\n change.child.change.type === 'child'\n ) {\n this.#pushWithFilter(change);\n return;\n }\n switch (change.child.change.type) {\n case 'add': {\n let size = this.#getSize(change.node);\n if (size !== undefined) {\n size++;\n this.#setSize(change.node, size);\n } else {\n size = this.#fetchSize(change.node);\n }\n if (size === 1) {\n if (this.#not) {\n // Since the add child change currently being processed is not\n // pushed to output, the added child needs to be excluded from\n // the remove being pushed to output (since the child has\n // never been added to the output).\n this.#output.push({\n type: 'remove',\n node: {\n row: change.node.row,\n relationships: {\n ...change.node.relationships,\n [this.#relationshipName]: () => [],\n },\n },\n });\n } else {\n this.#output.push({\n type: 'add',\n node: change.node,\n });\n }\n } else {\n this.#pushWithFilter(change, size);\n }\n return;\n }\n case 'remove': {\n let size = this.#getSize(change.node);\n if (size !== undefined) {\n assert(size > 0);\n size--;\n this.#setSize(change.node, size);\n } else {\n size = this.#fetchSize(change.node);\n }\n if (size === 0) {\n if (this.#not) {\n this.#output.push({\n type: 'add',\n node: change.node,\n });\n } else {\n // Since the remove child change currently being processed is\n // not pushed to output, the removed child needs to be added to\n // the remove being pushed to output.\n this.#output.push({\n type: 'remove',\n node: {\n row: change.node.row,\n relationships: {\n ...change.node.relationships,\n [this.#relationshipName]: () => [\n change.child.change.node,\n ],\n },\n },\n });\n }\n } else {\n this.#pushWithFilter(change, size);\n }\n return;\n }\n }\n return;\n default:\n unreachable(change);\n }\n } finally {\n this.#inPush = false;\n }\n }\n\n /**\n * Returns whether or not the node's this.#relationshipName\n * relationship passes the exist/not exists filter condition.\n * If the optional `size` is passed it is used.\n * Otherwise, if there is a stored size for the row it is used.\n * Otherwise the size is computed by streaming the node's\n * relationship with this.#relationshipName (this computed size is also\n * stored).\n */\n #filter(node: Node, size?: number): boolean {\n const exists = (size ?? this.#getOrFetchSize(node)) > 0;\n return this.#not ? !exists : exists;\n }\n\n /**\n * Pushes a change if this.#filter is true for its row.\n */\n #pushWithFilter(change: Change, size?: number): void {\n if (this.#filter(change.node, size)) {\n this.#output.push(change);\n }\n }\n\n #getSize(node: Node): number | undefined {\n return this.#storage.get(this.#makeSizeStorageKey(node));\n }\n\n #setSize(node: Node, size: number) {\n this.#storage.set(this.#makeSizeStorageKey(node), size);\n }\n\n #delSize(node: Node) {\n this.#storage.del(this.#makeSizeStorageKey(node));\n }\n\n #getOrFetchSize(node: Node): number {\n const size = this.#getSize(node);\n if (size !== undefined) {\n return size;\n }\n return this.#fetchSize(node);\n }\n\n #fetchSize(node: Node): number {\n if (!this.#noSizeReuse && !this.#inPush) {\n const cachedSizeEntry = first(\n this.#storage.scan({\n prefix: this.#makeSizeStorageKeyPrefix(node),\n }),\n );\n if (cachedSizeEntry !== undefined) {\n this.#setSize(node, cachedSizeEntry[1]);\n return cachedSizeEntry[1];\n }\n }\n\n const relationship = node.relationships[this.#relationshipName];\n assert(relationship);\n let size = 0;\n for (const _relatedNode of relationship()) {\n size++;\n }\n\n this.#setSize(node, size);\n return size;\n }\n\n #makeSizeStorageKeyPrefix(node: Node): SizeStorageKeyPrefix {\n return `row/${\n this.#noSizeReuse\n ? ''\n : JSON.stringify(this.#getKeyValues(node, this.#parentJoinKey))\n }/`;\n }\n\n #makeSizeStorageKey(node: Node): SizeStorageKey {\n return `${this.#makeSizeStorageKeyPrefix(node)}${JSON.stringify(\n this.#getKeyValues(node, this.#input.getSchema().primaryKey),\n )}`;\n }\n\n #getKeyValues(node: Node, def: CompoundKey): NormalizedValue[] {\n const values: NormalizedValue[] = [];\n for (const key of def) {\n values.push(normalizeUndefined(node.row[key]));\n }\n return values;\n }\n}\n", "import {assert} from './asserts.ts';\n\nexport function* joinIterables<T>(...iters: Iterable<T>[]) {\n for (const iter of iters) {\n yield* iter;\n }\n}\n\nfunction* filterIter<T>(\n iter: Iterable<T>,\n p: (t: T, index: number) => boolean,\n): Iterable<T> {\n let index = 0;\n for (const t of iter) {\n if (p(t, index++)) {\n yield t;\n }\n }\n}\n\nfunction* mapIter<T, U>(\n iter: Iterable<T>,\n f: (t: T, index: number) => U,\n): Iterable<U> {\n let index = 0;\n for (const t of iter) {\n yield f(t, index++);\n }\n}\n\nexport function first<T>(stream: Iterable<T>): T | undefined {\n const it = stream[Symbol.iterator]();\n const {value} = it.next();\n it.return?.();\n return value;\n}\n\n// TODO(arv): Use ES2024 Iterable.from when available\n// https://github.com/tc39/proposal-iterator-helpers\n\nclass IterWrapper<T> implements Iterable<T> {\n iter: Iterable<T>;\n constructor(iter: Iterable<T>) {\n this.iter = iter;\n }\n\n [Symbol.iterator]() {\n return this.iter[Symbol.iterator]();\n }\n\n map<U>(f: (t: T, index: number) => U): IterWrapper<U> {\n return new IterWrapper(mapIter(this.iter, f));\n }\n\n filter(p: (t: T, index: number) => boolean): IterWrapper<T> {\n return new IterWrapper(filterIter(this.iter, p));\n }\n}\n\nexport function wrapIterable<T>(iter: Iterable<T>): IterWrapper<T> {\n return new IterWrapper(iter);\n}\n\nexport function* mergeIterables<T>(\n iterables: Iterable<T>[],\n comparator: (l: T, r: T) => number,\n distinct = false,\n): IterableIterator<T> {\n const iterators = iterables.map(i => i[Symbol.iterator]());\n try {\n const current = iterators.map(i => i.next());\n let lastYielded: T | undefined;\n while (current.some(c => !c.done)) {\n const min = current.reduce(\n (acc: [T, number] | undefined, c, i): [T, number] | undefined => {\n if (c.done) {\n return acc;\n }\n if (acc === undefined || comparator(c.value, acc[0]) < 0) {\n return [c.value, i];\n }\n return acc;\n },\n undefined,\n );\n\n assert(min !== undefined, 'min is undefined');\n current[min[1]] = iterators[min[1]].next();\n if (\n lastYielded !== undefined &&\n distinct &&\n comparator(lastYielded, min[0]) === 0\n ) {\n continue;\n }\n lastYielded = min[0];\n yield min[0];\n }\n } finally {\n for (const it of iterators) {\n it.return?.();\n }\n }\n}\n", "import {assert} from '../../../shared/src/asserts.ts';\nimport {mergeIterables} from '../../../shared/src/iterables.ts';\nimport {must} from '../../../shared/src/must.ts';\nimport type {Change} from './change.ts';\nimport type {Node} from './data.ts';\nimport type {FanOut} from './fan-out.ts';\nimport {\n throwOutput,\n type FetchRequest,\n type Input,\n type Operator,\n type Output,\n} from './operator.ts';\nimport type {SourceSchema} from './schema.ts';\nimport type {Stream} from './stream.ts';\n\n/**\n * The FanIn operator merges multiple streams into one.\n * It eliminates duplicates and must be paired with a fan-out operator\n * somewhere upstream of the fan-in.\n *\n * issue\n * |\n * fan-out\n * / \\\n * a b\n * \\ /\n * fan-in\n * |\n */\nexport class FanIn implements Operator {\n readonly #inputs: readonly Input[];\n readonly #schema: SourceSchema;\n #output: Output = throwOutput;\n #accumulatedPushes: Change[];\n\n constructor(fanOut: FanOut, inputs: Input[]) {\n this.#inputs = inputs;\n this.#schema = fanOut.getSchema();\n for (const input of inputs) {\n input.setOutput(this);\n assert(this.#schema === input.getSchema(), `Schema mismatch in fan-in`);\n }\n this.#accumulatedPushes = [];\n }\n\n setOutput(output: Output): void {\n this.#output = output;\n }\n\n destroy(): void {\n for (const input of this.#inputs) {\n input.destroy();\n }\n }\n\n getSchema() {\n return this.#schema;\n }\n\n fetch(req: FetchRequest): Stream<Node> {\n return this.#fetchOrCleanup(input => input.fetch(req));\n }\n\n cleanup(req: FetchRequest): Stream<Node> {\n return this.#fetchOrCleanup(input => input.cleanup(req));\n }\n\n *#fetchOrCleanup(streamProvider: (input: Input) => Stream<Node>) {\n const iterables = this.#inputs.map(input => streamProvider(input));\n yield* mergeIterables(\n iterables,\n (l, r) => must(this.#schema).compareRows(l.row, r.row),\n true,\n );\n }\n\n push(change: Change) {\n this.#accumulatedPushes.push(change);\n }\n\n fanOutDonePushingToAllBranches(fanOutChangeType: Change['type']) {\n if (this.#inputs.length === 0) {\n assert(\n this.#accumulatedPushes.length === 0,\n 'If there are no inputs then fan-in should not receive any pushes.',\n );\n return;\n }\n\n if (this.#accumulatedPushes.length === 0) {\n // It is possible for no forks to pass along the push.\n // E.g., if no filters match in any fork.\n return;\n }\n\n // collapse down to a single change per type\n const candidatesToPush = new Map<Change['type'], Change>();\n for (const change of this.#accumulatedPushes) {\n if (fanOutChangeType === 'child' && change.type !== 'child') {\n assert(\n candidatesToPush.has(change.type) === false,\n () =>\n `Fan-in:child expected at most one ${change.type} when fan-out is of type child`,\n );\n }\n candidatesToPush.set(change.type, change);\n }\n\n this.#accumulatedPushes = [];\n\n const types = [...candidatesToPush.keys()];\n /**\n * Based on the received `fanOutChangeType` only certain output types are valid.\n *\n * - remove must result in all removes\n * - add must result in all adds\n * - edit must result in add or removes or edits\n * - child must result in a single add or single remove or many child changes\n */\n switch (fanOutChangeType) {\n case 'remove':\n assert(\n types.length === 1 && types[0] === 'remove',\n 'Fan-in:remove expected all removes',\n );\n this.#output.push(must(candidatesToPush.get('remove')));\n return;\n case 'add':\n assert(\n types.length === 1 && types[0] === 'add',\n 'Fan-in:add expected all adds',\n );\n this.#output.push(must(candidatesToPush.get('add')));\n return;\n case 'edit': {\n assert(\n types.every(\n type => type === 'add' || type === 'remove' || type === 'edit',\n ),\n 'Fan-in:edit expected all adds, removes, or edits',\n );\n const addChange = candidatesToPush.get('add');\n const removeChange = candidatesToPush.get('remove');\n const editChange = candidatesToPush.get('edit');\n\n // If an `edit` is present, it supersedes `add` and `remove`\n // as it semantically represents both.\n if (editChange) {\n this.#output.push(editChange);\n return;\n }\n\n // If `edit` didn't make it through but both `add` and `remove` did,\n // convert back to an edit.\n //\n // When can this happen?\n //\n // EDIT old: a=1, new: a=2\n // |\n // FanOut\n // / \\\n // a=1 a=2\n // | |\n // remove add\n // \\ /\n // FanIn\n //\n // The left filter converts the edit into a remove.\n // The right filter converts the edit into an add.\n if (addChange && removeChange) {\n this.#output.push({\n type: 'edit',\n node: addChange.node,\n oldNode: removeChange.node,\n } as const);\n return;\n }\n\n this.#output.push(must(addChange ?? removeChange));\n return;\n }\n case 'child': {\n assert(\n types.every(\n type =>\n type === 'add' || // exists can change child to add or remove\n type === 'remove' || // exists can change child to add or remove\n type === 'child', // other operators may preserve the child change\n ),\n 'Fan-in:child expected all adds, removes, or children',\n );\n assert(\n types.length <= 2,\n 'Fan-in:child expected at most 2 types on a child change from fan-out',\n );\n\n // If any branch preserved the original child change, that takes precedence over all other changes.\n const childChange = candidatesToPush.get('child');\n if (childChange) {\n this.#output.push(childChange);\n return;\n }\n\n const addChange = candidatesToPush.get('add');\n const removeChange = candidatesToPush.get('remove');\n\n assert(\n addChange === undefined || removeChange === undefined,\n 'Fan-in:child expected either add or remove, not both',\n );\n\n this.#output.push(must(addChange ?? removeChange));\n return;\n }\n default:\n fanOutChangeType satisfies never;\n }\n }\n}\n", "import {must} from '../../../shared/src/must.ts';\nimport type {Change} from './change.ts';\nimport type {FanIn} from './fan-in.ts';\nimport type {FetchRequest, Input, Operator, Output} from './operator.ts';\n\n/**\n * Forks a stream into multiple streams.\n * Is meant to be paired with a `FanIn` operator which will\n * later merge the forks back together.\n */\nexport class FanOut implements Operator {\n readonly #input: Input;\n readonly #outputs: Output[] = [];\n #fanIn: FanIn | undefined;\n #destroyCount: number = 0;\n\n constructor(input: Input) {\n this.#input = input;\n input.setOutput(this);\n }\n\n setFanIn(fanIn: FanIn) {\n this.#fanIn = fanIn;\n }\n\n setOutput(output: Output): void {\n this.#outputs.push(output);\n }\n\n destroy(): void {\n if (this.#destroyCount < this.#outputs.length) {\n if (this.#destroyCount === 0) {\n this.#input.destroy();\n }\n ++this.#destroyCount;\n } else {\n throw new Error('FanOut already destroyed once for each output');\n }\n }\n\n getSchema() {\n return this.#input.getSchema();\n }\n\n fetch(req: FetchRequest) {\n return this.#input.fetch(req);\n }\n\n cleanup(req: FetchRequest) {\n return this.#input.cleanup(req);\n }\n\n push(change: Change) {\n for (const out of this.#outputs) {\n out.push(change);\n }\n must(\n this.#fanIn,\n 'fan-out must have a corresponding fan-in set!',\n ).fanOutDonePushingToAllBranches(change.type);\n }\n}\n", "import type {Row} from '../../../zero-protocol/src/data.ts';\nimport type {EditChange} from './change.ts';\nimport type {Output} from './operator.ts';\n\n/**\n * This takes an {@linkcode EditChange} and a predicate that determines if a row\n * should be present based on the row's data. It then splits the change and\n * pushes the appropriate changes to the output based on the predicate.\n */\nexport function maybeSplitAndPushEditChange(\n change: EditChange,\n predicate: (row: Row) => boolean,\n output: Output,\n) {\n const oldWasPresent = predicate(change.oldNode.row);\n const newIsPresent = predicate(change.node.row);\n\n if (oldWasPresent && newIsPresent) {\n output.push(change);\n } else if (oldWasPresent && !newIsPresent) {\n output.push({\n type: 'remove',\n node: change.oldNode,\n });\n } else if (!oldWasPresent && newIsPresent) {\n output.push({\n type: 'add',\n node: change.node,\n });\n }\n}\n", "import {unreachable} from '../../../shared/src/asserts.ts';\nimport type {Row} from '../../../zero-protocol/src/data.ts';\nimport type {Change} from './change.ts';\nimport {maybeSplitAndPushEditChange} from './maybe-split-and-push-edit-change.ts';\nimport type {Output} from './operator.ts';\n\nexport function filterPush(\n change: Change,\n output: Output,\n predicate?: ((row: Row) => boolean) | undefined,\n) {\n if (!predicate) {\n output.push(change);\n return;\n }\n switch (change.type) {\n case 'add':\n case 'remove':\n if (predicate(change.node.row)) {\n output.push(change);\n }\n break;\n case 'child':\n if (predicate(change.node.row)) {\n output.push(change);\n }\n break;\n case 'edit':\n maybeSplitAndPushEditChange(change, predicate, output);\n break;\n default:\n unreachable(change);\n }\n}\n", "import type {Row} from '../../../zero-protocol/src/data.ts';\nimport type {Change} from './change.ts';\nimport {drainStreams} from './data.ts';\nimport {filterPush} from './filter-push.ts';\nimport {\n throwOutput,\n type FetchRequest,\n type Input,\n type Operator,\n type Output,\n} from './operator.ts';\nimport type {SourceSchema} from './schema.ts';\n\n/**\n * The Filter operator filters data through a predicate. It is stateless.\n *\n * The predicate must be pure.\n */\nexport class Filter implements Operator {\n readonly #input: Input;\n readonly #predicate: (row: Row) => boolean;\n\n #output: Output = throwOutput;\n\n constructor(input: Input, predicate: (row: Row) => boolean) {\n this.#input = input;\n this.#predicate = predicate;\n input.setOutput(this);\n }\n\n setOutput(output: Output) {\n this.#output = output;\n }\n\n destroy(): void {\n this.#input.destroy();\n }\n\n getSchema(): SourceSchema {\n return this.#input.getSchema();\n }\n\n *fetch(req: FetchRequest) {\n for (const node of this.#input.fetch(req)) {\n if (this.#predicate(node.row)) {\n yield node;\n }\n }\n }\n\n *cleanup(req: FetchRequest) {\n for (const node of this.#input.cleanup(req)) {\n if (this.#predicate(node.row)) {\n yield node;\n } else {\n drainStreams(node);\n }\n }\n }\n\n push(change: Change) {\n filterPush(change, this.#output, this.#predicate);\n }\n}\n", "import {assert, unreachable} from '../../../shared/src/asserts.ts';\nimport type {CompoundKey, System} from '../../../zero-protocol/src/ast.ts';\nimport type {Row, Value} from '../../../zero-protocol/src/data.ts';\nimport type {PrimaryKey} from '../../../zero-protocol/src/primary-key.ts';\nimport type {Change, ChildChange} from './change.ts';\nimport {compareValues, valuesEqual, type Node} from './data.ts';\nimport {\n throwOutput,\n type FetchRequest,\n type Input,\n type Output,\n type Storage,\n} from './operator.ts';\nimport type {SourceSchema} from './schema.ts';\nimport {take, type Stream} from './stream.ts';\n\ntype Args = {\n parent: Input;\n child: Input;\n storage: Storage;\n // The order of the keys does not have to match but the length must match.\n // The nth key in parentKey corresponds to the nth key in childKey.\n parentKey: CompoundKey;\n childKey: CompoundKey;\n\n // TODO: Change parentKey & childKey to a correlation\n\n relationshipName: string;\n hidden: boolean;\n system: System;\n};\n\ntype ChildChangeOverlay = {\n change: Change;\n position: Row | undefined;\n};\n\n/**\n * The Join operator joins the output from two upstream inputs. Zero's join\n * is a little different from SQL's join in that we output hierarchical data,\n * not a flat table. This makes it a lot more useful for UI programming and\n * avoids duplicating tons of data like left join would.\n *\n * The Nodes output from Join have a new relationship added to them, which has\n * the name #relationshipName. The value of the relationship is a stream of\n * child nodes which are the corresponding values from the child source.\n */\nexport class Join implements Input {\n readonly #parent: Input;\n readonly #child: Input;\n readonly #storage: Storage;\n readonly #parentKey: CompoundKey;\n readonly #childKey: CompoundKey;\n readonly #relationshipName: string;\n readonly #schema: SourceSchema;\n\n #output: Output = throwOutput;\n\n #inprogressChildChange: ChildChangeOverlay | undefined;\n\n constructor({\n parent,\n child,\n storage,\n parentKey,\n childKey,\n relationshipName,\n hidden,\n system,\n }: Args) {\n assert(parent !== child, 'Parent and child must be different operators');\n assert(\n parentKey.length === childKey.length,\n 'The parentKey and childKey keys must have same length',\n );\n this.#parent = parent;\n this.#child = child;\n this.#storage = storage;\n this.#parentKey = parentKey;\n this.#childKey = childKey;\n this.#relationshipName = relationshipName;\n\n const parentSchema = parent.getSchema();\n const childSchema = child.getSchema();\n this.#schema = {\n ...parentSchema,\n relationships: {\n ...parentSchema.relationships,\n [relationshipName]: {\n ...childSchema,\n isHidden: hidden,\n system,\n },\n },\n };\n\n parent.setOutput({\n push: (change: Change) => this.#pushParent(change),\n });\n child.setOutput({\n push: (change: Change) => this.#pushChild(change),\n });\n }\n\n destroy(): void {\n this.#parent.destroy();\n this.#child.destroy();\n }\n\n setOutput(output: Output): void {\n this.#output = output;\n }\n\n getSchema(): SourceSchema {\n return this.#schema;\n }\n\n *fetch(req: FetchRequest): Stream<Node> {\n for (const parentNode of this.#parent.fetch(req)) {\n yield this.#processParentNode(\n parentNode.row,\n parentNode.relationships,\n 'fetch',\n );\n }\n }\n\n *cleanup(req: FetchRequest): Stream<Node> {\n for (const parentNode of this.#parent.cleanup(req)) {\n yield this.#processParentNode(\n parentNode.row,\n parentNode.relationships,\n 'cleanup',\n );\n }\n }\n\n #pushParent(change: Change): void {\n switch (change.type) {\n case 'add':\n this.#output.push({\n type: 'add',\n node: this.#processParentNode(\n change.node.row,\n change.node.relationships,\n 'fetch',\n ),\n });\n break;\n case 'remove':\n this.#output.push({\n type: 'remove',\n node: this.#processParentNode(\n change.node.row,\n change.node.relationships,\n 'cleanup',\n ),\n });\n break;\n case 'child':\n this.#output.push({\n type: 'child',\n node: this.#processParentNode(\n change.node.row,\n change.node.relationships,\n 'fetch',\n ),\n child: change.child,\n });\n break;\n case 'edit': {\n // Assert the edit could not change the relationship.\n assert(\n rowEqualsForCompoundKey(\n change.oldNode.row,\n change.node.row,\n this.#parentKey,\n ),\n `Parent edit must not change relationship.`,\n );\n this.#output.push({\n type: 'edit',\n oldNode: this.#processParentNode(\n change.oldNode.row,\n change.oldNode.relationships,\n 'cleanup',\n ),\n node: this.#processParentNode(\n change.node.row,\n change.node.relationships,\n 'fetch',\n ),\n });\n break;\n }\n default:\n unreachable(change);\n }\n }\n\n #pushChild(change: Change): void {\n const pushChildChange = (childRow: Row, change: Change) => {\n this.#inprogressChildChange = {\n change,\n position: undefined,\n };\n try {\n const parentNodes = this.#parent.fetch({\n constraint: Object.fromEntries(\n this.#parentKey.map((key, i) => [key, childRow[this.#childKey[i]]]),\n ),\n });\n\n for (const parentNode of parentNodes) {\n this.#inprogressChildChange.position = parentNode.row;\n const childChange: ChildChange = {\n type: 'child',\n node: this.#processParentNode(\n parentNode.row,\n parentNode.relationships,\n 'fetch',\n ),\n child: {\n relationshipName: this.#relationshipName,\n change,\n },\n };\n this.#output.push(childChange);\n }\n } finally {\n this.#inprogressChildChange = undefined;\n }\n };\n\n switch (change.type) {\n case 'add':\n case 'remove':\n pushChildChange(change.node.row, change);\n break;\n case 'child':\n pushChildChange(change.node.row, change);\n break;\n case 'edit': {\n const childRow = change.node.row;\n const oldChildRow = change.oldNode.row;\n // Assert the edit could not change the relationship.\n assert(\n rowEqualsForCompoundKey(oldChildRow, childRow, this.#childKey),\n 'Child edit must not change relationship.',\n );\n pushChildChange(childRow, change);\n break;\n }\n\n default:\n unreachable(change);\n }\n }\n\n *#generateChildStreamWithOverlay(\n stream: Stream<Node>,\n overlay: Change,\n ): Stream<Node> {\n let applied = false;\n let editOldApplied = false;\n let editNewApplied = false;\n for (const child of stream) {\n let yieldChild = true;\n if (!applied) {\n switch (overlay.type) {\n case 'add': {\n if (\n this.#child\n .getSchema()\n .compareRows(overlay.node.row, child.row) === 0\n ) {\n applied = true;\n yieldChild = false;\n }\n break;\n }\n case 'remove': {\n if (\n this.#child.getSchema().compareRows(overlay.node.row, child.row) <\n 0\n ) {\n applied = true;\n yield overlay.node;\n }\n break;\n }\n case 'edit': {\n if (\n this.#child\n .getSchema()\n .compareRows(overlay.oldNode.row, child.row) < 0\n ) {\n editOldApplied = true;\n if (editNewApplied) {\n applied = true;\n }\n yield overlay.oldNode;\n }\n if (\n this.#child\n .getSchema()\n .compareRows(overlay.node.row, child.row) === 0\n ) {\n editNewApplied = true;\n if (editOldApplied) {\n applied = true;\n }\n yieldChild = false;\n }\n break;\n }\n case 'child': {\n if (\n this.#child\n .getSchema()\n .compareRows(overlay.node.row, child.row) === 0\n ) {\n applied = true;\n yield {\n row: child.row,\n relationships: {\n ...child.relationships,\n [overlay.child.relationshipName]: () =>\n this.#generateChildStreamWithOverlay(\n child.relationships[overlay.child.relationshipName](),\n overlay.child.change,\n ),\n },\n };\n yieldChild = false;\n }\n break;\n }\n }\n }\n if (yieldChild) {\n yield child;\n }\n }\n if (!applied) {\n if (overlay.type === 'remove') {\n applied = true;\n yield overlay.node;\n } else if (overlay.type === 'edit') {\n assert(editNewApplied);\n editOldApplied = true;\n applied = true;\n yield overlay.oldNode;\n }\n }\n\n assert(applied);\n }\n\n #processParentNode(\n parentNodeRow: Row,\n parentNodeRelations: Record<string, () => Stream<Node>>,\n mode: ProcessParentMode,\n ): Node {\n let method: ProcessParentMode = mode;\n let storageUpdated = false;\n const childStream = () => {\n if (!storageUpdated) {\n if (mode === 'cleanup') {\n this.#storage.del(\n makeStorageKey(\n this.#parentKey,\n this.#parent.getSchema().primaryKey,\n parentNodeRow,\n ),\n );\n const empty =\n [\n ...take(\n this.#storage.scan({\n prefix: makeStorageKeyPrefix(parentNodeRow, this.#parentKey),\n }),\n 1,\n ),\n ].length === 0;\n method = empty ? 'cleanup' : 'fetch';\n }\n\n storageUpdated = true;\n // Defer the work to update storage until the child stream\n // is actually accessed\n if (mode === 'fetch') {\n this.#storage.set(\n makeStorageKey(\n this.#parentKey,\n this.#parent.getSchema().primaryKey,\n parentNodeRow,\n ),\n true,\n );\n }\n }\n\n const stream = this.#child[method]({\n constraint: Object.fromEntries(\n this.#childKey.map((key, i) => [\n key,\n parentNodeRow[this.#parentKey[i]],\n ]),\n ),\n });\n\n if (\n this.#inprogressChildChange &&\n this.#isJoinMatch(\n parentNodeRow,\n this.#inprogressChildChange.change.node.row,\n ) &&\n this.#inprogressChildChange.position &&\n this.#schema.compareRows(\n parentNodeRow,\n this.#inprogressChildChange.position,\n ) > 0\n ) {\n return this.#generateChildStreamWithOverlay(\n stream,\n this.#inprogressChildChange.change,\n );\n }\n return stream;\n };\n\n return {\n row: parentNodeRow,\n relationships: {\n ...parentNodeRelations,\n [this.#relationshipName]: childStream,\n },\n };\n }\n\n #isJoinMatch(parent: Row, child: Row) {\n for (let i = 0; i < this.#parentKey.length; i++) {\n if (!valuesEqual(parent[this.#parentKey[i]], child[this.#childKey[i]])) {\n return false;\n }\n }\n return true;\n }\n}\n\ntype ProcessParentMode = 'fetch' | 'cleanup';\n\n/** Exported for testing. */\nexport function makeStorageKeyForValues(values: readonly Value[]): string {\n const json = JSON.stringify(['pKeySet', ...values]);\n return json.substring(1, json.length - 1) + ',';\n}\n\n/** Exported for testing. */\nexport function makeStorageKeyPrefix(row: Row, key: CompoundKey): string {\n return makeStorageKeyForValues(key.map(k => row[k]));\n}\n\n/** Exported for testing.\n * This storage key tracks the primary keys seen for each unique\n * value joined on. This is used to know when to cleanup a child's state.\n */\nexport function makeStorageKey(\n key: CompoundKey,\n primaryKey: PrimaryKey,\n row: Row,\n): string {\n const values: Value[] = key.map(k => row[k]);\n for (const key of primaryKey) {\n values.push(row[key]);\n }\n return makeStorageKeyForValues(values);\n}\n\nfunction rowEqualsForCompoundKey(a: Row, b: Row, key: CompoundKey): boolean {\n for (let i = 0; i < key.length; i++) {\n if (compareValues(a[key[i]], b[key[i]]) !== 0) {\n return false;\n }\n }\n return true;\n}\n", "import type {Row} from '../../../zero-protocol/src/data.ts';\nimport type {AddChange, Change, ChildChange, RemoveChange} from './change.ts';\nimport type {Comparator, Node} from './data.ts';\nimport {maybeSplitAndPushEditChange} from './maybe-split-and-push-edit-change.ts';\nimport {\n throwOutput,\n type FetchRequest,\n type Input,\n type Operator,\n type Output,\n type Start,\n} from './operator.ts';\nimport type {SourceSchema} from './schema.ts';\nimport type {Stream} from './stream.ts';\n\nexport type Bound = {\n row: Row;\n exclusive: boolean;\n};\n\n/**\n * Skip sets the start position for the pipeline. No rows before the bound will\n * be output.\n */\nexport class Skip implements Operator {\n readonly #input: Input;\n readonly #bound: Bound;\n readonly #comparator: Comparator;\n\n #output: Output = throwOutput;\n\n constructor(input: Input, bound: Bound) {\n this.#input = input;\n this.#bound = bound;\n this.#comparator = input.getSchema().compareRows;\n input.setOutput(this);\n }\n\n getSchema(): SourceSchema {\n return this.#input.getSchema();\n }\n\n fetch(req: FetchRequest): Stream<Node> {\n return this.#fetchOrCleanup('fetch', req);\n }\n\n cleanup(req: FetchRequest): Stream<Node> {\n return this.#fetchOrCleanup('fetch', req);\n }\n\n *#fetchOrCleanup(method: 'fetch' | 'cleanup', req: FetchRequest) {\n const start = this.#getStart(req);\n if (start === 'empty') {\n return;\n }\n const nodes = this.#input[method]({...req, start});\n if (!req.reverse) {\n yield* nodes;\n return;\n }\n for (const node of nodes) {\n if (!this.#shouldBePresent(node.row)) {\n return;\n }\n yield node;\n }\n }\n\n setOutput(output: Output): void {\n this.#output = output;\n }\n\n destroy(): void {\n this.#input.destroy();\n }\n\n #shouldBePresent(row: Row): boolean {\n const cmp = this.#comparator(this.#bound.row, row);\n return cmp < 0 || (cmp === 0 && !this.#bound.exclusive);\n }\n\n push(change: Change): void {\n const shouldBePresent = (row: Row) => this.#shouldBePresent(row);\n if (change.type === 'edit') {\n maybeSplitAndPushEditChange(change, shouldBePresent, this.#output);\n return;\n }\n\n change satisfies AddChange | RemoveChange | ChildChange;\n\n if (shouldBePresent(change.node.row)) {\n this.#output.push(change);\n }\n }\n\n #getStart(req: FetchRequest): Start | undefined | 'empty' {\n const boundStart = {\n row: this.#bound.row,\n basis: this.#bound.exclusive ? 'after' : 'at',\n } as const;\n\n if (!req.start) {\n if (req.reverse) {\n return undefined;\n }\n return boundStart;\n }\n\n const cmp = this.#comparator(this.#bound.row, req.start.row);\n\n if (!req.reverse) {\n // The skip bound is after the requested bound. The requested bound cannot\n // be relevant because even if it was basis: 'after', the skip bound is\n // itself after the requested bound. Return the skip bound.\n if (cmp > 0) {\n return boundStart;\n }\n\n // The skip bound and requested bound are equal. If either is exclusive,\n // return that bound with exclusive. Otherwise, return the skip bound.\n if (cmp === 0) {\n if (this.#bound.exclusive || req.start.basis === 'after') {\n return {\n row: this.#bound.row,\n basis: 'after',\n };\n }\n return boundStart;\n }\n\n return req.start;\n }\n\n req.reverse satisfies true;\n\n // bound is after the start, but request is for reverse so results\n // must be empty\n if (cmp > 0) {\n return 'empty';\n }\n\n if (cmp === 0) {\n // if both are inclusive, the result can be the single row at bound\n // return it as start\n if (!this.#bound.exclusive && req.start.basis === 'at') {\n return boundStart;\n }\n // otherwise the results must be empty, one or both are exclusive\n // in opposite directions\n return 'empty';\n }\n\n // bound is before the start, return start\n return req.start;\n }\n}\n", "import {assert, unreachable} from '../../../shared/src/asserts.ts';\nimport {hasOwn} from '../../../shared/src/has-own.ts';\nimport {must} from '../../../shared/src/must.ts';\nimport type {Row, Value} from '../../../zero-protocol/src/data.ts';\nimport type {PrimaryKey} from '../../../zero-protocol/src/primary-key.ts';\nimport {assertOrderingIncludesPK} from '../builder/builder.ts';\nimport {type Change, type EditChange, type RemoveChange} from './change.ts';\nimport type {Constraint} from './constraint.ts';\nimport {compareValues, type Comparator, type Node} from './data.ts';\nimport {\n throwOutput,\n type FetchRequest,\n type Input,\n type Operator,\n type Output,\n type Storage,\n} from './operator.ts';\nimport type {SourceSchema} from './schema.ts';\nimport {first, take, type Stream} from './stream.ts';\n\nconst MAX_BOUND_KEY = 'maxBound';\n\ntype TakeState = {\n size: number;\n bound: Row | undefined;\n};\n\ninterface TakeStorage {\n get(key: typeof MAX_BOUND_KEY): Row | undefined;\n get(key: string): TakeState | undefined;\n set(key: typeof MAX_BOUND_KEY, value: Row): void;\n set(key: string, value: TakeState): void;\n del(key: string): void;\n}\n\nexport type PartitionKey = PrimaryKey;\n\n/**\n * The Take operator is for implementing limit queries. It takes the first n\n * nodes of its input as determined by the input\u2019s comparator. It then keeps\n * a *bound* of the last item it has accepted so that it can evaluate whether\n * new incoming pushes should be accepted or rejected.\n *\n * Take can count rows globally or by unique value of some field.\n *\n * Maintains the invariant that its output size is always <= limit, even\n * mid processing of a push.\n */\nexport class Take implements Operator {\n readonly #input: Input;\n readonly #storage: TakeStorage;\n readonly #limit: number;\n readonly #partitionKey: PartitionKey | undefined;\n readonly #partitionKeyComparator: Comparator | undefined;\n // Fetch overlay needed for some split push cases.\n #rowHiddenFromFetch: Row | undefined;\n\n #output: Output = throwOutput;\n\n constructor(\n input: Input,\n storage: Storage,\n limit: number,\n partitionKey?: PartitionKey | undefined,\n ) {\n assert(limit >= 0);\n assertOrderingIncludesPK(\n input.getSchema().sort,\n input.getSchema().primaryKey,\n );\n input.setOutput(this);\n this.#input = input;\n this.#storage = storage as TakeStorage;\n this.#limit = limit;\n this.#partitionKey = partitionKey;\n this.#partitionKeyComparator =\n partitionKey && makePartitionKeyComparator(partitionKey);\n }\n\n setOutput(output: Output): void {\n this.#output = output;\n }\n\n getSchema(): SourceSchema {\n return this.#input.getSchema();\n }\n\n *fetch(req: FetchRequest): Stream<Node> {\n if (\n !this.#partitionKey ||\n (req.constraint &&\n constraintMatchesPartitionKey(req.constraint, this.#partitionKey))\n ) {\n const takeStateKey = getTakeStateKey(this.#partitionKey, req.constraint);\n const takeState = this.#storage.get(takeStateKey);\n if (!takeState) {\n yield* this.#initialFetch(req);\n return;\n }\n if (takeState.bound === undefined) {\n return;\n }\n for (const inputNode of this.#input.fetch(req)) {\n if (this.getSchema().compareRows(takeState.bound, inputNode.row) < 0) {\n return;\n }\n if (\n this.#rowHiddenFromFetch &&\n this.getSchema().compareRows(\n this.#rowHiddenFromFetch,\n inputNode.row,\n ) === 0\n ) {\n continue;\n }\n yield inputNode;\n }\n return;\n }\n // There is a partition key, but the fetch is not constrained or constrained\n // on a different key. Thus we don't have a single take state to bound by.\n // This currently only happens with nested sub-queries\n // e.g. issues include issuelabels include label. We could remove this\n // case if we added a translation layer (powered by some state) in join.\n // Specifically we need joinKeyValue => parent constraint key\n const maxBound = this.#storage.get(MAX_BOUND_KEY);\n if (maxBound === undefined) {\n return;\n }\n for (const inputNode of this.#input.fetch(req)) {\n if (this.getSchema().compareRows(inputNode.row, maxBound) > 0) {\n return;\n }\n const takeStateKey = getTakeStateKey(this.#partitionKey, inputNode.row);\n const takeState = this.#storage.get(takeStateKey);\n if (\n takeState?.bound !== undefined &&\n this.getSchema().compareRows(takeState.bound, inputNode.row) >= 0\n ) {\n yield inputNode;\n }\n }\n }\n\n *#initialFetch(req: FetchRequest): Stream<Node> {\n assert(req.start === undefined);\n assert(!req.reverse);\n assert(constraintMatchesPartitionKey(req.constraint, this.#partitionKey));\n\n if (this.#limit === 0) {\n return;\n }\n\n const takeStateKey = getTakeStateKey(this.#partitionKey, req.constraint);\n assert(this.#storage.get(takeStateKey) === undefined);\n\n let size = 0;\n let bound: Row | undefined;\n let downstreamEarlyReturn = true;\n let exceptionThrown = false;\n try {\n for (const inputNode of this.#input.fetch(req)) {\n yield inputNode;\n bound = inputNode.row;\n size++;\n if (size === this.#limit) {\n break;\n }\n }\n downstreamEarlyReturn = false;\n } catch (e) {\n exceptionThrown = true;\n throw e;\n } finally {\n if (!exceptionThrown) {\n this.#setTakeState(\n takeStateKey,\n size,\n bound,\n this.#storage.get(MAX_BOUND_KEY),\n );\n // If it becomes necessary to support downstream early return, this\n // assert should be removed, and replaced with code that consumes\n // the input stream until limit is reached or the input stream is\n // exhausted so that takeState is properly hydrated.\n assert(\n !downstreamEarlyReturn,\n 'Unexpected early return prevented full hydration',\n );\n }\n }\n }\n\n *cleanup(req: FetchRequest): Stream<Node> {\n assert(req.start === undefined);\n assert(constraintMatchesPartitionKey(req.constraint, this.#partitionKey));\n const takeStateKey = getTakeStateKey(this.#partitionKey, req.constraint);\n this.#storage.del(takeStateKey);\n let size = 0;\n for (const inputNode of this.#input.cleanup(req)) {\n if (size === this.#limit) {\n return;\n }\n size++;\n yield inputNode;\n }\n }\n\n #getStateAndConstraint(row: Row) {\n const takeStateKey = getTakeStateKey(this.#partitionKey, row);\n const takeState = this.#storage.get(takeStateKey);\n let maxBound: Row | undefined;\n let constraint: Constraint | undefined;\n if (takeState) {\n maxBound = this.#storage.get(MAX_BOUND_KEY);\n constraint =\n this.#partitionKey &&\n Object.fromEntries(\n this.#partitionKey.map(key => [key, row[key]] as const),\n );\n }\n\n return {takeState, takeStateKey, maxBound, constraint} as\n | {\n takeState: undefined;\n takeStateKey: string;\n maxBound: undefined;\n constraint: undefined;\n }\n | {\n takeState: TakeState;\n takeStateKey: string;\n maxBound: Row | undefined;\n constraint: Constraint | undefined;\n };\n }\n\n push(change: Change): void {\n if (change.type === 'edit') {\n this.#pushEditChange(change);\n return;\n }\n\n const {takeState, takeStateKey, maxBound, constraint} =\n this.#getStateAndConstraint(change.node.row);\n if (!takeState) {\n return;\n }\n\n const {compareRows} = this.getSchema();\n\n if (change.type === 'add') {\n if (takeState.size < this.#limit) {\n this.#setTakeState(\n takeStateKey,\n takeState.size + 1,\n takeState.bound === undefined ||\n compareRows(takeState.bound, change.node.row) < 0\n ? change.node.row\n : takeState.bound,\n maxBound,\n );\n this.#output.push(change);\n return;\n }\n // size === limit\n if (\n takeState.bound === undefined ||\n compareRows(change.node.row, takeState.bound) >= 0\n ) {\n return;\n }\n // added row < bound\n let beforeBoundNode: Node | undefined;\n let boundNode: Node;\n if (this.#limit === 1) {\n boundNode = must(\n first(\n this.#input.fetch({\n start: {\n row: takeState.bound,\n basis: 'at',\n },\n constraint,\n }),\n ),\n );\n } else {\n [boundNode, beforeBoundNode] = take(\n this.#input.fetch({\n start: {\n row: takeState.bound,\n basis: 'at',\n },\n constraint,\n reverse: true,\n }),\n 2,\n );\n }\n const removeChange: RemoveChange = {\n type: 'remove',\n node: boundNode,\n };\n // Remove before add to maintain invariant that\n // output size <= limit.\n this.#setTakeState(\n takeStateKey,\n takeState.size,\n beforeBoundNode === undefined ||\n compareRows(change.node.row, beforeBoundNode.row) > 0\n ? change.node.row\n : beforeBoundNode.row,\n maxBound,\n );\n this.#withRowHiddenFromFetch(change.node.row, () => {\n this.#output.push(removeChange);\n });\n this.#output.push(change);\n } else if (change.type === 'remove') {\n if (takeState.bound === undefined) {\n // change is after bound\n return;\n }\n const compToBound = compareRows(change.node.row, takeState.bound);\n if (compToBound > 0) {\n // change is after bound\n return;\n }\n const [beforeBoundNode] = take(\n this.#input.fetch({\n start: {\n row: takeState.bound,\n basis: 'after',\n },\n constraint,\n reverse: true,\n }),\n 1,\n );\n\n let newBound: {node: Node; push: boolean} | undefined;\n if (beforeBoundNode) {\n const push = compareRows(beforeBoundNode.row, takeState.bound) > 0;\n newBound = {\n node: beforeBoundNode,\n push,\n };\n }\n if (!newBound?.push) {\n for (const node of this.#input.fetch({\n start: {\n row: takeState.bound,\n basis: 'at',\n },\n constraint,\n })) {\n const push = compareRows(node.row, takeState.bound) > 0;\n newBound = {\n node,\n push,\n };\n if (push) {\n break;\n }\n }\n }\n\n if (newBound?.push) {\n this.#output.push(change);\n this.#setTakeState(\n takeStateKey,\n takeState.size,\n newBound.node.row,\n maxBound,\n );\n this.#output.push({\n type: 'add',\n node: newBound.node,\n });\n return;\n }\n this.#setTakeState(\n takeStateKey,\n takeState.size - 1,\n newBound?.node.row,\n maxBound,\n );\n this.#output.push(change);\n } else if (change.type === 'child') {\n // A 'child' change should be pushed to output if its row\n // is <= bound.\n if (\n takeState.bound &&\n compareRows(change.node.row, takeState.bound) <= 0\n ) {\n this.#output.push(change);\n }\n }\n }\n\n #pushEditChange(change: EditChange): void {\n assert(\n !this.#partitionKeyComparator ||\n this.#partitionKeyComparator(change.oldNode.row, change.node.row) === 0,\n 'Unexpected change of partition key',\n );\n\n const {takeState, takeStateKey, maxBound, constraint} =\n this.#getStateAndConstraint(change.oldNode.row);\n if (!takeState) {\n return;\n }\n\n assert(takeState.bound, 'Bound should be set');\n const {compareRows} = this.getSchema();\n const oldCmp = compareRows(change.oldNode.row, takeState.bound);\n const newCmp = compareRows(change.node.row, takeState.bound);\n\n const replaceBoundAndForwardChange = () => {\n this.#setTakeState(\n takeStateKey,\n takeState.size,\n change.node.row,\n maxBound,\n );\n this.#output.push(change);\n };\n\n // The bounds row was changed.\n if (oldCmp === 0) {\n // The new row is the new bound.\n if (newCmp === 0) {\n // no need to update the state since we are keeping the bounds\n this.#output.push(change);\n return;\n }\n\n if (newCmp < 0) {\n if (this.#limit === 1) {\n replaceBoundAndForwardChange();\n return;\n }\n\n // New row will be in the result but it might not be the bounds any\n // more. We need to find the row before the bounds to determine the new\n // bounds.\n\n const beforeBoundNode = must(\n first(\n this.#input.fetch({\n start: {\n row: takeState.bound,\n basis: 'after',\n },\n constraint,\n reverse: true,\n }),\n ),\n );\n\n this.#setTakeState(\n takeStateKey,\n takeState.size,\n beforeBoundNode.row,\n maxBound,\n );\n this.#output.push(change);\n return;\n }\n\n assert(newCmp > 0);\n // Find the first item at the old bounds. This will be the new bounds.\n const newBoundNode = must(\n first(\n this.#input.fetch({\n start: {\n row: takeState.bound,\n basis: 'at',\n },\n constraint,\n }),\n ),\n );\n\n // The next row is the new row. We can replace the bounds and keep the\n // edit change.\n if (compareRows(newBoundNode.row, change.node.row) === 0) {\n replaceBoundAndForwardChange();\n return;\n }\n\n // The new row is now outside the bounds, so we need to remove the old\n // row and add the new bounds row.\n this.#setTakeState(\n takeStateKey,\n takeState.size,\n newBoundNode.row,\n maxBound,\n );\n this.#output.push({\n type: 'add',\n node: newBoundNode,\n });\n return;\n }\n\n if (oldCmp > 0) {\n assert(newCmp !== 0, 'Invalid state. Row has duplicate primary key');\n\n // Both old and new outside of bounds\n if (newCmp > 0) {\n return;\n }\n\n // old was outside, new is inside. Pushing out the old bounds\n assert(newCmp < 0);\n\n const [oldBoundNode, newBoundNode] = take(\n this.#input.fetch({\n start: {\n row: takeState.bound,\n basis: 'at',\n },\n constraint,\n reverse: true,\n }),\n 2,\n );\n // Remove before add to maintain invariant that\n // output size <= limit.\n this.#setTakeState(\n takeStateKey,\n takeState.size,\n newBoundNode.row,\n maxBound,\n );\n this.#withRowHiddenFromFetch(change.node.row, () => {\n this.#output.push({\n type: 'remove',\n node: oldBoundNode,\n });\n });\n this.#output.push({\n type: 'add',\n node: change.node,\n });\n\n return;\n }\n\n if (oldCmp < 0) {\n assert(newCmp !== 0, 'Invalid state. Row has duplicate primary key');\n\n // Both old and new inside of bounds\n if (newCmp < 0) {\n this.#output.push(change);\n return;\n }\n\n // old was inside, new is larger than old bound\n\n assert(newCmp > 0);\n\n // at this point we need to find the row after the bound and use that or\n // the newRow as the new bound.\n const afterBoundNode = must(\n first(\n this.#input.fetch({\n start: {\n row: takeState.bound,\n basis: 'after',\n },\n constraint,\n }),\n ),\n );\n\n // The new row is the new bound. Use an edit change.\n if (compareRows(afterBoundNode.row, change.node.row) === 0) {\n replaceBoundAndForwardChange();\n return;\n }\n\n this.#output.push({\n type: 'remove',\n node: change.oldNode,\n });\n this.#setTakeState(\n takeStateKey,\n takeState.size,\n afterBoundNode.row,\n maxBound,\n );\n this.#output.push({\n type: 'add',\n node: afterBoundNode,\n });\n return;\n }\n\n unreachable();\n }\n\n #withRowHiddenFromFetch(row: Row, fn: () => void) {\n this.#rowHiddenFromFetch = row;\n try {\n fn();\n } finally {\n this.#rowHiddenFromFetch = undefined;\n }\n }\n\n #setTakeState(\n takeStateKey: string,\n size: number,\n bound: Row | undefined,\n maxBound: Row | undefined,\n ) {\n this.#storage.set(takeStateKey, {\n size,\n bound,\n });\n if (\n bound !== undefined &&\n (maxBound === undefined ||\n this.getSchema().compareRows(bound, maxBound) > 0)\n ) {\n this.#storage.set(MAX_BOUND_KEY, bound);\n }\n }\n\n destroy(): void {\n this.#input.destroy();\n }\n}\n\nfunction getTakeStateKey(\n partitionKey: PartitionKey | undefined,\n rowOrConstraint: Row | Constraint | undefined,\n): string {\n // The order must be consistent. We always use the order as defined by the\n // partition key.\n const partitionValues: Value[] = [];\n\n if (partitionKey && rowOrConstraint) {\n for (const key of partitionKey) {\n partitionValues.push(rowOrConstraint[key]);\n }\n }\n\n return JSON.stringify(['take', ...partitionValues]);\n}\n\nfunction constraintMatchesPartitionKey(\n constraint: Constraint | undefined,\n partitionKey: PartitionKey | undefined,\n): boolean {\n if (constraint === undefined || partitionKey === undefined) {\n return constraint === partitionKey;\n }\n if (partitionKey.length !== Object.keys(constraint).length) {\n return false;\n }\n for (const key of partitionKey) {\n if (!hasOwn(constraint, key)) {\n return false;\n }\n }\n return true;\n}\n\nfunction makePartitionKeyComparator(partitionKey: PartitionKey): Comparator {\n return (a, b) => {\n for (const key of partitionKey) {\n const cmp = compareValues(a[key], b[key]);\n if (cmp !== 0) {\n return cmp;\n }\n }\n return 0;\n };\n}\n", "import {assertString} from '../../../shared/src/asserts.ts';\nimport type {NonNullValue, SimplePredicateNoNull} from './filter.ts';\n\nexport function getLikePredicate(\n pattern: NonNullValue,\n flags: 'i' | '',\n): SimplePredicateNoNull {\n const op = getLikeOp(String(pattern), flags);\n return (lhs: NonNullValue) => {\n assertString(lhs);\n return op(String(lhs));\n };\n}\n\nfunction getLikeOp(pattern: string, flags: 'i' | ''): (lhs: string) => boolean {\n // if lhs does not contain '%' or '_' then it is a simple string comparison.\n // if it does contain '%' or '_' then it is a regex comparison.\n // '%' is a wildcard for any number of characters\n // '_' is a wildcard for a single character\n // Postgres SQL allows escaping using `\\`.\n\n if (!/_|%|\\\\/.test(pattern)) {\n if (flags === 'i') {\n const rhsLower = pattern.toLowerCase();\n return (lhs: string) => lhs.toLowerCase() === rhsLower;\n }\n return (lhs: string) => lhs === pattern;\n }\n const re = patternToRegExp(pattern, flags);\n return (lhs: string) => re.test(lhs);\n}\n\nconst specialCharsRe = /[$()*+.?[\\]\\\\^{|}]/;\n\nfunction patternToRegExp(source: string, flags: '' | 'i' = ''): RegExp {\n // There are a few cases:\n // % => .*\n // _ => .\n // \\x => \\x for any x except special regexp chars\n // special regexp chars => \\special regexp chars\n let pattern = '^';\n for (let i = 0; i < source.length; i++) {\n let c = source[i];\n switch (c) {\n case '%':\n pattern += '.*';\n break;\n case '_':\n pattern += '.';\n break;\n\n // @ts-expect-error fallthrough\n case '\\\\':\n if (i === source.length - 1) {\n throw new Error('LIKE pattern must not end with escape character');\n }\n i++;\n c = source[i];\n\n // fall through\n default:\n if (specialCharsRe.test(c)) {\n pattern += '\\\\';\n }\n pattern += c;\n\n break;\n }\n }\n return new RegExp(pattern + '$', flags + 'm');\n}\n", "import {assert, unreachable} from '../../../shared/src/asserts.ts';\nimport type {\n Condition,\n SimpleCondition,\n SimpleOperator,\n} from '../../../zero-protocol/src/ast.ts';\nimport type {Row, Value} from '../../../zero-protocol/src/data.ts';\nimport {getLikePredicate} from './like.ts';\n\nexport type NonNullValue = Exclude<Value, null | undefined>;\nexport type SimplePredicate = (rhs: Value) => boolean;\nexport type SimplePredicateNoNull = (rhs: NonNullValue) => boolean;\n\nexport type NoSubqueryCondition =\n | SimpleCondition\n | {\n type: 'and';\n conditions: readonly NoSubqueryCondition[];\n }\n | {\n type: 'or';\n conditions: readonly NoSubqueryCondition[];\n };\n\nexport function createPredicate(\n condition: NoSubqueryCondition,\n): (row: Row) => boolean {\n if (condition.type !== 'simple') {\n const predicates = condition.conditions.map(c => createPredicate(c));\n return condition.type === 'and'\n ? (row: Row) => {\n // and\n for (const predicate of predicates) {\n if (!predicate(row)) {\n return false;\n }\n }\n return true;\n }\n : (row: Row) => {\n // or\n for (const predicate of predicates) {\n if (predicate(row)) {\n return true;\n }\n }\n return false;\n };\n }\n const {left} = condition;\n const {right} = condition;\n assert(\n right.type !== 'static',\n 'static values should be resolved before creating predicates',\n );\n assert(\n left.type !== 'static',\n 'static values should be resolved before creating predicates',\n );\n\n switch (condition.op) {\n case 'IS':\n case 'IS NOT': {\n const impl = createIsPredicate(right.value, condition.op);\n if (left.type === 'literal') {\n const result = impl(left.value);\n return () => result;\n }\n return (row: Row) => impl(row[left.name]);\n }\n }\n\n if (right.value === null || right.value === undefined) {\n return (_row: Row) => false;\n }\n\n const impl = createPredicateImpl(right.value, condition.op);\n if (left.type === 'literal') {\n if (left.value === null || left.value === undefined) {\n return (_row: Row) => false;\n }\n const result = impl(left.value);\n return () => result;\n }\n\n return (row: Row) => {\n const lhs = row[left.name];\n if (lhs === null || lhs === undefined) {\n return false;\n }\n return impl(lhs);\n };\n}\n\nfunction createIsPredicate(\n rhs: Value | readonly Value[],\n operator: 'IS' | 'IS NOT',\n): SimplePredicate {\n switch (operator) {\n case 'IS':\n return lhs => lhs === rhs;\n case 'IS NOT':\n return lhs => lhs !== rhs;\n }\n}\n\nfunction createPredicateImpl(\n rhs: NonNullValue | readonly NonNullValue[],\n operator: Exclude<SimpleOperator, 'IS' | 'IS NOT'>,\n): SimplePredicateNoNull {\n switch (operator) {\n case '=':\n return lhs => lhs === rhs;\n case '!=':\n return lhs => lhs !== rhs;\n case '<':\n return lhs => lhs < rhs;\n case '<=':\n return lhs => lhs <= rhs;\n case '>':\n return lhs => lhs > rhs;\n case '>=':\n return lhs => lhs >= rhs;\n case 'LIKE':\n return getLikePredicate(rhs, '');\n case 'NOT LIKE':\n return not(getLikePredicate(rhs, ''));\n case 'ILIKE':\n return getLikePredicate(rhs, 'i');\n case 'NOT ILIKE':\n return not(getLikePredicate(rhs, 'i'));\n case 'IN': {\n assert(Array.isArray(rhs));\n const set = new Set(rhs);\n return lhs => set.has(lhs);\n }\n case 'NOT IN': {\n assert(Array.isArray(rhs));\n const set = new Set(rhs);\n return lhs => !set.has(lhs);\n }\n default:\n operator satisfies never;\n throw new Error(`Unexpected operator: ${operator}`);\n }\n}\n\nfunction not<T>(f: (lhs: T) => boolean) {\n return (lhs: T) => !f(lhs);\n}\n\n/**\n * If the condition contains any CorrelatedSubqueryConditions, returns a\n * transformed condition which contains no CorrelatedSubqueryCondition(s) but\n * which will filter a subset of the rows that would be filtered by the original\n * condition, or undefined if no such transformation exists.\n *\n * If the condition does not contain any CorrelatedSubqueryConditions\n * returns the condition unmodified and `conditionsRemoved: false`.\n *\n *\n * Assumes Condition is in DNF.\n */\nexport function transformFilters(filters: Condition | undefined): {\n filters: NoSubqueryCondition | undefined;\n conditionsRemoved: boolean;\n} {\n if (!filters) {\n return {filters: undefined, conditionsRemoved: false};\n }\n switch (filters.type) {\n case 'simple':\n return {filters, conditionsRemoved: false};\n case 'correlatedSubquery':\n return {filters: undefined, conditionsRemoved: true};\n case 'and': {\n const transformedConditions = [];\n for (const cond of filters.conditions) {\n assert(cond.type === 'simple' || cond.type === 'correlatedSubquery');\n if (cond.type === 'simple') {\n transformedConditions.push(cond);\n }\n }\n const conditionsRemoved =\n transformedConditions.length !== filters.conditions.length;\n if (transformedConditions.length === 0) {\n return {filters: undefined, conditionsRemoved};\n }\n if (transformedConditions.length === 1) {\n return {\n filters: transformedConditions[0],\n conditionsRemoved,\n };\n }\n return {\n filters: {\n type: 'and',\n conditions: transformedConditions,\n },\n conditionsRemoved,\n };\n }\n case 'or': {\n const transformedConditions: NoSubqueryCondition[] = [];\n let conditionsRemoved = false;\n for (const cond of filters.conditions) {\n assert(cond.type !== 'or');\n const transformed = transformFilters(cond);\n if (transformed.filters === undefined) {\n return {filters: undefined, conditionsRemoved: true};\n }\n conditionsRemoved = conditionsRemoved || transformed.conditionsRemoved;\n transformedConditions.push(transformed.filters);\n }\n return {\n filters: {type: 'or', conditions: transformedConditions},\n conditionsRemoved,\n };\n }\n default:\n unreachable(filters);\n }\n}\n", "import {assert} from '../../../shared/src/asserts.ts';\nimport type {JSONValue} from '../../../shared/src/json.ts';\nimport {must} from '../../../shared/src/must.ts';\nimport type {\n AST,\n ColumnReference,\n CompoundKey,\n Condition,\n Conjunction,\n CorrelatedSubquery,\n CorrelatedSubqueryCondition,\n Disjunction,\n LiteralValue,\n Ordering,\n Parameter,\n SimpleCondition,\n ValuePosition,\n} from '../../../zero-protocol/src/ast.ts';\nimport type {Row} from '../../../zero-protocol/src/data.ts';\nimport type {PrimaryKey} from '../../../zero-protocol/src/primary-key.ts';\nimport {Exists} from '../ivm/exists.ts';\nimport {FanIn} from '../ivm/fan-in.ts';\nimport {FanOut} from '../ivm/fan-out.ts';\nimport {Filter} from '../ivm/filter.ts';\nimport {Join} from '../ivm/join.ts';\nimport type {Input, Storage} from '../ivm/operator.ts';\nimport {Skip} from '../ivm/skip.ts';\nimport type {Source} from '../ivm/source.ts';\nimport {Take} from '../ivm/take.ts';\nimport {createPredicate, type NoSubqueryCondition} from './filter.ts';\n\nexport type StaticQueryParameters = {\n authData: Record<string, JSONValue>;\n preMutationRow?: Row | undefined;\n};\n\n/**\n * Interface required of caller to buildPipeline. Connects to constructed\n * pipeline to delegate environment to provide sources and storage.\n */\nexport interface BuilderDelegate {\n /**\n * Called once for each source needed by the AST.\n * Might be called multiple times with same tableName. It is OK to return\n * same storage instance in that case.\n */\n getSource(tableName: string): Source | undefined;\n\n /**\n * Called once for each operator that requires storage. Should return a new\n * unique storage object for each call.\n */\n createStorage(name: string): Storage;\n\n decorateInput(input: Input, name: string): Input;\n\n /**\n * The AST is mapped on-the-wire between client and server names.\n *\n * There is no \"wire\" for zqlite tests so this function is provided\n * to allow tests to remap the AST.\n */\n mapAst(ast: AST): AST;\n}\n\n/**\n * Builds a pipeline from an AST. Caller must provide a delegate to create source\n * and storage interfaces as necessary.\n *\n * Usage:\n *\n * ```ts\n * class MySink implements Output {\n * readonly #input: Input;\n *\n * constructor(input: Input) {\n * this.#input = input;\n * input.setOutput(this);\n * }\n *\n * push(change: Change, _: Operator) {\n * console.log(change);\n * }\n * }\n *\n * const input = buildPipeline(ast, myDelegate);\n * const sink = new MySink(input);\n * ```\n */\nexport function buildPipeline(ast: AST, delegate: BuilderDelegate): Input {\n return buildPipelineInternal(delegate.mapAst(ast), delegate, '');\n}\n\nexport function bindStaticParameters(\n ast: AST,\n staticQueryParameters: StaticQueryParameters | undefined,\n) {\n const visit = (node: AST): AST => ({\n ...node,\n where: node.where ? bindCondition(node.where) : undefined,\n related: node.related?.map(sq => ({\n ...sq,\n subquery: visit(sq.subquery),\n })),\n });\n\n function bindCondition(condition: Condition): Condition {\n if (condition.type === 'simple') {\n return {\n ...condition,\n left: bindValue(condition.left),\n right: bindValue(condition.right) as Exclude<\n ValuePosition,\n ColumnReference\n >,\n };\n }\n if (condition.type === 'correlatedSubquery') {\n return {\n ...condition,\n related: {\n ...condition.related,\n subquery: visit(condition.related.subquery),\n },\n };\n }\n return {\n ...condition,\n conditions: condition.conditions.map(bindCondition),\n };\n }\n\n const bindValue = (value: ValuePosition): ValuePosition => {\n if (isParameter(value)) {\n const anchor = must(\n staticQueryParameters,\n 'Static query params do not exist',\n )[value.anchor];\n const resolvedValue = resolveField(anchor, value.field);\n return {\n type: 'literal',\n value: resolvedValue as LiteralValue,\n };\n }\n return value;\n };\n\n return visit(ast);\n}\n\nfunction resolveField(\n anchor: Record<string, JSONValue> | Row | undefined,\n field: string | string[],\n): unknown {\n if (anchor === undefined) {\n return null;\n }\n\n if (Array.isArray(field)) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return field.reduce((acc, f) => (acc as any)?.[f], anchor) ?? null;\n }\n\n return anchor[field] ?? null;\n}\n\nfunction isParameter(value: ValuePosition): value is Parameter {\n return value.type === 'static';\n}\n\nfunction buildPipelineInternal(\n ast: AST,\n delegate: BuilderDelegate,\n name: string,\n partitionKey?: CompoundKey | undefined,\n): Input {\n const source = delegate.getSource(ast.table);\n if (!source) {\n throw new Error(`Source not found: ${ast.table}`);\n }\n ast = uniquifyCorrelatedSubqueryConditionAliases(ast);\n\n const csqsFromCondition = gatherCorrelatedSubqueryQueriesFromCondition(\n ast.where,\n );\n const splitEditKeys: Set<string> = partitionKey\n ? new Set(partitionKey)\n : new Set();\n for (const csq of csqsFromCondition) {\n for (const key of csq.correlation.parentField) {\n splitEditKeys.add(key);\n }\n }\n if (ast.related) {\n for (const csq of ast.related) {\n for (const key of csq.correlation.parentField) {\n splitEditKeys.add(key);\n }\n }\n }\n const conn = source.connect(must(ast.orderBy), ast.where, splitEditKeys);\n let end: Input = delegate.decorateInput(conn, `${name}:source(${ast.table})`);\n const {fullyAppliedFilters} = conn;\n\n if (ast.start) {\n end = delegate.decorateInput(new Skip(end, ast.start), `${name}:skip)`);\n }\n\n for (const csq of csqsFromCondition) {\n end = applyCorrelatedSubQuery(csq, delegate, end, name);\n }\n\n if (ast.where && !fullyAppliedFilters) {\n end = applyWhere(end, ast.where, delegate, name);\n }\n\n if (ast.limit !== undefined) {\n const takeName = `${name}:take`;\n end = delegate.decorateInput(\n new Take(end, delegate.createStorage(takeName), ast.limit, partitionKey),\n takeName,\n );\n }\n\n if (ast.related) {\n for (const csq of ast.related) {\n end = applyCorrelatedSubQuery(csq, delegate, end, name);\n }\n }\n\n return end;\n}\n\nfunction applyWhere(\n input: Input,\n condition: Condition,\n delegate: BuilderDelegate,\n name: string,\n): Input {\n switch (condition.type) {\n case 'and':\n return applyAnd(input, condition, delegate, name);\n case 'or':\n return applyOr(input, condition, delegate, name);\n case 'correlatedSubquery':\n return applyCorrelatedSubqueryCondition(input, condition, delegate, name);\n case 'simple':\n return applySimpleCondition(input, condition);\n }\n}\n\nfunction applyAnd(\n input: Input,\n condition: Conjunction,\n delegate: BuilderDelegate,\n name: string,\n) {\n for (const subCondition of condition.conditions) {\n input = applyWhere(input, subCondition, delegate, name);\n }\n return input;\n}\n\nexport function applyOr(\n input: Input,\n condition: Disjunction,\n delegate: BuilderDelegate,\n name: string,\n): Input {\n const [subqueryConditions, otherConditions] =\n groupSubqueryConditions(condition);\n // if there are no subquery conditions, no fan-in / fan-out is needed\n if (subqueryConditions.length === 0) {\n return new Filter(\n input,\n createPredicate({\n type: 'or',\n conditions: otherConditions,\n }),\n );\n }\n\n const fanOut = new FanOut(input);\n const branches = subqueryConditions.map(subCondition =>\n applyWhere(fanOut, subCondition, delegate, name),\n );\n if (otherConditions.length > 0) {\n branches.push(\n new Filter(\n fanOut,\n createPredicate({\n type: 'or',\n conditions: otherConditions,\n }),\n ),\n );\n }\n const ret = new FanIn(fanOut, branches);\n fanOut.setFanIn(ret);\n return ret;\n}\n\nexport function groupSubqueryConditions(condition: Disjunction) {\n const partitioned: [\n subqueryConditions: Condition[],\n otherConditions: NoSubqueryCondition[],\n ] = [[], []];\n for (const subCondition of condition.conditions) {\n if (isNotAndDoesNotContainSubquery(subCondition)) {\n partitioned[1].push(subCondition);\n } else {\n partitioned[0].push(subCondition);\n }\n }\n return partitioned;\n}\n\nexport function isNotAndDoesNotContainSubquery(\n condition: Condition,\n): condition is NoSubqueryCondition {\n if (condition.type === 'correlatedSubquery') {\n return false;\n }\n if (condition.type === 'and') {\n return condition.conditions.every(isNotAndDoesNotContainSubquery);\n }\n assert(condition.type !== 'or', 'where conditions are expected to be in DNF');\n return true;\n}\n\nfunction applySimpleCondition(input: Input, condition: SimpleCondition): Input {\n return new Filter(input, createPredicate(condition));\n}\n\nfunction applyCorrelatedSubQuery(\n sq: CorrelatedSubquery,\n delegate: BuilderDelegate,\n end: Input,\n name: string,\n) {\n assert(sq.subquery.alias, 'Subquery must have an alias');\n const child = buildPipelineInternal(\n sq.subquery,\n delegate,\n `${name}.${sq.subquery.alias}`,\n sq.correlation.childField,\n );\n const joinName = `${name}:join(${sq.subquery.alias})`;\n end = new Join({\n parent: end,\n child,\n storage: delegate.createStorage(joinName),\n parentKey: sq.correlation.parentField,\n childKey: sq.correlation.childField,\n relationshipName: sq.subquery.alias,\n hidden: sq.hidden ?? false,\n system: sq.system ?? 'client',\n });\n return delegate.decorateInput(end, joinName);\n}\n\nfunction applyCorrelatedSubqueryCondition(\n input: Input,\n condition: CorrelatedSubqueryCondition,\n delegate: BuilderDelegate,\n name: string,\n): Input {\n assert(condition.op === 'EXISTS' || condition.op === 'NOT EXISTS');\n const existsName = `${name}:exists(${condition.related.subquery.alias})`;\n return delegate.decorateInput(\n new Exists(\n input,\n delegate.createStorage(existsName),\n must(condition.related.subquery.alias),\n condition.related.correlation.parentField,\n condition.op,\n ),\n existsName,\n );\n}\n\nfunction gatherCorrelatedSubqueryQueriesFromCondition(\n condition: Condition | undefined,\n) {\n const csqs: CorrelatedSubquery[] = [];\n const gather = (condition: Condition) => {\n if (condition.type === 'correlatedSubquery') {\n assert(condition.op === 'EXISTS' || condition.op === 'NOT EXISTS');\n csqs.push({\n ...condition.related,\n subquery: {\n ...condition.related.subquery,\n limit:\n condition.related.system === 'permissions'\n ? PERMISSIONS_EXISTS_LIMIT\n : EXISTS_LIMIT,\n },\n });\n return;\n }\n if (condition.type === 'and' || condition.type === 'or') {\n for (const c of condition.conditions) {\n gather(c);\n }\n return;\n }\n };\n if (condition) {\n gather(condition);\n }\n return csqs;\n}\n\nconst EXISTS_LIMIT = 3;\nconst PERMISSIONS_EXISTS_LIMIT = 1;\n\nexport function assertOrderingIncludesPK(\n ordering: Ordering,\n pk: PrimaryKey,\n): void {\n const orderingFields = ordering.map(([field]) => field);\n const missingFields = pk.filter(pkField => !orderingFields.includes(pkField));\n\n if (missingFields.length > 0) {\n throw new Error(\n `Ordering must include all primary key fields. Missing: ${missingFields.join(\n ', ',\n )}. ZQL automatically appends primary key fields to the ordering if they are missing \n so a common cause of this error is a casing mismatch between Postgres and ZQL.\n E.g., \"userid\" vs \"userID\".\n You may want to add double-quotes around your Postgres column names to prevent Postgres from lower-casing them:\n https://www.postgresql.org/docs/current/sql-syntax-lexical.htm`,\n );\n }\n}\nfunction uniquifyCorrelatedSubqueryConditionAliases(ast: AST): AST {\n if (!ast.where) {\n return ast;\n }\n const {where} = ast;\n if (where.type !== 'and' && where.type !== 'or') {\n return ast;\n }\n let count = 0;\n\n const uniquifyCorrelatedSubquery = (csqc: CorrelatedSubqueryCondition) => ({\n ...csqc,\n related: {\n ...csqc.related,\n subquery: {\n ...csqc.related.subquery,\n alias: (csqc.related.subquery.alias ?? '') + '_' + count++,\n },\n },\n });\n\n const uniquifyAnd = (and: Conjunction) => {\n const conds = [];\n for (const cond of and.conditions) {\n if (cond.type === 'correlatedSubquery') {\n conds.push(uniquifyCorrelatedSubquery(cond));\n } else {\n conds.push(cond);\n }\n }\n return {\n ...and,\n conditions: conds,\n };\n };\n if (where.type === 'and') {\n return {\n ...ast,\n where: uniquifyAnd(where),\n };\n }\n // or\n const conds = [];\n for (const cond of where.conditions) {\n if (cond.type === 'simple') {\n conds.push(cond);\n } else if (cond.type === 'correlatedSubquery') {\n conds.push(uniquifyCorrelatedSubquery(cond));\n } else if (cond.type === 'and') {\n conds.push(uniquifyAnd(cond));\n }\n }\n return {\n ...ast,\n where: {\n ...where,\n conditions: conds,\n },\n };\n}\n", "import {assert} from '../../../shared/src/asserts.ts';\nimport type {Immutable} from '../../../shared/src/immutable.ts';\nimport type {TTL} from '../query/ttl.ts';\nimport type {Listener, TypedView} from '../query/typed-view.ts';\nimport type {Change} from './change.ts';\nimport type {Input, Output} from './operator.ts';\nimport type {SourceSchema} from './schema.ts';\nimport {applyChange} from './view-apply-change.ts';\nimport type {Entry, Format, View} from './view.ts';\n\n/**\n * Implements a materialized view of the output of an operator.\n *\n * It might seem more efficient to use an immutable b-tree for the\n * materialization, but it's not so clear. Inserts in the middle are\n * asymptotically slower in an array, but can often be done with zero\n * allocations, where changes to the b-tree will often require several allocs.\n *\n * Also the plain array view is more convenient for consumers since you can dump\n * it into console to see what it is, rather than having to iterate it.\n */\nexport class ArrayView<V extends View> implements Output, TypedView<V> {\n readonly #input: Input;\n readonly #listeners = new Set<Listener<V>>();\n readonly #schema: SourceSchema;\n readonly #format: Format;\n\n // Synthetic \"root\" entry that has a single \"\" relationship, so that we can\n // treat all changes, including the root change, generically.\n readonly #root: Entry;\n\n onDestroy: (() => void) | undefined;\n\n #dirty = false;\n #complete = false;\n readonly #updateTTL: (ttl: TTL) => void;\n\n constructor(\n input: Input,\n format: Format, // = {singular: false, relationships: {}},\n queryComplete: true | Promise<true>, // = true,\n updateTTL: (ttl: TTL) => void,\n ) {\n this.#input = input;\n this.#schema = input.getSchema();\n this.#format = format;\n this.#updateTTL = updateTTL;\n this.#root = {'': format.singular ? undefined : []};\n input.setOutput(this);\n\n if (queryComplete === true) {\n this.#complete = true;\n } else {\n void queryComplete.then(() => {\n this.#complete = true;\n this.#fireListeners();\n });\n }\n this.#hydrate();\n }\n\n get data() {\n return this.#root[''] as V;\n }\n\n addListener(listener: Listener<V>) {\n assert(!this.#listeners.has(listener), 'Listener already registered');\n this.#listeners.add(listener);\n\n this.#fireListener(listener);\n\n return () => {\n this.#listeners.delete(listener);\n };\n }\n\n #fireListeners() {\n for (const listener of this.#listeners) {\n this.#fireListener(listener);\n }\n }\n\n #fireListener(listener: Listener<V>) {\n listener(\n this.data as Immutable<V>,\n this.#complete ? 'complete' : 'unknown',\n );\n }\n\n destroy() {\n this.onDestroy?.();\n }\n\n #hydrate() {\n this.#dirty = true;\n for (const node of this.#input.fetch({})) {\n applyChange(\n this.#root,\n {type: 'add', node},\n this.#schema,\n '',\n this.#format,\n );\n }\n this.flush();\n }\n\n push(change: Change): void {\n this.#dirty = true;\n applyChange(this.#root, change, this.#schema, '', this.#format);\n }\n\n flush() {\n if (!this.#dirty) {\n return;\n }\n this.#dirty = false;\n this.#fireListeners();\n }\n\n updateTTL(ttl: TTL) {\n this.#updateTTL(ttl);\n }\n}\n", "/* eslint-disable @typescript-eslint/no-explicit-any */\nimport {must} from '../../../shared/src/must.ts';\nimport {\n toStaticParam,\n type Condition,\n type LiteralValue,\n type Parameter,\n type SimpleOperator,\n} from '../../../zero-protocol/src/ast.ts';\nimport type {Schema} from '../../../zero-schema/src/builder/schema-builder.ts';\nimport type {\n AvailableRelationships,\n DestTableName,\n GetFilterType,\n NoJsonSelector,\n PullTableSchema,\n Query,\n} from './query.ts';\n\nexport type ParameterReference = {\n [toStaticParam](): Parameter;\n};\n\n/**\n * A factory function that creates a condition. This is used to create\n * complex conditions that can be passed to the `where` method of a query.\n *\n * @example\n *\n * ```ts\n * const condition: ExpressionFactory<User> = ({and, cmp, or}) =>\n * and(\n * cmp('name', '=', 'Alice'),\n * or(cmp('age', '>', 18), cmp('isStudent', '=', true)),\n * );\n *\n * const query = z.query.user.where(condition);\n * ```\n */\nexport interface ExpressionFactory<\n TSchema extends Schema,\n TTable extends keyof TSchema['tables'] & string,\n> {\n (eb: ExpressionBuilder<TSchema, TTable>): Condition;\n}\n\nexport class ExpressionBuilder<\n TSchema extends Schema,\n TTable extends keyof TSchema['tables'] & string,\n> {\n readonly #exists: (\n relationship: string,\n cb?: (query: Query<TSchema, TTable>) => Query<TSchema, any>,\n ) => Condition;\n\n constructor(\n exists: (\n relationship: string,\n cb?: (query: Query<TSchema, TTable>) => Query<TSchema, any>,\n ) => Condition,\n ) {\n this.#exists = exists;\n this.exists = this.exists.bind(this);\n }\n\n get eb() {\n return this;\n }\n\n cmp<\n TSelector extends NoJsonSelector<PullTableSchema<TTable, TSchema>>,\n TOperator extends SimpleOperator,\n >(\n field: TSelector,\n op: TOperator,\n value:\n | GetFilterType<PullTableSchema<TTable, TSchema>, TSelector, TOperator>\n | ParameterReference,\n ): Condition;\n cmp<TSelector extends NoJsonSelector<PullTableSchema<TTable, TSchema>>>(\n field: TSelector,\n value:\n | GetFilterType<PullTableSchema<TTable, TSchema>, TSelector, '='>\n | ParameterReference,\n ): Condition;\n cmp(\n field: string,\n opOrValue: SimpleOperator | ParameterReference | LiteralValue,\n value?: ParameterReference | LiteralValue,\n ): Condition {\n return cmp(field, opOrValue, value);\n }\n\n cmpLit(\n left: ParameterReference | LiteralValue,\n op: SimpleOperator,\n right: ParameterReference | LiteralValue,\n ): Condition {\n return {\n type: 'simple',\n left: isParameterReference(left)\n ? left[toStaticParam]()\n : {type: 'literal', value: left},\n right: isParameterReference(right)\n ? right[toStaticParam]()\n : {type: 'literal', value: right},\n op,\n };\n }\n\n and = and;\n or = or;\n not = not;\n\n exists = <TRelationship extends AvailableRelationships<TTable, TSchema>>(\n relationship: TRelationship,\n cb?: (\n query: Query<TSchema, DestTableName<TTable, TSchema, TRelationship>>,\n ) => Query<TSchema, any>,\n ): Condition => this.#exists(relationship, cb);\n}\n\nexport function and(...conditions: (Condition | undefined)[]): Condition {\n const expressions = filterTrue(filterUndefined(conditions));\n\n if (expressions.length === 1) {\n return expressions[0];\n }\n\n if (expressions.some(isAlwaysFalse)) {\n return FALSE;\n }\n\n return {type: 'and', conditions: expressions};\n}\n\nexport function or(...conditions: (Condition | undefined)[]): Condition {\n const expressions = filterFalse(filterUndefined(conditions));\n\n if (expressions.length === 1) {\n return expressions[0];\n }\n\n if (expressions.some(isAlwaysTrue)) {\n return TRUE;\n }\n\n return {type: 'or', conditions: expressions};\n}\n\nexport function not(expression: Condition): Condition {\n switch (expression.type) {\n case 'and':\n return {\n type: 'or',\n conditions: expression.conditions.map(not),\n };\n case 'or':\n return {\n type: 'and',\n conditions: expression.conditions.map(not),\n };\n case 'correlatedSubquery':\n return {\n type: 'correlatedSubquery',\n related: expression.related,\n op: negateOperator(expression.op),\n };\n case 'simple':\n return {\n type: 'simple',\n op: negateOperator(expression.op),\n left: expression.left,\n right: expression.right,\n };\n }\n}\n\nexport function cmp(\n field: string,\n opOrValue: SimpleOperator | ParameterReference | LiteralValue,\n value?: ParameterReference | LiteralValue,\n): Condition {\n let op: SimpleOperator;\n if (value === undefined) {\n value = opOrValue;\n op = '=';\n } else {\n op = opOrValue as SimpleOperator;\n }\n\n return {\n type: 'simple',\n left: {type: 'column', name: field},\n right: isParameterReference(value)\n ? value[toStaticParam]()\n : {type: 'literal', value},\n op,\n };\n}\n\nfunction isParameterReference(\n value: ParameterReference | LiteralValue | null,\n): value is ParameterReference {\n return (\n value !== null && typeof value === 'object' && (value as any)[toStaticParam]\n );\n}\n\nexport const TRUE: Condition = {\n type: 'and',\n conditions: [],\n};\n\nconst FALSE: Condition = {\n type: 'or',\n conditions: [],\n};\n\nfunction isAlwaysTrue(condition: Condition): boolean {\n return condition.type === 'and' && condition.conditions.length === 0;\n}\n\nfunction isAlwaysFalse(condition: Condition): boolean {\n return condition.type === 'or' && condition.conditions.length === 0;\n}\n\nexport function flatten(\n type: 'and' | 'or',\n conditions: Condition[],\n): Condition[] {\n const flattened: Condition[] = [];\n for (const c of conditions) {\n if (c.type === type) {\n flattened.push(...c.conditions);\n } else {\n flattened.push(c);\n }\n }\n\n return flattened;\n}\n\nconst negateSimpleOperatorMap = {\n ['=']: '!=',\n ['!=']: '=',\n ['<']: '>=',\n ['>']: '<=',\n ['>=']: '<',\n ['<=']: '>',\n ['IN']: 'NOT IN',\n ['NOT IN']: 'IN',\n ['LIKE']: 'NOT LIKE',\n ['NOT LIKE']: 'LIKE',\n ['ILIKE']: 'NOT ILIKE',\n ['NOT ILIKE']: 'ILIKE',\n ['IS']: 'IS NOT',\n ['IS NOT']: 'IS',\n} as const;\n\nconst negateOperatorMap = {\n ...negateSimpleOperatorMap,\n ['EXISTS']: 'NOT EXISTS',\n ['NOT EXISTS']: 'EXISTS',\n} as const;\n\nexport function negateOperator<OP extends keyof typeof negateOperatorMap>(\n op: OP,\n): (typeof negateOperatorMap)[OP] {\n return must(negateOperatorMap[op]);\n}\n\nfunction filterUndefined<T>(array: (T | undefined)[]): T[] {\n return array.filter(e => e !== undefined);\n}\n\nfunction filterTrue(conditions: Condition[]): Condition[] {\n return conditions.filter(c => !isAlwaysTrue(c));\n}\n\nfunction filterFalse(conditions: Condition[]): Condition[] {\n return conditions.filter(c => !isAlwaysFalse(c));\n}\n", "import {unreachable} from '../../../shared/src/asserts.ts';\nimport type {Condition, Disjunction} from '../../../zero-protocol/src/ast.ts';\nimport {flatten, TRUE} from './expression.ts';\n\n/**\n * DNF (Disjunctive Normal Form) is a way to represent a boolean expression as a\n * series of `or` conditions where each `or` condition is a series of `and`\n * conditions. The `and` conditions are the terms (SimpleCondition) of the\n * expression.\n */\nexport function dnf(condition: Condition): Condition {\n return unwrap(dnfInner(condition));\n}\n\nfunction dnfInner(condition: Condition): Disjunction {\n switch (condition.type) {\n case 'simple':\n case 'correlatedSubquery':\n return {type: 'or', conditions: [condition]};\n\n case 'and':\n return distributeAnd(condition.conditions.map(dnfInner));\n\n case 'or':\n return {\n type: 'or',\n conditions: flatten(\n 'or',\n condition.conditions.map(dnfInner).flatMap(c => c.conditions),\n ),\n };\n\n default:\n unreachable(condition);\n }\n}\n\nfunction distributeAnd(conditions: Disjunction[]): Disjunction {\n if (conditions.length === 0) {\n return {type: 'or', conditions: [TRUE]};\n }\n\n return conditions.reduce((acc, orCondition): Disjunction => {\n const newConditions: Condition[] = [];\n for (const accCondition of acc.conditions) {\n for (const orSubCondition of orCondition.conditions) {\n newConditions.push({\n type: 'and',\n conditions: [accCondition, orSubCondition],\n });\n }\n }\n return {\n type: 'or',\n conditions: flatten('or', newConditions),\n };\n });\n}\n\nexport function unwrap(c: Condition): Condition {\n if (c.type === 'simple' || c.type === 'correlatedSubquery') {\n return c;\n }\n if (c.conditions.length === 1) {\n return unwrap(c.conditions[0]);\n }\n return {type: c.type, conditions: flatten(c.type, c.conditions.map(unwrap))};\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA,gBAAAA;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAEA;AAFA,YAAY,OAAO;AAEnB,6BAAc;AAEd,SAAS,UAAU,OAAwB;AACzC,UAAQ,OAAO,OAAO;AAAA,IACpB,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AACH,aAAO,KAAK,UAAU,KAAK;AAAA,IAC7B,KAAK;AACH,aAAO;AAAA,IACT,KAAK;AACH,aAAO,MAAM,SAAS,IAAI;AAAA,IAC5B;AACE,UAAI,UAAU,MAAM;AAClB,eAAO;AAAA,MACT;AACA,UAAI,MAAM,QAAQ,KAAK,GAAG;AACxB,eAAO;AAAA,MACT;AACA,aAAO,OAAO;AAAA,EAClB;AACF;AAIA,SAAS,gBAAgBC,IAAYC,OAAiC;AACpE,MAAI,CAACA,OAAM,QAAQ;AACjB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BAAoB,QAAqB,KAAe;AAC/D,SAAO;AAAA,IACL,GAAG;AAAA,IACH,SAAS,eAAe,QAAQ,IAAI,OAAO;AAAA,EAC7C;AACF;AAEA,SAAS,iBAKP,QACA,OACA,QACA,WACA,qBACA,eACA,WACmC;AACnC,QAAMA,KAAI,IAAI;AAAA,IACZ;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACA,EAAAA,GAAE,YAAY;AACd,sBAAoB,MAAM;AACxB,IAAAA,GAAE,MAAM;AAAA,EACV,CAAC;AACD,SAAOA;AACT;AAEA,SAAS,cAAc,OAAgD;AACrE,SAAO,MAAM,QAAQ,KAAK,KAAK,MAAM,UAAU;AACjD;",
|
|
6
6
|
"names": ["assert", "v", "path", "toDisplay", "err", "atPath", "hash", "defined", "v", "path", "v", "table", "val", "c", "hash", "v", "change", "key", "cmp", "cmp", "impl", "condition", "and", "conds", "not", "flattened", "array", "v"]
|
|
7
7
|
}
|