@murky-web/typebuddy 1.1.1 → 1.3.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/src/guards.ts ADDED
@@ -0,0 +1,341 @@
1
+ /**
2
+ * Runtime type guards. The leaf module: everything else here builds on it, it
3
+ * builds on nothing.
4
+ */
5
+
6
+ import type { Maybe } from "./types/maybe.js";
7
+ import type { Nullable } from "./types/nullable.js";
8
+ import type { Optional } from "./types/optional.js";
9
+
10
+ type UnknownFunction = (...args: readonly never[]) => unknown;
11
+
12
+ const EMPTY_LENGTH = 0;
13
+
14
+ /**
15
+ * Check if a value is a string.
16
+ *
17
+ * @param {unknown} value - The value to check.
18
+ * @returns {boolean} True if the value is a string.
19
+ */
20
+ function isString<T extends string>(value: Nullable<T>): value is T;
21
+ function isString(value: unknown): value is string;
22
+ function isString(value: unknown): value is string {
23
+ return typeof value === "string";
24
+ }
25
+
26
+ /**
27
+ * Parses the input value as a boolean. Returns false if the value is no string.
28
+ *
29
+ * @param {unknown} value - The value to check.
30
+ * @returns {boolean} True if the value is a string.
31
+ */
32
+ function isEmptyString(value: unknown): boolean {
33
+ if (!isString(value)) {
34
+ return false;
35
+ }
36
+ return value.trim() === "";
37
+ }
38
+
39
+ /**
40
+ * Returns true if the value is null.
41
+ *
42
+ * @param {unknown} value - The value to check.
43
+ * @returns {boolean} True if the value is null.
44
+ */
45
+ function isNull(value: unknown): value is null {
46
+ return value === null;
47
+ }
48
+
49
+ /**
50
+ * Returns true if the value is undefined.
51
+ *
52
+ * @param {unknown} value - The value to check.
53
+ * @returns {boolean} True if the value is undefined.
54
+ */
55
+ function isUndefined(value: unknown): value is undefined {
56
+ return typeof value === "undefined";
57
+ }
58
+
59
+ /**
60
+ * Checks whether an Optional value is currently in its missing state.
61
+ *
62
+ * @param {Optional<T>} value - The Optional value to check.
63
+ * @returns {boolean} True when the value is undefined.
64
+ */
65
+ function isOptional<T>(value: Optional<T>): value is undefined {
66
+ return isUndefined(value);
67
+ }
68
+
69
+ /**
70
+ * Checks whether a Maybe value is currently in its missing state.
71
+ *
72
+ * @param {Maybe<T>} value - The Maybe value to check.
73
+ * @returns {boolean} True when the value is null.
74
+ */
75
+ function isMaybe<T>(value: Maybe<T>): value is null {
76
+ return isNull(value);
77
+ }
78
+
79
+ /**
80
+ * Checks whether a Nullable value is currently in its missing state.
81
+ *
82
+ * @param {Nullable<T>} value - The Nullable value to check.
83
+ * @returns {boolean} True when the value is null or undefined.
84
+ */
85
+ function isNullable<T>(value: Nullable<T>): value is null | undefined {
86
+ return isNull(value) || isUndefined(value);
87
+ }
88
+
89
+ /**
90
+ * Check if a value is an array.
91
+ *
92
+ * @param {unknown} value - The value to check.
93
+ * @returns {boolean} True if the value is an array.
94
+ */
95
+ function isArray<T>(value: Nullable<readonly T[]>): value is readonly T[];
96
+ function isArray(value: unknown): value is readonly unknown[];
97
+ function isArray(value: unknown): value is readonly unknown[] {
98
+ return Array.isArray(value);
99
+ }
100
+
101
+ /**
102
+ * Check if a value is an empty array.
103
+ *
104
+ * @param {unknown} value - The value to check.
105
+ * @returns {boolean} True if the value is an empty array.
106
+ */
107
+ function isEmptyArray<T>(value: Nullable<readonly T[]>): value is readonly T[];
108
+ function isEmptyArray(value: unknown): value is readonly unknown[];
109
+ function isEmptyArray(value: unknown): value is readonly unknown[] {
110
+ return Array.isArray(value) && value.length === EMPTY_LENGTH;
111
+ }
112
+
113
+ /**
114
+ * More performant implementation of isArray for large arrays
115
+ *
116
+ * @param {unknown} value - The value to check.
117
+ * @returns {boolean} True if the value is an array.
118
+ */
119
+ function fastIsArray<T>(value: Nullable<readonly T[]>): value is readonly T[];
120
+ function fastIsArray(value: unknown): value is readonly unknown[];
121
+ function fastIsArray(value: unknown): value is readonly unknown[] {
122
+ return Object.prototype.toString.call(value) === "[object Array]";
123
+ }
124
+
125
+ /**
126
+ * Check if a value is a number.
127
+ *
128
+ * @param {unknown} value - The value to check.
129
+ * @returns {boolean} True if the value is a number.
130
+ */
131
+ function isNumber<T extends number>(value: Nullable<T>): value is T;
132
+ function isNumber(value: unknown): value is number;
133
+ function isNumber(value: unknown): value is number {
134
+ if (typeof value === "string" && value.trim() === "") {
135
+ return false;
136
+ }
137
+ return (
138
+ typeof value === "number" &&
139
+ !Number.isNaN(value) &&
140
+ Number.isFinite(value)
141
+ );
142
+ }
143
+
144
+ /**
145
+ * Returns true if the value is an object.
146
+ *
147
+ * @param {unknown} value - The value to check.
148
+ * @returns {boolean} True if the value is an object.
149
+ */
150
+ function isObject<T extends Record<string, unknown>>(
151
+ value: Nullable<T>,
152
+ ): value is T;
153
+ function isObject(value: unknown): value is Record<string, unknown>;
154
+ function isObject(value: unknown): value is Record<string, unknown> {
155
+ if (
156
+ typeof value !== "object" ||
157
+ value === null ||
158
+ isArray(value) ||
159
+ Object.prototype.toString.call(value) !== "[object Object]"
160
+ ) {
161
+ return false;
162
+ }
163
+
164
+ const objectValue: object = value;
165
+ return Object.getPrototypeOf(objectValue) === Object.prototype;
166
+ }
167
+
168
+ /**
169
+ * Returns true if the value is a boolean.
170
+ *
171
+ * @param {unknown} value - The value to check.
172
+ * @returns {boolean} True if the value is a boolean.
173
+ */
174
+ function isBoolean<T extends boolean>(value: Nullable<T>): value is T;
175
+ function isBoolean(value: unknown): value is boolean;
176
+ function isBoolean(value: unknown): value is boolean {
177
+ return typeof value === "boolean";
178
+ }
179
+
180
+ /**
181
+ * Returns true if the value is a function.
182
+ *
183
+ * @param {unknown} value - The value to check.
184
+ * @returns {boolean} True if the value is a function.
185
+ */
186
+ function isFunction<T extends UnknownFunction>(value: Nullable<T>): value is T;
187
+ function isFunction(value: unknown): value is UnknownFunction;
188
+ function isFunction(value: unknown): value is UnknownFunction {
189
+ return typeof value === "function";
190
+ }
191
+
192
+ /**
193
+ * Returns true if the value is a promise.
194
+ *
195
+ * @param {unknown} value - The value to check.
196
+ * @returns {boolean} True if the value is a promise.
197
+ */
198
+ function isPromise<T>(
199
+ value: Nullable<Readonly<PromiseLike<T>>>,
200
+ ): value is PromiseLike<T>;
201
+ function isPromise(value: unknown): value is PromiseLike<unknown>;
202
+ function isPromise(value: unknown): value is PromiseLike<unknown> {
203
+ if (typeof value !== "object" || value === null) {
204
+ return false;
205
+ }
206
+
207
+ return typeof Reflect.get(value, "then") === "function";
208
+ }
209
+
210
+ /**
211
+ * Returns true if the value is an error.
212
+ *
213
+ * @param {unknown} value - The value to check.
214
+ * @returns {boolean} True if the value is an error.
215
+ */
216
+ function isError<T extends Error>(value: Nullable<T>): value is T;
217
+ function isError(value: unknown): value is Error;
218
+ function isError(value: unknown): value is Error {
219
+ return value instanceof Error;
220
+ }
221
+
222
+ /**
223
+ * Returns true if the value is a date.
224
+ *
225
+ * @param {unknown} value - The value to check.
226
+ * @returns {boolean} True if the value is a date.
227
+ */
228
+ function isDate<T extends Date>(value: Nullable<T>): value is T;
229
+ function isDate(value: unknown): value is Date;
230
+ function isDate(value: unknown): value is Date {
231
+ return value instanceof Date;
232
+ }
233
+
234
+ /**
235
+ * Returns true if the value is a RegExp.
236
+ *
237
+ * @param {unknown} value - The value to check.
238
+ * @returns {boolean} True if the value is a RegExp.
239
+ */
240
+ function isRegExp<T extends RegExp>(value: Nullable<T>): value is T;
241
+ function isRegExp(value: unknown): value is RegExp;
242
+ function isRegExp(value: unknown): value is RegExp {
243
+ return value instanceof RegExp;
244
+ }
245
+
246
+ /**
247
+ * Returns true if the value is a symbol.
248
+ *
249
+ * @param {unknown} value - The value to check.
250
+ * @returns {boolean} True if the value is a symbol.
251
+ */
252
+ function isSymbol<T extends symbol>(value: Nullable<T>): value is T;
253
+ function isSymbol(value: unknown): value is symbol;
254
+ function isSymbol(value: unknown): value is symbol {
255
+ return typeof value === "symbol";
256
+ }
257
+
258
+ /**
259
+ * Check if a value is a plain object.
260
+ *
261
+ * @param {unknown} value - The value to check.
262
+ * @returns {boolean} True if the value is a plain object.
263
+ */
264
+ function isEmptyObject<T extends Record<string, unknown>>(
265
+ value: Nullable<T>,
266
+ ): value is T;
267
+ function isEmptyObject(value: unknown): value is Record<string, unknown>;
268
+ function isEmptyObject(value: unknown): value is Record<string, unknown> {
269
+ return (
270
+ typeof value === "object" &&
271
+ !isNull(value) &&
272
+ !isUndefined(value) &&
273
+ !isEmptyArray(value) &&
274
+ Object.getPrototypeOf(value) === Object.prototype &&
275
+ Object.keys(value).length === EMPTY_LENGTH
276
+ );
277
+ }
278
+
279
+ /**
280
+ * Check if a value is an instance of a class.
281
+ *
282
+ * @param {unknown} value - The value to check.
283
+ * @param {unknown} constructor - The class constructor to check against.
284
+ * @returns {boolean} True if the value is an instance of the class.
285
+ */
286
+ function isInstanceOf<T>(
287
+ value: unknown,
288
+ constructor: new (...args: unknown[]) => T,
289
+ ): value is T {
290
+ return value instanceof constructor;
291
+ }
292
+
293
+ /**
294
+ * Check if a value is an integer.
295
+ *
296
+ * @param {unknown} value - The value to check.
297
+ * @returns {boolean} True if the value is an integer.
298
+ */
299
+ function isInteger(value: unknown): value is number {
300
+ return typeof value === "number" && Number.isInteger(value);
301
+ }
302
+
303
+ /**
304
+ * Check if a value is a float.
305
+ *
306
+ * @param {unknown} value - The value to check.
307
+ * @returns {boolean} True if the value is a float.
308
+ */
309
+ function isFloat(value: unknown): value is number {
310
+ return (
311
+ typeof value === "number" &&
312
+ !Number.isNaN(value) &&
313
+ !Number.isInteger(value)
314
+ );
315
+ }
316
+
317
+ export {
318
+ fastIsArray,
319
+ isArray,
320
+ isBoolean,
321
+ isDate,
322
+ isEmptyArray,
323
+ isEmptyObject,
324
+ isEmptyString,
325
+ isError,
326
+ isFloat,
327
+ isFunction,
328
+ isInstanceOf,
329
+ isInteger,
330
+ isMaybe,
331
+ isNull,
332
+ isNullable,
333
+ isNumber,
334
+ isObject,
335
+ isOptional,
336
+ isPromise,
337
+ isRegExp,
338
+ isString,
339
+ isSymbol,
340
+ isUndefined,
341
+ };
package/src/ids.ts ADDED
@@ -0,0 +1,34 @@
1
+ /**
2
+ * Identifier-format checks. Their two regex literals are the only module-level
3
+ * allocations in the package, which is the whole reason they live alone: a
4
+ * bundler that keeps anything in a module keeps those too.
5
+ */
6
+
7
+ import { isString } from "./guards.js";
8
+
9
+ const uuidRegex =
10
+ /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-5][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$/;
11
+
12
+ const ulidRegex = /^[0123456789ABCDEFGHJKMNPQRSTVWXYZ]{26}$/;
13
+
14
+ /**
15
+ * Returns true if the input is a UUID string.
16
+ *
17
+ * @param {string} input - The input to check.
18
+ * @returns {boolean} True if the input is a UUID string.
19
+ */
20
+ function isUuidString(input: unknown): input is string {
21
+ return isString(input) && uuidRegex.test(input);
22
+ }
23
+
24
+ /**
25
+ * Returns true if the input is a ULID string.
26
+ *
27
+ * @param {string} input - The input to check.
28
+ * @returns {boolean} True if the input is a ULID string.
29
+ */
30
+ function isUlidString(input: unknown): input is string {
31
+ return typeof input === "string" && ulidRegex.test(input);
32
+ }
33
+
34
+ export { isUlidString, isUuidString };
package/src/index.ts CHANGED
@@ -1,6 +1,16 @@
1
+ // Side-effect type import: pulls the `declare global` block into any
2
+ // program that imports this package, so the global helpers need no
3
+ // tsconfig entry of their own. The empty brace form is the only way to say
4
+ // "load this module for its ambient declarations" without importing a value,
5
+ // and `globals.ts` sits at the package root because it is a published entry
6
+ // point (`@murky-web/typebuddy/globals`).
7
+ // oxlint-disable-next-line no-empty-named-blocks, no-relative-parent-imports, require-module-specifiers
8
+ import type {} from "../globals.js";
9
+
1
10
  export * from "./type_helper.js";
2
11
 
3
12
  export type {
13
+ AsyncResult,
4
14
  Failed,
5
15
  JsonifiedObject,
6
16
  JsonifiedValue,
@@ -11,6 +21,7 @@ export type {
11
21
  ResolveMaybe,
12
22
  ResolveNullable,
13
23
  ResolveOptional,
24
+ Result,
14
25
  Stringified,
15
26
  Success,
16
27
  } from "./types/index.js";
package/src/parse.ts ADDED
@@ -0,0 +1,215 @@
1
+ /**
2
+ * Coercions from unknown input to a concrete type, each with a caller-supplied
3
+ * fallback. Separate from the guards because parsing is what you do _after_ a
4
+ * guard said no.
5
+ */
6
+
7
+ import {
8
+ isArray,
9
+ isEmptyObject,
10
+ isNull,
11
+ isNumber,
12
+ isString,
13
+ isUndefined,
14
+ } from "./guards.js";
15
+ import type { Optional } from "./types/optional.js";
16
+
17
+ const EMPTY_LENGTH = 0;
18
+
19
+ function cloneDefaultArray(
20
+ defaultValue?: readonly unknown[],
21
+ ): unknown[] | undefined {
22
+ if (!defaultValue) {
23
+ return defaultValue;
24
+ }
25
+
26
+ return [...defaultValue];
27
+ }
28
+
29
+ /**
30
+ * Parses the input value as an integer. Returns NaN if the value cannot be
31
+ * parsed.
32
+ *
33
+ * @param {unknown} value - The value to check.
34
+ * @param {Optional<number>} defaultValue - Value gets returned if integer could
35
+ * not be parsed.
36
+ * @returns {number} The parsed integer.
37
+ */
38
+ function parseInteger(value: unknown): Optional<number>;
39
+ function parseInteger(value: unknown, defaultValue: number): number;
40
+ function parseInteger(value: unknown, defaultValue?: number): Optional<number> {
41
+ if (isNumber(value)) {
42
+ return Math.floor(value);
43
+ }
44
+
45
+ if (isString(value)) {
46
+ const parsed = Number(value.trim());
47
+ if (Number.isInteger(parsed)) {
48
+ return parsed;
49
+ }
50
+ }
51
+ return defaultValue;
52
+ }
53
+
54
+ /**
55
+ * Parses the input value as a float. Returns NaN if the value cannot be parsed.
56
+ *
57
+ * @param {unknown} value - The value to check.
58
+ * @param {Optional<number>} defaultValue - Value gets returned if float could
59
+ * not be parsed.
60
+ * @returns {number} The parsed float.
61
+ */
62
+ function parseFloat(value: unknown): Optional<number>;
63
+ function parseFloat(value: unknown, defaultValue: number): number;
64
+ function parseFloat(value: unknown, defaultValue?: number): Optional<number> {
65
+ if (isNumber(value)) {
66
+ return value;
67
+ }
68
+ if (isString(value)) {
69
+ const normalizedValue = value.trim().replace(",", ".");
70
+ const parsed = Number.parseFloat(normalizedValue);
71
+ if (!Number.isNaN(parsed)) {
72
+ return parsed;
73
+ }
74
+ }
75
+ return defaultValue;
76
+ }
77
+
78
+ /**
79
+ * Parses the input value as a number. Returns NaN if the value cannot be
80
+ * parsed.
81
+ *
82
+ * @param {unknown} value - The value to check.
83
+ * @param {Optional<number>} defaultValue - Value gets returned if number could
84
+ * not be parsed.
85
+ * @returns {number} The parsed number.
86
+ */
87
+ function parseNumber(value: unknown): Optional<number>;
88
+ function parseNumber(value: unknown, defaultValue: number): number;
89
+ function parseNumber(value: unknown, defaultValue?: number): Optional<number> {
90
+ if (isNumber(value)) {
91
+ return value;
92
+ }
93
+ if (isString(value)) {
94
+ const normalizedValue = value.trim().replace(",", ".");
95
+ const parsed = Number(normalizedValue);
96
+ if (Number.isFinite(parsed)) {
97
+ return parsed;
98
+ }
99
+ }
100
+ return defaultValue;
101
+ }
102
+
103
+ /**
104
+ * Parses the input value as a string. Returns an empty string if the value
105
+ * cannot be converted.
106
+ *
107
+ * @param {unknown} value - The value to check.
108
+ * @param {Optional<string>} defaultValue - Value gets returned if string could
109
+ * not be parsed.
110
+ * @returns {string} The parsed string.
111
+ */
112
+ function parseString(value: unknown, defaultValue = ""): string {
113
+ if (isString(value)) {
114
+ return value;
115
+ }
116
+ if (isNumber(value)) {
117
+ return value.toString();
118
+ }
119
+ if (typeof value === "boolean") {
120
+ return value.toString();
121
+ }
122
+ return defaultValue;
123
+ }
124
+
125
+ /**
126
+ * Parses the input value as an array. Returns an empty array if the value
127
+ * cannot be parsed as an array.
128
+ *
129
+ * @param {unknown} value - The value to check.
130
+ * @param {Optional<T[]>} defaultValue - Value gets returned if array could not
131
+ * be parsed.
132
+ * @returns {Optional<T[]>} The parsed array.
133
+ */
134
+
135
+ function parseArray<T>(value: readonly T[]): T[];
136
+ function parseArray(value: string): string[];
137
+ function parseArray(value: number): number[];
138
+ function parseArray<T extends Record<string, unknown>>(value: T): T[];
139
+ function parseArray<T>(value: unknown, defaultValue: readonly T[]): T[];
140
+ function parseArray(value: unknown): unknown[] | undefined;
141
+ function parseArray(
142
+ value: unknown,
143
+ defaultValue?: readonly unknown[],
144
+ ): unknown[] | undefined {
145
+ if (isArray(value)) {
146
+ return [...value];
147
+ }
148
+ if (isString(value)) {
149
+ const parsed = value
150
+ .split(/[,|;\n\t ]+/)
151
+ .map((entry) => {
152
+ return entry.trim();
153
+ })
154
+ .filter((entry) => {
155
+ return entry.length > EMPTY_LENGTH;
156
+ });
157
+ return parsed;
158
+ }
159
+ if (isNumber(value)) {
160
+ return [value];
161
+ }
162
+ if (isEmptyObject(value)) {
163
+ return [value];
164
+ }
165
+
166
+ if (isNull(value) || isUndefined(value)) {
167
+ return cloneDefaultArray(defaultValue);
168
+ }
169
+ return cloneDefaultArray(defaultValue);
170
+ }
171
+
172
+ /**
173
+ * Parses the domain name from a URL.
174
+ *
175
+ * @param {string} url - The URL to parse.
176
+ * @param {Optional<T>} defaultValue - The fallback when parsing fails.
177
+ * @returns {string} The domain name.
178
+ */
179
+ function parseDomainName(url: string): Optional<string>;
180
+ function parseDomainName(url: string, defaultValue: string): string;
181
+ function parseDomainName(url: string, defaultValue?: string): Optional<string> {
182
+ const normalizedValue = url.trim();
183
+ if (normalizedValue === "" || normalizedValue.startsWith("/")) {
184
+ return defaultValue;
185
+ }
186
+
187
+ let urlCandidate = normalizedValue;
188
+ if (!normalizedValue.includes("://")) {
189
+ urlCandidate = `https://${normalizedValue}`;
190
+ }
191
+
192
+ // Everything that depends on a parseable URL stays inside the `try`, so
193
+ // there is no binding that has to be declared before it can be assigned.
194
+ try {
195
+ const { hostname } = new URL(urlCandidate);
196
+ const normalizedHostname = hostname.replace(/^www\d?\./i, "");
197
+ const [domainName] = normalizedHostname.split(".");
198
+ if (domainName === undefined || domainName === "") {
199
+ return defaultValue;
200
+ }
201
+
202
+ return domainName;
203
+ } catch {
204
+ return defaultValue;
205
+ }
206
+ }
207
+
208
+ export {
209
+ parseArray,
210
+ parseDomainName,
211
+ parseFloat,
212
+ parseInteger,
213
+ parseNumber,
214
+ parseString,
215
+ };
package/src/result.ts ADDED
@@ -0,0 +1,57 @@
1
+ /**
2
+ * Result values for MaybePromise-style flows. Deliberately free of dependencies
3
+ * on the guards — a caller that only needs `ok`/`err` should not pull a
4
+ * type-guard module along with it.
5
+ */
6
+
7
+ import type { Failed, Result, Success } from "./types/maybe_promise.js";
8
+
9
+ /**
10
+ * Checks if the provided result is a `Success` type.
11
+ *
12
+ * @example
13
+ * ```typescript
14
+ * const result = await someAsyncFunction();
15
+ * if (isSuccess(result)) {
16
+ * return result.value; // TypeScript knows `value` is of type `T`
17
+ * }
18
+ * ```
19
+ *
20
+ * @template T The type of the value contained in the `Success` type.
21
+ * @param {Readonly<Result<T>>} result The result to check, which can
22
+ * be either a `Success<T>` or `Failed`.
23
+ * @returns {boolean} `true` if the result is a `Success<T>`, `false` if it is a
24
+ * `Failed`. This function acts as a type guard, narrowing the type of
25
+ * `result` to `Success<T>` when the condition is met.
26
+ */
27
+ function isSuccess<T>(
28
+ result: Readonly<Result<T>>,
29
+ ): result is Success<T> {
30
+ return !result.isError;
31
+ }
32
+
33
+ /** Creates a successful result object for MaybePromise-style flows. */
34
+ function ok(): Success<void>;
35
+ function ok<T>(value: T): Success<T>;
36
+ // oxlint-disable-next-line typescript-eslint/prefer-readonly-parameter-types -- ok() intentionally accepts arbitrary payload values, including mutable ones.
37
+ function ok<T>(...args: readonly [T] | []): Success<T | void> {
38
+ const [value] = args;
39
+ return {
40
+ isError: false,
41
+ value,
42
+ };
43
+ }
44
+
45
+ /** Creates the default failed result object for MaybePromise-style flows. */
46
+ function err(): Failed;
47
+ function err<T extends null>(value: T): Failed<T>;
48
+ // oxlint-disable-next-line typescript-eslint/prefer-readonly-parameter-types -- err() mirrors ok() and accepts the caller's payload shape without forcing readonly wrappers.
49
+ function err<T extends null>(...args: readonly [T] | []): Failed {
50
+ const [value] = args;
51
+ return {
52
+ isError: true,
53
+ value: value ?? null,
54
+ };
55
+ }
56
+
57
+ export { err, isSuccess, ok };