@darthcav/ts-utils 0.12.3 → 1.0.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.
Files changed (85) hide show
  1. package/README.md +152 -81
  2. package/dist/core/guards.d.ts +176 -0
  3. package/dist/core/guards.d.ts.map +1 -0
  4. package/dist/core/guards.js +207 -0
  5. package/dist/core/guards.js.map +1 -0
  6. package/dist/core/index.d.ts +16 -0
  7. package/dist/core/index.d.ts.map +1 -0
  8. package/dist/core/index.js +16 -0
  9. package/dist/core/index.js.map +1 -0
  10. package/dist/core/millisecondsToString.d.ts.map +1 -0
  11. package/dist/{millisecondsToString.js → core/millisecondsToString.js} +3 -4
  12. package/dist/core/millisecondsToString.js.map +1 -0
  13. package/dist/core/noop.d.ts +3 -0
  14. package/dist/core/noop.d.ts.map +1 -0
  15. package/dist/core/noop.js +3 -0
  16. package/dist/core/noop.js.map +1 -0
  17. package/dist/index.d.ts +13 -17
  18. package/dist/index.d.ts.map +1 -1
  19. package/dist/index.js +12 -10
  20. package/dist/index.js.map +1 -1
  21. package/dist/loggers/getConsoleLogger.d.ts +11 -12
  22. package/dist/loggers/getConsoleLogger.d.ts.map +1 -1
  23. package/dist/loggers/getConsoleLogger.js +14 -19
  24. package/dist/loggers/getConsoleLogger.js.map +1 -1
  25. package/dist/loggers/index.d.ts +14 -0
  26. package/dist/loggers/index.d.ts.map +1 -0
  27. package/dist/loggers/index.js +14 -0
  28. package/dist/loggers/index.js.map +1 -0
  29. package/dist/node/index.d.ts +15 -0
  30. package/dist/node/index.d.ts.map +1 -0
  31. package/dist/node/index.js +15 -0
  32. package/dist/node/index.js.map +1 -0
  33. package/dist/node/main.d.ts +156 -0
  34. package/dist/node/main.d.ts.map +1 -0
  35. package/dist/node/main.js +261 -0
  36. package/dist/node/main.js.map +1 -0
  37. package/dist/{monitorMemory.d.ts → node/monitorMemory.d.ts} +3 -5
  38. package/dist/node/monitorMemory.d.ts.map +1 -0
  39. package/dist/{monitorMemory.js → node/monitorMemory.js} +4 -7
  40. package/dist/node/monitorMemory.js.map +1 -0
  41. package/dist/node/osRelease.d.ts +55 -0
  42. package/dist/node/osRelease.d.ts.map +1 -0
  43. package/dist/{osRelease.js → node/osRelease.js} +77 -24
  44. package/dist/node/osRelease.js.map +1 -0
  45. package/dist/type-testing/index.d.ts +18 -0
  46. package/dist/type-testing/index.d.ts.map +1 -0
  47. package/dist/type-testing/index.js +12 -0
  48. package/dist/type-testing/index.js.map +1 -0
  49. package/package.json +20 -5
  50. package/src/core/guards.ts +243 -0
  51. package/src/core/index.ts +31 -0
  52. package/src/{millisecondsToString.ts → core/millisecondsToString.ts} +3 -4
  53. package/src/core/noop.ts +2 -0
  54. package/src/index.ts +13 -49
  55. package/src/loggers/getConsoleLogger.ts +14 -19
  56. package/src/loggers/index.ts +14 -0
  57. package/src/node/index.ts +21 -0
  58. package/src/node/main.ts +427 -0
  59. package/src/{monitorMemory.ts → node/monitorMemory.ts} +4 -7
  60. package/src/node/osRelease.ts +251 -0
  61. package/src/type-testing/index.ts +18 -0
  62. package/dist/main.d.ts +0 -112
  63. package/dist/main.d.ts.map +0 -1
  64. package/dist/main.js +0 -219
  65. package/dist/main.js.map +0 -1
  66. package/dist/millisecondsToString.d.ts.map +0 -1
  67. package/dist/millisecondsToString.js.map +0 -1
  68. package/dist/monitorMemory.d.ts.map +0 -1
  69. package/dist/monitorMemory.js.map +0 -1
  70. package/dist/noop.d.ts +0 -7
  71. package/dist/noop.d.ts.map +0 -1
  72. package/dist/noop.js +0 -7
  73. package/dist/noop.js.map +0 -1
  74. package/dist/osRelease.d.ts +0 -46
  75. package/dist/osRelease.d.ts.map +0 -1
  76. package/dist/osRelease.js.map +0 -1
  77. package/dist/types.d.ts +0 -70
  78. package/dist/types.d.ts.map +0 -1
  79. package/dist/types.js +0 -84
  80. package/dist/types.js.map +0 -1
  81. package/src/main.ts +0 -302
  82. package/src/noop.ts +0 -6
  83. package/src/osRelease.ts +0 -174
  84. package/src/types.ts +0 -98
  85. /package/dist/{millisecondsToString.d.ts → core/millisecondsToString.d.ts} +0 -0
@@ -0,0 +1,156 @@
1
+ import { type Logger } from "@logtape/logtape";
2
+ /**
3
+ * Starts the application once {@link main} has registered the process
4
+ * handlers. Use a closure to capture any context needed (e.g. a logger). It
5
+ * may be asynchronous; if it throws or rejects, {@link main} logs the failure
6
+ * and shuts down with exit status `1`.
7
+ */
8
+ export type LauncherFunction = () => void | Promise<void>;
9
+ /**
10
+ * Why {@link main} is shutting down, passed to the {@link ShutdownFunction}.
11
+ *
12
+ * - `reason: "signal"`: a normal stop requested with `SIGINT` or `SIGTERM`.
13
+ * - `reason: "error"`: a fatal failure; `source` says where it came from and
14
+ * `error` holds the thrown value or rejection reason. The application may
15
+ * be in an inconsistent state, so only clean up (e.g. close connections).
16
+ */
17
+ export type ShutdownContext = {
18
+ readonly reason: "signal";
19
+ readonly signal: "SIGINT" | "SIGTERM";
20
+ } | {
21
+ readonly reason: "error";
22
+ readonly source: "uncaughtException" | "unhandledRejection" | "launcher";
23
+ readonly error: unknown;
24
+ };
25
+ /**
26
+ * Application cleanup (e.g. closing servers and database connections), run
27
+ * once by {@link main} before the logs are flushed and the process exits. It
28
+ * may be asynchronous; {@link main} waits at most
29
+ * {@link MainOptions.shutdownTimeoutMs} for it.
30
+ *
31
+ * @param context - Why the process is shutting down.
32
+ */
33
+ export type ShutdownFunction = (context: ShutdownContext) => void | Promise<void>;
34
+ /** Options for {@link main}, all optional. */
35
+ export type MainOptions = {
36
+ /** Starts the application (see {@link LauncherFunction}). */
37
+ launcher?: LauncherFunction;
38
+ /**
39
+ * Application cleanup, run once on shutdown (see {@link ShutdownFunction}).
40
+ * If it throws, rejects, or exceeds {@link MainOptions.shutdownTimeoutMs},
41
+ * the failure is logged and the process exits with status `1`.
42
+ */
43
+ shutdown?: ShutdownFunction;
44
+ /**
45
+ * Maximum wait in milliseconds for {@link MainOptions.shutdown}, between
46
+ * `0` and 2³¹ − 1. Defaults to `10000`.
47
+ */
48
+ shutdownTimeoutMs?: number;
49
+ /**
50
+ * When greater than `0`, logs the memory usage every `monitorMemoryHours`
51
+ * hours via {@link monitorMemory}. Must be `0` or a positive finite
52
+ * number. Defaults to `0` (disabled).
53
+ */
54
+ monitorMemoryHours?: number;
55
+ /**
56
+ * When `true` (default), registers `SIGINT` and `SIGTERM` handlers that
57
+ * run the shutdown sequence and stop the process. Set to `false` when the
58
+ * application handles these signals itself.
59
+ */
60
+ defaultInterruptionHandler?: boolean;
61
+ /**
62
+ * Flushes the log sinks before the process exits; errors are ignored.
63
+ * Defaults to LogTape's `dispose`, which flushes the sinks configured
64
+ * through the `@logtape/logtape` copy this package uses. Pass another
65
+ * function (e.g. the `dispose` of the application's own LogTape copy), or
66
+ * `noop` to skip flushing.
67
+ */
68
+ flushLogs?: () => void | Promise<void>;
69
+ /**
70
+ * Maximum wait in milliseconds for {@link MainOptions.flushLogs}, between
71
+ * `0` and 2³¹ − 1. Defaults to `3000`.
72
+ */
73
+ flushTimeoutMs?: number;
74
+ };
75
+ /**
76
+ * Bootstraps an application process: logs startup information, optionally
77
+ * registers handlers for `SIGINT` and `SIGTERM` (see
78
+ * {@link MainOptions.defaultInterruptionHandler}), always registers handlers
79
+ * for `uncaughtException` and `unhandledRejection`, optionally starts memory
80
+ * monitoring, then runs the optional launcher function.
81
+ *
82
+ * The process title, PID, name, and `NODE_ENV` are logged at `info` level.
83
+ * The Node.js process options (`execArgv` and `NODE_OPTIONS`) are logged at
84
+ * `debug` level only, since they can reveal sensitive flags such as
85
+ * `--inspect=0.0.0.0` or `--require` paths.
86
+ *
87
+ * On `SIGINT`/`SIGTERM`, an uncaught exception, an unhandled rejection, or a
88
+ * launcher failure, `main` runs a shutdown sequence once:
89
+ *
90
+ * 1. The cause is logged (signals at `info`, failures at `error` level) and
91
+ * the memory monitoring stops.
92
+ * 2. The {@link MainOptions.shutdown} function, if any, runs for at most
93
+ * `shutdownTimeoutMs` (10 seconds by default). A failure or timeout is
94
+ * logged at `error` level.
95
+ * 3. The logs are flushed with {@link MainOptions.flushLogs} for at most
96
+ * `flushTimeoutMs` (3 seconds by default), so asynchronous sinks keep the
97
+ * final messages.
98
+ * 4. The process exits. A signal is re-raised, so the process ends as killed
99
+ * by it (exit status 130/143), which shells and supervisors such as
100
+ * systemd treat as a clean stop; if another listener for that signal
101
+ * exists, it exits with status `128 + signal number` instead. Fatal
102
+ * failures, and a failed or timed-out shutdown function, exit with
103
+ * status `1`.
104
+ *
105
+ * A second signal or fatal failure during the sequence exits immediately.
106
+ *
107
+ * Only one `main` call can be active at a time: calling it again before
108
+ * running the returned teardown function throws.
109
+ *
110
+ * @param name - Human-readable application name used in log output.
111
+ * @param logger - Logger instance used for all startup and lifecycle messages.
112
+ * @param options - Optional {@link MainOptions}.
113
+ * @returns A teardown function that removes the process handlers registered
114
+ * by this call and stops the memory monitoring, allowing `main` to be called
115
+ * again (e.g. in tests). It neither runs the shutdown function nor exits
116
+ * the process; calling it more than once is harmless.
117
+ * @throws {TypeError} If `options` is not an object, or `launcher`,
118
+ * `shutdown`, or `flushLogs` is not a function.
119
+ * @throws {Error} If another `main` call is still active.
120
+ * @throws {RangeError} If `monitorMemoryHours`, `shutdownTimeoutMs`, or
121
+ * `flushTimeoutMs` is out of range. Nothing is registered in that case.
122
+ *
123
+ * @example Without options:
124
+ * ```ts
125
+ * main("my-app", logger)
126
+ * ```
127
+ *
128
+ * @example With an async launcher and memory monitoring every 2 hours:
129
+ * ```ts
130
+ * main("my-app", logger, {
131
+ * launcher: async () => {
132
+ * await connectToDatabase()
133
+ * startServer()
134
+ * },
135
+ * monitorMemoryHours: 2,
136
+ * })
137
+ * ```
138
+ *
139
+ * @example With graceful shutdown of the application's resources:
140
+ * ```ts
141
+ * let server: Server | undefined
142
+ * main("my-app", logger, {
143
+ * launcher: async () => {
144
+ * await connectToDatabase()
145
+ * server = startServer()
146
+ * },
147
+ * shutdown: async () => {
148
+ * await server?.close()
149
+ * await disconnectFromDatabase()
150
+ * },
151
+ * shutdownTimeoutMs: 15_000,
152
+ * })
153
+ * ```
154
+ */
155
+ export declare function main(name: string, logger: Logger, options?: MainOptions): () => void;
156
+ //# sourceMappingURL=main.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"main.d.ts","sourceRoot":"","sources":["../../src/node/main.ts"],"names":[],"mappings":"AAEA,OAAO,EAAW,KAAK,MAAM,EAAE,MAAM,kBAAkB,CAAA;AAgFvD;;;;;GAKG;AACH,MAAM,MAAM,gBAAgB,GAAG,MAAM,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAA;AAEzD;;;;;;;GAOG;AACH,MAAM,MAAM,eAAe,GACrB;IACI,QAAQ,CAAC,MAAM,EAAE,QAAQ,CAAA;IACzB,QAAQ,CAAC,MAAM,EAAE,QAAQ,GAAG,SAAS,CAAA;CACxC,GACD;IACI,QAAQ,CAAC,MAAM,EAAE,OAAO,CAAA;IACxB,QAAQ,CAAC,MAAM,EACT,mBAAmB,GACnB,oBAAoB,GACpB,UAAU,CAAA;IAChB,QAAQ,CAAC,KAAK,EAAE,OAAO,CAAA;CAC1B,CAAA;AAEP;;;;;;;GAOG;AACH,MAAM,MAAM,gBAAgB,GAAG,CAC3B,OAAO,EAAE,eAAe,KACvB,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAA;AAEzB,8CAA8C;AAC9C,MAAM,MAAM,WAAW,GAAG;IACtB,6DAA6D;IAC7D,QAAQ,CAAC,EAAE,gBAAgB,CAAA;IAC3B;;;;OAIG;IACH,QAAQ,CAAC,EAAE,gBAAgB,CAAA;IAC3B;;;OAGG;IACH,iBAAiB,CAAC,EAAE,MAAM,CAAA;IAC1B;;;;OAIG;IACH,kBAAkB,CAAC,EAAE,MAAM,CAAA;IAC3B;;;;OAIG;IACH,0BAA0B,CAAC,EAAE,OAAO,CAAA;IACpC;;;;;;OAMG;IACH,SAAS,CAAC,EAAE,MAAM,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAA;IACtC;;;OAGG;IACH,cAAc,CAAC,EAAE,MAAM,CAAA;CAC1B,CAAA;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+EG;AACH,wBAAgB,IAAI,CAChB,IAAI,EAAE,MAAM,EACZ,MAAM,EAAE,MAAM,EACd,OAAO,CAAC,EAAE,WAAW,GACtB,MAAM,IAAI,CAgLZ"}
@@ -0,0 +1,261 @@
1
+ import { constants } from "node:os";
2
+ import process, { env, execArgv, pid, title } from "node:process";
3
+ import { dispose } from "@logtape/logtape";
4
+ import { monitorMemory } from "./monitorMemory.js";
5
+ /** Default for {@link MainOptions.flushTimeoutMs}. */
6
+ const DEFAULT_FLUSH_TIMEOUT_MS = 3_000;
7
+ /** Default for {@link MainOptions.shutdownTimeoutMs}. */
8
+ const DEFAULT_SHUTDOWN_TIMEOUT_MS = 10_000;
9
+ /**
10
+ * Longest delay `setTimeout` supports (2³¹ − 1 ms). Node.js silently replaces
11
+ * larger delays with 1 ms.
12
+ */
13
+ const MAX_TIMEOUT_MS = 2_147_483_647;
14
+ /** Whether a {@link main} call has not been torn down yet. */
15
+ let active = false;
16
+ /**
17
+ * Runs a possibly asynchronous task and waits for it for at most `timeoutMs`.
18
+ * Never rejects: a throwing or rejecting task is reported as `"rejected"`.
19
+ * The timer stays referenced, so the process keeps running while it waits.
20
+ */
21
+ async function runBounded(task, timeoutMs) {
22
+ let timer;
23
+ try {
24
+ return await Promise.race([
25
+ Promise.try(task).then(() => ({ status: "fulfilled" }), (reason) => ({
26
+ status: "rejected",
27
+ reason,
28
+ })),
29
+ new Promise((resolve) => {
30
+ timer = setTimeout(() => resolve({ status: "timeout" }), timeoutMs);
31
+ }),
32
+ ]);
33
+ }
34
+ finally {
35
+ clearTimeout(timer);
36
+ }
37
+ }
38
+ /** Renders an error (with its stack when available) or any other value. */
39
+ function describe(value) {
40
+ return value instanceof Error
41
+ ? (value.stack ?? String(value))
42
+ : String(value);
43
+ }
44
+ /** Throws a `RangeError` unless `value` is a valid timer delay. */
45
+ function assertTimeout(option, value) {
46
+ if (!Number.isFinite(value) || value < 0 || value > MAX_TIMEOUT_MS) {
47
+ throw new RangeError(`main: "${option}" must be a finite number between 0 and ${MAX_TIMEOUT_MS}, received ${value}`);
48
+ }
49
+ }
50
+ /** Throws a `TypeError` unless `value` is a function or `undefined`. */
51
+ function assertOptionalFunction(option, value) {
52
+ if (value !== undefined && typeof value !== "function") {
53
+ throw new TypeError(`main: "${option}" must be a function, received ${value === null ? "null" : typeof value}`);
54
+ }
55
+ }
56
+ /**
57
+ * Bootstraps an application process: logs startup information, optionally
58
+ * registers handlers for `SIGINT` and `SIGTERM` (see
59
+ * {@link MainOptions.defaultInterruptionHandler}), always registers handlers
60
+ * for `uncaughtException` and `unhandledRejection`, optionally starts memory
61
+ * monitoring, then runs the optional launcher function.
62
+ *
63
+ * The process title, PID, name, and `NODE_ENV` are logged at `info` level.
64
+ * The Node.js process options (`execArgv` and `NODE_OPTIONS`) are logged at
65
+ * `debug` level only, since they can reveal sensitive flags such as
66
+ * `--inspect=0.0.0.0` or `--require` paths.
67
+ *
68
+ * On `SIGINT`/`SIGTERM`, an uncaught exception, an unhandled rejection, or a
69
+ * launcher failure, `main` runs a shutdown sequence once:
70
+ *
71
+ * 1. The cause is logged (signals at `info`, failures at `error` level) and
72
+ * the memory monitoring stops.
73
+ * 2. The {@link MainOptions.shutdown} function, if any, runs for at most
74
+ * `shutdownTimeoutMs` (10 seconds by default). A failure or timeout is
75
+ * logged at `error` level.
76
+ * 3. The logs are flushed with {@link MainOptions.flushLogs} for at most
77
+ * `flushTimeoutMs` (3 seconds by default), so asynchronous sinks keep the
78
+ * final messages.
79
+ * 4. The process exits. A signal is re-raised, so the process ends as killed
80
+ * by it (exit status 130/143), which shells and supervisors such as
81
+ * systemd treat as a clean stop; if another listener for that signal
82
+ * exists, it exits with status `128 + signal number` instead. Fatal
83
+ * failures, and a failed or timed-out shutdown function, exit with
84
+ * status `1`.
85
+ *
86
+ * A second signal or fatal failure during the sequence exits immediately.
87
+ *
88
+ * Only one `main` call can be active at a time: calling it again before
89
+ * running the returned teardown function throws.
90
+ *
91
+ * @param name - Human-readable application name used in log output.
92
+ * @param logger - Logger instance used for all startup and lifecycle messages.
93
+ * @param options - Optional {@link MainOptions}.
94
+ * @returns A teardown function that removes the process handlers registered
95
+ * by this call and stops the memory monitoring, allowing `main` to be called
96
+ * again (e.g. in tests). It neither runs the shutdown function nor exits
97
+ * the process; calling it more than once is harmless.
98
+ * @throws {TypeError} If `options` is not an object, or `launcher`,
99
+ * `shutdown`, or `flushLogs` is not a function.
100
+ * @throws {Error} If another `main` call is still active.
101
+ * @throws {RangeError} If `monitorMemoryHours`, `shutdownTimeoutMs`, or
102
+ * `flushTimeoutMs` is out of range. Nothing is registered in that case.
103
+ *
104
+ * @example Without options:
105
+ * ```ts
106
+ * main("my-app", logger)
107
+ * ```
108
+ *
109
+ * @example With an async launcher and memory monitoring every 2 hours:
110
+ * ```ts
111
+ * main("my-app", logger, {
112
+ * launcher: async () => {
113
+ * await connectToDatabase()
114
+ * startServer()
115
+ * },
116
+ * monitorMemoryHours: 2,
117
+ * })
118
+ * ```
119
+ *
120
+ * @example With graceful shutdown of the application's resources:
121
+ * ```ts
122
+ * let server: Server | undefined
123
+ * main("my-app", logger, {
124
+ * launcher: async () => {
125
+ * await connectToDatabase()
126
+ * server = startServer()
127
+ * },
128
+ * shutdown: async () => {
129
+ * await server?.close()
130
+ * await disconnectFromDatabase()
131
+ * },
132
+ * shutdownTimeoutMs: 15_000,
133
+ * })
134
+ * ```
135
+ */
136
+ export function main(name, logger, options) {
137
+ // Rejects the positional arguments removed in 0.11.0 (e.g. a launcher
138
+ // function) from untyped callers, instead of silently ignoring them.
139
+ if (options !== undefined &&
140
+ (typeof options !== "object" || options === null)) {
141
+ throw new TypeError(`main: "options" must be a MainOptions object, received ${options === null ? "null" : typeof options}`);
142
+ }
143
+ const { launcher, shutdown, shutdownTimeoutMs = DEFAULT_SHUTDOWN_TIMEOUT_MS, monitorMemoryHours = 0, defaultInterruptionHandler = true, flushLogs = dispose, flushTimeoutMs = DEFAULT_FLUSH_TIMEOUT_MS, } = options ?? {};
144
+ assertOptionalFunction("launcher", launcher);
145
+ assertOptionalFunction("shutdown", shutdown);
146
+ assertOptionalFunction("flushLogs", flushLogs);
147
+ if (!Number.isFinite(monitorMemoryHours) || monitorMemoryHours < 0) {
148
+ throw new RangeError(`main: "monitorMemoryHours" must be 0 (disabled) or a positive finite number, received ${monitorMemoryHours}`);
149
+ }
150
+ assertTimeout("shutdownTimeoutMs", shutdownTimeoutMs);
151
+ assertTimeout("flushTimeoutMs", flushTimeoutMs);
152
+ if (active) {
153
+ throw new Error("main: already active; call the teardown function returned by the previous main() call first");
154
+ }
155
+ const __logger = logger.getChild(["main"]);
156
+ __logger.info `Main process launched [${title} :: ${pid}]`;
157
+ __logger.info `Process name: ${name}`;
158
+ __logger.info `Node.js environment: ${env["NODE_ENV"] ?? ""}`;
159
+ __logger.debug `Node.js process options: ${execArgv.concat(env["NODE_OPTIONS"] ?? []).join(" | ")}`;
160
+ // Started before any handler is registered, since it validates the hours
161
+ // further and may throw.
162
+ const stopMonitoring = monitorMemoryHours > 0
163
+ ? monitorMemory(__logger, monitorMemoryHours)
164
+ : undefined;
165
+ // A second signal or failure during the shutdown sequence exits at once.
166
+ let shuttingDown = false;
167
+ /** Runs the shutdown sequence, then `exit` (or status `1` on failure). */
168
+ const shutDown = async (context, exit) => {
169
+ if (shuttingDown) {
170
+ exit();
171
+ return;
172
+ }
173
+ shuttingDown = true;
174
+ stopMonitoring?.();
175
+ let cleanupFailed = false;
176
+ if (shutdown !== undefined) {
177
+ const outcome = await runBounded(() => shutdown(context), shutdownTimeoutMs);
178
+ if (outcome.status === "rejected") {
179
+ cleanupFailed = true;
180
+ __logger.error `Shutdown function failed: ${describe(outcome.reason)}`;
181
+ }
182
+ else if (outcome.status === "timeout") {
183
+ cleanupFailed = true;
184
+ __logger.error `Shutdown function timed out after ${shutdownTimeoutMs} ms`;
185
+ }
186
+ }
187
+ // Best effort: flush failures and timeouts are ignored.
188
+ await runBounded(flushLogs, flushTimeoutMs);
189
+ if (cleanupFailed) {
190
+ process.exit(1);
191
+ }
192
+ else {
193
+ exit();
194
+ }
195
+ };
196
+ const removeListeners = [];
197
+ if (defaultInterruptionHandler) {
198
+ for (const signal of ["SIGINT", "SIGTERM"]) {
199
+ const onSignal = () => {
200
+ __logger.info `Process interrupted. Received signal: ${signal}`;
201
+ return shutDown({ reason: "signal", signal }, () => {
202
+ // Re-raise the signal so the process ends as killed by it,
203
+ // unless another listener would intercept it.
204
+ process.off(signal, onSignal);
205
+ if (process.listenerCount(signal) === 0) {
206
+ process.kill(pid, signal);
207
+ }
208
+ else {
209
+ process.exit(128 + constants.signals[signal]);
210
+ }
211
+ });
212
+ };
213
+ process.on(signal, onSignal);
214
+ removeListeners.push(() => process.off(signal, onSignal));
215
+ }
216
+ }
217
+ const exitWithFailure = () => {
218
+ process.exit(1);
219
+ };
220
+ const onUncaughtException = (error, origin) => {
221
+ __logger.error `Uncaught exception: ${describe(error)}`;
222
+ __logger.error `Exception origin: ${origin}`;
223
+ return shutDown({ reason: "error", source: "uncaughtException", error }, exitWithFailure);
224
+ };
225
+ process.on("uncaughtException", onUncaughtException);
226
+ removeListeners.push(() => process.off("uncaughtException", onUncaughtException));
227
+ const onUnhandledRejection = (reason) => {
228
+ __logger.error `Unhandled promise rejection. Reason:\n${describe(reason)}`;
229
+ return shutDown({ reason: "error", source: "unhandledRejection", error: reason }, exitWithFailure);
230
+ };
231
+ process.on("unhandledRejection", onUnhandledRejection);
232
+ removeListeners.push(() => process.off("unhandledRejection", onUnhandledRejection));
233
+ active = true;
234
+ let tornDown = false;
235
+ const teardown = () => {
236
+ if (tornDown) {
237
+ return;
238
+ }
239
+ tornDown = true;
240
+ stopMonitoring?.();
241
+ for (const remove of removeListeners) {
242
+ remove();
243
+ }
244
+ active = false;
245
+ };
246
+ const onLauncherFailure = (error) => {
247
+ __logger.error `Launcher failed: ${describe(error)}`;
248
+ return shutDown({ reason: "error", source: "launcher", error }, exitWithFailure);
249
+ };
250
+ try {
251
+ const result = launcher?.();
252
+ if (result !== undefined) {
253
+ Promise.resolve(result).catch(onLauncherFailure);
254
+ }
255
+ }
256
+ catch (error) {
257
+ void onLauncherFailure(error);
258
+ }
259
+ return teardown;
260
+ }
261
+ //# sourceMappingURL=main.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"main.js","sourceRoot":"","sources":["../../src/node/main.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,SAAS,CAAA;AACnC,OAAO,OAAO,EAAE,EAAE,GAAG,EAAE,QAAQ,EAAE,GAAG,EAAE,KAAK,EAAE,MAAM,cAAc,CAAA;AACjE,OAAO,EAAE,OAAO,EAAe,MAAM,kBAAkB,CAAA;AACvD,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAA;AAElD,sDAAsD;AACtD,MAAM,wBAAwB,GAAG,KAAK,CAAA;AAEtC,yDAAyD;AACzD,MAAM,2BAA2B,GAAG,MAAM,CAAA;AAE1C;;;GAGG;AACH,MAAM,cAAc,GAAG,aAAa,CAAA;AAEpC,8DAA8D;AAC9D,IAAI,MAAM,GAAG,KAAK,CAAA;AAQlB;;;;GAIG;AACH,KAAK,UAAU,UAAU,CACrB,IAAmB,EACnB,SAAiB;IAEjB,IAAI,KAAgD,CAAA;IACpD,IAAI,CAAC;QACD,OAAO,MAAM,OAAO,CAAC,IAAI,CAAC;YACtB,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,IAAI,CAClB,GAAmB,EAAE,CAAC,CAAC,EAAE,MAAM,EAAE,WAAW,EAAE,CAAC,EAC/C,CAAC,MAAe,EAAkB,EAAE,CAAC,CAAC;gBAClC,MAAM,EAAE,UAAU;gBAClB,MAAM;aACT,CAAC,CACL;YACD,IAAI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A;QACZ,CAAC;QACD,MAAM,GAAG,KAAK,CAAA;IAClB,CAAC,CAAA;IAED,MAAM,iBAAiB,GAAG,CAAC,KAAc,EAAiB,EAAE;QACxD,QAAQ,CAAC,KAAK,CAAA,oBAAoB,QAAQ,CAAC,KAAK,CAAC,EAAE,CAAA;QACnD,OAAO,QAAQ,CACX,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,UAAU,EAAE,KAAK,EAAE,EAC9C,eAAe,CAClB,CAAA;IACL,CAAC,CAAA;IACD,IAAI,CAAC;QACD,MAAM,MAAM,GAAG,QAAQ,EAAE,EAAE,CAAA;QAC3B,IAAI,MAAM,KAAK,SAAS,EAAE,CAAC;YACvB,OAAO,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,KAAK,CAAC,iBAAiB,CAAC,CAAA;QACpD,CAAC;IACL,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACb,KAAK,iBAAiB,CAAC,KAAK,CAAC,CAAA;IACjC,CAAC;IAED,OAAO,QAAQ,CAAA;AACnB,CAAC"}
@@ -21,13 +21,11 @@ import type { Logger } from "@logtape/logtape";
21
21
  *
22
22
  * @param logger - Logger whose `"monitorMemory"` child emits the memory
23
23
  * reports.
24
- * @param hours - Interval between reports in hours. Must be a finite number
25
- * between `1 / 60` (one minute) and about `596.5` (2³¹ − 1 ms, the longest
26
- * delay `setInterval` supports). Defaults to `24`.
24
+ * @param hours - Interval between reports in hours, from `1 / 60` (one
25
+ * minute) to about `596.5` (2³¹ − 1 ms). Defaults to `24`.
27
26
  * @returns A function that stops the monitoring. Calling it more than once is
28
27
  * harmless.
29
- * @throws {RangeError} If `hours` is not finite or the resulting interval is
30
- * shorter than one minute or longer than 2³¹ − 1 milliseconds.
28
+ * @throws {RangeError} If `hours` is not finite or out of that range.
31
29
  *
32
30
  * @example
33
31
  * ```ts
@@ -0,0 +1 @@
1
+ {"version":3,"file":"monitorMemory.d.ts","sourceRoot":"","sources":["../../src/node/monitorMemory.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAA;AAY9C;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAuCG;AACH,wBAAgB,aAAa,CAAC,MAAM,EAAE,MAAM,EAAE,KAAK,GAAE,MAAW,GAAG,MAAM,IAAI,CAgC5E"}
@@ -1,5 +1,5 @@
1
1
  import { memoryUsage, uptime } from "node:process";
2
- import { millisecondsToString } from "./millisecondsToString.js";
2
+ import { millisecondsToString } from "../core/millisecondsToString.js";
3
3
  /** Shortest allowed reporting interval: one minute. */
4
4
  const MIN_DELAY_MS = 60 * 1_000;
5
5
  /**
@@ -29,13 +29,11 @@ const MAX_DELAY_MS = 2_147_483_647;
29
29
  *
30
30
  * @param logger - Logger whose `"monitorMemory"` child emits the memory
31
31
  * reports.
32
- * @param hours - Interval between reports in hours. Must be a finite number
33
- * between `1 / 60` (one minute) and about `596.5` (2³¹ − 1 ms, the longest
34
- * delay `setInterval` supports). Defaults to `24`.
32
+ * @param hours - Interval between reports in hours, from `1 / 60` (one
33
+ * minute) to about `596.5` (2³¹ − 1 ms). Defaults to `24`.
35
34
  * @returns A function that stops the monitoring. Calling it more than once is
36
35
  * harmless.
37
- * @throws {RangeError} If `hours` is not finite or the resulting interval is
38
- * shorter than one minute or longer than 2³¹ − 1 milliseconds.
36
+ * @throws {RangeError} If `hours` is not finite or out of that range.
39
37
  *
40
38
  * @example
41
39
  * ```ts
@@ -70,7 +68,6 @@ export function monitorMemory(logger, hours = 24) {
70
68
  });
71
69
  __logger.info("Process memory - Resident set size: {rss} | Heap total: {heapTotal} | Heap used: {heapUsed} | External: {external}", { rss, heapTotal, heapUsed, external });
72
70
  }, delay);
73
- // Monitoring alone must not keep the process alive.
74
71
  timer.unref();
75
72
  return () => clearInterval(timer);
76
73
  }
@@ -0,0 +1 @@
1
+ {"version":3,"file":"monitorMemory.js","sourceRoot":"","sources":["../../src/node/monitorMemory.ts"],"names":[],"mappings":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EAAE,SAAS,EAAE,QAAQ,EAAE,QAAQ,EAAE,CACzC,CAAA;IACL,CAAC,EAAE,KAAK,CAAC,CAAA;IACT,KAAK,CAAC,KAAK,EAAE,CAAA;IAEb,OAAO,GAAG,EAAE,CAAC,aAAa,CAAC,KAAK,CAAC,CAAA;AACrC,CAAC"}
@@ -0,0 +1,55 @@
1
+ import type { RuntimeObject } from "../core/guards.ts";
2
+ /**
3
+ * OS release information: the normalized `name`, `version`, and `arch`, plus
4
+ * the platform's raw keys by string index:
5
+ *
6
+ * - On Linux, the keys read from the os-release file (`/etc/os-release`, or
7
+ * `/usr/lib/os-release` as a fallback; e.g. `ID`, `PRETTY_NAME`,
8
+ * `ID_LIKE`).
9
+ * - On macOS, the string keys of
10
+ * `/System/Library/CoreServices/SystemVersion.plist` (e.g. `ProductName`,
11
+ * `ProductVersion`, `ProductBuildVersion`).
12
+ */
13
+ export type OsRelease = {
14
+ /** Human-readable OS name, e.g. `"Ubuntu"`, `"macOS"`, or `"Windows 11"`. */
15
+ name: string;
16
+ /**
17
+ * OS version string, e.g. `"24.04"`, `"15.1"`, or `"10.0.22000"`. On
18
+ * macOS it is the product version, not the Darwin kernel version (which
19
+ * `os.release()` returns).
20
+ */
21
+ version: string;
22
+ /** Processor architecture as returned by `os.arch()`, e.g. `"x64"`. */
23
+ arch: string;
24
+ } & RuntimeObject;
25
+ /**
26
+ * Returns OS release information for the current platform (Linux, macOS, or
27
+ * Windows). `arch` always comes from `os.arch()`.
28
+ *
29
+ * - On Linux, it reads `/etc/os-release`, falling back to
30
+ * `/usr/lib/os-release`. `name` comes from `NAME` (or `PRETTY_NAME`) and
31
+ * `version` from `VERSION_ID` (or `VERSION`). Values are unquoted as in a
32
+ * shell; comments and keys that are not upper-case variable names are
33
+ * skipped.
34
+ * - On macOS, it reads `/System/Library/CoreServices/SystemVersion.plist`.
35
+ * `name` is `ProductName` (or `"macOS"`) and `version` is
36
+ * `ProductVersion` (e.g. `"15.1"`), never the Darwin kernel version.
37
+ * - On Windows, `version` is the kernel version, and Windows 11 is told
38
+ * apart from Windows 10 by NT build number (>= 22000).
39
+ *
40
+ * On Linux and macOS, the raw keys of the file are also present.
41
+ *
42
+ * @returns An {@link OsRelease}, or `null` on unsupported platforms or when
43
+ * the release file cannot be read.
44
+ *
45
+ * @example
46
+ * ```ts
47
+ * import { osRelease } from "@darthcav/ts-utils"
48
+ *
49
+ * const info = osRelease()
50
+ * if (info) console.log(info.name) // e.g. "Ubuntu", "macOS", or "Windows 11"
51
+ * if (info) console.log(info.PRETTY_NAME) // e.g. "Ubuntu 24.04 LTS" (Linux only)
52
+ * ```
53
+ */
54
+ export declare function osRelease(): OsRelease | null;
55
+ //# sourceMappingURL=osRelease.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"osRelease.d.ts","sourceRoot":"","sources":["../../src/node/osRelease.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAA;AAEtD;;;;;;;;;;GAUG;AACH,MAAM,MAAM,SAAS,GAAG;IACpB,6EAA6E;IAC7E,IAAI,EAAE,MAAM,CAAA;IACZ;;;;OAIG;IACH,OAAO,EAAE,MAAM,CAAA;IACf,uEAAuE;IACvE,IAAI,EAAE,MAAM,CAAA;CACf,GAAG,aAAa,CAAA;AA+HjB;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH,wBAAgB,SAAS,IAAI,SAAS,GAAG,IAAI,CAoE5C"}