@atproto/lex-schema 0.0.20 → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +18 -0
- package/dist/core/$type.js +2 -6
- package/dist/core/$type.js.map +1 -1
- package/dist/core/record-key.js +4 -8
- package/dist/core/record-key.js.map +1 -1
- package/dist/core/result.js +6 -14
- package/dist/core/result.js.map +1 -1
- package/dist/core/schema.js +16 -20
- package/dist/core/schema.js.map +1 -1
- package/dist/core/standard-schema.js +5 -10
- package/dist/core/standard-schema.js.map +1 -1
- package/dist/core/string-format.d.ts.map +1 -1
- package/dist/core/string-format.js +37 -61
- package/dist/core/string-format.js.map +1 -1
- package/dist/core/types.js +1 -2
- package/dist/core/validation-error.js +14 -25
- package/dist/core/validation-error.js.map +1 -1
- package/dist/core/validation-issue.js +12 -40
- package/dist/core/validation-issue.js.map +1 -1
- package/dist/core/validator.js +19 -28
- package/dist/core/validator.js.map +1 -1
- package/dist/core.js +9 -12
- package/dist/core.js.map +1 -1
- package/dist/external.js +3 -6
- package/dist/external.js.map +1 -1
- package/dist/helpers.js +5 -9
- package/dist/helpers.js.map +1 -1
- package/dist/index.js +3 -7
- package/dist/index.js.map +1 -1
- package/dist/schema/array.js +5 -11
- package/dist/schema/array.js.map +1 -1
- package/dist/schema/blob.js +10 -17
- package/dist/schema/blob.js.map +1 -1
- package/dist/schema/boolean.js +8 -9
- package/dist/schema/boolean.js.map +1 -1
- package/dist/schema/bytes.js +7 -12
- package/dist/schema/bytes.js.map +1 -1
- package/dist/schema/cid.js +7 -12
- package/dist/schema/cid.js.map +1 -1
- package/dist/schema/custom.js +5 -13
- package/dist/schema/custom.js.map +1 -1
- package/dist/schema/dict.js +6 -13
- package/dist/schema/dict.js.map +1 -1
- package/dist/schema/discriminated-union.js +10 -18
- package/dist/schema/discriminated-union.js.map +1 -1
- package/dist/schema/enum.js +6 -11
- package/dist/schema/enum.js.map +1 -1
- package/dist/schema/integer.js +5 -10
- package/dist/schema/integer.js.map +1 -1
- package/dist/schema/intersection.js +4 -11
- package/dist/schema/intersection.js.map +1 -1
- package/dist/schema/lex-map.js +13 -14
- package/dist/schema/lex-map.js.map +1 -1
- package/dist/schema/lex-value.js +11 -12
- package/dist/schema/lex-value.js.map +1 -1
- package/dist/schema/literal.js +4 -10
- package/dist/schema/literal.js.map +1 -1
- package/dist/schema/never.js +8 -9
- package/dist/schema/never.js.map +1 -1
- package/dist/schema/null.js +9 -10
- package/dist/schema/null.js.map +1 -1
- package/dist/schema/nullable.js +5 -10
- package/dist/schema/nullable.js.map +1 -1
- package/dist/schema/object.js +8 -14
- package/dist/schema/object.js.map +1 -1
- package/dist/schema/optional.js +5 -10
- package/dist/schema/optional.js.map +1 -1
- package/dist/schema/params.js +39 -44
- package/dist/schema/params.js.map +1 -1
- package/dist/schema/payload.js +5 -13
- package/dist/schema/payload.js.map +1 -1
- package/dist/schema/permission-set.js +2 -10
- package/dist/schema/permission-set.js.map +1 -1
- package/dist/schema/permission.js +2 -9
- package/dist/schema/permission.js.map +1 -1
- package/dist/schema/procedure.js +3 -13
- package/dist/schema/procedure.js.map +1 -1
- package/dist/schema/query.js +3 -12
- package/dist/schema/query.js.map +1 -1
- package/dist/schema/record.js +15 -24
- package/dist/schema/record.js.map +1 -1
- package/dist/schema/ref.js +4 -9
- package/dist/schema/ref.js.map +1 -1
- package/dist/schema/refine.js +3 -6
- package/dist/schema/refine.js.map +1 -1
- package/dist/schema/regexp.js +4 -11
- package/dist/schema/regexp.js.map +1 -1
- package/dist/schema/string.js +15 -26
- package/dist/schema/string.js.map +1 -1
- package/dist/schema/subscription.js +3 -12
- package/dist/schema/subscription.js.map +1 -1
- package/dist/schema/token.js +5 -11
- package/dist/schema/token.js.map +1 -1
- package/dist/schema/typed-object.js +11 -18
- package/dist/schema/typed-object.js.map +1 -1
- package/dist/schema/typed-ref.js +4 -9
- package/dist/schema/typed-ref.js.map +1 -1
- package/dist/schema/typed-union.js +8 -15
- package/dist/schema/typed-union.js.map +1 -1
- package/dist/schema/union.js +5 -11
- package/dist/schema/union.js.map +1 -1
- package/dist/schema/unknown.js +8 -9
- package/dist/schema/unknown.js.map +1 -1
- package/dist/schema/with-default.js +4 -11
- package/dist/schema/with-default.js.map +1 -1
- package/dist/schema.js +38 -41
- package/dist/schema.js.map +1 -1
- package/dist/util/array-agg.js +1 -4
- package/dist/util/array-agg.js.map +1 -1
- package/dist/util/assertion-util.js +1 -2
- package/dist/util/if-any.js +1 -2
- package/dist/util/lazy-property.js +1 -4
- package/dist/util/lazy-property.js.map +1 -1
- package/dist/util/memoize.js +2 -6
- package/dist/util/memoize.js.map +1 -1
- package/package.json +7 -8
- package/src/core/string-format.ts +2 -1
- package/src/helpers.test.ts +52 -52
- package/src/schema/record.test.ts +2 -2
- package/src/schema/ref.test.ts +1 -1
- package/src/schema/string.test.ts +6 -6
- package/src/schema/subscription.test.ts +4 -4
- package/src/schema/typed-object.test.ts +2 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"validation-issue.js","sourceRoot":"","sources":["../../src/core/validation-issue.ts"],"names":[],"mappings":";;;AAAA,gDAAyE;AAEzE,MAAM,yBAAyB,GAAG,GAAG,CAAA;AACrC,MAAM,+BAA+B,GAAG,GAAG,CAAA;AAE3C;;;;;;;;;;;GAWG;AACH,MAAsB,KAAK;IAId;IACA;IACA;IAHX,YACW,IAAY,EACZ,IAA4B,EAC5B,KAAc;QAFd,SAAI,GAAJ,IAAI,CAAQ;QACZ,SAAI,GAAJ,IAAI,CAAwB;QAC5B,UAAK,GAAL,KAAK,CAAS;IACtB,CAAC;IAEJ;;OAEG;IACH,QAAQ;QACN,OAAO,GAAG,IAAI,CAAC,OAAO,GAAG,aAAa,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAA;IACrD,CAAC;IAED;;;;OAIG;IACH,MAAM;QACJ,OAAO;YACL,IAAI,EAAE,IAAI,CAAC,IAAI;YACf,IAAI,EAAE,IA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CAAC;gBAAE,OAAO,aAAa,CAAA;YAChD,IAAI,KAAK,YAAY,IAAI;gBAAE,OAAO,MAAM,CAAA;YACxC,IAAI,KAAK,YAAY,MAAM;gBAAE,OAAO,QAAQ,CAAA;YAC5C,IAAI,KAAK,YAAY,GAAG;gBAAE,OAAO,KAAK,CAAA;YACtC,IAAI,KAAK,YAAY,GAAG;gBAAE,OAAO,KAAK,CAAA;YACtC,OAAO,QAAQ,CAAA;QACjB;YACE,OAAO,OAAO,KAAK,CAAA;IACvB,CAAC;AACH,CAAC;AAED,wBAAwB;AACxB,SAAS,oBAAoB,CAAC,CAAC,GAAG,EAAE,MAAM,CAAyB;IACjE,OAAO,GAAG,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,OAAO,CAAA;AACtC,CAAC;AAED,wBAAwB;AACxB,SAAS,cAAc,CACrB,GAAiB,EACjB,EAAuB,EACvB,CAAC,GAAG,CAAC;IAEL,OAAO,GAAG,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,CAAC,CAAA;AAC7E,CAAC","sourcesContent":["import { ifCid, isLegacyBlobRef, isPlainObject } from '@atproto/lex-data'\n\nconst STRING_PREVIEW_MAX_LENGTH = 256\nconst STRING_PREVIEW_TRUNCATED_SUFFIX = '…'\n\n/**\n * Abstract base class for all validation issues.\n *\n * An issue represents a single validation failure, containing:\n * - A code identifying the type of issue\n * - The path to the invalid value in the data structure\n * - The actual input value that failed validation\n *\n * Subclasses add specific properties relevant to each issue type and implement\n * the {@link message} property for human-readable error messages (that don't\n * contain the error path)\n */\nexport abstract class Issue {\n abstract readonly message: string\n\n constructor(\n readonly code: string,\n readonly path: readonly PropertyKey[],\n readonly input: unknown,\n ) {}\n\n /**\n * Returns a human-readable description of the validation issue.\n */\n toString() {\n return `${this.message}${stringifyPath(this.path)}`\n }\n\n /**\n * Converts the issue to a JSON-serializable object.\n *\n * @returns An object containing the issue code, path, and message\n */\n toJSON() {\n return {\n code: this.code,\n path: this.path,\n message: this.message,\n }\n }\n}\n\n/**\n * A custom validation issue with a user-defined message.\n *\n * Use this for validation rules that don't fit into the standard issue categories.\n */\nexport class IssueCustom extends Issue {\n constructor(\n readonly path: readonly PropertyKey[],\n readonly input: unknown,\n readonly message: string,\n ) {\n super('custom', path, input)\n }\n}\n\n/**\n * Issue for string values that don't match an expected format.\n *\n * Used for AT Protocol specific formats like DID, handle, NSID, AT-URI, etc.\n */\nexport class IssueInvalidFormat extends Issue {\n constructor(\n path: readonly PropertyKey[],\n input: unknown,\n readonly format: string,\n readonly detail?: string,\n ) {\n super('invalid_format', path, input)\n }\n\n override get message(): string {\n return `Invalid ${this.formatDescription}${this.detail ? ` (${this.detail}, ` : ' ('}got ${stringifyValue(this.input)})`\n }\n\n /** Returns a human-readable description of the expected format. */\n get formatDescription(): string {\n switch (this.format) {\n case 'at-identifier':\n return `AT identifier`\n case 'did':\n return `DID`\n case 'nsid':\n return `NSID`\n case 'cid':\n return `CID string`\n case 'tid':\n return `TID string`\n case 'record-key':\n return `record key`\n default:\n return this.format\n }\n }\n\n toJSON() {\n return {\n ...super.toJSON(),\n format: this.format,\n }\n }\n}\n\n/**\n * Issue for values that have an unexpected type.\n *\n * This is one of the most common validation issues, occurring when the\n * runtime type of a value doesn't match the expected schema type.\n */\nexport class IssueInvalidType extends Issue {\n constructor(\n path: readonly PropertyKey[],\n input: unknown,\n readonly expected: readonly string[],\n ) {\n super('invalid_type', path, input)\n }\n\n override get message(): string {\n return `Expected ${oneOf(this.expected.map(stringifyExpectedType))} value type (got ${stringifyValue(this.input)})`\n }\n\n toJSON() {\n return {\n ...super.toJSON(),\n expected: this.expected,\n }\n }\n}\n\n/**\n * Issue for values that don't match any of the expected literal values.\n *\n * Used when a value must be one of a specific set of allowed values\n * (e.g., enum-like constraints).\n */\nexport class IssueInvalidValue extends Issue {\n constructor(\n path: readonly PropertyKey[],\n input: unknown,\n readonly values: readonly unknown[],\n ) {\n super('invalid_value', path, input)\n }\n\n override get message(): string {\n return `Expected ${oneOf(this.values.map(stringifyValue))} (got ${stringifyValue(this.input)})`\n }\n\n toJSON() {\n return {\n ...super.toJSON(),\n values: this.values,\n }\n }\n}\n\n/**\n * Issue for missing required object properties.\n */\nexport class IssueRequiredKey extends Issue {\n constructor(\n path: readonly PropertyKey[],\n input: unknown,\n readonly key: PropertyKey,\n ) {\n super('required_key', path, input)\n }\n\n override get message(): string {\n return `Missing required key \"${String(this.key)}\"`\n }\n\n toJSON() {\n return {\n ...super.toJSON(),\n key: this.key,\n }\n }\n}\n\n/**\n * The type of measurement for size constraint issues.\n *\n * - `'array'` - Array length\n * - `'string'` - String length in characters\n * - `'integer'` - Numeric value\n * - `'grapheme'` - String length in grapheme clusters\n * - `'bytes'` - Byte length\n * - `'blob'` - Blob size\n */\nexport type MeasurableType =\n | 'array'\n | 'string'\n | 'integer'\n | 'grapheme'\n | 'bytes'\n | 'blob'\n\n/**\n * Issue for values that exceed a maximum constraint.\n */\nexport class IssueTooBig extends Issue {\n constructor(\n path: readonly PropertyKey[],\n input: unknown,\n readonly maximum: number,\n readonly type: MeasurableType,\n readonly actual: number,\n ) {\n super('too_big', path, input)\n }\n\n override get message(): string {\n return `${this.type} too big (maximum ${this.maximum}, got ${this.actual})`\n }\n\n toJSON() {\n return {\n ...super.toJSON(),\n type: this.type,\n maximum: this.maximum,\n }\n }\n}\n\n/**\n * Issue for values that are below a minimum constraint.\n */\nexport class IssueTooSmall extends Issue {\n constructor(\n path: readonly PropertyKey[],\n input: unknown,\n readonly minimum: number,\n readonly type: MeasurableType,\n readonly actual: number,\n ) {\n super('too_small', path, input)\n }\n\n override get message(): string {\n return `${this.type} too small (minimum ${this.minimum}, got ${this.actual})`\n }\n\n toJSON() {\n return {\n ...super.toJSON(),\n type: this.type,\n minimum: this.minimum,\n }\n }\n}\n\n// -----------------------------------------------------------------------------\n// Helper functions for formatting error messages\n// -----------------------------------------------------------------------------\n\nfunction stringifyExpectedType(expected: string): string {\n if (expected === '$typed') {\n return 'an object which includes the \"$type\" property'\n }\n return expected\n}\n\nfunction stringifyPath(path: readonly PropertyKey[]) {\n return ` at ${buildJsonPath(path)}`\n}\n\nfunction buildJsonPath(path: readonly PropertyKey[]): string {\n return `$${path.map(toJsonPathSegment).join('')}`\n}\n\nfunction toJsonPathSegment(segment: PropertyKey): string {\n if (typeof segment === 'number' || typeof segment === 'symbol') {\n return `[${String(segment)}]`\n } else if (/^[a-zA-Z_$][a-zA-Z0-9_]*$/.test(segment)) {\n return `.${segment}`\n } else {\n return `[${JSON.stringify(segment)}]`\n }\n}\n\nfunction oneOf(arr: readonly string[]): string {\n if (arr.length === 0) return ''\n if (arr.length === 1) return arr[0]\n return `one of ${arr.slice(0, -1).join(', ')} or ${arr.at(-1)}`\n}\n\nfunction stringifyValue(value: unknown): string {\n switch (typeof value) {\n case 'bigint':\n return `${value}n`\n case 'number':\n case 'boolean':\n return String(value)\n case 'string':\n return JSON.stringify(\n value.length < STRING_PREVIEW_MAX_LENGTH\n ? value\n : `${value.slice(0, STRING_PREVIEW_MAX_LENGTH - STRING_PREVIEW_TRUNCATED_SUFFIX.length)}${STRING_PREVIEW_TRUNCATED_SUFFIX}`,\n )\n case 'object':\n if (value === null) return 'null'\n if (Array.isArray(value)) {\n return `[${stringifyArray(value, stringifyValue)}]`\n }\n if (isPlainObject(value)) {\n return `{${stringifyArray(Object.entries(value), stringifyObjectEntry)}}`\n }\n if (ifCid(value)) return 'cid'\n if (isLegacyBlobRef(value)) return 'legacy-blob'\n if (value instanceof Date) return 'date'\n if (value instanceof RegExp) return 'regexp'\n if (value instanceof Map) return 'map'\n if (value instanceof Set) return 'set'\n return 'object'\n default:\n return typeof value\n }\n}\n\n/*@__NO_SIDE_EFFECTS__*/\nfunction stringifyObjectEntry([key, _value]: [PropertyKey, unknown]): string {\n return `${JSON.stringify(key)}: ...`\n}\n\n/*@__NO_SIDE_EFFECTS__*/\nfunction stringifyArray<T>(\n arr: readonly T[],\n fn: (item: T) => string,\n n = 2,\n): string {\n return arr.slice(0, n).map(fn).join(', ') + (arr.length > n ? ', ...' : '')\n}\n"]}
|
|
1
|
+
{"version":3,"file":"validation-issue.js","sourceRoot":"","sources":["../../src/core/validation-issue.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,eAAe,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAA;AAEzE,MAAM,yBAAyB,GAAG,GAAG,CAAA;AACrC,MAAM,+BAA+B,GAAG,GAAG,CAAA;AAE3C;;;;;;;;;;;GAWG;AACH,MAAM,OAAgB,KAAK;IAGzB,YACW,IAAY,EACZ,IAA4B,EAC5B,KAAc;QAFd,SAAI,GAAJ,IAAI,CAAQ;QACZ,SAAI,GAAJ,IAAI,CAAwB;QAC5B,UAAK,GAAL,KAAK,CAAS;IACtB,CAAC;IAEJ;;OAEG;IACH,QAAQ;QACN,OAAO,GAAG,IAAI,CAAC,OAAO,GAAG,aAAa,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAA;IACrD,CAAC;IAED;;;;OAIG;IACH,MAAM;QACJ,OAAO;YACL,IAAI,EAAE,IAAI,CAAC,IAAI;YACf,IAAI,EAAE,IAAI,CAAC,IAAI;YACf,OAAO,EAAE,IAAI,CAAC,OAAO;SACtB,CAAA;IACH,CAAC;CACF;AAED;;;;GAIG;AACH,MAAM,OAAO,WAAY,SAAQ,KAAK;IACpC,YACW,IAA4B,EAC5B,KAAc,EACd,OAAe;QAExB,KAAK,CAAC,QAAQ,EAAE,IAAI,EAAE,KAAK,CAAC,CAAA;QAJnB,SAAI,GAAJ,IAAI,CAAwB;QAC5B,UAAK,GAAL,KAAK,CAAS;QACd,YAAO,GAAP,OAAO,CAAQ;IAG1B,CAAC;CACF;AAED;;;;GAIG;AACH,MAAM,OAAO,kBAAm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CAAC;IAEL,OAAO,GAAG,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,CAAC,CAAA;AAC7E,CAAC","sourcesContent":["import { ifCid, isLegacyBlobRef, isPlainObject } from '@atproto/lex-data'\n\nconst STRING_PREVIEW_MAX_LENGTH = 256\nconst STRING_PREVIEW_TRUNCATED_SUFFIX = '…'\n\n/**\n * Abstract base class for all validation issues.\n *\n * An issue represents a single validation failure, containing:\n * - A code identifying the type of issue\n * - The path to the invalid value in the data structure\n * - The actual input value that failed validation\n *\n * Subclasses add specific properties relevant to each issue type and implement\n * the {@link message} property for human-readable error messages (that don't\n * contain the error path)\n */\nexport abstract class Issue {\n abstract readonly message: string\n\n constructor(\n readonly code: string,\n readonly path: readonly PropertyKey[],\n readonly input: unknown,\n ) {}\n\n /**\n * Returns a human-readable description of the validation issue.\n */\n toString() {\n return `${this.message}${stringifyPath(this.path)}`\n }\n\n /**\n * Converts the issue to a JSON-serializable object.\n *\n * @returns An object containing the issue code, path, and message\n */\n toJSON() {\n return {\n code: this.code,\n path: this.path,\n message: this.message,\n }\n }\n}\n\n/**\n * A custom validation issue with a user-defined message.\n *\n * Use this for validation rules that don't fit into the standard issue categories.\n */\nexport class IssueCustom extends Issue {\n constructor(\n readonly path: readonly PropertyKey[],\n readonly input: unknown,\n readonly message: string,\n ) {\n super('custom', path, input)\n }\n}\n\n/**\n * Issue for string values that don't match an expected format.\n *\n * Used for AT Protocol specific formats like DID, handle, NSID, AT-URI, etc.\n */\nexport class IssueInvalidFormat extends Issue {\n constructor(\n path: readonly PropertyKey[],\n input: unknown,\n readonly format: string,\n readonly detail?: string,\n ) {\n super('invalid_format', path, input)\n }\n\n override get message(): string {\n return `Invalid ${this.formatDescription}${this.detail ? ` (${this.detail}, ` : ' ('}got ${stringifyValue(this.input)})`\n }\n\n /** Returns a human-readable description of the expected format. */\n get formatDescription(): string {\n switch (this.format) {\n case 'at-identifier':\n return `AT identifier`\n case 'did':\n return `DID`\n case 'nsid':\n return `NSID`\n case 'cid':\n return `CID string`\n case 'tid':\n return `TID string`\n case 'record-key':\n return `record key`\n default:\n return this.format\n }\n }\n\n toJSON() {\n return {\n ...super.toJSON(),\n format: this.format,\n }\n }\n}\n\n/**\n * Issue for values that have an unexpected type.\n *\n * This is one of the most common validation issues, occurring when the\n * runtime type of a value doesn't match the expected schema type.\n */\nexport class IssueInvalidType extends Issue {\n constructor(\n path: readonly PropertyKey[],\n input: unknown,\n readonly expected: readonly string[],\n ) {\n super('invalid_type', path, input)\n }\n\n override get message(): string {\n return `Expected ${oneOf(this.expected.map(stringifyExpectedType))} value type (got ${stringifyValue(this.input)})`\n }\n\n toJSON() {\n return {\n ...super.toJSON(),\n expected: this.expected,\n }\n }\n}\n\n/**\n * Issue for values that don't match any of the expected literal values.\n *\n * Used when a value must be one of a specific set of allowed values\n * (e.g., enum-like constraints).\n */\nexport class IssueInvalidValue extends Issue {\n constructor(\n path: readonly PropertyKey[],\n input: unknown,\n readonly values: readonly unknown[],\n ) {\n super('invalid_value', path, input)\n }\n\n override get message(): string {\n return `Expected ${oneOf(this.values.map(stringifyValue))} (got ${stringifyValue(this.input)})`\n }\n\n toJSON() {\n return {\n ...super.toJSON(),\n values: this.values,\n }\n }\n}\n\n/**\n * Issue for missing required object properties.\n */\nexport class IssueRequiredKey extends Issue {\n constructor(\n path: readonly PropertyKey[],\n input: unknown,\n readonly key: PropertyKey,\n ) {\n super('required_key', path, input)\n }\n\n override get message(): string {\n return `Missing required key \"${String(this.key)}\"`\n }\n\n toJSON() {\n return {\n ...super.toJSON(),\n key: this.key,\n }\n }\n}\n\n/**\n * The type of measurement for size constraint issues.\n *\n * - `'array'` - Array length\n * - `'string'` - String length in characters\n * - `'integer'` - Numeric value\n * - `'grapheme'` - String length in grapheme clusters\n * - `'bytes'` - Byte length\n * - `'blob'` - Blob size\n */\nexport type MeasurableType =\n | 'array'\n | 'string'\n | 'integer'\n | 'grapheme'\n | 'bytes'\n | 'blob'\n\n/**\n * Issue for values that exceed a maximum constraint.\n */\nexport class IssueTooBig extends Issue {\n constructor(\n path: readonly PropertyKey[],\n input: unknown,\n readonly maximum: number,\n readonly type: MeasurableType,\n readonly actual: number,\n ) {\n super('too_big', path, input)\n }\n\n override get message(): string {\n return `${this.type} too big (maximum ${this.maximum}, got ${this.actual})`\n }\n\n toJSON() {\n return {\n ...super.toJSON(),\n type: this.type,\n maximum: this.maximum,\n }\n }\n}\n\n/**\n * Issue for values that are below a minimum constraint.\n */\nexport class IssueTooSmall extends Issue {\n constructor(\n path: readonly PropertyKey[],\n input: unknown,\n readonly minimum: number,\n readonly type: MeasurableType,\n readonly actual: number,\n ) {\n super('too_small', path, input)\n }\n\n override get message(): string {\n return `${this.type} too small (minimum ${this.minimum}, got ${this.actual})`\n }\n\n toJSON() {\n return {\n ...super.toJSON(),\n type: this.type,\n minimum: this.minimum,\n }\n }\n}\n\n// -----------------------------------------------------------------------------\n// Helper functions for formatting error messages\n// -----------------------------------------------------------------------------\n\nfunction stringifyExpectedType(expected: string): string {\n if (expected === '$typed') {\n return 'an object which includes the \"$type\" property'\n }\n return expected\n}\n\nfunction stringifyPath(path: readonly PropertyKey[]) {\n return ` at ${buildJsonPath(path)}`\n}\n\nfunction buildJsonPath(path: readonly PropertyKey[]): string {\n return `$${path.map(toJsonPathSegment).join('')}`\n}\n\nfunction toJsonPathSegment(segment: PropertyKey): string {\n if (typeof segment === 'number' || typeof segment === 'symbol') {\n return `[${String(segment)}]`\n } else if (/^[a-zA-Z_$][a-zA-Z0-9_]*$/.test(segment)) {\n return `.${segment}`\n } else {\n return `[${JSON.stringify(segment)}]`\n }\n}\n\nfunction oneOf(arr: readonly string[]): string {\n if (arr.length === 0) return ''\n if (arr.length === 1) return arr[0]\n return `one of ${arr.slice(0, -1).join(', ')} or ${arr.at(-1)}`\n}\n\nfunction stringifyValue(value: unknown): string {\n switch (typeof value) {\n case 'bigint':\n return `${value}n`\n case 'number':\n case 'boolean':\n return String(value)\n case 'string':\n return JSON.stringify(\n value.length < STRING_PREVIEW_MAX_LENGTH\n ? value\n : `${value.slice(0, STRING_PREVIEW_MAX_LENGTH - STRING_PREVIEW_TRUNCATED_SUFFIX.length)}${STRING_PREVIEW_TRUNCATED_SUFFIX}`,\n )\n case 'object':\n if (value === null) return 'null'\n if (Array.isArray(value)) {\n return `[${stringifyArray(value, stringifyValue)}]`\n }\n if (isPlainObject(value)) {\n return `{${stringifyArray(Object.entries(value), stringifyObjectEntry)}}`\n }\n if (ifCid(value)) return 'cid'\n if (isLegacyBlobRef(value)) return 'legacy-blob'\n if (value instanceof Date) return 'date'\n if (value instanceof RegExp) return 'regexp'\n if (value instanceof Map) return 'map'\n if (value instanceof Set) return 'set'\n return 'object'\n default:\n return typeof value\n }\n}\n\n/*@__NO_SIDE_EFFECTS__*/\nfunction stringifyObjectEntry([key, _value]: [PropertyKey, unknown]): string {\n return `${JSON.stringify(key)}: ...`\n}\n\n/*@__NO_SIDE_EFFECTS__*/\nfunction stringifyArray<T>(\n arr: readonly T[],\n fn: (item: T) => string,\n n = 2,\n): string {\n return arr.slice(0, n).map(fn).join(', ') + (arr.length > n ? ', ...' : '')\n}\n"]}
|
package/dist/core/validator.js
CHANGED
|
@@ -1,10 +1,7 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.ValidationContext = void 0;
|
|
4
1
|
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
2
|
+
import { success } from './result.js';
|
|
3
|
+
import { LexValidationError } from './validation-error.js';
|
|
4
|
+
import { IssueInvalidFormat, IssueInvalidType, IssueInvalidValue, IssueRequiredKey, IssueTooBig, IssueTooSmall, } from './validation-issue.js';
|
|
8
5
|
/**
|
|
9
6
|
* Manages the state and context for validation operations.
|
|
10
7
|
*
|
|
@@ -33,8 +30,7 @@ const validation_issue_js_1 = require("./validation-issue.js");
|
|
|
33
30
|
* }
|
|
34
31
|
* ```
|
|
35
32
|
*/
|
|
36
|
-
class ValidationContext {
|
|
37
|
-
options;
|
|
33
|
+
export class ValidationContext {
|
|
38
34
|
static validate(input, validator, options) {
|
|
39
35
|
const context = new ValidationContext({
|
|
40
36
|
path: options?.path ?? [],
|
|
@@ -43,14 +39,6 @@ class ValidationContext {
|
|
|
43
39
|
});
|
|
44
40
|
return context.validate(input, validator);
|
|
45
41
|
}
|
|
46
|
-
/**
|
|
47
|
-
* The current path being validated, used for error reporting.
|
|
48
|
-
*/
|
|
49
|
-
currentPath;
|
|
50
|
-
/**
|
|
51
|
-
* Accumulated validation issues collected during traversal.
|
|
52
|
-
*/
|
|
53
|
-
issues = [];
|
|
54
42
|
/**
|
|
55
43
|
* Creates a new validation context with the specified options.
|
|
56
44
|
*
|
|
@@ -58,6 +46,10 @@ class ValidationContext {
|
|
|
58
46
|
*/
|
|
59
47
|
constructor(options) {
|
|
60
48
|
this.options = options;
|
|
49
|
+
/**
|
|
50
|
+
* Accumulated validation issues collected during traversal.
|
|
51
|
+
*/
|
|
52
|
+
this.issues = [];
|
|
61
53
|
// Create a copy because we will be mutating the array during validation.
|
|
62
54
|
this.currentPath = Array.from(options.path);
|
|
63
55
|
}
|
|
@@ -100,7 +92,7 @@ class ValidationContext {
|
|
|
100
92
|
if (this.issues.length > 0) {
|
|
101
93
|
// Validator returned a success but issues were added via the context.
|
|
102
94
|
// This means the overall validation failed.
|
|
103
|
-
return new
|
|
95
|
+
return new LexValidationError(Array.from(this.issues));
|
|
104
96
|
}
|
|
105
97
|
if (this.options.mode !== 'parse' && !Object.is(result.value, input)) {
|
|
106
98
|
// If the value changed, it means that a default (or some other
|
|
@@ -179,7 +171,7 @@ class ValidationContext {
|
|
|
179
171
|
* @returns A successful validation result
|
|
180
172
|
*/
|
|
181
173
|
success(value) {
|
|
182
|
-
return
|
|
174
|
+
return success(value);
|
|
183
175
|
}
|
|
184
176
|
/**
|
|
185
177
|
* Creates a failed validation result with the given error.
|
|
@@ -199,7 +191,7 @@ class ValidationContext {
|
|
|
199
191
|
* @returns A failed validation result
|
|
200
192
|
*/
|
|
201
193
|
issue(issue) {
|
|
202
|
-
return this.failure(new
|
|
194
|
+
return this.failure(new LexValidationError([...this.issues, issue]));
|
|
203
195
|
}
|
|
204
196
|
/**
|
|
205
197
|
* Creates a failure for an invalid value that doesn't match expected values.
|
|
@@ -209,7 +201,7 @@ class ValidationContext {
|
|
|
209
201
|
* @returns A failed validation result with an invalid value issue
|
|
210
202
|
*/
|
|
211
203
|
issueInvalidValue(input, values) {
|
|
212
|
-
return this.issue(new
|
|
204
|
+
return this.issue(new IssueInvalidValue(this.path, input, values));
|
|
213
205
|
}
|
|
214
206
|
/**
|
|
215
207
|
* Creates a failure for an invalid type.
|
|
@@ -219,7 +211,7 @@ class ValidationContext {
|
|
|
219
211
|
* @returns A failed validation result with an invalid type issue
|
|
220
212
|
*/
|
|
221
213
|
issueInvalidType(input, expected) {
|
|
222
|
-
return this.issue(new
|
|
214
|
+
return this.issue(new IssueInvalidType(this.path, input, expected));
|
|
223
215
|
}
|
|
224
216
|
/**
|
|
225
217
|
* Creates a failure for an invalid type.
|
|
@@ -239,7 +231,7 @@ class ValidationContext {
|
|
|
239
231
|
* @returns A failed validation result with a required key issue
|
|
240
232
|
*/
|
|
241
233
|
issueRequiredKey(input, key) {
|
|
242
|
-
return this.issue(new
|
|
234
|
+
return this.issue(new IssueRequiredKey(this.path, input, key));
|
|
243
235
|
}
|
|
244
236
|
/**
|
|
245
237
|
* Creates a failure for an invalid string format.
|
|
@@ -250,7 +242,7 @@ class ValidationContext {
|
|
|
250
242
|
* @returns A failed validation result with an invalid format issue
|
|
251
243
|
*/
|
|
252
244
|
issueInvalidFormat(input, format, msg) {
|
|
253
|
-
return this.issue(new
|
|
245
|
+
return this.issue(new IssueInvalidFormat(this.path, input, format, msg));
|
|
254
246
|
}
|
|
255
247
|
/**
|
|
256
248
|
* Creates a failure for a value that exceeds a maximum constraint.
|
|
@@ -262,7 +254,7 @@ class ValidationContext {
|
|
|
262
254
|
* @returns A failed validation result with a too big issue
|
|
263
255
|
*/
|
|
264
256
|
issueTooBig(input, type, max, actual) {
|
|
265
|
-
return this.issue(new
|
|
257
|
+
return this.issue(new IssueTooBig(this.path, input, max, type, actual));
|
|
266
258
|
}
|
|
267
259
|
/**
|
|
268
260
|
* Creates a failure for a value that is below a minimum constraint.
|
|
@@ -274,7 +266,7 @@ class ValidationContext {
|
|
|
274
266
|
* @returns A failed validation result with a too small issue
|
|
275
267
|
*/
|
|
276
268
|
issueTooSmall(input, type, min, actual) {
|
|
277
|
-
return this.issue(new
|
|
269
|
+
return this.issue(new IssueTooSmall(this.path, input, min, type, actual));
|
|
278
270
|
}
|
|
279
271
|
/**
|
|
280
272
|
* Creates a failure for an invalid property value within an object.
|
|
@@ -291,7 +283,7 @@ class ValidationContext {
|
|
|
291
283
|
issueInvalidPropertyValue(input, property, values) {
|
|
292
284
|
const value = input[property];
|
|
293
285
|
const path = this.concatPath(property);
|
|
294
|
-
return this.issue(new
|
|
286
|
+
return this.issue(new IssueInvalidValue(path, value, values));
|
|
295
287
|
}
|
|
296
288
|
/**
|
|
297
289
|
* Creates a failure for an invalid property type within an object.
|
|
@@ -308,8 +300,7 @@ class ValidationContext {
|
|
|
308
300
|
issueInvalidPropertyType(input, property, expected) {
|
|
309
301
|
const value = input[property];
|
|
310
302
|
const path = this.concatPath(property);
|
|
311
|
-
return this.issue(new
|
|
303
|
+
return this.issue(new IssueInvalidType(path, value, [expected]));
|
|
312
304
|
}
|
|
313
305
|
}
|
|
314
|
-
exports.ValidationContext = ValidationContext;
|
|
315
306
|
//# sourceMappingURL=validator.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"validator.js","source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sourcesContent":["// eslint-disable-next-line @typescript-eslint/no-unused-vars\nimport { ResultFailure, ResultSuccess, success } from './result.js'\nimport { LexValidationError } from './validation-error.js'\nimport {\n Issue,\n IssueInvalidFormat,\n IssueInvalidType,\n IssueInvalidValue,\n IssueRequiredKey,\n IssueTooBig,\n IssueTooSmall,\n MeasurableType,\n} from './validation-issue.js'\n\n/**\n * Represents a successful validation result.\n *\n * @typeParam Value - The type of the validated value\n */\nexport type ValidationSuccess<Value = unknown> = ResultSuccess<Value>\n\n/**\n * Represents a failed validation result containing a {@link LexValidationError}.\n *\n * @extends ResultFailure<LexValidationError>\n * @see {@link ResultFailure}\n * @see {@link LexValidationError}\n */\nexport type ValidationFailure = LexValidationError\n\n/**\n * Discriminated union representing the outcome of a validation operation.\n *\n * Check the `success` property to determine if validation passed or failed:\n * - If `success` is `true`, the `value` property contains the validated data\n * - If `success` is `false`, the `reason` property contains the {@link LexValidationError}\n *\n * @typeParam Value - The type of the validated value on success\n *\n * @example\n * ```typescript\n * const result: ValidationResult<string> = schema.safeParse(data)\n * if (result.success) {\n * // result.value is string\n * } else {\n * // result.reason is LexValidationError\n * }\n * ```\n */\nexport type ValidationResult<Value = unknown> =\n | ValidationSuccess<Value>\n | ValidationFailure\n\n/**\n * Extracts the input type that a validator accepts.\n *\n * Use this utility type to infer what type a schema will accept during validation.\n *\n * @typeParam V - A validator type\n *\n * @example\n * ```typescript\n * const userSchema = new ObjectSchema({ name: stringSchema, age: numberSchema })\n * type UserInput = InferInput<typeof userSchema>\n * // { name: string; age: number }\n * ```\n */\nexport type InferInput<V extends Validator> = V['__lex']['input']\n\n/**\n * Extracts the output type that a validator produces after parsing.\n *\n * The output type may differ from the input type when the schema applies\n * transformations such as default values or type coercion during parsing.\n *\n * @typeParam V - A validator type\n *\n * @example\n * ```typescript\n * const schema = new StringSchema().default('hello')\n * type Input = InferInput<typeof schema> // string | undefined\n * type Output = InferOutput<typeof schema> // string\n * ```\n */\nexport type InferOutput<V extends Validator> = V['__lex']['output']\n\n/**\n * Alias for {@link InferInput} for convenient type inference.\n *\n * @typeParam V - A validator type\n */\nexport type { InferInput as Infer }\n\nexport interface Validator<TInput = unknown, TOutput = TInput> {\n /**\n * This property is used for type inference purposes and does not actually\n * exist at runtime.\n *\n * @internal\n * @deprecated **INTERNAL API, DO NOT USE**.\n */\n readonly ['__lex']: {\n input: TInput\n output: TOutput\n }\n\n /**\n * @internal **INTERNAL API**: use {@link ValidationContext.validate} instead\n *\n * This method is implemented by subclasses to perform transformation and\n * validation of the input value. Do not call this method directly; as the\n * {@link ValidationContext.options.mode} option will **not** be enforced. See\n * {@link ValidationContext.validate} for details. When delegating validation\n * from one validator sub-class implementation to another schema,\n * {@link ValidationContext.validate} must be used instead of calling\n * {@link Validator.validateInContext}. This will allow to stop the validation\n * process if the value was transformed (by the other schema) but\n * transformations are not allowed.\n *\n * By convention, the {@link ValidationResult} must return the original input\n * value if validation was successful and no transformation was applied (i.e.\n * the input already conformed to the schema). If a default value, or any\n * other transformation was applied, the returned value can be different from\n * the input.\n *\n * This convention allows the {@link Validator.check check} and\n * {@link Validator.assert assert} methods to check whether the input value\n * exactly matches the schema (without defaults or transformations), by\n * checking if the returned value is strictly equal to the input.\n *\n * @see {@link ValidationContext.validate}\n */\n validateInContext(input: unknown, ctx: ValidationContext): ValidationResult\n}\n\n/**\n * Configuration options for validation and parsing operations.\n *\n * @example\n * ```typescript\n * // Validate mode (strict, no transformations)\n * ValidationContext.validate(data, schema, { mode: 'validate' })\n *\n * // Parse mode (allows transformations like defaults)\n * ValidationContext.validate(data, schema, { mode: 'parse' })\n *\n * // With initial path for nested validation\n * ValidationContext.validate(data, schema, { path: ['user', 'profile'] })\n * ```\n */\nexport type ValidationOptions = {\n /**\n * The validation mode determining how transformations are handled.\n *\n * - `\"validate\"`: Strict validation where the result must be\n * strictly equal to the input value. No transformations such as applying\n * default values are allowed.\n * - `\"parse\"`: Allows the schema to transform the input value, such as\n * applying default values or performing type coercion.\n *\n * @default \"validate\"\n */\n mode?: 'validate' | 'parse'\n\n /**\n * The initial path to the value being validated.\n *\n * This is used to provide context in validation issues when validating\n * nested structures. The path is prepended to all issue paths.\n *\n * @example\n * ```typescript\n * // Issues will be reported at paths like \"user.name\" instead of just \"name\"\n * ValidationContext.validate(data, schema, { path: ['user'] })\n * ```\n */\n path?: readonly PropertyKey[]\n\n /**\n * Whether to enforce strict validation rules (e.g., MIME type matching, size\n * limits, datetime format).\n *\n * This is typically useful to allow more lax validation when parsing server\n * responses, while enforcing strict validation for user input.\n *\n * @default true\n */\n strict?: boolean\n}\n\n/**\n * Manages the state and context for validation operations.\n *\n * The `ValidationContext` class is responsible for:\n * - Tracking the current path in nested structures for error reporting\n * - Collecting validation issues during traversal\n * - Enforcing validation mode (validate vs parse)\n * - Providing factory methods for creating validation results\n *\n * Use the static {@link ValidationContext.validate} method as the primary entry point\n * for validation. This ensures proper mode enforcement and issue aggregation.\n *\n * @example\n * ```typescript\n * // Primary usage via static method\n * const result = ValidationContext.validate(data, schema, { mode: 'parse' })\n *\n * // Within a custom validator implementation\n * class MyValidator implements Validator {\n * validateInContext(input: unknown, ctx: ValidationContext): ValidationResult {\n * if (typeof input !== 'string') {\n * return ctx.issueUnexpectedType(input, 'string')\n * }\n * return ctx.success(input)\n * }\n * }\n * ```\n */\nexport class ValidationContext {\n /**\n * Validates input against a validator in parse mode.\n *\n * In parse mode, the schema may transform the input (e.g., apply defaults).\n *\n * @param input - The value to validate\n * @param validator - The validator to use\n * @param options - Validation options with mode set to 'parse'\n * @returns A validation result with the parsed output type\n */\n static validate<V extends Validator>(\n input: unknown,\n validator: V,\n options: ValidationOptions & {\n mode: 'parse'\n },\n ): ValidationResult<InferOutput<V>>\n\n /**\n * Validates input against a validator in validate mode (default).\n *\n * In validate mode, the result must be strictly equal to the input.\n * No transformations are allowed.\n *\n * @typeParam V - The validator type\n * @typeParam I - The input type\n * @param input - The value to validate\n * @param validator - The validator to use\n * @param options - Optional validation options (defaults to validate mode)\n * @returns A validation result preserving the input type intersected with the schema type\n */\n static validate<V extends Validator, I = unknown>(\n input: I,\n validator: V,\n options?: ValidationOptions & {\n mode?: 'validate'\n },\n ): ValidationResult<I & InferInput<V>>\n\n /**\n * Validates input against a validator with configurable options.\n *\n * @param input - The value to validate\n * @param validator - The validator to use\n * @param options - Optional validation options\n * @returns A validation result with either the input or output type\n */\n static validate<V extends Validator>(\n input: unknown,\n validator: V,\n options?: ValidationOptions,\n ): ValidationResult<InferOutput<V> | InferInput<V>>\n static validate<V extends Validator>(\n input: unknown,\n validator: V,\n options?: ValidationOptions,\n ): ValidationResult<InferOutput<V> | InferInput<V>> {\n const context = new ValidationContext({\n path: options?.path ?? [],\n mode: options?.mode ?? 'validate',\n strict: options?.strict ?? true,\n })\n return context.validate(input, validator)\n }\n\n /**\n * The current path being validated, used for error reporting.\n */\n protected readonly currentPath: PropertyKey[]\n\n /**\n * Accumulated validation issues collected during traversal.\n */\n protected readonly issues: Issue[] = []\n\n /**\n * Creates a new validation context with the specified options.\n *\n * @param options - The validation options (path and mode are required)\n */\n constructor(readonly options: Required<ValidationOptions>) {\n // Create a copy because we will be mutating the array during validation.\n this.currentPath = Array.from(options.path)\n }\n\n /**\n * Returns a copy of the current validation path.\n *\n * The path represents the location in the data structure being validated,\n * used for constructing meaningful error messages.\n */\n get path() {\n return Array.from(this.currentPath)\n }\n\n /**\n * Creates a new path by appending segments to the current path.\n *\n * @param path - Optional path segment(s) to append\n * @returns A new path array with the segment(s) appended\n */\n concatPath(path?: PropertyKey | readonly PropertyKey[]) {\n if (path == null) return this.path\n return this.currentPath.concat(path)\n }\n\n /**\n * Validates input against a validator within this context.\n *\n * This is the primary entry point for validation within a context. Always use\n * this method instead of calling {@link Validator.validateInContext} directly,\n * as this method enforces validation mode rules and handles transformation detection.\n *\n * @typeParam V - The validator type\n * @param input - The value to validate\n * @param validator - The validator to use\n * @returns A validation result with the validated value or error\n */\n validate<V extends Validator>(\n input: unknown,\n validator: V,\n ): ValidationResult<InferInput<V>> {\n // This is the only place where validateInContext should be called.\n const result = validator.validateInContext(input, this)\n\n if (result.success) {\n if (this.issues.length > 0) {\n // Validator returned a success but issues were added via the context.\n // This means the overall validation failed.\n return new LexValidationError(Array.from(this.issues))\n }\n\n if (this.options.mode !== 'parse' && !Object.is(result.value, input)) {\n // If the value changed, it means that a default (or some other\n // transformation) was applied, meaning that the original value did\n // *not* match the (output) schema. When not in \"parse\" mode, we\n // consider this a failure.\n\n // This check is the reason why Validator.validateInContext should not\n // be used directly, and ValidatorContext.validate should be used\n // instead, even when delegating validation from one validator to\n // another.\n\n // This if block comes before the next one because 'this.issues' will\n // end-up being appended to the returned LexValidationError (see the\n // \"failure\" method below), resulting in a more complete error report.\n return this.issueInvalidValue(input, [result.value])\n }\n }\n\n return result as ValidationResult<InferInput<V>>\n }\n\n /**\n * Validates a child property of an object within this context.\n *\n * This method automatically manages the path stack, pushing the property key\n * before validation and popping it afterward. Use this for validating object\n * properties to ensure proper path tracking in error messages.\n *\n * @typeParam I - The input object type\n * @typeParam K - The property key type\n * @typeParam V - The validator type\n * @param input - The parent object containing the property\n * @param key - The property key to validate\n * @param validator - The validator to use for the property value\n * @returns A validation result for the property value\n *\n * @example\n * ```typescript\n * // In a custom object validator\n * const result = ctx.validateChild(input, 'name', stringSchema)\n * // If validation fails, error path will include 'name'\n * ```\n */\n validateChild<\n I extends object,\n K extends PropertyKey & keyof I,\n V extends Validator,\n >(input: I, key: K, validator: V): ValidationResult<InferInput<V>> {\n // @NOTE we could add support for recursive schemas by keeping track of\n // \"parent\" objects in the context and checking for circular references\n // here. This would allow us to validate recursive structures without\n // hitting maximum call stack errors, and would also allow us to provide\n // better error messages for circular reference issues. However, this is not\n // a priority at the moment as recursive structures are not supported in\n // the context of AT Protocol lexicons, and we can always add this in the\n // future if needed.\n\n // Instead of creating a new context, we just push/pop the path segment.\n this.currentPath.push(key)\n try {\n return this.validate(input[key], validator)\n } finally {\n this.currentPath.length--\n }\n }\n\n /**\n * Adds a validation issue to the context without immediately failing.\n *\n * Use this method to collect multiple issues during validation before\n * determining the final result. Issues added this way will be included\n * in the final error if validation fails.\n *\n * @param issue - The validation issue to add\n */\n addIssue(issue: Issue): void {\n this.issues.push(issue)\n }\n\n /**\n * Creates a successful validation result with the given value.\n *\n * @typeParam V - The value type\n * @param value - The validated value\n * @returns A successful validation result\n */\n success<V>(value: V): ValidationResult<V> {\n return success(value)\n }\n\n /**\n * Creates a failed validation result with the given error.\n *\n * @param reason - The validation error\n * @returns A failed validation result\n */\n failure(reason: LexValidationError): ValidationFailure {\n return reason\n }\n\n /**\n * Creates a failed validation result from a single issue.\n *\n * Any previously accumulated issues in the context are included in the error.\n *\n * @param issue - The validation issue that caused the failure\n * @returns A failed validation result\n */\n issue(issue: Issue) {\n return this.failure(new LexValidationError([...this.issues, issue]))\n }\n\n /**\n * Creates a failure for an invalid value that doesn't match expected values.\n *\n * @param input - The actual value that was received\n * @param values - The expected valid values\n * @returns A failed validation result with an invalid value issue\n */\n issueInvalidValue(input: unknown, values: readonly unknown[]) {\n return this.issue(new IssueInvalidValue(this.path, input, values))\n }\n\n /**\n * Creates a failure for an invalid type.\n *\n * @param input - The actual value that was received\n * @param expected - An array of expected type names\n * @returns A failed validation result with an invalid type issue\n */\n issueInvalidType(input: unknown, expected: readonly string[]) {\n return this.issue(new IssueInvalidType(this.path, input, expected))\n }\n\n /**\n * Creates a failure for an invalid type.\n *\n * @param input - The actual value that was received\n * @param expected - The expected type name\n * @returns A failed validation result with an invalid type issue\n */\n issueUnexpectedType(input: unknown, expected: string) {\n return this.issueInvalidType(input, [expected])\n }\n\n /**\n * Creates a failure for a missing required key in an object.\n *\n * @param input - The object missing the required key\n * @param key - The name of the required key\n * @returns A failed validation result with a required key issue\n */\n issueRequiredKey(input: object, key: PropertyKey) {\n return this.issue(new IssueRequiredKey(this.path, input, key))\n }\n\n /**\n * Creates a failure for an invalid string format.\n *\n * @param input - The actual value that was received\n * @param format - The expected format name (e.g., 'did', 'handle', 'uri')\n * @param msg - Optional additional message describing the format error\n * @returns A failed validation result with an invalid format issue\n */\n issueInvalidFormat(input: unknown, format: string, msg?: string) {\n return this.issue(new IssueInvalidFormat(this.path, input, format, msg))\n }\n\n /**\n * Creates a failure for a value that exceeds a maximum constraint.\n *\n * @param input - The actual value that was received\n * @param type - The type of measurement (e.g., 'string', 'array', 'bytes')\n * @param max - The maximum allowed value\n * @param actual - The actual measured value\n * @returns A failed validation result with a too big issue\n */\n issueTooBig(\n input: unknown,\n type: MeasurableType,\n max: number,\n actual: number,\n ) {\n return this.issue(new IssueTooBig(this.path, input, max, type, actual))\n }\n\n /**\n * Creates a failure for a value that is below a minimum constraint.\n *\n * @param input - The actual value that was received\n * @param type - The type of measurement (e.g., 'string', 'array', 'bytes')\n * @param min - The minimum required value\n * @param actual - The actual measured value\n * @returns A failed validation result with a too small issue\n */\n issueTooSmall(\n input: unknown,\n type: MeasurableType,\n min: number,\n actual: number,\n ) {\n return this.issue(new IssueTooSmall(this.path, input, min, type, actual))\n }\n\n /**\n * Creates a failure for an invalid property value within an object.\n *\n * This is a convenience method that automatically extracts the property value\n * and constructs the appropriate path.\n *\n * @typeParam I - The input object type\n * @param input - The object containing the invalid property\n * @param property - The property key with the invalid value\n * @param values - The expected valid values\n * @returns A failed validation result with an invalid value issue at the property path\n */\n issueInvalidPropertyValue<I>(\n input: I,\n property: keyof I & PropertyKey,\n values: readonly unknown[],\n ) {\n const value = input[property]\n const path = this.concatPath(property)\n return this.issue(new IssueInvalidValue(path, value, values))\n }\n\n /**\n * Creates a failure for an invalid property type within an object.\n *\n * This is a convenience method that automatically extracts the property value\n * and constructs the appropriate path.\n *\n * @typeParam I - The input object type\n * @param input - The object containing the invalid property\n * @param property - The property key with the invalid type\n * @param expected - The expected type name\n * @returns A failed validation result with an invalid type issue at the property path\n */\n issueInvalidPropertyType<I>(\n input: I,\n property: keyof I & PropertyKey,\n expected: string,\n ) {\n const value = input[property]\n const path = this.concatPath(property)\n return this.issue(new IssueInvalidType(path, value, [expected]))\n }\n}\n\n/**\n * Recursively unwraps a wrapped validator to its innermost validator type.\n *\n * Some validators wrap other validators (e.g., optional, nullable). This type\n * utility recursively unwraps such wrappers to reveal the core validator.\n *\n * @typeParam T - A validator type, possibly wrapped\n *\n * @example\n * ```typescript\n * type Inner = UnwrapValidator<OptionalValidator<NullableValidator<StringSchema>>>\n * // Result: StringSchema\n * ```\n */\nexport type UnwrapValidator<T extends Validator> = T extends {\n unwrap(): infer U extends Validator\n}\n ? UnwrapValidator<U>\n : T\n\n/**\n * Interface for validators that wrap another validator.\n *\n * Implement this interface when creating validators that wrap or modify\n * the behavior of another validator (e.g., optional, nullable, transform).\n *\n * @typeParam Validator - The type of the wrapped validator\n *\n * @example\n * ```typescript\n * class OptionalSchema<V extends Validator> implements WrappedValidator<V> {\n * constructor(private inner: V) {}\n *\n * unwrap(): V {\n * return this.inner\n * }\n * }\n * ```\n */\nexport interface WrappedValidator<out Validator> {\n /**\n * Returns the inner wrapped validator.\n *\n * @returns The wrapped validator\n */\n unwrap(): Validator\n}\n"]}
|
|
1
|
+
{"version":3,"file":"validator.js","sourceRoot":"","sources":["../../src/core/validator.ts"],"names":[],"mappings":"AAAA,6DAA6D;AAC7D,OAAO,EAAgC,OAAO,EAAE,MAAM,aAAa,CAAA;AACnE,OAAO,EAAE,kBAAkB,EAAE,MAAM,uBAAuB,CAAA;AAC1D,OAAO,EAEL,kBAAkB,EAClB,gBAAgB,EAChB,iBAAiB,EACjB,gBAAgB,EAChB,WAAW,EACX,aAAa,GAEd,MAAM,uBAAuB,CAAA;AAkL9B;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AACH,MAAM,OAAO,iBAAiB;IAqD5B,MAAM,CAAC,QAAQ,CACb,KAAc,EACd,SAAY,EACZ,OAA2B;QAE3B,MAAM,OAAO,GAAG,IAAI,iBAAiB,CAAC;YACpC,IAAI,EAAE,OAAO,EAAE,IAAI,IAAI,EAAE;YACzB,IAAI,EAAE,OAAO,EAAE,IA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AAc;QAEd,OAAO,IAAI,CAAC,KAAK,CAAC,IAAI,aAAa,CAAC,IAAI,CAAC,IAAI,EAAE,KAAK,EAAE,GAAG,EAAE,IAAI,EAAE,MAAM,CAAC,CAAC,CAAA;IAC3E,CAAC;IAED;;;;;;;;;;;OAWG;IACH,yBAAyB,CACvB,KAAQ,EACR,QAA+B,EAC/B,MAA0B;QAE1B,MAAM,KAAK,GAAG,KAAK,CAAC,QAAQ,CAAC,CAAA;QAC7B,MAAM,IAAI,GAAG,IAAI,CAAC,UAAU,CAAC,QAAQ,CAAC,CAAA;QACtC,OAAO,IAAI,CAAC,KAAK,CAAC,IAAI,iBAAiB,CAAC,IAAI,EAAE,KAAK,EAAE,MAAM,CAAC,CAAC,CAAA;IAC/D,CAAC;IAED;;;;;;;;;;;OAWG;IACH,wBAAwB,CACtB,KAAQ,EACR,QAA+B,EAC/B,QAAgB;QAEhB,MAAM,KAAK,GAAG,KAAK,CAAC,QAAQ,CAAC,CAAA;QAC7B,MAAM,IAAI,GAAG,IAAI,CAAC,UAAU,CAAC,QAAQ,CAAC,CAAA;QACtC,OAAO,IAAI,CAAC,KAAK,CAAC,IAAI,gBAAgB,CAAC,IAAI,EAAE,KAAK,EAAE,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAA;IAClE,CAAC;CACF","sourcesContent":["// eslint-disable-next-line @typescript-eslint/no-unused-vars\nimport { ResultFailure, ResultSuccess, success } from './result.js'\nimport { LexValidationError } from './validation-error.js'\nimport {\n Issue,\n IssueInvalidFormat,\n IssueInvalidType,\n IssueInvalidValue,\n IssueRequiredKey,\n IssueTooBig,\n IssueTooSmall,\n MeasurableType,\n} from './validation-issue.js'\n\n/**\n * Represents a successful validation result.\n *\n * @typeParam Value - The type of the validated value\n */\nexport type ValidationSuccess<Value = unknown> = ResultSuccess<Value>\n\n/**\n * Represents a failed validation result containing a {@link LexValidationError}.\n *\n * @extends ResultFailure<LexValidationError>\n * @see {@link ResultFailure}\n * @see {@link LexValidationError}\n */\nexport type ValidationFailure = LexValidationError\n\n/**\n * Discriminated union representing the outcome of a validation operation.\n *\n * Check the `success` property to determine if validation passed or failed:\n * - If `success` is `true`, the `value` property contains the validated data\n * - If `success` is `false`, the `reason` property contains the {@link LexValidationError}\n *\n * @typeParam Value - The type of the validated value on success\n *\n * @example\n * ```typescript\n * const result: ValidationResult<string> = schema.safeParse(data)\n * if (result.success) {\n * // result.value is string\n * } else {\n * // result.reason is LexValidationError\n * }\n * ```\n */\nexport type ValidationResult<Value = unknown> =\n | ValidationSuccess<Value>\n | ValidationFailure\n\n/**\n * Extracts the input type that a validator accepts.\n *\n * Use this utility type to infer what type a schema will accept during validation.\n *\n * @typeParam V - A validator type\n *\n * @example\n * ```typescript\n * const userSchema = new ObjectSchema({ name: stringSchema, age: numberSchema })\n * type UserInput = InferInput<typeof userSchema>\n * // { name: string; age: number }\n * ```\n */\nexport type InferInput<V extends Validator> = V['__lex']['input']\n\n/**\n * Extracts the output type that a validator produces after parsing.\n *\n * The output type may differ from the input type when the schema applies\n * transformations such as default values or type coercion during parsing.\n *\n * @typeParam V - A validator type\n *\n * @example\n * ```typescript\n * const schema = new StringSchema().default('hello')\n * type Input = InferInput<typeof schema> // string | undefined\n * type Output = InferOutput<typeof schema> // string\n * ```\n */\nexport type InferOutput<V extends Validator> = V['__lex']['output']\n\n/**\n * Alias for {@link InferInput} for convenient type inference.\n *\n * @typeParam V - A validator type\n */\nexport type { InferInput as Infer }\n\nexport interface Validator<TInput = unknown, TOutput = TInput> {\n /**\n * This property is used for type inference purposes and does not actually\n * exist at runtime.\n *\n * @internal\n * @deprecated **INTERNAL API, DO NOT USE**.\n */\n readonly ['__lex']: {\n input: TInput\n output: TOutput\n }\n\n /**\n * @internal **INTERNAL API**: use {@link ValidationContext.validate} instead\n *\n * This method is implemented by subclasses to perform transformation and\n * validation of the input value. Do not call this method directly; as the\n * {@link ValidationContext.options.mode} option will **not** be enforced. See\n * {@link ValidationContext.validate} for details. When delegating validation\n * from one validator sub-class implementation to another schema,\n * {@link ValidationContext.validate} must be used instead of calling\n * {@link Validator.validateInContext}. This will allow to stop the validation\n * process if the value was transformed (by the other schema) but\n * transformations are not allowed.\n *\n * By convention, the {@link ValidationResult} must return the original input\n * value if validation was successful and no transformation was applied (i.e.\n * the input already conformed to the schema). If a default value, or any\n * other transformation was applied, the returned value can be different from\n * the input.\n *\n * This convention allows the {@link Validator.check check} and\n * {@link Validator.assert assert} methods to check whether the input value\n * exactly matches the schema (without defaults or transformations), by\n * checking if the returned value is strictly equal to the input.\n *\n * @see {@link ValidationContext.validate}\n */\n validateInContext(input: unknown, ctx: ValidationContext): ValidationResult\n}\n\n/**\n * Configuration options for validation and parsing operations.\n *\n * @example\n * ```typescript\n * // Validate mode (strict, no transformations)\n * ValidationContext.validate(data, schema, { mode: 'validate' })\n *\n * // Parse mode (allows transformations like defaults)\n * ValidationContext.validate(data, schema, { mode: 'parse' })\n *\n * // With initial path for nested validation\n * ValidationContext.validate(data, schema, { path: ['user', 'profile'] })\n * ```\n */\nexport type ValidationOptions = {\n /**\n * The validation mode determining how transformations are handled.\n *\n * - `\"validate\"`: Strict validation where the result must be\n * strictly equal to the input value. No transformations such as applying\n * default values are allowed.\n * - `\"parse\"`: Allows the schema to transform the input value, such as\n * applying default values or performing type coercion.\n *\n * @default \"validate\"\n */\n mode?: 'validate' | 'parse'\n\n /**\n * The initial path to the value being validated.\n *\n * This is used to provide context in validation issues when validating\n * nested structures. The path is prepended to all issue paths.\n *\n * @example\n * ```typescript\n * // Issues will be reported at paths like \"user.name\" instead of just \"name\"\n * ValidationContext.validate(data, schema, { path: ['user'] })\n * ```\n */\n path?: readonly PropertyKey[]\n\n /**\n * Whether to enforce strict validation rules (e.g., MIME type matching, size\n * limits, datetime format).\n *\n * This is typically useful to allow more lax validation when parsing server\n * responses, while enforcing strict validation for user input.\n *\n * @default true\n */\n strict?: boolean\n}\n\n/**\n * Manages the state and context for validation operations.\n *\n * The `ValidationContext` class is responsible for:\n * - Tracking the current path in nested structures for error reporting\n * - Collecting validation issues during traversal\n * - Enforcing validation mode (validate vs parse)\n * - Providing factory methods for creating validation results\n *\n * Use the static {@link ValidationContext.validate} method as the primary entry point\n * for validation. This ensures proper mode enforcement and issue aggregation.\n *\n * @example\n * ```typescript\n * // Primary usage via static method\n * const result = ValidationContext.validate(data, schema, { mode: 'parse' })\n *\n * // Within a custom validator implementation\n * class MyValidator implements Validator {\n * validateInContext(input: unknown, ctx: ValidationContext): ValidationResult {\n * if (typeof input !== 'string') {\n * return ctx.issueUnexpectedType(input, 'string')\n * }\n * return ctx.success(input)\n * }\n * }\n * ```\n */\nexport class ValidationContext {\n /**\n * Validates input against a validator in parse mode.\n *\n * In parse mode, the schema may transform the input (e.g., apply defaults).\n *\n * @param input - The value to validate\n * @param validator - The validator to use\n * @param options - Validation options with mode set to 'parse'\n * @returns A validation result with the parsed output type\n */\n static validate<V extends Validator>(\n input: unknown,\n validator: V,\n options: ValidationOptions & {\n mode: 'parse'\n },\n ): ValidationResult<InferOutput<V>>\n\n /**\n * Validates input against a validator in validate mode (default).\n *\n * In validate mode, the result must be strictly equal to the input.\n * No transformations are allowed.\n *\n * @typeParam V - The validator type\n * @typeParam I - The input type\n * @param input - The value to validate\n * @param validator - The validator to use\n * @param options - Optional validation options (defaults to validate mode)\n * @returns A validation result preserving the input type intersected with the schema type\n */\n static validate<V extends Validator, I = unknown>(\n input: I,\n validator: V,\n options?: ValidationOptions & {\n mode?: 'validate'\n },\n ): ValidationResult<I & InferInput<V>>\n\n /**\n * Validates input against a validator with configurable options.\n *\n * @param input - The value to validate\n * @param validator - The validator to use\n * @param options - Optional validation options\n * @returns A validation result with either the input or output type\n */\n static validate<V extends Validator>(\n input: unknown,\n validator: V,\n options?: ValidationOptions,\n ): ValidationResult<InferOutput<V> | InferInput<V>>\n static validate<V extends Validator>(\n input: unknown,\n validator: V,\n options?: ValidationOptions,\n ): ValidationResult<InferOutput<V> | InferInput<V>> {\n const context = new ValidationContext({\n path: options?.path ?? [],\n mode: options?.mode ?? 'validate',\n strict: options?.strict ?? true,\n })\n return context.validate(input, validator)\n }\n\n /**\n * The current path being validated, used for error reporting.\n */\n protected readonly currentPath: PropertyKey[]\n\n /**\n * Accumulated validation issues collected during traversal.\n */\n protected readonly issues: Issue[] = []\n\n /**\n * Creates a new validation context with the specified options.\n *\n * @param options - The validation options (path and mode are required)\n */\n constructor(readonly options: Required<ValidationOptions>) {\n // Create a copy because we will be mutating the array during validation.\n this.currentPath = Array.from(options.path)\n }\n\n /**\n * Returns a copy of the current validation path.\n *\n * The path represents the location in the data structure being validated,\n * used for constructing meaningful error messages.\n */\n get path() {\n return Array.from(this.currentPath)\n }\n\n /**\n * Creates a new path by appending segments to the current path.\n *\n * @param path - Optional path segment(s) to append\n * @returns A new path array with the segment(s) appended\n */\n concatPath(path?: PropertyKey | readonly PropertyKey[]) {\n if (path == null) return this.path\n return this.currentPath.concat(path)\n }\n\n /**\n * Validates input against a validator within this context.\n *\n * This is the primary entry point for validation within a context. Always use\n * this method instead of calling {@link Validator.validateInContext} directly,\n * as this method enforces validation mode rules and handles transformation detection.\n *\n * @typeParam V - The validator type\n * @param input - The value to validate\n * @param validator - The validator to use\n * @returns A validation result with the validated value or error\n */\n validate<V extends Validator>(\n input: unknown,\n validator: V,\n ): ValidationResult<InferInput<V>> {\n // This is the only place where validateInContext should be called.\n const result = validator.validateInContext(input, this)\n\n if (result.success) {\n if (this.issues.length > 0) {\n // Validator returned a success but issues were added via the context.\n // This means the overall validation failed.\n return new LexValidationError(Array.from(this.issues))\n }\n\n if (this.options.mode !== 'parse' && !Object.is(result.value, input)) {\n // If the value changed, it means that a default (or some other\n // transformation) was applied, meaning that the original value did\n // *not* match the (output) schema. When not in \"parse\" mode, we\n // consider this a failure.\n\n // This check is the reason why Validator.validateInContext should not\n // be used directly, and ValidatorContext.validate should be used\n // instead, even when delegating validation from one validator to\n // another.\n\n // This if block comes before the next one because 'this.issues' will\n // end-up being appended to the returned LexValidationError (see the\n // \"failure\" method below), resulting in a more complete error report.\n return this.issueInvalidValue(input, [result.value])\n }\n }\n\n return result as ValidationResult<InferInput<V>>\n }\n\n /**\n * Validates a child property of an object within this context.\n *\n * This method automatically manages the path stack, pushing the property key\n * before validation and popping it afterward. Use this for validating object\n * properties to ensure proper path tracking in error messages.\n *\n * @typeParam I - The input object type\n * @typeParam K - The property key type\n * @typeParam V - The validator type\n * @param input - The parent object containing the property\n * @param key - The property key to validate\n * @param validator - The validator to use for the property value\n * @returns A validation result for the property value\n *\n * @example\n * ```typescript\n * // In a custom object validator\n * const result = ctx.validateChild(input, 'name', stringSchema)\n * // If validation fails, error path will include 'name'\n * ```\n */\n validateChild<\n I extends object,\n K extends PropertyKey & keyof I,\n V extends Validator,\n >(input: I, key: K, validator: V): ValidationResult<InferInput<V>> {\n // @NOTE we could add support for recursive schemas by keeping track of\n // \"parent\" objects in the context and checking for circular references\n // here. This would allow us to validate recursive structures without\n // hitting maximum call stack errors, and would also allow us to provide\n // better error messages for circular reference issues. However, this is not\n // a priority at the moment as recursive structures are not supported in\n // the context of AT Protocol lexicons, and we can always add this in the\n // future if needed.\n\n // Instead of creating a new context, we just push/pop the path segment.\n this.currentPath.push(key)\n try {\n return this.validate(input[key], validator)\n } finally {\n this.currentPath.length--\n }\n }\n\n /**\n * Adds a validation issue to the context without immediately failing.\n *\n * Use this method to collect multiple issues during validation before\n * determining the final result. Issues added this way will be included\n * in the final error if validation fails.\n *\n * @param issue - The validation issue to add\n */\n addIssue(issue: Issue): void {\n this.issues.push(issue)\n }\n\n /**\n * Creates a successful validation result with the given value.\n *\n * @typeParam V - The value type\n * @param value - The validated value\n * @returns A successful validation result\n */\n success<V>(value: V): ValidationResult<V> {\n return success(value)\n }\n\n /**\n * Creates a failed validation result with the given error.\n *\n * @param reason - The validation error\n * @returns A failed validation result\n */\n failure(reason: LexValidationError): ValidationFailure {\n return reason\n }\n\n /**\n * Creates a failed validation result from a single issue.\n *\n * Any previously accumulated issues in the context are included in the error.\n *\n * @param issue - The validation issue that caused the failure\n * @returns A failed validation result\n */\n issue(issue: Issue) {\n return this.failure(new LexValidationError([...this.issues, issue]))\n }\n\n /**\n * Creates a failure for an invalid value that doesn't match expected values.\n *\n * @param input - The actual value that was received\n * @param values - The expected valid values\n * @returns A failed validation result with an invalid value issue\n */\n issueInvalidValue(input: unknown, values: readonly unknown[]) {\n return this.issue(new IssueInvalidValue(this.path, input, values))\n }\n\n /**\n * Creates a failure for an invalid type.\n *\n * @param input - The actual value that was received\n * @param expected - An array of expected type names\n * @returns A failed validation result with an invalid type issue\n */\n issueInvalidType(input: unknown, expected: readonly string[]) {\n return this.issue(new IssueInvalidType(this.path, input, expected))\n }\n\n /**\n * Creates a failure for an invalid type.\n *\n * @param input - The actual value that was received\n * @param expected - The expected type name\n * @returns A failed validation result with an invalid type issue\n */\n issueUnexpectedType(input: unknown, expected: string) {\n return this.issueInvalidType(input, [expected])\n }\n\n /**\n * Creates a failure for a missing required key in an object.\n *\n * @param input - The object missing the required key\n * @param key - The name of the required key\n * @returns A failed validation result with a required key issue\n */\n issueRequiredKey(input: object, key: PropertyKey) {\n return this.issue(new IssueRequiredKey(this.path, input, key))\n }\n\n /**\n * Creates a failure for an invalid string format.\n *\n * @param input - The actual value that was received\n * @param format - The expected format name (e.g., 'did', 'handle', 'uri')\n * @param msg - Optional additional message describing the format error\n * @returns A failed validation result with an invalid format issue\n */\n issueInvalidFormat(input: unknown, format: string, msg?: string) {\n return this.issue(new IssueInvalidFormat(this.path, input, format, msg))\n }\n\n /**\n * Creates a failure for a value that exceeds a maximum constraint.\n *\n * @param input - The actual value that was received\n * @param type - The type of measurement (e.g., 'string', 'array', 'bytes')\n * @param max - The maximum allowed value\n * @param actual - The actual measured value\n * @returns A failed validation result with a too big issue\n */\n issueTooBig(\n input: unknown,\n type: MeasurableType,\n max: number,\n actual: number,\n ) {\n return this.issue(new IssueTooBig(this.path, input, max, type, actual))\n }\n\n /**\n * Creates a failure for a value that is below a minimum constraint.\n *\n * @param input - The actual value that was received\n * @param type - The type of measurement (e.g., 'string', 'array', 'bytes')\n * @param min - The minimum required value\n * @param actual - The actual measured value\n * @returns A failed validation result with a too small issue\n */\n issueTooSmall(\n input: unknown,\n type: MeasurableType,\n min: number,\n actual: number,\n ) {\n return this.issue(new IssueTooSmall(this.path, input, min, type, actual))\n }\n\n /**\n * Creates a failure for an invalid property value within an object.\n *\n * This is a convenience method that automatically extracts the property value\n * and constructs the appropriate path.\n *\n * @typeParam I - The input object type\n * @param input - The object containing the invalid property\n * @param property - The property key with the invalid value\n * @param values - The expected valid values\n * @returns A failed validation result with an invalid value issue at the property path\n */\n issueInvalidPropertyValue<I>(\n input: I,\n property: keyof I & PropertyKey,\n values: readonly unknown[],\n ) {\n const value = input[property]\n const path = this.concatPath(property)\n return this.issue(new IssueInvalidValue(path, value, values))\n }\n\n /**\n * Creates a failure for an invalid property type within an object.\n *\n * This is a convenience method that automatically extracts the property value\n * and constructs the appropriate path.\n *\n * @typeParam I - The input object type\n * @param input - The object containing the invalid property\n * @param property - The property key with the invalid type\n * @param expected - The expected type name\n * @returns A failed validation result with an invalid type issue at the property path\n */\n issueInvalidPropertyType<I>(\n input: I,\n property: keyof I & PropertyKey,\n expected: string,\n ) {\n const value = input[property]\n const path = this.concatPath(property)\n return this.issue(new IssueInvalidType(path, value, [expected]))\n }\n}\n\n/**\n * Recursively unwraps a wrapped validator to its innermost validator type.\n *\n * Some validators wrap other validators (e.g., optional, nullable). This type\n * utility recursively unwraps such wrappers to reveal the core validator.\n *\n * @typeParam T - A validator type, possibly wrapped\n *\n * @example\n * ```typescript\n * type Inner = UnwrapValidator<OptionalValidator<NullableValidator<StringSchema>>>\n * // Result: StringSchema\n * ```\n */\nexport type UnwrapValidator<T extends Validator> = T extends {\n unwrap(): infer U extends Validator\n}\n ? UnwrapValidator<U>\n : T\n\n/**\n * Interface for validators that wrap another validator.\n *\n * Implement this interface when creating validators that wrap or modify\n * the behavior of another validator (e.g., optional, nullable, transform).\n *\n * @typeParam Validator - The type of the wrapped validator\n *\n * @example\n * ```typescript\n * class OptionalSchema<V extends Validator> implements WrappedValidator<V> {\n * constructor(private inner: V) {}\n *\n * unwrap(): V {\n * return this.inner\n * }\n * }\n * ```\n */\nexport interface WrappedValidator<out Validator> {\n /**\n * Returns the inner wrapped validator.\n *\n * @returns The wrapped validator\n */\n unwrap(): Validator\n}\n"]}
|
package/dist/core.js
CHANGED
|
@@ -1,13 +1,10 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
tslib_1.__exportStar(require("./core/validation-error.js"), exports);
|
|
11
|
-
tslib_1.__exportStar(require("./core/validation-issue.js"), exports);
|
|
12
|
-
tslib_1.__exportStar(require("./core/validator.js"), exports);
|
|
1
|
+
export * from './core/$type.js';
|
|
2
|
+
export * from './core/record-key.js';
|
|
3
|
+
export * from './core/result.js';
|
|
4
|
+
export * from './core/schema.js';
|
|
5
|
+
export * from './core/string-format.js';
|
|
6
|
+
export * from './core/types.js';
|
|
7
|
+
export * from './core/validation-error.js';
|
|
8
|
+
export * from './core/validation-issue.js';
|
|
9
|
+
export * from './core/validator.js';
|
|
13
10
|
//# sourceMappingURL=core.js.map
|
package/dist/core.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"core.js","sourceRoot":"","sources":["../src/core.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"core.js","sourceRoot":"","sources":["../src/core.ts"],"names":[],"mappings":"AAAA,cAAc,iBAAiB,CAAA;AAC/B,cAAc,sBAAsB,CAAA;AACpC,cAAc,kBAAkB,CAAA;AAChC,cAAc,kBAAkB,CAAA;AAChC,cAAc,yBAAyB,CAAA;AACvC,cAAc,iBAAiB,CAAA;AAC/B,cAAc,4BAA4B,CAAA;AAC1C,cAAc,4BAA4B,CAAA;AAC1C,cAAc,qBAAqB,CAAA","sourcesContent":["export * from './core/$type.js'\nexport * from './core/record-key.js'\nexport * from './core/result.js'\nexport * from './core/schema.js'\nexport * from './core/string-format.js'\nexport * from './core/types.js'\nexport * from './core/validation-error.js'\nexport * from './core/validation-issue.js'\nexport * from './core/validator.js'\n"]}
|
package/dist/external.js
CHANGED
|
@@ -1,7 +1,4 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
tslib_1.__exportStar(require("./core.js"), exports);
|
|
5
|
-
tslib_1.__exportStar(require("./helpers.js"), exports);
|
|
6
|
-
tslib_1.__exportStar(require("./schema.js"), exports);
|
|
1
|
+
export * from './core.js';
|
|
2
|
+
export * from './helpers.js';
|
|
3
|
+
export * from './schema.js';
|
|
7
4
|
//# sourceMappingURL=external.js.map
|
package/dist/external.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"external.js","sourceRoot":"","sources":["../src/external.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"external.js","sourceRoot":"","sources":["../src/external.ts"],"names":[],"mappings":"AAAA,cAAc,WAAW,CAAA;AACzB,cAAc,cAAc,CAAA;AAC5B,cAAc,aAAa,CAAA","sourcesContent":["export * from './core.js'\nexport * from './helpers.js'\nexport * from './schema.js'\n"]}
|
package/dist/helpers.js
CHANGED
|
@@ -1,18 +1,14 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
exports.lexErrorDataSchema = void 0;
|
|
4
|
-
exports.getMain = getMain;
|
|
5
|
-
const schema_js_1 = require("./schema.js");
|
|
6
|
-
function getMain(ns) {
|
|
1
|
+
import { object, optional, regexp, string, } from './schema.js';
|
|
2
|
+
export function getMain(ns) {
|
|
7
3
|
return 'main' in ns ? ns.main : ns;
|
|
8
4
|
}
|
|
9
5
|
/**
|
|
10
6
|
* @see {@link https://atproto.com/specs/xrpc#error-responses}
|
|
11
7
|
*/
|
|
12
|
-
|
|
8
|
+
export const lexErrorDataSchema = object({
|
|
13
9
|
// type name of the error (generic ASCII constant, no whitespace)
|
|
14
|
-
error:
|
|
10
|
+
error: regexp(/^[\w_-]+$/, 'Expected ASCII constant with no whitespace'),
|
|
15
11
|
// description of the error, appropriate for display to humans
|
|
16
|
-
message:
|
|
12
|
+
message: optional(string()),
|
|
17
13
|
});
|
|
18
14
|
//# sourceMappingURL=helpers.js.map
|
package/dist/helpers.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"helpers.js","sourceRoot":"","sources":["../src/helpers.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"helpers.js","sourceRoot":"","sources":["../src/helpers.ts"],"names":[],"mappings":"AAEA,OAAO,EAOL,MAAM,EACN,QAAQ,EACR,MAAM,EACN,MAAM,GACP,MAAM,aAAa,CAAA;AAIpB,MAAM,UAAU,OAAO,CAAmB,EAAW;IACnD,OAAO,MAAM,IAAI,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAA;AACpC,CAAC;AAuFD;;GAEG;AACH,MAAM,CAAC,MAAM,kBAAkB,GAAG,MAAM,CAAC;IACvC,iEAAiE;IACjE,KAAK,EAAE,MAAM,CAAC,WAAW,EAAE,4CAA4C,CAAC;IACxE,8DAA8D;IAC9D,OAAO,EAAE,QAAQ,CAAC,MAAM,EAAE,CAAC;CAC5B,CAAgC,CAAA","sourcesContent":["import { LexErrorData } from '@atproto/lex-data'\nimport { InferOutput, Restricted, Schema } from './core.js'\nimport {\n InferPayload,\n InferPayloadBody,\n InferPayloadEncoding,\n Procedure,\n Query,\n Subscription,\n object,\n optional,\n regexp,\n string,\n} from './schema.js'\n\nexport type Main<T> = T | { main: T }\n\nexport function getMain<T extends object>(ns: Main<T>): T {\n return 'main' in ns ? ns.main : ns\n}\n\n/**\n * Every XRPC implementation should translate `application/json` and `text/*`\n * payloads into their native equivalent ({@link LexValue} or string). Binary\n * data payloads, however, can be represented differently depending on the\n * environment and use case (e.g. `Uint8Array`, `Blob`, `Buffer`,\n * `ReadableStream`, etc.). This type is a placeholder to represent binary data\n * when not explicitly provided.\n */\nexport type BinaryData = Restricted<'Binary data'>\n\nexport type InferMethodParams<\n M extends Procedure | Query | Subscription = Procedure | Query | Subscription,\n> =\n M extends Procedure<any, infer TParams, any, any, any>\n ? InferOutput<TParams>\n : M extends Query<any, infer TParams, any, any>\n ? InferOutput<TParams>\n : M extends Subscription<any, infer TParams, any, any>\n ? InferOutput<TParams>\n : never\n\nexport type InferMethodInput<\n M extends Procedure | Query | Subscription = Procedure | Query | Subscription,\n B = BinaryData,\n> =\n M extends Procedure<any, any, infer TInput, any, any>\n ? InferPayload<TInput, B>\n : undefined\n\nexport type InferMethodInputBody<\n M extends Procedure | Query | Subscription = Procedure | Query | Subscription,\n B = BinaryData,\n> =\n M extends Procedure<any, any, infer TInput, any, any>\n ? InferPayloadBody<TInput, B>\n : undefined\n\nexport type InferMethodInputEncoding<\n M extends Procedure | Query | Subscription = Procedure | Query | Subscription,\n> =\n M extends Procedure<any, any, infer TInput, any, any>\n ? InferPayloadEncoding<TInput>\n : undefined\n\nexport type InferMethodOutput<\n M extends Procedure | Query | Subscription = Procedure | Query | Subscription,\n B = BinaryData,\n> =\n M extends Procedure<any, any, any, infer TOutput, any>\n ? InferPayload<TOutput, B>\n : M extends Query<any, any, infer TOutput, any>\n ? InferPayload<TOutput, B>\n : undefined\n\nexport type InferMethodOutputBody<\n M extends Procedure | Query | Subscription = Procedure | Query | Subscription,\n B = BinaryData,\n> =\n M extends Procedure<any, any, any, infer TOutput, any>\n ? InferPayloadBody<TOutput, B>\n : M extends Query<any, any, infer TOutput, any>\n ? InferPayloadBody<TOutput, B>\n : undefined\n\nexport type InferMethodOutputEncoding<\n M extends Procedure | Query | Subscription = Procedure | Query | Subscription,\n> =\n M extends Procedure<any, any, any, infer TOutput, any>\n ? InferPayloadEncoding<TOutput>\n : M extends Query<any, any, infer TOutput, any>\n ? InferPayloadEncoding<TOutput>\n : undefined\n\nexport type InferMethodMessage<\n M extends Procedure | Query | Subscription = Procedure | Query | Subscription,\n> =\n M extends Subscription<any, any, infer TMessage, any>\n ? InferOutput<TMessage>\n : undefined\n\nexport type InferMethodError<\n //\n M extends Procedure | Query | Subscription = Procedure | Query | Subscription,\n> = M extends { errors: readonly (infer E extends string)[] } ? E : never\n\n/**\n * @see {@link https://atproto.com/specs/xrpc#error-responses}\n */\nexport const lexErrorDataSchema = object({\n // type name of the error (generic ASCII constant, no whitespace)\n error: regexp(/^[\\w_-]+$/, 'Expected ASCII constant with no whitespace'),\n // description of the error, appropriate for display to humans\n message: optional(string()),\n}) satisfies Schema<LexErrorData>\n"]}
|
package/dist/index.js
CHANGED
|
@@ -1,8 +1,4 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
const tslib_1 = require("tslib");
|
|
5
|
-
const l = tslib_1.__importStar(require("./external.js"));
|
|
6
|
-
exports.l = l;
|
|
7
|
-
tslib_1.__exportStar(require("./external.js"), exports);
|
|
1
|
+
import * as l from './external.js';
|
|
2
|
+
export * from './external.js';
|
|
3
|
+
export { l };
|
|
8
4
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,CAAC,MAAM,eAAe,CAAA;AAClC,cAAc,eAAe,CAAA;AAC7B,OAAO,EAAE,CAAC,EAAE,CAAA","sourcesContent":["import * as l from './external.js'\nexport * from './external.js'\nexport { l }\n"]}
|
package/dist/schema/array.js
CHANGED
|
@@ -1,8 +1,5 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
exports.array = exports.ArraySchema = void 0;
|
|
4
|
-
const core_js_1 = require("../core.js");
|
|
5
|
-
const memoize_js_1 = require("../util/memoize.js");
|
|
1
|
+
import { Schema, } from '../core.js';
|
|
2
|
+
import { memoizedTransformer } from '../util/memoize.js';
|
|
6
3
|
/**
|
|
7
4
|
* Schema for validating arrays where all items match a given schema.
|
|
8
5
|
*
|
|
@@ -17,14 +14,12 @@ const memoize_js_1 = require("../util/memoize.js");
|
|
|
17
14
|
* const result = schema.validate(['a', 'b', 'c'])
|
|
18
15
|
* ```
|
|
19
16
|
*/
|
|
20
|
-
class ArraySchema extends
|
|
21
|
-
validator;
|
|
22
|
-
options;
|
|
23
|
-
type = 'array';
|
|
17
|
+
export class ArraySchema extends Schema {
|
|
24
18
|
constructor(validator, options = {}) {
|
|
25
19
|
super();
|
|
26
20
|
this.validator = validator;
|
|
27
21
|
this.options = options;
|
|
22
|
+
this.type = 'array';
|
|
28
23
|
}
|
|
29
24
|
validateInContext(input, ctx) {
|
|
30
25
|
if (!Array.isArray(input)) {
|
|
@@ -55,9 +50,8 @@ class ArraySchema extends core_js_1.Schema {
|
|
|
55
50
|
return ctx.success(copy ?? input);
|
|
56
51
|
}
|
|
57
52
|
}
|
|
58
|
-
exports.ArraySchema = ArraySchema;
|
|
59
53
|
function arraySchema(items, options) {
|
|
60
54
|
return new ArraySchema(items, options);
|
|
61
55
|
}
|
|
62
|
-
|
|
56
|
+
export const array = /*#__PURE__*/ memoizedTransformer(arraySchema);
|
|
63
57
|
//# sourceMappingURL=array.js.map
|
package/dist/schema/array.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"array.js","sourceRoot":"","sources":["../../src/schema/array.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"array.js","sourceRoot":"","sources":["../../src/schema/array.ts"],"names":[],"mappings":"AAAA,OAAO,EAGL,MAAM,GAGP,MAAM,YAAY,CAAA;AACnB,OAAO,EAAE,mBAAmB,EAAE,MAAM,oBAAoB,CAAA;AAaxD;;;;;;;;;;;;;GAaG;AACH,MAAM,OAAO,WAA2C,SAAQ,MAG/D;IAGC,YACW,SAA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BACpC,sEAAsE;oBACtE,OAAO,GAAG,CAAC,yBAAyB,CAAC,KAAK,EAAE,CAAC,EAAE,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAA;gBAChE,CAAC;gBAED,6DAA6D;gBAC7D,IAAI,KAAK,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,CAAA;gBAC1B,IAAI,CAAC,CAAC,CAAC,GAAG,MAAM,CAAC,KAAK,CAAA;YACxB,CAAC;QACH,CAAC;QAED,OAAO,GAAG,CAAC,OAAO,CAAC,IAAI,IAAI,KAAK,CAAC,CAAA;IACnC,CAAC;CACF;AAoCD,SAAS,WAAW,CAClB,KAAiB,EACjB,OAA4B;IAE5B,OAAO,IAAI,WAAW,CAAa,KAAK,EAAE,OAAO,CAAC,CAAA;AACpD,CAAC;AAED,MAAM,CAAC,MAAM,KAAK,GAAG,aAAa,CAAC,mBAAmB,CAAC,WAAW,CAAC,CAAA","sourcesContent":["import {\n InferInput,\n InferOutput,\n Schema,\n ValidationContext,\n Validator,\n} from '../core.js'\nimport { memoizedTransformer } from '../util/memoize.js'\n\n/**\n * Configuration options for array schema validation.\n *\n * @property minLength - Minimum number of items in the array\n * @property maxLength - Maximum number of items in the array\n */\nexport type ArraySchemaOptions = {\n minLength?: number\n maxLength?: number\n}\n\n/**\n * Schema for validating arrays where all items match a given schema.\n *\n * Validates that the input is an array, checks length constraints, and\n * validates each item against the provided item schema.\n *\n * @template TItem - The validator type for array items\n *\n * @example\n * ```ts\n * const schema = new ArraySchema(l.string(), { maxLength: 10 })\n * const result = schema.validate(['a', 'b', 'c'])\n * ```\n */\nexport class ArraySchema<const TItem extends Validator> extends Schema<\n Array<InferInput<TItem>>,\n Array<InferOutput<TItem>>\n> {\n readonly type = 'array' as const\n\n constructor(\n readonly validator: TItem,\n readonly options: ArraySchemaOptions = {},\n ) {\n super()\n }\n\n validateInContext(input: unknown, ctx: ValidationContext) {\n if (!Array.isArray(input)) {\n return ctx.issueUnexpectedType(input, 'array')\n }\n\n const { minLength, maxLength } = this.options\n\n if (minLength != null && input.length < minLength) {\n return ctx.issueTooSmall(input, 'array', minLength, input.length)\n }\n\n if (maxLength != null && input.length > maxLength) {\n return ctx.issueTooBig(input, 'array', maxLength, input.length)\n }\n\n let copy: undefined | unknown[]\n\n for (let i = 0; i < input.length; i++) {\n const result = ctx.validateChild(input, i, this.validator)\n if (!result.success) return result\n\n if (result.value !== input[i]) {\n if (ctx.options.mode === 'validate') {\n // In \"validate\" mode, we can't modify the input, so we issue an error\n return ctx.issueInvalidPropertyValue(input, i, [result.value])\n }\n\n // Copy on write (but only if we did not already make a copy)\n copy ??= Array.from(input)\n copy[i] = result.value\n }\n }\n\n return ctx.success(copy ?? input)\n }\n}\n\n/**\n * Creates an array schema that validates each item against the provided schema.\n *\n * @param items - Schema to validate each array item against\n * @param options - Optional length constraints\n * @returns A new {@link ArraySchema} instance\n *\n * @example\n * ```ts\n * // Array of strings\n * const tagsSchema = l.array(l.string())\n *\n * // Array with length constraints\n * const limitedSchema = l.array(l.integer(), { maxLength: 100 })\n *\n * // Array of objects\n * const usersSchema = l.array(l.object({\n * name: l.string(),\n * age: l.integer(),\n * }))\n *\n * // Non-empty array\n * const nonEmptySchema = l.array(l.string(), { minLength: 1 })\n * ```\n */\n/*@__NO_SIDE_EFFECTS__*/\nfunction arraySchema<const TValidator extends Validator>(\n items: TValidator,\n options?: ArraySchemaOptions,\n): ArraySchema<TValidator>\nfunction arraySchema<\n const TValue,\n const TValidator extends Validator<TValue> = Validator<TValue>,\n>(items: TValidator, options?: ArraySchemaOptions): ArraySchema<TValidator>\nfunction arraySchema<const TValidator extends Validator>(\n items: TValidator,\n options?: ArraySchemaOptions,\n) {\n return new ArraySchema<TValidator>(items, options)\n}\n\nexport const array = /*#__PURE__*/ memoizedTransformer(arraySchema)\n"]}
|
package/dist/schema/blob.js
CHANGED
|
@@ -1,12 +1,7 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
Object.defineProperty(exports, "isBlobRef", { enumerable: true, get: function () { return lex_data_1.isBlobRef; } });
|
|
6
|
-
Object.defineProperty(exports, "isLegacyBlobRef", { enumerable: true, get: function () { return lex_data_1.isLegacyBlobRef; } });
|
|
7
|
-
Object.defineProperty(exports, "isTypedBlobRef", { enumerable: true, get: function () { return lex_data_1.isTypedBlobRef; } });
|
|
8
|
-
const core_js_1 = require("../core.js");
|
|
9
|
-
const memoize_js_1 = require("../util/memoize.js");
|
|
1
|
+
import { getBlobSize, isBlobRef, isLegacyBlobRef, isTypedBlobRef, } from '@atproto/lex-data';
|
|
2
|
+
import { Schema } from '../core.js';
|
|
3
|
+
import { memoizedOptions } from '../util/memoize.js';
|
|
4
|
+
export { isBlobRef, isLegacyBlobRef, isTypedBlobRef };
|
|
10
5
|
/**
|
|
11
6
|
* Schema for validating blob references in AT Protocol.
|
|
12
7
|
*
|
|
@@ -22,12 +17,11 @@ const memoize_js_1 = require("../util/memoize.js");
|
|
|
22
17
|
* const result = schema.validate(blobRef)
|
|
23
18
|
* ```
|
|
24
19
|
*/
|
|
25
|
-
class BlobSchema extends
|
|
26
|
-
options;
|
|
27
|
-
type = 'blob';
|
|
20
|
+
export class BlobSchema extends Schema {
|
|
28
21
|
constructor(options) {
|
|
29
22
|
super();
|
|
30
23
|
this.options = options;
|
|
24
|
+
this.type = 'blob';
|
|
31
25
|
}
|
|
32
26
|
validateInContext(input, ctx) {
|
|
33
27
|
const blob = parseValue.call(ctx, input);
|
|
@@ -43,7 +37,7 @@ class BlobSchema extends core_js_1.Schema {
|
|
|
43
37
|
}
|
|
44
38
|
const { maxSize } = this.options;
|
|
45
39
|
if (maxSize != null) {
|
|
46
|
-
const size =
|
|
40
|
+
const size = getBlobSize(blob);
|
|
47
41
|
if (size === undefined) {
|
|
48
42
|
// Unable to enforce size constraint if size is not available (legacy
|
|
49
43
|
// blob ref), so we treat it as a validation failure in strict mode.
|
|
@@ -63,19 +57,18 @@ class BlobSchema extends core_js_1.Schema {
|
|
|
63
57
|
return matchesMime(mime, accept);
|
|
64
58
|
}
|
|
65
59
|
}
|
|
66
|
-
exports.BlobSchema = BlobSchema;
|
|
67
60
|
function parseValue(input) {
|
|
68
61
|
// If there is a $type property, we treat if as a potential TypedBlobRef and
|
|
69
62
|
// validate accordingly.
|
|
70
63
|
if (input?.$type !== undefined) {
|
|
71
64
|
// Use the context's option for the "strict" check
|
|
72
|
-
return
|
|
65
|
+
return isTypedBlobRef(input, this.options) ? input : null;
|
|
73
66
|
}
|
|
74
67
|
// If there is no $type property, we may be dealing with a legacy blob ref. If
|
|
75
68
|
// legacy refs are allowed (non-strict mode), we check if the input matches
|
|
76
69
|
// the legacy format.
|
|
77
70
|
if (!this.options.strict) {
|
|
78
|
-
if (
|
|
71
|
+
if (isLegacyBlobRef(input, this.options))
|
|
79
72
|
return input;
|
|
80
73
|
}
|
|
81
74
|
return null;
|
|
@@ -113,7 +106,7 @@ function matchesMime(mime, accepted) {
|
|
|
113
106
|
* const avatarSchema = l.blob({ accept: ['image/*'], maxSize: 1000000 })
|
|
114
107
|
* ```
|
|
115
108
|
*/
|
|
116
|
-
|
|
109
|
+
export const blob = /*#__PURE__*/ memoizedOptions(function (options) {
|
|
117
110
|
return new BlobSchema(options);
|
|
118
111
|
});
|
|
119
112
|
//# sourceMappingURL=blob.js.map
|