@demicodes/utils 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +201 -0
- package/README.md +24 -0
- package/dist/index.d.mts +116 -0
- package/dist/index.mjs +290 -0
- package/package.json +34 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
# @demicodes/utils
|
|
2
|
+
|
|
3
|
+
Zero-dependency, platform-neutral utilities shared across the Demi toolkit. Every
|
|
4
|
+
generic helper lives here so nothing is re-implemented per package (a boundary
|
|
5
|
+
test enforces this).
|
|
6
|
+
|
|
7
|
+
## Modules
|
|
8
|
+
|
|
9
|
+
- **guards** — `isRecord`, `asRecord`, `asString`, `stringOrNull`, `nonEmptyString`,
|
|
10
|
+
`numberOrZero`, `numberOrNull`
|
|
11
|
+
- **errors** — `AbortError`, `asError`, `errorMessage`, `isAbortError`,
|
|
12
|
+
`throwIfAborted`, `abortable`
|
|
13
|
+
- **async** — `noop`, `deferred`, `delay`, `withTimeout`, `waitFor`
|
|
14
|
+
- **bytes** — `encodeUtf8`, `decodeUtf8`, `utf8Bytes`, `utf8Slice`, `concatBytes`
|
|
15
|
+
- **strings** — `clamp`, `truncate`, `tail`, `shortHash`, `normalizeBaseUrl`
|
|
16
|
+
- **json** — `parseJsonOrString`, `parseJsonObject`
|
|
17
|
+
- **paths** — `normalizePath`, `dirnamePath`, `isAbsolutePath`
|
|
18
|
+
- **id** — `createId`
|
|
19
|
+
|
|
20
|
+
```ts
|
|
21
|
+
import { errorMessage, truncate, parseJsonObject } from '@demicodes/utils'
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
Part of [Demi](../../README.md). Apache-2.0.
|
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
//#region src/guards.d.ts
|
|
2
|
+
/** Narrows an unknown value to a plain object record (not null, not an array). */
|
|
3
|
+
declare function isRecord(value: unknown): value is Record<string, unknown>;
|
|
4
|
+
/** Asserts that a value is a plain object record, throwing `TypeError(message)` otherwise. */
|
|
5
|
+
declare function asRecord(value: unknown, message?: string): Record<string, unknown>;
|
|
6
|
+
/** Returns the value when it is a string, otherwise `undefined`. */
|
|
7
|
+
declare function asString(value: unknown): string | undefined;
|
|
8
|
+
/** Returns the value when it is a string, otherwise `null`. */
|
|
9
|
+
declare function stringOrNull(value: unknown): string | null;
|
|
10
|
+
/** Returns the value when it is a non-blank string, otherwise `undefined`. */
|
|
11
|
+
declare function nonEmptyString(value: unknown): string | undefined;
|
|
12
|
+
/** Returns the value when it is a finite number, otherwise `0`. */
|
|
13
|
+
declare function numberOrZero(value: unknown): number;
|
|
14
|
+
/** Returns the value when it is a finite number, otherwise `null`. */
|
|
15
|
+
declare function numberOrNull(value: unknown): number | null;
|
|
16
|
+
//#endregion
|
|
17
|
+
//#region src/errors.d.ts
|
|
18
|
+
/** Error thrown when an operation is canceled via an `AbortSignal` or a session abort. */
|
|
19
|
+
declare class AbortError extends Error {
|
|
20
|
+
constructor(message?: string);
|
|
21
|
+
}
|
|
22
|
+
/** Normalizes an unknown thrown value into an `Error`. */
|
|
23
|
+
declare function asError(error: unknown): Error;
|
|
24
|
+
/** Extracts a human-readable message from an unknown thrown value, falling back to `String(error)`
|
|
25
|
+
* for non-Errors and for Errors with an empty message. */
|
|
26
|
+
declare function errorMessage(error: unknown): string;
|
|
27
|
+
/** Reports whether an unknown thrown value represents an abort: the {@link AbortError} class, a
|
|
28
|
+
* `DOMException` from a fetch/AbortController abort, or any object with `name === 'AbortError'`. */
|
|
29
|
+
declare function isAbortError(error: unknown): boolean;
|
|
30
|
+
/** Throws an `AbortError` if the signal is already aborted. */
|
|
31
|
+
declare function throwIfAborted(signal: AbortSignal): void;
|
|
32
|
+
/**
|
|
33
|
+
* Wraps a promise so it rejects with `AbortError` as soon as the signal aborts. The underlying
|
|
34
|
+
* promise is not canceled; this only stops the caller from awaiting it past the abort.
|
|
35
|
+
*/
|
|
36
|
+
declare function abortable<T>(promise: Promise<T>, signal: AbortSignal): Promise<T>;
|
|
37
|
+
/** Reports whether an unknown thrown value is a file-not-found error (ENOENT). */
|
|
38
|
+
declare function isFileNotFoundError(error: unknown): boolean;
|
|
39
|
+
//#endregion
|
|
40
|
+
//#region src/async.d.ts
|
|
41
|
+
/** A no-op function. */
|
|
42
|
+
declare function noop(): void;
|
|
43
|
+
/** An externally-resolvable promise handle. */
|
|
44
|
+
interface Deferred<T> {
|
|
45
|
+
readonly promise: Promise<T>;
|
|
46
|
+
resolve(value: T | PromiseLike<T>): void;
|
|
47
|
+
reject(reason?: unknown): void;
|
|
48
|
+
}
|
|
49
|
+
/** Creates a promise whose `resolve`/`reject` are exposed for external settlement. */
|
|
50
|
+
declare function deferred<T = void>(): Deferred<T>;
|
|
51
|
+
/** Resolves after `ms` milliseconds. */
|
|
52
|
+
declare function delay(ms: number): Promise<void>;
|
|
53
|
+
/**
|
|
54
|
+
* Polls `predicate` until it returns `true`, or rejects once `timeoutMs` elapses.
|
|
55
|
+
* `describe` (optional) supplies extra context for the timeout error.
|
|
56
|
+
*/
|
|
57
|
+
declare function waitFor(predicate: () => boolean, describe?: () => string, options?: {
|
|
58
|
+
timeoutMs?: number;
|
|
59
|
+
intervalMs?: number;
|
|
60
|
+
}): Promise<void>;
|
|
61
|
+
/** Rejects with `Error(message)` if `promise` does not settle within `ms` milliseconds. */
|
|
62
|
+
declare function withTimeout<T>(promise: Promise<T>, ms: number, message?: string): Promise<T>;
|
|
63
|
+
//#endregion
|
|
64
|
+
//#region src/bytes.d.ts
|
|
65
|
+
/** Encodes a string to UTF-8 bytes. */
|
|
66
|
+
declare function encodeUtf8(text: string): Uint8Array;
|
|
67
|
+
/** Decodes UTF-8 bytes to a string. */
|
|
68
|
+
declare function decodeUtf8(data: Uint8Array): string;
|
|
69
|
+
/** Returns the UTF-8 byte length of a string. */
|
|
70
|
+
declare function utf8Bytes(text: string): number;
|
|
71
|
+
/** Slices a string by UTF-8 byte offsets, returning the decoded substring. */
|
|
72
|
+
declare function utf8Slice(text: string, start: number, end: number): string;
|
|
73
|
+
/** Concatenates byte chunks into a single `Uint8Array`. */
|
|
74
|
+
declare function concatBytes(chunks: readonly Uint8Array[]): Uint8Array;
|
|
75
|
+
//#endregion
|
|
76
|
+
//#region src/strings.d.ts
|
|
77
|
+
/** Clamps a number into the inclusive `[min, max]` range. */
|
|
78
|
+
declare function clamp(value: number, min: number, max: number): number;
|
|
79
|
+
/** Strips trailing slashes from a base URL so paths can be appended consistently. */
|
|
80
|
+
declare function normalizeBaseUrl(baseUrl: string): string;
|
|
81
|
+
/** Truncates `text` to at most `maxChars` characters, appending `ellipsis` when shortened. */
|
|
82
|
+
declare function truncate(text: string, maxChars: number, ellipsis?: string): string;
|
|
83
|
+
/** Returns the last `maxChars` characters of `text`. */
|
|
84
|
+
declare function tail(text: string, maxChars: number): string;
|
|
85
|
+
/** A short, stable hex hash of a string (32-bit FNV-1a). Not cryptographic. */
|
|
86
|
+
declare function shortHash(value: string): string;
|
|
87
|
+
//#endregion
|
|
88
|
+
//#region src/json.d.ts
|
|
89
|
+
/** Parses JSON, returning the value, or the original string if it is not valid JSON. */
|
|
90
|
+
declare function parseJsonOrString(value: string): unknown;
|
|
91
|
+
/** Parses JSON and returns it only when it is a plain object; otherwise `null`. */
|
|
92
|
+
declare function parseJsonObject(value: string): Record<string, unknown> | null;
|
|
93
|
+
/**
|
|
94
|
+
* JSON.stringify tolerant of values that normally throw or vanish: bigints,
|
|
95
|
+
* symbols, and functions are rendered as strings, circular references as
|
|
96
|
+
* "[Circular]". Returns undefined when the top-level value has no JSON form.
|
|
97
|
+
*/
|
|
98
|
+
declare function safeJsonStringify(value: unknown): string | undefined;
|
|
99
|
+
//#endregion
|
|
100
|
+
//#region src/paths.d.ts
|
|
101
|
+
/**
|
|
102
|
+
* Collapse `.`/`..` segments and backslashes into a canonical forward-slash
|
|
103
|
+
* path. Absolute inputs keep their leading `/` (or `DRIVE:/`); relative inputs
|
|
104
|
+
* with no remaining segments become `.`.
|
|
105
|
+
*/
|
|
106
|
+
declare function normalizePath(path: string): string;
|
|
107
|
+
/** The parent directory of a path, after normalization (POSIX `dirname` semantics). */
|
|
108
|
+
declare function dirnamePath(path: string): string;
|
|
109
|
+
/** Whether a path is absolute (leading `/` or a `DRIVE:` prefix). */
|
|
110
|
+
declare function isAbsolutePath(path: string): boolean;
|
|
111
|
+
//#endregion
|
|
112
|
+
//#region src/id.d.ts
|
|
113
|
+
/** Generates a random UUID. */
|
|
114
|
+
declare function createId(): string;
|
|
115
|
+
//#endregion
|
|
116
|
+
export { AbortError, Deferred, abortable, asError, asRecord, asString, clamp, concatBytes, createId, decodeUtf8, deferred, delay, dirnamePath, encodeUtf8, errorMessage, isAbortError, isAbsolutePath, isFileNotFoundError, isRecord, nonEmptyString, noop, normalizeBaseUrl, normalizePath, numberOrNull, numberOrZero, parseJsonObject, parseJsonOrString, safeJsonStringify, shortHash, stringOrNull, tail, throwIfAborted, truncate, utf8Bytes, utf8Slice, waitFor, withTimeout };
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,290 @@
|
|
|
1
|
+
//#region src/guards.ts
|
|
2
|
+
/** Narrows an unknown value to a plain object record (not null, not an array). */
|
|
3
|
+
function isRecord(value) {
|
|
4
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
5
|
+
}
|
|
6
|
+
/** Asserts that a value is a plain object record, throwing `TypeError(message)` otherwise. */
|
|
7
|
+
function asRecord(value, message = "Expected an object") {
|
|
8
|
+
if (!isRecord(value)) throw new TypeError(message);
|
|
9
|
+
return value;
|
|
10
|
+
}
|
|
11
|
+
/** Returns the value when it is a string, otherwise `undefined`. */
|
|
12
|
+
function asString(value) {
|
|
13
|
+
return typeof value === "string" ? value : void 0;
|
|
14
|
+
}
|
|
15
|
+
/** Returns the value when it is a string, otherwise `null`. */
|
|
16
|
+
function stringOrNull(value) {
|
|
17
|
+
return typeof value === "string" ? value : null;
|
|
18
|
+
}
|
|
19
|
+
/** Returns the value when it is a non-blank string, otherwise `undefined`. */
|
|
20
|
+
function nonEmptyString(value) {
|
|
21
|
+
return typeof value === "string" && value.trim() ? value : void 0;
|
|
22
|
+
}
|
|
23
|
+
/** Returns the value when it is a finite number, otherwise `0`. */
|
|
24
|
+
function numberOrZero(value) {
|
|
25
|
+
return typeof value === "number" && Number.isFinite(value) ? value : 0;
|
|
26
|
+
}
|
|
27
|
+
/** Returns the value when it is a finite number, otherwise `null`. */
|
|
28
|
+
function numberOrNull(value) {
|
|
29
|
+
return typeof value === "number" && Number.isFinite(value) ? value : null;
|
|
30
|
+
}
|
|
31
|
+
//#endregion
|
|
32
|
+
//#region src/errors.ts
|
|
33
|
+
/** Error thrown when an operation is canceled via an `AbortSignal` or a session abort. */
|
|
34
|
+
var AbortError = class extends Error {
|
|
35
|
+
constructor(message = "Aborted") {
|
|
36
|
+
super(message);
|
|
37
|
+
this.name = "AbortError";
|
|
38
|
+
}
|
|
39
|
+
};
|
|
40
|
+
/** Normalizes an unknown thrown value into an `Error`. */
|
|
41
|
+
function asError(error) {
|
|
42
|
+
return error instanceof Error ? error : new Error(String(error));
|
|
43
|
+
}
|
|
44
|
+
/** Extracts a human-readable message from an unknown thrown value, falling back to `String(error)`
|
|
45
|
+
* for non-Errors and for Errors with an empty message. */
|
|
46
|
+
function errorMessage(error) {
|
|
47
|
+
return error instanceof Error && error.message.length > 0 ? error.message : String(error);
|
|
48
|
+
}
|
|
49
|
+
/** Reports whether an unknown thrown value represents an abort: the {@link AbortError} class, a
|
|
50
|
+
* `DOMException` from a fetch/AbortController abort, or any object with `name === 'AbortError'`. */
|
|
51
|
+
function isAbortError(error) {
|
|
52
|
+
if (error instanceof AbortError) return true;
|
|
53
|
+
return typeof error === "object" && error !== null && error.name === "AbortError";
|
|
54
|
+
}
|
|
55
|
+
/** Throws an `AbortError` if the signal is already aborted. */
|
|
56
|
+
function throwIfAborted(signal) {
|
|
57
|
+
if (signal.aborted) throw new AbortError();
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* Wraps a promise so it rejects with `AbortError` as soon as the signal aborts. The underlying
|
|
61
|
+
* promise is not canceled; this only stops the caller from awaiting it past the abort.
|
|
62
|
+
*/
|
|
63
|
+
function abortable(promise, signal) {
|
|
64
|
+
if (signal.aborted) return Promise.reject(new AbortError());
|
|
65
|
+
return new Promise((resolve, reject) => {
|
|
66
|
+
let settled = false;
|
|
67
|
+
const onAbort = () => {
|
|
68
|
+
if (settled) return;
|
|
69
|
+
settled = true;
|
|
70
|
+
signal.removeEventListener("abort", onAbort);
|
|
71
|
+
reject(new AbortError());
|
|
72
|
+
};
|
|
73
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
74
|
+
promise.then((value) => {
|
|
75
|
+
if (settled) return;
|
|
76
|
+
settled = true;
|
|
77
|
+
signal.removeEventListener("abort", onAbort);
|
|
78
|
+
resolve(value);
|
|
79
|
+
}, (error) => {
|
|
80
|
+
if (settled) return;
|
|
81
|
+
settled = true;
|
|
82
|
+
signal.removeEventListener("abort", onAbort);
|
|
83
|
+
reject(error);
|
|
84
|
+
});
|
|
85
|
+
});
|
|
86
|
+
}
|
|
87
|
+
/** Reports whether an unknown thrown value is a file-not-found error (ENOENT). */
|
|
88
|
+
function isFileNotFoundError(error) {
|
|
89
|
+
return typeof error === "object" && error !== null && error.code === "ENOENT";
|
|
90
|
+
}
|
|
91
|
+
//#endregion
|
|
92
|
+
//#region src/async.ts
|
|
93
|
+
/** A no-op function. */
|
|
94
|
+
function noop() {}
|
|
95
|
+
/** Creates a promise whose `resolve`/`reject` are exposed for external settlement. */
|
|
96
|
+
function deferred() {
|
|
97
|
+
let resolve;
|
|
98
|
+
let reject;
|
|
99
|
+
return {
|
|
100
|
+
promise: new Promise((res, rej) => {
|
|
101
|
+
resolve = res;
|
|
102
|
+
reject = rej;
|
|
103
|
+
}),
|
|
104
|
+
resolve,
|
|
105
|
+
reject
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
/** Resolves after `ms` milliseconds. */
|
|
109
|
+
function delay(ms) {
|
|
110
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
113
|
+
* Polls `predicate` until it returns `true`, or rejects once `timeoutMs` elapses.
|
|
114
|
+
* `describe` (optional) supplies extra context for the timeout error.
|
|
115
|
+
*/
|
|
116
|
+
async function waitFor(predicate, describe, options = {}) {
|
|
117
|
+
const timeoutMs = options.timeoutMs ?? 1e3;
|
|
118
|
+
const intervalMs = options.intervalMs ?? 1;
|
|
119
|
+
const startedAt = Date.now();
|
|
120
|
+
while (!predicate()) {
|
|
121
|
+
if (Date.now() - startedAt > timeoutMs) {
|
|
122
|
+
const detail = describe?.().trim();
|
|
123
|
+
throw new Error(`Timed out waiting for condition${detail ? `: ${detail}` : ""}`);
|
|
124
|
+
}
|
|
125
|
+
await new Promise((resolve) => setTimeout(resolve, intervalMs));
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
/** Rejects with `Error(message)` if `promise` does not settle within `ms` milliseconds. */
|
|
129
|
+
function withTimeout(promise, ms, message = `Timed out after ${ms}ms`) {
|
|
130
|
+
return new Promise((resolve, reject) => {
|
|
131
|
+
const timer = setTimeout(() => reject(new Error(message)), ms);
|
|
132
|
+
promise.then((value) => {
|
|
133
|
+
clearTimeout(timer);
|
|
134
|
+
resolve(value);
|
|
135
|
+
}, (error) => {
|
|
136
|
+
clearTimeout(timer);
|
|
137
|
+
reject(error);
|
|
138
|
+
});
|
|
139
|
+
});
|
|
140
|
+
}
|
|
141
|
+
//#endregion
|
|
142
|
+
//#region src/bytes.ts
|
|
143
|
+
const encoder = new TextEncoder();
|
|
144
|
+
const decoder = new TextDecoder();
|
|
145
|
+
/** Encodes a string to UTF-8 bytes. */
|
|
146
|
+
function encodeUtf8(text) {
|
|
147
|
+
return encoder.encode(text);
|
|
148
|
+
}
|
|
149
|
+
/** Decodes UTF-8 bytes to a string. */
|
|
150
|
+
function decodeUtf8(data) {
|
|
151
|
+
return decoder.decode(data);
|
|
152
|
+
}
|
|
153
|
+
/** Returns the UTF-8 byte length of a string. */
|
|
154
|
+
function utf8Bytes(text) {
|
|
155
|
+
return encoder.encode(text).byteLength;
|
|
156
|
+
}
|
|
157
|
+
/** Slices a string by UTF-8 byte offsets, returning the decoded substring. */
|
|
158
|
+
function utf8Slice(text, start, end) {
|
|
159
|
+
if (start <= 0 && end >= utf8Bytes(text)) return text;
|
|
160
|
+
return decoder.decode(encoder.encode(text).slice(start, end));
|
|
161
|
+
}
|
|
162
|
+
/** Concatenates byte chunks into a single `Uint8Array`. */
|
|
163
|
+
function concatBytes(chunks) {
|
|
164
|
+
const length = chunks.reduce((total, chunk) => total + chunk.byteLength, 0);
|
|
165
|
+
const combined = new Uint8Array(length);
|
|
166
|
+
let offset = 0;
|
|
167
|
+
for (const chunk of chunks) {
|
|
168
|
+
combined.set(chunk, offset);
|
|
169
|
+
offset += chunk.byteLength;
|
|
170
|
+
}
|
|
171
|
+
return combined;
|
|
172
|
+
}
|
|
173
|
+
//#endregion
|
|
174
|
+
//#region src/strings.ts
|
|
175
|
+
/** Clamps a number into the inclusive `[min, max]` range. */
|
|
176
|
+
function clamp(value, min, max) {
|
|
177
|
+
return Math.min(Math.max(value, min), max);
|
|
178
|
+
}
|
|
179
|
+
/** Strips trailing slashes from a base URL so paths can be appended consistently. */
|
|
180
|
+
function normalizeBaseUrl(baseUrl) {
|
|
181
|
+
return baseUrl.replace(/\/+$/, "");
|
|
182
|
+
}
|
|
183
|
+
/** Truncates `text` to at most `maxChars` characters, appending `ellipsis` when shortened. */
|
|
184
|
+
function truncate(text, maxChars, ellipsis = "…") {
|
|
185
|
+
if (text.length <= maxChars) return text;
|
|
186
|
+
if (maxChars <= ellipsis.length) return text.slice(0, Math.max(0, maxChars));
|
|
187
|
+
return text.slice(0, maxChars - ellipsis.length) + ellipsis;
|
|
188
|
+
}
|
|
189
|
+
/** Returns the last `maxChars` characters of `text`. */
|
|
190
|
+
function tail(text, maxChars) {
|
|
191
|
+
return text.length <= maxChars ? text : text.slice(text.length - maxChars);
|
|
192
|
+
}
|
|
193
|
+
/** A short, stable hex hash of a string (32-bit FNV-1a). Not cryptographic. */
|
|
194
|
+
function shortHash(value) {
|
|
195
|
+
let hash = 2166136261;
|
|
196
|
+
for (let i = 0; i < value.length; i += 1) {
|
|
197
|
+
hash ^= value.charCodeAt(i);
|
|
198
|
+
hash = Math.imul(hash, 16777619);
|
|
199
|
+
}
|
|
200
|
+
return (hash >>> 0).toString(16);
|
|
201
|
+
}
|
|
202
|
+
//#endregion
|
|
203
|
+
//#region src/json.ts
|
|
204
|
+
/** Parses JSON, returning the value, or the original string if it is not valid JSON. */
|
|
205
|
+
function parseJsonOrString(value) {
|
|
206
|
+
try {
|
|
207
|
+
return JSON.parse(value);
|
|
208
|
+
} catch {
|
|
209
|
+
return value;
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
/** Parses JSON and returns it only when it is a plain object; otherwise `null`. */
|
|
213
|
+
function parseJsonObject(value) {
|
|
214
|
+
try {
|
|
215
|
+
const parsed = JSON.parse(value);
|
|
216
|
+
return isRecord(parsed) ? parsed : null;
|
|
217
|
+
} catch {
|
|
218
|
+
return null;
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
/**
|
|
222
|
+
* JSON.stringify tolerant of values that normally throw or vanish: bigints,
|
|
223
|
+
* symbols, and functions are rendered as strings, circular references as
|
|
224
|
+
* "[Circular]". Returns undefined when the top-level value has no JSON form.
|
|
225
|
+
*/
|
|
226
|
+
function safeJsonStringify(value) {
|
|
227
|
+
const seen = /* @__PURE__ */ new WeakSet();
|
|
228
|
+
try {
|
|
229
|
+
return JSON.stringify(value, (_key, nested) => {
|
|
230
|
+
if (typeof nested === "bigint") return nested.toString();
|
|
231
|
+
if (typeof nested === "symbol") return String(nested);
|
|
232
|
+
if (typeof nested === "function") return `[Function ${nested.name || "anonymous"}]`;
|
|
233
|
+
if (nested !== null && typeof nested === "object") {
|
|
234
|
+
if (seen.has(nested)) return "[Circular]";
|
|
235
|
+
seen.add(nested);
|
|
236
|
+
}
|
|
237
|
+
return nested;
|
|
238
|
+
});
|
|
239
|
+
} catch {
|
|
240
|
+
return;
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
//#endregion
|
|
244
|
+
//#region src/paths.ts
|
|
245
|
+
/**
|
|
246
|
+
* Collapse `.`/`..` segments and backslashes into a canonical forward-slash
|
|
247
|
+
* path. Absolute inputs keep their leading `/` (or `DRIVE:/`); relative inputs
|
|
248
|
+
* with no remaining segments become `.`.
|
|
249
|
+
*/
|
|
250
|
+
function normalizePath(path) {
|
|
251
|
+
const slashPath = path.replace(/\\/g, "/");
|
|
252
|
+
const drive = /^[A-Za-z]:/.exec(slashPath)?.[0].toUpperCase() ?? "";
|
|
253
|
+
const absolute = slashPath.startsWith("/") || drive.length > 0;
|
|
254
|
+
const body = drive ? slashPath.slice(2) : slashPath;
|
|
255
|
+
const parts = [];
|
|
256
|
+
for (const segment of body.split("/")) {
|
|
257
|
+
if (segment === "" || segment === ".") continue;
|
|
258
|
+
if (segment === "..") {
|
|
259
|
+
if (parts.length > 0 && parts[parts.length - 1] !== "..") parts.pop();
|
|
260
|
+
else if (!absolute) parts.push(segment);
|
|
261
|
+
continue;
|
|
262
|
+
}
|
|
263
|
+
parts.push(segment);
|
|
264
|
+
}
|
|
265
|
+
if (drive) return parts.length > 0 ? `${drive}/${parts.join("/")}` : `${drive}/`;
|
|
266
|
+
if (absolute) return `/${parts.join("/")}`;
|
|
267
|
+
return parts.join("/") || ".";
|
|
268
|
+
}
|
|
269
|
+
/** The parent directory of a path, after normalization (POSIX `dirname` semantics). */
|
|
270
|
+
function dirnamePath(path) {
|
|
271
|
+
const normalized = normalizePath(path);
|
|
272
|
+
if (normalized === "/" || /^[A-Za-z]:\/?$/.test(normalized)) return normalized;
|
|
273
|
+
const index = normalized.lastIndexOf("/");
|
|
274
|
+
if (index === -1) return ".";
|
|
275
|
+
if (index === 0) return "/";
|
|
276
|
+
if (index === 2 && /^[A-Za-z]:/.test(normalized)) return normalized.slice(0, 3);
|
|
277
|
+
return normalized.slice(0, index);
|
|
278
|
+
}
|
|
279
|
+
/** Whether a path is absolute (leading `/` or a `DRIVE:` prefix). */
|
|
280
|
+
function isAbsolutePath(path) {
|
|
281
|
+
return path.startsWith("/") || /^[A-Za-z]:[\\/]/.test(path);
|
|
282
|
+
}
|
|
283
|
+
//#endregion
|
|
284
|
+
//#region src/id.ts
|
|
285
|
+
/** Generates a random UUID. */
|
|
286
|
+
function createId() {
|
|
287
|
+
return globalThis.crypto.randomUUID();
|
|
288
|
+
}
|
|
289
|
+
//#endregion
|
|
290
|
+
export { AbortError, abortable, asError, asRecord, asString, clamp, concatBytes, createId, decodeUtf8, deferred, delay, dirnamePath, encodeUtf8, errorMessage, isAbortError, isAbsolutePath, isFileNotFoundError, isRecord, nonEmptyString, noop, normalizeBaseUrl, normalizePath, numberOrNull, numberOrZero, parseJsonObject, parseJsonOrString, safeJsonStringify, shortHash, stringOrNull, tail, throwIfAborted, truncate, utf8Bytes, utf8Slice, waitFor, withTimeout };
|
package/package.json
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@demicodes/utils",
|
|
3
|
+
"description": "Shared zero-dependency utilities for Demi (type guards, errors, async, bytes, strings, paths, JSON).",
|
|
4
|
+
"version": "0.1.0",
|
|
5
|
+
"private": false,
|
|
6
|
+
"type": "module",
|
|
7
|
+
"main": "./dist/index.mjs",
|
|
8
|
+
"module": "./dist/index.mjs",
|
|
9
|
+
"types": "./dist/index.d.mts",
|
|
10
|
+
"exports": {
|
|
11
|
+
".": {
|
|
12
|
+
"development": "./src/index.ts",
|
|
13
|
+
"types": "./dist/index.d.mts",
|
|
14
|
+
"import": "./dist/index.mjs"
|
|
15
|
+
}
|
|
16
|
+
},
|
|
17
|
+
"files": [
|
|
18
|
+
"dist"
|
|
19
|
+
],
|
|
20
|
+
"scripts": {
|
|
21
|
+
"build": "tsdown"
|
|
22
|
+
},
|
|
23
|
+
"license": "Apache-2.0",
|
|
24
|
+
"publishConfig": {
|
|
25
|
+
"access": "public"
|
|
26
|
+
},
|
|
27
|
+
"repository": {
|
|
28
|
+
"type": "git",
|
|
29
|
+
"url": "git+https://github.com/wspl/demi.git",
|
|
30
|
+
"directory": "packages/utils"
|
|
31
|
+
},
|
|
32
|
+
"homepage": "https://github.com/wspl/demi/tree/main/packages/utils#readme",
|
|
33
|
+
"bugs": "https://github.com/wspl/demi/issues"
|
|
34
|
+
}
|