@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.
Files changed (40) hide show
  1. package/README.md +20 -10
  2. package/dist/core/guards.d.ts.map +1 -1
  3. package/dist/core/guards.js +4 -10
  4. package/dist/core/guards.js.map +1 -1
  5. package/dist/core/index.d.ts +2 -1
  6. package/dist/core/index.d.ts.map +1 -1
  7. package/dist/core/index.js +2 -1
  8. package/dist/core/index.js.map +1 -1
  9. package/dist/core/millisecondsToString.d.ts.map +1 -1
  10. package/dist/core/millisecondsToString.js +6 -10
  11. package/dist/core/millisecondsToString.js.map +1 -1
  12. package/dist/node/delays.d.ts +11 -0
  13. package/dist/node/delays.d.ts.map +1 -0
  14. package/dist/node/delays.js +14 -0
  15. package/dist/node/delays.js.map +1 -0
  16. package/dist/node/main.d.ts +5 -3
  17. package/dist/node/main.d.ts.map +1 -1
  18. package/dist/node/main.js +34 -40
  19. package/dist/node/main.js.map +1 -1
  20. package/dist/node/monitorMemory.d.ts +11 -0
  21. package/dist/node/monitorMemory.d.ts.map +1 -1
  22. package/dist/node/monitorMemory.js +18 -9
  23. package/dist/node/monitorMemory.js.map +1 -1
  24. package/dist/node/osRelease.d.ts +6 -3
  25. package/dist/node/osRelease.d.ts.map +1 -1
  26. package/dist/node/osRelease.js +60 -155
  27. package/dist/node/osRelease.js.map +1 -1
  28. package/dist/node/releaseParsers.d.ts +11 -0
  29. package/dist/node/releaseParsers.d.ts.map +1 -0
  30. package/dist/node/releaseParsers.js +92 -0
  31. package/dist/node/releaseParsers.js.map +1 -0
  32. package/package.json +9 -7
  33. package/src/core/guards.ts +7 -11
  34. package/src/core/index.ts +2 -1
  35. package/src/core/millisecondsToString.ts +6 -12
  36. package/src/node/delays.ts +15 -0
  37. package/src/node/main.ts +46 -54
  38. package/src/node/monitorMemory.ts +20 -11
  39. package/src/node/osRelease.ts +72 -171
  40. package/src/node/releaseParsers.ts +109 -0
@@ -1,29 +1,39 @@
1
1
  import { readFileSync } from "node:fs";
2
2
  import { arch, release as kernelRelease, platform } from "node:os";
3
+ import { parseOsRelease, parsePlistStrings } from "./releaseParsers.js";
4
+ /** The platforms whose release information comes from a file. */
5
+ const RELEASE_FILES = {
6
+ linux: {
7
+ // Per the freedesktop.org spec, `/etc/os-release` takes precedence and
8
+ // `/usr/lib/os-release` is the fallback.
9
+ files: ["/etc/os-release", "/usr/lib/os-release"],
10
+ parse: parseOsRelease,
11
+ name: (raw) => raw["NAME"] ?? raw["PRETTY_NAME"] ?? "",
12
+ version: (raw) => raw["VERSION_ID"] ?? raw["VERSION"] ?? "",
13
+ },
14
+ darwin: {
15
+ files: ["/System/Library/CoreServices/SystemVersion.plist"],
16
+ parse: parsePlistStrings,
17
+ name: (raw) => raw["ProductName"] || "macOS",
18
+ version: (raw) => raw["ProductVersion"] ?? "",
19
+ },
20
+ };
3
21
  /**
4
- * Candidate os-release files, in lookup order. Per the freedesktop.org spec,
5
- * `/etc/os-release` takes precedence and `/usr/lib/os-release` is the fallback.
6
- */
7
- const OS_RELEASE_FILES = ["/etc/os-release", "/usr/lib/os-release"];
8
- /**
9
- * Valid os-release keys: shell-compatible, upper-case variable names. This
10
- * also rules out keys such as `__proto__` or `constructor`.
22
+ * Windows names by the first three characters of the kernel version. Windows
23
+ * 11 also reports `10.`, so it is told apart by build number.
11
24
  */
12
- const OS_RELEASE_KEY = /^[A-Z][A-Z0-9_]*$/;
13
- /** The macOS property list with the product name and version. */
14
- const MACOS_SYSTEM_VERSION_FILE = "/System/Library/CoreServices/SystemVersion.plist";
15
- /** A `<key>…</key>` followed by a `<string>…</string>` value in a plist. */
16
- const PLIST_STRING_ENTRY = /<key>([^<]*)<\/key>\s*<string>([^<]*)<\/string>/g;
17
- /** Valid plist keys to copy; this also rules out keys such as `__proto__`. */
18
- const PLIST_KEY = /^[A-Za-z][A-Za-z0-9_]*$/;
19
- /** The predefined XML entities. */
20
- const XML_ENTITIES = {
21
- amp: "&",
22
- apos: "'",
23
- gt: ">",
24
- lt: "<",
25
- quot: '"',
26
- };
25
+ const WINDOWS_NAMES = new Map([
26
+ ["10.", "10"],
27
+ ["6.3", "8.1"],
28
+ ["6.2", "8"],
29
+ ["6.1", "7"],
30
+ ["6.0", "Vista"],
31
+ ["5.2", "XP 64-Bit Edition"],
32
+ ["5.1", "XP"],
33
+ ["5.0", "2000"],
34
+ ]);
35
+ /** First Windows 11 build number. */
36
+ const WINDOWS_11_BUILD = 22000;
27
37
  /** Reads the first readable file of `files`, or returns `null` if none is. */
28
38
  function readFirstFile(files) {
29
39
  for (const file of files) {
@@ -36,73 +46,13 @@ function readFirstFile(files) {
36
46
  }
37
47
  return null;
38
48
  }
39
- /** Decodes the predefined and numeric character references of XML text. */
40
- function decodeXml(text) {
41
- return text.replace(/&(?:#x([0-9a-fA-F]+)|#([0-9]+)|([a-z]+));/g, (match, hex, decimal, name) => {
42
- if (hex !== undefined || decimal !== undefined) {
43
- const codePoint = Number.parseInt(hex ?? decimal ?? "", hex === undefined ? 10 : 16);
44
- return codePoint <= 0x10ffff
45
- ? String.fromCodePoint(codePoint)
46
- : match;
47
- }
48
- return ((name !== undefined && Object.hasOwn(XML_ENTITIES, name)
49
- ? XML_ENTITIES[name]
50
- : undefined) ?? match);
51
- });
52
- }
53
- /**
54
- * Parses the `<string>` entries of an XML property list into a
55
- * null-prototype record, skipping other value types and invalid keys.
56
- */
57
- function parsePlistStrings(content) {
58
- const raw = Object.create(null);
59
- for (const [, rawKey = "", value = ""] of content.matchAll(PLIST_STRING_ENTRY)) {
60
- const key = decodeXml(rawKey.trim());
61
- if (PLIST_KEY.test(key)) {
62
- raw[key] = decodeXml(value.trim());
63
- }
64
- }
65
- return raw;
66
- }
67
- /**
68
- * Removes one level of shell-style quoting from an os-release value. Double
69
- * quotes allow the `\\`, `\"`, `` \` `` and `\$` escapes; single quotes are
70
- * literal.
71
- */
72
- function unquote(value) {
73
- if (value.length >= 2) {
74
- const quote = value[0];
75
- if (quote === '"' && value.endsWith('"')) {
76
- return value.slice(1, -1).replace(/\\([\\"`$])/g, "$1");
77
- }
78
- if (quote === "'" && value.endsWith("'")) {
79
- return value.slice(1, -1);
80
- }
49
+ /** Maps a Windows kernel version (e.g. `"10.0.22000"`) to a product name. */
50
+ function windowsName(version) {
51
+ const [major, , build = 0] = version.split(".").map(Number);
52
+ if (major === 10 && build >= WINDOWS_11_BUILD) {
53
+ return "Windows 11";
81
54
  }
82
- return value;
83
- }
84
- /**
85
- * Parses os-release content into a null-prototype record, skipping blank
86
- * lines, comments, lines without `=`, and invalid keys.
87
- */
88
- function parseOsRelease(content) {
89
- const raw = Object.create(null);
90
- for (const line of content.split("\n")) {
91
- const trimmed = line.trim();
92
- if (trimmed === "" || trimmed.startsWith("#")) {
93
- continue;
94
- }
95
- const eq = trimmed.indexOf("=");
96
- if (eq === -1) {
97
- continue;
98
- }
99
- const key = trimmed.substring(0, eq).trim();
100
- if (!OS_RELEASE_KEY.test(key)) {
101
- continue;
102
- }
103
- raw[key] = unquote(trimmed.substring(eq + 1).trim());
104
- }
105
- return raw;
55
+ return `Windows ${WINDOWS_NAMES.get(version.substring(0, 3)) ?? "unknown version"}`;
106
56
  }
107
57
  /**
108
58
  * Returns OS release information for the current platform (Linux, macOS, or
@@ -126,81 +76,36 @@ function parseOsRelease(content) {
126
76
  *
127
77
  * @example
128
78
  * ```ts
129
- * import { osRelease } from "@darthcav/ts-utils"
79
+ * import { asString, osRelease } from "@darthcav/ts-utils"
130
80
  *
131
81
  * const info = osRelease()
132
- * if (info) console.log(info.name) // e.g. "Ubuntu", "macOS", or "Windows 11"
133
- * if (info) console.log(info.PRETTY_NAME) // e.g. "Ubuntu 24.04 LTS" (Linux only)
82
+ * if (info) {
83
+ * console.log(info.name) // e.g. "Ubuntu", "macOS", or "Windows 11"
84
+ * // Raw keys are `unknown`; narrow them before use.
85
+ * const prettyName = asString(info["PRETTY_NAME"]) // e.g. "Ubuntu 24.04 LTS" (Linux only)
86
+ * }
134
87
  * ```
135
88
  */
136
89
  export function osRelease() {
137
90
  const p = platform();
138
- if (p === "linux") {
139
- const content = readFirstFile(OS_RELEASE_FILES);
140
- if (content === null) {
141
- return null;
142
- }
143
- const raw = parseOsRelease(content);
144
- return {
145
- ...raw,
146
- name: raw["NAME"] ?? raw["PRETTY_NAME"] ?? "",
147
- version: raw["VERSION_ID"] ?? raw["VERSION"] ?? "",
148
- arch: arch(),
149
- };
150
- }
151
- if (p === "darwin") {
152
- const content = readFirstFile([MACOS_SYSTEM_VERSION_FILE]);
153
- if (content === null) {
154
- return null;
155
- }
156
- const raw = parsePlistStrings(content);
157
- return {
158
- ...raw,
159
- name: raw["ProductName"] || "macOS",
160
- version: raw["ProductVersion"] ?? "",
161
- arch: arch(),
162
- };
163
- }
164
91
  if (p === "win32") {
165
92
  const version = kernelRelease();
166
- const [major, , build] = version.split(".").map(Number);
167
- let name = "Windows ";
168
- if (major === 10 && (build ?? 0) >= 22000) {
169
- name += "11";
170
- }
171
- else {
172
- switch (version.substring(0, 3)) {
173
- case "10.":
174
- name += "10";
175
- break;
176
- case "6.3":
177
- name += "8.1";
178
- break;
179
- case "6.2":
180
- name += "8";
181
- break;
182
- case "6.1":
183
- name += "7";
184
- break;
185
- case "6.0":
186
- name += "Vista";
187
- break;
188
- case "5.2":
189
- name += "XP 64-Bit Edition";
190
- break;
191
- case "5.1":
192
- name += "XP";
193
- break;
194
- case "5.0":
195
- name += "2000";
196
- break;
197
- default:
198
- name += "unknown version";
199
- break;
200
- }
201
- }
202
- return { name, version, arch: arch() };
93
+ return { name: windowsName(version), version, arch: arch() };
203
94
  }
204
- return null;
95
+ const source = RELEASE_FILES[p];
96
+ if (source === undefined) {
97
+ return null;
98
+ }
99
+ const content = readFirstFile(source.files);
100
+ if (content === null) {
101
+ return null;
102
+ }
103
+ const raw = source.parse(content);
104
+ return {
105
+ ...raw,
106
+ name: source.name(raw),
107
+ version: source.version(raw),
108
+ arch: arch(),
109
+ };
205
110
  }
206
111
  //# sourceMappingURL=osRelease.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"osRelease.js","sourceRoot":"","sources":["../../src/node/osRelease.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,SAAS,CAAA;AACtC,OAAO,EAAE,IAAI,EAAE,OAAO,IAAI,aAAa,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAA;AA2BlE;;;GAGG;AACH,MAAM,gBAAgB,GAAG,CAAC,iBAAiB,EAAE,qBAAqB,CAAU,CAAA;AAE5E;;;GAGG;AACH,MAAM,cAAc,GAAG,mBAAmB,CAAA;AAE1C,iEAAiE;AACjE,MAAM,yBAAyB,GAC3B,kDAAkD,CAAA;AAEtD,4EAA4E;AAC5E,MAAM,kBAAkB,GAAG,kDAAkD,CAAA;AAE7E,8EAA8E;AAC9E,MAAM,SAAS,GAAG,yBAAyB,CAAA;AAE3C,mCAAmC;AACnC,MAAM,YAAY,GAAqC;IACnD,GAAG,EAAE,GAAG;IACR,IAAI,EAAE,GAAG;IACT,EAAE,EAAE,GAAG;IACP,EAAE,EAAE,GAAG;IACP,IAAI,EAAE,GAAG;CACZ,CAAA;AAED,8EAA8E;AAC9E,SAAS,aAAa,CAAC,KAAwB;IAC3C,KAAK,MAAM,IAAI,IAAI,KAAK,EAAE,CAAC;QACvB,IAAI,CAAC;YACD,OAAO,YAAY,CAAC,IAAI,EAAE,OAAO,CAAC,CAAA;QACtC,CAAC;QAAC,MAAM,CAAC;YACL,0BAA0B;QAC9B,CAAC;IACL,CAAC;IACD,OAAO,IAAI,CAAA;AACf,CAAC;AAED,2EAA2E;AAC3E,SAAS,SAAS,CAAC,IAAY;IAC3B,OAAO,IAAI,CAAC,OAAO,CACf,4CAA4C,EAC5C,CAAC,KAAK,EAAE,GAAY,EAAE,OAAgB,EAAE,IAAa,EAAE,EAAE;QACrD,IAAI,GAAG,KAAK,SAAS,IAAI,OAAO,KAAK,SAAS,EAAE,CAAC;YAC7C,MAAM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G;QACN,IAAI,EAAE,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC;QACtB,OAAO,EAAE,MAAM,CAAC,OAAO,CAAC,GAAG,CAAC;QAC5B,IAAI,EAAE,IAAI,EAAE;KACf,CAAA;AACL,CAAC"}
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Parses os-release content into a null-prototype record, skipping blank
3
+ * lines, comments, lines without `=`, and invalid keys.
4
+ */
5
+ export declare function parseOsRelease(content: string): Record<string, string>;
6
+ /**
7
+ * Parses the `<string>` entries of an XML property list into a
8
+ * null-prototype record, skipping other value types and invalid keys.
9
+ */
10
+ export declare function parsePlistStrings(content: string): Record<string, string>;
11
+ //# sourceMappingURL=releaseParsers.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"releaseParsers.d.ts","sourceRoot":"","sources":["../../src/node/releaseParsers.ts"],"names":[],"mappings":"AAqEA;;;GAGG;AACH,wBAAgB,cAAc,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAkBtE;AAED;;;GAGG;AACH,wBAAgB,iBAAiB,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAWzE"}
@@ -0,0 +1,92 @@
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
+ * Valid os-release keys: shell-compatible, upper-case variable names. This
5
+ * also rules out keys such as `__proto__` or `constructor`.
6
+ */
7
+ const OS_RELEASE_KEY = /^[A-Z][A-Z0-9_]*$/;
8
+ /** A `<key>…</key>` followed by a `<string>…</string>` value in a plist. */
9
+ const PLIST_STRING_ENTRY = /<key>([^<]*)<\/key>\s*<string>([^<]*)<\/string>/g;
10
+ /** Valid plist keys to copy; this also rules out keys such as `__proto__`. */
11
+ const PLIST_KEY = /^[A-Za-z][A-Za-z0-9_]*$/;
12
+ /** The predefined XML entities. */
13
+ const XML_ENTITIES = new Map([
14
+ ["amp", "&"],
15
+ ["apos", "'"],
16
+ ["gt", ">"],
17
+ ["lt", "<"],
18
+ ["quot", '"'],
19
+ ]);
20
+ /** Decodes the predefined and numeric character references of XML text. */
21
+ function decodeXml(text) {
22
+ return text.replace(/&(?:#x([0-9a-fA-F]+)|#([0-9]+)|([a-z]+));/g, (match, hex, decimal,
23
+ // Set when neither `hex` nor `decimal` is: one group always matches.
24
+ name) => {
25
+ const codePoint = hex !== undefined
26
+ ? Number.parseInt(hex, 16)
27
+ : decimal !== undefined
28
+ ? Number.parseInt(decimal, 10)
29
+ : undefined;
30
+ if (codePoint === undefined) {
31
+ return XML_ENTITIES.get(name) ?? match;
32
+ }
33
+ return codePoint <= 0x10ffff
34
+ ? String.fromCodePoint(codePoint)
35
+ : match;
36
+ });
37
+ }
38
+ /**
39
+ * Removes one level of shell-style quoting from an os-release value. Double
40
+ * quotes allow the `\\`, `\"`, `` \` `` and `\$` escapes; single quotes are
41
+ * literal.
42
+ */
43
+ function unquote(value) {
44
+ if (value.length >= 2) {
45
+ const quote = value[0];
46
+ if (quote === '"' && value.endsWith('"')) {
47
+ return value.slice(1, -1).replace(/\\([\\"`$])/g, "$1");
48
+ }
49
+ if (quote === "'" && value.endsWith("'")) {
50
+ return value.slice(1, -1);
51
+ }
52
+ }
53
+ return value;
54
+ }
55
+ /**
56
+ * Parses os-release content into a null-prototype record, skipping blank
57
+ * lines, comments, lines without `=`, and invalid keys.
58
+ */
59
+ export function parseOsRelease(content) {
60
+ const raw = Object.create(null);
61
+ for (const line of content.split("\n")) {
62
+ const trimmed = line.trim();
63
+ if (trimmed === "" || trimmed.startsWith("#")) {
64
+ continue;
65
+ }
66
+ const eq = trimmed.indexOf("=");
67
+ if (eq === -1) {
68
+ continue;
69
+ }
70
+ const key = trimmed.substring(0, eq).trim();
71
+ if (!OS_RELEASE_KEY.test(key)) {
72
+ continue;
73
+ }
74
+ raw[key] = unquote(trimmed.substring(eq + 1).trim());
75
+ }
76
+ return raw;
77
+ }
78
+ /**
79
+ * Parses the `<string>` entries of an XML property list into a
80
+ * null-prototype record, skipping other value types and invalid keys.
81
+ */
82
+ export function parsePlistStrings(content) {
83
+ const raw = Object.create(null);
84
+ for (const [, rawKey = "", value = ""] of content.matchAll(PLIST_STRING_ENTRY)) {
85
+ const key = decodeXml(rawKey.trim());
86
+ if (PLIST_KEY.test(key)) {
87
+ raw[key] = decodeXml(value.trim());
88
+ }
89
+ }
90
+ return raw;
91
+ }
92
+ //# sourceMappingURL=releaseParsers.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"releaseParsers.js","sourceRoot":"","sources":["../../src/node/releaseParsers.ts"],"names":[],"mappings":"AAAA,+EAA+E;AAC/E,oEAAoE;AAEpE;;;GAGG;AACH,MAAM,cAAc,GAAG,mBAAmB,CAAA;AAE1C,4EAA4E;AAC5E,MAAM,kBAAkB,GAAG,kDAAkD,CAAA;AAE7E,8EAA8E;AAC9E,MAAM,SAAS,GAAG,yBAAyB,CAAA;AAE3C,mCAAmC;AACnC,MAAM,YAAY,GAAgC,IAAI,GAAG,CAAC;IACtD,CAAC,KAAK,EAAE,GAAG,CAAC;IACZ,CAAC,MAAM,EAAE,GAAG,CAAC;IACb,CAAC,IAAI,EAAE,GAAG,CAAC;IACX,CAAC,IAAI,EAAE,GAAG,CAAC;IACX,CAAC,MAAM,EAAE,GAAG,CAAC;CAChB,CAAC,CAAA;AAEF,2EAA2E;AAC3E,SAAS,SAAS,CAAC,IAAY;IAC3B,OAAO,IAAI,CAAC,OAAO,CACf,4CAA4C,EAC5C,CACI,KAAa,EACb,GAAuB,EACvB,OAA2B;IAC3B,qEAAqE;IACrE,IAAY,EACd,EAAE;QACA,MAAM,SAAS,GACX,GAAG,KAAK,SAAS;YACb,CAAC,CAAC,MAAM,CAAC,QAAQ,CAAC,GAAG,EAAE,EAAE,CAAC;YAC1B,CAAC,CAAC,OAAO,KAAK,SAAS;gBACrB,CAAC,CAAC,MAAM,CAAC,QAAQ,CAAC,OAAO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CAAC;YAC5C,SAAQ;QACZ,CAAC;QACD,MAAM,EAAE,GAAG,OAAO,CAAC,OAAO,CAAC,GAAG,CAAC,CAAA;QAC/B,IAAI,EAAE,KAAK,CAAC,CAAC,EAAE,CAAC;YACZ,SAAQ;QACZ,CAAC;QACD,MAAM,GAAG,GAAG,OAAO,CAAC,SAAS,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,IAAI,EAAE,CAAA;QAC3C,IAAI,CAAC,cAAc,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC;YAC5B,SAAQ;QACZ,CAAC;QACD,GAAG,CAAC,GAAG,CAAC,GAAG,OAAO,CAAC,OAAO,CAAC,SAAS,CAAC,EAAE,GAAG,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC,CAAA;IACxD,CAAC;IACD,OAAO,GAAG,CAAA;AACd,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,iBAAiB,CAAC,OAAe;IAC7C,MAAM,GAAG,GAA2B,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,CAAA;IACvD,KAAK,MAAM,CAAC,EAAE,MAAM,GAAG,EAAE,EAAE,KAAK,GAAG,EAAE,CAAC,IAAI,OAAO,CAAC,QAAQ,CACtD,kBAAkB,CACrB,EAAE,CAAC;QACA,MAAM,GAAG,GAAG,SAAS,CAAC,MAAM,CAAC,IAAI,EAAE,CAAC,CAAA;QACpC,IAAI,SAAS,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC;YACtB,GAAG,CAAC,GAAG,CAAC,GAAG,SAAS,CAAC,KAAK,CAAC,IAAI,EAAE,CAAC,CAAA;QACtC,CAAC;IACL,CAAC;IACD,OAAO,GAAG,CAAA;AACd,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": "1.0.0",
4
+ "version": "1.0.2",
5
5
  "author": {
6
6
  "name": "darthcav",
7
7
  "url": "https://github.com/darthcav"
@@ -39,13 +39,14 @@
39
39
  "dist"
40
40
  ],
41
41
  "dependencies": {
42
- "@logtape/logtape": "2.4.2"
42
+ "@logtape/logtape": "2.4.3"
43
43
  },
44
44
  "devDependencies": {
45
- "@biomejs/biome": "2.6.8",
46
- "@types/node": "26.6.6",
45
+ "@biomejs/biome": "2.6.9",
46
+ "@types/node": "26.6.11",
47
47
  "prettier": "3.10.1",
48
- "typedoc": "0.28.20"
48
+ "typedoc": "0.28.20",
49
+ "typescript": "6.0.3"
49
50
  },
50
51
  "repository": {
51
52
  "type": "git",
@@ -59,12 +60,13 @@
59
60
  "clean": "node -e \"fs.rmSync('dist', { recursive: true, force: true })\"",
60
61
  "build": "npm run clean && tsc -p tsconfig.build.json",
61
62
  "prepare": "npm run build",
63
+ "check:exports": "npm run build && node --input-type=module -e \"import p from './package.json' with { type: 'json' }; import { existsSync } from 'node:fs'; for (const [k, t] of Object.entries(p.exports)) { for (const f of Object.values(t)) if (existsSync(f) === false) throw new Error(k + ': ' + f + ' is missing'); await import(p.name + k.slice(1)) } console.log('exports OK')\"",
62
64
  "\n===== Typecheck =====": "",
63
65
  "typecheck": "tsc --noEmit",
64
66
  "\n===== Test =====": "",
65
67
  "test": "node --env-file-if-exists=.env.local --experimental-test-module-mocks --test --test-reporter=spec \"src/**/*.test.ts\"",
66
- "test:coverage": "node --env-file-if-exists=.env.local --experimental-test-module-mocks --experimental-test-coverage --test \"src/**/*.test.ts\"",
67
- "test:coverage:lcov": "node -e \"fs.mkdirSync('coverage', { recursive: true })\" && node --env-file-if-exists=.env.local --experimental-test-module-mocks --experimental-test-coverage --test-reporter=lcov --test-reporter-destination=coverage/lcov.info --test-reporter=spec --test-reporter-destination=stdout --test \"src/**/*.test.ts\"",
68
+ "test:coverage": "node --env-file-if-exists=.env.local --experimental-test-module-mocks --experimental-test-coverage --test-coverage-lines=100 --test-coverage-branches=100 --test-coverage-functions=100 --test-coverage-exclude=\"src/__tests__/**\" --test \"src/**/*.test.ts\"",
69
+ "test:coverage:lcov": "node -e \"fs.mkdirSync('coverage', { recursive: true })\" && node --env-file-if-exists=.env.local --experimental-test-module-mocks --experimental-test-coverage --test-coverage-lines=100 --test-coverage-branches=100 --test-coverage-functions=100 --test-coverage-exclude=\"src/__tests__/**\" --test-reporter=lcov --test-reporter-destination=coverage/lcov.info --test-reporter=spec --test-reporter-destination=stdout --test \"src/**/*.test.ts\"",
68
70
  "\n===== Linter =====": "",
69
71
  "lint": "biome check . && prettier --check \"**/*.md\" --ignore-path .gitignore",
70
72
  "lint:fix": "biome check --write . && prettier --write \"**/*.md\" --ignore-path .gitignore",
@@ -173,16 +173,12 @@ export function isArrayOf<T>(
173
173
  value: unknown,
174
174
  guard: TypeGuard<T>,
175
175
  ): value is T[] {
176
- if (!Array.isArray(value)) {
177
- return false
178
- }
179
- // An indexed loop, unlike `every`, also checks the holes of sparse arrays.
180
- for (let i = 0; i < value.length; i++) {
181
- if (!guard(value[i])) {
182
- return false
183
- }
184
- }
185
- return true
176
+ // An array iterator, unlike `Array#every`, visits the holes of sparse
177
+ // arrays, as `undefined`.
178
+ return (
179
+ Array.isArray(value) &&
180
+ value.values().every((element: unknown) => guard(element))
181
+ )
186
182
  }
187
183
 
188
184
  /**
@@ -226,7 +222,7 @@ export function asArrayOf<T>(
226
222
  */
227
223
  export function filterByGuard<T>(value: unknown, guard: TypeGuard<T>): T[] {
228
224
  return Array.isArray(value)
229
- ? value.filter((element: unknown) => guard(element))
225
+ ? value.filter((element: unknown): element is T => guard(element))
230
226
  : []
231
227
  }
232
228
 
package/src/core/index.ts CHANGED
@@ -1,7 +1,8 @@
1
1
  /**
2
2
  * Portable helpers: type guards and narrowing helpers, duration formatting,
3
3
  * and `noop`. They import no Node.js built-ins or packages, so they run in any
4
- * ES2025 runtime (`millisecondsToString` needs `Intl.DurationFormat`).
4
+ * ES2025 runtime (`millisecondsToString` also needs `Intl.DurationFormat` and
5
+ * `Temporal`).
5
6
  *
6
7
  * @example
7
8
  * ```ts
@@ -66,16 +66,10 @@ export function millisecondsToString(ms: number, locale = "en"): string {
66
66
  )
67
67
  }
68
68
 
69
- const totalMilliseconds = Math.round(ms)
70
- const magnitude = Math.abs(totalMilliseconds)
71
-
72
- const formatted = getDurationFormatter(locale).format({
73
- days: Math.floor(magnitude / 86_400_000),
74
- hours: Math.floor((magnitude % 86_400_000) / 3_600_000),
75
- minutes: Math.floor((magnitude % 3_600_000) / 60_000),
76
- seconds: Math.floor((magnitude % 60_000) / 1000),
77
- milliseconds: magnitude % 1000,
78
- })
79
-
80
- return totalMilliseconds < 0 && formatted ? `-${formatted}` : formatted
69
+ // Balances the milliseconds into days (of 24 hours) down to milliseconds.
70
+ // `Intl.DurationFormat` puts the sign of a negative duration in front.
71
+ const duration = Temporal.Duration.from({
72
+ milliseconds: Math.round(ms),
73
+ }).round({ largestUnit: "days" })
74
+ return getDurationFormatter(locale).format(duration)
81
75
  }
@@ -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
+ }