-
Notifications
You must be signed in to change notification settings - Fork 2
/
logged.ts
96 lines (84 loc) · 2.41 KB
/
logged.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
// A decorator that logs all kinds of events.
export function logged(value: any, context: DecoratorContext): any {
const name = String(context.name)
console.group(`${context.kind} decorator on ${name}`)
try {
switch (context.kind) {
case "class":
return class Class extends value {
constructor(...args: any[]) {
console.group(`constructing ${name}`)
try {
super(...args)
} finally {
console.groupEnd()
}
}
}
case "method":
case "getter":
if (typeof value == "function") {
return function (this: any, ...args: any[]) {
console.group(
`${
{
method: "calling",
getter: "getting",
setter: "setting",
}[context.kind]
} ${name}`,
)
try {
return value.call(this, ...args)
} finally {
console.groupEnd()
}
}
} else break
case "setter":
if (typeof value == "function") {
return function (this: any, newValue: any) {
console.group(`setting ${name} to ${newValue}`)
try {
return value.call(this, newValue)
} finally {
console.groupEnd()
}
}
} else break
case "field":
return (initializedValue: any) => {
console.log(`initializing field ${name}`)
return initializedValue
}
case "accessor":
return {
get() {
console.group(`getting ${name}`)
try {
return value.get.call(this)
} finally {
console.groupEnd()
}
},
set(newValue) {
console.group(`setting ${name} to ${String(newValue)}`)
try {
return value.set.call(this, newValue)
} finally {
console.groupEnd()
}
},
init(value) {
console.group(`initializing ${name} to ${String(value)}`)
console.groupEnd()
return value
},
} satisfies ClassAccessorDecoratorResult<any, any>
default:
throw new Error("Unsupported decorator type:" + (context as any).type)
}
} finally {
console.groupEnd()
}
}