@atproto/lex-schema 0.0.12 → 0.0.13
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 +35 -0
- package/dist/core/schema.d.ts +4 -4
- package/dist/core/schema.d.ts.map +1 -1
- package/dist/core/schema.js +1 -1
- package/dist/core/schema.js.map +1 -1
- package/dist/core/validation-issue.js +3 -1
- package/dist/core/validation-issue.js.map +1 -1
- package/dist/core/validator.d.ts +10 -2
- package/dist/core/validator.d.ts.map +1 -1
- package/dist/core/validator.js +21 -3
- package/dist/core/validator.js.map +1 -1
- package/dist/helpers.d.ts +10 -11
- package/dist/helpers.d.ts.map +1 -1
- package/dist/helpers.js.map +1 -1
- package/dist/schema/array.d.ts +1 -0
- package/dist/schema/array.d.ts.map +1 -1
- package/dist/schema/array.js +2 -1
- package/dist/schema/array.js.map +1 -1
- package/dist/schema/blob.d.ts +4 -2
- package/dist/schema/blob.d.ts.map +1 -1
- package/dist/schema/blob.js +5 -2
- package/dist/schema/blob.js.map +1 -1
- package/dist/schema/boolean.d.ts +1 -0
- package/dist/schema/boolean.d.ts.map +1 -1
- package/dist/schema/boolean.js +2 -1
- package/dist/schema/boolean.js.map +1 -1
- package/dist/schema/bytes.d.ts +1 -0
- package/dist/schema/bytes.d.ts.map +1 -1
- package/dist/schema/bytes.js +2 -1
- package/dist/schema/bytes.js.map +1 -1
- package/dist/schema/cid.d.ts +1 -0
- package/dist/schema/cid.d.ts.map +1 -1
- package/dist/schema/cid.js +2 -1
- package/dist/schema/cid.js.map +1 -1
- package/dist/schema/custom.d.ts +1 -0
- package/dist/schema/custom.d.ts.map +1 -1
- package/dist/schema/custom.js +1 -0
- package/dist/schema/custom.js.map +1 -1
- package/dist/schema/dict.d.ts +1 -0
- package/dist/schema/dict.d.ts.map +1 -1
- package/dist/schema/dict.js +2 -1
- package/dist/schema/dict.js.map +1 -1
- package/dist/schema/discriminated-union.d.ts +1 -0
- package/dist/schema/discriminated-union.d.ts.map +1 -1
- package/dist/schema/discriminated-union.js +2 -1
- package/dist/schema/discriminated-union.js.map +1 -1
- package/dist/schema/enum.d.ts +1 -0
- package/dist/schema/enum.d.ts.map +1 -1
- package/dist/schema/enum.js +1 -0
- package/dist/schema/enum.js.map +1 -1
- package/dist/schema/integer.d.ts +1 -0
- package/dist/schema/integer.d.ts.map +1 -1
- package/dist/schema/integer.js +2 -1
- package/dist/schema/integer.js.map +1 -1
- package/dist/schema/intersection.d.ts +1 -0
- package/dist/schema/intersection.d.ts.map +1 -1
- package/dist/schema/intersection.js +1 -0
- package/dist/schema/intersection.js.map +1 -1
- package/dist/schema/lex-map.d.ts +37 -0
- package/dist/schema/lex-map.d.ts.map +1 -0
- package/dist/schema/lex-map.js +60 -0
- package/dist/schema/lex-map.js.map +1 -0
- package/dist/schema/lex-value.d.ts +35 -0
- package/dist/schema/lex-value.d.ts.map +1 -0
- package/dist/schema/lex-value.js +87 -0
- package/dist/schema/lex-value.js.map +1 -0
- package/dist/schema/literal.d.ts +1 -0
- package/dist/schema/literal.d.ts.map +1 -1
- package/dist/schema/literal.js +1 -0
- package/dist/schema/literal.js.map +1 -1
- package/dist/schema/never.d.ts +1 -0
- package/dist/schema/never.d.ts.map +1 -1
- package/dist/schema/never.js +2 -1
- package/dist/schema/never.js.map +1 -1
- package/dist/schema/null.d.ts +1 -0
- package/dist/schema/null.d.ts.map +1 -1
- package/dist/schema/null.js +2 -1
- package/dist/schema/null.js.map +1 -1
- package/dist/schema/nullable.d.ts +1 -0
- package/dist/schema/nullable.d.ts.map +1 -1
- package/dist/schema/nullable.js +1 -0
- package/dist/schema/nullable.js.map +1 -1
- package/dist/schema/object.d.ts +1 -0
- package/dist/schema/object.d.ts.map +1 -1
- package/dist/schema/object.js +2 -1
- package/dist/schema/object.js.map +1 -1
- package/dist/schema/optional.d.ts +1 -0
- package/dist/schema/optional.d.ts.map +1 -1
- package/dist/schema/optional.js +1 -0
- package/dist/schema/optional.js.map +1 -1
- package/dist/schema/params.d.ts +14 -10
- package/dist/schema/params.d.ts.map +1 -1
- package/dist/schema/params.js +84 -24
- package/dist/schema/params.js.map +1 -1
- package/dist/schema/payload.d.ts.map +1 -1
- package/dist/schema/payload.js +3 -3
- package/dist/schema/payload.js.map +1 -1
- package/dist/schema/record.d.ts +13 -17
- package/dist/schema/record.d.ts.map +1 -1
- package/dist/schema/record.js +1 -0
- package/dist/schema/record.js.map +1 -1
- package/dist/schema/ref.d.ts +1 -0
- package/dist/schema/ref.d.ts.map +1 -1
- package/dist/schema/ref.js +1 -0
- package/dist/schema/ref.js.map +1 -1
- package/dist/schema/regexp.d.ts +1 -0
- package/dist/schema/regexp.d.ts.map +1 -1
- package/dist/schema/regexp.js +2 -1
- package/dist/schema/regexp.js.map +1 -1
- package/dist/schema/string.d.ts +22 -6
- package/dist/schema/string.d.ts.map +1 -1
- package/dist/schema/string.js +16 -9
- package/dist/schema/string.js.map +1 -1
- package/dist/schema/token.d.ts +1 -0
- package/dist/schema/token.d.ts.map +1 -1
- package/dist/schema/token.js +2 -1
- package/dist/schema/token.js.map +1 -1
- package/dist/schema/typed-object.d.ts +11 -15
- package/dist/schema/typed-object.d.ts.map +1 -1
- package/dist/schema/typed-object.js +2 -1
- package/dist/schema/typed-object.js.map +1 -1
- package/dist/schema/typed-ref.d.ts +1 -0
- package/dist/schema/typed-ref.d.ts.map +1 -1
- package/dist/schema/typed-ref.js +1 -0
- package/dist/schema/typed-ref.js.map +1 -1
- package/dist/schema/typed-union.d.ts +1 -0
- package/dist/schema/typed-union.d.ts.map +1 -1
- package/dist/schema/typed-union.js +2 -1
- package/dist/schema/typed-union.js.map +1 -1
- package/dist/schema/union.d.ts +1 -0
- package/dist/schema/union.d.ts.map +1 -1
- package/dist/schema/union.js +1 -0
- package/dist/schema/union.js.map +1 -1
- package/dist/schema/unknown.d.ts +1 -0
- package/dist/schema/unknown.d.ts.map +1 -1
- package/dist/schema/unknown.js +1 -0
- package/dist/schema/unknown.js.map +1 -1
- package/dist/schema/with-default.d.ts +1 -0
- package/dist/schema/with-default.d.ts.map +1 -1
- package/dist/schema/with-default.js +1 -0
- package/dist/schema/with-default.js.map +1 -1
- package/dist/schema.d.ts +2 -1
- package/dist/schema.d.ts.map +1 -1
- package/dist/schema.js +2 -1
- package/dist/schema.js.map +1 -1
- package/dist/util/if-any.d.ts +2 -0
- package/dist/util/if-any.d.ts.map +1 -0
- package/dist/util/if-any.js +3 -0
- package/dist/util/if-any.js.map +1 -0
- package/package.json +2 -2
- package/src/core/schema.ts +9 -3
- package/src/core/validation-issue.ts +3 -2
- package/src/core/validator.ts +23 -3
- package/src/helpers.test.ts +1 -1
- package/src/helpers.ts +53 -19
- package/src/schema/array.ts +3 -1
- package/src/schema/blob.ts +4 -1
- package/src/schema/boolean.ts +3 -1
- package/src/schema/bytes.ts +3 -1
- package/src/schema/cid.ts +3 -1
- package/src/schema/custom.ts +2 -0
- package/src/schema/dict.ts +3 -1
- package/src/schema/discriminated-union.ts +3 -1
- package/src/schema/enum.ts +2 -0
- package/src/schema/integer.ts +3 -1
- package/src/schema/intersection.ts +2 -0
- package/src/schema/{unknown-object.test.ts → lex-map.test.ts} +9 -9
- package/src/schema/lex-map.ts +63 -0
- package/src/schema/lex-value.test.ts +81 -0
- package/src/schema/lex-value.ts +86 -0
- package/src/schema/literal.ts +2 -0
- package/src/schema/never.ts +3 -1
- package/src/schema/null.ts +3 -1
- package/src/schema/nullable.ts +2 -0
- package/src/schema/object.ts +3 -1
- package/src/schema/optional.ts +2 -0
- package/src/schema/params.test.ts +82 -43
- package/src/schema/params.ts +133 -39
- package/src/schema/payload.test.ts +2 -2
- package/src/schema/payload.ts +3 -4
- package/src/schema/record.ts +19 -8
- package/src/schema/ref.ts +2 -0
- package/src/schema/regexp.ts +3 -1
- package/src/schema/string.test.ts +99 -2
- package/src/schema/string.ts +58 -15
- package/src/schema/token.ts +3 -1
- package/src/schema/typed-object.ts +19 -8
- package/src/schema/typed-ref.ts +2 -0
- package/src/schema/typed-union.ts +3 -1
- package/src/schema/union.ts +2 -0
- package/src/schema/unknown.ts +2 -0
- package/src/schema/with-default.ts +2 -0
- package/src/schema.ts +2 -1
- package/src/util/if-any.ts +3 -0
- package/dist/schema/unknown-object.d.ts +0 -42
- package/dist/schema/unknown-object.d.ts.map +0 -1
- package/dist/schema/unknown-object.js +0 -50
- package/dist/schema/unknown-object.js.map +0 -1
- package/src/schema/unknown-object.ts +0 -53
package/dist/schema/ref.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ref.js","sourceRoot":"","sources":["../../src/schema/ref.ts"],"names":[],"mappings":";;;
|
|
1
|
+
{"version":3,"file":"ref.js","sourceRoot":"","sources":["../../src/schema/ref.ts"],"names":[],"mappings":";;;AAsGA,kBAIC;AA1GD,wCAOmB;AASnB;;;;;;;;;;;;;;;;GAgBG;AACH,MAAa,SACX,SAAQ,gBAIP;IAGQ,IAAI,GAAG,KAAc,CAAA;IAE9B,OAAO,CAA6B;IAEpC,YAAY,MAAmC;QAC7C,uEAAuE;QACvE,sEAAsE;QAEtE,KAAK,EAAE,CAAA;QAEP,IAAI,CAAC,OAAO,GAAG,MAAM,CAAA;IACvB,CAAC;IAED,IAAI,SAAS;QACX,OAAO,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,CAAA;IAChC,CAAC;IAED,MAAM;QACJ,OAAO,IAAI,CAAC,SAAS,CAAA;IACvB,CAAC;IAED,iBAAiB,CAAC,KAAc,EAAE,GAAsB;QACtD,OAAO,GAAG,CAAC,QAAQ,CAAC,KAAK,EAAE,IAAI,CAAC,SAAS,CAAC,CAAA;IAC5C,CAAC;CACF;AAhCD,8BAgCC;AAqCD,SAAgB,GAAG,CACjB,GAAgC;IAEhC,OAAO,IAAI,SAAS,CAAa,GAAG,CAAC,CAAA;AACvC,CAAC","sourcesContent":["import {\n InferInput,\n InferOutput,\n Schema,\n ValidationContext,\n Validator,\n WrappedValidator,\n} from '../core.js'\n\n/**\n * Function type that returns a validator, used for lazy schema resolution.\n *\n * @template TValidator - The validator type that will be returned\n */\nexport type RefSchemaGetter<out TValidator extends Validator> = () => TValidator\n\n/**\n * Schema for creating references to other schemas with lazy resolution.\n *\n * Useful for handling circular references or breaking module dependency cycles.\n * The referenced schema is resolved lazily when first needed for validation.\n *\n * @template TValidator - The referenced validator type\n *\n * @example\n * ```ts\n * // Self-referential schema for tree structure\n * const nodeSchema = l.object({\n * value: l.string(),\n * children: l.array(l.ref(() => nodeSchema)),\n * })\n * ```\n */\nexport class RefSchema<const TValidator extends Validator>\n extends Schema<\n InferInput<TValidator>,\n InferOutput<TValidator>,\n TValidator['__lex']\n >\n implements WrappedValidator<TValidator>\n{\n readonly type = 'ref' as const\n\n #getter: RefSchemaGetter<TValidator>\n\n constructor(getter: RefSchemaGetter<TValidator>) {\n // @NOTE In order to avoid circular dependency issues, we don't resolve\n // the schema here. Instead, we resolve it lazily when first accessed.\n\n super()\n\n this.#getter = getter\n }\n\n get validator(): TValidator {\n return this.#getter.call(null)\n }\n\n unwrap(): TValidator {\n return this.validator\n }\n\n validateInContext(input: unknown, ctx: ValidationContext) {\n return ctx.validate(input, this.validator)\n }\n}\n\n/**\n * Creates a reference schema with lazy resolution.\n *\n * Allows referencing schemas that may not be defined yet, enabling\n * circular references and breaking dependency cycles. The getter function\n * is called lazily when validation is first performed.\n *\n * @param get - Function that returns the referenced validator\n * @returns A new {@link RefSchema} instance\n *\n * @example\n * ```ts\n * // Circular reference - tree node that contains children of the same type\n * const treeNodeSchema = l.object({\n * name: l.string(),\n * children: l.optional(l.array(l.ref(() => treeNodeSchema))),\n * })\n *\n * // Cross-module reference\n * const commentSchema = l.object({\n * text: l.string(),\n * author: l.ref(() => userSchema), // userSchema defined elsewhere\n * })\n *\n * // Explicitly typed reference\n * const itemSchema = l.ref<Item>(() => complexItemSchema)\n * ```\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function ref<const TValidator extends Validator>(\n get: RefSchemaGetter<TValidator>,\n): RefSchema<TValidator>\nexport function ref<TInput, TOutput extends TInput = TInput>(\n get: RefSchemaGetter<Validator<TInput, TOutput>>,\n): RefSchema<Validator<TInput, TOutput>>\nexport function ref<const TValidator extends Validator>(\n get: RefSchemaGetter<TValidator>,\n) {\n return new RefSchema<TValidator>(get)\n}\n"]}
|
package/dist/schema/regexp.d.ts
CHANGED
|
@@ -16,6 +16,7 @@ import { Schema, ValidationContext } from '../core.js';
|
|
|
16
16
|
*/
|
|
17
17
|
export declare class RegexpSchema<TValue extends string = string> extends Schema<TValue> {
|
|
18
18
|
readonly pattern: RegExp;
|
|
19
|
+
readonly type: "regexp";
|
|
19
20
|
constructor(pattern: RegExp);
|
|
20
21
|
validateInContext(input: unknown, ctx: ValidationContext): import("../core.js").ValidationResult<TValue>;
|
|
21
22
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"regexp.d.ts","sourceRoot":"","sources":["../../src/schema/regexp.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAA;AAEtD;;;;;;;;;;;;;;GAcG;AACH,qBAAa,YAAY,CACvB,MAAM,SAAS,MAAM,GAAG,MAAM,CAC9B,SAAQ,MAAM,CAAC,MAAM,CAAC;
|
|
1
|
+
{"version":3,"file":"regexp.d.ts","sourceRoot":"","sources":["../../src/schema/regexp.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAA;AAEtD;;;;;;;;;;;;;;GAcG;AACH,qBAAa,YAAY,CACvB,MAAM,SAAS,MAAM,GAAG,MAAM,CAC9B,SAAQ,MAAM,CAAC,MAAM,CAAC;aAGM,OAAO,EAAE,MAAM;IAF3C,QAAQ,CAAC,IAAI,EAAG,QAAQ,CAAS;gBAEL,OAAO,EAAE,MAAM;IAI3C,iBAAiB,CAAC,KAAK,EAAE,OAAO,EAAE,GAAG,EAAE,iBAAiB;CAWzD;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AAEH,wBAAgB,MAAM,CAAC,MAAM,SAAS,MAAM,GAAG,MAAM,EAAE,OAAO,EAAE,MAAM,wBAErE"}
|
package/dist/schema/regexp.js
CHANGED
|
@@ -20,13 +20,14 @@ const core_js_1 = require("../core.js");
|
|
|
20
20
|
*/
|
|
21
21
|
class RegexpSchema extends core_js_1.Schema {
|
|
22
22
|
pattern;
|
|
23
|
+
type = 'regexp';
|
|
23
24
|
constructor(pattern) {
|
|
24
25
|
super();
|
|
25
26
|
this.pattern = pattern;
|
|
26
27
|
}
|
|
27
28
|
validateInContext(input, ctx) {
|
|
28
29
|
if (typeof input !== 'string') {
|
|
29
|
-
return ctx.
|
|
30
|
+
return ctx.issueUnexpectedType(input, 'string');
|
|
30
31
|
}
|
|
31
32
|
if (!this.pattern.test(input)) {
|
|
32
33
|
return ctx.issueInvalidFormat(input, this.pattern.toString());
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"regexp.js","sourceRoot":"","sources":["../../src/schema/regexp.ts"],"names":[],"mappings":";;;
|
|
1
|
+
{"version":3,"file":"regexp.js","sourceRoot":"","sources":["../../src/schema/regexp.ts"],"names":[],"mappings":";;;AAqEA,wBAEC;AAvED,wCAAsD;AAEtD;;;;;;;;;;;;;;GAcG;AACH,MAAa,YAEX,SAAQ,gBAAc;IAGM;IAFnB,IAAI,GAAG,QAAiB,CAAA;IAEjC,YAA4B,OAAe;QACzC,KAAK,EAAE,CAAA;QADmB,YAAO,GAAP,OAAO,CAAQ;IAE3C,CAAC;IAED,iBAAiB,CAAC,KAAc,EAAE,GAAsB;QACtD,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE,CAAC;YAC9B,OAAO,GAAG,CAAC,mBAAmB,CAAC,KAAK,EAAE,QAAQ,CAAC,CAAA;QACjD,CAAC;QAED,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC;YAC9B,OAAO,GAAG,CAAC,kBAAkB,CAAC,KAAK,EAAE,IAAI,CAAC,OAAO,CAAC,QAAQ,EAAE,CAAC,CAAA;QAC/D,CAAC;QAED,OAAO,GAAG,CAAC,OAAO,CAAC,KAAe,CAAC,CAAA;IACrC,CAAC;CACF;AApBD,oCAoBC;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH,wBAAwB;AACxB,SAAgB,MAAM,CAAiC,OAAe;IACpE,OAAO,IAAI,YAAY,CAAS,OAAO,CAAC,CAAA;AAC1C,CAAC","sourcesContent":["import { Schema, ValidationContext } from '../core.js'\n\n/**\n * Schema for validating strings against a regular expression pattern.\n *\n * Validates that the input is a string and matches the provided pattern.\n * The pattern is tested using RegExp.test().\n *\n * @template TValue - The string type (can be narrowed with branded types)\n *\n * @example\n * ```ts\n * const schema = new RegexpSchema(/^[a-z]+$/)\n * schema.validate('hello') // success\n * schema.validate('Hello') // fails - uppercase not allowed\n * ```\n */\nexport class RegexpSchema<\n TValue extends string = string,\n> extends Schema<TValue> {\n readonly type = 'regexp' as const\n\n constructor(public readonly pattern: RegExp) {\n super()\n }\n\n validateInContext(input: unknown, ctx: ValidationContext) {\n if (typeof input !== 'string') {\n return ctx.issueUnexpectedType(input, 'string')\n }\n\n if (!this.pattern.test(input)) {\n return ctx.issueInvalidFormat(input, this.pattern.toString())\n }\n\n return ctx.success(input as TValue)\n }\n}\n\n/**\n * Creates a regexp schema that validates strings against a pattern.\n *\n * Useful for custom string formats not covered by the built-in format\n * validators.\n *\n * @param pattern - Regular expression pattern to match against\n * @returns A new {@link RegexpSchema} instance\n *\n * @example\n * ```ts\n * // Simple pattern\n * const slugSchema = l.regexp(/^[a-z0-9-]+$/)\n *\n * // With anchors for exact match\n * const uuidSchema = l.regexp(\n * /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i\n * )\n *\n * // Semantic versioning\n * const semverSchema = l.regexp(/^\\d+\\.\\d+\\.\\d+(-[\\w.]+)?(\\+[\\w.]+)?$/)\n *\n * // Use in object\n * const configSchema = l.object({\n * name: l.regexp(/^[a-z][a-z0-9-]*$/), // kebab-case identifier\n * version: semverSchema,\n * })\n * ```\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function regexp<TInput extends string = string>(pattern: RegExp) {\n return new RegexpSchema<TInput>(pattern)\n}\n"]}
|
package/dist/schema/string.d.ts
CHANGED
|
@@ -1,8 +1,10 @@
|
|
|
1
|
-
import { InferStringFormat, Schema, StringFormat, ValidationContext } from '../core.js';
|
|
1
|
+
import { InferStringFormat, Restricted, Schema, StringFormat, UnknownString, ValidationContext } from '../core.js';
|
|
2
|
+
import { IfAny } from '../util/if-any.js';
|
|
2
3
|
/**
|
|
3
4
|
* Configuration options for string schema validation.
|
|
4
5
|
*
|
|
5
6
|
* @property format - Expected string format (e.g., 'datetime', 'uri', 'at-uri', 'did', 'handle', 'nsid', 'cid', 'tid', 'record-key', 'at-identifier', 'language')
|
|
7
|
+
* @property knownValues - Known string literal values for type narrowing
|
|
6
8
|
* @property minLength - Minimum length in UTF-8 bytes
|
|
7
9
|
* @property maxLength - Maximum length in UTF-8 bytes
|
|
8
10
|
* @property minGraphemes - Minimum number of grapheme clusters
|
|
@@ -10,6 +12,7 @@ import { InferStringFormat, Schema, StringFormat, ValidationContext } from '../c
|
|
|
10
12
|
*/
|
|
11
13
|
export type StringSchemaOptions = {
|
|
12
14
|
format?: StringFormat;
|
|
15
|
+
knownValues?: readonly string[];
|
|
13
16
|
minLength?: number;
|
|
14
17
|
maxLength?: number;
|
|
15
18
|
minGraphemes?: number;
|
|
@@ -29,14 +32,26 @@ export type StringSchemaOptions = {
|
|
|
29
32
|
* const result = schema.validate('2024-01-15T10:30:00Z')
|
|
30
33
|
* ```
|
|
31
34
|
*/
|
|
32
|
-
export declare class StringSchema<const TOptions extends StringSchemaOptions = StringSchemaOptions> extends Schema<TOptions extends {
|
|
35
|
+
export declare class StringSchema<const TOptions extends StringSchemaOptions = StringSchemaOptions> extends Schema<IfAny<TOptions, string, TOptions extends {
|
|
33
36
|
format: infer F extends StringFormat;
|
|
34
|
-
} ? InferStringFormat<F> :
|
|
35
|
-
readonly
|
|
36
|
-
|
|
37
|
+
} ? InferStringFormat<F> : TOptions extends {
|
|
38
|
+
knownValues: readonly (infer V extends string)[];
|
|
39
|
+
} ? V | UnknownString : string>> {
|
|
40
|
+
readonly type: "string";
|
|
41
|
+
readonly options: StringSchemaOptions;
|
|
42
|
+
constructor(options: TOptions);
|
|
37
43
|
validateInContext(input: unknown, ctx: ValidationContext): import("../core.js").ValidationResult<string>;
|
|
38
44
|
}
|
|
39
45
|
export declare function coerceToString(input: unknown): string | null;
|
|
46
|
+
declare function _string(): StringSchema<NonNullable<unknown>>;
|
|
47
|
+
declare function _string<const TOptions extends {
|
|
48
|
+
knownValues: StringSchemaOptions['knownValues'];
|
|
49
|
+
} & {
|
|
50
|
+
[K in Exclude<keyof StringSchemaOptions, 'knownValues'>]?: Restricted<`An options argument is required when using the "${K}" option`>;
|
|
51
|
+
}>(): StringSchema<IfAny<TOptions, any, {
|
|
52
|
+
knownValues: TOptions['knownValues'];
|
|
53
|
+
}>>;
|
|
54
|
+
declare function _string<const TOptions extends StringSchemaOptions>(options: TOptions | Omit<TOptions, 'knownValues'>): StringSchema<TOptions>;
|
|
40
55
|
/**
|
|
41
56
|
* Creates a string schema with optional format and length constraints.
|
|
42
57
|
*
|
|
@@ -64,5 +79,6 @@ export declare function coerceToString(input: unknown): string | null;
|
|
|
64
79
|
* const handleSchema = l.string({ format: 'handle', minLength: 3, maxLength: 253 })
|
|
65
80
|
* ```
|
|
66
81
|
*/
|
|
67
|
-
export declare const string:
|
|
82
|
+
export declare const string: typeof _string;
|
|
83
|
+
export {};
|
|
68
84
|
//# sourceMappingURL=string.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"string.d.ts","sourceRoot":"","sources":["../../src/schema/string.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AAgB,cAAc,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM,GAAG,IAAI,CAsC5D;AAED,iBAAS,OAAO,IAAI,YAAY,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC,CAAA;AACtD,iBAAS,OAAO,CAId,KAAK,CAAC,QAAQ,SAAS;IACrB,WAAW,EAAE,mBAAmB,CAAC,aAAa,CAAC,CAAA;CAChD,GAAG;KACD,CAAC,IAAI,OAAO,CACX,MAAM,mBAAmB,EACzB,aAAa,CACd,CAAC,CAAC,EAAE,UAAU,CAAC,mDAAmD,CAAC,UAAU,CAAC;CAChF,KACE,YAAY,CACf,KAAK,CAAC,QAAQ,EAAE,GAAG,EAAE;IAAE,WAAW,EAAE,QAAQ,CAAC,aAAa,CAAC,CAAA;CAAE,CAAC,CAC/D,CAAA;AACD,iBAAS,OAAO,CAAC,KAAK,CAAC,QAAQ,SAAS,mBAAmB,EAIzD,OAAO,EAAE,QAAQ,GAAG,IAAI,CAAC,QAAQ,EAAE,aAAa,CAAC,GAChD,YAAY,CAAC,QAAQ,CAAC,CAAA;AAKzB;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,eAAO,MAAM,MAAM,gBAAyC,CAAA"}
|
package/dist/schema/string.js
CHANGED
|
@@ -21,6 +21,12 @@ const token_js_1 = require("./token.js");
|
|
|
21
21
|
* ```
|
|
22
22
|
*/
|
|
23
23
|
class StringSchema extends core_js_1.Schema {
|
|
24
|
+
type = 'string';
|
|
25
|
+
// @NOTE since the _string utility allows omitting knownValues when TOptions
|
|
26
|
+
// *does* include it (since it's only used for typing), we cannot type options
|
|
27
|
+
// as TOptions directly since it may not actually include knownValues at
|
|
28
|
+
// runtime, making schema.options.knownValues potentially undefined even when
|
|
29
|
+
// TOptions includes it.
|
|
24
30
|
options;
|
|
25
31
|
constructor(options) {
|
|
26
32
|
super();
|
|
@@ -29,16 +35,16 @@ class StringSchema extends core_js_1.Schema {
|
|
|
29
35
|
validateInContext(input, ctx) {
|
|
30
36
|
const str = coerceToString(input);
|
|
31
37
|
if (str == null) {
|
|
32
|
-
return ctx.
|
|
38
|
+
return ctx.issueUnexpectedType(input, 'string');
|
|
33
39
|
}
|
|
34
40
|
let lazyUtf8Len;
|
|
35
|
-
const minLength = this.options
|
|
41
|
+
const minLength = this.options.minLength;
|
|
36
42
|
if (minLength != null) {
|
|
37
43
|
if ((lazyUtf8Len ??= (0, lex_data_1.utf8Len)(str)) < minLength) {
|
|
38
44
|
return ctx.issueTooSmall(str, 'string', minLength, lazyUtf8Len);
|
|
39
45
|
}
|
|
40
46
|
}
|
|
41
|
-
const maxLength = this.options
|
|
47
|
+
const maxLength = this.options.maxLength;
|
|
42
48
|
if (maxLength != null) {
|
|
43
49
|
// Optimization: we can avoid computing the UTF-8 length if the maximum
|
|
44
50
|
// possible length, in bytes, of the input JS string is smaller than the
|
|
@@ -51,7 +57,7 @@ class StringSchema extends core_js_1.Schema {
|
|
|
51
57
|
}
|
|
52
58
|
}
|
|
53
59
|
let lazyGraphLen;
|
|
54
|
-
const minGraphemes = this.options
|
|
60
|
+
const minGraphemes = this.options.minGraphemes;
|
|
55
61
|
if (minGraphemes != null) {
|
|
56
62
|
// Optimization: avoid counting graphemes if the length check already fails
|
|
57
63
|
if (str.length < minGraphemes) {
|
|
@@ -61,13 +67,13 @@ class StringSchema extends core_js_1.Schema {
|
|
|
61
67
|
return ctx.issueTooSmall(str, 'grapheme', minGraphemes, lazyGraphLen);
|
|
62
68
|
}
|
|
63
69
|
}
|
|
64
|
-
const maxGraphemes = this.options
|
|
70
|
+
const maxGraphemes = this.options.maxGraphemes;
|
|
65
71
|
if (maxGraphemes != null) {
|
|
66
72
|
if ((lazyGraphLen ??= (0, lex_data_1.graphemeLen)(str)) > maxGraphemes) {
|
|
67
73
|
return ctx.issueTooBig(str, 'grapheme', maxGraphemes, lazyGraphLen);
|
|
68
74
|
}
|
|
69
75
|
}
|
|
70
|
-
const format = this.options
|
|
76
|
+
const format = this.options.format;
|
|
71
77
|
if (format != null && !(0, core_js_1.isStringFormat)(str, format)) {
|
|
72
78
|
return ctx.issueInvalidFormat(str, format);
|
|
73
79
|
}
|
|
@@ -111,6 +117,9 @@ function coerceToString(input) {
|
|
|
111
117
|
return null;
|
|
112
118
|
}
|
|
113
119
|
}
|
|
120
|
+
function _string(options = {}) {
|
|
121
|
+
return new StringSchema(options);
|
|
122
|
+
}
|
|
114
123
|
/**
|
|
115
124
|
* Creates a string schema with optional format and length constraints.
|
|
116
125
|
*
|
|
@@ -138,7 +147,5 @@ function coerceToString(input) {
|
|
|
138
147
|
* const handleSchema = l.string({ format: 'handle', minLength: 3, maxLength: 253 })
|
|
139
148
|
* ```
|
|
140
149
|
*/
|
|
141
|
-
exports.string = (0, memoize_js_1.memoizedOptions)(
|
|
142
|
-
return new StringSchema(options);
|
|
143
|
-
});
|
|
150
|
+
exports.string = (0, memoize_js_1.memoizedOptions)(_string);
|
|
144
151
|
//# sourceMappingURL=string.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"string.js","sourceRoot":"","sources":["../../src/schema/string.ts"],"names":[],"mappings":";;;AA4GA,wCAsCC;AAlJD,gDAA+D;AAC/D,wCAMmB;AACnB,mDAAoD;AACpD,yCAAwC;AAmBxC;;;;;;;;;;;;;GAaG;AACH,MAAa,YAEX,SAAQ,gBAIT;IACsB;IAArB,YAAqB,OAAkB;QACrC,KAAK,EAAE,CAAA;QADY,YAAO,GAAP,OAAO,CAAW;IAEvC,CAAC;IAED,iBAAiB,CAAC,KAAc,EAAE,GAAsB;QACtD,MAAM,GAAG,GAAG,cAAc,CAAC,KAAK,CAAC,CAAA;QACjC,IAAI,GAAG,IAAI,IAAI,EAAE,CAAC;YAChB,OAAO,GAAG,CAAC,gBAAgB,CAAC,KAAK,EAAE,QAAQ,CAAC,CAAA;QAC9C,CAAC;QAED,IAAI,WAAmB,CAAA;QAEvB,MAAM,SAAS,GAAG,IAAI,CAAC,OAAO,EAAE,SAAS,CAAA;QACzC,IAA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gBACzB,OAAO,KAAK,CAAC,QAAQ,EAAE,CAAA;YACzB,CAAC;YAED,MAAM,GAAG,GAAG,IAAA,gBAAK,EAAC,KAAK,CAAC,CAAA;YACxB,IAAI,GAAG;gBAAE,OAAO,GAAG,CAAC,QAAQ,EAAE,CAAA;YAE9B,IAAI,KAAK,YAAY,MAAM,EAAE,CAAC;gBAC5B,OAAO,KAAK,CAAC,OAAO,EAAE,CAAA;YACxB,CAAC;QACH,CAAC;QAED,gBAAgB;QAChB;YACE,OAAO,IAAI,CAAA;IACf,CAAC;AACH,CAAC;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACU,QAAA,MAAM,GAAiB,IAAA,4BAAe,EAAC,UAElD,OAAiC;IACjC,OAAO,IAAI,YAAY,CAAI,OAAO,CAAC,CAAA;AACrC,CAAC,CAAC,CAAA","sourcesContent":["import { graphemeLen, ifCid, utf8Len } from '@atproto/lex-data'\nimport {\n InferStringFormat,\n Schema,\n StringFormat,\n ValidationContext,\n isStringFormat,\n} from '../core.js'\nimport { memoizedOptions } from '../util/memoize.js'\nimport { TokenSchema } from './token.js'\n\n/**\n * Configuration options for string schema validation.\n *\n * @property format - Expected string format (e.g., 'datetime', 'uri', 'at-uri', 'did', 'handle', 'nsid', 'cid', 'tid', 'record-key', 'at-identifier', 'language')\n * @property minLength - Minimum length in UTF-8 bytes\n * @property maxLength - Maximum length in UTF-8 bytes\n * @property minGraphemes - Minimum number of grapheme clusters\n * @property maxGraphemes - Maximum number of grapheme clusters\n */\nexport type StringSchemaOptions = {\n format?: StringFormat\n minLength?: number\n maxLength?: number\n minGraphemes?: number\n maxGraphemes?: number\n}\n\n/**\n * Schema for validating string values with optional format and length constraints.\n *\n * Supports various string formats defined in the Lexicon specification, as well as\n * length constraints measured in UTF-8 bytes or grapheme clusters.\n *\n * @template TOptions - The configuration options type\n *\n * @example\n * ```ts\n * const schema = new StringSchema({ format: 'datetime', maxLength: 64 })\n * const result = schema.validate('2024-01-15T10:30:00Z')\n * ```\n */\nexport class StringSchema<\n const TOptions extends StringSchemaOptions = StringSchemaOptions,\n> extends Schema<\n TOptions extends { format: infer F extends StringFormat }\n ? InferStringFormat<F>\n : string\n> {\n constructor(readonly options?: TOptions) {\n super()\n }\n\n validateInContext(input: unknown, ctx: ValidationContext) {\n const str = coerceToString(input)\n if (str == null) {\n return ctx.issueInvalidType(input, 'string')\n }\n\n let lazyUtf8Len: number\n\n const minLength = this.options?.minLength\n if (minLength != null) {\n if ((lazyUtf8Len ??= utf8Len(str)) < minLength) {\n return ctx.issueTooSmall(str, 'string', minLength, lazyUtf8Len)\n }\n }\n\n const maxLength = this.options?.maxLength\n if (maxLength != null) {\n // Optimization: we can avoid computing the UTF-8 length if the maximum\n // possible length, in bytes, of the input JS string is smaller than the\n // maxLength (in UTF-8 string bytes).\n if (str.length * 3 <= maxLength) {\n // Input string so small it can't possibly exceed maxLength\n } else if ((lazyUtf8Len ??= utf8Len(str)) > maxLength) {\n return ctx.issueTooBig(str, 'string', maxLength, lazyUtf8Len)\n }\n }\n\n let lazyGraphLen: number\n\n const minGraphemes = this.options?.minGraphemes\n if (minGraphemes != null) {\n // Optimization: avoid counting graphemes if the length check already fails\n if (str.length < minGraphemes) {\n return ctx.issueTooSmall(str, 'grapheme', minGraphemes, str.length)\n } else if ((lazyGraphLen ??= graphemeLen(str)) < minGraphemes) {\n return ctx.issueTooSmall(str, 'grapheme', minGraphemes, lazyGraphLen)\n }\n }\n\n const maxGraphemes = this.options?.maxGraphemes\n if (maxGraphemes != null) {\n if ((lazyGraphLen ??= graphemeLen(str)) > maxGraphemes) {\n return ctx.issueTooBig(str, 'grapheme', maxGraphemes, lazyGraphLen)\n }\n }\n\n const format = this.options?.format\n if (format != null && !isStringFormat(str, format)) {\n return ctx.issueInvalidFormat(str, format)\n }\n\n return ctx.success(str)\n }\n}\n\nexport function coerceToString(input: unknown): string | null {\n switch (typeof input) {\n // @NOTE We do *not* coerce numbers/booleans to strings because that can\n // lead to them being accepted as string instead of being coerced to\n // number/boolean when the input is a string and the expected result is\n // number/boolean (e.g. in params).\n case 'string':\n return input\n case 'object': {\n if (input == null) return null\n\n // @NOTE Allow using TokenSchema instances in places expecting strings,\n // converting them to their string value.\n if (input instanceof TokenSchema) {\n return input.toString()\n }\n\n if (input instanceof Date) {\n if (Number.isNaN(input.getTime())) return null\n return input.toISOString()\n }\n\n if (input instanceof URL) {\n return input.toString()\n }\n\n const cid = ifCid(input)\n if (cid) return cid.toString()\n\n if (input instanceof String) {\n return input.valueOf()\n }\n }\n\n // falls through\n default:\n return null\n }\n}\n\n/**\n * Creates a string schema with optional format and length constraints.\n *\n * Strings can be validated against various formats (datetime, uri, did, handle, etc.)\n * and constrained by length in UTF-8 bytes or grapheme clusters.\n *\n * @param options - Optional configuration for format and length constraints\n * @returns A new {@link StringSchema} instance\n *\n * @example\n * ```ts\n * // Basic string\n * const nameSchema = l.string()\n *\n * // With format validation\n * const dateSchema = l.string({ format: 'datetime' })\n *\n * // With length constraints (UTF-8 bytes)\n * const bioSchema = l.string({ maxLength: 256 })\n *\n * // With grapheme constraints (user-perceived characters)\n * const displayNameSchema = l.string({ maxGraphemes: 64 })\n *\n * // Combining constraints\n * const handleSchema = l.string({ format: 'handle', minLength: 3, maxLength: 253 })\n * ```\n */\nexport const string = /*#__PURE__*/ memoizedOptions(function <\n const O extends StringSchemaOptions = NonNullable<unknown>,\n>(options?: StringSchemaOptions & O) {\n return new StringSchema<O>(options)\n})\n"]}
|
|
1
|
+
{"version":3,"file":"string.js","sourceRoot":"","sources":["../../src/schema/string.ts"],"names":[],"mappings":";;;AAiIA,wCAsCC;AAvKD,gDAA+D;AAC/D,wCAQmB;AAEnB,mDAAoD;AACpD,yCAAwC;AAqBxC;;;;;;;;;;;;;GAaG;AACH,MAAa,YAEX,SAAQ,gBAUT;IACU,IAAI,GAAG,QAAiB,CAAA;IAEjC,4EAA4E;IAC5E,8EAA8E;IAC9E,wEAAwE;IACxE,6EAA6E;IAC7E,wBAAwB;I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AC,CAAC;YACd,IAAI,KAAK,IAAI,IAAI;gBAAE,OAAO,IAAI,CAAA;YAE9B,uEAAuE;YACvE,yCAAyC;YACzC,IAAI,KAAK,YAAY,sBAAW,EAAE,CAAC;gBACjC,OAAO,KAAK,CAAC,QAAQ,EAAE,CAAA;YACzB,CAAC;YAED,IAAI,KAAK,YAAY,IAAI,EAAE,CAAC;gBAC1B,IAAI,MAAM,CAAC,KAAK,CAAC,KAAK,CAAC,OAAO,EAAE,CAAC;oBAAE,OAAO,IAAI,CAAA;gBAC9C,OAAO,KAAK,CAAC,WAAW,EAAE,CAAA;YAC5B,CAAC;YAED,IAAI,KAAK,YAAY,GAAG,EAAE,CAAC;gBACzB,OAAO,KAAK,CAAC,QAAQ,EAAE,CAAA;YACzB,CAAC;YAED,MAAM,GAAG,GAAG,IAAA,gBAAK,EAAC,KAAK,CAAC,CAAA;YACxB,IAAI,GAAG;gBAAE,OAAO,GAAG,CAAC,QAAQ,EAAE,CAAA;YAE9B,IAAI,KAAK,YAAY,MAAM,EAAE,CAAC;gBAC5B,OAAO,KAAK,CAAC,OAAO,EAAE,CAAA;YACxB,CAAC;QACH,CAAC;QAED,gBAAgB;QAChB;YACE,OAAO,IAAI,CAAA;IACf,CAAC;AACH,CAAC;AAwBD,SAAS,OAAO,CAAC,UAA+B,EAAE;IAChD,OAAO,IAAI,YAAY,CAAC,OAAO,CAAC,CAAA;AAClC,CAAC;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACU,QAAA,MAAM,GAAiB,IAAA,4BAAe,EAAC,OAAO,CAAC,CAAA","sourcesContent":["import { graphemeLen, ifCid, utf8Len } from '@atproto/lex-data'\nimport {\n InferStringFormat,\n Restricted,\n Schema,\n StringFormat,\n UnknownString,\n ValidationContext,\n isStringFormat,\n} from '../core.js'\nimport { IfAny } from '../util/if-any.js'\nimport { memoizedOptions } from '../util/memoize.js'\nimport { TokenSchema } from './token.js'\n\n/**\n * Configuration options for string schema validation.\n *\n * @property format - Expected string format (e.g., 'datetime', 'uri', 'at-uri', 'did', 'handle', 'nsid', 'cid', 'tid', 'record-key', 'at-identifier', 'language')\n * @property knownValues - Known string literal values for type narrowing\n * @property minLength - Minimum length in UTF-8 bytes\n * @property maxLength - Maximum length in UTF-8 bytes\n * @property minGraphemes - Minimum number of grapheme clusters\n * @property maxGraphemes - Maximum number of grapheme clusters\n */\nexport type StringSchemaOptions = {\n format?: StringFormat\n knownValues?: readonly string[]\n minLength?: number\n maxLength?: number\n minGraphemes?: number\n maxGraphemes?: number\n}\n\n/**\n * Schema for validating string values with optional format and length constraints.\n *\n * Supports various string formats defined in the Lexicon specification, as well as\n * length constraints measured in UTF-8 bytes or grapheme clusters.\n *\n * @template TOptions - The configuration options type\n *\n * @example\n * ```ts\n * const schema = new StringSchema({ format: 'datetime', maxLength: 64 })\n * const result = schema.validate('2024-01-15T10:30:00Z')\n * ```\n */\nexport class StringSchema<\n const TOptions extends StringSchemaOptions = StringSchemaOptions,\n> extends Schema<\n IfAny<\n TOptions,\n string,\n TOptions extends { format: infer F extends StringFormat }\n ? InferStringFormat<F>\n : TOptions extends { knownValues: readonly (infer V extends string)[] }\n ? V | UnknownString\n : string\n >\n> {\n readonly type = 'string' as const\n\n // @NOTE since the _string utility allows omitting knownValues when TOptions\n // *does* include it (since it's only used for typing), we cannot type options\n // as TOptions directly since it may not actually include knownValues at\n // runtime, making schema.options.knownValues potentially undefined even when\n // TOptions includes it.\n readonly options: StringSchemaOptions\n\n constructor(options: TOptions) {\n super()\n this.options = options\n }\n\n validateInContext(input: unknown, ctx: ValidationContext) {\n const str = coerceToString(input)\n if (str == null) {\n return ctx.issueUnexpectedType(input, 'string')\n }\n\n let lazyUtf8Len: number\n\n const minLength = this.options.minLength\n if (minLength != null) {\n if ((lazyUtf8Len ??= utf8Len(str)) < minLength) {\n return ctx.issueTooSmall(str, 'string', minLength, lazyUtf8Len)\n }\n }\n\n const maxLength = this.options.maxLength\n if (maxLength != null) {\n // Optimization: we can avoid computing the UTF-8 length if the maximum\n // possible length, in bytes, of the input JS string is smaller than the\n // maxLength (in UTF-8 string bytes).\n if (str.length * 3 <= maxLength) {\n // Input string so small it can't possibly exceed maxLength\n } else if ((lazyUtf8Len ??= utf8Len(str)) > maxLength) {\n return ctx.issueTooBig(str, 'string', maxLength, lazyUtf8Len)\n }\n }\n\n let lazyGraphLen: number\n\n const minGraphemes = this.options.minGraphemes\n if (minGraphemes != null) {\n // Optimization: avoid counting graphemes if the length check already fails\n if (str.length < minGraphemes) {\n return ctx.issueTooSmall(str, 'grapheme', minGraphemes, str.length)\n } else if ((lazyGraphLen ??= graphemeLen(str)) < minGraphemes) {\n return ctx.issueTooSmall(str, 'grapheme', minGraphemes, lazyGraphLen)\n }\n }\n\n const maxGraphemes = this.options.maxGraphemes\n if (maxGraphemes != null) {\n if ((lazyGraphLen ??= graphemeLen(str)) > maxGraphemes) {\n return ctx.issueTooBig(str, 'grapheme', maxGraphemes, lazyGraphLen)\n }\n }\n\n const format = this.options.format\n if (format != null && !isStringFormat(str, format)) {\n return ctx.issueInvalidFormat(str, format)\n }\n\n return ctx.success(str)\n }\n}\n\nexport function coerceToString(input: unknown): string | null {\n switch (typeof input) {\n // @NOTE We do *not* coerce numbers/booleans to strings because that can\n // lead to them being accepted as string instead of being coerced to\n // number/boolean when the input is a string and the expected result is\n // number/boolean (e.g. in params).\n case 'string':\n return input\n case 'object': {\n if (input == null) return null\n\n // @NOTE Allow using TokenSchema instances in places expecting strings,\n // converting them to their string value.\n if (input instanceof TokenSchema) {\n return input.toString()\n }\n\n if (input instanceof Date) {\n if (Number.isNaN(input.getTime())) return null\n return input.toISOString()\n }\n\n if (input instanceof URL) {\n return input.toString()\n }\n\n const cid = ifCid(input)\n if (cid) return cid.toString()\n\n if (input instanceof String) {\n return input.valueOf()\n }\n }\n\n // falls through\n default:\n return null\n }\n}\n\nfunction _string(): StringSchema<NonNullable<unknown>>\nfunction _string<\n // Allow calling `string<{ knownValues: [...] }>()` without passing an options\n // object, since knownValues is only used for typing and has no runtime\n // effect, so it can be safely omitted at runtime.\n const TOptions extends {\n knownValues: StringSchemaOptions['knownValues']\n } & {\n [K in Exclude<\n keyof StringSchemaOptions,\n 'knownValues'\n >]?: Restricted<`An options argument is required when using the \"${K}\" option`>\n },\n>(): StringSchema<\n IfAny<TOptions, any, { knownValues: TOptions['knownValues'] }>\n>\nfunction _string<const TOptions extends StringSchemaOptions>(\n // If TOptions is explicitly provided (e.g. `string<{ ... }>({ ... })`), we\n // allow the actual options argument to omit the \"knownValues\" property since\n // it's only used for inferring the type and has no runtime effect.\n options: TOptions | Omit<TOptions, 'knownValues'>,\n): StringSchema<TOptions>\nfunction _string(options: StringSchemaOptions = {}) {\n return new StringSchema(options)\n}\n\n/**\n * Creates a string schema with optional format and length constraints.\n *\n * Strings can be validated against various formats (datetime, uri, did, handle, etc.)\n * and constrained by length in UTF-8 bytes or grapheme clusters.\n *\n * @param options - Optional configuration for format and length constraints\n * @returns A new {@link StringSchema} instance\n *\n * @example\n * ```ts\n * // Basic string\n * const nameSchema = l.string()\n *\n * // With format validation\n * const dateSchema = l.string({ format: 'datetime' })\n *\n * // With length constraints (UTF-8 bytes)\n * const bioSchema = l.string({ maxLength: 256 })\n *\n * // With grapheme constraints (user-perceived characters)\n * const displayNameSchema = l.string({ maxGraphemes: 64 })\n *\n * // Combining constraints\n * const handleSchema = l.string({ format: 'handle', minLength: 3, maxLength: 253 })\n * ```\n */\nexport const string = /*#__PURE__*/ memoizedOptions(_string)\n"]}
|
package/dist/schema/token.d.ts
CHANGED
|
@@ -16,6 +16,7 @@ import { NsidString, Schema, ValidationContext } from '../core.js';
|
|
|
16
16
|
*/
|
|
17
17
|
export declare class TokenSchema<const TValue extends string = string> extends Schema<TValue> {
|
|
18
18
|
readonly value: TValue;
|
|
19
|
+
readonly type: "token";
|
|
19
20
|
constructor(value: TValue);
|
|
20
21
|
validateInContext(input: unknown, ctx: ValidationContext): import("../core.js").ValidationResult<TValue>;
|
|
21
22
|
toJSON(): string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"token.d.ts","sourceRoot":"","sources":["../../src/schema/token.ts"],"names":[],"mappings":"AAAA,OAAO,EAAS,UAAU,EAAE,MAAM,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAA;AAEzE;;;;;;;;;;;;;;GAcG;AACH,qBAAa,WAAW,CACtB,KAAK,CAAC,MAAM,SAAS,MAAM,GAAG,MAAM,CACpC,SAAQ,MAAM,CAAC,MAAM,CAAC;
|
|
1
|
+
{"version":3,"file":"token.d.ts","sourceRoot":"","sources":["../../src/schema/token.ts"],"names":[],"mappings":"AAAA,OAAO,EAAS,UAAU,EAAE,MAAM,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAA;AAEzE;;;;;;;;;;;;;;GAcG;AACH,qBAAa,WAAW,CACtB,KAAK,CAAC,MAAM,SAAS,MAAM,GAAG,MAAM,CACpC,SAAQ,MAAM,CAAC,MAAM,CAAC;IAGV,QAAQ,CAAC,KAAK,EAAE,MAAM;IAFlC,QAAQ,CAAC,IAAI,EAAG,OAAO,CAAS;gBAEX,KAAK,EAAE,MAAM;IAIlC,iBAAiB,CAAC,KAAK,EAAE,OAAO,EAAE,GAAG,EAAE,iBAAiB;IAqBxD,MAAM,IAAI,MAAM;IAIhB,QAAQ,IAAI,MAAM;CAGnB;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AAEH,wBAAgB,KAAK,CACnB,KAAK,CAAC,CAAC,SAAS,UAAU,EAC1B,KAAK,CAAC,CAAC,SAAS,MAAM,GAAG,MAAM,EAC/B,IAAI,EAAE,CAAC,EAAE,IAAI,GAAE,CAAe,iDAE/B"}
|
package/dist/schema/token.js
CHANGED
|
@@ -20,6 +20,7 @@ const core_js_1 = require("../core.js");
|
|
|
20
20
|
*/
|
|
21
21
|
class TokenSchema extends core_js_1.Schema {
|
|
22
22
|
value;
|
|
23
|
+
type = 'token';
|
|
23
24
|
constructor(value) {
|
|
24
25
|
super();
|
|
25
26
|
this.value = value;
|
|
@@ -34,7 +35,7 @@ class TokenSchema extends core_js_1.Schema {
|
|
|
34
35
|
return ctx.success(this.value);
|
|
35
36
|
}
|
|
36
37
|
if (typeof input !== 'string') {
|
|
37
|
-
return ctx.
|
|
38
|
+
return ctx.issueUnexpectedType(input, 'token');
|
|
38
39
|
}
|
|
39
40
|
return ctx.issueInvalidValue(input, [this.value]);
|
|
40
41
|
}
|
package/dist/schema/token.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"token.js","sourceRoot":"","sources":["../../src/schema/token.ts"],"names":[],"mappings":";;;
|
|
1
|
+
{"version":3,"file":"token.js","sourceRoot":"","sources":["../../src/schema/token.ts"],"names":[],"mappings":";;;AAyFA,sBAKC;AA9FD,wCAAyE;AAEzE;;;;;;;;;;;;;;GAcG;AACH,MAAa,WAEX,SAAQ,gBAAc;IAGD;IAFZ,IAAI,GAAG,OAAgB,CAAA;IAEhC,YAAqB,KAAa;QAChC,KAAK,EAAE,CAAA;QADY,UAAK,GAAL,KAAK,CAAQ;IAElC,CAAC;IAED,iBAAiB,CAAC,KAAc,EAAE,GAAsB;QACtD,IAAI,KAAK,KAAK,IAAI,CAAC,KAAK,EAAE,CAAC;YACzB,OAAO,GAAG,CAAC,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,CAAA;QAChC,CAAC;QAED,0EAA0E;QAC1E,eAAe;QACf,IAAI,KAAK,YAAY,WAAW,IAAI,KAAK,CAAC,KAAK,KAAK,IAAI,CAAC,KAAK,EAAE,CAAC;YAC/D,OAAO,GAAG,CAAC,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,CAAA;QAChC,CAAC;QAED,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE,CAAC;YAC9B,OAAO,GAAG,CAAC,mBAAmB,CAAC,KAAK,EAAE,OAAO,CAAC,CAAA;QAChD,CAAC;QAED,OAAO,GAAG,CAAC,iBAAiB,CAAC,KAAK,EAAE,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAA;IACnD,CAAC;IAED,yEAAyE;IACzE,cAAc;IAEd,MAAM;QACJ,OAAO,IAAI,CAAC,KAAK,CAAA;IACnB,CAAC;IAED,QAAQ;QACN,OAAO,IAAI,CAAC,KAAK,CAAA;IACnB,CAAC;CACF;AArCD,kCAqCC;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AACH,wBAAwB;AACxB,SAAgB,KAAK,CAGnB,IAAO,EAAE,OAAU,MAAW;IAC9B,OAAO,IAAI,WAAW,CAAC,IAAA,eAAK,EAAC,IAAI,EAAE,IAAI,CAAC,CAAC,CAAA;AAC3C,CAAC","sourcesContent":["import { $type, NsidString, Schema, ValidationContext } from '../core.js'\n\n/**\n * Schema for Lexicon token values.\n *\n * Tokens are named constants in Lexicon, identified by their NSID and hash.\n * They validate to their string value (e.g., 'app.bsky.feed.defs#requestLess').\n * TokenSchema instances can also be used as values themselves.\n *\n * @template TValue - The token string literal type\n *\n * @example\n * ```ts\n * const schema = new TokenSchema('app.bsky.feed.defs#requestLess')\n * schema.validate('app.bsky.feed.defs#requestLess') // success\n * ```\n */\nexport class TokenSchema<\n const TValue extends string = string,\n> extends Schema<TValue> {\n readonly type = 'token' as const\n\n constructor(readonly value: TValue) {\n super()\n }\n\n validateInContext(input: unknown, ctx: ValidationContext) {\n if (input === this.value) {\n return ctx.success(this.value)\n }\n\n // @NOTE: allow using the token instance itself (but convert to the actual\n // token value)\n if (input instanceof TokenSchema && input.value === this.value) {\n return ctx.success(this.value)\n }\n\n if (typeof input !== 'string') {\n return ctx.issueUnexpectedType(input, 'token')\n }\n\n return ctx.issueInvalidValue(input, [this.value])\n }\n\n // When using the TokenSchema instance as data, let's serialize it to the\n // token value\n\n toJSON(): string {\n return this.value\n }\n\n toString(): string {\n return this.value\n }\n}\n\n/**\n * Creates a token schema for Lexicon named constants.\n *\n * Tokens are used in Lexicon as named constants or enum-like values.\n * The token instance can be used both as a schema validator and as\n * the token value itself (it serializes to its string value).\n *\n * @param nsid - The NSID part of the token\n * @param hash - The hash part of the token (defaults to 'main')\n * @returns A new {@link TokenSchema} instance\n *\n * @example\n * ```ts\n * // Define tokens\n * const requestLess = l.token('app.bsky.feed.defs', 'requestLess')\n * const requestMore = l.token('app.bsky.feed.defs', 'requestMore')\n *\n * // Use as a value\n * console.log(requestLess.toString()) // 'app.bsky.feed.defs#requestLess'\n *\n * // Use in union for validation\n * const feedbackSchema = l.union([requestLess, requestMore])\n *\n * // Validate\n * feedbackSchema.parse('app.bsky.feed.defs#requestLess') // success\n *\n * // Token instances can be used as values in other schemas\n * const feedbackRequest = l.object({\n * feedback: requestLess, // Accepts the token value\n * })\n * ```\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function token<\n const N extends NsidString,\n const H extends string = 'main',\n>(nsid: N, hash: H = 'main' as H) {\n return new TokenSchema($type(nsid, hash))\n}\n"]}
|
|
@@ -1,4 +1,11 @@
|
|
|
1
1
|
import { $Type, $TypeOf, $Typed, $TypedMaybe, InferInput, InferOutput, NsidString, Schema, Unknown$TypedObject, ValidationContext, Validator } from '../core.js';
|
|
2
|
+
export type MaybeTypedObject<TType extends $Type, TValue extends {
|
|
3
|
+
$type?: unknown;
|
|
4
|
+
} = {
|
|
5
|
+
$type?: unknown;
|
|
6
|
+
}> = TValue extends {
|
|
7
|
+
$type?: TType;
|
|
8
|
+
} ? TValue : $TypedMaybe<Exclude<TValue, Unknown$TypedObject>, TType>;
|
|
2
9
|
/**
|
|
3
10
|
* Schema for typed objects in Lexicon unions.
|
|
4
11
|
*
|
|
@@ -22,23 +29,12 @@ export declare class TypedObjectSchema<const TType extends $Type = $Type, const
|
|
|
22
29
|
}> = any> extends Schema<$TypedMaybe<InferInput<TShape>, TType>, $TypedMaybe<InferOutput<TShape>, TType>> {
|
|
23
30
|
readonly $type: TType;
|
|
24
31
|
readonly schema: TShape;
|
|
32
|
+
readonly type: "typedObject";
|
|
25
33
|
constructor($type: TType, schema: TShape);
|
|
26
|
-
isTypeOf<
|
|
27
|
-
$type?: TType;
|
|
28
|
-
} ? X : $TypedMaybe<Exclude<X, Unknown$TypedObject>, TType>;
|
|
34
|
+
isTypeOf<TValue extends Record<string, unknown>>(value: TValue): value is MaybeTypedObject<TType, TValue>;
|
|
29
35
|
build(input: Omit<InferInput<this>, '$type'>): $Typed<InferOutput<this>, TType>;
|
|
30
|
-
$isTypeOf<
|
|
31
|
-
|
|
32
|
-
} ? X : Exclude<X, Unknown$TypedObject> & {
|
|
33
|
-
$type?: TType | undefined;
|
|
34
|
-
} extends infer T ? { [K in keyof T]: (Exclude<X, Unknown$TypedObject> & {
|
|
35
|
-
$type?: TType | undefined;
|
|
36
|
-
})[K]; } : never;
|
|
37
|
-
$build(input: Omit<InferInput<this>, '$type'>): InferOutput<this> & {
|
|
38
|
-
$type: TType;
|
|
39
|
-
} extends infer T ? { [K in keyof T]: (InferOutput<this> & {
|
|
40
|
-
$type: TType;
|
|
41
|
-
})[K]; } : never;
|
|
36
|
+
$isTypeOf<TValue extends Record<string, unknown>>(value: TValue): value is MaybeTypedObject<TType, TValue>;
|
|
37
|
+
$build(input: Omit<InferInput<this>, '$type'>): $Typed<InferOutput<this>, TType>;
|
|
42
38
|
validateInContext(input: unknown, ctx: ValidationContext): import("../core.js").ValidationResult<InferInput<TShape>>;
|
|
43
39
|
}
|
|
44
40
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"typed-object.d.ts","sourceRoot":"","sources":["../../src/schema/typed-object.ts"],"names":[],"mappings":"AACA,OAAO,EACL,KAAK,EACL,OAAO,EACP,MAAM,EACN,WAAW,EAGX,UAAU,EACV,WAAW,EACX,UAAU,EACV,MAAM,EACN,mBAAmB,EACnB,iBAAiB,EACjB,SAAS,EACV,MAAM,YAAY,CAAA;AAEnB;;;;;;;;;;;;;;;;;GAiBG;AACH,qBAAa,iBAAiB,CAC5B,KAAK,CAAC,KAAK,SAAS,KAAK,GAAG,KA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AAS;IAAE,KAAK,CAAC,EAAE,KAAK,CAAA;CAAE,EACrD,IAAI,EAAE,CAAC,SAAS;IAAE,KAAK,CAAC,EAAE,MAAM,CAAC,SAAS,MAAM,CAAA;CAAE,GAC9C,CAAC,SAAS,GAAG,MAAM,CAAC,IAAI,MAAM,EAAE,GAC9B,CAAC,GACD,CAAC,GACH,KAAK,EACT,IAAI,EAAE,CAAC,SAAS;IAAE,KAAK,CAAC,EAAE,MAAM,CAAC,SAAS,MAAM,CAAA;CAAE,GAC9C,CAAC,SAAS,GAAG,MAAM,IAAI,MAAM,CAAC,EAAE,GAC9B,CAAC,GACD,MAAM,GACR,KAAK,EACT,SAAS,EAAE,SAAS,CAAC,IAAI,CAAC,CAAC,EAAE,OAAO,CAAC,CAAC,GACrC,iBAAiB,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,SAAS,CAAC,CAAC,CAAC,CAAC,CAAA"}
|
|
@@ -25,6 +25,7 @@ const core_js_1 = require("../core.js");
|
|
|
25
25
|
class TypedObjectSchema extends core_js_1.Schema {
|
|
26
26
|
$type;
|
|
27
27
|
schema;
|
|
28
|
+
type = 'typedObject';
|
|
28
29
|
constructor($type, schema) {
|
|
29
30
|
super();
|
|
30
31
|
this.$type = $type;
|
|
@@ -44,7 +45,7 @@ class TypedObjectSchema extends core_js_1.Schema {
|
|
|
44
45
|
}
|
|
45
46
|
validateInContext(input, ctx) {
|
|
46
47
|
if (!(0, lex_data_1.isPlainObject)(input)) {
|
|
47
|
-
return ctx.
|
|
48
|
+
return ctx.issueUnexpectedType(input, 'object');
|
|
48
49
|
}
|
|
49
50
|
if ('$type' in input &&
|
|
50
51
|
input.$type !== undefined &&
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"typed-object.js","sourceRoot":"","sources":["../../src/schema/typed-object.ts"],"names":[],"mappings":";;;
|
|
1
|
+
{"version":3,"file":"typed-object.js","sourceRoot":"","sources":["../../src/schema/typed-object.ts"],"names":[],"mappings":";;;AAwK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IACzC,CAAC;CACF;AA1DD,8CA0DC;AAmED,wBAAwB;AACxB,SAAgB,WAAW,CAIzB,IAAO,EAAE,IAAO,EAAE,SAAY;IAC9B,OAAO,IAAI,iBAAiB,CAAiB,IAAA,eAAK,EAAC,IAAI,EAAE,IAAI,CAAC,EAAE,SAAS,CAAC,CAAA;AAC5E,CAAC","sourcesContent":["import { isPlainObject } from '@atproto/lex-data'\nimport {\n $Type,\n $TypeOf,\n $Typed,\n $TypedMaybe,\n $type,\n $typed,\n InferInput,\n InferOutput,\n NsidString,\n Schema,\n Unknown$TypedObject,\n ValidationContext,\n Validator,\n} from '../core.js'\n\nexport type MaybeTypedObject<\n TType extends $Type,\n TValue extends { $type?: unknown } = { $type?: unknown },\n> = TValue extends { $type?: TType }\n ? TValue\n : $TypedMaybe<Exclude<TValue, Unknown$TypedObject>, TType>\n\n/**\n * Schema for typed objects in Lexicon unions.\n *\n * Typed objects have a `$type` field that identifies which variant they are\n * in a union. The `$type` can be omitted in input (it's implicit), but if\n * present, it must match the expected value.\n *\n * @template TType - The $type string literal type\n * @template TShape - The validator type for the object's shape\n *\n * @example\n * ```ts\n * const schema = new TypedObjectSchema(\n * 'app.bsky.embed.images#view',\n * l.object({ images: l.array(imageSchema) })\n * )\n * ```\n */\nexport class TypedObjectSchema<\n const TType extends $Type = $Type,\n const TShape extends Validator<{ [k: string]: unknown }> = any,\n> extends Schema<\n $TypedMaybe<InferInput<TShape>, TType>,\n $TypedMaybe<InferOutput<TShape>, TType>\n> {\n readonly type = 'typedObject' as const\n\n constructor(\n readonly $type: TType,\n readonly schema: TShape,\n ) {\n super()\n }\n\n isTypeOf<TValue extends Record<string, unknown>>(\n value: TValue,\n ): value is MaybeTypedObject<TType, TValue> {\n return value.$type === undefined || value.$type === this.$type\n }\n\n build(\n input: Omit<InferInput<this>, '$type'>,\n ): $Typed<InferOutput<this>, TType> {\n return this.parse($typed(input, this.$type)) as $Typed<\n InferOutput<this>,\n TType\n >\n }\n\n $isTypeOf<TValue extends Record<string, unknown>>(\n value: TValue,\n ): value is MaybeTypedObject<TType, TValue> {\n return this.isTypeOf(value)\n }\n\n $build(\n input: Omit<InferInput<this>, '$type'>,\n ): $Typed<InferOutput<this>, TType> {\n return this.build(input)\n }\n\n validateInContext(input: unknown, ctx: ValidationContext) {\n if (!isPlainObject(input)) {\n return ctx.issueUnexpectedType(input, 'object')\n }\n\n if (\n '$type' in input &&\n input.$type !== undefined &&\n input.$type !== this.$type\n ) {\n return ctx.issueInvalidPropertyValue(input, '$type', [this.$type])\n }\n\n return ctx.validate(input, this.schema)\n }\n}\n\n/**\n * Creates a typed object schema for use in Lexicon unions.\n *\n * Typed objects are identified by their `$type` field, which combines an NSID\n * and a hash (e.g., 'app.bsky.embed.images#view'). Used for union variants.\n *\n * This function offers two overloads:\n * - One that infers the type from arguments (no circular reference support)\n * - One with explicit interface for codegen with circular references\n *\n * @param nsid - The NSID part of the type (e.g., 'app.bsky.embed.images')\n * @param hash - The hash part of the type (e.g., 'view'), defaults to 'main'\n * @param validator - Schema for validating the object properties\n * @returns A new {@link TypedObjectSchema} instance\n *\n * @example\n * ```ts\n * // Image embed view\n * const imageViewSchema = l.typedObject(\n * 'app.bsky.embed.images',\n * 'view',\n * l.object({\n * images: l.array(l.object({\n * thumb: l.string(),\n * fullsize: l.string(),\n * alt: l.string(),\n * })),\n * })\n * )\n *\n * // Main type (hash defaults to 'main')\n * const postViewSchema = l.typedObject(\n * 'app.bsky.feed.defs',\n * 'postView',\n * l.object({ uri: l.string(), cid: l.string(), author: authorSchema })\n * )\n *\n * // Use $isTypeOf to narrow union types\n * if (imageViewSchema.$isTypeOf(embed)) {\n * // embed is narrowed to image view type\n * }\n *\n * // Use $build to construct typed objects\n * const view = imageViewSchema.$build({ images: [...] })\n * // view.$type === 'app.bsky.embed.images#view'\n * ```\n */\nexport function typedObject<\n const N extends NsidString,\n const H extends string,\n const S extends Validator<{ [k: string]: unknown }>,\n>(nsid: N, hash: H, validator: S): TypedObjectSchema<$Type<N, H>, S>\nexport function typedObject<V extends { $type?: $Type }>(\n nsid: V extends { $type?: infer T extends string }\n ? T extends `${infer N}#${string}`\n ? N\n : T // (T is a \"main\" type, so already an NSID)\n : never,\n hash: V extends { $type?: infer T extends string }\n ? T extends `${string}#${infer H}`\n ? H\n : 'main'\n : never,\n validator: Validator<Omit<V, '$type'>>,\n): TypedObjectSchema<$TypeOf<V>, Validator<V>>\n/*@__NO_SIDE_EFFECTS__*/\nexport function typedObject<\n const N extends NsidString,\n const H extends string,\n const S extends Validator<{ [k: string]: unknown }>,\n>(nsid: N, hash: H, validator: S) {\n return new TypedObjectSchema<$Type<N, H>, S>($type(nsid, hash), validator)\n}\n"]}
|
|
@@ -37,6 +37,7 @@ export type TypedRefGetter<out TValidator extends TypedObjectValidator> = () =>
|
|
|
37
37
|
*/
|
|
38
38
|
export declare class TypedRefSchema<const TValidator extends TypedObjectValidator = TypedObjectValidator> extends Schema<$Typed<InferInput<TValidator>>, $Typed<InferOutput<TValidator>>> {
|
|
39
39
|
#private;
|
|
40
|
+
readonly type: "typedRef";
|
|
40
41
|
constructor(getter: TypedRefGetter<TValidator>);
|
|
41
42
|
get validator(): TValidator;
|
|
42
43
|
get $type(): TValidator['$type'];
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"typed-ref.d.ts","sourceRoot":"","sources":["../../src/schema/typed-ref.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,MAAM,EACN,UAAU,EACV,WAAW,EACX,MAAM,EACN,iBAAiB,EACjB,SAAS,EACV,MAAM,YAAY,CAAA;AAEnB;;;;;;;GAOG;AACH,MAAM,WAAW,oBAAoB,CACnC,MAAM,SAAS;IAAE,KAAK,CAAC,EAAE,MAAM,CAAA;CAAE,GAAG;IAAE,KAAK,CAAC,EAAE,MAAM,CAAA;CAAE,EACtD,OAAO,SAAS,MAAM,GAAG,MAAM,CAC/B,SAAQ,SAAS,CAAC,MAAM,EAAE,OAAO,CAAC;IAClC,KAAK,EAAE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UAAU,CAAS;gBAIvB,MAAM,EAAE,cAAc,CAAC,UAAU,CAAC;IAS9C,IAAI,SAAS,IAAI,UAAU,CAE1B;IAED,IAAI,KAAK,IAAI,UAAU,CAAC,OAAO,CAAC,CAE/B;IAED,iBAAiB,CAAC,KAAK,EAAE,OAAO,EAAE,GAAG,EAAE,iBAAiB;CAUzD;AAED;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AAEH,wBAAgB,QAAQ,CAAC,KAAK,CAAC,UAAU,SAAS,oBAAoB,EACpE,GAAG,EAAE,cAAc,CAAC,UAAU,CAAC,GAC9B,cAAc,CAAC,UAAU,CAAC,CAAA;AAC7B,wBAAgB,QAAQ,CACtB,MAAM,SAAS;IAAE,KAAK,CAAC,EAAE,MAAM,CAAA;CAAE,EACjC,OAAO,SAAS,MAAM,GAAG,MAAM,EAE/B,GAAG,EAAE,cAAc,CAAC,oBAAoB,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,GACzD,cAAc,CAAC,oBAAoB,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAAA"}
|
package/dist/schema/typed-ref.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"typed-ref.js","sourceRoot":"","sources":["../../src/schema/typed-ref.ts"],"names":[],"mappings":";;;
|
|
1
|
+
{"version":3,"file":"typed-ref.js","sourceRoot":"","sources":["../../src/schema/typed-ref.ts"],"names":[],"mappings":";;;AAyHA,4BAIC;AA7HD,wCAOmB;AAyBnB;;;;;;;;;;;;;;GAcG;AACH,MAAa,cAEX,SAAQ,gBAGT;IACU,IAAI,GAAG,UAAmB,CAAA;IAEnC,OAAO,CAA4B;IAEnC,YAAY,MAAkC;QAC5C,uEAAuE;QACvE,sEAAsE;QAEtE,KAAK,EAAE,CAAA;QAEP,IAAI,CAAC,OAAO,GAAG,MAAM,CAAA;IACvB,CAAC;IAED,IAAI,SAAS;QACX,OAAO,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,CAAA;IAChC,CAAC;IAED,IAAI,KAAK;QACP,OAAO,IAAI,CAAC,SAAS,CAAC,KAAK,CAAA;IAC7B,CAAC;IAED,iBAAiB,CAAC,KAAc,EAAE,GAAsB;QACtD,MAAM,MAAM,GAAG,GAAG,CAAC,QAAQ,CAAC,KAAK,EAAE,IAAI,CAAC,SAAS,CAAC,CAAA;QAClD,IAAI,CAAC,MAAM,CAAC,OAAO;YAAE,OAAO,MAAM,CAAA;QAElC,IAAI,MAAM,CAAC,KAAK,CAAC,KAAK,KAAK,IAAI,CAAC,KAAK,EAAE,CAAC;YACtC,OAAO,GAAG,CAAC,yBAAyB,CAAC,MAAM,CAAC,KAAK,EAAE,OAAO,EAAE,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAA;QAC3E,CAAC;QAED,OAAO,MAAM,CAAA;IACf,CAAC;CACF;AArCD,wCAqCC;AAqCD,SAAgB,QAAQ,CACtB,GAA+B;IAE/B,OAAO,IAAI,cAAc,CAAa,GAAG,CAAC,CAAA;AAC5C,CAAC","sourcesContent":["import {\n $Typed,\n InferInput,\n InferOutput,\n Schema,\n ValidationContext,\n Validator,\n} from '../core.js'\n\n/**\n * Interface for validators that have a $type property.\n *\n * Used by typed objects and records to identify their type in unions.\n *\n * @template TInput - The input type (with optional $type)\n * @template TOutput - The output type (with non-optional $type)\n */\nexport interface TypedObjectValidator<\n TInput extends { $type?: string } = { $type?: string },\n TOutput extends TInput = TInput,\n> extends Validator<TInput, TOutput> {\n $type: NonNullable<TOutput['$type']>\n}\n\n/**\n * Function type that returns a typed object validator, used for lazy resolution.\n *\n * @template TValidator - The typed object validator type\n */\nexport type TypedRefGetter<out TValidator extends TypedObjectValidator> =\n () => TValidator\n\n/**\n * Schema for referencing typed objects with lazy resolution.\n *\n * Used in typed unions to reference typed object schemas. Requires the\n * `$type` field to be present and match the referenced schema's type.\n * The referenced schema is resolved lazily to support circular references.\n *\n * @template TValidator - The referenced typed object validator type\n *\n * @example\n * ```ts\n * const ref = new TypedRefSchema(() => imageViewSchema)\n * // ref.$type === 'app.bsky.embed.images#view'\n * ```\n */\nexport class TypedRefSchema<\n const TValidator extends TypedObjectValidator = TypedObjectValidator,\n> extends Schema<\n $Typed<InferInput<TValidator>>,\n $Typed<InferOutput<TValidator>>\n> {\n readonly type = 'typedRef' as const\n\n #getter: TypedRefGetter<TValidator>\n\n constructor(getter: TypedRefGetter<TValidator>) {\n // @NOTE In order to avoid circular dependency issues, we don't resolve\n // the schema here. Instead, we resolve it lazily when first accessed.\n\n super()\n\n this.#getter = getter\n }\n\n get validator(): TValidator {\n return this.#getter.call(null)\n }\n\n get $type(): TValidator['$type'] {\n return this.validator.$type\n }\n\n validateInContext(input: unknown, ctx: ValidationContext) {\n const result = ctx.validate(input, this.validator)\n if (!result.success) return result\n\n if (result.value.$type !== this.$type) {\n return ctx.issueInvalidPropertyValue(result.value, '$type', [this.$type])\n }\n\n return result\n }\n}\n\n/**\n * Creates a reference to a typed object schema for use in typed unions.\n *\n * Unlike regular `ref()`, this requires the referenced schema to have a\n * `$type` property, and validates that the input's `$type` matches.\n *\n * @param get - Function that returns the typed object validator\n * @returns A new {@link TypedRefSchema} instance\n *\n * @example\n * ```ts\n * // Reference to image embed view\n * const imageRef = l.typedRef(() => imageViewSchema)\n *\n * // Use in a typed union\n * const embedUnion = l.typedUnion([\n * l.typedRef(() => imageViewSchema),\n * l.typedRef(() => videoViewSchema),\n * l.typedRef(() => externalViewSchema),\n * ], true) // closed union\n *\n * // The $type is accessible on the ref\n * console.log(imageRef.$type) // 'app.bsky.embed.images#view'\n * ```\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function typedRef<const TValidator extends TypedObjectValidator>(\n get: TypedRefGetter<TValidator>,\n): TypedRefSchema<TValidator>\nexport function typedRef<\n TInput extends { $type?: string },\n TOutput extends TInput = TInput,\n>(\n get: TypedRefGetter<TypedObjectValidator<TInput, TOutput>>,\n): TypedRefSchema<TypedObjectValidator<TInput, TOutput>>\nexport function typedRef<const TValidator extends TypedObjectValidator>(\n get: TypedRefGetter<TValidator>,\n): TypedRefSchema<TValidator> {\n return new TypedRefSchema<TValidator>(get)\n}\n"]}
|
|
@@ -22,6 +22,7 @@ import { TypedRefSchema } from './typed-ref.js';
|
|
|
22
22
|
export declare class TypedUnionSchema<const TValidators extends readonly (TypedRefSchema | TypedObjectSchema)[] = [], const TClosed extends boolean = boolean> extends Schema<TClosed extends true ? InferInput<TValidators[number]> : InferInput<TValidators[number]> | Unknown$TypedObject, TClosed extends true ? InferOutput<TValidators[number]> : InferOutput<TValidators[number]> | Unknown$TypedObject> {
|
|
23
23
|
protected readonly validators: TValidators;
|
|
24
24
|
readonly closed: TClosed;
|
|
25
|
+
readonly type: "typedUnion";
|
|
25
26
|
constructor(validators: TValidators, closed: TClosed);
|
|
26
27
|
get validatorsMap(): Map<unknown, TValidators[number]>;
|
|
27
28
|
get $types(): unknown[];
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"typed-union.d.ts","sourceRoot":"","sources":["../../src/schema/typed-union.ts"],"names":[],"mappings":"AACA,OAAO,EACL,UAAU,EACV,WAAW,EACX,MAAM,EACN,mBAAmB,EACnB,iBAAiB,EAClB,MAAM,YAAY,CAAA;AAEnB,OAAO,EAAE,iBAAiB,EAAE,MAAM,mBAAmB,CAAA;AACrD,OAAO,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAA;AAE/C;;;;;;;;;;;;;;;;;GAiBG;AACH,qBAAa,gBAAgB,CAC3B,KAAK,CAAC,WAAW,SAAS,SAAS,CAC/B,cAAc,GACd,iBAAiB,CACpB,EAAE,GAAG,EAAE,EACR,KAAK,CAAC,OAAO,SAAS,OAAO,GAAG,OAAO,CACvC,SAAQ,MAAM,CACd,OAAO,SAAS,IAAI,GAChB,UAAU,CAAC,WAAW,CAAC,MAAM,CAAC,CAAC,GAC/B,UAAU,CAAC,WAAW,CAAC,MAAM,CAAC,CAAC,GAAG,mBAAmB,EACzD,OAAO,SAAS,IAAI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CAsBzD;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AAEH,wBAAgB,UAAU,CACxB,KAAK,CAAC,CAAC,SAAS,SAAS,cAAc,EAAE,EACzC,KAAK,CAAC,CAAC,SAAS,OAAO,EACvB,IAAI,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,0BAEnB"}
|
|
@@ -26,6 +26,7 @@ const lazy_property_js_1 = require("../util/lazy-property.js");
|
|
|
26
26
|
class TypedUnionSchema extends core_js_1.Schema {
|
|
27
27
|
validators;
|
|
28
28
|
closed;
|
|
29
|
+
type = 'typedUnion';
|
|
29
30
|
constructor(validators, closed) {
|
|
30
31
|
// @NOTE In order to avoid circular dependency issues, we don't access the
|
|
31
32
|
// refs's schema (or $type) here. Instead, we access them lazily when first
|
|
@@ -46,7 +47,7 @@ class TypedUnionSchema extends core_js_1.Schema {
|
|
|
46
47
|
}
|
|
47
48
|
validateInContext(input, ctx) {
|
|
48
49
|
if (!(0, lex_data_1.isPlainObject)(input) || !('$type' in input)) {
|
|
49
|
-
return ctx.
|
|
50
|
+
return ctx.issueUnexpectedType(input, '$typed');
|
|
50
51
|
}
|
|
51
52
|
const { $type } = input;
|
|
52
53
|
const validator = this.validatorsMap.get($type);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"typed-union.js","sourceRoot":"","sources":["../../src/schema/typed-union.ts"],"names":[],"mappings":";;;
|
|
1
|
+
{"version":3,"file":"typed-union.js","sourceRoot":"","sources":["../../src/schema/typed-union.ts"],"names":[],"mappings":";;;AA4HA,gCAKC;AAjID,gDAAiD;AACjD,wCAMmB;AACnB,+DAAuD;AAIvD;;;;;;;;;;;;;;;;;GAiBG;AACH,MAAa,gBAMX,SAAQ,gBAOT;IAIsB;IACH;IAJT,IAAI,GAAG,YAAqB,CAAA;IAErC,YACqB,UAAuB,EAC1B,MAAe;QAE/B,0EAA0E;QAC1E,2EAA2E;QAC3E,sEAAsE;QACtE,+DAA+D;QAE/D,KAAK,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AAG,CAAC,OAAO,CAAC,KAAK,CAAC,CAAA;IAC3B,CAAC;CACF;AA7DD,4CA6DC;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AACH,wBAAwB;AACxB,SAAgB,UAAU,CAGxB,IAAO,EAAE,MAAS;IAClB,OAAO,IAAI,gBAAgB,CAAO,IAAI,EAAE,MAAM,CAAC,CAAA;AACjD,CAAC","sourcesContent":["import { isPlainObject } from '@atproto/lex-data'\nimport {\n InferInput,\n InferOutput,\n Schema,\n Unknown$TypedObject,\n ValidationContext,\n} from '../core.js'\nimport { lazyProperty } from '../util/lazy-property.js'\nimport { TypedObjectSchema } from './typed-object.js'\nimport { TypedRefSchema } from './typed-ref.js'\n\n/**\n * Schema for Lexicon typed unions (unions discriminated by $type).\n *\n * Typed unions are collections of typed objects identified by their `$type`\n * field. Can be \"open\" (accept unknown types) or \"closed\" (only accept\n * known types).\n *\n * @template TValidators - Tuple of {@link TypedRefSchema} or {@link TypedObjectSchema} instances\n * @template TClosed - Whether the union is closed (rejects unknown $types)\n *\n * @example\n * ```ts\n * const embedUnion = new TypedUnionSchema([\n * l.typedRef(() => imageSchema),\n * l.typedRef(() => videoSchema),\n * ], true) // closed - only accepts images and videos\n * ```\n */\nexport class TypedUnionSchema<\n const TValidators extends readonly (\n | TypedRefSchema\n | TypedObjectSchema\n )[] = [],\n const TClosed extends boolean = boolean,\n> extends Schema<\n TClosed extends true\n ? InferInput<TValidators[number]>\n : InferInput<TValidators[number]> | Unknown$TypedObject,\n TClosed extends true\n ? InferOutput<TValidators[number]>\n : InferOutput<TValidators[number]> | Unknown$TypedObject\n> {\n readonly type = 'typedUnion' as const\n\n constructor(\n protected readonly validators: TValidators,\n public readonly closed: TClosed,\n ) {\n // @NOTE In order to avoid circular dependency issues, we don't access the\n // refs's schema (or $type) here. Instead, we access them lazily when first\n // needed. The biggest issue with this strategy is that we can't throw\n // early if the refs contain multiple refs with the same $type.\n\n super()\n }\n\n get validatorsMap(): Map<unknown, TValidators[number]> {\n const map = new Map<unknown, TValidators[number]>()\n for (const ref of this.validators) map.set(ref.$type, ref)\n\n return lazyProperty(this, 'validatorsMap', map)\n }\n\n get $types() {\n return Array.from(this.validatorsMap.keys())\n }\n\n validateInContext(input: unknown, ctx: ValidationContext) {\n if (!isPlainObject(input) || !('$type' in input)) {\n return ctx.issueUnexpectedType(input, '$typed')\n }\n\n const { $type } = input\n\n const validator = this.validatorsMap.get($type)\n if (validator) {\n return ctx.validate(input, validator)\n }\n\n if (this.closed) {\n return ctx.issueInvalidPropertyValue(input, '$type', this.$types)\n }\n\n if (typeof $type !== 'string') {\n return ctx.issueInvalidPropertyType(input, '$type', 'string')\n }\n\n return ctx.success(input)\n }\n}\n\n/**\n * Creates a typed union schema for Lexicon unions.\n *\n * Typed unions discriminate variants by their `$type` field. Can be open\n * (accepts unknown types, useful for extensibility) or closed (strict).\n *\n * @param refs - Array of typed refs for the union variants\n * @param closed - Whether to reject unknown $type values\n * @returns A new {@link TypedUnionSchema} instance\n *\n * @example\n * ```ts\n * // Closed union - only accepts known types\n * const embedSchema = l.typedUnion([\n * l.typedRef(() => imageViewSchema),\n * l.typedRef(() => videoViewSchema),\n * l.typedRef(() => externalViewSchema),\n * ], true)\n *\n * // Open union - accepts unknown types for forward compatibility\n * const feedItemSchema = l.typedUnion([\n * l.typedRef(() => postSchema),\n * l.typedRef(() => repostSchema),\n * ], false) // unknown types pass through\n *\n * // Get all known $types\n * console.log(embedSchema.$types)\n * // ['app.bsky.embed.images#view', 'app.bsky.embed.video#view', ...]\n * ```\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function typedUnion<\n const R extends readonly TypedRefSchema[],\n const C extends boolean,\n>(refs: R, closed: C) {\n return new TypedUnionSchema<R, C>(refs, closed)\n}\n"]}
|
package/dist/schema/union.d.ts
CHANGED
|
@@ -23,6 +23,7 @@ export type UnionSchemaValidators = readonly [Validator, ...Validator[]];
|
|
|
23
23
|
*/
|
|
24
24
|
export declare class UnionSchema<const TValidators extends UnionSchemaValidators = any> extends Schema<InferInput<TValidators[number]>, InferOutput<TValidators[number]>> {
|
|
25
25
|
protected readonly validators: TValidators;
|
|
26
|
+
readonly type: "union";
|
|
26
27
|
constructor(validators: TValidators);
|
|
27
28
|
validateInContext(input: unknown, ctx: ValidationContext): ValidationFailure | import("../core.js").ValidationSuccess<unknown>;
|
|
28
29
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"union.d.ts","sourceRoot":"","sources":["../../src/schema/union.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,UAAU,EACV,WAAW,EACX,MAAM,EACN,iBAAiB,EAEjB,iBAAiB,EACjB,SAAS,EACV,MAAM,YAAY,CAAA;AAEnB;;;;GAIG;AACH,MAAM,MAAM,qBAAqB,GAAG,SAAS,CAAC,SAAS,EAAE,GAAG,SAAS,EAAE,CAAC,CAAA;AAExE;;;;;;;;;;;;;;;GAeG;AACH,qBAAa,WAAW,CACtB,KAAK,CAAC,WAAW,SAAS,qBAAqB,GAAG,GAAG,CACrD,SAAQ,MAAM,CACd,UAAU,CAAC,WAAW,CAAC,MAAM,CAAC,CAAC,EAC/B,WAAW,CAAC,WAAW,CAAC,MAAM,CAAC,CAAC,CACjC;
|
|
1
|
+
{"version":3,"file":"union.d.ts","sourceRoot":"","sources":["../../src/schema/union.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,UAAU,EACV,WAAW,EACX,MAAM,EACN,iBAAiB,EAEjB,iBAAiB,EACjB,SAAS,EACV,MAAM,YAAY,CAAA;AAEnB;;;;GAIG;AACH,MAAM,MAAM,qBAAqB,GAAG,SAAS,CAAC,SAAS,EAAE,GAAG,SAAS,EAAE,CAAC,CAAA;AAExE;;;;;;;;;;;;;;;GAeG;AACH,qBAAa,WAAW,CACtB,KAAK,CAAC,WAAW,SAAS,qBAAqB,GAAG,GAAG,CACrD,SAAQ,MAAM,CACd,UAAU,CAAC,WAAW,CAAC,MAAM,CAAC,CAAC,EAC/B,WAAW,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