@tanstack/db 0.1.12 → 0.2.1
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/dist/cjs/errors.cjs +18 -6
- package/dist/cjs/errors.cjs.map +1 -1
- package/dist/cjs/errors.d.cts +9 -3
- package/dist/cjs/index.cjs +5 -1
- package/dist/cjs/index.cjs.map +1 -1
- package/dist/cjs/query/builder/functions.cjs +12 -1
- package/dist/cjs/query/builder/functions.cjs.map +1 -1
- package/dist/cjs/query/builder/functions.d.cts +36 -21
- package/dist/cjs/query/builder/index.cjs +25 -16
- package/dist/cjs/query/builder/index.cjs.map +1 -1
- package/dist/cjs/query/builder/index.d.cts +8 -8
- package/dist/cjs/query/builder/ref-proxy.cjs +12 -8
- package/dist/cjs/query/builder/ref-proxy.cjs.map +1 -1
- package/dist/cjs/query/builder/ref-proxy.d.cts +2 -1
- package/dist/cjs/query/builder/types.d.cts +493 -28
- package/dist/cjs/query/compiler/evaluators.cjs +15 -0
- package/dist/cjs/query/compiler/evaluators.cjs.map +1 -1
- package/dist/cjs/query/compiler/group-by.cjs +4 -2
- package/dist/cjs/query/compiler/group-by.cjs.map +1 -1
- package/dist/cjs/query/compiler/index.cjs +13 -4
- package/dist/cjs/query/compiler/index.cjs.map +1 -1
- package/dist/cjs/query/compiler/joins.cjs +70 -60
- package/dist/cjs/query/compiler/joins.cjs.map +1 -1
- package/dist/cjs/query/compiler/select.cjs +131 -42
- package/dist/cjs/query/compiler/select.cjs.map +1 -1
- package/dist/cjs/query/compiler/select.d.cts +1 -5
- package/dist/cjs/query/index.d.cts +1 -1
- package/dist/cjs/query/ir.cjs +4 -0
- package/dist/cjs/query/ir.cjs.map +1 -1
- package/dist/cjs/query/ir.d.cts +6 -1
- package/dist/cjs/query/optimizer.cjs +61 -20
- package/dist/cjs/query/optimizer.cjs.map +1 -1
- package/dist/esm/errors.d.ts +9 -3
- package/dist/esm/errors.js +18 -6
- package/dist/esm/errors.js.map +1 -1
- package/dist/esm/index.js +7 -3
- package/dist/esm/query/builder/functions.d.ts +36 -21
- package/dist/esm/query/builder/functions.js +12 -1
- package/dist/esm/query/builder/functions.js.map +1 -1
- package/dist/esm/query/builder/index.d.ts +8 -8
- package/dist/esm/query/builder/index.js +27 -18
- package/dist/esm/query/builder/index.js.map +1 -1
- package/dist/esm/query/builder/ref-proxy.d.ts +2 -1
- package/dist/esm/query/builder/ref-proxy.js +12 -8
- package/dist/esm/query/builder/ref-proxy.js.map +1 -1
- package/dist/esm/query/builder/types.d.ts +493 -28
- package/dist/esm/query/compiler/evaluators.js +15 -0
- package/dist/esm/query/compiler/evaluators.js.map +1 -1
- package/dist/esm/query/compiler/group-by.js +4 -2
- package/dist/esm/query/compiler/group-by.js.map +1 -1
- package/dist/esm/query/compiler/index.js +15 -6
- package/dist/esm/query/compiler/index.js.map +1 -1
- package/dist/esm/query/compiler/joins.js +71 -61
- package/dist/esm/query/compiler/joins.js.map +1 -1
- package/dist/esm/query/compiler/select.d.ts +1 -5
- package/dist/esm/query/compiler/select.js +131 -42
- package/dist/esm/query/compiler/select.js.map +1 -1
- package/dist/esm/query/index.d.ts +1 -1
- package/dist/esm/query/ir.d.ts +6 -1
- package/dist/esm/query/ir.js +4 -0
- package/dist/esm/query/ir.js.map +1 -1
- package/dist/esm/query/optimizer.js +62 -21
- package/dist/esm/query/optimizer.js.map +1 -1
- package/package.json +2 -2
- package/src/errors.ts +17 -10
- package/src/query/builder/functions.ts +166 -108
- package/src/query/builder/index.ts +68 -48
- package/src/query/builder/ref-proxy.ts +14 -20
- package/src/query/builder/types.ts +622 -110
- package/src/query/compiler/evaluators.ts +16 -0
- package/src/query/compiler/group-by.ts +6 -1
- package/src/query/compiler/index.ts +23 -6
- package/src/query/compiler/joins.ts +132 -101
- package/src/query/compiler/select.ts +206 -113
- package/src/query/index.ts +2 -0
- package/src/query/ir.ts +14 -1
- package/src/query/optimizer.ts +131 -59
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"functions.js","sources":["../../../../src/query/builder/functions.ts"],"sourcesContent":["import { Aggregate, Func } from \"../ir\"\nimport { toExpression } from \"./ref-proxy.js\"\nimport type { BasicExpression } from \"../ir\"\nimport type { RefProxy } from \"./ref-proxy.js\"\n\n// Helper type for any expression-like value\ntype ExpressionLike = BasicExpression | RefProxy<any> | any\n\n// Operators\n\nexport function eq<T>(\n left: RefProxy<T>,\n right: T | RefProxy<T> | BasicExpression<T>\n): BasicExpression<boolean>\nexport function eq<T extends string | number | boolean>(\n left: T | BasicExpression<T>,\n right: T | BasicExpression<T>\n): BasicExpression<boolean>\nexport function eq<T>(left: Aggregate<T>, right: any): BasicExpression<boolean>\nexport function eq(left: any, right: any): BasicExpression<boolean> {\n return new Func(`eq`, [toExpression(left), toExpression(right)])\n}\n\nexport function gt<T>(\n left: RefProxy<T>,\n right: T | RefProxy<T> | BasicExpression<T>\n): BasicExpression<boolean>\nexport function gt<T extends string | number>(\n left: T | BasicExpression<T>,\n right: T | BasicExpression<T>\n): BasicExpression<boolean>\nexport function gt<T>(left: Aggregate<T>, right: any): BasicExpression<boolean>\nexport function gt(left: any, right: any): BasicExpression<boolean> {\n return new Func(`gt`, [toExpression(left), toExpression(right)])\n}\n\nexport function gte<T>(\n left: RefProxy<T>,\n right: T | RefProxy<T> | BasicExpression<T>\n): BasicExpression<boolean>\nexport function gte<T extends string | number>(\n left: T | BasicExpression<T>,\n right: T | BasicExpression<T>\n): BasicExpression<boolean>\nexport function gte<T>(left: Aggregate<T>, right: any): BasicExpression<boolean>\nexport function gte(left: any, right: any): BasicExpression<boolean> {\n return new Func(`gte`, [toExpression(left), toExpression(right)])\n}\n\nexport function lt<T>(\n left: RefProxy<T>,\n right: T | RefProxy<T> | BasicExpression<T>\n): BasicExpression<boolean>\nexport function lt<T extends string | number>(\n left: T | BasicExpression<T>,\n right: T | BasicExpression<T>\n): BasicExpression<boolean>\nexport function lt<T>(left: Aggregate<T>, right: any): BasicExpression<boolean>\nexport function lt(left: any, right: any): BasicExpression<boolean> {\n return new Func(`lt`, [toExpression(left), toExpression(right)])\n}\n\nexport function lte<T>(\n left: RefProxy<T>,\n right: T | RefProxy<T> | BasicExpression<T>\n): BasicExpression<boolean>\nexport function lte<T extends string | number>(\n left: T | BasicExpression<T>,\n right: T | BasicExpression<T>\n): BasicExpression<boolean>\nexport function lte<T>(left: Aggregate<T>, right: any): BasicExpression<boolean>\nexport function lte(left: any, right: any): BasicExpression<boolean> {\n return new Func(`lte`, [toExpression(left), toExpression(right)])\n}\n\n// Overloads for and() - support 2 or more arguments\nexport function and(\n left: ExpressionLike,\n right: ExpressionLike\n): BasicExpression<boolean>\nexport function and(\n left: ExpressionLike,\n right: ExpressionLike,\n ...rest: Array<ExpressionLike>\n): BasicExpression<boolean>\nexport function and(\n left: ExpressionLike,\n right: ExpressionLike,\n ...rest: Array<ExpressionLike>\n): BasicExpression<boolean> {\n const allArgs = [left, right, ...rest]\n return new Func(\n `and`,\n allArgs.map((arg) => toExpression(arg))\n )\n}\n\n// Overloads for or() - support 2 or more arguments\nexport function or(\n left: ExpressionLike,\n right: ExpressionLike\n): BasicExpression<boolean>\nexport function or(\n left: ExpressionLike,\n right: ExpressionLike,\n ...rest: Array<ExpressionLike>\n): BasicExpression<boolean>\nexport function or(\n left: ExpressionLike,\n right: ExpressionLike,\n ...rest: Array<ExpressionLike>\n): BasicExpression<boolean> {\n const allArgs = [left, right, ...rest]\n return new Func(\n `or`,\n allArgs.map((arg) => toExpression(arg))\n )\n}\n\nexport function not(value: ExpressionLike): BasicExpression<boolean> {\n return new Func(`not`, [toExpression(value)])\n}\n\nexport function inArray(\n value: ExpressionLike,\n array: ExpressionLike\n): BasicExpression<boolean> {\n return new Func(`in`, [toExpression(value), toExpression(array)])\n}\n\nexport function like(\n left:\n | RefProxy<string>\n | RefProxy<string | null>\n | RefProxy<string | undefined>\n | string\n | BasicExpression<string>,\n right: string | RefProxy<string> | BasicExpression<string>\n): BasicExpression<boolean>\nexport function like(left: any, right: any): BasicExpression<boolean> {\n return new Func(`like`, [toExpression(left), toExpression(right)])\n}\n\nexport function ilike(\n left:\n | RefProxy<string>\n | RefProxy<string | null>\n | RefProxy<string | undefined>\n | string\n | BasicExpression<string>,\n right: string | RefProxy<string> | BasicExpression<string>\n): BasicExpression<boolean> {\n return new Func(`ilike`, [toExpression(left), toExpression(right)])\n}\n\n// Functions\n\nexport function upper(\n arg:\n | RefProxy<string>\n | RefProxy<string | undefined>\n | string\n | BasicExpression<string>\n): BasicExpression<string> {\n return new Func(`upper`, [toExpression(arg)])\n}\n\nexport function lower(\n arg:\n | RefProxy<string>\n | RefProxy<string | undefined>\n | string\n | BasicExpression<string>\n): BasicExpression<string> {\n return new Func(`lower`, [toExpression(arg)])\n}\n\nexport function length(\n arg:\n | RefProxy<string>\n | RefProxy<string | undefined>\n | RefProxy<Array<any>>\n | RefProxy<Array<any> | undefined>\n | string\n | Array<any>\n | BasicExpression<string>\n | BasicExpression<Array<any>>\n): BasicExpression<number> {\n return new Func(`length`, [toExpression(arg)])\n}\n\nexport function concat(\n ...args: Array<ExpressionLike>\n): BasicExpression<string> {\n return new Func(\n `concat`,\n args.map((arg) => toExpression(arg))\n )\n}\n\nexport function coalesce(...args: Array<ExpressionLike>): BasicExpression<any> {\n return new Func(\n `coalesce`,\n args.map((arg) => toExpression(arg))\n )\n}\n\nexport function add(\n left:\n | RefProxy<number>\n | RefProxy<number | undefined>\n | number\n | BasicExpression<number>,\n right:\n | RefProxy<number>\n | RefProxy<number | undefined>\n | number\n | BasicExpression<number>\n): BasicExpression<number> {\n return new Func(`add`, [toExpression(left), toExpression(right)])\n}\n\n// Aggregates\n\nexport function count(arg: ExpressionLike): Aggregate<number> {\n return new Aggregate(`count`, [toExpression(arg)])\n}\n\nexport function avg(\n arg:\n | RefProxy<number>\n | RefProxy<number | undefined>\n | number\n | BasicExpression<number>\n): Aggregate<number> {\n return new Aggregate(`avg`, [toExpression(arg)])\n}\n\nexport function sum(\n arg:\n | RefProxy<number>\n | RefProxy<number | undefined>\n | number\n | BasicExpression<number>\n): Aggregate<number> {\n return new Aggregate(`sum`, [toExpression(arg)])\n}\n\nexport function min(\n arg:\n | RefProxy<number>\n | RefProxy<number | undefined>\n | number\n | BasicExpression<number>\n): Aggregate<number> {\n return new Aggregate(`min`, [toExpression(arg)])\n}\n\nexport function max(\n arg:\n | RefProxy<number>\n | RefProxy<number | undefined>\n | number\n | BasicExpression<number>\n): Aggregate<number> {\n return new Aggregate(`max`, [toExpression(arg)])\n}\n\n/**\n * List of comparison function names that can be used with indexes\n */\nexport const comparisonFunctions = [\n `eq`,\n `gt`,\n `gte`,\n `lt`,\n `lte`,\n `in`,\n `like`,\n `ilike`,\n] as const\n"],"names":[],"mappings":";;AAmBO,SAAS,GAAG,MAAW,OAAsC;AAClE,SAAO,IAAI,KAAK,MAAM,CAAC,aAAa,IAAI,GAAG,aAAa,KAAK,CAAC,CAAC;AACjE;AAWO,SAAS,GAAG,MAAW,OAAsC;AAClE,SAAO,IAAI,KAAK,MAAM,CAAC,aAAa,IAAI,GAAG,aAAa,KAAK,CAAC,CAAC;AACjE;AAWO,SAAS,IAAI,MAAW,OAAsC;AACnE,SAAO,IAAI,KAAK,OAAO,CAAC,aAAa,IAAI,GAAG,aAAa,KAAK,CAAC,CAAC;AAClE;AAWO,SAAS,GAAG,MAAW,OAAsC;AAClE,SAAO,IAAI,KAAK,MAAM,CAAC,aAAa,IAAI,GAAG,aAAa,KAAK,CAAC,CAAC;AACjE;AAWO,SAAS,IAAI,MAAW,OAAsC;AACnE,SAAO,IAAI,KAAK,OAAO,CAAC,aAAa,IAAI,GAAG,aAAa,KAAK,CAAC,CAAC;AAClE;AAYO,SAAS,IACd,MACA,UACG,MACuB;AAC1B,QAAM,UAAU,CAAC,MAAM,OAAO,GAAG,IAAI;AACrC,SAAO,IAAI;AAAA,IACT;AAAA,IACA,QAAQ,IAAI,CAAC,QAAQ,aAAa,GAAG,CAAC;AAAA,EAAA;AAE1C;AAYO,SAA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KAAK,CAAC,CAAC;AAClE;AAIO,SAAS,MAAM,KAAwC;AAC5D,SAAO,IAAI,UAAU,SAAS,CAAC,aAAa,GAAG,CAAC,CAAC;AACnD;AAEO,SAAS,IACd,KAKmB;AACnB,SAAO,IAAI,UAAU,OAAO,CAAC,aAAa,GAAG,CAAC,CAAC;AACjD;AAEO,SAAS,IACd,KAKmB;AACnB,SAAO,IAAI,UAAU,OAAO,CAAC,aAAa,GAAG,CAAC,CAAC;AACjD;AAEO,SAAS,IACd,KAKmB;AACnB,SAAO,IAAI,UAAU,OAAO,CAAC,aAAa,GAAG,CAAC,CAAC;AACjD;AAEO,SAAS,IACd,KAKmB;AACnB,SAAO,IAAI,UAAU,OAAO,CAAC,aAAa,GAAG,CAAC,CAAC;AACjD;AAKO,MAAM,sBAAsB;AAAA,EACjC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;"}
|
|
1
|
+
{"version":3,"file":"functions.js","sources":["../../../../src/query/builder/functions.ts"],"sourcesContent":["import { Aggregate, Func } from \"../ir\"\nimport { toExpression } from \"./ref-proxy.js\"\nimport type { BasicExpression } from \"../ir\"\nimport type { RefProxy } from \"./ref-proxy.js\"\nimport type { RefLeaf } from \"./types.js\"\n\ntype StringRef =\n | RefLeaf<string>\n | RefLeaf<string | null>\n | RefLeaf<string | undefined>\ntype StringRefProxy =\n | RefProxy<string>\n | RefProxy<string | null>\n | RefProxy<string | undefined>\ntype StringBasicExpression =\n | BasicExpression<string>\n | BasicExpression<string | null>\n | BasicExpression<string | undefined>\ntype StringLike =\n | StringRef\n | StringRefProxy\n | StringBasicExpression\n | string\n | null\n | undefined\n\ntype ComparisonOperand<T> =\n | RefProxy<T>\n | RefLeaf<T>\n | T\n | BasicExpression<T>\n | undefined\n | null\ntype ComparisonOperandPrimitive<T extends string | number | boolean> =\n | T\n | BasicExpression<T>\n | undefined\n | null\n\n// Helper type for any expression-like value\ntype ExpressionLike = BasicExpression | RefProxy<any> | RefLeaf<any> | any\n\n// Helper type to extract the underlying type from various expression types\ntype ExtractType<T> =\n T extends RefProxy<infer U>\n ? U\n : T extends RefLeaf<infer U>\n ? U\n : T extends BasicExpression<infer U>\n ? U\n : T\n\n// Helper type to determine aggregate return type based on input nullability\ntype AggregateReturnType<T> =\n ExtractType<T> extends infer U\n ? U extends number | undefined | null\n ? Aggregate<U>\n : Aggregate<number | undefined | null>\n : Aggregate<number | undefined | null>\n\n// Helper type to determine string function return type based on input nullability\ntype StringFunctionReturnType<T> =\n ExtractType<T> extends infer U\n ? U extends string | undefined | null\n ? BasicExpression<U>\n : BasicExpression<string | undefined | null>\n : BasicExpression<string | undefined | null>\n\n// Helper type to determine numeric function return type based on input nullability\n// This handles string, array, and number inputs for functions like length()\ntype NumericFunctionReturnType<T> =\n ExtractType<T> extends infer U\n ? U extends string | Array<any> | undefined | null | number\n ? BasicExpression<MapToNumber<U>>\n : BasicExpression<number | undefined | null>\n : BasicExpression<number | undefined | null>\n\n// Transform string/array types to number while preserving nullability\ntype MapToNumber<T> = T extends string | Array<any>\n ? number\n : T extends undefined\n ? undefined\n : T extends null\n ? null\n : T\n\n// Helper type for binary numeric operations (combines nullability of both operands)\ntype BinaryNumericReturnType<T1, T2> =\n ExtractType<T1> extends infer U1\n ? ExtractType<T2> extends infer U2\n ? U1 extends number\n ? U2 extends number\n ? BasicExpression<number>\n : U2 extends number | undefined\n ? BasicExpression<number | undefined>\n : U2 extends number | null\n ? BasicExpression<number | null>\n : BasicExpression<number | undefined | null>\n : U1 extends number | undefined\n ? U2 extends number\n ? BasicExpression<number | undefined>\n : U2 extends number | undefined\n ? BasicExpression<number | undefined>\n : BasicExpression<number | undefined | null>\n : U1 extends number | null\n ? U2 extends number\n ? BasicExpression<number | null>\n : BasicExpression<number | undefined | null>\n : BasicExpression<number | undefined | null>\n : BasicExpression<number | undefined | null>\n : BasicExpression<number | undefined | null>\n\n// Operators\n\nexport function eq<T>(\n left: ComparisonOperand<T>,\n right: ComparisonOperand<T>\n): BasicExpression<boolean>\nexport function eq<T extends string | number | boolean>(\n left: ComparisonOperandPrimitive<T>,\n right: ComparisonOperandPrimitive<T>\n): BasicExpression<boolean>\nexport function eq<T>(left: Aggregate<T>, right: any): BasicExpression<boolean>\nexport function eq(left: any, right: any): BasicExpression<boolean> {\n return new Func(`eq`, [toExpression(left), toExpression(right)])\n}\n\nexport function gt<T>(\n left: ComparisonOperand<T>,\n right: ComparisonOperand<T>\n): BasicExpression<boolean>\nexport function gt<T extends string | number>(\n left: ComparisonOperandPrimitive<T>,\n right: ComparisonOperandPrimitive<T>\n): BasicExpression<boolean>\nexport function gt<T>(left: Aggregate<T>, right: any): BasicExpression<boolean>\nexport function gt(left: any, right: any): BasicExpression<boolean> {\n return new Func(`gt`, [toExpression(left), toExpression(right)])\n}\n\nexport function gte<T>(\n left: ComparisonOperand<T>,\n right: ComparisonOperand<T>\n): BasicExpression<boolean>\nexport function gte<T extends string | number>(\n left: ComparisonOperandPrimitive<T>,\n right: ComparisonOperandPrimitive<T>\n): BasicExpression<boolean>\nexport function gte<T>(left: Aggregate<T>, right: any): BasicExpression<boolean>\nexport function gte(left: any, right: any): BasicExpression<boolean> {\n return new Func(`gte`, [toExpression(left), toExpression(right)])\n}\n\nexport function lt<T>(\n left: ComparisonOperand<T>,\n right: ComparisonOperand<T>\n): BasicExpression<boolean>\nexport function lt<T extends string | number>(\n left: ComparisonOperandPrimitive<T>,\n right: ComparisonOperandPrimitive<T>\n): BasicExpression<boolean>\nexport function lt<T>(left: Aggregate<T>, right: any): BasicExpression<boolean>\nexport function lt(left: any, right: any): BasicExpression<boolean> {\n return new Func(`lt`, [toExpression(left), toExpression(right)])\n}\n\nexport function lte<T>(\n left: ComparisonOperand<T>,\n right: ComparisonOperand<T>\n): BasicExpression<boolean>\nexport function lte<T extends string | number>(\n left: ComparisonOperandPrimitive<T>,\n right: ComparisonOperandPrimitive<T>\n): BasicExpression<boolean>\nexport function lte<T>(left: Aggregate<T>, right: any): BasicExpression<boolean>\nexport function lte(left: any, right: any): BasicExpression<boolean> {\n return new Func(`lte`, [toExpression(left), toExpression(right)])\n}\n\n// Overloads for and() - support 2 or more arguments\nexport function and(\n left: ExpressionLike,\n right: ExpressionLike\n): BasicExpression<boolean>\nexport function and(\n left: ExpressionLike,\n right: ExpressionLike,\n ...rest: Array<ExpressionLike>\n): BasicExpression<boolean>\nexport function and(\n left: ExpressionLike,\n right: ExpressionLike,\n ...rest: Array<ExpressionLike>\n): BasicExpression<boolean> {\n const allArgs = [left, right, ...rest]\n return new Func(\n `and`,\n allArgs.map((arg) => toExpression(arg))\n )\n}\n\n// Overloads for or() - support 2 or more arguments\nexport function or(\n left: ExpressionLike,\n right: ExpressionLike\n): BasicExpression<boolean>\nexport function or(\n left: ExpressionLike,\n right: ExpressionLike,\n ...rest: Array<ExpressionLike>\n): BasicExpression<boolean>\nexport function or(\n left: ExpressionLike,\n right: ExpressionLike,\n ...rest: Array<ExpressionLike>\n): BasicExpression<boolean> {\n const allArgs = [left, right, ...rest]\n return new Func(\n `or`,\n allArgs.map((arg) => toExpression(arg))\n )\n}\n\nexport function not(value: ExpressionLike): BasicExpression<boolean> {\n return new Func(`not`, [toExpression(value)])\n}\n\n// Null/undefined checking functions\nexport function isUndefined(value: ExpressionLike): BasicExpression<boolean> {\n return new Func(`isUndefined`, [toExpression(value)])\n}\n\nexport function isNull(value: ExpressionLike): BasicExpression<boolean> {\n return new Func(`isNull`, [toExpression(value)])\n}\n\nexport function inArray(\n value: ExpressionLike,\n array: ExpressionLike\n): BasicExpression<boolean> {\n return new Func(`in`, [toExpression(value), toExpression(array)])\n}\n\nexport function like(\n left: StringLike,\n right: StringLike\n): BasicExpression<boolean>\nexport function like(left: any, right: any): BasicExpression<boolean> {\n return new Func(`like`, [toExpression(left), toExpression(right)])\n}\n\nexport function ilike(\n left: StringLike,\n right: StringLike\n): BasicExpression<boolean> {\n return new Func(`ilike`, [toExpression(left), toExpression(right)])\n}\n\n// Functions\n\nexport function upper<T extends ExpressionLike>(\n arg: T\n): StringFunctionReturnType<T> {\n return new Func(`upper`, [toExpression(arg)]) as StringFunctionReturnType<T>\n}\n\nexport function lower<T extends ExpressionLike>(\n arg: T\n): StringFunctionReturnType<T> {\n return new Func(`lower`, [toExpression(arg)]) as StringFunctionReturnType<T>\n}\n\nexport function length<T extends ExpressionLike>(\n arg: T\n): NumericFunctionReturnType<T> {\n return new Func(`length`, [toExpression(arg)]) as NumericFunctionReturnType<T>\n}\n\nexport function concat(\n ...args: Array<ExpressionLike>\n): BasicExpression<string> {\n return new Func(\n `concat`,\n args.map((arg) => toExpression(arg))\n )\n}\n\nexport function coalesce(...args: Array<ExpressionLike>): BasicExpression<any> {\n return new Func(\n `coalesce`,\n args.map((arg) => toExpression(arg))\n )\n}\n\nexport function add<T1 extends ExpressionLike, T2 extends ExpressionLike>(\n left: T1,\n right: T2\n): BinaryNumericReturnType<T1, T2> {\n return new Func(`add`, [\n toExpression(left),\n toExpression(right),\n ]) as BinaryNumericReturnType<T1, T2>\n}\n\n// Aggregates\n\nexport function count(arg: ExpressionLike): Aggregate<number> {\n return new Aggregate(`count`, [toExpression(arg)])\n}\n\nexport function avg<T extends ExpressionLike>(arg: T): AggregateReturnType<T> {\n return new Aggregate(`avg`, [toExpression(arg)]) as AggregateReturnType<T>\n}\n\nexport function sum<T extends ExpressionLike>(arg: T): AggregateReturnType<T> {\n return new Aggregate(`sum`, [toExpression(arg)]) as AggregateReturnType<T>\n}\n\nexport function min<T extends ExpressionLike>(arg: T): AggregateReturnType<T> {\n return new Aggregate(`min`, [toExpression(arg)]) as AggregateReturnType<T>\n}\n\nexport function max<T extends ExpressionLike>(arg: T): AggregateReturnType<T> {\n return new Aggregate(`max`, [toExpression(arg)]) as AggregateReturnType<T>\n}\n\n/**\n * List of comparison function names that can be used with indexes\n */\nexport const comparisonFunctions = [\n `eq`,\n `gt`,\n `gte`,\n `lt`,\n `lte`,\n `in`,\n `like`,\n `ilike`,\n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gC;AAC5E,SAAO,IAAI,UAAU,OAAO,CAAC,aAAa,GAAG,CAAC,CAAC;AACjD;AAEO,SAAS,IAA8B,KAAgC;AAC5E,SAAO,IAAI,UAAU,OAAO,CAAC,aAAa,GAAG,CAAC,CAAC;AACjD;AAEO,SAAS,IAA8B,KAAgC;AAC5E,SAAO,IAAI,UAAU,OAAO,CAAC,aAAa,GAAG,CAAC,CAAC;AACjD;AAKO,MAAM,sBAAsB;AAAA,EACjC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { OrderByDirection, QueryIR } from '../ir.js';
|
|
2
|
-
import { Context, GroupByCallback, JoinOnCallback,
|
|
2
|
+
import { Context, GroupByCallback, JoinOnCallback, MergeContextForJoinCallback, MergeContextWithJoinType, OrderByCallback, OrderByOptions, RefsForContext, ResultTypeFromSelect, SchemaFromSource, SelectObject, Source, WhereCallback, WithResult } from './types.js';
|
|
3
3
|
export declare class BaseQueryBuilder<TContext extends Context = Context> {
|
|
4
4
|
private readonly query;
|
|
5
5
|
constructor(query?: Partial<QueryIR>);
|
|
@@ -59,7 +59,7 @@ export declare class BaseQueryBuilder<TContext extends Context = Context> {
|
|
|
59
59
|
* .from({ activeUsers })
|
|
60
60
|
* .join({ p: postsCollection }, ({u, p}) => eq(u.id, p.userId))
|
|
61
61
|
*/
|
|
62
|
-
join<TSource extends Source, TJoinType extends `inner` | `left` | `right` | `full` = `left`>(source: TSource, onCallback: JoinOnCallback<
|
|
62
|
+
join<TSource extends Source, TJoinType extends `inner` | `left` | `right` | `full` = `left`>(source: TSource, onCallback: JoinOnCallback<MergeContextForJoinCallback<TContext, SchemaFromSource<TSource>>>, type?: TJoinType): QueryBuilder<MergeContextWithJoinType<TContext, SchemaFromSource<TSource>, TJoinType>>;
|
|
63
63
|
/**
|
|
64
64
|
* Perform a LEFT JOIN with another table or subquery
|
|
65
65
|
*
|
|
@@ -75,7 +75,7 @@ export declare class BaseQueryBuilder<TContext extends Context = Context> {
|
|
|
75
75
|
* .leftJoin({ posts: postsCollection }, ({users, posts}) => eq(users.id, posts.userId))
|
|
76
76
|
* ```
|
|
77
77
|
*/
|
|
78
|
-
leftJoin<TSource extends Source>(source: TSource, onCallback: JoinOnCallback<
|
|
78
|
+
leftJoin<TSource extends Source>(source: TSource, onCallback: JoinOnCallback<MergeContextForJoinCallback<TContext, SchemaFromSource<TSource>>>): QueryBuilder<MergeContextWithJoinType<TContext, SchemaFromSource<TSource>, `left`>>;
|
|
79
79
|
/**
|
|
80
80
|
* Perform a RIGHT JOIN with another table or subquery
|
|
81
81
|
*
|
|
@@ -91,7 +91,7 @@ export declare class BaseQueryBuilder<TContext extends Context = Context> {
|
|
|
91
91
|
* .rightJoin({ posts: postsCollection }, ({users, posts}) => eq(users.id, posts.userId))
|
|
92
92
|
* ```
|
|
93
93
|
*/
|
|
94
|
-
rightJoin<TSource extends Source>(source: TSource, onCallback: JoinOnCallback<
|
|
94
|
+
rightJoin<TSource extends Source>(source: TSource, onCallback: JoinOnCallback<MergeContextForJoinCallback<TContext, SchemaFromSource<TSource>>>): QueryBuilder<MergeContextWithJoinType<TContext, SchemaFromSource<TSource>, `right`>>;
|
|
95
95
|
/**
|
|
96
96
|
* Perform an INNER JOIN with another table or subquery
|
|
97
97
|
*
|
|
@@ -107,7 +107,7 @@ export declare class BaseQueryBuilder<TContext extends Context = Context> {
|
|
|
107
107
|
* .innerJoin({ posts: postsCollection }, ({users, posts}) => eq(users.id, posts.userId))
|
|
108
108
|
* ```
|
|
109
109
|
*/
|
|
110
|
-
innerJoin<TSource extends Source>(source: TSource, onCallback: JoinOnCallback<
|
|
110
|
+
innerJoin<TSource extends Source>(source: TSource, onCallback: JoinOnCallback<MergeContextForJoinCallback<TContext, SchemaFromSource<TSource>>>): QueryBuilder<MergeContextWithJoinType<TContext, SchemaFromSource<TSource>, `inner`>>;
|
|
111
111
|
/**
|
|
112
112
|
* Perform a FULL JOIN with another table or subquery
|
|
113
113
|
*
|
|
@@ -123,7 +123,7 @@ export declare class BaseQueryBuilder<TContext extends Context = Context> {
|
|
|
123
123
|
* .fullJoin({ posts: postsCollection }, ({users, posts}) => eq(users.id, posts.userId))
|
|
124
124
|
* ```
|
|
125
125
|
*/
|
|
126
|
-
fullJoin<TSource extends Source>(source: TSource, onCallback: JoinOnCallback<
|
|
126
|
+
fullJoin<TSource extends Source>(source: TSource, onCallback: JoinOnCallback<MergeContextForJoinCallback<TContext, SchemaFromSource<TSource>>>): QueryBuilder<MergeContextWithJoinType<TContext, SchemaFromSource<TSource>, `full`>>;
|
|
127
127
|
/**
|
|
128
128
|
* Filter rows based on a condition
|
|
129
129
|
*
|
|
@@ -216,7 +216,7 @@ export declare class BaseQueryBuilder<TContext extends Context = Context> {
|
|
|
216
216
|
* }))
|
|
217
217
|
* ```
|
|
218
218
|
*/
|
|
219
|
-
select<TSelectObject extends SelectObject>(callback: (refs:
|
|
219
|
+
select<TSelectObject extends SelectObject>(callback: (refs: RefsForContext<TContext>) => TSelectObject): QueryBuilder<WithResult<TContext, ResultTypeFromSelect<TSelectObject>>>;
|
|
220
220
|
/**
|
|
221
221
|
* Sort the query results by one or more columns
|
|
222
222
|
*
|
|
@@ -400,4 +400,4 @@ export type InitialQueryBuilderConstructor = new () => InitialQueryBuilder;
|
|
|
400
400
|
export type QueryBuilder<TContext extends Context> = Omit<BaseQueryBuilder<TContext>, `from` | `_getQuery`>;
|
|
401
401
|
export declare const Query: InitialQueryBuilderConstructor;
|
|
402
402
|
export type ExtractContext<T> = T extends BaseQueryBuilder<infer TContext> ? TContext : T extends QueryBuilder<infer TContext> ? TContext : never;
|
|
403
|
-
export type { Context, Source, GetResult } from './types.js';
|
|
403
|
+
export type { Context, Source, GetResult, RefLeaf as Ref } from './types.js';
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { CollectionImpl } from "../../collection.js";
|
|
2
|
-
import { CollectionRef, QueryRef } from "../ir.js";
|
|
2
|
+
import { CollectionRef, QueryRef, isExpressionLike, Aggregate, Func, PropRef, Value } from "../ir.js";
|
|
3
3
|
import { OnlyOneSourceAllowedError, SubQueryMustHaveFromClauseError, InvalidSourceError, JoinConditionMustBeEqualityError, QueryMustHaveFromClauseError } from "../../errors.js";
|
|
4
|
-
import { createRefProxy, toExpression
|
|
4
|
+
import { createRefProxy, toExpression } from "./ref-proxy.js";
|
|
5
5
|
class BaseQueryBuilder {
|
|
6
6
|
constructor(query = {}) {
|
|
7
7
|
this.query = {};
|
|
@@ -295,21 +295,7 @@ class BaseQueryBuilder {
|
|
|
295
295
|
const aliases = this._getCurrentAliases();
|
|
296
296
|
const refProxy = createRefProxy(aliases);
|
|
297
297
|
const selectObject = callback(refProxy);
|
|
298
|
-
const
|
|
299
|
-
const select = {};
|
|
300
|
-
for (const spreadAlias of spreadSentinels) {
|
|
301
|
-
const sentinelKey = `__SPREAD_SENTINEL__${spreadAlias}`;
|
|
302
|
-
select[sentinelKey] = toExpression(spreadAlias);
|
|
303
|
-
}
|
|
304
|
-
for (const [key, value] of Object.entries(selectObject)) {
|
|
305
|
-
if (isRefProxy(value)) {
|
|
306
|
-
select[key] = toExpression(value);
|
|
307
|
-
} else if (typeof value === `object` && `type` in value && (value.type === `agg` || value.type === `func`)) {
|
|
308
|
-
select[key] = value;
|
|
309
|
-
} else {
|
|
310
|
-
select[key] = toExpression(value);
|
|
311
|
-
}
|
|
312
|
-
}
|
|
298
|
+
const select = buildNestedSelect(selectObject);
|
|
313
299
|
return new BaseQueryBuilder({
|
|
314
300
|
...this.query,
|
|
315
301
|
select,
|
|
@@ -400,9 +386,10 @@ class BaseQueryBuilder {
|
|
|
400
386
|
const refProxy = createRefProxy(aliases);
|
|
401
387
|
const result = callback(refProxy);
|
|
402
388
|
const newExpressions = Array.isArray(result) ? result.map((r) => toExpression(r)) : [toExpression(result)];
|
|
389
|
+
const existingGroupBy = this.query.groupBy || [];
|
|
403
390
|
return new BaseQueryBuilder({
|
|
404
391
|
...this.query,
|
|
405
|
-
groupBy: newExpressions
|
|
392
|
+
groupBy: [...existingGroupBy, ...newExpressions]
|
|
406
393
|
});
|
|
407
394
|
}
|
|
408
395
|
/**
|
|
@@ -583,6 +570,28 @@ class BaseQueryBuilder {
|
|
|
583
570
|
return this.query;
|
|
584
571
|
}
|
|
585
572
|
}
|
|
573
|
+
function toExpr(value) {
|
|
574
|
+
if (value === void 0) return toExpression(null);
|
|
575
|
+
if (value instanceof Aggregate || value instanceof Func || value instanceof PropRef || value instanceof Value) {
|
|
576
|
+
return value;
|
|
577
|
+
}
|
|
578
|
+
return toExpression(value);
|
|
579
|
+
}
|
|
580
|
+
function isPlainObject(value) {
|
|
581
|
+
return value !== null && typeof value === `object` && !isExpressionLike(value) && !value.__refProxy;
|
|
582
|
+
}
|
|
583
|
+
function buildNestedSelect(obj) {
|
|
584
|
+
if (!isPlainObject(obj)) return toExpr(obj);
|
|
585
|
+
const out = {};
|
|
586
|
+
for (const [k, v] of Object.entries(obj)) {
|
|
587
|
+
if (typeof k === `string` && k.startsWith(`__SPREAD_SENTINEL__`)) {
|
|
588
|
+
out[k] = v;
|
|
589
|
+
continue;
|
|
590
|
+
}
|
|
591
|
+
out[k] = buildNestedSelect(v);
|
|
592
|
+
}
|
|
593
|
+
return out;
|
|
594
|
+
}
|
|
586
595
|
function buildQuery(fn) {
|
|
587
596
|
const result = fn(new BaseQueryBuilder());
|
|
588
597
|
return getQueryIR(result);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sources":["../../../../src/query/builder/index.ts"],"sourcesContent":["import { CollectionImpl } from \"../../collection.js\"\nimport { CollectionRef, QueryRef } from \"../ir.js\"\nimport {\n InvalidSourceError,\n JoinConditionMustBeEqualityError,\n OnlyOneSourceAllowedError,\n QueryMustHaveFromClauseError,\n SubQueryMustHaveFromClauseError,\n} from \"../../errors.js\"\nimport { createRefProxy, isRefProxy, toExpression } from \"./ref-proxy.js\"\nimport type { NamespacedRow } from \"../../types.js\"\nimport type {\n Aggregate,\n BasicExpression,\n JoinClause,\n OrderBy,\n OrderByDirection,\n QueryIR,\n} from \"../ir.js\"\nimport type {\n CompareOptions,\n Context,\n GroupByCallback,\n JoinOnCallback,\n MergeContext,\n MergeContextWithJoinType,\n OrderByCallback,\n OrderByOptions,\n RefProxyForContext,\n ResultTypeFromSelect,\n SchemaFromSource,\n SelectObject,\n Source,\n WhereCallback,\n WithResult,\n} from \"./types.js\"\n\nexport class BaseQueryBuilder<TContext extends Context = Context> {\n private readonly query: Partial<QueryIR> = {}\n\n constructor(query: Partial<QueryIR> = {}) {\n this.query = { ...query }\n }\n\n /**\n * Creates a CollectionRef or QueryRef from a source object\n * @param source - An object with a single key-value pair\n * @param context - Context string for error messages (e.g., \"from clause\", \"join clause\")\n * @returns A tuple of [alias, ref] where alias is the source key and ref is the created reference\n */\n private _createRefForSource<TSource extends Source>(\n source: TSource,\n context: string\n ): [string, CollectionRef | QueryRef] {\n if (Object.keys(source).length !== 1) {\n throw new OnlyOneSourceAllowedError(context)\n }\n\n const alias = Object.keys(source)[0]!\n const sourceValue = source[alias]\n\n let ref: CollectionRef | QueryRef\n\n if (sourceValue instanceof CollectionImpl) {\n ref = new CollectionRef(sourceValue, alias)\n } else if (sourceValue instanceof BaseQueryBuilder) {\n const subQuery = sourceValue._getQuery()\n if (!(subQuery as Partial<QueryIR>).from) {\n throw new SubQueryMustHaveFromClauseError(context)\n }\n ref = new QueryRef(subQuery, alias)\n } else {\n throw new InvalidSourceError(alias)\n }\n\n return [alias, ref]\n }\n\n /**\n * Specify the source table or subquery for the query\n *\n * @param source - An object with a single key-value pair where the key is the table alias and the value is a Collection or subquery\n * @returns A QueryBuilder with the specified source\n *\n * @example\n * ```ts\n * // Query from a collection\n * query.from({ users: usersCollection })\n *\n * // Query from a subquery\n * const activeUsers = query.from({ u: usersCollection }).where(({u}) => u.active)\n * query.from({ activeUsers })\n * ```\n */\n from<TSource extends Source>(\n source: TSource\n ): QueryBuilder<{\n baseSchema: SchemaFromSource<TSource>\n schema: SchemaFromSource<TSource>\n fromSourceName: keyof TSource & string\n hasJoins: false\n }> {\n const [, from] = this._createRefForSource(source, `from clause`)\n\n return new BaseQueryBuilder({\n ...this.query,\n from,\n }) as any\n }\n\n /**\n * Join another table or subquery to the current query\n *\n * @param source - An object with a single key-value pair where the key is the table alias and the value is a Collection or subquery\n * @param onCallback - A function that receives table references and returns the join condition\n * @param type - The type of join: 'inner', 'left', 'right', or 'full' (defaults to 'left')\n * @returns A QueryBuilder with the joined table available\n *\n * @example\n * ```ts\n * // Left join users with posts\n * query\n * .from({ users: usersCollection })\n * .join({ posts: postsCollection }, ({users, posts}) => eq(users.id, posts.userId))\n *\n * // Inner join with explicit type\n * query\n * .from({ u: usersCollection })\n * .join({ p: postsCollection }, ({u, p}) => eq(u.id, p.userId), 'inner')\n * ```\n *\n * // Join with a subquery\n * const activeUsers = query.from({ u: usersCollection }).where(({u}) => u.active)\n * query\n * .from({ activeUsers })\n * .join({ p: postsCollection }, ({u, p}) => eq(u.id, p.userId))\n */\n join<\n TSource extends Source,\n TJoinType extends `inner` | `left` | `right` | `full` = `left`,\n >(\n source: TSource,\n onCallback: JoinOnCallback<\n MergeContext<TContext, SchemaFromSource<TSource>>\n >,\n type: TJoinType = `left` as TJoinType\n ): QueryBuilder<\n MergeContextWithJoinType<TContext, SchemaFromSource<TSource>, TJoinType>\n > {\n const [alias, from] = this._createRefForSource(source, `join clause`)\n\n // Create a temporary context for the callback\n const currentAliases = this._getCurrentAliases()\n const newAliases = [...currentAliases, alias]\n const refProxy = createRefProxy(newAliases) as RefProxyForContext<\n MergeContext<TContext, SchemaFromSource<TSource>>\n >\n\n // Get the join condition expression\n const onExpression = onCallback(refProxy)\n\n // Extract left and right from the expression\n // For now, we'll assume it's an eq function with two arguments\n let left: BasicExpression\n let right: BasicExpression\n\n if (\n onExpression.type === `func` &&\n onExpression.name === `eq` &&\n onExpression.args.length === 2\n ) {\n left = onExpression.args[0]!\n right = onExpression.args[1]!\n } else {\n throw new JoinConditionMustBeEqualityError()\n }\n\n const joinClause: JoinClause = {\n from,\n type,\n left,\n right,\n }\n\n const existingJoins = this.query.join || []\n\n return new BaseQueryBuilder({\n ...this.query,\n join: [...existingJoins, joinClause],\n }) as any\n }\n\n /**\n * Perform a LEFT JOIN with another table or subquery\n *\n * @param source - An object with a single key-value pair where the key is the table alias and the value is a Collection or subquery\n * @param onCallback - A function that receives table references and returns the join condition\n * @returns A QueryBuilder with the left joined table available\n *\n * @example\n * ```ts\n * // Left join users with posts\n * query\n * .from({ users: usersCollection })\n * .leftJoin({ posts: postsCollection }, ({users, posts}) => eq(users.id, posts.userId))\n * ```\n */\n leftJoin<TSource extends Source>(\n source: TSource,\n onCallback: JoinOnCallback<\n MergeContext<TContext, SchemaFromSource<TSource>>\n >\n ): QueryBuilder<\n MergeContextWithJoinType<TContext, SchemaFromSource<TSource>, `left`>\n > {\n return this.join(source, onCallback, `left`)\n }\n\n /**\n * Perform a RIGHT JOIN with another table or subquery\n *\n * @param source - An object with a single key-value pair where the key is the table alias and the value is a Collection or subquery\n * @param onCallback - A function that receives table references and returns the join condition\n * @returns A QueryBuilder with the right joined table available\n *\n * @example\n * ```ts\n * // Right join users with posts\n * query\n * .from({ users: usersCollection })\n * .rightJoin({ posts: postsCollection }, ({users, posts}) => eq(users.id, posts.userId))\n * ```\n */\n rightJoin<TSource extends Source>(\n source: TSource,\n onCallback: JoinOnCallback<\n MergeContext<TContext, SchemaFromSource<TSource>>\n >\n ): QueryBuilder<\n MergeContextWithJoinType<TContext, SchemaFromSource<TSource>, `right`>\n > {\n return this.join(source, onCallback, `right`)\n }\n\n /**\n * Perform an INNER JOIN with another table or subquery\n *\n * @param source - An object with a single key-value pair where the key is the table alias and the value is a Collection or subquery\n * @param onCallback - A function that receives table references and returns the join condition\n * @returns A QueryBuilder with the inner joined table available\n *\n * @example\n * ```ts\n * // Inner join users with posts\n * query\n * .from({ users: usersCollection })\n * .innerJoin({ posts: postsCollection }, ({users, posts}) => eq(users.id, posts.userId))\n * ```\n */\n innerJoin<TSource extends Source>(\n source: TSource,\n onCallback: JoinOnCallback<\n MergeContext<TContext, SchemaFromSource<TSource>>\n >\n ): QueryBuilder<\n MergeContextWithJoinType<TContext, SchemaFromSource<TSource>, `inner`>\n > {\n return this.join(source, onCallback, `inner`)\n }\n\n /**\n * Perform a FULL JOIN with another table or subquery\n *\n * @param source - An object with a single key-value pair where the key is the table alias and the value is a Collection or subquery\n * @param onCallback - A function that receives table references and returns the join condition\n * @returns A QueryBuilder with the full joined table available\n *\n * @example\n * ```ts\n * // Full join users with posts\n * query\n * .from({ users: usersCollection })\n * .fullJoin({ posts: postsCollection }, ({users, posts}) => eq(users.id, posts.userId))\n * ```\n */\n fullJoin<TSource extends Source>(\n source: TSource,\n onCallback: JoinOnCallback<\n MergeContext<TContext, SchemaFromSource<TSource>>\n >\n ): QueryBuilder<\n MergeContextWithJoinType<TContext, SchemaFromSource<TSource>, `full`>\n > {\n return this.join(source, onCallback, `full`)\n }\n\n /**\n * Filter rows based on a condition\n *\n * @param callback - A function that receives table references and returns an expression\n * @returns A QueryBuilder with the where condition applied\n *\n * @example\n * ```ts\n * // Simple condition\n * query\n * .from({ users: usersCollection })\n * .where(({users}) => gt(users.age, 18))\n *\n * // Multiple conditions\n * query\n * .from({ users: usersCollection })\n * .where(({users}) => and(\n * gt(users.age, 18),\n * eq(users.active, true)\n * ))\n *\n * // Multiple where calls are ANDed together\n * query\n * .from({ users: usersCollection })\n * .where(({users}) => gt(users.age, 18))\n * .where(({users}) => eq(users.active, true))\n * ```\n */\n where(callback: WhereCallback<TContext>): QueryBuilder<TContext> {\n const aliases = this._getCurrentAliases()\n const refProxy = createRefProxy(aliases) as RefProxyForContext<TContext>\n const expression = callback(refProxy)\n\n const existingWhere = this.query.where || []\n\n return new BaseQueryBuilder({\n ...this.query,\n where: [...existingWhere, expression],\n }) as any\n }\n\n /**\n * Filter grouped rows based on aggregate conditions\n *\n * @param callback - A function that receives table references and returns an expression\n * @returns A QueryBuilder with the having condition applied\n *\n * @example\n * ```ts\n * // Filter groups by count\n * query\n * .from({ posts: postsCollection })\n * .groupBy(({posts}) => posts.userId)\n * .having(({posts}) => gt(count(posts.id), 5))\n *\n * // Filter by average\n * query\n * .from({ orders: ordersCollection })\n * .groupBy(({orders}) => orders.customerId)\n * .having(({orders}) => gt(avg(orders.total), 100))\n *\n * // Multiple having calls are ANDed together\n * query\n * .from({ orders: ordersCollection })\n * .groupBy(({orders}) => orders.customerId)\n * .having(({orders}) => gt(count(orders.id), 5))\n * .having(({orders}) => gt(avg(orders.total), 100))\n * ```\n */\n having(callback: WhereCallback<TContext>): QueryBuilder<TContext> {\n const aliases = this._getCurrentAliases()\n const refProxy = createRefProxy(aliases) as RefProxyForContext<TContext>\n const expression = callback(refProxy)\n\n const existingHaving = this.query.having || []\n\n return new BaseQueryBuilder({\n ...this.query,\n having: [...existingHaving, expression],\n }) as any\n }\n\n /**\n * Select specific columns or computed values from the query\n *\n * @param callback - A function that receives table references and returns an object with selected fields or expressions\n * @returns A QueryBuilder that returns only the selected fields\n *\n * @example\n * ```ts\n * // Select specific columns\n * query\n * .from({ users: usersCollection })\n * .select(({users}) => ({\n * name: users.name,\n * email: users.email\n * }))\n *\n * // Select with computed values\n * query\n * .from({ users: usersCollection })\n * .select(({users}) => ({\n * fullName: concat(users.firstName, ' ', users.lastName),\n * ageInMonths: mul(users.age, 12)\n * }))\n *\n * // Select with aggregates (requires GROUP BY)\n * query\n * .from({ posts: postsCollection })\n * .groupBy(({posts}) => posts.userId)\n * .select(({posts, count}) => ({\n * userId: posts.userId,\n * postCount: count(posts.id)\n * }))\n * ```\n */\n select<TSelectObject extends SelectObject>(\n callback: (refs: RefProxyForContext<TContext>) => TSelectObject\n ): QueryBuilder<WithResult<TContext, ResultTypeFromSelect<TSelectObject>>> {\n const aliases = this._getCurrentAliases()\n const refProxy = createRefProxy(aliases) as RefProxyForContext<TContext>\n const selectObject = callback(refProxy)\n\n // Check if any tables were spread during the callback\n const spreadSentinels = (refProxy as any).__spreadSentinels as Set<string>\n\n // Convert the select object to use expressions, including spread sentinels\n const select: Record<string, BasicExpression | Aggregate> = {}\n\n // First, add spread sentinels for any tables that were spread\n for (const spreadAlias of spreadSentinels) {\n const sentinelKey = `__SPREAD_SENTINEL__${spreadAlias}`\n select[sentinelKey] = toExpression(spreadAlias) // Use alias as a simple reference\n }\n\n // Then add the explicit select fields\n for (const [key, value] of Object.entries(selectObject)) {\n if (isRefProxy(value)) {\n select[key] = toExpression(value)\n } else if (\n typeof value === `object` &&\n `type` in value &&\n (value.type === `agg` || value.type === `func`)\n ) {\n select[key] = value as BasicExpression | Aggregate\n } else {\n select[key] = toExpression(value)\n }\n }\n\n return new BaseQueryBuilder({\n ...this.query,\n select,\n fnSelect: undefined, // remove the fnSelect clause if it exists\n }) as any\n }\n\n /**\n * Sort the query results by one or more columns\n *\n * @param callback - A function that receives table references and returns the field to sort by\n * @param direction - Sort direction: 'asc' for ascending, 'desc' for descending (defaults to 'asc')\n * @returns A QueryBuilder with the ordering applied\n *\n * @example\n * ```ts\n * // Sort by a single column\n * query\n * .from({ users: usersCollection })\n * .orderBy(({users}) => users.name)\n *\n * // Sort descending\n * query\n * .from({ users: usersCollection })\n * .orderBy(({users}) => users.createdAt, 'desc')\n *\n * // Multiple sorts (chain orderBy calls)\n * query\n * .from({ users: usersCollection })\n * .orderBy(({users}) => users.lastName)\n * .orderBy(({users}) => users.firstName)\n * ```\n */\n orderBy(\n callback: OrderByCallback<TContext>,\n options: OrderByDirection | OrderByOptions = `asc`\n ): QueryBuilder<TContext> {\n const aliases = this._getCurrentAliases()\n const refProxy = createRefProxy(aliases) as RefProxyForContext<TContext>\n const result = callback(refProxy)\n\n const opts: CompareOptions =\n typeof options === `string`\n ? { direction: options, nulls: `first`, stringSort: `locale` }\n : {\n direction: options.direction ?? `asc`,\n nulls: options.nulls ?? `first`,\n stringSort: options.stringSort ?? `locale`,\n locale:\n options.stringSort === `locale` ? options.locale : undefined,\n localeOptions:\n options.stringSort === `locale`\n ? options.localeOptions\n : undefined,\n }\n\n const makeOrderByClause = (res: any) => {\n return {\n expression: toExpression(res),\n compareOptions: opts,\n }\n }\n\n // Create the new OrderBy structure with expression and direction\n const orderByClauses = Array.isArray(result)\n ? result.map((r) => makeOrderByClause(r))\n : [makeOrderByClause(result)]\n\n const existingOrderBy: OrderBy = this.query.orderBy || []\n\n return new BaseQueryBuilder({\n ...this.query,\n orderBy: [...existingOrderBy, ...orderByClauses],\n }) as any\n }\n\n /**\n * Group rows by one or more columns for aggregation\n *\n * @param callback - A function that receives table references and returns the field(s) to group by\n * @returns A QueryBuilder with grouping applied (enables aggregate functions in SELECT and HAVING)\n *\n * @example\n * ```ts\n * // Group by a single column\n * query\n * .from({ posts: postsCollection })\n * .groupBy(({posts}) => posts.userId)\n * .select(({posts, count}) => ({\n * userId: posts.userId,\n * postCount: count()\n * }))\n *\n * // Group by multiple columns\n * query\n * .from({ sales: salesCollection })\n * .groupBy(({sales}) => [sales.region, sales.category])\n * .select(({sales, sum}) => ({\n * region: sales.region,\n * category: sales.category,\n * totalSales: sum(sales.amount)\n * }))\n * ```\n */\n groupBy(callback: GroupByCallback<TContext>): QueryBuilder<TContext> {\n const aliases = this._getCurrentAliases()\n const refProxy = createRefProxy(aliases) as RefProxyForContext<TContext>\n const result = callback(refProxy)\n\n const newExpressions = Array.isArray(result)\n ? result.map((r) => toExpression(r))\n : [toExpression(result)]\n\n // Replace existing groupBy expressions instead of extending them\n return new BaseQueryBuilder({\n ...this.query,\n groupBy: newExpressions,\n }) as any\n }\n\n /**\n * Limit the number of rows returned by the query\n * `orderBy` is required for `limit`\n *\n * @param count - Maximum number of rows to return\n * @returns A QueryBuilder with the limit applied\n *\n * @example\n * ```ts\n * // Get top 5 posts by likes\n * query\n * .from({ posts: postsCollection })\n * .orderBy(({posts}) => posts.likes, 'desc')\n * .limit(5)\n * ```\n */\n limit(count: number): QueryBuilder<TContext> {\n return new BaseQueryBuilder({\n ...this.query,\n limit: count,\n }) as any\n }\n\n /**\n * Skip a number of rows before returning results\n * `orderBy` is required for `offset`\n *\n * @param count - Number of rows to skip\n * @returns A QueryBuilder with the offset applied\n *\n * @example\n * ```ts\n * // Get second page of results\n * query\n * .from({ posts: postsCollection })\n * .orderBy(({posts}) => posts.createdAt, 'desc')\n * .offset(page * pageSize)\n * .limit(pageSize)\n * ```\n */\n offset(count: number): QueryBuilder<TContext> {\n return new BaseQueryBuilder({\n ...this.query,\n offset: count,\n }) as any\n }\n\n /**\n * Specify that the query should return distinct rows.\n * Deduplicates rows based on the selected columns.\n * @returns A QueryBuilder with distinct enabled\n *\n * @example\n * ```ts\n * // Get countries our users are from\n * query\n * .from({ users: usersCollection })\n * .select(({users}) => users.country)\n * .distinct()\n * ```\n */\n distinct(): QueryBuilder<TContext> {\n return new BaseQueryBuilder({\n ...this.query,\n distinct: true,\n }) as any\n }\n\n // Helper methods\n private _getCurrentAliases(): Array<string> {\n const aliases: Array<string> = []\n\n // Add the from alias\n if (this.query.from) {\n aliases.push(this.query.from.alias)\n }\n\n // Add join aliases\n if (this.query.join) {\n for (const join of this.query.join) {\n aliases.push(join.from.alias)\n }\n }\n\n return aliases\n }\n\n /**\n * Functional variants of the query builder\n * These are imperative function that are called for ery row.\n * Warning: that these cannot be optimized by the query compiler, and may prevent\n * some type of optimizations being possible.\n * @example\n * ```ts\n * q.fn.select((row) => ({\n * name: row.user.name.toUpperCase(),\n * age: row.user.age + 1,\n * }))\n * ```\n */\n get fn() {\n const builder = this\n return {\n /**\n * Select fields using a function that operates on each row\n * Warning: This cannot be optimized by the query compiler\n *\n * @param callback - A function that receives a row and returns the selected value\n * @returns A QueryBuilder with functional selection applied\n *\n * @example\n * ```ts\n * // Functional select (not optimized)\n * query\n * .from({ users: usersCollection })\n * .fn.select(row => ({\n * name: row.users.name.toUpperCase(),\n * age: row.users.age + 1,\n * }))\n * ```\n */\n select<TFuncSelectResult>(\n callback: (row: TContext[`schema`]) => TFuncSelectResult\n ): QueryBuilder<WithResult<TContext, TFuncSelectResult>> {\n return new BaseQueryBuilder({\n ...builder.query,\n select: undefined, // remove the select clause if it exists\n fnSelect: callback,\n })\n },\n /**\n * Filter rows using a function that operates on each row\n * Warning: This cannot be optimized by the query compiler\n *\n * @param callback - A function that receives a row and returns a boolean\n * @returns A QueryBuilder with functional filtering applied\n *\n * @example\n * ```ts\n * // Functional where (not optimized)\n * query\n * .from({ users: usersCollection })\n * .fn.where(row => row.users.name.startsWith('A'))\n * ```\n */\n where(\n callback: (row: TContext[`schema`]) => any\n ): QueryBuilder<TContext> {\n return new BaseQueryBuilder({\n ...builder.query,\n fnWhere: [\n ...(builder.query.fnWhere || []),\n callback as (row: NamespacedRow) => any,\n ],\n })\n },\n /**\n * Filter grouped rows using a function that operates on each aggregated row\n * Warning: This cannot be optimized by the query compiler\n *\n * @param callback - A function that receives an aggregated row and returns a boolean\n * @returns A QueryBuilder with functional having filter applied\n *\n * @example\n * ```ts\n * // Functional having (not optimized)\n * query\n * .from({ posts: postsCollection })\n * .groupBy(({posts}) => posts.userId)\n * .fn.having(row => row.count > 5)\n * ```\n */\n having(\n callback: (row: TContext[`schema`]) => any\n ): QueryBuilder<TContext> {\n return new BaseQueryBuilder({\n ...builder.query,\n fnHaving: [\n ...(builder.query.fnHaving || []),\n callback as (row: NamespacedRow) => any,\n ],\n })\n },\n }\n }\n\n _getQuery(): QueryIR {\n if (!this.query.from) {\n throw new QueryMustHaveFromClauseError()\n }\n return this.query as QueryIR\n }\n}\n\n// Internal function to build a query from a callback\n// used by liveQueryCollectionOptions.query\nexport function buildQuery<TContext extends Context>(\n fn: (builder: InitialQueryBuilder) => QueryBuilder<TContext>\n): QueryIR {\n const result = fn(new BaseQueryBuilder())\n return getQueryIR(result)\n}\n\n// Internal function to get the QueryIR from a builder\nexport function getQueryIR(\n builder: BaseQueryBuilder | QueryBuilder<any> | InitialQueryBuilder\n): QueryIR {\n return (builder as unknown as BaseQueryBuilder)._getQuery()\n}\n\n// Type-only exports for the query builder\nexport type InitialQueryBuilder = Pick<BaseQueryBuilder<Context>, `from`>\n\nexport type InitialQueryBuilderConstructor = new () => InitialQueryBuilder\n\nexport type QueryBuilder<TContext extends Context> = Omit<\n BaseQueryBuilder<TContext>,\n `from` | `_getQuery`\n>\n\n// Main query builder class alias with the constructor type modified to hide all\n// but the from method on the initial instance\nexport const Query: InitialQueryBuilderConstructor = BaseQueryBuilder\n\n// Helper type to extract context from a QueryBuilder\nexport type ExtractContext<T> =\n T extends BaseQueryBuilder<infer TContext>\n ? TContext\n : T extends QueryBuilder<infer TContext>\n ? TContext\n : never\n\n// Export the types from types.ts for convenience\nexport type { Context, Source, GetResult } from \"./types.js\"\n"],"names":[],"mappings":";;;;AAqCO,MAAM,iBAAqD;AAAA,EAGhE,YAAY,QAA0B,IAAI;AAF1C,SAAiB,QAA0B,CAAA;AAGzC,SAAK,QAAQ,EAAE,GAAG,MAAA;AAAA,EACpB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQQ,oBACN,QACA,SACoC;AACpC,QAAI,OAAO,KAAK,MAAM,EAAE,WAAW,GAAG;AACpC,YAAM,IAAI,0BAA0B,OAAO;AAAA,IAC7C;AAEA,UAAM,QAAQ,OAAO,KAAK,MAAM,EAAE,CAAC;AACnC,UAAM,cAAc,OAAO,KAAK;AAEhC,QAAI;AAEJ,QAAI,uBAAuB,gBAAgB;AACzC,YAAM,IAAI,cAAc,aAAa,KAAK;AAAA,IAC5C,WAAW,uBAAuB,kBAAkB;AAClD,YAAM,WAAW,YAAY,UAAA;AAC7B,UAAI,CAAE,SAA8B,MAAM;AACxC,cAAM,IAAI,gCAAgC,OAAO;AAAA,MACnD;AACA,YAAM,IAAI,SAAS,UAAU,KAAK;AAAA,IACpC,OAAO;AACL,YAAM,IAAI,mBAAmB,KAAK;AAAA,IACpC;AAEA,WAAO,CAAC,OAAO,GAAG;AAAA,EACpB;AA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file":"index.js","sources":["../../../../src/query/builder/index.ts"],"sourcesContent":["import { CollectionImpl } from \"../../collection.js\"\nimport {\n Aggregate as AggregateExpr,\n CollectionRef,\n Func as FuncExpr,\n PropRef,\n QueryRef,\n Value as ValueExpr,\n isExpressionLike,\n} from \"../ir.js\"\nimport {\n InvalidSourceError,\n JoinConditionMustBeEqualityError,\n OnlyOneSourceAllowedError,\n QueryMustHaveFromClauseError,\n SubQueryMustHaveFromClauseError,\n} from \"../../errors.js\"\nimport { createRefProxy, toExpression } from \"./ref-proxy.js\"\nimport type { NamespacedRow } from \"../../types.js\"\nimport type {\n Aggregate,\n BasicExpression,\n JoinClause,\n OrderBy,\n OrderByDirection,\n QueryIR,\n} from \"../ir.js\"\nimport type {\n CompareOptions,\n Context,\n GroupByCallback,\n JoinOnCallback,\n MergeContextForJoinCallback,\n MergeContextWithJoinType,\n OrderByCallback,\n OrderByOptions,\n RefsForContext,\n ResultTypeFromSelect,\n SchemaFromSource,\n SelectObject,\n Source,\n WhereCallback,\n WithResult,\n} from \"./types.js\"\n\nexport class BaseQueryBuilder<TContext extends Context = Context> {\n private readonly query: Partial<QueryIR> = {}\n\n constructor(query: Partial<QueryIR> = {}) {\n this.query = { ...query }\n }\n\n /**\n * Creates a CollectionRef or QueryRef from a source object\n * @param source - An object with a single key-value pair\n * @param context - Context string for error messages (e.g., \"from clause\", \"join clause\")\n * @returns A tuple of [alias, ref] where alias is the source key and ref is the created reference\n */\n private _createRefForSource<TSource extends Source>(\n source: TSource,\n context: string\n ): [string, CollectionRef | QueryRef] {\n if (Object.keys(source).length !== 1) {\n throw new OnlyOneSourceAllowedError(context)\n }\n\n const alias = Object.keys(source)[0]!\n const sourceValue = source[alias]\n\n let ref: CollectionRef | QueryRef\n\n if (sourceValue instanceof CollectionImpl) {\n ref = new CollectionRef(sourceValue, alias)\n } else if (sourceValue instanceof BaseQueryBuilder) {\n const subQuery = sourceValue._getQuery()\n if (!(subQuery as Partial<QueryIR>).from) {\n throw new SubQueryMustHaveFromClauseError(context)\n }\n ref = new QueryRef(subQuery, alias)\n } else {\n throw new InvalidSourceError(alias)\n }\n\n return [alias, ref]\n }\n\n /**\n * Specify the source table or subquery for the query\n *\n * @param source - An object with a single key-value pair where the key is the table alias and the value is a Collection or subquery\n * @returns A QueryBuilder with the specified source\n *\n * @example\n * ```ts\n * // Query from a collection\n * query.from({ users: usersCollection })\n *\n * // Query from a subquery\n * const activeUsers = query.from({ u: usersCollection }).where(({u}) => u.active)\n * query.from({ activeUsers })\n * ```\n */\n from<TSource extends Source>(\n source: TSource\n ): QueryBuilder<{\n baseSchema: SchemaFromSource<TSource>\n schema: SchemaFromSource<TSource>\n fromSourceName: keyof TSource & string\n hasJoins: false\n }> {\n const [, from] = this._createRefForSource(source, `from clause`)\n\n return new BaseQueryBuilder({\n ...this.query,\n from,\n }) as any\n }\n\n /**\n * Join another table or subquery to the current query\n *\n * @param source - An object with a single key-value pair where the key is the table alias and the value is a Collection or subquery\n * @param onCallback - A function that receives table references and returns the join condition\n * @param type - The type of join: 'inner', 'left', 'right', or 'full' (defaults to 'left')\n * @returns A QueryBuilder with the joined table available\n *\n * @example\n * ```ts\n * // Left join users with posts\n * query\n * .from({ users: usersCollection })\n * .join({ posts: postsCollection }, ({users, posts}) => eq(users.id, posts.userId))\n *\n * // Inner join with explicit type\n * query\n * .from({ u: usersCollection })\n * .join({ p: postsCollection }, ({u, p}) => eq(u.id, p.userId), 'inner')\n * ```\n *\n * // Join with a subquery\n * const activeUsers = query.from({ u: usersCollection }).where(({u}) => u.active)\n * query\n * .from({ activeUsers })\n * .join({ p: postsCollection }, ({u, p}) => eq(u.id, p.userId))\n */\n join<\n TSource extends Source,\n TJoinType extends `inner` | `left` | `right` | `full` = `left`,\n >(\n source: TSource,\n onCallback: JoinOnCallback<\n MergeContextForJoinCallback<TContext, SchemaFromSource<TSource>>\n >,\n type: TJoinType = `left` as TJoinType\n ): QueryBuilder<\n MergeContextWithJoinType<TContext, SchemaFromSource<TSource>, TJoinType>\n > {\n const [alias, from] = this._createRefForSource(source, `join clause`)\n\n // Create a temporary context for the callback\n const currentAliases = this._getCurrentAliases()\n const newAliases = [...currentAliases, alias]\n const refProxy = createRefProxy(newAliases) as RefsForContext<\n MergeContextForJoinCallback<TContext, SchemaFromSource<TSource>>\n >\n\n // Get the join condition expression\n const onExpression = onCallback(refProxy)\n\n // Extract left and right from the expression\n // For now, we'll assume it's an eq function with two arguments\n let left: BasicExpression\n let right: BasicExpression\n\n if (\n onExpression.type === `func` &&\n onExpression.name === `eq` &&\n onExpression.args.length === 2\n ) {\n left = onExpression.args[0]!\n right = onExpression.args[1]!\n } else {\n throw new JoinConditionMustBeEqualityError()\n }\n\n const joinClause: JoinClause = {\n from,\n type,\n left,\n right,\n }\n\n const existingJoins = this.query.join || []\n\n return new BaseQueryBuilder({\n ...this.query,\n join: [...existingJoins, joinClause],\n }) as any\n }\n\n /**\n * Perform a LEFT JOIN with another table or subquery\n *\n * @param source - An object with a single key-value pair where the key is the table alias and the value is a Collection or subquery\n * @param onCallback - A function that receives table references and returns the join condition\n * @returns A QueryBuilder with the left joined table available\n *\n * @example\n * ```ts\n * // Left join users with posts\n * query\n * .from({ users: usersCollection })\n * .leftJoin({ posts: postsCollection }, ({users, posts}) => eq(users.id, posts.userId))\n * ```\n */\n leftJoin<TSource extends Source>(\n source: TSource,\n onCallback: JoinOnCallback<\n MergeContextForJoinCallback<TContext, SchemaFromSource<TSource>>\n >\n ): QueryBuilder<\n MergeContextWithJoinType<TContext, SchemaFromSource<TSource>, `left`>\n > {\n return this.join(source, onCallback, `left`)\n }\n\n /**\n * Perform a RIGHT JOIN with another table or subquery\n *\n * @param source - An object with a single key-value pair where the key is the table alias and the value is a Collection or subquery\n * @param onCallback - A function that receives table references and returns the join condition\n * @returns A QueryBuilder with the right joined table available\n *\n * @example\n * ```ts\n * // Right join users with posts\n * query\n * .from({ users: usersCollection })\n * .rightJoin({ posts: postsCollection }, ({users, posts}) => eq(users.id, posts.userId))\n * ```\n */\n rightJoin<TSource extends Source>(\n source: TSource,\n onCallback: JoinOnCallback<\n MergeContextForJoinCallback<TContext, SchemaFromSource<TSource>>\n >\n ): QueryBuilder<\n MergeContextWithJoinType<TContext, SchemaFromSource<TSource>, `right`>\n > {\n return this.join(source, onCallback, `right`)\n }\n\n /**\n * Perform an INNER JOIN with another table or subquery\n *\n * @param source - An object with a single key-value pair where the key is the table alias and the value is a Collection or subquery\n * @param onCallback - A function that receives table references and returns the join condition\n * @returns A QueryBuilder with the inner joined table available\n *\n * @example\n * ```ts\n * // Inner join users with posts\n * query\n * .from({ users: usersCollection })\n * .innerJoin({ posts: postsCollection }, ({users, posts}) => eq(users.id, posts.userId))\n * ```\n */\n innerJoin<TSource extends Source>(\n source: TSource,\n onCallback: JoinOnCallback<\n MergeContextForJoinCallback<TContext, SchemaFromSource<TSource>>\n >\n ): QueryBuilder<\n MergeContextWithJoinType<TContext, SchemaFromSource<TSource>, `inner`>\n > {\n return this.join(source, onCallback, `inner`)\n }\n\n /**\n * Perform a FULL JOIN with another table or subquery\n *\n * @param source - An object with a single key-value pair where the key is the table alias and the value is a Collection or subquery\n * @param onCallback - A function that receives table references and returns the join condition\n * @returns A QueryBuilder with the full joined table available\n *\n * @example\n * ```ts\n * // Full join users with posts\n * query\n * .from({ users: usersCollection })\n * .fullJoin({ posts: postsCollection }, ({users, posts}) => eq(users.id, posts.userId))\n * ```\n */\n fullJoin<TSource extends Source>(\n source: TSource,\n onCallback: JoinOnCallback<\n MergeContextForJoinCallback<TContext, SchemaFromSource<TSource>>\n >\n ): QueryBuilder<\n MergeContextWithJoinType<TContext, SchemaFromSource<TSource>, `full`>\n > {\n return this.join(source, onCallback, `full`)\n }\n\n /**\n * Filter rows based on a condition\n *\n * @param callback - A function that receives table references and returns an expression\n * @returns A QueryBuilder with the where condition applied\n *\n * @example\n * ```ts\n * // Simple condition\n * query\n * .from({ users: usersCollection })\n * .where(({users}) => gt(users.age, 18))\n *\n * // Multiple conditions\n * query\n * .from({ users: usersCollection })\n * .where(({users}) => and(\n * gt(users.age, 18),\n * eq(users.active, true)\n * ))\n *\n * // Multiple where calls are ANDed together\n * query\n * .from({ users: usersCollection })\n * .where(({users}) => gt(users.age, 18))\n * .where(({users}) => eq(users.active, true))\n * ```\n */\n where(callback: WhereCallback<TContext>): QueryBuilder<TContext> {\n const aliases = this._getCurrentAliases()\n const refProxy = createRefProxy(aliases) as RefsForContext<TContext>\n const expression = callback(refProxy)\n\n const existingWhere = this.query.where || []\n\n return new BaseQueryBuilder({\n ...this.query,\n where: [...existingWhere, expression],\n }) as any\n }\n\n /**\n * Filter grouped rows based on aggregate conditions\n *\n * @param callback - A function that receives table references and returns an expression\n * @returns A QueryBuilder with the having condition applied\n *\n * @example\n * ```ts\n * // Filter groups by count\n * query\n * .from({ posts: postsCollection })\n * .groupBy(({posts}) => posts.userId)\n * .having(({posts}) => gt(count(posts.id), 5))\n *\n * // Filter by average\n * query\n * .from({ orders: ordersCollection })\n * .groupBy(({orders}) => orders.customerId)\n * .having(({orders}) => gt(avg(orders.total), 100))\n *\n * // Multiple having calls are ANDed together\n * query\n * .from({ orders: ordersCollection })\n * .groupBy(({orders}) => orders.customerId)\n * .having(({orders}) => gt(count(orders.id), 5))\n * .having(({orders}) => gt(avg(orders.total), 100))\n * ```\n */\n having(callback: WhereCallback<TContext>): QueryBuilder<TContext> {\n const aliases = this._getCurrentAliases()\n const refProxy = createRefProxy(aliases) as RefsForContext<TContext>\n const expression = callback(refProxy)\n\n const existingHaving = this.query.having || []\n\n return new BaseQueryBuilder({\n ...this.query,\n having: [...existingHaving, expression],\n }) as any\n }\n\n /**\n * Select specific columns or computed values from the query\n *\n * @param callback - A function that receives table references and returns an object with selected fields or expressions\n * @returns A QueryBuilder that returns only the selected fields\n *\n * @example\n * ```ts\n * // Select specific columns\n * query\n * .from({ users: usersCollection })\n * .select(({users}) => ({\n * name: users.name,\n * email: users.email\n * }))\n *\n * // Select with computed values\n * query\n * .from({ users: usersCollection })\n * .select(({users}) => ({\n * fullName: concat(users.firstName, ' ', users.lastName),\n * ageInMonths: mul(users.age, 12)\n * }))\n *\n * // Select with aggregates (requires GROUP BY)\n * query\n * .from({ posts: postsCollection })\n * .groupBy(({posts}) => posts.userId)\n * .select(({posts, count}) => ({\n * userId: posts.userId,\n * postCount: count(posts.id)\n * }))\n * ```\n */\n select<TSelectObject extends SelectObject>(\n callback: (refs: RefsForContext<TContext>) => TSelectObject\n ): QueryBuilder<WithResult<TContext, ResultTypeFromSelect<TSelectObject>>> {\n const aliases = this._getCurrentAliases()\n const refProxy = createRefProxy(aliases) as RefsForContext<TContext>\n const selectObject = callback(refProxy)\n const select = buildNestedSelect(selectObject)\n\n return new BaseQueryBuilder({\n ...this.query,\n select: select,\n fnSelect: undefined, // remove the fnSelect clause if it exists\n }) as any\n }\n\n /**\n * Sort the query results by one or more columns\n *\n * @param callback - A function that receives table references and returns the field to sort by\n * @param direction - Sort direction: 'asc' for ascending, 'desc' for descending (defaults to 'asc')\n * @returns A QueryBuilder with the ordering applied\n *\n * @example\n * ```ts\n * // Sort by a single column\n * query\n * .from({ users: usersCollection })\n * .orderBy(({users}) => users.name)\n *\n * // Sort descending\n * query\n * .from({ users: usersCollection })\n * .orderBy(({users}) => users.createdAt, 'desc')\n *\n * // Multiple sorts (chain orderBy calls)\n * query\n * .from({ users: usersCollection })\n * .orderBy(({users}) => users.lastName)\n * .orderBy(({users}) => users.firstName)\n * ```\n */\n orderBy(\n callback: OrderByCallback<TContext>,\n options: OrderByDirection | OrderByOptions = `asc`\n ): QueryBuilder<TContext> {\n const aliases = this._getCurrentAliases()\n const refProxy = createRefProxy(aliases) as RefsForContext<TContext>\n const result = callback(refProxy)\n\n const opts: CompareOptions =\n typeof options === `string`\n ? { direction: options, nulls: `first`, stringSort: `locale` }\n : {\n direction: options.direction ?? `asc`,\n nulls: options.nulls ?? `first`,\n stringSort: options.stringSort ?? `locale`,\n locale:\n options.stringSort === `locale` ? options.locale : undefined,\n localeOptions:\n options.stringSort === `locale`\n ? options.localeOptions\n : undefined,\n }\n\n const makeOrderByClause = (res: any) => {\n return {\n expression: toExpression(res),\n compareOptions: opts,\n }\n }\n\n // Create the new OrderBy structure with expression and direction\n const orderByClauses = Array.isArray(result)\n ? result.map((r) => makeOrderByClause(r))\n : [makeOrderByClause(result)]\n\n const existingOrderBy: OrderBy = this.query.orderBy || []\n\n return new BaseQueryBuilder({\n ...this.query,\n orderBy: [...existingOrderBy, ...orderByClauses],\n }) as any\n }\n\n /**\n * Group rows by one or more columns for aggregation\n *\n * @param callback - A function that receives table references and returns the field(s) to group by\n * @returns A QueryBuilder with grouping applied (enables aggregate functions in SELECT and HAVING)\n *\n * @example\n * ```ts\n * // Group by a single column\n * query\n * .from({ posts: postsCollection })\n * .groupBy(({posts}) => posts.userId)\n * .select(({posts, count}) => ({\n * userId: posts.userId,\n * postCount: count()\n * }))\n *\n * // Group by multiple columns\n * query\n * .from({ sales: salesCollection })\n * .groupBy(({sales}) => [sales.region, sales.category])\n * .select(({sales, sum}) => ({\n * region: sales.region,\n * category: sales.category,\n * totalSales: sum(sales.amount)\n * }))\n * ```\n */\n groupBy(callback: GroupByCallback<TContext>): QueryBuilder<TContext> {\n const aliases = this._getCurrentAliases()\n const refProxy = createRefProxy(aliases) as RefsForContext<TContext>\n const result = callback(refProxy)\n\n const newExpressions = Array.isArray(result)\n ? result.map((r) => toExpression(r))\n : [toExpression(result)]\n\n // Extend existing groupBy expressions (multiple groupBy calls should accumulate)\n const existingGroupBy = this.query.groupBy || []\n return new BaseQueryBuilder({\n ...this.query,\n groupBy: [...existingGroupBy, ...newExpressions],\n }) as any\n }\n\n /**\n * Limit the number of rows returned by the query\n * `orderBy` is required for `limit`\n *\n * @param count - Maximum number of rows to return\n * @returns A QueryBuilder with the limit applied\n *\n * @example\n * ```ts\n * // Get top 5 posts by likes\n * query\n * .from({ posts: postsCollection })\n * .orderBy(({posts}) => posts.likes, 'desc')\n * .limit(5)\n * ```\n */\n limit(count: number): QueryBuilder<TContext> {\n return new BaseQueryBuilder({\n ...this.query,\n limit: count,\n }) as any\n }\n\n /**\n * Skip a number of rows before returning results\n * `orderBy` is required for `offset`\n *\n * @param count - Number of rows to skip\n * @returns A QueryBuilder with the offset applied\n *\n * @example\n * ```ts\n * // Get second page of results\n * query\n * .from({ posts: postsCollection })\n * .orderBy(({posts}) => posts.createdAt, 'desc')\n * .offset(page * pageSize)\n * .limit(pageSize)\n * ```\n */\n offset(count: number): QueryBuilder<TContext> {\n return new BaseQueryBuilder({\n ...this.query,\n offset: count,\n }) as any\n }\n\n /**\n * Specify that the query should return distinct rows.\n * Deduplicates rows based on the selected columns.\n * @returns A QueryBuilder with distinct enabled\n *\n * @example\n * ```ts\n * // Get countries our users are from\n * query\n * .from({ users: usersCollection })\n * .select(({users}) => users.country)\n * .distinct()\n * ```\n */\n distinct(): QueryBuilder<TContext> {\n return new BaseQueryBuilder({\n ...this.query,\n distinct: true,\n }) as any\n }\n\n // Helper methods\n private _getCurrentAliases(): Array<string> {\n const aliases: Array<string> = []\n\n // Add the from alias\n if (this.query.from) {\n aliases.push(this.query.from.alias)\n }\n\n // Add join aliases\n if (this.query.join) {\n for (const join of this.query.join) {\n aliases.push(join.from.alias)\n }\n }\n\n return aliases\n }\n\n /**\n * Functional variants of the query builder\n * These are imperative function that are called for ery row.\n * Warning: that these cannot be optimized by the query compiler, and may prevent\n * some type of optimizations being possible.\n * @example\n * ```ts\n * q.fn.select((row) => ({\n * name: row.user.name.toUpperCase(),\n * age: row.user.age + 1,\n * }))\n * ```\n */\n get fn() {\n const builder = this\n return {\n /**\n * Select fields using a function that operates on each row\n * Warning: This cannot be optimized by the query compiler\n *\n * @param callback - A function that receives a row and returns the selected value\n * @returns A QueryBuilder with functional selection applied\n *\n * @example\n * ```ts\n * // Functional select (not optimized)\n * query\n * .from({ users: usersCollection })\n * .fn.select(row => ({\n * name: row.users.name.toUpperCase(),\n * age: row.users.age + 1,\n * }))\n * ```\n */\n select<TFuncSelectResult>(\n callback: (row: TContext[`schema`]) => TFuncSelectResult\n ): QueryBuilder<WithResult<TContext, TFuncSelectResult>> {\n return new BaseQueryBuilder({\n ...builder.query,\n select: undefined, // remove the select clause if it exists\n fnSelect: callback,\n })\n },\n /**\n * Filter rows using a function that operates on each row\n * Warning: This cannot be optimized by the query compiler\n *\n * @param callback - A function that receives a row and returns a boolean\n * @returns A QueryBuilder with functional filtering applied\n *\n * @example\n * ```ts\n * // Functional where (not optimized)\n * query\n * .from({ users: usersCollection })\n * .fn.where(row => row.users.name.startsWith('A'))\n * ```\n */\n where(\n callback: (row: TContext[`schema`]) => any\n ): QueryBuilder<TContext> {\n return new BaseQueryBuilder({\n ...builder.query,\n fnWhere: [\n ...(builder.query.fnWhere || []),\n callback as (row: NamespacedRow) => any,\n ],\n })\n },\n /**\n * Filter grouped rows using a function that operates on each aggregated row\n * Warning: This cannot be optimized by the query compiler\n *\n * @param callback - A function that receives an aggregated row and returns a boolean\n * @returns A QueryBuilder with functional having filter applied\n *\n * @example\n * ```ts\n * // Functional having (not optimized)\n * query\n * .from({ posts: postsCollection })\n * .groupBy(({posts}) => posts.userId)\n * .fn.having(row => row.count > 5)\n * ```\n */\n having(\n callback: (row: TContext[`schema`]) => any\n ): QueryBuilder<TContext> {\n return new BaseQueryBuilder({\n ...builder.query,\n fnHaving: [\n ...(builder.query.fnHaving || []),\n callback as (row: NamespacedRow) => any,\n ],\n })\n },\n }\n }\n\n _getQuery(): QueryIR {\n if (!this.query.from) {\n throw new QueryMustHaveFromClauseError()\n }\n return this.query as QueryIR\n }\n}\n\n// Helper to ensure we have a BasicExpression/Aggregate for a value\nfunction toExpr(value: any): BasicExpression | Aggregate {\n if (value === undefined) return toExpression(null)\n if (\n value instanceof AggregateExpr ||\n value instanceof FuncExpr ||\n value instanceof PropRef ||\n value instanceof ValueExpr\n ) {\n return value as BasicExpression | Aggregate\n }\n return toExpression(value)\n}\n\nfunction isPlainObject(value: any): value is Record<string, any> {\n return (\n value !== null &&\n typeof value === `object` &&\n !isExpressionLike(value) &&\n !value.__refProxy\n )\n}\n\nfunction buildNestedSelect(obj: any): any {\n if (!isPlainObject(obj)) return toExpr(obj)\n const out: Record<string, any> = {}\n for (const [k, v] of Object.entries(obj)) {\n if (typeof k === `string` && k.startsWith(`__SPREAD_SENTINEL__`)) {\n // Preserve sentinel key and its value (value is unimportant at compile time)\n out[k] = v\n continue\n }\n out[k] = buildNestedSelect(v)\n }\n return out\n}\n\n// Internal function to build a query from a callback\n// used by liveQueryCollectionOptions.query\nexport function buildQuery<TContext extends Context>(\n fn: (builder: InitialQueryBuilder) => QueryBuilder<TContext>\n): QueryIR {\n const result = fn(new BaseQueryBuilder())\n return getQueryIR(result)\n}\n\n// Internal function to get the QueryIR from a builder\nexport function getQueryIR(\n builder: BaseQueryBuilder | QueryBuilder<any> | InitialQueryBuilder\n): QueryIR {\n return (builder as unknown as BaseQueryBuilder)._getQuery()\n}\n\n// Type-only exports for the query builder\nexport type InitialQueryBuilder = Pick<BaseQueryBuilder<Context>, `from`>\n\nexport type InitialQueryBuilderConstructor = new () => InitialQueryBuilder\n\nexport type QueryBuilder<TContext extends Context> = Omit<\n BaseQueryBuilder<TContext>,\n `from` | `_getQuery`\n>\n\n// Main query builder class alias with the constructor type modified to hide all\n// but the from method on the initial instance\nexport const Query: InitialQueryBuilderConstructor = BaseQueryBuilder\n\n// Helper type to extract context from a QueryBuilder\nexport type ExtractContext<T> =\n T extends BaseQueryBuilder<infer TContext>\n ? TContext\n : T extends QueryBuilder<infer TContext>\n ? TContext\n : never\n\n// Export the types from types.ts for convenience\nexport type { Context, Source, GetResult, RefLeaf as Ref } from \"./types.js\"\n"],"names":["AggregateExpr","FuncExpr","ValueExpr"],"mappings":";;;;AA6CO,MAAM,iBAAqD;AAAA,EAGhE,YAAY,QAA0B,IAAI;AAF1C,SAAiB,QAA0B,CAAA;AAGzC,SAAK,QAAQ,EAAE,GAAG,MAAA;AAAA,EACpB;AAAA;AAAA;AAAA;AAAA;AAA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A,WAAO,KAAK;AAAA,EACd;AACF;AAGA,SAAS,OAAO,OAAyC;AACvD,MAAI,UAAU,OAAW,QAAO,aAAa,IAAI;AACjD,MACE,iBAAiBA,aACjB,iBAAiBC,QACjB,iBAAiB,WACjB,iBAAiBC,OACjB;AACA,WAAO;AAAA,EACT;AACA,SAAO,aAAa,KAAK;AAC3B;AAEA,SAAS,cAAc,OAA0C;AAC/D,SACE,UAAU,QACV,OAAO,UAAU,YACjB,CAAC,iBAAiB,KAAK,KACvB,CAAC,MAAM;AAEX;AAEA,SAAS,kBAAkB,KAAe;AACxC,MAAI,CAAC,cAAc,GAAG,EAAG,QAAO,OAAO,GAAG;AAC1C,QAAM,MAA2B,CAAA;AACjC,aAAW,CAAC,GAAG,CAAC,KAAK,OAAO,QAAQ,GAAG,GAAG;AACxC,QAAI,OAAO,MAAM,YAAY,EAAE,WAAW,qBAAqB,GAAG;AAEhE,UAAI,CAAC,IAAI;AACT;AAAA,IACF;AACA,QAAI,CAAC,IAAI,kBAAkB,CAAC;AAAA,EAC9B;AACA,SAAO;AACT;AAIO,SAAS,WACd,IACS;AACT,QAAM,SAAS,GAAG,IAAI,kBAAkB;AACxC,SAAO,WAAW,MAAM;AAC1B;AAGO,SAAS,WACd,SACS;AACT,SAAQ,QAAwC,UAAA;AAClD;AAcO,MAAM,QAAwC;"}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { BasicExpression } from '../ir.js';
|
|
2
|
+
import { RefLeaf } from './types.js';
|
|
2
3
|
export interface RefProxy<T = any> {
|
|
3
4
|
/** @internal */
|
|
4
5
|
readonly __refProxy: true;
|
|
@@ -12,7 +13,7 @@ export interface RefProxy<T = any> {
|
|
|
12
13
|
* Used in collection indexes and where clauses
|
|
13
14
|
*/
|
|
14
15
|
export type SingleRowRefProxy<T> = T extends Record<string, any> ? {
|
|
15
|
-
[K in keyof T]: T[K] extends Record<string, any> ? SingleRowRefProxy<T[K]> & RefProxy<T[K]> :
|
|
16
|
+
[K in keyof T]: T[K] extends Record<string, any> ? SingleRowRefProxy<T[K]> & RefProxy<T[K]> : RefLeaf<T[K]>;
|
|
16
17
|
} & RefProxy<T> : RefProxy<T>;
|
|
17
18
|
/**
|
|
18
19
|
* Creates a proxy object that records property access paths for a single row
|
|
@@ -37,7 +37,7 @@ function createSingleRowRefProxy() {
|
|
|
37
37
|
}
|
|
38
38
|
function createRefProxy(aliases) {
|
|
39
39
|
const cache = /* @__PURE__ */ new Map();
|
|
40
|
-
|
|
40
|
+
let accessId = 0;
|
|
41
41
|
function createProxy(path) {
|
|
42
42
|
const pathKey = path.join(`.`);
|
|
43
43
|
if (cache.has(pathKey)) {
|
|
@@ -58,9 +58,14 @@ function createRefProxy(aliases) {
|
|
|
58
58
|
return Reflect.has(target, prop);
|
|
59
59
|
},
|
|
60
60
|
ownKeys(target) {
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
61
|
+
const id = ++accessId;
|
|
62
|
+
const sentinelKey = `__SPREAD_SENTINEL__${path.join(`.`)}__${id}`;
|
|
63
|
+
if (!Object.prototype.hasOwnProperty.call(target, sentinelKey)) {
|
|
64
|
+
Object.defineProperty(target, sentinelKey, {
|
|
65
|
+
enumerable: true,
|
|
66
|
+
configurable: true,
|
|
67
|
+
value: true
|
|
68
|
+
});
|
|
64
69
|
}
|
|
65
70
|
return Reflect.ownKeys(target);
|
|
66
71
|
},
|
|
@@ -79,7 +84,6 @@ function createRefProxy(aliases) {
|
|
|
79
84
|
if (prop === `__refProxy`) return true;
|
|
80
85
|
if (prop === `__path`) return [];
|
|
81
86
|
if (prop === `__type`) return void 0;
|
|
82
|
-
if (prop === `__spreadSentinels`) return spreadSentinels;
|
|
83
87
|
if (typeof prop === `symbol`) return Reflect.get(target, prop, receiver);
|
|
84
88
|
const propStr = String(prop);
|
|
85
89
|
if (aliases.includes(propStr)) {
|
|
@@ -88,16 +92,16 @@ function createRefProxy(aliases) {
|
|
|
88
92
|
return void 0;
|
|
89
93
|
},
|
|
90
94
|
has(target, prop) {
|
|
91
|
-
if (prop === `__refProxy` || prop === `__path` || prop === `__type`
|
|
95
|
+
if (prop === `__refProxy` || prop === `__path` || prop === `__type`)
|
|
92
96
|
return true;
|
|
93
97
|
if (typeof prop === `string` && aliases.includes(prop)) return true;
|
|
94
98
|
return Reflect.has(target, prop);
|
|
95
99
|
},
|
|
96
100
|
ownKeys(_target) {
|
|
97
|
-
return [...aliases, `__refProxy`, `__path`, `__type
|
|
101
|
+
return [...aliases, `__refProxy`, `__path`, `__type`];
|
|
98
102
|
},
|
|
99
103
|
getOwnPropertyDescriptor(target, prop) {
|
|
100
|
-
if (prop === `__refProxy` || prop === `__path` || prop === `__type`
|
|
104
|
+
if (prop === `__refProxy` || prop === `__path` || prop === `__type`) {
|
|
101
105
|
return { enumerable: false, configurable: true };
|
|
102
106
|
}
|
|
103
107
|
if (typeof prop === `string` && aliases.includes(prop)) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ref-proxy.js","sources":["../../../../src/query/builder/ref-proxy.ts"],"sourcesContent":["import { PropRef, Value } from \"../ir.js\"\nimport type { BasicExpression } from \"../ir.js\"\n\nexport interface RefProxy<T = any> {\n /** @internal */\n readonly __refProxy: true\n /** @internal */\n readonly __path: Array<string>\n /** @internal */\n readonly __type: T\n}\n\n/**\n * Type for creating a RefProxy for a single row/type without namespacing\n * Used in collection indexes and where clauses\n */\nexport type SingleRowRefProxy<T> =\n T extends Record<string, any>\n ? {\n [K in keyof T]: T[K] extends Record<string, any>\n ? SingleRowRefProxy<T[K]> & RefProxy<T[K]>\n :
|
|
1
|
+
{"version":3,"file":"ref-proxy.js","sources":["../../../../src/query/builder/ref-proxy.ts"],"sourcesContent":["import { PropRef, Value } from \"../ir.js\"\nimport type { BasicExpression } from \"../ir.js\"\nimport type { RefLeaf } from \"./types.js\"\n\nexport interface RefProxy<T = any> {\n /** @internal */\n readonly __refProxy: true\n /** @internal */\n readonly __path: Array<string>\n /** @internal */\n readonly __type: T\n}\n\n/**\n * Type for creating a RefProxy for a single row/type without namespacing\n * Used in collection indexes and where clauses\n */\nexport type SingleRowRefProxy<T> =\n T extends Record<string, any>\n ? {\n [K in keyof T]: T[K] extends Record<string, any>\n ? SingleRowRefProxy<T[K]> & RefProxy<T[K]>\n : RefLeaf<T[K]>\n } & RefProxy<T>\n : RefProxy<T>\n\n/**\n * Creates a proxy object that records property access paths for a single row\n * Used in collection indexes and where clauses\n */\nexport function createSingleRowRefProxy<\n T extends Record<string, any>,\n>(): SingleRowRefProxy<T> {\n const cache = new Map<string, any>()\n\n function createProxy(path: Array<string>): any {\n const pathKey = path.join(`.`)\n if (cache.has(pathKey)) {\n return cache.get(pathKey)\n }\n\n const proxy = new Proxy({} as any, {\n get(target, prop, receiver) {\n if (prop === `__refProxy`) return true\n if (prop === `__path`) return path\n if (prop === `__type`) return undefined // Type is only for TypeScript inference\n if (typeof prop === `symbol`) return Reflect.get(target, prop, receiver)\n\n const newPath = [...path, String(prop)]\n return createProxy(newPath)\n },\n\n has(target, prop) {\n if (prop === `__refProxy` || prop === `__path` || prop === `__type`)\n return true\n return Reflect.has(target, prop)\n },\n\n ownKeys(target) {\n return Reflect.ownKeys(target)\n },\n\n getOwnPropertyDescriptor(target, prop) {\n if (prop === `__refProxy` || prop === `__path` || prop === `__type`) {\n return { enumerable: false, configurable: true }\n }\n return Reflect.getOwnPropertyDescriptor(target, prop)\n },\n })\n\n cache.set(pathKey, proxy)\n return proxy\n }\n\n // Return the root proxy that starts with an empty path\n return createProxy([]) as SingleRowRefProxy<T>\n}\n\n/**\n * Creates a proxy object that records property access paths\n * Used in callbacks like where, select, etc. to create type-safe references\n */\nexport function createRefProxy<T extends Record<string, any>>(\n aliases: Array<string>\n): RefProxy<T> & T {\n const cache = new Map<string, any>()\n let accessId = 0 // Monotonic counter to record evaluation order\n\n function createProxy(path: Array<string>): any {\n const pathKey = path.join(`.`)\n if (cache.has(pathKey)) {\n return cache.get(pathKey)\n }\n\n const proxy = new Proxy({} as any, {\n get(target, prop, receiver) {\n if (prop === `__refProxy`) return true\n if (prop === `__path`) return path\n if (prop === `__type`) return undefined // Type is only for TypeScript inference\n if (typeof prop === `symbol`) return Reflect.get(target, prop, receiver)\n\n const newPath = [...path, String(prop)]\n return createProxy(newPath)\n },\n\n has(target, prop) {\n if (prop === `__refProxy` || prop === `__path` || prop === `__type`)\n return true\n return Reflect.has(target, prop)\n },\n\n ownKeys(target) {\n const id = ++accessId\n const sentinelKey = `__SPREAD_SENTINEL__${path.join(`.`)}__${id}`\n if (!Object.prototype.hasOwnProperty.call(target, sentinelKey)) {\n Object.defineProperty(target, sentinelKey, {\n enumerable: true,\n configurable: true,\n value: true,\n })\n }\n return Reflect.ownKeys(target)\n },\n\n getOwnPropertyDescriptor(target, prop) {\n if (prop === `__refProxy` || prop === `__path` || prop === `__type`) {\n return { enumerable: false, configurable: true }\n }\n return Reflect.getOwnPropertyDescriptor(target, prop)\n },\n })\n\n cache.set(pathKey, proxy)\n return proxy\n }\n\n // Create the root proxy with all aliases as top-level properties\n const rootProxy = new Proxy({} as any, {\n get(target, prop, receiver) {\n if (prop === `__refProxy`) return true\n if (prop === `__path`) return []\n if (prop === `__type`) return undefined // Type is only for TypeScript inference\n if (typeof prop === `symbol`) return Reflect.get(target, prop, receiver)\n\n const propStr = String(prop)\n if (aliases.includes(propStr)) {\n return createProxy([propStr])\n }\n\n return undefined\n },\n\n has(target, prop) {\n if (prop === `__refProxy` || prop === `__path` || prop === `__type`)\n return true\n if (typeof prop === `string` && aliases.includes(prop)) return true\n return Reflect.has(target, prop)\n },\n\n ownKeys(_target) {\n return [...aliases, `__refProxy`, `__path`, `__type`]\n },\n\n getOwnPropertyDescriptor(target, prop) {\n if (prop === `__refProxy` || prop === `__path` || prop === `__type`) {\n return { enumerable: false, configurable: true }\n }\n if (typeof prop === `string` && aliases.includes(prop)) {\n return { enumerable: true, configurable: true }\n }\n return undefined\n },\n })\n\n return rootProxy\n}\n\n/**\n * Converts a value to an Expression\n * If it's a RefProxy, creates a Ref, otherwise creates a Value\n */\nexport function toExpression<T = any>(value: T): BasicExpression<T>\nexport function toExpression(value: RefProxy<any>): BasicExpression<any>\nexport function toExpression(value: any): BasicExpression<any> {\n if (isRefProxy(value)) {\n return new PropRef(value.__path)\n }\n // If it's already an Expression (Func, Ref, Value) or Agg, return it directly\n if (\n value &&\n typeof value === `object` &&\n `type` in value &&\n (value.type === `func` ||\n value.type === `ref` ||\n value.type === `val` ||\n value.type === `agg`)\n ) {\n return value\n }\n return new Value(value)\n}\n\n/**\n * Type guard to check if a value is a RefProxy\n */\nexport function isRefProxy(value: any): value is RefProxy {\n return value && typeof value === `object` && value.__refProxy === true\n}\n\n/**\n * Helper to create a Value expression from a literal\n */\nexport function val<T>(value: T): BasicExpression<T> {\n return new Value(value)\n}\n"],"names":[],"mappings":";AA8BO,SAAS,0BAEU;AACxB,QAAM,4BAAY,IAAA;AAElB,WAAS,YAAY,MAA0B;AAC7C,UAAM,UAAU,KAAK,KAAK,GAAG;AAC7B,QAAI,MAAM,IAAI,OAAO,GAAG;AACtB,aAAO,MAAM,IAAI,OAAO;AAAA,IAC1B;AAEA,UAAM,QAAQ,IAAI,MAAM,IAAW;AAAA,MACjC,IAAI,QAAQ,MAAM,UAAU;AAC1B,YAAI,SAAS,aAAc,QAAO;AAClC,YAAI,SAAS,SAAU,QAAO;AAC9B,YAAI,SAAS,SAAU,QAAO;AAC9B,YAAI,OAAO,SAAS,SAAU,QAAO,QAAQ,IAAI,QAAQ,MAAM,QAAQ;AAEvE,cAAM,UAAU,CAAC,GAAG,MAAM,OAAO,IAAI,CAAC;AACtC,eAAO,YAAY,OAAO;AAAA,MAC5B;AAAA,MAEA,IAAI,QAAQ,MAAM;AAChB,YAAI,SAAS,gBAAgB,SAAS,YAAY,SAAS;AACzD,iBAAO;AACT,eAAO,QAAQ,IAAI,QAAQ,IAAI;AAAA,MACjC;AAAA,MAEA,QAAQ,QAAQ;AACd,eAAO,QAAQ,QAAQ,MAAM;AA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