@cleverbrush/schema 4.4.3 → 5.0.0
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/LICENSE +28 -0
- package/README.md +176 -19
- package/dist/builders/AnySchemaBuilder.d.ts +11 -2
- package/dist/builders/AnySchemaBuilder.js +1 -1
- package/dist/builders/ArraySchemaBuilder.d.ts +15 -4
- package/dist/builders/ArraySchemaBuilder.js +1 -1
- package/dist/builders/BooleanSchemaBuilder.d.ts +21 -6
- package/dist/builders/BooleanSchemaBuilder.js +1 -1
- package/dist/builders/DateSchemaBuilder.d.ts +24 -10
- package/dist/builders/DateSchemaBuilder.js +1 -1
- package/dist/builders/ExternSchemaBuilder.d.ts +3 -2
- package/dist/builders/ExternSchemaBuilder.js +1 -1
- package/dist/builders/FunctionSchemaBuilder.d.ts +14 -2
- package/dist/builders/FunctionSchemaBuilder.js +1 -1
- package/dist/builders/GenericSchemaBuilder.d.ts +14 -3
- package/dist/builders/IntersectionSchemaBuilder.d.ts +1 -0
- package/dist/builders/LazySchemaBuilder.d.ts +1 -0
- package/dist/builders/NullSchemaBuilder.d.ts +2 -4
- package/dist/builders/NumberSchemaBuilder.d.ts +21 -7
- package/dist/builders/NumberSchemaBuilder.js +1 -1
- package/dist/builders/ObjectSchemaBuilder.d.ts +15 -4
- package/dist/builders/ObjectSchemaBuilder.js +1 -1
- package/dist/builders/ParseStringSchemaBuilder.d.ts +1 -0
- package/dist/builders/ParseStringSchemaBuilder.js +1 -1
- package/dist/builders/PromiseSchemaBuilder.d.ts +13 -2
- package/dist/builders/PromiseSchemaBuilder.js +1 -1
- package/dist/builders/RecordSchemaBuilder.d.ts +12 -0
- package/dist/builders/RecordSchemaBuilder.js +1 -1
- package/dist/builders/SchemaBuilder.d.ts +59 -10
- package/dist/builders/StringSchemaBuilder.d.ts +23 -8
- package/dist/builders/StringSchemaBuilder.js +1 -1
- package/dist/builders/TupleSchemaBuilder.d.ts +16 -4
- package/dist/builders/TupleSchemaBuilder.js +1 -1
- package/dist/builders/UnionSchemaBuilder.d.ts +12 -2
- package/dist/builders/UnionSchemaBuilder.js +1 -1
- package/dist/chunk-25KL2NBJ.js +2 -0
- package/dist/chunk-25KL2NBJ.js.map +1 -0
- package/dist/chunk-2BKBVVZ3.js +2 -0
- package/dist/chunk-2BKBVVZ3.js.map +1 -0
- package/dist/chunk-3E5M6GRR.js +2 -0
- package/dist/chunk-3E5M6GRR.js.map +1 -0
- package/dist/chunk-66U6MMJ2.js +2 -0
- package/dist/chunk-66U6MMJ2.js.map +1 -0
- package/dist/chunk-BMA2X7LI.js +2 -0
- package/dist/chunk-BMA2X7LI.js.map +1 -0
- package/dist/chunk-BTR3ZGES.js +2 -0
- package/dist/chunk-BTR3ZGES.js.map +1 -0
- package/dist/chunk-CR2QIV5I.js +2 -0
- package/dist/chunk-CR2QIV5I.js.map +1 -0
- package/dist/chunk-D7RXO2FA.js +2 -0
- package/dist/chunk-D7RXO2FA.js.map +1 -0
- package/dist/chunk-JEBLDVKG.js +2 -0
- package/dist/chunk-JEBLDVKG.js.map +1 -0
- package/dist/chunk-JH7VLA6C.js +2 -0
- package/dist/chunk-JH7VLA6C.js.map +1 -0
- package/dist/chunk-K7TDPKGQ.js +2 -0
- package/dist/chunk-K7TDPKGQ.js.map +1 -0
- package/dist/chunk-NDESVCWI.js +2 -0
- package/dist/chunk-NDESVCWI.js.map +1 -0
- package/dist/chunk-VBPZRO7L.js +2 -0
- package/dist/chunk-VBPZRO7L.js.map +1 -0
- package/dist/chunk-W5D22D4P.js +2 -0
- package/dist/chunk-W5D22D4P.js.map +1 -0
- package/dist/{chunk-XHSBY2QK.js → chunk-X6CT6I2V.js} +2 -2
- package/dist/{chunk-XHSBY2QK.js.map → chunk-X6CT6I2V.js.map} +1 -1
- package/dist/chunk-XASMTNON.js +2 -0
- package/dist/chunk-XASMTNON.js.map +1 -0
- package/dist/chunk-ZYWDTLNL.js +2 -0
- package/dist/chunk-ZYWDTLNL.js.map +1 -0
- package/dist/core.d.ts +3 -3
- package/dist/core.js +1 -1
- package/dist/extension.d.ts +4 -1
- package/dist/extension.js +1 -1
- package/dist/extensions/string.d.ts +2 -4
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/metadata-extension.d.ts +196 -0
- package/package.json +6 -3
- package/dist/chunk-54RHS4F4.js +0 -2
- package/dist/chunk-54RHS4F4.js.map +0 -1
- package/dist/chunk-6LSN7NXQ.js +0 -2
- package/dist/chunk-6LSN7NXQ.js.map +0 -1
- package/dist/chunk-C6YQOKWB.js +0 -2
- package/dist/chunk-C6YQOKWB.js.map +0 -1
- package/dist/chunk-ELPPAHNO.js +0 -2
- package/dist/chunk-ELPPAHNO.js.map +0 -1
- package/dist/chunk-G424M7GI.js +0 -2
- package/dist/chunk-G424M7GI.js.map +0 -1
- package/dist/chunk-JUFZ7PLO.js +0 -2
- package/dist/chunk-JUFZ7PLO.js.map +0 -1
- package/dist/chunk-K4ZLXLE2.js +0 -2
- package/dist/chunk-K4ZLXLE2.js.map +0 -1
- package/dist/chunk-KC45JEFL.js +0 -2
- package/dist/chunk-KC45JEFL.js.map +0 -1
- package/dist/chunk-NF4CRFMN.js +0 -2
- package/dist/chunk-NF4CRFMN.js.map +0 -1
- package/dist/chunk-ORV2G6ZL.js +0 -2
- package/dist/chunk-ORV2G6ZL.js.map +0 -1
- package/dist/chunk-PQINUGZW.js +0 -2
- package/dist/chunk-PQINUGZW.js.map +0 -1
- package/dist/chunk-REYZ7G7J.js +0 -2
- package/dist/chunk-REYZ7G7J.js.map +0 -1
- package/dist/chunk-VSU5GILY.js +0 -2
- package/dist/chunk-VSU5GILY.js.map +0 -1
- package/dist/chunk-XL723XFL.js +0 -2
- package/dist/chunk-XL723XFL.js.map +0 -1
- package/dist/chunk-XPLTW5DI.js +0 -2
- package/dist/chunk-XPLTW5DI.js.map +0 -1
- package/dist/chunk-YAOZEA2R.js +0 -2
- package/dist/chunk-YAOZEA2R.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/builders/TupleSchemaBuilder.ts"],"sourcesContent":["import type {\n ObjectSchemaBuilder,\n ObjectSchemaValidationResult\n} from './ObjectSchemaBuilder.js';\nimport {\n type BRAND,\n createHybridErrorArray,\n type InferType,\n type NestedValidationResult,\n type PropertyDescriptor,\n SchemaBuilder,\n SYMBOL_SCHEMA_PROPERTY_DESCRIPTOR,\n type ValidationContext,\n type ValidationErrorMessageProvider,\n type ValidationResult\n} from './SchemaBuilder.js';\nimport type {\n UnionSchemaBuilder,\n UnionSchemaValidationResult\n} from './UnionSchemaBuilder.js';\n\n/**\n * Maps a tuple of schema builders to a tuple of their per-position\n * validation result types.\n * Union schema elements get `UnionSchemaValidationResult`,\n * object schema elements get `ObjectSchemaValidationResult`,\n * other types get `ValidationResult`.\n */\nexport type TupleElementValidationResults<\n TElements extends readonly SchemaBuilder<any, any, any, any, any>[]\n> = {\n [K in keyof TElements]: TElements[K] extends UnionSchemaBuilder<\n infer UOptions extends readonly SchemaBuilder<\n any,\n any,\n any,\n any,\n any\n >[],\n any,\n any\n >\n ? UnionSchemaValidationResult<InferType<TElements[K]>, UOptions>\n : TElements[K] extends ObjectSchemaBuilder<any, any, any, any, any>\n ? ObjectSchemaValidationResult<InferType<TElements[K]>, TElements[K]>\n : ValidationResult<InferType<TElements[K]>>;\n};\n\n/**\n * Validation result type returned by `TupleSchemaBuilder.validate()`.\n * Extends `ValidationResult` with `getNestedErrors` for root-level tuple\n * errors and per-position validation results.\n */\nexport type TupleSchemaValidationResult<\n TResult,\n TElements extends readonly SchemaBuilder<any, any, any, any, any>[]\n> = ValidationResult<TResult> & {\n /**\n * Returns root-level tuple validation errors combined with\n * per-position validation results.\n * The returned value has both `NestedValidationResult` properties\n * (`errors`, `isValid`, `descriptor`, `seenValue`) and indexed\n * position results (`[0]`, `[1]`, etc.).\n */\n getNestedErrors(): TupleElementValidationResults<TElements> &\n NestedValidationResult<any, any, any>;\n};\n\ntype TupleSchemaBuilderCreateProps<\n TElements extends readonly SchemaBuilder<any, any, any, any, any>[],\n TRestSchema extends\n | SchemaBuilder<any, any, any, any, any>\n | undefined = undefined,\n R extends boolean = true,\n N extends boolean = false\n> = Partial<\n ReturnType<\n TupleSchemaBuilder<\n TElements,\n R,\n N,\n undefined,\n false,\n {},\n TRestSchema\n >['introspect']\n >\n>;\n\n/**\n * Fixed-length array schema builder with per-position type validation.\n * Similar to TypeScript's tuple types — each element at a specific array index\n * is validated against its own schema.\n *\n * Use it when you need to validate function arguments, CSV rows, coordinate\n * pairs, structured event payloads, or any other fixed-structure array.\n *\n * **NOTE** this class is exported for type annotations and advanced use.\n * Customize via extensions rather than subclassing. Avoid instantiating it\n * directly. Use {@link tuple | tuple()} function instead.\n *\n * @example\n * ```ts\n * const schema = tuple([string(), number(), boolean()]);\n * // Inferred TypeScript type: [string, number, boolean]\n *\n * schema.validate(['hello', 42, true]);\n * // result.valid === true\n * // result.object === ['hello', 42, true]\n *\n * schema.validate(['hello', 42]);\n * // result.valid === false (too few elements)\n *\n * schema.validate(['hello', 'oops', true]);\n * // result.valid === false (wrong type at position 1)\n * ```\n *\n * @example\n * ```ts\n * // Tuple with variadic rest elements\n * const schema = tuple([string(), number()]).rest(boolean());\n * // Inferred TypeScript type: [string, number, ...boolean[]]\n *\n * schema.validate(['hello', 42, true, false]);\n * // result.valid === true — any number of extra booleans allowed\n * ```\n *\n * @example\n * ```ts\n * // Nested tuple combining with object schemas\n * const point = tuple([number(), number()]);\n * const segment = tuple([point, point]);\n *\n * segment.validate([[0, 0], [10, 20]]);\n * // result.valid === true\n * ```\n *\n * @see {@link tuple}\n */\nexport class TupleSchemaBuilder<\n TElements extends readonly SchemaBuilder<any, any, any, any, any>[],\n TRequired extends boolean = true,\n TNullable extends boolean = false,\n TExplicitType = undefined,\n THasDefault extends boolean = false,\n TExtensions = {},\n TRestSchema extends\n | SchemaBuilder<any, any, any, any, any>\n | undefined = undefined,\n TResult = TExplicitType extends undefined\n ? TRestSchema extends SchemaBuilder<any, any, any, any, any>\n ? [\n ...{ [K in keyof TElements]: InferType<TElements[K]> },\n ...Array<InferType<TRestSchema>>\n ]\n : { [K in keyof TElements]: InferType<TElements[K]> }\n : TExplicitType\n> extends SchemaBuilder<\n TResult,\n TRequired,\n TNullable,\n THasDefault,\n TExtensions\n> {\n /** Native type parameters for extension rebinding; never emitted at runtime. @internal */\n declare readonly __cleverbrush_builder_type__: readonly [\n 'tuple',\n TElements,\n TRequired,\n TNullable,\n TExplicitType,\n THasDefault,\n TRestSchema,\n TResult\n ];\n\n #elements!: TElements;\n #restSchema:\n | (TRestSchema & SchemaBuilder<any, any, any, any, any>)\n | undefined;\n\n /**\n * @hidden\n */\n public static create(\n props: TupleSchemaBuilderCreateProps<any, any, any, any>\n ) {\n return new TupleSchemaBuilder({\n type: 'tuple',\n ...props\n } as any);\n }\n\n protected constructor(\n props: TupleSchemaBuilderCreateProps<\n TElements,\n TRestSchema,\n TRequired,\n TNullable\n >\n ) {\n super(props as any);\n\n if (Array.isArray(props.elements)) {\n this.#elements = props.elements as TElements;\n } else {\n this.#elements = [] as unknown as TElements;\n }\n\n if (props.restSchema instanceof SchemaBuilder) {\n this.#restSchema = props.restSchema as any;\n }\n }\n\n /**\n * @inheritdoc\n */\n public hasType<T>(\n _notUsed?: T\n ): TupleSchemaBuilder<\n TElements,\n true,\n TNullable,\n T,\n THasDefault,\n TExtensions,\n TRestSchema\n > &\n TExtensions {\n return this.derive(\n {\n ...this.introspect()\n } as any,\n true\n ) as any;\n }\n\n /**\n * @inheritdoc\n */\n public clearHasType(): TupleSchemaBuilder<\n TElements,\n TRequired,\n TNullable,\n undefined,\n THasDefault,\n TExtensions,\n TRestSchema\n > &\n TExtensions {\n return this.derive(\n {\n ...this.introspect()\n } as any,\n true\n ) as any;\n }\n\n #getLengthError(arr: any[]): string | null {\n if (arr.length < this.#elements.length) {\n const n = this.#elements.length;\n return `expected a tuple with at least ${n} element${n === 1 ? '' : 's'}, got ${arr.length}`;\n }\n if (\n !(this.#restSchema instanceof SchemaBuilder) &&\n arr.length !== this.#elements.length\n ) {\n const n = this.#elements.length;\n return `expected a tuple of exactly ${n} element${n === 1 ? '' : 's'}, got ${arr.length}`;\n }\n return null;\n }\n\n #createValidationSetup(\n object: TResult,\n superResult: ReturnType<TupleSchemaBuilder<any, any>['preValidateSync']>\n ) {\n const {\n valid,\n context: prevalidationContext,\n errors,\n transaction: preValidationTransaction\n } = superResult;\n\n const selfDescriptor: PropertyDescriptor<any, any, any> = {\n [SYMBOL_SCHEMA_PROPERTY_DESCRIPTOR]: {\n setValue: () => false,\n getValue: (obj: any) => ({\n success: true,\n value: obj\n }),\n getSchema: () => this,\n parent: undefined,\n propertyName: undefined,\n toJsonPointer: () => ''\n }\n };\n\n const rootErrors: string[] = [];\n const elementResults = createHybridErrorArray(\n [] as any[],\n () => object,\n () => rootErrors,\n () => selfDescriptor[SYMBOL_SCHEMA_PROPERTY_DESCRIPTOR]\n );\n const getNestedErrors = (() => elementResults) as any;\n\n if (!valid) {\n rootErrors.push(\n ...(errors || []).map((e: any) => e.message || String(e))\n );\n return {\n needsElementValidation: false as const,\n result: {\n valid,\n errors,\n getNestedErrors\n } as TupleSchemaValidationResult<TResult, TElements>\n };\n }\n\n const {\n object: { validatedObject: objToValidate }\n } = preValidationTransaction!;\n\n if (\n (typeof objToValidate === 'undefined' && !this.isRequired) ||\n (objToValidate === null && (!this.isRequired || this.isNullable))\n ) {\n return {\n needsElementValidation: false as const,\n result: {\n valid: true,\n object: objToValidate,\n getNestedErrors\n } as TupleSchemaValidationResult<TResult, TElements>\n };\n }\n\n if (!Array.isArray(objToValidate)) {\n rootErrors.push('array expected');\n return {\n needsElementValidation: false as const,\n result: {\n valid: false,\n errors: [{ message: 'array expected' }],\n getNestedErrors\n } as TupleSchemaValidationResult<TResult, TElements>\n };\n }\n\n return {\n needsElementValidation: true as const,\n objToValidate,\n prevalidationContext,\n getNestedErrors,\n elementResults,\n rootErrors\n };\n }\n\n #assembleDoNotStopResults(\n results: any[],\n elementResults: any,\n getNestedErrors: any\n ) {\n let allValid = true;\n\n for (let i = 0; i < results.length; i++) {\n if (!results[i]?.valid) {\n allValid = false;\n }\n elementResults[i] = results[i] as any;\n }\n\n return Object.assign(\n {\n valid: allValid,\n getNestedErrors\n },\n allValid\n ? {}\n : {\n errors: results\n .map(r => r?.errors)\n .filter(r => r)\n .flatMap(e =>\n e?.map((r: any) => ({\n ...r\n }))\n ) as any\n },\n allValid\n ? {\n object: results.map(r => r?.object)\n }\n : {}\n ) as any;\n }\n\n /**\n * {@inheritDoc SchemaBuilder.validate}\n */\n public validate(\n object: TResult,\n context?: ValidationContext\n ): TupleSchemaValidationResult<TResult, TElements> {\n return super.validate(object, context) as TupleSchemaValidationResult<\n TResult,\n TElements\n >;\n }\n\n /**\n * {@inheritDoc SchemaBuilder.validateAsync}\n */\n public async validateAsync(\n object: TResult,\n context?: ValidationContext\n ): Promise<TupleSchemaValidationResult<TResult, TElements>> {\n return super.validateAsync(object, context) as Promise<\n TupleSchemaValidationResult<TResult, TElements>\n >;\n }\n\n /**\n * Performs synchronous validation of the schema over `object`.\n * Throws if any preprocessor, validator, or error message provider returns a Promise.\n * @param context Optional `ValidationContext` settings.\n */\n protected _validate(\n object: TResult,\n context?: ValidationContext\n ): TupleSchemaValidationResult<TResult, TElements> {\n // Fast path: no preprocessors/validators, stop-on-first-error mode\n if (this.canSkipPreValidation && !context?.doNotStopOnFirstError) {\n // Handle undefined / null\n if (typeof object === 'undefined' || object === null) {\n if (typeof object === 'undefined' && this.hasDefault) {\n object = this.resolveDefaultValue();\n } else if (\n !this.isRequired ||\n (object === null && this.isNullable)\n ) {\n const self = this;\n return {\n valid: true,\n object,\n getNestedErrors() {\n return self\n .#validateTupleFull(object, context)\n .getNestedErrors();\n }\n } as any;\n } else {\n return this.#validateTupleFull(object, context);\n }\n }\n\n if (!Array.isArray(object)) {\n return this.#validateTupleFull(object, context);\n }\n\n const lengthError = this.#getLengthError(object as any[]);\n if (lengthError) {\n const self = this;\n return {\n valid: false,\n errors: [{ message: lengthError }],\n getNestedErrors() {\n return self\n .#validateTupleFull(object, context)\n .getNestedErrors();\n }\n } as any;\n }\n\n const resultArray = new Array((object as any[]).length);\n\n for (let i = 0; i < this.#elements.length; i++) {\n const result = this.#elements[i].validate((object as any)[i]);\n if (!result.valid) {\n const self = this;\n return {\n valid: false,\n errors:\n result.errors && result.errors.length > 0\n ? [result.errors[0]]\n : [],\n getNestedErrors() {\n return self\n .#validateTupleFull(object, context)\n .getNestedErrors();\n }\n } as any;\n }\n resultArray[i] = result.object;\n }\n\n if (this.#restSchema instanceof SchemaBuilder) {\n for (\n let i = this.#elements.length;\n i < (object as any[]).length;\n i++\n ) {\n const result = this.#restSchema.validate(\n (object as any)[i]\n );\n if (!result.valid) {\n const self = this;\n return {\n valid: false,\n errors:\n result.errors && result.errors.length > 0\n ? [result.errors[0]]\n : [],\n getNestedErrors() {\n return self\n .#validateTupleFull(object, context)\n .getNestedErrors();\n }\n } as any;\n }\n resultArray[i] = result.object;\n }\n }\n\n const self = this;\n return {\n valid: true,\n object: resultArray as TResult,\n getNestedErrors() {\n return self\n .#validateTupleFull(object, context)\n .getNestedErrors();\n }\n } as any;\n }\n\n return this.#validateTupleFull(object, context);\n }\n\n /**\n * Full validation path with complete setup, error handling, and nested\n * error support.\n */\n #validateTupleFull(\n object: TResult,\n context?: ValidationContext\n ): TupleSchemaValidationResult<TResult, TElements> {\n const setup = this.#createValidationSetup(\n object,\n this.preValidateSync(object, context)\n );\n\n if (!setup.needsElementValidation) return setup.result;\n\n const {\n objToValidate,\n prevalidationContext,\n getNestedErrors,\n elementResults,\n rootErrors\n } = setup;\n\n const lengthError = this.#getLengthError(objToValidate);\n if (lengthError) {\n rootErrors.push(lengthError);\n return {\n valid: false,\n errors: [{ message: lengthError }],\n getNestedErrors\n };\n }\n\n const totalLength =\n this.#restSchema instanceof SchemaBuilder\n ? objToValidate.length\n : this.#elements.length;\n\n if (prevalidationContext.doNotStopOnFirstError) {\n const results: any[] = new Array(totalLength);\n\n for (let i = 0; i < this.#elements.length; i++) {\n results[i] = this.#elements[i].validate(objToValidate[i], {\n ...prevalidationContext\n });\n }\n\n if (this.#restSchema instanceof SchemaBuilder) {\n for (\n let i = this.#elements.length;\n i < objToValidate.length;\n i++\n ) {\n results[i] = this.#restSchema.validate(objToValidate[i], {\n ...prevalidationContext\n });\n }\n }\n\n return this.#assembleDoNotStopResults(\n results,\n elementResults,\n getNestedErrors\n );\n } else {\n const resultArray = new Array(totalLength);\n\n for (let i = 0; i < this.#elements.length; i++) {\n const result = this.#elements[i].validate(objToValidate[i], {\n ...prevalidationContext\n });\n elementResults[i] = result as any;\n if (result.valid) {\n resultArray[i] = result.object;\n } else {\n return {\n valid: false,\n errors:\n Array.isArray(result.errors) &&\n result.errors.length > 0\n ? [result.errors[0]]\n : [],\n getNestedErrors\n };\n }\n }\n\n if (this.#restSchema instanceof SchemaBuilder) {\n for (\n let i = this.#elements.length;\n i < objToValidate.length;\n i++\n ) {\n const result = this.#restSchema.validate(objToValidate[i], {\n ...prevalidationContext\n });\n elementResults[i] = result as any;\n if (result.valid) {\n resultArray[i] = result.object;\n } else {\n return {\n valid: false,\n errors:\n Array.isArray(result.errors) &&\n result.errors.length > 0\n ? [result.errors[0]]\n : [],\n getNestedErrors\n };\n }\n }\n }\n\n return {\n valid: true,\n object: resultArray as TResult,\n getNestedErrors\n };\n }\n }\n\n /**\n * Performs async validation of the schema over `object`.\n * Supports async preprocessors, validators, and error message providers.\n * @param context Optional `ValidationContext` settings.\n */\n protected async _validateAsync(\n object: TResult,\n context?: ValidationContext\n ): Promise<TupleSchemaValidationResult<TResult, TElements>> {\n const setup = this.#createValidationSetup(\n object,\n await super.preValidateAsync(object, context)\n );\n\n if (!setup.needsElementValidation) return setup.result;\n\n const {\n objToValidate,\n prevalidationContext,\n getNestedErrors,\n elementResults,\n rootErrors\n } = setup;\n\n const lengthError = this.#getLengthError(objToValidate);\n if (lengthError) {\n rootErrors.push(lengthError);\n return {\n valid: false,\n errors: [{ message: lengthError }],\n getNestedErrors\n };\n }\n\n const totalLength =\n this.#restSchema instanceof SchemaBuilder\n ? objToValidate.length\n : this.#elements.length;\n\n if (prevalidationContext.doNotStopOnFirstError) {\n const promises: Promise<any>[] = new Array(totalLength);\n\n for (let i = 0; i < this.#elements.length; i++) {\n promises[i] = this.#elements[i].validateAsync(\n objToValidate[i],\n { ...prevalidationContext }\n );\n }\n\n if (this.#restSchema instanceof SchemaBuilder) {\n for (\n let i = this.#elements.length;\n i < objToValidate.length;\n i++\n ) {\n promises[i] = this.#restSchema.validateAsync(\n objToValidate[i],\n { ...prevalidationContext }\n );\n }\n }\n\n const results = await Promise.all(promises);\n return this.#assembleDoNotStopResults(\n results,\n elementResults,\n getNestedErrors\n );\n } else {\n const resultArray = new Array(totalLength);\n\n for (let i = 0; i < this.#elements.length; i++) {\n const result = await this.#elements[i].validateAsync(\n objToValidate[i],\n { ...prevalidationContext }\n );\n elementResults[i] = result as any;\n if (result.valid) {\n resultArray[i] = result.object;\n } else {\n return {\n valid: false,\n errors:\n Array.isArray(result.errors) &&\n result.errors.length > 0\n ? [result.errors[0]]\n : [],\n getNestedErrors\n };\n }\n }\n\n if (this.#restSchema instanceof SchemaBuilder) {\n for (\n let i = this.#elements.length;\n i < objToValidate.length;\n i++\n ) {\n const result = await this.#restSchema.validateAsync(\n objToValidate[i],\n { ...prevalidationContext }\n );\n elementResults[i] = result as any;\n if (result.valid) {\n resultArray[i] = result.object;\n } else {\n return {\n valid: false,\n errors:\n Array.isArray(result.errors) &&\n result.errors.length > 0\n ? [result.errors[0]]\n : [],\n getNestedErrors\n };\n }\n }\n }\n\n return {\n valid: true,\n object: resultArray as TResult,\n getNestedErrors\n };\n }\n }\n\n /**\n * @hidden\n */\n protected createFromProps<TReq extends boolean>(\n props: TupleSchemaBuilderCreateProps<TElements, TRestSchema, TReq>\n ): this {\n return TupleSchemaBuilder.create(props as any) as any;\n }\n\n /**\n * @hidden\n */\n public required(\n errorMessage?: ValidationErrorMessageProvider\n ): TupleSchemaBuilder<\n TElements,\n true,\n TNullable,\n TExplicitType,\n THasDefault,\n TExtensions,\n TRestSchema\n > &\n TExtensions {\n return super.required(errorMessage);\n }\n\n /**\n * @hidden\n */\n public optional(): TupleSchemaBuilder<\n TElements,\n false,\n TNullable,\n TExplicitType,\n THasDefault,\n TExtensions,\n TRestSchema\n > &\n TExtensions {\n return super.optional();\n }\n\n /**\n * @hidden\n */\n public default(\n value: TResult | (() => TResult)\n ): TupleSchemaBuilder<\n TElements,\n true,\n TNullable,\n TExplicitType,\n true,\n TExtensions,\n TRestSchema\n > &\n TExtensions {\n return super.default(value) as any;\n }\n\n /**\n * @hidden\n */\n public clearDefault(): TupleSchemaBuilder<\n TElements,\n TRequired,\n TNullable,\n TExplicitType,\n false,\n TExtensions,\n TRestSchema\n > &\n TExtensions {\n return super.clearDefault() as any;\n }\n\n /**\n * @hidden\n */\n public brand<TBrand extends string | symbol>(\n _name?: TBrand\n ): TupleSchemaBuilder<\n TElements,\n TRequired,\n TNullable,\n TResult & { readonly [K in BRAND]: TBrand },\n THasDefault,\n TExtensions,\n TRestSchema\n > &\n TExtensions {\n return super.brand(_name);\n }\n\n public introspect() {\n return {\n ...super.introspect(),\n /**\n * Per-position element schemas defining the fixed tuple structure.\n */\n elements: this.#elements,\n /**\n * Optional schema for elements beyond the fixed positions.\n * When set, additional elements are validated against this schema.\n * Mirrors TypeScript's rest element syntax: `[string, number, ...boolean[]]`.\n */\n restSchema: this.#restSchema\n };\n }\n\n /**\n * Sets a schema that all elements beyond the fixed positions must satisfy.\n * Mirrors TypeScript's variadic tuple tail: `[string, number, ...boolean[]]`.\n *\n * When set, the tuple length must be at least equal to the number of fixed\n * elements, and any additional elements are validated against `schema`.\n * When not set, the tuple length must be exactly equal to the fixed count.\n *\n * @param schema Schema that extra array elements must satisfy.\n *\n * @example\n * ```ts\n * const schema = tuple([string(), number()]).rest(boolean());\n * // Inferred TypeScript type: [string, number, ...boolean[]]\n *\n * schema.validate(['hello', 42]); // valid\n * schema.validate(['hello', 42, true]); // valid\n * schema.validate(['hello', 42, true, false]); // valid\n * schema.validate(['hello', 42, 'extra']); // invalid — 'extra' not boolean\n * ```\n */\n public rest<TSchema extends SchemaBuilder<any, any, any, any, any>>(\n schema: TSchema\n ): TupleSchemaBuilder<\n TElements,\n TRequired,\n TNullable,\n TExplicitType,\n THasDefault,\n TExtensions,\n TSchema\n > &\n TExtensions {\n return this.derive({\n ...this.introspect(),\n restSchema: schema\n } as any) as any;\n }\n\n /**\n * Removes the rest schema set by `rest()`. After this call, the tuple\n * length must be exactly equal to the number of fixed element schemas.\n */\n public clearRest(): TupleSchemaBuilder<\n TElements,\n TRequired,\n TNullable,\n TExplicitType,\n THasDefault,\n TExtensions,\n undefined\n > &\n TExtensions {\n return this.derive({\n ...this.introspect(),\n restSchema: undefined\n } as any) as any;\n }\n\n /**\n * @hidden\n */\n public nullable(): TupleSchemaBuilder<\n TElements,\n TRequired,\n true,\n TExplicitType,\n THasDefault,\n TExtensions,\n TRestSchema\n > &\n TExtensions {\n return super.nullable() as any;\n }\n\n /**\n * @hidden\n */\n public notNullable(): TupleSchemaBuilder<\n TElements,\n TRequired,\n false,\n TExplicitType,\n THasDefault,\n TExtensions,\n TRestSchema\n > &\n TExtensions {\n return super.notNullable() as any;\n }\n}\n\n/**\n * Creates a fixed-length array schema (tuple) where each element at a\n * specific index is validated against its own schema.\n *\n * @param elements Array of per-position schemas. The length of this array\n * determines the required tuple length (unless `.rest()` is used).\n *\n * @example\n * ```ts\n * import { tuple, string, number, boolean } from '@cleverbrush/schema';\n *\n * const schema = tuple([string(), number(), boolean()]);\n * // Inferred TypeScript type: [string, number, boolean]\n *\n * schema.validate(['hello', 42, true]); // valid\n * schema.validate(['hello', 42]); // invalid — too few elements\n * schema.validate(['hello', 'oops', true]); // invalid — wrong type at [1]\n * ```\n *\n * @example\n * ```ts\n * // 2-D coordinate pair\n * const point = tuple([number(), number()]);\n * const result = point.validate([10.5, 20.3]);\n * // result.valid === true\n * // result.object === [10.5, 20.3]\n * ```\n *\n * @example\n * ```ts\n * // Optional tuple with default value\n * const schema = tuple([string(), number()])\n * .optional()\n * .default(() => ['', 0]);\n * ```\n */\nexport const tuple = <\n const TElements extends readonly SchemaBuilder<any, any, any, any, any>[]\n>(\n elements: [...TElements]\n) =>\n TupleSchemaBuilder.create({\n isRequired: true,\n elements\n }) as unknown as TupleSchemaBuilder<TElements, true>;\n"],"mappings":"sDA2IO,IAAMA,EAAN,MAAMC,UAkBHC,CAMR,CAaEC,GACAC,GAOA,OAAc,OACVC,EACF,CACE,OAAO,IAAIJ,EAAmB,CAC1B,KAAM,QACN,GAAGI,CACP,CAAQ,CACZ,CAEU,YACNA,EAMF,CACE,MAAMA,CAAY,EAEd,MAAM,QAAQA,EAAM,QAAQ,EAC5B,KAAKF,GAAYE,EAAM,SAEvB,KAAKF,GAAY,CAAC,EAGlBE,EAAM,sBAAsBH,IAC5B,KAAKE,GAAcC,EAAM,WAEjC,CAKO,QACHC,EAUY,CACZ,OAAO,KAAK,OACR,CACI,GAAG,KAAK,WAAW,CACvB,EACA,EACJ,CACJ,CAKO,cASS,CACZ,OAAO,KAAK,OACR,CACI,GAAG,KAAK,WAAW,CACvB,EACA,EACJ,CACJ,CAEAC,GAAgBC,EAA2B,CACvC,GAAIA,EAAI,OAAS,KAAKL,GAAU,OAAQ,CACpC,IAAMM,EAAI,KAAKN,GAAU,OACzB,MAAO,kCAAkCM,CAAC,WAAWA,IAAM,EAAI,GAAK,GAAG,SAASD,EAAI,MAAM,EAC9F,CACA,GACI,EAAE,KAAKJ,cAAuBF,IAC9BM,EAAI,SAAW,KAAKL,GAAU,OAChC,CACE,IAAMM,EAAI,KAAKN,GAAU,OACzB,MAAO,+BAA+BM,CAAC,WAAWA,IAAM,EAAI,GAAK,GAAG,SAASD,EAAI,MAAM,EAC3F,CACA,OAAO,IACX,CAEAE,GACIC,EAC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J,CACJ,CAKU,gBACNlB,EACI,CACJ,OAAOJ,EAAmB,OAAOI,CAAY,CACjD,CAKO,SACHmC,EAUY,CACZ,OAAO,MAAM,SAASA,CAAY,CACtC,CAKO,UASS,CACZ,OAAO,MAAM,SAAS,CAC1B,CAKO,QACHC,EAUY,CACZ,OAAO,MAAM,QAAQA,CAAK,CAC9B,CAKO,cASS,CACZ,OAAO,MAAM,aAAa,CAC9B,CAKO,MACHC,EAUY,CACZ,OAAO,MAAM,MAAMA,CAAK,CAC5B,CAEO,YAAa,CAChB,MAAO,CACH,GAAG,MAAM,WAAW,EAIpB,SAAU,KAAKvC,GAMf,WAAY,KAAKC,EACrB,CACJ,CAuBO,KACHuC,EAUY,CACZ,OAAO,KAAK,OAAO,CACf,GAAG,KAAK,WAAW,EACnB,WAAYA,CAChB,CAAQ,CACZ,CAMO,WASS,CACZ,OAAO,KAAK,OAAO,CACf,GAAG,KAAK,WAAW,EACnB,WAAY,MAChB,CAAQ,CACZ,CAKO,UASS,CACZ,OAAO,MAAM,SAAS,CAC1B,CAKO,aASS,CACZ,OAAO,MAAM,YAAY,CAC7B,CACJ,EAsCaC,EAGTC,GAEA7C,EAAmB,OAAO,CACtB,WAAY,GACZ,SAAA6C,CACJ,CAAC","names":["TupleSchemaBuilder","_TupleSchemaBuilder","SchemaBuilder","#elements","#restSchema","props","_notUsed","#getLengthError","arr","n","#createValidationSetup","object","superResult","valid","prevalidationContext","errors","preValidationTransaction","selfDescriptor","SYMBOL_SCHEMA_PROPERTY_DESCRIPTOR","obj","rootErrors","elementResults","createHybridErrorArray","getNestedErrors","e","objToValidate","#assembleDoNotStopResults","results","allValid","i","r","context","self","#validateTupleFull","lengthError","resultArray","result","setup","totalLength","promises","errorMessage","value","_name","schema","tuple","elements"]}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{f as m}from"./chunk-2BKBVVZ3.js";var p=class R extends m{#a;#e;static create(e){return new R({type:"record",...e})}constructor(e){super(e),e.keySchema instanceof m&&(this.#a=e.keySchema),e.valueSchema instanceof m&&(this.#e=e.valueSchema)}hasType(e){return this.derive({...this.introspect()},!0)}clearHasType(){return this.derive({...this.introspect()},!0)}createFromProps(e){return R.create(e)}required(e){return super.required(e)}optional(){return super.optional()}default(e){return super.default(e)}clearDefault(){return super.clearDefault()}brand(e){return super.brand(e)}introspect(){return{...super.introspect(),keySchema:this.#a,valueSchema:this.#e}}#s(e){let t={};for(let[l,u]of e)t[l]=u;return t}#r(e,t,l){let u=this.#e;return{errors:t,isValid:t.length===0,seenValue:l!==null&&typeof l=="object"?l[e]:void 0,descriptor:{key:e,getSchema:()=>u,getValue:r=>r!==null&&typeof r=="object"&&Object.hasOwn(r,e)?{success:!0,value:r[e]}:{success:!1},setValue:(r,d)=>r!==null&&typeof r=="object"?(r[e]=d,!0):!1}}}#l(e,t){let{valid:l,errors:u}=t,r=[],d=new Map,y=()=>this.#s(d),o=n=>{if(typeof n>"u")return{errors:r,isValid:r.length===0,seenValue:e};let i=d.get(n),s=i&&!i.valid?(i.errors??[]).map(T=>T.message):[];return this.#r(n,s,e)};if(!l){for(let n of u??[])r.push(n.message);return{earlyReturn:!0,result:{valid:l,errors:u,getNestedErrors:y,getErrorsFor:o}}}let a=t.transaction.object.validatedObject;return typeof a>"u"&&!this.isRequired||a===null&&(!this.isRequired||this.isNullable)?{earlyReturn:!0,result:{valid:!0,object:a,getNestedErrors:y,getErrorsFor:o}}:typeof a!="object"||Array.isArray(a)||a===null?(r.push("object expected"),{earlyReturn:!0,result:{valid:!1,errors:[{message:"object expected"}],getNestedErrors:y,getErrorsFor:o}}):{earlyReturn:!1,objToValidate:a,nestedKeyResults:d,getNestedErrors:y,getErrorsFor:o}}#n(e,t,l,u,r,d){return e?{valid:!0,object:l,getNestedErrors:r,getErrorsFor:d}:{valid:!1,errors:u?t:[t[0]],getNestedErrors:r,getErrorsFor:d}}validate(e,t){return super.validate(e,t)}async validateAsync(e,t){return super.validateAsync(e,t)}_validate(e,t){if(this.canSkipPreValidation&&!t?.doNotStopOnFirstError){if(typeof e>"u"||e===null)if(typeof e>"u"&&this.hasDefault)e=this.resolveDefaultValue();else if(!this.isRequired||e===null&&this.isNullable){let a=e;return{valid:!0,object:e,getNestedErrors(){return{}},getErrorsFor:n=>typeof n>"u"?{errors:[],isValid:!0,seenValue:a}:this.#r(n,[],a)}}else return this.#t(e,t);if(typeof e!="object"||Array.isArray(e)||e===null)return this.#t(e,t);let l=new Map,u={},r=null;for(let a of Object.keys(e)){let n=this.#a.validate(a);if(!n.valid){let s=n.errors&&n.errors.length>0?n.errors:[{message:`key "${a}" is invalid`}];l.set(a,{valid:!1,errors:s}),r=s[0];break}let i=this.#e.validate(e[a]);if(l.set(a,i),i.valid)u[a]=i.object;else{let s=i.errors&&i.errors.length>0?i.errors:[{message:`value for key "${a}" is invalid`}];l.set(a,{valid:!1,errors:s}),r=s[0];break}}let d=e,y=()=>this.#s(l),o=a=>{if(typeof a>"u")return{errors:[],isValid:!0,seenValue:d};let n=l.get(a),i=n&&!n.valid?(n.errors??[]).map(s=>s.message):[];return this.#r(a,i,d)};return r!==null?{valid:!1,errors:[r],getNestedErrors:y,getErrorsFor:o}:{valid:!0,object:u,getNestedErrors:y,getErrorsFor:o}}return this.#t(e,t)}#t(e,t){let l=this.#l(e,this.preValidateSync(e,t));if(l.earlyReturn)return l.result;let{objToValidate:u,nestedKeyResults:r,getNestedErrors:d,getErrorsFor:y}=l,o=t?.doNotStopOnFirstError??!1,a=!0,n={},i=[];for(let s of Object.keys(u)){let T=this.#a.validate(s);if(!T.valid){a=!1;let h=T.errors&&T.errors.length>0?T.errors:[{message:`key "${s}" is invalid`}];if(r.set(s,{valid:!1,errors:h}),i.push(...h),!o)break;continue}let c=this.#e.validate(u[s],o?{doNotStopOnFirstError:!0}:void 0);if(r.set(s,c),c.valid)n[s]=c.object;else{a=!1;let h=c.errors&&c.errors.length>0?c.errors:[{message:`value for key "${s}" is invalid`}];if(i.push(...h),!o)break}}return this.#n(a,i,n,o,d,y)}async _validateAsync(e,t){let l=this.#l(e,await this.preValidateAsync(e,t));if(l.earlyReturn)return l.result;let{objToValidate:u,nestedKeyResults:r,getNestedErrors:d,getErrorsFor:y}=l,o=t?.doNotStopOnFirstError??!1,a=!0,n={},i=[];for(let s of Object.keys(u)){let T=await this.#a.validateAsync(s);if(!T.valid){a=!1;let h=T.errors&&T.errors.length>0?T.errors:[{message:`key "${s}" is invalid`}];if(r.set(s,{valid:!1,errors:h}),i.push(...h),!o)break;continue}let c=await this.#e.validateAsync(u[s],o?{doNotStopOnFirstError:!0}:void 0);if(r.set(s,c),c.valid)n[s]=c.object;else{a=!1;let h=c.errors&&c.errors.length>0?c.errors:[{message:`value for key "${s}" is invalid`}];if(i.push(...h),!o)break}}return this.#n(a,i,n,o,d,y)}nullable(){return super.nullable()}notNullable(){return super.notNullable()}};function f(R,e){return p.create({type:"record",keySchema:R,valueSchema:e})}export{p as a,f as b};
|
|
2
|
+
//# sourceMappingURL=chunk-W5D22D4P.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/builders/RecordSchemaBuilder.ts"],"sourcesContent":["/**\n * Schema builder for objects with dynamic string keys, where every value\n * must satisfy the same value schema.\n *\n * Equivalent to TypeScript's `Record<string, V>` (or a more constrained key\n * set when using a string-literal key schema) and Zod's `z.record()`.\n *\n * Unlike `ObjectSchemaBuilder` — which validates objects with a **known,\n * fixed set of property names** — `RecordSchemaBuilder` validates objects\n * whose keys are not known at schema-definition time (look-up tables, i18n\n * bundles, caches, etc.).\n *\n * @module\n */\nimport {\n type BRAND,\n type InferType,\n type PreValidationResult,\n SchemaBuilder,\n type ValidationContext,\n type ValidationError,\n type ValidationErrorMessageProvider,\n type ValidationResult\n} from './SchemaBuilder.js';\nimport type { StringSchemaBuilder } from './StringSchemaBuilder.js';\n\n// ---------------------------------------------------------------------------\n// Public types\n// ---------------------------------------------------------------------------\n\n/**\n * Descriptor for a single key-value entry within a validated record.\n * Provides `getValue`, `setValue`, and `getSchema` operations for the entry.\n *\n * Returned as part of {@link RecordKeyValidationResult}.\n */\nexport type RecordKeyDescriptor<\n TRecord,\n TValueSchema extends SchemaBuilder<any, any, any, any, any>\n> = {\n /** The key within the record this descriptor refers to. */\n readonly key: string;\n /** Returns the value schema every record entry must satisfy. */\n getSchema(): TValueSchema;\n /**\n * Retrieves the value at `key` from the given record object.\n * Returns `{ success: false }` when the key is not present.\n */\n getValue(obj: TRecord): {\n value?: InferType<TValueSchema>;\n success: boolean;\n };\n /**\n * Sets the value at `key` on the given record object.\n * Returns `false` when `obj` is not a non-null object.\n */\n setValue(obj: TRecord, value: InferType<TValueSchema>): boolean;\n};\n\n/**\n * Validation result for a single key-value entry in a record.\n * Returned by {@link RecordSchemaValidationResult.getErrorsFor | getErrorsFor(key)}.\n */\nexport type RecordKeyValidationResult<\n TRecord,\n TValueSchema extends SchemaBuilder<any, any, any, any, any>\n> = {\n /** Validation error messages for this entry; empty array when valid. */\n readonly errors: ReadonlyArray<string>;\n /** `true` when there are no validation errors for this entry. */\n readonly isValid: boolean;\n /** The value that was seen at this key during validation. */\n readonly seenValue: InferType<TValueSchema> | undefined;\n /** Descriptor for reading/writing the value at this key. */\n readonly descriptor: RecordKeyDescriptor<TRecord, TValueSchema>;\n};\n\n/**\n * Root-level validation result for the record object itself.\n * Returned by {@link RecordSchemaValidationResult.getErrorsFor | getErrorsFor()} (no argument).\n */\nexport type RecordRootValidationResult<TResult> = {\n /** Root-level error messages (e.g. `\"object expected\"`); empty when valid. */\n readonly errors: ReadonlyArray<string>;\n /** `true` when there are no root-level errors. */\n readonly isValid: boolean;\n /** The value that was being validated. */\n readonly seenValue: TResult | undefined;\n};\n\n/**\n * Validation result type returned by `RecordSchemaBuilder.validate()`.\n *\n * Extends `ValidationResult` with:\n * - `getNestedErrors()` — a per-key map of `ValidationResult` objects.\n * - `getErrorsFor()` — root-level errors for the record container itself.\n * - `getErrorsFor(key)` — errors, seen value, and descriptor for a specific key.\n */\nexport type RecordSchemaValidationResult<\n TResult,\n TValueSchema extends SchemaBuilder<any, any, any, any, any>\n> = ValidationResult<TResult> & {\n /**\n * Returns per-key validation results as a plain object.\n *\n * Each key in the returned object corresponds to a key in the input that\n * **failed** validation (in `doNotStopOnFirstError` mode) or the single\n * first failing key (in the default stop-on-first-error mode). Keys that\n * passed are not included.\n *\n * @deprecated Prefer {@link getErrorsFor} for a richer per-entry result\n * that also includes a descriptor and `seenValue`.\n *\n * @example\n * ```ts\n * const schema = record(string(), number().positive());\n * const result = schema.validate(\n * { a: 1, b: -2, c: 'oops' },\n * { doNotStopOnFirstError: true }\n * );\n *\n * if (!result.valid) {\n * const nested = result.getNestedErrors();\n * console.log(nested['b']); // ValidationResult for key 'b'\n * console.log(nested['c']); // ValidationResult for key 'c'\n * }\n * ```\n */\n getNestedErrors(): Record<\n string,\n ValidationResult<InferType<TValueSchema>>\n >;\n /**\n * Returns root-level errors for the record container itself\n * (e.g. `\"object expected\"` when a non-object value is passed,\n * or errors from custom validators added to the record schema).\n *\n * @example\n * ```ts\n * const schema = record(string(), number());\n * const root = schema.validate(42 as any).getErrorsFor();\n * // root.errors[0] === 'object expected'\n * // root.isValid === false\n * ```\n */\n getErrorsFor(): RecordRootValidationResult<TResult>;\n /**\n * Returns the validation result for the entry with the given key,\n * including error messages, the seen value, and a descriptor for\n * accessing and modifying the value at that key.\n *\n * If the key was not reached during validation (e.g. an earlier key\n * already failed in stop-on-first-error mode), an empty result with\n * `isValid: true` and no errors is returned.\n *\n * @param key - the key whose validation result to retrieve\n *\n * @example\n * ```ts\n * const schema = record(string(), number().min(0));\n * const result = schema.validate(\n * { a: 5, b: -2 },\n * { doNotStopOnFirstError: true }\n * );\n *\n * const bErrors = result.getErrorsFor('b');\n * // bErrors.isValid === false\n * // bErrors.errors[0] === 'the value must be >= 0'\n * // bErrors.seenValue === -2\n * // bErrors.descriptor.key === 'b'\n * // bErrors.descriptor.getSchema() === valueSchema\n * ```\n */\n getErrorsFor(key: string): RecordKeyValidationResult<TResult, TValueSchema>;\n};\n\ntype RecordSchemaBuilderCreateProps<\n TKeySchema extends StringSchemaBuilder<any, any, any, any>,\n TValueSchema extends SchemaBuilder<any, any, any, any, any>,\n R extends boolean = true\n> = Partial<\n ReturnType<RecordSchemaBuilder<TKeySchema, TValueSchema, R>['introspect']>\n>;\n\n// ---------------------------------------------------------------------------\n// Builder class\n// ---------------------------------------------------------------------------\n\n/**\n * Schema builder for objects with dynamic string keys.\n *\n * Every key in the validated object must be accepted by `keySchema` (a\n * `StringSchemaBuilder`) and every value must satisfy `valueSchema`.\n *\n * The inferred TypeScript type mirrors `Record<K, V>` where `K` is the\n * string type produced by `keySchema` and `V` is the type produced by\n * `valueSchema`.\n *\n * **NOTE** — this class is exported to allow extension by inheritance. Use\n * the {@link record | record()} factory function instead of instantiating it\n * directly.\n *\n * @example\n * ```ts\n * import { record, string, number } from '@cleverbrush/schema';\n *\n * // Basic: string keys, number values\n * const scores = record(string(), number().min(0));\n * // InferType<typeof scores> → Record<string, number>\n *\n * scores.validate({ alice: 95, bob: 87 }); // valid\n * scores.validate({ alice: 95, bob: -1 }); // invalid (negative)\n * ```\n *\n * @example\n * ```ts\n * // Restrict keys to a specific set of literals with .equals()\n * const locales = record(\n * string().matches(/^[a-z]{2}(-[A-Z]{2})?$/),\n * string().nonempty()\n * );\n * // accepts: { en: 'Hello', fr: 'Bonjour' }\n * // rejects: { 123: 'oops' } ← key doesn't match pattern\n * ```\n *\n * @see {@link record}\n */\nexport class RecordSchemaBuilder<\n TKeySchema extends StringSchemaBuilder<any, any, any, any>,\n TValueSchema extends SchemaBuilder<any, any, any, any, any>,\n TRequired extends boolean = true,\n TNullable extends boolean = false,\n TExplicitType = undefined,\n THasDefault extends boolean = false,\n TExtensions = {},\n TResult = TExplicitType extends undefined\n ? Record<InferType<TKeySchema>, InferType<TValueSchema>>\n : TExplicitType\n> extends SchemaBuilder<\n TResult,\n TRequired,\n TNullable,\n THasDefault,\n TExtensions\n> {\n /** Native type parameters for extension rebinding; never emitted at runtime. @internal */\n declare readonly __cleverbrush_builder_type__: readonly [\n 'record',\n TKeySchema,\n TValueSchema,\n TRequired,\n TNullable,\n TExplicitType,\n THasDefault,\n TResult\n ];\n\n #keySchema!: TKeySchema;\n #valueSchema!: TValueSchema;\n\n /**\n * @hidden\n */\n public static create(props: RecordSchemaBuilderCreateProps<any, any, any>) {\n return new RecordSchemaBuilder({\n type: 'record',\n ...props\n } as any);\n }\n\n protected constructor(\n props: RecordSchemaBuilderCreateProps<\n TKeySchema,\n TValueSchema,\n TRequired\n >\n ) {\n super(props as any);\n\n if (props.keySchema instanceof SchemaBuilder) {\n this.#keySchema = props.keySchema as TKeySchema;\n }\n if (props.valueSchema instanceof SchemaBuilder) {\n this.#valueSchema = props.valueSchema as TValueSchema;\n }\n }\n\n /**\n * @inheritdoc\n */\n public hasType<T>(\n _notUsed?: T\n ): RecordSchemaBuilder<\n TKeySchema,\n TValueSchema,\n true,\n TNullable,\n T,\n THasDefault,\n TExtensions\n > &\n TExtensions {\n return this.derive(\n {\n ...this.introspect()\n } as any,\n true\n ) as any;\n }\n\n /**\n * @inheritdoc\n */\n public clearHasType(): RecordSchemaBuilder<\n TKeySchema,\n TValueSchema,\n TRequired,\n TNullable,\n undefined,\n THasDefault,\n TExtensions\n > &\n TExtensions {\n return this.derive(\n {\n ...this.introspect()\n } as any,\n true\n ) as any;\n }\n\n /**\n * @hidden\n */\n protected createFromProps<TReq extends boolean>(\n props: RecordSchemaBuilderCreateProps<TKeySchema, TValueSchema, TReq>\n ): this {\n return RecordSchemaBuilder.create(props as any) as any;\n }\n\n /**\n * @hidden\n */\n public required(\n errorMessage?: ValidationErrorMessageProvider\n ): RecordSchemaBuilder<\n TKeySchema,\n TValueSchema,\n true,\n TNullable,\n TExplicitType,\n THasDefault,\n TExtensions\n > &\n TExtensions {\n return super.required(errorMessage);\n }\n\n /**\n * @hidden\n */\n public optional(): RecordSchemaBuilder<\n TKeySchema,\n TValueSchema,\n false,\n TNullable,\n TExplicitType,\n THasDefault,\n TExtensions\n > &\n TExtensions {\n return super.optional();\n }\n\n /**\n * @hidden\n */\n public default(\n value: TResult | (() => TResult)\n ): RecordSchemaBuilder<\n TKeySchema,\n TValueSchema,\n true,\n TNullable,\n TExplicitType,\n true,\n TExtensions\n > &\n TExtensions {\n return super.default(value) as any;\n }\n\n /**\n * @hidden\n */\n public clearDefault(): RecordSchemaBuilder<\n TKeySchema,\n TValueSchema,\n TRequired,\n TNullable,\n TExplicitType,\n false,\n TExtensions\n > &\n TExtensions {\n return super.clearDefault() as any;\n }\n\n /**\n * @hidden\n */\n public brand<TBrand extends string | symbol>(\n _name?: TBrand\n ): RecordSchemaBuilder<\n TKeySchema,\n TValueSchema,\n TRequired,\n TNullable,\n TResult & { readonly [K in BRAND]: TBrand },\n THasDefault,\n TExtensions\n > &\n TExtensions {\n return super.brand(_name);\n }\n\n /**\n * Returns an introspection object describing the record schema.\n */\n public introspect() {\n return {\n ...super.introspect(),\n /**\n * The schema every key must satisfy (a `StringSchemaBuilder`).\n */\n keySchema: this.#keySchema,\n /**\n * The schema every value must satisfy.\n */\n valueSchema: this.#valueSchema\n };\n }\n\n // -----------------------------------------------------------------------\n // Validation helpers\n // -----------------------------------------------------------------------\n\n #buildNestedErrors(\n keyResults: Map<string, ValidationResult<any>>\n ): Record<string, ValidationResult<InferType<TValueSchema>>> {\n const out: Record<string, ValidationResult<any>> = {};\n for (const [k, v] of keyResults) {\n out[k] = v;\n }\n return out;\n }\n\n /**\n * Creates a {@link RecordKeyValidationResult} for `key` with the given\n * error message strings. Captures `rootObject` so the returned descriptor\n * can lazily read/write the value at that key.\n */\n #makeKeyResult(\n key: string,\n errors: string[],\n rootObject: TResult\n ): RecordKeyValidationResult<TResult, TValueSchema> {\n const valueSchema = this.#valueSchema;\n return {\n errors: errors as ReadonlyArray<string>,\n isValid: errors.length === 0,\n seenValue:\n rootObject !== null && typeof rootObject === 'object'\n ? (rootObject as any)[key]\n : undefined,\n descriptor: {\n key,\n getSchema: () => valueSchema,\n getValue: (obj: TResult) => {\n if (\n obj !== null &&\n typeof obj === 'object' &&\n Object.hasOwn(obj as any, key)\n ) {\n return { success: true, value: (obj as any)[key] };\n }\n return { success: false };\n },\n setValue: (obj: TResult, val: InferType<TValueSchema>) => {\n if (obj !== null && typeof obj === 'object') {\n (obj as any)[key] = val;\n return true;\n }\n return false;\n }\n }\n };\n }\n\n /**\n * Shared setup for {@link #validateFull} and {@link _validateAsync}.\n * Runs pre-validation guards (null / undefined / type checks) and\n * builds the `getNestedErrors` / `getErrorsFor` closures.\n *\n * Returns either an early result (when validation can short-circuit)\n * or the data needed for the per-entry loop.\n */\n #createValidationSetup(\n object: TResult,\n superResult: PreValidationResult<any, { validatedObject: any }>\n ):\n | {\n earlyReturn: true;\n result: RecordSchemaValidationResult<TResult, TValueSchema>;\n }\n | {\n earlyReturn: false;\n objToValidate: any;\n nestedKeyResults: Map<\n string,\n ValidationResult<InferType<TValueSchema>>\n >;\n getNestedErrors: () => Record<\n string,\n ValidationResult<InferType<TValueSchema>>\n >;\n getErrorsFor: (key?: string) => any;\n } {\n const { valid, errors } = superResult;\n\n const rootErrorMsgs: string[] = [];\n const nestedKeyResults = new Map<\n string,\n ValidationResult<InferType<TValueSchema>>\n >();\n const getNestedErrors = () => this.#buildNestedErrors(nestedKeyResults);\n const getErrorsFor = (key?: string): any => {\n if (typeof key === 'undefined') {\n return {\n errors: rootErrorMsgs as ReadonlyArray<string>,\n isValid: rootErrorMsgs.length === 0,\n seenValue: object\n };\n }\n const nestedResult = nestedKeyResults.get(key);\n const errMsgs =\n nestedResult && !nestedResult.valid\n ? (nestedResult.errors ?? []).map(\n (e: ValidationError) => e.message\n )\n : [];\n return this.#makeKeyResult(key, errMsgs, object);\n };\n\n if (!valid) {\n for (const e of errors ?? []) rootErrorMsgs.push(e.message);\n return {\n earlyReturn: true,\n result: {\n valid,\n errors,\n getNestedErrors,\n getErrorsFor\n } as any\n };\n }\n\n const objToValidate = superResult.transaction!.object\n .validatedObject as any;\n\n if (\n (typeof objToValidate === 'undefined' && !this.isRequired) ||\n (objToValidate === null && (!this.isRequired || this.isNullable))\n ) {\n return {\n earlyReturn: true,\n result: {\n valid: true,\n object: objToValidate,\n getNestedErrors,\n getErrorsFor\n } as any\n };\n }\n\n if (\n typeof objToValidate !== 'object' ||\n Array.isArray(objToValidate) ||\n objToValidate === null\n ) {\n rootErrorMsgs.push('object expected');\n return {\n earlyReturn: true,\n result: {\n valid: false,\n errors: [{ message: 'object expected' }],\n getNestedErrors,\n getErrorsFor\n } as any\n };\n }\n\n return {\n earlyReturn: false,\n objToValidate,\n nestedKeyResults,\n getNestedErrors,\n getErrorsFor\n };\n }\n\n /**\n * Builds the final validation result from the per-entry loop outcome.\n */\n #buildEntryResult(\n allValid: boolean,\n allErrors: ValidationError[],\n result: Record<string, any>,\n doNotStop: boolean,\n getNestedErrors: () => Record<\n string,\n ValidationResult<InferType<TValueSchema>>\n >,\n getErrorsFor: (key?: string) => any\n ): RecordSchemaValidationResult<TResult, TValueSchema> {\n if (!allValid) {\n return {\n valid: false,\n errors: doNotStop ? allErrors : [allErrors[0]],\n getNestedErrors,\n getErrorsFor\n } as any;\n }\n\n return {\n valid: true,\n object: result as TResult,\n getNestedErrors,\n getErrorsFor\n } as any;\n }\n\n /**\n * Core sync validation. {@inheritDoc SchemaBuilder.validate}\n */\n public validate(\n object: TResult,\n context?: ValidationContext\n ): RecordSchemaValidationResult<TResult, TValueSchema> {\n return super.validate(object, context) as RecordSchemaValidationResult<\n TResult,\n TValueSchema\n >;\n }\n\n /**\n * Core async validation. {@inheritDoc SchemaBuilder.validateAsync}\n */\n public async validateAsync(\n object: TResult,\n context?: ValidationContext\n ): Promise<RecordSchemaValidationResult<TResult, TValueSchema>> {\n return super.validateAsync(object, context) as Promise<\n RecordSchemaValidationResult<TResult, TValueSchema>\n >;\n }\n\n /**\n * Core sync validation. Returns `{ valid, object, errors, getNestedErrors, getErrorsFor }`.\n */\n protected _validate(\n object: TResult,\n context?: ValidationContext\n ): RecordSchemaValidationResult<TResult, TValueSchema> {\n // Fast path: skip pre-validation when no preprocessors/validators.\n if (this.canSkipPreValidation && !context?.doNotStopOnFirstError) {\n if (typeof object === 'undefined' || object === null) {\n if (typeof object === 'undefined' && this.hasDefault) {\n object = this.resolveDefaultValue();\n } else if (\n !this.isRequired ||\n (object === null && this.isNullable)\n ) {\n const capturedObj = object;\n return {\n valid: true,\n object,\n getNestedErrors() {\n return {};\n },\n getErrorsFor: (key?: string): any => {\n if (typeof key === 'undefined') {\n return {\n errors: [] as ReadonlyArray<string>,\n isValid: true,\n seenValue: capturedObj\n };\n }\n return this.#makeKeyResult(\n key,\n [],\n capturedObj as TResult\n );\n }\n } as any;\n } else {\n return this.#validateFull(object, context);\n }\n }\n\n if (\n typeof object !== 'object' ||\n Array.isArray(object) ||\n object === null\n ) {\n return this.#validateFull(object, context);\n }\n\n // Validate every entry inline, collecting per-key results as we go.\n const nestedKeyResults = new Map<string, ValidationResult<any>>();\n const result: Record<string, any> = {};\n let firstError: ValidationError | null = null;\n\n for (const key of Object.keys(object as any)) {\n const keyResult = this.#keySchema.validate(key);\n if (!keyResult.valid) {\n const keyErrors =\n keyResult.errors && keyResult.errors.length > 0\n ? keyResult.errors\n : [{ message: `key \"${key}\" is invalid` }];\n nestedKeyResults.set(key, {\n valid: false,\n errors: keyErrors\n });\n firstError = keyErrors[0];\n break;\n }\n\n const valueResult = this.#valueSchema.validate(\n (object as any)[key]\n );\n nestedKeyResults.set(key, valueResult as any);\n\n if (!valueResult.valid) {\n const valErrors =\n valueResult.errors && valueResult.errors.length > 0\n ? valueResult.errors\n : [\n {\n message: `value for key \"${key}\" is invalid`\n }\n ];\n nestedKeyResults.set(key, {\n valid: false,\n errors: valErrors\n });\n firstError = valErrors[0];\n break;\n } else {\n result[key] = valueResult.object;\n }\n }\n\n const capturedInput = object;\n const getNestedErrors = () =>\n this.#buildNestedErrors(nestedKeyResults);\n const getErrorsFor = (key?: string): any => {\n if (typeof key === 'undefined') {\n return {\n errors: [] as ReadonlyArray<string>,\n isValid: true,\n seenValue: capturedInput\n };\n }\n const nestedResult = nestedKeyResults.get(key);\n const errMsgs =\n nestedResult && !nestedResult.valid\n ? (nestedResult.errors ?? []).map(\n (e: ValidationError) => e.message\n )\n : [];\n return this.#makeKeyResult(key, errMsgs, capturedInput);\n };\n\n if (firstError !== null) {\n return {\n valid: false,\n errors: [firstError],\n getNestedErrors,\n getErrorsFor\n } as any;\n }\n\n return {\n valid: true,\n object: result as TResult,\n getNestedErrors,\n getErrorsFor\n } as any;\n }\n\n return this.#validateFull(object, context);\n }\n\n /**\n * Full validation path — processes preprocessors, validators, and collects\n * all per-entry results.\n */\n #validateFull(\n object: TResult,\n context?: ValidationContext\n ): RecordSchemaValidationResult<TResult, TValueSchema> {\n const setup = this.#createValidationSetup(\n object,\n this.preValidateSync(object, context)\n );\n if (setup.earlyReturn) return setup.result;\n\n const {\n objToValidate,\n nestedKeyResults,\n getNestedErrors,\n getErrorsFor\n } = setup;\n const doNotStop = context?.doNotStopOnFirstError ?? false;\n let allValid = true;\n const result: Record<string, any> = {};\n const allErrors: ValidationError[] = [];\n\n for (const key of Object.keys(objToValidate)) {\n const keyResult = this.#keySchema.validate(key);\n if (!keyResult.valid) {\n allValid = false;\n const keyErrors =\n keyResult.errors && keyResult.errors.length > 0\n ? keyResult.errors\n : [{ message: `key \"${key}\" is invalid` }];\n nestedKeyResults.set(key, {\n valid: false,\n errors: keyErrors\n });\n allErrors.push(...keyErrors);\n if (!doNotStop) break;\n continue;\n }\n\n const valueResult = this.#valueSchema.validate(\n objToValidate[key],\n doNotStop ? { doNotStopOnFirstError: true } : undefined\n );\n nestedKeyResults.set(key, valueResult as any);\n\n if (!valueResult.valid) {\n allValid = false;\n const valueErrors =\n valueResult.errors && valueResult.errors.length > 0\n ? valueResult.errors\n : [{ message: `value for key \"${key}\" is invalid` }];\n allErrors.push(...valueErrors);\n if (!doNotStop) break;\n } else {\n result[key] = valueResult.object;\n }\n }\n\n return this.#buildEntryResult(\n allValid,\n allErrors,\n result,\n doNotStop,\n getNestedErrors,\n getErrorsFor\n );\n }\n\n /**\n * Performs async validation of the record schema.\n *\n * Supports async preprocessors, validators, and error message providers.\n *\n * @param object - the value to validate\n * @param context - optional `ValidationContext` settings\n */\n protected async _validateAsync(\n object: TResult,\n context?: ValidationContext\n ): Promise<RecordSchemaValidationResult<TResult, TValueSchema>> {\n const setup = this.#createValidationSetup(\n object,\n await this.preValidateAsync(object, context)\n );\n if (setup.earlyReturn) return setup.result;\n\n const {\n objToValidate,\n nestedKeyResults,\n getNestedErrors,\n getErrorsFor\n } = setup;\n const doNotStop = context?.doNotStopOnFirstError ?? false;\n let allValid = true;\n const result: Record<string, any> = {};\n const allErrors: ValidationError[] = [];\n\n for (const key of Object.keys(objToValidate)) {\n const keyResult = await this.#keySchema.validateAsync(key);\n if (!keyResult.valid) {\n allValid = false;\n const keyErrors =\n keyResult.errors && keyResult.errors.length > 0\n ? keyResult.errors\n : [{ message: `key \"${key}\" is invalid` }];\n nestedKeyResults.set(key, {\n valid: false,\n errors: keyErrors\n });\n allErrors.push(...keyErrors);\n if (!doNotStop) break;\n continue;\n }\n\n const valueResult = await this.#valueSchema.validateAsync(\n objToValidate[key],\n doNotStop ? { doNotStopOnFirstError: true } : undefined\n );\n nestedKeyResults.set(key, valueResult as any);\n\n if (!valueResult.valid) {\n allValid = false;\n const valueErrors =\n valueResult.errors && valueResult.errors.length > 0\n ? valueResult.errors\n : [{ message: `value for key \"${key}\" is invalid` }];\n allErrors.push(...valueErrors);\n if (!doNotStop) break;\n } else {\n result[key] = valueResult.object;\n }\n }\n\n return this.#buildEntryResult(\n allValid,\n allErrors,\n result,\n doNotStop,\n getNestedErrors,\n getErrorsFor\n );\n }\n\n /**\n * @hidden\n */\n public nullable(): RecordSchemaBuilder<\n TKeySchema,\n TValueSchema,\n TRequired,\n true,\n TExplicitType,\n THasDefault,\n TExtensions\n > &\n TExtensions {\n return super.nullable() as any;\n }\n\n /**\n * @hidden\n */\n public notNullable(): RecordSchemaBuilder<\n TKeySchema,\n TValueSchema,\n TRequired,\n false,\n TExplicitType,\n THasDefault,\n TExtensions\n > &\n TExtensions {\n return super.notNullable() as any;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Factory function\n// ---------------------------------------------------------------------------\n\n/**\n * Creates a schema for objects with dynamic string keys, where every key\n * must satisfy `keySchema` and every value must satisfy `valueSchema`.\n *\n * The inferred TypeScript type is `Record<K, V>` where `K` is derived from\n * `keySchema` and `V` from `valueSchema`.\n *\n * @param keySchema - a `StringSchemaBuilder` that each key must satisfy\n * @param valueSchema - a `SchemaBuilder` that each value must satisfy\n *\n * @example\n * ```ts\n * import { record, string, number } from '@cleverbrush/schema';\n *\n * // Look-up table: string keys → number scores\n * const scores = record(string(), number().min(0).max(100));\n * // InferType<typeof scores> → Record<string, number>\n *\n * scores.validate({ alice: 95, bob: 87 }); // { valid: true }\n * scores.validate({ alice: 95, bob: -1 }); // { valid: false }\n * ```\n *\n * @example\n * ```ts\n * // i18n bundle: locale code keys → non-empty strings\n * const bundle = record(\n * string().matches(/^[a-z]{2}(-[A-Z]{2})?$/),\n * string().nonempty()\n * );\n *\n * bundle.validate({ en: 'Hello', 'fr-FR': 'Bonjour' }); // valid\n * bundle.validate({ en: '' }); // invalid (empty value)\n * bundle.validate({ '123': 'hi' }); // invalid (bad key)\n * ```\n *\n * @example\n * ```ts\n * // Optional record with a factory default\n * const cache = record(string(), number())\n * .optional()\n * .default(() => ({}));\n * ```\n *\n * @example\n * ```ts\n * // Nested record — values are objects\n * import { record, string, object, number } from '@cleverbrush/schema';\n *\n * const userMap = record(\n * string(),\n * object({ name: string(), age: number() })\n * );\n * ```\n */\nexport function record<\n TKeySchema extends StringSchemaBuilder<any, any, any, any>,\n TValueSchema extends SchemaBuilder<any, any, any, any, any>\n>(\n keySchema: TKeySchema,\n valueSchema: TValueSchema\n): RecordSchemaBuilder<TKeySchema, TValueSchema> {\n return RecordSchemaBuilder.create({\n type: 'record',\n keySchema,\n valueSchema\n } as any) as any;\n}\n"],"mappings":"wCAmOO,IAAMA,EAAN,MAAMC,UAWHC,CAMR,CAaEC,GACAC,GAKA,OAAc,OAAOC,EAAsD,CACvE,OAAO,IAAIJ,EAAoB,CAC3B,KAAM,SACN,GAAGI,CACP,CAAQ,CACZ,CAEU,YACNA,EAKF,CACE,MAAMA,CAAY,EAEdA,EAAM,qBAAqBH,IAC3B,KAAKC,GAAaE,EAAM,WAExBA,EAAM,uBAAuBH,IAC7B,KAAKE,GAAeC,EAAM,YAElC,CAKO,QACHC,EAUY,CACZ,OAAO,KAAK,OACR,CACI,GAAG,KAAK,WAAW,CACvB,EACA,EACJ,CACJ,CAKO,cASS,CACZ,OAAO,KAAK,OACR,CACI,GAAG,KAAK,WAAW,CACvB,EACA,EACJ,CACJ,CAKU,gBACND,EACI,CACJ,OAAOJ,EAAoB,OAAOI,CAAY,CAClD,CAKO,SACHE,EAUY,CACZ,OAAO,MAAM,SAASA,CAAY,CACtC,CAKO,UASS,CACZ,OAAO,MAAM,SAAS,CAC1B,CAKO,QACHC,EAUY,CACZ,OAAO,MAAM,QAAQA,CAAK,CAC9B,CAKO,cASS,CACZ,OAAO,MAAM,aAAa,CAC9B,CAKO,MACHC,EAUY,CACZ,OAAO,MAAM,MAAMA,CAAK,CAC5B,CAKO,YAAa,CAChB,MAAO,CACH,GAAG,MAAM,WAAW,EAIpB,UAAW,KAAKN,GAIhB,YAAa,KAAKC,EACtB,CACJ,CAMAM,GACIC,EACyD,CACzD,IAAMC,EAA6C,CAAC,EACpD,OAAW,CAACC,EAAGC,CAAC,IAAKH,EACjBC,EAAIC,CAAC,EAAIC,EAEb,OAAOF,CACX,CAOAG,GACIC,EACAC,EACAC,EACgD,CAChD,IAAMC,EAAc,KAAKf,GACzB,MAAO,CACH,OAAQa,EACR,QAASA,EAAO,SAAW,EAC3B,UACIC,IAAe,MAAQ,OAAOA,GAAe,SACtCA,EAAm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EAAW,KACpB,CAGJ,CAEA,OAAO,KAAKJ,GACRC,EACAC,EACAC,EACAC,EACAV,EACAC,CACJ,CACJ,CAKO,UASS,CACZ,OAAO,MAAM,SAAS,CAC1B,CAKO,aASS,CACZ,OAAO,MAAM,YAAY,CAC7B,CACJ,EA4DO,SAASqB,EAIZC,EACAhC,EAC6C,CAC7C,OAAOnB,EAAoB,OAAO,CAC9B,KAAM,SACN,UAAAmD,EACA,YAAAhC,CACJ,CAAQ,CACZ","names":["RecordSchemaBuilder","_RecordSchemaBuilder","SchemaBuilder","#keySchema","#valueSchema","props","_notUsed","errorMessage","value","_name","#buildNestedErrors","keyResults","out","k","v","#makeKeyResult","key","errors","rootObject","valueSchema","obj","val","#createValidationSetup","object","superResult","valid","rootErrorMsgs","nestedKeyResults","getNestedErrors","getErrorsFor","nestedResult","errMsgs","e","objToValidate","#buildEntryResult","allValid","allErrors","result","doNotStop","context","capturedObj","#validateFull","firstError","keyResult","keyErrors","valueResult","valErrors","capturedInput","setup","valueErrors","record","keySchema"]}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a as m}from"./chunk-
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import{a as m}from"./chunk-JEBLDVKG.js";import{c as f,f as S}from"./chunk-2BKBVVZ3.js";function x(o){return o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function P(o,e){let r=o;for(let a of e.split(".")){if(r==null)return;r=r[a]}return r}function b(o){let e=[];function r(a){return new Proxy(a,{get(t,s){if(s===f)return t[f];if(typeof s!="string")return t[s];let l=t[s];return typeof l!="object"||l===null?l:(e.push(s),r(l))}})}return{proxy:r(o),getPath:()=>e}}var R=class o extends S{#n;#e;#t=null;static create(e){return new o({type:"parseString",...e})}constructor(e){super(e),this.#n=e.objectSchema,this.#e=e.templateDefinition}#s(){if(this.#t)return this.#t;let{literals:e,segments:r}=this.#e,a="^";for(let t=0;t<r.length;t++){a+=x(e[t]);let s=t===r.length-1,l=e[t+1]??"";a+=s&&l===""?"(.*)":"(.*?)"}return a+=x(e[r.length]??""),a+="$",this.#t=new RegExp(a),this.#t}#r(){let{literals:e,segments:r}=this.#e,a="";for(let t=0;t<r.length;t++)a+=e[t]+`{${r[t].path}}`;return a+=e[r.length]??"",a}get template(){return this.#r()}introspect(){return{...super.introspect(),objectSchema:this.#n,templateDefinition:this.#e}}serialize(e){let{literals:r,segments:a}=this.#e,t="";for(let s=0;s<a.length;s++){t+=r[s];let l=a[s].path,d=P(e,l);if(d==null)throw new Error(`Missing required parameter "${l}" for template ${this.#r()}`);t+=String(d)}return t+=r[a.length]??"",t}validate(e,r){return super.validate(e,r)}async validateAsync(e,r){return super.validateAsync(e,r)}_validate(e,r){return typeof e>"u"||e===null?typeof e>"u"&&this.hasDefault?(e=this.resolveDefaultValue(),{valid:!0,object:e}):!this.isRequired||e===null&&this.isNullable?{valid:!0,object:e}:{valid:!1,errors:[{message:this.getValidationErrorMessageSync(this.requiredErrorMessage,e)}]}:this.#a(e,r,(a,t)=>a.validate(t))}async _validateAsync(e,r){return typeof e>"u"||e===null?typeof e>"u"&&this.hasDefault?(e=this.resolveDefaultValue(),{valid:!0,object:e}):!this.isRequired||e===null&&this.isNullable?{valid:!0,object:e}:{valid:!1,errors:[{message:await this.getValidationErrorMessage(this.requiredErrorMessage,e)}]}:this.#a(e,r,(a,t)=>a.validateAsync(t))}#a(e,r,a){if(typeof e!="string")return{valid:!1,errors:[{message:`expected a string to parse, but saw ${typeof e}`}]};let{segments:t}=this.#e;if(t.length===0){let n=this.#e.literals[0]??"";return e!==n?{valid:!1,errors:[{message:`expected "${n}" but saw "${e}"`}]}:{valid:!0,object:{}}}let l=this.#s().exec(e);if(!l)return{valid:!1,errors:[{message:`does not match the parse-string pattern ${this.#r()}`}]};let d=r?.doNotStopOnFirstError??!1,p=new Proxy([],{get:(n,u,c)=>{if(u==="length")return t.length;let i=typeof u=="string"?Number(u):Number.NaN;return Number.isInteger(i)&&i>=0&&i<t.length?(i in n||(n[i]=a(t[i].schema,l[i+1])),n[i]):Reflect.get(n,u,c)}});if(d)for(let n=0;n<t.length;n++)p[n];let g=p[0];if(g&&typeof g.then=="function")return(async()=>{let n=[],u={};for(let c=0;c<t.length;c++){let i=await p[c];if(!i.valid){let h=i.errors?.[0]?.message??"validation failed";if(n.push({message:`${t[c].path}: ${h}`}),!d)return{valid:!1,errors:n};continue}t[c].descriptor.setValue(u,i.object,{createMissingStructure:!0})}return n.length>0?{valid:!1,errors:n}:{valid:!0,object:u}})();let y=[],T={};for(let n=0;n<t.length;n++){let u=p[n];if(!u.valid){let c=u.errors?.[0]?.message??"validation failed";if(y.push({message:`${t[n].path}: ${c}`}),!d)return{valid:!1,errors:y};continue}t[n].descriptor.setValue(T,u.object,{createMissingStructure:!0})}return y.length>0?{valid:!1,errors:y}:{valid:!0,object:T}}hasType(e){return this.derive({...this.introspect()},!0)}clearHasType(){return this.derive({...this.introspect()},!0)}nullable(){return super.nullable()}notNullable(){return super.notNullable()}required(e){return super.required(e)}optional(){return super.optional()}default(e){return super.default(e)}clearDefault(){return super.clearDefault()}brand(e){return super.brand(e)}readonly(){return super.readonly()}createFromProps(e){return o.create(e)}};function v(o,e){if(!(o instanceof m))throw new Error("First argument must be an ObjectSchemaBuilder instance");let r=m.getPropertiesFor(o),t=e(((s,...l)=>{let d=new Set,p=[];for(let g of l){if(typeof g!="function")throw new Error("Template expressions must be property selector functions (e.g. t => t.id)");let{proxy:y,getPath:T}=b(r),n=g(y);if(!n||typeof n!="object"||!(f in n))throw new Error("Template expression must select a property from the schema (e.g. t => t.id)");let u=n[f],c=u.getSchema(),i=T();if(i.length===0)throw new Error("Template expression must select a specific property (e.g. t => t.id), not the root object");let h=i.join(".");if(d.has(h))throw new Error(`Duplicate template parameter: "${h}" is already used in this template`);d.add(h),p.push({schema:c,path:h,descriptor:u})}return{literals:[...s],segments:p}}));return R.create({isRequired:!0,objectSchema:o,templateDefinition:t})}export{R as a,v as b};
|
|
2
|
+
//# sourceMappingURL=chunk-X6CT6I2V.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/builders/ParseStringSchemaBuilder.ts"],"sourcesContent":["import { ObjectSchemaBuilder } from './ObjectSchemaBuilder.js';\nimport {\n type BRAND,\n type InferType,\n type PropertyDescriptor,\n type PropertyDescriptorInner,\n type PropertyDescriptorTree,\n SchemaBuilder,\n SYMBOL_SCHEMA_PROPERTY_DESCRIPTOR,\n type ValidationContext,\n type ValidationErrorMessageProvider,\n type ValidationResult\n} from './SchemaBuilder.js';\n\n// ---------------------------------------------------------------------------\n// Internal types\n// ---------------------------------------------------------------------------\n\n/** Descriptor for a single interpolation segment captured at creation time. */\ntype SegmentDef = {\n /** The property schema for this segment. */\n schema: SchemaBuilder<any, any, any, any, any>;\n /** Dot-separated property path (e.g. `'order.id'`) — used in error messages. */\n path: string;\n /** The property descriptor inner — used to set parsed values on the result object. */\n descriptor: PropertyDescriptorInner<any, any, any>;\n};\n\n/** Internal data captured by the `$template` tagged-template invocation. */\ntype ParseStringTemplateDefinition = {\n /** Literal string fragments from the tagged template. */\n literals: readonly string[];\n /** One segment per interpolation expression, in order. */\n segments: readonly SegmentDef[];\n};\n\n// ---------------------------------------------------------------------------\n// Public types\n// ---------------------------------------------------------------------------\n\n/**\n * The typed tagged-template function passed to the `parseString`\n * callback. Template expressions must be property-selector lambdas that\n * navigate the {@link PropertyDescriptorTree} of the object schema.\n *\n * Only properties whose inferred type extends `string | number | boolean | Date`\n * are selectable — nested `ObjectSchemaBuilder` children are navigable but\n * not themselves endpoints.\n */\nexport type ParseStringTemplateTag<\n TSchema extends ObjectSchemaBuilder<any, any, any, any, any, any, any>\n> = (\n strings: TemplateStringsArray,\n ...selectors: Array<\n (\n tree: PropertyDescriptorTree<\n TSchema,\n TSchema,\n string | number | boolean | Date\n >\n ) => PropertyDescriptor<TSchema, any, any>\n >\n) => ParseStringTemplateDefinition;\n\ntype ParseStringSchemaBuilderCreateProps<\n T = any,\n R extends boolean = true\n> = Partial<ReturnType<ParseStringSchemaBuilder<T, R>['introspect']>>;\n\n// ---------------------------------------------------------------------------\n// Regex helper\n// ---------------------------------------------------------------------------\n\n/** Escapes characters that have special meaning in a regular expression. */\nfunction escapeRegex(s: string): string {\n return s.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n}\n\n/**\n * Resolves a dot-separated property path on a (possibly nested) object.\n *\n * For flat paths like `'id'` this is equivalent to `obj['id']`.\n * For nested paths like `'order.id'` it traverses `obj.order.id`.\n */\nfunction resolvePath(obj: any, path: string): unknown {\n let current: any = obj;\n for (const part of path.split('.')) {\n if (current == null) return undefined;\n current = current[part];\n }\n return current;\n}\n\n// ---------------------------------------------------------------------------\n// Path-tracking Proxy (used at schema creation time)\n// ---------------------------------------------------------------------------\n\n/**\n * Wraps a `PropertyDescriptorTree` in a Proxy that records the traversed\n * property path. When the result is accessed via\n * `SYMBOL_SCHEMA_PROPERTY_DESCRIPTOR` we know we've reached a leaf, so we\n * return the real descriptor. All other property accesses are captured as\n * path segments and the proxy recurses.\n *\n * @returns A proxy that looks identical to the tree from TypeScript's\n * perspective but captures `[propName, propName, …]` as the user\n * navigates via `t => t.order.id`.\n */\nfunction createPathTrackingProxy(tree: any): {\n proxy: any;\n getPath: () => string[];\n} {\n // Shared mutable array — child proxy pushes propagate to parent's getPath\n const pathSegments: string[] = [];\n\n function wrapProxy(target: any): any {\n return new Proxy(target, {\n get(t, prop) {\n // Property descriptor access — return real descriptor\n if (prop === SYMBOL_SCHEMA_PROPERTY_DESCRIPTOR) {\n return t[SYMBOL_SCHEMA_PROPERTY_DESCRIPTOR];\n }\n\n // Symbol / non-string — pass through\n if (typeof prop !== 'string') {\n return t[prop];\n }\n\n const child = t[prop];\n if (typeof child !== 'object' || child === null) {\n return child;\n }\n\n // Record this segment and recurse\n pathSegments.push(prop);\n return wrapProxy(child);\n }\n });\n }\n\n return {\n proxy: wrapProxy(tree),\n getPath: () => pathSegments\n };\n}\n\n// ---------------------------------------------------------------------------\n// Builder\n// ---------------------------------------------------------------------------\n\n/**\n * Validates a string against a template pattern and parses it\n * into a strongly-typed object.\n *\n * Created via the {@link parseString} factory:\n *\n * ```ts\n * const RouteSchema = parseString(\n * object({ userId: string().uuid(), id: number() }),\n * $t => $t`/orders/${t => t.id}/${t => t.userId}`\n * );\n *\n * const result = RouteSchema.validate('/orders/42/550e8400-...');\n * // result.object === { id: 42, userId: '550e8400-...' }\n * ```\n *\n * @see {@link parseString}\n */\nexport class ParseStringSchemaBuilder<\n TResult = any,\n TRequired extends boolean = true,\n TNullable extends boolean = false,\n THasDefault extends boolean = false,\n TExtensions = {}\n> extends SchemaBuilder<\n TResult,\n TRequired,\n TNullable,\n THasDefault,\n TExtensions\n> {\n #objectSchema: ObjectSchemaBuilder<any, any, any, any, any, any, any>;\n #templateDef: ParseStringTemplateDefinition;\n #compiledRegex: RegExp | null = null;\n\n /**\n * @hidden\n */\n public static create(props: ParseStringSchemaBuilderCreateProps) {\n return new ParseStringSchemaBuilder({\n type: 'parseString',\n ...props\n });\n }\n\n protected constructor(props: ParseStringSchemaBuilderCreateProps) {\n super(props as any);\n\n this.#objectSchema = props.objectSchema!;\n this.#templateDef = props.templateDefinition!;\n }\n\n // -- Regex ---------------------------------------------------------------\n\n #buildRegex(): RegExp {\n if (this.#compiledRegex) return this.#compiledRegex;\n const { literals, segments } = this.#templateDef;\n let pattern = '^';\n for (let i = 0; i < segments.length; i++) {\n pattern += escapeRegex(literals[i]);\n // Use non-greedy unless this is the last capture AND the\n // trailing literal is empty (nothing to anchor to).\n const isLast = i === segments.length - 1;\n const trailingLiteral = literals[i + 1] ?? '';\n pattern += isLast && trailingLiteral === '' ? '(.*)' : '(.*?)';\n }\n // Append the trailing literal (after all segments)\n pattern += escapeRegex(literals[segments.length] ?? '');\n pattern += '$';\n this.#compiledRegex = new RegExp(pattern);\n return this.#compiledRegex;\n }\n\n /** Builds a human-readable pattern like `/orders/{id}/{userId}` for error messages. */\n #humanPattern(): string {\n const { literals, segments } = this.#templateDef;\n let result = '';\n for (let i = 0; i < segments.length; i++) {\n result += literals[i] + `{${segments[i].path}}`;\n }\n result += literals[segments.length] ?? '';\n return result;\n }\n\n /**\n * The human-readable message template pattern with `{property}` holes,\n * e.g. `\"Todo created: #{TodoId} \\\"{Title}\\\" by user {UserId}\"`.\n *\n * Useful for structured logging — pass this as the log `messageTemplate`\n * so events with the same shape can be grouped, and pass\n * `serialize(params)` as the rendered message.\n */\n get template(): string {\n return this.#humanPattern();\n }\n\n // -- Introspect ----------------------------------------------------------\n\n /**\n * Return a snapshot of this builder's configuration.\n *\n * Includes all base-class fields plus:\n * - `objectSchema` — the object schema defining the result shape.\n * - `templateDefinition` — the parsed template (literals and selector segments).\n */\n public introspect() {\n return {\n ...super.introspect(),\n /** The object schema defining the result shape. */\n objectSchema: this.#objectSchema,\n /** The template definition (literals + segments). */\n templateDefinition: this.#templateDef\n };\n }\n\n // -- Serialize -----------------------------------------------------------\n\n /**\n * Builds a string from the template by substituting parameter values.\n *\n * This is the reverse of {@link validate}: where `validate` parses a\n * string into a typed object, `serialize` takes a params object and\n * produces the string.\n *\n * @param params - An object matching the template's parsed result type.\n * Nested properties are resolved via dot-paths (e.g. `order.id`).\n * Values are coerced to strings via `String()`.\n * @returns The reconstructed string with all segments replaced.\n * @throws {Error} If a required parameter is missing (`undefined`).\n *\n * @example\n * ```ts\n * const Route = parseString(\n * object({ id: number().coerce() }),\n * $t => $t`/todos/${t => t.id}`\n * );\n *\n * Route.serialize({ id: 42 }); // '/todos/42'\n * ```\n */\n public serialize(params: TResult): string {\n const { literals, segments } = this.#templateDef;\n let result = '';\n for (let i = 0; i < segments.length; i++) {\n result += literals[i];\n const key = segments[i].path;\n const value = resolvePath(params, key);\n if (value === undefined || value === null) {\n throw new Error(\n `Missing required parameter \"${key}\" for template ${this.#humanPattern()}`\n );\n }\n result += String(value);\n }\n result += literals[segments.length] ?? '';\n return result;\n }\n\n // -- Validate (sync) -----------------------------------------------------\n\n /** {@inheritDoc SchemaBuilder.validate} */\n public validate(\n object: string,\n context?: ValidationContext\n ): ValidationResult<TResult> {\n return super.validate(object, context) as ValidationResult<TResult>;\n }\n\n /** {@inheritDoc SchemaBuilder.validateAsync} */\n public async validateAsync(\n object: string,\n context?: ValidationContext\n ): Promise<ValidationResult<TResult>> {\n return super.validateAsync(object, context) as Promise<\n ValidationResult<TResult>\n >;\n }\n\n protected _validate(\n object: any,\n context?: ValidationContext\n ): ValidationResult<TResult> {\n // Handle optional / nullable / default at the top\n if (typeof object === 'undefined' || object === null) {\n if (typeof object === 'undefined' && this.hasDefault) {\n object = this.resolveDefaultValue();\n return { valid: true, object: object as TResult };\n }\n if (!this.isRequired || (object === null && this.isNullable)) {\n return { valid: true, object: object as any };\n }\n return {\n valid: false,\n errors: [\n {\n message: this.getValidationErrorMessageSync(\n this.requiredErrorMessage,\n object\n )\n }\n ]\n };\n }\n\n return this.#matchAndValidate(object, context, (schema, raw) =>\n schema.validate(raw)\n );\n }\n\n // -- Validate (async) ----------------------------------------------------\n\n protected async _validateAsync(\n object: any,\n context?: ValidationContext\n ): Promise<ValidationResult<TResult>> {\n // Handle optional / nullable / default\n if (typeof object === 'undefined' || object === null) {\n if (typeof object === 'undefined' && this.hasDefault) {\n object = this.resolveDefaultValue();\n return { valid: true, object: object as TResult };\n }\n if (!this.isRequired || (object === null && this.isNullable)) {\n return { valid: true, object: object as any };\n }\n return {\n valid: false,\n errors: [\n {\n message: await this.getValidationErrorMessage(\n this.requiredErrorMessage,\n object\n )\n }\n ]\n };\n }\n\n return this.#matchAndValidate(object, context, (schema, raw) =>\n schema.validateAsync(raw)\n );\n }\n\n /**\n * Shared regex-match + per-segment validation logic used by both\n * `_validate` (sync) and `_validateAsync` (async).\n *\n * The caller supplies `validateSegment` which is either the sync\n * `schema.validate` or async `schema.validateAsync`.\n */\n #matchAndValidate<\n R extends ValidationResult<unknown> | Promise<ValidationResult<unknown>>\n >(\n object: any,\n context: ValidationContext | undefined,\n validateSegment: (\n schema: SchemaBuilder<any, any, any, any, any>,\n raw: string\n ) => R\n ): R extends Promise<any>\n ? Promise<ValidationResult<TResult>>\n : ValidationResult<TResult> {\n if (typeof object !== 'string') {\n return {\n valid: false,\n errors: [\n {\n message: `expected a string to parse, but saw ${typeof object}`\n }\n ]\n } as any;\n }\n\n const { segments } = this.#templateDef;\n\n // Degenerate case: no segments — just compare literals\n if (segments.length === 0) {\n const expected = this.#templateDef.literals[0] ?? '';\n if (object !== expected) {\n return {\n valid: false,\n errors: [\n {\n message: `expected \"${expected}\" but saw \"${object}\"`\n }\n ]\n } as any;\n }\n return { valid: true, object: {} as TResult } as any;\n }\n\n const regex = this.#buildRegex();\n const match = regex.exec(object);\n\n if (!match) {\n return {\n valid: false,\n errors: [\n {\n message: `does not match the parse-string pattern ${this.#humanPattern()}`\n }\n ]\n } as any;\n }\n\n const doNotStop = context?.doNotStopOnFirstError ?? false;\n\n // Compute segment validation results lazily so fail-fast mode can\n // short-circuit without eagerly validating later segments. When\n // doNotStopOnFirstError is enabled, prestart all validations to\n // preserve the existing eager/parallel behavior.\n const segResults = new Proxy([] as R[], {\n get: (target, prop, receiver) => {\n if (prop === 'length') return segments.length;\n\n const index =\n typeof prop === 'string' ? Number(prop) : Number.NaN;\n if (\n Number.isInteger(index) &&\n index >= 0 &&\n index < segments.length\n ) {\n if (!(index in target)) {\n target[index] = validateSegment(\n segments[index].schema,\n match[index + 1]\n );\n }\n return target[index];\n }\n\n return Reflect.get(target, prop, receiver);\n }\n }) as R[];\n\n if (doNotStop) {\n for (let i = 0; i < segments.length; i++) {\n void segResults[i];\n }\n }\n\n // If first result is a promise, the whole pipeline is async\n const firstResult = segResults[0];\n if (firstResult && typeof (firstResult as any).then === 'function') {\n return (async () => {\n const errors: { message: string }[] = [];\n const resultObj = {} as any;\n for (let i = 0; i < segments.length; i++) {\n const segResult = (await segResults[\n i\n ]) as ValidationResult<unknown>;\n if (!segResult.valid) {\n const inner =\n segResult.errors?.[0]?.message ??\n 'validation failed';\n errors.push({\n message: `${segments[i].path}: ${inner}`\n });\n if (!doNotStop) return { valid: false, errors };\n continue;\n }\n segments[i].descriptor.setValue(\n resultObj,\n segResult.object,\n { createMissingStructure: true }\n );\n }\n if (errors.length > 0) return { valid: false, errors };\n return { valid: true, object: resultObj as TResult };\n })() as any;\n }\n\n // Sync path\n const errors: { message: string }[] = [];\n const resultObj = {} as any;\n for (let i = 0; i < segments.length; i++) {\n const segResult = segResults[i] as ValidationResult<unknown>;\n if (!segResult.valid) {\n const inner =\n segResult.errors?.[0]?.message ?? 'validation failed';\n errors.push({\n message: `${segments[i].path}: ${inner}`\n });\n if (!doNotStop) return { valid: false, errors } as any;\n continue;\n }\n segments[i].descriptor.setValue(resultObj, segResult.object, {\n createMissingStructure: true\n });\n }\n if (errors.length > 0) return { valid: false, errors } as any;\n return { valid: true, object: resultObj as TResult } as any;\n }\n\n // -- Fluent overrides (return type narrowing) ----------------------------\n\n /**\n * @inheritdoc\n */\n public hasType<T>(\n _notUsed?: T\n ): ParseStringSchemaBuilder<T, true, TNullable, THasDefault, TExtensions> &\n TExtensions {\n return this.createFromProps({\n ...this.introspect()\n } as any) as any;\n }\n\n /**\n * @inheritdoc\n */\n public clearHasType(): ParseStringSchemaBuilder<\n any,\n TRequired,\n TNullable,\n THasDefault,\n TExtensions\n > &\n TExtensions {\n return this.createFromProps({\n ...this.introspect()\n } as any) as any;\n }\n\n /**\n * @hidden\n */\n public nullable(): ParseStringSchemaBuilder<\n TResult,\n TRequired,\n true,\n THasDefault,\n TExtensions\n > &\n TExtensions {\n return super.nullable() as any;\n }\n\n /**\n * @hidden\n */\n public notNullable(): ParseStringSchemaBuilder<\n TResult,\n TRequired,\n false,\n THasDefault,\n TExtensions\n > &\n TExtensions {\n return super.notNullable() as any;\n }\n\n /**\n * @hidden\n */\n public required(\n errorMessage?: ValidationErrorMessageProvider\n ): ParseStringSchemaBuilder<\n TResult,\n true,\n TNullable,\n THasDefault,\n TExtensions\n > &\n TExtensions {\n return super.required(errorMessage);\n }\n\n /**\n * @hidden\n */\n public optional(): ParseStringSchemaBuilder<\n TResult,\n false,\n TNullable,\n THasDefault,\n TExtensions\n > &\n TExtensions {\n return super.optional();\n }\n\n /**\n * @hidden\n */\n public default(\n value: TResult | (() => TResult)\n ): ParseStringSchemaBuilder<TResult, true, TNullable, true, TExtensions> &\n TExtensions {\n return super.default(value) as any;\n }\n\n /**\n * @hidden\n */\n public clearDefault(): ParseStringSchemaBuilder<\n TResult,\n TRequired,\n TNullable,\n false,\n TExtensions\n > &\n TExtensions {\n return super.clearDefault() as any;\n }\n\n /**\n * @hidden\n */\n public brand<TBrand extends string | symbol>(\n _name?: TBrand\n ): ParseStringSchemaBuilder<\n TResult & { readonly [K in BRAND]: TBrand },\n TRequired,\n TNullable,\n THasDefault,\n TExtensions\n > &\n TExtensions {\n return super.brand(_name);\n }\n\n /**\n * @hidden\n */\n public readonly(): ParseStringSchemaBuilder<\n Readonly<TResult>,\n TRequired,\n TNullable,\n THasDefault,\n TExtensions\n > &\n TExtensions {\n return super.readonly();\n }\n\n protected createFromProps<T, TReq extends boolean>(\n props: ParseStringSchemaBuilderCreateProps<T, TReq>\n ): this {\n return ParseStringSchemaBuilder.create(props as any) as any;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Factory\n// ---------------------------------------------------------------------------\n\n/**\n * Creates a parse-string schema that validates a string against a\n * template pattern and parses it into a strongly-typed object.\n *\n * The first argument defines the result shape via `object(...)`, and the\n * second argument is a callback receiving a typed `$template` tagged-template\n * function whose template expressions are type-safe property selectors.\n *\n * @example\n * ```ts\n * const RouteSchema = parseString(\n * object({\n * userId: string().uuid(),\n * id: number()\n * }),\n * $t => $t`/orders/${t => t.id}/${t => t.userId}`\n * );\n *\n * const result = RouteSchema.validate('/orders/42/550e8400-e29b-41d4-a716-446655440000');\n * // result.valid === true\n * // result.object === { id: 42, userId: '550e8400-e29b-41d4-a716-446655440000' }\n *\n * type Route = InferType<typeof RouteSchema>;\n * // { id: number; userId: string }\n * ```\n *\n * @example Nested objects\n * ```ts\n * const schema = parseString(\n * object({\n * order: object({ id: number() }),\n * user: object({ name: string() })\n * }),\n * $t => $t`/orders/${t => t.order.id}/by/${t => t.user.name}`\n * );\n * ```\n *\n * @param objectSchema - An `ObjectSchemaBuilder` defining the result type and\n * per-property validation schemas.\n * @param templateBuilder - Callback receiving the typed `$template`\n * tagged-template function. Must return the result of invoking `$template`.\n * @returns A `ParseStringSchemaBuilder` whose `validate()` accepts a\n * string and whose `InferType` is the object schema's inferred type.\n */\nexport function parseString<\n TSchema extends ObjectSchemaBuilder<any, any, any, any, any, any, any>\n>(\n objectSchema: TSchema,\n templateBuilder: (\n $template: ParseStringTemplateTag<TSchema>\n ) => ParseStringTemplateDefinition\n): ParseStringSchemaBuilder<InferType<TSchema>> {\n if (!(objectSchema instanceof ObjectSchemaBuilder)) {\n throw new Error(\n 'First argument must be an ObjectSchemaBuilder instance'\n );\n }\n\n // Get the PropertyDescriptorTree for the object schema\n const tree = ObjectSchemaBuilder.getPropertiesFor(objectSchema as any);\n\n // Build the $template tagged-template function\n const $template = ((\n strings: TemplateStringsArray,\n ...selectors: Array<(t: any) => any>\n ): ParseStringTemplateDefinition => {\n const seenPaths = new Set<string>();\n const segments: SegmentDef[] = [];\n\n for (const selector of selectors) {\n if (typeof selector !== 'function') {\n throw new Error(\n 'Template expressions must be property selector functions (e.g. t => t.id)'\n );\n }\n\n // Create a path-tracking proxy for this selector invocation\n const { proxy, getPath } = createPathTrackingProxy(tree);\n const descriptor = selector(proxy);\n\n if (\n !descriptor ||\n typeof descriptor !== 'object' ||\n !(SYMBOL_SCHEMA_PROPERTY_DESCRIPTOR in descriptor)\n ) {\n throw new Error(\n 'Template expression must select a property from the schema (e.g. t => t.id)'\n );\n }\n\n const inner: PropertyDescriptorInner<any, any, any> =\n descriptor[SYMBOL_SCHEMA_PROPERTY_DESCRIPTOR];\n const schema = inner.getSchema();\n const path = getPath();\n\n if (path.length === 0) {\n throw new Error(\n 'Template expression must select a specific property (e.g. t => t.id), not the root object'\n );\n }\n\n const pathStr = path.join('.');\n\n if (seenPaths.has(pathStr)) {\n throw new Error(\n `Duplicate template parameter: \"${pathStr}\" is already used in this template`\n );\n }\n seenPaths.add(pathStr);\n\n segments.push({\n schema,\n path: pathStr,\n descriptor: inner\n });\n }\n\n return {\n literals: [...strings],\n segments\n };\n }) as ParseStringTemplateTag<TSchema>;\n\n const templateDef = templateBuilder($template);\n\n return ParseStringSchemaBuilder.create({\n isRequired: true,\n objectSchema: objectSchema as any,\n templateDefinition: templateDef\n }) as any;\n}\n"],"mappings":"uFA0EA,SAASA,EAAYC,EAAmB,CACpC,OAAOA,EAAE,QAAQ,sBAAuB,MAAM,CAClD,CAQA,SAASC,EAAYC,EAAUC,EAAuB,CAClD,IAAIC,EAAeF,EACnB,QAAWG,KAAQF,EAAK,MAAM,GAAG,EAAG,CAChC,GAAIC,GAAW,KAAM,OACrBA,EAAUA,EAAQC,CAAI,CAC1B,CACA,OAAOD,CACX,CAiBA,SAASE,EAAwBC,EAG/B,CAEE,IAAMC,EAAyB,CAAC,EAEhC,SAASC,EAAUC,EAAkB,CACjC,OAAO,IAAI,MAAMA,EAAQ,CACrB,IAAI,EAAGC,EAAM,CAET,GAAIA,IAASC,EACT,OAAO,EAAEA,CAAiC,EAI9C,GAAI,OAAOD,GAAS,SAChB,OAAO,EAAEA,CAAI,EAGjB,IAAME,EAAQ,EAAEF,CAAI,EACpB,OAAI,OAAOE,GAAU,UAAYA,IAAU,KAChCA,GAIXL,EAAa,KAAKG,CAAI,EACfF,EAAUI,CAAK,EAC1B,CACJ,CAAC,CACL,CAEA,MAAO,CACH,MAAOJ,EAAUF,CAAI,EACrB,QAAS,IAAMC,CACnB,CACJ,CAwBO,IAAMM,EAAN,MAAMC,UAMHC,CAMR,CACEC,GACAC,GACAC,GAAgC,KAKhC,OAAc,OAAOC,EAA4C,CAC7D,OAAO,IAAIL,EAAyB,CAChC,KAAM,cACN,GAAGK,CAC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,IAAM8D,EAAU9D,EAAK,KAAK,GAAG,EAE7B,GAAIyD,EAAU,IAAIK,CAAO,EACrB,MAAM,IAAI,MACN,kCAAkCA,CAAO,oCAC7C,EAEJL,EAAU,IAAIK,CAAO,EAErB1C,EAAS,KAAK,CACV,OAAAa,EACA,KAAM6B,EACN,WAAYhB,CAChB,CAAC,CACL,CAEA,MAAO,CACH,SAAU,CAAC,GAAGS,CAAO,EACrB,SAAAnC,CACJ,CACJ,EAE6C,EAE7C,OAAOT,EAAyB,OAAO,CACnC,WAAY,GACZ,aAAcwC,EACd,mBAAoBG,CACxB,CAAC,CACL","names":["escapeRegex","s","resolvePath","obj","path","current","part","createPathTrackingProxy","tree","pathSegments","wrapProxy","target","prop","SYMBOL_SCHEMA_PROPERTY_DESCRIPTOR","child","ParseStringSchemaBuilder","_ParseStringSchemaBuilder","SchemaBuilder","#objectSchema","#templateDef","#compiledRegex","props","#buildRegex","literals","segments","pattern","i","isLast","trailingLiteral","#humanPattern","result","params","key","value","object","context","#matchAndValidate","schema","raw","validateSegment","expected","match","doNotStop","segResults","receiver","index","firstResult","errors","resultObj","segResult","inner","_notUsed","errorMessage","_name","parseString","objectSchema","templateBuilder","ObjectSchemaBuilder","templateDef","strings","selectors","seenPaths","selector","proxy","getPath","descriptor","pathStr"]}
|
|
1
|
+
{"version":3,"sources":["../src/builders/ParseStringSchemaBuilder.ts"],"sourcesContent":["import { ObjectSchemaBuilder } from './ObjectSchemaBuilder.js';\nimport {\n type BRAND,\n type InferType,\n type PropertyDescriptor,\n type PropertyDescriptorInner,\n type PropertyDescriptorTree,\n SchemaBuilder,\n SYMBOL_SCHEMA_PROPERTY_DESCRIPTOR,\n type ValidationContext,\n type ValidationErrorMessageProvider,\n type ValidationResult\n} from './SchemaBuilder.js';\n\n// ---------------------------------------------------------------------------\n// Internal types\n// ---------------------------------------------------------------------------\n\n/** Descriptor for a single interpolation segment captured at creation time. */\ntype SegmentDef = {\n /** The property schema for this segment. */\n schema: SchemaBuilder<any, any, any, any, any>;\n /** Dot-separated property path (e.g. `'order.id'`) — used in error messages. */\n path: string;\n /** The property descriptor inner — used to set parsed values on the result object. */\n descriptor: PropertyDescriptorInner<any, any, any>;\n};\n\n/** Internal data captured by the `$template` tagged-template invocation. */\ntype ParseStringTemplateDefinition = {\n /** Literal string fragments from the tagged template. */\n literals: readonly string[];\n /** One segment per interpolation expression, in order. */\n segments: readonly SegmentDef[];\n};\n\n// ---------------------------------------------------------------------------\n// Public types\n// ---------------------------------------------------------------------------\n\n/**\n * The typed tagged-template function passed to the `parseString`\n * callback. Template expressions must be property-selector lambdas that\n * navigate the {@link PropertyDescriptorTree} of the object schema.\n *\n * Only properties whose inferred type extends `string | number | boolean | Date`\n * are selectable — nested `ObjectSchemaBuilder` children are navigable but\n * not themselves endpoints.\n */\nexport type ParseStringTemplateTag<\n TSchema extends ObjectSchemaBuilder<any, any, any, any, any, any, any>\n> = (\n strings: TemplateStringsArray,\n ...selectors: Array<\n (\n tree: PropertyDescriptorTree<\n TSchema,\n TSchema,\n string | number | boolean | Date\n >\n ) => PropertyDescriptor<TSchema, any, any>\n >\n) => ParseStringTemplateDefinition;\n\ntype ParseStringSchemaBuilderCreateProps<\n T = any,\n R extends boolean = true\n> = Partial<ReturnType<ParseStringSchemaBuilder<T, R>['introspect']>>;\n\n// ---------------------------------------------------------------------------\n// Regex helper\n// ---------------------------------------------------------------------------\n\n/** Escapes characters that have special meaning in a regular expression. */\nfunction escapeRegex(s: string): string {\n return s.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n}\n\n/**\n * Resolves a dot-separated property path on a (possibly nested) object.\n *\n * For flat paths like `'id'` this is equivalent to `obj['id']`.\n * For nested paths like `'order.id'` it traverses `obj.order.id`.\n */\nfunction resolvePath(obj: any, path: string): unknown {\n let current: any = obj;\n for (const part of path.split('.')) {\n if (current == null) return undefined;\n current = current[part];\n }\n return current;\n}\n\n// ---------------------------------------------------------------------------\n// Path-tracking Proxy (used at schema creation time)\n// ---------------------------------------------------------------------------\n\n/**\n * Wraps a `PropertyDescriptorTree` in a Proxy that records the traversed\n * property path. When the result is accessed via\n * `SYMBOL_SCHEMA_PROPERTY_DESCRIPTOR` we know we've reached a leaf, so we\n * return the real descriptor. All other property accesses are captured as\n * path segments and the proxy recurses.\n *\n * @returns A proxy that looks identical to the tree from TypeScript's\n * perspective but captures `[propName, propName, …]` as the user\n * navigates via `t => t.order.id`.\n */\nfunction createPathTrackingProxy(tree: any): {\n proxy: any;\n getPath: () => string[];\n} {\n // Shared mutable array — child proxy pushes propagate to parent's getPath\n const pathSegments: string[] = [];\n\n function wrapProxy(target: any): any {\n return new Proxy(target, {\n get(t, prop) {\n // Property descriptor access — return real descriptor\n if (prop === SYMBOL_SCHEMA_PROPERTY_DESCRIPTOR) {\n return t[SYMBOL_SCHEMA_PROPERTY_DESCRIPTOR];\n }\n\n // Symbol / non-string — pass through\n if (typeof prop !== 'string') {\n return t[prop];\n }\n\n const child = t[prop];\n if (typeof child !== 'object' || child === null) {\n return child;\n }\n\n // Record this segment and recurse\n pathSegments.push(prop);\n return wrapProxy(child);\n }\n });\n }\n\n return {\n proxy: wrapProxy(tree),\n getPath: () => pathSegments\n };\n}\n\n// ---------------------------------------------------------------------------\n// Builder\n// ---------------------------------------------------------------------------\n\n/**\n * Validates a string against a template pattern and parses it\n * into a strongly-typed object.\n *\n * Created via the {@link parseString} factory:\n *\n * ```ts\n * const RouteSchema = parseString(\n * object({ userId: string().uuid(), id: number() }),\n * $t => $t`/orders/${t => t.id}/${t => t.userId}`\n * );\n *\n * const result = RouteSchema.validate('/orders/42/550e8400-...');\n * // result.object === { id: 42, userId: '550e8400-...' }\n * ```\n *\n * @see {@link parseString}\n */\nexport class ParseStringSchemaBuilder<\n TResult = any,\n TRequired extends boolean = true,\n TNullable extends boolean = false,\n THasDefault extends boolean = false,\n TExtensions = {}\n> extends SchemaBuilder<\n TResult,\n TRequired,\n TNullable,\n THasDefault,\n TExtensions\n> {\n #objectSchema: ObjectSchemaBuilder<any, any, any, any, any, any, any>;\n #templateDef: ParseStringTemplateDefinition;\n #compiledRegex: RegExp | null = null;\n\n /**\n * @hidden\n */\n public static create(props: ParseStringSchemaBuilderCreateProps) {\n return new ParseStringSchemaBuilder({\n type: 'parseString',\n ...props\n });\n }\n\n protected constructor(props: ParseStringSchemaBuilderCreateProps) {\n super(props as any);\n\n this.#objectSchema = props.objectSchema!;\n this.#templateDef = props.templateDefinition!;\n }\n\n // -- Regex ---------------------------------------------------------------\n\n #buildRegex(): RegExp {\n if (this.#compiledRegex) return this.#compiledRegex;\n const { literals, segments } = this.#templateDef;\n let pattern = '^';\n for (let i = 0; i < segments.length; i++) {\n pattern += escapeRegex(literals[i]);\n // Use non-greedy unless this is the last capture AND the\n // trailing literal is empty (nothing to anchor to).\n const isLast = i === segments.length - 1;\n const trailingLiteral = literals[i + 1] ?? '';\n pattern += isLast && trailingLiteral === '' ? '(.*)' : '(.*?)';\n }\n // Append the trailing literal (after all segments)\n pattern += escapeRegex(literals[segments.length] ?? '');\n pattern += '$';\n this.#compiledRegex = new RegExp(pattern);\n return this.#compiledRegex;\n }\n\n /** Builds a human-readable pattern like `/orders/{id}/{userId}` for error messages. */\n #humanPattern(): string {\n const { literals, segments } = this.#templateDef;\n let result = '';\n for (let i = 0; i < segments.length; i++) {\n result += literals[i] + `{${segments[i].path}}`;\n }\n result += literals[segments.length] ?? '';\n return result;\n }\n\n /**\n * The human-readable message template pattern with `{property}` holes,\n * e.g. `\"Todo created: #{TodoId} \\\"{Title}\\\" by user {UserId}\"`.\n *\n * Useful for structured logging — pass this as the log `messageTemplate`\n * so events with the same shape can be grouped, and pass\n * `serialize(params)` as the rendered message.\n */\n get template(): string {\n return this.#humanPattern();\n }\n\n // -- Introspect ----------------------------------------------------------\n\n /**\n * Return a snapshot of this builder's configuration.\n *\n * Includes all base-class fields plus:\n * - `objectSchema` — the object schema defining the result shape.\n * - `templateDefinition` — the parsed template (literals and selector segments).\n */\n public introspect() {\n return {\n ...super.introspect(),\n /** The object schema defining the result shape. */\n objectSchema: this.#objectSchema,\n /** The template definition (literals + segments). */\n templateDefinition: this.#templateDef\n };\n }\n\n // -- Serialize -----------------------------------------------------------\n\n /**\n * Builds a string from the template by substituting parameter values.\n *\n * This is the reverse of {@link validate}: where `validate` parses a\n * string into a typed object, `serialize` takes a params object and\n * produces the string.\n *\n * @param params - An object matching the template's parsed result type.\n * Nested properties are resolved via dot-paths (e.g. `order.id`).\n * Values are coerced to strings via `String()`.\n * @returns The reconstructed string with all segments replaced.\n * @throws {Error} If a required parameter is missing (`undefined`).\n *\n * @example\n * ```ts\n * const Route = parseString(\n * object({ id: number().coerce() }),\n * $t => $t`/todos/${t => t.id}`\n * );\n *\n * Route.serialize({ id: 42 }); // '/todos/42'\n * ```\n */\n public serialize(params: TResult): string {\n const { literals, segments } = this.#templateDef;\n let result = '';\n for (let i = 0; i < segments.length; i++) {\n result += literals[i];\n const key = segments[i].path;\n const value = resolvePath(params, key);\n if (value === undefined || value === null) {\n throw new Error(\n `Missing required parameter \"${key}\" for template ${this.#humanPattern()}`\n );\n }\n result += String(value);\n }\n result += literals[segments.length] ?? '';\n return result;\n }\n\n // -- Validate (sync) -----------------------------------------------------\n\n /** {@inheritDoc SchemaBuilder.validate} */\n public validate(\n object: string,\n context?: ValidationContext\n ): ValidationResult<TResult> {\n return super.validate(object, context) as ValidationResult<TResult>;\n }\n\n /** {@inheritDoc SchemaBuilder.validateAsync} */\n public async validateAsync(\n object: string,\n context?: ValidationContext\n ): Promise<ValidationResult<TResult>> {\n return super.validateAsync(object, context) as Promise<\n ValidationResult<TResult>\n >;\n }\n\n protected _validate(\n object: any,\n context?: ValidationContext\n ): ValidationResult<TResult> {\n // Handle optional / nullable / default at the top\n if (typeof object === 'undefined' || object === null) {\n if (typeof object === 'undefined' && this.hasDefault) {\n object = this.resolveDefaultValue();\n return { valid: true, object: object as TResult };\n }\n if (!this.isRequired || (object === null && this.isNullable)) {\n return { valid: true, object: object as any };\n }\n return {\n valid: false,\n errors: [\n {\n message: this.getValidationErrorMessageSync(\n this.requiredErrorMessage,\n object\n )\n }\n ]\n };\n }\n\n return this.#matchAndValidate(object, context, (schema, raw) =>\n schema.validate(raw)\n );\n }\n\n // -- Validate (async) ----------------------------------------------------\n\n protected async _validateAsync(\n object: any,\n context?: ValidationContext\n ): Promise<ValidationResult<TResult>> {\n // Handle optional / nullable / default\n if (typeof object === 'undefined' || object === null) {\n if (typeof object === 'undefined' && this.hasDefault) {\n object = this.resolveDefaultValue();\n return { valid: true, object: object as TResult };\n }\n if (!this.isRequired || (object === null && this.isNullable)) {\n return { valid: true, object: object as any };\n }\n return {\n valid: false,\n errors: [\n {\n message: await this.getValidationErrorMessage(\n this.requiredErrorMessage,\n object\n )\n }\n ]\n };\n }\n\n return this.#matchAndValidate(object, context, (schema, raw) =>\n schema.validateAsync(raw)\n );\n }\n\n /**\n * Shared regex-match + per-segment validation logic used by both\n * `_validate` (sync) and `_validateAsync` (async).\n *\n * The caller supplies `validateSegment` which is either the sync\n * `schema.validate` or async `schema.validateAsync`.\n */\n #matchAndValidate<\n R extends ValidationResult<unknown> | Promise<ValidationResult<unknown>>\n >(\n object: any,\n context: ValidationContext | undefined,\n validateSegment: (\n schema: SchemaBuilder<any, any, any, any, any>,\n raw: string\n ) => R\n ): R extends Promise<any>\n ? Promise<ValidationResult<TResult>>\n : ValidationResult<TResult> {\n if (typeof object !== 'string') {\n return {\n valid: false,\n errors: [\n {\n message: `expected a string to parse, but saw ${typeof object}`\n }\n ]\n } as any;\n }\n\n const { segments } = this.#templateDef;\n\n // Degenerate case: no segments — just compare literals\n if (segments.length === 0) {\n const expected = this.#templateDef.literals[0] ?? '';\n if (object !== expected) {\n return {\n valid: false,\n errors: [\n {\n message: `expected \"${expected}\" but saw \"${object}\"`\n }\n ]\n } as any;\n }\n return { valid: true, object: {} as TResult } as any;\n }\n\n const regex = this.#buildRegex();\n const match = regex.exec(object);\n\n if (!match) {\n return {\n valid: false,\n errors: [\n {\n message: `does not match the parse-string pattern ${this.#humanPattern()}`\n }\n ]\n } as any;\n }\n\n const doNotStop = context?.doNotStopOnFirstError ?? false;\n\n // Compute segment validation results lazily so fail-fast mode can\n // short-circuit without eagerly validating later segments. When\n // doNotStopOnFirstError is enabled, prestart all validations to\n // preserve the existing eager/parallel behavior.\n const segResults = new Proxy([] as R[], {\n get: (target, prop, receiver) => {\n if (prop === 'length') return segments.length;\n\n const index =\n typeof prop === 'string' ? Number(prop) : Number.NaN;\n if (\n Number.isInteger(index) &&\n index >= 0 &&\n index < segments.length\n ) {\n if (!(index in target)) {\n target[index] = validateSegment(\n segments[index].schema,\n match[index + 1]\n );\n }\n return target[index];\n }\n\n return Reflect.get(target, prop, receiver);\n }\n }) as R[];\n\n if (doNotStop) {\n for (let i = 0; i < segments.length; i++) {\n void segResults[i];\n }\n }\n\n // If first result is a promise, the whole pipeline is async\n const firstResult = segResults[0];\n if (firstResult && typeof (firstResult as any).then === 'function') {\n return (async () => {\n const errors: { message: string }[] = [];\n const resultObj = {} as any;\n for (let i = 0; i < segments.length; i++) {\n const segResult = (await segResults[\n i\n ]) as ValidationResult<unknown>;\n if (!segResult.valid) {\n const inner =\n segResult.errors?.[0]?.message ??\n 'validation failed';\n errors.push({\n message: `${segments[i].path}: ${inner}`\n });\n if (!doNotStop) return { valid: false, errors };\n continue;\n }\n segments[i].descriptor.setValue(\n resultObj,\n segResult.object,\n { createMissingStructure: true }\n );\n }\n if (errors.length > 0) return { valid: false, errors };\n return { valid: true, object: resultObj as TResult };\n })() as any;\n }\n\n // Sync path\n const errors: { message: string }[] = [];\n const resultObj = {} as any;\n for (let i = 0; i < segments.length; i++) {\n const segResult = segResults[i] as ValidationResult<unknown>;\n if (!segResult.valid) {\n const inner =\n segResult.errors?.[0]?.message ?? 'validation failed';\n errors.push({\n message: `${segments[i].path}: ${inner}`\n });\n if (!doNotStop) return { valid: false, errors } as any;\n continue;\n }\n segments[i].descriptor.setValue(resultObj, segResult.object, {\n createMissingStructure: true\n });\n }\n if (errors.length > 0) return { valid: false, errors } as any;\n return { valid: true, object: resultObj as TResult } as any;\n }\n\n // -- Fluent overrides (return type narrowing) ----------------------------\n\n /**\n * @inheritdoc\n */\n public hasType<T>(\n _notUsed?: T\n ): ParseStringSchemaBuilder<T, true, TNullable, THasDefault, TExtensions> &\n TExtensions {\n return this.derive(\n {\n ...this.introspect()\n } as any,\n true\n ) as any;\n }\n\n /**\n * @inheritdoc\n */\n public clearHasType(): ParseStringSchemaBuilder<\n any,\n TRequired,\n TNullable,\n THasDefault,\n TExtensions\n > &\n TExtensions {\n return this.derive(\n {\n ...this.introspect()\n } as any,\n true\n ) as any;\n }\n\n /**\n * @hidden\n */\n public nullable(): ParseStringSchemaBuilder<\n TResult,\n TRequired,\n true,\n THasDefault,\n TExtensions\n > &\n TExtensions {\n return super.nullable() as any;\n }\n\n /**\n * @hidden\n */\n public notNullable(): ParseStringSchemaBuilder<\n TResult,\n TRequired,\n false,\n THasDefault,\n TExtensions\n > &\n TExtensions {\n return super.notNullable() as any;\n }\n\n /**\n * @hidden\n */\n public required(\n errorMessage?: ValidationErrorMessageProvider\n ): ParseStringSchemaBuilder<\n TResult,\n true,\n TNullable,\n THasDefault,\n TExtensions\n > &\n TExtensions {\n return super.required(errorMessage);\n }\n\n /**\n * @hidden\n */\n public optional(): ParseStringSchemaBuilder<\n TResult,\n false,\n TNullable,\n THasDefault,\n TExtensions\n > &\n TExtensions {\n return super.optional();\n }\n\n /**\n * @hidden\n */\n public default(\n value: TResult | (() => TResult)\n ): ParseStringSchemaBuilder<TResult, true, TNullable, true, TExtensions> &\n TExtensions {\n return super.default(value) as any;\n }\n\n /**\n * @hidden\n */\n public clearDefault(): ParseStringSchemaBuilder<\n TResult,\n TRequired,\n TNullable,\n false,\n TExtensions\n > &\n TExtensions {\n return super.clearDefault() as any;\n }\n\n /**\n * @hidden\n */\n public brand<TBrand extends string | symbol>(\n _name?: TBrand\n ): ParseStringSchemaBuilder<\n TResult & { readonly [K in BRAND]: TBrand },\n TRequired,\n TNullable,\n THasDefault,\n TExtensions\n > &\n TExtensions {\n return super.brand(_name);\n }\n\n /**\n * @hidden\n */\n public readonly(): ParseStringSchemaBuilder<\n Readonly<TResult>,\n TRequired,\n TNullable,\n THasDefault,\n TExtensions\n > &\n TExtensions {\n return super.readonly();\n }\n\n protected createFromProps<T, TReq extends boolean>(\n props: ParseStringSchemaBuilderCreateProps<T, TReq>\n ): this {\n return ParseStringSchemaBuilder.create(props as any) as any;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Factory\n// ---------------------------------------------------------------------------\n\n/**\n * Creates a parse-string schema that validates a string against a\n * template pattern and parses it into a strongly-typed object.\n *\n * The first argument defines the result shape via `object(...)`, and the\n * second argument is a callback receiving a typed `$template` tagged-template\n * function whose template expressions are type-safe property selectors.\n *\n * @example\n * ```ts\n * const RouteSchema = parseString(\n * object({\n * userId: string().uuid(),\n * id: number()\n * }),\n * $t => $t`/orders/${t => t.id}/${t => t.userId}`\n * );\n *\n * const result = RouteSchema.validate('/orders/42/550e8400-e29b-41d4-a716-446655440000');\n * // result.valid === true\n * // result.object === { id: 42, userId: '550e8400-e29b-41d4-a716-446655440000' }\n *\n * type Route = InferType<typeof RouteSchema>;\n * // { id: number; userId: string }\n * ```\n *\n * @example Nested objects\n * ```ts\n * const schema = parseString(\n * object({\n * order: object({ id: number() }),\n * user: object({ name: string() })\n * }),\n * $t => $t`/orders/${t => t.order.id}/by/${t => t.user.name}`\n * );\n * ```\n *\n * @param objectSchema - An `ObjectSchemaBuilder` defining the result type and\n * per-property validation schemas.\n * @param templateBuilder - Callback receiving the typed `$template`\n * tagged-template function. Must return the result of invoking `$template`.\n * @returns A `ParseStringSchemaBuilder` whose `validate()` accepts a\n * string and whose `InferType` is the object schema's inferred type.\n */\nexport function parseString<\n TSchema extends ObjectSchemaBuilder<any, any, any, any, any, any, any>\n>(\n objectSchema: TSchema,\n templateBuilder: (\n $template: ParseStringTemplateTag<TSchema>\n ) => ParseStringTemplateDefinition\n): ParseStringSchemaBuilder<InferType<TSchema>> {\n if (!(objectSchema instanceof ObjectSchemaBuilder)) {\n throw new Error(\n 'First argument must be an ObjectSchemaBuilder instance'\n );\n }\n\n // Get the PropertyDescriptorTree for the object schema\n const tree = ObjectSchemaBuilder.getPropertiesFor(objectSchema as any);\n\n // Build the $template tagged-template function\n const $template = ((\n strings: TemplateStringsArray,\n ...selectors: Array<(t: any) => any>\n ): ParseStringTemplateDefinition => {\n const seenPaths = new Set<string>();\n const segments: SegmentDef[] = [];\n\n for (const selector of selectors) {\n if (typeof selector !== 'function') {\n throw new Error(\n 'Template expressions must be property selector functions (e.g. t => t.id)'\n );\n }\n\n // Create a path-tracking proxy for this selector invocation\n const { proxy, getPath } = createPathTrackingProxy(tree);\n const descriptor = selector(proxy);\n\n if (\n !descriptor ||\n typeof descriptor !== 'object' ||\n !(SYMBOL_SCHEMA_PROPERTY_DESCRIPTOR in descriptor)\n ) {\n throw new Error(\n 'Template expression must select a property from the schema (e.g. t => t.id)'\n );\n }\n\n const inner: PropertyDescriptorInner<any, any, any> =\n descriptor[SYMBOL_SCHEMA_PROPERTY_DESCRIPTOR];\n const schema = inner.getSchema();\n const path = getPath();\n\n if (path.length === 0) {\n throw new Error(\n 'Template expression must select a specific property (e.g. t => t.id), not the root object'\n );\n }\n\n const pathStr = path.join('.');\n\n if (seenPaths.has(pathStr)) {\n throw new Error(\n `Duplicate template parameter: \"${pathStr}\" is already used in this template`\n );\n }\n seenPaths.add(pathStr);\n\n segments.push({\n schema,\n path: pathStr,\n descriptor: inner\n });\n }\n\n return {\n literals: [...strings],\n segments\n };\n }) as ParseStringTemplateTag<TSchema>;\n\n const templateDef = templateBuilder($template);\n\n return ParseStringSchemaBuilder.create({\n isRequired: true,\n objectSchema: objectSchema as any,\n templateDefinition: templateDef\n }) as any;\n}\n"],"mappings":"uFA0EA,SAASA,EAAYC,EAAmB,CACpC,OAAOA,EAAE,QAAQ,sBAAuB,MAAM,CAClD,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AAK,CAC5B,CAKO,UAOS,CACZ,OAAO,MAAM,SAAS,CAC1B,CAEU,gBACNhC,EACI,CACJ,OAAOL,EAAyB,OAAOK,CAAY,CACvD,CACJ,EAkDO,SAASiC,EAGZC,EACAC,EAG4C,CAC5C,GAAI,EAAED,aAAwBE,GAC1B,MAAM,IAAI,MACN,wDACJ,EAIJ,IAAMjD,EAAOiD,EAAoB,iBAAiBF,CAAmB,EAgE/DG,EAAcF,GA7DD,CACfG,KACGC,IAC6B,CAChC,IAAMC,EAAY,IAAI,IAChBrC,EAAyB,CAAC,EAEhC,QAAWsC,KAAYF,EAAW,CAC9B,GAAI,OAAOE,GAAa,WACpB,MAAM,IAAI,MACN,2EACJ,EAIJ,GAAM,CAAE,MAAAC,EAAO,QAAAC,CAAQ,EAAIzD,EAAwBC,CAAI,EACjDyD,EAAaH,EAASC,CAAK,EAEjC,GACI,CAACE,GACD,OAAOA,GAAe,UACtB,EAAEpD,KAAqCoD,GAEvC,MAAM,IAAI,MACN,6EACJ,EAGJ,IAAMf,EACFe,EAAWpD,CAAiC,EAC1CwB,EAASa,EAAM,UAAU,EACzB9C,EAAO4D,EAAQ,EAErB,GAAI5D,EAAK,SAAW,EAChB,MAAM,IAAI,MACN,2FACJ,EAGJ,IAAM8D,EAAU9D,EAAK,KAAK,GAAG,EAE7B,GAAIyD,EAAU,IAAIK,CAAO,EACrB,MAAM,IAAI,MACN,kCAAkCA,CAAO,oCAC7C,EAEJL,EAAU,IAAIK,CAAO,EAErB1C,EAAS,KAAK,CACV,OAAAa,EACA,KAAM6B,EACN,WAAYhB,CAChB,CAAC,CACL,CAEA,MAAO,CACH,SAAU,CAAC,GAAGS,CAAO,EACrB,SAAAnC,CACJ,CACJ,EAE6C,EAE7C,OAAOT,EAAyB,OAAO,CACnC,WAAY,GACZ,aAAcwC,EACd,mBAAoBG,CACxB,CAAC,CACL","names":["escapeRegex","s","resolvePath","obj","path","current","part","createPathTrackingProxy","tree","pathSegments","wrapProxy","target","prop","SYMBOL_SCHEMA_PROPERTY_DESCRIPTOR","child","ParseStringSchemaBuilder","_ParseStringSchemaBuilder","SchemaBuilder","#objectSchema","#templateDef","#compiledRegex","props","#buildRegex","literals","segments","pattern","i","isLast","trailingLiteral","#humanPattern","result","params","key","value","object","context","#matchAndValidate","schema","raw","validateSegment","expected","match","doNotStop","segResults","receiver","index","firstResult","errors","resultObj","segResult","inner","_notUsed","errorMessage","_name","parseString","objectSchema","templateBuilder","ObjectSchemaBuilder","templateDef","strings","selectors","seenPaths","selector","proxy","getPath","descriptor","pathStr"]}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{c as m,e as p,f as c}from"./chunk-2BKBVVZ3.js";var y=class T extends c{#r;#u=function(){return`is expected to have no less than ${this.#r} elements`};#i=this.#u;#t;#o=function(){return`is expected to have no more than ${this.#t} elements`};#s=this.#o;#e;static create(e){return new T({type:"array",...e})}constructor(e){super(e),typeof e.minLength=="number"&&(this.#r=e.minLength),this.#i=this.assureValidationErrorMessageProvider(e.minLengthValidationErrorMessageProvider,this.#u),typeof e.maxLength=="number"&&(this.#t=e.maxLength),this.#s=this.assureValidationErrorMessageProvider(e.maxLengthValidationErrorMessageProvider,this.#o),e.elementSchema instanceof c&&(this.#e=e.elementSchema)}hasType(e){return this.derive({...this.introspect()},!0)}clearHasType(){return this.derive({...this.introspect()},!0)}#d(e,r){let{valid:l,context:t,errors:a,transaction:u}=r,d={[m]:{setValue:()=>!1,getValue:s=>({success:!0,value:s}),getSchema:()=>this,parent:void 0,propertyName:void 0,toJsonPointer:()=>""}},o=[],h=p([],()=>e,()=>o,()=>d[m]),i=(()=>h);if(!l)return o.push(...(a||[]).map(s=>s.message||String(s))),{needsElementValidation:!1,result:{valid:l,errors:a,getNestedErrors:i}};let{object:{validatedObject:n}}=u;return typeof n>"u"&&!this.isRequired||n===null&&(!this.isRequired||this.isNullable)?{needsElementValidation:!1,result:{valid:!0,object:n,getNestedErrors:i}}:Array.isArray(n)?{needsElementValidation:!0,objToValidate:n,prevalidationContext:t,getNestedErrors:i,elementResults:h,rootErrors:o}:(o.push("array expected"),{needsElementValidation:!1,result:{valid:!1,errors:[{message:"array expected"}],getNestedErrors:i}})}#l(e){return typeof this.#t=="number"&&e.length>this.#t?{provider:this.#s}:typeof this.#r=="number"&&e.length<this.#r?{provider:this.#i}:null}#h(e,r,l){let t=!0;for(let a=0;a<e.length;a++)e[a]?.valid||(t=!1),r[a]=e[a];return Object.assign({valid:t,getNestedErrors:l},t?{}:{errors:e.map(a=>a?.errors).filter(a=>a).flatMap(a=>a?.map(u=>({...u})))},t?{object:e.map(a=>a?.object)}:{})}#n(e,r){let l=e.currentPropertyDescriptor?.[r];return l?.[m]?{...e,currentPropertyDescriptor:l}:{...e}}validate(e,r){return super.validate(e,r)}async validateAsync(e,r){return super.validateAsync(e,r)}_validate(e,r){if(this.canSkipPreValidation&&!r?.doNotStopOnFirstError&&this.#e instanceof c){if(typeof e>"u"||e===null)if(typeof e>"u"&&this.hasDefault)e=this.resolveDefaultValue();else if(!this.isRequired||e===null&&this.isNullable){let a=this;return{valid:!0,object:e,getNestedErrors(){return a.#a(e,r).getNestedErrors()}}}else return this.#a(e,r);if(!Array.isArray(e))return this.#a(e,r);if(this.#l(e))return this.#a(e,r);let l=e.length;if(l>0){let a=new Array(l);for(let d=0;d<l;d++){let o=this.#e.validate(e[d]);if(!o.valid){let h=this;return{valid:!1,errors:o.errors&&o.errors.length>0?[o.errors[0]]:[],getNestedErrors(){return h.#a(e,r).getNestedErrors()}}}a[d]=o.object}let u=this;return{valid:!0,object:a,getNestedErrors(){return u.#a(e,r).getNestedErrors()}}}let t=this;return{valid:!0,object:e,getNestedErrors(){return t.#a(e,r).getNestedErrors()}}}return this.#a(e,r)}#a(e,r){let l=this.#d(e,this.preValidateSync(e,r));if(!l.needsElementValidation)return l.result;let{objToValidate:t,prevalidationContext:a,getNestedErrors:u,elementResults:d,rootErrors:o}=l,h=this.#l(t);if(h){let i=this.getValidationErrorMessageSync(h.provider,t);return o.push(i),{valid:!1,errors:[{message:i}],getNestedErrors:u}}if(t.length>0&&this.#e instanceof c)if(a.doNotStopOnFirstError){let i=[];for(let n=0;n<t.length;n++)i.push(this.#e.validate(t[n],this.#n(a,n)));return this.#h(i,d,u)}else{let i=new Array(t.length);for(let n=0;n<t.length;n++){let s=this.#e.validate(t[n],this.#n(a,n));if(d[n]=s,s.valid)i[n]=s.object;else return{valid:!1,errors:Array.isArray(s.errors)&&s.errors.length>0?[s.errors[0]]:[],getNestedErrors:u}}return{valid:!0,object:i,getNestedErrors:u}}return{valid:!0,object:t,getNestedErrors:u}}async _validateAsync(e,r){let l=this.#d(e,await super.preValidateAsync(e,r));if(!l.needsElementValidation)return l.result;let{objToValidate:t,prevalidationContext:a,getNestedErrors:u,elementResults:d,rootErrors:o}=l,h=this.#l(t);if(h){let i=await this.getValidationErrorMessage(h.provider,t);return o.push(i),{valid:!1,errors:[{message:i}],getNestedErrors:u}}if(t.length>0&&this.#e instanceof c)if(a.doNotStopOnFirstError){let i=await Promise.all(t.map((n,s)=>this.#e?.validateAsync(n,this.#n(a,s))));return this.#h(i,d,u)}else{let i=new Array(t.length);for(let n=0;n<t.length;n++){let s=await this.#e.validateAsync(t[n],this.#n(a,n));if(d[n]=s,s.valid)i[n]=s.object;else return{valid:!1,errors:Array.isArray(s.errors)&&s.errors.length>0?[s.errors[0]]:[],getNestedErrors:u}}return{valid:!0,object:i,getNestedErrors:u}}return{valid:!0,object:t,getNestedErrors:u}}createFromProps(e){return T.create(e)}required(e){return super.required(e)}optional(){return super.optional()}default(e){return super.default(e)}clearDefault(){return super.clearDefault()}brand(e){return super.brand(e)}readonly(){return super.readonly()}introspect(){return{...super.introspect(),elementSchema:this.#e,minLength:this.#r,minLengthValidationErrorMessageProvider:this.#i,maxLength:this.#t,maxLengthValidationErrorMessageProvider:this.#s}}of(e){return this.derive({...this.introspect(),elementSchema:e})}clearOf(){return this.derive({...this.introspect(),elementSchema:void 0})}minLength(e,r){if(typeof e!="number"||e<0)throw new Error("length is expected to be a number which is >= 0");return this.derive({...this.introspect(),minLength:e,minLengthValidationErrorMessageProvider:r})}clearMinLength(){let e=this.introspect();return delete e.minLength,this.derive({...e})}maxLength(e,r){if(typeof e!="number"||e<0)throw new Error("length is expected to be a number which is >= 0");return this.derive({...this.introspect(),maxLength:e,maxLengthValidationErrorMessageProvider:r})}clearMaxLength(){let e=this.introspect();return delete e.maxLength,this.derive({...e})}nullable(){return super.nullable()}notNullable(){return super.notNullable()}},S=T=>y.create({isRequired:!0,elementSchema:T});export{y as a,S as b};
|
|
2
|
+
//# sourceMappingURL=chunk-XASMTNON.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/builders/ArraySchemaBuilder.ts"],"sourcesContent":["import type {\n ObjectSchemaBuilder,\n ObjectSchemaValidationResult\n} from './ObjectSchemaBuilder.js';\nimport {\n type BRAND,\n createHybridErrorArray,\n type InferType,\n type NestedValidationResult,\n type PropertyDescriptor,\n SchemaBuilder,\n SYMBOL_SCHEMA_PROPERTY_DESCRIPTOR,\n type ValidationContext,\n type ValidationErrorMessageProvider,\n type ValidationResult\n} from './SchemaBuilder.js';\n\nimport type {\n UnionSchemaBuilder,\n UnionSchemaValidationResult\n} from './UnionSchemaBuilder.js';\n\n/**\n * Maps an element schema type to the appropriate validation result type.\n * Union schema elements get `UnionSchemaValidationResult`,\n * Object schema elements get `ObjectSchemaValidationResult`,\n * other types get `ValidationResult`.\n */\nexport type ElementValidationResult<\n TElementSchema extends SchemaBuilder<any, any, any, any, any>\n> =\n TElementSchema extends UnionSchemaBuilder<\n infer UOptions extends readonly SchemaBuilder<\n any,\n any,\n any,\n any,\n any\n >[],\n any,\n any\n >\n ? UnionSchemaValidationResult<InferType<TElementSchema>, UOptions>\n : TElementSchema extends ObjectSchemaBuilder<any, any, any, any, any>\n ? ObjectSchemaValidationResult<\n InferType<TElementSchema>,\n TElementSchema\n >\n : ValidationResult<InferType<TElementSchema>>;\n\n/**\n * Validation result type returned by `ArraySchemaBuilder.validate()`.\n * Extends `ValidationResult` with `getNestedErrors` for root-level array\n * errors and per-element validation results.\n */\nexport type ArraySchemaValidationResult<\n TResult,\n TElementSchema extends SchemaBuilder<any, any, any, any, any>\n> = ValidationResult<TResult> & {\n /**\n * Returns root-level array validation errors combined with\n * per-element validation results.\n * The returned value has both `NestedValidationResult` properties\n * (`errors`, `isValid`, `descriptor`, `seenValue`) and indexed\n * element results (`[0]`, `[1]`, etc.).\n */\n getNestedErrors(): Array<ElementValidationResult<TElementSchema>> &\n NestedValidationResult<any, any, any>;\n};\n\ntype ArraySchemaBuilderCreateProps<\n TElementSchema extends SchemaBuilder<any, any, any, any, any>,\n R extends boolean = true\n> = Partial<ReturnType<ArraySchemaBuilder<TElementSchema, R>['introspect']>>;\n\n/**\n * Similar to the `Array` type in TypeScript. It can be used to validate arrays of any type.\n * It can also be used to validate arrays of specific type.\n * For example, if you want to validate an array of numbers,\n * you can use `array(number())` to create a schema builder.\n * If you want to validate an array of users, you can use\n * `array().of(object({ name: string(), age: number() }))` to create a schema builder.\n * If you want to validate an array of numbers or strings,\n * you can use `array(union(number()).or(string()))`.\n *\n * Also you can limit the length of the array by using `minLength`\n * and `maxLength` methods.\n *\n * **NOTE** this class is exported for type annotations and advanced use.\n * Customize via extensions rather than subclassing. Avoid instantiating it\n * directly. Use {@link array | array()} function instead.\n * @see {@link array}\n */\nexport class ArraySchemaBuilder<\n TElementSchema extends SchemaBuilder<any, any, any, any, any>,\n TRequired extends boolean = true,\n TNullable extends boolean = false,\n TExplicitType = undefined,\n THasDefault extends boolean = false,\n TExtensions = {},\n TResult = TExplicitType extends undefined\n ? TElementSchema extends undefined\n ? Array<any>\n : TElementSchema extends SchemaBuilder<infer T1, infer T2>\n ? Array<InferType<SchemaBuilder<T1, T2>>>\n : never\n : TExplicitType\n> extends SchemaBuilder<\n TResult,\n TRequired,\n TNullable,\n THasDefault,\n TExtensions\n> {\n /** Native type parameters for extension rebinding; never emitted at runtime. @internal */\n declare readonly __cleverbrush_builder_type__: readonly [\n 'array',\n TElementSchema,\n TRequired,\n TNullable,\n TExplicitType,\n THasDefault,\n TResult\n ];\n\n #minLength?: number;\n #defaultMinLengthErrorMessageProvider: ValidationErrorMessageProvider<\n ArraySchemaBuilder<TElementSchema, TRequired, TNullable, TExplicitType>\n > = function (this: ArraySchemaBuilder<any, any, any, any, any>) {\n return `is expected to have no less than ${this.#minLength} elements`;\n };\n #minLengthErrorMessageProvider: ValidationErrorMessageProvider<\n ArraySchemaBuilder<TElementSchema, TRequired, TNullable, TExplicitType>\n > = this.#defaultMinLengthErrorMessageProvider;\n\n #maxLength?: number;\n #defaultMaxLengthErrorMessageProvider: ValidationErrorMessageProvider<\n ArraySchemaBuilder<TElementSchema, TRequired, TNullable, TExplicitType>\n > = function (this: ArraySchemaBuilder<any, any, any, any, any>) {\n return `is expected to have no more than ${this.#maxLength} elements`;\n };\n #maxLengthErrorMessageProvider: ValidationErrorMessageProvider<\n ArraySchemaBuilder<TElementSchema, TRequired, TNullable, TExplicitType>\n > = this.#defaultMaxLengthErrorMessageProvider;\n\n #elementSchema?: TElementSchema;\n\n /**\n * @hidden\n */\n public static create(props: ArraySchemaBuilderCreateProps<any, any>) {\n return new ArraySchemaBuilder({\n type: 'array',\n ...props\n } as any);\n }\n\n protected constructor(\n props: ArraySchemaBuilderCreateProps<TElementSchema, TRequired>\n ) {\n super(props as any);\n\n if (typeof props.minLength === 'number') {\n this.#minLength = props.minLength;\n }\n\n this.#minLengthErrorMessageProvider =\n this.assureValidationErrorMessageProvider(\n props.minLengthValidationErrorMessageProvider,\n this.#defaultMinLengthErrorMessageProvider\n );\n\n if (typeof props.maxLength === 'number') {\n this.#maxLength = props.maxLength;\n }\n\n this.#maxLengthErrorMessageProvider =\n this.assureValidationErrorMessageProvider(\n props.maxLengthValidationErrorMessageProvider,\n this.#defaultMaxLengthErrorMessageProvider\n );\n\n if (props.elementSchema instanceof SchemaBuilder) {\n this.#elementSchema = props.elementSchema;\n }\n }\n\n /**\n * @inheritdoc\n */\n public hasType<T>(\n _notUsed?: T\n ): ArraySchemaBuilder<\n TElementSchema,\n true,\n TNullable,\n T,\n THasDefault,\n TExtensions\n > &\n TExtensions {\n return this.derive(\n {\n ...this.introspect()\n } as any,\n true\n ) as any;\n }\n\n /**\n * @inheritdoc\n */\n public clearHasType(): ArraySchemaBuilder<\n TElementSchema,\n TRequired,\n TNullable,\n undefined,\n THasDefault,\n TExtensions\n > &\n TExtensions {\n return this.derive(\n {\n ...this.introspect()\n } as any,\n true\n ) as any;\n }\n\n #createValidationSetup(\n object: TResult,\n superResult: ReturnType<ArraySchemaBuilder<any, any>['preValidateSync']>\n ) {\n const {\n valid,\n context: prevalidationContext,\n errors,\n transaction: preValidationTransaction\n } = superResult;\n\n // Self-referencing property descriptor for the array root\n const selfDescriptor: PropertyDescriptor<any, any, any> = {\n [SYMBOL_SCHEMA_PROPERTY_DESCRIPTOR]: {\n setValue: () => false,\n getValue: (obj: any) => ({\n success: true,\n value: obj\n }),\n getSchema: () => this,\n parent: undefined,\n propertyName: undefined,\n toJsonPointer: () => ''\n }\n };\n\n const rootErrors: string[] = [];\n\n const elementResults = createHybridErrorArray(\n [] as any[],\n () => object,\n () => rootErrors,\n () => selfDescriptor[SYMBOL_SCHEMA_PROPERTY_DESCRIPTOR]\n );\n\n const getNestedErrors = (() => elementResults) as any;\n\n if (!valid) {\n rootErrors.push(\n ...(errors || []).map((e: any) => e.message || String(e))\n );\n return {\n needsElementValidation: false as const,\n result: {\n valid,\n errors,\n getNestedErrors\n } as ArraySchemaValidationResult<TResult, TElementSchema>\n };\n }\n\n const {\n object: { validatedObject: objToValidate }\n } = preValidationTransaction!;\n\n if (\n (typeof objToValidate === 'undefined' && !this.isRequired) ||\n (objToValidate === null && (!this.isRequired || this.isNullable))\n ) {\n return {\n needsElementValidation: false as const,\n result: {\n valid: true,\n object: objToValidate,\n getNestedErrors\n } as ArraySchemaValidationResult<TResult, TElementSchema>\n };\n }\n\n if (!Array.isArray(objToValidate)) {\n rootErrors.push('array expected');\n return {\n needsElementValidation: false as const,\n result: {\n valid: false,\n errors: [{ message: 'array expected' }],\n getNestedErrors\n } as ArraySchemaValidationResult<TResult, TElementSchema>\n };\n }\n\n return {\n needsElementValidation: true as const,\n objToValidate,\n prevalidationContext,\n getNestedErrors,\n elementResults,\n rootErrors\n };\n }\n\n #getLengthViolation(objToValidate: any[]): { provider: any } | null {\n if (\n typeof this.#maxLength === 'number' &&\n objToValidate.length > this.#maxLength\n ) {\n return { provider: this.#maxLengthErrorMessageProvider };\n }\n\n if (\n typeof this.#minLength === 'number' &&\n objToValidate.length < this.#minLength\n ) {\n return { provider: this.#minLengthErrorMessageProvider };\n }\n\n return null;\n }\n\n #assembleDoNotStopResults(\n results: any[],\n elementResults: any,\n getNestedErrors: any\n ) {\n let allValid = true;\n\n for (let i = 0; i < results.length; i++) {\n if (!results[i]?.valid) {\n allValid = false;\n }\n elementResults[i] = results[i] as any;\n }\n\n return Object.assign(\n {\n valid: allValid,\n getNestedErrors\n },\n allValid\n ? {}\n : {\n errors: results\n .map(r => r?.errors)\n .filter(r => r)\n .flatMap(e =>\n e?.map((r: any) => ({\n ...r\n }))\n ) as any\n },\n allValid\n ? {\n object: results.map(r => r?.object)\n }\n : {}\n ) as any;\n }\n\n /** Keep indexed object validators attached to their actual root descriptor. */\n #elementContext(\n context: ValidationContext,\n index: number\n ): ValidationContext {\n const descriptor = (context.currentPropertyDescriptor as any)?.[index];\n return descriptor?.[SYMBOL_SCHEMA_PROPERTY_DESCRIPTOR]\n ? { ...context, currentPropertyDescriptor: descriptor }\n : { ...context };\n }\n\n /**\n * {@inheritDoc SchemaBuilder.validate}\n */\n public validate(\n object: TResult,\n context?: ValidationContext\n ): ArraySchemaValidationResult<TResult, TElementSchema> {\n return super.validate(object, context) as ArraySchemaValidationResult<\n TResult,\n TElementSchema\n >;\n }\n\n /**\n * {@inheritDoc SchemaBuilder.validateAsync}\n */\n public async validateAsync(\n object: TResult,\n context?: ValidationContext\n ): Promise<ArraySchemaValidationResult<TResult, TElementSchema>> {\n return super.validateAsync(object, context) as Promise<\n ArraySchemaValidationResult<TResult, TElementSchema>\n >;\n }\n\n /**\n * Performs synchronous validation of the schema over `object`.\n * Throws if any preprocessor, validator, or error message provider returns a Promise.\n * @param context Optional `ValidationContext` settings.\n */\n protected _validate(\n object: TResult,\n context?: ValidationContext\n ): ArraySchemaValidationResult<TResult, TElementSchema> {\n // Fast path: no preprocessors/validators, default error mode, has element schema\n if (\n this.canSkipPreValidation &&\n !context?.doNotStopOnFirstError &&\n this.#elementSchema instanceof SchemaBuilder\n ) {\n // Required / optional check\n if (typeof object === 'undefined' || object === null) {\n if (typeof object === 'undefined' && this.hasDefault) {\n object = this.resolveDefaultValue();\n } else if (\n !this.isRequired ||\n (object === null && this.isNullable)\n ) {\n const self = this;\n return {\n valid: true,\n object: object,\n getNestedErrors() {\n return self\n .#validateArrayFull(object, context)\n .getNestedErrors();\n }\n } as any;\n } else {\n return this.#validateArrayFull(object, context);\n }\n }\n\n if (!Array.isArray(object)) {\n return this.#validateArrayFull(object, context);\n }\n\n // Length constraints\n if (this.#getLengthViolation(object as any)) {\n return this.#validateArrayFull(object, context);\n }\n\n // Validate elements inline — no path passed to children\n const len = (object as any).length;\n if (len > 0) {\n const resultArray = new Array(len);\n for (let i = 0; i < len; i++) {\n const result = this.#elementSchema.validate(\n (object as any)[i]\n );\n if (!result.valid) {\n const self = this;\n return {\n valid: false,\n errors:\n result.errors && result.errors.length > 0\n ? [result.errors[0]]\n : [],\n getNestedErrors() {\n return self\n .#validateArrayFull(object, context)\n .getNestedErrors();\n }\n } as any;\n }\n resultArray[i] = result.object;\n }\n\n // Lazy getNestedErrors\n const self = this;\n return {\n valid: true,\n object: resultArray as TResult,\n getNestedErrors() {\n return self\n .#validateArrayFull(object, context)\n .getNestedErrors();\n }\n } as any;\n }\n\n const self = this;\n return {\n valid: true,\n object: object as TResult,\n getNestedErrors() {\n return self\n .#validateArrayFull(object, context)\n .getNestedErrors();\n }\n } as any;\n }\n\n return this.#validateArrayFull(object, context);\n }\n\n /**\n * Full validation path with complete setup, error handling, and nested error support.\n */\n #validateArrayFull(\n object: TResult,\n context?: ValidationContext\n ): ArraySchemaValidationResult<TResult, TElementSchema> {\n const setup = this.#createValidationSetup(\n object,\n this.preValidateSync(object, context)\n );\n\n if (!setup.needsElementValidation) return setup.result;\n\n const {\n objToValidate,\n prevalidationContext,\n getNestedErrors,\n elementResults,\n rootErrors\n } = setup;\n\n const lengthViolation = this.#getLengthViolation(objToValidate);\n if (lengthViolation) {\n const msg = this.getValidationErrorMessageSync(\n lengthViolation.provider,\n objToValidate as TResult\n );\n rootErrors.push(msg);\n return {\n valid: false,\n errors: [{ message: msg }],\n getNestedErrors\n };\n }\n\n if (\n objToValidate.length > 0 &&\n this.#elementSchema instanceof SchemaBuilder\n ) {\n if (prevalidationContext.doNotStopOnFirstError) {\n const results: any[] = [];\n\n for (let i = 0; i < objToValidate.length; i++) {\n results.push(\n this.#elementSchema.validate(\n objToValidate[i],\n this.#elementContext(prevalidationContext, i)\n )\n );\n }\n\n return this.#assembleDoNotStopResults(\n results,\n elementResults,\n getNestedErrors\n );\n } else {\n const resultArray = new Array(objToValidate.length);\n for (let i = 0; i < objToValidate.length; i++) {\n const result = this.#elementSchema.validate(\n objToValidate[i],\n this.#elementContext(prevalidationContext, i)\n );\n elementResults[i] = result as any;\n if (result.valid) {\n resultArray[i] = result.object;\n } else {\n return {\n valid: false,\n errors:\n Array.isArray(result.errors) &&\n result.errors.length > 0\n ? [result.errors[0]]\n : [],\n getNestedErrors\n };\n }\n }\n\n return {\n valid: true,\n object: resultArray as TResult,\n getNestedErrors\n };\n }\n }\n\n return {\n valid: true,\n object: objToValidate as TResult,\n getNestedErrors\n };\n }\n\n /**\n * Performs async validation of the schema over `object`.\n * Supports async preprocessors, validators, and error message providers.\n * @param context Optional `ValidationContext` settings.\n */\n protected async _validateAsync(\n object: TResult,\n context?: ValidationContext\n ): Promise<ArraySchemaValidationResult<TResult, TElementSchema>> {\n const setup = this.#createValidationSetup(\n object,\n await super.preValidateAsync(object, context)\n );\n\n if (!setup.needsElementValidation) return setup.result;\n\n const {\n objToValidate,\n prevalidationContext,\n getNestedErrors,\n elementResults,\n rootErrors\n } = setup;\n\n const lengthViolation = this.#getLengthViolation(objToValidate);\n if (lengthViolation) {\n const msg = await this.getValidationErrorMessage(\n lengthViolation.provider,\n objToValidate as TResult\n );\n rootErrors.push(msg);\n return {\n valid: false,\n errors: [{ message: msg }],\n getNestedErrors\n };\n }\n\n if (\n objToValidate.length > 0 &&\n this.#elementSchema instanceof SchemaBuilder\n ) {\n if (prevalidationContext.doNotStopOnFirstError) {\n const results = await Promise.all(\n objToValidate.map((o, i) =>\n this.#elementSchema?.validateAsync(\n o,\n this.#elementContext(prevalidationContext, i)\n )\n )\n );\n\n return this.#assembleDoNotStopResults(\n results,\n elementResults,\n getNestedErrors\n );\n } else {\n const resultArray = new Array(objToValidate.length);\n for (let i = 0; i < objToValidate.length; i++) {\n const result = await this.#elementSchema.validateAsync(\n objToValidate[i],\n this.#elementContext(prevalidationContext, i)\n );\n elementResults[i] = result as any;\n if (result.valid) {\n resultArray[i] = result.object;\n } else {\n return {\n valid: false,\n errors:\n Array.isArray(result.errors) &&\n result.errors.length > 0\n ? [result.errors[0]]\n : [],\n getNestedErrors\n };\n }\n }\n\n return {\n valid: true,\n object: resultArray as TResult,\n getNestedErrors\n };\n }\n }\n\n return {\n valid: true,\n object: objToValidate as TResult,\n getNestedErrors\n };\n }\n\n /**\n * @hidden\n */\n protected createFromProps<TReq extends boolean>(\n props: ArraySchemaBuilderCreateProps<TElementSchema, TReq>\n ): this {\n return ArraySchemaBuilder.create(props as any) as any;\n }\n\n /**\n * @hidden\n */\n public required(\n errorMessage?: ValidationErrorMessageProvider\n ): ArraySchemaBuilder<\n TElementSchema,\n true,\n TNullable,\n TExplicitType,\n THasDefault,\n TExtensions\n > &\n TExtensions {\n return super.required(errorMessage);\n }\n\n /**\n * @hidden\n */\n public optional(): ArraySchemaBuilder<\n TElementSchema,\n false,\n TNullable,\n TExplicitType,\n THasDefault,\n TExtensions\n > &\n TExtensions {\n return super.optional();\n }\n\n /**\n * @hidden\n */\n public default(\n value: TResult | (() => TResult)\n ): ArraySchemaBuilder<\n TElementSchema,\n true,\n TNullable,\n TExplicitType,\n true,\n TExtensions\n > &\n TExtensions {\n return super.default(value) as any;\n }\n\n /**\n * @hidden\n */\n public clearDefault(): ArraySchemaBuilder<\n TElementSchema,\n TRequired,\n TNullable,\n TExplicitType,\n false,\n TExtensions\n > &\n TExtensions {\n return super.clearDefault() as any;\n }\n\n /**\n * @hidden\n */\n public brand<TBrand extends string | symbol>(\n _name?: TBrand\n ): ArraySchemaBuilder<\n TElementSchema,\n TRequired,\n TNullable,\n TResult & { readonly [K in BRAND]: TBrand },\n THasDefault,\n TExtensions\n > &\n TExtensions {\n return super.brand(_name);\n }\n\n /**\n * Marks the inferred type as `ReadonlyArray<T>` — disables `push`,\n * `pop`, and other mutating methods at the type level. Validation\n * behaviour is unchanged.\n *\n * @see {@link SchemaBuilder.readonly}\n */\n public readonly(): ArraySchemaBuilder<\n TElementSchema,\n TRequired,\n TNullable,\n ReadonlyArray<\n TElementSchema extends SchemaBuilder<infer T1, infer T2>\n ? InferType<SchemaBuilder<T1, T2>>\n : any\n >,\n THasDefault,\n TExtensions\n > &\n TExtensions {\n return super.readonly();\n }\n\n public introspect() {\n return {\n ...super.introspect(),\n /**\n * Schema of array item (if defined)\n */\n elementSchema: this.#elementSchema,\n /**\n * Min length of a valid array\n */\n minLength: this.#minLength,\n\n /**\n * Min length validation error message provider.\n * If not provided, default error message provider is used.\n */\n minLengthValidationErrorMessageProvider:\n this.#minLengthErrorMessageProvider,\n\n /**\n * Max length of a valid array\n */\n maxLength: this.#maxLength,\n\n /**\n * Max length validation error message provider.\n * If not provided, default error message provider is used.\n */\n maxLengthValidationErrorMessageProvider:\n this.#maxLengthErrorMessageProvider\n };\n }\n\n /**\n * Set a schema that every array item has to satisfy. If it is not set,\n * Item of any type is allowed.\n * @param schema Schema that every array item has to satisfy\n */\n public of<TSchema extends SchemaBuilder<any, any, any, any, any>>(\n schema: TSchema\n ): ArraySchemaBuilder<\n TSchema,\n TRequired,\n TNullable,\n TExplicitType,\n THasDefault,\n TExtensions\n > &\n TExtensions {\n return this.derive({\n ...this.introspect(),\n elementSchema: schema\n } as any) as any;\n }\n\n /**\n * Clears the element schema set by `of()`. After this call,\n * array items of any type will be accepted.\n */\n public clearOf(): ArraySchemaBuilder<\n any,\n TRequired,\n TNullable,\n TExplicitType,\n THasDefault,\n TExtensions\n > &\n TExtensions {\n return this.derive({\n ...this.introspect(),\n elementSchema: undefined\n } as any) as any;\n }\n\n /**\n * Set minimal length of the valid array value for schema.\n */\n public minLength<T extends number>(\n length: T,\n /**\n * Custom error message provider.\n */\n errorMessage?: ValidationErrorMessageProvider<\n ArraySchemaBuilder<\n TElementSchema,\n TRequired,\n TNullable,\n TExplicitType\n >\n >\n ): ArraySchemaBuilder<\n TElementSchema,\n TRequired,\n TNullable,\n TExplicitType,\n THasDefault,\n TExtensions\n > &\n TExtensions {\n if (typeof length !== 'number' || length < 0)\n throw new Error('length is expected to be a number which is >= 0');\n return this.derive({\n ...this.introspect(),\n minLength: length,\n minLengthValidationErrorMessageProvider: errorMessage\n } as any) as any;\n }\n\n /**\n * Clear minimal length of the valid array value for schema.\n */\n public clearMinLength(): ArraySchemaBuilder<\n TElementSchema,\n TRequired,\n TNullable,\n TExplicitType,\n THasDefault,\n TExtensions\n > &\n TExtensions {\n const schema = this.introspect();\n delete schema.minLength;\n return this.derive({\n ...schema\n } as any) as any;\n }\n\n /**\n * Set max length of the valid array value for schema.\n */\n public maxLength<T extends number>(\n length: T,\n /**\n * Custom error message provider.\n */\n errorMessage?: ValidationErrorMessageProvider<\n ArraySchemaBuilder<\n TElementSchema,\n TRequired,\n TNullable,\n TExplicitType\n >\n >\n ): ArraySchemaBuilder<\n TElementSchema,\n TRequired,\n TNullable,\n TExplicitType,\n THasDefault,\n TExtensions\n > &\n TExtensions {\n if (typeof length !== 'number' || length < 0)\n throw new Error('length is expected to be a number which is >= 0');\n return this.derive({\n ...this.introspect(),\n maxLength: length,\n maxLengthValidationErrorMessageProvider: errorMessage\n } as any) as any;\n }\n\n /**\n * Clear max length of the valid array value for schema.\n */\n public clearMaxLength(): ArraySchemaBuilder<\n TElementSchema,\n TRequired,\n TNullable,\n TExplicitType,\n THasDefault,\n TExtensions\n > &\n TExtensions {\n const schema = this.introspect();\n delete schema.maxLength;\n return this.derive({\n ...schema\n } as any) as any;\n }\n\n /**\n * @hidden\n */\n public nullable(): ArraySchemaBuilder<\n TElementSchema,\n TRequired,\n true,\n TExplicitType,\n THasDefault,\n TExtensions\n > &\n TExtensions {\n return super.nullable() as any;\n }\n\n /**\n * @hidden\n */\n public notNullable(): ArraySchemaBuilder<\n TElementSchema,\n TRequired,\n false,\n TExplicitType,\n THasDefault,\n TExtensions\n > &\n TExtensions {\n return super.notNullable() as any;\n }\n}\n\n/**\n * Creates a `Array` schema.\n *\n * @example\n * ```typescript\n * const schema = array().minLength(2).maxLength(5).of(string());\n * // [] - invalid\n * // ['a', 'b'] - valid\n * // ['a', 'b', 'c', 'd', 'e', 'f'] - invalid\n * // ['a', 'b', 'c', 'd', 'e'] - valid\n * // ['a', 'b', 'c', 'd', 1] - invalid\n * // ['a', 'b', null] - invalid\n * // null - invalid\n * // undefined - invalid\n * ```\n */\nexport const array = <\n TElementSchema extends SchemaBuilder<any, any, any, any, any>\n>(\n elementSchema?: TElementSchema\n) =>\n ArraySchemaBuilder.create({\n isRequired: true,\n elementSchema\n }) as unknown as ArraySchemaBuilder<TElementSchema, true>;\n"],"mappings":"sDA6FO,IAAMA,EAAN,MAAMC,UAcHC,CAMR,CAYEC,GACAC,GAEI,UAA6D,CAC7D,MAAO,oCAAoC,KAAKD,EAAU,WAC9D,EACAE,GAEI,KAAKD,GAETE,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KAAKE,EACb,CACJ,CAOO,GACH0C,EASY,CACZ,OAAO,KAAK,OAAO,CACf,GAAG,KAAK,WAAW,EACnB,cAAeA,CACnB,CAAQ,CACZ,CAMO,SAQS,CACZ,OAAO,KAAK,OAAO,CACf,GAAG,KAAK,WAAW,EACnB,cAAe,MACnB,CAAQ,CACZ,CAKO,UACHC,EAIAJ,EAgBY,CACZ,GAAI,OAAOI,GAAW,UAAYA,EAAS,EACvC,MAAM,IAAI,MAAM,iDAAiD,EACrE,OAAO,KAAK,OAAO,CACf,GAAG,KAAK,WAAW,EACnB,UAAWA,EACX,wCAAyCJ,CAC7C,CAAQ,CACZ,CAKO,gBAQS,CACZ,IAAMG,EAAS,KAAK,WAAW,EAC/B,cAAOA,EAAO,UACP,KAAK,OAAO,CACf,GAAGA,CACP,CAAQ,CACZ,CAKO,UACHC,EAIAJ,EAgBY,CACZ,GAAI,OAAOI,GAAW,UAAYA,EAAS,EACvC,MAAM,IAAI,MAAM,iDAAiD,EACrE,OAAO,KAAK,OAAO,CACf,GAAG,KAAK,WAAW,EACnB,UAAWA,EACX,wCAAyCJ,CAC7C,CAAQ,CACZ,CAKO,gBAQS,CACZ,IAAMG,EAAS,KAAK,WAAW,EAC/B,cAAOA,EAAO,UACP,KAAK,OAAO,CACf,GAAGA,CACP,CAAQ,CACZ,CAKO,UAQS,CACZ,OAAO,MAAM,SAAS,CAC1B,CAKO,aAQS,CACZ,OAAO,MAAM,YAAY,CAC7B,CACJ,EAkBaE,EAGTC,GAEArD,EAAmB,OAAO,CACtB,WAAY,GACZ,cAAAqD,CACJ,CAAC","names":["ArraySchemaBuilder","_ArraySchemaBuilder","SchemaBuilder","#minLength","#defaultMinLengthErrorMessageProvider","#minLengthErrorMessageProvider","#maxLength","#defaultMaxLengthErrorMessageProvider","#maxLengthErrorMessageProvider","#elementSchema","props","_notUsed","#createValidationSetup","object","superResult","valid","prevalidationContext","errors","preValidationTransaction","selfDescriptor","SYMBOL_SCHEMA_PROPERTY_DESCRIPTOR","obj","rootErrors","elementResults","createHybridErrorArray","getNestedErrors","e","objToValidate","#getLengthViolation","#assembleDoNotStopResults","results","allValid","i","r","#elementContext","context","index","descriptor","self","#validateArrayFull","len","resultArray","result","setup","lengthViolation","msg","o","errorMessage","value","_name","schema","length","array","elementSchema"]}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{f as u}from"./chunk-2BKBVVZ3.js";var o=class i extends u{#e;#t;static create(e){return new i({type:"intersection",...e})}constructor(e){super(e),e.left instanceof u&&(this.#e=e.left),e.right instanceof u&&(this.#t=e.right)}introspect(){return{...super.introspect(),left:this.#e,right:this.#t}}get isNullRequiredViolation(){return!1}hasType(e){return this.derive({...this.introspect()},!0)}clearHasType(){return this.derive({...this.introspect()},!0)}validate(e,t){return super.validate(e,t)}async validateAsync(e,t){return super.validateAsync(e,t)}#a(e,t){return typeof e=="object"&&e!==null&&typeof t=="object"&&t!==null&&!Array.isArray(e)&&!Array.isArray(t)?{...e,...t}:t}#r(e){let{valid:t,transaction:a,context:n,errors:l}=e;if(!t)return{needsValidation:!1,result:{valid:t,errors:l}};let{object:{validatedObject:r}}=a;return typeof r>"u"&&!this.isRequired||r===null&&(!this.isRequired||this.isNullable)?{needsValidation:!1,result:{valid:!0,object:r}}:{needsValidation:!0,objToValidate:r,prevalidationContext:n}}_validate(e,t){if(this.canSkipPreValidation&&!t?.doNotStopOnFirstError&&!t?.rootPropertyDescriptor){if(typeof e>"u")if(this.hasDefault)e=this.resolveDefaultValue();else return this.isRequired?{valid:!1,errors:[{message:this.getValidationErrorMessageSync(this.requiredErrorMessage,e)}]}:{valid:!0,object:e};else if(e===null&&(!this.isRequired||this.isNullable))return{valid:!0,object:e};let a=this.#e.validate(e);if(!a.valid)return{valid:!1,errors:a.errors};let n=this.#t.validate(e);return n.valid?{valid:!0,object:this.#a(a.object,n.object)}:{valid:!1,errors:n.errors}}return this.#n(e,t)}#n(e,t){let a=this.#r(this.preValidateSync(e,t));if(!a.needsValidation)return a.result;let{objToValidate:n,prevalidationContext:l}=a,r=this.#e.validate(n,{...l,currentPropertyDescriptor:void 0,rootPropertyDescriptor:void 0});if(!r.valid)return{valid:!1,errors:r.errors};let s=this.#t.validate(n,{...l,currentPropertyDescriptor:void 0,rootPropertyDescriptor:void 0});return s.valid?{valid:!0,object:this.#a(r.object,s.object)}:{valid:!1,errors:s.errors}}async _validateAsync(e,t){let a=this.#r(await super.preValidateAsync(e,t));if(!a.needsValidation)return a.result;let{objToValidate:n,prevalidationContext:l}=a,r=await this.#e.validateAsync(n,{...l,currentPropertyDescriptor:void 0,rootPropertyDescriptor:void 0});if(!r.valid)return{valid:!1,errors:r.errors};let s=await this.#t.validateAsync(n,{...l,currentPropertyDescriptor:void 0,rootPropertyDescriptor:void 0});return s.valid?{valid:!0,object:this.#a(r.object,s.object)}:{valid:!1,errors:s.errors}}createFromProps(e){return i.create(e)}required(e){return super.required(e)}optional(){return super.optional()}default(e){return super.default(e)}clearDefault(){return super.clearDefault()}brand(e){return super.brand(e)}readonly(){return super.readonly()}nullable(){return super.nullable()}notNullable(){return super.notNullable()}get leftSchema(){return this.#e}get rightSchema(){return this.#t}},p=(i,e)=>o.create({isRequired:!0,left:i,right:e});var d=class i extends u{#e;#t=null;static create(e){return new i({type:"lazy",...e})}constructor(e){if(super(e),typeof e.getter!="function")throw new Error("LazySchemaBuilder: getter must be a function");this.#e=e.getter}resolve(){return this.#t===null&&(this.#t=this.#e()),this.#t}introspect(){return{...super.introspect(),getter:this.#e}}#a(e,t){let{valid:a,transaction:n,errors:l}=e;if(!a)return{valid:a,errors:l};let{object:{validatedObject:r}}=n;return r==null?{valid:!0,object:r}:this.resolve().validate(r,t)}validate(e,t){return super.validate(e,t)}async validateAsync(e,t){return super.validateAsync(e,t)}_validate(e,t){return this.#a(this.preValidateSync(e,t),t)}async _validateAsync(e,t){let a=await super.preValidateAsync(e,t),{valid:n,transaction:l,errors:r}=a;if(!n)return{valid:n,errors:r};let{object:{validatedObject:s}}=l;return s==null?{valid:!0,object:s}:this.resolve().validateAsync(s,t)}createFromProps(e){return i.create(e)}hasType(e){return this.derive({...this.introspect()},!0)}clearHasType(){return this.derive({...this.introspect()},!0)}required(e){return super.required(e)}optional(){return super.optional()}default(e){return super.default(e)}clearDefault(){return super.clearDefault()}brand(e){return super.brand(e)}readonly(){return super.readonly()}nullable(){return super.nullable()}notNullable(){return super.notNullable()}};function y(i){return d.create({type:"lazy",isRequired:!0,preprocessors:[],validators:[],getter:i})}var c=class i extends u{static create(e){return new i({type:"null",...e})}constructor(e){super(e)}hasType(e){return this.derive({...this.introspect()},!0)}clearHasType(){return this.derive({...this.introspect()},!0)}#e(e){return e===null?{valid:!0,object:null}:e===void 0&&this.hasDefault?this.resolveDefaultValue()===null?{valid:!0,object:null}:{valid:!1,errors:[{message:"must be null"}]}:e===void 0&&!this.isRequired?{valid:!0,object:void 0}:{valid:!1,errors:[{message:"must be null"}]}}validate(e,t){return super.validate(e,t)}async validateAsync(e,t){return super.validateAsync(e,t)}_validate(e,t){return this.#e(e)}async _validateAsync(e,t){return this.#e(e)}createFromProps(e){return i.create(e)}required(e){return super.required(e)}optional(){return super.optional()}default(e){return super.default(e)}clearDefault(){return super.clearDefault()}brand(e){return super.brand(e)}readonly(){return super.readonly()}nullable(){return super.nullable()}notNullable(){return super.notNullable()}},h=()=>c.create({isRequired:!0});export{o as a,p as b,d as c,y as d,c as e,h as f};
|
|
2
|
+
//# sourceMappingURL=chunk-ZYWDTLNL.js.map
|