@cleverbrush/schema 3.1.0 → 4.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.
Files changed (64) hide show
  1. package/README.md +14 -2
  2. package/dist/builders/AnySchemaBuilder.js +1 -1
  3. package/dist/builders/ArraySchemaBuilder.js +1 -1
  4. package/dist/builders/BooleanSchemaBuilder.js +1 -1
  5. package/dist/builders/DateSchemaBuilder.js +1 -1
  6. package/dist/builders/ExternSchemaBuilder.js +1 -1
  7. package/dist/builders/FunctionSchemaBuilder.js +1 -1
  8. package/dist/builders/NumberSchemaBuilder.js +1 -1
  9. package/dist/builders/ObjectSchemaBuilder.js +1 -1
  10. package/dist/builders/ParseStringSchemaBuilder.d.ts +9 -0
  11. package/dist/builders/ParseStringSchemaBuilder.js +1 -1
  12. package/dist/builders/PromiseSchemaBuilder.js +1 -1
  13. package/dist/builders/RecordSchemaBuilder.js +1 -1
  14. package/dist/builders/SchemaBuilder.d.ts +13 -7
  15. package/dist/builders/StringSchemaBuilder.js +1 -1
  16. package/dist/builders/TupleSchemaBuilder.js +1 -1
  17. package/dist/builders/UnionSchemaBuilder.js +1 -1
  18. package/dist/{chunk-NUW3VXZV.js → chunk-3K7MOEPS.js} +2 -2
  19. package/dist/{chunk-K6Z47OQY.js → chunk-4RMOR7SV.js} +2 -2
  20. package/dist/{chunk-ZFI27R3L.js → chunk-57AZDIBB.js} +2 -2
  21. package/dist/chunk-C4LSLV6T.js +2 -0
  22. package/dist/chunk-C4LSLV6T.js.map +1 -0
  23. package/dist/{chunk-WQDYWDOE.js → chunk-EBGC6ZBF.js} +2 -2
  24. package/dist/{chunk-CFIJQ4GP.js → chunk-ETJPB3TR.js} +2 -2
  25. package/dist/{chunk-WDMJBGBD.js → chunk-FTA66XZT.js} +2 -2
  26. package/dist/{chunk-3JMDGYDT.js → chunk-G6HTNXRO.js} +1 -1
  27. package/dist/chunk-G6HTNXRO.js.map +1 -0
  28. package/dist/{chunk-ZC6YBKCP.js → chunk-OJJHAZZ4.js} +2 -2
  29. package/dist/{chunk-BUEVZ3KA.js → chunk-PUWIYD4T.js} +2 -2
  30. package/dist/{chunk-YQZHDMRF.js → chunk-QG254RGI.js} +2 -2
  31. package/dist/{chunk-PHE4LIAN.js → chunk-QWYVMYJ2.js} +2 -2
  32. package/dist/chunk-SY5EYKF2.js +2 -0
  33. package/dist/chunk-SY5EYKF2.js.map +1 -0
  34. package/dist/{chunk-QARCEYGO.js → chunk-VRRKXJ2H.js} +2 -2
  35. package/dist/{chunk-EIVZX4ZO.js → chunk-YYE5HQCL.js} +2 -2
  36. package/dist/chunk-ZC2HTRZF.js +2 -0
  37. package/dist/chunk-ZC2HTRZF.js.map +1 -0
  38. package/dist/{chunk-HN774HD7.js → chunk-ZHBJ46HB.js} +2 -2
  39. package/dist/core.d.ts +2 -2
  40. package/dist/core.js +1 -1
  41. package/dist/extension.d.ts +76 -4
  42. package/dist/extension.js +2 -0
  43. package/dist/extension.js.map +1 -0
  44. package/dist/index.js +1 -1
  45. package/dist/index.js.map +1 -1
  46. package/package.json +6 -2
  47. package/dist/chunk-3JMDGYDT.js.map +0 -1
  48. package/dist/chunk-DY7J6RNN.js +0 -2
  49. package/dist/chunk-DY7J6RNN.js.map +0 -1
  50. package/dist/chunk-GXPV6UQK.js +0 -2
  51. package/dist/chunk-GXPV6UQK.js.map +0 -1
  52. /package/dist/{chunk-NUW3VXZV.js.map → chunk-3K7MOEPS.js.map} +0 -0
  53. /package/dist/{chunk-K6Z47OQY.js.map → chunk-4RMOR7SV.js.map} +0 -0
  54. /package/dist/{chunk-ZFI27R3L.js.map → chunk-57AZDIBB.js.map} +0 -0
  55. /package/dist/{chunk-WQDYWDOE.js.map → chunk-EBGC6ZBF.js.map} +0 -0
  56. /package/dist/{chunk-CFIJQ4GP.js.map → chunk-ETJPB3TR.js.map} +0 -0
  57. /package/dist/{chunk-WDMJBGBD.js.map → chunk-FTA66XZT.js.map} +0 -0
  58. /package/dist/{chunk-ZC6YBKCP.js.map → chunk-OJJHAZZ4.js.map} +0 -0
  59. /package/dist/{chunk-BUEVZ3KA.js.map → chunk-PUWIYD4T.js.map} +0 -0
  60. /package/dist/{chunk-YQZHDMRF.js.map → chunk-QG254RGI.js.map} +0 -0
  61. /package/dist/{chunk-PHE4LIAN.js.map → chunk-QWYVMYJ2.js.map} +0 -0
  62. /package/dist/{chunk-QARCEYGO.js.map → chunk-VRRKXJ2H.js.map} +0 -0
  63. /package/dist/{chunk-EIVZX4ZO.js.map → chunk-YYE5HQCL.js.map} +0 -0
  64. /package/dist/{chunk-HN774HD7.js.map → chunk-ZHBJ46HB.js.map} +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/builders/GenericSchemaBuilder.ts","../src/extension.ts"],"sourcesContent":["import {\n type BRAND,\n SchemaBuilder,\n type ValidationContext,\n type ValidationErrorMessageProvider,\n type ValidationResult\n} from './SchemaBuilder.js';\n\ntype GenericSchemaBuilderCreateProps<TRequired extends boolean = true> =\n Partial<ReturnType<GenericSchemaBuilder<any, TRequired>['introspect']>>;\n\n/**\n * Schema builder that wraps a generic template function, enabling reusable\n * parameterized schemas. Call {@link GenericSchemaBuilder.apply | `.apply()`}\n * with concrete schema arguments to obtain a fully typed concrete schema\n * builder whose TypeScript type is inferred from the template function's\n * generic signature.\n *\n * **NOTE** this class is exported only to give opportunity to extend it\n * by inheriting. It is not recommended to create an instance of this class\n * directly. Use {@link generic | generic()} function instead.\n *\n * @example Single type parameter\n * ```ts\n * import { generic, object, array, number, string, InferType } from '@cleverbrush/schema';\n *\n * const PaginatedList = generic(\n * <T extends SchemaBuilder<any, any, any, any, any>>(itemSchema: T) =>\n * object({\n * items: array(itemSchema),\n * total: number(),\n * page: number(),\n * })\n * );\n *\n * const userSchema = object({ name: string(), age: number() });\n * const PaginatedUsers = PaginatedList.apply(userSchema);\n *\n * type PaginatedUsersType = InferType<typeof PaginatedUsers>;\n * // → { items: { name: string; age: number }[]; total: number; page: number }\n * ```\n *\n * @example Multiple type parameters\n * ```ts\n * const Result = generic(\n * <T extends SchemaBuilder<any, any, any, any, any>,\n * E extends SchemaBuilder<any, any, any, any, any>>(\n * valueSchema: T,\n * errorSchema: E\n * ) =>\n * object({\n * ok: boolean(),\n * value: valueSchema.optional(),\n * error: errorSchema.optional(),\n * })\n * );\n *\n * const StringResult = Result.apply(string(), number());\n * // InferType → { ok: boolean; value?: string; error?: number }\n * ```\n *\n * @example With default arguments (enables direct `.validate()` on the template)\n * ```ts\n * const AnyList = generic(\n * [any()], // default args — one per template parameter\n * <T extends SchemaBuilder<any, any, any, any, any>>(itemSchema: T) =>\n * object({ items: array(itemSchema), total: number() })\n * );\n *\n * // Validate directly using defaults:\n * AnyList.validate({ items: [1, 'two', true], total: 3 }); // valid\n *\n * // Or apply concrete schemas first:\n * AnyList.apply(string()).validate({ items: ['a', 'b'], total: 2 }); // valid\n * ```\n *\n * @see {@link generic}\n *\n * @typeParam TFn - The generic template function type. Its return type\n * determines `TResult` (the validated value type) when no explicit type\n * override has been applied via `.hasType<T>()`.\n * @typeParam TRequired - `true` when the schema is required (default),\n * `false` after calling `.optional()`. Governs whether `undefined` is a\n * valid value.\n * @typeParam TNullable - `true` after calling `.nullable()`. Governs whether\n * `null` is a valid value.\n * @typeParam TExplicitType - Type override set via `.hasType<T>()`. When\n * `undefined` (the default), `TResult` is derived from `TFn`'s return type.\n * @typeParam THasDefault - `true` after calling `.default(value)`. Governs\n * whether `InferType` emits `T` instead of `T | undefined` for optional\n * schemas with a default.\n * @typeParam TExtensions - Object type carrying extension methods added via\n * `withExtensions()`. Defaults to `{}`.\n * @typeParam TResult - The inferred result type: `TExplicitType` when set,\n * otherwise the value type inferred from `ReturnType<TFn>`.\n */\nexport class GenericSchemaBuilder<\n TFn extends (...args: any[]) => 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 ? ReturnType<TFn> extends SchemaBuilder<infer R, any, any, any, any>\n ? R\n : any\n : TExplicitType\n> extends SchemaBuilder<\n TResult,\n TRequired,\n TNullable,\n THasDefault,\n TExtensions\n> {\n #templateFn?: (...args: any[]) => SchemaBuilder<any, any, any, any, any>;\n #defaults?: readonly any[];\n #cachedDefaultSchema?: SchemaBuilder<any, any, any, any, any>;\n\n /**\n * Applies the template function with concrete schema arguments, returning\n * a fully typed concrete schema builder. TypeScript infers the result type\n * from the template function's own generic signature.\n *\n * The returned builder is independent of this `GenericSchemaBuilder` and\n * can be used like any other schema: `.validate()`, `.optional()`, etc.\n *\n * @example\n * ```ts\n * const Wrapper = generic(\n * <T extends SchemaBuilder<any, any, any, any, any>>(schema: T) =>\n * object({ data: schema })\n * );\n *\n * const s = Wrapper.apply(string());\n * // InferType<typeof s> → { data: string }\n * s.validate({ data: 'hello' }); // { valid: true }\n * ```\n */\n // Set to the actual function in the constructor; declared here for TypeScript.\n public declare readonly apply: TFn;\n\n /**\n * @hidden\n */\n public static create(props: GenericSchemaBuilderCreateProps<any>) {\n return new GenericSchemaBuilder({\n type: 'generic',\n ...props\n });\n }\n\n protected constructor(props: GenericSchemaBuilderCreateProps<TRequired>) {\n super(props as any);\n this.#templateFn = (props as any).templateFn;\n this.#defaults = (props as any).defaults;\n\n // Own property: typed as TFn so generic inference works at call sites.\n (this as any).apply = (...args: any[]) => {\n if (!this.#templateFn) {\n throw new Error(\n 'GenericSchemaBuilder: no template function defined'\n );\n }\n return this.#templateFn(...args);\n };\n }\n\n /**\n * Returns an object describing the current schema configuration.\n *\n * In addition to the base fields exposed by {@link SchemaBuilder.introspect},\n * the following fields are included:\n *\n * - `templateFn` — the template function passed to {@link generic}.\n * - `defaults` — the default argument list passed to the two-argument\n * form of {@link generic}, or `undefined` when no defaults were provided.\n *\n * @example\n * ```ts\n * const schema = generic([string()], <T>(s: T) => object({ data: s }));\n *\n * const info = schema.introspect();\n * // info.type → 'generic'\n * // info.templateFn → [Function]\n * // info.defaults → [StringSchemaBuilder]\n * ```\n */\n public introspect() {\n return {\n ...super.introspect(),\n /** Template function passed to {@link generic}. */\n templateFn: this.#templateFn,\n /** Default positional arguments for the template function, or `undefined`. */\n defaults: this.#defaults\n };\n }\n\n #getOrCreateDefaultSchema():\n | SchemaBuilder<any, any, any, any, any>\n | undefined {\n if (!this.#templateFn || !this.#defaults) {\n return undefined;\n }\n if (!this.#cachedDefaultSchema) {\n this.#cachedDefaultSchema = this.#templateFn(...this.#defaults);\n }\n return this.#cachedDefaultSchema;\n }\n\n #buildResult(\n superResult: ReturnType<\n GenericSchemaBuilder<TFn, TRequired>['preValidateSync']\n >,\n context?: ValidationContext\n ): ValidationResult<TResult> {\n const {\n valid,\n transaction: preValidationTransaction,\n errors\n } = superResult;\n\n if (!valid) {\n return { valid, errors };\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 { valid: true, object: objToValidate };\n }\n\n const defaultSchema = this.#getOrCreateDefaultSchema();\n if (!defaultSchema) {\n return {\n valid: false,\n errors: [\n {\n message:\n 'This is a generic schema template. Call .apply() with concrete schemas to get a validatable schema, or provide default arguments to generic().'\n }\n ]\n };\n }\n\n return defaultSchema.validate(\n objToValidate,\n context\n ) as ValidationResult<TResult>;\n }\n\n async #buildAsyncResult(\n superResult: Awaited<\n ReturnType<GenericSchemaBuilder<TFn, TRequired>['preValidateAsync']>\n >,\n context?: ValidationContext\n ): Promise<ValidationResult<TResult>> {\n const {\n valid,\n transaction: preValidationTransaction,\n errors\n } = superResult;\n\n if (!valid) {\n return { valid, errors };\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 { valid: true, object: objToValidate };\n }\n\n const defaultSchema = this.#getOrCreateDefaultSchema();\n if (!defaultSchema) {\n return {\n valid: false,\n errors: [\n {\n message:\n 'This is a generic schema template. Call .apply() with concrete schemas to get a validatable schema, or provide default arguments to generic().'\n }\n ]\n };\n }\n\n return (await defaultSchema.validateAsync(\n objToValidate,\n context\n )) as ValidationResult<TResult>;\n }\n\n /** {@inheritDoc SchemaBuilder.validate} */\n public validate(\n object: TResult,\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: TResult,\n context?: ValidationContext\n ): Promise<ValidationResult<TResult>> {\n return super.validateAsync(object, context) as Promise<\n ValidationResult<TResult>\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 ): ValidationResult<TResult> {\n return this.#buildResult(\n this.preValidateSync(object, context),\n context\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<ValidationResult<TResult>> {\n return this.#buildAsyncResult(\n await super.preValidateAsync(object, context),\n context\n );\n }\n\n protected createFromProps<TReq extends boolean>(\n props: GenericSchemaBuilderCreateProps<TReq>\n ): this {\n return GenericSchemaBuilder.create(props as any) as any;\n }\n\n /**\n * @hidden\n */\n public hasType<T>(\n _notUsed?: T\n ): GenericSchemaBuilder<TFn, true, TNullable, T, THasDefault, TExtensions> &\n TExtensions {\n return this.createFromProps({\n ...this.introspect()\n } as any) as any;\n }\n\n /**\n * @hidden\n */\n public clearHasType(): GenericSchemaBuilder<\n TFn,\n TRequired,\n TNullable,\n undefined,\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 required(\n errorMessage?: ValidationErrorMessageProvider\n ): GenericSchemaBuilder<\n TFn,\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(): GenericSchemaBuilder<\n TFn,\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 nullable(): GenericSchemaBuilder<\n TFn,\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(): GenericSchemaBuilder<\n TFn,\n TRequired,\n false,\n TExplicitType,\n THasDefault,\n TExtensions\n > &\n TExtensions {\n return super.notNullable() as any;\n }\n\n /**\n * @hidden\n */\n public default(\n value: TResult | (() => TResult)\n ): GenericSchemaBuilder<\n TFn,\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(): GenericSchemaBuilder<\n TFn,\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 ): GenericSchemaBuilder<\n TFn,\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 * @hidden\n */\n public readonly(): GenericSchemaBuilder<\n TFn,\n TRequired,\n TNullable,\n Readonly<TResult>,\n THasDefault,\n TExtensions\n > &\n TExtensions {\n return super.readonly();\n }\n}\n\n/**\n * Creates a generic schema template — a reusable, parameterized schema factory\n * whose TypeScript type is inferred from the template function's generic\n * signature.\n *\n * Call {@link GenericSchemaBuilder.apply | `.apply()`} on the returned builder\n * to instantiate the template with concrete schema arguments and receive a\n * fully typed concrete schema.\n *\n * There are two overloads:\n *\n * 1. **`generic(templateFn)`** — Provide only the template function. The\n * template must be called via `.apply()` before validation.\n * 2. **`generic(defaults, templateFn)`** — Provide positional default arguments\n * followed by the template function. The template can be validated directly\n * using those defaults (without calling `.apply()` first).\n *\n * @param templateFn - A (generic) function that accepts schema arguments and\n * returns a concrete schema. TypeScript infers the result type from this\n * function's generic signature when `.apply()` is called.\n *\n * @returns A new {@link GenericSchemaBuilder} with `isRequired` set to `true`.\n *\n * @example Single type parameter\n * ```ts\n * import { generic, object, array, number, string, any, InferType } from '@cleverbrush/schema';\n *\n * const PaginatedList = generic(\n * <T extends SchemaBuilder<any, any, any, any, any>>(itemSchema: T) =>\n * object({ items: array(itemSchema), total: number(), page: number() })\n * );\n *\n * const UserList = PaginatedList.apply(object({ name: string() }));\n * type UserListType = InferType<typeof UserList>;\n * // → { items: { name: string }[]; total: number; page: number }\n *\n * UserList.validate({ items: [{ name: 'Alice' }], total: 1, page: 1 }); // valid\n * ```\n *\n * @example Multiple type parameters\n * ```ts\n * const Result = generic(\n * <T extends SchemaBuilder<any, any, any, any, any>,\n * E extends SchemaBuilder<any, any, any, any, any>>(\n * valueSchema: T,\n * errorSchema: E\n * ) =>\n * union(\n * object({ ok: boolean().equalsTo(true), value: valueSchema }),\n * object({ ok: boolean().equalsTo(false), error: errorSchema })\n * )\n * );\n *\n * const StringResult = Result.apply(string(), number());\n * ```\n *\n * @example With defaults (enables direct validation on the template)\n * ```ts\n * const AnyList = generic(\n * [any()], // default args — positional, one per template parameter\n * <T extends SchemaBuilder<any, any, any, any, any>>(itemSchema: T) =>\n * object({ items: array(itemSchema), total: number() })\n * );\n *\n * // Validate directly — uses the default any() schema:\n * AnyList.validate({ items: [1, 'two'], total: 2 }); // valid\n *\n * // Or apply concrete schemas first:\n * AnyList.apply(string()).validate({ items: ['x'], total: 1 }); // valid\n * ```\n *\n * @see {@link GenericSchemaBuilder}\n */\nexport function generic<\n TFn extends (...args: any[]) => SchemaBuilder<any, any, any, any, any>\n>(\n templateFn: TFn\n): GenericSchemaBuilder<TFn, true, false, undefined, false, {}>;\nexport function generic<\n TFn extends (...args: any[]) => SchemaBuilder<any, any, any, any, any>\n>(\n defaults: readonly any[],\n templateFn: TFn\n): GenericSchemaBuilder<TFn, true, false, undefined, false, {}>;\nexport function generic<\n TFn extends (...args: any[]) => SchemaBuilder<any, any, any, any, any>\n>(\n fnOrDefaults: TFn | readonly any[],\n templateFn?: TFn\n): GenericSchemaBuilder<TFn, true, false, undefined, false, {}> {\n const fn = templateFn !== undefined ? templateFn : (fnOrDefaults as TFn);\n const defaults =\n templateFn !== undefined ? (fnOrDefaults as readonly any[]) : undefined;\n return GenericSchemaBuilder.create({\n isRequired: true,\n templateFn: fn,\n defaults\n }) as any;\n}\n","/**\n * @module extension\n *\n * The **extension system** for `@cleverbrush/schema` allows third-party and\n * first-party code to add custom methods to any schema builder type\n * (`string`, `number`, `date`, `object`, …) without modifying the core\n * library.\n *\n * ## Overview\n *\n * Extensions follow a two-step workflow:\n *\n * 1. **Define** an extension with {@link defineExtension} — declare which\n * builder types it targets and what methods it adds.\n * 2. **Apply** one or more extensions with {@link withExtensions} — get back\n * augmented factory functions (`string()`, `number()`, …) whose return\n * types include the new methods.\n *\n * ## Ergonomic authoring\n *\n * Extension methods do **not** need to call `withExtension()` manually.\n * The system automatically attaches metadata using the method name as the\n * extension key and the method arguments as the value. This keeps extension\n * definitions concise:\n *\n * ```ts\n * const slugExt = defineExtension({\n * string: {\n * slug(this: StringSchemaBuilder) {\n * return this.addValidator((val) => {\n * const valid = /^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(val);\n * return { valid, errors: valid ? [] : [{ message: 'must be a valid URL slug' }] };\n * });\n * }\n * }\n * });\n * ```\n *\n * If you need **custom metadata** (e.g. a different key or a transformed\n * value), call `this.withExtension(key, value)` explicitly — the auto-infer\n * logic will detect the existing key and skip the automatic attachment.\n *\n * ## Stacking and composition\n *\n * Multiple extensions can target the same builder type. Pass them all to\n * `withExtensions()` and the methods are merged. A runtime error is thrown\n * if two extensions define the same method name on the same builder type.\n *\n * ```ts\n * const s = withExtensions(emailExt, slugExt, rangeExt);\n * const schema = s.string().email().slug(); // both methods available\n * ```\n *\n * ## Introspection\n *\n * Extension metadata is accessible via `schema.introspect().extensions`.\n * Each key corresponds to an extension method name and its value is whatever\n * was passed (or auto-inferred) as the extension data.\n *\n * @see {@link defineExtension} — define an extension\n * @see {@link withExtensions} — apply extensions to builder factories\n * @see {@link ExtensionConfig} — shape of the configuration object\n * @see {@link ExtensionDescriptor} — branded descriptor returned by `defineExtension`\n */\nimport { AnySchemaBuilder, any } from './builders/AnySchemaBuilder.js';\nimport { ArraySchemaBuilder, array } from './builders/ArraySchemaBuilder.js';\nimport {\n BooleanSchemaBuilder,\n boolean\n} from './builders/BooleanSchemaBuilder.js';\nimport { DateSchemaBuilder, date } from './builders/DateSchemaBuilder.js';\nimport {\n FunctionSchemaBuilder,\n func\n} from './builders/FunctionSchemaBuilder.js';\nimport {\n GenericSchemaBuilder,\n generic\n} from './builders/GenericSchemaBuilder.js';\nimport { NumberSchemaBuilder, number } from './builders/NumberSchemaBuilder.js';\nimport { ObjectSchemaBuilder, object } from './builders/ObjectSchemaBuilder.js';\nimport {\n PromiseSchemaBuilder,\n promise\n} from './builders/PromiseSchemaBuilder.js';\nimport { RecordSchemaBuilder, record } from './builders/RecordSchemaBuilder.js';\nimport type {\n PropertyDescriptorTree,\n SchemaBuilder\n} from './builders/SchemaBuilder.js';\nimport { StringSchemaBuilder, string } from './builders/StringSchemaBuilder.js';\nimport { TupleSchemaBuilder, tuple } from './builders/TupleSchemaBuilder.js';\nimport { UnionSchemaBuilder, union } from './builders/UnionSchemaBuilder.js';\n\n// ---------------------------------------------------------------------------\n// Builder type name mapping\n// ---------------------------------------------------------------------------\n\n/**\n * Maps each builder type name to the corresponding generic builder class.\n *\n * Used internally to type-check extension method `this` bindings — for\n * example, an extension targeting `\"string\"` receives `this: StringSchemaBuilder`.\n *\n * @internal Not exported — used only by the extension type machinery.\n */\ntype BuilderMap = {\n string: StringSchemaBuilder<any, any, any, any, any>;\n number: NumberSchemaBuilder<any, any, any, any, any>;\n boolean: BooleanSchemaBuilder<any, any, any, any, any, any, any>;\n date: DateSchemaBuilder<any, any, any, any, any>;\n object: ObjectSchemaBuilder<any, any, any, any, any, any, any>;\n array: ArraySchemaBuilder<any, any, any, any, any, any, any>;\n tuple: TupleSchemaBuilder<any, any, any, any, any, any, any>;\n record: RecordSchemaBuilder<any, any, any, any, any, any, any>;\n union: UnionSchemaBuilder<any, any, any, any, any, any>;\n func: FunctionSchemaBuilder<any, any, any, any, any>;\n any: AnySchemaBuilder<any, any, any, any, any, any>;\n promise: PromiseSchemaBuilder<any, any, any, any, any>;\n generic: GenericSchemaBuilder<any, any, any, any, any, any>;\n};\n\ntype BuilderTypeName = keyof BuilderMap;\n\n// Runtime mapping from type name to the actual class constructor\nconst builderClasses: Record<BuilderTypeName, typeof SchemaBuilder> = {\n string: StringSchemaBuilder as any,\n number: NumberSchemaBuilder as any,\n boolean: BooleanSchemaBuilder as any,\n date: DateSchemaBuilder as any,\n object: ObjectSchemaBuilder as any,\n array: ArraySchemaBuilder as any,\n tuple: TupleSchemaBuilder as any,\n record: RecordSchemaBuilder as any,\n union: UnionSchemaBuilder as any,\n func: FunctionSchemaBuilder as any,\n any: AnySchemaBuilder as any,\n promise: PromiseSchemaBuilder as any,\n generic: GenericSchemaBuilder as any\n};\n\n// Runtime mapping from type name to factory function\nconst builderFactories: Record<BuilderTypeName, (...args: any[]) => any> = {\n string,\n number,\n boolean,\n date,\n object,\n array,\n tuple,\n record,\n union,\n func,\n any,\n promise,\n generic\n};\n\n// ---------------------------------------------------------------------------\n// Extension configuration types\n// ---------------------------------------------------------------------------\n\n/**\n * Defines the shape of an extension configuration object passed to\n * {@link defineExtension}.\n *\n * Each key is a **builder type name** — one of `\"string\"`, `\"number\"`,\n * `\"boolean\"`, `\"date\"`, `\"object\"`, `\"array\"`, `\"union\"`, `\"func\"`, or\n * `\"any\"`. The value is a record of **method implementations** to add to\n * that builder type.\n *\n * Method implementations receive `this` bound to the target builder instance\n * (e.g. `StringSchemaBuilder` for the `\"string\"` key) and **must** return a\n * builder of the same type to support fluent chaining.\n *\n * @remarks\n * Extension methods that only add validators/preprocessors do not need to\n * call `this.withExtension()` — the system will auto-attach metadata using\n * the method name as the key and the arguments as the value. Call\n * `this.withExtension(key, value)` explicitly only when you need custom\n * metadata (e.g. a transformed value or a different key).\n *\n * @example\n * ```ts\n * // Minimal extension config — auto-inferred metadata\n * const config: ExtensionConfig = {\n * string: {\n * slug(this: StringSchemaBuilder) {\n * return this.addValidator((v) => ({ valid: /^[a-z0-9-]+$/.test(v), errors: [] }));\n * }\n * },\n * number: {\n * port(this: NumberSchemaBuilder) {\n * return this.isInteger().min(1).max(65535);\n * }\n * }\n * };\n * ```\n *\n * @see {@link defineExtension}\n */\nexport type ExtensionConfig = {\n [K in BuilderTypeName]?: Record<\n string,\n (this: BuilderMap[K], ...args: any[]) => any\n >;\n};\n\n/**\n * A branded descriptor returned by {@link defineExtension}.\n *\n * The descriptor captures the extension's method signatures at the **type\n * level** so that {@link withExtensions} can produce correctly-typed factory\n * functions. At runtime it holds the (possibly wrapped) configuration object.\n *\n * Extension descriptors are intentionally **opaque** — consumers should not\n * access `config` directly. Instead, pass descriptors to\n * {@link withExtensions} to obtain augmented builder factories.\n *\n * @typeParam T - The concrete {@link ExtensionConfig} shape. Inferred\n * automatically by `defineExtension`; you rarely need to specify it.\n *\n * @example\n * ```ts\n * // The type is inferred — no need to annotate\n * const myExt: ExtensionDescriptor<{ string: { slug: ... } }> = defineExtension({ ... });\n * ```\n *\n * @see {@link defineExtension}\n * @see {@link withExtensions}\n */\nexport type ExtensionDescriptor<T extends ExtensionConfig = ExtensionConfig> = {\n readonly __brand: unique symbol;\n readonly config: T;\n};\n\n// ---------------------------------------------------------------------------\n// Type-level extraction of extension methods per builder type\n// ---------------------------------------------------------------------------\n\n/** Extracts the method signatures an extension adds to a given builder type. */\ntype ExtractMethods<\n TExt extends ExtensionConfig,\n TType extends BuilderTypeName\n> =\n TExt[TType] extends Record<string, (...args: any[]) => any>\n ? TExt[TType]\n : {};\n\n/** Merges the methods from multiple extensions for a given builder type. */\ntype MergeExtensionMethods<\n TExts extends readonly ExtensionDescriptor<any>[],\n TType extends BuilderTypeName\n> = TExts extends readonly [\n ExtensionDescriptor<infer TFirst>,\n ...infer TRest extends readonly ExtensionDescriptor<any>[]\n]\n ? ExtractMethods<TFirst, TType> & MergeExtensionMethods<TRest, TType>\n : {};\n\n// ---------------------------------------------------------------------------\n// Return types for withExtensions()\n// ---------------------------------------------------------------------------\n\n/**\n * Unique string-literal brand key used by {@link FixedMethods} to detect\n * extension methods whose first-argument literal should be accumulated in the\n * return type.\n *\n * Declare the return type of any extension method as\n * `this & { readonly [METHOD_LITERAL_BRAND]?: N }` (where `N extends string`)\n * and `FixedMethods` will automatically make it generic so the literal name\n * flows through the type system and accumulates across multiple calls.\n *\n * This powers scope-name autocomplete in `SchemaQueryBuilder.scoped()`.\n */\nconst METHOD_LITERAL_BRAND = '__cleverbrush_method_literal_brand__' as const;\n\nexport { METHOD_LITERAL_BRAND };\nexport type MethodLiteralBrandSymbol = typeof METHOD_LITERAL_BRAND;\n\n/**\n * Generic accumulator brand for extension methods that want to thread\n * a `Record<name, readonly string[]>` map through the builder chain.\n *\n * Extension authors can declare a method's return type as\n * `this & { readonly [EXTRA_TYPE_BRAND]?: { [name]: TKeys } }`\n * and {@link FixedMethods} will automatically:\n * - Make the first argument const-generic (to capture the literal name).\n * - Make the second argument const-generic when it is a `readonly string[]`\n * tuple (to capture the literal key list).\n * - Accumulate both into the 4th `TExtraTypes` parameter of `FixedMethods`\n * so the information survives subsequent method calls on the same builder.\n *\n * This is deliberately projection-agnostic — any extension that follows the\n * `(name: string, data: readonly string[] | function)` signature convention\n * can use it. Projection-specific semantics (e.g. `PROJECTION_BRAND`) live\n * in the consuming library, not here.\n *\n * @see {@link FixedMethods} for how the accumulation works.\n */\nconst EXTRA_TYPE_BRAND = '__cleverbrush_extra_type_brand__' as const;\n\nexport { EXTRA_TYPE_BRAND };\nexport type ExtraTypeBrandSymbol = typeof EXTRA_TYPE_BRAND;\n\n/** @internal Drops the first element of a tuple type. */\ntype TailArgs<T> = T extends readonly [unknown, ...infer R] ? R : [];\n\n/**\n * Intersected onto consumer-facing builder types to make `withExtension`\n * and `getExtension` uncallable (`never`). Using an intersection instead\n * of `Omit` preserves the class identity so extended builders remain\n * assignable to `SchemaBuilder<any, any, any, any, any>`.\n */\nexport type HiddenExtensionMethods = {\n /** @internal Extension-author only — use inside `defineExtension()`. */\n withExtension: never;\n /** @internal Extension-author only — use inside `defineExtension()`. */\n getExtension: never;\n};\n\n/**\n * Overrides extension method return types so they always return the full\n * extended builder type. This ensures extension methods preserve all other\n * extension methods through chaining (e.g. `s.string().email().slug()`).\n *\n * The self-reference (`FixedMethods` appears in its own mapped return\n * types) is resolved lazily by TypeScript because the recursion sits\n * inside a function-return position within a conditional mapped type.\n *\n * The optional third parameter `TAccum` accumulates literal string names\n * registered by methods whose raw return type includes\n * `{ readonly [METHOD_LITERAL_BRAND]?: any }`. Those methods are rewritten\n * as `const`-generic so the literal flows through; all other methods thread\n * the accumulator unchanged.\n *\n * The optional fourth parameter `TExtraTypes` accumulates a\n * `Record<name, readonly string[]>` map contributed by methods whose raw\n * return type includes `{ readonly [EXTRA_TYPE_BRAND]?: any }`. Those\n * methods are rewritten as const-generic for both the name and the keys\n * tuple so the mapping flows through; all other methods thread it unchanged.\n *\n * For object-schema methods the accessor-form callback parameter is\n * automatically typed as `PropertyDescriptorTree<TBase, TBase>` when\n * `TBase` is an `ObjectSchemaBuilder`, giving callers IDE autocomplete over\n * the schema's own properties.\n */\nexport type FixedMethods<\n TRawMethods,\n TBase,\n TAccum extends string = never,\n TExtraTypes extends Record<string, readonly string[]> = Record<never, never>\n> = {\n [K in keyof TRawMethods]: TRawMethods[K] extends (\n this: any,\n ...args: infer A\n ) => infer R\n ? R extends { readonly [EXTRA_TYPE_BRAND]?: any }\n ? // Extra-type-brand method: rest-param shape `(name, ...columns)`.\n // Each column is a property-name string or an accessor callback.\n // The string-literal union accumulates into `TKey` and lands in\n // the `EXTRA_TYPE_BRAND` under `TName` as `readonly TKey[]`.\n // When `TBase` is an `ObjectSchemaBuilder` the callback `t` is\n // typed as `PropertyDescriptorTree<TBase, TBase>` so callers get\n // IDE autocomplete over the schema's own properties.\n <const TName extends string & A[0], const TKey extends string>(\n name: TName,\n ...columns: ReadonlyArray<\n | TKey\n | (TBase extends ObjectSchemaBuilder<\n any,\n any,\n any,\n any,\n any\n >\n ? (t: PropertyDescriptorTree<TBase, TBase>) => any\n : (t: any) => any)\n >\n ) => TBase &\n FixedMethods<\n TRawMethods,\n TBase,\n TAccum,\n TExtraTypes & Record<TName, readonly TKey[]>\n > &\n HiddenExtensionMethods & {\n readonly [EXTRA_TYPE_BRAND]?: TExtraTypes &\n Record<TName, readonly TKey[]>;\n } & ([TAccum] extends [never]\n ? {}\n : { readonly [METHOD_LITERAL_BRAND]?: TAccum })\n : R extends { readonly [METHOD_LITERAL_BRAND]?: any }\n ? // Literal-brand method: becomes const-generic so the first-arg\n // literal accumulates in TAccum and in the [METHOD_LITERAL_BRAND]\n // property of the return type.\n <const TName extends string & A[0]>(\n name: TName,\n ...rest: TailArgs<A>\n ) => TBase &\n FixedMethods<\n TRawMethods,\n TBase,\n TAccum | TName,\n TExtraTypes\n > &\n HiddenExtensionMethods & {\n readonly [METHOD_LITERAL_BRAND]?: TAccum | TName;\n } & ([keyof TExtraTypes] extends [never]\n ? {}\n : { readonly [EXTRA_TYPE_BRAND]?: TExtraTypes })\n : // Regular method: threads both accumulators through so literals\n // defined earlier in the chain are not lost.\n (\n ...args: A\n ) => TBase &\n FixedMethods<TRawMethods, TBase, TAccum, TExtraTypes> &\n HiddenExtensionMethods &\n ([TAccum] extends [never]\n ? {}\n : { readonly [METHOD_LITERAL_BRAND]?: TAccum }) &\n ([keyof TExtraTypes] extends [never]\n ? {}\n : { readonly [EXTRA_TYPE_BRAND]?: TExtraTypes })\n : TRawMethods[K];\n};\n\n/**\n * Produces the consumer-facing type for an extended builder: the base\n * builder intersected with its fixed extension methods, with\n * `withExtension` / `getExtension` overridden to `never` so they\n * don't appear as callable in consumer code.\n */\nexport type CleanExtended<TBuilder, TExt> = TBuilder &\n FixedMethods<TExt, TBuilder> &\n HiddenExtensionMethods;\n\n// -- Factory types that return builders with corrected extension methods ------\n\ntype ExtendedStringFactory<TExt> = {\n (): CleanExtended<\n StringSchemaBuilder<string, true, false, false, TExt>,\n TExt\n >;\n <T extends string>(\n equals: T\n ): CleanExtended<StringSchemaBuilder<T, true, false, false, TExt>, TExt>;\n};\n\ntype ExtendedNumberFactory<TExt> = {\n (): CleanExtended<\n NumberSchemaBuilder<number, true, false, false, TExt>,\n TExt\n >;\n <T extends number>(\n equals: T\n ): CleanExtended<NumberSchemaBuilder<T, true, false, false, TExt>, TExt>;\n};\n\ntype ExtendedBooleanFactory<TExt> = () => CleanExtended<\n BooleanSchemaBuilder<boolean, true, false, undefined, false, TExt>,\n TExt\n>;\n\ntype ExtendedDateFactory<TExt> = () => CleanExtended<\n DateSchemaBuilder<Date, true, false, false, TExt>,\n TExt\n>;\n\ntype ExtendedObjectFactory<TExt> = <\n P extends Record<string, SchemaBuilder<any, any, any, any, any>>\n>(\n properties?: P\n) => CleanExtended<\n ObjectSchemaBuilder<P, true, false, undefined, false, TExt, []>,\n TExt\n>;\n\ntype ExtendedArrayFactory<TExt> = <\n TElementSchema extends SchemaBuilder<any, any, any, any, any>\n>(\n elementSchema?: TElementSchema\n) => CleanExtended<\n ArraySchemaBuilder<TElementSchema, true, false, undefined, false, TExt>,\n TExt\n>;\n\ntype ExtendedUnionFactory<TExt> = <\n T extends SchemaBuilder<any, any, any, any, any>\n>(\n schema: T\n) => CleanExtended<\n UnionSchemaBuilder<[T], true, false, undefined, false, TExt>,\n TExt\n>;\n\ntype ExtendedFuncFactory<TExt> = () => CleanExtended<\n FunctionSchemaBuilder<true, false, undefined, false, TExt>,\n TExt\n>;\n\ntype ExtendedAnyFactory<TExt> = () => CleanExtended<\n AnySchemaBuilder<true, false, undefined, false, TExt>,\n TExt\n>;\n\ntype ExtendedTupleFactory<TExt> = <\n const TElements extends readonly SchemaBuilder<any, any, any, any, any>[]\n>(\n elements: [...TElements]\n) => CleanExtended<\n TupleSchemaBuilder<TElements, true, false, undefined, false, TExt>,\n TExt\n>;\n\ntype ExtendedRecordFactory<TExt> = <\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) => CleanExtended<\n RecordSchemaBuilder<\n TKeySchema,\n TValueSchema,\n true,\n false,\n undefined,\n false,\n TExt\n >,\n TExt\n>;\n\ntype ExtendedPromiseFactory<TExt> = <\n TSchema extends SchemaBuilder<any, any, any, any, any>\n>(\n resolvedTypeSchema?: TSchema\n) => CleanExtended<\n PromiseSchemaBuilder<true, false, undefined, false, TExt, TSchema>,\n TExt\n>;\n\ntype ExtendedGenericFactory<TExt> = <\n TFn extends (...args: any[]) => SchemaBuilder<any, any, any, any, any>\n>(\n templateFn: TFn\n) => CleanExtended<\n GenericSchemaBuilder<TFn, true, false, undefined, false, TExt>,\n TExt\n>;\n\n/**\n * The return type of {@link withExtensions}.\n *\n * Contains a factory function for every builder type (`string`, `number`,\n * `boolean`, `date`, `object`, `array`, `union`, `func`, `any`). Each\n * factory returns a builder whose type includes the methods contributed\n * by all provided extension descriptors.\n *\n * @typeParam TExts - Tuple of extension descriptors passed to `withExtensions`.\n *\n * @see {@link withExtensions}\n */\ntype WithExtensionsResult<TExts extends readonly ExtensionDescriptor<any>[]> = {\n string: ExtendedStringFactory<MergeExtensionMethods<TExts, 'string'>>;\n number: ExtendedNumberFactory<MergeExtensionMethods<TExts, 'number'>>;\n boolean: ExtendedBooleanFactory<MergeExtensionMethods<TExts, 'boolean'>>;\n date: ExtendedDateFactory<MergeExtensionMethods<TExts, 'date'>>;\n object: ExtendedObjectFactory<MergeExtensionMethods<TExts, 'object'>>;\n array: ExtendedArrayFactory<MergeExtensionMethods<TExts, 'array'>>;\n tuple: ExtendedTupleFactory<MergeExtensionMethods<TExts, 'tuple'>>;\n record: ExtendedRecordFactory<MergeExtensionMethods<TExts, 'record'>>;\n union: ExtendedUnionFactory<MergeExtensionMethods<TExts, 'union'>>;\n func: ExtendedFuncFactory<MergeExtensionMethods<TExts, 'func'>>;\n any: ExtendedAnyFactory<MergeExtensionMethods<TExts, 'any'>>;\n promise: ExtendedPromiseFactory<MergeExtensionMethods<TExts, 'promise'>>;\n generic: ExtendedGenericFactory<MergeExtensionMethods<TExts, 'generic'>>;\n};\n\n// ---------------------------------------------------------------------------\n// Reserved method names — cannot be overridden by extensions\n// ---------------------------------------------------------------------------\n\n/**\n * Method names on `SchemaBuilder` that extensions are **not** allowed to\n * override. An error is thrown at definition time if an extension tries\n * to use any of these names.\n *\n * @internal\n */\nconst RESERVED_METHODS = new Set([\n 'validate',\n 'validateAsync',\n 'parse',\n 'parseAsync',\n 'safeParse',\n 'safeParseAsync',\n 'introspect',\n 'optional',\n 'required',\n 'addPreprocessor',\n 'clearPreprocessors',\n 'addValidator',\n 'clearValidators',\n 'hasType',\n 'clearHasType',\n 'createFromProps',\n 'preValidate',\n 'preValidateSync',\n 'preValidateAsync',\n 'getValidationErrorMessage',\n 'getValidationErrorMessageSync',\n 'assureValidationErrorMessageProvider',\n 'withExtension',\n 'getExtension'\n]);\n\n// ---------------------------------------------------------------------------\n// defineExtension()\n// ---------------------------------------------------------------------------\n\n/**\n * Defines an extension targeting one or more schema builder types.\n *\n * Each extension is a plain object keyed by builder type name (`\"string\"`,\n * `\"number\"`, `\"date\"`, …) whose values are method implementations.\n * Methods receive `this` bound to the builder instance and must return a\n * builder to support fluent chaining.\n *\n * ## Ergonomic metadata (auto-infer)\n *\n * Extension methods **do not** have to call `this.withExtension()`. The\n * system wraps each method and automatically attaches\n * `withExtension(methodName, args)` to the returned builder when the key\n * is not already present. This eliminates the most common source of\n * duplication in extension code.\n *\n * - **Zero-arg methods** → metadata value is `true`\n * - **Single-arg methods** → metadata value is the argument itself\n * - **Multi-arg methods** → metadata value is the arguments array\n *\n * If you need **custom metadata** (e.g. a different key, a transformed\n * value, or a structured object), call `this.withExtension(key, value)`\n * explicitly inside the method — the auto-infer logic detects the existing\n * key and skips automatic attachment.\n *\n * ## Validation\n *\n * `defineExtension` validates the configuration eagerly:\n * - Unknown builder type names throw immediately.\n * - {@link RESERVED_METHODS | Reserved method names} (e.g. `validate`,\n * `introspect`) cannot be overridden.\n * - Non-function values in the method record are rejected.\n *\n * @param config - An {@link ExtensionConfig} object mapping builder type\n * names to method records.\n * @returns A branded {@link ExtensionDescriptor} ready to pass to\n * {@link withExtensions}.\n *\n * @example Simple extension (auto-inferred metadata)\n * ```ts\n * const slugExt = defineExtension({\n * string: {\n * slug(this: StringSchemaBuilder) {\n * return this.addValidator((val) => {\n * const valid = /^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(val);\n * return { valid, errors: valid ? [] : [{ message: 'invalid slug' }] };\n * });\n * }\n * }\n * });\n *\n * // Usage:\n * const s = withExtensions(slugExt);\n * const schema = s.string().slug();\n * schema.introspect().extensions.slug; // true\n * ```\n *\n * @example Extension with custom metadata\n * ```ts\n * const currencyExt = defineExtension({\n * number: {\n * currency(this: NumberSchemaBuilder, opts?: { maxDecimals?: number }) {\n * const maxDec = opts?.maxDecimals ?? 2;\n * return this.withExtension('currency', { maxDecimals: maxDec })\n * .min(0)\n * .addValidator((val) => {\n * const decimals = (String(val).split('.')[1] ?? '').length;\n * const valid = decimals <= maxDec;\n * return { valid, errors: valid ? [] : [{ message: `max ${maxDec} decimals` }] };\n * });\n * }\n * }\n * });\n * ```\n *\n * @example Multi-builder extension\n * ```ts\n * const myExt = defineExtension({\n * string: {\n * email(this: StringSchemaBuilder) { return this.addValidator(...); }\n * },\n * number: {\n * port(this: NumberSchemaBuilder) { return this.isInteger().min(1).max(65535); }\n * }\n * });\n * ```\n *\n * @throws {Error} If a builder type name is unknown.\n * @throws {Error} If a method name is reserved.\n * @throws {Error} If a method value is not a function.\n *\n * @see {@link withExtensions} — apply the defined extension\n * @see {@link ExtensionConfig} — configuration shape\n */\nexport function defineExtension<T extends ExtensionConfig>(\n config: T\n): ExtensionDescriptor<T> {\n // Validate at definition time and wrap methods for auto-infer extension key\n const wrappedConfig: any = {};\n for (const builderName of Object.keys(config) as BuilderTypeName[]) {\n if (!(builderName in builderClasses)) {\n throw new Error(\n `Unknown builder type \"${builderName}\". Valid types: ${Object.keys(builderClasses).join(', ')}`\n );\n }\n\n const methods = config[builderName];\n if (!methods || typeof methods !== 'object') {\n throw new Error(\n `Extension config for \"${builderName}\" must be an object of methods`\n );\n }\n\n wrappedConfig[builderName] = {};\n for (const methodName of Object.keys(methods)) {\n if (RESERVED_METHODS.has(methodName)) {\n throw new Error(\n `Cannot override reserved method \"${methodName}\" on \"${builderName}\"`\n );\n }\n const origMethod = methods[methodName];\n if (typeof origMethod !== 'function') {\n throw new Error(\n `Extension method \"${builderName}.${methodName}\" must be a function`\n );\n }\n // Wrap the method to auto-infer extension key if not already set\n wrappedConfig[builderName][methodName] = function (\n this: any,\n ...args: any[]\n ) {\n const result = (origMethod as any).apply(this, args);\n // If result is a builder and does not have the extension key, auto-apply withExtension\n if (\n result &&\n typeof result === 'object' &&\n typeof result.withExtension === 'function' &&\n // Only auto-apply if the extension key is not already present\n (typeof result.getExtension !== 'function' ||\n result.getExtension(methodName) === undefined)\n ) {\n // Only auto-apply if the original method did not call withExtension\n return result.withExtension(\n methodName,\n args.length === 1\n ? args[0]\n : args.length === 0\n ? true\n : args\n );\n }\n return result;\n };\n }\n }\n\n return { config: wrappedConfig } as ExtensionDescriptor<T>;\n}\n\n// ---------------------------------------------------------------------------\n// withExtensions()\n// ---------------------------------------------------------------------------\n\n/**\n * Creates a set of schema factory functions with the provided extensions\n * applied.\n *\n * Each factory function (`string()`, `number()`, `date()`, …) returned by\n * `withExtensions` produces builder instances whose prototypes include the\n * extension methods. All built-in builder methods remain available and\n * fully chainable alongside the new ones.\n *\n * ## Stacking multiple extensions\n *\n * Pass any number of {@link ExtensionDescriptor}s — their methods are\n * merged per builder type. If two extensions define the **same** method\n * name on the same builder type, a runtime error is thrown to prevent\n * silent conflicts.\n *\n * ## Type safety\n *\n * The return type is fully inferred: TypeScript knows exactly which\n * extension methods are available on each builder factory. Extension\n * methods return the full extended builder type, so chaining like\n * `s.string().email().slug().minLength(3)` is fully typed.\n *\n * ## Builder types without extensions\n *\n * Builders that have no methods from any of the provided extensions\n * use the standard (unextended) factory, so there is zero overhead.\n *\n * @param extensions - One or more {@link ExtensionDescriptor}s created\n * by {@link defineExtension}.\n * @returns An object with factory functions for all builder types\n * (`string`, `number`, `boolean`, `date`, `object`, `array`, `union`,\n * `func`, `any`), each returning augmented builders.\n *\n * @example Basic usage\n * ```ts\n * const s = withExtensions(emailExt, rangeExt);\n *\n * // string() now has .email()\n * const emailSchema = s.string().email().minLength(5);\n *\n * // number() now has .range()\n * const rangeSchema = s.number().range(0, 100);\n *\n * // builders without targeted extensions work as normal\n * const dateSchema = s.date();\n * ```\n *\n * @example Stacking extensions on the same builder\n * ```ts\n * const s = withExtensions(emailExt, slugExt, trimmedExt);\n * const schema = s.string().email().slug().trimmed();\n * ```\n *\n * @example Using extensions in object schemas\n * ```ts\n * const s = withExtensions(emailExt, portExt);\n * const ServerConfig = s.object({\n * host: s.string().email(),\n * port: s.number().port()\n * });\n * ```\n *\n * @throws {Error} If two extensions define the same method name on the\n * same builder type.\n *\n * @see {@link defineExtension} — create extension descriptors\n * @see {@link ExtensionDescriptor}\n */\nexport function withExtensions<\n const TExts extends readonly ExtensionDescriptor<any>[]\n>(...extensions: TExts): WithExtensionsResult<TExts> {\n // Collect all methods per builder type and check for collisions\n const methodsByBuilder = new Map<BuilderTypeName, Map<string, Function>>();\n\n for (const ext of extensions) {\n for (const builderName of Object.keys(\n ext.config\n ) as BuilderTypeName[]) {\n if (!methodsByBuilder.has(builderName)) {\n methodsByBuilder.set(builderName, new Map());\n }\n const methods = methodsByBuilder.get(builderName)!;\n const extMethods = ext.config[builderName]!;\n\n for (const methodName of Object.keys(extMethods)) {\n if (methods.has(methodName)) {\n throw new Error(\n `Extension method collision: \"${methodName}\" is defined by multiple extensions for \"${builderName}\"`\n );\n }\n methods.set(methodName, extMethods[methodName]);\n }\n }\n }\n\n // For each builder type, create a dynamic subclass if there are extension methods\n const factories: Record<string, (...args: any[]) => any> = {};\n\n for (const builderName of Object.keys(\n builderClasses\n ) as BuilderTypeName[]) {\n const methods = methodsByBuilder.get(builderName);\n\n if (!methods || methods.size === 0) {\n // No extensions for this builder type — use the standard factory\n factories[builderName] = builderFactories[builderName];\n continue;\n }\n\n const BaseClass = builderClasses[builderName] as any;\n\n // Create a dynamic subclass\n const ExtendedClass = class extends BaseClass {\n // biome-ignore lint/complexity/noUselessConstructor: required\n constructor(...args: any[]) {\n super(...args);\n }\n\n static create(props: any) {\n return new ExtendedClass({\n ...props\n });\n }\n\n protected createFromProps(props: any): any {\n return ExtendedClass.create(props);\n }\n };\n\n // Add extension methods to the subclass prototype\n for (const [methodName, methodFn] of methods) {\n Object.defineProperty(ExtendedClass.prototype, methodName, {\n value: methodFn,\n writable: true,\n configurable: true,\n enumerable: false\n });\n }\n\n // Create a factory that uses the extended class\n factories[builderName] = (...args: any[]) => {\n // Delegate to the original factory to get an initialized instance,\n // then upgrade its prototype so it gains the extension methods.\n // Note: Object.setPrototypeOf can cause V8 hidden-class deoptimization\n // on the mutated object, but avoids the double allocation and\n // introspect() round-trip of the previous approach.\n const original = builderFactories[builderName](...args);\n Object.setPrototypeOf(original, ExtendedClass.prototype);\n return original;\n };\n }\n\n return factories as WithExtensionsResult<TExts>;\n}\n"],"mappings":"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","names":["GenericSchemaBuilder","_GenericSchemaBuilder","SchemaBuilder","#templateFn","#defaults","#cachedDefaultSchema","props","args","#getOrCreateDefaultSchema","#buildResult","superResult","context","valid","preValidationTransaction","errors","objToValidate","defaultSchema","#buildAsyncResult","object","_notUsed","errorMessage","value","_name","generic","fnOrDefaults","templateFn","fn","defaults","builderClasses","StringSchemaBuilder","NumberSchemaBuilder","BooleanSchemaBuilder","DateSchemaBuilder","ObjectSchemaBuilder","ArraySchemaBuilder","TupleSchemaBuilder","RecordSchemaBuilder","UnionSchemaBuilder","FunctionSchemaBuilder","AnySchemaBuilder","PromiseSchemaBuilder","GenericSchemaBuilder","builderFactories","string","number","boolean","date","object","array","tuple","record","union","func","any","promise","generic","METHOD_LITERAL_BRAND","EXTRA_TYPE_BRAND","RESERVED_METHODS","defineExtension","config","wrappedConfig","builderName","builderClasses","methods","methodName","origMethod","args","result","withExtensions","extensions","methodsByBuilder","ext","extMethods","factories","builderFactories","BaseClass","ExtendedClass","props","methodFn","original"]}
@@ -1,2 +1,2 @@
1
- import{f as n}from"./chunk-3JMDGYDT.js";var a=class l extends n{static create(e){return new l({type:"any",...e})}constructor(e){super(e)}hasType(e){return this.createFromProps({...this.introspect()})}clearHasType(){return this.createFromProps({...this.introspect()})}#e(e){let{valid:t,transaction:s,errors:i}=e;if(!t)return{valid:t,errors:i};let{object:{validatedObject:r}}=s;return{valid:!0,object:r}}validate(e,t){return super.validate(e,t)}async validateAsync(e,t){return super.validateAsync(e,t)}_validate(e,t){return this.#e(this.preValidateSync(e,t))}async _validateAsync(e,t){return this.#e(await super.preValidateAsync(e,t))}createFromProps(e){return l.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()}},o=()=>a.create({isRequired:!0});export{a,o as b};
2
- //# sourceMappingURL=chunk-HN774HD7.js.map
1
+ import{f as n}from"./chunk-G6HTNXRO.js";var a=class l extends n{static create(e){return new l({type:"any",...e})}constructor(e){super(e)}hasType(e){return this.createFromProps({...this.introspect()})}clearHasType(){return this.createFromProps({...this.introspect()})}#e(e){let{valid:t,transaction:s,errors:i}=e;if(!t)return{valid:t,errors:i};let{object:{validatedObject:r}}=s;return{valid:!0,object:r}}validate(e,t){return super.validate(e,t)}async validateAsync(e,t){return super.validateAsync(e,t)}_validate(e,t){return this.#e(this.preValidateSync(e,t))}async _validateAsync(e,t){return this.#e(await super.preValidateAsync(e,t))}createFromProps(e){return l.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()}},o=()=>a.create({isRequired:!0});export{a,o as b};
2
+ //# sourceMappingURL=chunk-ZHBJ46HB.js.map
package/dist/core.d.ts CHANGED
@@ -24,5 +24,5 @@ export type { TupleElementValidationResults, TupleSchemaValidationResult } from
24
24
  export { TupleSchemaBuilder, tuple } from './builders/TupleSchemaBuilder.js';
25
25
  export type { OptionValidationResults, UnionSchemaValidationResult } from './builders/UnionSchemaBuilder.js';
26
26
  export { UnionSchemaBuilder, union } from './builders/UnionSchemaBuilder.js';
27
- export type { CleanExtended, ExtensionConfig, ExtensionDescriptor, FixedMethods, HiddenExtensionMethods } from './extension.js';
28
- export { defineExtension, withExtensions } from './extension.js';
27
+ export type { CleanExtended, ExtensionConfig, ExtensionDescriptor, ExtraTypeBrandSymbol, FixedMethods, HiddenExtensionMethods, MethodLiteralBrandSymbol } from './extension.js';
28
+ export { defineExtension, EXTRA_TYPE_BRAND, METHOD_LITERAL_BRAND, withExtensions } from './extension.js';
package/dist/core.js CHANGED
@@ -1,2 +1,2 @@
1
- import{a as q,b as r,c as s,d as t,e as u,f as v,g as M,h as N}from"./chunk-GXPV6UQK.js";import{a as w,b as x}from"./chunk-BUEVZ3KA.js";import{a as A,b as B}from"./chunk-DY7J6RNN.js";import{a as y,b as z}from"./chunk-K6Z47OQY.js";import{a as C,b as D}from"./chunk-WDMJBGBD.js";import{a as E,b as F}from"./chunk-ZFI27R3L.js";import{a as G,b as H}from"./chunk-YQZHDMRF.js";import{a as I,b as J}from"./chunk-QARCEYGO.js";import{a as K,b as L}from"./chunk-WQDYWDOE.js";import{a as e,b as f}from"./chunk-HN774HD7.js";import{a as g,b as h}from"./chunk-NUW3VXZV.js";import{a as i,b as j}from"./chunk-CFIJQ4GP.js";import{a as k,b as l}from"./chunk-EIVZX4ZO.js";import{a as m,b as n}from"./chunk-PHE4LIAN.js";import{a as o,b as p}from"./chunk-ZC6YBKCP.js";import{b as a,c as b,d as c,f as d}from"./chunk-3JMDGYDT.js";export{e as AnySchemaBuilder,g as ArraySchemaBuilder,i as BooleanSchemaBuilder,k as DateSchemaBuilder,m as ExternSchemaBuilder,o as FunctionSchemaBuilder,q as GenericSchemaBuilder,s as LazySchemaBuilder,u as NullSchemaBuilder,w as NumberSchemaBuilder,y as ObjectSchemaBuilder,A as ParseStringSchemaBuilder,C as PromiseSchemaBuilder,E as RecordSchemaBuilder,c as SYMBOL_HAS_PROPERTIES,b as SYMBOL_SCHEMA_PROPERTY_DESCRIPTOR,d as SchemaBuilder,a as SchemaValidationError,G as StringSchemaBuilder,I as TupleSchemaBuilder,K as UnionSchemaBuilder,f as any,h as array,j as boolean,l as date,M as defineExtension,n as extern,p as func,r as generic,t as lazy,v as nul,x as number,z as object,B as parseString,D as promise,F as record,H as string,J as tuple,L as union,N as withExtensions};
1
+ import{a as s,b as t,c as u,d as v}from"./chunk-C4LSLV6T.js";import{a as A,b as B}from"./chunk-SY5EYKF2.js";import{a as q,b as r,c as M,d as N,e as O,f as P}from"./chunk-ZC2HTRZF.js";import{a as K,b as L}from"./chunk-EBGC6ZBF.js";import{a as o,b as p}from"./chunk-OJJHAZZ4.js";import{a as w,b as x}from"./chunk-PUWIYD4T.js";import{a as y,b as z}from"./chunk-4RMOR7SV.js";import{a as C,b as D}from"./chunk-FTA66XZT.js";import{a as E,b as F}from"./chunk-57AZDIBB.js";import{a as G,b as H}from"./chunk-QG254RGI.js";import{a as I,b as J}from"./chunk-VRRKXJ2H.js";import{a as e,b as f}from"./chunk-ZHBJ46HB.js";import{a as g,b as h}from"./chunk-3K7MOEPS.js";import{a as i,b as j}from"./chunk-ETJPB3TR.js";import{a as k,b as l}from"./chunk-YYE5HQCL.js";import{a as m,b as n}from"./chunk-QWYVMYJ2.js";import{b as a,c as b,d as c,f as d}from"./chunk-G6HTNXRO.js";export{e as AnySchemaBuilder,g as ArraySchemaBuilder,i as BooleanSchemaBuilder,k as DateSchemaBuilder,N as EXTRA_TYPE_BRAND,m as ExternSchemaBuilder,o as FunctionSchemaBuilder,q as GenericSchemaBuilder,s as LazySchemaBuilder,M as METHOD_LITERAL_BRAND,u as NullSchemaBuilder,w as NumberSchemaBuilder,y as ObjectSchemaBuilder,A as ParseStringSchemaBuilder,C as PromiseSchemaBuilder,E as RecordSchemaBuilder,c as SYMBOL_HAS_PROPERTIES,b as SYMBOL_SCHEMA_PROPERTY_DESCRIPTOR,d as SchemaBuilder,a as SchemaValidationError,G as StringSchemaBuilder,I as TupleSchemaBuilder,K as UnionSchemaBuilder,f as any,h as array,j as boolean,l as date,O as defineExtension,n as extern,p as func,r as generic,t as lazy,v as nul,x as number,z as object,B as parseString,D as promise,F as record,H as string,J as tuple,L as union,P as withExtensions};
2
2
  //# sourceMappingURL=core.js.map
@@ -72,7 +72,7 @@ import { NumberSchemaBuilder } from './builders/NumberSchemaBuilder.js';
72
72
  import { ObjectSchemaBuilder } from './builders/ObjectSchemaBuilder.js';
73
73
  import { PromiseSchemaBuilder } from './builders/PromiseSchemaBuilder.js';
74
74
  import { RecordSchemaBuilder } from './builders/RecordSchemaBuilder.js';
75
- import type { SchemaBuilder } from './builders/SchemaBuilder.js';
75
+ import type { PropertyDescriptorTree, SchemaBuilder } from './builders/SchemaBuilder.js';
76
76
  import { StringSchemaBuilder } from './builders/StringSchemaBuilder.js';
77
77
  import { TupleSchemaBuilder } from './builders/TupleSchemaBuilder.js';
78
78
  import { UnionSchemaBuilder } from './builders/UnionSchemaBuilder.js';
@@ -176,6 +176,46 @@ type MergeExtensionMethods<TExts extends readonly ExtensionDescriptor<any>[], TT
176
176
  ExtensionDescriptor<infer TFirst>,
177
177
  ...infer TRest extends readonly ExtensionDescriptor<any>[]
178
178
  ] ? ExtractMethods<TFirst, TType> & MergeExtensionMethods<TRest, TType> : {};
179
+ /**
180
+ * Unique string-literal brand key used by {@link FixedMethods} to detect
181
+ * extension methods whose first-argument literal should be accumulated in the
182
+ * return type.
183
+ *
184
+ * Declare the return type of any extension method as
185
+ * `this & { readonly [METHOD_LITERAL_BRAND]?: N }` (where `N extends string`)
186
+ * and `FixedMethods` will automatically make it generic so the literal name
187
+ * flows through the type system and accumulates across multiple calls.
188
+ *
189
+ * This powers scope-name autocomplete in `SchemaQueryBuilder.scoped()`.
190
+ */
191
+ declare const METHOD_LITERAL_BRAND: "__cleverbrush_method_literal_brand__";
192
+ export { METHOD_LITERAL_BRAND };
193
+ export type MethodLiteralBrandSymbol = typeof METHOD_LITERAL_BRAND;
194
+ /**
195
+ * Generic accumulator brand for extension methods that want to thread
196
+ * a `Record<name, readonly string[]>` map through the builder chain.
197
+ *
198
+ * Extension authors can declare a method's return type as
199
+ * `this & { readonly [EXTRA_TYPE_BRAND]?: { [name]: TKeys } }`
200
+ * and {@link FixedMethods} will automatically:
201
+ * - Make the first argument const-generic (to capture the literal name).
202
+ * - Make the second argument const-generic when it is a `readonly string[]`
203
+ * tuple (to capture the literal key list).
204
+ * - Accumulate both into the 4th `TExtraTypes` parameter of `FixedMethods`
205
+ * so the information survives subsequent method calls on the same builder.
206
+ *
207
+ * This is deliberately projection-agnostic — any extension that follows the
208
+ * `(name: string, data: readonly string[] | function)` signature convention
209
+ * can use it. Projection-specific semantics (e.g. `PROJECTION_BRAND`) live
210
+ * in the consuming library, not here.
211
+ *
212
+ * @see {@link FixedMethods} for how the accumulation works.
213
+ */
214
+ declare const EXTRA_TYPE_BRAND: "__cleverbrush_extra_type_brand__";
215
+ export { EXTRA_TYPE_BRAND };
216
+ export type ExtraTypeBrandSymbol = typeof EXTRA_TYPE_BRAND;
217
+ /** @internal Drops the first element of a tuple type. */
218
+ type TailArgs<T> = T extends readonly [unknown, ...infer R] ? R : [];
179
219
  /**
180
220
  * Intersected onto consumer-facing builder types to make `withExtension`
181
221
  * and `getExtension` uncallable (`never`). Using an intersection instead
@@ -196,9 +236,42 @@ export type HiddenExtensionMethods = {
196
236
  * The self-reference (`FixedMethods` appears in its own mapped return
197
237
  * types) is resolved lazily by TypeScript because the recursion sits
198
238
  * inside a function-return position within a conditional mapped type.
239
+ *
240
+ * The optional third parameter `TAccum` accumulates literal string names
241
+ * registered by methods whose raw return type includes
242
+ * `{ readonly [METHOD_LITERAL_BRAND]?: any }`. Those methods are rewritten
243
+ * as `const`-generic so the literal flows through; all other methods thread
244
+ * the accumulator unchanged.
245
+ *
246
+ * The optional fourth parameter `TExtraTypes` accumulates a
247
+ * `Record<name, readonly string[]>` map contributed by methods whose raw
248
+ * return type includes `{ readonly [EXTRA_TYPE_BRAND]?: any }`. Those
249
+ * methods are rewritten as const-generic for both the name and the keys
250
+ * tuple so the mapping flows through; all other methods thread it unchanged.
251
+ *
252
+ * For object-schema methods the accessor-form callback parameter is
253
+ * automatically typed as `PropertyDescriptorTree<TBase, TBase>` when
254
+ * `TBase` is an `ObjectSchemaBuilder`, giving callers IDE autocomplete over
255
+ * the schema's own properties.
199
256
  */
200
- export type FixedMethods<TRawMethods, TBase> = {
201
- [K in keyof TRawMethods]: TRawMethods[K] extends (this: any, ...args: infer A) => any ? (...args: A) => TBase & FixedMethods<TRawMethods, TBase> & HiddenExtensionMethods : TRawMethods[K];
257
+ export type FixedMethods<TRawMethods, TBase, TAccum extends string = never, TExtraTypes extends Record<string, readonly string[]> = Record<never, never>> = {
258
+ [K in keyof TRawMethods]: TRawMethods[K] extends (this: any, ...args: infer A) => infer R ? R extends {
259
+ readonly [EXTRA_TYPE_BRAND]?: any;
260
+ } ? <const TName extends string & A[0], const TKey extends string>(name: TName, ...columns: ReadonlyArray<TKey | (TBase extends ObjectSchemaBuilder<any, any, any, any, any> ? (t: PropertyDescriptorTree<TBase, TBase>) => any : (t: any) => any)>) => TBase & FixedMethods<TRawMethods, TBase, TAccum, TExtraTypes & Record<TName, readonly TKey[]>> & HiddenExtensionMethods & {
261
+ readonly [EXTRA_TYPE_BRAND]?: TExtraTypes & Record<TName, readonly TKey[]>;
262
+ } & ([TAccum] extends [never] ? {} : {
263
+ readonly [METHOD_LITERAL_BRAND]?: TAccum;
264
+ }) : R extends {
265
+ readonly [METHOD_LITERAL_BRAND]?: any;
266
+ } ? <const TName extends string & A[0]>(name: TName, ...rest: TailArgs<A>) => TBase & FixedMethods<TRawMethods, TBase, TAccum | TName, TExtraTypes> & HiddenExtensionMethods & {
267
+ readonly [METHOD_LITERAL_BRAND]?: TAccum | TName;
268
+ } & ([keyof TExtraTypes] extends [never] ? {} : {
269
+ readonly [EXTRA_TYPE_BRAND]?: TExtraTypes;
270
+ }) : (...args: A) => TBase & FixedMethods<TRawMethods, TBase, TAccum, TExtraTypes> & HiddenExtensionMethods & ([TAccum] extends [never] ? {} : {
271
+ readonly [METHOD_LITERAL_BRAND]?: TAccum;
272
+ }) & ([keyof TExtraTypes] extends [never] ? {} : {
273
+ readonly [EXTRA_TYPE_BRAND]?: TExtraTypes;
274
+ }) : TRawMethods[K];
202
275
  };
203
276
  /**
204
277
  * Produces the consumer-facing type for an extended builder: the base
@@ -418,4 +491,3 @@ export declare function defineExtension<T extends ExtensionConfig>(config: T): E
418
491
  * @see {@link ExtensionDescriptor}
419
492
  */
420
493
  export declare function withExtensions<const TExts extends readonly ExtensionDescriptor<any>[]>(...extensions: TExts): WithExtensionsResult<TExts>;
421
- export {};
@@ -0,0 +1,2 @@
1
+ import{c as a,d as b,e as c,f as d}from"./chunk-ZC2HTRZF.js";import"./chunk-EBGC6ZBF.js";import"./chunk-OJJHAZZ4.js";import"./chunk-PUWIYD4T.js";import"./chunk-4RMOR7SV.js";import"./chunk-FTA66XZT.js";import"./chunk-57AZDIBB.js";import"./chunk-QG254RGI.js";import"./chunk-VRRKXJ2H.js";import"./chunk-ZHBJ46HB.js";import"./chunk-3K7MOEPS.js";import"./chunk-ETJPB3TR.js";import"./chunk-YYE5HQCL.js";import"./chunk-G6HTNXRO.js";export{b as EXTRA_TYPE_BRAND,a as METHOD_LITERAL_BRAND,c as defineExtension,d as withExtensions};
2
+ //# sourceMappingURL=extension.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- import{a as Y,b as Z,c as E,d as g,e as ee,f as re,g as u,h as p}from"./chunk-GXPV6UQK.js";import{a as ne}from"./chunk-BUEVZ3KA.js";import{a as B,b}from"./chunk-DY7J6RNN.js";import{a as te}from"./chunk-K6Z47OQY.js";import{a as T}from"./chunk-WDMJBGBD.js";import{a as V}from"./chunk-ZFI27R3L.js";import{a as ie}from"./chunk-YQZHDMRF.js";import{a as v}from"./chunk-QARCEYGO.js";import{a as ae}from"./chunk-WQDYWDOE.js";import{a as C}from"./chunk-HN774HD7.js";import{a as W}from"./chunk-NUW3VXZV.js";import{a as _}from"./chunk-CFIJQ4GP.js";import{a as G}from"./chunk-EIVZX4ZO.js";import{a as J,b as Q}from"./chunk-PHE4LIAN.js";import{a as X}from"./chunk-ZC6YBKCP.js";import{b as I,c as L,d as K,f as z}from"./chunk-3JMDGYDT.js";function i(e,r,n,a){return{valid:!1,errors:[{message:M(e,r,n,a)}]}}function M(e,r,n,a){if(e===void 0)return r;if(typeof e=="string")return e;let t=e(n,a);if(t instanceof Promise)throw new Error("Async error message providers require validateAsync(). Use a string or sync function instead.");return t}var l=u({array:{nonempty(e){return this.withExtension("nonempty",!0).addValidator(r=>Array.isArray(r)?r.length>0?{valid:!0,errors:[]}:i(e,"must not be empty",r,this):i(e,"must not be empty",r,this))},unique(e,r){let n=e??!0;return this.withExtension("unique",n).addValidator(a=>{if(!Array.isArray(a))return i(r,"must contain unique elements",a,this);let t=new Set;for(let s of a){let d=e?e(s):s;if(t.has(d))return i(r,"must contain unique elements",a,this);t.add(d)}return{valid:!0,errors:[]}})}}});var m=u({number:{positive(e){return this.withExtension("positive",!0).addValidator(r=>typeof r!="number"?i(e,"must be a positive number",r,this):r>0?{valid:!0,errors:[]}:i(e,"must be a positive number",r,this))},negative(e){return this.withExtension("negative",!0).addValidator(r=>typeof r!="number"?i(e,"must be a negative number",r,this):r<0?{valid:!0,errors:[]}:i(e,"must be a negative number",r,this))},finite(e){return this.withExtension("finite",!0).addValidator(r=>typeof r!="number"?i(e,"must be a finite number",r,this):Number.isFinite(r)?{valid:!0,errors:[]}:i(e,"must be a finite number",r,this))},multipleOf(e,r){if(e===0||!Number.isFinite(e))throw new Error("multipleOf: n must be a finite, non-zero number");return this.withExtension("multipleOf",e).addValidator(n=>{if(typeof n!="number")return i(r,`must be a multiple of ${e}`,n,this);let a=Math.abs(n%e),t=Math.abs(e)*1e-10;return a<t||Math.abs(a-Math.abs(e))<t?{valid:!0,errors:[]}:i(r,`must be a multiple of ${e}`,n,this)})},oneOf(...e){let r,n;if(e.length===0)throw new Error("oneOf requires at least one value");if(Array.isArray(e[0]))r=e[0],n=e[1];else{let t=e[e.length-1];typeof t=="string"||typeof t=="function"?(r=e.slice(0,-1),n=t):(r=e,n=void 0)}if(r.length===0)throw new Error("oneOf requires at least one value");let a=new Set(r);return this.withExtension("oneOf",r).addValidator(t=>typeof t=="number"&&a.has(t)?{valid:!0,errors:[]}:i(n,`must be one of: ${r.join(", ")}`,t,this))}}});var P=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,f=/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,S=/^(?:[0-9a-f]{1,4}:){7}[0-9a-f]{1,4}$|^::(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4}$|^(?:[0-9a-f]{1,4}:){1,6}:[0-9a-f]{1,4}$|^(?:[0-9a-f]{1,4}:){1,5}(?::[0-9a-f]{1,4}){1,2}$|^(?:[0-9a-f]{1,4}:){1,4}(?::[0-9a-f]{1,4}){1,3}$|^(?:[0-9a-f]{1,4}:){1,3}(?::[0-9a-f]{1,4}){1,4}$|^(?:[0-9a-f]{1,4}:){1,2}(?::[0-9a-f]{1,4}){1,5}$|^[0-9a-f]{1,4}:(?::[0-9a-f]{1,4}){1,6}$|^::$/i,y=u({string:{email(e){return this.withExtension("email",!0).addValidator(r=>typeof r!="string"?i(e,"must be a valid email",r,this):/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(r)?{valid:!0,errors:[]}:i(e,"must be a valid email",r,this))},url(e,r){let n;if(typeof e=="string"||typeof e=="function"?(r=e,n=void 0):n=e,n?.protocols!==void 0&&(n.protocols.length===0||n.protocols.some(s=>!s||s.trim()==="")))throw new Error("url: opts.protocols must be a non-empty array of non-empty strings");let a=n?.protocols??["http","https"],t=n?.protocols?{protocols:n.protocols}:!0;return this.withExtension("url",t).addValidator(s=>{if(typeof s!="string")return i(r,"must be a valid URL",s,this);let d=!1,h="must be a valid URL";try{let x=new URL(s).protocol.replace(":","");d=a.includes(x),d||(h=`protocol must be one of: ${a.join(", ")}`)}catch{}return d?{valid:!0,errors:[]}:i(r,h,s,this)})},uuid(e){return this.withExtension("uuid",!0).addValidator(r=>typeof r!="string"?i(e,"must be a valid UUID",r,this):P.test(r)?{valid:!0,errors:[]}:i(e,"must be a valid UUID",r,this))},ip(e,r){let n=e?.version,a=n?{version:n}:!0;return this.withExtension("ip",a).addValidator(t=>{let s=n?`must be a valid ${n} IP address`:"must be a valid IP address";if(typeof t!="string")return i(r,s,t,this);let d;return n==="v4"?d=f.test(t):n==="v6"?d=S.test(t):d=f.test(t)||S.test(t),d?{valid:!0,errors:[]}:i(r,s,t,this)})},trim(){return this.addPreprocessor(e=>typeof e=="string"?e.trim():e)},toLowerCase(){return this.addPreprocessor(e=>typeof e=="string"?e.toLowerCase():e)},nonempty(e){return this.withExtension("nonempty",!0).addValidator(r=>typeof r!="string"?i(e,"must not be empty",r,this):r.length>0?{valid:!0,errors:[]}:i(e,"must not be empty",r,this))},oneOf(...e){let r,n;if(e.length===0)throw new Error("oneOf requires at least one value");if(Array.isArray(e[0]))r=e[0],n=e[1];else{let t=e[e.length-1];typeof t=="function"?(r=e.slice(0,-1),n=t):(r=e,n=void 0)}if(r.length===0)throw new Error("oneOf requires at least one value");let a=new Set(r);return this.withExtension("oneOf",r).addValidator(t=>typeof t=="string"&&a.has(t)?{valid:!0,errors:[]}:i(n,`must be one of: ${r.join(", ")}`,t,this))}}});var o=p(y,m,l),c=o.string,w=o.number,N=o.array,O=o.boolean,A=o.date,R=o.object,j=o.union,H=o.func,$=o.any,U=o.tuple,k=o.record,F=o.promise;function q(...e){return Array.isArray(e[0])?c().oneOf(e[0],e[1]):c().oneOf(...e)}export{C as AnySchemaBuilder,W as ArraySchemaBuilder,_ as BooleanSchemaBuilder,G as DateSchemaBuilder,J as ExternSchemaBuilder,X as FunctionSchemaBuilder,Y as GenericSchemaBuilder,E as LazySchemaBuilder,ee as NullSchemaBuilder,ne as NumberSchemaBuilder,te as ObjectSchemaBuilder,B as ParseStringSchemaBuilder,T as PromiseSchemaBuilder,V as RecordSchemaBuilder,K as SYMBOL_HAS_PROPERTIES,L as SYMBOL_SCHEMA_PROPERTY_DESCRIPTOR,z as SchemaBuilder,I as SchemaValidationError,ie as StringSchemaBuilder,v as TupleSchemaBuilder,ae as UnionSchemaBuilder,$ as any,N as array,l as arrayExtensions,O as boolean,A as date,u as defineExtension,q as enumOf,Q as extern,H as func,Z as generic,g as lazy,re as nul,w as number,m as numberExtensions,R as object,b as parseString,F as promise,k as record,c as string,y as stringExtensions,U as tuple,j as union,p as withExtensions};
1
+ import{a as E,b as g,c as ee,d as re}from"./chunk-C4LSLV6T.js";import{a as B,b}from"./chunk-SY5EYKF2.js";import{a as Y,b as Z,c as se,d as oe,e as u,f as p}from"./chunk-ZC2HTRZF.js";import{a as ae}from"./chunk-EBGC6ZBF.js";import{a as X}from"./chunk-OJJHAZZ4.js";import{a as ne}from"./chunk-PUWIYD4T.js";import{a as te}from"./chunk-4RMOR7SV.js";import{a as T}from"./chunk-FTA66XZT.js";import{a as V}from"./chunk-57AZDIBB.js";import{a as ie}from"./chunk-QG254RGI.js";import{a as v}from"./chunk-VRRKXJ2H.js";import{a as C}from"./chunk-ZHBJ46HB.js";import{a as W}from"./chunk-3K7MOEPS.js";import{a as _}from"./chunk-ETJPB3TR.js";import{a as G}from"./chunk-YYE5HQCL.js";import{a as J,b as Q}from"./chunk-QWYVMYJ2.js";import{b as I,c as L,d as K,f as z}from"./chunk-G6HTNXRO.js";function i(e,r,n,a){return{valid:!1,errors:[{message:M(e,r,n,a)}]}}function M(e,r,n,a){if(e===void 0)return r;if(typeof e=="string")return e;let t=e(n,a);if(t instanceof Promise)throw new Error("Async error message providers require validateAsync(). Use a string or sync function instead.");return t}var l=u({array:{nonempty(e){return this.withExtension("nonempty",!0).addValidator(r=>Array.isArray(r)?r.length>0?{valid:!0,errors:[]}:i(e,"must not be empty",r,this):i(e,"must not be empty",r,this))},unique(e,r){let n=e??!0;return this.withExtension("unique",n).addValidator(a=>{if(!Array.isArray(a))return i(r,"must contain unique elements",a,this);let t=new Set;for(let s of a){let d=e?e(s):s;if(t.has(d))return i(r,"must contain unique elements",a,this);t.add(d)}return{valid:!0,errors:[]}})}}});var m=u({number:{positive(e){return this.withExtension("positive",!0).addValidator(r=>typeof r!="number"?i(e,"must be a positive number",r,this):r>0?{valid:!0,errors:[]}:i(e,"must be a positive number",r,this))},negative(e){return this.withExtension("negative",!0).addValidator(r=>typeof r!="number"?i(e,"must be a negative number",r,this):r<0?{valid:!0,errors:[]}:i(e,"must be a negative number",r,this))},finite(e){return this.withExtension("finite",!0).addValidator(r=>typeof r!="number"?i(e,"must be a finite number",r,this):Number.isFinite(r)?{valid:!0,errors:[]}:i(e,"must be a finite number",r,this))},multipleOf(e,r){if(e===0||!Number.isFinite(e))throw new Error("multipleOf: n must be a finite, non-zero number");return this.withExtension("multipleOf",e).addValidator(n=>{if(typeof n!="number")return i(r,`must be a multiple of ${e}`,n,this);let a=Math.abs(n%e),t=Math.abs(e)*1e-10;return a<t||Math.abs(a-Math.abs(e))<t?{valid:!0,errors:[]}:i(r,`must be a multiple of ${e}`,n,this)})},oneOf(...e){let r,n;if(e.length===0)throw new Error("oneOf requires at least one value");if(Array.isArray(e[0]))r=e[0],n=e[1];else{let t=e[e.length-1];typeof t=="string"||typeof t=="function"?(r=e.slice(0,-1),n=t):(r=e,n=void 0)}if(r.length===0)throw new Error("oneOf requires at least one value");let a=new Set(r);return this.withExtension("oneOf",r).addValidator(t=>typeof t=="number"&&a.has(t)?{valid:!0,errors:[]}:i(n,`must be one of: ${r.join(", ")}`,t,this))}}});var P=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,f=/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,S=/^(?:[0-9a-f]{1,4}:){7}[0-9a-f]{1,4}$|^::(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4}$|^(?:[0-9a-f]{1,4}:){1,6}:[0-9a-f]{1,4}$|^(?:[0-9a-f]{1,4}:){1,5}(?::[0-9a-f]{1,4}){1,2}$|^(?:[0-9a-f]{1,4}:){1,4}(?::[0-9a-f]{1,4}){1,3}$|^(?:[0-9a-f]{1,4}:){1,3}(?::[0-9a-f]{1,4}){1,4}$|^(?:[0-9a-f]{1,4}:){1,2}(?::[0-9a-f]{1,4}){1,5}$|^[0-9a-f]{1,4}:(?::[0-9a-f]{1,4}){1,6}$|^::$/i,y=u({string:{email(e){return this.withExtension("email",!0).addValidator(r=>typeof r!="string"?i(e,"must be a valid email",r,this):/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(r)?{valid:!0,errors:[]}:i(e,"must be a valid email",r,this))},url(e,r){let n;if(typeof e=="string"||typeof e=="function"?(r=e,n=void 0):n=e,n?.protocols!==void 0&&(n.protocols.length===0||n.protocols.some(s=>!s||s.trim()==="")))throw new Error("url: opts.protocols must be a non-empty array of non-empty strings");let a=n?.protocols??["http","https"],t=n?.protocols?{protocols:n.protocols}:!0;return this.withExtension("url",t).addValidator(s=>{if(typeof s!="string")return i(r,"must be a valid URL",s,this);let d=!1,h="must be a valid URL";try{let x=new URL(s).protocol.replace(":","");d=a.includes(x),d||(h=`protocol must be one of: ${a.join(", ")}`)}catch{}return d?{valid:!0,errors:[]}:i(r,h,s,this)})},uuid(e){return this.withExtension("uuid",!0).addValidator(r=>typeof r!="string"?i(e,"must be a valid UUID",r,this):P.test(r)?{valid:!0,errors:[]}:i(e,"must be a valid UUID",r,this))},ip(e,r){let n=e?.version,a=n?{version:n}:!0;return this.withExtension("ip",a).addValidator(t=>{let s=n?`must be a valid ${n} IP address`:"must be a valid IP address";if(typeof t!="string")return i(r,s,t,this);let d;return n==="v4"?d=f.test(t):n==="v6"?d=S.test(t):d=f.test(t)||S.test(t),d?{valid:!0,errors:[]}:i(r,s,t,this)})},trim(){return this.addPreprocessor(e=>typeof e=="string"?e.trim():e)},toLowerCase(){return this.addPreprocessor(e=>typeof e=="string"?e.toLowerCase():e)},nonempty(e){return this.withExtension("nonempty",!0).addValidator(r=>typeof r!="string"?i(e,"must not be empty",r,this):r.length>0?{valid:!0,errors:[]}:i(e,"must not be empty",r,this))},oneOf(...e){let r,n;if(e.length===0)throw new Error("oneOf requires at least one value");if(Array.isArray(e[0]))r=e[0],n=e[1];else{let t=e[e.length-1];typeof t=="function"?(r=e.slice(0,-1),n=t):(r=e,n=void 0)}if(r.length===0)throw new Error("oneOf requires at least one value");let a=new Set(r);return this.withExtension("oneOf",r).addValidator(t=>typeof t=="string"&&a.has(t)?{valid:!0,errors:[]}:i(n,`must be one of: ${r.join(", ")}`,t,this))}}});var o=p(y,m,l),c=o.string,w=o.number,N=o.array,O=o.boolean,A=o.date,R=o.object,j=o.union,H=o.func,$=o.any,U=o.tuple,k=o.record,F=o.promise;function q(...e){return Array.isArray(e[0])?c().oneOf(e[0],e[1]):c().oneOf(...e)}export{C as AnySchemaBuilder,W as ArraySchemaBuilder,_ as BooleanSchemaBuilder,G as DateSchemaBuilder,oe as EXTRA_TYPE_BRAND,J as ExternSchemaBuilder,X as FunctionSchemaBuilder,Y as GenericSchemaBuilder,E as LazySchemaBuilder,se as METHOD_LITERAL_BRAND,ee as NullSchemaBuilder,ne as NumberSchemaBuilder,te as ObjectSchemaBuilder,B as ParseStringSchemaBuilder,T as PromiseSchemaBuilder,V as RecordSchemaBuilder,K as SYMBOL_HAS_PROPERTIES,L as SYMBOL_SCHEMA_PROPERTY_DESCRIPTOR,z as SchemaBuilder,I as SchemaValidationError,ie as StringSchemaBuilder,v as TupleSchemaBuilder,ae as UnionSchemaBuilder,$ as any,N as array,l as arrayExtensions,O as boolean,A as date,u as defineExtension,q as enumOf,Q as extern,H as func,Z as generic,g as lazy,re as nul,w as number,m as numberExtensions,R as object,b as parseString,F as promise,k as record,c as string,y as stringExtensions,U as tuple,j as union,p as withExtensions};
2
2
  //# sourceMappingURL=index.js.map