@darthcav/ts-utils 0.12.3 → 1.0.1

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 (96) hide show
  1. package/README.md +162 -84
  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 +201 -0
  5. package/dist/core/guards.js.map +1 -0
  6. package/dist/core/index.d.ts +17 -0
  7. package/dist/core/index.d.ts.map +1 -0
  8. package/dist/core/index.js +17 -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} +9 -14
  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/delays.d.ts +11 -0
  30. package/dist/node/delays.d.ts.map +1 -0
  31. package/dist/node/delays.js +14 -0
  32. package/dist/node/delays.js.map +1 -0
  33. package/dist/node/index.d.ts +15 -0
  34. package/dist/node/index.d.ts.map +1 -0
  35. package/dist/node/index.js +15 -0
  36. package/dist/node/index.js.map +1 -0
  37. package/dist/node/main.d.ts +158 -0
  38. package/dist/node/main.d.ts.map +1 -0
  39. package/dist/node/main.js +255 -0
  40. package/dist/node/main.js.map +1 -0
  41. package/dist/{monitorMemory.d.ts → node/monitorMemory.d.ts} +14 -5
  42. package/dist/node/monitorMemory.d.ts.map +1 -0
  43. package/dist/{monitorMemory.js → node/monitorMemory.js} +22 -16
  44. package/dist/node/monitorMemory.js.map +1 -0
  45. package/dist/node/osRelease.d.ts +58 -0
  46. package/dist/node/osRelease.d.ts.map +1 -0
  47. package/dist/node/osRelease.js +111 -0
  48. package/dist/node/osRelease.js.map +1 -0
  49. package/dist/node/releaseParsers.d.ts +11 -0
  50. package/dist/node/releaseParsers.d.ts.map +1 -0
  51. package/dist/node/releaseParsers.js +92 -0
  52. package/dist/node/releaseParsers.js.map +1 -0
  53. package/dist/type-testing/index.d.ts +18 -0
  54. package/dist/type-testing/index.d.ts.map +1 -0
  55. package/dist/type-testing/index.js +12 -0
  56. package/dist/type-testing/index.js.map +1 -0
  57. package/package.json +22 -7
  58. package/src/core/guards.ts +239 -0
  59. package/src/core/index.ts +32 -0
  60. package/src/{millisecondsToString.ts → core/millisecondsToString.ts} +9 -16
  61. package/src/core/noop.ts +2 -0
  62. package/src/index.ts +13 -49
  63. package/src/loggers/getConsoleLogger.ts +14 -19
  64. package/src/loggers/index.ts +14 -0
  65. package/src/node/delays.ts +15 -0
  66. package/src/node/index.ts +21 -0
  67. package/src/node/main.ts +419 -0
  68. package/src/{monitorMemory.ts → node/monitorMemory.ts} +24 -18
  69. package/src/node/osRelease.ts +152 -0
  70. package/src/node/releaseParsers.ts +109 -0
  71. package/src/type-testing/index.ts +18 -0
  72. package/dist/main.d.ts +0 -112
  73. package/dist/main.d.ts.map +0 -1
  74. package/dist/main.js +0 -219
  75. package/dist/main.js.map +0 -1
  76. package/dist/millisecondsToString.d.ts.map +0 -1
  77. package/dist/millisecondsToString.js.map +0 -1
  78. package/dist/monitorMemory.d.ts.map +0 -1
  79. package/dist/monitorMemory.js.map +0 -1
  80. package/dist/noop.d.ts +0 -7
  81. package/dist/noop.d.ts.map +0 -1
  82. package/dist/noop.js +0 -7
  83. package/dist/noop.js.map +0 -1
  84. package/dist/osRelease.d.ts +0 -46
  85. package/dist/osRelease.d.ts.map +0 -1
  86. package/dist/osRelease.js +0 -153
  87. package/dist/osRelease.js.map +0 -1
  88. package/dist/types.d.ts +0 -70
  89. package/dist/types.d.ts.map +0 -1
  90. package/dist/types.js +0 -84
  91. package/dist/types.js.map +0 -1
  92. package/src/main.ts +0 -302
  93. package/src/noop.ts +0 -6
  94. package/src/osRelease.ts +0 -174
  95. package/src/types.ts +0 -98
  96. /package/dist/{millisecondsToString.d.ts → core/millisecondsToString.d.ts} +0 -0
package/src/index.ts CHANGED
@@ -1,54 +1,18 @@
1
1
  /**
2
2
  * A collection of utility functions for TypeScript applications and modules.
3
3
  *
4
- * @packageDocumentation
4
+ * The root entry point re-exports every public utility. Import from a subpath
5
+ * to load only one domain:
6
+ *
7
+ * - `@darthcav/ts-utils/core`: portable helpers (no Node.js built-ins).
8
+ * - `@darthcav/ts-utils/node`: Node.js process utilities.
9
+ * - `@darthcav/ts-utils/loggers`: LogTape logger helpers.
10
+ * - `@darthcav/ts-utils/type-testing`: type-level testing helpers.
11
+ *
12
+ * @module @darthcav/ts-utils
5
13
  */
6
14
 
7
- import { getConsoleLogger } from "./loggers/getConsoleLogger.ts"
8
- import { getDummyLogger } from "./loggers/getDummyLogger.ts"
9
- import { type LauncherFunction, type MainOptions, main } from "./main.ts"
10
- import { millisecondsToString } from "./millisecondsToString.ts"
11
- import { monitorMemory } from "./monitorMemory.ts"
12
- import { noop } from "./noop.ts"
13
- import { type OsRelease, osRelease } from "./osRelease.ts"
14
- import type { Assert } from "./type-testing/Assert.ts"
15
- import type { Equal } from "./type-testing/Equal.ts"
16
- import type { Extends } from "./type-testing/Extends.ts"
17
- import type { IsAny } from "./type-testing/IsAny.ts"
18
- import type { IsNever } from "./type-testing/IsNever.ts"
19
- import type { IsUnknown } from "./type-testing/IsUnknown.ts"
20
- import type { Not } from "./type-testing/Not.ts"
21
- import {
22
- asRuntimeObject,
23
- asString,
24
- isRuntimeObject,
25
- isString,
26
- type RuntimeObject,
27
- toRuntimeObjectArray,
28
- } from "./types.ts"
29
-
30
- export {
31
- type Assert,
32
- asRuntimeObject,
33
- asString,
34
- type Equal,
35
- type Extends,
36
- getConsoleLogger,
37
- getDummyLogger,
38
- type IsAny,
39
- type IsNever,
40
- type IsUnknown,
41
- isRuntimeObject,
42
- isString,
43
- type LauncherFunction,
44
- type MainOptions,
45
- main,
46
- millisecondsToString,
47
- monitorMemory,
48
- type Not,
49
- noop,
50
- type OsRelease,
51
- osRelease,
52
- type RuntimeObject,
53
- toRuntimeObjectArray,
54
- }
15
+ export * from "./core/index.ts"
16
+ export * from "./loggers/index.ts"
17
+ export * from "./node/index.ts"
18
+ export type * from "./type-testing/index.ts"
@@ -17,13 +17,9 @@ const FORMATTER_OPTIONS: TextFormatterOptions = {
17
17
  }
18
18
 
19
19
  /**
20
- * Decides whether console output should use ANSI colors.
21
- *
22
- * `FORCE_COLOR` wins when set (`"0"` or `"false"` disable colors, any other
23
- * value enables them). Otherwise colors are used only when both stdout and
24
- * stderr are terminals that support them, since the console sink writes
25
- * warnings and errors to stderr. `hasColors()` also honors `NO_COLOR`,
26
- * `NODE_DISABLE_COLORS`, and `TERM=dumb`.
20
+ * Whether console output should use ANSI colors. `FORCE_COLOR` wins when set;
21
+ * otherwise both stdout and stderr must support colors, since the console
22
+ * sink writes warnings and errors to stderr.
27
23
  */
28
24
  function useColors(): boolean {
29
25
  const force = process.env["FORCE_COLOR"]
@@ -36,22 +32,21 @@ function useColors(): boolean {
36
32
  }
37
33
 
38
34
  /**
39
- * Configures logging and returns a {@link Logger} for the given category name.
35
+ * Configures LogTape globally and returns a {@link Logger} for the given
36
+ * category.
40
37
  *
41
- * Records at or above `lowestLevel` are written to the console with RFC 3339
42
- * timestamps and full level names. The internal `logtape/meta` logger is
38
+ * Records at or above `lowestLevel` go to the console with RFC 3339
39
+ * timestamps and full level names; the internal `logtape/meta` logger is
43
40
  * silenced.
44
41
  *
45
- * ANSI colors are used only when both stdout and stderr are terminals that
46
- * support them (respecting `NO_COLOR`, `NODE_DISABLE_COLORS`, and `TERM=dumb`),
47
- * so output redirected to files or pipes stays free of escape codes. Set
48
- * `FORCE_COLOR` to override: `"0"` or `"false"` disables colors, any other
49
- * value enables them. The decision is made when this function is called.
42
+ * ANSI colors are used only when both stdout and stderr are color terminals
43
+ * (respecting `NO_COLOR`, `NODE_DISABLE_COLORS`, and `TERM=dumb`), so
44
+ * redirected output has no escape codes. `FORCE_COLOR` overrides this: `"0"`
45
+ * or `"false"` disables colors, any other value enables them.
50
46
  *
51
- * Logging is configured with `reset: true`, so this function is safe to call
52
- * more than once: each call reconfigures logtape from scratch and the most
53
- * recent call wins. (Without it, logtape throws because logging is already
54
- * configured.)
47
+ * Each call replaces the whole global LogTape configuration, so the latest
48
+ * call wins. Applications that configure LogTape themselves should use
49
+ * LogTape's `getLogger` instead.
55
50
  *
56
51
  * @param name - The top-level category name (typically the application name).
57
52
  * @param lowestLevel - The minimum log level to output. Defaults to `"info"`.
@@ -0,0 +1,14 @@
1
+ /**
2
+ * LogTape logger helpers: a configured console logger and a no-op logger for
3
+ * tests.
4
+ *
5
+ * @example
6
+ * ```ts
7
+ * import { getConsoleLogger } from "@darthcav/ts-utils/loggers"
8
+ * ```
9
+ *
10
+ * @module loggers
11
+ */
12
+
13
+ export { getConsoleLogger } from "./getConsoleLogger.ts"
14
+ export { getDummyLogger } from "./getDummyLogger.ts"
@@ -0,0 +1,15 @@
1
+ import { isFiniteNumber } from "../core/guards.ts"
2
+
3
+ /**
4
+ * Longest delay `setTimeout` and `setInterval` support (2³¹ − 1 ms, about
5
+ * 596.5 hours). Node.js silently replaces larger delays with 1 ms.
6
+ */
7
+ export const MAX_DELAY_MS = 2_147_483_647
8
+
9
+ /**
10
+ * Whether `ms` is a finite timer delay between `minMs` and
11
+ * {@link MAX_DELAY_MS}. Internal: not re-exported by the `node` entry point.
12
+ */
13
+ export function isValidDelay(ms: unknown, minMs = 0): ms is number {
14
+ return isFiniteNumber(ms) && ms >= minMs && ms <= MAX_DELAY_MS
15
+ }
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Node.js process utilities: application bootstrap and shutdown (`main`),
3
+ * memory monitoring, and OS release information.
4
+ *
5
+ * @example
6
+ * ```ts
7
+ * import { main, osRelease } from "@darthcav/ts-utils/node"
8
+ * ```
9
+ *
10
+ * @module node
11
+ */
12
+
13
+ export {
14
+ type LauncherFunction,
15
+ type MainOptions,
16
+ main,
17
+ type ShutdownContext,
18
+ type ShutdownFunction,
19
+ } from "./main.ts"
20
+ export { monitorMemory } from "./monitorMemory.ts"
21
+ export { type OsRelease, osRelease } from "./osRelease.ts"
@@ -0,0 +1,419 @@
1
+ import { constants } from "node:os"
2
+ import process, { env, execArgv, pid, title } from "node:process"
3
+ import { setTimeout as delay } from "node:timers/promises"
4
+ import { dispose, type Logger } from "@logtape/logtape"
5
+ import { isValidDelay, MAX_DELAY_MS } from "./delays.ts"
6
+ import { HOURS_RANGE, isValidHours, monitorMemory } from "./monitorMemory.ts"
7
+
8
+ /** Default for {@link MainOptions.flushTimeoutMs}. */
9
+ const DEFAULT_FLUSH_TIMEOUT_MS = 3_000
10
+
11
+ /** Default for {@link MainOptions.shutdownTimeoutMs}. */
12
+ const DEFAULT_SHUTDOWN_TIMEOUT_MS = 10_000
13
+
14
+ /** Whether a {@link main} call has not been torn down yet. */
15
+ let active = false
16
+
17
+ /** How a task run by {@link runBounded} ended. */
18
+ type BoundedOutcome =
19
+ | { status: "fulfilled" }
20
+ | { status: "rejected"; reason: unknown }
21
+ | { status: "timeout" }
22
+
23
+ /**
24
+ * Runs a possibly asynchronous task and waits for it for at most `timeoutMs`.
25
+ * Never rejects: a throwing or rejecting task is reported as `"rejected"`.
26
+ * The timer stays referenced, so the process keeps running while it waits.
27
+ */
28
+ async function runBounded(
29
+ task: () => unknown,
30
+ timeoutMs: number,
31
+ ): Promise<BoundedOutcome> {
32
+ const timeout = new AbortController()
33
+ try {
34
+ return await Promise.race([
35
+ Promise.try(task).then(
36
+ (): BoundedOutcome => ({ status: "fulfilled" }),
37
+ (reason: unknown): BoundedOutcome => ({
38
+ status: "rejected",
39
+ reason,
40
+ }),
41
+ ),
42
+ delay<BoundedOutcome>(
43
+ timeoutMs,
44
+ { status: "timeout" },
45
+ { signal: timeout.signal },
46
+ ),
47
+ ])
48
+ } finally {
49
+ // Cancels the timer. The pending delay then rejects, but the race has
50
+ // already handled that.
51
+ timeout.abort()
52
+ }
53
+ }
54
+
55
+ /**
56
+ * Renders an error (with its stack when available) or any other value.
57
+ * `Error.isError`, unlike `instanceof`, also recognizes errors from another
58
+ * realm (e.g. a `node:vm` context).
59
+ */
60
+ function describe(value: unknown): string {
61
+ return Error.isError(value) ? (value.stack ?? String(value)) : String(value)
62
+ }
63
+
64
+ /** Names the type of `value`, telling `null` apart from objects. */
65
+ function typeName(value: unknown): string {
66
+ return value === null ? "null" : typeof value
67
+ }
68
+
69
+ /** Throws a `RangeError` unless `value` is a valid timer delay. */
70
+ function assertTimeout(option: string, value: number): void {
71
+ if (!isValidDelay(value)) {
72
+ throw new RangeError(
73
+ `main: "${option}" must be a finite number between 0 and ${MAX_DELAY_MS}, received ${value}`,
74
+ )
75
+ }
76
+ }
77
+
78
+ /** Throws a `TypeError` unless `value` is a function or `undefined`. */
79
+ function assertOptionalFunction(option: string, value: unknown): void {
80
+ if (value !== undefined && typeof value !== "function") {
81
+ throw new TypeError(
82
+ `main: "${option}" must be a function, received ${typeName(value)}`,
83
+ )
84
+ }
85
+ }
86
+
87
+ /**
88
+ * Starts the application once {@link main} has registered the process
89
+ * handlers. Use a closure to capture any context needed (e.g. a logger). It
90
+ * may be asynchronous; if it throws or rejects, {@link main} logs the failure
91
+ * and shuts down with exit status `1`.
92
+ */
93
+ export type LauncherFunction = () => void | Promise<void>
94
+
95
+ /**
96
+ * Why {@link main} is shutting down, passed to the {@link ShutdownFunction}.
97
+ *
98
+ * - `reason: "signal"`: a normal stop requested with `SIGINT` or `SIGTERM`.
99
+ * - `reason: "error"`: a fatal failure; `source` says where it came from and
100
+ * `error` holds the thrown value or rejection reason. The application may
101
+ * be in an inconsistent state, so only clean up (e.g. close connections).
102
+ */
103
+ export type ShutdownContext =
104
+ | {
105
+ readonly reason: "signal"
106
+ readonly signal: "SIGINT" | "SIGTERM"
107
+ }
108
+ | {
109
+ readonly reason: "error"
110
+ readonly source:
111
+ | "uncaughtException"
112
+ | "unhandledRejection"
113
+ | "launcher"
114
+ readonly error: unknown
115
+ }
116
+
117
+ /**
118
+ * Application cleanup (e.g. closing servers and database connections), run
119
+ * once by {@link main} before the logs are flushed and the process exits. It
120
+ * may be asynchronous; {@link main} waits at most
121
+ * {@link MainOptions.shutdownTimeoutMs} for it.
122
+ *
123
+ * @param context - Why the process is shutting down.
124
+ */
125
+ export type ShutdownFunction = (
126
+ context: ShutdownContext,
127
+ ) => void | Promise<void>
128
+
129
+ /** Options for {@link main}, all optional. */
130
+ export type MainOptions = {
131
+ /** Starts the application (see {@link LauncherFunction}). */
132
+ launcher?: LauncherFunction
133
+ /**
134
+ * Application cleanup, run once on shutdown (see {@link ShutdownFunction}).
135
+ * If it throws, rejects, or exceeds {@link MainOptions.shutdownTimeoutMs},
136
+ * the failure is logged and the process exits with status `1`.
137
+ */
138
+ shutdown?: ShutdownFunction
139
+ /**
140
+ * Maximum wait in milliseconds for {@link MainOptions.shutdown}, between
141
+ * `0` and 2³¹ − 1. Defaults to `10000`.
142
+ */
143
+ shutdownTimeoutMs?: number
144
+ /**
145
+ * When greater than `0`, logs the memory usage every `monitorMemoryHours`
146
+ * hours via {@link monitorMemory}. Must be `0` or an interval that
147
+ * {@link monitorMemory} accepts (one minute to 2³¹ − 1 ms). Defaults to
148
+ * `0` (disabled).
149
+ */
150
+ monitorMemoryHours?: number
151
+ /**
152
+ * When `true` (default), registers `SIGINT` and `SIGTERM` handlers that
153
+ * run the shutdown sequence and stop the process. Set to `false` when the
154
+ * application handles these signals itself.
155
+ */
156
+ defaultInterruptionHandler?: boolean
157
+ /**
158
+ * Flushes the log sinks before the process exits; errors are ignored.
159
+ * Defaults to LogTape's `dispose`, which flushes the sinks configured
160
+ * through the `@logtape/logtape` copy this package uses. Pass another
161
+ * function (e.g. the `dispose` of the application's own LogTape copy), or
162
+ * `noop` to skip flushing.
163
+ */
164
+ flushLogs?: () => void | Promise<void>
165
+ /**
166
+ * Maximum wait in milliseconds for {@link MainOptions.flushLogs}, between
167
+ * `0` and 2³¹ − 1. Defaults to `3000`.
168
+ */
169
+ flushTimeoutMs?: number
170
+ }
171
+
172
+ /**
173
+ * Bootstraps an application process: logs startup information, optionally
174
+ * registers handlers for `SIGINT` and `SIGTERM` (see
175
+ * {@link MainOptions.defaultInterruptionHandler}), always registers handlers
176
+ * for `uncaughtException` and `unhandledRejection`, optionally starts memory
177
+ * monitoring, then runs the optional launcher function.
178
+ *
179
+ * The process title, PID, name, and `NODE_ENV` are logged at `info` level.
180
+ * The Node.js process options (`execArgv` and `NODE_OPTIONS`) are logged at
181
+ * `debug` level only, since they can reveal sensitive flags such as
182
+ * `--inspect=0.0.0.0` or `--require` paths.
183
+ *
184
+ * On `SIGINT`/`SIGTERM`, an uncaught exception, an unhandled rejection, or a
185
+ * launcher failure, `main` runs a shutdown sequence once:
186
+ *
187
+ * 1. The cause is logged (signals at `info`, failures at `error` level) and
188
+ * the memory monitoring stops.
189
+ * 2. The {@link MainOptions.shutdown} function, if any, runs for at most
190
+ * `shutdownTimeoutMs` (10 seconds by default). A failure or timeout is
191
+ * logged at `error` level.
192
+ * 3. The logs are flushed with {@link MainOptions.flushLogs} for at most
193
+ * `flushTimeoutMs` (3 seconds by default), so asynchronous sinks keep the
194
+ * final messages.
195
+ * 4. The process exits. A signal is re-raised, so the process ends as killed
196
+ * by it (exit status 130/143), which shells and supervisors such as
197
+ * systemd treat as a clean stop; if another listener for that signal
198
+ * exists, it exits with status `128 + signal number` instead. Fatal
199
+ * failures, and a failed or timed-out shutdown function, exit with
200
+ * status `1`.
201
+ *
202
+ * A second signal or fatal failure during the sequence exits immediately.
203
+ *
204
+ * Only one `main` call can be active at a time: calling it again before
205
+ * running the returned teardown function throws.
206
+ *
207
+ * @param name - Human-readable application name used in log output.
208
+ * @param logger - Logger instance used for all startup and lifecycle messages.
209
+ * @param options - Optional {@link MainOptions}.
210
+ * @returns A teardown function that removes the process handlers registered
211
+ * by this call and stops the memory monitoring, allowing `main` to be called
212
+ * again (e.g. in tests). It neither runs the shutdown function nor exits
213
+ * the process; calling it more than once is harmless.
214
+ * @throws {TypeError} If `options` is not an object, or `launcher`,
215
+ * `shutdown`, or `flushLogs` is not a function.
216
+ * @throws {Error} If another `main` call is still active.
217
+ * @throws {RangeError} If `monitorMemoryHours`, `shutdownTimeoutMs`, or
218
+ * `flushTimeoutMs` is out of range. Nothing is logged or registered in that
219
+ * case.
220
+ *
221
+ * @example Without options:
222
+ * ```ts
223
+ * main("my-app", logger)
224
+ * ```
225
+ *
226
+ * @example With an async launcher and memory monitoring every 2 hours:
227
+ * ```ts
228
+ * main("my-app", logger, {
229
+ * launcher: async () => {
230
+ * await connectToDatabase()
231
+ * startServer()
232
+ * },
233
+ * monitorMemoryHours: 2,
234
+ * })
235
+ * ```
236
+ *
237
+ * @example With graceful shutdown of the application's resources:
238
+ * ```ts
239
+ * let server: Server | undefined
240
+ * main("my-app", logger, {
241
+ * launcher: async () => {
242
+ * await connectToDatabase()
243
+ * server = startServer()
244
+ * },
245
+ * shutdown: async () => {
246
+ * await server?.close()
247
+ * await disconnectFromDatabase()
248
+ * },
249
+ * shutdownTimeoutMs: 15_000,
250
+ * })
251
+ * ```
252
+ */
253
+ export function main(
254
+ name: string,
255
+ logger: Logger,
256
+ options?: MainOptions,
257
+ ): () => void {
258
+ // Rejects the positional arguments removed in 0.11.0 (e.g. a launcher
259
+ // function) from untyped callers, instead of silently ignoring them.
260
+ if (
261
+ options !== undefined &&
262
+ (typeof options !== "object" || options === null)
263
+ ) {
264
+ throw new TypeError(
265
+ `main: "options" must be a MainOptions object, received ${typeName(options)}`,
266
+ )
267
+ }
268
+ const {
269
+ launcher,
270
+ shutdown,
271
+ shutdownTimeoutMs = DEFAULT_SHUTDOWN_TIMEOUT_MS,
272
+ monitorMemoryHours = 0,
273
+ defaultInterruptionHandler = true,
274
+ flushLogs = dispose,
275
+ flushTimeoutMs = DEFAULT_FLUSH_TIMEOUT_MS,
276
+ } = options ?? {}
277
+
278
+ assertOptionalFunction("launcher", launcher)
279
+ assertOptionalFunction("shutdown", shutdown)
280
+ assertOptionalFunction("flushLogs", flushLogs)
281
+ if (monitorMemoryHours !== 0 && !isValidHours(monitorMemoryHours)) {
282
+ throw new RangeError(
283
+ `main: "monitorMemoryHours" must be 0 (disabled) or a finite number ${HOURS_RANGE}, received ${monitorMemoryHours}`,
284
+ )
285
+ }
286
+ assertTimeout("shutdownTimeoutMs", shutdownTimeoutMs)
287
+ assertTimeout("flushTimeoutMs", flushTimeoutMs)
288
+ if (active) {
289
+ throw new Error(
290
+ "main: already active; call the teardown function returned by the previous main() call first",
291
+ )
292
+ }
293
+
294
+ const __logger = logger.getChild(["main"])
295
+
296
+ __logger.info`Main process launched [${title} :: ${pid}]`
297
+ __logger.info`Process name: ${name}`
298
+ __logger.info`Node.js environment: ${env["NODE_ENV"] ?? ""}`
299
+ __logger.debug`Node.js process options: ${execArgv.concat(env["NODE_OPTIONS"] ?? []).join(" | ")}`
300
+
301
+ const stopMonitoring =
302
+ monitorMemoryHours > 0
303
+ ? monitorMemory(__logger, monitorMemoryHours)
304
+ : undefined
305
+
306
+ // A second signal or failure during the shutdown sequence exits at once.
307
+ let shuttingDown = false
308
+
309
+ /** Runs the shutdown sequence, then `exit` (or status `1` on failure). */
310
+ const shutDown = async (
311
+ context: ShutdownContext,
312
+ exit: () => void,
313
+ ): Promise<void> => {
314
+ if (shuttingDown) {
315
+ exit()
316
+ return
317
+ }
318
+ shuttingDown = true
319
+ stopMonitoring?.()
320
+
321
+ let cleanupFailed = false
322
+ if (shutdown !== undefined) {
323
+ const outcome = await runBounded(
324
+ () => shutdown(context),
325
+ shutdownTimeoutMs,
326
+ )
327
+ cleanupFailed = outcome.status !== "fulfilled"
328
+ if (outcome.status === "rejected") {
329
+ __logger.error`Shutdown function failed: ${describe(outcome.reason)}`
330
+ } else if (outcome.status === "timeout") {
331
+ __logger.error`Shutdown function timed out after ${shutdownTimeoutMs} ms`
332
+ }
333
+ }
334
+
335
+ // Best effort: flush failures and timeouts are ignored.
336
+ await runBounded(flushLogs, flushTimeoutMs)
337
+
338
+ if (cleanupFailed) {
339
+ process.exit(1)
340
+ } else {
341
+ exit()
342
+ }
343
+ }
344
+
345
+ const removeListeners: (() => void)[] = []
346
+
347
+ if (defaultInterruptionHandler) {
348
+ for (const signal of ["SIGINT", "SIGTERM"] as const) {
349
+ const onSignal = (): Promise<void> => {
350
+ __logger.info`Process interrupted. Received signal: ${signal}`
351
+ return shutDown({ reason: "signal", signal }, () => {
352
+ // Re-raise the signal so the process ends as killed by it,
353
+ // unless another listener would intercept it.
354
+ process.off(signal, onSignal)
355
+ if (process.listenerCount(signal) === 0) {
356
+ process.kill(pid, signal)
357
+ } else {
358
+ process.exit(128 + constants.signals[signal])
359
+ }
360
+ })
361
+ }
362
+ process.on(signal, onSignal)
363
+ removeListeners.push(() => process.off(signal, onSignal))
364
+ }
365
+ }
366
+
367
+ /** Runs the shutdown sequence for a fatal failure, then exits with `1`. */
368
+ const fail = (
369
+ source: Extract<ShutdownContext, { reason: "error" }>["source"],
370
+ error: unknown,
371
+ ): Promise<void> =>
372
+ shutDown({ reason: "error", source, error }, () => process.exit(1))
373
+
374
+ const onUncaughtException = (
375
+ error: Error,
376
+ origin: NodeJS.UncaughtExceptionOrigin,
377
+ ): Promise<void> => {
378
+ __logger.error`Uncaught exception: ${describe(error)}`
379
+ __logger.error`Exception origin: ${origin}`
380
+ return fail("uncaughtException", error)
381
+ }
382
+ process.on("uncaughtException", onUncaughtException)
383
+ removeListeners.push(() =>
384
+ process.off("uncaughtException", onUncaughtException),
385
+ )
386
+
387
+ const onUnhandledRejection = (reason: unknown): Promise<void> => {
388
+ __logger.error`Unhandled promise rejection. Reason:\n${describe(reason)}`
389
+ return fail("unhandledRejection", reason)
390
+ }
391
+ process.on("unhandledRejection", onUnhandledRejection)
392
+ removeListeners.push(() =>
393
+ process.off("unhandledRejection", onUnhandledRejection),
394
+ )
395
+
396
+ active = true
397
+ let tornDown = false
398
+ const teardown = (): void => {
399
+ if (tornDown) {
400
+ return
401
+ }
402
+ tornDown = true
403
+ stopMonitoring?.()
404
+ for (const remove of removeListeners) {
405
+ remove()
406
+ }
407
+ active = false
408
+ }
409
+
410
+ const onLauncherFailure = (error: unknown): Promise<void> => {
411
+ __logger.error`Launcher failed: ${describe(error)}`
412
+ return fail("launcher", error)
413
+ }
414
+ if (launcher !== undefined) {
415
+ Promise.try(launcher).catch(onLauncherFailure)
416
+ }
417
+
418
+ return teardown
419
+ }
@@ -1,15 +1,29 @@
1
1
  import { memoryUsage, uptime } from "node:process"
2
2
  import type { Logger } from "@logtape/logtape"
3
- import { millisecondsToString } from "./millisecondsToString.ts"
3
+ import { isFiniteNumber } from "../core/guards.ts"
4
+ import { millisecondsToString } from "../core/millisecondsToString.ts"
5
+ import { isValidDelay, MAX_DELAY_MS } from "./delays.ts"
4
6
 
5
7
  /** Shortest allowed reporting interval: one minute. */
6
8
  const MIN_DELAY_MS = 60 * 1_000
7
9
 
10
+ /** One hour in milliseconds. */
11
+ const HOUR_MS = 60 * 60 * 1_000
12
+
8
13
  /**
9
- * Longest delay `setInterval` supports (2³¹ − 1 ms, about 596.5 hours). Node.js
10
- * silently replaces larger delays with 1 ms, which would flood the logs.
14
+ * The valid range of a reporting interval in hours, for error messages.
15
+ * Internal, like {@link isValidHours}.
11
16
  */
12
- const MAX_DELAY_MS = 2_147_483_647
17
+ export const HOURS_RANGE: string = `between ${MIN_DELAY_MS / HOUR_MS} and ${MAX_DELAY_MS / HOUR_MS} (1 minute to 2^31 - 1 ms)`
18
+
19
+ /**
20
+ * Whether `hours` is a valid reporting interval ({@link HOURS_RANGE}).
21
+ * Internal: {@link main} uses it too, but the `node` entry point does not
22
+ * re-export it.
23
+ */
24
+ export function isValidHours(hours: unknown): hours is number {
25
+ return isFiniteNumber(hours) && isValidDelay(hours * HOUR_MS, MIN_DELAY_MS)
26
+ }
13
27
 
14
28
  /**
15
29
  * Starts a periodic interval that logs process uptime and memory usage, and
@@ -33,13 +47,11 @@ const MAX_DELAY_MS = 2_147_483_647
33
47
  *
34
48
  * @param logger - Logger whose `"monitorMemory"` child emits the memory
35
49
  * reports.
36
- * @param hours - Interval between reports in hours. Must be a finite number
37
- * between `1 / 60` (one minute) and about `596.5` (2³¹ − 1 ms, the longest
38
- * delay `setInterval` supports). Defaults to `24`.
50
+ * @param hours - Interval between reports in hours, from `1 / 60` (one
51
+ * minute) to about `596.5` (2³¹ − 1 ms). Defaults to `24`.
39
52
  * @returns A function that stops the monitoring. Calling it more than once is
40
53
  * harmless.
41
- * @throws {RangeError} If `hours` is not finite or the resulting interval is
42
- * shorter than one minute or longer than 2³¹ − 1 milliseconds.
54
+ * @throws {RangeError} If `hours` is not finite or out of that range.
43
55
  *
44
56
  * @example
45
57
  * ```ts
@@ -54,14 +66,9 @@ const MAX_DELAY_MS = 2_147_483_647
54
66
  * ```
55
67
  */
56
68
  export function monitorMemory(logger: Logger, hours: number = 24): () => void {
57
- const delay = 60 * 60 * 1_000 * hours
58
- if (
59
- !Number.isFinite(delay) ||
60
- delay < MIN_DELAY_MS ||
61
- delay > MAX_DELAY_MS
62
- ) {
69
+ if (!isValidHours(hours)) {
63
70
  throw new RangeError(
64
- `monitorMemory: "hours" must be a finite number between ${MIN_DELAY_MS / 3_600_000} and ${MAX_DELAY_MS / 3_600_000} (1 minute to 2^31 - 1 ms), received ${hours}`,
71
+ `monitorMemory: "hours" must be a finite number ${HOURS_RANGE}, received ${hours}`,
65
72
  )
66
73
  }
67
74
  const __logger = logger.getChild(["monitorMemory"])
@@ -81,8 +88,7 @@ export function monitorMemory(logger: Logger, hours: number = 24): () => void {
81
88
  "Process memory - Resident set size: {rss} | Heap total: {heapTotal} | Heap used: {heapUsed} | External: {external}",
82
89
  { rss, heapTotal, heapUsed, external },
83
90
  )
84
- }, delay)
85
- // Monitoring alone must not keep the process alive.
91
+ }, hours * HOUR_MS)
86
92
  timer.unref()
87
93
 
88
94
  return () => clearInterval(timer)