-
-
Notifications
You must be signed in to change notification settings - Fork 21
/
ComponentParser.ts
556 lines (472 loc) · 16.7 KB
/
ComponentParser.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
import { compile, walk } from "svelte/compiler";
import * as commentParser from "comment-parser";
import { Ast, TemplateNode, Var } from "svelte/types/compiler/interfaces";
import { getElementByTag } from "./element-tag-map";
import { Node } from "estree-walker";
import type { VariableDeclaration } from "estree";
interface CompiledSvelteCode {
vars: Var[];
ast: Ast;
}
interface ComponentParserDiagnostics {
moduleName: string;
filePath: string;
}
interface ComponentParserOptions {
verbose?: boolean;
}
type ComponentPropName = string;
interface ComponentProp {
name: string;
kind: "let" | "const" | "function";
constant: boolean;
type?: string;
value?: any;
description?: string;
isFunction: boolean;
isFunctionDeclaration: boolean;
reactive: boolean;
}
const DEFAULT_SLOT_NAME = "__default__";
type ComponentSlotName = typeof DEFAULT_SLOT_NAME | string;
interface ComponentSlot {
name?: string;
default: boolean;
fallback?: string;
slot_props?: string;
}
interface SlotPropValue {
value?: string;
replace: boolean;
}
type SlotProps = Record<string, SlotPropValue>;
type ComponentEventName = string;
interface ForwardedEvent {
type: "forwarded";
name: string;
element: ComponentInlineElement | ComponentElement;
}
interface DispatchedEvent {
type: "dispatched";
name: string;
detail?: any;
}
type ComponentEvent = ForwardedEvent | DispatchedEvent;
type TypeDefName = string;
interface TypeDef extends Pick<commentParser.Tag, "type" | "name"> {
description?: string;
ts: string;
}
interface ComponentInlineElement {
type: "InlineComponent";
name: string;
}
interface ComponentElement {
type: "Element";
name: string;
}
type RestProps = undefined | ComponentInlineElement | ComponentElement;
interface Extends {
interface: string;
import: string;
}
interface ComponentPropBindings {
elements: string[];
}
export interface ParsedComponent {
props: ComponentProp[];
slots: ComponentSlot[];
events: ComponentEvent[];
typedefs: TypeDef[];
rest_props: RestProps;
extends?: Extends;
componentComment?: string;
}
export default class ComponentParser {
private options?: ComponentParserOptions;
private source?: string;
private compiled?: CompiledSvelteCode;
private rest_props?: RestProps;
private extends?: Extends;
private componentComment?: string;
private readonly reactive_vars: Set<string> = new Set();
private readonly vars: Set<VariableDeclaration> = new Set();
private readonly props: Map<ComponentPropName, ComponentProp> = new Map();
private readonly slots: Map<ComponentSlotName, ComponentSlot> = new Map();
private readonly events: Map<ComponentEventName, ComponentEvent> = new Map();
private readonly typedefs: Map<TypeDefName, TypeDef> = new Map();
private readonly bindings: Map<ComponentPropName, ComponentPropBindings> = new Map();
constructor(options?: ComponentParserOptions) {
this.options = options;
}
private static mapToArray(map: Map<any, any>) {
return Array.from(map, ([key, value]) => value);
}
private static assignValue(value?: "" | string) {
return value === undefined || value === "" ? undefined : value;
}
private static formatComment(comment: string) {
let formatted_comment = comment;
if (!formatted_comment.startsWith("/*")) {
formatted_comment = "/*" + formatted_comment;
}
if (!formatted_comment.endsWith("*/")) {
formatted_comment += "*/";
}
return formatted_comment;
}
private sourceAtPos(start: number, end: number) {
return this.source?.slice(start, end);
}
private collectReactiveVars() {
this.compiled?.vars
.filter(({ reassigned, writable }) => reassigned && writable)
.forEach(({ name }) => this.reactive_vars.add(name));
}
private addProp(prop_name: string, data: ComponentProp) {
if (ComponentParser.assignValue(prop_name) === undefined) return;
if (this.props.has(prop_name)) {
const existing_slot = this.props.get(prop_name)!;
this.props.set(prop_name, {
...existing_slot,
...data,
});
} else {
this.props.set(prop_name, data);
}
}
private aliasType(type: any) {
if (type === "*") return "any";
return type;
}
private addSlot(slot_name?: string, slot_props?: string, slot_fallback?: string) {
const default_slot = slot_name === undefined || slot_name === "";
const name: ComponentSlotName = default_slot ? DEFAULT_SLOT_NAME : slot_name!;
const fallback = ComponentParser.assignValue(slot_fallback);
const props = ComponentParser.assignValue(slot_props);
if (this.slots.has(name)) {
const existing_slot = this.slots.get(name)!;
this.slots.set(name, {
...existing_slot,
fallback,
slot_props: existing_slot.slot_props === undefined ? props : existing_slot.slot_props,
});
} else {
this.slots.set(name, {
name,
default: default_slot,
fallback,
slot_props,
});
}
}
private addDispatchedEvent(name?: string, detail?: string) {
if (name === undefined) return;
if (this.events.has(name)) {
const existing_event = this.events.get(name) as DispatchedEvent;
this.events.set(name, {
...existing_event,
detail: existing_event.detail === undefined ? ComponentParser.assignValue(detail) : existing_event.detail,
});
} else {
this.events.set(name, {
type: "dispatched",
name,
detail: ComponentParser.assignValue(detail),
});
}
}
private parseCustomTypes() {
commentParser(this.source!).forEach(({ tags }) => {
tags.forEach(({ tag, type: tagType, name, description }) => {
const type = this.aliasType(tagType);
switch (tag) {
case "extends":
this.extends = {
interface: name,
import: type,
};
break;
case "restProps":
this.rest_props = {
type: "Element",
name: type,
};
break;
case "slot":
this.addSlot(name, type);
break;
case "event":
this.addDispatchedEvent(name, type);
break;
case "typedef":
this.typedefs.set(name, {
type,
name,
description: ComponentParser.assignValue(description),
ts: /(\}|\};)$/.test(type) ? `interface ${name} ${type}` : `type ${name} = ${type}`,
});
break;
}
});
});
}
public cleanup() {
this.source = undefined;
this.compiled = undefined;
this.rest_props = undefined;
this.extends = undefined;
this.componentComment = undefined;
this.reactive_vars.clear();
this.props.clear();
this.slots.clear();
this.events.clear();
this.typedefs.clear();
this.bindings.clear();
}
public parseSvelteComponent(source: string, diagnostics: ComponentParserDiagnostics): ParsedComponent {
if (this.options?.verbose) {
process.stdout.write(`[parsing] "${diagnostics.moduleName}" ${diagnostics.filePath}\n`);
}
this.cleanup();
this.source = source;
this.compiled = compile(source);
this.collectReactiveVars();
this.parseCustomTypes();
let dispatcher_name: undefined | string = undefined;
let callees: { name: string; arguments: any }[] = [];
walk(this.compiled.ast as unknown as Node, {
enter: (node, parent, prop) => {
if (node.type === "CallExpression") {
if (node.callee.name === "createEventDispatcher") {
dispatcher_name = parent?.id.name;
}
callees.push({
name: node.callee.name,
arguments: node.arguments,
});
}
if (node.type === "Spread" && node?.expression.name === "$$restProps") {
if (this.rest_props === undefined && (parent?.type === "InlineComponent" || parent?.type === "Element")) {
this.rest_props = {
type: parent.type,
name: parent.name,
};
}
}
if (node.type === "VariableDeclaration") {
this.vars.add(node as unknown as VariableDeclaration);
}
if (node.type === "ExportNamedDeclaration") {
// Handle renamed exports
let prop_name: string;
if (node.declaration == null && node.specifiers[0]?.type === "ExportSpecifier") {
const specifier = node.specifiers[0];
const localName = specifier.local.name,
exportedName = specifier.exported.name;
let declaration: VariableDeclaration;
// Search through all variable declarations for this variable
// Limitation: the variable must have been declared before the export
this.vars.forEach((varDecl) => {
if (varDecl.declarations.some((decl) => decl.id.type === "Identifier" && decl.id.name === localName)) {
declaration = varDecl;
}
});
node.declaration = declaration!;
prop_name = exportedName;
}
const {
type: declaration_type,
id,
init,
body,
} = node.declaration.declarations ? node.declaration.declarations[0] : node.declaration;
prop_name ??= id.name;
let value = undefined;
let type = undefined;
let kind = node.declaration.kind;
let description = undefined;
let isFunction = false;
let isFunctionDeclaration = false;
if (init != null) {
if (
init.type === "ObjectExpression" ||
init.type === "BinaryExpression" ||
init.type === "ArrayExpression" ||
init.type === "ArrowFunctionExpression"
) {
value = this.sourceAtPos(init.start, init.end)?.replace(/\n/g, " ");
type = value;
isFunction = init.type === "ArrowFunctionExpression";
if (init.type === "BinaryExpression") {
if (init?.left.type === "Literal" && typeof init?.left.value === "string") {
type = "string";
}
}
} else {
if (init.type === "UnaryExpression") {
value = this.sourceAtPos(init.start, init.end);
type = typeof init.argument?.value;
} else {
value = init.raw;
type = init.value == null ? undefined : typeof init.value;
}
}
}
if (declaration_type === "FunctionDeclaration") {
value = "() => " + this.sourceAtPos(body.start, body.end)?.replace(/\n/g, " ");
type = "() => any";
kind = "function";
isFunction = true;
isFunctionDeclaration = true;
}
if (node.leadingComments) {
const last_comment = node.leadingComments[node.leadingComments.length - 1];
const comment = commentParser(ComponentParser.formatComment(last_comment.value));
const tag = comment[0]?.tags[comment[0]?.tags.length - 1];
if (tag?.tag === "type") type = this.aliasType(tag.type);
description = ComponentParser.assignValue(comment[0]?.description);
}
if (!description && this.typedefs.has(type)) {
description = this.typedefs.get(type)!.description;
}
this.addProp(prop_name, {
name: prop_name,
kind,
description,
type,
value,
isFunction,
isFunctionDeclaration,
constant: kind === "const",
reactive: this.reactive_vars.has(prop_name),
});
}
if (node.type === "Comment") {
let data: string = node?.data?.trim() ?? "";
if (/^@component/.test(data)) {
this.componentComment = data.replace(/^@component/, "");
}
}
if (node.type === "Slot") {
const slot_name = node.attributes.find((attr: any) => attr.name === "name")?.value[0].data;
const slot_props = node.attributes
.filter((attr: { name?: string }) => attr.name !== "name")
.reduce((slot_props: SlotProps, { name, value }: { name: string; value?: any }) => {
let slot_prop_value: SlotPropValue = {
value: undefined,
replace: false,
};
if (value === undefined) return {};
if (value[0]) {
const { type, expression, raw, start, end } = value[0];
if (type === "Text") {
slot_prop_value.value = raw;
} else if (type === "AttributeShorthand") {
slot_prop_value.value = expression.name;
slot_prop_value.replace = true;
}
if (expression) {
if (expression.type === "Literal") {
slot_prop_value.value = expression.value;
} else if (expression.type !== "Identifier") {
if (expression.type === "ObjectExpression" || expression.type === "TemplateLiteral") {
slot_prop_value.value = this.sourceAtPos(start + 1, end - 1);
} else {
slot_prop_value.value = this.sourceAtPos(start, end);
}
}
}
}
return { ...slot_props, [name]: slot_prop_value };
}, {});
const fallback = (node.children as TemplateNode[])
?.map(({ start, end }) => this.sourceAtPos(start, end))
.join("")
.trim();
this.addSlot(slot_name, JSON.stringify(slot_props, null, 2), fallback);
}
if (node.type === "EventHandler" && node.expression == null) {
if (!this.events.has(node.name) && parent !== undefined) {
this.events.set(node.name, {
type: "forwarded",
name: node.name,
element: parent.name,
});
}
}
if (parent?.type === "Element" && node.type === "Binding" && node.name === "this") {
const prop_name = node.expression.name;
const element_name = parent.name;
if (this.bindings.has(prop_name)) {
const existing_bindings = this.bindings.get(prop_name)!;
if (!existing_bindings.elements.includes(element_name)) {
this.bindings.set(prop_name, {
...existing_bindings,
elements: [...existing_bindings.elements, element_name],
});
}
} else {
this.bindings.set(prop_name, {
elements: [element_name],
});
}
}
},
});
if (dispatcher_name !== undefined) {
callees.forEach((callee) => {
if (callee.name === dispatcher_name) {
const event_name = callee.arguments[0]?.value;
const event_detail = callee.arguments[1]?.value;
this.addDispatchedEvent(event_name, event_detail);
}
});
}
return {
props: ComponentParser.mapToArray(this.props).map((prop) => {
if (this.bindings.has(prop.name)) {
return {
...prop,
type:
"null | " +
this.bindings
.get(prop.name)!
.elements.sort()
.map((element) => getElementByTag(element))
.join(" | "),
};
}
return prop;
}),
slots: ComponentParser.mapToArray(this.slots)
.map((slot) => {
try {
const slot_props: SlotProps = JSON.parse(slot.slot_props);
const new_props: string[] = [];
Object.keys(slot_props).forEach((key) => {
if (slot_props[key].replace && slot_props[key].value !== undefined) {
slot_props[key].value = this.props.get(slot_props[key].value!)?.type;
}
if (slot_props[key].value === undefined) slot_props[key].value = "any";
new_props.push(`${key}: ${slot_props[key].value}`);
});
const formatted_slot_props = new_props.length === 0 ? "{}" : "{ " + new_props.join(", ") + " }";
return { ...slot, slot_props: formatted_slot_props };
} catch (e) {
return slot;
}
})
.sort((a, b) => {
if (a.name! < b.name!) return -1;
if (a.name! > b.name) return 1;
return 0;
}),
events: ComponentParser.mapToArray(this.events),
typedefs: ComponentParser.mapToArray(this.typedefs),
rest_props: this.rest_props,
extends: this.extends,
componentComment: this.componentComment,
};
}
}