|
| 1 | +import { ParseOptions, Schema } from '../core.ts' |
| 2 | + |
| 3 | +const isArray = (value: unknown): value is readonly unknown[] => Array.isArray(value) |
| 4 | + |
| 5 | +export namespace $Array { |
| 6 | + export interface Options<S, T extends S = S> { |
| 7 | + inner: Schema<S, T> |
| 8 | + length?: Schema<number> |
| 9 | + } |
| 10 | +} |
| 11 | + |
| 12 | +export class $Array<S, T extends S = S> extends Schema<readonly S[], T[]> { |
| 13 | + type = 'array' |
| 14 | + options: $Array.Options<S, T> |
| 15 | + |
| 16 | + constructor(inner: Schema<S, T>) { |
| 17 | + super() |
| 18 | + this.options = { inner } |
| 19 | + } |
| 20 | + |
| 21 | + length(value: Schema<number>) { |
| 22 | + this.options.length = value |
| 23 | + return this |
| 24 | + } |
| 25 | + |
| 26 | + format(): string { |
| 27 | + return `Array<${this.options.inner.format()}>` |
| 28 | + } |
| 29 | + |
| 30 | + validate(value: unknown, options: ParseOptions) { |
| 31 | + if (!isArray(value)) return this.failure(value, options.path) |
| 32 | + if (this.options.length) { |
| 33 | + const result = this.options.length.validate(value.length, options) |
| 34 | + if (result.issues) { |
| 35 | + // TODO: improve message |
| 36 | + return this.failure(value, options.path, ` with length ${result.issues[0].message}`) |
| 37 | + } |
| 38 | + } |
| 39 | + const values: T[] = [] |
| 40 | + const issues: Schema.Issue[] = [] |
| 41 | + for (let i = 0; i < value.length; i++) { |
| 42 | + const result = this.options.inner.validate(value[i], { |
| 43 | + ...options, |
| 44 | + path: [...options.path || [], i], |
| 45 | + }) |
| 46 | + if (!result.issues) { |
| 47 | + values.push(result.value) |
| 48 | + } else if (options.autofix) { |
| 49 | + values.push(this.options.inner.default()) |
| 50 | + } else { |
| 51 | + issues.push(...result.issues) |
| 52 | + } |
| 53 | + } |
| 54 | + if (issues.length) return { issues } |
| 55 | + return { value: values } |
| 56 | + } |
| 57 | +} |
0 commit comments