viborm 0.1.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/README.md +529 -0
- package/dist/adapters.d.mts +2 -0
- package/dist/adapters.mjs +1 -0
- package/dist/bun-sql.d.mts +3 -0
- package/dist/bun-sql.mjs +2 -0
- package/dist/bun-sql.mjs.map +1 -0
- package/dist/bun-sqlite.d.mts +3 -0
- package/dist/bun-sqlite.mjs +2 -0
- package/dist/bun-sqlite.mjs.map +1 -0
- package/dist/cache/cloudflare-kv.d.mts +3 -0
- package/dist/cache/cloudflare-kv.mjs +2 -0
- package/dist/cache/cloudflare-kv.mjs.map +1 -0
- package/dist/cache/memory.d.mts +3 -0
- package/dist/cache/memory.mjs +2 -0
- package/dist/cache/memory.mjs.map +1 -0
- package/dist/cache.d.mts +4 -0
- package/dist/cache.mjs +1 -0
- package/dist/cli.d.mts +1 -0
- package/dist/cli.mjs +41 -0
- package/dist/cli.mjs.map +1 -0
- package/dist/client-CgdtiDGV.mjs +2 -0
- package/dist/client-CgdtiDGV.mjs.map +1 -0
- package/dist/client.d.mts +3 -0
- package/dist/client.mjs +1 -0
- package/dist/cloudflare-kv-DauXhtnT.d.mts +1110 -0
- package/dist/d1-http.d.mts +3 -0
- package/dist/d1-http.mjs +2 -0
- package/dist/d1-http.mjs.map +1 -0
- package/dist/d1.d.mts +3 -0
- package/dist/d1.mjs +2 -0
- package/dist/d1.mjs.map +1 -0
- package/dist/driver-B_vBzQ6A.mjs +2 -0
- package/dist/driver-B_vBzQ6A.mjs.map +1 -0
- package/dist/driver-Cj1EbciY.mjs +2 -0
- package/dist/driver-Cj1EbciY.mjs.map +1 -0
- package/dist/driver.d.mts +2 -0
- package/dist/driver.mjs +1 -0
- package/dist/errors-DvcqIdEo.mjs +2 -0
- package/dist/errors-DvcqIdEo.mjs.map +1 -0
- package/dist/helper-cDCDjRAD.d.mts +3020 -0
- package/dist/helpers-WNr9B-2U.mjs +2 -0
- package/dist/helpers-WNr9B-2U.mjs.map +1 -0
- package/dist/hydration-CFnwc7j6.mjs +2 -0
- package/dist/hydration-CFnwc7j6.mjs.map +1 -0
- package/dist/index-3sdVKfeG.d.mts +1447 -0
- package/dist/index-BGmpst1h.d.mts +2158 -0
- package/dist/index.d.mts +46 -0
- package/dist/index.mjs +2 -0
- package/dist/index.mjs.map +1 -0
- package/dist/instrumentation.d.mts +2 -0
- package/dist/instrumentation.mjs +1 -0
- package/dist/libsql.d.mts +3 -0
- package/dist/libsql.mjs +2 -0
- package/dist/libsql.mjs.map +1 -0
- package/dist/migrations.d.mts +1588 -0
- package/dist/migrations.mjs +11 -0
- package/dist/migrations.mjs.map +1 -0
- package/dist/mysql-adapter-0catKeCI.mjs +6 -0
- package/dist/mysql-adapter-0catKeCI.mjs.map +1 -0
- package/dist/mysql-utils-BPw9qhac.mjs +2 -0
- package/dist/mysql-utils-BPw9qhac.mjs.map +1 -0
- package/dist/mysql2.d.mts +3 -0
- package/dist/mysql2.mjs +2 -0
- package/dist/mysql2.mjs.map +1 -0
- package/dist/native-types-BwICkVjz.mjs +2 -0
- package/dist/native-types-BwICkVjz.mjs.map +1 -0
- package/dist/neon-http.d.mts +3 -0
- package/dist/neon-http.mjs +2 -0
- package/dist/neon-http.mjs.map +1 -0
- package/dist/pending-operation-CkzYTpi4.mjs +2 -0
- package/dist/pending-operation-CkzYTpi4.mjs.map +1 -0
- package/dist/pg.d.mts +3 -0
- package/dist/pg.mjs +2 -0
- package/dist/pg.mjs.map +1 -0
- package/dist/pglite.d.mts +3 -0
- package/dist/pglite.mjs +2 -0
- package/dist/pglite.mjs.map +1 -0
- package/dist/planetscale.d.mts +3 -0
- package/dist/planetscale.mjs +2 -0
- package/dist/planetscale.mjs.map +1 -0
- package/dist/postgres-adapter-Blzqj1bl.mjs +6 -0
- package/dist/postgres-adapter-Blzqj1bl.mjs.map +1 -0
- package/dist/postgres.d.mts +3 -0
- package/dist/postgres.mjs +2 -0
- package/dist/postgres.mjs.map +1 -0
- package/dist/push-qZreXYkb.mjs +252 -0
- package/dist/push-qZreXYkb.mjs.map +1 -0
- package/dist/result-parsing-FNQbuHvC.mjs +2 -0
- package/dist/result-parsing-FNQbuHvC.mjs.map +1 -0
- package/dist/schema-DeAJZocc.mjs +2 -0
- package/dist/schema-DeAJZocc.mjs.map +1 -0
- package/dist/schema.d.mts +293 -0
- package/dist/schema.mjs +2 -0
- package/dist/schema.mjs.map +1 -0
- package/dist/spans-CJt5UgbJ.mjs +2 -0
- package/dist/spans-CJt5UgbJ.mjs.map +1 -0
- package/dist/sqlite-adapter-5Em_-oGU.mjs +6 -0
- package/dist/sqlite-adapter-5Em_-oGU.mjs.map +1 -0
- package/dist/sqlite-utils-BW7elKTz.mjs +2 -0
- package/dist/sqlite-utils-BW7elKTz.mjs.map +1 -0
- package/dist/sqlite3.d.mts +3 -0
- package/dist/sqlite3.mjs +2 -0
- package/dist/sqlite3.mjs.map +1 -0
- package/dist/tracer-CGzIAsj8.mjs +2 -0
- package/dist/tracer-CGzIAsj8.mjs.map +1 -0
- package/dist/validation-RtU-wu4N.mjs +2 -0
- package/dist/validation-RtU-wu4N.mjs.map +1 -0
- package/dist/validation.d.mts +2 -0
- package/dist/validation.mjs +1 -0
- package/dist/validator-DpJsJcd7.mjs +3 -0
- package/dist/validator-DpJsJcd7.mjs.map +1 -0
- package/package.json +278 -0
- package/readme/README.md +69 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"validation-RtU-wu4N.mjs","names":["v","getDefault","transform","array","nullable","optional","date","result","object","v","stringFn","numberFn","integerFn","booleanFn","bigintFn","literalFn","enumFn","jsonFn","dateFn","isoTimestampFn","isoDateFn","isoTimeFn","instanceFn","blobFn","vectorFn","pointFn","arrayFn","nullableFn","maybeNullableFn","optionalFn","nonNullableFn","nonOptionalFn","requiredFn","nonArrayFn","elementFn","objectFn","fromObjectFn","unionFn","pipeFn","transformActionFn","recordFn","fromKeysFn","coerceFn","mapFn"],"sources":["../src/validation/json-schema/converters.ts","../src/validation/json-schema/factory.ts","../src/validation/helpers.ts","../src/validation/inferred.ts","../src/validation/schemas/array.ts","../src/validation/schemas/bigint.ts","../src/validation/schemas/blob.ts","../src/validation/schemas/boolean.ts","../src/validation/schemas/date.ts","../src/validation/schemas/enum.ts","../src/validation/schemas/instance.ts","../src/validation/schemas/iso.ts","../src/validation/schemas/json.ts","../src/validation/schemas/literal.ts","../src/validation/schemas/nonArray.ts","../src/validation/schemas/nonNullable.ts","../src/validation/schemas/nonOptional.ts","../src/validation/schemas/nullable.ts","../src/validation/schemas/number.ts","../src/validation/schemas/object.ts","../src/validation/schemas/optional.ts","../src/validation/schemas/point.ts","../src/validation/schemas/string.ts","../src/validation/schemas/union.ts","../src/validation/schemas/vector.ts","../src/validation/schemas/from-object.ts","../src/validation/schemas/pipe.ts","../src/validation/schemas/record.ts","../src/validation/schemas/transform.ts","../src/validation/types.ts","../src/validation/index.ts"],"sourcesContent":["/**\n * Schema to JSON Schema converters.\n * Handles conversion of VibORM schemas to JSON Schema format.\n */\n\nimport type { VibSchema } from \"../types\";\nimport type { ConversionContext, JsonSchema, JsonSchemaTarget } from \"./types\";\n\n// =============================================================================\n// Helper Functions\n// =============================================================================\n\n/**\n * Wrapper schema types that should be traversed to find inner schemas.\n */\nconst WRAPPER_TYPES = new Set([\n \"array\",\n \"nullable\",\n \"optional\",\n \"nonNullable\",\n \"nonOptional\",\n \"nonArray\",\n]);\n\n/**\n * Traverse through wrapper schemas to find the innermost schema.\n * Wrappers include: array, nullable, optional, nonNullable, nonOptional, nonArray\n */\nfunction getInnerSchema(schema: any): any {\n let current = schema;\n while (current && WRAPPER_TYPES.has(current.type)) {\n // array uses 'item', others use 'wrapped'\n current = current.item ?? current.wrapped;\n }\n return current;\n}\n\n/**\n * Get the name of a schema by traversing wrappers to find an inner named object.\n * Returns null if no name is found - in that case, the schema should be inlined.\n */\nfunction getSchemaName(schema: any): string | null {\n const inner = getInnerSchema(schema);\n const name = inner?.options?.name;\n return name && typeof name === \"string\" ? name : null;\n}\n\n// =============================================================================\n// Main Converter\n// =============================================================================\n\n/**\n * Converts a VibORM schema to JSON Schema format.\n *\n * @param schema - The VibORM schema to convert\n * @param context - The conversion context for tracking references\n * @param skipRef - Whether to skip reference lookup (for inline conversion)\n * @returns The converted JSON Schema\n */\nexport function convertSchema(\n schema: VibSchema<unknown, unknown> & {\n type: string;\n [key: string]: unknown;\n },\n context: ConversionContext,\n skipRef = false\n): JsonSchema {\n const jsonSchema: JsonSchema = {};\n\n // Check for existing reference (circular schema support)\n if (!skipRef) {\n const existingRef = context.referenceMap.get(schema);\n if (existingRef) {\n return { $ref: `#/$defs/${existingRef}` };\n }\n }\n\n // Get schema type\n const schemaType = schema.type as string;\n\n // Convert based on schema type\n switch (schemaType) {\n // =========================================================================\n // Primitive Schemas\n // =========================================================================\n\n case \"string\":\n jsonSchema.type = \"string\";\n break;\n\n case \"number\":\n case \"integer\":\n jsonSchema.type = schemaType === \"integer\" ? \"integer\" : \"number\";\n break;\n\n case \"boolean\":\n jsonSchema.type = \"boolean\";\n break;\n\n case \"bigint\":\n // BigInt maps to integer in JSON Schema\n jsonSchema.type = \"integer\";\n break;\n\n case \"literal\": {\n const value = (schema as any).value;\n if (context.target === \"openapi-3.0\") {\n // OpenAPI 3.0 doesn't support const, use enum\n jsonSchema.enum = [value];\n } else {\n jsonSchema.const = value;\n }\n break;\n }\n\n case \"enum\": {\n const values = (schema as any).values;\n jsonSchema.enum = values;\n break;\n }\n\n // =========================================================================\n // Wrapper Schemas\n // =========================================================================\n\n case \"nullable\": {\n const wrapped = (schema as any).wrapped as VibSchema<unknown, unknown>;\n const wrappedSchema = convertSchema(wrapped as any, context);\n\n if (context.target === \"openapi-3.0\") {\n // OpenAPI 3.0 uses nullable property\n Object.assign(jsonSchema, wrappedSchema);\n jsonSchema.nullable = true;\n } else {\n // Use anyOf with null\n jsonSchema.anyOf = [wrappedSchema, { type: \"null\" }];\n }\n break;\n }\n\n case \"optional\": {\n // Optional just passes through - optionality is handled at object level\n const wrapped = (schema as any).wrapped as VibSchema<unknown, unknown>;\n return convertSchema(wrapped as any, context);\n }\n\n case \"array\": {\n const item = (schema as any).item as VibSchema<unknown, unknown>;\n jsonSchema.type = \"array\";\n jsonSchema.items = convertSchema(item as any, context);\n break;\n }\n\n case \"nonNullable\":\n case \"nonOptional\":\n case \"nonArray\": {\n // These are just type narrowers, pass through to wrapped\n const wrapped = (schema as any).wrapped as VibSchema<unknown, unknown>;\n return convertSchema(wrapped as any, context);\n }\n\n // =========================================================================\n // Composite Schemas\n // =========================================================================\n\n case \"object\": {\n const entries = (schema as any).entries as Record<string, unknown>;\n const options = (schema as any).options as\n | { partial?: boolean; strict?: boolean }\n | undefined;\n const partial = options?.partial ?? true;\n const strict = options?.strict ?? true;\n\n jsonSchema.type = \"object\";\n jsonSchema.properties = {};\n jsonSchema.required = [];\n\n for (const key in entries) {\n const entry = entries[key];\n const isThunk = typeof entry === \"function\";\n\n // Resolve thunks to get the actual schema\n const entrySchema = isThunk\n ? (entry as () => VibSchema<unknown, unknown>)()\n : (entry as VibSchema<unknown, unknown>);\n\n // Find the inner named object (if any) and pre-register it\n const innerSchema = getInnerSchema(entrySchema);\n const schemaName = innerSchema?.options?.name;\n\n if (schemaName && typeof schemaName === \"string\") {\n // Pre-register the inner named object (not the wrapper)\n if (!context.referenceMap.has(innerSchema)) {\n context.referenceMap.set(innerSchema, schemaName);\n // Convert the inner object and add to definitions\n context.definitions[schemaName] = convertSchema(\n innerSchema as any,\n context,\n true\n );\n }\n }\n\n // Now convert the entry normally - if it hits a registered schema, it will emit $ref\n jsonSchema.properties[key] = convertSchema(entrySchema as any, context);\n\n // Determine if field is required\n const entryType = (entrySchema as any).type;\n const isOptionalWrapper =\n entryType === \"optional\" || entryType === \"nullish\";\n\n if (!(partial || isOptionalWrapper)) {\n jsonSchema.required.push(key);\n }\n }\n\n // Handle strict mode\n if (strict) {\n jsonSchema.additionalProperties = false;\n }\n\n // Remove empty required array\n if (jsonSchema.required.length === 0) {\n delete jsonSchema.required;\n }\n\n break;\n }\n\n case \"record\": {\n const valueSchema = (schema as any).value as VibSchema<unknown, unknown>;\n jsonSchema.type = \"object\";\n jsonSchema.additionalProperties = convertSchema(\n valueSchema as any,\n context\n );\n break;\n }\n\n case \"union\": {\n const options = (schema as any).options as VibSchema<unknown, unknown>[];\n jsonSchema.anyOf = options.map((opt) =>\n convertSchema(opt as any, context)\n );\n break;\n }\n\n // =========================================================================\n // Date Schemas\n // =========================================================================\n\n case \"date\":\n jsonSchema.type = \"string\";\n jsonSchema.format = \"date-time\";\n break;\n\n case \"iso_timestamp\":\n jsonSchema.type = \"string\";\n jsonSchema.format = \"date-time\";\n break;\n\n case \"iso_date\":\n jsonSchema.type = \"string\";\n jsonSchema.format = \"date\";\n break;\n\n case \"iso_time\":\n jsonSchema.type = \"string\";\n jsonSchema.format = \"time\";\n break;\n\n // =========================================================================\n // Special Schemas\n // =========================================================================\n\n case \"json\":\n // JSON accepts any valid JSON value - empty schema accepts anything\n break;\n\n case \"blob\":\n jsonSchema.type = \"string\";\n jsonSchema.contentEncoding = \"base64\";\n break;\n\n case \"vector\": {\n const dimensions = (schema as any).dimensions as number | undefined;\n jsonSchema.type = \"array\";\n jsonSchema.items = { type: \"number\" };\n if (dimensions !== undefined) {\n jsonSchema.minItems = dimensions;\n jsonSchema.maxItems = dimensions;\n }\n break;\n }\n\n case \"point\":\n jsonSchema.type = \"object\";\n jsonSchema.properties = {\n x: { type: \"number\" },\n y: { type: \"number\" },\n };\n jsonSchema.required = [\"x\", \"y\"];\n jsonSchema.additionalProperties = false;\n break;\n\n case \"instance\": {\n // Instance schemas validate class instances - represent as object\n // with a custom property to indicate the expected type\n const ctor = (schema as any).ctor as new (...args: any[]) => unknown;\n const className = ctor?.name ?? \"Instance\";\n\n // Special handling for common types\n if (className === \"Date\") {\n jsonSchema.type = \"string\";\n jsonSchema.format = \"date-time\";\n } else if (\n className === \"Uint8Array\" ||\n className === \"Buffer\" ||\n className === \"ArrayBuffer\"\n ) {\n jsonSchema.type = \"string\";\n jsonSchema.contentEncoding = \"base64\";\n } else {\n // Generic object representation with instance hint\n jsonSchema.type = \"object\";\n // Use x- prefix for vendor extension (valid in JSON Schema)\n (jsonSchema as any)[\"x-instance\"] = className;\n }\n break;\n }\n\n case \"transform\": {\n // Transform wraps another schema - use the wrapped schema for JSON representation\n const wrapped = (schema as any).wrapped as VibSchema<unknown, unknown>;\n return convertSchema(wrapped as any, context);\n }\n\n case \"pipe\": {\n // Pipe contains a base schema and actions - use the base schema\n const baseSchema = (schema as any).schema as VibSchema<unknown, unknown>;\n if (baseSchema) {\n return convertSchema(baseSchema as any, context);\n }\n break;\n }\n\n default:\n throw new Error(\n `Cannot convert \"${schemaType}\" schema to JSON Schema: unsupported type`\n );\n }\n\n return jsonSchema;\n}\n\n// =============================================================================\n// Top-Level Conversion\n// =============================================================================\n\n/**\n * Converts a VibORM schema to a complete JSON Schema document.\n *\n * @param schema - The VibORM schema to convert\n * @param target - The target JSON Schema version\n * @returns Complete JSON Schema with $schema and $defs if needed\n */\nexport function toJsonSchema(\n schema: VibSchema<unknown, unknown>,\n target: JsonSchemaTarget = \"draft-07\"\n): JsonSchema {\n const context: ConversionContext = {\n definitions: {},\n referenceMap: new Map(),\n refCount: 0,\n target,\n };\n\n const jsonSchema = convertSchema(schema as any, context);\n\n // Add $schema URI based on target\n if (target === \"draft-2020-12\") {\n jsonSchema.$schema = \"https://json-schema.org/draft/2020-12/schema\";\n } else if (target === \"draft-07\") {\n jsonSchema.$schema = \"http://json-schema.org/draft-07/schema#\";\n }\n // OpenAPI 3.0 does not use $schema\n\n // Add definitions if any\n if (Object.keys(context.definitions).length > 0) {\n jsonSchema.$defs = context.definitions;\n }\n\n return jsonSchema;\n}\n","/**\n * Factory for creating JSON Schema converters.\n * Each schema gets its own jsonSchema property with input/output methods.\n */\n\nimport type { VibSchema } from \"../types\";\nimport { toJsonSchema } from \"./converters\";\nimport type { JsonSchemaConverter, JsonSchemaOptions } from \"./types\";\n\n/**\n * Creates a JSON Schema converter for a VibORM schema.\n * The converter provides `input` and `output` methods that generate\n * JSON Schema representations of the schema's input and output types.\n *\n * @param schema - The VibORM schema to create a converter for\n * @returns A JsonSchemaConverter with input and output methods\n */\nexport function createJsonSchemaConverter(\n schema: VibSchema<unknown, unknown>\n): JsonSchemaConverter {\n const supportedTargets = [\"draft-07\", \"draft-2020-12\", \"openapi-3.0\"];\n\n return {\n input(options: JsonSchemaOptions): Record<string, unknown> {\n if (!supportedTargets.includes(options.target)) {\n throw new Error(`Unsupported JSON Schema target: ${options.target}`);\n }\n // For input type, we use the same conversion\n // (VibORM doesn't have separate input/output transformations at schema level)\n return toJsonSchema(schema, options.target) as Record<string, unknown>;\n },\n\n output(options: JsonSchemaOptions): Record<string, unknown> {\n if (!supportedTargets.includes(options.target)) {\n throw new Error(`Unsupported JSON Schema target: ${options.target}`);\n }\n // For output type, we use the same conversion\n // (VibORM doesn't have separate input/output transformations at schema level)\n return toJsonSchema(schema, options.target) as Record<string, unknown>;\n },\n };\n}\n","import type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport { createJsonSchemaConverter } from \"./json-schema/factory\";\nimport type {\n ComputeInput,\n ComputeOutput,\n ScalarOptions,\n ValidationIssue,\n ValidationResult,\n VibSchema,\n} from \"./types\";\n\n// =============================================================================\n// Core Validation Primitives\n// =============================================================================\n\n/**\n * Create a failure result with a single issue.\n */\nexport function fail(\n message: string,\n path?: PropertyKey[]\n): ValidationResult<never> {\n const issue: ValidationIssue =\n path && path.length > 0 ? { message, path } : { message };\n return { issues: [issue] };\n}\n\n/**\n * Create a success result.\n */\nexport function ok<T>(value: T): ValidationResult<T> {\n return { value };\n}\n\n// =============================================================================\n// Set Theory Optimized Validators\n// =============================================================================\n\n// Pre-allocated error objects (avoid allocation in hot path)\nconst ARRAY_TYPE_ERROR = Object.freeze({\n issues: Object.freeze([Object.freeze({ message: \"Expected array\" })]),\n});\n\n// Pre-allocated null/undefined results for fast paths\nconst OK_NULL = Object.freeze({ value: null });\nconst OK_UNDEFINED = Object.freeze({ value: undefined });\n\n/**\n * Validate array items with the provided validator.\n * Shared by both array() wrapper and options.array.\n */\nfunction validateArray<T>(\n value: unknown,\n validate: (v: unknown) => ValidationResult<T>\n): ValidationResult<T[]> {\n if (!Array.isArray(value)) {\n return ARRAY_TYPE_ERROR as ValidationResult<T[]>;\n }\n\n const len = value.length;\n if (len === 0) return ok([]);\n\n const results = new Array<T>(len);\n for (let i = 0; i < len; i++) {\n const r = validate(value[i]);\n if (r.issues) {\n const issue = r.issues[0]!;\n return fail(\n issue.message as string,\n issue.path\n ? ([i] as PropertyKey[]).concat(issue.path as PropertyKey[])\n : [i]\n );\n }\n results[i] = (r as { value: T }).value;\n }\n return ok(results);\n}\n\n// =============================================================================\n// 8 Pre-defined Validator Factories (Set Theory Approach)\n// =============================================================================\n// Using bit flags: nullable=4, optional=2, array=1\n// This eliminates runtime option checking during validation\n\ntype ValidatorFn<T> = (value: unknown) => ValidationResult<T>;\ntype ValidatorFactory = <T>(v: ValidatorFn<T>) => ValidatorFn<any>;\n\nconst FACTORIES: ValidatorFactory[] = [\n // 000: no options - pass through\n (v) => v,\n\n // 001: array only\n (v) => (val) => validateArray(val, v),\n\n // 010: optional only\n (v) => (val) => (val === undefined ? OK_UNDEFINED : v(val)),\n\n // 011: optional + array\n (v) => (val) => (val === undefined ? OK_UNDEFINED : validateArray(val, v)),\n\n // 100: nullable only\n (v) => (val) => (val === null ? OK_NULL : v(val)),\n\n // 101: nullable + array\n (v) => (val) => (val === null ? OK_NULL : validateArray(val, v)),\n\n // 110: nullable + optional (use == null for both!)\n (v) => (val) => (val == null ? ok(val) : v(val)),\n\n // 111: nullable + optional + array\n (v) => (val) => (val == null ? ok(val) : validateArray(val, v)),\n];\n\n/**\n * Select factory index using bit flags (O(1) lookup).\n */\nfunction selectFactoryIndex(options?: {\n nullable?: boolean;\n optional?: boolean;\n array?: boolean;\n}): number {\n if (!options) return 0;\n return (\n (options.nullable ? 4 : 0) |\n (options.optional ? 2 : 0) |\n (options.array ? 1 : 0)\n );\n}\n\n// =============================================================================\n// Factories with Default (for optional + default cases)\n// =============================================================================\n\n/**\n * Create validator that returns default when undefined.\n * Default is computed and returned directly inside the optional check.\n */\nfunction createOptionalWithDefault<T>(\n validate: ValidatorFn<T>,\n getDefault: () => T\n): ValidatorFn<T> {\n return (val) => (val === undefined ? ok(getDefault()) : validate(val));\n}\n\nfunction createNullableOptionalWithDefault<T>(\n validate: ValidatorFn<T>,\n getDefault: () => T\n): ValidatorFn<T | null> {\n return (val) => {\n if (val === undefined) return ok(getDefault());\n if (val === null) return OK_NULL as ValidationResult<T | null>;\n return validate(val) as ValidationResult<T | null>;\n };\n}\n\nfunction createOptionalArrayWithDefault<T>(\n validate: ValidatorFn<T>,\n getDefault: () => T[]\n): ValidatorFn<T[]> {\n return (val) =>\n val === undefined ? ok(getDefault()) : validateArray(val, validate);\n}\n\nfunction createNullableOptionalArrayWithDefault<T>(\n validate: ValidatorFn<T>,\n getDefault: () => T[]\n): ValidatorFn<T[] | null> {\n return (val) => {\n if (val === undefined) return ok(getDefault());\n if (val === null) return OK_NULL as ValidationResult<T[] | null>;\n return validateArray(val, validate) as ValidationResult<T[] | null>;\n };\n}\n\n// =============================================================================\n// Optimized Validator Builder (Set Theory + Composition)\n// =============================================================================\n\n/**\n * Build an optimized validator at schema creation time.\n * Uses set theory approach for nullable/optional/array/default combinations.\n *\n * @param baseValidate - The base type validator\n * @param options - Schema options\n * @param typeName - Type name for error messages (unused but kept for API consistency)\n */\nexport function buildValidator<T, TOut, TSchemaOut = T>(\n baseValidate: ValidatorFn<T>,\n options: ScalarOptions<T, TOut, TSchemaOut> | undefined,\n _typeName: string\n): ValidatorFn<TOut> {\n // Fast path: no options at all\n if (!options) {\n return baseValidate as unknown as ValidatorFn<TOut>;\n }\n\n const {\n nullable,\n optional,\n array,\n default: defaultVal,\n transform,\n schema,\n } = options;\n\n // Check what we have\n const hasDefault = defaultVal !== undefined;\n const hasTransform = transform !== undefined;\n const hasSchema = schema !== undefined;\n\n // Build the core validator (base + schema + transform chain)\n let validate: ValidatorFn<any> = baseValidate;\n\n // Chain custom schema validation (if any)\n\n if (hasSchema) {\n const schemaValidate = schema![\"~standard\"].validate;\n const prev = validate;\n validate = (v): ValidationResult<any> => {\n const r = prev(v);\n if (r.issues) return r;\n const sr = schemaValidate((r as { value: any }).value);\n if (\"then\" in sr) return fail(\"Async schemas are not supported\");\n if (sr.issues) return { issues: sr.issues as readonly ValidationIssue[] };\n return ok((sr as { value: any }).value);\n };\n }\n\n // Chain transform (if any)\n if (hasTransform) {\n const fn = transform!;\n const prev = validate;\n validate = (v) => {\n const r = prev(v);\n if (r.issues) return r;\n return ok(fn((r as { value: any }).value));\n };\n }\n\n // Now apply nullable/optional/array/default handling\n // Default is computed and returned INSIDE the optional check\n\n if (hasDefault) {\n // Compute default getter once\n const getDefault =\n typeof defaultVal === \"function\"\n ? (defaultVal as () => any)\n : () => defaultVal;\n\n // Apply the appropriate factory with default\n if (array) {\n if (nullable) {\n return createNullableOptionalArrayWithDefault(\n validate,\n getDefault\n ) as ValidatorFn<TOut>;\n }\n return createOptionalArrayWithDefault(\n validate,\n getDefault\n ) as ValidatorFn<TOut>;\n }\n if (nullable) {\n return createNullableOptionalWithDefault(\n validate,\n getDefault\n ) as ValidatorFn<TOut>;\n }\n return createOptionalWithDefault(validate, getDefault) as ValidatorFn<TOut>;\n }\n\n // No default - use pure 8-way factory\n if (array) {\n const itemValidator = validate;\n validate = (val) => validateArray(val, itemValidator);\n const wrapperIndex = (nullable ? 4 : 0) | (optional ? 2 : 0);\n if (wrapperIndex > 0) {\n validate = FACTORIES[wrapperIndex]!(validate);\n }\n } else {\n const factoryIndex = selectFactoryIndex(options);\n if (factoryIndex > 0) {\n validate = FACTORIES[factoryIndex]!(validate);\n }\n }\n\n return validate as ValidatorFn<TOut>;\n}\n\n// =============================================================================\n// Schema Builder (Returns complete schema object)\n// =============================================================================\n\n/**\n * Build a complete schema object with optimized validator.\n * This is the main entry point for creating scalar schemas.\n *\n * @param type - Schema type name\n * @param baseValidate - The base type validator\n * @param options - Schema options\n * @param extras - Additional properties to add to the schema (e.g., `value` for literal)\n */\nexport function buildSchema<\n T,\n const Opts extends ScalarOptions<T, any> | undefined,\n TExtras extends Record<string, unknown> = {},\n>(\n type: string,\n baseValidate: ValidatorFn<T>,\n options: Opts,\n extras?: TExtras\n): VibSchema<ComputeInput<T, Opts>, ComputeOutput<T, Opts>> &\n TExtras & { type: string; options: Opts } {\n const validate = buildValidator(baseValidate, options, type);\n\n const schema = {\n type,\n options,\n ...extras,\n \"~standard\": {\n version: 1 as const,\n vendor: \"viborm\" as const,\n validate,\n // Lazy jsonSchema - converter is created when first accessed\n get jsonSchema() {\n const converter = createJsonSchemaConverter(\n schema as unknown as VibSchema<unknown, unknown>\n );\n // Replace getter with static value for subsequent access\n Object.defineProperty(this, \"jsonSchema\", {\n value: converter,\n writable: false,\n enumerable: true,\n });\n return converter;\n },\n },\n };\n\n return schema as VibSchema<ComputeInput<T, Opts>, ComputeOutput<T, Opts>> &\n TExtras & { options: Opts; type: string };\n}\n\n// =============================================================================\n// Reusable Validation Logic (Exported for wrapper schemas)\n// =============================================================================\n\n/**\n * Validate an array of items using the provided validate function.\n * Exported for use by array() wrapper schema.\n */\nexport function validateArrayItems<T, TOut = T>(\n value: unknown,\n validate: (item: unknown) => any,\n transform?: (item: T) => TOut\n): ValidationResult<TOut[]> {\n if (!Array.isArray(value)) {\n return ARRAY_TYPE_ERROR as ValidationResult<TOut[]>;\n }\n\n const len = value.length;\n if (len === 0) return ok([]);\n\n const results = new Array<TOut>(len);\n for (let i = 0; i < len; i++) {\n const itemResult = validate(value[i]);\n if (\"then\" in itemResult)\n return fail(\"Async schemas are not supported\", [i]);\n if (itemResult.issues) {\n const issue = itemResult.issues[0]!;\n return fail(\n issue.message as string,\n issue.path\n ? ([i] as PropertyKey[]).concat(issue.path as PropertyKey[])\n : [i]\n );\n }\n results[i] = transform\n ? transform(itemResult.value as T)\n : (itemResult.value as TOut);\n }\n return ok(results);\n}\n\n/**\n * Get default value from options.\n */\nexport function getDefault<T>(\n options: ScalarOptions<T, any> | undefined\n): T | undefined {\n if (options?.default === undefined) return undefined;\n return typeof options.default === \"function\"\n ? (options.default as () => T)()\n : options.default;\n}\n\n/**\n * Create a StandardSchema-compatible schema object.\n */\nexport function createSchema<TInput, TOutput>(\n type: string,\n validate: (value: unknown) => ValidationResult<TOutput>\n): VibSchema<TInput, TOutput> {\n const schema = {\n type,\n \"~standard\": {\n version: 1 as const,\n vendor: \"viborm\" as const,\n validate,\n // Lazy jsonSchema - converter is created when first accessed\n get jsonSchema() {\n const converter = createJsonSchemaConverter(\n schema as unknown as VibSchema<unknown, unknown>\n );\n // Replace getter with static value for subsequent access\n Object.defineProperty(this, \"jsonSchema\", {\n value: converter,\n writable: false,\n enumerable: true,\n });\n return converter;\n },\n },\n };\n\n // Add the inferred property for type branding\n Object.defineProperty(schema, \" vibInferred\", {\n value: undefined,\n enumerable: false,\n });\n\n return schema as VibSchema<TInput, TOutput>;\n}\n\n/**\n * Validate a value against a StandardSchema.\n */\nexport function validateSchema<T>(\n schema: StandardSchemaV1<unknown, T>,\n value: unknown\n): ValidationResult<T> {\n const result = schema[\"~standard\"].validate(value);\n if (\"then\" in result) {\n return fail(\"Async schemas are not supported\");\n }\n if (result.issues) {\n return { issues: result.issues as readonly ValidationIssue[] };\n }\n return ok((result as { value: T }).value);\n}\n","/**\n * Branded key for type inference.\n *\n * KEY INSIGHT: ArkType uses a STRING, not a unique symbol.\n * This is: export declare const inferred: \" arkInferred\";\n *\n * Using a string literal allows TypeScript's pattern matching\n * to work correctly during circular reference resolution.\n */\nexport const inferred = \" vibInferred\" as const;\nexport type inferred = typeof inferred;\n","import { createSchema, validateArrayItems } from \"../helpers\";\nimport type { InferInput, InferOutput, VibSchema } from \"../types\";\n\n// =============================================================================\n// Array Schema\n// =============================================================================\n\nexport interface ArraySchema<\n TItem extends VibSchema<any, any>,\n TInput = InferInput<TItem>[],\n TOutput = InferOutput<TItem>[],\n> extends VibSchema<TInput, TOutput> {\n readonly type: \"array\";\n readonly item: TItem;\n}\n\n/**\n * Create an array schema that validates each item.\n *\n * @example\n * const tags = v.array(v.string());\n * const scores = v.array(v.number());\n */\nexport function array<TItem extends VibSchema<any, any>>(\n item: TItem\n): ArraySchema<TItem> {\n // Cache the validate function directly\n const validate = item[\"~standard\"].validate;\n\n const schema = createSchema<InferInput<TItem>[], InferOutput<TItem>[]>(\n \"array\",\n (value) => validateArrayItems(value, validate)\n ) as ArraySchema<TItem>;\n\n (schema as any).item = item;\n\n return schema;\n}\n","import { buildSchema, ok } from \"../helpers\";\nimport type {\n ComputeInput,\n ComputeOutput,\n ScalarOptions,\n VibSchema,\n} from \"../types\";\n\n// =============================================================================\n// BigInt Schema\n// =============================================================================\n\nexport interface BaseBigIntSchema<\n Opts extends ScalarOptions<bigint, any> | undefined = undefined,\n> extends VibSchema<ComputeInput<bigint, Opts>, ComputeOutput<bigint, Opts>> {}\n\nexport interface BigIntSchema<TInput = bigint, TOutput = bigint>\n extends VibSchema<TInput, TOutput> {\n readonly type: \"bigint\";\n}\n\n// Pre-computed error for fast path\nconst BIGINT_ERROR = Object.freeze({\n issues: Object.freeze([Object.freeze({ message: \"Expected bigint\" })]),\n});\n\n/**\n * Validate that a value is a bigint.\n */\nfunction validateBigInt(value: unknown) {\n return typeof value === \"bigint\" ? ok(value) : BIGINT_ERROR;\n}\n\n/**\n * Create a bigint schema.\n *\n * @example\n * const id = v.bigint();\n * const optionalId = v.bigint({ optional: true });\n */\nexport function bigint<\n const Opts extends ScalarOptions<bigint, any> | undefined = undefined,\n>(\n options?: Opts\n): BigIntSchema<ComputeInput<bigint, Opts>, ComputeOutput<bigint, Opts>> {\n return buildSchema(\"bigint\", validateBigInt, options) as BigIntSchema<\n ComputeInput<bigint, Opts>,\n ComputeOutput<bigint, Opts>\n >;\n}\n\n// Export the validate function for reuse\nexport { validateBigInt };\n","import { buildSchema, ok } from \"../helpers\";\nimport type {\n ComputeInput,\n ComputeOutput,\n ScalarOptions,\n VibSchema,\n} from \"../types\";\n\n// =============================================================================\n// Blob Schema (Uint8Array / Buffer)\n// =============================================================================\n\nexport interface BaseBlobSchema<\n Opts extends ScalarOptions<Uint8Array, any> | undefined = undefined,\n> extends VibSchema<\n ComputeInput<Uint8Array, Opts>,\n ComputeOutput<Uint8Array, Opts>\n > {}\n\nexport interface BlobSchema<TInput = Uint8Array, TOutput = Uint8Array>\n extends VibSchema<TInput, TOutput> {\n readonly type: \"blob\";\n}\n\n// Pre-computed error for fast path\nconst BLOB_ERROR = Object.freeze({\n issues: Object.freeze([\n Object.freeze({ message: \"Expected Uint8Array or Buffer\" }),\n ]),\n});\n\n/**\n * Validate that a value is a Uint8Array or Buffer.\n */\nexport function validateBlob(value: unknown) {\n return value instanceof Uint8Array || Buffer.isBuffer(value)\n ? ok(value as Uint8Array)\n : BLOB_ERROR;\n}\n\n/**\n * Create a blob schema for binary data (Uint8Array/Buffer).\n *\n * @example\n * const avatar = v.blob();\n * const optionalBlob = v.blob({ optional: true });\n * const nullableBlob = v.blob({ nullable: true });\n */\nexport function blob<\n const Opts extends ScalarOptions<Uint8Array, any> | undefined = undefined,\n>(\n options?: Opts\n): BlobSchema<ComputeInput<Uint8Array, Opts>, ComputeOutput<Uint8Array, Opts>> {\n return buildSchema(\"blob\", validateBlob, options) as BlobSchema<\n ComputeInput<Uint8Array, Opts>,\n ComputeOutput<Uint8Array, Opts>\n >;\n}\n","import { buildSchema, ok } from \"../helpers\";\nimport type {\n ComputeInput,\n ComputeOutput,\n ScalarOptions,\n VibSchema,\n} from \"../types\";\n\n// =============================================================================\n// Boolean Schema\n// =============================================================================\n\nexport interface BaseBooleanSchema<\n Opts extends ScalarOptions<boolean, any> | undefined = undefined,\n> extends VibSchema<\n ComputeInput<boolean, Opts>,\n ComputeOutput<boolean, Opts>\n > {}\n\nexport interface BooleanSchema<TInput = boolean, TOutput = boolean>\n extends VibSchema<TInput, TOutput> {\n readonly type: \"boolean\";\n}\n\n// Pre-computed error for fast path\nconst BOOLEAN_ERROR = Object.freeze({\n issues: Object.freeze([Object.freeze({ message: \"Expected boolean\" })]),\n});\n\n/**\n * Validate that a value is a boolean.\n */\nfunction validateBoolean(value: unknown) {\n return typeof value === \"boolean\" ? ok(value) : BOOLEAN_ERROR;\n}\n\n/**\n * Create a boolean schema.\n *\n * @example\n * const active = v.boolean();\n * const optionalFlag = v.boolean({ optional: true });\n */\nexport function boolean<\n const Opts extends ScalarOptions<boolean, any> | undefined = undefined,\n>(\n options?: Opts\n): BooleanSchema<ComputeInput<boolean, Opts>, ComputeOutput<boolean, Opts>> {\n return buildSchema(\"boolean\", validateBoolean, options) as BooleanSchema<\n ComputeInput<boolean, Opts>,\n ComputeOutput<boolean, Opts>\n >;\n}\n\n// Export the validate function for reuse\nexport { validateBoolean };\n","import { buildSchema, ok } from \"../helpers\";\nimport type {\n ComputeInput,\n ComputeOutput,\n ScalarOptions,\n VibSchema,\n} from \"../types\";\n\n// =============================================================================\n// Date Schema (JavaScript Date objects)\n// =============================================================================\n\nexport interface BaseDateSchema<\n Opts extends ScalarOptions<Date, any> | undefined = undefined,\n> extends VibSchema<ComputeInput<Date, Opts>, ComputeOutput<Date, Opts>> {}\n\nexport interface DateSchema<TInput = Date, TOutput = Date>\n extends VibSchema<TInput, TOutput> {\n readonly type: \"date\";\n}\n\n// Pre-computed errors for fast path\nconst NOT_DATE_ERROR = Object.freeze({\n issues: Object.freeze([Object.freeze({ message: \"Expected Date\" })]),\n});\nconst INVALID_DATE_ERROR = Object.freeze({\n issues: Object.freeze([Object.freeze({ message: \"Expected valid Date\" })]),\n});\n\n/**\n * Validate that a value is a JavaScript Date object.\n */\nfunction validateDate(value: unknown) {\n if (!(value instanceof Date)) return NOT_DATE_ERROR;\n if (Number.isNaN(value.getTime())) return INVALID_DATE_ERROR;\n return ok(value);\n}\n\n/**\n * Create a date schema for JavaScript Date objects.\n *\n * @example\n * const createdAt = v.date();\n * const optionalDate = v.date({ optional: true });\n */\nexport function date<\n const Opts extends ScalarOptions<Date, any> | undefined = undefined,\n>(\n options?: Opts\n): DateSchema<ComputeInput<Date, Opts>, ComputeOutput<Date, Opts>> {\n return buildSchema(\"date\", validateDate, options) as DateSchema<\n ComputeInput<Date, Opts>,\n ComputeOutput<Date, Opts>\n >;\n}\n\n// Export the validate function for reuse\nexport { validateDate };\n","import { buildSchema, ok } from \"../helpers\";\nimport type {\n ComputeInput,\n ComputeOutput,\n InferInput,\n ScalarOptions,\n VibSchema,\n} from \"../types\";\n\n// =============================================================================\n// Enum Schema\n// =============================================================================\nexport type EnumValues<S extends VibSchema> =\n S extends EnumSchema<infer TValues, any, any> ? TValues : never;\nexport type AnyEnumSchema = EnumSchema<string[], any, any>;\nexport type BaseEnumSchema<\n TValues extends string[],\n Opts extends ScalarOptions<TValues[number], any> | undefined = undefined,\n> = EnumSchema<\n TValues,\n ComputeInput<TValues[number], Opts>,\n ComputeOutput<TValues[number], Opts>\n>;\n\nexport interface EnumSchema<\n TValues extends string[],\n TInput = TValues[number],\n TOutput = TValues[number],\n> extends VibSchema<TInput, TOutput> {\n readonly type: \"enum\";\n readonly values: TValues;\n}\n\n/**\n * Create an enum schema that validates a value is one of the allowed values.\n *\n * @param values - Array of allowed values (strings or numbers)\n * @param options - Schema options\n *\n * @example\n * const status = v.enum_([\"active\", \"inactive\", \"pending\"]);\n * const level = v.enum_([1, 2, 3]);\n * const mixed = v.enum_([\"a\", 1, \"b\", 2]);\n */\n// @__NO_SIDE_EFFECTS__\nexport function enum_<\n const TValues extends string[],\n const Opts extends\n | ScalarOptions<TValues[number], any>\n | undefined = undefined,\n>(\n values: TValues,\n options?: Opts\n): EnumSchema<\n TValues,\n ComputeInput<TValues[number], Opts>,\n ComputeOutput<TValues[number], Opts>\n> {\n // Create a Set for O(1) lookup\n const valueSet = new Set<TValues[number]>(values);\n\n // Create base validator\n const baseValidate = (value: unknown) => {\n if (typeof value === \"string\" && valueSet.has(value)) {\n return ok(value as TValues[number]);\n }\n return {\n issues: [\n {\n message: `Expected one of: ${values.join(\" | \")}`,\n },\n ],\n };\n };\n\n const schema = buildSchema(\"enum\", baseValidate, options, {\n values,\n }) as EnumSchema<\n TValues,\n ComputeInput<TValues[number], Opts>,\n ComputeOutput<TValues[number], Opts>\n >;\n\n return schema;\n}\n\nconst test = enum_([\"a\", \"b\", \"c\"]);\ntype In = InferInput<typeof test>;\n","import { buildSchema, ok } from \"../helpers\";\nimport type {\n ComputeInput,\n ComputeOutput,\n ScalarOptions,\n VibSchema,\n} from \"../types\";\n\n// =============================================================================\n// Instance Schema (for class instances like Uint8Array, Buffer, etc.)\n// =============================================================================\n\nexport interface InstanceSchema<\n TClass extends abstract new (\n ...args: any\n ) => any,\n TInput = InstanceType<TClass>,\n TOutput = InstanceType<TClass>,\n> extends VibSchema<TInput, TOutput> {\n readonly type: \"instance\";\n}\n\n/**\n * Create an instance schema for validating class instances.\n *\n * @example\n * const buffer = v.instance(Uint8Array);\n * const blob = v.union([v.instance(Uint8Array), v.instance(Buffer)]);\n */\nexport function instance<\n TClass extends abstract new (\n ...args: any\n ) => any,\n const Opts extends\n | ScalarOptions<InstanceType<TClass>, any>\n | undefined = undefined,\n>(\n classConstructor: TClass,\n options?: Opts\n): InstanceSchema<\n TClass,\n ComputeInput<InstanceType<TClass>, Opts>,\n ComputeOutput<InstanceType<TClass>, Opts>\n> {\n // Pre-compute error for fast path\n const typeName = classConstructor.name || \"instance\";\n const errorResult = Object.freeze({\n issues: Object.freeze([Object.freeze({ message: `Expected ${typeName}` })]),\n });\n\n // Create base validator\n const baseValidate = (value: unknown) =>\n value instanceof classConstructor\n ? ok(value as InstanceType<TClass>)\n : errorResult;\n\n return buildSchema(\"instance\", baseValidate, options, {\n ctor: classConstructor,\n }) as InstanceSchema<\n TClass,\n ComputeInput<InstanceType<TClass>, Opts>,\n ComputeOutput<InstanceType<TClass>, Opts>\n >;\n}\n","import { buildSchema, ok } from \"../helpers\";\nimport type {\n ComputeInput,\n ComputeOutput,\n ScalarOptions,\n VibSchema,\n} from \"../types\";\n\n// =============================================================================\n// ISO Format Validators\n// =============================================================================\n\n// ISO timestamp regex: 2023-12-15T10:30:00.000Z\nconst ISO_TIMESTAMP_REGEX =\n /^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d{1,3})?(Z|[+-]\\d{2}:\\d{2})$/;\n\n// ISO date regex: 2023-12-15\nconst ISO_DATE_REGEX = /^\\d{4}-\\d{2}-\\d{2}$/;\n\n// ISO time regex: 10:30:00 or 10:30:00.000\nconst ISO_TIME_REGEX = /^\\d{2}:\\d{2}:\\d{2}(\\.\\d{1,3})?$/;\n\n// Pre-computed errors\nconst NOT_STRING_OR_DATE_ERROR = Object.freeze({\n issues: Object.freeze([\n Object.freeze({ message: \"Expected string or Date\" }),\n ]),\n});\n\n// =============================================================================\n// ISO Timestamp Schema\n// =============================================================================\n\nexport interface BaseIsoTimestampSchema<\n Opts extends ScalarOptions<string, any> | undefined = undefined,\n> extends VibSchema<\n ComputeInput<string | Date, Opts>,\n ComputeOutput<string, Opts>\n > {}\n\nexport interface IsoTimestampSchema<TInput = string | Date, TOutput = string>\n extends VibSchema<TInput, TOutput> {\n readonly type: \"iso_timestamp\";\n}\n\n// Pre-computed errors\nconst INVALID_TIMESTAMP_FORMAT = Object.freeze({\n issues: Object.freeze([\n Object.freeze({\n message: \"Expected ISO timestamp format (YYYY-MM-DDTHH:mm:ss.sssZ)\",\n }),\n ]),\n});\nconst INVALID_TIMESTAMP_DATE = Object.freeze({\n issues: Object.freeze([\n Object.freeze({ message: \"Invalid date in ISO timestamp\" }),\n ]),\n});\n\n/**\n * Validate ISO timestamp format.\n * Accepts Date objects and converts them to ISO strings.\n */\nfunction validateIsoTimestamp(value: unknown) {\n // Handle Date objects - convert to ISO string\n if (value instanceof Date) {\n if (Number.isNaN(value.getTime())) return INVALID_TIMESTAMP_DATE;\n return ok(value.toISOString());\n }\n\n if (typeof value !== \"string\") return NOT_STRING_OR_DATE_ERROR;\n if (!ISO_TIMESTAMP_REGEX.test(value)) return INVALID_TIMESTAMP_FORMAT;\n const date = new Date(value);\n if (Number.isNaN(date.getTime())) return INVALID_TIMESTAMP_DATE;\n return ok(value);\n}\n\n/**\n * Create an ISO timestamp schema.\n * Accepts strings in format: 2023-12-15T10:30:00.000Z or Date objects.\n * Date objects are automatically converted to ISO strings.\n *\n * @example\n * const timestamp = v.isoTimestamp();\n * parse(timestamp, new Date()) // Returns ISO string\n */\nexport function isoTimestamp<\n const Opts extends ScalarOptions<string, any> | undefined = undefined,\n>(\n options?: Opts\n): IsoTimestampSchema<\n ComputeInput<string | Date, Opts>,\n ComputeOutput<string, Opts>\n> {\n return buildSchema(\n \"iso_timestamp\",\n validateIsoTimestamp,\n options\n ) as IsoTimestampSchema<\n ComputeInput<string | Date, Opts>,\n ComputeOutput<string, Opts>\n >;\n}\n\n// =============================================================================\n// ISO Date Schema\n// =============================================================================\n\nexport interface BaseIsoDateSchema<\n Opts extends ScalarOptions<string, any> | undefined = undefined,\n> extends VibSchema<\n ComputeInput<string | Date, Opts>,\n ComputeOutput<string, Opts>\n > {}\n\nexport interface IsoDateSchema<TInput = string | Date, TOutput = string>\n extends VibSchema<TInput, TOutput> {\n readonly type: \"iso_date\";\n}\n\n// Pre-computed errors\nconst INVALID_DATE_FORMAT = Object.freeze({\n issues: Object.freeze([\n Object.freeze({\n message: \"Expected ISO date format (YYYY-MM-DD)\",\n }),\n ]),\n});\nconst INVALID_DATE = Object.freeze({\n issues: Object.freeze([Object.freeze({ message: \"Invalid date\" })]),\n});\n\n/**\n * Validate ISO date format.\n * Accepts Date objects and converts them to ISO date strings (YYYY-MM-DD).\n */\nfunction validateIsoDate(value: unknown) {\n // Handle Date objects - convert to ISO date string\n if (value instanceof Date) {\n if (Number.isNaN(value.getTime())) return INVALID_DATE;\n return ok(value.toISOString().split(\"T\")[0]!);\n }\n\n if (typeof value !== \"string\") return NOT_STRING_OR_DATE_ERROR;\n if (!ISO_DATE_REGEX.test(value)) return INVALID_DATE_FORMAT;\n const date = new Date(value + \"T00:00:00Z\");\n if (Number.isNaN(date.getTime())) return INVALID_DATE;\n return ok(value);\n}\n\n/**\n * Create an ISO date schema.\n * Accepts strings in format: 2023-12-15 or Date objects.\n * Date objects are automatically converted to ISO date strings (YYYY-MM-DD).\n *\n * @example\n * const birthDate = v.isoDate();\n * parse(birthDate, new Date()) // Returns \"2023-12-15\"\n */\nexport function isoDate<\n const Opts extends ScalarOptions<string, any> | undefined = undefined,\n>(\n options?: Opts\n): IsoDateSchema<\n ComputeInput<string | Date, Opts>,\n ComputeOutput<string, Opts>\n> {\n return buildSchema(\"iso_date\", validateIsoDate, options) as IsoDateSchema<\n ComputeInput<string | Date, Opts>,\n ComputeOutput<string, Opts>\n >;\n}\n\n// =============================================================================\n// ISO Time Schema\n// =============================================================================\n\nexport interface BaseIsoTimeSchema<\n Opts extends ScalarOptions<string, any> | undefined = undefined,\n> extends VibSchema<\n ComputeInput<string | Date, Opts>,\n ComputeOutput<string, Opts>\n > {}\n\nexport interface IsoTimeSchema<TInput = string | Date, TOutput = string>\n extends VibSchema<TInput, TOutput> {\n readonly type: \"iso_time\";\n}\n\n// Pre-computed errors\nconst INVALID_TIME_FORMAT = Object.freeze({\n issues: Object.freeze([\n Object.freeze({\n message: \"Expected ISO time format (HH:mm:ss)\",\n }),\n ]),\n});\nconst INVALID_TIME = Object.freeze({\n issues: Object.freeze([Object.freeze({ message: \"Invalid time\" })]),\n});\n\n/**\n * Validate ISO time format.\n * Accepts Date objects and extracts the time portion (HH:mm:ss.sss).\n */\nfunction validateIsoTime(value: unknown) {\n // Handle Date objects - extract time portion\n if (value instanceof Date) {\n if (Number.isNaN(value.getTime())) return INVALID_TIME;\n // Extract HH:mm:ss.sss from ISO string\n const isoString = value.toISOString();\n const timePart = isoString.split(\"T\")[1]!.replace(\"Z\", \"\");\n return ok(timePart);\n }\n\n if (typeof value !== \"string\") return NOT_STRING_OR_DATE_ERROR;\n if (!ISO_TIME_REGEX.test(value)) return INVALID_TIME_FORMAT;\n\n const parts = value.split(\":\").map(Number);\n const hours = parts[0] ?? 0;\n const minutes = parts[1] ?? 0;\n const seconds = parts[2] ?? 0;\n\n if (\n hours < 0 ||\n hours > 23 ||\n minutes < 0 ||\n minutes > 59 ||\n seconds < 0 ||\n seconds > 59\n ) {\n return INVALID_TIME;\n }\n return ok(value);\n}\n\n/**\n * Create an ISO time schema.\n * Accepts strings in format: 10:30:00 or Date objects.\n * Date objects are automatically converted to time strings (HH:mm:ss.sss).\n *\n * @example\n * const startTime = v.isoTime();\n * parse(startTime, new Date()) // Returns \"10:30:00.000\"\n */\nexport function isoTime<\n const Opts extends ScalarOptions<string, any> | undefined = undefined,\n>(\n options?: Opts\n): IsoTimeSchema<\n ComputeInput<string | Date, Opts>,\n ComputeOutput<string, Opts>\n> {\n return buildSchema(\"iso_time\", validateIsoTime, options) as IsoTimeSchema<\n ComputeInput<string | Date, Opts>,\n ComputeOutput<string, Opts>\n >;\n}\n\n// Export validators for reuse\nexport { validateIsoTimestamp, validateIsoDate, validateIsoTime };\n","import { buildSchema, ok } from \"../helpers\";\nimport type {\n ComputeInput,\n ComputeOutput,\n ScalarOptions,\n VibSchema,\n} from \"../types\";\n\n// =============================================================================\n// JSON Schema\n// =============================================================================\n\n/**\n * JSON-compatible value type.\n * Represents any value that can be safely serialized to JSON.\n */\nexport type JsonValue =\n | string\n | number\n | boolean\n | null\n | JsonValue[]\n | { [key: string]: JsonValue };\n\nexport interface BaseJsonSchema<\n Opts extends ScalarOptions<JsonValue, any> | undefined = undefined,\n> extends VibSchema<\n ComputeInput<JsonValue, Opts>,\n ComputeOutput<JsonValue, Opts>\n > {}\n\nexport interface JsonSchema<TInput = JsonValue, TOutput = JsonValue>\n extends VibSchema<TInput, TOutput> {\n readonly type: \"json\";\n}\n\n// Pre-computed errors for fast path\nconst NOT_JSON_ERROR = Object.freeze({\n issues: Object.freeze([\n Object.freeze({ message: \"Expected JSON-compatible value\" }),\n ]),\n});\n\n/**\n * Check if a value is JSON-compatible (can be serialized without loss).\n * Rejects: undefined, functions, symbols, bigint, circular references.\n */\nfunction isJsonValue(value: unknown, seen = new WeakSet<object>()): boolean {\n // Primitives\n if (value === null) return true;\n if (typeof value === \"string\") return true;\n if (typeof value === \"number\") return Number.isFinite(value); // Reject NaN, Infinity\n if (typeof value === \"boolean\") return true;\n\n // Reject non-JSON types\n if (typeof value === \"undefined\") return false;\n if (typeof value === \"function\") return false;\n if (typeof value === \"symbol\") return false;\n if (typeof value === \"bigint\") return false;\n\n // Arrays\n if (Array.isArray(value)) {\n // Check for circular reference\n if (seen.has(value)) return false;\n seen.add(value);\n for (let i = 0; i < value.length; i++) {\n if (!isJsonValue(value[i], seen)) return false;\n }\n return true;\n }\n\n // Objects\n if (typeof value === \"object\") {\n // Check for circular reference\n if (seen.has(value)) return false;\n seen.add(value);\n\n // Must be a plain object (not Date, RegExp, etc.)\n const proto = Object.getPrototypeOf(value);\n if (proto !== null && proto !== Object.prototype) return false;\n\n for (const key in value) {\n if (\n Object.hasOwn(value, key) &&\n !isJsonValue((value as Record<string, unknown>)[key], seen)\n ) {\n return false;\n }\n }\n return true;\n }\n\n return false;\n}\n\n/**\n * Validate that a value is JSON-compatible.\n */\nfunction validateJson(value: unknown) {\n return isJsonValue(value) ? ok(value as JsonValue) : NOT_JSON_ERROR;\n}\n\n/**\n * Create a JSON schema that validates any JSON-compatible value.\n * Accepts: strings, numbers (finite), booleans, null, arrays, plain objects.\n * Rejects: undefined, functions, symbols, bigint, circular references, class instances.\n *\n * @example\n * const data = v.json();\n * const optionalData = v.json({ optional: true });\n * const nullableData = v.json({ nullable: true });\n */\n// @__NO_SIDE_EFFECTS__\nexport function json<\n const Opts extends ScalarOptions<JsonValue, any> | undefined = undefined,\n>(\n options?: Opts\n): JsonSchema<ComputeInput<JsonValue, Opts>, ComputeOutput<JsonValue, Opts>> {\n return buildSchema(\"json\", validateJson, options) as JsonSchema<\n ComputeInput<JsonValue, Opts>,\n ComputeOutput<JsonValue, Opts>\n >;\n}\n\n// Export for reuse\nexport { validateJson, isJsonValue };\n","import { buildSchema, ok } from \"../helpers\";\nimport type {\n ComputeInput,\n ComputeOutput,\n ScalarOptions,\n VibSchema,\n} from \"../types\";\n\n// =============================================================================\n// Literal Schema\n// =============================================================================\n\nexport type LiteralValue =\n | string\n | number\n | boolean\n | null\n | undefined\n | bigint;\n\nexport interface LiteralSchema<T extends LiteralValue, TInput = T, TOutput = T>\n extends VibSchema<TInput, TOutput> {\n readonly type: \"literal\";\n readonly value: T;\n}\n\n/**\n * Create a literal schema that matches an exact value.\n *\n * @example\n * const admin = v.literal(\"admin\");\n * const zero = v.literal(0);\n * const isTrue = v.literal(true);\n */\nexport function literal<\n const T extends LiteralValue,\n const Opts extends ScalarOptions<T, any> | undefined = undefined,\n>(\n expected: T,\n options?: Opts\n): LiteralSchema<T, ComputeInput<T, Opts>, ComputeOutput<T, Opts>> {\n // Pre-compute error for fast path\n const expectedStr = expected === null ? \"null\" : String(expected);\n const errorResult = Object.freeze({\n issues: Object.freeze([\n Object.freeze({\n message: `Expected literal: ${expectedStr}`,\n }),\n ]),\n });\n\n // Create base validator\n const baseValidate = (value: unknown) =>\n value === expected ? ok(value as T) : errorResult;\n\n return buildSchema(\"literal\", baseValidate, options, {\n value: expected,\n }) as LiteralSchema<T, ComputeInput<T, Opts>, ComputeOutput<T, Opts>>;\n}\n","import type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport { createSchema, fail, ok } from \"../helpers\";\nimport type { ValidationResult, VibSchema } from \"../types\";\n\n// =============================================================================\n// NonArray Schema (Element / Unwrap)\n// =============================================================================\n\n/**\n * Extract element type from array type.\n */\ntype ElementOf<T> = T extends readonly (infer E)[] ? E : T;\n\n/**\n * Schema that validates a single element instead of an array.\n * Useful for unwrapping array schemas.\n */\nexport interface NonArraySchema<TInput, TOutput>\n extends VibSchema<TInput, TOutput> {\n readonly type: \"nonArray\";\n}\n\n/**\n * Unwrap an array schema to validate single elements.\n * If the wrapped schema expects an array, this validates a single element.\n *\n * @example\n * const tags = v.string({ array: true });\n * // tags validates: string[]\n *\n * const singleTag = v.nonArray(tags);\n * // singleTag validates: string\n *\n * @example\n * // Alias: element()\n * const oneItem = v.element(v.number({ array: true }));\n */\nexport function nonArray<I, O>(\n schema: StandardSchemaV1<I[], O[]>\n): NonArraySchema<ElementOf<I>, ElementOf<O>>;\nexport function nonArray<I, O>(\n schema: StandardSchemaV1<I, O>\n): NonArraySchema<ElementOf<I>, ElementOf<O>>;\nexport function nonArray<I, O>(\n schema: StandardSchemaV1<I, O>\n): NonArraySchema<ElementOf<I>, ElementOf<O>> {\n return createSchema(\"nonArray\", (value): ValidationResult<ElementOf<O>> => {\n // If value is an array, validate first element\n // If not, validate directly\n const toValidate = Array.isArray(value) ? value[0] : value;\n\n // For array schemas, wrap in array for validation then unwrap\n const result = schema[\"~standard\"].validate([toValidate] as unknown as I);\n if (\"then\" in result) {\n return fail(\"Async schemas are not supported\");\n }\n if (result.issues) {\n const issue = result.issues[0];\n return fail(issue?.message ?? \"Validation failed\");\n }\n\n // Unwrap the array result\n const output = (result as { value: O }).value;\n const arrayResult = output as unknown as O[];\n if (Array.isArray(arrayResult) && arrayResult.length > 0) {\n return ok(arrayResult[0] as ElementOf<O>);\n }\n\n // Fallback: maybe the schema doesn't actually require array\n return ok(output as unknown as ElementOf<O>);\n }) as NonArraySchema<ElementOf<I>, ElementOf<O>>;\n}\n\n/**\n * Alias for nonArray.\n * Extracts the element schema from an array schema.\n */\nexport const element = nonArray;\n","import type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport { createSchema, fail, ok } from \"../helpers\";\nimport type { ValidationResult, VibSchema } from \"../types\";\n\n// =============================================================================\n// NonNullable Schema\n// =============================================================================\n\n/**\n * Schema that wraps another schema and excludes null from both input and output.\n * Rejects null values at validation time.\n */\nexport interface NonNullableSchema<TInput, TOutput>\n extends VibSchema<TInput, TOutput> {\n readonly type: \"nonNullable\";\n}\n\n/**\n * Wrap a schema to exclude null from both input and output types.\n * Fails validation if the value is null.\n *\n * @example\n * const maybeNull = v.string({ nullable: true });\n * const definitelyString = v.nonNullable(maybeNull);\n * // Input: string, Output: string (null excluded from both)\n *\n * @example\n * // Works with any StandardSchemaV1\n * const externalSchema: StandardSchemaV1<unknown, string | null> = ...;\n * const strict = v.nonNullable(externalSchema);\n */\nexport function nonNullable<I, O>(\n schema: StandardSchemaV1<I, O | null> | StandardSchemaV1<I, O>\n): NonNullableSchema<NonNullable<I>, NonNullable<O>> {\n return createSchema(\n \"nonNullable\",\n (value): ValidationResult<NonNullable<O>> => {\n // Reject null at input\n if (value === null) {\n return fail(\"Expected non-null value, received null\");\n }\n const result = schema[\"~standard\"].validate(value);\n if (\"then\" in result) {\n return fail(\"Async schemas are not supported\");\n }\n if (result.issues) {\n const issue = result.issues[0];\n return fail(issue?.message ?? \"Validation failed\");\n }\n const output = (result as { value: O | null }).value;\n // Also reject null output (in case wrapped schema produces null)\n if (output === null) {\n return fail(\"Expected non-null value, received null\");\n }\n return ok(output as NonNullable<O>);\n }\n ) as NonNullableSchema<NonNullable<I>, NonNullable<O>>;\n}\n","import type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport { createSchema, fail, ok } from \"../helpers\";\nimport type { ValidationResult, VibSchema } from \"../types\";\n\n// =============================================================================\n// NonOptional Schema (Required)\n// =============================================================================\n\n/**\n * Schema that wraps another schema and ensures the value is defined.\n * Rejects undefined values.\n */\nexport interface NonOptionalSchema<TInput, TOutput>\n extends VibSchema<TInput, TOutput> {\n readonly type: \"nonOptional\";\n}\n\n/**\n * Wrap a schema to ensure its input/output is not undefined.\n * Fails validation if the value is undefined.\n *\n * @example\n * const maybeUndefined = v.string({ optional: true });\n * const required = v.nonOptional(maybeUndefined);\n * // Input: string, Output: string (undefined rejected)\n *\n * @example\n * // Alias: required()\n * const requiredName = v.required(v.string({ optional: true }));\n */\nexport function nonOptional<I, O>(\n schema:\n | StandardSchemaV1<I | undefined, O | undefined>\n | StandardSchemaV1<I, O | undefined>\n | StandardSchemaV1<I | undefined, O>\n | StandardSchemaV1<I, O>\n): NonOptionalSchema<Exclude<I, undefined>, Exclude<O, undefined>> {\n return createSchema(\n \"nonOptional\",\n (value): ValidationResult<Exclude<O, undefined>> => {\n if (value === undefined) {\n return fail(\"Value is required, received undefined\");\n }\n const result = schema[\"~standard\"].validate(value);\n if (\"then\" in result) {\n return fail(\"Async schemas are not supported\");\n }\n if (result.issues) {\n const issue = result.issues[0];\n return fail(issue?.message ?? \"Validation failed\");\n }\n const output = (result as { value: O | undefined }).value;\n if (output === undefined) {\n return fail(\"Value is required, received undefined\");\n }\n return ok(output as Exclude<O, undefined>);\n }\n ) as NonOptionalSchema<Exclude<I, undefined>, Exclude<O, undefined>>;\n}\n\n/**\n * Alias for nonOptional.\n * Makes a schema required (rejects undefined).\n */\nexport const required = nonOptional;\n","import { createSchema, ok } from \"../helpers\";\nimport type {\n InferInput,\n InferOutput,\n ValidationResult,\n VibSchema,\n} from \"../types\";\n\n// =============================================================================\n// Nullable Schema\n// =============================================================================\n\nexport interface NullableSchema<\n TWrapped extends VibSchema<any, any>,\n TInput = InferInput<TWrapped> | null,\n TOutput = InferOutput<TWrapped> | null,\n> extends VibSchema<TInput, TOutput> {\n readonly type: \"nullable\";\n readonly wrapped: TWrapped;\n}\n\n/**\n * Create a nullable schema that allows null values.\n *\n * @example\n * const nullableName = v.nullable(v.string());\n */\nexport function nullable<TWrapped extends VibSchema<any, any>>(\n wrapped: TWrapped\n): NullableSchema<TWrapped> {\n // Cache validate function directly\n const validate = wrapped[\"~standard\"].validate;\n\n const schema = createSchema(\n \"nullable\",\n (value): ValidationResult<InferOutput<TWrapped> | null> => {\n // Handle null - fast path\n if (value === null) {\n return ok(null);\n }\n\n // Delegate to wrapped schema (cast to our result type)\n return validate(value) as ValidationResult<InferOutput<TWrapped>>;\n }\n ) as NullableSchema<TWrapped>;\n\n // Add reference\n (schema as any).wrapped = wrapped;\n\n return schema;\n}\n\n/**\n * Conditionally wrap a schema in nullable based on a boolean flag.\n * Useful for building schemas dynamically where nullability is determined at compile time.\n *\n * @example\n * const schema = v.maybeNullable(v.string(), true); // NullableSchema<StringSchema>\n * const schema2 = v.maybeNullable(v.string(), false); // StringSchema\n */\nexport function maybeNullable<\n TWrapped extends VibSchema<any, any>,\n TIsNullable extends boolean,\n>(\n wrapped: TWrapped,\n isNullable: TIsNullable\n): TIsNullable extends true ? NullableSchema<TWrapped> : TWrapped {\n if (isNullable) {\n return nullable(wrapped) as TIsNullable extends true\n ? NullableSchema<TWrapped>\n : TWrapped;\n }\n return wrapped as TIsNullable extends true\n ? NullableSchema<TWrapped>\n : TWrapped;\n}\n","import { buildSchema, ok } from \"../helpers\";\nimport type {\n ComputeInput,\n ComputeOutput,\n ScalarOptions,\n VibSchema,\n} from \"../types\";\n\n// =============================================================================\n// Number Schema\n// =============================================================================\n\nexport interface BaseNumberSchema<\n Opts extends ScalarOptions<number, any> | undefined = undefined,\n> extends VibSchema<ComputeInput<number, Opts>, ComputeOutput<number, Opts>> {}\n\nexport interface NumberSchema<TInput = number, TOutput = number>\n extends VibSchema<TInput, TOutput> {\n readonly type: \"number\";\n}\n\n// Pre-computed error for fast path\nconst NUMBER_ERROR = Object.freeze({\n issues: Object.freeze([Object.freeze({ message: \"Expected finite number\" })]),\n});\n\n/**\n * Validate that a value is a finite number (rejects NaN and Infinity).\n */\nfunction validateNumber(value: unknown) {\n return typeof value === \"number\" && Number.isFinite(value)\n ? ok(value)\n : NUMBER_ERROR;\n}\n\n/**\n * Create a number schema.\n *\n * @example\n * const age = v.number();\n * const optionalAge = v.number({ optional: true });\n * const scores = v.number({ array: true });\n */\nexport function number<\n const Opts extends ScalarOptions<number, any> | undefined = undefined,\n>(\n options?: Opts\n): NumberSchema<ComputeInput<number, Opts>, ComputeOutput<number, Opts>> {\n return buildSchema(\"number\", validateNumber, options) as NumberSchema<\n ComputeInput<number, Opts>,\n ComputeOutput<number, Opts>\n >;\n}\n\n// =============================================================================\n// Integer Schema (number with integer constraint)\n// =============================================================================\n\nexport interface BaseIntegerSchema<\n Opts extends ScalarOptions<number, any> | undefined = undefined,\n> extends VibSchema<ComputeInput<number, Opts>, ComputeOutput<number, Opts>> {}\n\nexport interface IntegerSchema<TInput = number, TOutput = number>\n extends VibSchema<TInput, TOutput> {\n readonly type: \"integer\";\n}\n\n// Pre-computed error for fast path\nconst INTEGER_ERROR = Object.freeze({\n issues: Object.freeze([Object.freeze({ message: \"Expected integer\" })]),\n});\n\n/**\n * Validate that a value is an integer.\n */\nfunction validateInteger(value: unknown) {\n return typeof value === \"number\" && Number.isInteger(value)\n ? ok(value)\n : INTEGER_ERROR;\n}\n\n/**\n * Create an integer schema.\n *\n * @example\n * const count = v.integer();\n */\nexport function integer<\n const Opts extends ScalarOptions<number, any> | undefined = undefined,\n>(\n options?: Opts\n): IntegerSchema<ComputeInput<number, Opts>, ComputeOutput<number, Opts>> {\n return buildSchema(\"integer\", validateInteger, options) as IntegerSchema<\n ComputeInput<number, Opts>,\n ComputeOutput<number, Opts>\n >;\n}\n\n// Export validate functions for reuse\nexport { validateNumber, validateInteger };\n","import type { StandardSchemaV1 } from \"@standard-schema\";\nimport { fail, ok } from \"../helpers\";\nimport { createJsonSchemaConverter } from \"../json-schema/factory\";\nimport type {\n InferInputShape,\n InferOutputShape,\n ThunkCast,\n VibSchema,\n} from \"../types\";\n\n// =============================================================================\n// Object Schema Types\n// =============================================================================\n\n/**\n * Object entries - a record of field names to schemas or thunks.\n */\nexport type ObjectEntries = Record<\n string,\n VibSchema<any, any> | ThunkCast<any, any>\n>;\n\n/**\n * Options for object schemas.\n */\nexport interface ObjectOptions<T = unknown, TKeys extends string = string> {\n /** Make all fields optional (default: true) */\n partial?: boolean;\n /** Reject unknown keys (default: true) */\n strict?: boolean;\n /** Make the object itself optional (undefined allowed) */\n optional?: boolean;\n /** Make the object itself nullable (null allowed) */\n nullable?: boolean;\n /** Validate as array of objects */\n array?: boolean;\n /** Default value when undefined/null */\n default?: T | (() => T);\n /** Transform output */\n transform?: (value: T) => T;\n /** Object name for circular references in json schema*/\n name?: string;\n /** Object description for json schema*/\n description?: string;\n /** Require at least these specific keys (works with partial: true) */\n atLeast?: TKeys[];\n}\n\n/**\n * Compute input type based on partial option.\n * Default is partial: true, so only non-partial when explicitly { partial: false }\n * If atLeast is specified, those keys are required even when partial: true\n */\ntype ComputeObjectInput<TEntries, TOpts> = TOpts extends { partial: false }\n ? InferInputShape<TEntries>\n : TOpts extends { atLeast: infer Keys extends readonly string[] }\n ? RequireKeys<Partial<InferInputShape<TEntries>>, Keys[number]>\n : Partial<InferInputShape<TEntries>>;\n\n/**\n * Compute output type based on entries.\n * Unlike input, output doesn't use Partial - each field's schema determines\n * whether its output includes undefined (based on whether it has a default).\n */\ntype ComputeObjectOutput<TEntries, _TOpts> = InferOutputShape<TEntries>;\n\n/**\n * Make specific keys required in an otherwise partial object.\n * Uses a mapped type instead of Omit & Required<Pick> to reduce type depth.\n */\ntype RequireKeys<T, K extends string> = {\n [P in keyof T as P extends K ? never : P]?: T[P];\n} & {\n [P in keyof T as P extends K ? P : never]-?: T[P];\n};\n\n/**\n * Apply wrapper options (optional, nullable, array) to input type.\n * Input accepts undefined when optional (even with default).\n */\ntype ApplyObjectOptionsInput<TBase, TOpts> = TOpts extends { array: true }\n ? TOpts extends { optional: true }\n ? TOpts extends { nullable: true }\n ? TBase[] | undefined | null\n : TBase[] | undefined\n : TOpts extends { nullable: true }\n ? TBase[] | null\n : TBase[]\n : TOpts extends { optional: true }\n ? TOpts extends { nullable: true }\n ? TBase | undefined | null\n : TBase | undefined\n : TOpts extends { nullable: true }\n ? TBase | null\n : TBase;\n\n/**\n * Apply wrapper options (optional, nullable, array) to output type.\n * When a default is provided, undefined is not included in output\n * (the default will always be applied).\n */\ntype ApplyObjectOptionsOutput<TBase, TOpts> = TOpts extends { array: true }\n ? TOpts extends { optional: true }\n ? TOpts extends { default: any }\n ? TOpts extends { nullable: true }\n ? TBase[] | null\n : TBase[]\n : TOpts extends { nullable: true }\n ? TBase[] | undefined | null\n : TBase[] | undefined\n : TOpts extends { nullable: true }\n ? TBase[] | null\n : TBase[]\n : TOpts extends { optional: true }\n ? TOpts extends { default: any }\n ? TOpts extends { nullable: true }\n ? TBase | null\n : TBase\n : TOpts extends { nullable: true }\n ? TBase | undefined | null\n : TBase | undefined\n : TOpts extends { nullable: true }\n ? TBase | null\n : TBase;\n\n/**\n * Object schema interface.\n */\nexport interface ObjectSchema<\n TEntries,\n TOpts extends ObjectOptions | undefined = undefined,\n TInput = ApplyObjectOptionsInput<ComputeObjectInput<TEntries, TOpts>, TOpts>,\n TOutput = ApplyObjectOptionsOutput<\n ComputeObjectOutput<TEntries, TOpts>,\n TOpts\n >,\n> extends VibSchema<TInput, TOutput> {\n readonly type: \"object\";\n readonly entries: TEntries;\n readonly options: TOpts;\n readonly parse: VibSchema<TInput, TOutput>[\"~standard\"][\"validate\"];\n /** Extend this schema with additional entries */\n extend<\n TNewEntries extends ObjectEntries,\n TNewTOpts extends ObjectOptions | undefined = undefined,\n >(\n newEntries: TNewEntries,\n options?: TNewTOpts\n ): ObjectSchema<TEntries & TNewEntries, TOpts & TNewTOpts>;\n}\n\n// =============================================================================\n// Object Schema Implementation\n// =============================================================================\n\n// Pre-computed error for fast path\nconst OBJECT_TYPE_ERROR = { issues: [{ message: \"Expected object\" }] };\n\n/**\n * Create an optimized validator for an object schema.\n * Minimal overhead, Valibot-style simplicity.\n */\nfunction createObjectValidator(\n entries: ObjectEntries,\n options: ObjectOptions = {}\n) {\n const { partial = true, strict = true, atLeast } = options;\n const keys = Object.keys(entries);\n const keyCount = keys.length;\n const keySet = new Set(keys);\n\n // Pre-compute which keys are required via atLeast\n const atLeastSet = atLeast ? new Set(atLeast) : null;\n\n // Lazy resolution flag - for circular refs\n let resolved = false;\n // Direct arrays for maximum access speed (no object property lookup)\n const validates: ((v: unknown) => any)[] = new Array(keyCount);\n const acceptsUndefined: boolean[] = new Array(keyCount);\n const isRequired: boolean[] = new Array(keyCount);\n const keyPaths: PropertyKey[][] = new Array(keyCount);\n const missingErrors: {\n issues: { message: string; path: PropertyKey[] }[];\n }[] = new Array(keyCount);\n\n // Pre-compute key paths, error messages, and required flags\n for (let i = 0; i < keyCount; i++) {\n const key = keys[i]!;\n keyPaths[i] = [key];\n missingErrors[i] = {\n issues: [{ message: `Missing required field: ${key}`, path: [key] }],\n };\n // Key is required if: not partial, OR key is in atLeast list\n isRequired[i] = !partial || (atLeastSet?.has(key) ?? false);\n }\n\n // Resolve validators lazily (for circular refs)\n const resolve = () => {\n if (resolved) return;\n resolved = true;\n for (let i = 0; i < keyCount; i++) {\n const key = keys[i]!;\n const entry = entries[key]!;\n const schema =\n typeof entry === \"function\"\n ? (entry as () => VibSchema<any, any> | undefined)()\n : entry;\n\n // Defensive null check: if schema is undefined or invalid, create a failing validator\n if (!schema?.[\"~standard\"]) {\n console.warn(\n `[VibORM] Schema for key \"${key}\" is undefined or invalid`\n );\n validates[i] = () => ({\n issues: [{ message: `Schema error: \"${key}\" schema is undefined` }],\n });\n acceptsUndefined[i] = true;\n continue;\n }\n\n const validate = schema[\"~standard\"].validate;\n validates[i] = validate;\n\n // Check if schema accepts undefined by inspecting schema properties\n // This avoids calling the validator (which would trigger default functions)\n const schemaAny = schema as {\n type?: string;\n options?: { optional?: boolean; default?: unknown };\n default?: unknown;\n wrapped?: {\n type?: string;\n default?: unknown;\n options?: { optional?: boolean; default?: unknown };\n };\n };\n\n // Schema accepts undefined if:\n // 1. It's an optional wrapper (type: \"optional\")\n // 2. It has options.optional: true (like string({ optional: true }))\n // 3. It has options.default (like number({ default: 18 }))\n // 4. It has a default property directly (optional wrapper with default)\n // 5. It's a transform wrapper that wraps an optional schema with default\n const isOptionalWrapper = schemaAny.type === \"optional\";\n const hasOptionalOption = schemaAny.options?.optional === true;\n const hasDefaultOption = schemaAny.options?.default !== undefined;\n const hasDefaultProp = schemaAny.default !== undefined;\n // Check for transform (coerce) wrapping a schema with default\n // Handles both: v.coerce(v.optional(x, default), fn) and v.coerce(v.number({ default }), fn)\n const isTransformWithDefault =\n schemaAny.type === \"transform\" &&\n (schemaAny.wrapped?.default !== undefined ||\n schemaAny.wrapped?.options?.default !== undefined);\n\n acceptsUndefined[i] =\n isOptionalWrapper ||\n hasOptionalOption ||\n hasDefaultOption ||\n hasDefaultProp ||\n isTransformWithDefault;\n }\n };\n\n return (value: unknown) => {\n // Type check\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n return OBJECT_TYPE_ERROR;\n }\n\n const input = value as Record<string, unknown>;\n resolve(); // Inline the resolution check\n const output: Record<string, unknown> = {};\n\n // Strict mode: check for extra keys first (fail-fast)\n if (strict) {\n for (const key in input) {\n if (!keySet.has(key)) {\n return { issues: [{ message: `Unknown key: ${key}`, path: [key] }] };\n }\n }\n }\n\n // Validate each field - direct array access, no object property lookup\n for (let i = 0; i < keyCount; i++) {\n const key = keys[i]!;\n\n // Handle missing key\n if (!(key in input)) {\n // Key is required (partial: false OR in atLeast) and schema doesn't accept undefined\n if (isRequired[i] && !acceptsUndefined[i]) {\n return missingErrors[i];\n }\n\n // If schema accepts undefined, run validator to apply defaults\n if (acceptsUndefined[i]) {\n const result = validates[i]!(undefined);\n if (result.issues) {\n // Should not happen if acceptsUndefined is correct, but handle it\n return missingErrors[i];\n }\n if (\"then\" in result) {\n return {\n issues: [{ message: \"Async not supported\", path: keyPaths[i] }],\n };\n }\n output[key] = result.value;\n } else {\n // Field is optional (partial: true, not in atLeast) but schema doesn't have defaults\n // Just set to undefined without running validator\n output[key] = undefined;\n }\n continue;\n }\n\n // Validate field - direct function call\n const result = validates[i]!(input[key]);\n\n // Handle validation error (most common unhappy path)\n if (result.issues) {\n const issue = result.issues[0]!;\n return {\n issues: [\n {\n message: issue.message,\n path: issue.path ? keyPaths[i]!.concat(issue.path) : keyPaths[i],\n },\n ],\n };\n }\n\n // Handle async (rare)\n if (\"then\" in result) {\n return {\n issues: [{ message: \"Async not supported\", path: keyPaths[i] }],\n };\n }\n\n output[key] = result.value;\n }\n\n return { value: output };\n };\n}\n\n/**\n * Create an object schema.\n *\n * IMPORTANT: No constraint on TEntries to allow circular reference resolution.\n * The identity conditional (R extends infer _ ? _ : never) defers type evaluation.\n *\n * @param entries - Object field definitions\n * @param options - Schema options\n * - `strict` (default: true) - Reject unknown keys\n * - `partial` (default: true) - Make all fields optional\n * - `optional` - Allow undefined\n * - `nullable` - Allow null\n * - `array` - Validate as array of objects\n * - `default` - Default value\n * - `transform` - Transform output\n *\n * @example\n * // Basic object (strict by default)\n * const user = v.object({\n * name: v.string(),\n * age: v.number(),\n * });\n *\n * // Circular references\n * const node = v.object({\n * value: v.string(),\n * child: () => node, // Thunk\n * });\n */\nexport function object<\n TEntries, // NO constraint - critical for circular references\n const TOpts extends ObjectOptions | undefined = undefined,\n R = ObjectSchema<TEntries, TOpts>,\n>(entries: TEntries, options?: TOpts): R extends infer _ ? _ : never {\n type BaseOutput = ComputeObjectOutput<TEntries, TOpts>;\n\n // Pre-create the optimized object validator (caches keys and schemas)\n const validateObj = createObjectValidator(entries as ObjectEntries, options);\n\n // Check if we have wrapper options (optional/nullable/array)\n const hasOptional = options?.optional === true;\n const hasNullable = options?.nullable === true;\n const hasArray = options?.array === true;\n const hasTransform = options?.transform !== undefined;\n const hasDefault = options?.default !== undefined;\n\n // Fast path: no wrapper options (most common case)\n const needsWrapper =\n hasOptional || hasNullable || hasArray || hasTransform || hasDefault;\n\n let validate: (value: unknown) => any;\n\n if (needsWrapper) {\n // Slow path: handle wrapper options\n validate = (value: unknown) => {\n // Handle optional\n if (hasOptional && value === undefined) {\n if (hasDefault) {\n const defaultVal =\n typeof options!.default === \"function\"\n ? (options!.default as () => BaseOutput)()\n : options!.default;\n return ok(defaultVal);\n }\n return ok(undefined);\n }\n\n // Handle nullable\n if (hasNullable && value === null) {\n if (hasDefault) {\n const defaultVal =\n typeof options!.default === \"function\"\n ? (options!.default as () => BaseOutput)()\n : options!.default;\n return ok(defaultVal);\n }\n return ok(null);\n }\n\n // Handle array\n if (hasArray) {\n if (!Array.isArray(value)) {\n return fail(`Expected array of objects, received ${typeof value}`);\n }\n\n const len = value.length;\n const results = new Array<BaseOutput>(len);\n\n for (let i = 0; i < len; i++) {\n const itemResult = validateObj(value[i])!;\n if (itemResult.issues) {\n const issue = itemResult.issues[0] as {\n message: string;\n path?: PropertyKey[];\n };\n const newPath = issue.path\n ? ([i] as PropertyKey[]).concat(issue.path)\n : [i];\n return fail(issue.message, newPath);\n }\n results[i] = hasTransform\n ? (options!.transform!(\n (itemResult as { value: any }).value\n ) as BaseOutput)\n : ((itemResult as { value: any }).value as BaseOutput);\n }\n return ok(results);\n }\n\n // Single object validation\n const result = validateObj(value)!;\n if (result.issues) {\n return result;\n }\n\n return hasTransform\n ? ok(\n options!.transform!((result as { value: any }).value as BaseOutput)\n )\n : result;\n };\n } else {\n // Fast path: direct object validation\n validate = validateObj;\n }\n\n const schema = {\n type: \"object\" as const,\n entries,\n options,\n parse: (value: unknown) => {\n return validate(value) as\n | StandardSchemaV1.SuccessResult<BaseOutput>\n | StandardSchemaV1.FailureResult;\n },\n\n \"~standard\": {\n version: 1 as const,\n vendor: \"viborm\" as const,\n validate,\n parse: (value: unknown) => {\n return validate(value) as\n | StandardSchemaV1.SuccessResult<BaseOutput>\n | StandardSchemaV1.FailureResult;\n },\n // Lazy jsonSchema - converter is created when first accessed\n get jsonSchema() {\n const converter = createJsonSchemaConverter(\n schema as unknown as VibSchema<unknown, unknown>\n );\n // Replace getter with static value for subsequent access\n Object.defineProperty(this, \"jsonSchema\", {\n value: converter,\n writable: false,\n enumerable: true,\n });\n return converter;\n },\n },\n extend: (newEntries: ObjectEntries) =>\n object({ ...entries, ...newEntries } as any, options),\n };\n\n return schema as R extends infer _ ? _ : never;\n}\n","import { createSchema, ok } from \"../helpers\";\nimport type {\n Cast,\n InferInput,\n InferOutput,\n ThunkCast,\n ValidationResult,\n VibSchema,\n} from \"../types\";\n\n// =============================================================================\n// Optional Schema\n// =============================================================================\n\n/**\n * Schema or thunk that can be wrapped with optional.\n */\nexport type WrappableSchema =\n | VibSchema<any, any>\n | ThunkCast<any, any>\n | (() => Cast<any, any>);\n\n/**\n * Unwrap a schema or thunk to get the underlying schema type.\n */\ntype UnwrapSchema<T> =\n T extends VibSchema<any, any>\n ? T\n : T extends ThunkCast<infer I, infer O>\n ? VibSchema<I, O>\n : T extends () => Cast<infer I, infer O>\n ? VibSchema<I, O>\n : never;\n\nexport interface OptionalSchema<\n TWrapped extends WrappableSchema,\n TDefault = undefined,\n TInput = InferInput<UnwrapSchema<TWrapped>> | undefined,\n TOutput = TDefault extends undefined\n ? InferOutput<UnwrapSchema<TWrapped>> | undefined\n : InferOutput<UnwrapSchema<TWrapped>>,\n> extends VibSchema<TInput, TOutput> {\n readonly type: \"optional\";\n readonly wrapped: TWrapped;\n readonly default: TDefault;\n}\n\n// Compute output type based on default\ntype OptionalOutput<\n TWrapped extends WrappableSchema,\n TDefault,\n> = TDefault extends undefined\n ? InferOutput<UnwrapSchema<TWrapped>> | undefined\n : InferOutput<UnwrapSchema<TWrapped>>;\n\n/**\n * Create an optional schema that allows undefined values.\n * Supports both direct schemas and thunks (for circular references).\n * Optionally provide a default value for when undefined is received.\n *\n * @example\n * const optionalName = v.optional(v.string());\n * const nameWithDefault = v.optional(v.string(), \"Unknown\");\n *\n * // With thunks (circular references)\n * const node = v.object({ child: v.optional(() => node) });\n */\nexport function optional<\n TWrapped extends WrappableSchema,\n TDefault extends\n | InferOutput<UnwrapSchema<TWrapped>>\n | (() => InferOutput<UnwrapSchema<TWrapped>>)\n | undefined = undefined,\n>(\n wrapped: TWrapped,\n defaultValue?: TDefault\n): OptionalSchema<TWrapped, TDefault> {\n // Check if wrapped is a thunk (function) or direct schema\n const isThunk = typeof wrapped === \"function\" && !(\"~standard\" in wrapped);\n\n // Lazy resolution for thunks\n let resolvedSchema: VibSchema<any, any> | null = null;\n let cachedValidate: ((value: unknown) => any) | null = null;\n\n const getValidate = () => {\n if (cachedValidate) return cachedValidate;\n\n if (isThunk) {\n // Resolve thunk lazily\n resolvedSchema = (wrapped as () => VibSchema<any, any>)();\n cachedValidate = resolvedSchema[\"~standard\"].validate;\n } else {\n // Direct schema - cache immediately\n cachedValidate = (wrapped as VibSchema<any, any>)[\"~standard\"].validate;\n }\n\n return cachedValidate;\n };\n\n // If not a thunk, cache validate immediately for performance\n if (!isThunk) {\n cachedValidate = (wrapped as VibSchema<any, any>)[\"~standard\"].validate;\n }\n\n const schema = createSchema(\n \"optional\",\n (value): ValidationResult<OptionalOutput<TWrapped, TDefault>> => {\n // Handle undefined - fast path\n if (value === undefined) {\n if (defaultValue !== undefined) {\n const resolved =\n typeof defaultValue === \"function\"\n ? (defaultValue as () => InferOutput<UnwrapSchema<TWrapped>>)()\n : defaultValue;\n return ok(resolved) as ValidationResult<\n OptionalOutput<TWrapped, TDefault>\n >;\n }\n return ok(undefined) as ValidationResult<\n OptionalOutput<TWrapped, TDefault>\n >;\n }\n\n // Delegate to wrapped schema (resolve thunk if needed)\n const validate = getValidate();\n return validate(value) as ValidationResult<\n OptionalOutput<TWrapped, TDefault>\n >;\n }\n ) as OptionalSchema<TWrapped, TDefault>;\n\n // Add references\n (schema as any).wrapped = wrapped;\n (schema as any).default = defaultValue;\n\n return schema;\n}\n","import { buildSchema, ok } from \"../helpers\";\nimport type {\n ComputeInput,\n ComputeOutput,\n ScalarOptions,\n VibSchema,\n} from \"../types\";\n\n// =============================================================================\n// Point Schema ({ x: number, y: number })\n// =============================================================================\n\n/**\n * Point type with x and y coordinates.\n */\nexport interface Point {\n x: number;\n y: number;\n}\n\nexport interface BasePointSchema<\n Opts extends ScalarOptions<Point, any> | undefined = undefined,\n> extends VibSchema<ComputeInput<Point, Opts>, ComputeOutput<Point, Opts>> {}\n\nexport interface PointSchema<TInput = Point, TOutput = Point>\n extends VibSchema<TInput, TOutput> {\n readonly type: \"point\";\n}\n\n// Pre-computed errors for fast path\nconst NOT_OBJECT_ERROR = Object.freeze({\n issues: Object.freeze([Object.freeze({ message: \"Expected point object\" })]),\n});\nconst MISSING_XY_ERROR = Object.freeze({\n issues: Object.freeze([\n Object.freeze({ message: \"Expected point with x and y properties\" }),\n ]),\n});\nconst INVALID_X_ERROR = Object.freeze({\n issues: Object.freeze([\n Object.freeze({ message: \"Expected x to be a number\" }),\n ]),\n});\nconst INVALID_Y_ERROR = Object.freeze({\n issues: Object.freeze([\n Object.freeze({ message: \"Expected y to be a number\" }),\n ]),\n});\n\n/**\n * Validate that a value is a point with x and y coordinates.\n */\nexport function validatePoint(value: unknown) {\n if (typeof value !== \"object\" || value === null) return NOT_OBJECT_ERROR;\n\n const obj = value as Record<string, unknown>;\n if (!(\"x\" in obj && \"y\" in obj)) return MISSING_XY_ERROR;\n if (typeof obj.x !== \"number\" || Number.isNaN(obj.x)) return INVALID_X_ERROR;\n if (typeof obj.y !== \"number\" || Number.isNaN(obj.y)) return INVALID_Y_ERROR;\n\n return ok({ x: obj.x, y: obj.y } as Point);\n}\n\n/**\n * Create a point schema for { x, y } coordinates.\n *\n * @example\n * const location = v.point();\n * const optionalPoint = v.point({ optional: true });\n * const pointArray = v.point({ array: true });\n */\nexport function point<\n const Opts extends ScalarOptions<Point, any> | undefined = undefined,\n>(\n options?: Opts\n): PointSchema<ComputeInput<Point, Opts>, ComputeOutput<Point, Opts>> {\n return buildSchema(\"point\", validatePoint, options) as PointSchema<\n ComputeInput<Point, Opts>,\n ComputeOutput<Point, Opts>\n >;\n}\n","import { buildSchema, ok } from \"../helpers\";\nimport type {\n ComputeInput,\n ComputeOutput,\n ScalarOptions,\n VibSchema,\n} from \"../types\";\n\n// =============================================================================\n// String Schema\n// =============================================================================\nexport interface BaseStringSchema<\n Opts extends ScalarOptions<string, any> | undefined = undefined,\n> extends VibSchema<ComputeInput<string, Opts>, ComputeOutput<string, Opts>> {}\n\nexport interface StringSchema<TInput = string, TOutput = string>\n extends VibSchema<TInput, TOutput> {\n readonly type: \"string\";\n}\n\n// Pre-computed error for fast path (avoid allocation on error)\nconst STRING_ERROR = Object.freeze({\n issues: Object.freeze([Object.freeze({ message: \"Expected string\" })]),\n});\n\n/**\n * Validate that a value is a string.\n */\nfunction validateString(value: unknown) {\n return typeof value === \"string\" ? ok(value) : STRING_ERROR;\n}\n\n/**\n * Create a string schema.\n *\n * @example\n * const name = v.string();\n * const optionalName = v.string({ optional: true });\n * const tags = v.string({ array: true });\n */\nexport function string<\n const Opts extends ScalarOptions<string, any> | undefined = undefined,\n>(\n options?: Opts\n): StringSchema<ComputeInput<string, Opts>, ComputeOutput<string, Opts>> {\n return buildSchema(\"string\", validateString, options) as StringSchema<\n ComputeInput<string, Opts>,\n ComputeOutput<string, Opts>\n >;\n}\n\n// Export the validate function for reuse\nexport { validateString };\n","import { createSchema, fail, ok, validateSchema } from \"../helpers\";\nimport type { InferInput, InferOutput, VibSchema } from \"../types\";\n\n// =============================================================================\n// Union Schema\n// =============================================================================\n\nexport type UnionOptions<T extends readonly VibSchema<any, any>[]> = T;\n\nexport interface UnionSchema<\n TOptions extends readonly VibSchema<any, any>[],\n TInput = TOptions[number][\" vibInferred\"][\"0\"],\n TOutput = InferOutput<TOptions[number]>,\n> extends VibSchema<TInput, TOutput> {\n readonly type: \"union\";\n readonly options: TOptions;\n}\n\n/**\n * Create a union schema that validates against multiple options.\n * Returns the result of the first matching schema.\n *\n * @example\n * const stringOrNumber = v.union([v.string(), v.number()]);\n */\nexport function union<const TOptions extends readonly VibSchema<any, any>[]>(\n options: TOptions\n): UnionSchema<TOptions> {\n const schema = createSchema<\n InferInput<TOptions[number]>,\n InferOutput<TOptions[number]>\n >(\"union\", (value) => {\n const errors: string[] = [];\n\n for (const option of options) {\n const result = validateSchema(option, value);\n if (!result.issues) {\n return ok(\n (result as { value: unknown }).value as InferOutput<TOptions[number]>\n );\n }\n errors.push(result.issues[0]!.message);\n }\n\n return fail(`Value did not match any union member: ${errors.join(\", \")}`);\n }) as UnionSchema<TOptions>;\n\n (schema as any).options = options;\n\n return schema;\n}\n","import { buildSchema, fail, ok } from \"../helpers\";\nimport type {\n ComputeInput,\n ComputeOutput,\n ScalarOptions,\n VibSchema,\n} from \"../types\";\n\n// =============================================================================\n// Vector Schema (array of numbers for embeddings/ML)\n// =============================================================================\n\nexport interface BaseVectorSchema<\n Opts extends ScalarOptions<number[], any> | undefined = undefined,\n> extends VibSchema<\n ComputeInput<number[], Opts>,\n ComputeOutput<number[], Opts>\n > {}\n\nexport interface VectorSchema<TInput = number[], TOutput = number[]>\n extends VibSchema<TInput, TOutput> {\n readonly type: \"vector\";\n}\n\n// Pre-computed error for fast path\nconst NOT_ARRAY_ERROR = Object.freeze({\n issues: Object.freeze([\n Object.freeze({ message: \"Expected array of numbers\" }),\n ]),\n});\n\n/**\n * Validate that a value is a vector (array of numbers).\n * Optionally check for specific dimensions.\n */\nfunction createVectorValidator(dimensions?: number) {\n // Pre-compute dimension error if applicable\n const dimensionError =\n dimensions !== undefined\n ? Object.freeze({\n issues: Object.freeze([\n Object.freeze({\n message: `Expected vector of ${dimensions} dimensions`,\n }),\n ]),\n })\n : null;\n\n return (value: unknown) => {\n if (!Array.isArray(value)) return NOT_ARRAY_ERROR;\n\n const len = value.length;\n for (let i = 0; i < len; i++) {\n if (typeof value[i] !== \"number\" || Number.isNaN(value[i])) {\n return fail(`Expected number at index ${i}`);\n }\n }\n\n if (dimensionError && len !== dimensions) return dimensionError;\n\n return ok(value as number[]);\n };\n}\n\n/**\n * Create a vector schema for arrays of numbers (embeddings, coordinates, etc.)\n *\n * @param dimensions - Optional fixed number of dimensions\n * @param options - Schema options\n *\n * @example\n * const embedding = v.vector(); // Any length\n * const embedding3d = v.vector(3); // Exactly 3 dimensions\n * const optionalVector = v.vector(undefined, { optional: true });\n */\nexport function vector<\n const Opts extends ScalarOptions<number[], any> | undefined = undefined,\n>(\n dimensions?: number,\n options?: Opts\n): VectorSchema<ComputeInput<number[], Opts>, ComputeOutput<number[], Opts>> & {\n dimensions?: number;\n} {\n const baseValidate = createVectorValidator(dimensions);\n return buildSchema(\"vector\", baseValidate, options, {\n dimensions,\n }) as VectorSchema<\n ComputeInput<number[], Opts>,\n ComputeOutput<number[], Opts>\n > & { dimensions?: number };\n}\n\n// Export validator for reuse\nexport { createVectorValidator as validateVector };\n","import type { Cast, ThunkCast, VibSchema } from \"../types\";\nimport { type ObjectOptions, type ObjectSchema, object } from \"./object\";\n\n// =============================================================================\n// Path Utilities for Nested Object Access\n// =============================================================================\n\n/**\n * Gets the value at a dot path in an object type.\n * Supports nested paths like \"create.name\" or \"create.friends\".\n */\ntype PathValue<T, P extends string> = P extends `${infer Key}.${infer Rest}`\n ? Key extends keyof T\n ? T[Key] extends Record<string, any>\n ? PathValue<T[Key], Rest>\n : never\n : never\n : P extends keyof T\n ? T[P]\n : never;\n\n/**\n * Recursively extracts all dot paths that lead to VibSchema or ThunkCast instances.\n * Returns a union of all valid paths (e.g., \"create\" | \"create.name\").\n * Limited to 5 levels of nesting to avoid infinite recursion.\n */\ntype PathsToSchemas<\n T extends string,\n Prefix extends string = \"\",\n Depth extends readonly unknown[] = [],\n> = Depth[\"length\"] extends 5\n ? never\n : // Check if T is a VibSchema\n T extends VibSchema<any, any>\n ? Prefix\n : // Check if T is a ThunkCast (function returning Cast)\n T extends ThunkCast<any, any>\n ? Prefix\n : T extends () => Cast<any, any>\n ? Prefix\n : // Otherwise recurse into object properties\n T extends Record<string, any>\n ? {\n [K in keyof T]: K extends string\n ? PathsToSchemas<\n T[K],\n Prefix extends \"\" ? K : `${Prefix}.${K}`,\n [...Depth, unknown]\n >\n : never;\n }[keyof T]\n : never;\n\n/**\n * Normalize a schema entry to VibSchema.\n * Handles both direct VibSchema and ThunkCast (unwrapping the thunk's return type).\n */\ntype NormalizeSchemaEntry<T> =\n T extends VibSchema<infer I, infer O>\n ? VibSchema<I, O>\n : T extends ThunkCast<infer I, infer O>\n ? VibSchema<I, O>\n : T extends () => Cast<infer I, infer O>\n ? VibSchema<I, O>\n : never;\n\n/**\n * Gets the schema type at a specific path for a specific key.\n * Handles both VibSchema and ThunkCast entries.\n */\ntype SchemaAtPath<\n TObject extends Record<string, any>,\n TPath extends string,\n K extends keyof TObject,\n> = NormalizeSchemaEntry<PathValue<TObject[K], TPath>>;\n\n/**\n * Extracts all valid paths that lead to schemas from all keys in the object.\n */\nexport type AllPathsToSchemas<TObject extends Record<string, any>> = {\n [K in keyof TObject]: K extends string ? PathsToSchemas<TObject[K]> : never;\n}[keyof TObject];\n\n// =============================================================================\n// FromObject Schema Types\n// =============================================================================\n\n/**\n * Options for fromObject schemas (same as ObjectOptions).\n */\nexport type FromObjectOptions<T = unknown> = ObjectOptions<T>;\n\n/**\n * Compute the entries type from an object and path.\n */\ntype ComputeEntries<\n TObject extends Record<string, any>,\n TPath extends string,\n> = {\n [K in keyof TObject]: SchemaAtPath<TObject, TPath, K>;\n};\n\n/**\n * FromObject schema type (alias for ObjectSchema with computed entries).\n */\nexport type FromObjectSchema<\n TEntries,\n TOpts extends FromObjectOptions | undefined = undefined,\n TInput = unknown,\n TOutput = unknown,\n> = ObjectSchema<TEntries, TOpts>;\n\n// =============================================================================\n// FromObject Schema Implementation\n// =============================================================================\n\n/**\n * Runtime helper to get a nested value by dot path.\n */\nfunction getNestedValue(obj: any, path: string): any {\n const parts = path.split(\".\");\n let current = obj;\n for (const part of parts) {\n if (current === null || current === undefined) {\n return undefined;\n }\n current = current[part];\n }\n return current;\n}\n\n/**\n * Extract entries from an object using a dot path.\n */\nfunction extractEntries<TObject extends Record<string, any>>(\n object: TObject,\n path: string\n): Record<string, VibSchema<any, any>> {\n const result: Record<string, VibSchema<any, any>> = {};\n for (const key in object) {\n const value = getNestedValue(object[key], path);\n if (value !== undefined) {\n result[key] = value;\n }\n }\n return result;\n}\n\n/**\n * Creates an object schema by extracting schemas from a record using a dot path.\n * This is a convenient way to build an object schema from a record with proper type inference.\n *\n * @param sourceObject - Source object containing nested schemas\n * @param path - Dot path to extract schemas (e.g., \"create\", \"filter.where\")\n * @param options - Schema options (same as object schema)\n *\n * @example\n * // Given a record of models with nested schemas:\n * const models = {\n * user: { create: v.string(), update: v.string() },\n * post: { create: v.number(), update: v.number() },\n * };\n *\n * // Extract all \"create\" schemas into a single object schema:\n * const createSchema = fromObject(models, \"create\");\n * // Validates: { user: string, post: number }\n *\n * // With options:\n * const optionalSchema = fromObject(models, \"create\", { optional: true });\n * // Validates: { user: string, post: number } | undefined\n *\n * @example\n * // Nested paths work too:\n * const nestedModels = {\n * user: { schemas: { create: v.string() } },\n * post: { schemas: { create: v.number() } },\n * };\n * const nestedSchema = fromObject(nestedModels, \"schemas.create\");\n * // Validates: { user: string, post: number }\n */\nexport function fromObject<\n TObject extends Record<string, any>,\n TPath extends string,\n // TPath extends AllPathsToSchemas<TObject>,\n const TOpts extends FromObjectOptions | undefined = undefined,\n>(\n sourceObject: TObject,\n path: TPath,\n options?: TOpts\n): ObjectSchema<ComputeEntries<TObject, TPath>, TOpts> {\n // Extract entries from the source object at the given path\n const entries = extractEntries(sourceObject, path);\n\n // Delegate to the existing object schema builder\n return object(entries, options) as ObjectSchema<\n ComputeEntries<TObject, TPath>,\n TOpts\n >;\n}\n\nexport type { ComputeEntries as ComputeEntriesFromObject };\n","import { createSchema, fail, ok, validateSchema } from \"../helpers\";\nimport type { InferInput, InferOutput, VibSchema } from \"../types\";\n\n// =============================================================================\n// Pipe Schema\n// =============================================================================\n\n/**\n * Transform action interface.\n */\nexport interface TransformAction<TIn, TOut> {\n readonly type: \"transform\";\n readonly transform: (value: TIn) => TOut;\n}\n\n/**\n * Create a transform action for use with pipe.\n *\n * @example\n * const upperCase = v.pipe(v.string(), v.transform(s => s.toUpperCase()));\n */\nexport function transform<TIn, TOut>(\n fn: (value: TIn) => TOut\n): TransformAction<TIn, TOut> {\n return {\n type: \"transform\",\n transform: fn,\n };\n}\n\n/**\n * Pipe action types.\n */\nexport type PipeAction<TIn, TOut> = TransformAction<TIn, TOut>;\n\n/**\n * Pipe schema interface.\n */\nexport interface PipeSchema<\n TSchema extends VibSchema<any, any>,\n TActions extends readonly PipeAction<any, any>[],\n TInput = InferInput<TSchema>,\n TOutput = TActions extends readonly [...any[], PipeAction<any, infer TLast>]\n ? TLast\n : InferOutput<TSchema>,\n> extends VibSchema<TInput, TOutput> {\n readonly type: \"pipe\";\n readonly schema: TSchema;\n readonly actions: TActions;\n}\n\n/**\n * Infer the final output type from a chain of actions.\n */\ntype InferPipeOutput<\n TSchema extends VibSchema<any, any>,\n TActions extends readonly PipeAction<any, any>[],\n> = TActions extends readonly []\n ? InferOutput<TSchema>\n : TActions extends readonly [PipeAction<any, infer TOut>]\n ? TOut\n : TActions extends readonly [PipeAction<any, infer TMid>, ...infer TRest]\n ? TRest extends readonly PipeAction<any, any>[]\n ? InferPipeOutput<VibSchema<TMid, TMid>, TRest>\n : TMid\n : InferOutput<TSchema>;\n\n/**\n * Create a pipe schema that chains a base schema with transform actions.\n *\n * @example\n * const trimmedString = v.pipe(v.string(), v.transform(s => s.trim()));\n * const isoDate = v.pipe(v.date(), v.transform(d => d.toISOString()));\n */\nexport function pipe<\n TSchema extends VibSchema<any, any>,\n const TActions extends readonly PipeAction<any, any>[],\n>(\n schema: TSchema,\n ...actions: TActions\n): PipeSchema<\n TSchema,\n TActions,\n InferInput<TSchema>,\n InferPipeOutput<TSchema, TActions>\n> {\n const pipeSchema = createSchema<\n InferInput<TSchema>,\n InferPipeOutput<TSchema, TActions>\n >(\"pipe\", (value) => {\n const result = validateSchema(schema, value);\n if (result.issues) {\n return result as any;\n }\n\n let current: unknown = (result as { value: unknown }).value;\n for (const action of actions) {\n if (action.type === \"transform\") {\n try {\n current = action.transform(current);\n } catch (e) {\n return fail(\n `Transform failed: ${e instanceof Error ? e.message : String(e)}`\n );\n }\n }\n }\n\n return ok(current as InferPipeOutput<TSchema, TActions>);\n }) as PipeSchema<\n TSchema,\n TActions,\n InferInput<TSchema>,\n InferPipeOutput<TSchema, TActions>\n >;\n\n (pipeSchema as any).schema = schema;\n (pipeSchema as any).actions = actions;\n\n return pipeSchema;\n}\n","import { createSchema, fail, ok, validateSchema } from \"../helpers\";\nimport type {\n Cast,\n InferInput,\n InferOutput,\n ThunkCast,\n VibSchema,\n} from \"../types\";\nimport { type ObjectOptions, type ObjectSchema, object } from \"./object\";\n\n// =============================================================================\n// Record Schema (dynamic keys)\n// =============================================================================\n\nexport interface RecordSchema<\n TKey extends VibSchema<string, string>,\n TValue extends VibSchema<any, any>,\n TInput = Record<InferInput<TKey>, InferInput<TValue>>,\n TOutput = Record<InferOutput<TKey>, InferOutput<TValue>>,\n> extends VibSchema<TInput, TOutput> {\n readonly type: \"record\";\n readonly key: TKey;\n readonly value: TValue;\n}\n\n/**\n * Create a record schema that validates keys and values.\n *\n * @example\n * const stringRecord = v.record(v.string(), v.number());\n * // Validates: { foo: 1, bar: 2 }\n */\nexport function record<\n TKey extends VibSchema<string, string>,\n TValue extends VibSchema<any, any>,\n>(key: TKey, value: TValue): RecordSchema<TKey, TValue> {\n const schema = createSchema<\n Record<InferInput<TKey>, InferInput<TValue>>,\n Record<InferOutput<TKey>, InferOutput<TValue>>\n >(\"record\", (input) => {\n if (!input || typeof input !== \"object\" || Array.isArray(input)) {\n return fail(\n `Expected object, received ${\n Array.isArray(input) ? \"array\" : typeof input\n }`\n );\n }\n\n const output: Record<string, unknown> = {};\n\n for (const [k, v] of Object.entries(input as Record<string, unknown>)) {\n const keyResult = validateSchema(key, k);\n if (keyResult.issues) {\n return fail(`Invalid key \"${k}\": ${keyResult.issues[0]!.message}`, [k]);\n }\n\n const valueResult = validateSchema(value, v);\n if (valueResult.issues) {\n const issue = valueResult.issues[0]!;\n // Use concat instead of spread for better performance\n const newPath = issue.path\n ? ([k] as PropertyKey[]).concat(issue.path)\n : [k];\n return fail(issue.message, newPath);\n }\n\n output[(keyResult as { value: string }).value] = (\n valueResult as { value: unknown }\n ).value;\n }\n\n return ok(output as Record<InferOutput<TKey>, InferOutput<TValue>>);\n }) as RecordSchema<TKey, TValue>;\n\n (schema as any).key = key;\n (schema as any).value = value;\n\n return schema;\n}\n\n// =============================================================================\n// FromKeys Schema (static keys with same value schema)\n// =============================================================================\n\n/**\n * Schema entry type - VibSchema or ThunkCast for circular references.\n */\ntype SchemaEntry =\n | VibSchema<any, any>\n | ThunkCast<any, any>\n | (() => Cast<any, any>);\n\n/**\n * Normalize a schema entry to VibSchema for type extraction.\n */\ntype NormalizeEntry<T> =\n T extends VibSchema<infer I, infer O>\n ? VibSchema<I, O>\n : T extends ThunkCast<infer I, infer O>\n ? VibSchema<I, O>\n : T extends () => Cast<infer I, infer O>\n ? VibSchema<I, O>\n : never;\n\n/**\n * Compute entries from a tuple of keys and a schema.\n */\nexport type ComputeEntriesFromKeys<\n TKeys extends readonly string[],\n TSchema extends SchemaEntry,\n> = {\n [K in TKeys[number]]: NormalizeEntry<TSchema>;\n};\n\n/**\n * Options for fromKeys (same as ObjectOptions).\n */\nexport type FromKeysOptions<T = unknown> = ObjectOptions<T>;\n\n/**\n * Creates an object schema from an array of keys, all mapping to the same schema.\n * This is a convenient wrapper around `object()` for creating uniform schemas.\n *\n * @param keys - Array of key names (use `as const` for type inference)\n * @param schema - Schema to use for all keys (can be a thunk for circular refs)\n * @param options - Schema options (same as object schema)\n *\n * @example\n * // All keys have the same string schema\n * const schema = v.fromKeys([\"name\", \"email\", \"bio\"] as const, v.string());\n * // → ObjectSchema<{ name: string, email: string, bio: string }>\n *\n * @example\n * // With options\n * const optionalSchema = v.fromKeys(\n * [\"user\", \"post\"] as const,\n * v.number(),\n * { partial: false }\n * );\n * // → ObjectSchema<{ user: number, post: number }> (all required)\n *\n * @example\n * // With thunks for circular references\n * const nodeSchema: VibSchema<any, any> = v.object({ value: v.string() });\n * const schema = v.fromKeys(\n * [\"left\", \"right\"] as const,\n * () => nodeSchema,\n * { optional: true }\n * );\n */\nexport function fromKeys<\n const TKeys extends readonly string[],\n TSchema extends SchemaEntry,\n const TOpts extends FromKeysOptions | undefined = undefined,\n>(\n keys: TKeys,\n schema: TSchema,\n options?: TOpts\n): ObjectSchema<ComputeEntriesFromKeys<TKeys, TSchema>, TOpts> {\n // Build entries object from keys\n const entries: Record<string, SchemaEntry> = {};\n for (const key of keys) {\n entries[key] = schema;\n }\n\n // Delegate to the existing object schema builder\n return object(entries, options) as ObjectSchema<\n ComputeEntriesFromKeys<TKeys, TSchema>,\n TOpts\n >;\n}\n","import { createSchema, fail, ok, validateSchema } from \"../helpers\";\nimport type {\n InferInput,\n InferOutput,\n ValidationResult,\n VibSchema,\n} from \"../types\";\n\n// =============================================================================\n// Transform Schema Wrapper\n// =============================================================================\n\n/**\n * Schema that wraps another schema and transforms its output.\n */\nexport interface TransformSchema<TInput, TOutput>\n extends VibSchema<TInput, TOutput> {\n readonly type: \"transform\";\n}\n\n/**\n * Wrap a schema with a transform function.\n * Validates with the wrapped schema, then applies the transform to the output.\n *\n * @param schema - The base schema to validate with\n * @param fn - Transform function: (validatedValue) => newValue\n *\n * @example\n * // String to uppercase\n * const upper = v.coerce(v.string(), s => s.toUpperCase());\n *\n * @example\n * // Parse string to number\n * const parseNum = v.coerce(v.string(), s => parseInt(s, 10));\n * type Out = InferOutput<typeof parseNum>; // number\n *\n * @example\n * // Date to ISO string\n * const isoDate = v.coerce(v.date(), d => d.toISOString());\n * type Out = InferOutput<typeof isoDate>; // string\n *\n * @example\n * // Extract property from object\n * const getName = v.coerce(\n * v.object({ name: v.string(), age: v.number() }),\n * obj => obj.name\n * );\n * type Out = InferOutput<typeof getName>; // string\n */\nexport function coerce<S extends VibSchema<any, any>, TOut>(\n schema: S,\n fn: (value: S[\" vibInferred\"][\"1\"]) => TOut\n): TransformSchema<InferInput<S>, TOut> & { wrapped: S } {\n const transformSchema = createSchema<InferInput<S>, TOut>(\n \"transform\",\n (value): ValidationResult<TOut> => {\n const result = validateSchema(schema, value);\n if (result.issues) {\n return fail(result.issues[0]?.message ?? \"Validation failed\");\n }\n try {\n return ok(fn((result as { value: InferOutput<S> }).value));\n } catch (e) {\n return fail(\n `Transform failed: ${e instanceof Error ? e.message : String(e)}`\n );\n }\n }\n ) as TransformSchema<InferInput<S>, TOut> & { wrapped: S };\n\n (transformSchema as any).wrapped = schema;\n\n return transformSchema;\n}\n\n/**\n * Alias for coerce - transform wrapper.\n */\nexport const map = coerce;\n","import type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport { inferred } from \"./inferred\";\nimport type { JsonSchemaConverter } from \"./json-schema/types\";\n\n// =============================================================================\n// Core Type Utilities\n// =============================================================================\n\n/**\n * Simplify flattens intersection types into a single object type.\n * Forces TypeScript to compute and cache the result once.\n * Non-recursive - use for shallow flattening.\n */\nexport type Simplify<T> = { [K in keyof T]: T[K] } & {};\n\n/**\n * Prettify forces TypeScript to fully evaluate the type.\n * Recursively prettifies nested objects for cleaner type display.\n * Use sparingly - mapped types are expensive!\n */\nexport type Prettify<T> = T extends (...args: any[]) => any\n ? T // Preserve functions as-is\n : T extends object\n ? T extends Date\n ? T\n : { [K in keyof T]: Prettify<T[K]> } & {}\n : T;\n\n// =============================================================================\n// Schema Interfaces (using interface for caching)\n// =============================================================================\n\n/**\n * Cast interface with OPTIONAL [inferred] - for pattern matching.\n * Uses a tuple [Input, Output] to carry both types.\n */\nexport interface Cast<TInput = unknown, TOutput = TInput> {\n [inferred]?: [TInput, TOutput];\n}\n\n/**\n * Thunk returning a Cast - for lazy type resolution in circular references.\n */\nexport type ThunkCast<TInput = unknown, TOutput = TInput> = () => Cast<\n TInput,\n TOutput\n>;\n\n/**\n * Base schema interface implementing StandardSchemaV1 and StandardJSONSchemaV1.\n * All VibORM schemas extend this interface.\n */\nexport interface VibSchema<TInput = unknown, TOutput = TInput>\n extends StandardSchemaV1<TInput, TOutput> {\n /**\n * Branded type carrier for pattern matching.\n * The tuple [Input, Output] allows extracting both types.\n */\n [inferred]: [TInput, TOutput];\n\n /**\n * Schema type identifier for runtime checks.\n */\n readonly type: string;\n\n /**\n * Standard properties extended with JSON Schema converter.\n */\n readonly \"~standard\": StandardSchemaV1<TInput, TOutput>[\"~standard\"] & {\n /**\n * JSON Schema converter methods.\n * Implements StandardJSONSchemaV1 specification.\n */\n readonly jsonSchema: JsonSchemaConverter;\n };\n}\n\n// =============================================================================\n// Options Interfaces (interface for caching)\n// =============================================================================\n\n/**\n * Options for scalar schemas (string, number, boolean, etc.)\n * TSchemaOut allows the `schema` property to influence output type.\n */\nexport interface ScalarOptions<T, TOut = T, TSchemaOut = TOut> {\n optional?: boolean;\n nullable?: boolean;\n array?: boolean;\n default?: any | (() => any) | undefined;\n /** Transform function applied AFTER schema validation */\n transform?: ((value: TSchemaOut) => TOut) | undefined;\n /** Additional StandardSchema for extra validation. Its output flows to transform. */\n schema?: StandardSchemaV1<T, TSchemaOut> | undefined;\n}\n\n/**\n * Options for object schemas.\n */\nexport interface ObjectOptions<T, TOut = T, TSchemaOut = TOut>\n extends ScalarOptions<T, TOut, TSchemaOut> {\n partial?: boolean;\n strict?: boolean;\n}\n\n// =============================================================================\n// Type Inference - Optimized with constrained infer (TS 4.7+)\n// =============================================================================\n\n/**\n * Extract output type from branded [inferred] property.\n * Uses constrained infer for fewer type branches.\n */\nexport type InferOutput<Def> = Def extends { [inferred]?: [any, infer O] }\n ? O\n : Def extends () => { [inferred]?: [any, infer O] }\n ? O\n : unknown;\n\n/**\n * Extract input type from branded [inferred] property.\n */\nexport type InferInput<Def> = Def extends { [inferred]?: [infer I, any] }\n ? I\n : Def extends () => { [inferred]?: [infer I, any] }\n ? I\n : unknown;\n\n/**\n * Infer output shape from object field definitions.\n * Prettify applied once at the end, not per-field.\n */\nexport type InferOutputShape<Defs> = {\n [K in keyof Defs]: InferOutput<Defs[K]>;\n};\n\n/**\n * Infer input shape from object field definitions.\n */\nexport type InferInputShape<Defs> = {\n [K in keyof Defs]: InferInput<Defs[K]>;\n};\n\n// =============================================================================\n// Computed Types - Optimized with lookup pattern\n// =============================================================================\n\n/**\n * Boolean key helper for option lookup.\n */\ntype BoolKey<T, K extends keyof T> = T[K] extends true ? \"t\" : \"f\";\n\n/**\n * Extract the effective input type considering schema.\n * If a schema is provided, use its input type; otherwise use base type.\n */\ntype EffectiveInput<\n T,\n Opts extends ScalarOptions<any, any, any>,\n> = Opts[\"schema\"] extends StandardSchemaV1<infer I, any> ? I : T;\n\n/**\n * Compute input type using lookup pattern (fewer conditionals).\n */\nexport type ComputeInput<\n T,\n Opts extends ScalarOptions<any, any, any> | undefined,\n> = Opts extends ScalarOptions<any, any, any>\n ? ComputeInputLookup<EffectiveInput<T, Opts>, Opts>[`${BoolKey<\n Opts,\n \"array\"\n >}${BoolKey<Opts, \"nullable\">}${BoolKey<Opts, \"optional\">}`]\n : T;\n\ninterface ComputeInputLookup<T, Opts extends ScalarOptions<any, any, any>> {\n ttt: T[] | null | undefined;\n ttf: Opts[\"default\"] extends T | (() => T)\n ? T[] | null | undefined\n : T[] | null;\n tft: T[] | undefined;\n tff: Opts[\"default\"] extends T | (() => T) ? T[] | undefined : T[];\n ftt: T | null | undefined;\n ftf: Opts[\"default\"] extends T | (() => T) ? T | null | undefined : T | null;\n fft: T | undefined;\n fff: Opts[\"default\"] extends T | (() => T) ? T | undefined : T;\n}\n\n/**\n * Extract the effective output type considering schema and transform.\n * Priority: transform > schema > base type\n */\ntype EffectiveOutput<\n T,\n Opts extends ScalarOptions<any, any, any>,\n> = Opts[\"transform\"] extends (v: any) => infer R\n ? R\n : Opts[\"schema\"] extends StandardSchemaV1<any, infer S>\n ? S\n : T;\n\n/**\n * Compute output type using lookup pattern.\n */\nexport type ComputeOutput<\n T,\n Opts extends ScalarOptions<any, any, any> | undefined,\n> = Opts extends ScalarOptions<any, any, any>\n ? ComputeOutputLookup<EffectiveOutput<T, Opts>, Opts>[`${BoolKey<\n Opts,\n \"array\"\n >}${BoolKey<Opts, \"nullable\">}`]\n : T;\n\ninterface ComputeOutputLookup<T, _Opts> {\n tt: T[] | null;\n tf: T[];\n ft: T | null;\n ff: T;\n}\n\n// =============================================================================\n// Validation Result Types (interfaces for caching)\n// =============================================================================\n\nexport interface ValidationIssue {\n readonly message: string;\n readonly path?: readonly PropertyKey[];\n}\n\nexport interface ValidationSuccess<T> {\n readonly value: T;\n readonly issues?: undefined;\n}\n\nexport interface ValidationFailure {\n readonly issues: readonly ValidationIssue[];\n}\n\nexport type ValidationResult<T> = ValidationSuccess<T> | ValidationFailure;\n\nexport function isSuccess<T>(\n result: ValidationResult<T>\n): result is ValidationSuccess<T> {\n return !result.issues;\n}\n\nexport function isFailure<T>(\n result: ValidationResult<T>\n): result is ValidationFailure {\n return !!result.issues;\n}\n\n// =============================================================================\n// Schema Type Guards\n// =============================================================================\n\nexport function isVibSchema(value: unknown): value is VibSchema {\n return (\n typeof value === \"object\" &&\n value !== null &&\n \"~standard\" in value &&\n typeof (value as any)[\"~standard\"] === \"object\"\n );\n}\n","// =============================================================================\n// VibORM Validation Library\n// =============================================================================\n//\n// A minimal, StandardSchema-compliant validation library with:\n// - Recursive type support (thunks for circular references)\n// - Fail-fast validation (throws on first error)\n// - Options-based API (optional, nullable, array, transform, default)\n// - Strict objects by default\n//\n// =============================================================================\n\n// Helpers\nexport {\n buildValidator,\n createSchema,\n fail,\n getDefault,\n ok,\n validateSchema,\n} from \"./helpers\";\nexport type { inferred as inferredType } from \"./inferred\";\n\n// Branded type symbol\nexport { inferred } from \"./inferred\";\n// JSON Schema conversion (StandardJSONSchemaV1)\nexport type {\n JsonSchema as JSONSchemaOutput,\n JsonSchemaConverter,\n JsonSchemaOptions,\n JsonSchemaTarget,\n} from \"./json-schema\";\nexport { createJsonSchemaConverter, toJsonSchema } from \"./json-schema\";\nexport type {\n AllPathsToSchemas,\n // Wrapper types\n ArraySchema,\n BaseBigIntSchema,\n BaseBlobSchema,\n BaseBooleanSchema,\n BaseDateSchema,\n BaseEnumSchema,\n BaseIntegerSchema,\n BaseIsoDateSchema,\n BaseIsoTimeSchema,\n BaseIsoTimestampSchema,\n BaseJsonSchema,\n BaseNumberSchema,\n BasePointSchema,\n BaseStringSchema,\n BaseVectorSchema,\n BigIntSchema,\n // Blob, Vector, Point types\n BlobSchema,\n BooleanSchema,\n // Date types\n DateSchema,\n EnumSchema,\n FromKeysOptions,\n FromObjectOptions,\n FromObjectSchema,\n // Instance type\n InstanceSchema,\n IntegerSchema,\n IsoDateSchema,\n IsoTimeSchema,\n IsoTimestampSchema,\n JsonSchema,\n JsonValue,\n LiteralSchema,\n LiteralValue,\n NonArraySchema,\n // Negative wrapper types\n NonNullableSchema,\n NonOptionalSchema,\n NullableSchema,\n NumberSchema,\n ObjectEntries,\n ObjectOptions,\n // Object types\n ObjectSchema,\n OptionalSchema,\n PipeAction,\n PipeSchema,\n Point,\n PointSchema,\n RecordSchema,\n // Scalar types\n StringSchema,\n TransformAction,\n // Transform wrapper type\n TransformSchema,\n // Composition types\n UnionSchema,\n VectorSchema,\n} from \"./schemas\";\n// All schemas\nexport {\n // Wrappers\n array,\n bigint,\n // Blob, Vector, Point\n blob,\n boolean,\n // Transform wrapper\n coerce,\n // Date & Time\n date,\n element,\n enum_,\n fromKeys,\n fromObject,\n // Instance (Uint8Array, Buffer, etc.)\n instance,\n integer,\n isJsonValue,\n isoDate,\n isoTime,\n isoTimestamp,\n json,\n literal,\n map,\n maybeNullable,\n nonArray,\n // Negative wrappers (narrowing)\n nonNullable,\n nonOptional,\n nullable,\n number,\n // Objects\n object,\n optional,\n pipe,\n point,\n record,\n required,\n // Scalars\n string,\n transformAction,\n // Composition\n union,\n validateBigInt,\n validateBlob,\n validateBoolean,\n validateDate,\n validateInteger,\n validateIsoDate,\n validateIsoTime,\n validateIsoTimestamp,\n validateJson,\n validateNumber,\n validatePoint,\n // Validators (for reuse)\n validateString,\n validateVector,\n vector,\n} from \"./schemas\";\n// Core types\nexport type {\n Cast,\n ComputeInput,\n ComputeOutput,\n InferInput,\n InferInputShape,\n InferOutput,\n InferOutputShape,\n Prettify,\n ScalarOptions,\n ThunkCast,\n ValidationFailure,\n ValidationIssue,\n ValidationResult,\n ValidationSuccess,\n VibSchema,\n} from \"./types\";\nexport { isVibSchema } from \"./types\";\n\n// V Namespace - Type-level schema mirrors for explicit type annotations\nexport type { V } from \"./V\";\n\n// =============================================================================\n// Convenience namespace (v.string(), v.number(), etc.)\n// =============================================================================\n\nimport {\n array as arrayFn,\n bigint as bigintFn,\n blob as blobFn,\n boolean as booleanFn,\n coerce as coerceFn,\n date as dateFn,\n element as elementFn,\n enum_ as enumFn,\n fromKeys as fromKeysFn,\n fromObject as fromObjectFn,\n instance as instanceFn,\n integer as integerFn,\n isoDate as isoDateFn,\n isoTime as isoTimeFn,\n isoTimestamp as isoTimestampFn,\n json as jsonFn,\n literal as literalFn,\n map as mapFn,\n maybeNullable as maybeNullableFn,\n nonArray as nonArrayFn,\n nonNullable as nonNullableFn,\n nonOptional as nonOptionalFn,\n nullable as nullableFn,\n number as numberFn,\n object as objectFn,\n optional as optionalFn,\n pipe as pipeFn,\n point as pointFn,\n record as recordFn,\n required as requiredFn,\n string as stringFn,\n transformAction as transformActionFn,\n union as unionFn,\n vector as vectorFn,\n} from \"./schemas\";\nimport type { VibSchema } from \"./types\";\n\n/**\n * VibORM validation namespace.\n *\n * @example\n * import { v } from \"viborm/validation\";\n *\n * const user = v.object({\n * name: v.string(),\n * age: v.number({ optional: true }),\n * email: v.string(),\n * createdAt: v.date(),\n * });\n *\n * // Circular references use thunks\n * const node = v.object({\n * value: v.string(),\n * parent: () => node, // Thunk for self-reference\n * });\n */\nexport const v = {\n // Scalars\n string: stringFn,\n number: numberFn,\n integer: integerFn,\n boolean: booleanFn,\n bigint: bigintFn,\n literal: literalFn,\n enum: enumFn,\n json: jsonFn,\n // Date & Time\n date: dateFn,\n isoTimestamp: isoTimestampFn,\n isoDate: isoDateFn,\n isoTime: isoTimeFn,\n // Instance\n instance: instanceFn,\n // Blob, Vector, Point\n blob: blobFn,\n vector: vectorFn,\n point: pointFn,\n // Wrappers\n array: arrayFn,\n nullable: nullableFn,\n maybeNullable: maybeNullableFn,\n optional: optionalFn,\n // Negative wrappers (narrowing)\n nonNullable: nonNullableFn,\n nonOptional: nonOptionalFn,\n required: requiredFn,\n nonArray: nonArrayFn,\n element: elementFn,\n // Objects\n object: objectFn,\n fromObject: fromObjectFn,\n // Composition\n union: unionFn,\n pipe: pipeFn,\n transformAction: transformActionFn,\n record: recordFn,\n fromKeys: fromKeysFn,\n // Transform wrappers\n coerce: coerceFn,\n map: mapFn,\n} as const;\n\n// Default export for convenience\nexport default v;\n\nexport const parse = <const S extends VibSchema>(schema: S, value: unknown) => {\n return schema[\"~standard\"].validate(value) as Awaited<\n ReturnType<(typeof schema)[\"~standard\"][\"validate\"]>\n >;\n};\n"],"mappings":"AAeA,MAAM,EAAgB,IAAI,IAAI,CAC5B,QACA,WACA,WACA,cACA,cACA,WACD,CAAC,CAMF,SAAS,EAAe,EAAkB,CACxC,IAAI,EAAU,EACd,KAAO,GAAW,EAAc,IAAI,EAAQ,KAAK,EAE/C,EAAU,EAAQ,MAAQ,EAAQ,QAEpC,OAAO,EAyBT,SAAgB,EACd,EAIA,EACA,EAAU,GACE,CACZ,IAAM,EAAyB,EAAE,CAGjC,GAAI,CAAC,EAAS,CACZ,IAAM,EAAc,EAAQ,aAAa,IAAI,EAAO,CACpD,GAAI,EACF,MAAO,CAAE,KAAM,WAAW,IAAe,CAK7C,IAAM,EAAa,EAAO,KAG1B,OAAQ,EAAR,CAKE,IAAK,SACH,EAAW,KAAO,SAClB,MAEF,IAAK,SACL,IAAK,UACH,EAAW,KAAO,IAAe,UAAY,UAAY,SACzD,MAEF,IAAK,UACH,EAAW,KAAO,UAClB,MAEF,IAAK,SAEH,EAAW,KAAO,UAClB,MAEF,IAAK,UAAW,CACd,IAAM,EAAS,EAAe,MAC1B,EAAQ,SAAW,cAErB,EAAW,KAAO,CAAC,EAAM,CAEzB,EAAW,MAAQ,EAErB,MAGF,IAAK,OAEH,EAAW,KADK,EAAe,OAE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A,MAGJ,OAAO,EAAG,EAAyD,EACnE,CAKF,MAHC,GAAe,IAAM,EACrB,EAAe,MAAQ,EAEjB,EAyET,SAAgB,GAKd,EACA,EACA,EAC6D,CAE7D,IAAM,EAAuC,EAAE,CAC/C,IAAK,IAAM,KAAO,EAChB,EAAQ,GAAO,EAIjB,OAAO,EAAO,EAAS,EAAQ,CCrHjC,SAAgB,EACd,EACA,EACuD,CACvD,IAAM,EAAkB,EACtB,YACC,GAAkC,CACjC,IAAM,EAAS,EAAe,EAAQ,EAAM,CAC5C,GAAI,EAAO,OACT,OAAO,EAAK,EAAO,OAAO,IAAI,SAAW,oBAAoB,CAE/D,GAAI,CACF,OAAO,EAAG,EAAI,EAAqC,MAAM,CAAC,OACnD,EAAG,CACV,OAAO,EACL,qBAAqB,aAAa,MAAQ,EAAE,QAAU,OAAO,EAAE,GAChE,GAGN,CAID,MAFC,GAAwB,QAAU,EAE5B,EAMT,MAAa,GAAM,ECkLnB,SAAgB,GAAY,EAAoC,CAC9D,OACE,OAAO,GAAU,YACjB,GACA,cAAe,GACf,OAAQ,EAAc,cAAiB,SCpB3C,MAAa,EAAI,CAEPC,UACAC,UACCC,WACAC,UACDC,UACCC,UACT,KAAMC,EACAC,OAEAC,OACQC,eACLC,UACAC,UAECC,WAEJC,OACEC,UACDC,SAEAC,SACGC,WACKC,iBACLC,YAEGC,cACAC,cACHC,WACAC,WACDC,UAEDC,SACIC,cAELC,SACDC,OACN,gBAAiBC,GACTC,UACEC,YAEFC,SACHC,OACN,CAGD,IAAA,GAAe,EAEf,MAAa,IAAoC,EAAW,IACnD,EAAO,aAAa,SAAS,EAAM"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import { $ as nonOptional, $t as buildValidator, A as BasePointSchema, At as EnumSchema, B as object, Bt as validateBoolean, C as vector, Cn as JsonSchemaOptions, Ct as isoTimestamp, D as StringSchema, Dt as InstanceSchema, E as BaseStringSchema, Et as validateIsoTimestamp, F as OptionalSchema, Ft as date, G as integer, Gt as BaseBigIntSchema, H as BaseNumberSchema, Ht as BlobSchema, I as optional, It as validateDate, J as validateNumber, Jt as validateBigInt, K as number, Kt as BigIntSchema, L as ObjectEntries, Lt as BaseBooleanSchema, M as PointSchema, Mt as enum_, N as point, Nt as BaseDateSchema, O as string, Ot as instance, P as validatePoint, Pt as DateSchema, Q as NonOptionalSchema, Qt as toJsonSchema, R as ObjectOptions, Rt as BooleanSchema, S as createVectorValidator, Sn as JsonSchemaConverter, St as isoTime, T as union, Tn as inferred, Tt as validateIsoTime, U as IntegerSchema, Ut as blob, V as BaseIntegerSchema, Vt as BaseBlobSchema, W as NumberSchema, Wt as validateBlob, X as maybeNullable, Xt as array, Y as NullableSchema, Yt as ArraySchema, Z as nullable, Zt as createJsonSchemaConverter, _ as FromObjectOptions, _n as ValidationResult, _t as BaseIsoTimestampSchema, a as coerce, an as Cast, at as nonArray, b as BaseVectorSchema, bn as isVibSchema, bt as IsoTimestampSchema, c as RecordSchema, cn as InferInput, ct as literal, d as PipeAction, dn as InferOutputShape, dt as JsonValue, en as createSchema, et as required, f as PipeSchema, fn as Prettify, ft as isJsonValue, g as AllPathsToSchemas, gn as ValidationIssue, gt as BaseIsoTimeSchema, h as transform, hn as ValidationFailure, ht as BaseIsoDateSchema, i as TransformSchema, in as validateSchema, it as element, j as Point, k as validateString, kt as BaseEnumSchema, l as fromKeys, ln as InferInputShape, lt as BaseJsonSchema, m as pipe, mn as ThunkCast, mt as validateJson, n as v, nn as getDefault, nt as nonNullable, o as map, on as ComputeInput, ot as LiteralSchema, p as TransformAction, pn as ScalarOptions, pt as json, q as validateInteger, qt as bigint, r as V, rn as ok, rt as NonArraySchema, s as FromKeysOptions, sn as ComputeOutput, st as LiteralValue, t as parse, tn as fail, tt as NonNullableSchema, u as record, un as InferOutput, ut as JsonSchema$1, v as FromObjectSchema, vn as ValidationSuccess, vt as IsoDateSchema, w as UnionSchema, wn as JsonSchemaTarget, wt as validateIsoDate, x as VectorSchema, xn as JsonSchema, xt as isoDate, y as fromObject, yn as VibSchema, yt as IsoTimeSchema, z as ObjectSchema, zt as boolean } from "./index-3sdVKfeG.mjs";
|
|
2
|
+
export { AllPathsToSchemas, ArraySchema, BaseBigIntSchema, BaseBlobSchema, BaseBooleanSchema, BaseDateSchema, BaseEnumSchema, BaseIntegerSchema, BaseIsoDateSchema, BaseIsoTimeSchema, BaseIsoTimestampSchema, BaseJsonSchema, BaseNumberSchema, BasePointSchema, BaseStringSchema, BaseVectorSchema, BigIntSchema, BlobSchema, BooleanSchema, Cast, ComputeInput, ComputeOutput, DateSchema, EnumSchema, FromKeysOptions, FromObjectOptions, FromObjectSchema, InferInput, InferInputShape, InferOutput, InferOutputShape, InstanceSchema, IntegerSchema, IsoDateSchema, IsoTimeSchema, IsoTimestampSchema, JsonSchema as JSONSchemaOutput, JsonSchema$1 as JsonSchema, JsonSchemaConverter, JsonSchemaOptions, JsonSchemaTarget, JsonValue, LiteralSchema, LiteralValue, NonArraySchema, NonNullableSchema, NonOptionalSchema, NullableSchema, NumberSchema, ObjectEntries, ObjectOptions, ObjectSchema, OptionalSchema, PipeAction, PipeSchema, Point, PointSchema, Prettify, RecordSchema, ScalarOptions, StringSchema, ThunkCast, TransformAction, TransformSchema, UnionSchema, V, ValidationFailure, ValidationIssue, ValidationResult, ValidationSuccess, VectorSchema, VibSchema, array, bigint, blob, boolean, buildValidator, coerce, createJsonSchemaConverter, createSchema, date, v as default, v, element, enum_, fail, fromKeys, fromObject, getDefault, inferred, inferred as inferredType, instance, integer, isJsonValue, isVibSchema, isoDate, isoTime, isoTimestamp, json, literal, map, maybeNullable, nonArray, nonNullable, nonOptional, nullable, number, object, ok, optional, parse, pipe, point, record, required, string, toJsonSchema, transform as transformAction, union, validateBigInt, validateBlob, validateBoolean, validateDate, validateInteger, validateIsoDate, validateIsoTime, validateIsoTimestamp, validateJson, validateNumber, validatePoint, validateSchema, validateString, createVectorValidator as validateVector, vector };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{$ as e,A as t,B as n,C as r,D as i,E as a,F as o,G as s,H as c,I as l,J as u,K as d,L as f,M as p,N as m,O as h,P as g,Q as _,R as v,S as y,T as b,U as x,V as S,W as C,X as w,Y as T,Z as E,_ as D,a as O,at as k,b as A,c as j,d as M,et as N,f as P,g as F,h as I,i as L,it as R,j as z,k as B,l as V,m as H,n as U,nt as W,o as G,ot as K,p as q,q as J,r as Y,rt as X,s as Z,st as Q,t as $,tt as ee,u as te,v as ne,w as re,x as ie,y as ae,z as oe}from"./validation-RtU-wu4N.mjs";export{_ as array,w as bigint,u as blob,d as boolean,N as buildValidator,O as coerce,K as createJsonSchemaConverter,ee as createSchema,C as date,Y as default,t as element,x as enum_,W as fail,Z as fromKeys,M as fromObject,X as getDefault,e as inferred,c as instance,ie as integer,m as isJsonValue,L as isVibSchema,l as isoDate,f as isoTime,v as isoTimestamp,g as json,p as literal,G as map,b as maybeNullable,z as nonArray,B as nonNullable,i as nonOptional,a as nullable,y as number,A as object,R as ok,ae as optional,$ as parse,V as pipe,D as point,j as record,h as required,I as string,Q as toJsonSchema,te as transformAction,H as union,U as v,E as validateBigInt,T as validateBlob,J as validateBoolean,s as validateDate,r as validateInteger,oe as validateIsoDate,n as validateIsoTime,S as validateIsoTimestamp,o as validateJson,re as validateNumber,ne as validatePoint,k as validateSchema,F as validateString,P as validateVector,q as vector};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
function e(e){return Object.entries(e[`~`].state.scalars)}function t(t,n,r){let i=[];for(let[t,n]of e(r))if(n[`~`].state.type!==`enum`)continue;return i}const n=[t];function r(e){return Object.entries(e[`~`].state.relations)}function i(e,t){return e[`~`].state.scalars[t]}function a(e,t,n){let i=[],a=new Set(Object.keys(n[`~`].state.scalars));for(let[e,o]of r(n)){let n=o[`~`].state.fields;if(n)for(let r of n)a.has(r)||i.push({code:`FK001`,message:`FK '${r}' in '${e}' not in '${t}'`,severity:`error`,model:t,relation:e,field:r})}return i}function o(e,t,n,i){let a=[];for(let[o,s]of r(n)){let n=s[`~`].state.references;if(!n)continue;let r=s[`~`].state.getter(),c=_(e,r,i);if(!c)continue;let l=new Set(Object.keys(r[`~`].state.scalars));for(let e of n)l.has(e)||a.push({code:`FK002`,message:`Reference '${e}' not in '${c}'`,severity:`error`,model:t,relation:o,field:e})}return a}function s(e,t,n,a){let o=[];for(let[s,c]of r(n)){let r=c[`~`].state.fields,l=c[`~`].state.references;if(!(r&&l))continue;let u=c[`~`].state.getter(),d=_(e,u,a)??`?`,f=Math.min(r.length,l.length);for(let e=0;e<f;e++){let a=r[e],c=l[e],f=i(n,a),p=i(u,c);if(!(f&&p))continue;let m=f[`~`].state.type,h=p[`~`].state.type;m!==h&&o.push({code:`FK003`,message:`Type mismatch: '${a}' (${m}) → '${c}' (${h}) in ${d}`,severity:`error`,model:t,relation:s})}}return o}function c(e,t,n){let i=[];for(let[e,a]of r(n))a[`~`].state.type===`manyToOne`&&!a[`~`].state.fields&&i.push({code:`FK004`,message:`ManyToOne '${e}' in '${t}' should define .fields()`,severity:`warning`,model:t,relation:e});return i}function l(e,t,n,a){let o=[];for(let[s,c]of r(n)){let n=c[`~`].state.references;if(!n)continue;let r=c[`~`].state.getter(),l=_(e,r,a)??`?`;for(let e of n){let n=i(r,e);if(!n)continue;let a=n[`~`].state;a.isId||a.isUnique||o.push({code:`FK005`,message:`'${e}' in '${l}' should be unique/ID`,severity:`warning`,model:t,relation:s})}}return o}function u(e,t,n){let i=[],a=new Set(Object.keys(n[`~`].state.relations));for(let[e,o]of r(n)){let n=o[`~`].state.fields;if(n)for(let r of n)a.has(r)&&i.push({code:`FK006`,message:`FK '${r}' in '${e}' cannot reference relation`,severity:`error`,model:t,relation:e})}return i}function d(e,t,n){let i=[];for(let[e,a]of r(n)){let n=a[`~`].state.fields,r=a[`~`].state.references;n&&r&&n.length!==r.length&&i.push({code:`FK007`,message:`'${e}': fields(${n.length}) != references(${r.length})`,severity:`error`,model:t,relation:e})}return i}const f=new Set([`cascade`,`setNull`,`restrict`,`noAction`]);function p(e,t,n){let i=[];for(let[e,a]of r(n)){let n=a[`~`].state.onDelete;n&&!f.has(n)&&i.push({code:`RA001`,message:`Invalid onDelete '${n}' in '${e}'`,severity:`error`,model:t,relation:e})}return i}function m(e,t,n){let i=[];for(let[e,a]of r(n)){let n=a[`~`].state.onUpdate;n&&!f.has(n)&&i.push({code:`RA002`,message:`Invalid onUpdate '${n}' in '${e}'`,severity:`error`,model:t,relation:e})}return i}function h(e,t,n){let i=[];for(let[e,a]of r(n))a[`~`].state.onDelete===`cascade`&&!a[`~`].state.optional&&i.push({code:`RA003`,message:`CASCADE on required '${e}' may cause data loss`,severity:`warning`,model:t,relation:e});return i}function g(e,t,n){let a=[];for(let[e,o]of r(n)){let r=o[`~`].state.onDelete,s=o[`~`].state.fields;if(r===`setNull`&&s)for(let r of s){let o=i(n,r);o&&!o[`~`].state.nullable&&a.push({code:`RA004`,message:`SET NULL on '${e}' but '${r}' not nullable`,severity:`error`,model:t,relation:e})}}return a}function _(e,t,n){if(n)return n.modelToName.get(t);for(let[n,r]of e)if(r===t)return n}const ee=[a,o,s,c,l,u,d,p,m,h,g];function v(e){return Object.entries(e[`~`].state.scalars)}const y=new Set(`model.field.relation.index.unique.table.column.key.primary.foreign.constraint.default.null.not.and.or.select.from.where.order.group.by.having.limit.offset.join.inner.left.right.outer.on.as.distinct.all.any.exists.in.between.like.is.true.false.insert.update.delete.create.drop.alter.truncate`.split(`.`)),b=/^[a-zA-Z_][a-zA-Z0-9_]*$/;function x(e,t,n){return Object.keys(n[`~`].state.scalars).length===0?[{code:`M002`,message:`'${t}' must have at least one field`,severity:`error`,model:t}]:[]}function S(e,t,n){let r=0;for(let n of e.keys())n===t&&r++;return r>1?[{code:`M003`,message:`Model name '${t}' is duplicated`,severity:`error`,model:t}]:[]}function C(e,t,n){return b.test(t)?[]:[{code:`M005`,message:`'${t}' is not a valid identifier`,severity:`error`,model:t}]}function w(e,t,n){return y.has(t.toLowerCase())?[{code:`M006`,message:`'${t}' is a reserved word`,severity:`error`,model:t}]:[]}function T(e){let t=e[`~`].state.compoundId;if(!t)return[];let n=Object.keys(t)[0];if(!n)return[];let r=t[n][`~`]?.state?.entries;return r?Object.keys(r):[]}function E(e){let t=e[`~`].state.compoundUniques;return t?Object.entries(t).map(([e,t])=>{let n=t[`~`]?.state?.entries;return{name:e,fields:n?Object.keys(n):[]}}):[]}function D(e,t,n){let r=[],i=0,a=new Map;for(let[e,o]of v(n)){let n=o[`~`].state;b.test(e)||r.push({code:`F001`,message:`Field '${e}' in '${t}' is invalid identifier`,severity:`error`,model:t,field:e}),n.isId&&i++;let s=n.columnName??e;if(a.has(s)||a.set(s,[]),a.get(s).push(e),n.hasDefault&&n.default!==void 0&&typeof n.default!=`function`){let i=o[`~`].schemas.base[`~standard`].validate(n.default);i instanceof Promise||i.issues&&r.push({code:`F004`,message:`Default value for '${e}' in '${t}' doesn't match type`,severity:`error`,model:t,field:e})}n.isId&&n.nullable&&r.push({code:`F006`,message:`ID '${e}' in '${t}' cannot be nullable`,severity:`error`,model:t,field:e}),n.isId&&n.array&&r.push({code:`F007`,message:`ID '${e}' in '${t}' cannot be array`,severity:`error`,model:t,field:e}),n.autoGenerate&&!n.isId&&r.push({code:`F008`,message:`Auto-generate on '${e}' in '${t}' requires .id()`,severity:`warning`,model:t,field:e})}let o=T(n).length>0;i===0&&!o&&r.push({code:`M001`,message:`'${t}' must have an ID field (or use .id() for compound key)`,severity:`error`,model:t}),(i>1||i>0&&o)&&r.push({code:`F002`,message:`'${t}' has conflicting ID definitions (use either single field .id() or model .id())`,severity:`error`,model:t});for(let[e,n]of a)n.length>1&&r.push({code:`F003`,message:`Column '${e}' used by multiple fields in '${t}': ${n.join(`, `)}`,severity:`error`,model:t});return r}function O(e,t,n){let r=[],i=new Set(Object.keys(n[`~`].state.scalars));for(let e of n[`~`].state.indexes)for(let n of e.fields)i.has(n)||r.push({code:`I001`,message:`Index field '${n}' not in '${t}'`,severity:`error`,model:t,field:n});return r}function k(e,t,n){let r=new Map;for(let e of n[`~`].state.indexes)e.options.name&&r.set(e.options.name,(r.get(e.options.name)??0)+1);let i=[];for(let[e,n]of r)n>1&&i.push({code:`I002`,message:`Index name '${e}' duplicated in '${t}'`,severity:`error`,model:t});return i}function A(e,t,n){let r=[],i=new Set(Object.keys(n[`~`].state.scalars)),a=T(n);for(let e of a)i.has(e)||r.push({code:`I003`,message:`Compound ID field '${e}' not in '${t}'`,severity:`error`,model:t,field:e});let o=E(n);for(let e of o)for(let n of e.fields)i.has(n)||r.push({code:`I003`,message:`Compound unique field '${n}' not in '${t}'`,severity:`error`,model:t,field:n});return r}const j=[x,S,C,w,D,O,k,A],M={oneToOne:`oneToOne`,oneToMany:`manyToOne`,manyToOne:`oneToMany`,manyToMany:`manyToMany`},N=/^[a-zA-Z_][a-zA-Z0-9_]*$/;function P(e){return e===`oneToOne`||e===`manyToOne`}function F(e){return F(e)}function I(e){return I(e)}function L(e){return L(e)}function R(e,t,n,r){let i=[];for(let[a,o]of F(n))Q(e,o[`~`].state.getter(),r)||i.push({code:`R006`,message:`'${a}' in '${t}' targets unregistered model`,severity:`error`,model:t,relation:a});return i}function z(e,t,n,r){let i=[];for(let[a,o]of F(n)){let n=o[`~`].state.type,s=o[`~`].state.getter(),c=Q(e,s,r);if(!c)continue;let l=M[n];if(!ne(s,t,e,l,r)){let e;switch(n){case`oneToOne`:e=`R002`;break;case`oneToMany`:e=`R003`;break;case`manyToOne`:e=`R004`;break;case`manyToMany`:e=`R005`;break;default:e=`R002`;break}i.push({code:e,message:`'${a}' (${n}) in '${t}' missing inverse ${l} in '${c}'`,severity:`error`,model:t,relation:a})}}return i}function B(e,t,n,r){let i=new Map;for(let[a,o]of F(n)){let n=Q(e,o[`~`].state.getter(),r);if(!n)continue;let s=`${t}->${n}`;i.has(s)||i.set(s,[]),i.get(s).push(a)}let a=[];for(let[e,n]of i)n.length>1&&a.push({code:`R007`,message:`Multiple relations ${n.join(`, `)} for ${e} - disambiguate with relation names`,severity:`warning`,model:t});return a}function V(e,t,n){let r=new Map;for(let[t,n]of e)for(let[e,i]of F(n)){let n=i[`~`].state.through;if(n){let i=`${t}.${e}`;r.has(n)||r.set(n,[]),r.get(n).push(i)}}let i=[];for(let[e,t]of r)t.length>2&&i.push({code:`JT001`,message:`Junction '${e}' used by: ${t.join(`, `)}`,severity:`error`});return i}function te(e,t,n){let r=[];for(let[e,i]of F(n)){let n=i[`~`].state.A,a=i[`~`].state.B;n&&!N.test(n)&&r.push({code:`JT002`,message:`Junction field A '${n}' in '${e}' invalid`,severity:`error`,model:t,relation:e}),a&&!N.test(a)&&r.push({code:`JT002`,message:`Junction field B '${a}' in '${e}' invalid`,severity:`error`,model:t,relation:e})}return r}function H(e,t,n){let r=[];for(let[e,i]of F(n)){let n=i[`~`].state.A,a=i[`~`].state.B;n&&a&&n===a&&r.push({code:`JT003`,message:`A and B same ('${n}') in '${e}'`,severity:`error`,model:t,relation:e})}return r}function U(e,t,n,r){let i=[];for(let[a,o]of F(n)){if(o[`~`].state.type!==`manyToMany`||Q(e,o[`~`].state.getter(),r)!==t)continue;let n=o[`~`].state.A,s=o[`~`].state.B;n&&s&&n.localeCompare(s)>0&&i.push({code:`JT004`,message:`Self-ref M:N '${a}': A('${n}') should be < B('${s}') alphabetically`,severity:`warning`,model:t,relation:a})}return i}function W(e,t,n){let r=[];for(let[e,i]of F(n))i[`~`].state.through&&i[`~`].state.type!==`manyToMany`&&r.push({code:`JT005`,message:`.through() on '${e}' requires manyToMany`,severity:`error`,model:t,relation:e});return r}function G(e,t,n,r){let i=[];for(let[a,o]of F(n)){if(Q(e,o[`~`].state.getter(),r)!==t)continue;let s=o[`~`].state.type,c=M[s],l=!1;for(let[i,o]of F(n))if(i!==a&&o[`~`].state.type===c&&Q(e,o[`~`].state.getter(),r)===t){l=!0;break}!l&&s!==`manyToMany`&&i.push({code:`SR001`,message:`Self-ref '${a}' needs inverse ${c} in same model`,severity:`error`,model:t,relation:a})}return i}function K(e,t,n,r){let i=[];for(let[a,o]of F(n))Q(e,o[`~`].state.getter(),r)===t&&i.push(a);return i.length>1&&new Set(i).size!==i.length?[{code:`SR002`,message:`Self-ref relations in '${t}' have duplicate names`,severity:`error`,model:t}]:[]}function q(e,t,n){let r=[],i=new Set;for(let e of I(n)){let t=e[`~`].state.fields;if(t)for(let e of t)i.add(e)}for(let[e,a]of L(n))e.endsWith(`Id`)&&!i.has(e)&&!a[`~`].state.isId&&r.push({code:`CM001`,message:`'${e}' in '${t}' looks like FK but no relation uses it`,severity:`warning`,model:t,field:e});return r}function J(e,t,n,r){let i=[];for(let[a,o]of F(n)){if(o[`~`].state.type!==`oneToOne`||!o[`~`].state.fields)continue;let n=o[`~`].state.getter(),s=Q(e,n,r);if(s){for(let o of I(n))if(o[`~`].state.type===`oneToOne`&&Q(e,o[`~`].state.getter(),r)===t&&o[`~`].state.fields){i.push({code:`CM003`,message:`1:1 between '${t}' and '${s}' has FK on both sides`,severity:`warning`,model:t,relation:a});break}}}return i}const Y=/_type$|Type$/;function X(e,t,n){let r=[],i=Object.keys(n[`~`].state.scalars);for(let e of i){if(!(e.endsWith(`_type`)||e.endsWith(`Type`)))continue;let a=e.replace(Y,``),o=i.find(e=>e===`${a}_id`||e===`${a}Id`);if(o){let i=!1;for(let e of I(n))if(e[`~`].state.fields?.includes(o)){i=!0;break}i||r.push({code:`CM004`,message:`'${e}' + '${o}' in '${t}' looks like polymorphic pattern (not type-safe)`,severity:`warning`,model:t,field:e})}}return r}function Z(e,t,n,r){let i=new Map;for(let[t,n]of e){let a=[];for(let t of I(n))if(P(t[`~`].state.type)&&!t[`~`].state.optional){let n=Q(e,t[`~`].state.getter(),r);n&&a.push(n)}i.set(t,a)}let a=new Set,o=new Set,s=[];function c(e,t){if(o.has(e)){let n=t.indexOf(e);return s.push([...t.slice(n),e]),!0}if(a.has(e))return!1;a.add(e),o.add(e),t.push(e);for(let n of i.get(e)??[])c(n,t);return o.delete(e),t.pop(),!1}for(let e of i.keys())a.has(e)||c(e,[]);let l=new Set,u=[];for(let e of s){let t=[...e].sort().join(`->`);l.has(t)||(l.add(t),u.push({code:`CM002`,message:`Circular required relations: ${e.join(` → `)}`,severity:`error`}))}return u}function Q(e,t,n){if(n)return n.modelToName.get(t);for(let[n,r]of e)if(r===t)return n}function ne(e,t,n,r,i){for(let a of I(e))if(Q(n,a[`~`].state.getter(),i)===t&&a[`~`].state.type===r)return!0;return!1}const re=[R,z,B,V,te,H,U,W,G,K,q,J,X,Z],ie=[...j,...re,...ee,...n];function ae(e){let t=new Map,n=new Map;for(let[r,i]of e){t.set(i,r);let e=i[`~`].state.tableName??r;n.has(e)||n.set(e,[]),n.get(e).push(r)}return{schema:e,modelToName:t,tableToModels:n}}var $=class{constructor(){this.schema=new Map}register(e,t){return this.schema.set(e,t),this}registerAll(e){for(let[t,n]of Object.entries(e))this.schema.set(t,n);return this}validate(e=ie){let t=[],n=[],r=ae(this.schema);for(let[e,n]of r.tableToModels)n.length>1&&t.push({code:`M004`,message:`Table name '${e}' used by multiple models: ${n.join(`, `)}`,severity:`error`});for(let[i,a]of this.schema)for(let o of e){let e=o(this.schema,i,a,r);for(let r of e)r.severity===`error`?t.push(r):n.push(r)}return{valid:t.length===0,errors:t,warnings:n}}validateOrThrow(e){let t=this.validate(e);if(!t.valid){let e=t.errors.map(e=>`[${e.code}] ${e.message}`);throw Error(`Schema validation failed:\n${e.join(`
|
|
2
|
+
`)}`)}}};function oe(e,t){return new $().registerAll(e).validate(t)}function se(e,t){new $().registerAll(e).validateOrThrow(t)}export{se as n,oe as t};
|
|
3
|
+
//# sourceMappingURL=validator-DpJsJcd7.mjs.map
|