@murky-web/typebuddy 1.2.0 → 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.
@@ -0,0 +1,28 @@
1
+ import { isArray } from "./guards.js";
2
+ //#region src/collections.ts
3
+ /** Operations on collections rather than checks on them. */
4
+ /**
5
+ * Get the keys of an object.
6
+ *
7
+ * @param {unknown} object - The object to get the keys of.
8
+ * @returns {Array} Keys of object.
9
+ */
10
+ function getKeys(object) {
11
+ return Object.keys(object);
12
+ }
13
+ /**
14
+ * Compares two arrays and returns true if they have at least one common value.
15
+ *
16
+ * @param {readonly T[]} array1 - First array.
17
+ * @param {readonly T[]} array2 - Second array.
18
+ * @returns {boolean} True if the arrays have at least one common value.
19
+ */
20
+ function arrayContainsCommonValue(array1, array2) {
21
+ if (!isArray(array1) || !isArray(array2)) return false;
22
+ const valueOccurrences = new Set(array1);
23
+ return array2.some((value) => {
24
+ return valueOccurrences.has(value);
25
+ });
26
+ }
27
+ //#endregion
28
+ export { arrayContainsCommonValue, getKeys };
package/dist/empty.js ADDED
@@ -0,0 +1,53 @@
1
+ import { isArray, isBoolean, isEmptyObject, isEmptyString, isNull, isObject, isString, isUndefined } from "./guards.js";
2
+ //#region src/empty.ts
3
+ /**
4
+ * The recursive "is this effectively blank" checks. Split out because they walk
5
+ * arbitrary object graphs — far more code than the one-line guards they are
6
+ * filed next to, and needed far less often.
7
+ */
8
+ /**
9
+ * Returns true for values that behave like "empty" application input.
10
+ *
11
+ * @param {unknown} value - The value to check.
12
+ * @returns {boolean} True if the value is nullish, empty string, empty array,
13
+ * false, or a plain object whose values are all empty-like.
14
+ */
15
+ 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);
26
+ });
27
+ }
28
+ return false;
29
+ }
30
+ /**
31
+ * Checks if the provided value contains empty values.
32
+ *
33
+ * This function determines if the given value is either an empty string, an
34
+ * empty object, or a string representation of an empty object.
35
+ *
36
+ * @param {unknown} value - The value to check for emptiness. It can be of any
37
+ * type.
38
+ * @returns {boolean} `true` if the value is an empty string, an empty object,
39
+ * or a string representation of an empty object; otherwise, `false`.
40
+ */
41
+ function hasEmptyValues(value) {
42
+ if (isString(value)) {
43
+ try {
44
+ if (isEmptyObject(JSON.parse(value))) return true;
45
+ } catch {
46
+ return isEmptyString(value);
47
+ }
48
+ return isEmptyString(value);
49
+ }
50
+ return isEmptyObject(value);
51
+ }
52
+ //#endregion
53
+ export { hasEmptyValues, isEmptyLike };
package/dist/guards.js ADDED
@@ -0,0 +1,132 @@
1
+ //#region src/guards.ts
2
+ const EMPTY_LENGTH = 0;
3
+ function isString(value) {
4
+ return typeof value === "string";
5
+ }
6
+ /**
7
+ * Parses the input value as a boolean. Returns false if the value is no string.
8
+ *
9
+ * @param {unknown} value - The value to check.
10
+ * @returns {boolean} True if the value is a string.
11
+ */
12
+ function isEmptyString(value) {
13
+ if (!isString(value)) return false;
14
+ return value.trim() === "";
15
+ }
16
+ /**
17
+ * Returns true if the value is null.
18
+ *
19
+ * @param {unknown} value - The value to check.
20
+ * @returns {boolean} True if the value is null.
21
+ */
22
+ function isNull(value) {
23
+ return value === null;
24
+ }
25
+ /**
26
+ * Returns true if the value is undefined.
27
+ *
28
+ * @param {unknown} value - The value to check.
29
+ * @returns {boolean} True if the value is undefined.
30
+ */
31
+ function isUndefined(value) {
32
+ return typeof value === "undefined";
33
+ }
34
+ /**
35
+ * Checks whether an Optional value is currently in its missing state.
36
+ *
37
+ * @param {Optional<T>} value - The Optional value to check.
38
+ * @returns {boolean} True when the value is undefined.
39
+ */
40
+ function isOptional(value) {
41
+ return isUndefined(value);
42
+ }
43
+ /**
44
+ * Checks whether a Maybe value is currently in its missing state.
45
+ *
46
+ * @param {Maybe<T>} value - The Maybe value to check.
47
+ * @returns {boolean} True when the value is null.
48
+ */
49
+ function isMaybe(value) {
50
+ return isNull(value);
51
+ }
52
+ /**
53
+ * Checks whether a Nullable value is currently in its missing state.
54
+ *
55
+ * @param {Nullable<T>} value - The Nullable value to check.
56
+ * @returns {boolean} True when the value is null or undefined.
57
+ */
58
+ function isNullable(value) {
59
+ return isNull(value) || isUndefined(value);
60
+ }
61
+ function isArray(value) {
62
+ return Array.isArray(value);
63
+ }
64
+ function isEmptyArray(value) {
65
+ return Array.isArray(value) && value.length === EMPTY_LENGTH;
66
+ }
67
+ function fastIsArray(value) {
68
+ return Object.prototype.toString.call(value) === "[object Array]";
69
+ }
70
+ function isNumber(value) {
71
+ if (typeof value === "string" && value.trim() === "") return false;
72
+ return typeof value === "number" && !Number.isNaN(value) && Number.isFinite(value);
73
+ }
74
+ function isObject(value) {
75
+ if (typeof value !== "object" || value === null || isArray(value) || Object.prototype.toString.call(value) !== "[object Object]") return false;
76
+ return Object.getPrototypeOf(value) === Object.prototype;
77
+ }
78
+ function isBoolean(value) {
79
+ return typeof value === "boolean";
80
+ }
81
+ function isFunction(value) {
82
+ return typeof value === "function";
83
+ }
84
+ function isPromise(value) {
85
+ if (typeof value !== "object" || value === null) return false;
86
+ return typeof Reflect.get(value, "then") === "function";
87
+ }
88
+ function isError(value) {
89
+ return value instanceof Error;
90
+ }
91
+ function isDate(value) {
92
+ return value instanceof Date;
93
+ }
94
+ function isRegExp(value) {
95
+ return value instanceof RegExp;
96
+ }
97
+ function isSymbol(value) {
98
+ return typeof value === "symbol";
99
+ }
100
+ 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;
102
+ }
103
+ /**
104
+ * Check if a value is an instance of a class.
105
+ *
106
+ * @param {unknown} value - The value to check.
107
+ * @param {unknown} constructor - The class constructor to check against.
108
+ * @returns {boolean} True if the value is an instance of the class.
109
+ */
110
+ function isInstanceOf(value, constructor) {
111
+ return value instanceof constructor;
112
+ }
113
+ /**
114
+ * Check if a value is an integer.
115
+ *
116
+ * @param {unknown} value - The value to check.
117
+ * @returns {boolean} True if the value is an integer.
118
+ */
119
+ function isInteger(value) {
120
+ return typeof value === "number" && Number.isInteger(value);
121
+ }
122
+ /**
123
+ * Check if a value is a float.
124
+ *
125
+ * @param {unknown} value - The value to check.
126
+ * @returns {boolean} True if the value is a float.
127
+ */
128
+ function isFloat(value) {
129
+ return typeof value === "number" && !Number.isNaN(value) && !Number.isInteger(value);
130
+ }
131
+ //#endregion
132
+ 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 ADDED
@@ -0,0 +1,29 @@
1
+ import { isString } from "./guards.js";
2
+ //#region src/ids.ts
3
+ /**
4
+ * Identifier-format checks. Their two regex literals are the only module-level
5
+ * allocations in the package, which is the whole reason they live alone: a
6
+ * bundler that keeps anything in a module keeps those too.
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}$/;
10
+ /**
11
+ * Returns true if the input is a UUID string.
12
+ *
13
+ * @param {string} input - The input to check.
14
+ * @returns {boolean} True if the input is a UUID string.
15
+ */
16
+ function isUuidString(input) {
17
+ return isString(input) && uuidRegex.test(input);
18
+ }
19
+ /**
20
+ * Returns true if the input is a ULID string.
21
+ *
22
+ * @param {string} input - The input to check.
23
+ * @returns {boolean} True if the input is a ULID string.
24
+ */
25
+ function isUlidString(input) {
26
+ return typeof input === "string" && ulidRegex.test(input);
27
+ }
28
+ //#endregion
29
+ export { isUlidString, isUuidString };
package/dist/index.js CHANGED
@@ -1,2 +1,7 @@
1
- import { arrayContainsCommonValue, err, fastIsArray, getKeys, hasEmptyValues, isArray, isBoolean, isDate, isEmptyArray, isEmptyLike, isEmptyObject, isEmptyString, isError, isFloat, isFunction, isInstanceOf, isInteger, isMaybe, isNull, isNullable, isNumber, isObject, isOptional, isPromise, isRegExp, isString, isSuccess, isSymbol, isUlidString, isUndefined, isUuidString, ok, parseArray, parseDomainName, parseFloat, parseInteger, parseNumber, parseString } from "./src/type_helper.js";
1
+ import { fastIsArray, isArray, isBoolean, isDate, isEmptyArray, isEmptyObject, isEmptyString, isError, isFloat, isFunction, isInstanceOf, isInteger, isMaybe, isNull, isNullable, isNumber, isObject, isOptional, isPromise, isRegExp, isString, isSymbol, isUndefined } from "./guards.js";
2
+ import { arrayContainsCommonValue, getKeys } from "./collections.js";
3
+ import { hasEmptyValues, isEmptyLike } from "./empty.js";
4
+ import { isUlidString, isUuidString } from "./ids.js";
5
+ import { parseArray, parseDomainName, parseFloat, parseInteger, parseNumber, parseString } from "./parse.js";
6
+ import { err, isSuccess, ok } from "./result.js";
2
7
  export { arrayContainsCommonValue, err, fastIsArray, getKeys, hasEmptyValues, isArray, isBoolean, isDate, isEmptyArray, isEmptyLike, isEmptyObject, isEmptyString, isError, isFloat, isFunction, isInstanceOf, isInteger, isMaybe, isNull, isNullable, isNumber, isObject, isOptional, isPromise, isRegExp, isString, isSuccess, isSymbol, isUlidString, isUndefined, isUuidString, ok, parseArray, parseDomainName, parseFloat, parseInteger, parseNumber, parseString };
package/dist/parse.js ADDED
@@ -0,0 +1,81 @@
1
+ import { isArray, isEmptyObject, isNull, isNumber, isString, isUndefined } from "./guards.js";
2
+ //#region src/parse.ts
3
+ /**
4
+ * Coercions from unknown input to a concrete type, each with a caller-supplied
5
+ * fallback. Separate from the guards because parsing is what you do _after_ a
6
+ * guard said no.
7
+ */
8
+ const EMPTY_LENGTH = 0;
9
+ function cloneDefaultArray(defaultValue) {
10
+ if (!defaultValue) return defaultValue;
11
+ return [...defaultValue];
12
+ }
13
+ function parseInteger(value, defaultValue) {
14
+ if (isNumber(value)) return Math.floor(value);
15
+ if (isString(value)) {
16
+ const parsed = Number(value.trim());
17
+ if (Number.isInteger(parsed)) return parsed;
18
+ }
19
+ return defaultValue;
20
+ }
21
+ function parseFloat(value, defaultValue) {
22
+ if (isNumber(value)) return value;
23
+ if (isString(value)) {
24
+ const normalizedValue = value.trim().replace(",", ".");
25
+ const parsed = Number.parseFloat(normalizedValue);
26
+ if (!Number.isNaN(parsed)) return parsed;
27
+ }
28
+ return defaultValue;
29
+ }
30
+ function parseNumber(value, defaultValue) {
31
+ if (isNumber(value)) return value;
32
+ if (isString(value)) {
33
+ const normalizedValue = value.trim().replace(",", ".");
34
+ const parsed = Number(normalizedValue);
35
+ if (Number.isFinite(parsed)) return parsed;
36
+ }
37
+ return defaultValue;
38
+ }
39
+ /**
40
+ * Parses the input value as a string. Returns an empty string if the value
41
+ * cannot be converted.
42
+ *
43
+ * @param {unknown} value - The value to check.
44
+ * @param {Optional<string>} defaultValue - Value gets returned if string could
45
+ * not be parsed.
46
+ * @returns {string} The parsed string.
47
+ */
48
+ function parseString(value, defaultValue = "") {
49
+ if (isString(value)) return value;
50
+ if (isNumber(value)) return value.toString();
51
+ if (typeof value === "boolean") return value.toString();
52
+ return defaultValue;
53
+ }
54
+ function parseArray(value, defaultValue) {
55
+ if (isArray(value)) return [...value];
56
+ if (isString(value)) return value.split(/[,|;\n\t ]+/).map((entry) => {
57
+ return entry.trim();
58
+ }).filter((entry) => {
59
+ return entry.length > EMPTY_LENGTH;
60
+ });
61
+ if (isNumber(value)) return [value];
62
+ if (isEmptyObject(value)) return [value];
63
+ if (isNull(value) || isUndefined(value)) return cloneDefaultArray(defaultValue);
64
+ return cloneDefaultArray(defaultValue);
65
+ }
66
+ function parseDomainName(url, defaultValue) {
67
+ const normalizedValue = url.trim();
68
+ if (normalizedValue === "" || normalizedValue.startsWith("/")) return defaultValue;
69
+ let urlCandidate = normalizedValue;
70
+ if (!normalizedValue.includes("://")) urlCandidate = `https://${normalizedValue}`;
71
+ try {
72
+ const { hostname } = new URL(urlCandidate);
73
+ const [domainName] = hostname.replace(/^www\d?\./i, "").split(".");
74
+ if (domainName === void 0 || domainName === "") return defaultValue;
75
+ return domainName;
76
+ } catch {
77
+ return defaultValue;
78
+ }
79
+ }
80
+ //#endregion
81
+ export { parseArray, parseDomainName, parseFloat, parseInteger, parseNumber, parseString };
package/dist/result.js ADDED
@@ -0,0 +1,38 @@
1
+ //#region src/result.ts
2
+ /**
3
+ * Checks if the provided result is a `Success` type.
4
+ *
5
+ * @example
6
+ * ```typescript
7
+ * const result = await someAsyncFunction();
8
+ * if (isSuccess(result)) {
9
+ * return result.value; // TypeScript knows `value` is of type `T`
10
+ * }
11
+ * ```
12
+ *
13
+ * @template T The type of the value contained in the `Success` type.
14
+ * @param {Readonly<Result<T>>} result The result to check, which can
15
+ * be either a `Success<T>` or `Failed`.
16
+ * @returns {boolean} `true` if the result is a `Success<T>`, `false` if it is a
17
+ * `Failed`. This function acts as a type guard, narrowing the type of
18
+ * `result` to `Success<T>` when the condition is met.
19
+ */
20
+ function isSuccess(result) {
21
+ return !result.isError;
22
+ }
23
+ function ok(...args) {
24
+ const [value] = args;
25
+ return {
26
+ isError: false,
27
+ value
28
+ };
29
+ }
30
+ function err(...args) {
31
+ const [value] = args;
32
+ return {
33
+ isError: true,
34
+ value: value ?? null
35
+ };
36
+ }
37
+ //#endregion
38
+ export { err, isSuccess, ok };
@@ -1,3 +1,4 @@
1
+ import { throwsDeliberately } from "./deliberate_throw.js";
1
2
  //#region rules/async_rule.ts
2
3
  function isNode(value) {
3
4
  return typeof value === "object" && value !== null && "type" in value;
@@ -91,6 +92,7 @@ ${indent}}
91
92
  const bodyNode = node.body;
92
93
  if (!bodyNode || Array.isArray(bodyNode) || bodyNode.type !== "BlockStatement") return;
93
94
  if (hasTryCatch(Array.isArray(bodyNode.body) ? bodyNode.body : [])) return;
95
+ if (throwsDeliberately(bodyNode)) return;
94
96
  context.report({
95
97
  node,
96
98
  messageId: "missingTryCatch",
@@ -0,0 +1,49 @@
1
+ //#region rules/deliberate_throw.ts
2
+ const FUNCTION_TYPES = /* @__PURE__ */ new Set([
3
+ "ArrowFunctionExpression",
4
+ "FunctionDeclaration",
5
+ "FunctionExpression"
6
+ ]);
7
+ function isNode(value) {
8
+ return typeof value === "object" && value !== null && "type" in value;
9
+ }
10
+ /**
11
+ * Whether a function body throws on purpose.
12
+ *
13
+ * A `throw` in a function's own body is the author saying this failure is not a
14
+ * value to hand back. A missing manifest for a route the app is navigating to,
15
+ * an unreachable branch, a broken invariant — those should be loud. Turning them
16
+ * into `err()` converts a bug into a silently handled outcome, and the caller
17
+ * degrades politely instead of surfacing that something is wrong.
18
+ *
19
+ * So both async rules leave such a function alone. The rules exist to push
20
+ * *recoverable* failures into the return type, not to abolish throwing.
21
+ *
22
+ * Two boundaries matter. A throw inside a nested function belongs to that
23
+ * function, so the walk does not descend into one. A throw inside `catch` still
24
+ * counts: a rethrow is as deliberate as an original throw, and it is how code
25
+ * says "this one is not mine to handle".
26
+ *
27
+ * @param {unknown} body - The function body node to inspect.
28
+ * @returns {boolean} True when the body throws outside any nested function.
29
+ */
30
+ function throwsDeliberately(body) {
31
+ if (!isNode(body)) return false;
32
+ const pending = [body];
33
+ while (pending.length > 0) {
34
+ const current = pending.pop();
35
+ if (current === void 0) break;
36
+ if (current.type === "ThrowStatement") return true;
37
+ for (const [key, value] of Object.entries(current)) {
38
+ if (key === "parent") continue;
39
+ const candidates = Array.isArray(value) ? value : [value];
40
+ for (const candidate of candidates) {
41
+ if (!isNode(candidate) || FUNCTION_TYPES.has(candidate.type)) continue;
42
+ pending.push(candidate);
43
+ }
44
+ }
45
+ }
46
+ return false;
47
+ }
48
+ //#endregion
49
+ export { throwsDeliberately };
@@ -1,3 +1,4 @@
1
+ import { throwsDeliberately } from "./deliberate_throw.js";
1
2
  //#region rules/maybe_promise_rule.ts
2
3
  function isNode(value) {
3
4
  return typeof value === "object" && value !== null && "type" in value;
@@ -108,6 +109,7 @@ const rule = {
108
109
  function checkReturnType(node) {
109
110
  if (!isAsyncFunction(node)) return;
110
111
  if (isCallArgumentCallback(node)) return;
112
+ if (throwsDeliberately(node["body"])) return;
111
113
  if (!isNode(node["returnType"])) return;
112
114
  const typeAnnotation = node["returnType"]["typeAnnotation"];
113
115
  if (!isTypeReference(typeAnnotation)) return;
@@ -182,6 +184,7 @@ const rule = {
182
184
  }
183
185
  if (!isAsync || !parentFunction) return;
184
186
  if (isCallArgumentCallback(parentFunction)) return;
187
+ if (throwsDeliberately(parentFunction["body"])) return;
185
188
  let returnType = null;
186
189
  if (isNode(parentFunction["returnType"])) {
187
190
  const typeAnnotation = parentFunction["returnType"]["typeAnnotation"];
package/jsr.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "$schema": "https://jsr.io/schema/config-file.v1.json",
3
3
  "name": "@murky-web/typebuddy",
4
- "version": "1.2.0",
4
+ "version": "1.3.0",
5
5
  "license": "ISC",
6
6
  "exports": {
7
7
  ".": "./src/index.ts",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@murky-web/typebuddy",
3
- "version": "1.2.0",
3
+ "version": "1.3.0",
4
4
  "description": "Your new best friend for simple typescript guards every project needs.",
5
5
  "private": false,
6
6
  "main": "./dist/index.js",
@@ -12,6 +12,36 @@
12
12
  "import": "./dist/index.js",
13
13
  "default": "./dist/index.js"
14
14
  },
15
+ "./guards": {
16
+ "types": "./src/guards.ts",
17
+ "import": "./dist/guards.js",
18
+ "default": "./dist/guards.js"
19
+ },
20
+ "./result": {
21
+ "types": "./src/result.ts",
22
+ "import": "./dist/result.js",
23
+ "default": "./dist/result.js"
24
+ },
25
+ "./parse": {
26
+ "types": "./src/parse.ts",
27
+ "import": "./dist/parse.js",
28
+ "default": "./dist/parse.js"
29
+ },
30
+ "./empty": {
31
+ "types": "./src/empty.ts",
32
+ "import": "./dist/empty.js",
33
+ "default": "./dist/empty.js"
34
+ },
35
+ "./ids": {
36
+ "types": "./src/ids.ts",
37
+ "import": "./dist/ids.js",
38
+ "default": "./dist/ids.js"
39
+ },
40
+ "./collections": {
41
+ "types": "./src/collections.ts",
42
+ "import": "./dist/collections.js",
43
+ "default": "./dist/collections.js"
44
+ },
15
45
  "./globals": {
16
46
  "types": "./globals.ts",
17
47
  "import": "./dist/globals.js",
@@ -41,19 +71,18 @@
41
71
  "smoke:globals": "bun run build && tsc --project ./smoke/globals/tsconfig.json --noEmit",
42
72
  "smoke:oxlint": "bun run build && bun ./smoke/oxlint/run-smoke.ts",
43
73
  "smoke:oxlint:fix": "bun run build && bun ./smoke/oxlint/run-fix-smoke.ts",
74
+ "smoke:subpath": "bun run build && bun ./smoke/subpath/run.ts",
44
75
  "smoke:treeshake": "bun run build && bun ./smoke/treeshake/run.ts",
45
76
  "typecheck": "tsc --project ./tsconfig.json --noEmit && tsc --project ./tsconfig.vitest.json --noEmit"
46
77
  },
47
78
  "files": [
79
+ "biome",
48
80
  "dist",
49
81
  "globals.ts",
50
82
  "jsr.json",
51
- "src/index.ts",
52
- "src/type_helper.ts",
53
- "src/types",
54
83
  "oxlint/index.ts",
55
- "biome",
56
- "rules"
84
+ "rules",
85
+ "src"
57
86
  ],
58
87
  "repository": {
59
88
  "type": "git",
@@ -1,3 +1,5 @@
1
+ import { throwsDeliberately } from "./deliberate_throw.js";
2
+
1
3
  type AstNode = {
2
4
  type: string;
3
5
  body?: AstNode | AstNode[];
@@ -215,6 +217,9 @@ ${indent}}
215
217
 
216
218
  const body = Array.isArray(bodyNode.body) ? bodyNode.body : [];
217
219
  if (hasTryCatch(body)) return;
220
+ // A function that throws has already decided its failure is not a
221
+ // value. Wrapping it in try/catch would swallow that decision.
222
+ if (throwsDeliberately(bodyNode)) return;
218
223
 
219
224
  context.report({
220
225
  node,
@@ -0,0 +1,73 @@
1
+ type AstNode = {
2
+ type: string;
3
+ [key: string]: unknown;
4
+ };
5
+
6
+ const FUNCTION_TYPES = new Set([
7
+ "ArrowFunctionExpression",
8
+ "FunctionDeclaration",
9
+ "FunctionExpression",
10
+ ]);
11
+
12
+ function isNode(value: unknown): value is AstNode {
13
+ return typeof value === "object" && value !== null && "type" in value;
14
+ }
15
+
16
+ /**
17
+ * Whether a function body throws on purpose.
18
+ *
19
+ * A `throw` in a function's own body is the author saying this failure is not a
20
+ * value to hand back. A missing manifest for a route the app is navigating to,
21
+ * an unreachable branch, a broken invariant — those should be loud. Turning them
22
+ * into `err()` converts a bug into a silently handled outcome, and the caller
23
+ * degrades politely instead of surfacing that something is wrong.
24
+ *
25
+ * So both async rules leave such a function alone. The rules exist to push
26
+ * *recoverable* failures into the return type, not to abolish throwing.
27
+ *
28
+ * Two boundaries matter. A throw inside a nested function belongs to that
29
+ * function, so the walk does not descend into one. A throw inside `catch` still
30
+ * counts: a rethrow is as deliberate as an original throw, and it is how code
31
+ * says "this one is not mine to handle".
32
+ *
33
+ * @param {unknown} body - The function body node to inspect.
34
+ * @returns {boolean} True when the body throws outside any nested function.
35
+ */
36
+ function throwsDeliberately(body: unknown): boolean {
37
+ if (!isNode(body)) {
38
+ return false;
39
+ }
40
+
41
+ const pending: AstNode[] = [body];
42
+ while (pending.length > 0) {
43
+ // `pop` on a non-empty array always yields a node; the length check above is
44
+ // the loop condition, but `noUncheckedIndexedAccess` cannot see that.
45
+ const current = pending.pop();
46
+ if (current === undefined) {
47
+ break;
48
+ }
49
+
50
+ if (current.type === "ThrowStatement") {
51
+ return true;
52
+ }
53
+
54
+ for (const [key, value] of Object.entries(current)) {
55
+ // `parent` points back up the tree; following it would never terminate.
56
+ if (key === "parent") {
57
+ continue;
58
+ }
59
+
60
+ const candidates = Array.isArray(value) ? value : [value];
61
+ for (const candidate of candidates) {
62
+ if (!isNode(candidate) || FUNCTION_TYPES.has(candidate.type)) {
63
+ continue;
64
+ }
65
+ pending.push(candidate);
66
+ }
67
+ }
68
+ }
69
+
70
+ return false;
71
+ }
72
+
73
+ export { throwsDeliberately };
@@ -1,3 +1,5 @@
1
+ import { throwsDeliberately } from "./deliberate_throw.js";
2
+
1
3
  type AstNode = {
2
4
  type: string;
3
5
  parent?: AstNode;
@@ -262,6 +264,9 @@ const rule = {
262
264
  function checkReturnType(node: AstNode) {
263
265
  if (!isAsyncFunction(node)) return;
264
266
  if (isCallArgumentCallback(node)) return;
267
+ // Same exemption as `require-try-catch`: a deliberate throw is not a
268
+ // result waiting to be wrapped.
269
+ if (throwsDeliberately(node["body"])) return;
265
270
  if (!isNode(node["returnType"])) return;
266
271
 
267
272
  const typeAnnotation = node["returnType"]["typeAnnotation"];
@@ -398,6 +403,7 @@ const rule = {
398
403
 
399
404
  if (!isAsync || !parentFunction) return;
400
405
  if (isCallArgumentCallback(parentFunction)) return;
406
+ if (throwsDeliberately(parentFunction["body"])) return;
401
407
 
402
408
  let returnType: AstNode | null = null;
403
409
  if (isNode(parentFunction["returnType"])) {