forked from arktypeio/arktype
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfn.ts
More file actions
191 lines (167 loc) · 5.24 KB
/
Copy pathfn.ts
File metadata and controls
191 lines (167 loc) · 5.24 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
import type { BaseRoot, IntersectionNode } from "@ark/schema"
import {
Callable,
throwParseError,
type applyElementLabels,
type conform,
type Fn,
type get
} from "@ark/util"
import type { distill } from "./attributes.ts"
import type { type } from "./keywords/keywords.ts"
import type { validateInnerDefinition } from "./parser/definition.ts"
import type {
inferTupleLiteral,
validateTupleLiteral
} from "./parser/tupleLiteral.ts"
import type { InternalScope, Scope } from "./scope.ts"
import type { Type } from "./type.ts"
export type BaseFnParser<$ = {}> = <
const args extends readonly unknown[],
paramsT extends readonly unknown[] = inferTupleLiteral<
args extends readonly [...infer params, ":", unknown] ? params : args,
$,
{}
>,
returnT = args extends readonly [...unknown[], ":", infer returnDef] ?
type.infer<returnDef, $>
: unknown
>(
...args: {
[i in keyof args]: conform<args[i], get<validateFnArgs<args, $>, i>>
}
) => <
internalSignature extends (
...args: distill.Out<paramsT>
) => distill.In<returnT>,
externalSignature extends Fn = (
...args: applyElementLabels<
distill.In<paramsT>,
Parameters<internalSignature>
>
) => args extends readonly [...unknown[], ":", unknown] ? distill.Out<returnT>
: ReturnType<internalSignature>
>(
implementation: internalSignature
) => TypedFn<
externalSignature,
$,
args extends readonly [...unknown[], ":", unknown] ? Return.introspectable
: {}
>
export interface FnParser<$ = {}> extends BaseFnParser<$> {
/**
* The {@link Scope} in which definitions passed to this function will be parsed.
*/
$: Scope<$>
/**
* An alias of `fn` with no type-level validation or inference.
*
* Useful when wrapping `fn` or using it to parse a dynamic definition.
*/
raw: RawFnParser
}
export type RawFnParser = (
...args: unknown[]
) => (...args: unknown[]) => unknown
type FnParserAttachments = Omit<FnParser, never>
export class InternalFnParser extends Callable<(...args: unknown[]) => Fn> {
constructor($: InternalScope) {
const parse = (...signature: unknown[]) => {
const returnOperatorIndex = signature.indexOf(":")
const lastParamIndex =
returnOperatorIndex === -1 ?
signature.length - 1
: returnOperatorIndex - 1
const paramDefs = signature.slice(0, lastParamIndex + 1)
const paramTuple = $.parse(paramDefs).assertHasKind("intersection")
let returnType: BaseRoot = $.intrinsic.unknown
if (returnOperatorIndex !== -1) {
if (returnOperatorIndex !== signature.length - 2)
return throwParseError(badFnReturnTypeMessage)
returnType = $.parse(signature[returnOperatorIndex + 1])
}
return (impl: Fn) => new InternalTypedFn(impl, paramTuple, returnType)
}
// `raw` is an alias of `fn` itself with no type-level validation. It must
// reference `parse` directly rather than `$.fn`, which is still being
// constructed (and thus `undefined`) at this point.
const attach: FnParserAttachments = {
$: $ as never,
raw: parse
}
super(parse, { attach })
}
}
export declare namespace TypedFn {
export type meta = {
introspectableReturn?: true
}
}
export interface TypedFn<
signature extends Fn = Fn,
$ = {},
meta extends TypedFn.meta = {}
> extends Callable<signature> {
expression: string
params: signature extends Fn<infer params> ? Type<params, $> : never
returns: Type<
meta extends Return.introspectable ? ReturnType<signature> : unknown,
$
>
}
export class InternalTypedFn extends Callable<(...args: unknown[]) => unknown> {
raw: Fn
params: IntersectionNode
returns: BaseRoot
expression: string
constructor(raw: Fn, params: IntersectionNode, returns: BaseRoot) {
const typedName = `typed ${raw.name}`
const typed = {
// assign to a key with the expected name to force it to be created that way
[typedName]: (...args: unknown[]) => {
const validatedArgs = params.assert(args) as unknown[]
const returned = raw(...validatedArgs)
return returns.assert(returned)
}
}[typedName]
super(typed)
this.raw = raw
this.params = params
this.returns = returns
let argsExpression = params.expression
if (
argsExpression[0] === "[" &&
argsExpression[argsExpression.length - 1] === "]"
)
argsExpression = argsExpression.slice(1, -1)
else if (argsExpression.endsWith("[]"))
argsExpression = `...${argsExpression}`
this.expression = `(${argsExpression}) => ${returns?.expression ?? "unknown"}`
}
}
export declare namespace Return {
export interface introspectable {
introspectableReturn: true
}
}
type validateFnArgs<args, $> =
args extends readonly unknown[] ?
args extends readonly [...infer paramDefs, ":", infer returnDef] ?
readonly [
...validateFnParamDefs<paramDefs, $>,
":",
type.validate<returnDef, $>
]
: validateFnParamDefs<args, $>
: never
type validateFnParamDefs<paramDefs extends readonly unknown[], $> =
paramDefs extends validateTupleLiteral<paramDefs, $, {}> ? paramDefs
: paramDefs extends {
[i in keyof paramDefs]: paramDefs[i] extends "..." ? paramDefs[i]
: validateInnerDefinition<paramDefs[i], $, {}>
} ?
validateTupleLiteral<paramDefs, $, {}>
: { [i in keyof paramDefs]: validateInnerDefinition<paramDefs[i], $, {}> }
export const badFnReturnTypeMessage = `":" must be followed by exactly one return type e.g:
fn("string", ":", "number")(s => s.length)`