-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.js
More file actions
115 lines (95 loc) · 2.21 KB
/
Copy pathindex.js
File metadata and controls
115 lines (95 loc) · 2.21 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
const zones = Object.create(null);
let current;
const asyncHooks = require("async_hooks");
const asyncHook = asyncHooks.createHook({
init(uid) {
zones[uid] = current;
},
before(uid) {
current = zones[uid];
// it appears `init` is not called when using the `cluster` module,
// therefore `zones[uid]` might not exist in `before`
//
// Work-around: set the current zone to the root zone, it's incorrect but it
// allows using root data and create new zones by forking.
//
// see https://github.com/JsCommunity/node-zone/issues/3
if (current === undefined) {
current = root;
}
},
destroy(uid) {
delete zones[uid];
},
});
asyncHook.enable();
class Zone {
constructor(parent, spec) {
if (parent === null) {
// root zone
this._data = Object.create(null);
this._name = "<root>";
this._parent = null;
} else {
const data = (this._data = Object.create(parent.data));
this._parent = parent;
let name;
if (typeof spec === "string") {
name = spec;
} else if (spec != null) {
name = spec.name;
const { properties } = spec;
if (properties) {
for (const key in properties) {
data[key] = properties[key];
}
}
}
this._name = name || `${parent.name} child`;
}
}
get data() {
return this._data;
}
get name() {
return this._name;
}
get parent() {
return this._parent;
}
fork(spec) {
return new Zone(this, spec);
}
run(callback, thisArg, args) {
const previous = current;
try {
current = this;
return callback.apply(thisArg, args);
} finally {
current = previous;
}
}
wrap(callback) {
const zone = this;
return function(...args) {
return zone.run(callback, this, args);
};
}
// minimal zone.js compatibility
get(key) {
return this._data[key];
}
getZoneWith(key) {
if (Object.prototype.hasOwnProperty.call(this._data, key)) {
return this;
}
const parent = this._parent;
return parent && parent.getZoneWith(key);
}
}
const root = (current = new Zone(null));
module.exports = {
get current() {
return current;
},
};