-
Notifications
You must be signed in to change notification settings - Fork 6
/
index.ts
695 lines (620 loc) · 22.8 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
import { clone, deepEqual, Dict, filterKeys, isNullable, isPlainObject, pick, valueMap } from 'cosmokit'
const kSchema = Symbol.for('schemastery')
declare global {
namespace Schemastery {
export type From<X> =
| X extends string | number | boolean ? Schema<X>
: X extends Schema ? X
: X extends typeof String ? Schema<string>
: X extends typeof Number ? Schema<number>
: X extends typeof Boolean ? Schema<boolean>
: X extends typeof Function ? Schema<Function, (...args: any[]) => any>
: X extends Constructor<infer S> ? Schema<S>
: never
type TypeS1<X> = X extends Schema<infer S, unknown> ? S : never
type Inverse<X> = X extends Schema<any, infer Y> ? (arg: Y) => void : never
export type TypeS<X> = TypeS1<From<X>>
export type TypeT<X> = ReturnType<From<X>>
export type Resolve = (data: any, schema: Schema, options?: Options, strict?: boolean) => [any, any?]
export type IntersectS<X> = From<X> extends Schema<infer S, unknown> ? S : never
export type IntersectT<X> = Inverse<From<X>> extends ((arg: infer T) => void) ? T : never
type TupleS<X extends readonly any[]> = X extends readonly [infer L, ...infer R] ? [TypeS<L>?, ...TupleS<R>] : any[]
type TupleT<X extends readonly any[]> = X extends readonly [infer L, ...infer R] ? [TypeT<L>?, ...TupleT<R>] : any[]
type ObjectS<X extends Dict> = { [K in keyof X]?: TypeS<X[K]> | null } & Dict
type ObjectT<X extends Dict> = { [K in keyof X]: TypeT<X[K]> } & Dict
type Constructor<T = any> = new (...args: any[]) => T
export interface Static {
<T = any>(options: Partial<Schema<T>>): Schema<T>
new <T = any>(options: Partial<Schema<T>>): Schema<T>
prototype: Schema
resolve: Resolve
from<X = any>(source?: X): From<X>
extend(type: string, resolve: Resolve): void
any(): Schema<any>
never(): Schema<never>
const<const T>(value: T): Schema<T>
string(): Schema<string>
number(): Schema<number>
natural(): Schema<number>
percent(): Schema<number>
boolean(): Schema<boolean>
date(): Schema<string | Date, Date>
bitset<K extends string>(bits: Partial<Record<K, number>>): Schema<number | readonly K[], number>
function(): Schema<Function, (...args: any[]) => any>
is<T>(constructor: Constructor<T>): Schema<T>
array<X>(inner: X): Schema<TypeS<X>[], TypeT<X>[]>
dict<X, Y extends Schema<any, string> = Schema<string>>(inner: X, sKey?: Y): Schema<Dict<TypeS<X>, TypeS<Y>>, Dict<TypeT<X>, TypeT<Y>>>
tuple<X extends readonly any[]>(list: X): Schema<TupleS<X>, TupleT<X>>
object<X extends Dict>(dict: X): Schema<ObjectS<X>, ObjectT<X>>
union<const X>(list: readonly X[]): Schema<TypeS<X>, TypeT<X>>
intersect<const X>(list: readonly X[]): Schema<IntersectS<X>, IntersectT<X>>
transform<X, T>(inner: X, callback: (value: TypeS<X>) => T, preserve?: boolean): Schema<TypeS<X>, T>
}
interface Options {
autofix?: boolean
}
export interface Meta<T = any> {
default?: T extends {} ? Partial<T> : T
required?: boolean
disabled?: boolean
collapse?: boolean
badges?: { text: string; type: string }[]
hidden?: boolean
loose?: boolean
role?: string
extra?: any
link?: string
description?: string | Dict<string>
comment?: string
pattern?: { source: string; flags?: string }
max?: number
min?: number
step?: number
}
}
interface Schemastery<S = any, T = S> {
(data?: S | null, options?: Schemastery.Options): T
new (data?: S | null, options?: Schemastery.Options): T
[kSchema]: true
uid: number
meta: Schemastery.Meta<T>
type: string
sKey?: Schema
inner?: Schema
list?: Schema[]
dict?: Dict<Schema>
bits?: Dict<number>
callback?: Function
value?: T
refs?: Dict<Schema>
preserve?: boolean
toString(inline?: boolean): string
toJSON(): Schema<S, T>
required(value?: boolean): Schema<S, T>
hidden(value?: boolean): Schema<S, T>
loose(value?: boolean): Schema<S, T>
role(text: string, extra?: any): Schema<S, T>
link(link: string): Schema<S, T>
default(value: T): Schema<S, T>
comment(text: string): Schema<S, T>
description(text: string): Schema<S, T>
disabled(value?: boolean): Schema<S, T>
collapse(value?: boolean): Schema<S, T>
deprecated(): Schema<S, T>
experimental(): Schema<S, T>
pattern(regexp: RegExp): Schema<S, T>
max(value: number): Schema<S, T>
min(value: number): Schema<S, T>
step(value: number): Schema<S, T>
set(key: string, value: Schema): Schema<S, T>
push(value: Schema): Schema<S, T>
simplify(value?: any): any
i18n(messages: Dict): Schema<S, T>
extra<K extends keyof Schemastery.Meta>(key: K, value: Schemastery.Meta[K]): Schema<S, T>
}
}
declare module globalThis {
// eslint-disable-next-line @typescript-eslint/naming-convention
export let __schemastery_index__: number
}
globalThis.__schemastery_index__ ??= 0
type Schema<S = any, T = S> = Schemastery<S, T>
const Schema = function (options: Schema) {
const schema = function (data: any, options?: Schemastery.Options) {
return Schema.resolve(data, schema, options)[0]
} as Schema
if (options.refs) {
const refs = valueMap(options.refs, options => new Schema(options))
const getRef = (uid: any) => refs[uid]!
for (const key in refs) {
const options = refs[key]!
options.sKey = getRef(options.sKey)
options.inner = getRef(options.inner)
options.list = options.list && options.list.map(getRef)
options.dict = options.dict && valueMap(options.dict, getRef)
}
return refs[options.uid!]
}
Object.assign(schema, options)
if (typeof schema.callback === 'string') {
try {
// eslint-disable-next-line no-new-func
schema.callback = new Function('return ' + schema.callback)()
} catch {}
}
Object.defineProperty(schema, 'uid', { value: globalThis.__schemastery_index__++ })
Object.setPrototypeOf(schema, Schema.prototype)
schema.meta ||= {}
schema.toString = schema.toString.bind(schema)
return schema
} as Schemastery.Static
Schema.prototype = Object.create(Function.prototype)
Schema.prototype[kSchema] = true
let refs: Record<number, Schema> | undefined
Schema.prototype.toJSON = function toJSON() {
if (refs) {
refs[this.uid] ??= JSON.parse(JSON.stringify({ ...this }))
return this.uid as any
}
refs = { [this.uid]: { ...this } as Schema }
refs[this.uid] = JSON.parse(JSON.stringify({ ...this }))
const result = { uid: this.uid, refs }
refs = undefined
return result
}
Schema.prototype.set = function set(key, value) {
this.dict![key] = value
return this
}
Schema.prototype.push = function push(value) {
this.list!.push(value)
return this
}
function mergeDesc(original: undefined | string | Dict<string>, messages: Dict) {
const result: Dict<string> = typeof original === 'string' ? { '': original } : { ...original }
for (const locale in messages) {
const value = messages[locale]
if (value?.$description || value?.$desc) {
result[locale] = value.$description || value.$desc
} else if (typeof value === 'string') {
result[locale] = value
}
}
return result
}
function getInner(value: any) {
return value?.$value ?? value?.$inner
}
function extractKeys(data: any) {
return filterKeys(data ?? {}, key => !key.startsWith('$'))
}
Schema.prototype.i18n = function i18n(messages) {
const schema = Schema(this)
schema.meta.description = mergeDesc(schema.meta.description, messages)
if (schema.dict) {
schema.dict = valueMap(schema.dict, (inner, key) => {
return inner.i18n(valueMap(messages, (data) => getInner(data)?.[key] ?? data?.[key]))
})
}
if (schema.list) {
schema.list = schema.list!.map((inner, index) => {
return inner.i18n(valueMap(messages, (data = {}) => {
if (Array.isArray(getInner(data))) return getInner(data)[index]
if (Array.isArray(data)) return data[index]
return extractKeys(data)
}))
})
}
if (schema.inner) {
schema.inner = schema.inner.i18n(valueMap(messages, (data) => {
if (getInner(data)) return getInner(data)
return extractKeys(data)
}))
}
if (schema.sKey) {
schema.sKey = schema.sKey.i18n(valueMap(messages, (data) => data?.$key))
}
return schema
}
Schema.prototype.extra = function extra(key, value) {
const schema = Schema(this)
schema.meta = { ...schema.meta, [key]: value }
return schema
}
for (const key of ['required', 'disabled', 'collapse', 'hidden', 'loose']) {
Object.assign(Schema.prototype, {
[key](this: Schema, value = true) {
const schema = Schema(this)
schema.meta = { ...schema.meta, [key]: value }
return schema
},
})
}
Schema.prototype.deprecated = function deprecated() {
const schema = Schema(this)
schema.meta.badges ||= []
schema.meta.badges.push({ text: 'deprecated', type: 'danger' })
return schema
}
Schema.prototype.experimental = function experimental() {
const schema = Schema(this)
schema.meta.badges ||= []
schema.meta.badges.push({ text: 'experimental', type: 'warning' })
return schema
}
Schema.prototype.pattern = function pattern(regexp) {
const schema = Schema(this)
const pattern = pick(regexp, ['source', 'flags'])
schema.meta = { ...schema.meta, pattern }
return schema
}
Schema.prototype.simplify = function simplify(this: Schema, value) {
if (deepEqual(value, this.meta.default)) return null
if (isNullable(value)) return value
if (this.type === 'object' || this.type === 'dict') {
const result: Dict = {}
for (const key in value) {
const schema = this.type === 'object' ? this.dict![key] : this.inner
const item = schema?.simplify(value[key])
if (this.type === 'dict' || !isNullable(item)) result[key] = item
}
return result
} else if (this.type === 'array' || this.type === 'tuple') {
const result: any[] = []
;(value as any[]).forEach((value, index) => {
const schema = this.type === 'array' ? this.inner : this.list![index]
const item = schema ? schema.simplify(value) : value
result.push(item)
})
return result
} else if (this.type === 'intersect') {
const result: Dict = {}
for (const item of this.list!) {
Object.assign(result, item.simplify(value))
}
return result
} else if (this.type === 'union') {
for (const schema of this.list!) {
try {
Schema.resolve(value, schema)
return schema.simplify(value)
} catch {}
}
}
return value
}
Schema.prototype.toString = function toString(inline?: boolean) {
return formatters[this.type]?.(this, inline) ?? `Schema<${this.type}>`
}
Schema.prototype.role = function role(role, extra) {
const schema = Schema(this)
schema.meta = { ...schema.meta, role, extra }
return schema
}
for (const key of ['default', 'link', 'comment', 'description', 'max', 'min', 'step']) {
Object.assign(Schema.prototype, {
[key](this: Schema, value: any) {
const schema = Schema(this)
schema.meta = { ...schema.meta, [key]: value }
return schema
},
})
}
const resolvers: Dict<Schemastery.Resolve> = {}
Schema.extend = function extend(type, resolve) {
resolvers[type] = resolve
}
Schema.resolve = function resolve(data, schema, options = {}, strict = false) {
if (!schema) return [data]
if (isNullable(data)) {
if (schema.meta.required) throw new TypeError(`missing required value`)
let current = schema
let fallback = schema.meta.default
while (current?.type === 'intersect' && isNullable(fallback)) {
current = current.list![0]
fallback = current?.meta.default
}
if (isNullable(fallback)) return [data]
data = clone(fallback)
}
const callback = resolvers[schema.type]
if (!callback) throw new TypeError(`unsupported type "${schema.type}"`)
try {
return callback(data, schema, options, strict)
} catch (error) {
if (!schema.meta.loose) throw error
return [schema.meta.default]
}
}
Schema.from = function from(source: any) {
if (isNullable(source)) {
return Schema.any()
} else if (['string', 'number', 'boolean'].includes(typeof source)) {
return Schema.const(source).required()
} else if (source[kSchema]) {
return source
} else if (typeof source === 'function') {
switch (source) {
case String: return Schema.string().required()
case Number: return Schema.number().required()
case Boolean: return Schema.boolean().required()
case Function: return Schema.function().required()
default: return Schema.is(source).required()
}
} else {
throw new TypeError(`cannot infer schema from ${source}`)
}
}
Schema.natural = function natural() {
return Schema.number().step(1).min(0)
}
Schema.percent = function percent() {
return Schema.number().step(0.01).min(0).max(1).role('slider')
}
Schema.date = function date() {
return Schema.union([
Schema.is(Date),
Schema.transform(Schema.string().role('datetime'), (value) => {
const date = new Date(value)
if (isNaN(+date)) throw new TypeError(`invalid date "${value}"`)
return date
}, true),
])
}
Schema.extend('any', (data) => {
return [data]
})
Schema.extend('never', (data) => {
throw new TypeError(`expected nullable but got ${data}`)
})
Schema.extend('const', (data, { value }) => {
if (data === value) return [value]
throw new TypeError(`expected ${value} but got ${data}`)
})
function checkWithinRange(data: number, meta: Schemastery.Meta<any>, description: string, skipMin = false) {
const { max = Infinity, min = -Infinity } = meta
if (data > max) throw new TypeError(`expected ${description} <= ${max} but got ${data}`)
if (data < min && !skipMin) throw new TypeError(`expected ${description} >= ${min} but got ${data}`)
}
Schema.extend('string', (data, { meta }) => {
if (typeof data !== 'string') throw new TypeError(`expected string but got ${data}`)
if (meta.pattern) {
const regexp = new RegExp(meta.pattern.source, meta.pattern.flags)
if (!regexp.test(data)) throw new TypeError(`expect string to match regexp ${regexp}`)
}
checkWithinRange(data.length, meta, 'string length')
return [data]
})
function decimalShift(data: number, digits: number) {
const str = data.toString()
if (str.includes('e')) return data * Math.pow(10, digits)
const index = str.indexOf('.')
if (index === -1) return data * Math.pow(10, digits)
const frac = str.slice(index + 1)
const integer = str.slice(0, index)
if (frac.length <= digits) return +(integer + frac.padEnd(digits, '0'))
return +(integer + frac.slice(0, digits) + '.' + frac.slice(digits))
}
function isMultipleOf(data: number, min: number, step: number) {
step = Math.abs(step)
if (!/^\d+\.\d+$/.test(step.toString())) {
return (data - min) % step === 0
}
const index = step.toString().indexOf('.')
const digits = step.toString().slice(index + 1).length
return Math.abs(decimalShift(data, digits) - decimalShift(min, digits)) % decimalShift(step, digits) === 0
}
Schema.extend('number', (data, { meta }) => {
if (typeof data !== 'number') throw new TypeError(`expected number but got ${data}`)
checkWithinRange(data, meta, 'number')
const { step } = meta
if (step && !isMultipleOf(data, meta.min ?? 0, step)) {
throw new TypeError(`expected number multiple of ${step} but got ${data}`)
}
return [data]
})
Schema.extend('boolean', (data) => {
if (typeof data === 'boolean') return [data]
throw new TypeError(`expected boolean but got ${data}`)
})
Schema.extend('bitset', (data, { bits, meta }) => {
let value = 0, keys: string[] = []
if (typeof data === 'number') {
value = data
for (const key in bits!) {
if (data & bits![key]!) {
keys.push(key)
}
}
} else if (Array.isArray(data)) {
keys = data
for (const key of keys) {
if (typeof key !== 'string') throw new TypeError(`expected string but got ${key}`)
if (key in bits!) value |= bits![key]!
}
} else {
throw new TypeError(`expected number or array but got ${data}`)
}
if (value === meta.default) return [value]
return [value, keys]
})
Schema.extend('function', (data) => {
if (typeof data === 'function') return [data]
throw new TypeError(`expected function but got ${data}`)
})
Schema.extend('is', (data, { callback }) => {
if (data instanceof callback!) return [data]
throw new TypeError(`expected ${callback!.name} but got ${data}`)
})
function property(data: any, key: keyof any, schema: Schema, options?: Schemastery.Options) {
try {
const [value, adapted] = Schema.resolve(data[key], schema, options)
if (adapted !== undefined) data[key] = adapted
return value
} catch (e) {
if (!options?.autofix) throw e
delete data[key]
return schema.meta.default
}
}
Schema.extend('array', (data, { inner, meta }, options) => {
if (!Array.isArray(data)) throw new TypeError(`expected array but got ${data}`)
while (data.length && isNullable(data[data.length - 1])) data.pop()
checkWithinRange(data.length, meta, 'array length', !isNullable(inner!.meta.default))
return [data.map((_, index) => property(data, index, inner!, options))]
})
Schema.extend('dict', (data, { inner, sKey }, options, strict) => {
if (!isPlainObject(data)) throw new TypeError(`expected object but got ${data}`)
const result: any = {}
for (const key in data) {
let rKey: string
try {
rKey = Schema.resolve(key, sKey!)[0]
} catch (error) {
if (strict) continue
throw error
}
result[rKey] = property(data, key, inner!, options)
data[rKey] = data[key]
if (key !== rKey) delete data[key]
}
return [result]
})
Schema.extend('tuple', (data, { list }, options, strict) => {
if (!Array.isArray(data)) throw new TypeError(`expected array but got ${data}`)
const result = list!.map((inner, index) => property(data, index, inner, options))
if (strict) return [result]
result.push(...data.slice(list!.length))
return [result]
})
function merge(result: any, data: any) {
for (const key in data) {
if (key in result) continue
result[key] = data[key]
}
}
Schema.extend('object', (data, { dict }, options, strict) => {
if (!isPlainObject(data)) throw new TypeError(`expected object but got ${data}`)
const result: any = {}
for (const key in dict) {
const value = property(data, key, dict![key]!, options)
if (!isNullable(value) || key in data) {
result[key] = value
}
}
if (!strict) merge(result, data)
return [result]
})
Schema.extend('union', (data, { list, toString }, options, strict) => {
const messages: any[] = []
for (const inner of list!) {
try {
return Schema.resolve(data, inner, options, strict)
} catch (error) {
messages.push(error)
}
}
throw new TypeError(`expected ${toString()} but got ${JSON.stringify(data)}`)
})
Schema.extend('intersect', (data, { list, toString }, options, strict) => {
let result
for (const inner of list!) {
const value: any = Schema.resolve(data, inner, options, true)[0]
if (isNullable(value)) continue
if (isNullable(result)) {
result = value
} else if (typeof result !== typeof value) {
throw new TypeError(`expected ${toString()} but got ${JSON.stringify(data)}`)
} else if (typeof value === 'object') {
merge(result ??= {}, value)
} else if (result !== value) {
throw new TypeError(`expected ${toString()} but got ${JSON.stringify(data)}`)
}
}
if (!strict && isPlainObject(data)) merge(result, data)
return [result]
})
Schema.extend('transform', (data, { inner, callback, preserve }, options) => {
const [result, adapted = data] = Schema.resolve(data, inner!, options, true)
if (preserve) {
return [callback!(result)]
// } else if (isPlainObject(data)) {
// const temp: any = {}
// for (const key in result) {
// if (!(key in data)) continue
// temp[key] = data[key]
// delete data[key]
// }
// Object.assign(data, callback!(temp))
// return [callback!(result)]
} else {
return [callback!(result), callback!(adapted)]
}
})
type Formatter = (schema: Schema, inline?: boolean) => string
const formatters: Dict<Formatter> = {}
function defineMethod(name: string, keys: (keyof Schema)[], format: Formatter) {
formatters[name] = format
Object.assign(Schema, {
[name](...args: any[]) {
const schema = new Schema({ type: name } as Schema)
keys.forEach((key, index) => {
switch (key) {
case 'sKey': schema.sKey = args[index] ?? Schema.string(); break
case 'inner': schema.inner = Schema.from(args[index]); break
case 'list': schema.list = args[index].map(Schema.from); break
case 'dict': schema.dict = valueMap(args[index], Schema.from); break
case 'bits': {
schema.bits = {}
for (const key in args[index]) {
if (typeof args[index][key] !== 'number') continue
schema.bits[key] = args[index][key]
}
break
}
case 'callback': {
schema.callback = args[index]
;(schema.callback as any)['toJSON'] ||= () => schema.callback!.toString()
break
}
default: schema[key] = args[index] as never
}
})
if (name === 'object' || name === 'dict') {
schema.meta.default = {}
} else if (name === 'array' || name === 'tuple') {
schema.meta.default = []
} else if (name === 'bitset') {
schema.meta.default = 0
}
return schema
},
})
}
defineMethod('is', ['callback'], ({ callback }) => callback!.name)
defineMethod('any', [], () => 'any')
defineMethod('never', [], () => 'never')
defineMethod('const', ['value'], ({ value }) => typeof value === 'string' ? JSON.stringify(value) : value)
defineMethod('string', [], () => 'string')
defineMethod('number', [], () => 'number')
defineMethod('boolean', [], () => 'boolean')
defineMethod('bitset', ['bits'], () => 'bitset')
defineMethod('function', [], () => 'function')
defineMethod('array', ['inner'], ({ inner }) => `${inner!.toString(true)}[]`)
defineMethod('dict', ['inner', 'sKey'], ({ inner, sKey }) => `{ [key: ${sKey!.toString()}]: ${inner!.toString()} }`)
defineMethod('tuple', ['list'], ({ list }) => `[${list!.map((inner) => inner.toString()).join(', ')}]`)
defineMethod('object', ['dict'], ({ dict }) => {
if (Object.keys(dict!).length === 0) return '{}'
return `{ ${Object.entries(dict!).map(([key, inner]) => {
return `${key}${inner!.meta.required ? '' : '?'}: ${inner!.toString()}`
}).join(', ')} }`
})
defineMethod('union', ['list'], ({ list }, inline) => {
const result = list!.map(({ toString: format }) => format()).join(' | ')
return inline ? `(${result})` : result
})
defineMethod('intersect', ['list'], ({ list }) => {
return `${list!.map((inner) => inner.toString(true)).join(' & ')}`
})
defineMethod('transform', ['inner', 'callback', 'preserve'], ({ inner }, isInner) => inner!.toString(isInner))
export = Schema