@antelopejs/tooling-configs 0.2.15 → 0.2.17

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 (41) hide show
  1. package/README.md +88 -48
  2. package/dist/bin/api-diff.mjs +409 -97
  3. package/dist/bin/body-check.d.mts +1 -0
  4. package/dist/bin/body-check.mjs +344 -0
  5. package/dist/bin/check-size.mjs +3 -3
  6. package/dist/bin/checks.mjs +3 -3
  7. package/dist/bin/comment-proof.mjs +4 -3
  8. package/dist/bin/garden.mjs +5 -5
  9. package/dist/bin/ratchet.mjs +267 -7
  10. package/dist/bin/suppressions.mjs +118 -80
  11. package/dist/bin/sync.mjs +490 -35
  12. package/dist/bin/verify.mjs +48 -26
  13. package/dist/{ceilings-BSw9p4YB.mjs → ceilings-B7KayYIG.mjs} +11 -3
  14. package/dist/{checks-BlWDFYio.mjs → checks-CxkSu2E6.mjs} +1 -1
  15. package/dist/{ci-workflow-C0nT5SnX.mjs → ci-workflow-ChW4He0r.mjs} +103 -3
  16. package/dist/{files-2FikHZ9F.mjs → files-Bc036sJW.mjs} +2 -2
  17. package/dist/{json-BqvuCkqr.mjs → json-CG2L7YFl.mjs} +12 -8
  18. package/dist/oxc/anti-slop/index.mjs +160 -13
  19. package/dist/oxc/fmt.mjs +1 -1
  20. package/dist/oxc/guardrails/index.d.mts +1 -1
  21. package/dist/oxc/guardrails/index.mjs +645 -1
  22. package/dist/oxc/lint.d.mts +11 -3
  23. package/dist/oxc/lint.mjs +21 -8
  24. package/dist/oxlint-Bltmk8-6.mjs +94 -0
  25. package/dist/{package-Dtjt_lSa.mjs → package-DTxLPNDu.mjs} +3 -2
  26. package/dist/proof-stamp-w-3j47A-.mjs +279 -0
  27. package/dist/ratchet-DwRj9h4L.mjs +275 -0
  28. package/dist/{renames-BGO4dWJ8.mjs → renames-L2owF5GD.mjs} +2 -2
  29. package/dist/shared-CoUt4GUm.mjs +73 -0
  30. package/dist/{size-BVgNbLO6.mjs → size-DNtWruCO.mjs} +3 -3
  31. package/dist/suppression-base-DAfCXwjL.mjs +95 -0
  32. package/dist/{suppression-budget-Yyf5_J5l.mjs → suppression-budget-Bd2GqMYb.mjs} +248 -33
  33. package/dist/{suppressions-BJAngUxo.mjs → suppressions-BD_f8f7L.mjs} +180 -18
  34. package/dist/typescript-BmS5BmrS.mjs +222 -0
  35. package/dist/verify/index.mjs +1 -1
  36. package/package.json +4 -2
  37. package/dist/kinds-Bzyyi9yk.mjs +0 -25
  38. package/dist/ratchet-DRdIYwmv.mjs +0 -80
  39. package/dist/shared-CsXIMK3I.mjs +0 -34
  40. package/dist/staged-ratchet-CjoRfZaM.mjs +0 -236
  41. package/dist/typescript-C54ONh9m.mjs +0 -433
@@ -193,6 +193,648 @@ const noFsReadInTestsRule = defineRule({
193
193
  }
194
194
  });
195
195
  //#endregion
196
+ //#region src/oxc/guardrails/local-types.ts
197
+ /** Collects top-level and exported type declarations; local ones inside functions are not resolved. */
198
+ function collectLocalTypes(program) {
199
+ const types = {
200
+ aliases: /* @__PURE__ */ new Map(),
201
+ interfaces: /* @__PURE__ */ new Map()
202
+ };
203
+ for (const statement of program.body) {
204
+ const declaration = statement.type === "ExportNamedDeclaration" ? statement.declaration : statement;
205
+ if (declaration?.type === "TSTypeAliasDeclaration") types.aliases.set(declaration.id.name, declaration.typeAnnotation);
206
+ if (declaration?.type === "TSInterfaceDeclaration") {
207
+ const merged = types.interfaces.get(declaration.id.name) ?? [];
208
+ merged.push(declaration);
209
+ types.interfaces.set(declaration.id.name, merged);
210
+ }
211
+ }
212
+ return types;
213
+ }
214
+ /** The type reference's name when it is a plain identifier, such as `Record` in `Record<string, T>`. */
215
+ function referenceName(type) {
216
+ return type.typeName.type === "Identifier" ? type.typeName.name : null;
217
+ }
218
+ /** Strips parentheses and non-null assertions, which change neither the value nor its prototype. */
219
+ function unwrapExpression(node) {
220
+ let current = node;
221
+ while (current.type === "ParenthesizedExpression" || current.type === "TSNonNullExpression") current = current.expression;
222
+ return current;
223
+ }
224
+ /** The variable an identifier refers to, found by walking out from its scope. */
225
+ function resolveVariable(source, identifier) {
226
+ let scope = source.getScope(identifier);
227
+ while (scope !== null) {
228
+ const variable = scope.set.get(identifier.name);
229
+ if (variable !== void 0) return variable;
230
+ scope = scope.upper;
231
+ }
232
+ return null;
233
+ }
234
+ /** The nearest function around a node, or null at module level. */
235
+ function enclosingFunction(node) {
236
+ let current = node.parent;
237
+ while (current !== null) {
238
+ if (current.type === "ArrowFunctionExpression" || current.type === "FunctionDeclaration" || current.type === "FunctionExpression") return current;
239
+ current = current.parent;
240
+ }
241
+ return null;
242
+ }
243
+ /** The predicate a function's return type declares, when it names a parameter (`x is T`, `asserts x is T`). */
244
+ function parameterPredicate(fn) {
245
+ const predicate = fn.returnType?.typeAnnotation;
246
+ return predicate?.type === "TSTypePredicate" && predicate.parameterName.type === "Identifier" ? predicate : null;
247
+ }
248
+ /** The parameter name a predicate narrows, or null for `this` predicates. */
249
+ function predicateName(predicate) {
250
+ return predicate.parameterName.type === "Identifier" ? predicate.parameterName.name : null;
251
+ }
252
+ /** The field `this.<name>` refers to: a property or constructor parameter property of the class around `node`. */
253
+ function classField(node, name) {
254
+ let current = node.parent;
255
+ while (current !== null && current.type !== "ClassBody") {
256
+ if (current.type === "FunctionDeclaration" || current.type === "FunctionExpression" && current.parent.type !== "MethodDefinition") return null;
257
+ current = current.parent;
258
+ }
259
+ if (current === null) return null;
260
+ for (const member of current.body) {
261
+ if (member.type === "PropertyDefinition" && !member.computed && member.key.type === "Identifier" && member.key.name === name) return {
262
+ typeAnnotation: member.typeAnnotation ?? null,
263
+ value: member.value
264
+ };
265
+ if (member.type === "MethodDefinition" && member.kind === "constructor") {
266
+ for (const parameter of member.value.params) if (parameter.type === "TSParameterProperty" && parameter.parameter.type === "Identifier" && parameter.parameter.name === name) return {
267
+ typeAnnotation: parameter.parameter.typeAnnotation ?? null,
268
+ value: null
269
+ };
270
+ }
271
+ }
272
+ return null;
273
+ }
274
+ //#endregion
275
+ //#region src/oxc/guardrails/key-provenance.ts
276
+ const OWN_KEY_LISTS = /* @__PURE__ */ new Set(["Object.keys", "Object.getOwnPropertyNames"]);
277
+ const KEY_PRESERVING_METHODS = /* @__PURE__ */ new Set([
278
+ "filter",
279
+ "reverse",
280
+ "slice",
281
+ "sort",
282
+ "toReversed",
283
+ "toSorted"
284
+ ]);
285
+ const ITERATING_METHODS = /* @__PURE__ */ new Set([
286
+ "every",
287
+ "filter",
288
+ "find",
289
+ "findIndex",
290
+ "flatMap",
291
+ "forEach",
292
+ "map",
293
+ "some"
294
+ ]);
295
+ /** A literal, a template without substitutions, or a `typeof` result: never an `Object.prototype` key. */
296
+ function isStaticKey(key) {
297
+ if (key.type === "Literal") return true;
298
+ if (key.type === "UnaryExpression") return key.operator === "typeof";
299
+ return key.type === "TemplateLiteral" && key.expressions.length === 0;
300
+ }
301
+ function constInitializer(identifier, source) {
302
+ const [definition] = resolveVariable(source, identifier)?.defs ?? [];
303
+ if (definition?.type !== "Variable" || definition.parent?.type !== "VariableDeclaration" || definition.parent.kind !== "const" || definition.node.type !== "VariableDeclarator" || definition.node.init === null) return null;
304
+ let init = definition.node.init;
305
+ while (init.type === "TSAsExpression" || init.type === "TSSatisfiesExpression") init = init.expression;
306
+ return unwrapExpression(init);
307
+ }
308
+ function propertyValue(object, name) {
309
+ for (const property of object.properties) if (property.type === "Property" && !property.computed && property.key.type === "Identifier" && property.key.name === name) return property.value;
310
+ return null;
311
+ }
312
+ /** `const KEY = "a"` or `const LABELS = { a: "x" }` read as `LABELS.a`, declared in this file. */
313
+ function isConstantKey(key, source) {
314
+ if (key.type === "Identifier") {
315
+ const init = constInitializer(key, source);
316
+ return init !== null && isStaticKey(init);
317
+ }
318
+ if (key.type !== "MemberExpression" || key.computed || key.object.type !== "Identifier" || key.property.type !== "Identifier") return false;
319
+ const init = constInitializer(key.object, source);
320
+ const value = init?.type === "ObjectExpression" ? propertyValue(init, key.property.name) : null;
321
+ return value !== null && isStaticKey(value);
322
+ }
323
+ function keyList(node, source, depth = 0) {
324
+ if (depth > 8) return null;
325
+ if (node.type === "Identifier") {
326
+ const init = constInitializer(node, source);
327
+ return init === null ? null : keyList(init, source, depth + 1);
328
+ }
329
+ if (node.type === "ArrayExpression") return node.elements.every((element) => element !== null && isStaticKey(element)) ? { kind: "literal" } : null;
330
+ if (node.type !== "CallExpression") return null;
331
+ const name = callName(node.callee);
332
+ const [first] = node.arguments;
333
+ if (first !== void 0 && OWN_KEY_LISTS.has(name ?? "")) return {
334
+ kind: "keys",
335
+ table: source.getText(first)
336
+ };
337
+ if (first !== void 0 && name === "Object.entries") return {
338
+ kind: "entries",
339
+ table: source.getText(first)
340
+ };
341
+ const callee = node.callee;
342
+ return callee.type === "MemberExpression" && !callee.computed && callee.property.type === "Identifier" && KEY_PRESERVING_METHODS.has(callee.property.name) ? keyList(callee.object, source, depth + 1) : null;
343
+ }
344
+ /** The pattern that binds a key: the whole binding, or the first element of `[key, value]`. */
345
+ function keyBinding(pattern, name) {
346
+ if (pattern === name) return "plain";
347
+ return pattern.type === "ArrayPattern" && pattern.elements[0] === name ? "entry" : null;
348
+ }
349
+ /** The list a key is iterated from, with how it is bound, or a `for...in` loop. */
350
+ function keySource(definition) {
351
+ if (definition.type === "Parameter") {
352
+ const fn = definition.node;
353
+ const call = fn.parent;
354
+ if (fn.type !== "ArrowFunctionExpression" && fn.type !== "FunctionExpression" || call?.type !== "CallExpression" || call.arguments[0] !== fn || call.callee.type !== "MemberExpression" || call.callee.computed || call.callee.property.type !== "Identifier" || !ITERATING_METHODS.has(call.callee.property.name) || fn.params[0] === void 0) return null;
355
+ return {
356
+ list: call.callee.object,
357
+ binding: keyBinding(fn.params[0], definition.name)
358
+ };
359
+ }
360
+ const loop = definition.parent?.parent;
361
+ if (definition.node.type !== "VariableDeclarator") return null;
362
+ if (loop?.type === "ForInStatement") return {
363
+ list: loop,
364
+ binding: "plain"
365
+ };
366
+ return loop?.type === "ForOfStatement" ? {
367
+ list: loop.right,
368
+ binding: keyBinding(definition.node.id, definition.name)
369
+ } : null;
370
+ }
371
+ function isOwnKeyBinding(key, table, source) {
372
+ if (key.type !== "Identifier") return false;
373
+ const [definition] = resolveVariable(source, key)?.defs ?? [];
374
+ const found = definition === void 0 ? null : keySource(definition);
375
+ if (found === null || found.binding === null) return false;
376
+ if (found.list.type === "ForInStatement") return source.getText(found.list.right) === table;
377
+ const list = keyList(found.list, source);
378
+ if (list === null) return false;
379
+ if (list.kind === "literal") return found.binding === "plain";
380
+ const binding = list.kind === "keys" ? "plain" : "entry";
381
+ return list.table === table && found.binding === binding;
382
+ }
383
+ /**
384
+ * Keys the rule can prove are not inherited: static keys, same-file constants, and keys iterated
385
+ * from string literals or from `Object.keys`, `Object.entries` or `for...in` of the same table,
386
+ * through `filter`, `sort` and similar key-preserving calls. Imported constants are not resolved.
387
+ */
388
+ function isKnownKey(key, table, source) {
389
+ return isStaticKey(key) || isConstantKey(key, source) || isOwnKeyBinding(key, table, source);
390
+ }
391
+ /** `Object.prototype.hasOwnProperty.call`, `{}.hasOwnProperty.call` and other `<x>.hasOwnProperty.call` forms. */
392
+ function isHasOwnPropertyCall(callee) {
393
+ return callee.type === "MemberExpression" && !callee.computed && callee.property.type === "Identifier" && callee.property.name === "call" && callee.object.type === "MemberExpression" && !callee.object.computed && callee.object.property.type === "Identifier" && callee.object.property.name === "hasOwnProperty";
394
+ }
395
+ //#endregion
396
+ //#region src/oxc/guardrails/rules/no-inherited-key-lookup.ts
397
+ const WRAPPER_TYPES = /* @__PURE__ */ new Set([
398
+ "Readonly",
399
+ "Partial",
400
+ "Required"
401
+ ]);
402
+ const HAS_OWN_CALLS = /* @__PURE__ */ new Set(["Object.hasOwn", "hasOwnProperty.call"]);
403
+ const MAX_ALIAS_DEPTH$1 = 8;
404
+ function isStringKey(type) {
405
+ if (type.type === "TSStringKeyword") return true;
406
+ if (type.type === "TSUnionType") return type.types.some(isStringKey);
407
+ return type.type === "TSTypeReference" && referenceName(type) === "PropertyKey";
408
+ }
409
+ function hasStringIndex(members) {
410
+ return members.some((member) => member.type === "TSIndexSignature" && member.parameters.some((parameter) => isStringKey(parameter.typeAnnotation.typeAnnotation)));
411
+ }
412
+ function isStringKeyedReference(type, environment, depth) {
413
+ const name = referenceName(type);
414
+ if (name === null) return false;
415
+ const alias = environment.types.aliases.get(name);
416
+ if (alias !== void 0) return isStringKeyedType(alias, environment, depth + 1);
417
+ const declarations = environment.types.interfaces.get(name);
418
+ if (declarations !== void 0) return declarations.some((declaration) => hasStringIndex(declaration.body.body));
419
+ const [first] = type.typeArguments?.params ?? [];
420
+ if (first === void 0) return false;
421
+ if (name === "Record") return isStringKey(first);
422
+ return WRAPPER_TYPES.has(name) && isStringKeyedType(first, environment, depth + 1);
423
+ }
424
+ function isStringKeyedType(type, environment, depth = 0) {
425
+ if (depth > MAX_ALIAS_DEPTH$1) return false;
426
+ switch (type.type) {
427
+ case "TSParenthesizedType": return isStringKeyedType(type.typeAnnotation, environment, depth);
428
+ case "TSTypeLiteral": return hasStringIndex(type.members);
429
+ case "TSMappedType": return isStringKey(type.constraint);
430
+ case "TSIntersectionType":
431
+ case "TSUnionType": return type.types.some((part) => isStringKeyedType(part, environment, depth));
432
+ case "TSTypeReference": return isStringKeyedReference(type, environment, depth);
433
+ case "TSTypeQuery": return type.exprName.type === "Identifier" && tableKind(type.exprName, environment, depth + 1) === "dictionary";
434
+ default: return false;
435
+ }
436
+ }
437
+ function isProtoKey(key) {
438
+ return key.type === "Identifier" && key.name === "__proto__" || key.type === "Literal" && key.value === "__proto__";
439
+ }
440
+ function isNullPrototype(init) {
441
+ const value = unwrapExpression(init.type === "TSAsExpression" || init.type === "TSSatisfiesExpression" ? init.expression : init);
442
+ if (value.type === "CallExpression") return callName(value.callee) === "Object.create" && value.arguments[0]?.type === "Literal" && value.arguments[0].value === null;
443
+ return value.type === "ObjectExpression" && value.properties.some((property) => property.type === "Property" && !property.computed && isProtoKey(property.key) && property.value.type === "Literal" && property.value.value === null);
444
+ }
445
+ function initializerKind(init, environment, depth) {
446
+ if (init.type === "TSSatisfiesExpression") return isStringKeyedType(init.typeAnnotation, environment, depth) ? "dictionary" : initializerKind(init.expression, environment, depth);
447
+ if (init.type === "TSAsExpression") {
448
+ if (init.typeAnnotation.type === "TSTypeReference" && referenceName(init.typeAnnotation) === "const") return initializerKind(init.expression, environment, depth);
449
+ return isStringKeyedType(init.typeAnnotation, environment, depth) ? "dictionary" : null;
450
+ }
451
+ return unwrapExpression(init).type === "ObjectExpression" ? "literal" : null;
452
+ }
453
+ function annotationOf(definition) {
454
+ const name = definition.name;
455
+ return name.type === "Identifier" && "typeAnnotation" in name ? name.typeAnnotation?.typeAnnotation ?? void 0 : void 0;
456
+ }
457
+ function variableKind(variable, environment, depth) {
458
+ const [definition] = variable.defs;
459
+ if (definition === void 0) return null;
460
+ const annotation = annotationOf(definition);
461
+ if (definition.type === "Parameter") return annotation !== void 0 && isStringKeyedType(annotation, environment, depth) ? "dictionary" : null;
462
+ if (definition.type !== "Variable" || definition.node.type !== "VariableDeclarator") return null;
463
+ return declaredKind(annotation, definition.node.init, environment, depth);
464
+ }
465
+ /** The table a field declares, given its type annotation and initializer. */
466
+ function declaredKind(annotation, init, environment, depth) {
467
+ if (init !== null && isNullPrototype(init)) return null;
468
+ if (annotation !== void 0) return isStringKeyedType(annotation, environment, depth) ? "dictionary" : null;
469
+ return init === null ? null : initializerKind(init, environment, depth);
470
+ }
471
+ function fieldKind(node, environment, depth) {
472
+ if (node.computed || node.object.type !== "ThisExpression" || node.property.type !== "Identifier") return null;
473
+ const field = classField(node, node.property.name);
474
+ if (field === null) return null;
475
+ return declaredKind(field.typeAnnotation?.typeAnnotation ?? void 0, field.value, environment, depth);
476
+ }
477
+ function tableKind(node, environment, depth = 0) {
478
+ const value = node.type === "Identifier" ? node : unwrapExpression(node);
479
+ if (value.type === "ConditionalExpression") {
480
+ const kinds = [value.consequent, value.alternate].map((branch) => tableKind(branch, environment, depth));
481
+ if (kinds.includes("dictionary")) return "dictionary";
482
+ return kinds.includes("literal") ? "literal" : null;
483
+ }
484
+ if (value.type === "MemberExpression") return fieldKind(value, environment, depth);
485
+ if (value.type !== "Identifier") return null;
486
+ const variable = resolveVariable(environment.source, value);
487
+ return variable === null ? null : variableKind(variable, environment, depth);
488
+ }
489
+ function isWrite(node) {
490
+ const parent = node.parent;
491
+ if (parent.type === "AssignmentExpression") return parent.left === node && parent.operator === "=";
492
+ if (parent.type === "UnaryExpression") return parent.operator === "delete";
493
+ return (parent.type === "ForInStatement" || parent.type === "ForOfStatement") && parent.left === node;
494
+ }
495
+ function ownKeyCheck(node, source) {
496
+ const [first, second] = node.arguments;
497
+ if (first === void 0) return null;
498
+ if (HAS_OWN_CALLS.has(callName(node.callee) ?? "") || isHasOwnPropertyCall(node.callee)) return second === void 0 ? null : {
499
+ table: source.getText(first),
500
+ key: source.getText(second)
501
+ };
502
+ const callee = node.callee;
503
+ if (callee.type === "MemberExpression" && !callee.computed && callee.property.type === "Identifier" && callee.property.name === "hasOwnProperty") return {
504
+ table: source.getText(callee.object),
505
+ key: source.getText(first)
506
+ };
507
+ return null;
508
+ }
509
+ function isPredicateKey(node) {
510
+ const fn = enclosingFunction(node);
511
+ const predicate = fn === null ? null : parameterPredicate(fn);
512
+ return predicate !== null && node.left.type === "Identifier" && predicateName(predicate) === node.left.name;
513
+ }
514
+ function contains(outer, inner) {
515
+ return outer.range[0] <= inner.range[0] && inner.range[1] <= outer.range[1];
516
+ }
517
+ /** Lookups into string-keyed object tables must not answer inherited `Object.prototype` keys. */
518
+ const noInheritedKeyLookupRule = defineRule({
519
+ meta: {
520
+ type: "problem",
521
+ docs: { description: "Disallow reading a string-keyed object table with a computed key, or testing it with `in`, without an own-key check." },
522
+ messages: {
523
+ lookup: "`{{ table }}` is a string-keyed object table, so `{{ table }}[{{ key }}]` also answers keys inherited from `Object.prototype` such as `constructor` and `toString`. Store the table in a `Map` and call `.get({{ key }})`, check `Object.hasOwn({{ table }}, {{ key }})` before the read, or build the table with a null prototype (`Object.create(null)` or `{ __proto__: null, ... }`).",
524
+ inOperator: "`{{ key }} in {{ table }}` is also true for keys inherited from `Object.prototype` such as `constructor` and `toString`. Use `Object.hasOwn({{ table }}, {{ key }})`, or store the table in a `Map` and call `.has({{ key }})`."
525
+ }
526
+ },
527
+ createOnce(context) {
528
+ let environment = null;
529
+ let candidates = [];
530
+ let checks = [];
531
+ return {
532
+ Program(node) {
533
+ environment = {
534
+ source: context.sourceCode,
535
+ types: collectLocalTypes(node),
536
+ program: node
537
+ };
538
+ candidates = [];
539
+ checks = [];
540
+ },
541
+ MemberExpression(node) {
542
+ if (environment === null || !node.computed || isWrite(node)) return;
543
+ const kind = tableKind(node.object, environment);
544
+ if (kind === null || kind === "literal" && node.property.type !== "TSAsExpression") return;
545
+ const table = context.sourceCode.getText(node.object);
546
+ if (isKnownKey(node.property, table, context.sourceCode)) return;
547
+ candidates.push({
548
+ node,
549
+ messageId: "lookup",
550
+ table,
551
+ key: context.sourceCode.getText(node.property)
552
+ });
553
+ },
554
+ BinaryExpression(node) {
555
+ if (environment === null || node.operator !== "in" || isStaticKey(node.left) || isPredicateKey(node) || tableKind(node.right, environment) === null) return;
556
+ candidates.push({
557
+ node,
558
+ messageId: "inOperator",
559
+ table: context.sourceCode.getText(node.right),
560
+ key: context.sourceCode.getText(node.left)
561
+ });
562
+ },
563
+ CallExpression(node) {
564
+ const check = ownKeyCheck(node, context.sourceCode);
565
+ if (check !== null && environment !== null) checks.push({
566
+ ...check,
567
+ scope: enclosingFunction(node) ?? environment.program
568
+ });
569
+ },
570
+ "Program:exit"() {
571
+ for (const candidate of candidates) if (!checks.some((check) => check.table === candidate.table && check.key === candidate.key && contains(check.scope, candidate.node))) context.report({
572
+ node: candidate.node,
573
+ messageId: candidate.messageId,
574
+ data: {
575
+ table: candidate.table,
576
+ key: candidate.key
577
+ }
578
+ });
579
+ }
580
+ };
581
+ }
582
+ });
583
+ //#endregion
584
+ //#region src/oxc/guardrails/rules/no-presence-only-type-guard.ts
585
+ const MAX_ALIAS_DEPTH = 8;
586
+ const OPEN_TYPES = /* @__PURE__ */ new Set(["TSUnknownKeyword", "TSAnyKeyword"]);
587
+ const WIDE_TYPES = /* @__PURE__ */ new Set([...OPEN_TYPES, "TSObjectKeyword"]);
588
+ function signatureName(member) {
589
+ if (member.type !== "TSPropertySignature" && member.type !== "TSMethodSignature" || member.computed) return null;
590
+ if (member.key.type === "Identifier") return member.key.name;
591
+ return member.key.type === "Literal" ? String(member.key.value) : null;
592
+ }
593
+ function addSignatures(members, body) {
594
+ for (const member of body) {
595
+ const name = signatureName(member);
596
+ if (name === null) continue;
597
+ members.set(name, member.type === "TSPropertySignature" ? member.typeAnnotation?.typeAnnotation ?? null : null);
598
+ }
599
+ }
600
+ function referenceMembers(type, types, depth) {
601
+ const name = referenceName(type);
602
+ if (name === null) return null;
603
+ const alias = types.aliases.get(name);
604
+ if (alias !== void 0) return declaredMembers(alias, types, depth + 1);
605
+ const declarations = types.interfaces.get(name);
606
+ if (declarations === void 0) return null;
607
+ const members = /* @__PURE__ */ new Map();
608
+ for (const declaration of declarations) addSignatures(members, declaration.body.body);
609
+ return members;
610
+ }
611
+ /** The members a narrowed type declares in this file, or null when the file does not declare them. */
612
+ function declaredMembers(type, types, depth = 0) {
613
+ if (depth > MAX_ALIAS_DEPTH) return null;
614
+ switch (type.type) {
615
+ case "TSParenthesizedType": return declaredMembers(type.typeAnnotation, types, depth);
616
+ case "TSTypeLiteral": {
617
+ const members = /* @__PURE__ */ new Map();
618
+ addSignatures(members, type.members);
619
+ return members;
620
+ }
621
+ case "TSTypeReference": return referenceMembers(type, types, depth);
622
+ case "TSIntersectionType": {
623
+ const parts = type.types.map((part) => declaredMembers(part, types, depth)).filter((part) => part !== null);
624
+ return parts.length === 0 ? null : new Map(parts.flatMap((part) => [...part]));
625
+ }
626
+ default: return null;
627
+ }
628
+ }
629
+ function parameterType(fn, name) {
630
+ for (const parameter of fn.params) {
631
+ const binding = parameter.type === "AssignmentPattern" ? parameter.left : parameter;
632
+ if (binding.type === "Identifier" && binding.name === name) return binding.typeAnnotation?.typeAnnotation ?? void 0;
633
+ }
634
+ }
635
+ function isOpenRecord(type) {
636
+ const value = type.typeArguments?.params[1];
637
+ return referenceName(type) === "Record" && value !== void 0 && OPEN_TYPES.has(value.type);
638
+ }
639
+ /**
640
+ * A parameter typed `unknown`, `object`, `{}` or an open record carries no member types, so the guard
641
+ * alone vouches for them. A named or inferred parameter type already declares what a discriminant leaves out.
642
+ */
643
+ function isWide(type) {
644
+ if (type === void 0) return false;
645
+ if (WIDE_TYPES.has(type.type)) return true;
646
+ if (type.type === "TSTypeLiteral") return type.members.length === 0;
647
+ if (type.type === "TSTypeReference") return isOpenRecord(type);
648
+ return type.type === "TSUnionType" && type.types.some(isWide);
649
+ }
650
+ function frameFor(fn) {
651
+ const predicate = parameterPredicate(fn);
652
+ const name = predicate === null ? null : predicateName(predicate);
653
+ const narrowed = predicate?.typeAnnotation?.typeAnnotation;
654
+ if (predicate === null || name === null || narrowed === void 0) return null;
655
+ return {
656
+ name,
657
+ predicate,
658
+ narrowed,
659
+ parameter: parameterType(fn, name),
660
+ aliases: /* @__PURE__ */ new Set([name]),
661
+ reads: [],
662
+ dynamicReads: [],
663
+ presence: []
664
+ };
665
+ }
666
+ function guardDeclarations(program) {
667
+ const guards = /* @__PURE__ */ new Map();
668
+ const record = (name, fn) => {
669
+ const narrowed = parameterPredicate(fn)?.typeAnnotation?.typeAnnotation;
670
+ if (narrowed !== void 0) guards.set(name, narrowed);
671
+ };
672
+ for (const statement of program.body) {
673
+ const declaration = statement.type === "ExportNamedDeclaration" ? statement.declaration : statement;
674
+ if (declaration?.type === "FunctionDeclaration" && declaration.id !== null) record(declaration.id.name, declaration);
675
+ if (declaration?.type !== "VariableDeclaration") continue;
676
+ for (const declarator of declaration.declarations) {
677
+ const init = declarator.init;
678
+ if (declarator.id.type === "Identifier" && (init?.type === "ArrowFunctionExpression" || init?.type === "FunctionExpression")) record(declarator.id.name, init);
679
+ }
680
+ }
681
+ return guards;
682
+ }
683
+ function unwrapAlias(node) {
684
+ let current = unwrapExpression(node);
685
+ while (current.type === "TSAsExpression" || current.type === "TSSatisfiesExpression" || current.type === "TSTypeAssertion") current = unwrapExpression(current.expression);
686
+ return current;
687
+ }
688
+ const PRESENCE_CALLS = /* @__PURE__ */ new Set([
689
+ "Object.hasOwn",
690
+ "hasOwnProperty.call",
691
+ "Reflect.has"
692
+ ]);
693
+ /** `Object.hasOwn(x, "k")`, `hasOwnProperty.call(x, "k")` and `Reflect.has(x, "k")` test presence, as `"k" in x` does. */
694
+ function presenceCall(node) {
695
+ const [first, second] = node.arguments;
696
+ if (!PRESENCE_CALLS.has(callName(node.callee) ?? "") && !isHasOwnPropertyCall(node.callee) || first === void 0 || first.type === "SpreadElement" || second?.type !== "Literal") return null;
697
+ const object = unwrapAlias(first);
698
+ return object.type === "Identifier" ? {
699
+ object: object.name,
700
+ key: String(second.value)
701
+ } : null;
702
+ }
703
+ function callReads(node, environment) {
704
+ const objects = node.arguments.flatMap((argument) => argument.type === "Identifier" ? [argument.name] : []);
705
+ const keys = node.arguments.flatMap((argument) => argument.type === "Literal" ? [String(argument.value)] : []);
706
+ const guard = node.callee.type === "Identifier" ? environment.guards.get(node.callee.name) : void 0;
707
+ if (guard !== void 0) keys.push(...declaredMembers(guard, environment.types)?.keys() ?? []);
708
+ return objects.flatMap((object) => keys.map((key) => [object, key]));
709
+ }
710
+ /** Reports the presence-only checks and unread members of one finished guard. */
711
+ function evaluate(frame, env, context) {
712
+ const wide = isWide(frame.parameter);
713
+ if (!wide && frame.narrowed.type !== "TSIntersectionType") return;
714
+ const members = declaredMembers(frame.narrowed, env.types);
715
+ const isRead = (key) => frame.reads.some(([object, read]) => read === key && frame.aliases.has(object));
716
+ const isOpen = (key) => {
717
+ const type = members?.get(key);
718
+ return type !== void 0 && type !== null && OPEN_TYPES.has(type.type);
719
+ };
720
+ const present = /* @__PURE__ */ new Set();
721
+ for (const presence of frame.presence) {
722
+ if (!frame.aliases.has(presence.object)) continue;
723
+ present.add(presence.key);
724
+ if (isRead(presence.key) || isOpen(presence.key)) continue;
725
+ context.report({
726
+ node: presence.node,
727
+ messageId: "presenceOnly",
728
+ data: {
729
+ key: presence.key,
730
+ param: presence.object
731
+ }
732
+ });
733
+ }
734
+ const dynamic = frame.dynamicReads.some((object) => frame.aliases.has(object));
735
+ if (!wide || dynamic) return;
736
+ for (const member of members?.keys() ?? []) {
737
+ if (isOpen(member) || present.has(member) || isRead(member)) continue;
738
+ context.report({
739
+ node: frame.predicate,
740
+ messageId: "uncheckedMember",
741
+ data: {
742
+ member,
743
+ param: frame.name,
744
+ type: context.sourceCode.getText(frame.narrowed)
745
+ }
746
+ });
747
+ }
748
+ }
749
+ /** A type predicate must check what it narrows to, not only that a key is present. */
750
+ const noPresenceOnlyTypeGuardRule = defineRule({
751
+ meta: {
752
+ type: "problem",
753
+ docs: { description: "Disallow type predicates that narrow on `in` alone: a key answered by the prototype, or a member whose value is never checked." },
754
+ messages: {
755
+ inheritedKey: "`{{ key }} in ...` is also true for keys inherited from `Object.prototype` such as `constructor` and `toString`, so this guard narrows `{{ key }}` to keys the table does not have. Use `Object.hasOwn(table, {{ key }})`, or keep the keys in a `Map` or `Set` and call `.has({{ key }})`.",
756
+ presenceOnly: "`\"{{ key }}\" in {{ param }}` checks only that `{{ key }}` is present, yet the guard narrows `{{ param }}` to a type that declares its value. Check the value too (`typeof {{ param }}.{{ key }} === \"function\"`, `Array.isArray({{ param }}.{{ key }})`, a nested guard), or parse `{{ param }}` with a schema.",
757
+ uncheckedMember: "This guard narrows `{{ param }}` to `{{ type }}` but never reads `{{ param }}.{{ member }}`, so a value with any `{{ member }}` passes. Check it (`typeof`, `Array.isArray`, a nested guard), narrow to a type without it (`Pick<...>`), or parse `{{ param }}` with a schema."
758
+ }
759
+ },
760
+ createOnce(context) {
761
+ let environment = null;
762
+ const stack = [];
763
+ const active = () => stack.filter((frame) => frame !== null);
764
+ const enter = (fn) => {
765
+ stack.push(frameFor(fn));
766
+ };
767
+ const leave = () => {
768
+ const frame = stack.pop();
769
+ if (frame !== null && frame !== void 0 && environment !== null) evaluate(frame, environment, context);
770
+ };
771
+ return {
772
+ Program(node) {
773
+ environment = {
774
+ types: collectLocalTypes(node),
775
+ guards: guardDeclarations(node)
776
+ };
777
+ stack.length = 0;
778
+ },
779
+ FunctionDeclaration: enter,
780
+ FunctionExpression: enter,
781
+ ArrowFunctionExpression: enter,
782
+ "FunctionDeclaration:exit": leave,
783
+ "FunctionExpression:exit": leave,
784
+ "ArrowFunctionExpression:exit": leave,
785
+ MemberExpression(node) {
786
+ const target = unwrapAlias(node.object);
787
+ if (target.type !== "Identifier") return;
788
+ const object = target.name;
789
+ const key = memberName(node);
790
+ for (const frame of active()) if (key === null) frame.dynamicReads.push(object);
791
+ else frame.reads.push([object, key]);
792
+ },
793
+ CallExpression(node) {
794
+ if (environment === null) return;
795
+ const presence = presenceCall(node);
796
+ if (presence !== null) {
797
+ active().at(-1)?.presence.push({
798
+ node,
799
+ ...presence
800
+ });
801
+ return;
802
+ }
803
+ const reads = callReads(node, environment);
804
+ for (const frame of active()) frame.reads.push(...reads);
805
+ },
806
+ VariableDeclarator(node) {
807
+ if (node.init === null) return;
808
+ const init = unwrapAlias(node.init);
809
+ if (init.type !== "Identifier") return;
810
+ for (const frame of active()) {
811
+ if (!frame.aliases.has(init.name)) continue;
812
+ if (node.id.type === "Identifier") frame.aliases.add(node.id.name);
813
+ if (node.id.type !== "ObjectPattern") continue;
814
+ for (const property of node.id.properties) if (property.type === "Property" && property.key.type === "Identifier") frame.reads.push([init.name, property.key.name]);
815
+ }
816
+ },
817
+ BinaryExpression(node) {
818
+ const frame = active().at(-1);
819
+ if (node.operator !== "in" || frame === void 0) return;
820
+ if (node.left.type === "Identifier" && node.left.name === frame.name) {
821
+ context.report({
822
+ node,
823
+ messageId: "inheritedKey",
824
+ data: { key: frame.name }
825
+ });
826
+ return;
827
+ }
828
+ if (node.left.type === "Literal" && node.right.type === "Identifier") frame.presence.push({
829
+ node,
830
+ object: node.right.name,
831
+ key: String(node.left.value)
832
+ });
833
+ }
834
+ };
835
+ }
836
+ });
837
+ //#endregion
196
838
  //#region src/oxc/guardrails/self-package.ts
197
839
  function isObject(value) {
198
840
  return typeof value === "object" && value !== null && !Array.isArray(value);
@@ -421,12 +1063,14 @@ const requireAssertionRule = defineRule({
421
1063
  });
422
1064
  //#endregion
423
1065
  //#region src/oxc/guardrails/index.ts
424
- /** AntelopeJS rules that reject comments and low-evidence tests. */
1066
+ /** AntelopeJS rules that reject comments, inherited-key lookups, presence-only type guards and low-evidence tests. */
425
1067
  const guardrailsPlugin = eslintCompatPlugin({
426
1068
  meta: { name: "antelopejs" },
427
1069
  rules: {
428
1070
  "no-comments": noCommentsRule,
429
1071
  "no-fs-read-in-tests": noFsReadInTestsRule,
1072
+ "no-inherited-key-lookup": noInheritedKeyLookupRule,
1073
+ "no-presence-only-type-guard": noPresenceOnlyTypeGuardRule,
430
1074
  "no-constant-value-assertion": noConstantValueAssertionRule,
431
1075
  "no-self-import-in-tests": noSelfImportInTestsRule,
432
1076
  "no-typeof-function-only-test": noTypeofFunctionOnlyTestRule,