-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathparse-ctors.ts
113 lines (85 loc) · 2.39 KB
/
parse-ctors.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
import { isConstructor, not } from './utils'
type Ctor = Function | null
class Tree {
constructor(
public ctor: Ctor,
public path: string,
public depth: number,
public children: Array<Tree> = []
) {}
}
export const trees: Array<Tree> = []
const visitedScopes = new Set()
function ctorChain(ctor: Function): Array<Ctor> {
const prototype = ctor.prototype
// Proxy
if (prototype === undefined) {
return [ctor]
}
const proto = Object.getPrototypeOf(prototype)
// Object
// Object.create(null)
if (proto === null) {
return [null, ctor]
}
return ctorChain(proto.constructor).concat(ctor)
}
function parse(scope: any, basePath: string, blacklist: Array<RegExp>) {
if (scope === null || scope === undefined) {
return
}
if (visitedScopes.has(scope)) {
return
}
visitedScopes.add(scope)
Object.getOwnPropertyNames(scope)
.filter(k => not(['prototype', 'constructor'].includes(k)))
.forEach(k => {
const x = scope[k]
if (isConstructor(x)) {
let nodes = trees
ctorChain(x).forEach((ctor, depth) => {
const name = ctor === null ? 'null' : ctor.name
const path = basePath + name
if (blacklist.some(b => b.test(path))) {
return
}
let node = nodes.find(node => node.ctor === ctor)
if (node === undefined) {
node = new Tree(ctor, path, depth)
nodes.push(node)
} else if (name === k || depth < node.depth) {
node.path = path
}
nodes = node.children
})
}
parse(x, basePath + k + '.', blacklist)
})
}
export function pruneTree(node: Tree, keys: Array<keyof Tree>) {
keys.forEach(k => {
delete node[k]
})
node.children.forEach(child => {
pruneTree(child, keys)
})
}
export function sortTree(node: Tree) {
node.children.sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0))
node.children.forEach(child => {
sortTree(child)
})
}
export function parseModule(mod: object, blacklist: Array<RegExp>): void
export function parseModule(name: string, mod: object, blacklist: Array<RegExp>): void
export function parseModule(...args: any) {
if (args.length === 2) {
const [mod, blacklist] = args
parse(mod, '', blacklist)
}
if (args.length === 3) {
const [name, mod, blacklist] = args
parse(mod, name + '::', blacklist)
}
}