import { JsonLogicAll, JsonLogicAnd, JsonLogicDoubleNegation, JsonLogicEqual, JsonLogicGreaterThan, JsonLogicGreaterThanOrEqual, JsonLogicInArray, JsonLogicInString, JsonLogicLessThan, JsonLogicLessThanOrEqual, JsonLogicNegation, JsonLogicNone, JsonLogicNotEqual, JsonLogicOr, JsonLogicSome, JsonLogicStrictEqual, JsonLogicStrictNotEqual, JsonLogicVar, ReservedOperations as JsonLogicReservedOperations, RulesLogic, RulesLogic as JsonLogicRulesLogic } from "json-logic-js"; import { Column, Operators, SQL, Table } from "drizzle-orm"; import { WhereOptions } from "sequelize"; //#region ../../node_modules/type-fest/source/primitive.d.ts /** Matches any [primitive value](https://developer.mozilla.org/en-US/docs/Glossary/Primitive). @category Type */ type Primitive = null | undefined | string | number | boolean | symbol | bigint; //#endregion //#region ../../node_modules/type-fest/source/union-to-intersection.d.ts /** Convert a union type to an intersection type using [distributive conditional types](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-8.html#distributive-conditional-types). Inspired by [this Stack Overflow answer](https://stackoverflow.com/a/50375286/2172153). @example ``` import type {UnionToIntersection} from 'type-fest'; type Union = {the(): void} | {great(arg: string): void} | {escape: boolean}; type Intersection = UnionToIntersection; //=> {the(): void} & {great(arg: string): void} & {escape: boolean} ``` @category Type */ type UnionToIntersection = (// `extends unknown` is always going to be the case and is used to convert the // `Union` into a [distributive conditional // type](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-8.html#distributive-conditional-types). Union extends unknown // The union type is used as the only argument to a function since the union // of function arguments is an intersection. ? (distributedUnion: Union) => void // This won't happen. : never // Infer the `Intersection` type since TypeScript represents the positional // arguments of unions of functions as an intersection of the union. ) extends ((mergedIntersection: infer Intersection) => void) // The `& Union` is to ensure result of `UnionToIntersection` is always assignable to `A | B` ? Intersection & Union : never; //#endregion //#region ../../node_modules/type-fest/source/keys-of-union.d.ts /** Create a union of all keys from a given type, even those exclusive to specific union members. Unlike the native `keyof` keyword, which returns keys present in **all** union members, this type returns keys from **any** member. @link https://stackoverflow.com/a/49402091 @example ``` import type {KeysOfUnion} from 'type-fest'; type A = { common: string; a: number; }; type B = { common: string; b: string; }; type C = { common: string; c: boolean; }; type Union = A | B | C; type CommonKeys = keyof Union; //=> 'common' type AllKeys = KeysOfUnion; //=> 'common' | 'a' | 'b' | 'c' ``` @category Object */ type KeysOfUnion = // Hack to fix https://github.com/sindresorhus/type-fest/issues/1008 keyof UnionToIntersection : never>; //#endregion //#region ../../node_modules/type-fest/source/is-any.d.ts /** Returns a boolean for whether the given type is `any`. @link https://stackoverflow.com/a/49928360/1490091 Useful in type utilities, such as disallowing `any`s to be passed to a function. @example ``` import type {IsAny} from 'type-fest'; const typedObject = {a: 1, b: 2} as const; const anyObject: any = {a: 1, b: 2}; function get extends true ? {} : Record), K extends keyof O = keyof O>(object: O, key: K) { return object[key]; } const typedA = get(typedObject, 'a'); //=> 1 const anyA = get(anyObject, 'a'); //=> any ``` @category Type Guard @category Utilities */ type IsAny = 0 extends 1 & NoInfer ? true : false; //#endregion //#region ../../node_modules/type-fest/source/is-optional-key-of.d.ts /** Returns a boolean for whether the given key is an optional key of type. This is useful when writing utility types or schema validators that need to differentiate `optional` keys. @example ``` import type {IsOptionalKeyOf} from 'type-fest'; type User = { name: string; surname: string; luckyNumber?: number; }; type Admin = { name: string; surname?: string; }; type T1 = IsOptionalKeyOf; //=> true type T2 = IsOptionalKeyOf; //=> false type T3 = IsOptionalKeyOf; //=> boolean type T4 = IsOptionalKeyOf; //=> false type T5 = IsOptionalKeyOf; //=> boolean ``` @category Type Guard @category Utilities */ type IsOptionalKeyOf = IsAny extends true ? never : Key extends keyof Type ? Type extends Record ? false : true : false; //#endregion //#region ../../node_modules/type-fest/source/optional-keys-of.d.ts /** Extract all optional keys from the given type. This is useful when you want to create a new type that contains different type values for the optional keys only. @example ``` import type {OptionalKeysOf, Except} from 'type-fest'; type User = { name: string; surname: string; luckyNumber?: number; }; const REMOVE_FIELD = Symbol('remove field symbol'); type UpdateOperation = Except, OptionalKeysOf> & { [Key in OptionalKeysOf]?: Entity[Key] | typeof REMOVE_FIELD; }; const update1: UpdateOperation = { name: 'Alice', }; const update2: UpdateOperation = { name: 'Bob', luckyNumber: REMOVE_FIELD, }; ``` @category Utilities */ type OptionalKeysOf = Type extends unknown // For distributing `Type` ? (keyof { [Key in keyof Type as IsOptionalKeyOf extends false ? never : Key]: never }) & keyof Type // Intersect with `keyof Type` to ensure result of `OptionalKeysOf` is always assignable to `keyof Type` : never; //#endregion //#region ../../node_modules/type-fest/source/required-keys-of.d.ts /** Extract all required keys from the given type. This is useful when you want to create a new type that contains different type values for the required keys only or use the list of keys for validation purposes, etc... @example ``` import type {RequiredKeysOf} from 'type-fest'; declare function createValidation< Entity extends object, Key extends RequiredKeysOf = RequiredKeysOf, >(field: Key, validator: (value: Entity[Key]) => boolean): (entity: Entity) => boolean; type User = { name: string; surname: string; luckyNumber?: number; }; const validator1 = createValidation('name', value => value.length < 25); const validator2 = createValidation('surname', value => value.length < 25); // @ts-expect-error const validator3 = createValidation('luckyNumber', value => value > 0); // Error: Argument of type '"luckyNumber"' is not assignable to parameter of type '"name" | "surname"'. ``` @category Utilities */ type RequiredKeysOf = Type extends unknown // For distributing `Type` ? Exclude> : never; //#endregion //#region ../../node_modules/type-fest/source/is-never.d.ts /** Returns a boolean for whether the given type is `never`. @link https://github.com/microsoft/TypeScript/issues/31751#issuecomment-498526919 @link https://stackoverflow.com/a/53984913/10292952 @link https://www.zhenghao.io/posts/ts-never Useful in type utilities, such as checking if something does not occur. @example ``` import type {IsNever, And} from 'type-fest'; type A = IsNever; //=> true type B = IsNever; //=> false type C = IsNever; //=> false type D = IsNever; //=> false type E = IsNever; //=> false type F = IsNever; //=> false ``` @example ``` import type {IsNever} from 'type-fest'; type IsTrue = T extends true ? true : false; // When a distributive conditional is instantiated with `never`, the entire conditional results in `never`. type A = IsTrue; //=> never // If you don't want that behaviour, you can explicitly add an `IsNever` check before the distributive conditional. type IsTrueFixed = IsNever extends true ? false : T extends true ? true : false; type B = IsTrueFixed; //=> false ``` @category Type Guard @category Utilities */ type IsNever = [T] extends [never] ? true : false; //#endregion //#region ../../node_modules/type-fest/source/if.d.ts /** An if-else-like type that resolves depending on whether the given `boolean` type is `true` or `false`. Use-cases: - You can use this in combination with `Is*` types to create an if-else-like experience. For example, `If, 'is any', 'not any'>`. Note: - Returns a union of if branch and else branch if the given type is `boolean` or `any`. For example, `If` will return `'Y' | 'N'`. - Returns the else branch if the given type is `never`. For example, `If` will return `'N'`. @example ``` import type {If} from 'type-fest'; type A = If; //=> 'yes' type B = If; //=> 'no' type C = If; //=> 'yes' | 'no' type D = If; //=> 'yes' | 'no' type E = If; //=> 'no' ``` @example ``` import type {If, IsAny, IsNever} from 'type-fest'; type A = If, 'is any', 'not any'>; //=> 'not any' type B = If, 'is never', 'not never'>; //=> 'is never' ``` @example ``` import type {If, IsEqual} from 'type-fest'; type IfEqual = If, IfBranch, ElseBranch>; type A = IfEqual; //=> 'equal' type B = IfEqual; //=> 'not equal' ``` Note: Sometimes using the `If` type can make an implementation non–tail-recursive, which can impact performance. In such cases, it’s better to use a conditional directly. Refer to the following example: @example ``` import type {If, IsEqual, StringRepeat} from 'type-fest'; type HundredZeroes = StringRepeat<'0', 100>; // The following implementation is not tail recursive type Includes = S extends `${infer First}${infer Rest}` ? If, 'found', Includes> : 'not found'; // Hence, instantiations with long strings will fail // @ts-expect-error type Fails = Includes; // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Error: Type instantiation is excessively deep and possibly infinite. // However, if we use a simple conditional instead of `If`, the implementation becomes tail-recursive type IncludesWithoutIf = S extends `${infer First}${infer Rest}` ? IsEqual extends true ? 'found' : IncludesWithoutIf : 'not found'; // Now, instantiations with long strings will work type Works = IncludesWithoutIf; //=> 'not found' ``` @category Type Guard @category Utilities */ type If = IsNever extends true ? ElseBranch : Type extends true ? IfBranch : ElseBranch; //#endregion //#region ../../node_modules/type-fest/source/unknown-array.d.ts /** Represents an array with `unknown` value. Use case: You want a type that all arrays can be assigned to, but you don't care about the value. @example ``` import type {UnknownArray} from 'type-fest'; type IsArray = T extends UnknownArray ? true : false; type A = IsArray<['foo']>; //=> true type B = IsArray; //=> true type C = IsArray; //=> false ``` @category Type @category Array */ type UnknownArray = readonly unknown[]; //#endregion //#region ../../node_modules/type-fest/source/internal/type.d.ts /** Matches any primitive, `void`, `Date`, or `RegExp` value. */ type BuiltIns = Primitive | void | Date | RegExp; /** Test if the given function has multiple call signatures. Needed to handle the case of a single call signature with properties. Multiple call signatures cannot currently be supported due to a TypeScript limitation. @see https://github.com/microsoft/TypeScript/issues/29732 */ type HasMultipleCallSignatures unknown> = T extends { (...arguments_: infer A): unknown; (...arguments_: infer B): unknown; } ? B extends A ? A extends B ? false : true : true : false; /** An if-else-like type that resolves depending on whether the given type is `any` or `never`. @example ``` // When `T` is a NOT `any` or `never` (like `string`) => Returns `IfNotAnyOrNever` branch type A = IfNotAnyOrNever; //=> 'VALID' // When `T` is `any` => Returns `IfAny` branch type B = IfNotAnyOrNever; //=> 'IS_ANY' // When `T` is `never` => Returns `IfNever` branch type C = IfNotAnyOrNever; //=> 'IS_NEVER' ``` Note: Wrapping a tail-recursive type with `IfNotAnyOrNever` makes the implementation non-tail-recursive. To fix this, move the recursion into a helper type. Refer to the following example: @example ```ts import type {StringRepeat} from 'type-fest'; type NineHundredNinetyNineSpaces = StringRepeat<' ', 999>; // The following implementation is not tail recursive type TrimLeft = IfNotAnyOrNever : S>; // Hence, instantiations with long strings will fail // @ts-expect-error type T1 = TrimLeft; // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Error: Type instantiation is excessively deep and possibly infinite. // To fix this, move the recursion into a helper type type TrimLeftOptimised = IfNotAnyOrNever>; type _TrimLeftOptimised = S extends ` ${infer R}` ? _TrimLeftOptimised : S; type T2 = TrimLeftOptimised; //=> '' ``` */ type IfNotAnyOrNever = If, IfAny, If, IfNever, IfNotAnyOrNever>>; //#endregion //#region ../../node_modules/type-fest/source/internal/array.d.ts /** Returns whether the given array `T` is readonly. */ type IsArrayReadonly = If, false, T extends unknown[] ? false : true>; //#endregion //#region ../../node_modules/type-fest/source/simplify.d.ts /** Useful to flatten the type output to improve type hints shown in editors. And also to transform an interface into a type to aide with assignability. @example ``` import type {Simplify} from 'type-fest'; type PositionProps = { top: number; left: number; }; type SizeProps = { width: number; height: number; }; // In your editor, hovering over `Props` will show a flattened object with all the properties. type Props = Simplify; ``` Sometimes it is desired to pass a value as a function argument that has a different type. At first inspection it may seem assignable, and then you discover it is not because the `value`'s type definition was defined as an interface. In the following example, `fn` requires an argument of type `Record`. If the value is defined as a literal, then it is assignable. And if the `value` is defined as type using the `Simplify` utility the value is assignable. But if the `value` is defined as an interface, it is not assignable because the interface is not sealed and elsewhere a non-string property could be added to the interface. If the type definition must be an interface (perhaps it was defined in a third-party npm package), then the `value` can be defined as `const value: Simplify = ...`. Then `value` will be assignable to the `fn` argument. Or the `value` can be cast as `Simplify` if you can't re-declare the `value`. @example ``` import type {Simplify} from 'type-fest'; interface SomeInterface { foo: number; bar?: string; baz: number | undefined; } type SomeType = { foo: number; bar?: string; baz: number | undefined; }; const literal = {foo: 123, bar: 'hello', baz: 456}; const someType: SomeType = literal; const someInterface: SomeInterface = literal; declare function fn(object: Record): void; fn(literal); // Good: literal object type is sealed fn(someType); // Good: type is sealed // @ts-expect-error fn(someInterface); // Error: Index signature for type 'string' is missing in type 'someInterface'. Because `interface` can be re-opened fn(someInterface as Simplify); // Good: transform an `interface` into a `type` ``` @link https://github.com/microsoft/TypeScript/issues/15300 @see {@link SimplifyDeep} @category Object */ type Simplify = { [KeyType in keyof T]: T[KeyType] } & {}; //#endregion //#region ../../node_modules/type-fest/source/is-equal.d.ts /** Returns a boolean for whether the two given types are equal. @link https://github.com/microsoft/TypeScript/issues/27024#issuecomment-421529650 @link https://stackoverflow.com/questions/68961864/how-does-the-equals-work-in-typescript/68963796#68963796 Use-cases: - If you want to make a conditional branch based on the result of a comparison of two types. @example ``` import type {IsEqual} from 'type-fest'; // This type returns a boolean for whether the given array includes the given item. // `IsEqual` is used to compare the given array at position 0 and the given item and then return true if they are equal. type Includes = Value extends readonly [Value[0], ...infer rest] ? IsEqual extends true ? true : Includes : false; ``` @category Type Guard @category Utilities */ type IsEqual = [A] extends [B] ? [B] extends [A] ? _IsEqual : false : false; // This version fails the `equalWrappedTupleIntersectionToBeNeverAndNeverExpanded` test in `test-d/is-equal.ts`. type _IsEqual = (() => G extends A & G | G ? 1 : 2) extends (() => G extends B & G | G ? 1 : 2) ? true : false; //#endregion //#region ../../node_modules/type-fest/source/omit-index-signature.d.ts /** Omit any index signatures from the given object type, leaving only explicitly defined properties. This is the counterpart of `PickIndexSignature`. Use-cases: - Remove overly permissive signatures from third-party types. This type was taken from this [StackOverflow answer](https://stackoverflow.com/a/68261113/420747). It relies on the fact that an empty object (`{}`) is assignable to an object with just an index signature, like `Record`, but not to an object with explicitly defined keys, like `Record<'foo' | 'bar', unknown>`. (The actual value type, `unknown`, is irrelevant and could be any type. Only the key type matters.) ``` const indexed: Record = {}; // Allowed // @ts-expect-error const keyed: Record<'foo', unknown> = {}; // Error // TS2739: Type '{}' is missing the following properties from type 'Record<"foo" | "bar", unknown>': foo, bar ``` Instead of causing a type error like the above, you can also use a [conditional type](https://www.typescriptlang.org/docs/handbook/2/conditional-types.html) to test whether a type is assignable to another: ``` type Indexed = {} extends Record ? '✅ `{}` is assignable to `Record`' : '❌ `{}` is NOT assignable to `Record`'; type IndexedResult = Indexed; //=> '✅ `{}` is assignable to `Record`' type Keyed = {} extends Record<'foo' | 'bar', unknown> ? '✅ `{}` is assignable to `Record<\'foo\' | \'bar\', unknown>`' : '❌ `{}` is NOT assignable to `Record<\'foo\' | \'bar\', unknown>`'; type KeyedResult = Keyed; //=> '❌ `{}` is NOT assignable to `Record<\'foo\' | \'bar\', unknown>`' ``` Using a [mapped type](https://www.typescriptlang.org/docs/handbook/2/mapped-types.html#further-exploration), you can then check for each `KeyType` of `ObjectType`... ``` type OmitIndexSignature = { [KeyType in keyof ObjectType // Map each key of `ObjectType`... ]: ObjectType[KeyType]; // ...to its original value, i.e. `OmitIndexSignature == Foo`. }; ``` ...whether an empty object (`{}`) would be assignable to an object with that `KeyType` (`Record`)... ``` type OmitIndexSignature = { [KeyType in keyof ObjectType // Is `{}` assignable to `Record`? as {} extends Record ? never // ✅ `{}` is assignable to `Record` : KeyType // ❌ `{}` is NOT assignable to `Record` ]: ObjectType[KeyType]; }; ``` If `{}` is assignable, it means that `KeyType` is an index signature and we want to remove it. If it is not assignable, `KeyType` is a "real" key and we want to keep it. @example ``` import type {OmitIndexSignature} from 'type-fest'; type Example = { // These index signatures will be removed. [x: string]: any; [x: number]: any; [x: symbol]: any; [x: `head-${string}`]: string; [x: `${string}-tail`]: string; [x: `head-${string}-tail`]: string; [x: `${bigint}`]: string; [x: `embedded-${number}`]: string; // These explicitly defined keys will remain. foo: 'bar'; qux?: 'baz'; }; type ExampleWithoutIndexSignatures = OmitIndexSignature; //=> {foo: 'bar'; qux?: 'baz'} ``` @see {@link PickIndexSignature} @category Object */ type OmitIndexSignature = { [KeyType in keyof ObjectType as {} extends Record ? never : KeyType]: ObjectType[KeyType] }; //#endregion //#region ../../node_modules/type-fest/source/pick-index-signature.d.ts /** Pick only index signatures from the given object type, leaving out all explicitly defined properties. This is the counterpart of `OmitIndexSignature`. @example ``` import type {PickIndexSignature} from 'type-fest'; declare const symbolKey: unique symbol; type Example = { // These index signatures will remain. [x: string]: unknown; [x: number]: unknown; [x: symbol]: unknown; [x: `head-${string}`]: string; [x: `${string}-tail`]: string; [x: `head-${string}-tail`]: string; [x: `${bigint}`]: string; [x: `embedded-${number}`]: string; // These explicitly defined keys will be removed. ['kebab-case-key']: string; [symbolKey]: string; foo: 'bar'; qux?: 'baz'; }; type ExampleIndexSignature = PickIndexSignature; // { // [x: string]: unknown; // [x: number]: unknown; // [x: symbol]: unknown; // [x: `head-${string}`]: string; // [x: `${string}-tail`]: string; // [x: `head-${string}-tail`]: string; // [x: `${bigint}`]: string; // [x: `embedded-${number}`]: string; // } ``` @see {@link OmitIndexSignature} @category Object */ type PickIndexSignature = { [KeyType in keyof ObjectType as {} extends Record ? KeyType : never]: ObjectType[KeyType] }; //#endregion //#region ../../node_modules/type-fest/source/merge.d.ts // Merges two objects without worrying about index signatures. type SimpleMerge = Simplify<{ [Key in keyof Destination as Key extends keyof Source ? never : Key]: Destination[Key] } & Source>; /** Merge two types into a new type. Keys of the second type overrides keys of the first type. This is different from the TypeScript `&` (intersection) operator. With `&`, conflicting property types are intersected, which often results in `never`. For example, `{a: string} & {a: number}` makes `a` become `string & number`, which resolves to `never`. With `Merge`, the second type's keys cleanly override the first, so `Merge<{a: string}, {a: number}>` gives `{a: number}` as expected. `Merge` also produces a flattened type (via `Simplify`), making it more readable in IDE tooltips compared to `A & B`. @example ``` import type {Merge} from 'type-fest'; type Foo = { a: string; b: number; }; type Bar = { a: number; // Conflicts with Foo['a'] c: boolean; }; // With `&`, `a` becomes `string & number` which is `never`. Not what you want. type WithIntersection = (Foo & Bar)['a']; //=> never // With `Merge`, `a` is cleanly overridden to `number`. type WithMerge = Merge['a']; //=> number ``` @example ``` import type {Merge} from 'type-fest'; type Foo = { [x: string]: unknown; [x: number]: unknown; foo: string; bar: symbol; }; type Bar = { [x: number]: number; [x: symbol]: unknown; bar: Date; baz: boolean; }; export type FooBar = Merge; //=> { // [x: string]: unknown; // [x: number]: number; // [x: symbol]: unknown; // foo: string; // bar: Date; // baz: boolean; // } ``` Note: If you want a merge type that more accurately reflects the runtime behavior of object spread or `Object.assign`, refer to the {@link ObjectMerge} type. @see {@link ObjectMerge} @category Object */ type Merge = Destination extends unknown // For distributing `Destination` ? Source extends unknown // For distributing `Source` ? If, Destination, _Merge> : never // Should never happen : never; // Should never happen type _Merge = Simplify, PickIndexSignature> & SimpleMerge, OmitIndexSignature>>; //#endregion //#region ../../node_modules/type-fest/source/internal/object.d.ts /** Works similar to the built-in `Pick` utility type, except for the following differences: - Distributes over union types and allows picking keys from any member of the union type. - Primitives types are returned as-is. - Picks all keys if `Keys` is `any`. - Doesn't pick `number` from a `string` index signature. @example ``` type ImageUpload = { url: string; size: number; thumbnailUrl: string; }; type VideoUpload = { url: string; duration: number; encodingFormat: string; }; // Distributes over union types and allows picking keys from any member of the union type type MediaDisplay = HomomorphicPick; //=> {url: string; size: number} | {url: string; duration: number} // Primitive types are returned as-is type Primitive = HomomorphicPick; //=> string | number // Picks all keys if `Keys` is `any` type Any = HomomorphicPick<{a: 1; b: 2} | {c: 3}, any>; //=> {a: 1; b: 2} | {c: 3} // Doesn't pick `number` from a `string` index signature type IndexSignature = HomomorphicPick<{[k: string]: unknown}, number>; //=> {} */ type HomomorphicPick> = { [P in keyof T as Extract]: T[P] }; /** Merges user specified options with default options. @example ``` type PathsOptions = {maxRecursionDepth?: number; leavesOnly?: boolean}; type DefaultPathsOptions = {maxRecursionDepth: 10; leavesOnly: false}; type SpecifiedOptions = {leavesOnly: true}; type Result = ApplyDefaultOptions; //=> {maxRecursionDepth: 10; leavesOnly: true} ``` @example ``` // Complains if default values are not provided for optional options type PathsOptions = {maxRecursionDepth?: number; leavesOnly?: boolean}; type DefaultPathsOptions = {maxRecursionDepth: 10}; type SpecifiedOptions = {}; type Result = ApplyDefaultOptions; // ~~~~~~~~~~~~~~~~~~~ // Property 'leavesOnly' is missing in type 'DefaultPathsOptions' but required in type '{ maxRecursionDepth: number; leavesOnly: boolean; }'. ``` @example ``` // Complains if an option's default type does not conform to the expected type type PathsOptions = {maxRecursionDepth?: number; leavesOnly?: boolean}; type DefaultPathsOptions = {maxRecursionDepth: 10; leavesOnly: 'no'}; type SpecifiedOptions = {}; type Result = ApplyDefaultOptions; // ~~~~~~~~~~~~~~~~~~~ // Types of property 'leavesOnly' are incompatible. Type 'string' is not assignable to type 'boolean'. ``` @example ``` // Complains if an option's specified type does not conform to the expected type type PathsOptions = {maxRecursionDepth?: number; leavesOnly?: boolean}; type DefaultPathsOptions = {maxRecursionDepth: 10; leavesOnly: false}; type SpecifiedOptions = {leavesOnly: 'yes'}; type Result = ApplyDefaultOptions; // ~~~~~~~~~~~~~~~~ // Types of property 'leavesOnly' are incompatible. Type 'string' is not assignable to type 'boolean'. ``` */ type ApplyDefaultOptions, RequiredKeysOf> & Partial, never>>>, SpecifiedOptions extends Options> = If, Defaults, If, Defaults, Simplify ? undefined extends SpecifiedOptions[Key] ? never : Key : Key]: SpecifiedOptions[Key] }> & Required>>>; //#endregion //#region ../../node_modules/type-fest/source/except.d.ts /** Filter out keys from an object. Returns `never` if `Exclude` is strictly equal to `Key`. Returns `never` if `Key` extends `Exclude`. Returns `Key` otherwise. @example ``` type Filtered = Filter<'foo', 'foo'>; //=> never ``` @example ``` type Filtered = Filter<'bar', string>; //=> never ``` @example ``` type Filtered = Filter<'bar', 'foo'>; //=> 'bar' ``` @see {Except} */ type Filter = IsEqual extends true ? never : (KeyType extends ExcludeType ? never : KeyType); type ExceptOptions = { /** Disallow assigning non-specified properties. Note that any omitted properties in the resulting type will be present in autocomplete as `undefined`. @default false */ requireExactProps?: boolean; }; type DefaultExceptOptions = { requireExactProps: false; }; /** Create a type from an object type without certain keys. We recommend setting the `requireExactProps` option to `true`. This type is a stricter version of [`Omit`](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-5.html#the-omit-helper-type). The `Omit` type does not restrict the omitted keys to be keys present on the given type, while `Except` does. The benefits of a stricter type are avoiding typos and allowing the compiler to pick up on rename refactors automatically. This type was proposed to the TypeScript team, which declined it, saying they prefer that libraries implement stricter versions of the built-in types ([microsoft/TypeScript#30825](https://github.com/microsoft/TypeScript/issues/30825#issuecomment-523668235)). @example ``` import type {Except} from 'type-fest'; type Foo = { a: number; b: string; }; type FooWithoutA = Except; //=> {b: string} // @ts-expect-error const fooWithoutA: FooWithoutA = {a: 1, b: '2'}; // errors: 'a' does not exist in type '{ b: string; }' type FooWithoutB = Except; //=> {a: number} & Partial> // @ts-expect-error const fooWithoutB: FooWithoutB = {a: 1, b: '2'}; // errors at 'b': Type 'string' is not assignable to type 'undefined'. // The `Omit` utility type doesn't work when omitting specific keys from objects containing index signatures. // Consider the following example: type UserData = { [metadata: string]: string; email: string; name: string; role: 'admin' | 'user'; }; // `Omit` clearly doesn't behave as expected in this case: type PostPayload = Omit; //=> {[x: string]: string; [x: number]: string} // In situations like this, `Except` works better. // It simply removes the `email` key while preserving all the other keys. type PostPayloadFixed = Except; //=> {[x: string]: string; name: string; role: 'admin' | 'user'} ``` @category Object */ type Except = _Except>; type _Except> = { [KeyType in keyof ObjectType as Filter]: ObjectType[KeyType] } & (Options['requireExactProps'] extends true ? Partial> : {}); //#endregion //#region ../../node_modules/type-fest/source/require-at-least-one.d.ts /** Create a type that requires at least one of the given keys. The remaining keys are kept as is. @example ``` import type {RequireAtLeastOne} from 'type-fest'; type Responder = { text?: () => string; json?: () => string; secure?: boolean; }; const responder: RequireAtLeastOne = { json: () => '{"message": "ok"}', secure: true, }; ``` @category Object */ type RequireAtLeastOne$1 = IfNotAnyOrNever, never, _RequireAtLeastOne, keyof ObjectType, KeysType>>>>; type _RequireAtLeastOne = { // For each `Key` in `KeysType` make a mapped type: [Key in KeysType]-?: Required> & // 1. Make `Key`'s type required // 2. Make all other keys in `KeysType` optional Partial>> }[KeysType] & // 3. Add the remaining keys not in `KeysType` Except; //#endregion //#region ../../node_modules/type-fest/source/required-deep.d.ts /** Create a type from another type with all keys and nested keys set to required. Use-cases: - Creating optional configuration interfaces where the underlying implementation still requires all options to be fully specified. - Modeling the resulting type after a deep merge with a set of defaults. @example ``` import type {RequiredDeep} from 'type-fest'; type Settings = { textEditor?: { fontSize?: number; fontColor?: string; fontWeight?: number | undefined; }; autocomplete?: boolean; autosave?: boolean | undefined; }; type RequiredSettings = RequiredDeep; //=> { // textEditor: { // fontSize: number; // fontColor: string; // fontWeight: number | undefined; // }; // autocomplete: boolean; // autosave: boolean | undefined; // } ``` Note that types containing overloaded functions are not made deeply required due to a [TypeScript limitation](https://github.com/microsoft/TypeScript/issues/29732). @category Utilities @category Object @category Array @category Set @category Map */ type RequiredDeep = T extends BuiltIns ? T : T extends Map ? Map, RequiredDeep> : T extends Set ? Set> : T extends ReadonlyMap ? ReadonlyMap, RequiredDeep> : T extends ReadonlySet ? ReadonlySet> : T extends WeakMap ? WeakMap, RequiredDeep> : T extends WeakSet ? WeakSet> : T extends Promise ? Promise> : T extends ((...arguments_: any[]) => unknown) ? IsNever extends true ? T : HasMultipleCallSignatures extends true ? T : ((...arguments_: Parameters) => ReturnType) & RequiredObjectDeep : T extends object ? Simplify> // `Simplify` to prevent `RequiredObjectDeep` from appearing in the resulting type : unknown; type RequiredObjectDeep = { [KeyType in keyof ObjectType]-?: RequiredDeep }; //#endregion //#region ../../node_modules/type-fest/source/set-optional.d.ts /** Create a type that makes the given keys optional. The remaining keys are kept as is. The sister of the `SetRequired` type. Use-case: You want to define a single model where the only thing that changes is whether or not some of the keys are optional. @example ``` import type {SetOptional} from 'type-fest'; type Foo = { a: number; b?: string; c: boolean; }; type SomeOptional = SetOptional; //=> {a: number; b?: string; c?: boolean} ``` @category Object */ type SetOptional = (BaseType extends ((...arguments_: never) => any) ? (...arguments_: Parameters) => ReturnType : unknown) & _SetOptional; type _SetOptional = BaseType extends unknown // To distribute `BaseType` when it's a union type. ? Simplify< // Pick just the keys that are readonly from the base type. Except & // Pick the keys that should be mutable from the base type and make them mutable. Partial>> : never; //#endregion //#region ../../node_modules/type-fest/source/set-required.d.ts /** Create a type that makes the given keys required. The remaining keys are kept as is. The sister of the `SetOptional` type. Use-case: You want to define a single model where the only thing that changes is whether or not some of the keys are required. @example ``` import type {SetRequired} from 'type-fest'; type Foo = { a?: number; b: string; c?: boolean; }; type SomeRequired = SetRequired; //=> {a?: number; b: string; c: boolean} // Set specific indices in an array to be required. type ArrayExample = SetRequired<[number?, number?, number?], 0 | 1>; //=> [number, number, number?] ``` @category Object */ type SetRequired = (BaseType extends ((...arguments_: never) => any) ? (...arguments_: Parameters) => ReturnType : unknown) & _SetRequired; type _SetRequired = BaseType extends UnknownArray ? SetArrayRequired extends infer ResultantArray ? If, Readonly, ResultantArray> : never : Simplify< // Pick just the keys that are optional from the base type. Except & // Pick the keys that should be required from the base type and make them required. Required>>; /** Remove the optional modifier from the specified keys in an array. */ type SetArrayRequired = TArray extends unknown // For distributing `TArray` when it's a union ? keyof TArray & `${number}` extends never // Exit if `TArray` is empty (e.g., []), or // `TArray` contains no non-rest elements preceding the rest element (e.g., `[...string[]]` or `[...string[], string]`). ? [...Accumulator, ...TArray] : TArray extends readonly [(infer First)?, ...infer Rest] ? '0' extends OptionalKeysOf // If the first element of `TArray` is optional ? `${Counter['length']}` extends `${Keys & (string | number)}` // If the current index needs to be required ? SetArrayRequired // If the current element is optional, but it doesn't need to be required, // then we can exit early, since no further elements can now be made required. : [...Accumulator, ...TArray] : SetArrayRequired : never // Should never happen, since `[(infer F)?, ...infer R]` is a top-type for arrays. : never; // Should never happen //#endregion //#region src/types/options.d.ts type RequireAtLeastOne = { [Key in KeysType]-?: Required> & Partial>> }[KeysType] & Except; type StringUnionToFlexibleOptionArray = Array : never>; type StringUnionToFullOptionArray = Array : never>; /** * Extracts the {@link Option} type from a {@link FlexibleOptionList}. * * @group Option Lists */ type GetOptionType
    > = OL extends FlexibleOptionList ? Opt : never; /** * Extracts the type of the identifying property from a {@link Option}, * {@link ValueOption}, or {@link FullOption}. * * @group Option Lists */ type GetOptionIdentifierType = Opt extends Option | ValueOption ? NameType : string; /** * Adds an `unknown` index property to an interface. */ type WithUnknownIndex = T & { [key: string]: unknown; }; /** * Do not use this type directly; use {@link Option}, {@link ValueOption}, * or {@link FullOption} instead. For specific option types, you can use * {@link FullField}, {@link FullOperator}, or {@link FullCombinator}, * all of which extend {@link FullOption}. * * @group Option Lists */ interface BaseOption { name?: N; value?: N; label: string; disabled?: boolean; } /** * A generic option. Used directly in {@link OptionList} or * as the child element of an {@link OptionGroup}. * * @group Option Lists */ type Option = Simplify, "name">>>; /** * Like {@link Option} but requiring `value` instead of `name`. * * @group Option Lists */ type ValueOption = Simplify, "value">>>; /** * A generic {@link Option} with either a `name` or `value` as its primary identifier. * {@link OptionList}-type props on the {@link react-querybuilder!QueryBuilder QueryBuilder} component accept this type, * but corresponding props passed down to subcomponents will always be augmented * to {@link FullOption} first. * * @group Option Lists */ type FlexibleOption = Simplify, "name" | "value">>>; /** * Utility type to turn an {@link Option}, {@link ValueOption}, or {@link BaseOption} * into a {@link FlexibleOption}. * * @group Option Lists */ type ToFlexibleOption = WithUnknownIndex : Opt, "name" | "value">>; /** * A generic {@link Option} requiring both `name` _and_ `value` properties. * Props that extend {@link OptionList} accept {@link BaseOption}, but * corresponding props sent to subcomponents will always be augmented to this * type first to ensure both `name` and `value` are available. * * NOTE: Do not extend from this type directly. Use {@link BaseFullOption} * (optionally wrapped in {@link WithUnknownIndex}) instead, otherwise * the `unknown` index property will cause issues. See {@link Option} and * {@link ValueOption} for examples. * * @group Option Lists */ type FullOption = Simplify, "name" | "value">>>; /** * This type is identical to {@link FullOption} but without the `unknown` index * property. Extend from this type instead of {@link FullOption} directly. * * @group Option Lists */ type BaseFullOption = Simplify, "name" | "value">>; /** * Utility type to turn an {@link Option}, {@link ValueOption} or * {@link BaseOption} into a {@link FullOption}. * * @group Option Lists */ type ToFullOption = Opt extends BaseFullOption ? Opt : Opt extends BaseOption ? WithUnknownIndex> : never; /** * @deprecated Renamed to {@link Option}. * * @group Option Lists */ type NameLabelPair = Option; /** * A group of {@link Option}s, usually within an {@link OptionList}. * * @group Option Lists */ interface OptionGroup { label: string; options: WithUnknownIndex[]; } /** * A group of {@link BaseOption}s, usually within a {@link FlexibleOptionList}. * * @group Option Lists */ type FlexibleOptionGroup = { label: string; options: (Opt extends BaseFullOption ? Opt : ToFlexibleOption)[]; }; /** * Either an array of {@link Option}s or an array of {@link OptionGroup}s. * * @group Option Lists */ type OptionList = Opt[] | OptionGroup[]; /** * An array of options or option groups, like {@link OptionList} but the option type * may use either `name` or `value` as the primary identifier. * * @group Option Lists */ type FlexibleOptionList = ToFlexibleOption[] | FlexibleOptionGroup>[]; /** * An array of options or option groups, like {@link OptionList} but the option type * may use either `name` or `value` as the primary identifier. * * @group Option Lists */ type FlexibleOptionListProp = (ToFlexibleOption | GetOptionIdentifierType)[] | FlexibleOptionGroup | GetOptionIdentifierType>[]; /** * An array of options or option groups, like {@link OptionList}, but using * {@link FullOption} instead of {@link Option}. This means that every member is * guaranteed to have both `name` and `value`. * * @group Option Lists */ type FullOptionList = Opt extends BaseFullOption ? Opt[] | OptionGroup[] : ToFullOption[] | OptionGroup>[]; /** * Map of option identifiers to their respective {@link Option}. * * @group Option Lists */ type BaseOptionMap> = { [k in K]?: ToFlexibleOption }; /** * Map of option identifiers to their respective {@link FullOption}. * * @group Option Lists */ type FullOptionMap> = { [k in K]?: V }; /** * Map of option identifiers to their respective {@link FullOption}. * Must include all possible strings from the identifier type. * * @group Option Lists */ type FullOptionRecord> = Record; //#endregion //#region src/types/ruleGroups.d.ts /** * Properties common to both rules and groups. */ interface CommonRuleAndGroupProperties { path?: Path; id?: string; disabled?: boolean; /** * Whether this rule or group is muted. When muted, the rule or group * is excluded from query export formats (SQL, JSON, MongoDB, etc.). * For groups, muting recursively mutes all children. */ muted?: boolean; } /** * The main rule type. The `field`, `operator`, and `value` properties * can be narrowed with generics. */ interface RuleType extends CommonRuleAndGroupProperties { field: F; operator: O; value: V; valueSource?: ValueSource; match?: MatchConfig; /** * Only used when adding a rule to a query that uses independent combinators. */ combinatorPreceding?: C; } /** * The main rule group type. This type is used for query definitions as well as * all sub-groups of queries. */ interface RuleGroupType extends CommonRuleAndGroupProperties { combinator: C; rules: RuleGroupArray, R>; not?: boolean; } /** * The type of the `rules` array in a {@link RuleGroupType}. */ type RuleGroupArray = (R | RG)[]; /** * All updateable properties of rules and groups (everything except * `id`, `path`, and `rules`). */ type UpdateableProperties = Exclude | (string & {}); /** * The type of the `rules` array in a {@link DefaultRuleGroupType}. */ type DefaultRuleGroupArray = RuleGroupArray>; /** * {@link RuleGroupType} with the `combinator` property limited to * {@link DefaultCombinatorNameExtended} and `rules` limited to {@link DefaultRuleType}. */ type DefaultRuleGroupType = RuleGroupType, DefaultCombinatorNameExtended> & { rules: DefaultRuleGroupArray; }; /** * {@link RuleType} with the `operator` property limited to {@link DefaultOperatorName}. */ type DefaultRuleType = RuleType; /** * Default allowed values for the `combinator` property. * * @group Option Lists */ type DefaultCombinatorName = "and" | "or"; /** * Default allowed values for the `combinator` property, plus `"xor"`. * * @group Option Lists */ type DefaultCombinatorNameExtended = DefaultCombinatorName | "xor"; /** * Default values for the `operator` property. * * @group Option Lists */ type DefaultOperatorName = "=" | "!=" | "<" | ">" | "<=" | ">=" | "contains" | "beginsWith" | "endsWith" | "doesNotContain" | "doesNotBeginWith" | "doesNotEndWith" | "null" | "notNull" | "in" | "notIn" | "between" | "notBetween"; /** * A {@link FullCombinator} definition with a {@link DefaultCombinatorName} `name` property. * * @group Option Lists */ type DefaultCombinator = FullCombinator; /** * A {@link FullCombinator} definition with a {@link DefaultCombinatorNameExtended} `name` property. * * @group Option Lists */ type DefaultCombinatorExtended = FullCombinator; /** * An {@link FullOperator} definition with a {@link DefaultOperatorName} `name` property. * * @group Option Lists */ type DefaultOperator = FullOperator; //#endregion //#region src/types/ruleGroupsIC.utils.d.ts type MAXIMUM_ALLOWED_BOUNDARY = 80; type MappedTuple, Result extends Array = [], Count extends ReadonlyArray = []> = Count["length"] extends MAXIMUM_ALLOWED_BOUNDARY ? Result : Tuple extends [] ? [] : Result extends [] ? MappedTuple : MappedTuple; //#endregion //#region src/types/ruleGroupsIC.d.ts /** * The main rule group interface when using independent combinators. This type is used * for query definitions as well as all sub-groups of queries. */ interface RuleGroupTypeIC extends Except, "combinator" | "rules"> { combinator?: undefined; rules: RuleGroupICArray, R, C>; /** * Only used when adding a rule to a query that uses independent combinators */ combinatorPreceding?: C; } /** * Shorthand for "either {@link RuleGroupType} or {@link RuleGroupTypeIC}". */ type RuleGroupTypeAny = RuleGroupType | RuleGroupTypeIC; /** * The type of the `rules` array in a {@link RuleGroupTypeIC}. */ type RuleGroupICArray = [R | RG] | [R | RG, ...MappedTuple<[C, R | RG]>] | ((R | RG)[] & { length: 0; }); /** * Shorthand for "either {@link RuleGroupArray} or {@link RuleGroupICArray}". */ type RuleOrGroupArray = RuleGroupArray | RuleGroupICArray; /** * The type of the `rules` array in a {@link DefaultRuleGroupTypeIC}. */ type DefaultRuleGroupICArray = RuleGroupICArray, DefaultRuleType, DefaultCombinatorName>; /** * Shorthand for "either {@link DefaultRuleGroupArray} or {@link DefaultRuleGroupICArray}". */ type DefaultRuleOrGroupArray = DefaultRuleGroupArray | DefaultRuleGroupICArray; /** * {@link RuleGroupTypeIC} with combinators limited to * {@link DefaultCombinatorName} and rules limited to {@link DefaultRuleType}. */ interface DefaultRuleGroupTypeIC extends RuleGroupTypeIC> { rules: DefaultRuleGroupICArray; } /** * Shorthand for "either {@link DefaultRuleGroupType} or {@link DefaultRuleGroupTypeIC}". */ type DefaultRuleGroupTypeAny = DefaultRuleGroupType | DefaultRuleGroupTypeIC; /** * Determines if a type extending {@link RuleGroupTypeAny} is actually * {@link RuleGroupType} or {@link RuleGroupTypeIC}. */ type GetRuleGroupType = RG extends { combinator: string; } ? RuleGroupType : RuleGroupTypeIC; /** * Determines the {@link RuleType} of a given {@link RuleGroupType} * or {@link RuleGroupTypeIC}. If the field and operator name types of * the rule type extend the identifier types of the provided Field and * Operator types, the given rule type is returned as is. Otherwise, * the rule type has its field and operator types narrowed to the * identifier types of the provided Field and Operator types. */ type GetRuleTypeFromGroupWithFieldAndOperator = RG extends RuleGroupType | RuleGroupTypeIC ? RT extends RuleType ? RuleFieldName extends GetOptionIdentifierType ? RuleOperatorName extends GetOptionIdentifierType ? RuleType : RuleType, RuleValueName, RuleCombinatorName> : RuleOperatorName extends GetOptionIdentifierType ? RuleType, RuleOperatorName, RuleValueName, RuleCombinatorName> : RuleType, GetOptionIdentifierType, RuleValueName, RuleCombinatorName> : never : never; /** * Converts a narrowed rule group type to its most generic form. */ type GenericizeRuleGroupType = RG extends RuleGroupType ? RuleGroupType : RuleGroupTypeIC; /** * Converts a {@link RuleGroupType} extension to the corresponding * {@link RuleGroupTypeIC} type, preserving any additional properties. * If the type already extends {@link RuleGroupTypeIC}, it is returned as-is. */ type ToRuleGroupTypeIC = T extends RuleGroupTypeIC ? T : T extends DefaultRuleGroupType ? DefaultRuleGroupTypeIC : T extends RuleGroupType ? RuleGroupTypeIC & Omit> : T; /** * Converts a {@link RuleGroupTypeIC} extension to the corresponding * {@link RuleGroupType} type, preserving any additional properties. * If the type already extends {@link RuleGroupType} (non-IC), it is returned as-is. */ type ToRuleGroupType = T extends { combinator: string; } ? T : T extends DefaultRuleGroupTypeIC ? DefaultRuleGroupType : T extends RuleGroupTypeIC ? RuleGroupType & Omit> : T; //#endregion //#region src/types/validation.d.ts /** * Object with a `valid` boolean value and optional `reasons`. */ interface ValidationResult { valid: boolean; reasons?: any[]; } /** * Map of rule/group `id` to its respective {@link ValidationResult}. */ type ValidationMap = Record; /** * Function that validates a query. */ type QueryValidator = (query: RuleGroupTypeAny) => boolean | ValidationMap; /** * Function that validates a rule. */ type RuleValidator = (rule: RuleType) => boolean | ValidationResult; //#endregion //#region src/types/basic.d.ts /** * @see https://react-querybuilder.js.org/docs/tips/path */ type Path = number[]; /** * String of classnames, array of classname strings, or object where the * keys are classnames and those with truthy values will be included. * Suitable for passing to the `clsx` package. */ type Classname = string | string[] | Record; /** * A source for the `value` property of a rule. */ type ValueSource = "value" | "field"; /** * Type of {@link react-querybuilder!ValueEditor ValueEditor} that will be displayed. */ type ValueEditorType = "text" | "select" | "checkbox" | "radio" | "textarea" | "switch" | "multiselect" | null; /** * A valid array of potential value sources. * * @see {@link ValueSource} */ type ValueSources = ["value"] | ["value", "field"] | ["field", "value"] | ["field"]; type ValueSourceFlexibleOptions = ToFlexibleOptionArrays; type ValueSourceFullOptions = ToOptionArrays; type ToOptionArrays = Sources extends unknown ? { [K in keyof Sources]: { name: Sources[K]; value: Sources[K]; label: string; } } : never; type ToFlexibleOptionArrays = Sources extends unknown ? { [K in keyof Sources]: FlexibleOption } : never; type WithOptionalClassName = T & { className?: Classname; }; /** * HTML5 input types */ type InputType = "button" | "checkbox" | "color" | "date" | "datetime-local" | "email" | "file" | "hidden" | "image" | "month" | "number" | "password" | "radio" | "range" | "reset" | "search" | "submit" | "tel" | "text" | "time" | "url" | "week" | "bigint" | (string & {}); /** * Quantification mode describing how many elements of the value array must pass * the filter for the rule itself to pass. * * For "atLeast", "atMost", and "exactly", the threshold value will be converted to * a percentage if the number is less than 1. Non-numeric values and numbers less * than 0 will be ignored. */ interface MatchConfig { mode: MatchMode; threshold?: number | null | undefined; } type MatchMode = "all" | "some" | "none" | "atLeast" | "atMost" | "exactly"; type MatchModeOptions = StringUnionToFullOptionArray; type ActionElementEventHandler = (event?: any, context?: any) => void; type ValueChangeEventHandler = (value?: any, context?: any) => void; /** * Base for all Field types/interfaces. */ interface BaseFullField, ValueObj extends FullOption = FullOption> extends WithOptionalClassName> { id?: string; operators?: FlexibleOptionList | OperatorName[] | FlexibleOption[] | (OperatorName | FlexibleOption)[]; valueEditorType?: ValueEditorType | ((operator: OperatorName) => ValueEditorType); valueSources?: ValueSources | ValueSourceFlexibleOptions | ((operator: OperatorName) => ValueSources | ValueSourceFlexibleOptions); inputType?: InputType | null; values?: FlexibleOptionList; matchModes?: boolean | MatchMode[] | FlexibleOption[]; /** Properties of items in the value. */ subproperties?: FlexibleOptionList; defaultOperator?: OperatorName; defaultValue?: any; placeholder?: string; validator?: RuleValidator; comparator?: string | ((f: FullField, operator: string) => boolean); } /** * Full field definition used in the `fields` prop of {@link react-querybuilder!QueryBuilder QueryBuilder}. * This type requires both `name` and `value`, but the `fields` prop itself * can use a {@link FlexibleOption} where only one of `name` or `value` is * required (along with `label`), or {@link Field} where only `name` and * `label` are required. * * The `name`/`value`, `operators`, and `values` properties of this interface * can be narrowed with generics. * * @group Option Lists */ type FullField, ValueObj extends FullOption = FullOption> = Simplify & BaseFullField>; /** * Field definition used in the `fields` prop of {@link react-querybuilder!QueryBuilder QueryBuilder}. * This type is an extension of {@link FullField} where only `name` and * `label` are required. * * The `name`/`value`, `operators`, and `values` properties of this interface * can be narrowed with generics. * * @group Option Lists */ type Field> = WithUnknownIndex<{ value?: FieldName; } & Pick, Exclude>>; /** * Field definition used in the `fields` prop of {@link react-querybuilder!QueryBuilder QueryBuilder}. * This type is an extension of {@link FullField} where only `value` and * `label` are required. * * The `name`/`value`, `operators`, and `values` properties of this interface * can be narrowed with generics. * * @group Option Lists */ type FieldByValue> = WithUnknownIndex<{ name?: FieldName; } & Pick, Exclude>>; /** * Utility type to make one or more properties required. */ type WithRequired = T & { [P in K]-?: T[P] }; /** * Utility type to make all properties non-nullable. */ type RemoveNullability> = { [k in keyof T]: NonNullable }; /** * Allowed values of the {@link FullOperator} property `arity`. A value of `"unary"` or * a number less than two will cause the default {@link react-querybuilder!ValueEditor ValueEditor} to render `null`. */ type Arity = number | "unary" | "binary" | "ternary"; /** * Full operator definition used in the `operators`/`getOperators` props of * {@link react-querybuilder!QueryBuilder QueryBuilder}. This type requires both `name` and `value`, but the * `operators`/`getOperators` props themselves can use a {@link FlexibleOption} * where only one of `name` or `value` is required, or {@link FullOperator} where * only `name` is required. * * The `name`/`value` properties of this interface can be narrowed with generics. * * @group Option Lists */ interface FullOperator extends WithOptionalClassName> { arity?: Arity; } /** * Operator definition used in the `operators`/`getOperators` props of * {@link react-querybuilder!QueryBuilder QueryBuilder}. This type is an extension of {@link FullOperator} * where only `name` and `label` are required. * * The `name`/`value` properties of this interface can be narrowed with generics. * * @group Option Lists */ type Operator = WithUnknownIndex, "value"> & WithOptionalClassName<{ arity?: Arity; }>>; /** * Operator definition used in the `operators`/`getOperators` props of * {@link react-querybuilder!QueryBuilder QueryBuilder}. This type is an extension of {@link FullOperator} * where only `value` and `label` are required. * * The `name`/`value` properties of this interface can be narrowed with generics. * * @group Option Lists */ type OperatorByValue = WithUnknownIndex, "name"> & WithOptionalClassName<{ arity?: Arity; }>>; /** * Full combinator definition used in the `combinators` prop of {@link react-querybuilder!QueryBuilder QueryBuilder}. * This type requires both `name` and `value`, but the `combinators` prop itself * can use a {@link FlexibleOption} where only one of `name` or `value` is required, * or {@link Combinator} where only `name` is required. * * The `name`/`value` properties of this interface can be narrowed with generics. * * @group Option Lists */ type FullCombinator = WithOptionalClassName>; /** * Combinator definition used in the `combinators` prop of {@link react-querybuilder!QueryBuilder QueryBuilder}. * This type is an extension of {@link FullCombinator} where only `name` and * `label` are required. * * The `name`/`value` properties of this interface can be narrowed with generics. * * @group Option Lists */ type Combinator = WithUnknownIndex, "value">>>; /** * Combinator definition used in the `combinators` prop of {@link react-querybuilder!QueryBuilder QueryBuilder}. * This type is an extension of {@link FullCombinator} where only `value` and * `label` are required. * * The `name`/`value` properties of this interface can be narrowed with generics. * * @group Option Lists */ type CombinatorByValue = WithUnknownIndex, "name">>>; type ParseNumberMethodName = "enhanced" | "native" | "strict"; /** * Parsing algorithms used by {@link parseNumber}. */ type ParseNumberMethod = boolean | ParseNumberMethodName; type ParseNumbersModerationLevel = "-limited" | ""; /** * Options for the `parseNumbers` prop of {@link react-querybuilder!QueryBuilder QueryBuilder}. */ type ParseNumbersPropConfig = boolean | `${ParseNumberMethodName}${ParseNumbersModerationLevel}`; /** * Signature of `accessibleDescriptionGenerator` prop, used by {@link react-querybuilder!QueryBuilder QueryBuilder} to generate * accessible descriptions for each {@link react-querybuilder!RuleGroup RuleGroup}. */ type AccessibleDescriptionGenerator = (props: { path: Path; qbId: string; }) => string; //#endregion //#region src/types/dnd.d.ts type DndDropTargetType = "rule" | "ruleGroup" | "inlineCombinator"; type DraggedItem = (RuleType & { path: Path; qbId: string; }) | (RuleGroupTypeAny & { path: Path; qbId: string; }); type DropEffect = "move" | "copy"; interface DropResult { path: Path; type: DndDropTargetType; dropEffect?: DropEffect; groupItems?: boolean; qbId: string; getQuery: () => RuleGroupTypeAny; dispatchQuery: (query: RuleGroupTypeAny) => void; } interface DragCollection { isDragging: boolean; dragMonitorId: string | symbol; } interface DropCollection { dropNotAllowed: boolean; isOver: boolean; dropMonitorId: string | symbol; dropEffect?: DropEffect; groupItems?: boolean; } //#endregion //#region src/types/export.d.ts /** * Available export formats for {@link formatQuery}. * * @group Export */ type ExportFormat = "json" | "sql" | "json_without_ids" | "parameterized" | "parameterized_named" | "mongodb" | "mongodb_query" | "cel" | "jsonlogic" | "spel" | "elasticsearch" | "jsonata" | "natural_language" | "ldap" | "drizzle" | "prisma" | "sequelize" | "diagnostics"; /** * Export formats for {@link formatQuery} that produce objects instead of strings. * * @group Export */ type ExportObjectFormats = "parameterized" | "parameterized_named" | "jsonlogic" | "elasticsearch" | "jsonata" | "mongodb_query" | "diagnostics"; /** * Available presets for the "sql" export format. * * @group Export */ type SQLPreset = "ansi" | "sqlite" | "postgresql" | "mysql" | "mssql" | "oracle"; /** * A map of operators to strings to be used in the output of {@link formatQuery}. If the * result can differ based on the `valueSource`, the key should map to an array where the * second element represents the string to be used when `valueSource` is "field". The first * element will be used in all other cases. * * @group Export */ type ExportOperatorMap = Partial | DefaultOperatorName, string | [string, string]>>; /** * Options object shape for {@link formatQuery}. * * @group Export */ interface FormatQueryOptions { /** * The {@link ExportFormat}. */ format?: ExportFormat; /** * This function will be used to process the `operator` from each rule * for query language formats. If not defined, the appropriate * `defaultOperatorProcessor*` for the format will be used. */ operatorProcessor?: RuleProcessor; /** * This function will be used to process the `value` from each rule * for query language formats. If not defined, the appropriate * `defaultValueProcessor*` for the format will be used. */ valueProcessor?: ValueProcessorLegacy | ValueProcessorByRule; /** * This function will be used to process each rule. If not defined, the appropriate * `defaultRuleProcessor*` for the given format will be used. */ ruleProcessor?: RuleProcessor; /** * This function will be used to process each rule group. If not defined, the appropriate * `defaultRuleGroupProcessor*` for the format will be used. * * If this function is defined, it will override the `format` option. This also allows * `formatQuery` to produce completely custom output formats. */ ruleGroupProcessor?: RuleGroupProcessor; /** * In the "sql", "parameterized", "parameterized_named", and "jsonata" export * formats, field names will be bracketed by this string. If an array of strings * is passed, field names will be preceded by the first element and * succeeded by the second element. * * Tip: Use `fieldIdentifierSeparator` to bracket identifiers individually within field names. * * @default '' // the empty string * * @example * formatQuery(query, { format: 'sql', quoteFieldNamesWith: '"' }) * // `"First name" = 'Steve'` * * @example * formatQuery(query, { format: 'sql', quoteFieldNamesWith: ['[', ']'] }) * // "[First name] = 'Steve'" */ quoteFieldNamesWith?: string | [string, string]; /** * When used in conjunction with the `quoteFieldNamesWith` option, field names will * be split by this string, each part being individually processed as per the rules * of the `quoteFieldNamesWith` configuration. The parts will then be re-joined * by the same string. * * A common value for this option is `'.'`. * * A value of `''` (the empty string) will disable splitting/rejoining. * * @default '' * * @example * formatQuery(query, { * format: 'sql', * quoteFieldNamesWith: ['[', ']'], * fieldIdentifierSeparator: '.', * }) * // "[dbo].[Musicians].[First name] = 'Steve'" */ fieldIdentifierSeparator?: string; /** * Character to use for quoting string values in the SQL format. * @default `'` */ quoteValuesWith?: string; /** * Validator function for the entire query. Can be the same function passed * as `validator` prop to {@link react-querybuilder!QueryBuilder QueryBuilder}. */ validator?: QueryValidator; /** * This can be the same {@link FullField} array passed to {@link react-querybuilder!QueryBuilder QueryBuilder}, but * really all you need to provide is the `name` and `validator` for each field. * * The full field object from this array, where the field's identifying property * matches the rule's `field`, will be passed to the rule processor. */ fields?: FlexibleOptionList; /** * This can be the same `getOperators` function passed to {@link react-querybuilder!QueryBuilder QueryBuilder}. * * The full operator object from this array, where the operator's identifying property * matches the rule's `operator`, will be passed to the rule processor. */ getOperators?(field: string, misc: { fieldData: FullField; }): FlexibleOptionList | null; /** * This string will be inserted in place of invalid groups for non-JSON formats. * Defaults to `'(1 = 1)'` for "sql"/"parameterized"/"parameterized_named" and * `'$and:[{$expr:true}]'` for "mongodb". */ fallbackExpression?: string; /** * This string will be placed in front of named parameters (aka bind variables) * when using the "parameterized_named" export format. * * @default ":" */ paramPrefix?: string; /** * Maintains the parameter prefix in the `params` object keys when using the * "parameterized_named" export format. Recommended when using SQLite. * * @default false * * @example * console.log(formatQuery(query, { * format: "parameterized_named", * paramPrefix: "$", * paramsKeepPrefix: true * }).params) * // { $firstName: "Stev" } * // Default (`paramsKeepPrefix` is `false`): * // { firstName: "Stev" } */ paramsKeepPrefix?: boolean; /** * Renders parameter placeholders as a series of sequential numbers * instead of '?' like the default. This option will respect the * `paramPrefix` option like the 'parameterized_named' format. * * @default false */ numberedParams?: boolean; /** * Preserves the order of values for "between" and "notBetween" rules, even if a larger * value comes before a smaller value (which will always evaluate to false). */ preserveValueOrder?: boolean; /** * Renders values as either `number`-types or unquoted strings, as * appropriate and when possible. Each `string`-type value is evaluated * against {@link numericRegex} to determine if it can be represented as a * plain numeric value. If so, `parseFloat` is used to convert it to a number. */ parseNumbers?: ParseNumbersPropConfig; /** * Any rules where the field is equal to this value will be ignored. * * @default '~' */ placeholderFieldName?: string; /** * Any rules where the operator is equal to this value will be ignored. * * @default '~' */ placeholderOperatorName?: string; /** * Any rules where the value is equal to this value will be ignored. * * @default '~' */ placeholderValueName?: string; /** * Operator to use when concatenating wildcard characters and field names in "sql" format. * The ANSI standard is `||`, while SQL Server uses `+`. MySQL does not implement a concatenation * operator by default, and therefore requires use of the `CONCAT` function. * * If `concatOperator` is set to `"CONCAT"` (case-insensitive), the `CONCAT` function will be * used. Note that Oracle SQL does not support more than two values in the `CONCAT` function, * so this option should not be used in that context. The default setting (`"||"`) is already * compatible with Oracle SQL. * * @default '||' */ concatOperator?: "||" | "+" | "CONCAT" | (string & {}); /** * Option presets to maximize compatibility with various SQL dialects. */ preset?: SQLPreset; /** * Map of operators to their translations for the "natural_language" format. If the * result can differ based on the `valueSource`, the key should map to an array where the * second element represents the string to be used when `valueSource` is "field". The first * element will be used in all other cases. */ operatorMap?: ExportOperatorMap; /** * [Constituent word order](https://en.wikipedia.org/wiki/Word_order#Constituent_word_orders) * for the "natural_language" format. Can be abbreviated like "SVO" or spelled out like * "subject-verb-object". * * - Subject = field * - Verb = operator * - Object = value */ wordOrder?: ConstituentWordOrderString | Lowercase | ({} & string); /** * Translatable strings used by the "natural_language" format. */ translations?: Partial>; context?: Record; } /** * Options object for {@link ValueProcessorByRule} functions. * * @group Export */ interface ValueProcessorOptions extends FormatQueryOptions { valueProcessor?: ValueProcessorByRule; escapeQuotes?: boolean; /** * The full field object, if `fields` was provided in the * {@link formatQuery} options parameter. */ fieldData?: FullField; /** * Included for the "parameterized_named" format only. Keys of this object represent * field names and values represent the current list of parameter names for that * field based on the query rules processed up to that point. Use this list to * ensure that parameter names generated by the custom rule processor are unique. */ fieldParamNames?: Record; /** * Included for the "parameterized_named" format only. Call this function with a * field name to get a unique parameter name, as yet unused during query processing. */ getNextNamedParam?: (field: string) => string; /** * Additional prefix and suffix characters to wrap the value in. Useful for augmenting * the default value processor results with special syntax (e.g., for dates or function * calls). */ wrapValueWith?: [string, string]; /** * Parse numbers in the rule value. * * @default false */ parseNumbers?: boolean; } /** * Options object curated by {@link formatQuery} and passed to a {@link RuleGroupProcessor}. * * @group Export */ interface FormatQueryFinalOptions extends Required> { fields: FullOptionList; getParseNumberBoolean: (inputType?: InputType | null) => boolean | undefined; parseNumbers?: ParseNumbersPropConfig | undefined; placeholderValueName?: string | undefined; valueProcessor: ValueProcessorByRule; validator?: QueryValidator; validateRule: FormatQueryValidateRule; validationMap: ValidationMap; context?: Record; } /** * Function that produces a processed value for a given {@link RuleType}. * * @group Export */ type ValueProcessorByRule = (rule: RuleType, options?: ValueProcessorOptions) => string; /** * Function that produces a processed value for a given `field`, `operator`, `value`, * and `valueSource`. * * @group Export */ type ValueProcessorLegacy = (field: string, operator: string, value: any, valueSource?: ValueSource) => string; /** * @group Export */ type ValueProcessor = ValueProcessorLegacy; /** * Function to produce a result that {@link formatQuery} uses when processing a * {@link RuleType} object. * * See the default rule processor for each format to know what type to return. * | Format | Default rule processor | * | ------------------------ | ----------------------------------------- | * | `sql` | {@link defaultRuleProcessorSQL} | * | `parameterized` | {@link defaultRuleProcessorParameterized} | * | `parameterized_named` | {@link defaultRuleProcessorParameterized} | * | `mongodb` _(deprecated)_ | {@link defaultRuleProcessorMongoDB} | * | `mongodb_query` | {@link defaultRuleProcessorMongoDBQuery} | * | `cel` | {@link defaultRuleProcessorCEL} | * | `spel` | {@link defaultRuleProcessorSpEL} | * | `jsonlogic` | {@link defaultRuleProcessorJsonLogic} | * | `elasticsearch` | {@link defaultRuleProcessorElasticSearch} | * | `jsonata` | {@link defaultRuleProcessorJSONata} | * * @group Export */ type RuleProcessor = (rule: RuleType, options?: ValueProcessorOptions, meta?: { processedParams?: Record | any[]; context?: Record; }) => any; /** * Function to produce a result that {@link formatQuery} uses when processing a * {@link RuleGroupType} or {@link RuleGroupTypeIC} object. * * See the default rule group processor for each format to know what type to return. * | Format | Default rule group processor | * | ------------------------ | ---------------------------------------------- | * | `sql` | {@link defaultRuleGroupProcessorSQL} | * | `parameterized` | {@link defaultRuleGroupProcessorParameterized} | * | `parameterized_named` | {@link defaultRuleGroupProcessorParameterized} | * | `mongodb` _(deprecated)_ | {@link defaultRuleGroupProcessorMongoDB} | * | `mongodb_query` | {@link defaultRuleGroupProcessorMongoDBQuery} | * | `cel` | {@link defaultRuleGroupProcessorCEL} | * | `spel` | {@link defaultRuleGroupProcessorSpEL} | * | `jsonlogic` | {@link defaultRuleGroupProcessorJsonLogic} | * | `elasticsearch` | {@link defaultRuleGroupProcessorElasticSearch} | * | `jsonata` | {@link defaultRuleGroupProcessorJSONata} | * * @group Export */ type RuleGroupProcessor = (ruleGroup: RuleGroupTypeAny, options: FormatQueryFinalOptions, meta?: { processedParams?: Record | any[]; context?: Record; }) => TResult; /** * Rule validator for {@link formatQuery}. * * @group Export */ type FormatQueryValidateRule = (rule: RuleType) => readonly [boolean | ValidationResult | undefined, RuleValidator | undefined]; /** * Object produced by {@link formatQuery} for the `"parameterized"` format. * * @group Export */ interface ParameterizedSQL { /** The SQL `WHERE` clause fragment with `?` placeholders for each value. */ sql: string; /** * Parameter values in the same order their respective placeholders * appear in the `sql` string. */ params: any[]; } /** * Object produced by {@link formatQuery} for the `"parameterized_named"` format. * * @group Export */ interface ParameterizedNamedSQL { /** The SQL `WHERE` clause fragment with bind variable placeholders for each value. */ sql: string; /** * Map of bind variable names from the `sql` string to the associated values. */ params: Record; } /** * A {@link RuleType} annotated with diagnostics results, as produced * by {@link formatQuery} for the `"diagnostics"` format. * * The generics mirror those of {@link RuleType}. * * @group Export */ type RuleDiagnosticsResult = RuleType & { /** Whether the rule passed all validation checks. */valid: boolean; /** * Reasons why the rule is invalid. Only present when * the rule is invalid and specific reasons were provided * by the validator. */ reasons?: any[]; /** The path to this rule within the query tree. */ path: number[]; /** The nesting depth of this rule (`path.length`). */ level: number; }; /** * The type of the `rules` array in a {@link RuleGroupDiagnosticsResult}. * * @group Export */ type RuleGroupDiagnosticsArray = RuleGroupArray; /** * A {@link RuleGroupType} annotated with diagnostics results, as produced * by {@link formatQuery} for the `"diagnostics"` format. * * The generics mirror those of {@link RuleGroupType}. * * @group Export */ interface RuleGroupDiagnosticsResult extends Omit, "rules"> { /** Whether the group and all of its descendants are valid. */ valid: boolean; /** * Reasons why the group itself is invalid. Only present when * the group is invalid and specific reasons were provided * by the validator. */ reasons?: any[]; /** The path to this group within the query tree. */ path: number[]; /** The nesting depth of this group (`path.length`). */ level: number; rules: RuleGroupDiagnosticsArray, R>; } /** * The type of the `rules` array in a {@link RuleGroupICDiagnosticsResult}. * * Mirrors {@link RuleGroupICArray} but with diagnostics-annotated node types. * * @group Export */ type RuleGroupICDiagnosticsArray = RuleGroupICArray; /** * A {@link RuleGroupTypeIC} annotated with diagnostics results, as produced * by {@link formatQuery} for the `"diagnostics"` format (independent combinators). * * The generics mirror those of {@link RuleGroupTypeIC}. * * @group Export */ interface RuleGroupICDiagnosticsResult extends Omit, "rules"> { /** Whether the group and all of its descendants are valid. */ valid: boolean; /** * Reasons why the group itself is invalid. Only present when * the group is invalid and specific reasons were provided * by the validator. */ reasons?: any[]; /** The path to this group within the query tree. */ path: number[]; /** The nesting depth of this group (`path.length`). */ level: number; rules: RuleGroupICDiagnosticsArray, R, C>; } /** * A single diagnostic entry produced by the `"diagnostics"` format. * * @group Export */ interface DiagnosticEntry { /** The `id` of the rule or group this diagnostic pertains to. */ id: string; /** The path to the rule or group within the query tree. */ path: number[]; /** A machine-readable code identifying the type of diagnostic. */ code: string; /** A human-readable description of the diagnostic. */ message: string; /** * Which check produced this diagnostic. * * - `"placeholder"` — a placeholder field, operator, or value * - `"muted"` — a muted rule or group * - `"query-validator"` — the query-level validator * - `"field-validator"` — a field-level validator * - `"type-check"` — value/type mismatch based on field `inputType` * - `"field-check"` — field existence check against the `fields` config */ source: "placeholder" | "muted" | "query-validator" | "field-validator" | "type-check" | "field-check"; } /** * Aggregate statistics for the `"diagnostics"` format. * * @group Export */ interface DiagnosticsStats { totalRules: number; totalGroups: number; validRules: number; invalidRules: number; validGroups: number; invalidGroups: number; } /** * Per-field summary entry for the `"diagnostics"` format. * * @group Export */ interface DiagnosticsFieldSummaryEntry { /** Number of rules referencing this field. */ ruleCount: number; /** Number of invalid rules referencing this field. */ invalidCount: number; } /** * Top-level result of {@link formatQuery} for the `"diagnostics"` format. * * @group Export */ interface DiagnosticsResult { /** The annotated query tree with `valid`, `path`, and `level` on every node. */ query: RuleGroupDiagnosticsResult | RuleGroupICDiagnosticsResult; /** A flat array of all diagnostic entries across the tree. */ diagnostics: DiagnosticEntry[]; /** Aggregate statistics about the query. */ stats: DiagnosticsStats; /** Per-field summary of rule counts and invalid counts. */ fieldSummary: Record; } /** * @group Export */ interface RQBJsonLogicStartsWith { startsWith: [RQBJsonLogic, RQBJsonLogic, ...RQBJsonLogic[]]; } /** * @group Export */ interface RQBJsonLogicEndsWith { endsWith: [RQBJsonLogic, RQBJsonLogic, ...RQBJsonLogic[]]; } /** * @group Export */ interface RQBJsonLogicVar { var: string; } /** * JsonLogic rule object with additional operators generated by {@link formatQuery} * and accepted by {@link parseJsonLogic!parseJsonLogic}. * * @group Export */ type RQBJsonLogic = RulesLogic; /** * Constituent word order (as array) for the "natural_language" format. * * - S (subject) = field * - V (verb) = operator * - O (object) = value * * @group Export */ type ConstituentWordOrder = ["S", "V", "O"] | ["S", "O", "V"] | ["O", "S", "V"] | ["O", "V", "S"] | ["V", "S", "O"] | ["V", "O", "S"]; /** * Constituent word order (as string) for the "natural_language" format. * * - S (subject) = field * - V (verb) = operator * - O (object) = value * * @group Export */ type ConstituentWordOrderString = "SVO" | "SOV" | "OSV" | "OVS" | "VSO" | "VOS"; type RepeatStrings = Depth["length"] extends 2 ? "" : "" | `_${S[number]}${RepeatStrings}`; type ZeroOrMoreGroupVariants = RepeatStrings<["xor", "not"]>; /** * Rule group condition identifier for the "natural_language" format. * * @group Export */ type GroupVariantCondition = "not" | "xor"; /** * Keys for the `translations` config object used by the "natural_language" format. * * @group Export */ type NLTranslationKey = "and" | "or" | "true" | "false" | `groupPrefix${ZeroOrMoreGroupVariants}` | `groupSuffix${ZeroOrMoreGroupVariants}`; /** * `translations` config object for "natural_language" format. * * @group Export */ type NLTranslations = Partial>; //#endregion //#region src/types/queryBuilder.d.ts /** * Base interface for all rule subcomponents. * * @group Props */ interface CommonRuleSubComponentProps { rule: RuleType; } /** * Classnames applied to each component. * * @group Props */ interface Classnames { /** * Classnames applied to the root `
    ` element. */ queryBuilder: Classname; /** * Classnames applied to the `
    ` containing the RuleGroup. */ ruleGroup: Classname; /** * Classnames applied to the `
    ` containing the RuleGroup header controls. */ header: Classname; /** * Classnames applied to the `
    ` containing the RuleGroup child rules/groups. */ body: Classname; /** * Classnames applied to the `` control for fields. */ fields: Classname; /** * Classnames applied to the `` for match thresholds. */ matchThreshold: Classname; /** * Classnames applied to the `` for the rule value. */ value: Classname; /** * Classnames applied to the `