forked from arktypeio/arktype
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscope.ts
More file actions
900 lines (764 loc) · 24.8 KB
/
Copy pathscope.ts
File metadata and controls
900 lines (764 loc) · 24.8 KB
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
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
import {
ParseError,
flatMorph,
hasDomain,
isArray,
isThunk,
printable,
throwInternalError,
throwParseError,
type Dict,
type Fn,
type Hkt,
type JsonStructure,
type anyOrNever,
type array,
type conform,
type flattenListable,
type intersectUnion,
type listable,
type noSuggest,
type satisfy,
type show
} from "@ark/util"
import {
mergeConfigs,
type ArkSchemaConfig,
type ResolvedConfig
} from "./config.ts"
import {
GenericRoot,
LazyGenericBody,
type GenericRootParser
} from "./generic.ts"
import {
nodeImplementationsByKind,
type NodeSchema,
type RootSchema,
type nodeOfKind,
type reducibleKindOf
} from "./kinds.ts"
import {
RootModule,
bindModule,
type InternalModule,
type PreparsedNodeResolution,
type SchemaModule,
type instantiateRoot
} from "./module.ts"
import type { BaseNode } from "./node.ts"
import {
nodesByRegisteredId,
parseNode,
registerNodeId,
schemaKindOf,
withId,
type AttachedParseContext,
type BaseParseContext,
type BaseParseContextInput,
type BaseParseOptions,
type NodeId,
type NodeParseContext,
type NodeParseContextInput
} from "./parse.ts"
import { Alias } from "./roots/alias.ts"
import type { BaseRoot } from "./roots/root.ts"
import type { UnionNode } from "./roots/union.ts"
import { CompiledFunction, NodeCompiler } from "./shared/compile.ts"
import type { NodeKind, RootKind } from "./shared/implement.ts"
import { $ark } from "./shared/registry.ts"
import {
Traversal,
type TraverseAllows,
type TraverseApply
} from "./shared/traversal.ts"
import { arkKind, hasArkKind, isNode } from "./shared/utils.ts"
export type InternalResolutions = Record<string, InternalResolution | undefined>
export type exportedNameOf<$> = Exclude<keyof $ & string, PrivateDeclaration>
export type resolvableReferenceIn<$> = {
[k in keyof $]: k extends string ?
k extends PrivateDeclaration<infer alias> ? alias
: // technically, root subtypes are resolvable, but there's never a good
// reason to use them over the base alias
k extends noSuggest | "root" ? never
: k
: never
}[keyof $]
export type resolveReference<reference extends resolvableReferenceIn<$>, $> =
reference extends keyof $ ? $[reference] : $[`#${reference}` & keyof $]
export type flatResolutionsOf<$> = show<
intersectUnion<
resolvableReferenceIn<$> extends infer k ?
k extends keyof $ & string ?
resolutionsOfReference<k, $[k]>
: unknown
: unknown
>
>
type resolutionsOfReference<k extends string, v> =
[v] extends [{ [arkKind]: "module" }] ?
[v] extends [anyOrNever] ?
{ [_ in k]: v }
: prefixKeys<flatResolutionsOf<v>, k> & {
[innerKey in keyof v as innerKey extends "root" ? k
: never]: v[innerKey]
}
: { [_ in k]: v }
type prefixKeys<o, prefix extends string> = {
[k in keyof o & string as `${prefix}.${k}`]: o[k]
} & unknown
export type PrivateDeclaration<key extends string = string> = `#${key}`
export type InternalResolution = BaseRoot | GenericRoot | InternalModule
export type toInternalScope<$> = BaseScope<{
[k in keyof $]: $[k] extends { [arkKind]: infer kind } ?
[$[k]] extends [anyOrNever] ? BaseRoot
: kind extends "generic" ? GenericRoot
: kind extends "module" ? InternalModule
: never
: BaseRoot
}>
type CachedResolution = NodeId | BaseRoot | GenericRoot
const schemaBranchesOf = (schema: object) =>
isArray(schema) ? schema
: "branches" in schema && isArray(schema.branches) ? schema.branches
: undefined
const throwMismatchedNodeRootError = (expected: NodeKind, actual: NodeKind) =>
throwParseError(
`Node of kind ${actual} is not valid as a ${expected} definition`
)
export const writeDuplicateAliasError = <alias extends string>(
alias: alias
): writeDuplicateAliasError<alias> =>
`#${alias} duplicates public alias ${alias}`
export type writeDuplicateAliasError<alias extends string> =
`#${alias} duplicates public alias ${alias}`
export type AliasDefEntry = [name: string, defValue: unknown]
const scopesByName: Record<string, BaseScope | undefined> = {}
export type GlobalOnlyConfigOptionName = satisfy<
keyof ArkSchemaConfig,
"dateAllowsInvalid" | "numberAllowsNaN" | "onUndeclaredKey" | "keywords"
>
export interface ScopeOnlyConfigOptions {
name?: string
prereducedAliases?: boolean
}
export interface ArkSchemaScopeConfig
extends Omit<ArkSchemaConfig, GlobalOnlyConfigOptionName>,
ScopeOnlyConfigOptions {}
export interface ResolvedScopeConfig
extends ResolvedConfig,
ScopeOnlyConfigOptions {}
$ark.ambient ??= {} as never
let rawUnknownUnion: UnionNode | undefined
const rootScopeFnName = "function $"
const precompile = (references: readonly BaseNode[]): void =>
bindPrecompilation(references, precompileReferences(references))
const bindPrecompilation = (
references: readonly BaseNode[],
precompiler: CompiledFunction<() => PrecompiledReferences>,
owningScope?: BaseScope
): void => {
const precompilation = precompiler.write(rootScopeFnName, 4)
const compiledTraversals = precompiler.compile()()
for (const node of references) {
if (node.precompilation && (!owningScope || node.$ !== owningScope)) {
// if node has already been bound to another scope or anonymous type, don't rebind it
continue
}
node.traverseAllows =
compiledTraversals[`${node.id}Allows`].bind(compiledTraversals)
if (node.isRoot() && !node.allowsRequiresContext) {
// if the reference doesn't require context, we can assign over
// it directly to avoid having to initialize it
node.allows = node.traverseAllows as never
}
node.traverseApply =
compiledTraversals[`${node.id}Apply`].bind(compiledTraversals)
if (compiledTraversals[`${node.id}Optimistic`]) {
;(node as UnionNode).traverseOptimistic =
compiledTraversals[`${node.id}Optimistic`].bind(compiledTraversals)
}
node.precompilation = precompilation
}
}
export type PrecompiledReferences = {
[k: `${string}Allows`]: TraverseAllows
[k: `${string}Apply`]: TraverseApply
[k: `${string}Optimistic`]: (data: unknown) => unknown
}
const precompileReferences = (references: readonly BaseNode[]) =>
new CompiledFunction<() => PrecompiledReferences>().return(
references.reduce((js, node) => {
const allowsCompiler = new NodeCompiler({ kind: "Allows" }).indent()
node.compile(allowsCompiler)
const allowsJs = allowsCompiler.write(`${node.id}Allows`)
const applyCompiler = new NodeCompiler({ kind: "Apply" }).indent()
node.compile(applyCompiler)
const applyJs = applyCompiler.write(`${node.id}Apply`)
const result = `${js}${allowsJs},\n${applyJs},\n`
if (!node.hasKind("union")) return result
const optimisticCompiler = new NodeCompiler({
kind: "Allows",
optimistic: true
}).indent()
node.compile(optimisticCompiler)
const optimisticJs = optimisticCompiler.write(`${node.id}Optimistic`)
return `${result}${optimisticJs},\n`
}, "{\n") + "}"
)
export abstract class BaseScope<$ extends {} = {}> {
readonly config: ArkSchemaScopeConfig
readonly resolvedConfig: ResolvedScopeConfig
readonly name: string
get [arkKind](): "scope" {
return "scope"
}
readonly referencesById: { [id: string]: BaseNode } = {}
references: readonly BaseNode[] = []
readonly resolutions: {
[alias: string]: CachedResolution | undefined
} = {}
exportedNames: string[] = []
readonly aliases: Record<string, unknown> = {}
protected resolved = false
readonly nodesByHash: Record<string, BaseNode> = {}
readonly intrinsic: Omit<typeof $ark.intrinsic, `json${string}`>
constructor(
/** The set of names defined at the root-level of the scope mapped to their
* corresponding definitions.**/
def: Record<string, unknown>,
config?: ArkSchemaScopeConfig
) {
this.config = mergeConfigs($ark.config, config)
this.resolvedConfig = mergeConfigs($ark.resolvedConfig, config)
this.name =
this.resolvedConfig.name ??
`anonymousScope${Object.keys(scopesByName).length}`
if (this.name in scopesByName)
throwParseError(`A Scope already named ${this.name} already exists`)
scopesByName[this.name] = this
const aliasEntries = Object.entries(def).map(entry =>
this.preparseOwnAliasEntry(...entry)
)
for (const [k, v] of aliasEntries) {
let name = k
if (k[0] === "#") {
name = k.slice(1)
if (name in this.aliases)
throwParseError(writeDuplicateAliasError(name))
this.aliases[name] = v
} else {
if (name in this.aliases) throwParseError(writeDuplicateAliasError(k))
this.aliases[name] = v
this.exportedNames.push(name)
}
if (
!hasArkKind(v, "module") &&
!hasArkKind(v, "generic") &&
!isThunk(v)
) {
const preparsed = this.preparseOwnDefinitionFormat(v, { alias: name })
this.resolutions[name] =
hasArkKind(preparsed, "root") ?
this.bindReference(preparsed)
: this.createParseContext(preparsed).id
}
}
// reduce union of all possible values reduces to unknown
rawUnknownUnion ??= this.node(
"union",
{
branches: [
"string",
"number",
"object",
"bigint",
"symbol",
{ unit: true },
{ unit: false },
{ unit: undefined },
{ unit: null }
]
},
{ prereduced: true }
)
this.nodesByHash[rawUnknownUnion.hash] = this.node(
"intersection",
{},
{ prereduced: true }
)
this.intrinsic =
$ark.intrinsic ?
flatMorph($ark.intrinsic, (k, v) =>
// don't include cyclic aliases from JSON scope
k.startsWith("json") ? [] : [k, this.bindReference(v as never)]
)
// intrinsic won't be available during bootstrapping, so we lie
// about the type here as an extrnal convenience
: ({} as never)
}
protected cacheGetter<name extends keyof this>(
name: name,
value: this[name]
): this[name] {
Object.defineProperty(this, name, { value })
return value
}
get internal(): this {
return this
}
// json is populated when the scope is exported, so ensure it is populated
// before allowing external access
private _json: JsonStructure | undefined
get json(): JsonStructure {
if (!this._json) this.export()
return this._json!
}
defineSchema<def extends RootSchema>(def: def): def {
return def
}
generic: GenericRootParser = (...params) => {
const $: BaseScope = this as never
return (def: unknown, possibleHkt?: Hkt.constructor) =>
new GenericRoot(
params,
possibleHkt ? new LazyGenericBody(def as Fn) : def,
$,
$,
possibleHkt ?? null
) as never
}
units = (values: array, opts?: BaseParseOptions): BaseRoot => {
const uniqueValues: unknown[] = []
for (const value of values)
if (!uniqueValues.includes(value)) uniqueValues.push(value)
const branches = uniqueValues.map(unit => this.node("unit", { unit }, opts))
return this.node("union", branches, {
...opts,
prereduced: true
})
}
protected lazyResolutions: Alias.Node[] = []
lazilyResolve(resolve: () => BaseRoot, syntheticAlias?: string): Alias.Node {
const node = this.node(
"alias",
{
reference: syntheticAlias ?? "synthetic",
resolve
},
{ prereduced: true }
)
if (!this.resolved) this.lazyResolutions.push(node)
return node
}
schema: InternalSchemaParser = (schema, opts) =>
this.finalize(this.parseSchema(schema, opts))
parseSchema: InternalSchemaParser = (schema, opts) =>
this.node(schemaKindOf(schema), schema, opts)
protected preparseNode(
kinds: NodeKind | listable<RootKind>,
schema: unknown,
opts: BaseParseOptions
): BaseNode | NodeParseContextInput {
let kind: NodeKind =
typeof kinds === "string" ? kinds : schemaKindOf(schema, kinds)
if (isNode(schema) && schema.kind === kind) return schema
if (kind === "alias" && !opts?.prereduced) {
const { reference } = Alias.implementation.normalize(
schema as never,
this
)
if (reference.startsWith("$")) {
const resolution = this.resolveRoot(reference.slice(1))
schema = resolution
kind = resolution.kind
}
} else if (kind === "union" && hasDomain(schema, "object")) {
const branches = schemaBranchesOf(schema)
if (branches?.length === 1) {
schema = branches[0]
kind = schemaKindOf(schema)
}
}
if (isNode(schema) && schema.kind === kind) return schema
const impl = nodeImplementationsByKind[kind]
const normalizedSchema = impl.normalize?.(schema, this) ?? schema
// check again after normalization in case a node is a valid collapsed
// schema for the kind (e.g. sequence can collapse to element accepting a Node')
if (isNode(normalizedSchema)) {
return normalizedSchema.kind === kind ?
normalizedSchema
: throwMismatchedNodeRootError(kind, normalizedSchema.kind)
}
return {
...opts,
$: this,
kind,
def: normalizedSchema,
prefix: opts.alias ?? kind
}
}
bindReference<reference extends BaseNode | GenericRoot>(
reference: reference
): reference {
let bound: reference
if (isNode(reference)) {
bound =
reference.$ === this ?
reference
: new (reference.constructor as any)(reference.attachments, this)
} else {
bound =
reference.$ === this ?
reference
: (new GenericRoot(
reference.params as never,
reference.bodyDef,
reference.$,
this as never,
reference.hkt
) as never)
}
if (!this.resolved) {
// we're still parsing the scope itself, so defer compilation but
// add the node as a reference
Object.assign(this.referencesById, bound.referencesById)
}
return bound as never
}
resolveRoot(name: string): BaseRoot {
return (
this.maybeResolveRoot(name) ??
throwParseError(writeUnresolvableMessage(name))
)
}
maybeResolveRoot(name: string): BaseRoot | undefined {
const result = this.maybeResolve(name)
if (hasArkKind(result, "generic")) return
return result
}
/** If name is a valid reference to a submodule alias, return its resolution */
protected maybeResolveSubalias(
name: string
): BaseRoot | GenericRoot | undefined {
return (
maybeResolveSubalias(this.aliases, name) ??
maybeResolveSubalias(this.ambient, name)
)
}
get ambient(): InternalModule {
return $ark.ambient as never
}
maybeResolve(name: string): Exclude<CachedResolution, string> | undefined {
const cached = this.resolutions[name]
if (cached) {
if (typeof cached !== "string") return this.bindReference(cached)
const v = nodesByRegisteredId[cached]
if (hasArkKind(v, "root")) return (this.resolutions[name] = v)
if (hasArkKind(v, "context")) {
if (v.phase === "resolving") {
return this.node(
"alias",
{ reference: `$${name}` },
{ prereduced: true }
)
}
if (v.phase === "resolved") {
return throwInternalError(
`Unexpected resolved context for was uncached by its scope: ${printable(v)}`
)
}
v.phase = "resolving"
const node = this.bindReference(this.parseOwnDefinitionFormat(v.def, v))
v.phase = "resolved"
nodesByRegisteredId[node.id] = node
nodesByRegisteredId[v.id] = node
return (this.resolutions[name] = node)
}
return throwInternalError(
`Unexpected nodesById entry for ${cached}: ${printable(v)}`
)
}
let def: unknown = this.aliases[name] ?? this.ambient?.[name]
if (!def) return this.maybeResolveSubalias(name)
def = this.normalizeRootScopeValue(def)
if (hasArkKind(def, "generic"))
return (this.resolutions[name] = this.bindReference(def))
if (hasArkKind(def, "module")) {
if (!def.root) throwParseError(writeMissingSubmoduleAccessMessage(name))
return (this.resolutions[name] = this.bindReference(def.root))
}
return (this.resolutions[name] = this.parse(def, {
alias: name
}))
}
protected createParseContext<input extends BaseParseContextInput>(
input: input
): input & AttachedParseContext {
const id = input.id ?? registerNodeId(input.prefix)
return (nodesByRegisteredId[id] = Object.assign(input, {
[arkKind]: "context" as const,
$: this as never,
id,
phase: "unresolved" as const
}))
}
traversal(root: unknown): Traversal {
return new Traversal(root, this.resolvedConfig)
}
import(): SchemaModule<{
[k in exportedNameOf<$> as PrivateDeclaration<k>]: $[k]
}>
import<names extends exportedNameOf<$>[]>(
...names: names
): SchemaModule<
{
[k in names[number] as PrivateDeclaration<k>]: $[k]
} & unknown
>
import(...names: string[]): SchemaModule {
return new RootModule(
flatMorph(this.export(...(names as any)), (alias, value) => [
`#${alias}`,
value
]) as never
) as never
}
precompilation: string | undefined
private _exportedResolutions: InternalResolutions | undefined
private _exports: RootExportCache | undefined
export(): SchemaModule<{ [k in exportedNameOf<$>]: $[k] }>
export<names extends exportedNameOf<$>[]>(
...names: names
): SchemaModule<
{
[k in names[number]]: $[k]
} & unknown
>
export(...names: string[]): SchemaModule {
if (!this._exports) {
this._exports = {}
for (const name of this.exportedNames) {
const def = this.aliases[name]
this._exports[name] =
hasArkKind(def, "module") ?
bindModule(def, this)
: bootstrapAliasReferences(this.maybeResolve(name)!)
}
// force node.resolution getter evaluation
// eslint-disable-next-line @typescript-eslint/no-unused-expressions
for (const node of this.lazyResolutions) node.resolution
this._exportedResolutions = resolutionsOfModule(this, this._exports)
this._json = resolutionsToJson(this._exportedResolutions)
Object.assign(this.resolutions, this._exportedResolutions)
this.references = Object.values(this.referencesById)
if (!this.resolvedConfig.jitless) {
const precompiler = precompileReferences(this.references)
this.precompilation = precompiler.write(rootScopeFnName, 4)
bindPrecompilation(this.references, precompiler, this)
}
this.resolved = true
}
const namesToExport = names.length ? names : this.exportedNames
return new RootModule(
flatMorph(namesToExport, (_, name) => [
name,
this._exports![name]
]) as never
) as never
}
resolve<name extends exportedNameOf<$>>(
name: name
): instantiateRoot<$[name]> {
return this.export()[name as never]
}
node = <
kinds extends NodeKind | array<RootKind>,
prereduced extends boolean = false
>(
kinds: kinds,
nodeSchema: NodeSchema<flattenListable<kinds>>,
opts = {} as BaseParseOptions<prereduced>
): nodeOfKind<
prereduced extends true ? flattenListable<kinds>
: reducibleKindOf<flattenListable<kinds>>
> => {
const ctxOrNode = this.preparseNode(kinds, nodeSchema, opts)
if (isNode(ctxOrNode)) return this.bindReference(ctxOrNode) as never
const ctx = this.createParseContext(ctxOrNode)
const node = parseNode(ctx)
const bound = this.bindReference(node)
return (nodesByRegisteredId[ctx.id] = bound) as never
}
parse = (def: unknown, opts: BaseParseOptions = {}): BaseRoot =>
this.finalize(this.parseDefinition(def, opts))
parseDefinition(def: unknown, opts: BaseParseOptions = {}): BaseRoot {
if (hasArkKind(def, "root")) return this.bindReference(def)
const ctxInputOrNode = this.preparseOwnDefinitionFormat(def, opts)
if (hasArkKind(ctxInputOrNode, "root"))
return this.bindReference(ctxInputOrNode)
const ctx = this.createParseContext(ctxInputOrNode)
nodesByRegisteredId[ctx.id] = ctx
let node = this.bindReference(this.parseOwnDefinitionFormat(def, ctx))
// if the node is recursive e.g. { box: "this" }, we need to make sure it
// has the original id from context so that its references compile correctly
if (node.isCyclic) node = withId(node, ctx.id)
nodesByRegisteredId[ctx.id] = node
return node
}
finalize<node extends BaseRoot>(node: node): node {
bootstrapAliasReferences(node)
if (!node.precompilation && !this.resolvedConfig.jitless)
precompile(node.references)
return node
}
protected abstract preparseOwnDefinitionFormat(
def: unknown,
opts: BaseParseOptions
): BaseRoot | BaseParseContextInput
abstract parseOwnDefinitionFormat(
def: unknown,
ctx: BaseParseContext
): BaseRoot
protected abstract preparseOwnAliasEntry(k: string, v: unknown): AliasDefEntry
protected abstract normalizeRootScopeValue(resolution: unknown): unknown
}
export class SchemaScope<$ extends {} = {}> extends BaseScope<$> {
parseOwnDefinitionFormat(def: unknown, ctx: NodeParseContext): BaseRoot {
return parseNode(ctx) as never
}
protected preparseOwnDefinitionFormat(
schema: RootSchema,
opts: BaseParseOptions
): BaseRoot | NodeParseContextInput {
return this.preparseNode(schemaKindOf(schema), schema, opts) as never
}
protected preparseOwnAliasEntry(k: string, v: unknown): AliasDefEntry {
return [k, v]
}
protected normalizeRootScopeValue(v: unknown): unknown {
return v
}
}
const bootstrapAliasReferences = (resolution: BaseRoot | GenericRoot) => {
const aliases = resolution.references.filter(node => node.hasKind("alias"))
for (const aliasNode of aliases) {
Object.assign(aliasNode.referencesById, aliasNode.resolution.referencesById)
for (const ref of resolution.references) {
if (aliasNode.id in ref.referencesById)
Object.assign(ref.referencesById, aliasNode.referencesById)
}
}
return resolution
}
const resolutionsToJson = (resolutions: InternalResolutions): JsonStructure =>
flatMorph(resolutions, (k, v) => [
k,
hasArkKind(v, "root") || hasArkKind(v, "generic") ? v.json
: hasArkKind(v, "module") ? resolutionsToJson(v)
: throwInternalError(`Unexpected resolution ${printable(v)}`)
])
const maybeResolveSubalias = (
base: Dict,
name: string
): BaseRoot | GenericRoot | undefined => {
const dotIndex = name.indexOf(".")
if (dotIndex === -1) return
const dotPrefix = name.slice(0, dotIndex)
const prefixSchema = base[dotPrefix]
// if the name includes ".", but the prefix is not an alias, it
// might be something like a decimal literal, so just fall through to return
if (prefixSchema === undefined) return
if (!hasArkKind(prefixSchema, "module"))
return throwParseError(writeNonSubmoduleDotMessage(dotPrefix))
const subalias = name.slice(dotIndex + 1)
const resolution = prefixSchema[subalias]
if (resolution === undefined)
return maybeResolveSubalias(prefixSchema, subalias)
if (hasArkKind(resolution, "root") || hasArkKind(resolution, "generic"))
return resolution
if (hasArkKind(resolution, "module")) {
return (
resolution.root ??
throwParseError(writeMissingSubmoduleAccessMessage(name))
)
}
throwInternalError(
`Unexpected resolution for alias '${name}': ${printable(resolution)}`
)
}
type instantiateAliases<aliases> = {
[k in keyof aliases]: aliases[k] extends InternalResolution ? aliases[k]
: BaseRoot
} & unknown
export type SchemaScopeParser = <const aliases>(
aliases: {
[k in keyof aliases]: conform<
aliases[k],
RootSchema | PreparsedNodeResolution
>
},
config?: ArkSchemaScopeConfig
) => BaseScope<instantiateAliases<aliases>>
export const schemaScope: SchemaScopeParser = (aliases, config) =>
new SchemaScope(aliases, config)
export type InternalSchemaParser = (
schema: RootSchema,
opts?: BaseParseOptions
) => BaseRoot
export const rootSchemaScope: SchemaScope = new SchemaScope({})
export const parseAsSchema = (
def: unknown,
opts?: BaseParseOptions
): BaseRoot | ParseError => {
try {
return rootSchema(def as RootSchema, opts) as never
} catch (e) {
if (e instanceof ParseError) return e
throw e
}
}
export type RootExportCache = Record<
string,
BaseRoot | GenericRoot | RootModule | undefined
>
const resolutionsOfModule = ($: BaseScope, typeSet: RootExportCache) => {
const result: InternalResolutions = {}
for (const k in typeSet) {
const v = typeSet[k]
if (hasArkKind(v, "module")) {
const innerResolutions = resolutionsOfModule($, v as never)
const prefixedResolutions = flatMorph(
innerResolutions,
(innerK, innerV) => [`${k}.${innerK}`, innerV]
)
Object.assign(result, prefixedResolutions)
} else if (hasArkKind(v, "root") || hasArkKind(v, "generic")) result[k] = v
else throwInternalError(`Unexpected scope resolution ${printable(v)}`)
}
return result
}
export const writeUnresolvableMessage = <token extends string>(
token: token
): writeUnresolvableMessage<token> => `'${token}' is unresolvable`
export type writeUnresolvableMessage<token extends string> =
`'${token}' is unresolvable`
export const writeNonSubmoduleDotMessage = <name extends string>(
name: name
): writeNonSubmoduleDotMessage<name> =>
`'${name}' must reference a module to be accessed using dot syntax`
export type writeNonSubmoduleDotMessage<name extends string> =
`'${name}' must reference a module to be accessed using dot syntax`
export const writeMissingSubmoduleAccessMessage = <name extends string>(
name: name
): writeMissingSubmoduleAccessMessage<name> =>
`Reference to submodule '${name}' must specify an alias`
export type writeMissingSubmoduleAccessMessage<name extends string> =
`Reference to submodule '${name}' must specify an alias`
// ensure the scope is resolved so JIT will be applied to future types
rootSchemaScope.export()
export const rootSchema: BaseScope["schema"] = rootSchemaScope.schema
export const node: BaseScope["node"] = rootSchemaScope.node
export const defineSchema: BaseScope["defineSchema"] =
rootSchemaScope.defineSchema
export const genericNode: BaseScope["generic"] = rootSchemaScope.generic