@darthcav/ts-utils 1.0.0 → 1.0.2
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/README.md +20 -10
- package/dist/core/guards.d.ts.map +1 -1
- package/dist/core/guards.js +4 -10
- package/dist/core/guards.js.map +1 -1
- package/dist/core/index.d.ts +2 -1
- package/dist/core/index.d.ts.map +1 -1
- package/dist/core/index.js +2 -1
- package/dist/core/index.js.map +1 -1
- package/dist/core/millisecondsToString.d.ts.map +1 -1
- package/dist/core/millisecondsToString.js +6 -10
- package/dist/core/millisecondsToString.js.map +1 -1
- package/dist/node/delays.d.ts +11 -0
- package/dist/node/delays.d.ts.map +1 -0
- package/dist/node/delays.js +14 -0
- package/dist/node/delays.js.map +1 -0
- package/dist/node/main.d.ts +5 -3
- package/dist/node/main.d.ts.map +1 -1
- package/dist/node/main.js +34 -40
- package/dist/node/main.js.map +1 -1
- package/dist/node/monitorMemory.d.ts +11 -0
- package/dist/node/monitorMemory.d.ts.map +1 -1
- package/dist/node/monitorMemory.js +18 -9
- package/dist/node/monitorMemory.js.map +1 -1
- package/dist/node/osRelease.d.ts +6 -3
- package/dist/node/osRelease.d.ts.map +1 -1
- package/dist/node/osRelease.js +60 -155
- package/dist/node/osRelease.js.map +1 -1
- package/dist/node/releaseParsers.d.ts +11 -0
- package/dist/node/releaseParsers.d.ts.map +1 -0
- package/dist/node/releaseParsers.js +92 -0
- package/dist/node/releaseParsers.js.map +1 -0
- package/package.json +9 -7
- package/src/core/guards.ts +7 -11
- package/src/core/index.ts +2 -1
- package/src/core/millisecondsToString.ts +6 -12
- package/src/node/delays.ts +15 -0
- package/src/node/main.ts +46 -54
- package/src/node/monitorMemory.ts +20 -11
- package/src/node/osRelease.ts +72 -171
- package/src/node/releaseParsers.ts +109 -0
package/src/node/main.ts
CHANGED
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
import { constants } from "node:os"
|
|
2
2
|
import process, { env, execArgv, pid, title } from "node:process"
|
|
3
|
+
import { setTimeout as delay } from "node:timers/promises"
|
|
3
4
|
import { dispose, type Logger } from "@logtape/logtape"
|
|
4
|
-
import {
|
|
5
|
+
import { isValidDelay, MAX_DELAY_MS } from "./delays.ts"
|
|
6
|
+
import { HOURS_RANGE, isValidHours, monitorMemory } from "./monitorMemory.ts"
|
|
5
7
|
|
|
6
8
|
/** Default for {@link MainOptions.flushTimeoutMs}. */
|
|
7
9
|
const DEFAULT_FLUSH_TIMEOUT_MS = 3_000
|
|
@@ -9,12 +11,6 @@ const DEFAULT_FLUSH_TIMEOUT_MS = 3_000
|
|
|
9
11
|
/** Default for {@link MainOptions.shutdownTimeoutMs}. */
|
|
10
12
|
const DEFAULT_SHUTDOWN_TIMEOUT_MS = 10_000
|
|
11
13
|
|
|
12
|
-
/**
|
|
13
|
-
* Longest delay `setTimeout` supports (2³¹ − 1 ms). Node.js silently replaces
|
|
14
|
-
* larger delays with 1 ms.
|
|
15
|
-
*/
|
|
16
|
-
const MAX_TIMEOUT_MS = 2_147_483_647
|
|
17
|
-
|
|
18
14
|
/** Whether a {@link main} call has not been torn down yet. */
|
|
19
15
|
let active = false
|
|
20
16
|
|
|
@@ -33,7 +29,7 @@ async function runBounded(
|
|
|
33
29
|
task: () => unknown,
|
|
34
30
|
timeoutMs: number,
|
|
35
31
|
): Promise<BoundedOutcome> {
|
|
36
|
-
|
|
32
|
+
const timeout = new AbortController()
|
|
37
33
|
try {
|
|
38
34
|
return await Promise.race([
|
|
39
35
|
Promise.try(task).then(
|
|
@@ -43,30 +39,38 @@ async function runBounded(
|
|
|
43
39
|
reason,
|
|
44
40
|
}),
|
|
45
41
|
),
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
}),
|
|
42
|
+
delay<BoundedOutcome>(
|
|
43
|
+
timeoutMs,
|
|
44
|
+
{ status: "timeout" },
|
|
45
|
+
{ signal: timeout.signal },
|
|
46
|
+
),
|
|
52
47
|
])
|
|
53
48
|
} finally {
|
|
54
|
-
|
|
49
|
+
// Cancels the timer. The pending delay then rejects, but the race has
|
|
50
|
+
// already handled that.
|
|
51
|
+
timeout.abort()
|
|
55
52
|
}
|
|
56
53
|
}
|
|
57
54
|
|
|
58
|
-
/**
|
|
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
|
+
*/
|
|
59
60
|
function describe(value: unknown): string {
|
|
60
|
-
return value
|
|
61
|
-
|
|
62
|
-
|
|
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
|
|
63
67
|
}
|
|
64
68
|
|
|
65
69
|
/** Throws a `RangeError` unless `value` is a valid timer delay. */
|
|
66
70
|
function assertTimeout(option: string, value: number): void {
|
|
67
|
-
if (!
|
|
71
|
+
if (!isValidDelay(value)) {
|
|
68
72
|
throw new RangeError(
|
|
69
|
-
`main: "${option}" must be a finite number between 0 and ${
|
|
73
|
+
`main: "${option}" must be a finite number between 0 and ${MAX_DELAY_MS}, received ${value}`,
|
|
70
74
|
)
|
|
71
75
|
}
|
|
72
76
|
}
|
|
@@ -75,7 +79,7 @@ function assertTimeout(option: string, value: number): void {
|
|
|
75
79
|
function assertOptionalFunction(option: string, value: unknown): void {
|
|
76
80
|
if (value !== undefined && typeof value !== "function") {
|
|
77
81
|
throw new TypeError(
|
|
78
|
-
`main: "${option}" must be a function, received ${value
|
|
82
|
+
`main: "${option}" must be a function, received ${typeName(value)}`,
|
|
79
83
|
)
|
|
80
84
|
}
|
|
81
85
|
}
|
|
@@ -139,8 +143,9 @@ export type MainOptions = {
|
|
|
139
143
|
shutdownTimeoutMs?: number
|
|
140
144
|
/**
|
|
141
145
|
* When greater than `0`, logs the memory usage every `monitorMemoryHours`
|
|
142
|
-
* hours via {@link monitorMemory}. Must be `0` or
|
|
143
|
-
*
|
|
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).
|
|
144
149
|
*/
|
|
145
150
|
monitorMemoryHours?: number
|
|
146
151
|
/**
|
|
@@ -210,7 +215,8 @@ export type MainOptions = {
|
|
|
210
215
|
* `shutdown`, or `flushLogs` is not a function.
|
|
211
216
|
* @throws {Error} If another `main` call is still active.
|
|
212
217
|
* @throws {RangeError} If `monitorMemoryHours`, `shutdownTimeoutMs`, or
|
|
213
|
-
* `flushTimeoutMs` is out of range. Nothing is registered in that
|
|
218
|
+
* `flushTimeoutMs` is out of range. Nothing is logged or registered in that
|
|
219
|
+
* case.
|
|
214
220
|
*
|
|
215
221
|
* @example Without options:
|
|
216
222
|
* ```ts
|
|
@@ -256,7 +262,7 @@ export function main(
|
|
|
256
262
|
(typeof options !== "object" || options === null)
|
|
257
263
|
) {
|
|
258
264
|
throw new TypeError(
|
|
259
|
-
`main: "options" must be a MainOptions object, received ${options
|
|
265
|
+
`main: "options" must be a MainOptions object, received ${typeName(options)}`,
|
|
260
266
|
)
|
|
261
267
|
}
|
|
262
268
|
const {
|
|
@@ -272,9 +278,9 @@ export function main(
|
|
|
272
278
|
assertOptionalFunction("launcher", launcher)
|
|
273
279
|
assertOptionalFunction("shutdown", shutdown)
|
|
274
280
|
assertOptionalFunction("flushLogs", flushLogs)
|
|
275
|
-
if (
|
|
281
|
+
if (monitorMemoryHours !== 0 && !isValidHours(monitorMemoryHours)) {
|
|
276
282
|
throw new RangeError(
|
|
277
|
-
`main: "monitorMemoryHours" must be 0 (disabled) or a
|
|
283
|
+
`main: "monitorMemoryHours" must be 0 (disabled) or a finite number ${HOURS_RANGE}, received ${monitorMemoryHours}`,
|
|
278
284
|
)
|
|
279
285
|
}
|
|
280
286
|
assertTimeout("shutdownTimeoutMs", shutdownTimeoutMs)
|
|
@@ -292,8 +298,6 @@ export function main(
|
|
|
292
298
|
__logger.info`Node.js environment: ${env["NODE_ENV"] ?? ""}`
|
|
293
299
|
__logger.debug`Node.js process options: ${execArgv.concat(env["NODE_OPTIONS"] ?? []).join(" | ")}`
|
|
294
300
|
|
|
295
|
-
// Started before any handler is registered, since it validates the hours
|
|
296
|
-
// further and may throw.
|
|
297
301
|
const stopMonitoring =
|
|
298
302
|
monitorMemoryHours > 0
|
|
299
303
|
? monitorMemory(__logger, monitorMemoryHours)
|
|
@@ -320,11 +324,10 @@ export function main(
|
|
|
320
324
|
() => shutdown(context),
|
|
321
325
|
shutdownTimeoutMs,
|
|
322
326
|
)
|
|
327
|
+
cleanupFailed = outcome.status !== "fulfilled"
|
|
323
328
|
if (outcome.status === "rejected") {
|
|
324
|
-
cleanupFailed = true
|
|
325
329
|
__logger.error`Shutdown function failed: ${describe(outcome.reason)}`
|
|
326
330
|
} else if (outcome.status === "timeout") {
|
|
327
|
-
cleanupFailed = true
|
|
328
331
|
__logger.error`Shutdown function timed out after ${shutdownTimeoutMs} ms`
|
|
329
332
|
}
|
|
330
333
|
}
|
|
@@ -361,9 +364,12 @@ export function main(
|
|
|
361
364
|
}
|
|
362
365
|
}
|
|
363
366
|
|
|
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))
|
|
367
373
|
|
|
368
374
|
const onUncaughtException = (
|
|
369
375
|
error: Error,
|
|
@@ -371,10 +377,7 @@ export function main(
|
|
|
371
377
|
): Promise<void> => {
|
|
372
378
|
__logger.error`Uncaught exception: ${describe(error)}`
|
|
373
379
|
__logger.error`Exception origin: ${origin}`
|
|
374
|
-
return
|
|
375
|
-
{ reason: "error", source: "uncaughtException", error },
|
|
376
|
-
exitWithFailure,
|
|
377
|
-
)
|
|
380
|
+
return fail("uncaughtException", error)
|
|
378
381
|
}
|
|
379
382
|
process.on("uncaughtException", onUncaughtException)
|
|
380
383
|
removeListeners.push(() =>
|
|
@@ -383,10 +386,7 @@ export function main(
|
|
|
383
386
|
|
|
384
387
|
const onUnhandledRejection = (reason: unknown): Promise<void> => {
|
|
385
388
|
__logger.error`Unhandled promise rejection. Reason:\n${describe(reason)}`
|
|
386
|
-
return
|
|
387
|
-
{ reason: "error", source: "unhandledRejection", error: reason },
|
|
388
|
-
exitWithFailure,
|
|
389
|
-
)
|
|
389
|
+
return fail("unhandledRejection", reason)
|
|
390
390
|
}
|
|
391
391
|
process.on("unhandledRejection", onUnhandledRejection)
|
|
392
392
|
removeListeners.push(() =>
|
|
@@ -409,18 +409,10 @@ export function main(
|
|
|
409
409
|
|
|
410
410
|
const onLauncherFailure = (error: unknown): Promise<void> => {
|
|
411
411
|
__logger.error`Launcher failed: ${describe(error)}`
|
|
412
|
-
return
|
|
413
|
-
{ reason: "error", source: "launcher", error },
|
|
414
|
-
exitWithFailure,
|
|
415
|
-
)
|
|
412
|
+
return fail("launcher", error)
|
|
416
413
|
}
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
if (result !== undefined) {
|
|
420
|
-
Promise.resolve(result).catch(onLauncherFailure)
|
|
421
|
-
}
|
|
422
|
-
} catch (error) {
|
|
423
|
-
void onLauncherFailure(error)
|
|
414
|
+
if (launcher !== undefined) {
|
|
415
|
+
Promise.try(launcher).catch(onLauncherFailure)
|
|
424
416
|
}
|
|
425
417
|
|
|
426
418
|
return teardown
|
|
@@ -1,15 +1,29 @@
|
|
|
1
1
|
import { memoryUsage, uptime } from "node:process"
|
|
2
2
|
import type { Logger } from "@logtape/logtape"
|
|
3
|
+
import { isFiniteNumber } from "../core/guards.ts"
|
|
3
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
|
-
*
|
|
10
|
-
*
|
|
14
|
+
* The valid range of a reporting interval in hours, for error messages.
|
|
15
|
+
* Internal, like {@link isValidHours}.
|
|
11
16
|
*/
|
|
12
|
-
const
|
|
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
|
|
@@ -52,14 +66,9 @@ const MAX_DELAY_MS = 2_147_483_647
|
|
|
52
66
|
* ```
|
|
53
67
|
*/
|
|
54
68
|
export function monitorMemory(logger: Logger, hours: number = 24): () => void {
|
|
55
|
-
|
|
56
|
-
if (
|
|
57
|
-
!Number.isFinite(delay) ||
|
|
58
|
-
delay < MIN_DELAY_MS ||
|
|
59
|
-
delay > MAX_DELAY_MS
|
|
60
|
-
) {
|
|
69
|
+
if (!isValidHours(hours)) {
|
|
61
70
|
throw new RangeError(
|
|
62
|
-
`monitorMemory: "hours" must be a finite number
|
|
71
|
+
`monitorMemory: "hours" must be a finite number ${HOURS_RANGE}, received ${hours}`,
|
|
63
72
|
)
|
|
64
73
|
}
|
|
65
74
|
const __logger = logger.getChild(["monitorMemory"])
|
|
@@ -79,7 +88,7 @@ export function monitorMemory(logger: Logger, hours: number = 24): () => void {
|
|
|
79
88
|
"Process memory - Resident set size: {rss} | Heap total: {heapTotal} | Heap used: {heapUsed} | External: {external}",
|
|
80
89
|
{ rss, heapTotal, heapUsed, external },
|
|
81
90
|
)
|
|
82
|
-
},
|
|
91
|
+
}, hours * HOUR_MS)
|
|
83
92
|
timer.unref()
|
|
84
93
|
|
|
85
94
|
return () => clearInterval(timer)
|
package/src/node/osRelease.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { readFileSync } from "node:fs"
|
|
2
2
|
import { arch, release as kernelRelease, platform } from "node:os"
|
|
3
3
|
import type { RuntimeObject } from "../core/guards.ts"
|
|
4
|
+
import { parseOsRelease, parsePlistStrings } from "./releaseParsers.ts"
|
|
4
5
|
|
|
5
6
|
/**
|
|
6
7
|
* OS release information: the normalized `name`, `version`, and `arch`, plus
|
|
@@ -26,36 +27,53 @@ export type OsRelease = {
|
|
|
26
27
|
arch: string
|
|
27
28
|
} & RuntimeObject
|
|
28
29
|
|
|
29
|
-
/**
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
30
|
+
/** Where a platform keeps its release file, and how to read it. */
|
|
31
|
+
type ReleaseFile = {
|
|
32
|
+
/** Candidate files, in lookup order. */
|
|
33
|
+
readonly files: readonly string[]
|
|
34
|
+
/** Parses the file content into a null-prototype record of raw keys. */
|
|
35
|
+
readonly parse: (content: string) => Record<string, string>
|
|
36
|
+
/** Picks the normalized `name` from the raw keys. */
|
|
37
|
+
readonly name: (raw: Record<string, string>) => string
|
|
38
|
+
/** Picks the normalized `version` from the raw keys. */
|
|
39
|
+
readonly version: (raw: Record<string, string>) => string
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** The platforms whose release information comes from a file. */
|
|
43
|
+
const RELEASE_FILES: Readonly<Partial<Record<NodeJS.Platform, ReleaseFile>>> = {
|
|
44
|
+
linux: {
|
|
45
|
+
// Per the freedesktop.org spec, `/etc/os-release` takes precedence and
|
|
46
|
+
// `/usr/lib/os-release` is the fallback.
|
|
47
|
+
files: ["/etc/os-release", "/usr/lib/os-release"],
|
|
48
|
+
parse: parseOsRelease,
|
|
49
|
+
name: (raw) => raw["NAME"] ?? raw["PRETTY_NAME"] ?? "",
|
|
50
|
+
version: (raw) => raw["VERSION_ID"] ?? raw["VERSION"] ?? "",
|
|
51
|
+
},
|
|
52
|
+
darwin: {
|
|
53
|
+
files: ["/System/Library/CoreServices/SystemVersion.plist"],
|
|
54
|
+
parse: parsePlistStrings,
|
|
55
|
+
name: (raw) => raw["ProductName"] || "macOS",
|
|
56
|
+
version: (raw) => raw["ProductVersion"] ?? "",
|
|
57
|
+
},
|
|
58
|
+
}
|
|
34
59
|
|
|
35
60
|
/**
|
|
36
|
-
*
|
|
37
|
-
* also
|
|
61
|
+
* Windows names by the first three characters of the kernel version. Windows
|
|
62
|
+
* 11 also reports `10.`, so it is told apart by build number.
|
|
38
63
|
*/
|
|
39
|
-
const
|
|
64
|
+
const WINDOWS_NAMES: ReadonlyMap<string, string> = new Map([
|
|
65
|
+
["10.", "10"],
|
|
66
|
+
["6.3", "8.1"],
|
|
67
|
+
["6.2", "8"],
|
|
68
|
+
["6.1", "7"],
|
|
69
|
+
["6.0", "Vista"],
|
|
70
|
+
["5.2", "XP 64-Bit Edition"],
|
|
71
|
+
["5.1", "XP"],
|
|
72
|
+
["5.0", "2000"],
|
|
73
|
+
])
|
|
40
74
|
|
|
41
|
-
/**
|
|
42
|
-
const
|
|
43
|
-
"/System/Library/CoreServices/SystemVersion.plist"
|
|
44
|
-
|
|
45
|
-
/** A `<key>…</key>` followed by a `<string>…</string>` value in a plist. */
|
|
46
|
-
const PLIST_STRING_ENTRY = /<key>([^<]*)<\/key>\s*<string>([^<]*)<\/string>/g
|
|
47
|
-
|
|
48
|
-
/** Valid plist keys to copy; this also rules out keys such as `__proto__`. */
|
|
49
|
-
const PLIST_KEY = /^[A-Za-z][A-Za-z0-9_]*$/
|
|
50
|
-
|
|
51
|
-
/** The predefined XML entities. */
|
|
52
|
-
const XML_ENTITIES: Readonly<Record<string, string>> = {
|
|
53
|
-
amp: "&",
|
|
54
|
-
apos: "'",
|
|
55
|
-
gt: ">",
|
|
56
|
-
lt: "<",
|
|
57
|
-
quot: '"',
|
|
58
|
-
}
|
|
75
|
+
/** First Windows 11 build number. */
|
|
76
|
+
const WINDOWS_11_BUILD = 22000
|
|
59
77
|
|
|
60
78
|
/** Reads the first readable file of `files`, or returns `null` if none is. */
|
|
61
79
|
function readFirstFile(files: readonly string[]): string | null {
|
|
@@ -69,86 +87,13 @@ function readFirstFile(files: readonly string[]): string | null {
|
|
|
69
87
|
return null
|
|
70
88
|
}
|
|
71
89
|
|
|
72
|
-
/**
|
|
73
|
-
function
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
if (hex !== undefined || decimal !== undefined) {
|
|
78
|
-
const codePoint = Number.parseInt(
|
|
79
|
-
hex ?? decimal ?? "",
|
|
80
|
-
hex === undefined ? 10 : 16,
|
|
81
|
-
)
|
|
82
|
-
return codePoint <= 0x10ffff
|
|
83
|
-
? String.fromCodePoint(codePoint)
|
|
84
|
-
: match
|
|
85
|
-
}
|
|
86
|
-
return (
|
|
87
|
-
(name !== undefined && Object.hasOwn(XML_ENTITIES, name)
|
|
88
|
-
? XML_ENTITIES[name]
|
|
89
|
-
: undefined) ?? match
|
|
90
|
-
)
|
|
91
|
-
},
|
|
92
|
-
)
|
|
93
|
-
}
|
|
94
|
-
|
|
95
|
-
/**
|
|
96
|
-
* Parses the `<string>` entries of an XML property list into a
|
|
97
|
-
* null-prototype record, skipping other value types and invalid keys.
|
|
98
|
-
*/
|
|
99
|
-
function parsePlistStrings(content: string): Record<string, string> {
|
|
100
|
-
const raw: Record<string, string> = Object.create(null)
|
|
101
|
-
for (const [, rawKey = "", value = ""] of content.matchAll(
|
|
102
|
-
PLIST_STRING_ENTRY,
|
|
103
|
-
)) {
|
|
104
|
-
const key = decodeXml(rawKey.trim())
|
|
105
|
-
if (PLIST_KEY.test(key)) {
|
|
106
|
-
raw[key] = decodeXml(value.trim())
|
|
107
|
-
}
|
|
108
|
-
}
|
|
109
|
-
return raw
|
|
110
|
-
}
|
|
111
|
-
|
|
112
|
-
/**
|
|
113
|
-
* Removes one level of shell-style quoting from an os-release value. Double
|
|
114
|
-
* quotes allow the `\\`, `\"`, `` \` `` and `\$` escapes; single quotes are
|
|
115
|
-
* literal.
|
|
116
|
-
*/
|
|
117
|
-
function unquote(value: string): string {
|
|
118
|
-
if (value.length >= 2) {
|
|
119
|
-
const quote = value[0]
|
|
120
|
-
if (quote === '"' && value.endsWith('"')) {
|
|
121
|
-
return value.slice(1, -1).replace(/\\([\\"`$])/g, "$1")
|
|
122
|
-
}
|
|
123
|
-
if (quote === "'" && value.endsWith("'")) {
|
|
124
|
-
return value.slice(1, -1)
|
|
125
|
-
}
|
|
126
|
-
}
|
|
127
|
-
return value
|
|
128
|
-
}
|
|
129
|
-
|
|
130
|
-
/**
|
|
131
|
-
* Parses os-release content into a null-prototype record, skipping blank
|
|
132
|
-
* lines, comments, lines without `=`, and invalid keys.
|
|
133
|
-
*/
|
|
134
|
-
function parseOsRelease(content: string): Record<string, string> {
|
|
135
|
-
const raw: Record<string, string> = Object.create(null)
|
|
136
|
-
for (const line of content.split("\n")) {
|
|
137
|
-
const trimmed = line.trim()
|
|
138
|
-
if (trimmed === "" || trimmed.startsWith("#")) {
|
|
139
|
-
continue
|
|
140
|
-
}
|
|
141
|
-
const eq = trimmed.indexOf("=")
|
|
142
|
-
if (eq === -1) {
|
|
143
|
-
continue
|
|
144
|
-
}
|
|
145
|
-
const key = trimmed.substring(0, eq).trim()
|
|
146
|
-
if (!OS_RELEASE_KEY.test(key)) {
|
|
147
|
-
continue
|
|
148
|
-
}
|
|
149
|
-
raw[key] = unquote(trimmed.substring(eq + 1).trim())
|
|
90
|
+
/** Maps a Windows kernel version (e.g. `"10.0.22000"`) to a product name. */
|
|
91
|
+
function windowsName(version: string): string {
|
|
92
|
+
const [major, , build = 0] = version.split(".").map(Number)
|
|
93
|
+
if (major === 10 && build >= WINDOWS_11_BUILD) {
|
|
94
|
+
return "Windows 11"
|
|
150
95
|
}
|
|
151
|
-
return
|
|
96
|
+
return `Windows ${WINDOWS_NAMES.get(version.substring(0, 3)) ?? "unknown version"}`
|
|
152
97
|
}
|
|
153
98
|
|
|
154
99
|
/**
|
|
@@ -173,79 +118,35 @@ function parseOsRelease(content: string): Record<string, string> {
|
|
|
173
118
|
*
|
|
174
119
|
* @example
|
|
175
120
|
* ```ts
|
|
176
|
-
* import { osRelease } from "@darthcav/ts-utils"
|
|
121
|
+
* import { asString, osRelease } from "@darthcav/ts-utils"
|
|
177
122
|
*
|
|
178
123
|
* const info = osRelease()
|
|
179
|
-
* if (info)
|
|
180
|
-
*
|
|
124
|
+
* if (info) {
|
|
125
|
+
* console.log(info.name) // e.g. "Ubuntu", "macOS", or "Windows 11"
|
|
126
|
+
* // Raw keys are `unknown`; narrow them before use.
|
|
127
|
+
* const prettyName = asString(info["PRETTY_NAME"]) // e.g. "Ubuntu 24.04 LTS" (Linux only)
|
|
128
|
+
* }
|
|
181
129
|
* ```
|
|
182
130
|
*/
|
|
183
131
|
export function osRelease(): OsRelease | null {
|
|
184
132
|
const p = platform()
|
|
185
|
-
if (p === "linux") {
|
|
186
|
-
const content = readFirstFile(OS_RELEASE_FILES)
|
|
187
|
-
if (content === null) {
|
|
188
|
-
return null
|
|
189
|
-
}
|
|
190
|
-
const raw = parseOsRelease(content)
|
|
191
|
-
return {
|
|
192
|
-
...raw,
|
|
193
|
-
name: raw["NAME"] ?? raw["PRETTY_NAME"] ?? "",
|
|
194
|
-
version: raw["VERSION_ID"] ?? raw["VERSION"] ?? "",
|
|
195
|
-
arch: arch(),
|
|
196
|
-
}
|
|
197
|
-
}
|
|
198
|
-
if (p === "darwin") {
|
|
199
|
-
const content = readFirstFile([MACOS_SYSTEM_VERSION_FILE])
|
|
200
|
-
if (content === null) {
|
|
201
|
-
return null
|
|
202
|
-
}
|
|
203
|
-
const raw = parsePlistStrings(content)
|
|
204
|
-
return {
|
|
205
|
-
...raw,
|
|
206
|
-
name: raw["ProductName"] || "macOS",
|
|
207
|
-
version: raw["ProductVersion"] ?? "",
|
|
208
|
-
arch: arch(),
|
|
209
|
-
}
|
|
210
|
-
}
|
|
211
133
|
if (p === "win32") {
|
|
212
134
|
const version = kernelRelease()
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
name += "7"
|
|
230
|
-
break
|
|
231
|
-
case "6.0":
|
|
232
|
-
name += "Vista"
|
|
233
|
-
break
|
|
234
|
-
case "5.2":
|
|
235
|
-
name += "XP 64-Bit Edition"
|
|
236
|
-
break
|
|
237
|
-
case "5.1":
|
|
238
|
-
name += "XP"
|
|
239
|
-
break
|
|
240
|
-
case "5.0":
|
|
241
|
-
name += "2000"
|
|
242
|
-
break
|
|
243
|
-
default:
|
|
244
|
-
name += "unknown version"
|
|
245
|
-
break
|
|
246
|
-
}
|
|
247
|
-
}
|
|
248
|
-
return { name, version, arch: arch() }
|
|
135
|
+
return { name: windowsName(version), version, arch: arch() }
|
|
136
|
+
}
|
|
137
|
+
const source = RELEASE_FILES[p]
|
|
138
|
+
if (source === undefined) {
|
|
139
|
+
return null
|
|
140
|
+
}
|
|
141
|
+
const content = readFirstFile(source.files)
|
|
142
|
+
if (content === null) {
|
|
143
|
+
return null
|
|
144
|
+
}
|
|
145
|
+
const raw = source.parse(content)
|
|
146
|
+
return {
|
|
147
|
+
...raw,
|
|
148
|
+
name: source.name(raw),
|
|
149
|
+
version: source.version(raw),
|
|
150
|
+
arch: arch(),
|
|
249
151
|
}
|
|
250
|
-
return null
|
|
251
152
|
}
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
// Parsers for the OS release files read by `osRelease()`. Internal: the `node`
|
|
2
|
+
// entry point does not re-export them, so they are tested directly.
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Valid os-release keys: shell-compatible, upper-case variable names. This
|
|
6
|
+
* also rules out keys such as `__proto__` or `constructor`.
|
|
7
|
+
*/
|
|
8
|
+
const OS_RELEASE_KEY = /^[A-Z][A-Z0-9_]*$/
|
|
9
|
+
|
|
10
|
+
/** A `<key>…</key>` followed by a `<string>…</string>` value in a plist. */
|
|
11
|
+
const PLIST_STRING_ENTRY = /<key>([^<]*)<\/key>\s*<string>([^<]*)<\/string>/g
|
|
12
|
+
|
|
13
|
+
/** Valid plist keys to copy; this also rules out keys such as `__proto__`. */
|
|
14
|
+
const PLIST_KEY = /^[A-Za-z][A-Za-z0-9_]*$/
|
|
15
|
+
|
|
16
|
+
/** The predefined XML entities. */
|
|
17
|
+
const XML_ENTITIES: ReadonlyMap<string, string> = new Map([
|
|
18
|
+
["amp", "&"],
|
|
19
|
+
["apos", "'"],
|
|
20
|
+
["gt", ">"],
|
|
21
|
+
["lt", "<"],
|
|
22
|
+
["quot", '"'],
|
|
23
|
+
])
|
|
24
|
+
|
|
25
|
+
/** Decodes the predefined and numeric character references of XML text. */
|
|
26
|
+
function decodeXml(text: string): string {
|
|
27
|
+
return text.replace(
|
|
28
|
+
/&(?:#x([0-9a-fA-F]+)|#([0-9]+)|([a-z]+));/g,
|
|
29
|
+
(
|
|
30
|
+
match: string,
|
|
31
|
+
hex: string | undefined,
|
|
32
|
+
decimal: string | undefined,
|
|
33
|
+
// Set when neither `hex` nor `decimal` is: one group always matches.
|
|
34
|
+
name: string,
|
|
35
|
+
) => {
|
|
36
|
+
const codePoint =
|
|
37
|
+
hex !== undefined
|
|
38
|
+
? Number.parseInt(hex, 16)
|
|
39
|
+
: decimal !== undefined
|
|
40
|
+
? Number.parseInt(decimal, 10)
|
|
41
|
+
: undefined
|
|
42
|
+
if (codePoint === undefined) {
|
|
43
|
+
return XML_ENTITIES.get(name) ?? match
|
|
44
|
+
}
|
|
45
|
+
return codePoint <= 0x10ffff
|
|
46
|
+
? String.fromCodePoint(codePoint)
|
|
47
|
+
: match
|
|
48
|
+
},
|
|
49
|
+
)
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Removes one level of shell-style quoting from an os-release value. Double
|
|
54
|
+
* quotes allow the `\\`, `\"`, `` \` `` and `\$` escapes; single quotes are
|
|
55
|
+
* literal.
|
|
56
|
+
*/
|
|
57
|
+
function unquote(value: string): string {
|
|
58
|
+
if (value.length >= 2) {
|
|
59
|
+
const quote = value[0]
|
|
60
|
+
if (quote === '"' && value.endsWith('"')) {
|
|
61
|
+
return value.slice(1, -1).replace(/\\([\\"`$])/g, "$1")
|
|
62
|
+
}
|
|
63
|
+
if (quote === "'" && value.endsWith("'")) {
|
|
64
|
+
return value.slice(1, -1)
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
return value
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* Parses os-release content into a null-prototype record, skipping blank
|
|
72
|
+
* lines, comments, lines without `=`, and invalid keys.
|
|
73
|
+
*/
|
|
74
|
+
export function parseOsRelease(content: string): Record<string, string> {
|
|
75
|
+
const raw: Record<string, string> = Object.create(null)
|
|
76
|
+
for (const line of content.split("\n")) {
|
|
77
|
+
const trimmed = line.trim()
|
|
78
|
+
if (trimmed === "" || trimmed.startsWith("#")) {
|
|
79
|
+
continue
|
|
80
|
+
}
|
|
81
|
+
const eq = trimmed.indexOf("=")
|
|
82
|
+
if (eq === -1) {
|
|
83
|
+
continue
|
|
84
|
+
}
|
|
85
|
+
const key = trimmed.substring(0, eq).trim()
|
|
86
|
+
if (!OS_RELEASE_KEY.test(key)) {
|
|
87
|
+
continue
|
|
88
|
+
}
|
|
89
|
+
raw[key] = unquote(trimmed.substring(eq + 1).trim())
|
|
90
|
+
}
|
|
91
|
+
return raw
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* Parses the `<string>` entries of an XML property list into a
|
|
96
|
+
* null-prototype record, skipping other value types and invalid keys.
|
|
97
|
+
*/
|
|
98
|
+
export function parsePlistStrings(content: string): Record<string, string> {
|
|
99
|
+
const raw: Record<string, string> = Object.create(null)
|
|
100
|
+
for (const [, rawKey = "", value = ""] of content.matchAll(
|
|
101
|
+
PLIST_STRING_ENTRY,
|
|
102
|
+
)) {
|
|
103
|
+
const key = decodeXml(rawKey.trim())
|
|
104
|
+
if (PLIST_KEY.test(key)) {
|
|
105
|
+
raw[key] = decodeXml(value.trim())
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
return raw
|
|
109
|
+
}
|