-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
emits.ts
245 lines (211 loc) · 6.24 KB
/
emits.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
import {
babelParse,
isStaticExpression,
resolveLiteral,
} from '@vue-macros/common'
import {
isTSExports,
resolveTSProperties,
resolveTSReferencedType,
resolveTSScope,
} from '../ts'
import { keyToString } from '../utils'
import { DefinitionKind } from './types'
import { attachNodeLoc } from './utils'
import type { TSFile, TSResolvedType } from '../ts'
import type { MagicString, SFC } from '@vue-macros/common'
import type { ASTDefinition } from './types'
import type {
CallExpression,
ExpressionStatement,
LVal,
Node,
StringLiteral,
TSCallSignatureDeclaration,
TSInterfaceDeclaration,
TSIntersectionType,
TSType,
TSTypeLiteral,
UnaryExpression,
VariableDeclaration,
} from '@babel/types'
export async function handleTSEmitsDefinition({
s,
file,
offset,
defineEmitsAst,
typeDeclRaw,
declId,
statement,
}: {
s: MagicString
file: TSFile
sfc: SFC
offset: number
defineEmitsAst: CallExpression
typeDeclRaw: TSType
statement: DefineEmitsStatement
declId?: LVal
}): Promise<TSEmits> {
const { definitions, definitionsAst } = await resolveDefinitions({
type: typeDeclRaw,
scope: file,
})
const addEmit: TSEmits['addEmit'] = (name, signature) => {
const key = keyToString(name)
if (definitionsAst.scope === file) {
if (definitionsAst.ast.type === 'TSIntersectionType') {
s.appendLeft(definitionsAst.ast.end! + offset, ` & { ${signature} }`)
} else {
s.appendLeft(definitionsAst.ast.end! + offset - 1, ` ${signature}\n`)
}
}
if (!definitions[key]) definitions[key] = []
const ast = parseSignature(signature)
definitions[key].push({
code: signature,
ast,
scope: undefined,
})
}
const setEmit: TSEmits['setEmit'] = (name, idx, signature) => {
const key = keyToString(name)
const def = definitions[key][idx]
if (!def) return false
const ast = parseSignature(signature)
attachNodeLoc(def.ast, ast)
if (def.scope === file) s.overwriteNode(def.ast, signature, { offset })
definitions[key][idx] = {
code: signature,
ast,
scope: undefined,
}
return true
}
const removeEmit: TSEmits['removeEmit'] = (name, idx) => {
const key = keyToString(name)
const def = definitions[key][idx]
if (!def) return false
if (def.scope === file) s.removeNode(def.ast, { offset })
delete definitions[key][idx]
return true
}
return {
kind: DefinitionKind.TS,
definitions,
definitionsAst,
declId,
addEmit,
setEmit,
removeEmit,
statementAst: statement,
defineEmitsAst,
}
function parseSignature(signature: string): TSCallSignatureDeclaration {
return (babelParse(`interface T {${signature}}`, 'ts').body[0] as any).body
.body[0]
}
async function resolveDefinitions(typeDeclRaw: TSResolvedType<TSType>) {
const resolved = await resolveTSReferencedType(typeDeclRaw)
if (!resolved || isTSExports(resolved))
throw new SyntaxError(`Cannot resolve TS definition.`)
const { type: definitionsAst, scope } = resolved
if (
definitionsAst.type !== 'TSInterfaceDeclaration' &&
definitionsAst.type !== 'TSTypeLiteral' &&
definitionsAst.type !== 'TSIntersectionType'
)
throw new SyntaxError(`Cannot resolve TS definition.`)
const properties = await resolveTSProperties({
scope,
type: definitionsAst,
})
const definitions: TSEmits['definitions'] = {}
for (const signature of properties.callSignatures) {
const evtArg = signature.type.parameters[0]
if (
!evtArg ||
evtArg.type !== 'Identifier' ||
evtArg.typeAnnotation?.type !== 'TSTypeAnnotation'
)
continue
const evtType = await resolveTSReferencedType({
type: evtArg.typeAnnotation.typeAnnotation,
scope: signature.scope,
})
if (isTSExports(evtType) || !evtType?.type) continue
const types =
evtType.type.type === 'TSUnionType'
? evtType.type.types
: [evtType.type]
for (const type of types) {
if (type.type !== 'TSLiteralType') continue
const literal = type.literal
if (!isStaticExpression(literal)) continue
const evt = String(
resolveLiteral(literal as Exclude<typeof literal, UnaryExpression>)
)
if (!definitions[evt]) definitions[evt] = []
definitions[evt].push(buildDefinition(signature))
}
}
return {
definitions,
definitionsAst: buildDefinition({ scope, type: definitionsAst }),
}
}
function buildDefinition<T extends Node>({
type,
scope,
}: TSResolvedType<T>): ASTDefinition<T> {
return {
code: resolveTSScope(scope).file.content.slice(type.start!, type.end!),
ast: type,
scope,
}
}
}
export type Emits = TSEmits | undefined
export type DefineEmitsStatement = VariableDeclaration | ExpressionStatement
export interface EmitsBase {
declId?: LVal
statementAst: DefineEmitsStatement
defineEmitsAst: CallExpression
}
export interface TSEmits extends EmitsBase {
kind: DefinitionKind.TS
definitions: Record<string, ASTDefinition<TSCallSignatureDeclaration>[]>
definitionsAst: ASTDefinition<
TSTypeLiteral | TSIntersectionType | TSInterfaceDeclaration
>
/**
* Adds a new emit to the definitions. `definitions` will updated after this call.
*
* Added definition cannot be set and removed again.
*
* @example add('change', '(evt: "change", value: string): void')
*/
addEmit(name: string | StringLiteral, signature: string): void
/**
* Modify a definition of a emit. `definitions` will updated after this call.
*
* @limitation Cannot set the emit added by `addEmit`.
*
* @example setEmit('foo', 0, '(evt: "change", value: string): void')
*
* @returns false if the definition does not exist.
*/
setEmit(
name: string | StringLiteral,
index: number,
signature: string
): boolean
/**
* Removes specified emit from TS interface. `definitions` will updated after this call.
*
* @limitation Cannot remove emit added by `addEmit`. (it will be removed in definitions though)
*
* @returns `true` if emit was removed, `false` if emit was not found.
*/
removeEmit(name: string | StringLiteral, index: number): boolean
}