-
Notifications
You must be signed in to change notification settings - Fork 0
/
esm.mjs
253 lines (235 loc) · 9.27 KB
/
esm.mjs
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
import fs from "fs";
import path from "path";
import url from "url";
import { EventEmitter } from "events";
import { getStack } from "backtracker";
const refreshRegex = /(\?refresh=\d+)/;
function isObject(item) {
if (typeof item !== "object" || item === null || Array.isArray(item)) return false
return (item.constructor?.name === "Object");
}
class Sync {
/**
* @param {{ watchFS?: boolean; persistentWatchers?: boolean; }} [options]
*/
constructor(options) {
/** @type {{ watchFS: boolean; persistentWatchers: boolean; }} */
// @ts-expect-error
this._options = {};
if (options?.watchFS === undefined) this._options.watchFS = true;
else this._options.watchFS = options.watchFS ?? false;
if (options?.persistentWatchers === undefined) this._options.persistentWatchers = true;
else this._options.persistentWatchers = options.persistentWatchers ?? false;
this.events = new EventEmitter();
/**
* @type {Map<string, Array<[EventEmitter, string, (...args: Array<any>) => any]>>}
*/
this._listeners = new Map();
/**
* @type {Map<string, any>}
*/
this._references = new Map();
/**
* @type {Map<string, import("fs").FSWatcher>}
*/
this._watchers = new Map();
/** @type {Set<string>} */
this._needsrefresh = new Set();
/** @type {Map<string, Array<["timeout" | "interval", NodeJS.Timeout]>>} */
this._timers = new Map();
}
/**
* @param {string | Array<string>} id
* @param {string} [_from]
* @returns {any}
*/
require(id, _from) {
throw new Error("The ESM version of this module does not support the require statement");
}
/**
* @param {string | Array<string>} id
* @param {string} [_from]
* @returns {Promise<any>}
*/
async import(id, _from) {
/** @type {string} */
let from;
// @ts-expect-error
from = _from ?? getStack().first().dir;
if (from.startsWith("file://")) from = url.fileURLToPath(from);
from = path.normalize(from);
if (Array.isArray(id)) return Promise.all(id.map(item => this.import(item, from)));
let directory = (!path.isAbsolute(id) ? await Sync.#resolve(path.join(from, id)) : await Sync.#resolve(id));
if (directory.startsWith("file://")) directory = url.fileURLToPath(directory);
directory = path.normalize(directory);
if (this._references.get(directory) && !this._needsrefresh.has(directory)) return this._references.get(directory);
const value = await import(`file://${directory}?refresh=${Date.now()}`); // this busts the internal import cache
if (!isObject(value)) throw new Error(`${directory} does not seem to export an Object and as such, changes made to the file cannot be reflected as the value would be immutable. Importing through HeatSync isn't supported and may be erraneous. Should the export be an Object made through Object.create, make sure that you reference the export.constructor as the Object.constructor as HeatSync checks constuctor names. Exports being Classes will not reload properly`);
this._needsrefresh.delete(directory);
const oldObject = this._references.get(directory);
if (!oldObject) {
this._references.set(directory, value);
let timer = null;
if (this._options.watchFS) {
this._watchers.set(directory, fs.watch(directory, { persistent: this._options.persistentWatchers }, () => {
if (timer) {
clearTimeout(timer);
timer = null;
}
timer = setTimeout(async () => {
this._needsrefresh.add(directory);
this.events.emit(directory);
this.events.emit("any", directory);
const normalized = path.normalize(directory);
const listeners = this._listeners.get(normalized);
if (listeners) {
for (const [target, event, func] of listeners) {
target.removeListener(event, func);
}
}
const timers = this._timers.get(directory)
if (timers) {
for (const [type, timer] of timers) {
if (type === "timeout") clearTimeout(timer)
else clearInterval(timer)
}
}
try {
await this.import(directory);
} catch (e) {
return this.events.emit("error", e);
}
}, 1000); // Only emit and re-require once all changes have finished
}));
}
} else {
for (const key of Object.keys(oldObject)) {
if (value[key] === undefined) delete oldObject[key];
}
if (oldObject.default && value && value.default && isObject(oldObject.default) && isObject(value.default)) {
for (const key of Object.keys(oldObject.default)) {
if (value.default[key] === undefined) delete oldObject.default[key];
}
}
if (oldObject.default && value && value.default && isObject(oldObject.default) && isObject(value.default)) {
if (typeof value.default === "object" && !Array.isArray(value.default)) {
for (const key of Object.keys(value.default)) {
oldObject.default[key] = value.default[key];
}
}
}
for (const key of Object.keys(value)) {
if (key === "default") continue;
oldObject[key] = value[key];
delete value[key] // Allows the old values to get garbage collected when the module is eventually imported again. Not the import itself though
} // Don't use Object.assign because of export default being readonly and no ignore list
}
return oldObject ?? value;
}
/**
* @template {EventEmitter} Target
* @param {Target} target
* @param {Parameters<Target["on"]>[0]} event
* @param {(...args: Array<any>) => any} callback
* @param {"on" | "once"} method
* @returns {Target}
*/
addTemporaryListener(target, event, callback, method = "on") {
if (typeof target?.[method] !== "function") throw new TypeError(`${target?.constructor?.name ?? typeof target} does not include the method "${method}". It may not implement/extend or only partially implements/extends an EventEmitter`);
// @ts-expect-error It's always there, trust!
let first = getStack().first().absolute.replace(refreshRegex, "");
if (first.startsWith("file://")) first = url.fileURLToPath(first);
first = path.normalize(first);
if (!this._listeners.get(first)) this._listeners.set(first, []);
// @ts-expect-error On thread race conditions???
this._listeners.get(first).push([target, event, callback]);
setImmediate(() => target[method](event, callback));
return target;
}
/**
* @template {any[]} TArgs
* @param {(...args: TArgs) => void} callback
* @param {number} [ms]
* @param {...TArgs} args
* @returns {NodeJS.Timeout}
*/
addTemporaryTimeout(callback, ms, ...args) {
// @ts-expect-error
let first = getStack().first().absolute.replace(refreshRegex, "");
if (first.startsWith("file://")) first = url.fileURLToPath(first);
first = path.normalize(first);
if (!this._timers.get(first)) this._timers.set(first, []);
/** @type {NodeJS.Timeout} */
// @ts-expect-error
const timer = setTimeout(callback, ms, ...args);
// @ts-expect-error
this._timers.get(absolute).push(["timeout", timer]);
return timer;
}
/**
* @template {any[]} TArgs
* @param {(...args: TArgs) => void} callback
* @param {number} [ms]
* @param {...TArgs} args
* @returns {NodeJS.Timeout}
*/
addTemporaryInterval(callback, ms, ...args) {
// @ts-expect-error
let first = getStack().first().absolute.replace(refreshRegex, "");
if (first.startsWith("file://")) first = url.fileURLToPath(first);
first = path.normalize(first);
if (!this._timers.get(first)) this._timers.set(first, []);
/** @type {NodeJS.Timeout} */
// @ts-expect-error
const timer = setInterval(callback, ms, ...args);
// @ts-expect-error
this._timers.get(absolute).push(["interval", timer]);
return timer;
}
/**
* @param {string} id
* @param {string} [_from]
* @returns {Promise<any>}
*/
async resync(id, _from) {
/** @type {string} */
let from;
if (typeof id === "string" && !id.startsWith(".")) from = await Sync.#resolve(id);
// @ts-expect-error
else from = _from ?? getStack().first().dir;
if (from.startsWith("file://")) from = url.fileURLToPath(from);
from = path.normalize(from);
if (Array.isArray(id)) return Promise.all(id.map(item => this.resync(item, from)));
let directory = (!path.isAbsolute(id) ? await Sync.#resolve(path.join(from, id)) : await Sync.#resolve(id));
if (directory.startsWith("file://")) directory = url.fileURLToPath(directory);
directory = path.normalize(directory);
this._needsrefresh.add(directory);
return this.import(directory);
}
/**
* @param {string} id
* @returns {Promise<string>}
*/
static async #resolve(id) {
let absolute = path.normalize(id.startsWith("file://") ? url.fileURLToPath(id) : id);
const decon = path.parse(absolute);
if (!decon.ext || decon.ext.length === 0) {
// check if the id is a directory
const isDir = await fs.promises.stat(absolute).then(s => s.isDirectory()).catch(() => false);
if (isDir) {
const dirContents = await fs.promises.readdir(absolute);
if (dirContents.includes("index.mjs")) absolute = path.join(absolute, "index.mjs");
else absolute = path.join(absolute, "index.js");
// Even if it doesn't exist in the directory, the user still needs to know the intent of the resolver
} else {
// read the base dir
const dirContents = await fs.promises.readdir(decon.dir);
if (dirContents.includes(`${decon.name}.mjs`)) absolute = path.join(absolute, `${decon.name}.mjs`);
else absolute = path.join(absolute, `${decon.name}.js`);
}
}
await fs.promises.access(absolute, fs.constants.R_OK);
return absolute;
}
}
export default Sync;