@antelopejs/tooling-configs 0.2.16 → 0.2.18

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 (51) hide show
  1. package/README.md +101 -52
  2. package/dist/bin/api-diff.mjs +430 -107
  3. package/dist/bin/body-check.d.mts +1 -0
  4. package/dist/bin/body-check.mjs +344 -0
  5. package/dist/bin/capture.d.mts +1 -0
  6. package/dist/bin/capture.mjs +559 -0
  7. package/dist/bin/check-size.mjs +3 -3
  8. package/dist/bin/checks.mjs +3 -3
  9. package/dist/bin/comment-proof.mjs +4 -3
  10. package/dist/bin/garden.mjs +6 -6
  11. package/dist/bin/ratchet.mjs +316 -10
  12. package/dist/bin/suppressions.mjs +118 -80
  13. package/dist/bin/sync.mjs +554 -153
  14. package/dist/bin/verify.mjs +240 -127
  15. package/dist/capture/index.d.mts +50 -0
  16. package/dist/capture/index.mjs +2 -0
  17. package/dist/{ceilings-BSw9p4YB.mjs → ceilings-B7KayYIG.mjs} +11 -3
  18. package/dist/{checks-BlWDFYio.mjs → checks-CxkSu2E6.mjs} +1 -1
  19. package/dist/{ci-workflow-DIsoEgMd.mjs → ci-workflow-ChW4He0r.mjs} +84 -3
  20. package/dist/{files-2FikHZ9F.mjs → files-DJ0TeaTU.mjs} +11 -5
  21. package/dist/formal/index.d.mts +40 -0
  22. package/dist/formal/index.mjs +205 -0
  23. package/dist/{json-BqvuCkqr.mjs → json-CG2L7YFl.mjs} +12 -8
  24. package/dist/oxc/anti-slop/index.mjs +869 -21
  25. package/dist/oxc/fmt.mjs +1 -1
  26. package/dist/oxc/guardrails/index.d.mts +1 -1
  27. package/dist/oxc/guardrails/index.mjs +736 -4
  28. package/dist/oxc/lint.d.mts +20 -3
  29. package/dist/oxc/lint.mjs +34 -10
  30. package/dist/oxlint-DIV-lLSS.mjs +98 -0
  31. package/dist/{package-Dtjt_lSa.mjs → package-BRTjkzt5.mjs} +29 -3
  32. package/dist/proof-stamp-DDDC0J6l.mjs +279 -0
  33. package/dist/ratchet-BAcLRYuM.mjs +448 -0
  34. package/dist/{renames-BGO4dWJ8.mjs → renames-L2owF5GD.mjs} +2 -2
  35. package/dist/scenes-DZVXkcxS.mjs +104 -0
  36. package/dist/shared-igPpEDpS.mjs +622 -0
  37. package/dist/{size-BVgNbLO6.mjs → size-DBatLT-F.mjs} +4 -4
  38. package/dist/suppression-base-9L8dlMQK.mjs +120 -0
  39. package/dist/suppression-budget-C0SkPO5R.mjs +535 -0
  40. package/dist/{suppressions-BJAngUxo.mjs → suppressions-DM60NkvL.mjs} +180 -18
  41. package/dist/templates-CypDm-j9.mjs +121 -0
  42. package/dist/typescript-CM0LrVP7.mjs +222 -0
  43. package/dist/verify/index.d.mts +6 -1
  44. package/dist/verify/index.mjs +1 -1
  45. package/package.json +31 -5
  46. package/dist/kinds-Bzyyi9yk.mjs +0 -25
  47. package/dist/ratchet-DRdIYwmv.mjs +0 -80
  48. package/dist/shared-CsXIMK3I.mjs +0 -34
  49. package/dist/staged-ratchet-CjoRfZaM.mjs +0 -236
  50. package/dist/suppression-budget-Yyf5_J5l.mjs +0 -283
  51. package/dist/typescript-C54ONh9m.mjs +0 -433
@@ -625,7 +625,7 @@ function typePredicateSubjectIndex(sourceCode, owner) {
625
625
  function annotationTarget(annotation, environment) {
626
626
  return annotation === null || annotation === void 0 ? null : classifyWideningTarget(annotation.typeAnnotation, environment);
627
627
  }
628
- function enclosingFunction(node) {
628
+ function enclosingFunction$1(node) {
629
629
  let current = node.parent;
630
630
  while (current !== null && current.type !== "Program") {
631
631
  if (current.type === "ArrowFunctionExpression" || current.type === "FunctionDeclaration" || current.type === "FunctionExpression") return current;
@@ -726,7 +726,7 @@ const noKnownValueWideningRule = defineRule({
726
726
  },
727
727
  ReturnStatement(node) {
728
728
  if (node.argument === null) return;
729
- const owner = enclosingFunction(node);
729
+ const owner = enclosingFunction$1(node);
730
730
  reportFlow(node.argument, targetFromAnnotation(owner?.returnType), `return value of \`${functionName(context.sourceCode, owner)}\``);
731
731
  },
732
732
  ArrowFunctionExpression(node) {
@@ -908,18 +908,126 @@ const noReflectGetRule = defineRule({
908
908
  }
909
909
  });
910
910
  //#endregion
911
- //#region src/oxc/anti-slop/rules/no-runtime-typeof.ts
911
+ //#region src/oxc/anti-slop/shared/binding-origin.ts
912
+ /** Return the variable an identifier refers to, searching outward from its scope, or null for an unresolved global. */
913
+ function variableOf(identifier, sourceCode) {
914
+ let scope = sourceCode.getScope(identifier);
915
+ while (scope !== null) {
916
+ const variable = scope.set.get(identifier.name);
917
+ if (variable !== void 0) return variable;
918
+ scope = scope.upper;
919
+ }
920
+ return null;
921
+ }
922
+ /**
923
+ * Return whether a definition takes its value from another module: an `import` declaration, or `import x = require()`.
924
+ * An `import x = Namespace.member` only renames a name, so its value comes from where that name is declared.
925
+ */
926
+ function isModuleImport(definition) {
927
+ if (definition.type !== "ImportBinding") return false;
928
+ const { node } = definition;
929
+ return node.type !== "TSImportEqualsDeclaration" || node.moduleReference.type === "TSExternalModuleReference";
930
+ }
931
+ /**
932
+ * Return whether a name has no definition in this file: a name no scope binds, or a global the environment declares (`Array`,
933
+ * `Error`), which oxlint binds to a variable with no definition.
934
+ */
935
+ function isGlobalName(identifier, sourceCode) {
936
+ const variable = variableOf(identifier, sourceCode);
937
+ return variable === null || variable.defs.length === 0;
938
+ }
939
+ /** Return whether a node sits inside another, or is it. */
940
+ function isWithin(node, ancestor) {
941
+ for (let at = node; at !== null; at = at.parent) if (at === ancestor) return true;
942
+ return false;
943
+ }
944
+ /**
945
+ * Return whether a name read inside a namespace block may be a member that another block of the same namespace declares.
946
+ * TypeScript merges the blocks of one namespace, and the scope manager does not, so a name that has no definition in the file
947
+ * (see `isGlobalName`), or whose definitions sit outside the block, may resolve to such a member and not to the binding the
948
+ * scope manager found.
949
+ */
950
+ function mayBeMergedMember(identifier, variable) {
951
+ for (let node = identifier.parent; node !== null; node = node.parent) {
952
+ if (node.type !== "TSModuleBlock") continue;
953
+ const block = node;
954
+ return variable === null || variable.defs.length === 0 || !variable.defs.every((definition) => isWithin(definition.node, block));
955
+ }
956
+ return false;
957
+ }
958
+ /**
959
+ * Return whether a name no scope binds is a global that nothing in this file writes, including a global that a `declare global`
960
+ * introduces.
961
+ */
962
+ function isUnwrittenGlobal(identifier, sourceCode) {
963
+ const scope = sourceCode.scopeManager.globalScope;
964
+ return scope !== null && !scope.through.some((reference) => reference.identifier.name === identifier.name && reference.isWrite());
965
+ }
966
+ /**
967
+ * Return whether a name takes its value from outside this file, which only a binding or reference the code can place proves:
968
+ * a module import, or a parameter, that nothing here defaults, assigns or redeclares, or a global that nothing here writes,
969
+ * and that no block of a namespace may shadow with a merged member. The kind of the first definition does not say it: a
970
+ * default, an assignment and a later `var` give a parameter a value written here, and an `import x = Namespace.member` is no
971
+ * module import. Any other name is not outside.
972
+ */
973
+ function isSuppliedFromOutside(identifier, sourceCode) {
974
+ const variable = variableOf(identifier, sourceCode);
975
+ if (mayBeMergedMember(identifier, variable)) return false;
976
+ if (variable === null) return isUnwrittenGlobal(identifier, sourceCode);
977
+ return variable.defs.every((definition) => definition.type === "Parameter" || isModuleImport(definition)) && variable.references.every((reference) => !reference.isWrite());
978
+ }
979
+ //#endregion
980
+ //#region src/oxc/anti-slop/shared/type-guards.ts
981
+ /** Files whose functions may declare a type predicate in JSDoc instead of a TypeScript return type. */
982
+ const JSDOC_PREDICATE_FILE = /\.[cm]?js$/;
983
+ /** A `@returns {x is T}` type, `x` captured: `asserts x is T` does not match. */
984
+ const JSDOC_PREDICATE = /^\s*([A-Za-z_$][\w$]*)\s+is\s+\S/;
912
985
  function isRuntimeFunction(node) {
913
986
  return node.type === "ArrowFunctionExpression" || node.type === "FunctionDeclaration" || node.type === "FunctionExpression";
914
987
  }
915
- function isInsideTypeGuard(node) {
988
+ /** Return the statement or member a JSDoc block documenting this function is attached to. */
989
+ function documentedNode(fn) {
990
+ const parent = fn.parent;
991
+ if ((parent.type === "Property" || parent.type === "MethodDefinition") && parent.value === fn) return parent;
992
+ let node = fn;
993
+ if (parent.type === "VariableDeclarator" && parent.init === fn && parent.parent.type === "VariableDeclaration" && parent.parent.declarations.length === 1) node = parent.parent;
994
+ const container = node.parent;
995
+ return container !== null && (container.type === "ExportNamedDeclaration" || container.type === "ExportDefaultDeclaration") ? container : node;
996
+ }
997
+ /** Return the type inside the braces of the first `@returns {...}` tag of a JSDoc block. */
998
+ function jsDocReturnType(text) {
999
+ const tag = /@returns\s*\{/.exec(text);
1000
+ if (tag === null) return null;
1001
+ const start = tag.index + tag[0].length;
1002
+ let depth = 1;
1003
+ for (let index = start; index < text.length; index++) if (text[index] === "{") depth++;
1004
+ else if (text[index] === "}" && --depth === 0) return text.slice(start, index);
1005
+ return null;
1006
+ }
1007
+ /** Return whether the JSDoc block right before the function declares `@returns {param is T}` for one of its parameters. */
1008
+ function hasJsDocTypePredicate(fn, sourceCode) {
1009
+ const comment = sourceCode.getCommentsBefore(documentedNode(fn)).at(-1);
1010
+ if (comment === void 0 || comment.type !== "Block" || !comment.value.startsWith("*")) return false;
1011
+ const returnType = jsDocReturnType(comment.value);
1012
+ const subject = returnType === null ? void 0 : JSDOC_PREDICATE.exec(returnType)?.[1];
1013
+ return subject !== void 0 && fn.params.some((parameter) => parameter.type === "Identifier" && parameter.name === subject);
1014
+ }
1015
+ /** Return whether a function declares a type predicate or assertion, or a JSDoc `@returns {x is T}` in a `.js`, `.mjs` or `.cjs` file. */
1016
+ function isTypeGuard(fn, sourceCode, filename) {
1017
+ if (fn.returnType?.typeAnnotation.type === "TSTypePredicate") return true;
1018
+ return JSDOC_PREDICATE_FILE.test(filename) && hasJsDocTypePredicate(fn, sourceCode);
1019
+ }
1020
+ /** Return the nearest runtime function around a node when that function is a type guard. */
1021
+ function enclosingTypeGuard(node, sourceCode, filename) {
916
1022
  let current = node.parent;
917
1023
  while (current !== null && current.type !== "Program") {
918
- if (isRuntimeFunction(current)) return current.returnType?.typeAnnotation.type === "TSTypePredicate";
1024
+ if (isRuntimeFunction(current)) return isTypeGuard(current, sourceCode, filename) ? current : null;
919
1025
  current = current.parent;
920
1026
  }
921
- return false;
1027
+ return null;
922
1028
  }
1029
+ //#endregion
1030
+ //#region src/oxc/anti-slop/rules/no-runtime-typeof.ts
923
1031
  /** Return whether typeof safely probes for the existence of a possibly absent binding. */
924
1032
  function isExistenceProbe(node) {
925
1033
  const parent = node.parent;
@@ -933,12 +1041,88 @@ function isExistenceProbe(node) {
933
1041
  const other = parent.left === node ? parent.right : parent.left;
934
1042
  return other.type === "Literal" && other.value === "undefined";
935
1043
  }
1044
+ /** Return the name a callee is read from, through members and type wrappers, or null when it is read from `this`, a call or anything else. */
1045
+ function rootOf(node) {
1046
+ switch (node.type) {
1047
+ case "Identifier": return node;
1048
+ case "MemberExpression": return rootOf(node.object);
1049
+ case "TSNonNullExpression":
1050
+ case "TSAsExpression":
1051
+ case "TSSatisfiesExpression":
1052
+ case "TSTypeAssertion": return rootOf(node.expression);
1053
+ default: return null;
1054
+ }
1055
+ }
1056
+ /** Return whether a callee is read from a name that takes its value from outside this file, through members and type wrappers. */
1057
+ function isReadFromOutside(callee, sourceCode) {
1058
+ const root = rootOf(callee);
1059
+ return root !== null && isSuppliedFromOutside(root, sourceCode);
1060
+ }
1061
+ /**
1062
+ * Return whether a callee only raises or records the message it is given: a bare `assert(...)`, or the `log` method of any object,
1063
+ * when its root is a module import, a global or a parameter. A root written in this file (a function, a class, a `const`, `this`, a
1064
+ * parameter this file defaults or assigns) can compare or store the message, so it is no sink. A call to any other name can too
1065
+ * (`assert.equal`, `Set#add`, `emit`).
1066
+ */
1067
+ function isMessageSink(callee, sourceCode) {
1068
+ if (!isReadFromOutside(callee, sourceCode)) return false;
1069
+ if (callee.type === "Identifier") return callee.name === "assert";
1070
+ return callee.type === "MemberExpression" && !callee.computed && callee.property.type === "Identifier" && callee.property.name === "log";
1071
+ }
1072
+ /**
1073
+ * Return whether a message ends at this parent: it is thrown, handed to the `assert` or `log` call that stands as a statement,
1074
+ * or handed to the `new` a `throw` throws when its class is read from outside this file, as `Error` is. Any other call, and a text a function returns, can be tested or used as a key by
1075
+ * whatever receives it, so they are not message sinks.
1076
+ */
1077
+ function endsMessage(parent, sourceCode) {
1078
+ switch (parent.type) {
1079
+ case "ThrowStatement": return true;
1080
+ case "CallExpression": return parent.parent.type === "ExpressionStatement" && isMessageSink(parent.callee, sourceCode);
1081
+ case "NewExpression": return parent.parent.type === "ThrowStatement" && isReadFromOutside(parent.callee, sourceCode);
1082
+ default: return false;
1083
+ }
1084
+ }
1085
+ /**
1086
+ * Return whether a `typeof` only fills in the text of a message that a `throw`, an `assert` or a `log` call, or the `new` under a `throw` takes.
1087
+ * Such a template holds other text, so no comparison with a `typeof` result matches it, and TypeScript narrows nothing from it.
1088
+ */
1089
+ function isMessageText(node, sourceCode) {
1090
+ let current = node.parent;
1091
+ if (current.type !== "TemplateLiteral" || current.quasis.every((quasi) => quasi.value.raw === "")) return false;
1092
+ while (current.parent.type === "TemplateLiteral" || current.parent.type === "ConditionalExpression" && current.parent.test !== current) current = current.parent;
1093
+ return endsMessage(current.parent, sourceCode);
1094
+ }
1095
+ /** Built-ins whose `.constructor` comparison re-implements a `typeof` result. */
1096
+ const TYPEOF_CONSTRUCTORS = /* @__PURE__ */ new Set([
1097
+ "String",
1098
+ "Number",
1099
+ "Boolean",
1100
+ "BigInt",
1101
+ "Symbol",
1102
+ "Function"
1103
+ ]);
1104
+ /** Return the built-in name when the comparison is `x.constructor === String` or its mirror. */
1105
+ function constructorCheckTarget(node) {
1106
+ if (![
1107
+ "===",
1108
+ "!==",
1109
+ "==",
1110
+ "!="
1111
+ ].includes(node.operator)) return void 0;
1112
+ for (const [operand, other] of [[node.left, node.right], [node.right, node.left]]) {
1113
+ const side = operand.type === "ChainExpression" ? operand.expression : operand;
1114
+ if (side.type === "MemberExpression" && !side.computed && side.property.type === "Identifier" && side.property.name === "constructor" && other.type === "Identifier" && TYPEOF_CONSTRUCTORS.has(other.name)) return other.name;
1115
+ }
1116
+ }
936
1117
  /** Disallow runtime typeof checks that narrow unparsed values instead of decoding them. */
937
1118
  const noRuntimeTypeofRule = defineRule({
938
1119
  meta: {
939
1120
  type: "problem",
940
- docs: { description: "Disallow runtime typeof checks; external values must be decoded into meaningful types at their I/O boundary." },
941
- messages: { runtimeTypeof: "A `typeof` check narrows a representation without establishing its contract. Parse input at its I/O boundary, then branch on the domain value." },
1121
+ docs: { description: "Disallow runtime typeof checks; external values must be decoded into meaningful types at their I/O boundary. A `typeof` that only fills in the text of a message checks nothing." },
1122
+ messages: {
1123
+ runtimeTypeof: "A `typeof` check narrows a representation without establishing its contract. Parse input at its I/O boundary, then branch on the domain value.",
1124
+ constructorCheck: "`.constructor === {{name}}` is a `typeof` check in another form. Parse input at its I/O boundary, or move the check into a type guard such as `(value: unknown): value is string`."
1125
+ },
942
1126
  schema: [{
943
1127
  type: "object",
944
1128
  properties: { allowInTypeGuards: { type: "boolean" } },
@@ -947,14 +1131,26 @@ const noRuntimeTypeofRule = defineRule({
947
1131
  defaultOptions: [{ allowInTypeGuards: false }]
948
1132
  },
949
1133
  createOnce(context) {
950
- return { UnaryExpression(node) {
1134
+ function allowedInTypeGuard(node) {
951
1135
  const option = context.options?.[0];
952
- const allowInTypeGuards = typeof option === "object" && option !== null && !Array.isArray(option) && option.allowInTypeGuards === true;
953
- if (node.operator === "typeof" && !isExistenceProbe(node) && (!allowInTypeGuards || !isInsideTypeGuard(node))) context.report({
954
- node,
955
- messageId: "runtimeTypeof"
956
- });
957
- } };
1136
+ return typeof option === "object" && option !== null && !Array.isArray(option) && option.allowInTypeGuards === true && enclosingTypeGuard(node, context.sourceCode, context.filename) !== null;
1137
+ }
1138
+ return {
1139
+ UnaryExpression(node) {
1140
+ if (node.operator === "typeof" && !isExistenceProbe(node) && !isMessageText(node, context.sourceCode) && !allowedInTypeGuard(node)) context.report({
1141
+ node,
1142
+ messageId: "runtimeTypeof"
1143
+ });
1144
+ },
1145
+ BinaryExpression(node) {
1146
+ const name = constructorCheckTarget(node);
1147
+ if (name !== void 0 && !allowedInTypeGuard(node)) context.report({
1148
+ node,
1149
+ messageId: "constructorCheck",
1150
+ data: { name }
1151
+ });
1152
+ }
1153
+ };
958
1154
  }
959
1155
  });
960
1156
  //#endregion
@@ -993,26 +1189,637 @@ const noForbiddenTermInSymbolNamesRule = defineRule({
993
1189
  }
994
1190
  });
995
1191
  //#endregion
1192
+ //#region src/oxc/anti-slop/shared/brand-probe.ts
1193
+ /** Primitive types a probe may hand back: a derived value, never an object shape the function claims to know. */
1194
+ const PRIMITIVE_TYPES = /* @__PURE__ */ new Set([
1195
+ "TSBigIntKeyword",
1196
+ "TSBooleanKeyword",
1197
+ "TSNullKeyword",
1198
+ "TSNumberKeyword",
1199
+ "TSStringKeyword",
1200
+ "TSSymbolKeyword",
1201
+ "TSUndefinedKeyword",
1202
+ "TSVoidKeyword"
1203
+ ]);
1204
+ function isPrimitiveType(type) {
1205
+ if (type.type === "TSUnionType") return type.types.every(isPrimitiveType);
1206
+ if (type.type === "TSParenthesizedType") return isPrimitiveType(type.typeAnnotation);
1207
+ return PRIMITIVE_TYPES.has(type.type) || type.type === "TSLiteralType";
1208
+ }
1209
+ /** Return whether a call creates a symbol: `Symbol(...)` or `Symbol.for(...)` on the global `Symbol`. */
1210
+ function createsSymbol(node, sourceCode) {
1211
+ if (node === null || node === void 0 || node.type !== "CallExpression") return false;
1212
+ const { callee } = node;
1213
+ const root = callee.type === "MemberExpression" && !callee.computed && callee.property.type === "Identifier" && callee.property.name === "for" ? callee.object : callee;
1214
+ return root.type === "Identifier" && root.name === "Symbol" && isGlobalName(root, sourceCode);
1215
+ }
1216
+ /** Return whether an expression is a symbol this file creates: a `const` bound to `Symbol(...)` or `Symbol.for(...)`, or such a call. */
1217
+ function isOwnSymbol(node, sourceCode) {
1218
+ if (node.type !== "Identifier") return createsSymbol(node, sourceCode);
1219
+ const definition = variableOf(node, sourceCode)?.defs[0];
1220
+ const declarator = definition?.node;
1221
+ return definition?.type === "Variable" && declarator?.type === "VariableDeclarator" && declarator.parent.type === "VariableDeclaration" && declarator.parent.kind === "const" && createsSymbol(declarator.init, sourceCode);
1222
+ }
1223
+ /** Return whether a reference reads a symbol-keyed member of the value (`value[BRAND]`) or asks `BRAND in value`. */
1224
+ function isProbe(reference, sourceCode) {
1225
+ const user = reference.parent;
1226
+ if (user.type === "MemberExpression") return user.object === reference && user.computed && isOwnSymbol(user.property, sourceCode);
1227
+ return user.type === "BinaryExpression" && user.operator === "in" && user.right === reference && isOwnSymbol(user.left, sourceCode);
1228
+ }
1229
+ /** Return the type-predicate subject a call position names, for a callee declared in this file. */
1230
+ function declaredFunctionOf(callee, sourceCode) {
1231
+ if (callee.type !== "Identifier") return null;
1232
+ const definition = variableOf(callee, sourceCode)?.defs[0];
1233
+ if (definition?.type === "FunctionName" && isRuntimeFunction(definition.node)) return definition.node;
1234
+ const declarator = definition?.node;
1235
+ if (definition?.type === "Variable" && declarator?.type === "VariableDeclarator" && declarator.parent.type === "VariableDeclaration" && declarator.parent.kind === "const" && declarator.init !== null && declarator.init !== void 0 && isRuntimeFunction(declarator.init)) return declarator.init;
1236
+ return null;
1237
+ }
1238
+ function parameterAt(owner, position, sourceCode) {
1239
+ const parameter = owner.params[position];
1240
+ if (parameter?.type !== "Identifier") return null;
1241
+ return sourceCode.getDeclaredVariables(owner).find((variable) => variable.name === parameter.name && variable.defs[0]?.type === "Parameter") ?? null;
1242
+ }
1243
+ /** Return whether a function declared in this file is a type guard on the parameter at `position`. */
1244
+ function guardsParameterAt(owner, position) {
1245
+ const predicate = owner.returnType?.typeAnnotation;
1246
+ const parameter = owner.params[position];
1247
+ return predicate?.type === "TSTypePredicate" && !predicate.asserts && predicate.parameterName.type === "Identifier" && parameter?.type === "Identifier" && predicate.parameterName.name === parameter.name;
1248
+ }
1249
+ /** Operators whose result is a boolean about the operands, which a probe may hand back. */
1250
+ const COMPARISONS = /* @__PURE__ */ new Set([
1251
+ "===",
1252
+ "!==",
1253
+ "==",
1254
+ "!=",
1255
+ "<",
1256
+ ">",
1257
+ "<=",
1258
+ ">="
1259
+ ]);
1260
+ /** Return whether a function declares a primitive return type, so what it hands back is a derived value. */
1261
+ function returnsPrimitive(fn) {
1262
+ const returned = fn.returnType?.typeAnnotation;
1263
+ return returned !== void 0 && isPrimitiveType(returned);
1264
+ }
1265
+ /** Return the function a node is written in. */
1266
+ function enclosingFunction(node) {
1267
+ for (let at = node.parent; at !== null; at = at.parent) if (isRuntimeFunction(at)) return at;
1268
+ return null;
1269
+ }
1270
+ /** Return whether every reference of a `const` or function binding is a use that `reaches` accepts. */
1271
+ function everyUseReaches(variable, reaches) {
1272
+ if (variable === null || variable === void 0) return false;
1273
+ const reads = variable.references.filter((reference) => !reference.init);
1274
+ return reads.length > 0 && variable.references.every((reference) => reference.init || !reference.isWrite()) && reads.every((reference) => reaches(reference.identifier));
1275
+ }
1276
+ /**
1277
+ * Return whether the value an expression yields reaches nothing but the result of the probe. The value may be tested,
1278
+ * compared, negated, read further (`.identity`), pass through `Boolean(...)`, a type wrapper, a `&&`, `||`, `??` or a
1279
+ * conditional branch, be held in a `const` whose uses obey the same rule, or be returned. Only the probe ends the walk. A function that is not the
1280
+ * probe may return it when it is declared in this file and every use of it is a call whose value obeys the same rule, or when it
1281
+ * declares a primitive return type and nothing in the file refers to it (an exported sibling probe).
1282
+ * An assignment, a `delete`, an update, a call of the value, an argument to any other call, a store or a spread refuses.
1283
+ */
1284
+ function resultReachesOnlyReturn(node, owner, sourceCode, seen) {
1285
+ if (seen.has(node)) return true;
1286
+ seen.add(node);
1287
+ const user = node.parent;
1288
+ if (user === null) return false;
1289
+ const next = (target) => resultReachesOnlyReturn(target, owner, sourceCode, seen);
1290
+ switch (user.type) {
1291
+ case "ChainExpression":
1292
+ case "TSAsExpression":
1293
+ case "TSNonNullExpression":
1294
+ case "TSSatisfiesExpression":
1295
+ case "TSTypeAssertion": return next(user);
1296
+ case "MemberExpression": return user.object === node && next(user);
1297
+ case "UnaryExpression": return (user.operator === "!" || user.operator === "typeof") && next(user);
1298
+ case "BinaryExpression": return COMPARISONS.has(user.operator) && next(user);
1299
+ case "LogicalExpression": return next(user);
1300
+ case "ConditionalExpression": return user.test === node || next(user);
1301
+ case "IfStatement": return user.test === node;
1302
+ case "ExpressionStatement": return true;
1303
+ case "CallExpression": return user.callee.type === "Identifier" && user.callee.name === "Boolean" && isGlobalName(user.callee, sourceCode) && user.arguments[0] === node && next(user);
1304
+ case "VariableDeclarator":
1305
+ if (user.id.type !== "Identifier" || user.parent.type !== "VariableDeclaration" || user.parent.kind !== "const") return false;
1306
+ return everyUseReaches(sourceCode.getDeclaredVariables(user).find((each) => each.name === user.id.name), next);
1307
+ case "ReturnStatement":
1308
+ case "ArrowFunctionExpression": {
1309
+ if (user.type === "ArrowFunctionExpression" && user.body !== node) return false;
1310
+ const returner = user.type === "ArrowFunctionExpression" ? user : enclosingFunction(user);
1311
+ if (returner === null) return false;
1312
+ if (returner === owner) return true;
1313
+ const bound = readerVariable(returner, sourceCode);
1314
+ if (returnsPrimitive(returner) && bound !== null && bound.references.length === 0) return true;
1315
+ return everyUseReaches(bound, (use) => use.parent.type === "CallExpression" && use.parent.callee === use && next(use.parent));
1316
+ }
1317
+ default: return false;
1318
+ }
1319
+ }
1320
+ /** Return the variable a function declared in this file is bound to. */
1321
+ function readerVariable(reader, sourceCode) {
1322
+ if (reader.type === "FunctionDeclaration") return reader.id === null ? null : sourceCode.getDeclaredVariables(reader).find((variable) => variable.name === reader.id?.name && variable.defs[0]?.type === "FunctionName") ?? null;
1323
+ const declarator = reader.parent;
1324
+ if (declarator.type !== "VariableDeclarator" || declarator.init !== reader || declarator.id.type !== "Identifier") return null;
1325
+ return sourceCode.getDeclaredVariables(declarator).find((variable) => variable.name === declarator.id.name) ?? null;
1326
+ }
1327
+ const REFUSED = {
1328
+ allowed: false,
1329
+ probed: false
1330
+ };
1331
+ function combine(uses) {
1332
+ return {
1333
+ allowed: uses.every((use) => use.allowed),
1334
+ probed: uses.some((use) => use.probed)
1335
+ };
1336
+ }
1337
+ /**
1338
+ * Walk every use of a value. A use is allowed when it is a symbol-keyed probe, an argument to a type guard declared in this
1339
+ * file, the initializer of a `const` alias whose own uses are allowed, or an argument to a function declared in this file whose
1340
+ * matching parameter's uses are allowed. Any other use (a store, a return, a call elsewhere, a cast, an assignment) refuses.
1341
+ */
1342
+ function usesOf(variable, owner, sourceCode, seen) {
1343
+ if (seen.has(variable)) return {
1344
+ allowed: true,
1345
+ probed: false
1346
+ };
1347
+ seen.add(variable);
1348
+ const reads = variable.references.filter((reference) => !reference.init);
1349
+ if (variable.references.some((reference) => reference.isWrite() && !reference.init) || reads.length === 0) return REFUSED;
1350
+ return combine(reads.map((reference) => {
1351
+ const { identifier } = reference;
1352
+ if (isProbe(identifier, sourceCode)) return resultReachesOnlyReturn(identifier.parent, owner, sourceCode, /* @__PURE__ */ new Set()) ? {
1353
+ allowed: true,
1354
+ probed: true
1355
+ } : REFUSED;
1356
+ const user = identifier.parent;
1357
+ if (user.type === "VariableDeclarator" && user.init === identifier && user.id.type === "Identifier" && user.parent.type === "VariableDeclaration" && user.parent.kind === "const") {
1358
+ const alias = sourceCode.getDeclaredVariables(user).find((each) => each.name === user.id.name);
1359
+ return alias === void 0 ? REFUSED : usesOf(alias, owner, sourceCode, seen);
1360
+ }
1361
+ if (user.type !== "CallExpression") return REFUSED;
1362
+ const position = user.arguments.findIndex((argument) => argument === identifier);
1363
+ const callee = declaredFunctionOf(user.callee, sourceCode);
1364
+ if (position < 0 || callee === null) return REFUSED;
1365
+ if (guardsParameterAt(callee, position)) return {
1366
+ allowed: true,
1367
+ probed: false
1368
+ };
1369
+ const parameter = parameterAt(callee, position, sourceCode);
1370
+ return parameter === null ? REFUSED : usesOf(parameter, owner, sourceCode, seen);
1371
+ }));
1372
+ }
1373
+ /**
1374
+ * Return whether a function is a brand probe on a parameter typed `unknown`: it declares a primitive return type, so the
1375
+ * value it hands back is derived, and the only things it does with the parameter are to read a symbol-keyed member that this
1376
+ * file creates (or ask `in` with one), through guards and readers declared in this file, and at least one such read happens.
1377
+ * Storing, forwarding, casting or returning the parameter, reading it by a string key, or a reader imported from elsewhere
1378
+ * is not one.
1379
+ */
1380
+ function isBrandProbe(owner, parameter, sourceCode) {
1381
+ const returned = owner.returnType?.typeAnnotation;
1382
+ if (parameter === void 0 || returned === void 0 || !isPrimitiveType(returned)) return false;
1383
+ const uses = usesOf(parameter, owner, sourceCode, /* @__PURE__ */ new Set());
1384
+ return uses.allowed && uses.probed;
1385
+ }
1386
+ //#endregion
1387
+ //#region src/oxc/anti-slop/shared/caught-callback.ts
1388
+ /** Return whether an identifier is a catch clause's own binding, never reassigned, so it holds exactly what was thrown. */
1389
+ function isCaughtValue(node, sourceCode) {
1390
+ if (node.type !== "Identifier") return false;
1391
+ const definition = variableOf(node, sourceCode)?.defs[0];
1392
+ if (definition?.type !== "CatchClause" || definition.node.type !== "CatchClause") return false;
1393
+ return definition.node.param?.type === "Identifier" && definition.node.param.name === node.name && variableOf(node, sourceCode)?.references.every((reference) => !reference.isWrite()) === true;
1394
+ }
1395
+ /** Return whether a use of a callback leaves it unable to run with anything but what a call site passes: a plain test of whether it exists. */
1396
+ function isExistenceTest(reference) {
1397
+ const user = reference.parent;
1398
+ return user.type === "ConditionalExpression" && user.test === reference || user.type === "IfStatement" && user.test === reference || user.type === "LogicalExpression" && user.operator === "&&" && user.left === reference;
1399
+ }
1400
+ /** Return whether a call hands a caught value to every parameter of the callback type that is `unknown`. */
1401
+ function passesCaughtValues(call, unknownPositions, sourceCode) {
1402
+ return unknownPositions.every((position) => {
1403
+ const argument = call.arguments[position];
1404
+ return argument !== void 0 && isCaughtValue(argument, sourceCode);
1405
+ });
1406
+ }
1407
+ function parameterVariable(owner, parameter, sourceCode) {
1408
+ return sourceCode.getDeclaredVariables(owner).find((variable) => variable.name === parameter.name && variable.defs[0]?.type === "Parameter");
1409
+ }
1410
+ /**
1411
+ * Return whether a function type is the type of a callback parameter that the function only calls with a caught value.
1412
+ * The callback parameter is a plain identifier of a function that has a body, its type is written directly as a function
1413
+ * type, it is called at least once, and every use of it is such a call (with a caught value in each `unknown` position of
1414
+ * the type) or a test of whether it exists. A callback that is stored, passed on, never called, or called with any other
1415
+ * value is not one: the thrown value has no type JavaScript promises, so `unknown` is the true type only there.
1416
+ */
1417
+ function isCaughtValueCallbackType(owner, sourceCode) {
1418
+ const annotation = owner.parent;
1419
+ if (annotation.type !== "TSTypeAnnotation") return false;
1420
+ const callback = annotation.parent;
1421
+ if (callback.type !== "Identifier") return false;
1422
+ const holder = callback.parent;
1423
+ if (!isRuntimeFunction(holder) || holder.body === null || holder.body === void 0) return false;
1424
+ const unknownPositions = owner.params.flatMap((parameter, position) => {
1425
+ const type = functionParameterTypeAnnotation(parameter)?.typeAnnotation;
1426
+ return type !== void 0 && containsUnknownType(type) ? [position] : [];
1427
+ });
1428
+ const reads = parameterVariable(holder, callback, sourceCode)?.references.filter((reference) => !reference.init);
1429
+ if (reads === void 0) return false;
1430
+ const calls = reads.filter((reference) => !isExistenceTest(reference.identifier));
1431
+ return calls.length > 0 && calls.every((reference) => {
1432
+ const call = reference.identifier.parent;
1433
+ return call.type === "CallExpression" && call.callee === reference.identifier && passesCaughtValues(call, unknownPositions, sourceCode);
1434
+ });
1435
+ }
1436
+ //#endregion
1437
+ //#region src/oxc/anti-slop/shared/callee-origin.ts
1438
+ const NO_VARIABLES = /* @__PURE__ */ new Set();
1439
+ /** Return the name an `import x = Outer.Inner.member` reads first, the one the file must declare. */
1440
+ function entityRoot(name) {
1441
+ return name.type === "TSQualifiedName" ? entityRoot(name.left) : name;
1442
+ }
1443
+ /** Return the name an `import x = Namespace.member` reads, or null for a module import, which another file gives a value. */
1444
+ function aliasRoot(definition) {
1445
+ const { node } = definition;
1446
+ if (node.type !== "TSImportEqualsDeclaration") return null;
1447
+ return node.moduleReference.type === "TSExternalModuleReference" ? null : entityRoot(node.moduleReference);
1448
+ }
1449
+ /** Return whether a definition is a `const` with an initializer, a parameter or an import, so that nothing but a write reference changes its value. */
1450
+ function isFixedDefinition(definition) {
1451
+ const { node } = definition;
1452
+ return definition.type !== "Variable" || node.type === "VariableDeclarator" && node.init !== null && node.parent.type === "VariableDeclaration" && node.parent.kind === "const";
1453
+ }
1454
+ /**
1455
+ * Classify a name by every definition and write it has, not by its first definition. It is outside this file only when
1456
+ * `isSuppliedFromOutside` places it there. A name no scope binds, or that a merged namespace member may shadow, is unplaced.
1457
+ * A function, class, namespace or catch binding is a declaration written here. Any other name is a variable read through the
1458
+ * expressions written to it.
1459
+ */
1460
+ function bindingOf(identifier, sourceCode) {
1461
+ if (isSuppliedFromOutside(identifier, sourceCode)) return { kind: "outside" };
1462
+ const variable = variableOf(identifier, sourceCode);
1463
+ if (variable === null || mayBeMergedMember(identifier, variable)) return { kind: "unplaced" };
1464
+ const declared = variable.defs.find((definition) => ![
1465
+ "Variable",
1466
+ "Parameter",
1467
+ "ImportBinding"
1468
+ ].includes(definition.type));
1469
+ if (declared !== void 0) return {
1470
+ kind: "declaration",
1471
+ type: declared.type
1472
+ };
1473
+ const writes = variable.references.filter((reference) => reference.isWrite());
1474
+ return {
1475
+ kind: "variable",
1476
+ variable,
1477
+ sources: [...variable.defs.map(aliasRoot), ...writes.map((write) => write.writeExpr)].filter((source) => source !== null),
1478
+ constant: variable.defs.every(isFixedDefinition) && writes.every((write) => write.writeExpr !== null)
1479
+ };
1480
+ }
1481
+ /** Return the expression a type wrapper, an `await` or an optional chain only passes through, or null when the node is none of these. */
1482
+ function passThrough(node) {
1483
+ switch (node.type) {
1484
+ case "TSAsExpression":
1485
+ case "TSSatisfiesExpression":
1486
+ case "TSNonNullExpression":
1487
+ case "TSTypeAssertion":
1488
+ case "ChainExpression": return node.expression;
1489
+ case "AwaitExpression": return node.argument;
1490
+ default: return null;
1491
+ }
1492
+ }
1493
+ /**
1494
+ * Return whether a value reaches back to code written in this file: walk through members, calls, `new`, type
1495
+ * wrappers and `const` aliases to the name or literal at the root. An import, a parameter and a global are
1496
+ * outside the file. A function, class, namespace, `let`, `var`, `this`, `super`, object literal or anything this
1497
+ * walk cannot place is inside it. A call also counts when it is handed an object that holds a function written
1498
+ * here, which it can hand back as a method. A call rooted at a global (`Object.freeze`, `Array.from`, `Promise.resolve`) is
1499
+ * no factory that wraps a schema, so a function handed to it counts too, as a callback it can call.
1500
+ */
1501
+ function isWrittenHere(node, sourceCode, seen) {
1502
+ const inner = passThrough(node);
1503
+ if (inner !== null) return isWrittenHere(inner, sourceCode, seen);
1504
+ switch (node.type) {
1505
+ case "Identifier": {
1506
+ const binding = bindingOf(node, sourceCode);
1507
+ if (binding.kind === "outside") return false;
1508
+ if (binding.kind !== "variable") return true;
1509
+ return !binding.constant || seen.has(binding.variable) || followSources(binding, sourceCode, seen, isWrittenHere);
1510
+ }
1511
+ case "ImportExpression": return false;
1512
+ case "MemberExpression": return node.object.type === "ThisExpression" ? thisFieldIsWrittenHere(node, sourceCode, seen) : isWrittenHere(node.object, sourceCode, seen);
1513
+ case "CallExpression":
1514
+ case "NewExpression": {
1515
+ const handsOver = isRootedAtGlobal(node.callee, sourceCode) ? isFunctionHere : holdsFunctionHere;
1516
+ return isWrittenHere(node.callee, sourceCode, seen) || node.arguments.some((argument) => handsOver(argument, sourceCode, seen));
1517
+ }
1518
+ case "ConditionalExpression": return isWrittenHere(node.consequent, sourceCode, seen) || isWrittenHere(node.alternate, sourceCode, seen);
1519
+ case "LogicalExpression": return isWrittenHere(node.left, sourceCode, seen) || isWrittenHere(node.right, sourceCode, seen);
1520
+ default: return true;
1521
+ }
1522
+ }
1523
+ /** Return whether a callee is read from a global that has no definition in the file, through members, calls and type wrappers. */
1524
+ function isRootedAtGlobal(node, sourceCode) {
1525
+ const inner = passThrough(node);
1526
+ if (inner !== null) return isRootedAtGlobal(inner, sourceCode);
1527
+ switch (node.type) {
1528
+ case "Identifier": return isGlobalName(node, sourceCode);
1529
+ case "MemberExpression": return isRootedAtGlobal(node.object, sourceCode);
1530
+ case "CallExpression":
1531
+ case "NewExpression": return isRootedAtGlobal(node.callee, sourceCode);
1532
+ default: return false;
1533
+ }
1534
+ }
1535
+ /** Return whether a node is a primitive value, which holds no function: a literal, a template, or the result of a unary, binary or update operator. */
1536
+ function isPrimitive(node) {
1537
+ switch (node.type) {
1538
+ case "Literal":
1539
+ case "TemplateLiteral":
1540
+ case "UnaryExpression":
1541
+ case "BinaryExpression":
1542
+ case "UpdateExpression": return true;
1543
+ default: return false;
1544
+ }
1545
+ }
1546
+ /** Return the name a class element or member is read by, or null for a computed one. A private name carries its `#`, so it is no element of the public name. */
1547
+ function elementName(key, computed) {
1548
+ if (computed) return null;
1549
+ if (key.type === "PrivateIdentifier") return `#${key.name}`;
1550
+ return key.type === "Identifier" ? key.name : null;
1551
+ }
1552
+ /** Return the class a node is written in, or null at the top level. */
1553
+ function enclosingClass(node) {
1554
+ let current = node.parent;
1555
+ while (current !== null && current.type !== "ClassDeclaration" && current.type !== "ClassExpression") current = current.parent;
1556
+ return current;
1557
+ }
1558
+ /**
1559
+ * Return what `this` is where a node is written: the instance or the class itself when the nearest non-arrow function is a
1560
+ * class method, or when no function sits between the node and a field initializer or static block. Any other function (an
1561
+ * object-literal method, a function expression, a declaration) gets its `this` from its caller, as does a node in a class
1562
+ * heritage clause, a decorator or a computed key, which the walk meets as the class itself. Those give null.
1563
+ */
1564
+ function receiverOf(node) {
1565
+ let child = node;
1566
+ for (let current = node.parent; current !== null; current = current.parent) switch (current.type) {
1567
+ case "FunctionExpression": return current.parent.type === "MethodDefinition" && current.parent.value === current ? current.parent.static ? "static" : "instance" : null;
1568
+ case "PropertyDefinition":
1569
+ case "AccessorProperty": return current.value === child ? current.static ? "static" : "instance" : null;
1570
+ case "StaticBlock": return "static";
1571
+ case "FunctionDeclaration":
1572
+ case "ClassDeclaration":
1573
+ case "ClassExpression": return null;
1574
+ default: child = current;
1575
+ }
1576
+ return null;
1577
+ }
1578
+ /**
1579
+ * Return whether `this.field` reaches back to code written here. The element is the one of that exact name, `#` included, and of
1580
+ * the receiver's kind, static or instance. A field with an initializer is read through it. A constructor parameter property is
1581
+ * an instance element handed in by the caller, as a parameter is. A name that no element or two elements declare, an
1582
+ * accessor, a method, a field without an initializer, an inherited field and a computed name are not placed, so they count as
1583
+ * written here.
1584
+ */
1585
+ function thisFieldIsWrittenHere(member, sourceCode, seen) {
1586
+ const klass = enclosingClass(member);
1587
+ const name = elementName(member.property, member.computed);
1588
+ const receiver = receiverOf(member);
1589
+ if (klass === null || name === null || receiver === null) return true;
1590
+ const elements = klass.body.body.filter((element) => (element.type === "PropertyDefinition" || element.type === "AccessorProperty" || element.type === "MethodDefinition") && element.static === (receiver === "static") && elementName(element.key, element.computed) === name);
1591
+ const handedIn = receiver === "instance" && klass.body.body.some((element) => element.type === "MethodDefinition" && declaresParameterProperty(element, name));
1592
+ if (elements.length + (handedIn ? 1 : 0) !== 1) return true;
1593
+ const [element] = elements;
1594
+ if (element === void 0) return false;
1595
+ if (element.type !== "PropertyDefinition") return true;
1596
+ return element.value === null || seen.has(element) || isWrittenHere(element.value, sourceCode, /* @__PURE__ */ new Set([...seen, element]));
1597
+ }
1598
+ /** Return whether a method declares a parameter property of this name, which only a constructor can. */
1599
+ function declaresParameterProperty(method, name) {
1600
+ return method.value.params.some((parameter) => parameter.type === "TSParameterProperty" && parameter.parameter.type === "Identifier" && parameter.parameter.name === name);
1601
+ }
1602
+ /**
1603
+ * Return whether a value is local code: a function or class written here, an object or array of such members, or a member or call
1604
+ * that reaches back to this file. Only a primitive, an import, a parameter and an object of such values are not, so a node this
1605
+ * walk does not list, a function, a class and any syntax added later included, is reported.
1606
+ */
1607
+ function isFunctionHere(node, sourceCode, seen) {
1608
+ const inner = passThrough(node);
1609
+ if (inner !== null) return isFunctionHere(inner, sourceCode, seen);
1610
+ switch (node.type) {
1611
+ case "ObjectExpression":
1612
+ case "ArrayExpression": return holdsFunctionHere(node, sourceCode, seen);
1613
+ case "ConditionalExpression": return isFunctionHere(node.consequent, sourceCode, seen) || isFunctionHere(node.alternate, sourceCode, seen);
1614
+ case "LogicalExpression": return isFunctionHere(node.left, sourceCode, seen) || isFunctionHere(node.right, sourceCode, seen);
1615
+ case "Identifier": {
1616
+ const binding = bindingOf(node, sourceCode);
1617
+ if (binding.kind === "unplaced") return true;
1618
+ if (binding.kind === "declaration") return true;
1619
+ return binding.kind === "variable" && followSources(binding, sourceCode, seen, isFunctionHere);
1620
+ }
1621
+ case "MemberExpression":
1622
+ case "CallExpression":
1623
+ case "NewExpression": return isWrittenHere(node, sourceCode, seen);
1624
+ default: return !isPrimitive(node);
1625
+ }
1626
+ }
1627
+ /**
1628
+ * Return whether an argument is an object, an array or a class whose members include a function written here, or a `this`.
1629
+ * A function handed over on its own is not: a schema may take a local refinement. A node this walk does not list is reported
1630
+ * unless it is a primitive.
1631
+ */
1632
+ function holdsFunctionHere(node, sourceCode, seen) {
1633
+ const inner = passThrough(node);
1634
+ if (inner !== null) return holdsFunctionHere(inner, sourceCode, seen);
1635
+ switch (node.type) {
1636
+ case "FunctionExpression":
1637
+ case "ArrowFunctionExpression": return false;
1638
+ case "SpreadElement": return holdsFunctionHere(node.argument, sourceCode, seen);
1639
+ case "ObjectExpression": return node.properties.some((property) => property.type === "SpreadElement" ? isFunctionHere(property.argument, sourceCode, seen) : isFunctionHere(property.value, sourceCode, seen));
1640
+ case "ArrayExpression": return node.elements.some((element) => element !== null && (element.type === "SpreadElement" ? holdsFunctionHere(element.argument, sourceCode, seen) : isFunctionHere(element, sourceCode, seen)));
1641
+ case "Identifier": {
1642
+ const binding = bindingOf(node, sourceCode);
1643
+ if (binding.kind === "unplaced") return true;
1644
+ if (binding.kind === "declaration") return binding.type !== "FunctionName";
1645
+ return binding.kind === "variable" && followSources(binding, sourceCode, seen, holdsFunctionHere);
1646
+ }
1647
+ case "MemberExpression":
1648
+ case "CallExpression":
1649
+ case "NewExpression":
1650
+ case "ConditionalExpression":
1651
+ case "LogicalExpression": return isWrittenHere(node, sourceCode, seen);
1652
+ default: return !isPrimitive(node);
1653
+ }
1654
+ }
1655
+ /** Apply a test to each expression written to a variable, once per variable on the path, and answer false for a variable written nothing. */
1656
+ function followSources(binding, sourceCode, seen, test) {
1657
+ const { sources, variable } = binding;
1658
+ return !seen.has(variable) && sources.some((source) => test(source, sourceCode, /* @__PURE__ */ new Set([...seen, variable])));
1659
+ }
1660
+ /**
1661
+ * Return whether a call goes to code written in this file. A bare callee counts when it is not outside the file, as
1662
+ * `isSuppliedFromOutside` decides, or when it is a parameter. A member callee counts when the value it is read from reaches back
1663
+ * to this file, so a member of a parameter, which the caller supplies, does not.
1664
+ */
1665
+ function calleeIsWrittenHere(call, sourceCode) {
1666
+ const { callee } = call;
1667
+ if (callee.type === "Identifier") {
1668
+ const variable = variableOf(callee, sourceCode);
1669
+ return !isSuppliedFromOutside(callee, sourceCode) || variable !== null && variable.defs.some((definition) => definition.type === "Parameter");
1670
+ }
1671
+ return callee.type === "MemberExpression" && isWrittenHere(callee.object, sourceCode, NO_VARIABLES);
1672
+ }
1673
+ //#endregion
1674
+ //#region src/oxc/anti-slop/shared/parse-boundary.ts
1675
+ /**
1676
+ * Callee names that read as a schema or decoder: `parse`, `safeParse` and their `Async` forms, `decode`,
1677
+ * `parseX` and `decodeX` helpers in either case, and interface-api-util's `assertValidation`. A name proves
1678
+ * nothing alone. A callee declared in the same file never counts (see `calleeIsWrittenHere`), so a chain of wrappers
1679
+ * cannot close on itself, and an imported callee that takes `unknown` is checked where it is declared.
1680
+ */
1681
+ const DECODER_NAME = /^(?:assertValidation|safeParse(?:Async)?|[Pp]arse(?:[A-Z]\w*)?|[Dd]ecode(?:[A-Z]\w*)?)$/;
1682
+ const PROMISE_TYPES = /* @__PURE__ */ new Set(["Promise", "PromiseLike"]);
1683
+ function calleeName(call) {
1684
+ const { callee } = call;
1685
+ if (callee.type === "Identifier") return callee.name;
1686
+ return callee.type === "MemberExpression" && !callee.computed && callee.property.type === "Identifier" ? callee.property.name : null;
1687
+ }
1688
+ /** Return the initializer of the single-name `const` a variable declares. */
1689
+ function constInitializerOf(variable) {
1690
+ const declarator = variable?.defs[0]?.node;
1691
+ return declarator?.type === "VariableDeclarator" && declarator.id.type === "Identifier" && declarator.parent.type === "VariableDeclaration" && declarator.parent.kind === "const" ? declarator.init : null;
1692
+ }
1693
+ /**
1694
+ * Return the decoder call whose direct argument a reference is. An `unknown` value is not callable, so it is
1695
+ * never the callee. A callee written in this file carries its own row and is no decoder.
1696
+ */
1697
+ function decoderCallOf(identifier, sourceCode) {
1698
+ const call = identifier.parent;
1699
+ return call.type === "CallExpression" && DECODER_NAME.test(calleeName(call) ?? "") && !calleeIsWrittenHere(call, sourceCode) ? call : null;
1700
+ }
1701
+ /** Return whether a declared return type states a value, not `unknown` or `any`, promised or not. */
1702
+ function declaresParsedType(annotation) {
1703
+ const type = annotation?.typeAnnotation;
1704
+ if (type === void 0) return false;
1705
+ const promised = type.type === "TSTypeReference" && type.typeName.type === "Identifier" && PROMISE_TYPES.has(type.typeName.name) ? type.typeArguments?.params[0] : type;
1706
+ return promised !== void 0 && promised.type !== "TSAnyKeyword" && !containsUnknownType(promised);
1707
+ }
1708
+ /** Strip what leaves a decoder's result the parsed value: `await` and the `.data` of a safe parse. */
1709
+ function parsedSource(node) {
1710
+ if (node.type === "AwaitExpression") return parsedSource(node.argument);
1711
+ return node.type === "MemberExpression" && !node.computed && node.property.type === "Identifier" && node.property.name === "data" ? parsedSource(node.object) : node;
1712
+ }
1713
+ /** Names that read a parameter without a reference to it: the `arguments` object, and a direct `eval` that can name it in a string. */
1714
+ const IMPLICIT_READERS = /* @__PURE__ */ new Set(["arguments", "eval"]);
1715
+ /** Return the expressions a function hands back: an arrow's expression body, or what its `return` statements return. */
1716
+ function returnedExpressions(owner, returns) {
1717
+ if (owner.body === null || owner.body === void 0) return [];
1718
+ return owner.body.type === "BlockStatement" ? returns.map((statement) => statement.argument) : [owner.body];
1719
+ }
1720
+ /**
1721
+ * Return whether a parameter typed exactly `unknown` is a parse boundary: every read of it is a direct argument
1722
+ * to a schema or decoder declared outside this file, every value the function returns is such a call's result,
1723
+ * and the function declares a return type that states what it parsed. A function that stores, forwards, reads
1724
+ * by hand (through `arguments` or `eval` too) or discards the parsed value is not one.
1725
+ */
1726
+ function decodesParameterIntoResult(owner, name, annotated, facts, sourceCode) {
1727
+ if (annotated.type !== "TSUnknownKeyword" || facts.readsImplicitly || !declaresParsedType(owner.returnType)) return false;
1728
+ const reads = sourceCode.getDeclaredVariables(owner).find((variable) => variable.name === name && variable.defs[0]?.type === "Parameter")?.references.filter((reference) => !reference.init);
1729
+ const decoders = new Set(reads?.map((reference) => decoderCallOf(reference.identifier, sourceCode)));
1730
+ if (decoders.has(null)) return false;
1731
+ const results = returnedExpressions(owner, facts.returns);
1732
+ return results.length > 0 && results.every((result) => {
1733
+ if (result === null) return false;
1734
+ const source = parsedSource(result);
1735
+ if (source.type !== "Identifier") return decoders.has(source);
1736
+ const initializer = constInitializerOf(variableOf(source, sourceCode));
1737
+ return initializer !== null && decoders.has(parsedSource(initializer));
1738
+ });
1739
+ }
1740
+ //#endregion
996
1741
  //#region src/oxc/anti-slop/rules/no-unknown-parameters.ts
997
1742
  function isTypePredicateSubject(owner, parameterName) {
998
1743
  const predicate = owner.returnType?.typeAnnotation;
999
1744
  return predicate?.type === "TSTypePredicate" && predicate.parameterName.type === "Identifier" && predicate.parameterName.name === parameterName;
1000
1745
  }
1746
+ /** Parameter decorators that inject a request value: interface-api's `JSONBody` and `Parameter`, and dms-lang's `JsonBody`. The decorated parameter is the I/O boundary the value is decoded at. */
1747
+ const BOUNDARY_PARAMETER_DECORATORS = /* @__PURE__ */ new Set([
1748
+ "JSONBody",
1749
+ "JsonBody",
1750
+ "Parameter"
1751
+ ]);
1752
+ function decoratorName(decorator) {
1753
+ const target = decorator.expression.type === "CallExpression" ? decorator.expression.callee : decorator.expression;
1754
+ return target.type === "Identifier" ? target.name : null;
1755
+ }
1756
+ function hasBoundaryDecorator(parameter) {
1757
+ return (parameter.decorators ?? []).some((decorator) => {
1758
+ const name = decoratorName(decorator);
1759
+ return name !== null && BOUNDARY_PARAMETER_DECORATORS.has(name);
1760
+ });
1761
+ }
1762
+ function isThisParameter(parameter) {
1763
+ return parameter.type === "Identifier" && parameter.name === "this";
1764
+ }
1765
+ /** Return whether a function is passed directly as argument `position` of a `.method(...)` call. */
1766
+ function isMethodArgument(owner, method, position) {
1767
+ const call = owner.parent;
1768
+ return call.type === "CallExpression" && call.arguments[position] === owner && call.callee.type === "MemberExpression" && !call.callee.computed && call.callee.property.type === "Identifier" && call.callee.property.name === method;
1769
+ }
1770
+ /** Return whether a callback is written directly as `.catch(onRejected)` or `.then(_, onRejected)`. */
1771
+ function isRejectionCallback(owner) {
1772
+ return isRuntimeFunction(owner) && (isMethodArgument(owner, "catch", 0) || isMethodArgument(owner, "then", 1));
1773
+ }
1774
+ /** Return whether a binding is the second parameter of a `new Promise(...)` executor. */
1775
+ function isPromiseExecutorReject(binding) {
1776
+ const executor = binding.parent;
1777
+ if (executor === null || !isRuntimeFunction(executor) || executor.params[1] !== binding) return false;
1778
+ const construction = executor.parent;
1779
+ return construction.type === "NewExpression" && construction.arguments[0] === executor && construction.callee.type === "Identifier" && construction.callee.name === "Promise";
1780
+ }
1781
+ /** Return whether a `(reason: unknown) => void` type is declared as a promise's `reject` or typed on a `new Promise` executor's reject parameter. */
1782
+ function isRejectFunctionType(owner) {
1783
+ if (owner.type !== "TSFunctionType" || owner.params.length !== 1 || owner.returnType.typeAnnotation.type !== "TSVoidKeyword" || owner.parent.type !== "TSTypeAnnotation") return false;
1784
+ const holder = owner.parent.parent;
1785
+ if (holder.type === "TSPropertySignature" || holder.type === "PropertyDefinition") return !holder.computed && holder.key.type === "Identifier" && holder.key.name === "reject";
1786
+ return holder.type === "Identifier" && (holder.name === "reject" || isPromiseExecutorReject(holder));
1787
+ }
1788
+ /** Return whether a parameter is exempt whatever its name: `this`, a boundary-decorated request value, or a promise rejection reason. */
1789
+ function isExemptPosition(owner, parameter, sourceCode) {
1790
+ if (isThisParameter(parameter) || hasBoundaryDecorator(parameter)) return true;
1791
+ if (owner.params[0] === parameter && isRejectionCallback(owner)) return true;
1792
+ return isRejectFunctionType(owner) || owner.type === "TSFunctionType" && isCaughtValueCallbackType(owner, sourceCode);
1793
+ }
1794
+ /** Return whether a parameter typed exactly `unknown` is only probed for a symbol-keyed brand this file creates, see `isBrandProbe`. */
1795
+ function probesBrand(owner, name, annotated, facts, sourceCode) {
1796
+ if (annotated.type !== "TSUnknownKeyword" || facts.readsImplicitly) return false;
1797
+ return isBrandProbe(owner, sourceCode.getDeclaredVariables(owner).find((variable) => variable.name === name && variable.defs[0]?.type === "Parameter"), sourceCode);
1798
+ }
1799
+ /** The facts of a function the rule did not walk: a signature with no body. */
1800
+ const NO_FACTS = {
1801
+ returns: [],
1802
+ readsImplicitly: false
1803
+ };
1001
1804
  /** Disallow unknown inputs except explicitly named error-cause enrichment. */
1002
1805
  const noUnknownParametersRule = defineRule({
1003
1806
  meta: {
1004
1807
  type: "problem",
1005
- docs: { description: "Disallow explicitly unknown function parameters except `cause` and type-predicate subjects; decode unknown input at its I/O boundary instead." },
1006
- messages: { unknownParameter: "Parameter `{{parameter}}` leaves input unparsed. Accept a named domain type; run the expected schema or parser at the I/O boundary before calling this function." }
1808
+ docs: { description: "Disallow explicitly unknown function parameters except `cause`, type-predicate subjects, `this`, request values injected by `@JSONBody`, `@JsonBody` or `@Parameter`, promise rejection reasons, the parameter of a callback type that the function only calls with a caught value, a symbol-keyed brand probe, and a parameter a function only decodes through a schema or decoder into the value it returns; decode unknown input at its I/O boundary instead." },
1809
+ messages: { unknownParameter: "Parameter `{{parameter}}` leaves input unparsed. Accept a named domain type and run the expected schema or parser at the I/O boundary before calling this function, or make this function that parser: pass the parameter only to the schema and return its result under a declared type." }
1007
1810
  },
1008
1811
  createOnce(context) {
1009
- const checkParameters = (node) => {
1812
+ const open = [];
1813
+ const checkParameters = (node, facts = NO_FACTS) => {
1010
1814
  for (const parameter of node.params) {
1011
1815
  const annotation = functionParameterTypeAnnotation(parameter);
1012
1816
  if (annotation === null || annotation === void 0) continue;
1013
1817
  if (!containsUnknownType(annotation.typeAnnotation)) continue;
1818
+ if (isExemptPosition(node, parameter, context.sourceCode)) continue;
1014
1819
  const name = functionParameterBindingName(parameter, context.sourceCode);
1015
1820
  if (name === "cause" || isTypePredicateSubject(node, name)) continue;
1821
+ if (isRuntimeFunction(node) && decodesParameterIntoResult(node, name, annotation.typeAnnotation, facts, context.sourceCode)) continue;
1822
+ if (isRuntimeFunction(node) && probesBrand(node, name, annotation.typeAnnotation, facts, context.sourceCode)) continue;
1016
1823
  context.report({
1017
1824
  node: annotation.typeAnnotation,
1018
1825
  messageId: "unknownParameter",
@@ -1020,10 +1827,29 @@ const noUnknownParametersRule = defineRule({
1020
1827
  });
1021
1828
  }
1022
1829
  };
1830
+ const enterFunction = () => {
1831
+ open.push({
1832
+ returns: [],
1833
+ readsImplicitly: false
1834
+ });
1835
+ };
1836
+ const leaveFunction = (node) => {
1837
+ checkParameters(node, open.pop());
1838
+ };
1023
1839
  return {
1024
- ArrowFunctionExpression: checkParameters,
1025
- FunctionDeclaration: checkParameters,
1026
- FunctionExpression: checkParameters,
1840
+ ArrowFunctionExpression: enterFunction,
1841
+ FunctionDeclaration: enterFunction,
1842
+ FunctionExpression: enterFunction,
1843
+ "ArrowFunctionExpression:exit": leaveFunction,
1844
+ "FunctionDeclaration:exit": leaveFunction,
1845
+ "FunctionExpression:exit": leaveFunction,
1846
+ ReturnStatement(node) {
1847
+ open.at(-1)?.returns.push(node);
1848
+ },
1849
+ Identifier(node) {
1850
+ if (!IMPLICIT_READERS.has(node.name)) return;
1851
+ for (const frame of open) frame.readsImplicitly = true;
1852
+ },
1027
1853
  TSCallSignatureDeclaration: checkParameters,
1028
1854
  TSConstructSignatureDeclaration: checkParameters,
1029
1855
  TSConstructorType: checkParameters,
@@ -1157,6 +1983,27 @@ function isTypeNode(node) {
1157
1983
  function typeReferenceName$1(type) {
1158
1984
  return type.typeName.type === "Identifier" ? type.typeName.name : null;
1159
1985
  }
1986
+ /** Return whether a type is literally `Record<string, unknown>`. */
1987
+ function isStringUnknownRecord(node) {
1988
+ if (node.type !== "TSTypeReference" || typeReferenceName$1(node) !== "Record") return false;
1989
+ const params = node.typeArguments?.params ?? [];
1990
+ const [key, value] = params;
1991
+ return params.length === 2 && key?.type === "TSStringKeyword" && value?.type === "TSUnknownKeyword";
1992
+ }
1993
+ /** Return whether a type is the whole target of a `value is T` predicate. */
1994
+ function isTypePredicateTarget(node) {
1995
+ const annotation = node.parent;
1996
+ return annotation.type === "TSTypeAnnotation" && annotation.parent.type === "TSTypePredicate" && !annotation.parent.asserts;
1997
+ }
1998
+ /** Return whether a type is written in the body of its nearest function, and that function is a type guard. */
1999
+ function isInsideTypeGuardBody(node, sourceCode, filename) {
2000
+ const body = enclosingTypeGuard(node, sourceCode, filename)?.body;
2001
+ return body !== void 0 && body !== null && node.start >= body.start && node.end <= body.end;
2002
+ }
2003
+ /** `Record<string, unknown>` is the narrowing a type guard establishes before it reads keys, so it passes as a predicate target or inside a guard body. */
2004
+ function isTypeGuardRecord(node, sourceCode, filename) {
2005
+ return isStringUnknownRecord(node) && (isTypePredicateTarget(node) || isInsideTypeGuardBody(node, sourceCode, filename));
2006
+ }
1160
2007
  function isInsideTypeAliasDeclaration(node) {
1161
2008
  let current = node.parent;
1162
2009
  while (current !== null && current.type !== "Program") {
@@ -1209,6 +2056,7 @@ const noUnsafeDictionaryTypeRule = defineRule({
1209
2056
  };
1210
2057
  const reportIfUnsafe = (node) => {
1211
2058
  if (environment === null || !shouldReportType(node, environment)) return;
2059
+ if (isTypeGuardRecord(node, context.sourceCode, context.filename)) return;
1212
2060
  const unsafe = classifyUnsafeDictionary(node, environment);
1213
2061
  if (unsafe === null) return;
1214
2062
  report(node, unsafe.unsafeValue);