@murky-web/typebuddy 2.1.0 → 3.0.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.
Files changed (45) hide show
  1. package/README.md +184 -72
  2. package/dist/collections.js +1 -2
  3. package/dist/empty.js +34 -13
  4. package/dist/guards.js +33 -9
  5. package/dist/ids.js +6 -6
  6. package/dist/oxlint.js +7 -7
  7. package/dist/parse.js +39 -15
  8. package/dist/result.js +6 -6
  9. package/dist/rules/async_rule.js +39 -25
  10. package/dist/rules/deliberate_throw.js +5 -6
  11. package/dist/rules/maybe_promise_rule.js +99 -40
  12. package/dist/rules/maybe_rule.js +7 -5
  13. package/dist/rules/nullable_rule.js +7 -5
  14. package/dist/rules/optional_rule.js +8 -4
  15. package/dist/rules/own_subtree.js +1 -2
  16. package/dist/rules/test_file.js +63 -0
  17. package/dist/rules/typebuddy_import.js +242 -35
  18. package/dist/rules/use_server.js +1 -2
  19. package/globals.d.ts +49 -44
  20. package/jsr.json +3 -2
  21. package/oxlint/index.ts +7 -5
  22. package/package.json +92 -91
  23. package/rules/async_rule.ts +80 -64
  24. package/rules/deliberate_throw.ts +11 -11
  25. package/rules/maybe_promise_rule.ts +218 -91
  26. package/rules/maybe_rule.ts +74 -47
  27. package/rules/nullable_rule.ts +78 -50
  28. package/rules/optional_rule.ts +80 -51
  29. package/rules/own_subtree.ts +33 -33
  30. package/rules/test_file.ts +114 -0
  31. package/rules/typebuddy_import.ts +479 -87
  32. package/rules/use_server.ts +2 -1
  33. package/src/empty.ts +57 -19
  34. package/src/guards.ts +96 -30
  35. package/src/ids.ts +10 -4
  36. package/src/index.ts +1 -18
  37. package/src/parse.ts +104 -25
  38. package/src/public_api.ts +22 -0
  39. package/src/result.ts +5 -4
  40. package/src/types/globals.ts +11 -11
  41. package/src/types/index.ts +21 -21
  42. package/src/types/json.ts +48 -11
  43. package/src/types/maybe_promise.ts +17 -12
  44. package/src/types/nullable.ts +2 -2
  45. package/src/types/optional.ts +6 -6
package/README.md CHANGED
@@ -1,19 +1,20 @@
1
1
  # TypeBuddy
2
2
 
3
- TypeBuddy is a utility library for type guards, parsing, and small TypeScript-first helper types. It focuses on two things:
3
+ TypeBuddy is a utility library for type guards, parsing, and small
4
+ TypeScript-first helper types. It focuses on two things:
4
5
 
5
6
  - predictable runtime helpers for common JavaScript values
6
7
  - a small type system around `Optional`, `Maybe`, and `Nullable`
7
8
 
8
9
  ## Features
9
10
 
10
- - runtime guards for common JavaScript values
11
- - parsing helpers for strings, numbers, arrays, and URLs
12
- - utility types like `Optional<T>`, `Maybe<T>`, `Nullable<T>`
13
- - type-system guards like `isOptional`, `isMaybe`, `isNullable`
14
- - global type opt-in through `@murky-web/typebuddy/globals`
15
- - custom `oxlint` rules through `@murky-web/typebuddy/oxlint`
16
- - tree-shake-friendly ESM output for frontend and backend bundles
11
+ - runtime guards for common JavaScript values
12
+ - parsing helpers for strings, numbers, arrays, and URLs
13
+ - utility types like `Optional<T>`, `Maybe<T>`, `Nullable<T>`
14
+ - type-system guards like `isOptional`, `isMaybe`, `isNullable`
15
+ - global type opt-in through `@murky-web/typebuddy/globals`
16
+ - custom `oxlint` rules through `@murky-web/typebuddy/oxlint`
17
+ - tree-shake-friendly ESM output for frontend and backend bundles
17
18
 
18
19
  ## Installation
19
20
 
@@ -34,7 +35,12 @@ npx jsr add @murky-web/typebuddy
34
35
  Here's an example of how to use TypeBuddy in your TypeScript project:
35
36
 
36
37
  ```typescript
37
- import { isString, parseNumber, isUuidString, isEmptyObject } from "@murky-web/typebuddy";
38
+ import {
39
+ isString,
40
+ parseNumber,
41
+ isUuidString,
42
+ isEmptyObject,
43
+ } from "@murky-web/typebuddy";
38
44
 
39
45
  const value: unknown = "123";
40
46
 
@@ -96,9 +102,9 @@ If you want the `typebuddy` utility types globally, opt in once in your project:
96
102
  ```jsonc
97
103
  // tsconfig.json
98
104
  {
99
- "compilerOptions": {
100
- "types": ["@murky-web/typebuddy/globals"]
101
- }
105
+ "compilerOptions": {
106
+ "types": ["@murky-web/typebuddy/globals"],
107
+ },
102
108
  }
103
109
  ```
104
110
 
@@ -112,63 +118,91 @@ import type {} from "@murky-web/typebuddy/globals";
112
118
 
113
119
  That makes these names available globally:
114
120
 
115
- - `Optional`
116
- - `ResolveOptional`
117
- - `Maybe`
118
- - `ResolveMaybe`
119
- - `Nullable`
120
- - `ResolveNullable`
121
- - `MaybePromise`
122
- - `Success`
123
- - `Failed`
124
- - `JsonifiedValue`
125
- - `Stringified`
121
+ - `Optional`
122
+ - `ResolveOptional`
123
+ - `Maybe`
124
+ - `ResolveMaybe`
125
+ - `Nullable`
126
+ - `ResolveNullable`
127
+ - `MaybePromise`
128
+ - `Success`
129
+ - `Failed`
130
+ - `JsonifiedValue`
131
+ - `Stringified`
126
132
 
127
133
  ## API
128
134
 
129
135
  ### Type Checking Functions
130
136
 
131
- - `isObject(value: unknown): value is object`
132
- - `isBoolean(value: unknown): value is boolean`
133
- - `isNull(value: unknown): value is null`
134
- - `isUndefined(value: unknown): value is undefined`
135
- - `isOptional<T>(value: Optional<T>): value is undefined`
136
- - `isMaybe<T>(value: Maybe<T>): value is null`
137
- - `isNullable<T>(value: Nullable<T>): value is null | undefined`
138
- - `isFunction(value: unknown): value is Function`
139
- - `isPromise(value: unknown): value is Promise<unknown>`
140
- - `isError(value: unknown): value is Error`
141
- - `isDate(value: unknown): value is Date`
142
- - `isRegExp(value: unknown): value is RegExp`
143
- - `isSymbol(value: unknown): value is symbol`
144
- - `isEmptyObject(value: unknown): value is Record<string, unknown>`
145
- - `isInstanceOf<T>(value: unknown, constructor: { new (...args: unknown[]): T }): value is T`
146
- - `isArray<T>(value: unknown): value is T[]`
147
- - `isEmptyArray<T>(value: unknown): value is T[]`
148
- - `isNumber(value: unknown): value is number`
149
- - `isInteger(value: unknown): value is number`
150
- - `isFloat(value: unknown): value is number`
151
- - `isString(value: unknown): value is string`
152
- - `isUuidString(input: unknown): input is string`
153
- - `isUlidString(input: unknown): input is string`
137
+ - `isObject(value: unknown): value is object`
138
+ - `isBoolean(value: unknown): value is boolean`
139
+ - `isNull(value: unknown): value is null`
140
+ - `isUndefined(value: unknown): value is undefined`
141
+ - `isOptional<T>(value: Optional<T>): value is undefined`
142
+ - `isMaybe<T>(value: Maybe<T>): value is null`
143
+ - `isNullable<T>(value: Nullable<T>): value is null | undefined`
144
+ - `isFunction(value: unknown): value is Function`
145
+ - `isPromise(value: unknown): value is PromiseLike<unknown>` (any thenable, also
146
+ a callable one; `false` when reading `then` throws)
147
+ - `isError(value: unknown): value is Error`
148
+ - `isDate(value: unknown): value is Date`
149
+ - `isRegExp(value: unknown): value is RegExp`
150
+ - `isSymbol(value: unknown): value is symbol`
151
+ - `isEmptyObject(value: unknown): value is EmptyObject` (a plain object without
152
+ any own key, symbol and non-enumerable keys included)
153
+ - `isInstanceOf<T>(value: unknown, constructor: { new (...args: unknown[]): T }): value is T`
154
+ - `isArray<T>(value: unknown): value is T[]`
155
+ - `isEmptyArray<T>(value: unknown): value is T[]`
156
+ - `isNumber(value: unknown): value is FiniteNumber` (not `NaN`, not `±Infinity`;
157
+ `FiniteNumber` is a `number` brand, so the `false` branch keeps `NaN`)
158
+ - `isInteger(value: unknown): value is IntegerNumber` (a `number` brand, like
159
+ `FiniteNumber`)
160
+ - `isFloat(value: unknown): value is FloatNumber` (finite, with a fractional
161
+ part; a `number` brand)
162
+ - `isString(value: unknown): value is string`
163
+ - `isUuidString(input: unknown): input is string` (versions 1 to 8, plus the nil
164
+ and max UUID, any case)
165
+ - `isUlidString(input: unknown): input is string` (any case, first character `0`
166
+ to `7`)
154
167
 
155
168
  ### Parsing Functions
156
169
 
157
- - `parseNumber<T extends number, R extends Optional<T>>(value: unknown, defaultValue?: R): ResolveOptional<T, R>`
158
- - `parseInteger(value: unknown, defaultValue?: Optional<number>): Optional<number>`
159
- - `parseFloat<T extends number, R extends Optional<T>>(value: unknown, defaultValue?: R): ResolveOptional<T, R>`
160
- - `parseString<T extends string, R extends Optional<T>>(value: unknown, defaultValue?: R): ResolveOptional<T, R>`
161
- - `parseArray<T, R extends Optional<T[]>>(value: unknown, defaultValue?: R): ResolveOptional<T[], R>`
162
- - `parseDomainName<T extends string, R extends Optional<T>>(url: string, defaultValue?: R): ResolveOptional<T, R>`
170
+ - `parseNumber<T extends number, R extends Optional<T>>(value: unknown, defaultValue?: R): ResolveOptional<T, R>`
171
+ - `parseInteger(value: unknown, defaultValue?: Optional<number>): Optional<number>`
172
+ - `parseFloat<T extends number, R extends Optional<T>>(value: unknown, defaultValue?: R): ResolveOptional<T, R>`
173
+ - `parseString<T extends string, R extends Optional<T>>(value: unknown, defaultValue?: R): ResolveOptional<T, R>`
174
+ - `parseArray<T, R extends Optional<T[]>>(value: unknown, defaultValue?: R): ResolveOptional<T[], R>`
175
+ - `parseDomainName<T extends string, R extends Optional<T>>(url: string, defaultValue?: R): ResolveOptional<T, R>`
176
+
177
+ What the number parsers accept in a string (the whole string, after trimming;
178
+ anything else gives the default):
179
+
180
+ - `parseInteger`: digits with an optional sign, and a zero-only fraction
181
+ (`"42"`, `"-7"`, `"42.0"`). Not `""`, `"12abc"`, `"0x10"`, `"1e3"`, `"1,000"`.
182
+ A number is truncated toward zero (`-1.5` is `-1`).
183
+ - `parseFloat`: decimal notation with an optional exponent (`"1.5"`, `".5"`,
184
+ `"1.5e2"`). Not `""`, `"12abc"`, `"0x10"`, `"Infinity"`.
185
+ - `parseNumber`: everything `Number()` accepts for the whole string, so also
186
+ `"1e3"`, `"0xff"` and `"0b10"`. Not `""`, `"12abc"`, `"Infinity"`.
187
+ - A comma is accepted only as the one decimal separator (`"1,5"` is `1.5`).
188
+ Mixed forms (`"1,234.56"`, `"1.234,56"`), several commas and grouped forms
189
+ (`"1,000"`, `"12,345"`, which read as one thousand in English and as one in
190
+ German) give the default.
191
+ - `parseArray(NaN)` has no array to return: a single-argument call with a number
192
+ is typed `number[] | undefined`. Plain objects become `[object]`.
193
+ - `parseDomainName` returns the leftmost label of the hostname
194
+ (`"example.attacker.net"` is `"example"`). It is a display helper and not a
195
+ registrable-domain check: never use it for an allowlist, compare
196
+ `new URL(url).hostname` with the exact hosts you trust.
163
197
 
164
198
  ### Utility Functions
165
199
 
166
- - `ok(value)` and `err()` helpers for `MaybePromise` result objects
167
- - `getKeys<T extends Record<string, unknown>>(object: T): Array<keyof T>`
168
- - `arrayContainsCommonValue<T>(array1: T[], array2: T[]): boolean`
169
- - `isEmptyString(value: unknown): boolean`
170
- - `isEmptyLike(value: unknown): boolean`
171
- - `hasEmptyValues(value: unknown): boolean`
200
+ - `ok(value)` and `err()` helpers for `MaybePromise` result objects
201
+ - `getKeys<T extends Record<string, unknown>>(object: T): Array<keyof T>`
202
+ - `arrayContainsCommonValue<T>(array1: T[], array2: T[]): boolean`
203
+ - `isEmptyString(value: unknown): boolean`
204
+ - `isEmptyLike(value: unknown): boolean`
205
+ - `hasEmptyValues(value: unknown): boolean`
172
206
 
173
207
  ### Result Helpers
174
208
 
@@ -193,20 +227,98 @@ export async function flush(): MaybePromise<void> {
193
227
 
194
228
  ### Types
195
229
 
196
- - `Optional<T>`
197
- - `ResolveOptional<T, R>`
198
- - `Maybe<T>`
199
- - `ResolveMaybe<T, R>`
200
- - `Nullable<T>`
201
- - `ResolveNullable<T, R>`
202
- - `MaybePromise<T>`
203
- - `Success<T>`
204
- - `Failed<T>`
205
- - `JsonifiedObject<T>`
206
- - `JsonifiedValue<T>`
207
- - `Stringified<T>`
230
+ - `Optional<T>`
231
+ - `ResolveOptional<T, R>`
232
+ - `Maybe<T>`
233
+ - `ResolveMaybe<T, R>`
234
+ - `Nullable<T>`
235
+ - `ResolveNullable<T, R>`
236
+ - `MaybePromise<T>`
237
+ - `Success<T>`
238
+ - `Failed<T>`
239
+ - `JsonifiedObject<T>`
240
+ - `JsonifiedValue<T>`
241
+ - `Stringified<T>`
242
+
243
+ ### Oxlint rules
244
+
245
+ `@murky-web/typebuddy/oxlint` has `prefer-maybe`, `prefer-maybe-promise`,
246
+ `prefer-nullable`, `prefer-optional` and `require-try-catch`. They skip test
247
+ files: `*.test.*`, `*.spec.*` and `*.bench.*`, anything under a `__tests__/`,
248
+ `tests/`, `test/` or `__mocks__/` directory, and `vitest.setup.*`,
249
+ `vitest-setup.*` and `setupTests.*`. Names like `latest.ts` or `contest.ts` are
250
+ source files and stay checked. Directories count relative to the directory
251
+ oxlint runs in, so a project checked out under `/tmp/test/` is not silenced.
252
+
253
+ Autofixes only do what cannot change what the code means:
254
+
255
+ - A fix is offered only where the name it writes is free. `catch (err)` makes
256
+ `err()` the caught value, a local `ok` is not the helper, and another
257
+ library's `Maybe` is not ours: there the rule reports without a fix. `ok` and
258
+ `err` count as imported from `@murky-web/typebuddy` or
259
+ `@murky-web/typebuddy/result`.
260
+ - Fixed: `Promise<T>` to `MaybePromise<T>` on an async function this file
261
+ defines, `return;` to `return ok();`, `isError`/`value` literals with exactly
262
+ those two properties to `ok(value)`/`err()`, a `return err()` added to a catch
263
+ without a return, `T | null` to `Maybe<T>` and the like.
264
+ - A fix that needs an import carries it: appended to an existing import of the
265
+ same kind from the package, otherwise a new line after the last import (after
266
+ a `"use client"` directive, never above it). Fixes that need the same import
267
+ share one insertion point, so one `--fix` pass applies one of them and the
268
+ next pass applies the rest. A type joins an existing `import type { … }` of
269
+ the package, or else a value import as an inline `type Name` specifier. In a
270
+ module, `declare global` and `declare module` blocks get the import like any
271
+ other code. In a script file (no `import` or `export`, e.g. `vite-env.d.ts`)
272
+ no import is added, because that would turn the script into a module: a type
273
+ is written by its global name (it needs the `@murky-web/typebuddy/globals`
274
+ entry), a fix that needs `ok` or `err` is not offered, and `Promise` to
275
+ `MaybePromise` on the file's own functions is a suggestion there, since the
276
+ `ok(...)`/`err()` that must follow cannot be fixed.
277
+ - Suggestions, applied one by one from your editor: wrapping a returned value in
278
+ `ok(...)` (it may already be a `Result` or a `MaybePromise`), wrapping a
279
+ function body in `try`/`catch` (every exception becomes `err()`), and
280
+ `Promise` to `MaybePromise` in an interface method, a function type or an
281
+ overload (that shape is often a library's).
282
+ - Async generators are left alone.
283
+
284
+ ### Migrating from 2.x to 3.0
285
+
286
+ - `Success<T>` is `{ isError: false; value: T }`. Code that read
287
+ `ok(null).isError` as `true` in the types is wrong; read `value`.
288
+ - `isNumber`, `isInteger` and `isFloat` narrow to the brands `FiniteNumber`,
289
+ `IntegerNumber` and `FloatNumber` (assignable to `number`). The false branch
290
+ keeps `number`: after `if (!isNumber(value))` a `number | null` is still
291
+ `number | null`. Where you relied on it becoming `null`, test `isNull`. The
292
+ brand also spreads into inferred types: `[1, null].filter(isNumber)` is
293
+ `FiniteNumber[]`, so `xs.push(3)` fails. Widen with an annotation:
294
+ `const xs: number[] = [1, null].filter(isNumber);`.
295
+ - `JSON.parse` of a `Stringified<T>` returns `JsonifiedValue<T>`, no longer
296
+ `JsonifiedObject<T>`. Generic code that declares `JsonifiedObject<T>` as its
297
+ return type has to change it to `JsonifiedValue<T>`.
298
+ - `isFloat(Infinity)` is `false`, `fastIsArray` is `Array.isArray`,
299
+ `isUuidString` accepts versions 6 to 8 and the nil and max UUID, and
300
+ `isUlidString` accepts lower case. Check code that relied on the old answers.
301
+ - `parseInteger` also refuses numbers beyond 2^53 (`1e21`).
302
+ - `prefer-maybe`, `prefer-nullable`, `prefer-optional` and the `MaybePromise`
303
+ fix now add an `import type` line (or merge into an existing import of the
304
+ package). A project that relied on the global names in a module file gets the
305
+ import; script files are left alone.
306
+ - `isEmptyObject(value)` has no type parameter and narrows to `EmptyObject`. A
307
+ symbol key or a non-enumerable key now counts as a key.
308
+ - `parseArray(value: number)` is typed `number[] | undefined`. Handle the
309
+ `undefined` or pass a default.
310
+ - `parseInteger`, `parseFloat` and `parseNumber` return the default for blank
311
+ strings, for grouped numbers such as `"1,000"`, and for anything that is not a
312
+ number as a whole (`"12abc"`). `parseInteger` takes digits only (`"1e3"`,
313
+ `"0x10"` give the default), truncates toward zero and refuses digits beyond
314
+ 2^53. If you used `"1,000"` or `"1e3"` as input, normalise the string before
315
+ parsing.
316
+ - `prefer-maybe-promise` and `require-try-catch`: `--fix` no longer wraps return
317
+ values in `ok(...)`, no longer wraps bodies in `try`/`catch` and no longer
318
+ rewrites `Promise` in interface methods, function types and overloads. They
319
+ are editor suggestions now; apply them by hand.
208
320
 
209
321
  ### Tooling Entries
210
322
 
211
- - `@murky-web/typebuddy/oxlint`
212
- - `@murky-web/typebuddy/globals`
323
+ - `@murky-web/typebuddy/oxlint`
324
+ - `@murky-web/typebuddy/globals`
@@ -1,5 +1,5 @@
1
1
  import { isArray } from "./guards.js";
2
- //#region src/collections.ts
2
+ // src/collections.ts
3
3
  /** Operations on collections rather than checks on them. */
4
4
  /**
5
5
  * Get the keys of an object.
@@ -24,5 +24,4 @@ function arrayContainsCommonValue(array1, array2) {
24
24
  return valueOccurrences.has(value);
25
25
  });
26
26
  }
27
- //#endregion
28
27
  export { arrayContainsCommonValue, getKeys };
package/dist/empty.js CHANGED
@@ -1,31 +1,53 @@
1
1
  import { isArray, isBoolean, isEmptyObject, isEmptyString, isNull, isObject, isString, isUndefined } from "./guards.js";
2
- //#region src/empty.ts
2
+ // src/empty.ts
3
3
  /**
4
4
  * The recursive "is this effectively blank" checks. Split out because they walk
5
5
  * arbitrary object graphs — far more code than the one-line guards they are
6
6
  * filed next to, and needed far less often.
7
7
  */
8
+ function toContainer(value) {
9
+ if (isArray(value)) return {
10
+ entries: value,
11
+ node: value
12
+ };
13
+ if (isObject(value) && Object.getPrototypeOf(value) === Object.prototype) return {
14
+ entries: Object.values(value),
15
+ node: value
16
+ };
17
+ }
8
18
  /**
9
19
  * Returns true for values that behave like "empty" application input.
10
20
  *
21
+ * A reference back to an array or object that is still being walked adds no
22
+ * content of its own, so it counts as empty and the walk ends there: a cyclic
23
+ * structure is empty-like when everything else in it is. A value that merely
24
+ * appears twice is not a cycle and is walked both times.
25
+ *
11
26
  * @param {unknown} value - The value to check.
12
27
  * @returns {boolean} True if the value is nullish, empty string, empty array,
13
28
  * false, or a plain object whose values are all empty-like.
14
29
  */
15
30
  function isEmptyLike(value) {
16
- if (isNull(value) || isUndefined(value)) return true;
17
- if (isString(value)) return isEmptyString(value);
18
- if (isArray(value)) return value.every((entry) => {
19
- return isEmptyLike(entry);
20
- });
21
- if (isBoolean(value)) return !value;
22
- if (isObject(value)) {
23
- if (Object.getPrototypeOf(value) !== Object.prototype) return false;
24
- return Object.values(value).every((entry) => {
25
- return isEmptyLike(entry);
31
+ const walking = /* @__PURE__ */ new WeakSet();
32
+ /**
33
+ * @param {unknown} candidate - The value being looked at.
34
+ * @returns {boolean} True if the candidate is empty-like.
35
+ */
36
+ function walk(candidate) {
37
+ if (isNull(candidate) || isUndefined(candidate)) return true;
38
+ if (isString(candidate)) return isEmptyString(candidate);
39
+ if (isBoolean(candidate)) return !candidate;
40
+ const container = toContainer(candidate);
41
+ if (container === void 0) return false;
42
+ if (walking.has(container.node)) return true;
43
+ walking.add(container.node);
44
+ const result = container.entries.every((entry) => {
45
+ return walk(entry);
26
46
  });
47
+ walking.delete(container.node);
48
+ return result;
27
49
  }
28
- return false;
50
+ return walk(value);
29
51
  }
30
52
  /**
31
53
  * Checks if the provided value contains empty values.
@@ -49,5 +71,4 @@ function hasEmptyValues(value) {
49
71
  }
50
72
  return isEmptyObject(value);
51
73
  }
52
- //#endregion
53
74
  export { hasEmptyValues, isEmptyLike };
package/dist/guards.js CHANGED
@@ -1,4 +1,4 @@
1
- //#region src/guards.ts
1
+ // src/guards.ts
2
2
  const EMPTY_LENGTH = 0;
3
3
  function isString(value) {
4
4
  return typeof value === "string";
@@ -65,7 +65,7 @@ function isEmptyArray(value) {
65
65
  return Array.isArray(value) && value.length === EMPTY_LENGTH;
66
66
  }
67
67
  function fastIsArray(value) {
68
- return Object.prototype.toString.call(value) === "[object Array]";
68
+ return Array.isArray(value);
69
69
  }
70
70
  function isNumber(value) {
71
71
  if (typeof value === "string" && value.trim() === "") return false;
@@ -82,8 +82,12 @@ function isFunction(value) {
82
82
  return typeof value === "function";
83
83
  }
84
84
  function isPromise(value) {
85
- if (typeof value !== "object" || value === null) return false;
86
- return typeof Reflect.get(value, "then") === "function";
85
+ if (typeof value !== "object" && typeof value !== "function" || value === null) return false;
86
+ try {
87
+ return typeof Reflect.get(value, "then") === "function";
88
+ } catch {
89
+ return false;
90
+ }
87
91
  }
88
92
  function isError(value) {
89
93
  return value instanceof Error;
@@ -97,8 +101,25 @@ function isRegExp(value) {
97
101
  function isSymbol(value) {
98
102
  return typeof value === "symbol";
99
103
  }
104
+ /**
105
+ * Check if a value is an empty plain object: its prototype is
106
+ * `Object.prototype` and it has no own keys at all. A symbol key or a
107
+ * non-enumerable key counts as a key, so `{ [Symbol()]: 1 }` is not empty.
108
+ *
109
+ * The guard narrows to `EmptyObject`, never to the caller's own object type: an
110
+ * object type with required keys can not be empty, and narrowing to it would
111
+ * hide the very values the guard rejects from the false branch.
112
+ *
113
+ * @param {unknown} value - The value to check.
114
+ * @returns {boolean} True if the value is an empty plain object.
115
+ */
100
116
  function isEmptyObject(value) {
101
- return typeof value === "object" && !isNull(value) && !isUndefined(value) && !isEmptyArray(value) && Object.getPrototypeOf(value) === Object.prototype && Object.keys(value).length === EMPTY_LENGTH;
117
+ if (typeof value !== "object" || value === null) return false;
118
+ try {
119
+ return Object.getPrototypeOf(value) === Object.prototype && Reflect.ownKeys(value).length === EMPTY_LENGTH;
120
+ } catch {
121
+ return false;
122
+ }
102
123
  }
103
124
  /**
104
125
  * Check if a value is an instance of a class.
@@ -111,7 +132,9 @@ function isInstanceOf(value, constructor) {
111
132
  return value instanceof constructor;
112
133
  }
113
134
  /**
114
- * Check if a value is an integer.
135
+ * Check if a value is an integer. The narrowed type is `IntegerNumber`, a brand
136
+ * over `number`, so the false branch still contains the `number`s this guard
137
+ * rejects.
115
138
  *
116
139
  * @param {unknown} value - The value to check.
117
140
  * @returns {boolean} True if the value is an integer.
@@ -120,13 +143,14 @@ function isInteger(value) {
120
143
  return typeof value === "number" && Number.isInteger(value);
121
144
  }
122
145
  /**
123
- * Check if a value is a float.
146
+ * Check if a value is a float: a finite number with a fractional part. `NaN`
147
+ * and `±Infinity` are not floats, consistent with `isNumber`. The narrowed type
148
+ * is `FloatNumber`, a brand over `number`, like `isInteger`'s.
124
149
  *
125
150
  * @param {unknown} value - The value to check.
126
151
  * @returns {boolean} True if the value is a float.
127
152
  */
128
153
  function isFloat(value) {
129
- return typeof value === "number" && !Number.isNaN(value) && !Number.isInteger(value);
154
+ return typeof value === "number" && Number.isFinite(value) && !Number.isInteger(value);
130
155
  }
131
- //#endregion
132
156
  export { fastIsArray, isArray, isBoolean, isDate, isEmptyArray, isEmptyObject, isEmptyString, isError, isFloat, isFunction, isInstanceOf, isInteger, isMaybe, isNull, isNullable, isNumber, isObject, isOptional, isPromise, isRegExp, isString, isSymbol, isUndefined };
package/dist/ids.js CHANGED
@@ -1,14 +1,15 @@
1
1
  import { isString } from "./guards.js";
2
- //#region src/ids.ts
2
+ // src/ids.ts
3
3
  /**
4
4
  * Identifier-format checks. Their two regex literals are the only module-level
5
5
  * allocations in the package, which is the whole reason they live alone: a
6
6
  * bundler that keeps anything in a module keeps those too.
7
7
  */
8
- const uuidRegex = /^[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}$/;
9
- const ulidRegex = /^[0123456789ABCDEFGHJKMNPQRSTVWXYZ]{26}$/;
8
+ const uuidRegex = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|0{8}-0{4}-0{4}-0{4}-0{12}|f{8}-f{4}-f{4}-f{4}-f{12})$/i;
9
+ const ulidRegex = /^[0-7][0-9A-HJKMNP-TV-Z]{25}$/i;
10
10
  /**
11
- * Returns true if the input is a UUID string.
11
+ * Returns true if the input is a UUID string: versions 1 to 8, or the nil or
12
+ * max UUID, in either case.
12
13
  *
13
14
  * @param {string} input - The input to check.
14
15
  * @returns {boolean} True if the input is a UUID string.
@@ -17,7 +18,7 @@ function isUuidString(input) {
17
18
  return isString(input) && uuidRegex.test(input);
18
19
  }
19
20
  /**
20
- * Returns true if the input is a ULID string.
21
+ * Returns true if the input is a ULID string, in either case.
21
22
  *
22
23
  * @param {string} input - The input to check.
23
24
  * @returns {boolean} True if the input is a ULID string.
@@ -25,5 +26,4 @@ function isUuidString(input) {
25
26
  function isUlidString(input) {
26
27
  return typeof input === "string" && ulidRegex.test(input);
27
28
  }
28
- //#endregion
29
29
  export { isUlidString, isUuidString };
package/dist/oxlint.js CHANGED
@@ -3,16 +3,16 @@ import { errorSafeAsyncRule as rule$1 } from "./rules/maybe_promise_rule.js";
3
3
  import { maybeRule as rule$2 } from "./rules/maybe_rule.js";
4
4
  import { nullableRule as rule$3 } from "./rules/nullable_rule.js";
5
5
  import { optionalRule as rule$4 } from "./rules/optional_rule.js";
6
- //#region oxlint/index.ts
6
+ import { withoutTestFiles } from "./rules/test_file.js";
7
+ // oxlint/index.ts
7
8
  const plugin = {
8
9
  meta: { name: "typebuddy" },
9
10
  rules: {
10
- "prefer-maybe": rule$2,
11
- "prefer-maybe-promise": rule$1,
12
- "prefer-nullable": rule$3,
13
- "prefer-optional": rule$4,
14
- "require-try-catch": rule
11
+ "prefer-maybe": withoutTestFiles(rule$2),
12
+ "prefer-maybe-promise": withoutTestFiles(rule$1),
13
+ "prefer-nullable": withoutTestFiles(rule$3),
14
+ "prefer-optional": withoutTestFiles(rule$4),
15
+ "require-try-catch": withoutTestFiles(rule)
15
16
  }
16
17
  };
17
- //#endregion
18
18
  export { plugin as default, plugin as typebuddyOxlintPlugin };
package/dist/parse.js CHANGED
@@ -1,38 +1,63 @@
1
- import { isArray, isEmptyObject, isNull, isNumber, isString, isUndefined } from "./guards.js";
2
- //#region src/parse.ts
1
+ import { isArray, isNull, isNumber, isObject, isString, isUndefined } from "./guards.js";
2
+ // src/parse.ts
3
3
  /**
4
4
  * Coercions from unknown input to a concrete type, each with a caller-supplied
5
5
  * fallback. Separate from the guards because parsing is what you do _after_ a
6
6
  * guard said no.
7
7
  */
8
8
  const EMPTY_LENGTH = 0;
9
+ const ZERO = 0;
10
+ const INTEGER_TEXT = /^[+-]?\d+(?:\.0+)?$/;
11
+ const DECIMAL_TEXT = /^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$/;
12
+ const COMMA_DECIMAL_TEXT = /^[+-]?\d*,\d+$/;
13
+ const GROUPED_TEXT = /^[+-]?[1-9]\d{0,2},\d{3}$/;
14
+ function toDotDecimal(text) {
15
+ if (!COMMA_DECIMAL_TEXT.test(text)) return text;
16
+ if (GROUPED_TEXT.test(text)) return;
17
+ return text.replace(",", ".");
18
+ }
19
+ function withoutNegativeZero(value) {
20
+ if (value === ZERO) return ZERO;
21
+ return value;
22
+ }
9
23
  function cloneDefaultArray(defaultValue) {
10
24
  if (!defaultValue) return defaultValue;
11
25
  return [...defaultValue];
12
26
  }
13
27
  function parseInteger(value, defaultValue) {
14
- if (isNumber(value)) return Math.floor(value);
28
+ if (isNumber(value)) {
29
+ const truncated = Math.trunc(value);
30
+ if (Number.isSafeInteger(truncated)) return withoutNegativeZero(truncated);
31
+ return defaultValue;
32
+ }
15
33
  if (isString(value)) {
16
- const parsed = Number(value.trim());
17
- if (Number.isInteger(parsed)) return parsed;
34
+ const trimmed = value.trim();
35
+ if (INTEGER_TEXT.test(trimmed)) {
36
+ const parsed = Number(trimmed);
37
+ if (Number.isSafeInteger(parsed)) return withoutNegativeZero(parsed);
38
+ }
18
39
  }
19
40
  return defaultValue;
20
41
  }
21
42
  function parseFloat(value, defaultValue) {
22
- if (isNumber(value)) return value;
43
+ if (isNumber(value)) return withoutNegativeZero(value);
23
44
  if (isString(value)) {
24
- const normalizedValue = value.trim().replace(",", ".");
25
- const parsed = Number.parseFloat(normalizedValue);
26
- if (!Number.isNaN(parsed)) return parsed;
45
+ const dotted = toDotDecimal(value.trim());
46
+ if (dotted !== void 0 && DECIMAL_TEXT.test(dotted)) {
47
+ const parsed = Number(dotted);
48
+ if (Number.isFinite(parsed)) return withoutNegativeZero(parsed);
49
+ }
27
50
  }
28
51
  return defaultValue;
29
52
  }
30
53
  function parseNumber(value, defaultValue) {
31
- if (isNumber(value)) return value;
54
+ if (isNumber(value)) return withoutNegativeZero(value);
32
55
  if (isString(value)) {
33
- const normalizedValue = value.trim().replace(",", ".");
34
- const parsed = Number(normalizedValue);
35
- if (Number.isFinite(parsed)) return parsed;
56
+ const dotted = toDotDecimal(value.trim());
57
+ if (dotted !== void 0 && dotted !== "") {
58
+ const parsed = Number(dotted);
59
+ if (Number.isFinite(parsed)) return withoutNegativeZero(parsed);
60
+ }
36
61
  }
37
62
  return defaultValue;
38
63
  }
@@ -59,7 +84,7 @@ function parseArray(value, defaultValue) {
59
84
  return entry.length > EMPTY_LENGTH;
60
85
  });
61
86
  if (isNumber(value)) return [value];
62
- if (isEmptyObject(value)) return [value];
87
+ if (isObject(value)) return [value];
63
88
  if (isNull(value) || isUndefined(value)) return cloneDefaultArray(defaultValue);
64
89
  return cloneDefaultArray(defaultValue);
65
90
  }
@@ -77,5 +102,4 @@ function parseDomainName(url, defaultValue) {
77
102
  return defaultValue;
78
103
  }
79
104
  }
80
- //#endregion
81
105
  export { parseArray, parseDomainName, parseFloat, parseInteger, parseNumber, parseString };
package/dist/result.js CHANGED
@@ -1,4 +1,4 @@
1
- //#region src/result.ts
1
+ // src/result.ts
2
2
  /**
3
3
  * Checks if the provided result is a `Success` type.
4
4
  *
@@ -6,14 +6,15 @@
6
6
  * ```typescript
7
7
  * const result = await someAsyncFunction();
8
8
  * if (isSuccess(result)) {
9
- * return result.value; // TypeScript knows `value` is of type `T`
9
+ * return result.value; // TypeScript knows `value` is of type `T`
10
10
  * }
11
11
  * ```
12
12
  *
13
13
  * @template R The result type passed in. The guard narrows it by its `isError`
14
- * flag, so `value` keeps the success type without an extra `| null`.
15
- * @param {R} result The result to check, which can be either a `Success<T>`
16
- * or `Failed`.
14
+ * flag, so `value` keeps the success type without an extra `| null`. A
15
+ * `Result<T | null>`, a generic `Result<T>` and a `Result<any>` all work.
16
+ * @param {R} result The result to check, which can be either a `Success<T>` or
17
+ * `Failed`.
17
18
  * @returns {boolean} `true` if the result is a `Success<T>`, `false` if it is a
18
19
  * `Failed`. This function acts as a type guard, narrowing `result` to its
19
20
  * `Success` member when the condition is met.
@@ -35,5 +36,4 @@ function err(...args) {
35
36
  value: value ?? null
36
37
  };
37
38
  }
38
- //#endregion
39
39
  export { err, isSuccess, ok };