@darthcav/ts-utils 0.10.4 → 0.10.6

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 CHANGED
@@ -30,7 +30,8 @@ npm install @darthcav/ts-utils
30
30
 
31
31
  Configures logging and returns a `Logger` for the given category name. Records at or above
32
32
  `lowestLevel` are written to the console using an ANSI color formatter with RFC 3339 timestamps. The
33
- internal `logtape/meta` logger is silenced.
33
+ internal `logtape/meta` logger is silenced. The function is safe to call more than once — each call
34
+ reconfigures logtape from scratch (the most recent call wins).
34
35
 
35
36
  ```ts
36
37
  import { getConsoleLogger, main } from "@darthcav/ts-utils"
@@ -69,8 +70,9 @@ main("my-app", logger, () => {
69
70
 
70
71
  Converts a duration in milliseconds to a human-readable string via `Intl.DurationFormat`. Sub-second
71
72
  values are rounded to the nearest second, and any zero-valued components are omitted — so a
72
- zero-millisecond input returns an empty string. An optional BCP 47 locale tag (default `"en"`)
73
- controls the unit labels.
73
+ zero-millisecond input returns an empty string. Negative durations are formatted from their
74
+ magnitude and prefixed with `"-"`. An optional BCP 47 locale tag (default `"en"`) controls the unit
75
+ labels. Throws a `RangeError` if `ms` is not finite or `locale` is not a valid BCP 47 tag.
74
76
 
75
77
  ```ts
76
78
  import { millisecondsToString } from "@darthcav/ts-utils"
@@ -78,6 +80,7 @@ import { millisecondsToString } from "@darthcav/ts-utils"
78
80
  millisecondsToString(3_661_000) // "1h 1m 1s"
79
81
  millisecondsToString(90_000) // "1m 30s"
80
82
  millisecondsToString(5_000) // "5s"
83
+ millisecondsToString(-90_000) // "-1m 30s"
81
84
  millisecondsToString(90_061_000, "es") // "1d 1h 1min 1s"
82
85
  ```
83
86
 
@@ -213,7 +216,7 @@ public/ # Documentation output (generated)
213
216
 
214
217
  [node-version]: https://img.shields.io/badge/node-%3E%3D26-orange.svg?style=flat-square
215
218
  [node-url]: https://nodejs.org
216
- [version-image]: https://img.shields.io/badge/version-0.10.4-blue.svg?style=flat-square
219
+ [version-image]: https://img.shields.io/badge/version-0.10.6-blue.svg?style=flat-square
217
220
  [ci-badge]: https://github.com/darthcav/ts-utils/actions/workflows/tests.yml/badge.svg
218
221
  [coverage-badge]:
219
222
  https://codecov.io/github/darthcav/ts-utils/branch/dev/graph/badge.svg?token=RNEPER4KEI
@@ -6,6 +6,11 @@ import { type Logger, type LogLevel } from "@logtape/logtape";
6
6
  * color formatter with RFC 3339 timestamps. The internal `logtape/meta` logger
7
7
  * is silenced.
8
8
  *
9
+ * Logging is configured with `reset: true`, so this function is safe to call
10
+ * more than once: each call reconfigures logtape from scratch and the most
11
+ * recent call wins. (Without it, logtape throws because logging is already
12
+ * configured.)
13
+ *
9
14
  * @param name - The top-level category name (typically the application name).
10
15
  * @param lowestLevel - The minimum log level to output. Defaults to `"info"`.
11
16
  * @returns A promise resolving to a logger scoped to the given category.
@@ -1 +1 @@
1
- {"version":3,"file":"getConsoleLogger.d.ts","sourceRoot":"","sources":["../../src/loggers/getConsoleLogger.ts"],"names":[],"mappings":"AAAA,OAAO,EAKH,KAAK,MAAM,EACX,KAAK,QAAQ,EAChB,MAAM,kBAAkB,CAAA;AAEzB;;;;;;;;;;GAUG;AACH,wBAA8B,gBAAgB,CAC1C,IAAI,EAAE,MAAM,EACZ,WAAW,GAAE,QAAiB,GAC/B,OAAO,CAAC,MAAM,CAAC,CAoBjB"}
1
+ {"version":3,"file":"getConsoleLogger.d.ts","sourceRoot":"","sources":["../../src/loggers/getConsoleLogger.ts"],"names":[],"mappings":"AAAA,OAAO,EAKH,KAAK,MAAM,EACX,KAAK,QAAQ,EAChB,MAAM,kBAAkB,CAAA;AAEzB;;;;;;;;;;;;;;;GAeG;AACH,wBAA8B,gBAAgB,CAC1C,IAAI,EAAE,MAAM,EACZ,WAAW,GAAE,QAAiB,GAC/B,OAAO,CAAC,MAAM,CAAC,CAqBjB"}
@@ -6,6 +6,11 @@ import { configure, getAnsiColorFormatter, getConsoleSink, getLogger, } from "@l
6
6
  * color formatter with RFC 3339 timestamps. The internal `logtape/meta` logger
7
7
  * is silenced.
8
8
  *
9
+ * Logging is configured with `reset: true`, so this function is safe to call
10
+ * more than once: each call reconfigures logtape from scratch and the most
11
+ * recent call wins. (Without it, logtape throws because logging is already
12
+ * configured.)
13
+ *
9
14
  * @param name - The top-level category name (typically the application name).
10
15
  * @param lowestLevel - The minimum log level to output. Defaults to `"info"`.
11
16
  * @returns A promise resolving to a logger scoped to the given category.
@@ -28,6 +33,7 @@ export default async function getConsoleLogger(name, lowestLevel = "info") {
28
33
  parentSinks: "override",
29
34
  },
30
35
  ],
36
+ reset: true,
31
37
  });
32
38
  return getLogger([name]);
33
39
  }
@@ -1 +1 @@
1
- {"version":3,"file":"getConsoleLogger.js","sourceRoot":"","sources":["../../src/loggers/getConsoleLogger.ts"],"names":[],"mappings":"AAAA,OAAO,EACH,SAAS,EACT,qBAAqB,EACrB,cAAc,EACd,SAAS,GAGZ,MAAM,kBAAkB,CAAA;AAEzB;;;;;;;;;;GAUG;AACH,MAAM,CAAC,OAAO,CAAC,KAAK,UAAU,gBAAgB,CAC1C,IAAY,EACZ,cAAwB,MAAM;IAE9B,MAAM,SAAS,CAAC;QACZ,KAAK,EAAE;YACH,OAAO,EAAE,cAAc,CAAC;gBACpB,SAAS,EAAE,qBAAqB,CAAC;oBAC7B,SAAS,EAAE,SAAS;oBACpB,KAAK,EAAE,MAAM;iBAChB,CAAC;aACL,CAAC;SACL;QACD,OAAO,EAAE;YACL,EAAE,QAAQ,EAAE,EAAE,EAAE,KAAK,EAAE,CAAC,SAAS,CAAC,EAAE,WAAW,EAAE;YACjD;gBACI,QAAQ,EAAE,CAAC,SAAS,EAAE,MAAM,CAAC;gBAC7B,KAAK,EAAE,EAAE;gBACT,WAAW,EAAE,UAAU;aAC1B;SACJ;KACJ,CAAC,CAAA;IACF,OAAO,SAAS,CAAC,CAAC,IAAI,CAAC,CAAC,CAAA;AAC5B,CAAC"}
1
+ {"version":3,"file":"getConsoleLogger.js","sourceRoot":"","sources":["../../src/loggers/getConsoleLogger.ts"],"names":[],"mappings":"AAAA,OAAO,EACH,SAAS,EACT,qBAAqB,EACrB,cAAc,EACd,SAAS,GAGZ,MAAM,kBAAkB,CAAA;AAEzB;;;;;;;;;;;;;;;GAeG;AACH,MAAM,CAAC,OAAO,CAAC,KAAK,UAAU,gBAAgB,CAC1C,IAAY,EACZ,cAAwB,MAAM;IAE9B,MAAM,SAAS,CAAC;QACZ,KAAK,EAAE;YACH,OAAO,EAAE,cAAc,CAAC;gBACpB,SAAS,EAAE,qBAAqB,CAAC;oBAC7B,SAAS,EAAE,SAAS;oBACpB,KAAK,EAAE,MAAM;iBAChB,CAAC;aACL,CAAC;SACL;QACD,OAAO,EAAE;YACL,EAAE,QAAQ,EAAE,EAAE,EAAE,KAAK,EAAE,CAAC,SAAS,CAAC,EAAE,WAAW,EAAE;YACjD;gBACI,QAAQ,EAAE,CAAC,SAAS,EAAE,MAAM,CAAC;gBAC7B,KAAK,EAAE,EAAE;gBACT,WAAW,EAAE,UAAU;aAC1B;SACJ;QACD,KAAK,EAAE,IAAI;KACd,CAAC,CAAA;IACF,OAAO,SAAS,CAAC,CAAC,IAAI,CAAC,CAAC,CAAA;AAC5B,CAAC"}
package/dist/main.js CHANGED
@@ -26,28 +26,28 @@ export function main(name, logger, arg3, arg4, arg5) {
26
26
  defaultInterruptionHandler = arg3;
27
27
  }
28
28
  const __logger = logger.getChild(["main"]);
29
- __logger.info(`Main process launched [${title} :: ${pid}]`);
30
- __logger.info(`Process name: ${name}`);
31
- __logger.info(`Node.js environment: ${env["NODE_ENV"] ?? ""}`);
32
- __logger.info(`Node.js process options: ${execArgv.concat(env["NODE_OPTIONS"] ?? []).join(" | ")}`);
29
+ __logger.info `Main process launched [${title} :: ${pid}]`;
30
+ __logger.info `Process name: ${name}`;
31
+ __logger.info `Node.js environment: ${env["NODE_ENV"] ?? ""}`;
32
+ __logger.info `Node.js process options: ${execArgv.concat(env["NODE_OPTIONS"] ?? []).join(" | ")}`;
33
33
  if (monitorMemoryHours > 0) {
34
34
  monitorMemory(__logger, monitorMemoryHours);
35
35
  }
36
36
  if (defaultInterruptionHandler) {
37
37
  for (const signal of ["SIGINT", "SIGTERM"]) {
38
38
  process.on(signal, (signal) => {
39
- __logger.error(`Process interrupted. Received signal: ${signal}`);
39
+ __logger.error `Process interrupted. Received signal: ${signal}`;
40
40
  process.exit(0);
41
41
  });
42
42
  }
43
43
  }
44
44
  process.on("uncaughtException", (error, origin) => {
45
- __logger.error(`Uncaught exception: ${error instanceof Error ? (error.stack ?? String(error)) : String(error)}`);
46
- __logger.error(`Exception origin: ${origin}`);
45
+ __logger.error `Uncaught exception: ${error instanceof Error ? (error.stack ?? String(error)) : String(error)}`;
46
+ __logger.error `Exception origin: ${origin}`;
47
47
  process.exit(1);
48
48
  });
49
49
  process.on("unhandledRejection", (reason) => {
50
- __logger.error(`Unhandled promise rejection. Reason:\n${reason instanceof Error ? (reason.stack ?? String(reason)) : String(reason)}`);
50
+ __logger.error `Unhandled promise rejection. Reason:\n${reason instanceof Error ? (reason.stack ?? String(reason)) : String(reason)}`;
51
51
  process.exit(1);
52
52
  });
53
53
  launcher?.();
package/dist/main.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"main.js","sourceRoot":"","sources":["../src/main.ts"],"names":[],"mappings":"AAAA,OAAO,OAAO,EAAE,EAAE,GAAG,EAAE,QAAQ,EAAE,GAAG,EAAE,KAAK,EAAE,MAAM,cAAc,CAAA;AAEjE,OAAO,aAAa,MAAM,oBAAoB,CAAA;AA8G9C,MAAM,UAAU,IAAI,CAChB,IAAY,EACZ,MAAc,EACd,IAA0C,EAC1C,IAAuB,EACvB,IAAc;IAEd,IAAI,QAAsC,CAAA;IAC1C,IAAI,kBAAkB,GAAG,CAAC,CAAA;IAC1B,IAAI,0BAA0B,GAAG,IAAI,CAAA;IAErC,IAAI,OAAO,IAAI,KAAK,UAAU,EAAE,CAAC;QAC7B,QAAQ,GAAG,IAAI,CAAA;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CAAA;IAEF,QAAQ,EAAE,EAAE,CAAA;AAChB,CAAC"}
@@ -4,18 +4,22 @@
4
4
  *
5
5
  * Sub-second values are rounded to the nearest second. Any zero-valued
6
6
  * components are omitted from the formatted output, so a zero-millisecond
7
- * input produces an empty string.
7
+ * input produces an empty string. Negative durations are formatted from their
8
+ * magnitude and prefixed with `"-"` (e.g. `-90_000` → `"-1m 30s"`).
8
9
  *
9
- * @param ms - Duration in milliseconds.
10
+ * @param ms - Duration in milliseconds. Must be a finite number.
10
11
  * @param locale - BCP 47 locale tag passed to `Intl.DurationFormat`. Defaults
11
12
  * to `"en"`.
12
13
  * @returns A formatted duration string.
14
+ * @throws {RangeError} If `ms` is not finite (`NaN`, `Infinity`, `-Infinity`)
15
+ * or `locale` is not a valid BCP 47 language tag.
13
16
  *
14
17
  * @example
15
18
  * ```ts
16
19
  * millisecondsToString(3_661_000) // "1h 1m 1s"
17
20
  * millisecondsToString(90_000) // "1m 30s"
18
21
  * millisecondsToString(5_000) // "5s"
22
+ * millisecondsToString(-90_000) // "-1m 30s"
19
23
  * millisecondsToString(90_061_000, "es") // "1d 1h 1min 1s"
20
24
  * ```
21
25
  */
@@ -1 +1 @@
1
- {"version":3,"file":"millisecondsToString.d.ts","sourceRoot":"","sources":["../src/millisecondsToString.ts"],"names":[],"mappings":"AAcA;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,MAAM,CAAC,OAAO,UAAU,oBAAoB,CACxC,EAAE,EAAE,MAAM,EACV,MAAM,SAAO,GACd,MAAM,CASR"}
1
+ {"version":3,"file":"millisecondsToString.d.ts","sourceRoot":"","sources":["../src/millisecondsToString.ts"],"names":[],"mappings":"AAqBA;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AACH,MAAM,CAAC,OAAO,UAAU,oBAAoB,CACxC,EAAE,EAAE,MAAM,EACV,MAAM,SAAO,GACd,MAAM,CAkBR"}
@@ -2,9 +2,14 @@ const durationFormatters = new Map();
2
2
  function getDurationFormatter(locale) {
3
3
  let formatter = durationFormatters.get(locale);
4
4
  if (formatter === undefined) {
5
- formatter = new Intl.DurationFormat(locale, {
6
- style: "narrow",
7
- });
5
+ try {
6
+ formatter = new Intl.DurationFormat(locale, {
7
+ style: "narrow",
8
+ });
9
+ }
10
+ catch (cause) {
11
+ throw new RangeError(`millisecondsToString: invalid locale "${locale}"`, { cause });
12
+ }
8
13
  durationFormatters.set(locale, formatter);
9
14
  }
10
15
  return formatter;
@@ -15,28 +20,37 @@ function getDurationFormatter(locale) {
15
20
  *
16
21
  * Sub-second values are rounded to the nearest second. Any zero-valued
17
22
  * components are omitted from the formatted output, so a zero-millisecond
18
- * input produces an empty string.
23
+ * input produces an empty string. Negative durations are formatted from their
24
+ * magnitude and prefixed with `"-"` (e.g. `-90_000` → `"-1m 30s"`).
19
25
  *
20
- * @param ms - Duration in milliseconds.
26
+ * @param ms - Duration in milliseconds. Must be a finite number.
21
27
  * @param locale - BCP 47 locale tag passed to `Intl.DurationFormat`. Defaults
22
28
  * to `"en"`.
23
29
  * @returns A formatted duration string.
30
+ * @throws {RangeError} If `ms` is not finite (`NaN`, `Infinity`, `-Infinity`)
31
+ * or `locale` is not a valid BCP 47 language tag.
24
32
  *
25
33
  * @example
26
34
  * ```ts
27
35
  * millisecondsToString(3_661_000) // "1h 1m 1s"
28
36
  * millisecondsToString(90_000) // "1m 30s"
29
37
  * millisecondsToString(5_000) // "5s"
38
+ * millisecondsToString(-90_000) // "-1m 30s"
30
39
  * millisecondsToString(90_061_000, "es") // "1d 1h 1min 1s"
31
40
  * ```
32
41
  */
33
42
  export default function millisecondsToString(ms, locale = "en") {
43
+ if (!Number.isFinite(ms)) {
44
+ throw new RangeError(`millisecondsToString: "ms" must be a finite number, received ${ms}`);
45
+ }
34
46
  const totalSeconds = Math.round(ms / 1000);
35
- return getDurationFormatter(locale).format({
36
- days: Math.floor(totalSeconds / 86400),
37
- hours: Math.floor((totalSeconds % 86400) / 3600),
38
- minutes: Math.floor((totalSeconds % 3600) / 60),
39
- seconds: totalSeconds % 60,
47
+ const magnitude = Math.abs(totalSeconds);
48
+ const formatted = getDurationFormatter(locale).format({
49
+ days: Math.floor(magnitude / 86400),
50
+ hours: Math.floor((magnitude % 86400) / 3600),
51
+ minutes: Math.floor((magnitude % 3600) / 60),
52
+ seconds: magnitude % 60,
40
53
  });
54
+ return totalSeconds < 0 && formatted ? `-${formatted}` : formatted;
41
55
  }
42
56
  //# sourceMappingURL=millisecondsToString.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"millisecondsToString.js","sourceRoot":"","sources":["../src/millisecondsToString.ts"],"names":[],"mappings":"AAAA,MAAM,kBAAkB,GAAG,IAAI,GAAG,EAA+B,CAAA;AAEjE,SAAS,oBAAoB,CAAC,MAAc;IACxC,IAAI,SAAS,GAAG,kBAAkB,CAAC,GAAG,CAAC,MAAM,CAAC,CAAA;IAC9C,IAAI,SAAS,KAAK,SAAS,EAAE,CAAC;QAC1B,SAAS,GAAG,IAAI,IAAI,CAAC,cAAc,CAAC,MAAM,EAAE;YACxC,KAAK,EAAE,QAAQ;SAClB,CAAC,CAAA;QACF,kBAAkB,CAAC,GAAG,CAAC,MAAM,EAAE,SAAS,CAAC,CAAA;IAC7C,CAAC;IAED,OAAO,SAAS,CAAA;AACpB,CAAC;AAED;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,MAAM,CAAC,OAAO,UAAU,oBAAoB,CACxC,EAAU,EACV,MAAM,GAAG,IAAI;IAEb,MAAM,YAAY,GAAG,IAAI,CAAC,KAAK,CAAC,EAAE,GAAG,IAAI,CAAC,CAAA;IAE1C,OAAO,oBAAoB,CAAC,MAAM,CAAC,CAAC,MAAM,CAAC;QACvC,IAAI,EAAE,IAAI,CAAC,KAAK,CAAC,YAAY,GAAG,KAAK,CAAC;QACtC,KAAK,EAAE,IAAI,CAAC,KAAK,CAAC,CAAC,YAAY,GAAG,KAAK,CAAC,GAAG,IAAI,CAAC;QAChD,OAAO,EAAE,IAAI,CAAC,KAAK,CAAC,CAAC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,EAAE,IAAI,CAAC,KAAK,CAAC,SAAS,GAAG,KAAK,CAAC;QACnC,KAAK,EAAE,IAAI,CAAC,KAAK,CAAC,CAAC,SAAS,GAAG,KAAK,CAAC,GAAG,IAAI,CAAC;QAC7C,OAAO,EAAE,IAAI,CAAC,KAAK,CAAC,CAAC,SAAS,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC;QAC5C,OAAO,EAAE,SAAS,GAAG,EAAE;KAC1B,CAAC,CAAA;IAEF,OAAO,YAAY,GAAG,CAAC,IAAI,SAAS,CAAC,CAAC,CAAC,IAAI,SAAS,EAAE,CAAC,CAAC,CAAC,SAAS,CAAA;AACtE,CAAC"}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@darthcav/ts-utils",
3
3
  "description": "A collection of utility functions for TypeScript applications and modules",
4
- "version": "0.10.4",
4
+ "version": "0.10.6",
5
5
  "author": {
6
6
  "name": "darthcav",
7
7
  "url": "https://github.com/darthcav"
@@ -24,13 +24,13 @@
24
24
  "!dist/__tests__"
25
25
  ],
26
26
  "dependencies": {
27
- "@logtape/logtape": "2.1.1"
27
+ "@logtape/logtape": "2.1.4"
28
28
  },
29
29
  "devDependencies": {
30
- "@biomejs/biome": "2.4.15",
31
- "@types/node": "25.9.1",
30
+ "@biomejs/biome": "2.5.0",
31
+ "@types/node": "25.9.3",
32
32
  "asserttt": "1.0.1",
33
- "prettier": "3.8.3",
33
+ "prettier": "3.8.4",
34
34
  "shx": "0.4.0",
35
35
  "typedoc": "0.28.19"
36
36
  },
@@ -14,6 +14,11 @@ import {
14
14
  * color formatter with RFC 3339 timestamps. The internal `logtape/meta` logger
15
15
  * is silenced.
16
16
  *
17
+ * Logging is configured with `reset: true`, so this function is safe to call
18
+ * more than once: each call reconfigures logtape from scratch and the most
19
+ * recent call wins. (Without it, logtape throws because logging is already
20
+ * configured.)
21
+ *
17
22
  * @param name - The top-level category name (typically the application name).
18
23
  * @param lowestLevel - The minimum log level to output. Defaults to `"info"`.
19
24
  * @returns A promise resolving to a logger scoped to the given category.
@@ -39,6 +44,7 @@ export default async function getConsoleLogger(
39
44
  parentSinks: "override",
40
45
  },
41
46
  ],
47
+ reset: true,
42
48
  })
43
49
  return getLogger([name])
44
50
  }
package/src/main.ts CHANGED
@@ -142,12 +142,10 @@ export function main(
142
142
 
143
143
  const __logger = logger.getChild(["main"])
144
144
 
145
- __logger.info(`Main process launched [${title} :: ${pid}]`)
146
- __logger.info(`Process name: ${name}`)
147
- __logger.info(`Node.js environment: ${env["NODE_ENV"] ?? ""}`)
148
- __logger.info(
149
- `Node.js process options: ${execArgv.concat(env["NODE_OPTIONS"] ?? []).join(" | ")}`,
150
- )
145
+ __logger.info`Main process launched [${title} :: ${pid}]`
146
+ __logger.info`Process name: ${name}`
147
+ __logger.info`Node.js environment: ${env["NODE_ENV"] ?? ""}`
148
+ __logger.info`Node.js process options: ${execArgv.concat(env["NODE_OPTIONS"] ?? []).join(" | ")}`
151
149
 
152
150
  if (monitorMemoryHours > 0) {
153
151
  monitorMemory(__logger, monitorMemoryHours)
@@ -156,26 +154,20 @@ export function main(
156
154
  if (defaultInterruptionHandler) {
157
155
  for (const signal of ["SIGINT", "SIGTERM"] as const) {
158
156
  process.on(signal, (signal) => {
159
- __logger.error(
160
- `Process interrupted. Received signal: ${signal}`,
161
- )
157
+ __logger.error`Process interrupted. Received signal: ${signal}`
162
158
  process.exit(0)
163
159
  })
164
160
  }
165
161
  }
166
162
 
167
163
  process.on("uncaughtException", (error, origin) => {
168
- __logger.error(
169
- `Uncaught exception: ${error instanceof Error ? (error.stack ?? String(error)) : String(error)}`,
170
- )
171
- __logger.error(`Exception origin: ${origin}`)
164
+ __logger.error`Uncaught exception: ${error instanceof Error ? (error.stack ?? String(error)) : String(error)}`
165
+ __logger.error`Exception origin: ${origin}`
172
166
  process.exit(1)
173
167
  })
174
168
 
175
169
  process.on("unhandledRejection", (reason) => {
176
- __logger.error(
177
- `Unhandled promise rejection. Reason:\n${reason instanceof Error ? (reason.stack ?? String(reason)) : String(reason)}`,
178
- )
170
+ __logger.error`Unhandled promise rejection. Reason:\n${reason instanceof Error ? (reason.stack ?? String(reason)) : String(reason)}`
179
171
  process.exit(1)
180
172
  })
181
173
 
@@ -3,9 +3,16 @@ const durationFormatters = new Map<string, Intl.DurationFormat>()
3
3
  function getDurationFormatter(locale: string): Intl.DurationFormat {
4
4
  let formatter = durationFormatters.get(locale)
5
5
  if (formatter === undefined) {
6
- formatter = new Intl.DurationFormat(locale, {
7
- style: "narrow",
8
- })
6
+ try {
7
+ formatter = new Intl.DurationFormat(locale, {
8
+ style: "narrow",
9
+ })
10
+ } catch (cause) {
11
+ throw new RangeError(
12
+ `millisecondsToString: invalid locale "${locale}"`,
13
+ { cause },
14
+ )
15
+ }
9
16
  durationFormatters.set(locale, formatter)
10
17
  }
11
18
 
@@ -18,18 +25,22 @@ function getDurationFormatter(locale: string): Intl.DurationFormat {
18
25
  *
19
26
  * Sub-second values are rounded to the nearest second. Any zero-valued
20
27
  * components are omitted from the formatted output, so a zero-millisecond
21
- * input produces an empty string.
28
+ * input produces an empty string. Negative durations are formatted from their
29
+ * magnitude and prefixed with `"-"` (e.g. `-90_000` → `"-1m 30s"`).
22
30
  *
23
- * @param ms - Duration in milliseconds.
31
+ * @param ms - Duration in milliseconds. Must be a finite number.
24
32
  * @param locale - BCP 47 locale tag passed to `Intl.DurationFormat`. Defaults
25
33
  * to `"en"`.
26
34
  * @returns A formatted duration string.
35
+ * @throws {RangeError} If `ms` is not finite (`NaN`, `Infinity`, `-Infinity`)
36
+ * or `locale` is not a valid BCP 47 language tag.
27
37
  *
28
38
  * @example
29
39
  * ```ts
30
40
  * millisecondsToString(3_661_000) // "1h 1m 1s"
31
41
  * millisecondsToString(90_000) // "1m 30s"
32
42
  * millisecondsToString(5_000) // "5s"
43
+ * millisecondsToString(-90_000) // "-1m 30s"
33
44
  * millisecondsToString(90_061_000, "es") // "1d 1h 1min 1s"
34
45
  * ```
35
46
  */
@@ -37,12 +48,21 @@ export default function millisecondsToString(
37
48
  ms: number,
38
49
  locale = "en",
39
50
  ): string {
51
+ if (!Number.isFinite(ms)) {
52
+ throw new RangeError(
53
+ `millisecondsToString: "ms" must be a finite number, received ${ms}`,
54
+ )
55
+ }
56
+
40
57
  const totalSeconds = Math.round(ms / 1000)
58
+ const magnitude = Math.abs(totalSeconds)
41
59
 
42
- return getDurationFormatter(locale).format({
43
- days: Math.floor(totalSeconds / 86400),
44
- hours: Math.floor((totalSeconds % 86400) / 3600),
45
- minutes: Math.floor((totalSeconds % 3600) / 60),
46
- seconds: totalSeconds % 60,
60
+ const formatted = getDurationFormatter(locale).format({
61
+ days: Math.floor(magnitude / 86400),
62
+ hours: Math.floor((magnitude % 86400) / 3600),
63
+ minutes: Math.floor((magnitude % 3600) / 60),
64
+ seconds: magnitude % 60,
47
65
  })
66
+
67
+ return totalSeconds < 0 && formatted ? `-${formatted}` : formatted
48
68
  }