olum-compiler 0.8.6 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bin/compiler.js CHANGED
@@ -1,4 +1,4 @@
1
- const spawn = require("cross-spawn");
1
+ const spawn = require("../lib/cross-spawn");
2
2
  const path = require("path");
3
3
  const fs = require("fs");
4
4
  const colors = require("../lib/colors");
package/bin/dev.js CHANGED
@@ -2,7 +2,7 @@ const serve = require("./server");
2
2
  const watch = require("./watcher");
3
3
  const compile = require("./compiler");
4
4
  const copySrc = require("./copySrc");
5
- const WebSocket = require("ws");
5
+ const WebSocket = require("../lib/websocket");
6
6
  const path = require("path");
7
7
  const fs = require("fs");
8
8
 
package/bin/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  const path = require("path");
3
- const spawn = require("cross-spawn");
3
+ const spawn = require("../lib/cross-spawn");
4
4
  const script = process.argv[2];
5
5
 
6
6
  if (typeof script !== undefined && ["dev", "build"].includes(script)) {
package/bin/watcher.js CHANGED
@@ -1,4 +1,4 @@
1
- const chokidar = require("chokidar");
1
+ const chokidar = require("../lib/chokidar");
2
2
  const path = require("path");
3
3
  // Resolve against the project root (process.cwd()), same as copySrc.js.
4
4
  // The old "../../src" pointed at node_modules/src, which doesn't exist, so
@@ -0,0 +1,344 @@
1
+ /**
2
+ * chokidar.js — standalone single-file recursive file watcher
3
+ * Minimal replacement for the `chokidar` package, using only node built-ins
4
+ * (fs, path, events). Cross-platform: instead of fs.watch's `recursive` flag
5
+ * (whose support and event detail differ per OS), every directory gets its own
6
+ * non-recursive fs.watch and events trigger a rescan-and-diff of that
7
+ * directory against a stat snapshot — so add/change/unlink detection behaves
8
+ * identically on Linux, macOS and Windows.
9
+ *
10
+ * Covered (same API shape as chokidar@5.0.0):
11
+ * const chokidar = require("./chokidar");
12
+ * const watcher = chokidar.watch(paths, {
13
+ * persistent: true, // keep the process alive (default true)
14
+ * ignoreInitial: false, // suppress add/addDir for the initial scan
15
+ * ignored: regex|fn|array, // paths to skip entirely
16
+ * awaitWriteFinish: { stabilityThreshold, pollIntervall } | true,
17
+ * });
18
+ * watcher.on("add" | "change" | "unlink" | "addDir" | "unlinkDir" | "ready" | "error", ...)
19
+ * watcher.close();
20
+ *
21
+ * Watched roots that don't exist yet (or get deleted) are polled for and
22
+ * picked up when they appear, like chokidar does.
23
+ *
24
+ * KNOWN LIMITATIONS vs the real chokidar (future maintenance):
25
+ *
26
+ * 1. No `usePolling` fallback — NFS / Docker / VM compatibility.
27
+ * fs.watch relies on OS change events (inotify on Linux, FSEvents/kqueue on
28
+ * macOS, ReadDirectoryChangesW on Windows). On filesystems that don't
29
+ * propagate those events — NFS mounts, Docker bind-mounted volumes with a
30
+ * macOS/Windows host, some VM shared folders (VirtualBox vboxsf, older
31
+ * Vagrant/WSL1 setups) — the watcher goes silent: no errors, just no
32
+ * events. Real chokidar covers this with `usePolling: true` (fs.watchFile
33
+ * stat polling). If dev-inside-Docker/NFS ever becomes a use case, add a
34
+ * polling mode here: replace fs.watch per directory with a setInterval
35
+ * that calls _rescan(dir) (the diffing logic already works unchanged);
36
+ * only _watchDir needs the branch.
37
+ *
38
+ * 2. Whole-directory rescan per event burst.
39
+ * On any event we readdir+stat the affected directory instead of stat-ing
40
+ * just the named file like chokidar. Identical behavior, negligible cost
41
+ * for source trees (measured: 305-dir Next.js project ready in ~41ms,
42
+ * 1000-file burst handled 1:1 with chokidar@5), but a single flat
43
+ * directory with tens of thousands of entries would rescan slowly. If that
44
+ * happens, use the filename argument from fs.watch's callback to stat only
45
+ * that entry, falling back to a full rescan when it's null.
46
+ *
47
+ * 3. Linux inotify limits apply (as they do to chokidar).
48
+ * One watch descriptor per directory, capped by
49
+ * /proc/sys/fs/inotify/max_user_watches (typically 8k–128k). Always pass
50
+ * `ignored` for node_modules/.git/build-output dirs on big repos.
51
+ *
52
+ * 4. Not implemented (unused by this project): add()/unwatch()/getWatched(),
53
+ * depth, cwd, alwaysStat, atomic, followSymlinks:false (symlinked dirs are
54
+ * watched, with realpath-based cycle protection), and sub-mtime-resolution
55
+ * edge: a rewrite with identical size landing in the same mtime tick is
56
+ * undetectable by stat diffing (theoretical on ext4/APFS/NTFS — ns mtime).
57
+ */
58
+ "use strict";
59
+
60
+ const fs = require("fs");
61
+ const path = require("path");
62
+ const { EventEmitter } = require("events");
63
+
64
+ const SCAN_DEBOUNCE = 25; // coalesce fs.watch event bursts per directory
65
+ const ROOT_POLL = 1000; // how often to look for a missing watched root
66
+
67
+ function normalizeIgnored(ignored) {
68
+ if (!ignored) return () => false;
69
+ const list = Array.isArray(ignored) ? ignored : [ignored];
70
+ return p =>
71
+ list.some(entry => {
72
+ if (typeof entry === "function") return entry(p);
73
+ if (entry instanceof RegExp) return entry.test(p);
74
+ return p === entry || p.startsWith(entry + path.sep); // plain path prefix
75
+ });
76
+ }
77
+
78
+ class FSWatcher extends EventEmitter {
79
+ constructor(paths, options = {}) {
80
+ super();
81
+
82
+ this._persistent = options.persistent !== false;
83
+ this._ignoreInitial = !!options.ignoreInitial;
84
+ this._ignored = normalizeIgnored(options.ignored);
85
+
86
+ const awf = options.awaitWriteFinish;
87
+ // chokidar defaults: threshold 2000ms, poll 100ms when awaitWriteFinish: true
88
+ this._awf = awf ? { threshold: awf.stabilityThreshold || 2000, poll: awf.pollInterval || 100 } : null;
89
+
90
+ this._roots = (Array.isArray(paths) ? paths : [paths]).map(p => path.resolve(p));
91
+ this._watchers = new Map(); // dir → fs.FSWatcher
92
+ this._snapshots = new Map(); // dir → Map(name → { isDir, mtimeMs, size })
93
+ this._scanTimers = new Map(); // dir → debounce timeout
94
+ this._pending = new Map(); // file → awaitWriteFinish poll state
95
+ this._rootTimers = new Map(); // missing root → poll interval
96
+ this._realPaths = new Set(); // real paths of watched dirs (symlink-cycle guard)
97
+ this._realByDir = new Map(); // dir → its real path, for cleanup
98
+ this._closed = false;
99
+
100
+ process.nextTick(() => {
101
+ if (this._closed) return;
102
+ for (const root of this._roots) this._addRoot(root, true);
103
+ this.emit("ready");
104
+ });
105
+ }
106
+
107
+ // ------------------------------------------------------------ setup
108
+ _addRoot(root, isInitial) {
109
+ let stat;
110
+ try {
111
+ stat = fs.statSync(root);
112
+ } catch (e) {
113
+ this._waitForRoot(root);
114
+ return;
115
+ }
116
+ if (stat.isDirectory()) {
117
+ // chokidar reports the watched root itself, subject to ignoreInitial
118
+ if (!(isInitial && this._ignoreInitial)) this.emit("addDir", root);
119
+ this._watchDir(root, isInitial);
120
+ }
121
+ // single-file roots: watch the parent dir but only report this file
122
+ else this._watchDir(path.dirname(root), isInitial, root);
123
+ }
124
+
125
+ _waitForRoot(root) {
126
+ if (this._closed || this._rootTimers.has(root)) return;
127
+ const timer = setInterval(() => {
128
+ if (fs.existsSync(root)) {
129
+ clearInterval(timer);
130
+ this._rootTimers.delete(root);
131
+ this._addRoot(root, false); // appeared later → its contents are new adds
132
+ }
133
+ }, ROOT_POLL);
134
+ if (!this._persistent && timer.unref) timer.unref();
135
+ this._rootTimers.set(root, timer);
136
+ }
137
+
138
+ _watchDir(dir, isInitial, onlyFile) {
139
+ if (this._closed || this._watchers.has(dir) || this._ignored(dir)) return;
140
+
141
+ // symlink-cycle guard: a link pointing back into the watched tree must not
142
+ // cause infinite recursion — track the real path of every watched dir
143
+ let real;
144
+ try {
145
+ real = fs.realpathSync(dir);
146
+ } catch (e) {
147
+ return;
148
+ }
149
+ if (this._realPaths.has(real)) return;
150
+ this._realPaths.add(real);
151
+ this._realByDir.set(dir, real);
152
+
153
+ let watcher;
154
+ try {
155
+ watcher = fs.watch(dir, { persistent: this._persistent });
156
+ } catch (err) {
157
+ this.emit("error", err);
158
+ return;
159
+ }
160
+ // fs.watch errors (e.g. EPERM on windows when the dir is deleted) are not
161
+ // fatal: the parent directory's rescan tears this watcher down
162
+ watcher.on("error", () => watcher.close());
163
+ watcher.on("change", () => this._scheduleScan(dir));
164
+
165
+ this._watchers.set(dir, watcher);
166
+ this._snapshots.set(dir, new Map());
167
+ if (onlyFile) this._onlyFile = onlyFile;
168
+ this._rescan(dir, isInitial);
169
+ }
170
+
171
+ // ------------------------------------------------------------ scanning
172
+ _scheduleScan(dir) {
173
+ if (this._closed || this._scanTimers.has(dir)) return;
174
+ this._scanTimers.set(
175
+ dir,
176
+ setTimeout(() => {
177
+ this._scanTimers.delete(dir);
178
+ this._rescan(dir, false);
179
+ }, SCAN_DEBOUNCE)
180
+ );
181
+ }
182
+
183
+ _rescan(dir, isInitial) {
184
+ if (this._closed || !this._snapshots.has(dir)) return;
185
+
186
+ let names;
187
+ try {
188
+ names = fs.readdirSync(dir);
189
+ } catch (e) {
190
+ // directory itself vanished
191
+ this._teardownDir(dir, true);
192
+ if (this._roots.includes(dir)) this._waitForRoot(dir);
193
+ return;
194
+ }
195
+
196
+ const old = this._snapshots.get(dir);
197
+ const next = new Map();
198
+
199
+ for (const name of names) {
200
+ const full = path.join(dir, name);
201
+ if (this._ignored(full)) continue;
202
+
203
+ let stat;
204
+ try {
205
+ stat = fs.statSync(full);
206
+ } catch (e) {
207
+ continue; // deleted between readdir and stat
208
+ }
209
+
210
+ const entry = { isDir: stat.isDirectory(), mtimeMs: stat.mtimeMs, size: stat.size };
211
+ next.set(name, entry);
212
+
213
+ const prev = old.get(name);
214
+ const silent = isInitial && this._ignoreInitial;
215
+
216
+ if (!prev) {
217
+ if (entry.isDir) {
218
+ if (!silent) this.emit("addDir", full);
219
+ this._watchDir(full, isInitial); // walks and reports its contents
220
+ } else if (!silent) {
221
+ this._settle(full, "add");
222
+ }
223
+ } else if (prev.isDir !== entry.isDir) {
224
+ // replaced by the other kind: unlink the old, add the new
225
+ if (prev.isDir) this._teardownDir(full, true);
226
+ else this.emit("unlink", full);
227
+ if (entry.isDir) {
228
+ this.emit("addDir", full);
229
+ this._watchDir(full, false);
230
+ } else {
231
+ this._settle(full, "add");
232
+ }
233
+ } else if (!entry.isDir && (prev.mtimeMs !== entry.mtimeMs || prev.size !== entry.size)) {
234
+ this._settle(full, "change");
235
+ }
236
+ }
237
+
238
+ for (const [name, prev] of old) {
239
+ if (next.has(name)) continue;
240
+ const full = path.join(dir, name);
241
+ if (prev.isDir) this._teardownDir(full, true);
242
+ else this._dropFile(full);
243
+ }
244
+
245
+ this._snapshots.set(dir, next);
246
+ }
247
+
248
+ _dropFile(file) {
249
+ const pending = this._pending.get(file);
250
+ if (pending) {
251
+ clearInterval(pending.timer);
252
+ this._pending.delete(file);
253
+ // a file that vanished while its "add" was still stabilizing was never
254
+ // reported, so there is nothing to unlink
255
+ if (pending.event === "add") return;
256
+ }
257
+ this.emit("unlink", file);
258
+ }
259
+
260
+ _teardownDir(dir, emitEvents) {
261
+ const watcher = this._watchers.get(dir);
262
+ if (watcher) watcher.close();
263
+ this._watchers.delete(dir);
264
+
265
+ const real = this._realByDir.get(dir);
266
+ if (real !== undefined) {
267
+ this._realPaths.delete(real);
268
+ this._realByDir.delete(dir);
269
+ }
270
+
271
+ const timer = this._scanTimers.get(dir);
272
+ if (timer) clearTimeout(timer);
273
+ this._scanTimers.delete(dir);
274
+
275
+ const snapshot = this._snapshots.get(dir);
276
+ this._snapshots.delete(dir);
277
+ if (!snapshot) return;
278
+
279
+ for (const [name, entry] of snapshot) {
280
+ const full = path.join(dir, name);
281
+ if (entry.isDir) this._teardownDir(full, emitEvents);
282
+ else if (emitEvents) this._dropFile(full);
283
+ }
284
+ if (emitEvents) this.emit("unlinkDir", dir);
285
+ }
286
+
287
+ // ------------------------------------------------- awaitWriteFinish
288
+ _settle(file, event) {
289
+ if (this._onlyFile && file !== this._onlyFile) return; // single-file root filter
290
+
291
+ if (!this._awf) return this.emit(event, file);
292
+
293
+ // an event already stabilizing keeps its original type: more writes while
294
+ // an "add" settles must still surface as a single "add", not a "change"
295
+ const existing = this._pending.get(file);
296
+ if (existing) {
297
+ existing.stableSince = Date.now();
298
+ return;
299
+ }
300
+
301
+ const state = { event, stableSince: Date.now(), mtimeMs: -1, size: -1, timer: null };
302
+ state.timer = setInterval(() => {
303
+ let stat;
304
+ try {
305
+ stat = fs.statSync(file);
306
+ } catch (e) {
307
+ clearInterval(state.timer); // vanished mid-write; unlink comes from the dir rescan
308
+ this._pending.delete(file);
309
+ return;
310
+ }
311
+ if (stat.mtimeMs !== state.mtimeMs || stat.size !== state.size) {
312
+ state.mtimeMs = stat.mtimeMs;
313
+ state.size = stat.size;
314
+ state.stableSince = Date.now();
315
+ return;
316
+ }
317
+ if (Date.now() - state.stableSince >= this._awf.threshold) {
318
+ clearInterval(state.timer);
319
+ this._pending.delete(file);
320
+ this.emit(state.event, file);
321
+ }
322
+ }, this._awf.poll);
323
+ this._pending.set(file, state);
324
+ }
325
+
326
+ // ------------------------------------------------------------ teardown
327
+ close() {
328
+ this._closed = true;
329
+ for (const watcher of this._watchers.values()) watcher.close();
330
+ for (const timer of this._scanTimers.values()) clearTimeout(timer);
331
+ for (const state of this._pending.values()) clearInterval(state.timer);
332
+ for (const timer of this._rootTimers.values()) clearInterval(timer);
333
+ this._watchers.clear();
334
+ this._scanTimers.clear();
335
+ this._pending.clear();
336
+ this._rootTimers.clear();
337
+ this._snapshots.clear();
338
+ this._realPaths.clear();
339
+ this._realByDir.clear();
340
+ return Promise.resolve();
341
+ }
342
+ }
343
+
344
+ module.exports = { watch: (paths, options) => new FSWatcher(paths, options), FSWatcher };
@@ -0,0 +1,318 @@
1
+ /**
2
+ * spawn.js — standalone single-file port of cross-spawn@7.0.6 (MIT)
3
+ * with its dependencies inlined: which@2.0.2, isexe@2.0.0, path-key@3.1.1,
4
+ * shebang-command@2.0.0, shebang-regex@3.0.0 (all MIT).
5
+ * Uses only node built-ins (child_process, fs, path).
6
+ *
7
+ * API (same as cross-spawn):
8
+ * spawn(command, [args], [options]) → ChildProcess
9
+ * spawn.sync(command, [args], [options]) → SpawnSyncReturns
10
+ */
11
+ "use strict";
12
+
13
+ const cp = require("child_process");
14
+ const fs = require("fs");
15
+ const path = require("path");
16
+
17
+ const isWin = process.platform === "win32";
18
+ // `which`/`isexe` treat cygwin/msys shells as windows too
19
+ const isWindowsEnv = isWin || process.env.OSTYPE === "cygwin" || process.env.OSTYPE === "msys";
20
+
21
+ // ---------------------------------------------------------------- path-key
22
+ function pathKey(options = {}) {
23
+ const environment = options.env || process.env;
24
+ const platform = options.platform || process.platform;
25
+ if (platform !== "win32") return "PATH";
26
+ return Object.keys(environment).reverse().find(key => key.toUpperCase() === "PATH") || "Path";
27
+ }
28
+
29
+ // ------------------------------------------------------------------- isexe
30
+ // windows flavor: a file is executable if its extension is in PATHEXT
31
+ function checkPathExt(file, options) {
32
+ let pathext = options.pathExt !== undefined ? options.pathExt : process.env.PATHEXT;
33
+ if (!pathext) return true;
34
+ pathext = pathext.split(";");
35
+ if (pathext.indexOf("") !== -1) return true;
36
+ for (let i = 0; i < pathext.length; i++) {
37
+ const p = pathext[i].toLowerCase();
38
+ if (p && file.substr(-p.length).toLowerCase() === p) return true;
39
+ }
40
+ return false;
41
+ }
42
+
43
+ function isexeWindows(file, options) {
44
+ const stat = fs.statSync(file);
45
+ if (!stat.isSymbolicLink() && !stat.isFile()) return false;
46
+ return checkPathExt(file, options);
47
+ }
48
+
49
+ function isexePosix(file) {
50
+ const stat = fs.statSync(file);
51
+ if (!stat.isFile()) return false;
52
+ const mod = stat.mode;
53
+ const uid = stat.uid;
54
+ const gid = stat.gid;
55
+ const myUid = process.getuid && process.getuid();
56
+ const myGid = process.getgid && process.getgid();
57
+ const u = parseInt("100", 8);
58
+ const g = parseInt("010", 8);
59
+ const o = parseInt("001", 8);
60
+ const ug = u | g;
61
+ return (mod & o) || (mod & g && gid === myGid) || (mod & u && uid === myUid) || (mod & ug && myUid === 0);
62
+ }
63
+
64
+ function isexeSync(file, options) {
65
+ return isWindowsEnv ? isexeWindows(file, options) : isexePosix(file);
66
+ }
67
+
68
+ // ------------------------------------------------------------------- which
69
+ function getPathInfo(cmd, opt) {
70
+ const colon = opt.colon || (isWindowsEnv ? ";" : ":");
71
+
72
+ // if cmd has a slash, don't search PATH — check the file itself
73
+ const pathEnv = cmd.match(/\//) || (isWindowsEnv && cmd.match(/\\/))
74
+ ? [""]
75
+ : [
76
+ // windows always checks the cwd first
77
+ ...(isWindowsEnv ? [process.cwd()] : []),
78
+ ...(opt.path || process.env.PATH || "").split(colon),
79
+ ];
80
+ const pathExtExe = isWindowsEnv ? opt.pathExt || process.env.PATHEXT || ".EXE;.CMD;.BAT;.COM" : "";
81
+ const pathExt = isWindowsEnv ? pathExtExe.split(colon) : [""];
82
+
83
+ if (isWindowsEnv) {
84
+ if (cmd.indexOf(".") !== -1 && pathExt[0] !== "") pathExt.unshift("");
85
+ }
86
+
87
+ return { pathEnv, pathExt, pathExtExe };
88
+ }
89
+
90
+ function whichSync(cmd, opt) {
91
+ opt = opt || {};
92
+ const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt);
93
+
94
+ for (let i = 0; i < pathEnv.length; i++) {
95
+ const ppRaw = pathEnv[i];
96
+ const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw;
97
+
98
+ const pCmd = path.join(pathPart, cmd);
99
+ const p = !pathPart && /^\.[\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd : pCmd;
100
+
101
+ for (let j = 0; j < pathExt.length; j++) {
102
+ const cur = p + pathExt[j];
103
+ try {
104
+ if (isexeSync(cur, { pathExt: pathExtExe })) return cur;
105
+ } catch (ex) { /* Empty */ }
106
+ }
107
+ }
108
+
109
+ if (opt.nothrow) return null;
110
+ throw Object.assign(new Error("not found: " + cmd), { code: "ENOENT" });
111
+ }
112
+
113
+ // -------------------------------------------------- cross-spawn/lib/util/*
114
+ function resolveCommandAttempt(parsed, withoutPathExt) {
115
+ const env = parsed.options.env || process.env;
116
+ const cwd = process.cwd();
117
+ const hasCustomCwd = parsed.options.cwd != null;
118
+ // worker threads do not have process.chdir()
119
+ const shouldSwitchCwd = hasCustomCwd && process.chdir !== undefined && !process.chdir.disabled;
120
+
121
+ // `which` stats against the process cwd, so temporarily switch to the custom one
122
+ if (shouldSwitchCwd) {
123
+ try {
124
+ process.chdir(parsed.options.cwd);
125
+ } catch (err) { /* Empty */ }
126
+ }
127
+
128
+ let resolved;
129
+
130
+ try {
131
+ resolved = whichSync(parsed.command, {
132
+ path: env[pathKey({ env })],
133
+ pathExt: withoutPathExt ? path.delimiter : undefined,
134
+ });
135
+ } catch (e) { /* Empty */ } finally {
136
+ if (shouldSwitchCwd) process.chdir(cwd);
137
+ }
138
+
139
+ // ensure an absolute path is returned (resolved against the custom cwd if any)
140
+ if (resolved) resolved = path.resolve(hasCustomCwd ? parsed.options.cwd : "", resolved);
141
+
142
+ return resolved;
143
+ }
144
+
145
+ function resolveCommand(parsed) {
146
+ return resolveCommandAttempt(parsed) || resolveCommandAttempt(parsed, true);
147
+ }
148
+
149
+ // shebang-command: "#!/usr/bin/env node" → "node", "#!/usr/bin/node -x" → "node -x"
150
+ function shebangCommand(string = "") {
151
+ const match = string.match(/^#!(.*)/);
152
+ if (!match) return null;
153
+
154
+ const [shebangPath, argument] = match[0].replace(/#! ?/, "").split(" ");
155
+ const binary = shebangPath.split("/").pop();
156
+
157
+ if (binary === "env") return argument;
158
+ return argument ? `${binary} ${argument}` : binary;
159
+ }
160
+
161
+ function readShebang(command) {
162
+ // read the first 150 bytes of the file
163
+ const size = 150;
164
+ const buffer = Buffer.alloc(size);
165
+
166
+ let fd;
167
+ try {
168
+ fd = fs.openSync(command, "r");
169
+ fs.readSync(fd, buffer, 0, size, 0);
170
+ fs.closeSync(fd);
171
+ } catch (e) { /* Empty */ }
172
+
173
+ return shebangCommand(buffer.toString());
174
+ }
175
+
176
+ // see http://www.robvanderwoude.com/escapechars.php
177
+ const metaCharsRegExp = /([()\][%!^"`<>&|;, *?])/g;
178
+
179
+ function escapeCommand(arg) {
180
+ return arg.replace(metaCharsRegExp, "^$1");
181
+ }
182
+
183
+ function escapeArgument(arg, doubleEscapeMetaChars) {
184
+ arg = `${arg}`;
185
+
186
+ // algorithm based on https://qntm.org/cmd, altered to avoid regex backtracking
187
+ // sequence of backslashes followed by a double quote: double the backslashes, escape the quote
188
+ arg = arg.replace(/(?=(\\+?)?)\1"/g, '$1$1\\"');
189
+ // sequence of backslashes at the end (a double quote follows once wrapped): double them
190
+ arg = arg.replace(/(?=(\\+?)?)\1$/, "$1$1");
191
+
192
+ // quote the whole thing, then escape cmd.exe meta chars
193
+ arg = `"${arg}"`;
194
+ arg = arg.replace(metaCharsRegExp, "^$1");
195
+
196
+ // cmd-shims are re-parsed by a second cmd.exe, so escape twice
197
+ if (doubleEscapeMetaChars) arg = arg.replace(metaCharsRegExp, "^$1");
198
+
199
+ return arg;
200
+ }
201
+
202
+ // --------------------------------------------------- cross-spawn/lib/parse
203
+ const isExecutableRegExp = /\.(?:com|exe)$/i;
204
+ const isCmdShimRegExp = /node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;
205
+
206
+ function detectShebang(parsed) {
207
+ parsed.file = resolveCommand(parsed);
208
+
209
+ const shebang = parsed.file && readShebang(parsed.file);
210
+
211
+ if (shebang) {
212
+ parsed.args.unshift(parsed.file);
213
+ parsed.command = shebang;
214
+ return resolveCommand(parsed);
215
+ }
216
+
217
+ return parsed.file;
218
+ }
219
+
220
+ function parseNonShell(parsed) {
221
+ if (!isWin) return parsed;
222
+
223
+ const commandFile = detectShebang(parsed);
224
+
225
+ // no shell needed if the command resolved to a real executable (.com/.exe)
226
+ const needsShell = !isExecutableRegExp.test(commandFile);
227
+
228
+ if (parsed.options.forceShell || needsShell) {
229
+ // cmd-shims in node_modules/.bin invoke a nested cmd.exe, requiring double escaping
230
+ const needsDoubleEscapeMetaChars = isCmdShimRegExp.test(commandFile);
231
+
232
+ // normalize posix paths (foo/bar → foo\bar) or cmd.exe fails with ENOENT
233
+ parsed.command = path.normalize(parsed.command);
234
+
235
+ parsed.command = escapeCommand(parsed.command);
236
+ parsed.args = parsed.args.map(arg => escapeArgument(arg, needsDoubleEscapeMetaChars));
237
+
238
+ const shellCommand = [parsed.command].concat(parsed.args).join(" ");
239
+
240
+ parsed.args = ["/d", "/s", "/c", `"${shellCommand}"`];
241
+ parsed.command = process.env.comspec || "cmd.exe";
242
+ parsed.options.windowsVerbatimArguments = true; // args are already escaped
243
+ }
244
+
245
+ return parsed;
246
+ }
247
+
248
+ function parse(command, args, options) {
249
+ // normalize arguments, similar to nodejs
250
+ if (args && !Array.isArray(args)) {
251
+ options = args;
252
+ args = null;
253
+ }
254
+
255
+ args = args ? args.slice(0) : [];
256
+ options = Object.assign({}, options);
257
+
258
+ const parsed = {
259
+ command,
260
+ args,
261
+ options,
262
+ file: undefined,
263
+ original: { command, args },
264
+ };
265
+
266
+ return options.shell ? parsed : parseNonShell(parsed);
267
+ }
268
+
269
+ // -------------------------------------------------- cross-spawn/lib/enoent
270
+ function notFoundError(original, syscall) {
271
+ return Object.assign(new Error(`${syscall} ${original.command} ENOENT`), {
272
+ code: "ENOENT",
273
+ errno: "ENOENT",
274
+ syscall: `${syscall} ${original.command}`,
275
+ path: original.command,
276
+ spawnargs: original.args,
277
+ });
278
+ }
279
+
280
+ // on windows a missing command exits cmd.exe with status 1 instead of erroring;
281
+ // convert that into the ENOENT error posix would have produced
282
+ function verifyENOENT(status, parsed, syscall) {
283
+ if (isWin && status === 1 && !parsed.file) return notFoundError(parsed.original, syscall);
284
+ return null;
285
+ }
286
+
287
+ function hookChildProcess(child, parsed) {
288
+ if (!isWin) return;
289
+
290
+ const originalEmit = child.emit;
291
+ child.emit = function (name, arg1) {
292
+ if (name === "exit") {
293
+ const err = verifyENOENT(arg1, parsed, "spawn");
294
+ if (err) return originalEmit.call(child, "error", err);
295
+ }
296
+ return originalEmit.apply(child, arguments);
297
+ };
298
+ }
299
+
300
+ // ------------------------------------------------------- cross-spawn/index
301
+ function spawn(command, args, options) {
302
+ const parsed = parse(command, args, options);
303
+ const spawned = cp.spawn(parsed.command, parsed.args, parsed.options);
304
+ hookChildProcess(spawned, parsed);
305
+ return spawned;
306
+ }
307
+
308
+ function spawnSync(command, args, options) {
309
+ const parsed = parse(command, args, options);
310
+ const result = cp.spawnSync(parsed.command, parsed.args, parsed.options);
311
+ result.error = result.error || verifyENOENT(result.status, parsed, "spawnSync");
312
+ return result;
313
+ }
314
+
315
+ module.exports = spawn;
316
+ module.exports.spawn = spawn;
317
+ module.exports.sync = spawnSync;
318
+ module.exports._parse = parse;
package/lib/getImports.js CHANGED
@@ -1,9 +1,9 @@
1
- const esprima = require("esprima");
1
+ const acorn = require("acorn");
2
2
  const { isFullArr } = require("./helpers");
3
3
  // FYI: it ignores the comments by default beacuse it's based on lexial environment not based on regex
4
4
  function getImports(str) {
5
5
  let finalImports = [];
6
- let arr = esprima.parse(str, { sourceType: "module" }).body;
6
+ let arr = acorn.parse(str, { ecmaVersion: "latest", sourceType: "module" }).body;
7
7
  arr.forEach((obj) => {
8
8
  if (obj.type === "ImportDeclaration") {
9
9
  if (obj.specifiers) {
package/lib/helpers.js CHANGED
@@ -16,7 +16,7 @@ const hasForwardSlash = (paths) => paths.find((item) => /\//g.test(item));
16
16
  const hasSlash = (paths) => paths.find((item) => /\//g.test(item) || /\\/g.test(item));
17
17
  const stringToBase64 = (str) => Buffer.from(str).toString('base64');
18
18
  const base64ToString = (base64) => Buffer.from(base64, 'base64').toString('ascii');
19
- const esprima = require("esprima");
19
+ const acorn = require("acorn");
20
20
 
21
21
  function isUpper(char) {
22
22
  const upperChar = char.toUpperCase();
@@ -372,8 +372,8 @@ function createScopeHandler({ stateProps, hasState, propsTobeExcluded, jsAttrs:
372
372
 
373
373
  // get methods names
374
374
  function getGlobalMethods(str) {
375
- return esprima
376
- .parse(str, { sourceType: "module" })
375
+ return acorn
376
+ .parse(str, { ecmaVersion: "latest", sourceType: "module" })
377
377
  .body.map((obj) => {
378
378
  if (obj.type === "FunctionDeclaration") return obj.id.name;
379
379
  if (
@@ -395,8 +395,8 @@ function getGlobalMethods(str) {
395
395
 
396
396
  // get props names
397
397
  function getGlobalProps(str) {
398
- return esprima
399
- .parse(str, { sourceType: "module" })
398
+ return acorn
399
+ .parse(str, { ecmaVersion: "latest", sourceType: "module" })
400
400
  .body.map((obj) => {
401
401
  if (
402
402
  obj.type === "VariableDeclaration" &&
@@ -663,7 +663,6 @@ ${routes
663
663
  ];`;
664
664
  }
665
665
 
666
- // todo: move it to olum-router and bind it from there to window
667
666
  const routerParamsParser = `<script>
668
667
  /**
669
668
  * Extract route params from a file path and pathname.
@@ -0,0 +1,213 @@
1
+ /**
2
+ * magic-string.js — standalone single-file source map generator
3
+ * Minimal replacement for the `magic-string` package (v0.30.21), using only
4
+ * node built-ins. This project (lib/sourcemap.js) only ever builds an
5
+ * IDENTITY map — `new MagicString(str)` with zero edits, then
6
+ * `generateMap({ source, file, includeContent })` — so that surface is ported
7
+ * faithfully (byte-identical output, including the VLQ `mappings`, JSON key
8
+ * order and `toString()`/`toUrl()`):
9
+ *
10
+ * const MagicString = require("./magic-string");
11
+ * const map = new MagicString(code).generateMap({ source, file, includeContent, hires });
12
+ * map.mappings / map.toString() / map.toUrl()
13
+ *
14
+ * Supported: generateMap / generateDecodedMap with options
15
+ * `source`, `file`, `includeContent`, `hires` (true | "boundary" | falsy).
16
+ *
17
+ * KNOWN LIMITATIONS vs the real magic-string (future maintenance):
18
+ * The string EDITING api (overwrite, update, appendLeft/Right, prepend,
19
+ * append, remove, move, indent, trim, slice, clone, addSourcemapLocation,
20
+ * Bundle, ...) is NOT implemented — those methods throw with a clear message
21
+ * instead of failing silently. If the compiler ever needs to transform code
22
+ * while tracking mappings (e.g. the sourcemap.js TODO about mapping html
23
+ * above the script tag), either extend this file's char-walk in
24
+ * generateDecodedMap to consume an edit list, or reinstall the real package.
25
+ */
26
+ "use strict";
27
+
28
+ // ------------------------------------------------ base64 VLQ (sourcemap-codec)
29
+ const BASE64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
30
+
31
+ function encodeVlq(num) {
32
+ num = num < 0 ? (-num << 1) | 1 : num << 1;
33
+ let out = "";
34
+ do {
35
+ let digit = num & 31;
36
+ num >>>= 5;
37
+ if (num > 0) digit |= 32; // continuation bit
38
+ out += BASE64[digit];
39
+ } while (num > 0);
40
+ return out;
41
+ }
42
+
43
+ // encode decoded mappings ([[ [genCol, srcIdx, srcLine, srcCol, name?], ...], ...])
44
+ // into the standard delta-encoded VLQ string: fields are relative to the
45
+ // previous segment; generated column resets per line, the rest carry over
46
+ function encodeMappings(decoded) {
47
+ let sourceIndex = 0;
48
+ let sourceLine = 0;
49
+ let sourceColumn = 0;
50
+ let nameIndex = 0;
51
+
52
+ return decoded
53
+ .map(line => {
54
+ let genColumn = 0;
55
+ return line
56
+ .map(segment => {
57
+ let out = encodeVlq(segment[0] - genColumn);
58
+ genColumn = segment[0];
59
+ if (segment.length > 1) {
60
+ out += encodeVlq(segment[1] - sourceIndex) + encodeVlq(segment[2] - sourceLine) + encodeVlq(segment[3] - sourceColumn);
61
+ sourceIndex = segment[1];
62
+ sourceLine = segment[2];
63
+ sourceColumn = segment[3];
64
+ }
65
+ if (segment.length === 5) {
66
+ out += encodeVlq(segment[4] - nameIndex);
67
+ nameIndex = segment[4];
68
+ }
69
+ return out;
70
+ })
71
+ .join(",");
72
+ })
73
+ .join(";");
74
+ }
75
+
76
+ // path of `to` relative to `from`'s directory (magic-string's own helper)
77
+ function getRelativePath(from, to) {
78
+ const fromParts = from.split(/[/\\]/);
79
+ const toParts = to.split(/[/\\]/);
80
+
81
+ fromParts.pop(); // get dirname
82
+
83
+ while (fromParts[0] === toParts[0]) {
84
+ fromParts.shift();
85
+ toParts.shift();
86
+ }
87
+
88
+ if (fromParts.length) {
89
+ let i = fromParts.length;
90
+ while (i--) fromParts[i] = "..";
91
+ }
92
+
93
+ return fromParts.concat(toParts).join("/");
94
+ }
95
+
96
+ // --------------------------------------------------------------- SourceMap
97
+ class SourceMap {
98
+ constructor(properties) {
99
+ this.version = 3;
100
+ this.file = properties.file;
101
+ this.sources = properties.sources;
102
+ this.sourcesContent = properties.sourcesContent;
103
+ this.names = properties.names;
104
+ this.mappings = encodeMappings(properties.mappings);
105
+ }
106
+
107
+ toString() {
108
+ return JSON.stringify(this); // undefined keys (file, sourcesContent) drop out
109
+ }
110
+
111
+ toUrl() {
112
+ return "data:application/json;charset=utf-8;base64," + Buffer.from(this.toString(), "utf-8").toString("base64");
113
+ }
114
+ }
115
+
116
+ // -------------------------------------------------------------- MagicString
117
+ const wordRegex = /\w/;
118
+
119
+ class MagicString {
120
+ constructor(string, options = {}) {
121
+ this.original = string;
122
+ this.filename = options.filename;
123
+ }
124
+
125
+ toString() {
126
+ return this.original;
127
+ }
128
+
129
+ get length() {
130
+ return this.original.length;
131
+ }
132
+
133
+ // identity mapping: walk the original char by char, mirroring magic-string's
134
+ // Mappings.addUneditedChunk — a segment at the first char of every line
135
+ // (every char for hires: true, word boundaries for hires: "boundary");
136
+ // lines with no characters get no segment
137
+ generateDecodedMap(options = {}) {
138
+ const hires = options.hires;
139
+ const mappings = [];
140
+ let line = [];
141
+ let genColumn = 0;
142
+ let sourceLine = 0;
143
+ let sourceColumn = 0;
144
+ let first = true;
145
+ let inBoundary = false;
146
+
147
+ for (let i = 0; i < this.original.length; i++) {
148
+ if (this.original[i] === "\n") {
149
+ mappings.push(line);
150
+ line = [];
151
+ genColumn = 0;
152
+ sourceLine += 1;
153
+ sourceColumn = 0;
154
+ first = true;
155
+ inBoundary = false;
156
+ } else {
157
+ if (hires || first) {
158
+ const segment = [genColumn, 0, sourceLine, sourceColumn];
159
+ if (hires === "boundary") {
160
+ // one segment per word, plus one for every non-word char
161
+ if (wordRegex.test(this.original[i])) {
162
+ if (!inBoundary) {
163
+ line.push(segment);
164
+ inBoundary = true;
165
+ }
166
+ } else {
167
+ line.push(segment);
168
+ inBoundary = false;
169
+ }
170
+ } else {
171
+ line.push(segment);
172
+ }
173
+ }
174
+ sourceColumn += 1;
175
+ genColumn += 1;
176
+ first = false;
177
+ }
178
+ }
179
+ mappings.push(line);
180
+
181
+ return {
182
+ file: options.file ? options.file.split(/[/\\]/).pop() : undefined,
183
+ sources: [options.source ? getRelativePath(options.file || "", options.source) : options.file || ""],
184
+ sourcesContent: options.includeContent ? [this.original] : undefined,
185
+ names: [],
186
+ mappings,
187
+ };
188
+ }
189
+
190
+ generateMap(options) {
191
+ return new SourceMap(this.generateDecodedMap(options));
192
+ }
193
+ }
194
+
195
+ // editing api is intentionally absent — fail loudly, not silently
196
+ for (const method of [
197
+ "addSourcemapLocation", "append", "appendLeft", "appendRight", "clone", "indent",
198
+ "insertLeft", "insertRight", "move", "overwrite", "prepend", "prependLeft",
199
+ "prependRight", "remove", "replace", "replaceAll", "reset", "slice", "snip",
200
+ "trim", "trimEnd", "trimStart", "trimLines", "update",
201
+ ]) {
202
+ MagicString.prototype[method] = function () {
203
+ throw new Error(
204
+ `MagicString#${method}() is not implemented in the standalone lib/magic-string.js — ` +
205
+ "only identity source map generation (generateMap) is supported. " +
206
+ "See the header comment for how to extend it, or reinstall the real magic-string package."
207
+ );
208
+ };
209
+ }
210
+
211
+ module.exports = MagicString;
212
+ module.exports.default = MagicString;
213
+ module.exports.SourceMap = SourceMap;
package/lib/sourcemap.js CHANGED
@@ -1,5 +1,5 @@
1
1
  // todo support mapping for html (stuff above script tag)
2
- const MagicString = require('magic-string');
2
+ const MagicString = require('./magic-string');
3
3
  const { stringToBase64 } = require("./helpers");
4
4
  const path = require("path");
5
5
 
@@ -0,0 +1,347 @@
1
+ /**
2
+ * websocket.js — standalone single-file WebSocket server (RFC 6455)
3
+ * Minimal replacement for the `ws` package's server side, using only node
4
+ * built-ins (http, crypto, events). Cross-platform by construction.
5
+ *
6
+ * Covered (same API shape as ws@8.21.0):
7
+ * const WebSocket = require("./websocket");
8
+ * const wss = new WebSocket.Server({ port }); // or { server } / { noServer: true }
9
+ * wss.on("listening" | "connection" | "error" | "close" | "headers", ...)
10
+ * ws.send(data, [cb]) / ws.ping() / ws.close(code, reason) / ws.terminate()
11
+ * ws.on("message" | "close" | "error" | "ping" | "pong", ...)
12
+ *
13
+ * Not included: the client-side WebSocket(url) constructor (browsers provide
14
+ * their own) and the permessage-deflate extension (never negotiated, so
15
+ * clients transparently fall back to uncompressed frames per the RFC).
16
+ */
17
+ "use strict";
18
+
19
+ const crypto = require("crypto");
20
+ const http = require("http");
21
+ const { EventEmitter } = require("events");
22
+
23
+ const GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; // fixed magic value from RFC 6455 §1.3
24
+ const EMPTY = Buffer.alloc(0);
25
+
26
+ const CONNECTING = 0;
27
+ const OPEN = 1;
28
+ const CLOSING = 2;
29
+ const CLOSED = 3;
30
+
31
+ // build one server→client frame: FIN set, no mask (RFC 6455 §5.1: servers must not mask)
32
+ function encodeFrame(opcode, payload) {
33
+ const len = payload.length;
34
+ let header;
35
+
36
+ if (len < 126) {
37
+ header = Buffer.allocUnsafe(2);
38
+ header[1] = len;
39
+ } else if (len < 65536) {
40
+ header = Buffer.allocUnsafe(4);
41
+ header[1] = 126;
42
+ header.writeUInt16BE(len, 2);
43
+ } else {
44
+ header = Buffer.allocUnsafe(10);
45
+ header[1] = 127;
46
+ header.writeUInt32BE(Math.floor(len / 2 ** 32), 2);
47
+ header.writeUInt32BE(len >>> 0, 6);
48
+ }
49
+
50
+ header[0] = 0x80 | opcode; // FIN + opcode
51
+ return Buffer.concat([header, payload]);
52
+ }
53
+
54
+ function toBuffer(data) {
55
+ if (Buffer.isBuffer(data)) return data;
56
+ if (ArrayBuffer.isView(data)) return Buffer.from(data.buffer, data.byteOffset, data.byteLength);
57
+ if (data instanceof ArrayBuffer) return Buffer.from(data);
58
+ return Buffer.from(String(data));
59
+ }
60
+
61
+ class WebSocket extends EventEmitter {
62
+ constructor(socket) {
63
+ super();
64
+
65
+ this._socket = socket;
66
+ this._buffer = EMPTY;
67
+ this._fragments = [];
68
+ this._fragmentOpcode = 0;
69
+ this._closeSent = false;
70
+ this._closeReceived = false;
71
+ this._closeCode = 1006; // abnormal closure unless a close frame says otherwise
72
+ this._closeReason = EMPTY;
73
+ this.readyState = OPEN;
74
+
75
+ socket.setNoDelay(true);
76
+ socket.on("data", chunk => this._parse(chunk));
77
+ // upgraded sockets are half-open: when the peer stops sending without a
78
+ // close frame, end our side too so the tcp socket can actually close
79
+ socket.on("end", () => {
80
+ this.readyState = CLOSING;
81
+ socket.end();
82
+ });
83
+ socket.on("error", err => {
84
+ this.emit("error", err);
85
+ socket.destroy();
86
+ });
87
+ socket.on("close", () => {
88
+ this.readyState = CLOSED;
89
+ this.emit("close", this._closeCode, this._closeReason);
90
+ });
91
+ }
92
+
93
+ // ------------------------------------------------------------ outgoing
94
+ send(data, options, cb) {
95
+ if (typeof options === "function") {
96
+ cb = options;
97
+ options = {};
98
+ }
99
+
100
+ if (this.readyState !== OPEN) {
101
+ // match ws: sending on a closed socket is a no-op unless a callback wants the error
102
+ if (cb) {
103
+ const err = new Error("WebSocket is not open: readyState " + this.readyState);
104
+ process.nextTick(cb, err);
105
+ }
106
+ return;
107
+ }
108
+
109
+ const isBinary = typeof data !== "string";
110
+ this._socket.write(encodeFrame(isBinary ? 0x2 : 0x1, toBuffer(data)), cb);
111
+ }
112
+
113
+ ping(data) {
114
+ if (this.readyState === OPEN) this._socket.write(encodeFrame(0x9, toBuffer(data == null ? EMPTY : data)));
115
+ }
116
+
117
+ pong(data) {
118
+ if (this.readyState === OPEN) this._socket.write(encodeFrame(0xa, toBuffer(data == null ? EMPTY : data)));
119
+ }
120
+
121
+ close(code, reason) {
122
+ if (this.readyState !== OPEN && this.readyState !== CLOSING) return;
123
+ this._sendClose(code === undefined ? 1000 : code, reason == null ? EMPTY : toBuffer(reason));
124
+ // if the client never answers with its own close frame, force-drop the tcp socket
125
+ const timer = setTimeout(() => this._socket.destroy(), 30000);
126
+ if (timer.unref) timer.unref();
127
+ }
128
+
129
+ terminate() {
130
+ this._socket.destroy();
131
+ }
132
+
133
+ _sendClose(code, reason) {
134
+ if (this._closeSent) return;
135
+ this._closeSent = true;
136
+ this.readyState = CLOSING;
137
+
138
+ let payload = EMPTY;
139
+ if (code !== undefined) {
140
+ payload = Buffer.allocUnsafe(2 + reason.length);
141
+ payload.writeUInt16BE(code, 0);
142
+ reason.copy(payload, 2);
143
+ }
144
+ this._socket.write(encodeFrame(0x8, payload));
145
+ // close handshake complete → shut down the tcp stream
146
+ if (this._closeReceived) this._socket.end();
147
+ }
148
+
149
+ // ------------------------------------------------------------ incoming
150
+ _abort(code) {
151
+ // protocol violation: send close frame with the given code and cut the connection
152
+ this._closeCode = code;
153
+ this._sendClose(code, EMPTY);
154
+ this._socket.end();
155
+ }
156
+
157
+ _parse(chunk) {
158
+ this._buffer = this._buffer.length === 0 ? chunk : Buffer.concat([this._buffer, chunk]);
159
+
160
+ while (true) {
161
+ const buf = this._buffer;
162
+ if (buf.length < 2) return;
163
+
164
+ const fin = (buf[0] & 0x80) !== 0;
165
+ const rsv = buf[0] & 0x70;
166
+ const opcode = buf[0] & 0x0f;
167
+ const masked = (buf[1] & 0x80) !== 0;
168
+ let length = buf[1] & 0x7f;
169
+ let offset = 2;
170
+
171
+ // no extension negotiated → RSV bits must be 0; clients must always mask
172
+ if (rsv !== 0 || !masked) return this._abort(1002);
173
+
174
+ if (length === 126) {
175
+ if (buf.length < 4) return;
176
+ length = buf.readUInt16BE(2);
177
+ offset = 4;
178
+ } else if (length === 127) {
179
+ if (buf.length < 10) return;
180
+ const length64 = buf.readBigUInt64BE(2);
181
+ if (length64 > BigInt(Number.MAX_SAFE_INTEGER)) return this._abort(1009);
182
+ length = Number(length64);
183
+ offset = 10;
184
+ }
185
+
186
+ if (length > 100 * 1024 * 1024) return this._abort(1009); // same default max payload as ws
187
+
188
+ if (buf.length < offset + 4 + length) return;
189
+ const mask = buf.slice(offset, offset + 4);
190
+ offset += 4;
191
+
192
+ const payload = buf.slice(offset, offset + length);
193
+ for (let i = 0; i < payload.length; i++) payload[i] ^= mask[i & 3];
194
+
195
+ this._buffer = buf.slice(offset + length);
196
+ this._handleFrame(fin, opcode, payload);
197
+ if (this.readyState === CLOSED) return;
198
+ }
199
+ }
200
+
201
+ _handleFrame(fin, opcode, payload) {
202
+ // control frames (§5.5): never fragmented, payload ≤ 125
203
+ if (opcode >= 0x8) {
204
+ if (!fin || payload.length > 125) return this._abort(1002);
205
+
206
+ if (opcode === 0x8) {
207
+ this._closeReceived = true;
208
+ let code = 1005; // no status received
209
+ let reason = EMPTY;
210
+ if (payload.length >= 2) {
211
+ code = payload.readUInt16BE(0);
212
+ reason = payload.slice(2);
213
+ } else if (payload.length === 1) {
214
+ return this._abort(1002);
215
+ }
216
+ this._closeCode = code === 1005 ? 1000 : code;
217
+ this._closeReason = reason;
218
+ this._sendClose(payload.length >= 2 ? code : undefined, reason); // echo close per §5.5.1
219
+ this._socket.end();
220
+ } else if (opcode === 0x9) {
221
+ this.pong(payload); // §5.5.2: a ping must be answered with an identical pong
222
+ this.emit("ping", payload);
223
+ } else if (opcode === 0xa) {
224
+ this.emit("pong", payload);
225
+ } else {
226
+ this._abort(1002);
227
+ }
228
+ return;
229
+ }
230
+
231
+ // data frames: 0x1 text, 0x2 binary, 0x0 continuation of a fragmented message
232
+ if (opcode === 0x1 || opcode === 0x2) {
233
+ if (this._fragments.length > 0) return this._abort(1002); // new message before finishing the last
234
+ if (fin) return this.emit("message", payload, opcode === 0x2);
235
+ this._fragmentOpcode = opcode;
236
+ this._fragments.push(payload);
237
+ } else if (opcode === 0x0) {
238
+ if (this._fragments.length === 0) return this._abort(1002); // continuation with nothing to continue
239
+ this._fragments.push(payload);
240
+ if (fin) {
241
+ const message = Buffer.concat(this._fragments);
242
+ const isBinary = this._fragmentOpcode === 0x2;
243
+ this._fragments = [];
244
+ this.emit("message", message, isBinary);
245
+ }
246
+ } else {
247
+ this._abort(1002); // unknown opcode
248
+ }
249
+ }
250
+ }
251
+
252
+ WebSocket.CONNECTING = CONNECTING;
253
+ WebSocket.OPEN = OPEN;
254
+ WebSocket.CLOSING = CLOSING;
255
+ WebSocket.CLOSED = CLOSED;
256
+
257
+ class WebSocketServer extends EventEmitter {
258
+ constructor(options = {}, callback) {
259
+ super();
260
+
261
+ this.clients = new Set();
262
+
263
+ if (options.server) {
264
+ this._server = options.server;
265
+ this._ownServer = false;
266
+ } else if (options.noServer) {
267
+ this._server = null;
268
+ this._ownServer = false;
269
+ } else {
270
+ // plain http requests get the same answer ws gives: 426 Upgrade Required
271
+ this._server = http.createServer((req, res) => {
272
+ const body = http.STATUS_CODES[426];
273
+ res.writeHead(426, { "Content-Length": body.length, "Content-Type": "text/plain" });
274
+ res.end(body);
275
+ });
276
+ this._ownServer = true;
277
+ this._server.listen(options.port, options.host, options.backlog, callback);
278
+ }
279
+
280
+ if (this._server) {
281
+ this._server.on("listening", () => this.emit("listening"));
282
+ this._server.on("error", err => this.emit("error", err));
283
+ this._server.on("upgrade", (req, socket, head) => {
284
+ this.handleUpgrade(req, socket, head, ws => this.emit("connection", ws, req));
285
+ });
286
+ }
287
+ }
288
+
289
+ address() {
290
+ return this._server && this._server.address();
291
+ }
292
+
293
+ handleUpgrade(req, socket, head, callback) {
294
+ socket.on("error", () => socket.destroy());
295
+
296
+ const key = req.headers["sec-websocket-key"];
297
+ const version = +req.headers["sec-websocket-version"];
298
+ const upgrade = (req.headers.upgrade || "").split(/, */).some(p => p.toLowerCase() === "websocket");
299
+
300
+ if (req.method !== "GET" || !upgrade || !key || (version !== 13 && version !== 8)) {
301
+ const body = http.STATUS_CODES[400];
302
+ socket.write(
303
+ "HTTP/1.1 400 Bad Request\r\n" +
304
+ "Connection: close\r\n" +
305
+ "Content-Type: text/plain\r\n" +
306
+ `Content-Length: ${body.length}\r\n\r\n` +
307
+ body
308
+ );
309
+ socket.destroy();
310
+ return;
311
+ }
312
+
313
+ // RFC 6455 §4.2.2: accept key proves the server actually speaks websocket
314
+ const accept = crypto.createHash("sha1").update(key + GUID).digest("base64");
315
+ const headers = [
316
+ "HTTP/1.1 101 Switching Protocols",
317
+ "Upgrade: websocket",
318
+ "Connection: Upgrade",
319
+ `Sec-WebSocket-Accept: ${accept}`,
320
+ ];
321
+
322
+ this.emit("headers", headers, req);
323
+ socket.write(headers.concat("\r\n").join("\r\n"));
324
+
325
+ const ws = new WebSocket(socket);
326
+ if (head && head.length > 0) ws._parse(head); // bytes the client sent before we attached
327
+
328
+ this.clients.add(ws);
329
+ ws.on("close", () => this.clients.delete(ws));
330
+ callback(ws);
331
+ }
332
+
333
+ close(cb) {
334
+ for (const ws of this.clients) ws.terminate();
335
+ const done = () => {
336
+ this.emit("close");
337
+ if (cb) cb();
338
+ };
339
+ if (this._ownServer) this._server.close(done);
340
+ else process.nextTick(done);
341
+ }
342
+ }
343
+
344
+ module.exports = WebSocket;
345
+ module.exports.WebSocket = WebSocket;
346
+ module.exports.Server = WebSocketServer;
347
+ module.exports.WebSocketServer = WebSocketServer;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "olum-compiler",
3
- "version": "0.8.6",
3
+ "version": "0.9.0",
4
4
  "description": "A module for compiling/bundling olumjs projects",
5
5
  "main": "bin/index.js",
6
6
  "bin": {
@@ -25,11 +25,7 @@
25
25
  "node": ">=14"
26
26
  },
27
27
  "dependencies": {
28
- "chokidar": "^3.5.3",
29
- "cross-spawn": "^7.0.3",
30
- "esprima": "^4.0.1",
31
- "jsdom": "^19.0.0",
32
- "magic-string": "^0.26.7",
33
- "ws": "^8.5.0"
28
+ "acorn": "^8.17.0",
29
+ "jsdom": "^19.0.0"
34
30
  }
35
31
  }