@vielzeug/spell 1.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 +68 -0
- package/dist/_dev.cjs +2 -0
- package/dist/_dev.cjs.map +1 -0
- package/dist/_dev.d.ts +2 -0
- package/dist/_dev.d.ts.map +1 -0
- package/dist/_dev.js +2 -0
- package/dist/_dev.js.map +1 -0
- package/dist/core.cjs +2 -0
- package/dist/core.cjs.map +1 -0
- package/dist/core.d.ts +108 -0
- package/dist/core.d.ts.map +1 -0
- package/dist/core.js +2 -0
- package/dist/core.js.map +1 -0
- package/dist/errors.cjs +3 -0
- package/dist/errors.cjs.map +1 -0
- package/dist/errors.d.ts +53 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +3 -0
- package/dist/errors.js.map +1 -0
- package/dist/formats.cjs +2 -0
- package/dist/formats.cjs.map +1 -0
- package/dist/formats.d.ts +41 -0
- package/dist/formats.d.ts.map +1 -0
- package/dist/formats.js +2 -0
- package/dist/formats.js.map +1 -0
- package/dist/index.cjs +1 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +1 -0
- package/dist/json-schema.cjs +2 -0
- package/dist/json-schema.cjs.map +1 -0
- package/dist/json-schema.d.ts +15 -0
- package/dist/json-schema.d.ts.map +1 -0
- package/dist/json-schema.js +2 -0
- package/dist/json-schema.js.map +1 -0
- package/dist/messages.cjs +2 -0
- package/dist/messages.cjs.map +1 -0
- package/dist/messages.d.ts +228 -0
- package/dist/messages.d.ts.map +1 -0
- package/dist/messages.js +2 -0
- package/dist/messages.js.map +1 -0
- package/dist/s.cjs +2 -0
- package/dist/s.cjs.map +1 -0
- package/dist/s.d.ts +65 -0
- package/dist/s.d.ts.map +1 -0
- package/dist/s.js +2 -0
- package/dist/s.js.map +1 -0
- package/dist/safe-object.cjs +2 -0
- package/dist/safe-object.cjs.map +1 -0
- package/dist/safe-object.d.ts +6 -0
- package/dist/safe-object.d.ts.map +1 -0
- package/dist/safe-object.js +2 -0
- package/dist/safe-object.js.map +1 -0
- package/dist/schemas/array.cjs +2 -0
- package/dist/schemas/array.cjs.map +1 -0
- package/dist/schemas/array.d.ts +49 -0
- package/dist/schemas/array.d.ts.map +1 -0
- package/dist/schemas/array.js +2 -0
- package/dist/schemas/array.js.map +1 -0
- package/dist/schemas/bigint.cjs +2 -0
- package/dist/schemas/bigint.cjs.map +1 -0
- package/dist/schemas/bigint.d.ts +42 -0
- package/dist/schemas/bigint.d.ts.map +1 -0
- package/dist/schemas/bigint.js +2 -0
- package/dist/schemas/bigint.js.map +1 -0
- package/dist/schemas/boolean.cjs +2 -0
- package/dist/schemas/boolean.cjs.map +1 -0
- package/dist/schemas/boolean.d.ts +18 -0
- package/dist/schemas/boolean.d.ts.map +1 -0
- package/dist/schemas/boolean.js +2 -0
- package/dist/schemas/boolean.js.map +1 -0
- package/dist/schemas/date.cjs +2 -0
- package/dist/schemas/date.cjs.map +1 -0
- package/dist/schemas/date.d.ts +25 -0
- package/dist/schemas/date.d.ts.map +1 -0
- package/dist/schemas/date.js +2 -0
- package/dist/schemas/date.js.map +1 -0
- package/dist/schemas/enum.cjs +2 -0
- package/dist/schemas/enum.cjs.map +1 -0
- package/dist/schemas/enum.d.ts +14 -0
- package/dist/schemas/enum.d.ts.map +1 -0
- package/dist/schemas/enum.js +2 -0
- package/dist/schemas/enum.js.map +1 -0
- package/dist/schemas/instanceof.cjs +2 -0
- package/dist/schemas/instanceof.cjs.map +1 -0
- package/dist/schemas/instanceof.d.ts +11 -0
- package/dist/schemas/instanceof.d.ts.map +1 -0
- package/dist/schemas/instanceof.js +2 -0
- package/dist/schemas/instanceof.js.map +1 -0
- package/dist/schemas/intersect.cjs +2 -0
- package/dist/schemas/intersect.cjs.map +1 -0
- package/dist/schemas/intersect.d.ts +16 -0
- package/dist/schemas/intersect.d.ts.map +1 -0
- package/dist/schemas/intersect.js +2 -0
- package/dist/schemas/intersect.js.map +1 -0
- package/dist/schemas/lazy.cjs +2 -0
- package/dist/schemas/lazy.cjs.map +1 -0
- package/dist/schemas/lazy.d.ts +16 -0
- package/dist/schemas/lazy.d.ts.map +1 -0
- package/dist/schemas/lazy.js +2 -0
- package/dist/schemas/lazy.js.map +1 -0
- package/dist/schemas/literal.cjs +2 -0
- package/dist/schemas/literal.cjs.map +1 -0
- package/dist/schemas/literal.d.ts +11 -0
- package/dist/schemas/literal.d.ts.map +1 -0
- package/dist/schemas/literal.js +2 -0
- package/dist/schemas/literal.js.map +1 -0
- package/dist/schemas/map.cjs +2 -0
- package/dist/schemas/map.cjs.map +1 -0
- package/dist/schemas/map.d.ts +29 -0
- package/dist/schemas/map.d.ts.map +1 -0
- package/dist/schemas/map.js +2 -0
- package/dist/schemas/map.js.map +1 -0
- package/dist/schemas/never.cjs +2 -0
- package/dist/schemas/never.cjs.map +1 -0
- package/dist/schemas/never.d.ts +10 -0
- package/dist/schemas/never.d.ts.map +1 -0
- package/dist/schemas/never.js +2 -0
- package/dist/schemas/never.js.map +1 -0
- package/dist/schemas/number.cjs +2 -0
- package/dist/schemas/number.cjs.map +1 -0
- package/dist/schemas/number.d.ts +50 -0
- package/dist/schemas/number.d.ts.map +1 -0
- package/dist/schemas/number.js +2 -0
- package/dist/schemas/number.js.map +1 -0
- package/dist/schemas/object.cjs +2 -0
- package/dist/schemas/object.cjs.map +1 -0
- package/dist/schemas/object.d.ts +95 -0
- package/dist/schemas/object.d.ts.map +1 -0
- package/dist/schemas/object.js +2 -0
- package/dist/schemas/object.js.map +1 -0
- package/dist/schemas/pipe.d.ts +2 -0
- package/dist/schemas/pipe.d.ts.map +1 -0
- package/dist/schemas/raw-or.cjs +2 -0
- package/dist/schemas/raw-or.cjs.map +1 -0
- package/dist/schemas/raw-or.d.ts +17 -0
- package/dist/schemas/raw-or.d.ts.map +1 -0
- package/dist/schemas/raw-or.js +2 -0
- package/dist/schemas/raw-or.js.map +1 -0
- package/dist/schemas/record.cjs +2 -0
- package/dist/schemas/record.cjs.map +1 -0
- package/dist/schemas/record.d.ts +16 -0
- package/dist/schemas/record.d.ts.map +1 -0
- package/dist/schemas/record.js +2 -0
- package/dist/schemas/record.js.map +1 -0
- package/dist/schemas/set.cjs +2 -0
- package/dist/schemas/set.cjs.map +1 -0
- package/dist/schemas/set.d.ts +28 -0
- package/dist/schemas/set.d.ts.map +1 -0
- package/dist/schemas/set.js +2 -0
- package/dist/schemas/set.js.map +1 -0
- package/dist/schemas/string.cjs +2 -0
- package/dist/schemas/string.cjs.map +1 -0
- package/dist/schemas/string.d.ts +155 -0
- package/dist/schemas/string.d.ts.map +1 -0
- package/dist/schemas/string.js +2 -0
- package/dist/schemas/string.js.map +1 -0
- package/dist/schemas/tuple.cjs +2 -0
- package/dist/schemas/tuple.cjs.map +1 -0
- package/dist/schemas/tuple.d.ts +22 -0
- package/dist/schemas/tuple.d.ts.map +1 -0
- package/dist/schemas/tuple.js +2 -0
- package/dist/schemas/tuple.js.map +1 -0
- package/dist/schemas/union.cjs +2 -0
- package/dist/schemas/union.cjs.map +1 -0
- package/dist/schemas/union.d.ts +13 -0
- package/dist/schemas/union.d.ts.map +1 -0
- package/dist/schemas/union.js +2 -0
- package/dist/schemas/union.js.map +1 -0
- package/dist/schemas/variant.cjs +2 -0
- package/dist/schemas/variant.cjs.map +1 -0
- package/dist/schemas/variant.d.ts +26 -0
- package/dist/schemas/variant.d.ts.map +1 -0
- package/dist/schemas/variant.js +2 -0
- package/dist/schemas/variant.js.map +1 -0
- package/dist/spell.cjs +3 -0
- package/dist/spell.cjs.map +1 -0
- package/dist/spell.iife.js +3 -0
- package/dist/spell.iife.js.map +1 -0
- package/dist/spell.js +3 -0
- package/dist/spell.js.map +1 -0
- package/dist/types.cjs +2 -0
- package/dist/types.cjs.map +1 -0
- package/dist/types.d.ts +326 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +2 -0
- package/dist/types.js.map +1 -0
- package/dist/validators.cjs +2 -0
- package/dist/validators.cjs.map +1 -0
- package/dist/validators.d.ts +20 -0
- package/dist/validators.d.ts.map +1 -0
- package/dist/validators.js +2 -0
- package/dist/validators.js.map +1 -0
- package/package.json +43 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"tuple.js","names":[],"sources":["../../src/schemas/tuple.ts"],"sourcesContent":["import type { AnySchema, Issue, ParseContext, ParseValue, SchemaDescriptor } from '../core';\n\nimport { ErrorCode, prependIssuePath, Schema, SpellValidationError, _makeCtx } from '../core';\nimport { _messages } from '../messages';\n\nexport type TupleSchemas = readonly [AnySchema, ...AnySchema[]];\nexport type InferTuple<T extends TupleSchemas, R extends AnySchema | null = null> =\n R extends Schema<infer O>\n ? readonly [...{ [K in keyof T]: T[K] extends Schema<infer V> ? V : never }, ...O[]]\n : { readonly [K in keyof T]: T[K] extends Schema<infer V> ? V : never };\n\nexport class TupleSchema<T extends TupleSchemas, R extends AnySchema | null = null> extends Schema<InferTuple<T, R>> {\n readonly items: T;\n readonly restSchema: R;\n\n protected override get _kind(): string {\n return 'tuple';\n }\n\n constructor(items: T, restSchema: R = null as R) {\n super();\n this.items = items;\n this.restSchema = restSchema;\n }\n\n rest<U>(schema: Schema<U>): TupleSchema<T, Schema<U>> {\n return this._copyStateTo(new TupleSchema(this.items, schema));\n }\n\n private _guardTupleInput(\n value: unknown[],\n ctx: ParseContext,\n ): { ok: true; value: unknown[] } | { issues: Issue[]; ok: false } {\n if (this.restSchema === null && value.length !== this.items.length) {\n return {\n issues: [\n {\n code: ErrorCode.invalid_length,\n message: ctx.messages.tuple.length({ exact: this.items.length }),\n params: { exact: this.items.length },\n path: [],\n },\n ],\n ok: false,\n };\n }\n\n if (this.restSchema !== null && value.length < this.items.length) {\n return {\n issues: [\n {\n code: ErrorCode.too_small,\n message: ctx.messages.tuple.min({ min: this.items.length }),\n params: { min: this.items.length },\n path: [],\n },\n ],\n ok: false,\n };\n }\n\n return { ok: true, value };\n }\n\n protected override _parse(value: unknown, ctx: ParseContext): ParseValue {\n if (!Array.isArray(value)) {\n return {\n data: value,\n issues: [{ code: ErrorCode.invalid_type, message: ctx.messages.tuple.type(), path: [] }],\n typeOk: false,\n };\n }\n\n const guarded = this._guardTupleInput(value, ctx);\n\n if (!guarded.ok) return { data: value, issues: guarded.issues, typeOk: false };\n\n const issues: Issue[] = [];\n const output: unknown[] = [];\n const tupleValue = guarded.value;\n\n for (let i = 0; i < this.items.length; i++) {\n const result = this.items[i]._parseFullSync(tupleValue[i], ctx);\n\n if (result.issues.length === 0) {\n output.push(result.data);\n } else {\n issues.push(...prependIssuePath(result.issues, i));\n output.push(tupleValue[i]);\n }\n }\n\n if (this.restSchema !== null) {\n for (let i = this.items.length; i < tupleValue.length; i++) {\n const result = this.restSchema._parseFullSync(tupleValue[i], ctx);\n\n if (result.issues.length === 0) {\n output.push(result.data);\n } else {\n issues.push(...prependIssuePath(result.issues, i));\n output.push(tupleValue[i]);\n }\n }\n }\n\n return { data: output, issues, typeOk: true };\n }\n\n override async parseAsync(value: unknown, ctx?: ParseContext): Promise<InferTuple<T, R>> {\n const c = ctx ?? _makeCtx();\n\n return this._withCatchAsync(async () => {\n const prepared = this._prepareInput(value);\n\n if (prepared.skip) return prepared.value as unknown as InferTuple<T, R>;\n\n const raw = prepared.value;\n\n if (!Array.isArray(raw)) {\n throw new SpellValidationError([{ code: ErrorCode.invalid_type, message: c.messages.tuple.type(), path: [] }]);\n }\n\n const guarded = this._guardTupleInput(raw, c);\n\n if (!guarded.ok) throw new SpellValidationError(guarded.issues);\n\n const tupleValue = guarded.value;\n const issues: Issue[] = [];\n const output: unknown[] = [];\n\n const fixedResults = await Promise.all(this.items.map((schema, i) => schema._parseFullAsync(tupleValue[i], c)));\n\n for (let i = 0; i < fixedResults.length; i++) {\n const result = fixedResults[i];\n\n if (result.issues.length === 0) {\n output.push(result.data);\n } else {\n issues.push(...prependIssuePath(result.issues, i));\n output.push(tupleValue[i]);\n }\n }\n\n const rest = this.restSchema;\n\n if (rest !== null) {\n const restItems = tupleValue.slice(this.items.length);\n const restResults = await Promise.all(restItems.map((item) => rest._parseFullAsync(item, c)));\n\n for (let i = 0; i < restResults.length; i++) {\n const result = restResults[i];\n const idx = this.items.length + i;\n\n if (result.issues.length === 0) {\n output.push(result.data);\n } else {\n issues.push(...prependIssuePath(result.issues, idx));\n output.push(tupleValue[idx]);\n }\n }\n }\n\n const validationIssues = await this._runValidatorsAsync(output, c);\n const allIssues = [...issues, ...validationIssues];\n\n if (allIssues.length > 0) throw new SpellValidationError(allIssues);\n\n return this._runPostprocessors(output) as InferTuple<T, R>;\n });\n }\n\n protected override _toDescriptorImpl(): SchemaDescriptor {\n return {\n ...this._describeBase(),\n items: this.items.map((s) => s.toDescriptor()),\n kind: 'tuple',\n rest: this.restSchema !== null ? this.restSchema.toDescriptor() : null,\n };\n }\n\n protected override _walk<R>(visitor: import('../core').SchemaWalker<R>): R | null {\n const items = this.items.map((s) => s.walk(visitor));\n const rest = this.restSchema !== null ? this.restSchema.walk(visitor) : null;\n\n if (visitor.tuple) return visitor.tuple(this, items, rest);\n\n return super._walk(visitor);\n }\n\n protected override _equalsImpl(other: import('../core').AnySchema): boolean {\n if (!(other instanceof TupleSchema)) return false;\n\n if (this.items.length !== other.items.length) return false;\n\n for (let i = 0; i < this.items.length; i++) {\n if (!this.items[i].equals(other.items[i])) return false;\n }\n\n const rs = this.restSchema;\n const ors = other.restSchema;\n\n if ((rs === null) !== (ors === null)) return false;\n\n if (rs !== null && ors !== null && !rs.equals(ors)) return false;\n\n return true;\n }\n}\n"],"mappings":"2LAWA,IAAa,EAAb,MAAa,UAA+E,CAAyB,CACnH,MACA,WAEA,IAAuB,OAAgB,CACrC,MAAO,OACT,CAEA,YAAY,EAAU,EAAgB,KAAW,CAC/C,MAAM,EACN,KAAK,MAAQ,EACb,KAAK,WAAa,CACpB,CAEA,KAAQ,EAA8C,CACpD,OAAO,KAAK,aAAa,IAAI,EAAY,KAAK,MAAO,CAAM,CAAC,CAC9D,CAEA,iBACE,EACA,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OAAQ,IACrC,GAAI,CAAC,KAAK,MAAM,EAAE,CAAC,OAAO,EAAM,MAAM,EAAE,EAAG,MAAO,GAGpD,IAAM,EAAK,KAAK,WACV,EAAM,EAAM,WAMlB,MAFA,EAFK,IAAO,OAAW,IAAQ,OAE3B,IAAO,MAAQ,IAAQ,MAAQ,CAAC,EAAG,OAAO,CAAG,EAGnD,CACF"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const e=require("../types.cjs"),t=require("../errors.cjs"),n=require("../core.cjs");var r=class r extends n.Schema{schemas;get _kind(){return`union`}constructor(e){super(),this.schemas=e}_parse(t,n){let r=[];for(let e of this.schemas){let i=e._parseFullSync(t,n);if(i.issues.length===0)return{data:i.data,issues:[],typeOk:!0};r.push(i.issues)}return{data:t,issues:[{code:e.ErrorCode.invalid_union,message:n.messages.union.invalid(),params:{errors:r},path:[]}],typeOk:!1}}async parseAsync(r,i){let a=i??n._makeCtx();return this._withCatchAsync(async()=>{let n=this._prepareInput(r);if(n.skip)return n.value;let i=n.value;try{let e=await Promise.any(this.schemas.map(e=>e.safeParseAsync(i,a).then(e=>{if(e.success)return e.data;throw e.error}))),n=await this._runValidatorsAsync(e,a);if(n.length)throw new t.SpellValidationError(n);return this._runPostprocessors(e)}catch(n){if(n instanceof AggregateError){let r=n.errors,i=r.find(e=>!t.SpellValidationError.is(e));if(i!==void 0)throw i;let o=r.map(e=>e.issues);throw new t.SpellValidationError([{code:e.ErrorCode.invalid_union,message:a.messages.union.invalid(),params:{errors:o},path:[]}])}throw n}})}_toDescriptorImpl(){return{...this._describeBase(),branches:this.schemas.map(e=>e.toDescriptor()),kind:`union`}}_walk(e){let t=this.schemas.map(t=>t.walk(e));return e.union?e.union(this,t):super._walk(e)}_equalsImpl(e){return!(e instanceof r)||this.schemas.length!==e.schemas.length?!1:this.schemas.every((t,n)=>t.equals(e.schemas[n]))}};exports.UnionSchema=r;
|
|
2
|
+
//# sourceMappingURL=union.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"union.cjs","names":[],"sources":["../../src/schemas/union.ts"],"sourcesContent":["import type { AnySchema, InferOutput, Issue, ParseContext, ParseValue, SchemaDescriptor } from '../core';\n\nimport { ErrorCode, Schema, SpellValidationError, _makeCtx } from '../core';\n\nexport class UnionSchema<T extends readonly AnySchema[]> extends Schema<InferOutput<T[number]>> {\n readonly schemas: T;\n\n protected override get _kind(): string {\n return 'union';\n }\n\n constructor(schemas: T) {\n super();\n this.schemas = schemas;\n }\n\n protected override _parse(value: unknown, ctx: ParseContext): ParseValue | Promise<ParseValue> {\n const branchErrors: Issue[][] = [];\n\n for (const schema of this.schemas) {\n const result = schema._parseFullSync(value, ctx);\n\n if (result.issues.length === 0) return { data: result.data, issues: [], typeOk: true };\n\n branchErrors.push(result.issues);\n }\n\n return {\n data: value,\n issues: [\n {\n code: ErrorCode.invalid_union,\n message: ctx.messages.union.invalid(),\n params: { errors: branchErrors },\n path: [],\n },\n ],\n typeOk: false,\n };\n }\n\n override async parseAsync(value: unknown, ctx?: ParseContext): Promise<InferOutput<T[number]>> {\n const c = ctx ?? _makeCtx();\n\n return this._withCatchAsync(async () => {\n const prepared = this._prepareInput(value);\n\n if (prepared.skip) return prepared.value as InferOutput<T[number]>;\n\n const v = prepared.value;\n\n try {\n const data = await Promise.any(\n this.schemas.map((schema) =>\n schema.safeParseAsync(v, c).then((result) => {\n if (result.success) return result.data;\n\n throw result.error;\n }),\n ),\n );\n\n const validationIssues = await this._runValidatorsAsync(data, c);\n\n if (validationIssues.length) throw new SpellValidationError(validationIssues);\n\n return this._runPostprocessors(data) as InferOutput<T[number]>;\n } catch (err) {\n if (err instanceof AggregateError) {\n const errors = err.errors as unknown[];\n const nonValidation = errors.find((e) => !SpellValidationError.is(e));\n\n if (nonValidation !== undefined) throw nonValidation;\n\n const branchErrors = (errors as SpellValidationError[]).map((e) => e.issues);\n\n throw new SpellValidationError([\n {\n code: ErrorCode.invalid_union,\n message: c.messages.union.invalid(),\n params: { errors: branchErrors },\n path: [],\n },\n ]);\n }\n\n throw err;\n }\n });\n }\n\n protected override _toDescriptorImpl(): SchemaDescriptor {\n return { ...this._describeBase(), branches: this.schemas.map((s) => s.toDescriptor()), kind: 'union' };\n }\n\n protected override _walk<R>(visitor: import('../core').SchemaWalker<R>): R | null {\n const branches = this.schemas.map((s) => s.walk(visitor));\n\n if (visitor.union) return visitor.union(this, branches);\n\n return super._walk(visitor);\n }\n\n protected override _equalsImpl(other: import('../core').AnySchema): boolean {\n if (!(other instanceof UnionSchema)) return false;\n\n if (this.schemas.length !== other.schemas.length) return false;\n\n return this.schemas.every((s, i) => s.equals(other.schemas[i]));\n }\n}\n"],"mappings":"oFAIA,IAAa,EAAb,MAAa,UAAoD,EAAA,MAA+B,CAC9F,QAEA,IAAuB,OAAgB,CACrC,MAAO,OACT,CAEA,YAAY,EAAY,CACtB,MAAM,EACN,KAAK,QAAU,CACjB,CAEA,OAA0B,EAAgB,EAAqD,CAC7F,IAAM,EAA0B,CAAC,EAEjC,IAAK,IAAM,KAAU,KAAK,QAAS,CACjC,IAAM,EAAS,EAAO,eAAe,EAAO,CAAG,EAE/C,GAAI,EAAO,OAAO,SAAW,EAAG,MAAO,CAAE,KAAM,EAAO,KAAM,OAAQ,CAAC,EAAG,OAAQ,EAAK,EAErF,EAAa,KAAK,EAAO,MAAM,CACjC,CAEA,MAAO,CACL,KAAM,EACN,OAAQ,CACN,CACE,KAAM,EAAA,UAAU,cAChB,QAAS,EAAI,SAAS,MAAM,QAAQ,EACpC,OAAQ,CAAE,OAAQ,CAAa,EAC/B,KAAM,CAAC,CACT,CACF,EACA,OAAQ,EACV,CACF,CAEA,MAAe,WAAW,EAAgB,EAAqD,CAC7F,IAAM,EAAI,GAAO,EAAA,SAAS,EAE1B,OAAO,KAAK,gBAAgB,SAAY,CACtC,IAAM,EAAW,KAAK,cAAc,CAAK,EAEzC,GAAI,EAAS,KAAM,OAAO,EAAS,MAEnC,IAAM,EAAI,EAAS,MAE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,CAAC,CAChE,CACF"}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { AnySchema, InferOutput, ParseContext, ParseValue, SchemaDescriptor } from '../core';
|
|
2
|
+
import { Schema } from '../core';
|
|
3
|
+
export declare class UnionSchema<T extends readonly AnySchema[]> extends Schema<InferOutput<T[number]>> {
|
|
4
|
+
readonly schemas: T;
|
|
5
|
+
protected get _kind(): string;
|
|
6
|
+
constructor(schemas: T);
|
|
7
|
+
protected _parse(value: unknown, ctx: ParseContext): ParseValue | Promise<ParseValue>;
|
|
8
|
+
parseAsync(value: unknown, ctx?: ParseContext): Promise<InferOutput<T[number]>>;
|
|
9
|
+
protected _toDescriptorImpl(): SchemaDescriptor;
|
|
10
|
+
protected _walk<R>(visitor: import('../core').SchemaWalker<R>): R | null;
|
|
11
|
+
protected _equalsImpl(other: import('../core').AnySchema): boolean;
|
|
12
|
+
}
|
|
13
|
+
//# sourceMappingURL=union.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"union.d.ts","sourceRoot":"","sources":["../../src/schemas/union.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,WAAW,EAAS,YAAY,EAAE,UAAU,EAAE,gBAAgB,EAAE,MAAM,SAAS,CAAC;AAEzG,OAAO,EAAa,MAAM,EAAkC,MAAM,SAAS,CAAC;AAE5E,qBAAa,WAAW,CAAC,CAAC,SAAS,SAAS,SAAS,EAAE,CAAE,SAAQ,MAAM,CAAC,WAAW,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC;IAC7F,QAAQ,CAAC,OAAO,EAAE,CAAC,CAAC;IAEpB,cAAuB,KAAK,IAAI,MAAM,CAErC;gBAEW,OAAO,EAAE,CAAC;cAKH,MAAM,CAAC,KAAK,EAAE,OAAO,EAAE,GAAG,EAAE,YAAY,GAAG,UAAU,GAAG,OAAO,CAAC,UAAU,CAAC;IAyB/E,UAAU,CAAC,KAAK,EAAE,OAAO,EAAE,GAAG,CAAC,EAAE,YAAY,GAAG,OAAO,CAAC,WAAW,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC;cAkD3E,iBAAiB,IAAI,gBAAgB;cAIrC,KAAK,CAAC,CAAC,EAAE,OAAO,EAAE,OAAO,SAAS,EAAE,YAAY,CAAC,CAAC,CAAC,GAAG,CAAC,GAAG,IAAI;cAQ9D,WAAW,CAAC,KAAK,EAAE,OAAO,SAAS,EAAE,SAAS,GAAG,OAAO;CAO5E"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{ErrorCode as e}from"../types.js";import{SpellValidationError as t}from"../errors.js";import{Schema as n,_makeCtx as r}from"../core.js";var i=class i extends n{schemas;get _kind(){return`union`}constructor(e){super(),this.schemas=e}_parse(t,n){let r=[];for(let e of this.schemas){let i=e._parseFullSync(t,n);if(i.issues.length===0)return{data:i.data,issues:[],typeOk:!0};r.push(i.issues)}return{data:t,issues:[{code:e.invalid_union,message:n.messages.union.invalid(),params:{errors:r},path:[]}],typeOk:!1}}async parseAsync(n,i){let a=i??r();return this._withCatchAsync(async()=>{let r=this._prepareInput(n);if(r.skip)return r.value;let i=r.value;try{let e=await Promise.any(this.schemas.map(e=>e.safeParseAsync(i,a).then(e=>{if(e.success)return e.data;throw e.error}))),n=await this._runValidatorsAsync(e,a);if(n.length)throw new t(n);return this._runPostprocessors(e)}catch(n){if(n instanceof AggregateError){let r=n.errors,i=r.find(e=>!t.is(e));if(i!==void 0)throw i;let o=r.map(e=>e.issues);throw new t([{code:e.invalid_union,message:a.messages.union.invalid(),params:{errors:o},path:[]}])}throw n}})}_toDescriptorImpl(){return{...this._describeBase(),branches:this.schemas.map(e=>e.toDescriptor()),kind:`union`}}_walk(e){let t=this.schemas.map(t=>t.walk(e));return e.union?e.union(this,t):super._walk(e)}_equalsImpl(e){return!(e instanceof i)||this.schemas.length!==e.schemas.length?!1:this.schemas.every((t,n)=>t.equals(e.schemas[n]))}};export{i as UnionSchema};
|
|
2
|
+
//# sourceMappingURL=union.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"union.js","names":[],"sources":["../../src/schemas/union.ts"],"sourcesContent":["import type { AnySchema, InferOutput, Issue, ParseContext, ParseValue, SchemaDescriptor } from '../core';\n\nimport { ErrorCode, Schema, SpellValidationError, _makeCtx } from '../core';\n\nexport class UnionSchema<T extends readonly AnySchema[]> extends Schema<InferOutput<T[number]>> {\n readonly schemas: T;\n\n protected override get _kind(): string {\n return 'union';\n }\n\n constructor(schemas: T) {\n super();\n this.schemas = schemas;\n }\n\n protected override _parse(value: unknown, ctx: ParseContext): ParseValue | Promise<ParseValue> {\n const branchErrors: Issue[][] = [];\n\n for (const schema of this.schemas) {\n const result = schema._parseFullSync(value, ctx);\n\n if (result.issues.length === 0) return { data: result.data, issues: [], typeOk: true };\n\n branchErrors.push(result.issues);\n }\n\n return {\n data: value,\n issues: [\n {\n code: ErrorCode.invalid_union,\n message: ctx.messages.union.invalid(),\n params: { errors: branchErrors },\n path: [],\n },\n ],\n typeOk: false,\n };\n }\n\n override async parseAsync(value: unknown, ctx?: ParseContext): Promise<InferOutput<T[number]>> {\n const c = ctx ?? _makeCtx();\n\n return this._withCatchAsync(async () => {\n const prepared = this._prepareInput(value);\n\n if (prepared.skip) return prepared.value as InferOutput<T[number]>;\n\n const v = prepared.value;\n\n try {\n const data = await Promise.any(\n this.schemas.map((schema) =>\n schema.safeParseAsync(v, c).then((result) => {\n if (result.success) return result.data;\n\n throw result.error;\n }),\n ),\n );\n\n const validationIssues = await this._runValidatorsAsync(data, c);\n\n if (validationIssues.length) throw new SpellValidationError(validationIssues);\n\n return this._runPostprocessors(data) as InferOutput<T[number]>;\n } catch (err) {\n if (err instanceof AggregateError) {\n const errors = err.errors as unknown[];\n const nonValidation = errors.find((e) => !SpellValidationError.is(e));\n\n if (nonValidation !== undefined) throw nonValidation;\n\n const branchErrors = (errors as SpellValidationError[]).map((e) => e.issues);\n\n throw new SpellValidationError([\n {\n code: ErrorCode.invalid_union,\n message: c.messages.union.invalid(),\n params: { errors: branchErrors },\n path: [],\n },\n ]);\n }\n\n throw err;\n }\n });\n }\n\n protected override _toDescriptorImpl(): SchemaDescriptor {\n return { ...this._describeBase(), branches: this.schemas.map((s) => s.toDescriptor()), kind: 'union' };\n }\n\n protected override _walk<R>(visitor: import('../core').SchemaWalker<R>): R | null {\n const branches = this.schemas.map((s) => s.walk(visitor));\n\n if (visitor.union) return visitor.union(this, branches);\n\n return super._walk(visitor);\n }\n\n protected override _equalsImpl(other: import('../core').AnySchema): boolean {\n if (!(other instanceof UnionSchema)) return false;\n\n if (this.schemas.length !== other.schemas.length) return false;\n\n return this.schemas.every((s, i) => s.equals(other.schemas[i]));\n }\n}\n"],"mappings":"8IAIA,IAAa,EAAb,MAAa,UAAoD,CAA+B,CAC9F,QAEA,IAAuB,OAAgB,CACrC,MAAO,OACT,CAEA,YAAY,EAAY,CACtB,MAAM,EACN,KAAK,QAAU,CACjB,CAEA,OAA0B,EAAgB,EAAqD,CAC7F,IAAM,EAA0B,CAAC,EAEjC,IAAK,IAAM,KAAU,KAAK,QAAS,CACjC,IAAM,EAAS,EAAO,eAAe,EAAO,CAAG,EAE/C,GAAI,EAAO,OAAO,SAAW,EAAG,MAAO,CAAE,KAAM,EAAO,KAAM,OAAQ,CAAC,EAAG,OAAQ,EAAK,EAErF,EAAa,KAAK,EAAO,MAAM,CACjC,CAEA,MAAO,CACL,KAAM,EACN,OAAQ,CACN,CACE,KAAM,EAAU,cAChB,QAAS,EAAI,SAAS,MAAM,QAAQ,EACpC,OAAQ,CAAE,OAAQ,CAAa,EAC/B,KAAM,CAAC,CACT,CACF,EACA,OAAQ,EACV,CACF,CAEA,MAAe,WAAW,EAAgB,EAAqD,CAC7F,IAAM,EAAI,GAAO,EAAS,EAE1B,OAAO,KAAK,gBAAgB,SAAY,CACtC,IAAM,EAAW,KAAK,cAAc,CAAK,EAEzC,GAAI,EAAS,KAAM,OAAO,EAAS,MAEnC,IA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AChE,CACF"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const e=require("../types.cjs"),t=require("../errors.cjs"),n=require("../safe-object.cjs");require("../messages.cjs");const r=require("../core.cjs"),i=require("./literal.cjs");require("./object.cjs");var a=class a extends r.Schema{_map;_discriminator;get _kind(){return`variant`}constructor(e,n){let r=new Map;for(let[a,o]of Object.entries(n)){let n=new i.LiteralSchema(a),s=o.shape[e];if(s&&!s.equals(n))throw new t.SpellError(`s.variant(): branch "${a}" defines a conflicting discriminator schema for "${e}".`);let c={[e]:n};r.set(a,s?o:o.extend(c))}super(),this._discriminator=e,this._map=r}get discriminator(){return this._discriminator}get variantMap(){return this._map}_resolveVariant(t,n){if(typeof t!=`object`||!t||Array.isArray(t))return{issues:[{code:e.ErrorCode.invalid_type,message:n.messages.variant.type(),path:[]}]};let r=t,i=r[this._discriminator],a=this._map.get(i);if(!a){let t=[...this._map.keys()];return{issues:[{code:e.ErrorCode.invalid_variant,message:n.messages.variant.invalidDiscriminator({discriminator:this._discriminator,expected:t}),params:{discriminator:this._discriminator,expected:t},path:[]}]}}return{matched:a,obj:r}}_parse(e,t){let n=this._resolveVariant(e,t);if(`issues`in n)return{data:e,issues:n.issues,typeOk:!1};let r=n.matched._parseFullSync(e,t);return r.issues.length===0?{data:r.data,issues:[],typeOk:!0}:{data:e,issues:r.issues,typeOk:!0}}_toDescriptorImpl(){let e={};for(let[t,r]of this._map.entries())n.defineOwnProperty(e,t,r.toDescriptor());return{...this._describeBase(),branches:e,discriminator:this._discriminator,kind:`variant`}}_walk(e){let t=n.objectFromEntries([...this._map.entries()].map(([t,n])=>[t,n.walk(e)]));return e.variant?e.variant(this,t):super._walk(e)}_equalsImpl(e){if(!(e instanceof a)||this._discriminator!==e._discriminator||this._map.size!==e._map.size)return!1;for(let[t,n]of this._map){let r=e._map.get(t);if(!r||!n.equals(r))return!1}return!0}};exports.VariantSchema=a;
|
|
2
|
+
//# sourceMappingURL=variant.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"variant.cjs","names":[],"sources":["../../src/schemas/variant.ts"],"sourcesContent":["import type { AnySchema, Issue, ParseContext, ParseValue, SchemaDescriptor } from '../core';\n\nimport { ErrorCode, Schema } from '../core';\nimport { SpellError } from '../errors';\nimport { _messages } from '../messages';\nimport { defineOwnProperty, objectFromEntries } from '../safe-object';\nimport { LiteralSchema } from './literal';\nimport { type InferObject, ObjectSchema, type ObjectShape } from './object';\n\ntype VariantMap = Record<string, ObjectSchema<any>>;\ntype InferVariantMap<K extends string, M extends VariantMap> = {\n [Tag in keyof M & string]: M[Tag] extends ObjectSchema<infer S extends ObjectShape>\n ? InferObject<S> & { [P in K]: Tag }\n : never;\n}[keyof M & string];\n\nexport class VariantSchema<K extends string, M extends VariantMap> extends Schema<InferVariantMap<K, M>> {\n private readonly _map: Map<string, ObjectSchema<any>>;\n private readonly _discriminator: K;\n\n protected override get _kind(): string {\n return 'variant';\n }\n\n constructor(discriminator: K, variantMap: M) {\n const map = new Map<string, ObjectSchema<any>>();\n\n for (const [tag, schema] of Object.entries(variantMap)) {\n const discriminatorSchema = new LiteralSchema(tag);\n const existingDiscriminator = schema.shape[discriminator];\n\n if (existingDiscriminator && !existingDiscriminator.equals(discriminatorSchema)) {\n throw new SpellError(\n `s.variant(): branch \"${tag}\" defines a conflicting discriminator schema for \"${discriminator}\".`,\n );\n }\n\n const discriminatorShape = {\n [discriminator]: discriminatorSchema,\n } as unknown as Record<K, AnySchema>;\n\n map.set(tag, existingDiscriminator ? schema : schema.extend(discriminatorShape));\n }\n\n super();\n this._discriminator = discriminator;\n this._map = map;\n }\n\n /** The discriminator field key used to select the matching variant. */\n get discriminator(): K {\n return this._discriminator;\n }\n\n /** Map from discriminator tag value to the extended ObjectSchema for that variant. */\n get variantMap(): ReadonlyMap<string, ObjectSchema<any>> {\n return this._map;\n }\n\n private _resolveVariant(\n value: unknown,\n ctx: ParseContext,\n ): { matched: ObjectSchema<any>; obj: Record<string, unknown> } | { issues: Issue[] } {\n if (value == null || typeof value !== 'object' || Array.isArray(value)) {\n return {\n issues: [{ code: ErrorCode.invalid_type, message: ctx.messages.variant.type(), path: [] }],\n };\n }\n\n const obj = value as Record<string, unknown>;\n const discValue = obj[this._discriminator] as string;\n const matched = this._map.get(discValue);\n\n if (!matched) {\n const expected = [...this._map.keys()];\n\n return {\n issues: [\n {\n code: ErrorCode.invalid_variant,\n message: ctx.messages.variant.invalidDiscriminator({\n discriminator: this._discriminator,\n expected,\n }),\n params: { discriminator: this._discriminator, expected },\n path: [],\n },\n ],\n };\n }\n\n return { matched, obj };\n }\n\n protected override _parse(value: unknown, ctx: ParseContext): ParseValue {\n const resolved = this._resolveVariant(value, ctx);\n\n if ('issues' in resolved) return { data: value, issues: resolved.issues, typeOk: false };\n\n const result = resolved.matched._parseFullSync(value, ctx);\n\n return result.issues.length === 0\n ? { data: result.data, issues: [], typeOk: true }\n : { data: value, issues: result.issues, typeOk: true };\n }\n\n protected override _toDescriptorImpl(): SchemaDescriptor {\n const branches: Record<string, SchemaDescriptor> = {};\n\n for (const [key, schema] of this._map.entries()) {\n defineOwnProperty(branches, key, schema.toDescriptor());\n }\n\n return { ...this._describeBase(), branches, discriminator: this._discriminator, kind: 'variant' };\n }\n\n protected override _walk<R>(visitor: import('../core').SchemaWalker<R>): R | null {\n const branches = objectFromEntries([...this._map.entries()].map(([k, s]) => [k, s.walk(visitor)]));\n\n if (visitor.variant) return visitor.variant(this, branches);\n\n return super._walk(visitor);\n }\n\n protected override _equalsImpl(other: import('../core').AnySchema): boolean {\n if (!(other instanceof VariantSchema)) return false;\n\n if (this._discriminator !== other._discriminator) return false;\n\n if (this._map.size !== other._map.size) return false;\n\n for (const [tag, schema] of this._map) {\n const otherSchema = other._map.get(tag);\n\n if (!otherSchema || !schema.equals(otherSchema)) return false;\n }\n\n return true;\n }\n}\n"],"mappings":"wMAgBA,IAAa,EAAb,MAAa,UAA8D,EAAA,MAA8B,CACvG,KACA,eAEA,IAAuB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{ type InferObject, ObjectSchema, type ObjectShape } from './object';
|
|
4
|
+
type VariantMap = Record<string, ObjectSchema<any>>;
|
|
5
|
+
type InferVariantMap<K extends string, M extends VariantMap> = {
|
|
6
|
+
[Tag in keyof M & string]: M[Tag] extends ObjectSchema<infer S extends ObjectShape> ? InferObject<S> & {
|
|
7
|
+
[P in K]: Tag;
|
|
8
|
+
} : never;
|
|
9
|
+
}[keyof M & string];
|
|
10
|
+
export declare class VariantSchema<K extends string, M extends VariantMap> extends Schema<InferVariantMap<K, M>> {
|
|
11
|
+
private readonly _map;
|
|
12
|
+
private readonly _discriminator;
|
|
13
|
+
protected get _kind(): string;
|
|
14
|
+
constructor(discriminator: K, variantMap: M);
|
|
15
|
+
/** The discriminator field key used to select the matching variant. */
|
|
16
|
+
get discriminator(): K;
|
|
17
|
+
/** Map from discriminator tag value to the extended ObjectSchema for that variant. */
|
|
18
|
+
get variantMap(): ReadonlyMap<string, ObjectSchema<any>>;
|
|
19
|
+
private _resolveVariant;
|
|
20
|
+
protected _parse(value: unknown, ctx: ParseContext): ParseValue;
|
|
21
|
+
protected _toDescriptorImpl(): SchemaDescriptor;
|
|
22
|
+
protected _walk<R>(visitor: import('../core').SchemaWalker<R>): R | null;
|
|
23
|
+
protected _equalsImpl(other: import('../core').AnySchema): boolean;
|
|
24
|
+
}
|
|
25
|
+
export {};
|
|
26
|
+
//# sourceMappingURL=variant.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"variant.d.ts","sourceRoot":"","sources":["../../src/schemas/variant.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAoB,YAAY,EAAE,UAAU,EAAE,gBAAgB,EAAE,MAAM,SAAS,CAAC;AAE5F,OAAO,EAAa,MAAM,EAAE,MAAM,SAAS,CAAC;AAK5C,OAAO,EAAE,KAAK,WAAW,EAAE,YAAY,EAAE,KAAK,WAAW,EAAE,MAAM,UAAU,CAAC;AAE5E,KAAK,UAAU,GAAG,MAAM,CAAC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"../errors.js";import{defineOwnProperty as n,objectFromEntries as r}from"../safe-object.js";import"../messages.js";import{Schema as i}from"../core.js";import{LiteralSchema as a}from"./literal.js";import"./object.js";var o=class o extends i{_map;_discriminator;get _kind(){return`variant`}constructor(e,n){let r=new Map;for(let[i,o]of Object.entries(n)){let n=new a(i),s=o.shape[e];if(s&&!s.equals(n))throw new t(`s.variant(): branch "${i}" defines a conflicting discriminator schema for "${e}".`);let c={[e]:n};r.set(i,s?o:o.extend(c))}super(),this._discriminator=e,this._map=r}get discriminator(){return this._discriminator}get variantMap(){return this._map}_resolveVariant(t,n){if(typeof t!=`object`||!t||Array.isArray(t))return{issues:[{code:e.invalid_type,message:n.messages.variant.type(),path:[]}]};let r=t,i=r[this._discriminator],a=this._map.get(i);if(!a){let t=[...this._map.keys()];return{issues:[{code:e.invalid_variant,message:n.messages.variant.invalidDiscriminator({discriminator:this._discriminator,expected:t}),params:{discriminator:this._discriminator,expected:t},path:[]}]}}return{matched:a,obj:r}}_parse(e,t){let n=this._resolveVariant(e,t);if(`issues`in n)return{data:e,issues:n.issues,typeOk:!1};let r=n.matched._parseFullSync(e,t);return r.issues.length===0?{data:r.data,issues:[],typeOk:!0}:{data:e,issues:r.issues,typeOk:!0}}_toDescriptorImpl(){let e={};for(let[t,r]of this._map.entries())n(e,t,r.toDescriptor());return{...this._describeBase(),branches:e,discriminator:this._discriminator,kind:`variant`}}_walk(e){let t=r([...this._map.entries()].map(([t,n])=>[t,n.walk(e)]));return e.variant?e.variant(this,t):super._walk(e)}_equalsImpl(e){if(!(e instanceof o)||this._discriminator!==e._discriminator||this._map.size!==e._map.size)return!1;for(let[t,n]of this._map){let r=e._map.get(t);if(!r||!n.equals(r))return!1}return!0}};export{o as VariantSchema};
|
|
2
|
+
//# sourceMappingURL=variant.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"variant.js","names":[],"sources":["../../src/schemas/variant.ts"],"sourcesContent":["import type { AnySchema, Issue, ParseContext, ParseValue, SchemaDescriptor } from '../core';\n\nimport { ErrorCode, Schema } from '../core';\nimport { SpellError } from '../errors';\nimport { _messages } from '../messages';\nimport { defineOwnProperty, objectFromEntries } from '../safe-object';\nimport { LiteralSchema } from './literal';\nimport { type InferObject, ObjectSchema, type ObjectShape } from './object';\n\ntype VariantMap = Record<string, ObjectSchema<any>>;\ntype InferVariantMap<K extends string, M extends VariantMap> = {\n [Tag in keyof M & string]: M[Tag] extends ObjectSchema<infer S extends ObjectShape>\n ? InferObject<S> & { [P in K]: Tag }\n : never;\n}[keyof M & string];\n\nexport class VariantSchema<K extends string, M extends VariantMap> extends Schema<InferVariantMap<K, M>> {\n private readonly _map: Map<string, ObjectSchema<any>>;\n private readonly _discriminator: K;\n\n protected override get _kind(): string {\n return 'variant';\n }\n\n constructor(discriminator: K, variantMap: M) {\n const map = new Map<string, ObjectSchema<any>>();\n\n for (const [tag, schema] of Object.entries(variantMap)) {\n const discriminatorSchema = new LiteralSchema(tag);\n const existingDiscriminator = schema.shape[discriminator];\n\n if (existingDiscriminator && !existingDiscriminator.equals(discriminatorSchema)) {\n throw new SpellError(\n `s.variant(): branch \"${tag}\" defines a conflicting discriminator schema for \"${discriminator}\".`,\n );\n }\n\n const discriminatorShape = {\n [discriminator]: discriminatorSchema,\n } as unknown as Record<K, AnySchema>;\n\n map.set(tag, existingDiscriminator ? schema : schema.extend(discriminatorShape));\n }\n\n super();\n this._discriminator = discriminator;\n this._map = map;\n }\n\n /** The discriminator field key used to select the matching variant. */\n get discriminator(): K {\n return this._discriminator;\n }\n\n /** Map from discriminator tag value to the extended ObjectSchema for that variant. */\n get variantMap(): ReadonlyMap<string, ObjectSchema<any>> {\n return this._map;\n }\n\n private _resolveVariant(\n value: unknown,\n ctx: ParseContext,\n ): { matched: ObjectSchema<any>; obj: Record<string, unknown> } | { issues: Issue[] } {\n if (value == null || typeof value !== 'object' || Array.isArray(value)) {\n return {\n issues: [{ code: ErrorCode.invalid_type, message: ctx.messages.variant.type(), path: [] }],\n };\n }\n\n const obj = value as Record<string, unknown>;\n const discValue = obj[this._discriminator] as string;\n const matched = this._map.get(discValue);\n\n if (!matched) {\n const expected = [...this._map.keys()];\n\n return {\n issues: [\n {\n code: ErrorCode.invalid_variant,\n message: ctx.messages.variant.invalidDiscriminator({\n discriminator: this._discriminator,\n expected,\n }),\n params: { discriminator: this._discriminator, expected },\n path: [],\n },\n ],\n };\n }\n\n return { matched, obj };\n }\n\n protected override _parse(value: unknown, ctx: ParseContext): ParseValue {\n const resolved = this._resolveVariant(value, ctx);\n\n if ('issues' in resolved) return { data: value, issues: resolved.issues, typeOk: false };\n\n const result = resolved.matched._parseFullSync(value, ctx);\n\n return result.issues.length === 0\n ? { data: result.data, issues: [], typeOk: true }\n : { data: value, issues: result.issues, typeOk: true };\n }\n\n protected override _toDescriptorImpl(): SchemaDescriptor {\n const branches: Record<string, SchemaDescriptor> = {};\n\n for (const [key, schema] of this._map.entries()) {\n defineOwnProperty(branches, key, schema.toDescriptor());\n }\n\n return { ...this._describeBase(), branches, discriminator: this._discriminator, kind: 'variant' };\n }\n\n protected override _walk<R>(visitor: import('../core').SchemaWalker<R>): R | null {\n const branches = objectFromEntries([...this._map.entries()].map(([k, s]) => [k, s.walk(visitor)]));\n\n if (visitor.variant) return visitor.variant(this, branches);\n\n return super._walk(visitor);\n }\n\n protected override _equalsImpl(other: import('../core').AnySchema): boolean {\n if (!(other instanceof VariantSchema)) return false;\n\n if (this._discriminator !== other._discriminator) return false;\n\n if (this._map.size !== other._map.size) return false;\n\n for (const [tag, schema] of this._map) {\n const otherSchema = other._map.get(tag);\n\n if (!otherSchema || !schema.equals(otherSchema)) return false;\n }\n\n return true;\n }\n}\n"],"mappings":"2RAgBA,IAAa,EAAb,MAAa,UAA8D,CAA8B,CACvG,KACA,eAEA,IAAuB,OAAgB,CACrC,MAAO,SACT,CAEA,YAAY,EAAkB,EAAe,CAC3C,IAAM,EAAM,IAAI,IAEhB,IAAK,GAAM,CAAC,EAAK,KAAW,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,EAAO,CAAG,EAEzD,OAAO,EAAO,OAAO,SAAW,EAC5B,CAAE,KAAM,EAAO,KAAM,OAAQ,CAAC,EAAG,OAAQ,EAAK,EAC9C,CAAE,KAAM,EAAO,OAAQ,EAAO,OAAQ,OAAQ,EAAK,CACzD,CAEA,mBAAyD,CACvD,IAAM,EAA6C,CAAC,EAEpD,IAAK,GAAM,CAAC,EAAK,KAAW,KAAK,KAAK,QAAQ,EAC5C,EAAkB,EAAU,EAAK,EAAO,aAAa,CAAC,EAGxD,MAAO,CAAE,GAAG,KAAK,cAAc,EAAG,WAAU,cAAe,KAAK,eAAgB,KAAM,SAAU,CAClG,CAEA,MAA4B,EAAsD,CAChF,IAAM,EAAW,EAAkB,CAAC,GAAG,KAAK,KAAK,QAAQ,CAAC,CAAC,CAAC,KAAK,CAAC,EAAG,KAAO,CAAC,EAAG,EAAE,KAAK,CAAO,CAAC,CAAC,CAAC,EAIjG,OAFI,EAAQ,QAAgB,EAAQ,QAAQ,KAAM,CAAQ,EAEnD,MAAM,MAAM,CAAO,CAC5B,CAEA,YAA+B,EAA6C,CAK1E,GAJI,EAAE,aAAiB,IAEnB,KAAK,iBAAmB,EAAM,gBAE9B,KAAK,KAAK,OAAS,EAAM,KAAK,KAAM,MAAO,GAE/C,IAAK,GAAM,CAAC,EAAK,KAAW,KAAK,KAAM,CACrC,IAAM,EAAc,EAAM,KAAK,IAAI,CAAG,EAEtC,GAAI,CAAC,GAAe,CAAC,EAAO,OAAO,CAAW,EAAG,MAAO,EAC1D,CAEA,MAAO,EACT,CACF"}
|
package/dist/spell.cjs
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});let e=require("@vielzeug/arsenal");var t={custom:`custom`,invalid_base64:`invalid_base64`,invalid_date:`invalid_date`,invalid_duration:`invalid_duration`,invalid_enum:`invalid_enum`,invalid_finite:`invalid_finite`,invalid_integer:`invalid_integer`,invalid_keys:`invalid_keys`,invalid_length:`invalid_length`,invalid_literal:`invalid_literal`,invalid_multiple_of:`invalid_multiple_of`,invalid_safe:`invalid_safe`,invalid_string:`invalid_string`,invalid_type:`invalid_type`,invalid_union:`invalid_union`,invalid_unique:`invalid_unique`,invalid_url:`invalid_url`,invalid_variant:`invalid_variant`,too_big:`too_big`,too_small:`too_small`};function n(e,t,n){return[{code:e,message:t,params:n,path:[]}]}function r(e,t){return typeof e==`function`?e(t):e}function i(e,t){return e.map(e=>({...e,path:[t,...e.path]}))}function a(e,...t){let n=e;for(let e of t){if(Array.isArray(n))return[];n=n[String(e)===`_errors`?`_errors_`:String(e)]??{_errors:[]}}return Array.isArray(n)?n:n._errors}var o=class e extends Error{constructor(e,t){super(e,t),this.name=new.target.name,Object.setPrototypeOf(this,new.target.prototype)}static is(t){return t instanceof e}};function s(e){return e.map(({code:e,message:t,path:n})=>`${n.length?n.join(`.`):`value`}: ${t} [${e}]`).join(`
|
|
2
|
+
`)}function c(){let e=Object.create(null);return e._errors=[],e}var l=class e extends o{issues;constructor(e,t){super(s(e),{cause:t}),this.issues=e}static is(t){return t instanceof e}bestMatch(){let e=this.issues.find(e=>e.code===t.invalid_union);if(!e)return null;let n=e.params.errors;if(n.length===0)return null;let r=n.map(e=>({issues:e,score:e.reduce((e,t)=>Math.max(e,t.path.length),0)*1e3-e.length}));return r.sort((e,t)=>t.score-e.score),r[0].issues}flatten(){let e=[],t=[],n=new Map;for(let r of this.issues)if(r.path.length===0)t.push(r.message);else{let t=JSON.stringify(r.path),i=n.get(t);i===void 0?(n.set(t,e.length),e.push({messages:[r.message],path:[...r.path]})):e[i].messages.push(r.message)}return{fieldErrors:e,formErrors:t}}flattenFirst(){let{fieldErrors:e,formErrors:t}=this.flatten();return{fieldErrors:e.map(e=>({message:e.messages[0],path:e.path})),formErrors:t}}format(){let e=c();for(let t of this.issues){if(t.path.length===0){e._errors.push(t.message);continue}let n=e;for(let e of t.path){let t=String(e),r=t===`_errors`?`_errors_`:t;Object.hasOwn(n,r)||(n[r]=c()),n=n[r]}n._errors.push(t.message)}return e}},u=new Set([`__proto__`,`constructor`,`prototype`]);function d(e){return u.has(e)}function f(e,t,n){Object.defineProperty(e,t,{configurable:!0,enumerable:!0,value:n,writable:!0})}function p(e){let t={};for(let[n,r]of e)f(t,n,r);return t}function m(e){return p(Object.entries(e))}function h(e){return g(e.toDescriptor())}function g(e){let t=ee(e),n=t;return e.isNullable&&(n={anyOf:[t,{type:`null`}]}),e.description&&(n={...n,description:e.description}),n}function ee(e){switch(e.kind){case`any`:case`unknown`:return{};case`array`:{let t={items:g(e.items),type:`array`};return e.minItems!==void 0&&(t.minItems=e.minItems),e.maxItems!==void 0&&(t.maxItems=e.maxItems),t}case`bigint`:return{type:`integer`};case`boolean`:return{type:`boolean`};case`date`:return{$comment:`Date objects are not representable in JSON Schema. Validate as a string with a date format in JSON contexts.`};case`enum`:return{enum:[...e.values]};case`instanceof`:return{$comment:`Instances of "${e.className}" are not representable in JSON Schema.`};case`intersect`:return{allOf:e.branches.map(g)};case`lazy`:return{};case`literal`:return e.value===null?{type:`null`}:e.value===void 0?{}:{const:e.value};case`map`:return{$comment:`Map type — represented as an object with arbitrary string keys.`,additionalProperties:g(e.value),type:`object`};case`never`:return{not:{}};case`number`:{let t={type:e.typeHint===`integer`?`integer`:`number`};return e.minimum!==void 0&&(t.minimum=e.minimum),e.maximum!==void 0&&(t.maximum=e.maximum),e.exclusiveMinimum!==void 0&&(t.exclusiveMinimum=e.exclusiveMinimum),e.exclusiveMaximum!==void 0&&(t.exclusiveMaximum=e.exclusiveMaximum),e.multipleOf!==void 0&&(t.multipleOf=e.multipleOf),t}case`object`:{let t={},n=[];for(let[r,i]of Object.entries(e.fields))f(t,r,g(i)),i.isOptional||n.push(r);let r={properties:t,type:`object`};return n.length>0&&(r.required=n),e.strict&&(r.additionalProperties=!1),r}case`pipe`:return g(e.to);case`record`:return{additionalProperties:g(e.value),type:`object`};case`set`:return{$comment:`Set<T> — no standard JSON Schema equivalent; treated as an ordered unique-item array.`,items:g(e.items),type:`array`,uniqueItems:!0};case`string`:{let t={type:`string`};return e.minLength!==void 0&&(t.minLength=e.minLength),e.maxLength!==void 0&&(t.maxLength=e.maxLength),e.pattern!=null&&(t.pattern=e.pattern),e.format!==void 0&&(t.format=e.format),e.contentEncoding!==void 0&&(t.contentEncoding=e.contentEncoding),t}case`tuple`:{let t={prefixItems:e.items.map(g),type:`array`};return e.rest===null?t.items=!1:t.items=g(e.rest),t}case`union`:return{anyOf:e.branches.map(g)};case`variant`:return{discriminator:{propertyName:e.discriminator},oneOf:Object.values(e.branches).map(g)}}}var te=!globalThis.__SPELL_PROD__;function ne(e){te&&console.warn(`[@vielzeug/spell] ${e}`)}var _={array:{length:({exact:e})=>`Must have exactly ${e} items`,max:({max:e})=>`Must have at most ${e} items`,min:({min:e})=>`Must have at least ${e} items`,nonEmpty:()=>`Cannot be empty`,type:()=>`Expected array`,unique:()=>`All items must be unique`},bigint:{max:({max:e})=>`Must be at most ${e}`,min:({min:e})=>`Must be at least ${e}`,multipleOf:({step:e})=>`Must be a multiple of ${e}`,negative:()=>`Must be negative`,nonNegative:()=>`Must be non-negative`,nonPositive:()=>`Must be non-positive`,positive:()=>`Must be positive`,type:()=>`Expected bigint`},boolean:{type:()=>`Expected boolean`},check:{default:()=>`Invalid value`},date:{max:({max:e})=>`Must be before ${e.toISOString()}`,min:({min:e})=>`Must be after ${e.toISOString()}`,type:()=>`Expected valid date`},enum:{invalid:({values:e})=>`Expected one of: ${e.map(e=>JSON.stringify(e)).join(`, `)}`},instanceof:{type:({className:e})=>`Expected instance of ${e}`},literal:{expected:({expected:e})=>`Expected ${JSON.stringify(e)}`},map:{max:({max:e})=>`Must contain at most ${e} entries`,min:({min:e})=>`Must contain at least ${e} entries`,nonEmpty:()=>`Cannot be empty`,size:({exact:e})=>`Must contain exactly ${e} entries`,type:()=>`Expected map`},never:{invalid:()=>`Value is not allowed`},number:{finite:()=>`Must be finite`,int:()=>`Must be an integer`,max:({max:e})=>`Must be at most ${e}`,min:({min:e})=>`Must be at least ${e}`,multipleOf:({step:e})=>`Must be a multiple of ${e}`,negative:()=>`Must be negative`,nonNegative:()=>`Must be non-negative`,nonPositive:()=>`Must be non-positive`,positive:()=>`Must be positive`,safe:()=>`Must be a safe integer`,type:()=>`Expected number`},object:{invalidKeys:({keys:e})=>`Unrecognized keys: ${e.join(`, `)}`,type:()=>`Expected object`},set:{max:({max:e})=>`Must contain at most ${e} items`,min:({min:e})=>`Must contain at least ${e} items`,nonEmpty:()=>`Cannot be empty`,size:({exact:e})=>`Must contain exactly ${e} items`,type:()=>`Expected set`},string:{base64:()=>`Invalid base64`,base64url:()=>`Invalid base64url`,cuid:()=>`Invalid CUID`,cuid2:()=>`Invalid CUID2`,date:()=>`Invalid date`,dateTime:()=>`Invalid datetime`,duration:()=>`Invalid ISO 8601 duration`,email:()=>`Invalid email address`,emoji:()=>`Invalid emoji sequence`,endsWith:({suffix:e})=>`Must end with "${e}"`,hex:()=>`Invalid hex`,hexColor:()=>`Invalid hex color`,includes:({substr:e})=>`Must include "${e}"`,ip:()=>`Invalid IP address`,jwt:()=>`Invalid JWT`,length:({exact:e})=>`Must be exactly ${e} characters`,max:({max:e})=>`Must be at most ${e} characters`,min:({min:e})=>`Must be at least ${e} characters`,nanoid:()=>`Invalid NanoID`,nonEmpty:()=>`Cannot be empty`,numeric:()=>`Invalid numeric string`,regex:()=>`Invalid format`,semver:()=>`Invalid semver`,slug:()=>`Invalid slug`,startsWith:({prefix:e})=>`Must start with "${e}"`,time:()=>`Invalid time`,type:()=>`Expected string`,ulid:()=>`Invalid ULID`,url:()=>`Invalid URL`,uuid:()=>`Invalid UUID`},tuple:{length:({exact:e})=>`Expected tuple of length ${e}`,min:({min:e})=>`Expected tuple with at least ${e} items`,type:()=>`Expected array`},union:{invalid:()=>`Does not match any of the expected types`},variant:{invalidDiscriminator:({discriminator:e,expected:t})=>`Invalid discriminator value at "${e}": expected ${t.map(e=>JSON.stringify(e)).join(` | `)}`,type:()=>`Expected object`}},v=_,y=e=>{ne(e)};function b(e){y(e)}function re(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function ie(e,t){let n=m(e);for(let[e,r]of Object.entries(t)){if(r===void 0)continue;if(d(e)){b(`[spell] Ignoring unsafe message override key "${e}" to prevent prototype mutation.`);continue}let t=n[e];re(t)&&re(r)?f(n,e,ie(t,r)):f(n,e,r)}return n}function ae(e){v=ie(_,e)}function oe(e){y=e??(()=>{})}function se(){v=_}function x(){return v}function S(t){if(typeof t!=`object`||!t)return t;if(Array.isArray(t))return t.map(e=>S(e));if(t instanceof Date)return new Date(t.getTime());if(t instanceof Map){let e=new Map;for(let[n,r]of t.entries())e.set(S(n),S(r));return e}if(t instanceof Set)return new Set([...t.values()].map(e=>S(e)));if((0,e.isPlainObject)(t)){let e={};for(let[n,r]of Object.entries(t))f(e,n,S(r));return e}return t}function ce(){return{isNullable:!1,isOptional:!1,postprocessors:[],preprocessors:[],validators:[]}}function C(e){return{catch:e.catch,defaultValue:e.defaultValue,description:e.description,isNullable:e.isNullable,isOptional:e.isOptional,postprocessors:[...e.postprocessors],preprocessors:[...e.preprocessors],validators:[...e.validators]}}function w(e){return{messages:e??x()}}function T(e,n){let r=[...n];return typeof e==`string`?r.push({code:t.custom,message:e,path:[]}):e===!1&&r.length===0&&r.push({code:t.custom,message:x().check.default(),path:[]}),r.length?r:null}var E=class{state;_annotations={};_typeValidator=null;constructor(e){this.state=ce(),this._typeValidator=e??null}parse(e,n){let r=n??w();return this._withCatch(()=>{let n=this._prepareInput(e);if(n.skip)return n.value;let i=this._parse(n.value,r);if(i instanceof Promise)throw new l([{code:t.custom,message:`parse() received an async schema. Use parseAsync() instead.`,path:[]}]);let a=i,o=a.typeOk?this._runValidatorsSync(a.data,r):[],s=[...a.issues,...o];if(s.length)throw new l(s);return this._runPostprocessors(a.data)})}safeParse(e,t){try{return{data:this.parse(e,t),success:!0}}catch(e){if(l.is(e))return{error:e,success:!1};throw e}}async parseAsync(e,t){let n=t??w();return this._withCatchAsync(async()=>{let t=this._prepareInput(e);if(t.skip)return t.value;let r=await this._parse(t.value,n),i=r.typeOk?await this._runValidatorsAsync(r.data,n):[],a=[...r.issues,...i];if(a.length)throw new l(a);return this._runPostprocessors(r.data)})}async safeParseAsync(e,t){try{return{data:await this.parseAsync(e,t),success:!0}}catch(e){if(l.is(e))return{error:e,success:!1};throw e}}_parseFullSync(e,n){let r=n??w(),i=this._prepareInput(e);if(i.skip)return{data:i.value,issues:[]};let a=this._parse(i.value,r);if(a instanceof Promise)throw new l([{code:t.custom,message:`Sync parse path received an async schema. Use parseAsync() instead.`,path:[]}]);let o=a,s=o.typeOk?this._runValidatorsSync(o.data,r):[],c=[...o.issues,...s];return c.length>0?this.state.catch?{data:this.state.catch(),issues:[]}:{data:o.data,issues:c}:{data:this._runPostprocessors(o.data),issues:[]}}async _parseFullAsync(e,t){let n=t??w(),r=this._prepareInput(e);if(r.skip)return{data:r.value,issues:[]};let i=await this._parse(r.value,n),a=i.typeOk?await this._runValidatorsAsync(i.data,n):[],o=[...i.issues,...a];return o.length>0?this.state.catch?{data:this.state.catch(),issues:[]}:{data:i.data,issues:o}:{data:this._runPostprocessors(i.data),issues:[]}}validate(e){return this._addConstraint((t,n)=>{let r=[],i=e(t,{addIssue:e=>r.push({...e,path:e.path??[]})});return i instanceof Promise?i.then(e=>T(e,r)):T(i,r)})}refine(e,i){return this._addConstraint((a,o)=>{if(e(a))return null;let s=i?r(i,{value:a}):o.messages.check.default();return n(t.custom,s)})}optional(){let e=this._clone();return e.state.isOptional=!0,e}nullable(){let e=this._clone();return e.state.isNullable=!0,e}nullish(){let e=this._clone();return e.state.isOptional=!0,e.state.isNullable=!0,e}required(){let e=this._clone();return e.state.isOptional=!1,e}default(e){let t=this._clone();return t.state.defaultValue=typeof e==`function`?e:()=>S(e),t}catch(e){let t=this._clone();return t.state.catch=typeof e==`function`?e:()=>S(e),t}transform(e){let t=this._clone();return t.state.postprocessors.push(e),t}preprocess(e){let t=this._clone();return t.state.preprocessors.push(e),t}pipe(e){return new D(this,e)}label(e){let t=this._clone();return t.state.description=e,t}toDescriptor(){return this.state.preprocessors.length>0&&b(`toDescriptor(): this schema has preprocessors (e.g. trim(), lowercase(), coerce()). Preprocessors are not serializable and will not appear in the descriptor output.`),this._toDescriptorImpl()}get description(){return this.state.description}get isOptional(){return this.state.isOptional}get isNullable(){return this.state.isNullable}is(e){return this.safeParse(e).success}toJsonSchema(){return h(this)}assert(e,t){let n=this._parseFullSync(e);if(n.issues.length!==0)throw new l(t?n.issues.map(e=>({...e,message:e.path.length===0?`${t}: ${e.message}`:e.message})):n.issues)}walk(e){return this._walk(e)}equals(e){return e===this?!0:Object.getPrototypeOf(e)!==Object.getPrototypeOf(this)||e.isOptional!==this.isOptional||e.isNullable!==this.isNullable||e.description!==this.description?!1:this._equalsImpl(e)}get kind(){return this._kind}get _kind(){return`any`}_describeBase(){return{...this.state.description===void 0?{}:{description:this.state.description},...this.state.isNullable?{isNullable:!0}:{},...this.state.isOptional?{isOptional:!0}:{}}}_annotationsEqual(e){let t=this._annotations,n=e._annotations,r=Object.keys(t),i=Object.keys(n);return r.length===i.length?r.every(e=>t[e]===n[e]):!1}_addConstraint(e,t){let n=this._clone();return n.state.validators.push(e),t&&(n._annotations=t({...n._annotations})),n}_construct(e){let t=Object.assign(Object.create(Object.getPrototypeOf(this)),this,{state:e});return t._annotations={...this._annotations},t}_clone(){return this._construct(C(this.state))}_copyStateTo(e){return e.state=C(this.state),e}_walk(e){return e.unknown?e.unknown(this):null}_toDescriptorImpl(){return{...this._describeBase(),kind:`any`}}_equalsImpl(e){return!0}_withCatch(e){if(!this.state.catch)return e();try{return e()}catch(e){if(l.is(e))return this.state.catch();throw e}}async _withCatchAsync(e){if(!this.state.catch)return e();try{return await e()}catch(e){if(l.is(e))return this.state.catch();throw e}}_prepareInput(e){let t=this._runPreprocessors(e),n=t===void 0&&this.state.defaultValue?this.state.defaultValue():t;return this.state.isOptional&&n===void 0||this.state.isNullable&&n===null?{skip:!0,value:n}:{skip:!1,value:n}}_runPreprocessors(e){let t=e;for(let e of this.state.preprocessors)t=e(t);return t}_runPostprocessors(e){let t=e;for(let e of this.state.postprocessors)t=e(t);return t}_runValidatorsSync(e,n){if(this._typeValidator){let r=this._typeValidator(e,n);if(r instanceof Promise)throw new l([{code:t.custom,message:`Type validator returned a Promise. Use parseAsync() for async validation.`,path:[]}]);if(r&&r.length>0)return r}let r=[];for(let t of this.state.validators){let i=t(e,n);if(i instanceof Promise){b(`An async validate() callback was skipped because parse()/safeParse() cannot await it. The value passed this check unvalidated — use parseAsync()/safeParseAsync() instead.`);continue}i&&r.push(...i)}return r}async _runValidatorsAsync(e,t){if(this._typeValidator){let n=await this._typeValidator(e,t);if(n&&n.length>0)return n}let n=[];for(let r of this.state.validators){let i=await r(e,t);i&&n.push(...i)}return n}_parse(e,t){return{data:e,issues:[],typeOk:!0}}},D=class e extends E{from;to;get _kind(){return`pipe`}constructor(e,t){super(),this.from=e,this.to=t}_parse(e,t){let n=this.from._parseFullSync(e,t);if(n instanceof Promise)return n.then(n=>n.issues.length>0?{data:e,issues:n.issues,typeOk:!1}:this.to._parseFullAsync(n.data,t).then(e=>e.issues.length>0?{data:n.data,issues:e.issues,typeOk:!1}:{data:e.data,issues:[],typeOk:!0}));if(n.issues.length>0)return{data:e,issues:n.issues,typeOk:!1};let r=this.to._parseFullSync(n.data,t);return r instanceof Promise?r.then(e=>e.issues.length>0?{data:n.data,issues:e.issues,typeOk:!1}:{data:e.data,issues:[],typeOk:!0}):r.issues.length>0?{data:n.data,issues:r.issues,typeOk:!1}:{data:r.data,issues:[],typeOk:!0}}_walk(e){let t=this.from.walk(e),n=this.to.walk(e);return e.pipe?e.pipe(this,t,n):super._walk(e)}_toDescriptorImpl(){return{...this._describeBase(),from:this.from.toDescriptor(),kind:`pipe`,to:this.to.toDescriptor()}}_equalsImpl(t){return t instanceof e?this.from.equals(t.from)&&this.to.equals(t.to):!1}},le=(e,t)=>e.length>=t,ue=(e,t)=>e.length<=t,de=(e,t,n)=>e>=t&&e<=n,fe=e=>Number.isInteger(e),pe=e=>e>0,me=e=>e>=0,he=e=>e<0,ge=(e,t)=>e%t===0,_e=e=>typeof e==`string`,ve=e=>typeof e==`number`&&!Number.isNaN(e),ye=e=>typeof e==`boolean`,be=e=>e==null,xe=e=>e instanceof Date&&!Number.isNaN(e.getTime()),Se=e=>Array.isArray(e);function O(e){return/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(e)}var Ce=new Set([`http`,`https`]);function k(e,t){try{let n=new URL(e);return(t?new Set(t.map(e=>e.toLowerCase())):Ce).has(n.protocol.replace(`:`,``).toLowerCase())}catch{return!1}}function A(e){return/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e)}function j(e){if(!/^\d{4}-\d{2}-\d{2}$/.test(e))return!1;let t=new Date(e);return!Number.isNaN(t.getTime())&&t.toISOString().startsWith(e)}function M(e){return/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:Z|[+-]\d{2}:\d{2})?$/.test(e)&&!Number.isNaN(new Date(e).getTime())}function N(e){if(/^(\d{1,3}\.){3}\d{1,3}$/.test(e))return e.split(`.`).every(e=>{let t=parseInt(e,10);return t>=0&&t<=255});try{return new URL(`http://[${e}]/`),!0}catch{return!1}}function P(e){return/^c[a-z0-9]{8,}$/.test(e)}function F(e){return/^[a-z][a-z0-9]{23}$/.test(e)}function I(e){return/^[0-7][0-9A-HJKMNP-TV-Z]{25}$/.test(e)}function L(e,t=21){return e.length===t&&/^[A-Za-z0-9_-]+$/.test(e)}function R(e){return/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{4})$/.test(e)}function we(e){return e.length===0||e.length%4==1?!1:/^[A-Za-z0-9_-]*={0,2}$/.test(e)}function z(e){return/^[A-Fa-f0-9]+$/.test(e)}function B(e){return/^#(?:[A-Fa-f0-9]{3}|[A-Fa-f0-9]{6}|[A-Fa-f0-9]{8})$/.test(e)}function V(e){return/^\p{Extended_Pictographic}+$/u.test(e)}function H(e){return/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(e)}function U(e){return/^(?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d)?$/.test(e)}function W(e){return/^P(?=\d|T\d)(\d+Y)?(\d+M)?(\d+W)?(\d+D)?(T(\d+H)?(\d+M)?(\d+(?:\.\d+)?S)?)?$/.test(e)}function G(e){return/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*)(?:\.(?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*))*))?(?:\+([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?$/.test(e)}function K(e){return/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(e)}function q(e){return/^[-+]?(?:\d+\.?\d*|\.\d+)(?:e[-+]?\d+)?$/i.test(e)}var Te=class e extends E{itemSchema;get _kind(){return`array`}constructor(e){super(),this.itemSchema=e}_parseItemsSync(e,t){let n=[],r=[];for(let a=0;a<e.length;a++){let o=this.itemSchema._parseFullSync(e[a],t);o.issues.length===0?r.push(o.data):(n.push(...i(o.issues,a)),r.push(e[a]))}return{data:r,issues:n}}_parse(e,r){if(!Array.isArray(e))return{data:e,issues:n(t.invalid_type,r.messages.array.type()),typeOk:!1};let{data:i,issues:a}=this._parseItemsSync(e,r);return{data:i,issues:a,typeOk:!0}}async parseAsync(e,r){let a=r??w();return this._withCatchAsync(async()=>{let r=this._prepareInput(e);if(r.skip)return r.value;let o=r.value;if(!Array.isArray(o))throw new l(n(t.invalid_type,a.messages.array.type()));let s=await Promise.all(o.map(e=>this.itemSchema._parseFullAsync(e,a))),c=[],u=[];for(let e=0;e<s.length;e++){let t=s[e];t.issues.length===0?u.push(t.data):(c.push(...i(t.issues,e)),u.push(o[e]))}let d=await this._runValidatorsAsync(u,a),f=[...c,...d];if(f.length>0)throw new l(f);return this._runPostprocessors(u)})}min(e,i=e=>x().array.min(e)){return this._addConstraint((a,o)=>a.length>=e?null:n(t.too_small,r(i,{min:e,value:a}),{min:e}),t=>{let n=t;return{...n,minItems:n.minItems===void 0?e:Math.max(n.minItems,e)}})}max(e,i=e=>x().array.max(e)){return this._addConstraint((a,o)=>a.length<=e?null:n(t.too_big,r(i,{max:e,value:a}),{max:e}),t=>{let n=t;return{...n,maxItems:n.maxItems===void 0?e:Math.min(n.maxItems,e)}})}length(e,i=e=>x().array.length(e)){return this._addConstraint((a,o)=>a.length===e?null:n(t.invalid_length,r(i,{exact:e,value:a}),{exact:e}),t=>({...t,maxItems:e,minItems:e}))}nonEmpty(e=()=>x().array.nonEmpty()){return this.min(1,e)}unique(e,i=()=>x().array.unique()){let a=typeof e==`function`&&e.length===2,o=a?e:null,s=a?i:typeof e==`function`?e:()=>x().array.unique();return this._addConstraint((e,i)=>{let a=e,c;return c=o?a.every((e,t)=>a.slice(0,t).every(t=>!o(e,t))):new Set(a).size===a.length,c?null:n(t.invalid_unique,r(s,{value:a}),{unique:!0})})}_toDescriptorImpl(){let e=this._annotations;return{...this._describeBase(),...e.maxItems===void 0?{}:{maxItems:e.maxItems},...e.minItems===void 0?{}:{minItems:e.minItems},items:this.itemSchema.toDescriptor(),kind:`array`}}_walk(e){let t=this.itemSchema.walk(e);return e.array?e.array(this,t):super._walk(e)}_equalsImpl(t){if(!(t instanceof e))return!1;let n=t,r=this._annotations,i=t._annotations;return this.itemSchema.equals(n.itemSchema)&&r.minItems===i.minItems&&r.maxItems===i.maxItems}},J=class e extends E{get _kind(){return`bigint`}constructor(){super((e,r)=>typeof e==`bigint`?null:n(t.invalid_type,(r?.messages??x()).bigint.type()))}min(e,i=e=>x().bigint.min(e)){return this._addConstraint((a,o)=>{let s=a;return s>=e?null:n(t.too_small,r(i,{min:e,value:s}),{min:e})})}max(e,i=e=>x().bigint.max(e)){return this._addConstraint((a,o)=>{let s=a;return s<=e?null:n(t.too_big,r(i,{max:e,value:s}),{max:e})})}positive(e=()=>x().bigint.positive()){return this._addConstraint((i,a)=>{let o=i;return o>0n?null:n(t.too_small,r(e,{value:o}),{exclusive:!0,min:0n})})}negative(e=()=>x().bigint.negative()){return this._addConstraint((i,a)=>{let o=i;return o<0n?null:n(t.too_big,r(e,{value:o}),{exclusive:!0,max:0n})})}nonNegative(e=()=>x().bigint.nonNegative()){return this._addConstraint((i,a)=>{let o=i;return o>=0n?null:n(t.too_small,r(e,{value:o}),{min:0n})})}nonPositive(e=()=>x().bigint.nonPositive()){return this._addConstraint((i,a)=>{let o=i;return o<=0n?null:n(t.too_big,r(e,{value:o}),{max:0n})})}multipleOf(e,i=e=>x().bigint.multipleOf(e)){return this._addConstraint((a,o)=>{let s=a;return s%e===0n?null:n(t.invalid_multiple_of,r(i,{step:e,value:s}),{step:e})})}_walk(e){return e.bigint?e.bigint(this):super._walk(e)}coerce(){return e.coerce()}_toDescriptorImpl(){return this.state.validators.length>0&&b(`toDescriptor(): this bigint schema has constraints (e.g. min(), max(), positive()). BigInt constraints are not serializable and will not appear in toDescriptor() output.`),{...this._describeBase(),kind:`bigint`}}_equalsImpl(t){return t instanceof e}static coerce(){return new e().preprocess(e=>{if(typeof e==`bigint`)return e;if(typeof e==`number`){if(!Number.isFinite(e)||!Number.isInteger(e))return e;try{return BigInt(e)}catch{return e}}if(typeof e==`string`){let t=e.trim();if(t.length===0||t.length>1e3)return e;try{return BigInt(t)}catch{return e}}return e})}},Y=class e extends E{get _kind(){return`boolean`}constructor(){super((e,n)=>typeof e==`boolean`?null:[{code:t.invalid_type,message:(n?.messages??x()).boolean.type(),path:[]}])}coerce(){return e.coerce()}_toDescriptorImpl(){return{...this._describeBase(),kind:`boolean`}}_walk(e){return e.boolean?e.boolean(this):super._walk(e)}_equalsImpl(t){return t instanceof e}static coerce(){return new e().preprocess(e=>typeof e==`boolean`?e:e===`true`||e===`1`||e===1?!0:e===`false`||e===`0`||e===0?!1:e)}},X=class e extends E{get _kind(){return`date`}constructor(){super((e,r)=>e instanceof Date&&!Number.isNaN(e.getTime())?null:n(t.invalid_date,(r?.messages??x()).date.type()))}min(e,i=e=>x().date.min(e)){return this._addConstraint((a,o)=>{let s=a;return s>=e?null:n(t.too_small,r(i,{min:e,value:s}),{min:e})})}max(e,i=e=>x().date.max(e)){return this._addConstraint((a,o)=>{let s=a;return s<=e?null:n(t.too_big,r(i,{max:e,value:s}),{max:e})})}coerce(){return e.coerce()}_toDescriptorImpl(){return{...this._describeBase(),kind:`date`}}_walk(e){return e.date?e.date(this):super._walk(e)}_equalsImpl(t){return t instanceof e}static coerce(){return new e().preprocess(e=>e instanceof Date?e:typeof e==`string`||typeof e==`number`?new Date(e):e)}};function Ee(e){let n=new Set(e);return(r,i)=>n.has(r)?null:[{code:t.invalid_enum,message:(i?.messages??x()).enum.invalid({values:e}),params:{values:e},path:[]}]}var De=class e extends E{values;get _kind(){return`enum`}constructor(e){super(Ee(e)),this.values=e}_toDescriptorImpl(){return{...this._describeBase(),kind:`enum`,values:this.values}}_walk(e){return e.enum?e.enum(this):super._walk(e)}_equalsImpl(t){return t instanceof e?JSON.stringify(this.values)===JSON.stringify(t.values):!1}},Oe=class e extends E{cls;get _kind(){return`instanceof`}constructor(e){super((n,r)=>n instanceof e?null:[{code:t.invalid_type,message:(r?.messages??x()).instanceof.type({className:e.name}),path:[]}]),this.cls=e}_toDescriptorImpl(){return{...this._describeBase(),className:this.cls.name,kind:`instanceof`}}_walk(e){return e.instanceof?e.instanceof(this):super._walk(e)}_equalsImpl(t){return t instanceof e&&this.cls===t.cls}};function Z(t,n){if((0,e.isPlainObject)(t)&&(0,e.isPlainObject)(n)){let e=m(t);for(let[r,i]of Object.entries(n))f(e,r,Z(t[r],i));return e}return n}var ke=class e extends E{schemas;get _kind(){return`intersect`}constructor(e){super(),this.schemas=e}_parse(e,t){let n={hasOutput:!1,issues:[],output:e};for(let r=0;r<this.schemas.length;r++){let i=this.schemas[r]._parseFullSync(e,t);i.issues.length>0?n.issues.push(...i.issues):n.hasOutput?n.output=Z(n.output,i.data):(n.hasOutput=!0,n.output=i.data)}return{data:n.output,issues:n.issues,typeOk:n.issues.length===0}}async parseAsync(e,t){let n=t??w();return this._withCatchAsync(async()=>{let t=this._prepareInput(e);if(t.skip)return t.value;let r={hasOutput:!1,issues:[],output:t.value};for(let e=0;e<this.schemas.length;e++){let i=await this.schemas[e]._parseFullAsync(t.value,n);i.issues.length>0?r.issues.push(...i.issues):r.hasOutput?r.output=Z(r.output,i.data):(r.hasOutput=!0,r.output=i.data)}if(r.issues.length>0)throw new l(r.issues);let i=await this._runValidatorsAsync(r.output,n);if(i.length)throw new l(i);return this._runPostprocessors(r.output)})}_toDescriptorImpl(){return{...this._describeBase(),branches:this.schemas.map(e=>e.toDescriptor()),kind:`intersect`}}_walk(e){let t=this.schemas.map(t=>t.walk(e));return e.intersect?e.intersect(this,t):super._walk(e)}_equalsImpl(t){return!(t instanceof e)||this.schemas.length!==t.schemas.length?!1:this.schemas.every((e,n)=>e.equals(t.schemas[n]))}},Ae=class e extends E{_getter;_resolved;get _kind(){return`lazy`}constructor(e){super(),this._getter=e}_resolve(){return this._resolved??=this._getter()}_parse(e,t){let n=this._resolve()._parseFullSync(e,t);return n.issues.length===0?{data:n.data,issues:[],typeOk:!0}:{data:e,issues:n.issues,typeOk:!0}}async parseAsync(e,t){let n=t??w();return this._withCatchAsync(async()=>{let t=this._prepareInput(e);if(t.skip)return t.value;let r=await this._resolve()._parseFullAsync(t.value,n);if(r.issues.length>0)throw new l(r.issues);let i=await this._runValidatorsAsync(r.data,n);if(i.length>0)throw new l(i);return this._runPostprocessors(r.data)})}_toDescriptorImpl(){return{...this._describeBase(),kind:`lazy`}}_walk(e){return e.lazy?e.lazy(this):super._walk(e)}_equalsImpl(t){return t instanceof e?this._getter===t._getter:!1}_construct(t){let n=new e(this._getter);return n.state=t,n}},Q=class e extends E{value;get _kind(){return`literal`}constructor(e){super((n,r)=>n===e?null:[{code:t.invalid_literal,message:(r?.messages??x()).literal.expected({expected:e}),params:{expected:e},path:[]}]),this.value=e}_toDescriptorImpl(){return{...this._describeBase(),kind:`literal`,value:this.value}}_walk(e){return e.literal?e.literal(this):super._walk(e)}_equalsImpl(t){return t instanceof e?this.value===t.value:!1}},je=class e extends E{keySchema;valueSchema;get _kind(){return`map`}constructor(e,t){super(),this.keySchema=e,this.valueSchema=t}_parse(e,n){if(!(e instanceof Map))return{data:e,issues:[{code:t.invalid_type,message:n.messages.map.type(),path:[]}],typeOk:!1};let r=new Map,a=[],o=0;for(let[t,s]of e){let e=this.keySchema._parseFullSync(t,n),c=this.valueSchema._parseFullSync(s,n);e.issues.length>0&&a.push(...i(e.issues,o)),c.issues.length>0&&a.push(...i(c.issues,o)),e.issues.length===0&&c.issues.length===0&&r.set(e.data,c.data),o+=1}return{data:r,issues:a,typeOk:!0}}async parseAsync(e,n){let r=n??w();return this._withCatchAsync(async()=>{let n=this._prepareInput(e);if(n.skip)return n.value;let a=n.value;if(!(a instanceof Map))throw new l([{code:t.invalid_type,message:r.messages.map.type(),path:[]}]);let o=[...a],s=await Promise.all(o.map(([e,t])=>Promise.all([this.keySchema._parseFullAsync(e,r),this.valueSchema._parseFullAsync(t,r)]))),c=[],u=new Map;for(let e=0;e<s.length;e++){let[t,n]=s[e];t.issues.length>0&&c.push(...i(t.issues,e)),n.issues.length>0&&c.push(...i(n.issues,e)),t.issues.length===0&&n.issues.length===0&&u.set(t.data,n.data)}let d=await this._runValidatorsAsync(u,r),f=[...c,...d];if(f.length>0)throw new l(f);return this._runPostprocessors(u)})}min(e,i=e=>x().map.min(e)){return this._addConstraint((a,o)=>{let s=a;return s.size>=e?null:n(t.too_small,r(i,{min:e,value:s}),{min:e})})}max(e,i=e=>x().map.max(e)){return this._addConstraint((a,o)=>{let s=a;return s.size<=e?null:n(t.too_big,r(i,{max:e,value:s}),{max:e})})}size(e,i=e=>x().map.size(e)){return this._addConstraint((a,o)=>{let s=a;return s.size===e?null:n(t.invalid_length,r(i,{exact:e,value:s}),{exact:e})})}nonEmpty(e=()=>x().map.nonEmpty()){return this._addConstraint((i,a)=>i.size>0?null:n(t.too_small,r(e,{min:1}),{min:1}))}_toDescriptorImpl(){return{...this._describeBase(),key:this.keySchema.toDescriptor(),kind:`map`,value:this.valueSchema.toDescriptor()}}_walk(e){let t=this.keySchema.walk(e),n=this.valueSchema.walk(e);return e.map?e.map(this,t,n):super._walk(e)}_equalsImpl(t){return t instanceof e?this.keySchema.equals(t.keySchema)&&this.valueSchema.equals(t.valueSchema):!1}},Me=class e extends E{get _kind(){return`never`}constructor(){super((e,n)=>[{code:t.invalid_type,message:(n?.messages??x()).never.invalid(),path:[]}])}_toDescriptorImpl(){return{...this._describeBase(),kind:`never`}}_walk(e){return e.never?e.never(this):super._walk(e)}_equalsImpl(t){return t instanceof e}},Ne=class e extends E{get _kind(){return`number`}constructor(){super((e,r)=>typeof e==`number`&&!Number.isNaN(e)?null:n(t.invalid_type,(r?.messages??x()).number.type()))}min(e,i=e=>x().number.min(e)){return this._addConstraint((a,o)=>a>=e?null:n(t.too_small,r(i,{min:e,value:a}),{min:e}),t=>{let n=t;return{...n,minimum:n.minimum===void 0?e:Math.max(n.minimum,e)}})}max(e,i=e=>x().number.max(e)){return this._addConstraint((a,o)=>a<=e?null:n(t.too_big,r(i,{max:e,value:a}),{max:e}),t=>{let n=t;return{...n,maximum:n.maximum===void 0?e:Math.min(n.maximum,e)}})}int(e=()=>x().number.int()){return this._addConstraint((i,a)=>Number.isInteger(i)?null:n(t.invalid_integer,r(e,{value:i})),e=>({...e,typeHint:`integer`}))}positive(e=()=>x().number.positive()){return this._addConstraint((i,a)=>i>0?null:n(t.too_small,r(e,{value:i}),{exclusive:!0,min:0}),e=>{let t=e;return{...t,exclusiveMinimum:t.exclusiveMinimum===void 0?0:Math.max(t.exclusiveMinimum,0)}})}negative(e=()=>x().number.negative()){return this._addConstraint((i,a)=>i<0?null:n(t.too_big,r(e,{value:i}),{exclusive:!0,max:0}),e=>{let t=e;return{...t,exclusiveMaximum:t.exclusiveMaximum===void 0?0:Math.min(t.exclusiveMaximum,0)}})}nonNegative(e=()=>x().number.nonNegative()){return this._addConstraint((i,a)=>i>=0?null:n(t.too_small,r(e,{value:i}),{min:0}),e=>{let t=e;return{...t,minimum:t.minimum===void 0?0:Math.max(t.minimum,0)}})}nonPositive(e=()=>x().number.nonPositive()){return this._addConstraint((i,a)=>i<=0?null:n(t.too_big,r(e,{value:i}),{max:0}),e=>{let t=e;return{...t,maximum:t.maximum===void 0?0:Math.min(t.maximum,0)}})}multipleOf(e,i=e=>x().number.multipleOf(e)){return this._addConstraint((a,o)=>Math.abs(Math.round(a/e)-a/e)<1e-9?null:n(t.invalid_multiple_of,r(i,{step:e,value:a}),{step:e}),t=>({...t,multipleOf:e}))}safe(e=()=>x().number.safe()){return this._addConstraint((i,a)=>Number.isSafeInteger(i)?null:n(t.invalid_safe,r(e,{value:i})))}finite(e=()=>x().number.finite()){return this._addConstraint((i,a)=>Number.isFinite(i)?null:n(t.invalid_finite,r(e,{value:i})))}coerce(){return e.coerce()}_walk(e){return e.number?e.number(this):super._walk(e)}_toDescriptorImpl(){let e=this._annotations;return{...this._describeBase(),...e.exclusiveMaximum===void 0?{}:{exclusiveMaximum:e.exclusiveMaximum},...e.exclusiveMinimum===void 0?{}:{exclusiveMinimum:e.exclusiveMinimum},...e.maximum===void 0?{}:{maximum:e.maximum},...e.minimum===void 0?{}:{minimum:e.minimum},...e.multipleOf===void 0?{}:{multipleOf:e.multipleOf},...e.typeHint===void 0?{}:{typeHint:e.typeHint},kind:`number`}}_equalsImpl(t){return t instanceof e?this._annotationsEqual(t):!1}static coerce(){return new e().preprocess(e=>{if(typeof e==`number`)return e;if(typeof e==`string`||typeof e==`boolean`){let t=Number(e);return Number.isNaN(t)?e:t}return e})}},Pe=class e extends E{schemas;get _kind(){return`union`}constructor(e){super(),this.schemas=e}_parse(e,n){let r=[];for(let t of this.schemas){let i=t._parseFullSync(e,n);if(i.issues.length===0)return{data:i.data,issues:[],typeOk:!0};r.push(i.issues)}return{data:e,issues:[{code:t.invalid_union,message:n.messages.union.invalid(),params:{errors:r},path:[]}],typeOk:!1}}async parseAsync(e,n){let r=n??w();return this._withCatchAsync(async()=>{let n=this._prepareInput(e);if(n.skip)return n.value;let i=n.value;try{let e=await Promise.any(this.schemas.map(e=>e.safeParseAsync(i,r).then(e=>{if(e.success)return e.data;throw e.error}))),t=await this._runValidatorsAsync(e,r);if(t.length)throw new l(t);return this._runPostprocessors(e)}catch(e){if(e instanceof AggregateError){let n=e.errors,i=n.find(e=>!l.is(e));if(i!==void 0)throw i;let a=n.map(e=>e.issues);throw new l([{code:t.invalid_union,message:r.messages.union.invalid(),params:{errors:a},path:[]}])}throw e}})}_toDescriptorImpl(){return{...this._describeBase(),branches:this.schemas.map(e=>e.toDescriptor()),kind:`union`}}_walk(e){let t=this.schemas.map(t=>t.walk(e));return e.union?e.union(this,t):super._walk(e)}_equalsImpl(t){return!(t instanceof e)||this.schemas.length!==t.schemas.length?!1:this.schemas.every((e,n)=>e.equals(t.schemas[n]))}},Fe=class e extends E{shape;_isRelaxed;get _kind(){return`object`}constructor(e,t=!1){super(),this.shape=e,this._isRelaxed=t}_unknownKeys(e){return Object.keys(e).filter(e=>!Object.hasOwn(this.shape,e))}_strictUnknownKeyIssues(e,n){if(this._isRelaxed)return[];let r=this._unknownKeys(e);return r.length===0?[]:[{code:t.invalid_keys,message:n.messages.object.invalidKeys({keys:r}),params:{keys:r},path:[]}]}_copyRelaxedUnknownKeys(e,t){if(this._isRelaxed)for(let n of this._unknownKeys(e))d(n)||Object.defineProperty(t,n,{configurable:!0,enumerable:!0,value:e[n],writable:!0})}_guardObjectInput(e,n){return typeof e!=`object`||!e||Array.isArray(e)?{issues:[{code:t.invalid_type,message:n.messages.object.type(),path:[]}],ok:!1}:{obj:e,ok:!0}}_createObjectParseContext(e,t){return{issues:[...this._strictUnknownKeyIssues(e,t)],output:{}}}_rebuildWith(t,n=this._isRelaxed){return this._copyStateTo(new e(t,n))}_parse(e,t){let n=this._guardObjectInput(e,t);if(!n.ok)return{data:e,issues:n.issues,typeOk:!1};let{obj:r}=n,{issues:a,output:o}=this._createObjectParseContext(r,t);for(let e of Object.keys(this.shape)){let n=this.shape[e]._parseFullSync(r[e],t);n.issues.length===0?f(o,e,n.data):a.push(...i(n.issues,e))}return this._copyRelaxedUnknownKeys(r,o),{data:o,issues:a,typeOk:!0}}async parseAsync(e,t){let n=t??w();return this._withCatchAsync(async()=>{let t=this._prepareInput(e);if(t.skip)return t.value;let r=this._guardObjectInput(t.value,n);if(!r.ok)throw new l(r.issues);let{obj:a}=r,{issues:o,output:s}=this._createObjectParseContext(a,n),c=Object.keys(this.shape),u=await Promise.all(c.map(e=>this.shape[e]._parseFullAsync(a[e],n)));for(let e=0;e<c.length;e++){let t=c[e],n=u[e];n.issues.length===0?f(s,t,n.data):o.push(...i(n.issues,t))}this._copyRelaxedUnknownKeys(a,s);let d=await this._runValidatorsAsync(s,n),p=[...o,...d];if(p.length>0)throw new l(p);return this._runPostprocessors(s)})}partial(...e){let t=e.length>0?new Set(e):null;return this._rebuildWith(p(Object.entries(this.shape).map(([e,n])=>[e,t===null||t.has(e)?n.optional():n])),this._isRelaxed)}required(){return this._rebuildWith(p(Object.entries(this.shape).map(([e,t])=>[e,t.required()])),this._isRelaxed)}extend(e){return this._rebuildWith(p([...Object.entries(this.shape),...Object.entries(e)]),this._isRelaxed)}pick(...e){let t=new Set(e);return this._rebuildWith(p(Object.entries(this.shape).filter(([e])=>t.has(e))))}omit(...e){let t=new Set(e);return this._rebuildWith(p(Object.entries(this.shape).filter(([e])=>!t.has(e))))}defaults(){return this.parse({})}partialDefaults(){let e={};for(let t of Object.keys(this.shape)){let n=this.shape[t]._parseFullSync(void 0);n.issues.length===0&&f(e,t,n.data)}return e}requiredFields(){return Object.keys(this.shape).filter(e=>!this.shape[e].isOptional)}optionalFields(){return Object.keys(this.shape).filter(e=>this.shape[e].isOptional)}relaxed(){return this._rebuildWith(this.shape,!0)}strict(){return this._rebuildWith(this.shape,!1)}keyof(){return new Pe(Object.keys(this.shape).map(e=>new Q(e)))}_toDescriptorImpl(){let e={};for(let[t,n]of Object.entries(this.shape))f(e,t,n.toDescriptor());return{...this._describeBase(),fields:e,kind:`object`,strict:!this._isRelaxed}}_walk(e){let t=p(Object.entries(this.shape).map(([t,n])=>[t,n.walk(e)]));return e.object?e.object(this,t):super._walk(e)}merge(e){return this._rebuildWith(p([...Object.entries(this.shape),...Object.entries(e.shape)]),e._isRelaxed)}_equalsImpl(t){if(!(t instanceof e)||this._isRelaxed!==t._isRelaxed)return!1;let n=Object.keys(this.shape);if(n.length!==Object.keys(t.shape).length)return!1;for(let e of n)if(!Object.hasOwn(t.shape,e)||!this.shape[e].equals(t.shape[e]))return!1;return!0}};function Ie(e){return e.map(e=>e instanceof E?e:new Q(e))}var Le=class e extends E{keySchema;valueSchema;get _kind(){return`record`}constructor(e,t){super(),this.keySchema=e,this.valueSchema=t}_guardRecordInput(e,n){return typeof e!=`object`||!e||Array.isArray(e)?{issues:[{code:t.invalid_type,message:n.messages.object.type(),path:[]}],ok:!1}:{ok:!0,value:e}}_parseRecordEntries(e,t){let n=[],r={};for(let a of Object.keys(e)){let o=this.keySchema._parseFullSync(a,t);if(o.issues.length>0){n.push(...i(o.issues,a));continue}let s=o.data;if(d(s))continue;let c=this.valueSchema._parseFullSync(e[a],t);c.issues.length===0?Object.defineProperty(r,s,{configurable:!0,enumerable:!0,value:c.data,writable:!0}):n.push(...i(c.issues,a))}return{issues:n,output:r}}_parse(e,t){let n=this._guardRecordInput(e,t);if(!n.ok)return{data:e,issues:n.issues,typeOk:!1};let{issues:r,output:i}=this._parseRecordEntries(n.value,t);return{data:i,issues:r,typeOk:!0}}async parseAsync(e,t){let n=t??w();return this._withCatchAsync(async()=>{let t=this._prepareInput(e);if(t.skip)return t.value;let r=this._guardRecordInput(t.value,n);if(!r.ok)throw new l(r.issues);let a=r.value,o=Object.keys(a),s=await Promise.all(o.map(e=>Promise.all([this.keySchema._parseFullAsync(e,n),this.valueSchema._parseFullAsync(a[e],n)]))),c=[],u={};for(let e=0;e<o.length;e++){let t=o[e],[n,r]=s[e];if(n.issues.length>0){c.push(...i(n.issues,t));continue}let a=n.data;d(a)||(r.issues.length===0?Object.defineProperty(u,a,{configurable:!0,enumerable:!0,value:r.data,writable:!0}):c.push(...i(r.issues,t)))}let f=await this._runValidatorsAsync(u,n),p=[...c,...f];if(p.length>0)throw new l(p);return this._runPostprocessors(u)})}_toDescriptorImpl(){return{...this._describeBase(),key:this.keySchema.toDescriptor(),kind:`record`,value:this.valueSchema.toDescriptor()}}_walk(e){let t=this.keySchema.walk(e),n=this.valueSchema.walk(e);return e.record?e.record(this,t,n):super._walk(e)}_equalsImpl(t){return t instanceof e?this.keySchema.equals(t.keySchema)&&this.valueSchema.equals(t.valueSchema):!1}},Re=class e extends E{itemSchema;get _kind(){return`set`}constructor(e){super(),this.itemSchema=e}_parse(e,n){if(!(e instanceof Set))return{data:e,issues:[{code:t.invalid_type,message:n.messages.set.type(),path:[]}],typeOk:!1};let r=[],a=new Set,o=0;for(let t of e){let e=this.itemSchema._parseFullSync(t,n);e.issues.length===0?a.add(e.data):r.push(...i(e.issues,o)),o+=1}return{data:a,issues:r,typeOk:!0}}async parseAsync(e,n){let r=n??w();return this._withCatchAsync(async()=>{let n=this._prepareInput(e);if(n.skip)return n.value;let a=n.value;if(!(a instanceof Set))throw new l([{code:t.invalid_type,message:r.messages.set.type(),path:[]}]);let o=[...a],s=await Promise.all(o.map(e=>this.itemSchema._parseFullAsync(e,r))),c=[],u=new Set;for(let e=0;e<s.length;e++){let t=s[e];t.issues.length===0?u.add(t.data):c.push(...i(t.issues,e))}let d=await this._runValidatorsAsync(u,r),f=[...c,...d];if(f.length>0)throw new l(f);return this._runPostprocessors(u)})}min(e,i=e=>x().set.min(e)){return this._addConstraint((a,o)=>{let s=a;return s.size>=e?null:n(t.too_small,r(i,{min:e,value:s}),{min:e})})}max(e,i=e=>x().set.max(e)){return this._addConstraint((a,o)=>{let s=a;return s.size<=e?null:n(t.too_big,r(i,{max:e,value:s}),{max:e})})}size(e,i=e=>x().set.size(e)){return this._addConstraint((a,o)=>{let s=a;return s.size===e?null:n(t.invalid_length,r(i,{exact:e,value:s}),{exact:e})})}nonEmpty(e=()=>x().set.nonEmpty()){return this._addConstraint((i,a)=>i.size>0?null:n(t.too_small,r(e,{min:1}),{min:1}))}_toDescriptorImpl(){return{...this._describeBase(),items:this.itemSchema.toDescriptor(),kind:`set`}}_walk(e){let t=this.itemSchema.walk(e);return e.set?e.set(this,t):super._walk(e)}_equalsImpl(t){return t instanceof e?this.itemSchema.equals(t.itemSchema):!1}},ze=class e extends E{get _kind(){return`string`}constructor(){super((e,r)=>typeof e==`string`?null:n(t.invalid_type,(r?.messages??x()).string.type()))}min(e,i=e=>x().string.min(e)){return this._addConstraint((a,o)=>a.length>=e?null:n(t.too_small,r(i,{min:e,value:a}),{min:e}),t=>{let n=t;return{...n,minLength:n.minLength===void 0?e:Math.max(n.minLength,e)}})}max(e,i=e=>x().string.max(e)){return this._addConstraint((a,o)=>a.length<=e?null:n(t.too_big,r(i,{max:e,value:a}),{max:e}),t=>{let n=t;return{...n,maxLength:n.maxLength===void 0?e:Math.min(n.maxLength,e)}})}length(e,i=e=>x().string.length(e)){return this._addConstraint((a,o)=>a.length===e?null:n(t.invalid_length,r(i,{exact:e,value:a}),{exact:e}),t=>({...t,maxLength:e,minLength:e}))}nonempty(e=()=>x().string.nonEmpty()){return this.nonEmpty(e)}nonEmpty(e=()=>x().string.nonEmpty()){return this._addConstraint((i,a)=>i.length>0?null:n(t.too_small,r(e,{min:1,value:i}),{min:1}),e=>{let t=e;return{...t,minLength:Math.max(t.minLength??0,1)}})}startsWith(e,i=e=>x().string.startsWith(e)){return this._addConstraint((a,o)=>a.startsWith(e)?null:n(t.invalid_string,r(i,{prefix:e,value:a}),{prefix:e}))}endsWith(e,i=e=>x().string.endsWith(e)){return this._addConstraint((a,o)=>a.endsWith(e)?null:n(t.invalid_string,r(i,{suffix:e,value:a}),{suffix:e}))}includes(e,i=e=>x().string.includes(e)){return this._addConstraint((a,o)=>a.includes(e)?null:n(t.invalid_string,r(i,{substr:e,value:a}),{includes:e}))}regex(e,i=e=>x().string.regex(e)){let a=new RegExp(e.source,e.flags.replace(/[gy]/g,``));return this._addConstraint((e,o)=>a.test(e)?null:n(t.invalid_string,r(i,{value:e}),{pattern:a.source}),e=>{let t=e;return t.pattern===null?t:t.pattern===void 0?{...t,pattern:a.source}:t.pattern===a.source?t:(b("[spell] Multiple .regex() constraints detected on a single string schema. JSON Schema `pattern` cannot represent multiple patterns and will be omitted from toJsonSchema() output."),{...t,pattern:null})})}email(e=()=>x().string.email()){return this._addConstraint((i,a)=>O(i)?null:n(t.invalid_string,r(e,{value:i}),{format:`email`}),e=>({...e,format:`email`}))}url(e={}){let{message:i=()=>x().string.url(),protocols:a=[`http`,`https`]}=e;return this._addConstraint((e,o)=>k(e,a)?null:n(t.invalid_url,r(i,{value:e}),{format:`url`}),e=>({...e,format:`uri`}))}uuid(e=()=>x().string.uuid()){return this._addConstraint((i,a)=>A(i)?null:n(t.invalid_string,r(e,{value:i}),{format:`uuid`}),e=>({...e,format:`uuid`}))}isoDate(e=()=>x().string.date()){return this._addConstraint((i,a)=>j(i)?null:n(t.invalid_string,r(e,{value:i}),{format:`iso-date`}),e=>({...e,format:`date`}))}isoDateTime(e=()=>x().string.dateTime()){return this._addConstraint((i,a)=>M(i)?null:n(t.invalid_string,r(e,{value:i}),{format:`iso-datetime`}),e=>({...e,format:`date-time`}))}ip(e=()=>x().string.ip()){return this._addConstraint((i,a)=>N(i)?null:n(t.invalid_string,r(e,{value:i}),{format:`ip`}))}cuid(e=()=>x().string.cuid()){return this._addConstraint((i,a)=>P(i)?null:n(t.invalid_string,r(e,{value:i}),{format:`cuid`}))}cuid2(e=()=>x().string.cuid2()){return this._addConstraint((i,a)=>F(i)?null:n(t.invalid_string,r(e,{value:i}),{format:`cuid2`}))}ulid(e=()=>x().string.ulid()){return this._addConstraint((i,a)=>I(i)?null:n(t.invalid_string,r(e,{value:i}),{format:`ulid`}))}nanoid(e,i=()=>x().string.nanoid()){return this._addConstraint((a,o)=>L(a,e)?null:n(t.invalid_string,r(i,{value:a}),{format:`nanoid`}))}base64(e=()=>x().string.base64()){return this._addConstraint((i,a)=>R(i)?null:n(t.invalid_base64,r(e,{value:i}),{format:`base64`}),e=>({...e,contentEncoding:`base64`}))}base64url(e=()=>x().string.base64url()){return this._addConstraint((i,a)=>we(i)?null:n(t.invalid_base64,r(e,{value:i}),{format:`base64url`}))}hex(e=()=>x().string.hex()){return this._addConstraint((i,a)=>z(i)?null:n(t.invalid_string,r(e,{value:i}),{format:`hex`}))}hexColor(e=()=>x().string.hexColor()){return this._addConstraint((i,a)=>B(i)?null:n(t.invalid_string,r(e,{value:i}),{format:`hex-color`}))}emoji(e=()=>x().string.emoji()){return this._addConstraint((i,a)=>V(i)?null:n(t.invalid_string,r(e,{value:i}),{format:`emoji`}))}jwt(e=()=>x().string.jwt()){return this._addConstraint((i,a)=>H(i)?null:n(t.invalid_string,r(e,{value:i}),{format:`jwt`}))}time(e=()=>x().string.time()){return this._addConstraint((i,a)=>U(i)?null:n(t.invalid_string,r(e,{value:i}),{format:`time`}))}duration(e=()=>x().string.duration()){return this._addConstraint((i,a)=>W(i)?null:n(t.invalid_duration,r(e,{value:i}),{format:`duration`}),e=>({...e,format:`duration`}))}semver(e=()=>x().string.semver()){return this._addConstraint((i,a)=>G(i)?null:n(t.invalid_string,r(e,{value:i}),{format:`semver`}))}slug(e=()=>x().string.slug()){return this._addConstraint((i,a)=>K(i)?null:n(t.invalid_string,r(e,{value:i}),{format:`slug`}))}numeric(e=()=>x().string.numeric()){return this._addConstraint((i,a)=>q(i)?null:n(t.invalid_string,r(e,{value:i}),{format:`numeric`}))}coerce(){return e.coerce()}trim(){return this.preprocess(e=>typeof e==`string`?e.trim():e)}lowercase(){return this.preprocess(e=>typeof e==`string`?e.toLowerCase():e)}uppercase(){return this.preprocess(e=>typeof e==`string`?e.toUpperCase():e)}_walk(e){return e.string?e.string(this):super._walk(e)}_toDescriptorImpl(){let e=this._annotations;return{...this._describeBase(),...e.contentEncoding===void 0?{}:{contentEncoding:e.contentEncoding},...e.format===void 0?{}:{format:e.format},...e.maxLength===void 0?{}:{maxLength:e.maxLength},...e.minLength===void 0?{}:{minLength:e.minLength},...e.pattern===void 0?{}:{pattern:e.pattern},kind:`string`}}_equalsImpl(t){return t instanceof e?this._annotationsEqual(t):!1}static coerce(){return new e().preprocess(e=>e==null?e:String(e))}},Be=class e extends E{items;restSchema;get _kind(){return`tuple`}constructor(e,t=null){super(),this.items=e,this.restSchema=t}rest(t){return this._copyStateTo(new e(this.items,t))}_guardTupleInput(e,n){return this.restSchema===null&&e.length!==this.items.length?{issues:[{code:t.invalid_length,message:n.messages.tuple.length({exact:this.items.length}),params:{exact:this.items.length},path:[]}],ok:!1}:this.restSchema!==null&&e.length<this.items.length?{issues:[{code:t.too_small,message:n.messages.tuple.min({min:this.items.length}),params:{min:this.items.length},path:[]}],ok:!1}:{ok:!0,value:e}}_parse(e,n){if(!Array.isArray(e))return{data:e,issues:[{code:t.invalid_type,message:n.messages.tuple.type(),path:[]}],typeOk:!1};let r=this._guardTupleInput(e,n);if(!r.ok)return{data:e,issues:r.issues,typeOk:!1};let a=[],o=[],s=r.value;for(let e=0;e<this.items.length;e++){let t=this.items[e]._parseFullSync(s[e],n);t.issues.length===0?o.push(t.data):(a.push(...i(t.issues,e)),o.push(s[e]))}if(this.restSchema!==null)for(let e=this.items.length;e<s.length;e++){let t=this.restSchema._parseFullSync(s[e],n);t.issues.length===0?o.push(t.data):(a.push(...i(t.issues,e)),o.push(s[e]))}return{data:o,issues:a,typeOk:!0}}async parseAsync(e,n){let r=n??w();return this._withCatchAsync(async()=>{let n=this._prepareInput(e);if(n.skip)return n.value;let a=n.value;if(!Array.isArray(a))throw new l([{code:t.invalid_type,message:r.messages.tuple.type(),path:[]}]);let o=this._guardTupleInput(a,r);if(!o.ok)throw new l(o.issues);let s=o.value,c=[],u=[],d=await Promise.all(this.items.map((e,t)=>e._parseFullAsync(s[t],r)));for(let e=0;e<d.length;e++){let t=d[e];t.issues.length===0?u.push(t.data):(c.push(...i(t.issues,e)),u.push(s[e]))}let f=this.restSchema;if(f!==null){let e=s.slice(this.items.length),t=await Promise.all(e.map(e=>f._parseFullAsync(e,r)));for(let e=0;e<t.length;e++){let n=t[e],r=this.items.length+e;n.issues.length===0?u.push(n.data):(c.push(...i(n.issues,r)),u.push(s[r]))}}let p=await this._runValidatorsAsync(u,r),m=[...c,...p];if(m.length>0)throw new l(m);return this._runPostprocessors(u)})}_toDescriptorImpl(){return{...this._describeBase(),items:this.items.map(e=>e.toDescriptor()),kind:`tuple`,rest:this.restSchema===null?null:this.restSchema.toDescriptor()}}_walk(e){let t=this.items.map(t=>t.walk(e)),n=this.restSchema===null?null:this.restSchema.walk(e);return e.tuple?e.tuple(this,t,n):super._walk(e)}_equalsImpl(t){if(!(t instanceof e)||this.items.length!==t.items.length)return!1;for(let e=0;e<this.items.length;e++)if(!this.items[e].equals(t.items[e]))return!1;let n=this.restSchema,r=t.restSchema;return!(n===null!=(r===null)||n!==null&&r!==null&&!n.equals(r))}},Ve=class e extends E{_map;_discriminator;get _kind(){return`variant`}constructor(e,t){let n=new Map;for(let[r,i]of Object.entries(t)){let t=new Q(r),a=i.shape[e];if(a&&!a.equals(t))throw new o(`s.variant(): branch "${r}" defines a conflicting discriminator schema for "${e}".`);let s={[e]:t};n.set(r,a?i:i.extend(s))}super(),this._discriminator=e,this._map=n}get discriminator(){return this._discriminator}get variantMap(){return this._map}_resolveVariant(e,n){if(typeof e!=`object`||!e||Array.isArray(e))return{issues:[{code:t.invalid_type,message:n.messages.variant.type(),path:[]}]};let r=e,i=r[this._discriminator],a=this._map.get(i);if(!a){let e=[...this._map.keys()];return{issues:[{code:t.invalid_variant,message:n.messages.variant.invalidDiscriminator({discriminator:this._discriminator,expected:e}),params:{discriminator:this._discriminator,expected:e},path:[]}]}}return{matched:a,obj:r}}_parse(e,t){let n=this._resolveVariant(e,t);if(`issues`in n)return{data:e,issues:n.issues,typeOk:!1};let r=n.matched._parseFullSync(e,t);return r.issues.length===0?{data:r.data,issues:[],typeOk:!0}:{data:e,issues:r.issues,typeOk:!0}}_toDescriptorImpl(){let e={};for(let[t,n]of this._map.entries())f(e,t,n.toDescriptor());return{...this._describeBase(),branches:e,discriminator:this._discriminator,kind:`variant`}}_walk(e){let t=p([...this._map.entries()].map(([t,n])=>[t,n.walk(e)]));return e.variant?e.variant(this,t):super._walk(e)}_equalsImpl(t){if(!(t instanceof e)||this._discriminator!==t._discriminator||this._map.size!==t._map.size)return!1;for(let[e,n]of this._map){let r=t._map.get(e);if(!r||!n.equals(r))return!1}return!0}},He=(e,t)=>Xe(e,t),Ue=()=>new E,We=e=>new Te(e),Ge=()=>new J,Ke=()=>new Y,qe=()=>new X,Je=e=>new De(e),Ye=e=>new Oe(e),Xe=(...e)=>new ke(Ie(e)),Ze=e=>new Ae(e),Qe=e=>new Q(e),$e=(e,t)=>new je(e,t),et=()=>new Me,tt=()=>new Q(null),nt=()=>new Ne,rt=e=>new Fe(e),it=(e,t)=>new Le(e,t),at=e=>new Re(e),ot=()=>new ze,st=e=>new Be(e),ct=()=>new Q(void 0),$=(...e)=>new Pe(Ie(e)),lt={and:He,any:Ue,array:We,bigint:Ge,boolean:Ke,coerce:{bigint:()=>J.coerce(),boolean:()=>Y.coerce(),date:()=>X.coerce(),number:()=>Ne.coerce(),string:()=>ze.coerce()},date:qe,enum:Je,instanceof:Ye,intersect:Xe,lazy:Ze,literal:Qe,map:$e,never:et,null:tt,number:nt,object:rt,or:(e,t)=>$(e,t),record:it,set:at,string:ot,tuple:st,undefined:ct,union:$,unknown:()=>new E,variant:(e,t)=>new Ve(e,t)};exports.ErrorCode=t,exports.PipeSchema=D,exports.Schema=E,exports.SpellError=o,exports.SpellValidationError=l,exports.descriptorToJsonSchema=g,exports.errorsAt=a,exports.fail=n,exports.hasMaxLength=ue,exports.hasMinLength=le,exports.isArray=Se,exports.isBase64=R,exports.isBase64url=we,exports.isBoolean=ye,exports.isCuid=P,exports.isCuid2=F,exports.isDate=xe,exports.isDuration=W,exports.isEmail=O,exports.isEmoji=V,exports.isHex=z,exports.isHexColor=B,exports.isInRange=de,exports.isInteger=fe,exports.isIp=N,exports.isIsoDate=j,exports.isIsoDateTime=M,exports.isJwt=H,exports.isMultipleOf=ge,exports.isNanoid=L,exports.isNegative=he,exports.isNonNegative=me,exports.isNullOrUndefined=be,exports.isNumber=ve,exports.isNumeric=q,exports.isPositive=pe,exports.isSemver=G,exports.isSlug=K,exports.isString=_e,exports.isTime=U,exports.isUlid=I,exports.isUrl=k,exports.isUuid=A,exports.prependIssuePath=i,exports.resetMessages=se,exports.s=lt,exports.schemaToJsonSchema=h,exports.setLogger=oe,exports.setMessages=ae;
|
|
3
|
+
//# sourceMappingURL=spell.cjs.map
|