@alchemy.run/node-utils 0.0.5 → 2.0.0-beta.72

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.
Files changed (49) hide show
  1. package/LICENSE +201 -0
  2. package/NOTICE +5 -0
  3. package/THIRD_PARTY_LICENSES.md +138 -0
  4. package/lib/ignore.d.ts +49 -16
  5. package/lib/ignore.d.ts.map +1 -1
  6. package/lib/ignore.js +50 -61
  7. package/lib/ignore.js.map +1 -1
  8. package/package.json +33 -31
  9. package/src/ignore.ts +157 -105
  10. package/lib/adapter.d.ts +0 -14
  11. package/lib/adapter.d.ts.map +0 -1
  12. package/lib/adapter.js +0 -65
  13. package/lib/adapter.js.map +0 -1
  14. package/lib/exit-hook.d.ts +0 -22
  15. package/lib/exit-hook.d.ts.map +0 -1
  16. package/lib/exit-hook.js +0 -86
  17. package/lib/exit-hook.js.map +0 -1
  18. package/lib/foreground-child.d.ts +0 -57
  19. package/lib/foreground-child.d.ts.map +0 -1
  20. package/lib/foreground-child.js +0 -201
  21. package/lib/foreground-child.js.map +0 -1
  22. package/lib/index.d.ts +0 -6
  23. package/lib/index.d.ts.map +0 -1
  24. package/lib/index.js +0 -6
  25. package/lib/index.js.map +0 -1
  26. package/lib/lockfile-async.d.ts +0 -9
  27. package/lib/lockfile-async.d.ts.map +0 -1
  28. package/lib/lockfile-async.js +0 -23
  29. package/lib/lockfile-async.js.map +0 -1
  30. package/lib/lockfile.d.ts +0 -53
  31. package/lib/lockfile.d.ts.map +0 -1
  32. package/lib/lockfile.js +0 -287
  33. package/lib/lockfile.js.map +0 -1
  34. package/lib/mtime-precision.d.ts +0 -11
  35. package/lib/mtime-precision.d.ts.map +0 -1
  36. package/lib/mtime-precision.js +0 -40
  37. package/lib/mtime-precision.js.map +0 -1
  38. package/lib/retry.d.ts +0 -56
  39. package/lib/retry.d.ts.map +0 -1
  40. package/lib/retry.js +0 -203
  41. package/lib/retry.js.map +0 -1
  42. package/src/adapter.ts +0 -94
  43. package/src/exit-hook.ts +0 -96
  44. package/src/foreground-child.ts +0 -243
  45. package/src/index.ts +0 -5
  46. package/src/lockfile-async.ts +0 -44
  47. package/src/lockfile.ts +0 -502
  48. package/src/mtime-precision.ts +0 -83
  49. package/src/retry.ts +0 -309
package/src/adapter.ts DELETED
@@ -1,94 +0,0 @@
1
- import fs from "node:fs";
2
-
3
- type AnyFs = Record<string, any>;
4
- type AnyCallback = (err: NodeJS.ErrnoException | null, result?: any) => void;
5
- type AsyncMethod = (...args: any[]) => void;
6
-
7
- function createSyncFs(fs: AnyFs): AnyFs {
8
- const methods = ["mkdir", "realpath", "stat", "rmdir", "utimes"] as const;
9
- const newFs: AnyFs = { ...fs };
10
-
11
- methods.forEach((method) => {
12
- newFs[method] = (...args: any[]) => {
13
- const callback = args.pop() as AnyCallback;
14
- let ret;
15
-
16
- try {
17
- ret = fs[`${method}Sync`](...args);
18
- } catch (err) {
19
- return callback(err as NodeJS.ErrnoException);
20
- }
21
-
22
- callback(null, ret);
23
- };
24
- });
25
-
26
- return newFs;
27
- }
28
-
29
- // ----------------------------------------------------------
30
-
31
- export function toPromise<T = any>(
32
- method: AsyncMethod,
33
- ): (...args: any[]) => Promise<T> {
34
- return (...args: any[]) =>
35
- new Promise<T>((resolve, reject) => {
36
- args.push((err: NodeJS.ErrnoException | null, result: T) => {
37
- if (err) {
38
- reject(err);
39
- } else {
40
- resolve(result);
41
- }
42
- });
43
-
44
- method(...args);
45
- });
46
- }
47
-
48
- export function toSync<T = any>(method: AsyncMethod): (...args: any[]) => T {
49
- return (...args: any[]) => {
50
- let err: NodeJS.ErrnoException | null | undefined;
51
- let result: T | undefined;
52
-
53
- args.push((_err: NodeJS.ErrnoException | null, _result: T) => {
54
- err = _err;
55
- result = _result;
56
- });
57
-
58
- method(...args);
59
-
60
- if (err) {
61
- throw err;
62
- }
63
-
64
- return result as T;
65
- };
66
- }
67
-
68
- export interface SyncOptions {
69
- fs?: AnyFs;
70
- retries?: number | { retries?: number };
71
- [key: string]: any;
72
- }
73
-
74
- export function toSyncOptions(options?: SyncOptions): SyncOptions {
75
- // Shallow clone options because we are going to mutate them
76
- const next: SyncOptions = { ...options };
77
-
78
- // Transform fs to use the sync methods instead
79
- next.fs = createSyncFs(next.fs || fs);
80
-
81
- // Retries are not allowed because it requires the flow to be sync
82
- if (
83
- (typeof next.retries === "number" && next.retries > 0) ||
84
- (next.retries &&
85
- typeof (next.retries as { retries?: number }).retries === "number" &&
86
- ((next.retries as { retries?: number }).retries as number) > 0)
87
- ) {
88
- throw Object.assign(new Error("Cannot use retries with the sync api"), {
89
- code: "ESYNC",
90
- });
91
- }
92
-
93
- return next;
94
- }
package/src/exit-hook.ts DELETED
@@ -1,96 +0,0 @@
1
- /**
2
- * Lightweight replacement for the `exit-hook` npm package.
3
- *
4
- * The third-party `exit-hook` registers process listeners (`exit`, `SIGINT`,
5
- * `SIGTERM`, and `message`) that are never removed — even after every
6
- * callback has been unregistered. Those dangling listeners are harmless in
7
- * long-running processes, but in short-lived child processes (e.g. those
8
- * spawned by `node --test`) they can prevent clean exit by holding refs on
9
- * handles such as the IPC channel.
10
- *
11
- * This module tracks the number of active registrations and removes **all**
12
- * process listeners once the last registration is unregistered, so they
13
- * cannot keep the event loop alive after dispose.
14
- */
15
-
16
- const callbacks = new Set<() => void>();
17
- let registered = false;
18
- let called = false;
19
-
20
- function runCallbacks(): void {
21
- if (called) {
22
- return;
23
- }
24
- called = true;
25
- for (const callback of callbacks) {
26
- callback();
27
- }
28
- }
29
-
30
- function onExit(): void {
31
- runCallbacks();
32
- }
33
-
34
- function onSignalInt(): void {
35
- runCallbacks();
36
- // eslint-disable-next-line unicorn/no-process-exit -- intentional: replicate default SIGINT behavior
37
- process.exit(128 + 2);
38
- }
39
-
40
- function onSignalTerm(): void {
41
- runCallbacks();
42
- // eslint-disable-next-line unicorn/no-process-exit -- intentional: replicate default SIGTERM behavior
43
- process.exit(128 + 15);
44
- }
45
-
46
- function onMessage(message: unknown): void {
47
- if (message === "shutdown") {
48
- runCallbacks();
49
- // eslint-disable-next-line unicorn/no-process-exit -- intentional: PM2 graceful shutdown
50
- process.exit(0);
51
- }
52
- }
53
-
54
- function addListeners(): void {
55
- registered = true;
56
- called = false;
57
- process.on("exit", onExit);
58
- process.on("SIGINT", onSignalInt);
59
- process.on("SIGTERM", onSignalTerm);
60
- // Only listen for IPC "shutdown" messages (PM2 support) when the process
61
- // actually has an IPC channel. Even without this guard the listener is
62
- // harmless when there is no channel, but being explicit avoids any
63
- // accidental ref of a future channel.
64
- if (process.send !== undefined) {
65
- process.on("message", onMessage);
66
- }
67
- }
68
-
69
- function removeListeners(): void {
70
- registered = false;
71
- process.removeListener("exit", onExit);
72
- process.removeListener("SIGINT", onSignalInt);
73
- process.removeListener("SIGTERM", onSignalTerm);
74
- process.removeListener("message", onMessage);
75
- }
76
-
77
- /**
78
- * Register a callback to run when the process exits. Returns a function
79
- * that unregisters the callback. When the last callback is unregistered,
80
- * all underlying process listeners are removed so they cannot keep the
81
- * event loop alive.
82
- */
83
- export function exitHook(callback: () => void): () => void {
84
- callbacks.add(callback);
85
-
86
- if (!registered) {
87
- addListeners();
88
- }
89
-
90
- return () => {
91
- callbacks.delete(callback);
92
- if (callbacks.size === 0 && registered) {
93
- removeListeners();
94
- }
95
- };
96
- }
@@ -1,243 +0,0 @@
1
- /**
2
- * Run a child process in the foreground: proxy signals to it, forward stdio,
3
- * bridge IPC, and exit with the child's code/signal. A watchdog process
4
- * ensures the child is killed if the parent dies unexpectedly.
5
- *
6
- * Adapted from `foreground-child@4.0.3` (© Isaac Z. Schlueter et al.):
7
- * https://github.com/tapjs/foreground-child
8
- * Licensed under the Blue Oak Model License 1.0.0:
9
- * https://blueoakcouncil.org/license/1.0.0
10
- *
11
- * The behavioral additions on top of upstream are:
12
- * 1. Optional `stderrFilter` — upstream hardcodes `stdio = [0, 1, 2]`,
13
- * which makes intercepting child stderr impossible without forking.
14
- * When `stderrFilter` is provided, the child's stderr is piped,
15
- * line-buffered, and each line is passed through the filter
16
- * (return `false` to drop, `true` to forward).
17
- * 2. Uses the in-tree {@link exitHook} instead of `signal-exit`, so this
18
- * package has no external runtime dependencies.
19
- *
20
- * Everything else — signal proxying, the watchdog, IPC bridging, exit-code
21
- * forwarding — is preserved verbatim from upstream.
22
- */
23
- import { type ChildProcess, spawn } from "node:child_process";
24
- import constants from "node:constants";
25
- import { exitHook } from "./exit-hook.ts";
26
-
27
- type Signal = NodeJS.Signals;
28
-
29
- const allSignals = Object.keys(constants).filter(
30
- (k) => k.startsWith("SIG") && k !== "SIGPROF" && k !== "SIGKILL",
31
- ) as Signal[];
32
-
33
- function proxySignals(child: ChildProcess): () => void {
34
- const listeners = new Map<Signal, () => void>();
35
- for (const sig of allSignals) {
36
- const listener = (): void => {
37
- try {
38
- child.kill(sig);
39
- } catch (_) {}
40
- };
41
- try {
42
- process.on(sig, listener);
43
- listeners.set(sig, listener);
44
- } catch (_) {}
45
- }
46
- const unproxy = (): void => {
47
- for (const [sig, listener] of listeners) {
48
- process.removeListener(sig, listener);
49
- }
50
- };
51
- child.on("exit", unproxy);
52
- return unproxy;
53
- }
54
-
55
- const watchdogCode = String.raw`
56
- const pid = parseInt(process.argv[1], 10)
57
- process.title = 'node (foreground-child watchdog pid=' + pid + ')'
58
- if (!isNaN(pid)) {
59
- let barked = false
60
- const interval = setInterval(() => {}, 60000)
61
- const bark = () => {
62
- clearInterval(interval)
63
- if (barked) return
64
- barked = true
65
- process.removeListener('SIGHUP', bark)
66
- setTimeout(() => {
67
- try {
68
- process.kill(pid, 'SIGKILL')
69
- setTimeout(() => process.exit(), 200)
70
- } catch (_) {}
71
- }, 500)
72
- }
73
- process.on('SIGHUP', bark)
74
- }
75
- `;
76
-
77
- function watchdog(child: ChildProcess): ChildProcess {
78
- let dogExited = false;
79
- const dog = spawn(process.execPath, ["-e", watchdogCode, String(child.pid)], {
80
- stdio: ["ignore", "ignore", "pipe"],
81
- });
82
- dog.on("exit", () => {
83
- dogExited = true;
84
- });
85
- dog.stderr?.pipe(process.stderr, { end: false });
86
- child.on("exit", () => {
87
- if (!dogExited) dog.kill("SIGKILL");
88
- });
89
- process.on("exit", () => {
90
- if (!dogExited) dog.kill("SIGKILL");
91
- });
92
- return dog;
93
- }
94
-
95
- function isPromise<T>(o: unknown): o is Promise<T> {
96
- return (
97
- !!o &&
98
- typeof o === "object" &&
99
- typeof (o as { then?: unknown }).then === "function"
100
- );
101
- }
102
-
103
- type SyncCleanupResult =
104
- | void
105
- | undefined
106
- | null
107
- | boolean
108
- | number
109
- | string
110
- | NodeJS.Signals;
111
-
112
- export type CleanupResult = SyncCleanupResult | Promise<SyncCleanupResult>;
113
-
114
- export interface ForegroundChildOptions {
115
- /**
116
- * Line-level filter for the child's stderr. Return `true` to forward the
117
- * line to the parent's stderr, `false` to drop it. When omitted, the
118
- * child's stderr is inherited directly (no buffering, no filtering).
119
- */
120
- stderrFilter?: (line: string) => boolean;
121
- /**
122
- * Called when the child closes. May return:
123
- * - `false` — suppress propagation of the child's exit
124
- * - `number` — override the parent's exit code
125
- * - `string` (a signal name) — kill the parent with that signal
126
- * - `void` / `undefined` — propagate the child's code/signal verbatim
127
- * Async (Promise-returning) cleanup is supported.
128
- */
129
- cleanup?: (
130
- code: number | null,
131
- signal: NodeJS.Signals | null,
132
- extra: { watchdogPid: number | undefined },
133
- ) => CleanupResult;
134
- }
135
-
136
- /**
137
- * Run `program` with `args` as a foreground child of the current process.
138
- *
139
- * Signals received by the parent are proxied to the child, the child's stdio
140
- * is connected to the parent's (with optional stderr filtering via
141
- * {@link ForegroundChildOptions.stderrFilter}), IPC messages are bridged in
142
- * both directions, and the parent exits with the child's exit code or
143
- * signal. A watchdog subprocess ensures the child is force-killed if the
144
- * parent dies unexpectedly.
145
- */
146
- export function foregroundChild(
147
- program: string,
148
- args: ReadonlyArray<string>,
149
- opts: ForegroundChildOptions = {},
150
- ): ChildProcess {
151
- const { stderrFilter, cleanup = (): void => {} } = opts;
152
-
153
- const stdio: Array<"pipe" | "ignore" | "inherit" | number> = stderrFilter
154
- ? [0, 1, "pipe"]
155
- : [0, 1, 2];
156
- if (process.send) stdio.push("ipc" as unknown as number);
157
-
158
- const child = spawn(program, args as string[], { stdio });
159
-
160
- if (stderrFilter && child.stderr) {
161
- let buf = "";
162
- child.stderr.on("data", (chunk: Buffer | string) => {
163
- buf += chunk.toString();
164
- let nl: number;
165
- while ((nl = buf.search(/\r?\n/)) !== -1) {
166
- const eol = buf.startsWith("\r\n", nl) ? 2 : 1;
167
- const line = buf.slice(0, nl + eol);
168
- buf = buf.slice(nl + eol);
169
- if (stderrFilter(line)) process.stderr.write(line);
170
- }
171
- });
172
- child.stderr.on("end", () => {
173
- if (buf && stderrFilter(buf)) process.stderr.write(buf);
174
- });
175
- }
176
-
177
- const childHangup = (): void => {
178
- try {
179
- child.kill("SIGHUP");
180
- } catch (_) {
181
- child.kill("SIGTERM");
182
- }
183
- };
184
- const removeOnExit = exitHook(childHangup);
185
-
186
- proxySignals(child);
187
- const dog = watchdog(child);
188
-
189
- let done = false;
190
- dog.on("close", (code, signal) => {
191
- if (done) return;
192
- child.kill("SIGKILL");
193
- throw new Error("foreground-child watchdog process died unexpectedly!", {
194
- cause: {
195
- pid: dog.pid,
196
- code,
197
- signal,
198
- watchedProcess: { cmd: program, args, pid: child.pid },
199
- },
200
- });
201
- });
202
-
203
- child.on("close", async (code, signal) => {
204
- if (done) return;
205
- done = true;
206
- const result = cleanup(code, signal, { watchdogPid: dog.pid });
207
- const res = isPromise<SyncCleanupResult>(result) ? await result : result;
208
- removeOnExit();
209
- if (res === false) return;
210
- let finalCode: number | null = code;
211
- let finalSignal: NodeJS.Signals | null = signal;
212
- if (typeof res === "string") {
213
- finalSignal = res as NodeJS.Signals;
214
- finalCode = null;
215
- } else if (typeof res === "number") {
216
- finalCode = res;
217
- finalSignal = null;
218
- }
219
- if (finalSignal) {
220
- setTimeout(() => {}, 2000);
221
- try {
222
- process.kill(process.pid, finalSignal);
223
- } catch (_) {
224
- process.kill(process.pid, "SIGTERM");
225
- }
226
- } else {
227
- process.exit(finalCode ?? 0);
228
- }
229
- });
230
-
231
- if (process.send) {
232
- process.removeAllListeners("message");
233
- child.on("message", (message, sendHandle) => {
234
- process.send?.(message, sendHandle);
235
- });
236
- process.on("message", (message, sendHandle) => {
237
- if (message === null) return;
238
- child.send(message, sendHandle);
239
- });
240
- }
241
-
242
- return child;
243
- }
package/src/index.ts DELETED
@@ -1,5 +0,0 @@
1
- export * from "./exit-hook.ts";
2
- export * from "./foreground-child.ts";
3
- export * from "./ignore.ts";
4
- export * from "./lockfile-async.ts";
5
- export * from "./retry.ts";
@@ -1,44 +0,0 @@
1
- import { toPromise, toSync, toSyncOptions } from "./adapter.ts";
2
- import type {
3
- CheckOptions,
4
- LockOptions,
5
- ReleaseFn,
6
- UnlockOptions,
7
- } from "./lockfile.ts";
8
- import * as lockfile from "./lockfile.ts";
9
-
10
- export type { CheckOptions, LockOptions, ReleaseFn, UnlockOptions };
11
-
12
- export async function lock(
13
- file: string,
14
- options?: LockOptions,
15
- ): Promise<() => Promise<void>> {
16
- const release = await toPromise<ReleaseFn>(lockfile.lock)(file, options);
17
-
18
- return toPromise<void>(release);
19
- }
20
-
21
- export function lockSync(file: string, options?: LockOptions): () => void {
22
- const release = toSync<ReleaseFn>(lockfile.lock)(
23
- file,
24
- toSyncOptions(options),
25
- );
26
-
27
- return toSync<void>(release);
28
- }
29
-
30
- export function unlock(file: string, options?: UnlockOptions): Promise<void> {
31
- return toPromise<void>(lockfile.unlock)(file, options);
32
- }
33
-
34
- export function unlockSync(file: string, options?: UnlockOptions): void {
35
- return toSync<void>(lockfile.unlock)(file, toSyncOptions(options));
36
- }
37
-
38
- export function check(file: string, options?: CheckOptions): Promise<boolean> {
39
- return toPromise<boolean>(lockfile.check)(file, options);
40
- }
41
-
42
- export function checkSync(file: string, options?: CheckOptions): boolean {
43
- return toSync<boolean>(lockfile.check)(file, toSyncOptions(options));
44
- }