import { Parser } from './Parser' import { AdaptedParser } from './AdaptedParser' import { ParseResult, ParseIssue } from './ParseResult' import { JsonSchema } from './JsonSchema' export { Parser } // primitive values export function string(): Parser { return AdaptedParser.create({ name: 'string', jsonSchema: { type: 'string' }, parse: ({ input, path, typeAlias, typeDescriptor }) => { if (typeof input === 'string') { return { valid: true, output: input } } return { valid: false, issues: [{ path, typeAlias, typeDescriptor }], } }, }) } export function number(): Parser { return AdaptedParser.create({ name: 'number', jsonSchema: { type: 'number' }, parse: ({ input, path, typeAlias, typeDescriptor }) => { if (typeof input === 'number') { return { valid: true, output: input } } return { valid: false, issues: [{ path, typeAlias, typeDescriptor }], } }, }) } export function boolean(): Parser { return AdaptedParser.create({ name: 'boolean', jsonSchema: { type: 'boolean' }, parse: ({ input, path, typeAlias, typeDescriptor }) => { if (typeof input === 'boolean') { return { valid: true, output: input } } return { valid: false, issues: [{ path, typeAlias, typeDescriptor }], } }, }) } export { null_ as null } function null_(): Parser { return AdaptedParser.create({ name: 'null', jsonSchema: { type: 'null' }, parse: ({ input, path, typeAlias, typeDescriptor }) => { if (input === null) { return { valid: true, output: input } } return { valid: false, issues: [{ path, typeAlias, typeDescriptor }], } }, }) } export type LiteralValue = string | number | boolean | null export { literal as const } export function literal(value: V): Parser { return AdaptedParser.create({ name: value === null ? 'literal null' : `literal ${typeof value} ${JSON.stringify(value)}`, jsonSchema: { const: value }, parse: ({ input, path, typeAlias, typeDescriptor }) => { if (input === value) { return { valid: true, output: input as V } } return { valid: false, issues: [{ path, typeAlias, typeDescriptor }], } }, }) } // non-primitive values export function array(itemParser: Parser): Parser { return AdaptedParser.create({ name: `array [ ${itemParser.descriptor} ]`, jsonSchema: { type: 'array', items: itemParser.jsonSchema }, parse: ({ input, path, typeAlias, typeDescriptor }) => { if (!Array.isArray(input)) { return { valid: false, issues: [{ path, typeAlias, typeDescriptor }], } } const results = input.map((item, index) => itemParser.parse(item, [...path, index]), ) return requireAllValid(input, results) }, }) } export type UndefinedProperties = { [K in keyof T]-?: undefined extends T[K] ? K : never }[keyof T] export type OptionalUndefined = Partial>> & Pick>> export type PropertyParsers = { [K in keyof T]: Parser } export function object( properties: PropertyParsers, ): Parser> { const propertyParsers = Object.keys(properties).map(property => ({ property: property as string & keyof T, parser: (properties as any)[property] as Parser, })) const propertyDescriptors = propertyParsers .map( ({ property, parser }) => `${JSON.stringify(property)}: ${parser.descriptor}`, ) .join(', ') const jsonSchema: JsonSchema = { type: 'object', properties: propertyParsers.reduce<{ [key: string]: JsonSchema }>((acc, { property, parser }) => { acc[property] = parser.jsonSchema return acc }, {}), required: propertyParsers .filter(({ parser }) => !parser.isOptional) .map(({ property }) => property), } return AdaptedParser.create({ name: `object { ${propertyDescriptors} }`, jsonSchema, parse: ({ input, path, typeAlias, typeDescriptor }) => { if (typeof input !== 'object' || !input || Array.isArray(input)) { return { valid: false, issues: [{ path, typeAlias, typeDescriptor }], } } const results = propertyParsers.map(({ property, parser }) => { return parser.parse((input as any)[property], [...path, property]) }) return requireAllValid(input, results) }, }) } // composite types export function partial(properties: PropertyParsers): Parser> { const mapped: { [key: string]: Parser } = {} Object.keys(properties).forEach(property => { mapped[property] = properties[ property as keyof typeof properties ].optional() }) return object(mapped) as any } export { union as anyOf } export function union(a: Parser, b: Parser): Parser export function union( a: Parser, b: Parser, c: Parser, ): Parser export function union( a: Parser, b: Parser, c: Parser, d: Parser, ): Parser export function union( a: Parser, b: Parser, c: Parser, d: Parser, e: Parser, ): Parser export function union( a: Parser, b: Parser, c: Parser, d: Parser, e: Parser, f: Parser, ): Parser export function union(...parsers: Array>): Parser { const nameContents = parsers.map(parser => parser.descriptor).join(' | ') return AdaptedParser.create({ name: `any ( ${nameContents} )`, jsonSchema: { anyOf: parsers.map(parser => parser.jsonSchema) }, parse: ({ input, path, typeAlias, typeDescriptor }) => { const results = parsers.map(parser => parser.parse(input, path)) const validResult = results.find(result => result.valid) if (validResult) { return validResult } return { valid: false, issues: [ { path, typeAlias, typeDescriptor, }, ...results.reduce((acc, result) => { if (result.valid) { throw new Error('invariant violation') } acc.push(...result.issues) return acc }, []), ], } }, }) } export { intersection as allOf } export function intersection(a: Parser, b: Parser): Parser export function intersection( a: Parser, b: Parser, c: Parser, ): Parser export function intersection( a: Parser, b: Parser, c: Parser, d: Parser, ): Parser export function intersection( a: Parser, b: Parser, c: Parser, d: Parser, e: Parser, ): Parser export function intersection( a: Parser, b: Parser, c: Parser, d: Parser, e: Parser, f: Parser, ): Parser export function intersection( ...parsers: Array> ): Parser { const nameContents = parsers.map(parser => parser.descriptor).join(' & ') return AdaptedParser.create({ name: `all ( ${nameContents} )`, jsonSchema: { allOf: parsers.map(parser => parser.jsonSchema) }, parse: ({ input, path, typeAlias, typeDescriptor }) => { const results = parsers.map(parser => parser.parse(input, path)) const result = requireAllValid(input, results) if (!result.valid) { result.issues.unshift({ path, typeAlias, typeDescriptor }) } return result }, }) } // helpers export type Type = T extends Parser ? U : never function requireAllValid( input: unknown, results: Array>, ): ParseResult { const issues = results.reduce((acc, result) => { if (!result.valid) { acc.push(...result.issues) } return acc }, []) if (issues.length) { return { valid: false, issues } } return { valid: true, output: input } }