@kikiutils/eslint-config 11.4.0 → 12.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (112) hide show
  1. package/README.md +41 -23
  2. package/dist/_internals/configs/base-rules.d.ts.map +1 -1
  3. package/dist/_internals/configs/base-rules.js +39 -40
  4. package/dist/_internals/configs/base-rules.js.map +1 -1
  5. package/dist/_internals/configs/jsdoc.d.ts +0 -39
  6. package/dist/_internals/configs/jsdoc.d.ts.map +1 -1
  7. package/dist/_internals/configs/jsdoc.js +1 -45
  8. package/dist/_internals/configs/jsdoc.js.map +1 -1
  9. package/dist/_internals/configs/type-aware.d.ts.map +1 -1
  10. package/dist/_internals/configs/type-aware.js +26 -1
  11. package/dist/_internals/configs/type-aware.js.map +1 -1
  12. package/dist/_internals/configs/typescript.d.ts +42 -0
  13. package/dist/_internals/configs/typescript.d.ts.map +1 -0
  14. package/dist/_internals/configs/typescript.js +49 -0
  15. package/dist/_internals/configs/typescript.js.map +1 -0
  16. package/dist/_internals/eslint-plugin-promise.d.ts +7 -0
  17. package/dist/_internals/eslint-plugin-promise.d.ts.map +1 -0
  18. package/dist/_internals/rules/consistent-condition-layout.d.ts.map +1 -1
  19. package/dist/_internals/rules/consistent-condition-layout.js +15 -14
  20. package/dist/_internals/rules/consistent-condition-layout.js.map +1 -1
  21. package/dist/_internals/rules/consistent-parameter-layout.d.ts.map +1 -1
  22. package/dist/_internals/rules/consistent-parameter-layout.js +17 -11
  23. package/dist/_internals/rules/consistent-parameter-layout.js.map +1 -1
  24. package/dist/_internals/rules/index.d.ts +7 -1
  25. package/dist/_internals/rules/index.d.ts.map +1 -1
  26. package/dist/_internals/rules/index.js +11 -2
  27. package/dist/_internals/rules/index.js.map +1 -1
  28. package/dist/_internals/rules/no-composable-in-head-getter.d.ts.map +1 -1
  29. package/dist/_internals/rules/no-composable-in-head-getter.js +97 -19
  30. package/dist/_internals/rules/no-composable-in-head-getter.js.map +1 -1
  31. package/dist/_internals/rules/no-reactive-composable-return.d.ts +3 -0
  32. package/dist/_internals/rules/no-reactive-composable-return.d.ts.map +1 -0
  33. package/dist/_internals/rules/no-reactive-composable-return.js +43 -0
  34. package/dist/_internals/rules/no-reactive-composable-return.js.map +1 -0
  35. package/dist/_internals/rules/no-reactive-destructure.d.ts +3 -0
  36. package/dist/_internals/rules/no-reactive-destructure.d.ts.map +1 -0
  37. package/dist/_internals/rules/no-reactive-destructure.js +44 -0
  38. package/dist/_internals/rules/no-reactive-destructure.js.map +1 -0
  39. package/dist/_internals/rules/no-silent-catch.d.ts.map +1 -1
  40. package/dist/_internals/rules/no-silent-catch.js +3 -2
  41. package/dist/_internals/rules/no-silent-catch.js.map +1 -1
  42. package/dist/_internals/rules/no-thenable-zod-refinement.d.ts.map +1 -1
  43. package/dist/_internals/rules/no-thenable-zod-refinement.js +9 -3
  44. package/dist/_internals/rules/no-thenable-zod-refinement.js.map +1 -1
  45. package/dist/_internals/rules/prefer-enhanced-date.d.ts +3 -0
  46. package/dist/_internals/rules/prefer-enhanced-date.d.ts.map +1 -0
  47. package/dist/_internals/rules/prefer-enhanced-date.js +307 -0
  48. package/dist/_internals/rules/prefer-enhanced-date.js.map +1 -0
  49. package/dist/_internals/rules/promise-function-async.d.ts.map +1 -1
  50. package/dist/_internals/rules/promise-function-async.js.map +1 -1
  51. package/dist/_internals/rules/statement-padding.d.ts.map +1 -1
  52. package/dist/_internals/rules/statement-padding.js +19 -15
  53. package/dist/_internals/rules/statement-padding.js.map +1 -1
  54. package/dist/_internals/rules/utils.d.ts +23 -0
  55. package/dist/_internals/rules/utils.d.ts.map +1 -0
  56. package/dist/_internals/rules/utils.js +17 -0
  57. package/dist/_internals/rules/utils.js.map +1 -0
  58. package/dist/_internals/rules/vue-reactivity.d.ts +3 -0
  59. package/dist/_internals/rules/vue-reactivity.d.ts.map +1 -0
  60. package/dist/_internals/rules/vue-reactivity.js +30 -0
  61. package/dist/_internals/rules/vue-reactivity.js.map +1 -0
  62. package/dist/base.d.ts.map +1 -1
  63. package/dist/base.js +51 -29
  64. package/dist/base.js.map +1 -1
  65. package/dist/nuxt.d.ts +3 -1
  66. package/dist/nuxt.d.ts.map +1 -1
  67. package/dist/nuxt.js +53 -3
  68. package/dist/nuxt.js.map +1 -1
  69. package/dist/style.d.ts.map +1 -1
  70. package/dist/style.js +1 -0
  71. package/dist/style.js.map +1 -1
  72. package/dist/vue.d.ts +1 -1
  73. package/dist/vue.d.ts.map +1 -1
  74. package/dist/vue.js +17 -19
  75. package/dist/vue.js.map +1 -1
  76. package/package.json +13 -12
  77. package/src/_internals/configs/base-rules.ts +33 -52
  78. package/src/_internals/configs/jsdoc.ts +0 -57
  79. package/src/_internals/configs/type-aware.ts +29 -1
  80. package/src/_internals/configs/typescript.ts +62 -0
  81. package/src/_internals/eslint-plugin-promise.d.ts +6 -0
  82. package/src/_internals/rules/consistent-condition-layout.ts +20 -23
  83. package/src/_internals/rules/consistent-parameter-layout.ts +30 -34
  84. package/src/_internals/rules/index.ts +10 -1
  85. package/src/_internals/rules/no-composable-in-head-getter.ts +132 -26
  86. package/src/_internals/rules/no-reactive-composable-return.ts +55 -0
  87. package/src/_internals/rules/no-reactive-destructure.ts +64 -0
  88. package/src/_internals/rules/no-silent-catch.ts +4 -10
  89. package/src/_internals/rules/no-thenable-zod-refinement.ts +14 -9
  90. package/src/_internals/rules/prefer-enhanced-date.ts +448 -0
  91. package/src/_internals/rules/promise-function-async.ts +2 -6
  92. package/src/_internals/rules/statement-padding.ts +23 -24
  93. package/src/_internals/{utils.ts → rules/utils.ts} +31 -0
  94. package/src/_internals/rules/vue-reactivity.ts +42 -0
  95. package/src/base.ts +51 -47
  96. package/src/nuxt.ts +90 -5
  97. package/src/style.ts +1 -0
  98. package/src/vue.ts +24 -26
  99. package/dist/_internals/configs/restricted-syntax.d.ts +0 -5
  100. package/dist/_internals/configs/restricted-syntax.d.ts.map +0 -1
  101. package/dist/_internals/configs/restricted-syntax.js +0 -12
  102. package/dist/_internals/configs/restricted-syntax.js.map +0 -1
  103. package/dist/_internals/configs/typefest.d.ts +0 -3
  104. package/dist/_internals/configs/typefest.d.ts.map +0 -1
  105. package/dist/_internals/configs/typefest.js +0 -21
  106. package/dist/_internals/configs/typefest.js.map +0 -1
  107. package/dist/_internals/utils.d.ts +0 -4
  108. package/dist/_internals/utils.d.ts.map +0 -1
  109. package/dist/_internals/utils.js +0 -10
  110. package/dist/_internals/utils.js.map +0 -1
  111. package/src/_internals/configs/restricted-syntax.ts +0 -8
  112. package/src/_internals/configs/typefest.ts +0 -19
@@ -0,0 +1 @@
1
+ {"version":3,"file":"no-reactive-destructure.js","names":[],"sources":["../../../src/_internals/rules/no-reactive-destructure.ts"],"sourcesContent":["import type { Rule } from 'eslint';\n\nimport type { ParserServices } from './utils';\nimport { composablePattern } from './utils';\nimport { isReactiveProxy } from './vue-reactivity';\n\n// Destructuring loses reactivity only where it runs once: at module or `<script setup>` top level, in a composable or in\n// `setup()`. Callbacks such as event handlers or `computed()` getters read the current values on every call.\nfunction runsOnce(node: Rule.Node): boolean {\n let current: null | Rule.Node = node.parent;\n while (current) {\n if (\n current.type === 'ArrowFunctionExpression'\n || current.type === 'FunctionDeclaration'\n || current.type === 'FunctionExpression'\n ) {\n const { parent } = current;\n const name = current.type === 'FunctionDeclaration'\n ? current.id?.name\n : parent.type === 'VariableDeclarator' && parent.id.type === 'Identifier'\n ? parent.id.name\n : parent.type === 'Property' && parent.key.type === 'Identifier'\n ? parent.key.name\n : undefined;\n\n return !!name && (name === 'setup' || composablePattern.test(name));\n }\n\n current = current.parent;\n }\n\n return true;\n}\n\nexport const noReactiveDestructure: Rule.RuleModule = {\n create(context) {\n const services = context.sourceCode.parserServices as Partial<ParserServices> | undefined;\n if (!services?.program || !services.esTreeNodeToTSNodeMap) return {};\n const checker = services.program.getTypeChecker();\n const { esTreeNodeToTSNodeMap } = services;\n\n return {\n VariableDeclarator(node) {\n if (!node.init || (node.id.type !== 'ObjectPattern' && node.id.type !== 'ArrayPattern') || !runsOnce(node)) return;\n // `toRaw()` keeps the proxy's type but returns the raw object, so destructuring it is an intended snapshot.\n if (node.init.type === 'CallExpression' && node.init.callee.type === 'Identifier' && node.init.callee.name === 'toRaw') return;\n if (!isReactiveProxy(checker, checker.getTypeAtLocation(esTreeNodeToTSNodeMap.get(node.init)))) return;\n context.report({\n messageId: 'destructure',\n node: node.id,\n });\n },\n };\n },\n meta: {\n docs: {\n description: 'Disallow destructuring values created by Vue\\'s reactive(), shallowReactive(), readonly() and proxyRefs().',\n requiresTypeChecking: true,\n } as Rule.RuleMetaData['docs'],\n messages: { destructure: 'Destructuring a reactive object reads each property once and loses reactivity. Keep the object and access its properties where they are needed.' },\n schema: [],\n type: 'problem',\n },\n};\n"],"mappings":";;;AAQA,SAAS,SAAS,MAA0B;CACxC,IAAI,UAA4B,KAAK;CACrC,OAAO,SAAS;EACZ,IACI,QAAQ,SAAS,6BACd,QAAQ,SAAS,yBACjB,QAAQ,SAAS,sBACtB;GACE,MAAM,EAAE,WAAW;GACnB,MAAM,OAAO,QAAQ,SAAS,wBACxB,QAAQ,IAAI,OACZ,OAAO,SAAS,wBAAwB,OAAO,GAAG,SAAS,eACvD,OAAO,GAAG,OACV,OAAO,SAAS,cAAc,OAAO,IAAI,SAAS,eAC9C,OAAO,IAAI,OACX,KAAA;GAEd,OAAO,CAAC,CAAC,SAAS,SAAS,WAAW,kBAAkB,KAAK,IAAI;EACrE;EAEA,UAAU,QAAQ;CACtB;CAEA,OAAO;AACX;AAEA,MAAa,wBAAyC;CAClD,OAAO,SAAS;EACZ,MAAM,WAAW,QAAQ,WAAW;EACpC,IAAI,CAAC,UAAU,WAAW,CAAC,SAAS,uBAAuB,OAAO,CAAC;EACnE,MAAM,UAAU,SAAS,QAAQ,eAAe;EAChD,MAAM,EAAE,0BAA0B;EAElC,OAAO,EACH,mBAAmB,MAAM;GACrB,IAAI,CAAC,KAAK,QAAS,KAAK,GAAG,SAAS,mBAAmB,KAAK,GAAG,SAAS,kBAAmB,CAAC,SAAS,IAAI,GAAG;GAE5G,IAAI,KAAK,KAAK,SAAS,oBAAoB,KAAK,KAAK,OAAO,SAAS,gBAAgB,KAAK,KAAK,OAAO,SAAS,SAAS;GACxH,IAAI,CAAC,gBAAgB,SAAS,QAAQ,kBAAkB,sBAAsB,IAAI,KAAK,IAAI,CAAC,CAAC,GAAG;GAChG,QAAQ,OAAO;IACX,WAAW;IACX,MAAM,KAAK;GACf,CAAC;EACL,EACJ;CACJ;CACA,MAAM;EACF,MAAM;GACF,aAAa;GACb,sBAAsB;EAC1B;EACA,UAAU,EAAE,aAAa,kJAAkJ;EAC3K,QAAQ,CAAC;EACT,MAAM;CACV;AACJ"}
@@ -1 +1 @@
1
- {"version":3,"file":"no-silent-catch.d.ts","names":[],"sources":["../../../src/_internals/rules/no-silent-catch.ts"],"mappings":";qBAoBa,eAAe,KAAK"}
1
+ {"version":3,"file":"no-silent-catch.d.ts","names":[],"sources":["../../../src/_internals/rules/no-silent-catch.ts"],"mappings":";qBAsBa,eAAe,KAAK"}
@@ -1,3 +1,4 @@
1
+ import { isMemberNamed } from "./utils.js";
1
2
  // src/_internals/rules/no-silent-catch.ts
2
3
  function isNothing(node) {
3
4
  if (!node) return true;
@@ -17,9 +18,9 @@ const noSilentCatch = {
17
18
  return { CallExpression(node) {
18
19
  const { callee } = node;
19
20
  const callback = node.arguments[0];
20
- if (callee.type !== "MemberExpression" || callee.computed || callee.property.type !== "Identifier" || callee.property.name !== "catch" || !callback || !isSilent(callback)) return;
21
+ if (!isMemberNamed(callee, "catch") || !callback || !isSilent(callback)) return;
21
22
  const { sourceCode } = context;
22
- if ([...sourceCode.getCommentsBefore(callback), ...sourceCode.getCommentsInside(callback)].length) return;
23
+ if (sourceCode.getCommentsBefore(callback).length || sourceCode.getCommentsInside(callback).length) return;
23
24
  context.report({
24
25
  messageId: "silent",
25
26
  node: callback
@@ -1 +1 @@
1
- {"version":3,"file":"no-silent-catch.js","names":[],"sources":["../../../src/_internals/rules/no-silent-catch.ts"],"sourcesContent":["import type { Rule } from 'eslint';\n\ntype CallArgument = Extract<Rule.Node, { type: 'CallExpression' }>['arguments'][number];\ntype Expression = Exclude<CallArgument, { type: 'SpreadElement' }>;\n\nfunction isNothing(node: Expression | null | undefined): boolean {\n if (!node) return true;\n if (node.type === 'Identifier') return node.name === 'undefined';\n if (node.type === 'Literal') return node.raw === 'null';\n return node.type === 'UnaryExpression' && node.operator === 'void' && node.argument.type === 'Literal';\n}\n\nfunction isSilent(callback: CallArgument): boolean {\n if (callback.type !== 'ArrowFunctionExpression' && callback.type !== 'FunctionExpression') return false;\n const { body } = callback;\n if (body.type !== 'BlockStatement') return isNothing(body);\n const [statement, ...rest] = body.body;\n return !statement || (!rest.length && statement.type === 'ReturnStatement' && isNothing(statement.argument));\n}\n\nexport const noSilentCatch: Rule.RuleModule = {\n create(context) {\n return {\n CallExpression(node) {\n const { callee } = node;\n const callback = node.arguments[0];\n if (\n callee.type !== 'MemberExpression'\n || callee.computed\n || callee.property.type !== 'Identifier'\n || callee.property.name !== 'catch'\n || !callback\n || !isSilent(callback)\n ) return;\n\n // A comment right before or inside the callback is the reason the rejection can be ignored.\n const { sourceCode } = context;\n if (\n [\n ...sourceCode.getCommentsBefore(callback),\n ...sourceCode.getCommentsInside(callback),\n ].length\n ) return;\n\n context.report({\n messageId: 'silent',\n node: callback,\n });\n },\n };\n },\n meta: {\n docs: { description: 'Disallow `.catch()` callbacks that silently swallow the rejection.' },\n messages: { silent: 'Do not swallow the rejection silently: log it, or add a comment before or inside the callback explaining why it can be ignored.' },\n schema: [],\n type: 'problem',\n },\n};\n"],"mappings":";AAKA,SAAS,UAAU,MAA8C;CAC7D,IAAI,CAAC,MAAM,OAAO;CAClB,IAAI,KAAK,SAAS,cAAc,OAAO,KAAK,SAAS;CACrD,IAAI,KAAK,SAAS,WAAW,OAAO,KAAK,QAAQ;CACjD,OAAO,KAAK,SAAS,qBAAqB,KAAK,aAAa,UAAU,KAAK,SAAS,SAAS;AACjG;AAEA,SAAS,SAAS,UAAiC;CAC/C,IAAI,SAAS,SAAS,6BAA6B,SAAS,SAAS,sBAAsB,OAAO;CAClG,MAAM,EAAE,SAAS;CACjB,IAAI,KAAK,SAAS,kBAAkB,OAAO,UAAU,IAAI;CACzD,MAAM,CAAC,WAAW,GAAG,QAAQ,KAAK;CAClC,OAAO,CAAC,aAAc,CAAC,KAAK,UAAU,UAAU,SAAS,qBAAqB,UAAU,UAAU,QAAQ;AAC9G;AAEA,MAAa,gBAAiC;CAC1C,OAAO,SAAS;EACZ,OAAO,EACH,eAAe,MAAM;GACjB,MAAM,EAAE,WAAW;GACnB,MAAM,WAAW,KAAK,UAAU;GAChC,IACI,OAAO,SAAS,sBACb,OAAO,YACP,OAAO,SAAS,SAAS,gBACzB,OAAO,SAAS,SAAS,WACzB,CAAC,YACD,CAAC,SAAS,QAAQ,GACvB;GAGF,MAAM,EAAE,eAAe;GACvB,IACI,CACI,GAAG,WAAW,kBAAkB,QAAQ,GACxC,GAAG,WAAW,kBAAkB,QAAQ,CAC5C,CAAC,CAAC,QACJ;GAEF,QAAQ,OAAO;IACX,WAAW;IACX,MAAM;GACV,CAAC;EACL,EACJ;CACJ;CACA,MAAM;EACF,MAAM,EAAE,aAAa,qEAAqE;EAC1F,UAAU,EAAE,QAAQ,kIAAkI;EACtJ,QAAQ,CAAC;EACT,MAAM;CACV;AACJ"}
1
+ {"version":3,"file":"no-silent-catch.js","names":[],"sources":["../../../src/_internals/rules/no-silent-catch.ts"],"sourcesContent":["import type { Rule } from 'eslint';\n\nimport { isMemberNamed } from './utils';\n\ntype CallArgument = Extract<Rule.Node, { type: 'CallExpression' }>['arguments'][number];\ntype Expression = Exclude<CallArgument, { type: 'SpreadElement' }>;\n\nfunction isNothing(node: Expression | null | undefined): boolean {\n if (!node) return true;\n if (node.type === 'Identifier') return node.name === 'undefined';\n if (node.type === 'Literal') return node.raw === 'null';\n return node.type === 'UnaryExpression' && node.operator === 'void' && node.argument.type === 'Literal';\n}\n\nfunction isSilent(callback: CallArgument): boolean {\n if (callback.type !== 'ArrowFunctionExpression' && callback.type !== 'FunctionExpression') return false;\n const { body } = callback;\n if (body.type !== 'BlockStatement') return isNothing(body);\n const [statement, ...rest] = body.body;\n return !statement || (!rest.length && statement.type === 'ReturnStatement' && isNothing(statement.argument));\n}\n\nexport const noSilentCatch: Rule.RuleModule = {\n create(context) {\n return {\n CallExpression(node) {\n const { callee } = node;\n const callback = node.arguments[0];\n if (\n !isMemberNamed(callee, 'catch')\n || !callback\n || !isSilent(callback)\n ) return;\n\n // A comment right before or inside the callback is the reason the rejection can be ignored.\n const { sourceCode } = context;\n if (sourceCode.getCommentsBefore(callback).length || sourceCode.getCommentsInside(callback).length) return;\n\n context.report({\n messageId: 'silent',\n node: callback,\n });\n },\n };\n },\n meta: {\n docs: { description: 'Disallow `.catch()` callbacks that silently swallow the rejection.' },\n messages: { silent: 'Do not swallow the rejection silently: log it, or add a comment before or inside the callback explaining why it can be ignored.' },\n schema: [],\n type: 'problem',\n },\n};\n"],"mappings":";;AAOA,SAAS,UAAU,MAA8C;CAC7D,IAAI,CAAC,MAAM,OAAO;CAClB,IAAI,KAAK,SAAS,cAAc,OAAO,KAAK,SAAS;CACrD,IAAI,KAAK,SAAS,WAAW,OAAO,KAAK,QAAQ;CACjD,OAAO,KAAK,SAAS,qBAAqB,KAAK,aAAa,UAAU,KAAK,SAAS,SAAS;AACjG;AAEA,SAAS,SAAS,UAAiC;CAC/C,IAAI,SAAS,SAAS,6BAA6B,SAAS,SAAS,sBAAsB,OAAO;CAClG,MAAM,EAAE,SAAS;CACjB,IAAI,KAAK,SAAS,kBAAkB,OAAO,UAAU,IAAI;CACzD,MAAM,CAAC,WAAW,GAAG,QAAQ,KAAK;CAClC,OAAO,CAAC,aAAc,CAAC,KAAK,UAAU,UAAU,SAAS,qBAAqB,UAAU,UAAU,QAAQ;AAC9G;AAEA,MAAa,gBAAiC;CAC1C,OAAO,SAAS;EACZ,OAAO,EACH,eAAe,MAAM;GACjB,MAAM,EAAE,WAAW;GACnB,MAAM,WAAW,KAAK,UAAU;GAChC,IACI,CAAC,cAAc,QAAQ,OAAO,KAC3B,CAAC,YACD,CAAC,SAAS,QAAQ,GACvB;GAGF,MAAM,EAAE,eAAe;GACvB,IAAI,WAAW,kBAAkB,QAAQ,CAAC,CAAC,UAAU,WAAW,kBAAkB,QAAQ,CAAC,CAAC,QAAQ;GAEpG,QAAQ,OAAO;IACX,WAAW;IACX,MAAM;GACV,CAAC;EACL,EACJ;CACJ;CACA,MAAM;EACF,MAAM,EAAE,aAAa,qEAAqE;EAC1F,UAAU,EAAE,QAAQ,kIAAkI;EACtJ,QAAQ,CAAC;EACT,MAAM;CACV;AACJ"}
@@ -1 +1 @@
1
- {"version":3,"file":"no-thenable-zod-refinement.d.ts","names":[],"sources":["../../../src/_internals/rules/no-thenable-zod-refinement.ts"],"mappings":";qBAyBa,yBAAyB,KAAK"}
1
+ {"version":3,"file":"no-thenable-zod-refinement.d.ts","names":[],"sources":["../../../src/_internals/rules/no-thenable-zod-refinement.ts"],"mappings":";qBA8Ba,yBAAyB,KAAK"}
@@ -4,8 +4,14 @@ const refinementMethods = /* @__PURE__ */ new Set([
4
4
  "refine",
5
5
  "superRefine"
6
6
  ]);
7
- function isNonPromiseThenable(type) {
8
- return (type.isUnion() ? type.types : [type]).some((part) => part.getProperty("then") && part.getSymbol()?.getName() !== "Promise");
7
+ function isNonPromiseThenable(checker, type) {
8
+ return (type.isUnion() ? type.types : [type]).some((part) => part.getProperty("then") && !isPromise(checker, part));
9
+ }
10
+ function isPromise(checker, type) {
11
+ if (type.isIntersection()) return type.types.some((part) => isPromise(checker, part));
12
+ if (type.getSymbol()?.getName() === "Promise") return true;
13
+ const target = type.target ?? type;
14
+ return target.isClassOrInterface() && checker.getBaseTypes(target).some((base) => isPromise(checker, base));
9
15
  }
10
16
  const noThenableZodRefinement = {
11
17
  create(context) {
@@ -17,7 +23,7 @@ const noThenableZodRefinement = {
17
23
  if (callee.type !== "MemberExpression" || callee.computed || callee.property.type !== "Identifier" || !refinementMethods.has(callee.property.name) || !getType(node).getProperty("_zod")) return;
18
24
  const method = callee.property.name;
19
25
  for (const callback of node.arguments) {
20
- if (!getType(callback).getCallSignatures().some((signature) => isNonPromiseThenable(checker.getReturnTypeOfSignature(signature)))) continue;
26
+ if (!getType(callback).getCallSignatures().some((signature) => isNonPromiseThenable(checker, checker.getReturnTypeOfSignature(signature)))) continue;
21
27
  context.report({
22
28
  data: { method },
23
29
  messageId: "thenable",
@@ -1 +1 @@
1
- {"version":3,"file":"no-thenable-zod-refinement.js","names":[],"sources":["../../../src/_internals/rules/no-thenable-zod-refinement.ts"],"sourcesContent":["import type { Rule } from 'eslint';\nimport type {\n Node,\n Type,\n TypeChecker,\n} from 'typescript';\n\ninterface ParserServices {\n esTreeNodeToTSNodeMap: { get: (node: unknown) => Node };\n program: { getTypeChecker: () => TypeChecker };\n}\n\nconst refinementMethods = new Set([\n 'check',\n 'refine',\n 'superRefine',\n]);\n\n// Zod awaits a refinement only when it returns a native Promise; any other thenable counts as a truthy result.\nfunction isNonPromiseThenable(type: Type): boolean {\n return (type.isUnion() ? type.types : [type]).some(\n (part) => part.getProperty('then') && part.getSymbol()?.getName() !== 'Promise',\n );\n}\n\nexport const noThenableZodRefinement: Rule.RuleModule = {\n create(context) {\n const services = context.sourceCode.parserServices as ParserServices;\n const checker = services.program.getTypeChecker();\n const getType = (node: unknown) => checker.getTypeAtLocation(services.esTreeNodeToTSNodeMap.get(node));\n\n return {\n CallExpression(node) {\n const { callee } = node;\n if (\n callee.type !== 'MemberExpression'\n || callee.computed\n || callee.property.type !== 'Identifier'\n || !refinementMethods.has(callee.property.name)\n // Covers schema methods such as `z.objectId().refine()` and standalone checks such as `z.refine()`.\n || !getType(node).getProperty('_zod')\n ) return;\n\n const method = callee.property.name;\n // `.check()` takes several checks; non-function checks have no call signatures.\n for (const callback of node.arguments) {\n const returnsThenable = getType(callback)\n .getCallSignatures()\n .some((signature) => isNonPromiseThenable(checker.getReturnTypeOfSignature(signature)));\n\n if (!returnsThenable) continue;\n context.report({\n data: { method },\n messageId: 'thenable',\n node: callback,\n });\n }\n },\n };\n },\n meta: {\n docs: {\n description: 'Disallow Zod refinements and checks that return a thenable other than a Promise.',\n requiresTypeChecking: true,\n } as Rule.RuleMetaData['docs'],\n messages: { thenable: 'Zod only awaits a native Promise, so this `{{ method }}()` callback\\'s thenable (such as a Mongoose Query) counts as a passing check. Make the callback `async` and `await` the value.' },\n schema: [],\n type: 'problem',\n },\n};\n"],"mappings":";AAYA,MAAM,oCAAoB,IAAI,IAAI;CAC9B;CACA;CACA;AACJ,CAAC;AAGD,SAAS,qBAAqB,MAAqB;CAC/C,QAAQ,KAAK,QAAQ,IAAI,KAAK,QAAQ,CAAC,IAAI,EAAA,CAAG,MACzC,SAAS,KAAK,YAAY,MAAM,KAAK,KAAK,UAAU,CAAC,EAAE,QAAQ,MAAM,SAC1E;AACJ;AAEA,MAAa,0BAA2C;CACpD,OAAO,SAAS;EACZ,MAAM,WAAW,QAAQ,WAAW;EACpC,MAAM,UAAU,SAAS,QAAQ,eAAe;EAChD,MAAM,WAAW,SAAkB,QAAQ,kBAAkB,SAAS,sBAAsB,IAAI,IAAI,CAAC;EAErG,OAAO,EACH,eAAe,MAAM;GACjB,MAAM,EAAE,WAAW;GACnB,IACI,OAAO,SAAS,sBACb,OAAO,YACP,OAAO,SAAS,SAAS,gBACzB,CAAC,kBAAkB,IAAI,OAAO,SAAS,IAAI,KAE3C,CAAC,QAAQ,IAAI,CAAC,CAAC,YAAY,MAAM,GACtC;GAEF,MAAM,SAAS,OAAO,SAAS;GAE/B,KAAK,MAAM,YAAY,KAAK,WAAW;IAKnC,IAAI,CAJoB,QAAQ,QAAQ,CAAC,CACpC,kBAAkB,CAAC,CACnB,MAAM,cAAc,qBAAqB,QAAQ,yBAAyB,SAAS,CAAC,CAEtE,GAAG;IACtB,QAAQ,OAAO;KACX,MAAM,EAAE,OAAO;KACf,WAAW;KACX,MAAM;IACV,CAAC;GACL;EACJ,EACJ;CACJ;CACA,MAAM;EACF,MAAM;GACF,aAAa;GACb,sBAAsB;EAC1B;EACA,UAAU,EAAE,UAAU,wLAAyL;EAC/M,QAAQ,CAAC;EACT,MAAM;CACV;AACJ"}
1
+ {"version":3,"file":"no-thenable-zod-refinement.js","names":[],"sources":["../../../src/_internals/rules/no-thenable-zod-refinement.ts"],"sourcesContent":["import type { Rule } from 'eslint';\nimport type {\n Type,\n TypeChecker,\n TypeReference,\n} from 'typescript';\n\nimport type { ParserServices } from './utils';\n\nconst refinementMethods = new Set([\n 'check',\n 'refine',\n 'superRefine',\n]);\n\nfunction isNonPromiseThenable(checker: TypeChecker, type: Type): boolean {\n return (type.isUnion() ? type.types : [type]).some(\n (part) => part.getProperty('then') && !isPromise(checker, part),\n );\n}\n\n// Zod awaits a refinement only when it returns a native Promise (`instanceof Promise`, so subtypes and branded\n// intersections such as `SafePromise` count); any other thenable counts as a truthy result.\nfunction isPromise(checker: TypeChecker, type: Type): boolean {\n if (type.isIntersection()) return type.types.some((part) => isPromise(checker, part));\n if (type.getSymbol()?.getName() === 'Promise') return true;\n const target = (type as TypeReference).target ?? type;\n return target.isClassOrInterface() && checker.getBaseTypes(target).some((base) => isPromise(checker, base));\n}\n\nexport const noThenableZodRefinement: Rule.RuleModule = {\n create(context) {\n const services = context.sourceCode.parserServices as ParserServices;\n const checker = services.program.getTypeChecker();\n const getType = (node: unknown) => checker.getTypeAtLocation(services.esTreeNodeToTSNodeMap.get(node));\n\n return {\n CallExpression(node) {\n const { callee } = node;\n if (\n callee.type !== 'MemberExpression'\n || callee.computed\n || callee.property.type !== 'Identifier'\n || !refinementMethods.has(callee.property.name)\n // Covers schema methods such as `z.objectId().refine()` and standalone checks such as `z.refine()`.\n || !getType(node).getProperty('_zod')\n ) return;\n\n const method = callee.property.name;\n // `.check()` takes several checks; non-function checks have no call signatures.\n for (const callback of node.arguments) {\n const returnsThenable = getType(callback)\n .getCallSignatures()\n .some((signature) => isNonPromiseThenable(checker, checker.getReturnTypeOfSignature(signature)));\n\n if (!returnsThenable) continue;\n context.report({\n data: { method },\n messageId: 'thenable',\n node: callback,\n });\n }\n },\n };\n },\n meta: {\n docs: {\n description: 'Disallow Zod refinements and checks that return a thenable other than a Promise.',\n requiresTypeChecking: true,\n } as Rule.RuleMetaData['docs'],\n messages: { thenable: 'Zod only awaits a native Promise, so this `{{ method }}()` callback\\'s thenable (such as a Mongoose Query) counts as a passing check. Make the callback `async` and `await` the value.' },\n schema: [],\n type: 'problem',\n },\n};\n"],"mappings":";AASA,MAAM,oCAAoB,IAAI,IAAI;CAC9B;CACA;CACA;AACJ,CAAC;AAED,SAAS,qBAAqB,SAAsB,MAAqB;CACrE,QAAQ,KAAK,QAAQ,IAAI,KAAK,QAAQ,CAAC,IAAI,EAAA,CAAG,MACzC,SAAS,KAAK,YAAY,MAAM,KAAK,CAAC,UAAU,SAAS,IAAI,CAClE;AACJ;AAIA,SAAS,UAAU,SAAsB,MAAqB;CAC1D,IAAI,KAAK,eAAe,GAAG,OAAO,KAAK,MAAM,MAAM,SAAS,UAAU,SAAS,IAAI,CAAC;CACpF,IAAI,KAAK,UAAU,CAAC,EAAE,QAAQ,MAAM,WAAW,OAAO;CACtD,MAAM,SAAU,KAAuB,UAAU;CACjD,OAAO,OAAO,mBAAmB,KAAK,QAAQ,aAAa,MAAM,CAAC,CAAC,MAAM,SAAS,UAAU,SAAS,IAAI,CAAC;AAC9G;AAEA,MAAa,0BAA2C;CACpD,OAAO,SAAS;EACZ,MAAM,WAAW,QAAQ,WAAW;EACpC,MAAM,UAAU,SAAS,QAAQ,eAAe;EAChD,MAAM,WAAW,SAAkB,QAAQ,kBAAkB,SAAS,sBAAsB,IAAI,IAAI,CAAC;EAErG,OAAO,EACH,eAAe,MAAM;GACjB,MAAM,EAAE,WAAW;GACnB,IACI,OAAO,SAAS,sBACb,OAAO,YACP,OAAO,SAAS,SAAS,gBACzB,CAAC,kBAAkB,IAAI,OAAO,SAAS,IAAI,KAE3C,CAAC,QAAQ,IAAI,CAAC,CAAC,YAAY,MAAM,GACtC;GAEF,MAAM,SAAS,OAAO,SAAS;GAE/B,KAAK,MAAM,YAAY,KAAK,WAAW;IAKnC,IAAI,CAJoB,QAAQ,QAAQ,CAAC,CACpC,kBAAkB,CAAC,CACnB,MAAM,cAAc,qBAAqB,SAAS,QAAQ,yBAAyB,SAAS,CAAC,CAE/E,GAAG;IACtB,QAAQ,OAAO;KACX,MAAM,EAAE,OAAO;KACf,WAAW;KACX,MAAM;IACV,CAAC;GACL;EACJ,EACJ;CACJ;CACA,MAAM;EACF,MAAM;GACF,aAAa;GACb,sBAAsB;EAC1B;EACA,UAAU,EAAE,UAAU,wLAAyL;EAC/M,QAAQ,CAAC;EACT,MAAM;CACV;AACJ"}
@@ -0,0 +1,3 @@
1
+ import { Rule } from "eslint";
2
+ export declare const preferEnhancedDate: Rule.RuleModule;
3
+ //# sourceMappingURL=prefer-enhanced-date.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"prefer-enhanced-date.d.ts","names":[],"sources":["../../../src/_internals/rules/prefer-enhanced-date.ts"],"mappings":";qBAqHa,oBAAoB,KAAK"}
@@ -0,0 +1,307 @@
1
+ import { objectEntries } from "ts-extras";
2
+ // src/_internals/rules/prefer-enhanced-date.ts
3
+ const importSources = {
4
+ EnhancedDate: "@kikiutils/shared/classes/enhanced-date",
5
+ formatDate: "@kikiutils/shared/datetime"
6
+ };
7
+ const instanceMethods = /* @__PURE__ */ new Set([
8
+ ...[
9
+ "Days",
10
+ "Hours",
11
+ "Milliseconds",
12
+ "Minutes",
13
+ "Months",
14
+ "Seconds",
15
+ "Weeks",
16
+ "Years"
17
+ ].flatMap((unit) => [`add${unit}`, `sub${unit}`]),
18
+ ...[
19
+ "Day",
20
+ "Minute",
21
+ "Month",
22
+ "Week"
23
+ ].flatMap((unit) => [`endOf${unit}`, `startOf${unit}`]),
24
+ "differenceInCalendarDays",
25
+ "differenceInCalendarWeeks",
26
+ "differenceInMinutes",
27
+ "differenceInSeconds",
28
+ "format",
29
+ "formatDistanceToNow",
30
+ "getUnixTime",
31
+ "isAfter",
32
+ "isBefore",
33
+ "isEqual",
34
+ "isFuture",
35
+ "isSameDay",
36
+ "isSameMinute",
37
+ "isToday",
38
+ "isTomorrow",
39
+ "isValid"
40
+ ]);
41
+ const staticMethods = new Map(objectEntries({
42
+ endOfToday: "endOfToday",
43
+ endOfTomorrow: "endOfTomorrow",
44
+ endOfYesterday: "endOfYesterday",
45
+ fromUnixTime: "fromUnixSeconds",
46
+ max: "max",
47
+ min: "min",
48
+ parse: "fromFormat",
49
+ parseISO: "fromISO",
50
+ startOfToday: "startOfToday",
51
+ startOfTomorrow: "startOfTomorrow",
52
+ startOfYesterday: "startOfYesterday"
53
+ }));
54
+ const memberSafeTypes = /* @__PURE__ */ new Set([
55
+ "CallExpression",
56
+ "Identifier",
57
+ "MemberExpression",
58
+ "NewExpression",
59
+ "ThisExpression"
60
+ ]);
61
+ function findVariable(scope, name) {
62
+ for (let current = scope; current; current = current.upper) {
63
+ const variable = current.set.get(name);
64
+ if (variable) return variable;
65
+ }
66
+ }
67
+ function getDateFnsName(source, importedName) {
68
+ let name = importedName;
69
+ if (source !== "date-fns") {
70
+ if (!source.startsWith("date-fns/") || /^date-fns\/(?:fp|locale)(?:\/|$)/.test(source)) return;
71
+ if (importedName === "default") name = source.slice(9);
72
+ }
73
+ return name === "formatDate" ? "format" : name;
74
+ }
75
+ function isTypeImport(node) {
76
+ return node.importKind === "type";
77
+ }
78
+ const preferEnhancedDate = {
79
+ create(context) {
80
+ const { sourceCode } = context;
81
+ const services = sourceCode.parserServices;
82
+ const checker = services?.program?.getTypeChecker();
83
+ const nodeMap = services?.esTreeNodeToTSNodeMap;
84
+ const dateFnsCalls = /* @__PURE__ */ new Map();
85
+ const plans = /* @__PURE__ */ new Map();
86
+ const chainedCalls = /* @__PURE__ */ new Set();
87
+ function isEnhancedDate(node) {
88
+ if (!checker || !nodeMap) return false;
89
+ return checker.getTypeAtLocation(nodeMap.get(node)).getSymbol()?.getName() === "EnhancedDate";
90
+ }
91
+ function isNativeDate(node) {
92
+ if (node.type !== "Identifier" || node.name !== "Date") return false;
93
+ return (findVariable(sourceCode.getScope(node), "Date")?.defs ?? []).every((definition) => definition.type === "ImportBinding" && isTypeImport(definition.parent));
94
+ }
95
+ function isUnresolved(name) {
96
+ return sourceCode.scopeManager.globalScope.through.some((reference) => reference.identifier.name === name);
97
+ }
98
+ function provide(node, fixer, name) {
99
+ const variable = findVariable(sourceCode.getScope(node), name);
100
+ if (variable) return variable.defs.every((definition) => definition.type !== "ImportBinding" || !isTypeImport(definition.node) && !isTypeImport(definition.parent)) ? [] : void 0;
101
+ if (isUnresolved(name)) return [];
102
+ const { body, sourceType } = sourceCode.ast;
103
+ if (sourceType !== "module" || /\.c[jt]s$/.test(context.filename)) return;
104
+ const importText = `import { ${name} } from '${importSources[name]}';`;
105
+ const lastImport = body.findLast((statement) => statement.type === "ImportDeclaration");
106
+ if (lastImport) {
107
+ const after = sourceCode.getTokenAfter(lastImport, { includeComments: true });
108
+ const end = (after?.type === "Block" || after?.type === "Line") && after.loc.start.line === lastImport.loc.end.line ? after.range[1] : lastImport.range[1];
109
+ return [fixer.insertTextAfterRange([end, end], `\n${importText}`)];
110
+ }
111
+ const lastDirective = body.findLast((statement) => "directive" in statement && !!statement.directive);
112
+ if (lastDirective) return [fixer.insertTextAfter(lastDirective, `\n\n${importText}`)];
113
+ const [first] = body;
114
+ let start = first.range[0];
115
+ let line = first.loc.start.line;
116
+ for (const comment of sourceCode.getCommentsBefore(first).toReversed()) {
117
+ if (comment.type === "Shebang" || comment.loc.end.line + 1 < line) break;
118
+ start = comment.range[0];
119
+ line = comment.loc.start.line;
120
+ }
121
+ return [fixer.insertTextBeforeRange([start, start], `${importText}\n\n`)];
122
+ }
123
+ function isSharedFormatDateAvailable(node) {
124
+ const definitions = findVariable(sourceCode.getScope(node), "formatDate")?.defs;
125
+ if (!definitions) return !isUnresolved("formatDate");
126
+ return definitions.length > 0 && definitions.every((definition) => definition.type === "ImportBinding" && definition.parent.source.value === importSources.formatDate);
127
+ }
128
+ function withProvided(node, fixer, name, fix) {
129
+ const provided = provide(node, fixer, name);
130
+ return provided ? [fix, ...provided] : null;
131
+ }
132
+ function getArgumentTokens(node, openParen) {
133
+ let first = sourceCode.getFirstToken(node);
134
+ let last = sourceCode.getLastToken(node);
135
+ for (;;) {
136
+ const before = sourceCode.getTokenBefore(first);
137
+ const after = sourceCode.getTokenAfter(last);
138
+ if (before === openParen || before.value !== "(" || after.value !== ")") break;
139
+ first = before;
140
+ last = after;
141
+ }
142
+ return [first, last];
143
+ }
144
+ function getPlan(node) {
145
+ if (plans.has(node)) return plans.get(node);
146
+ const plan = createPlan(node, dateFnsCalls.get(node));
147
+ plans.set(node, plan);
148
+ return plan;
149
+ }
150
+ function getRewrittenText(node, edit) {
151
+ return edit.text + sourceCode.text.slice(edit.range[1], node.range[1]);
152
+ }
153
+ function createPlan(node, name) {
154
+ if (node.optional || node.arguments.some((argument) => argument.type === "SpreadElement")) return;
155
+ const openParen = sourceCode.getTokenAfter(node.callee, (token) => token.value === "(");
156
+ const staticMethod = staticMethods.get(name);
157
+ if (staticMethod) {
158
+ if (name === "fromUnixTime" && node.arguments.length > 1) return;
159
+ return {
160
+ edit: {
161
+ provides: "EnhancedDate",
162
+ range: [node.range[0], openParen.range[0]],
163
+ text: `EnhancedDate.${staticMethod}`
164
+ },
165
+ replacement: `EnhancedDate.${staticMethod}()`,
166
+ returnsDate: true
167
+ };
168
+ }
169
+ const [target, ...rest] = node.arguments;
170
+ if (!target || !instanceMethods.has(name)) return;
171
+ const inner = target.type === "CallExpression" && dateFnsCalls.has(target) ? getPlan(target) : void 0;
172
+ const innerEdit = inner?.returnsDate ? inner.edit : void 0;
173
+ const isNewDate = target.type === "NewExpression" && target.callee.type === "Identifier" && (target.callee.name === "EnhancedDate" || isNativeDate(target.callee));
174
+ const isFresh = !!innerEdit || isNewDate;
175
+ const isExisting = !isFresh && isEnhancedDate(target);
176
+ const isWrapped = !isFresh && !isExisting;
177
+ if (name === "isValid" && isWrapped) return;
178
+ const [firstToken, lastToken] = getArgumentTokens(target, openParen);
179
+ const targetText = sourceCode.text.slice(firstToken.range[0], lastToken.range[1]);
180
+ const closeParen = sourceCode.getLastToken(node);
181
+ const separator = rest.length ? sourceCode.getTokenAfter(lastToken) : closeParen;
182
+ const hasLostComments = sourceCode.commentsExistBetween(openParen, firstToken) || sourceCode.commentsExistBetween(lastToken, separator);
183
+ const awaitsLater = isWrapped && rest.some((argument) => sourceCode.getTokens(argument).some((token) => token.value === "await" || token.value === "yield"));
184
+ if (name === "format" && isWrapped && isSharedFormatDateAvailable(node)) return {
185
+ edit: {
186
+ provides: "formatDate",
187
+ range: [node.range[0], openParen.range[0]],
188
+ text: "formatDate"
189
+ },
190
+ replacement: "formatDate()",
191
+ returnsDate: false
192
+ };
193
+ let receiver = `new EnhancedDate(${targetText})`;
194
+ if (innerEdit) {
195
+ const [start, end] = target.range;
196
+ receiver = sourceCode.text.slice(firstToken.range[0], start) + getRewrittenText(target, innerEdit) + sourceCode.text.slice(end, lastToken.range[1]);
197
+ } else if (isNewDate) {
198
+ const callee = target.callee;
199
+ receiver = `new EnhancedDate${sourceCode.text.slice(callee.range[1], target.range[1]) || "()"}`;
200
+ } else if (isExisting) {
201
+ const isParenthesized = firstToken !== sourceCode.getFirstToken(target);
202
+ receiver = memberSafeTypes.has(target.type) || isParenthesized ? targetText : `(${targetText})`;
203
+ }
204
+ const replacement = `${isWrapped ? "new EnhancedDate(date)" : "date"}.${name}()`;
205
+ const returnsDate = /^(?:add|endOf|startOf|sub)[A-Z]/.test(name);
206
+ if (hasLostComments || awaitsLater) return {
207
+ replacement,
208
+ returnsDate
209
+ };
210
+ if (innerEdit) chainedCalls.add(target);
211
+ return {
212
+ edit: {
213
+ provides: innerEdit ? innerEdit.provides : isExisting ? void 0 : "EnhancedDate",
214
+ range: [node.range[0], rest.length ? sourceCode.getTokenAfter(separator, { includeComments: true }).range[0] : closeParen.range[1]],
215
+ text: `${receiver}.${name}${rest.length ? "(" : "()"}`
216
+ },
217
+ replacement,
218
+ returnsDate
219
+ };
220
+ }
221
+ function reportDateFnsCall(node, name) {
222
+ const plan = getPlan(node);
223
+ if (!plan) return;
224
+ const edit = chainedCalls.has(node) ? void 0 : plan.edit;
225
+ context.report({
226
+ data: {
227
+ name,
228
+ replacement: plan.replacement
229
+ },
230
+ fix: edit ? (fixer) => {
231
+ const fix = fixer.replaceTextRange(edit.range, edit.text);
232
+ return edit.provides ? withProvided(node, fixer, edit.provides, fix) : [fix];
233
+ } : null,
234
+ messageId: "dateFns",
235
+ node
236
+ });
237
+ }
238
+ function checkNativeDateReference(identifier) {
239
+ const parent = identifier.parent;
240
+ const isCallee = (parent.type === "CallExpression" || parent.type === "NewExpression") && parent.callee === identifier;
241
+ if (isCallee && parent.type === "CallExpression") {
242
+ context.report({
243
+ messageId: "dateCall",
244
+ node: parent
245
+ });
246
+ return;
247
+ }
248
+ if (!isCallee) return;
249
+ context.report({
250
+ fix: (fixer) => withProvided(parent, fixer, "EnhancedDate", fixer.replaceText(identifier, "EnhancedDate")),
251
+ messageId: "date",
252
+ node: parent
253
+ });
254
+ }
255
+ function checkNamespaceReference(identifier) {
256
+ const parent = identifier.parent;
257
+ if (parent.type !== "MemberExpression" || parent.object !== identifier || parent.computed || parent.optional || parent.property.type !== "Identifier") return;
258
+ const call = parent.parent;
259
+ if (call.type === "CallExpression" && call.callee === parent) dateFnsCalls.set(call, getDateFnsName("date-fns", parent.property.name));
260
+ }
261
+ return {
262
+ "ImportDeclaration": (node) => {
263
+ const source = node.source.value;
264
+ if (isTypeImport(node) || typeof source !== "string") return;
265
+ for (const specifier of node.specifiers) {
266
+ if (isTypeImport(specifier)) continue;
267
+ let name;
268
+ if (specifier.type !== "ImportNamespaceSpecifier") {
269
+ const { imported } = specifier;
270
+ name = getDateFnsName(source, imported ? imported.name ?? String(imported.value) : "default");
271
+ if (!name) continue;
272
+ } else if (source !== "date-fns") continue;
273
+ for (const { references } of sourceCode.getDeclaredVariables(specifier)) for (const reference of references) {
274
+ const identifier = reference.identifier;
275
+ const parent = identifier.parent;
276
+ if (!name) checkNamespaceReference(identifier);
277
+ else if (parent.type === "CallExpression" && parent.callee === identifier) dateFnsCalls.set(parent, name);
278
+ }
279
+ }
280
+ },
281
+ "Program:exit": () => {
282
+ for (const node of dateFnsCalls.keys()) getPlan(node);
283
+ for (const [node, name] of dateFnsCalls) reportDateFnsCall(node, name);
284
+ const { globalScope } = sourceCode.scopeManager;
285
+ const references = globalScope.set.get("Date")?.references ?? globalScope.through.filter((reference) => reference.identifier.name === "Date");
286
+ for (const reference of references) {
287
+ if (reference.isValueReference === false) continue;
288
+ checkNativeDateReference(reference.identifier);
289
+ }
290
+ }
291
+ };
292
+ },
293
+ meta: {
294
+ docs: { description: "Prefer `EnhancedDate` from `@kikiutils/shared` over native `Date` creation and the date-fns functions it wraps." },
295
+ fixable: "code",
296
+ messages: {
297
+ date: "Use `EnhancedDate` instead of `Date`: it is a drop-in subclass with chainable date-fns methods. Disable this line only where a plain `Date` is required.",
298
+ dateCall: "`Date()` returns a string; use `new EnhancedDate().toString()` instead.",
299
+ dateFns: "Use `{{ replacement }}` instead of date-fns `{{ name }}()` to keep date handling on `EnhancedDate`."
300
+ },
301
+ schema: [],
302
+ type: "suggestion"
303
+ }
304
+ };
305
+ export { preferEnhancedDate };
306
+
307
+ //# sourceMappingURL=prefer-enhanced-date.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"prefer-enhanced-date.js","names":[],"sources":["../../../src/_internals/rules/prefer-enhanced-date.ts"],"sourcesContent":["import type {\n AST,\n Rule,\n Scope,\n} from 'eslint';\nimport { objectEntries } from 'ts-extras';\n\nimport type { ParserServices } from './utils';\n\ntype CallNode = Extract<Rule.Node, { type: 'CallExpression' }>;\ntype ProvidedName = keyof typeof importSources;\n\n// Replaces the start of a call up to `range[1]` with `text`; the rest of the call stays as written.\ninterface Edit {\n provides?: ProvidedName;\n range: AST.Range;\n text: string;\n}\n\ninterface Plan {\n edit?: Edit;\n replacement: string;\n returnsDate: boolean;\n}\n\nconst importSources = {\n EnhancedDate: '@kikiutils/shared/classes/enhanced-date',\n formatDate: '@kikiutils/shared/datetime',\n} as const;\n\n// EnhancedDate mirrors these date-fns functions with the date as `this` and the remaining arguments, options included.\nconst instanceMethods = new Set([\n ...[\n 'Days',\n 'Hours',\n 'Milliseconds',\n 'Minutes',\n 'Months',\n 'Seconds',\n 'Weeks',\n 'Years',\n ].flatMap((unit) => [\n `add${unit}`,\n `sub${unit}`,\n ]),\n ...[\n 'Day',\n 'Minute',\n 'Month',\n 'Week',\n ].flatMap((unit) => [\n `endOf${unit}`,\n `startOf${unit}`,\n ]),\n 'differenceInCalendarDays',\n 'differenceInCalendarWeeks',\n 'differenceInMinutes',\n 'differenceInSeconds',\n 'format',\n 'formatDistanceToNow',\n 'getUnixTime',\n 'isAfter',\n 'isBefore',\n 'isEqual',\n 'isFuture',\n 'isSameDay',\n 'isSameMinute',\n 'isToday',\n 'isTomorrow',\n 'isValid',\n]);\n\nconst staticMethods = new Map<string, string>(objectEntries({\n endOfToday: 'endOfToday',\n endOfTomorrow: 'endOfTomorrow',\n endOfYesterday: 'endOfYesterday',\n fromUnixTime: 'fromUnixSeconds',\n max: 'max',\n min: 'min',\n parse: 'fromFormat',\n parseISO: 'fromISO',\n startOfToday: 'startOfToday',\n startOfTomorrow: 'startOfTomorrow',\n startOfYesterday: 'startOfYesterday',\n}));\n\n// Receivers that need no parentheses before a member access.\nconst memberSafeTypes = new Set([\n 'CallExpression',\n 'Identifier',\n 'MemberExpression',\n 'NewExpression',\n 'ThisExpression',\n]);\n\nfunction findVariable(scope: Scope.Scope, name: string): Scope.Variable | undefined {\n for (let current: null | Scope.Scope = scope; current; current = current.upper) {\n const variable = current.set.get(name);\n if (variable) return variable;\n }\n}\n\n// `date-fns/fp` is curried and `date-fns/locale` has no date functions; `formatDate` is date-fns' alias of `format`.\nfunction getDateFnsName(source: string, importedName: string): string | undefined {\n let name = importedName;\n if (source !== 'date-fns') {\n if (!source.startsWith('date-fns/') || /^date-fns\\/(?:fp|locale)(?:\\/|$)/.test(source)) return;\n if (importedName === 'default') name = source.slice('date-fns/'.length);\n }\n\n return name === 'formatDate' ? 'format' : name;\n}\n\nfunction isTypeImport(node: unknown): boolean {\n return (node as { importKind?: string }).importKind === 'type';\n}\n\nexport const preferEnhancedDate: Rule.RuleModule = {\n create(context) {\n const { sourceCode } = context;\n const services = sourceCode.parserServices as Partial<ParserServices> | undefined;\n // Type information only finds receivers that already are EnhancedDate; files without it are still fixed.\n const checker = services?.program?.getTypeChecker();\n const nodeMap = services?.esTreeNodeToTSNodeMap;\n // Calls are collected first so a call can chain onto the rewrite of a date-fns call in its arguments.\n const dateFnsCalls = new Map<CallNode, string>();\n const plans = new Map<CallNode, Plan | undefined>();\n const chainedCalls = new Set<CallNode>();\n\n function isEnhancedDate(node: Rule.Node): boolean {\n if (!checker || !nodeMap) return false;\n return checker.getTypeAtLocation(nodeMap.get(node)).getSymbol()?.getName() === 'EnhancedDate';\n }\n\n function isNativeDate(node: Rule.Node): boolean {\n if (node.type !== 'Identifier' || node.name !== 'Date') return false;\n // Value references skip type-only declarations; anything else declared as `Date` is not the global.\n const definitions = findVariable(sourceCode.getScope(node), 'Date')?.defs ?? [];\n return definitions.every((definition) => definition.type === 'ImportBinding' && isTypeImport(definition.parent));\n }\n\n // Nuxt auto-imports and globals the parser does not know show up as unresolved references.\n function isUnresolved(name: string): boolean {\n return sourceCode.scopeManager.globalScope!.through.some((reference) => reference.identifier.name === name);\n }\n\n // Returns undefined when the name cannot be provided, such as a type-only binding or a CommonJS file.\n function provide(node: Rule.Node, fixer: Rule.RuleFixer, name: ProvidedName): Rule.Fix[] | undefined {\n const variable = findVariable(sourceCode.getScope(node), name);\n if (variable) {\n // Configured globals have no definitions.\n const isValue = variable.defs.every((definition) => definition.type !== 'ImportBinding' || (!isTypeImport(definition.node) && !isTypeImport(definition.parent)));\n return isValue ? [] : undefined;\n }\n\n if (isUnresolved(name)) return [];\n const { body, sourceType } = sourceCode.ast;\n // Configs often parse CommonJS files as modules, so the extension decides as well.\n if (sourceType !== 'module' || /\\.c[jt]s$/.test(context.filename)) return;\n const importText = `import { ${name} } from '${importSources[name]}';`;\n const lastImport = body.findLast((statement) => statement.type === 'ImportDeclaration');\n if (lastImport) {\n // A trailing comment, such as `// eslint-disable-line`, stays on the import it belongs to.\n const after = sourceCode.getTokenAfter(lastImport, { includeComments: true });\n const isTrailingComment = (after?.type === 'Block' || after?.type === 'Line') && after.loc!.start.line === lastImport.loc!.end.line;\n const end = isTrailingComment ? after.range![1] : lastImport.range![1];\n return [\n fixer.insertTextAfterRange(\n [\n end,\n end,\n ],\n `\\n${importText}`,\n ),\n ];\n }\n\n const lastDirective = body.findLast((statement) => 'directive' in statement && !!statement.directive);\n if (lastDirective) return [fixer.insertTextAfter(lastDirective, `\\n\\n${importText}`)];\n // Comments directly above the first statement, such as JSDoc or `eslint-disable-next-line`, stay attached to it.\n const [first] = body;\n let start = first!.range![0];\n let line = first!.loc!.start.line;\n for (const comment of sourceCode.getCommentsBefore(first!).toReversed()) {\n if ((comment.type as string) === 'Shebang' || comment.loc!.end.line + 1 < line) break;\n start = comment.range![0];\n line = comment.loc!.start.line;\n }\n\n return [\n fixer.insertTextBeforeRange(\n [\n start,\n start,\n ],\n `${importText}\\n\\n`,\n ),\n ];\n }\n\n // Another local, date-fns, global or auto-imported `formatDate` may take other arguments, so those files keep the wrapper.\n function isSharedFormatDateAvailable(node: Rule.Node): boolean {\n const definitions = findVariable(sourceCode.getScope(node), 'formatDate')?.defs;\n if (!definitions) return !isUnresolved('formatDate');\n return definitions.length > 0 && definitions.every((definition) => definition.type === 'ImportBinding'\n && (definition.parent as unknown as { source: { value: unknown } }).source.value === importSources.formatDate);\n }\n\n function withProvided(node: Rule.Node, fixer: Rule.RuleFixer, name: ProvidedName, fix: Rule.Fix): null | Rule.Fix[] {\n const provided = provide(node, fixer, name);\n return provided\n ? [\n fix,\n ...provided,\n ]\n : null;\n }\n\n // Includes the parentheses written around an argument, which belong to its text.\n function getArgumentTokens(node: Rule.Node, openParen: AST.Token): [AST.Token, AST.Token] {\n let first = sourceCode.getFirstToken(node)!;\n let last = sourceCode.getLastToken(node)!;\n for (;;) {\n const before = sourceCode.getTokenBefore(first)!;\n const after = sourceCode.getTokenAfter(last)!;\n if (before === openParen || before.value !== '(' || after.value !== ')') break;\n first = before;\n last = after;\n }\n\n return [\n first,\n last,\n ];\n }\n\n function getPlan(node: CallNode): Plan | undefined {\n if (plans.has(node)) return plans.get(node);\n const plan = createPlan(node, dateFnsCalls.get(node)!);\n plans.set(node, plan);\n return plan;\n }\n\n function getRewrittenText(node: Rule.Node, edit: Edit): string {\n return edit.text + sourceCode.text.slice(edit.range[1], node.range![1]);\n }\n\n function createPlan(node: CallNode, name: string): Plan | undefined {\n if (node.optional || node.arguments.some((argument) => argument.type === 'SpreadElement')) return;\n const openParen = sourceCode.getTokenAfter(node.callee, (token) => token.value === '(')!;\n const staticMethod = staticMethods.get(name);\n if (staticMethod) {\n // `fromUnixSeconds()` takes no options; `fromUnixTime()` options only pick the returned Date class.\n if (name === 'fromUnixTime' && node.arguments.length > 1) return;\n return {\n edit: {\n provides: 'EnhancedDate',\n range: [\n node.range![0],\n openParen.range[0],\n ],\n text: `EnhancedDate.${staticMethod}`,\n },\n replacement: `EnhancedDate.${staticMethod}()`,\n returnsDate: true,\n };\n }\n\n const [target, ...rest] = node.arguments as Rule.Node[];\n if (!target || !instanceMethods.has(name)) return;\n // A date-fns call that is rewritten too returns a new EnhancedDate, so the method chains onto its rewrite.\n const inner = target.type === 'CallExpression' && dateFnsCalls.has(target) ? getPlan(target) : undefined;\n const innerEdit = inner?.returnsDate ? inner.edit : undefined;\n const isNewDate = target.type === 'NewExpression'\n && target.callee.type === 'Identifier'\n && (target.callee.name === 'EnhancedDate' || isNativeDate(target.callee as Rule.Node));\n\n const isFresh = !!innerEdit || isNewDate;\n const isExisting = !isFresh && isEnhancedDate(target);\n const isWrapped = !isFresh && !isExisting;\n // date-fns `isValid()` is false for anything but a Date or number, which a wrapper would parse instead.\n if (name === 'isValid' && isWrapped) return;\n const [firstToken, lastToken] = getArgumentTokens(target, openParen);\n const targetText = sourceCode.text.slice(firstToken.range[0], lastToken.range[1]);\n const closeParen = sourceCode.getLastToken(node)!;\n const separator = rest.length ? sourceCode.getTokenAfter(lastToken)! : closeParen;\n const hasLostComments = sourceCode.commentsExistBetween(openParen, firstToken) || sourceCode.commentsExistBetween(lastToken, separator);\n // A wrapper copies the date before an awaited argument settles, while date-fns reads it afterwards.\n const awaitsLater = isWrapped && rest.some((argument) => sourceCode.getTokens(argument).some((token) => token.value === 'await' || token.value === 'yield'));\n // Shared's `formatDate` takes the same arguments and reads better than a wrapper.\n if (name === 'format' && isWrapped && isSharedFormatDateAvailable(node)) {\n return {\n edit: {\n provides: 'formatDate',\n range: [\n node.range![0],\n openParen.range[0],\n ],\n text: 'formatDate',\n },\n replacement: 'formatDate()',\n returnsDate: false,\n };\n }\n\n let receiver = `new EnhancedDate(${targetText})`;\n if (innerEdit) {\n const [start, end] = target.range!;\n receiver = sourceCode.text.slice(firstToken.range[0], start) + getRewrittenText(target, innerEdit) + sourceCode.text.slice(end, lastToken.range[1]);\n } else if (isNewDate) {\n const callee = target.callee as Rule.Node;\n receiver = `new EnhancedDate${sourceCode.text.slice(callee.range![1], target.range![1]) || '()'}`;\n } else if (isExisting) {\n const isParenthesized = firstToken !== sourceCode.getFirstToken(target);\n receiver = memberSafeTypes.has(target.type) || isParenthesized ? targetText : `(${targetText})`;\n }\n\n const replacement = `${isWrapped ? 'new EnhancedDate(date)' : 'date'}.${name}()`;\n const returnsDate = /^(?:add|endOf|startOf|sub)[A-Z]/.test(name);\n if (hasLostComments || awaitsLater) {\n return {\n replacement,\n returnsDate,\n };\n }\n\n // The inner rewrite is part of this edit; its own edit would overlap, and when it shares the import insertion it could win.\n if (innerEdit) chainedCalls.add(target as CallNode);\n return {\n edit: {\n provides: innerEdit ? innerEdit.provides : isExisting ? undefined : 'EnhancedDate',\n range: [\n node.range![0],\n rest.length ? sourceCode.getTokenAfter(separator, { includeComments: true })!.range![0] : closeParen.range[1],\n ],\n text: `${receiver}.${name}${rest.length ? '(' : '()'}`,\n },\n replacement,\n returnsDate,\n };\n }\n\n function reportDateFnsCall(node: CallNode, name: string): void {\n const plan = getPlan(node);\n if (!plan) return;\n const edit = chainedCalls.has(node) ? undefined : plan.edit;\n context.report({\n data: {\n name,\n replacement: plan.replacement,\n },\n fix: edit\n ? (fixer) => {\n const fix = fixer.replaceTextRange(edit.range, edit.text);\n return edit.provides ? withProvided(node, fixer, edit.provides, fix) : [fix];\n }\n : null,\n messageId: 'dateFns',\n node,\n });\n }\n\n function checkNativeDateReference(identifier: Rule.Node): void {\n const parent = identifier.parent!;\n const isCallee = (parent.type === 'CallExpression' || parent.type === 'NewExpression') && parent.callee === identifier;\n if (isCallee && parent.type === 'CallExpression') {\n context.report({\n messageId: 'dateCall',\n node: parent,\n });\n\n return;\n }\n\n // `Date.now()` and other statics return numbers; `EnhancedDate` inherits them and would only add an import.\n if (!isCallee) return;\n context.report({\n fix: (fixer) => withProvided(parent, fixer, 'EnhancedDate', fixer.replaceText(identifier, 'EnhancedDate')),\n messageId: 'date',\n node: parent,\n });\n }\n\n function checkNamespaceReference(identifier: Rule.Node): void {\n const parent = identifier.parent!;\n if (\n parent.type !== 'MemberExpression'\n || parent.object !== identifier\n || parent.computed\n || parent.optional\n || parent.property.type !== 'Identifier'\n ) return;\n\n const call = parent.parent;\n if (call.type === 'CallExpression' && call.callee === parent) dateFnsCalls.set(call, getDateFnsName('date-fns', parent.property.name)!);\n }\n\n return {\n 'ImportDeclaration': (node) => {\n const source = node.source.value;\n if (isTypeImport(node) || typeof source !== 'string') return;\n for (const specifier of node.specifiers) {\n if (isTypeImport(specifier)) continue;\n let name: string | undefined;\n if (specifier.type !== 'ImportNamespaceSpecifier') {\n const { imported } = specifier as { imported?: { name?: string; value?: unknown } };\n name = getDateFnsName(source, imported ? imported.name ?? String(imported.value) : 'default');\n if (!name) continue;\n } else if (source !== 'date-fns') continue;\n\n for (const { references } of sourceCode.getDeclaredVariables(specifier)) {\n for (const reference of references) {\n const identifier = reference.identifier as Rule.Node;\n const parent = identifier.parent!;\n if (!name) checkNamespaceReference(identifier);\n else if (parent.type === 'CallExpression' && parent.callee === identifier) dateFnsCalls.set(parent, name);\n }\n }\n }\n },\n 'Program:exit': () => {\n // Every plan exists before reporting, so calls chained into an outer rewrite are known.\n for (const node of dateFnsCalls.keys()) getPlan(node);\n for (const [node, name] of dateFnsCalls) reportDateFnsCall(node, name);\n const { globalScope } = sourceCode.scopeManager;\n const references = globalScope!.set.get('Date')?.references\n ?? globalScope!.through.filter((reference) => reference.identifier.name === 'Date');\n\n for (const reference of references) {\n // typescript-eslint also resolves `: Date` annotations here; only value references create dates.\n if ((reference as { isValueReference?: boolean }).isValueReference === false) continue;\n checkNativeDateReference(reference.identifier as Rule.Node);\n }\n },\n };\n },\n meta: {\n docs: { description: 'Prefer `EnhancedDate` from `@kikiutils/shared` over native `Date` creation and the date-fns functions it wraps.' },\n fixable: 'code',\n messages: {\n date: 'Use `EnhancedDate` instead of `Date`: it is a drop-in subclass with chainable date-fns methods. Disable this line only where a plain `Date` is required.',\n dateCall: '`Date()` returns a string; use `new EnhancedDate().toString()` instead.',\n dateFns: 'Use `{{ replacement }}` instead of date-fns `{{ name }}()` to keep date handling on `EnhancedDate`.',\n },\n schema: [],\n type: 'suggestion',\n },\n};\n"],"mappings":";;AAyBA,MAAM,gBAAgB;CAClB,cAAc;CACd,YAAY;AAChB;AAGA,MAAM,kCAAkB,IAAI,IAAI;CAC5B,GAAG;EACC;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACJ,CAAC,CAAC,SAA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AU,UAAuB;IAC9D;GACJ;EACJ;CACJ;CACA,MAAM;EACF,MAAM,EAAE,aAAa,kHAAkH;EACvI,SAAS;EACT,UAAU;GACN,MAAM;GACN,UAAU;GACV,SAAS;EACb;EACA,QAAQ,CAAC;EACT,MAAM;CACV;AACJ"}
@@ -1 +1 @@
1
- {"version":3,"file":"promise-function-async.d.ts","names":[],"sources":["../../../src/_internals/rules/promise-function-async.ts"],"mappings":";qBA6Ba,sBAAsB,KAAK"}
1
+ {"version":3,"file":"promise-function-async.d.ts","names":[],"sources":["../../../src/_internals/rules/promise-function-async.ts"],"mappings":";qBAyBa,sBAAsB,KAAK"}
@@ -1 +1 @@
1
- {"version":3,"file":"promise-function-async.js","names":[],"sources":["../../../src/_internals/rules/promise-function-async.ts"],"sourcesContent":["import tseslint from '@typescript-eslint/eslint-plugin';\nimport type { Rule } from 'eslint';\nimport type {\n Node,\n SignatureDeclaration,\n Type,\n TypeChecker,\n} from 'typescript';\n\ninterface ParserServices {\n esTreeNodeToTSNodeMap: { get: (node: unknown) => Node };\n program: { getTypeChecker: () => TypeChecker };\n}\n\nconst upstream = tseslint.rules['promise-function-async'] as unknown as Rule.RuleModule;\nconst promiseMembers = new Set([\n 'catch',\n 'finally',\n 'then',\n]);\n\n// A thenable with extra members, such as Nuxt's `AsyncData`, loses those members once the function becomes async.\nfunction hasNonPromiseMembers(checker: TypeChecker, type: Type): boolean {\n return (type.isUnion() ? type.types : [type]).some((part) => {\n const names = checker.getPropertiesOfType(part).map((symbol) => symbol.getName());\n return names.includes('then') && names.some((name) => !promiseMembers.has(name) && !name.startsWith('__@'));\n });\n}\n\nexport const promiseFunctionAsync: Rule.RuleModule = {\n create(context) {\n const report = (descriptor: Rule.ReportDescriptor) => {\n if ('node' in descriptor) {\n const services = context.sourceCode.parserServices as ParserServices;\n const checker = services.program.getTypeChecker();\n const tsNode = services.esTreeNodeToTSNodeMap.get(descriptor.node) as SignatureDeclaration;\n // Overloads are what callers see, so they count alongside the implementation signature.\n const signatures = [\n checker.getSignatureFromDeclaration(tsNode),\n ...checker.getTypeAtLocation(tsNode).getCallSignatures(),\n ];\n\n if (\n signatures.some((signature) => signature\n && hasNonPromiseMembers(checker, checker.getReturnTypeOfSignature(signature)))\n ) return;\n }\n\n context.report(descriptor);\n };\n\n // The upstream rule validates that type information is available.\n return upstream.create(Object.create(context, { report: { value: report } }));\n },\n meta: upstream.meta,\n};\n"],"mappings":";;AAcA,MAAM,WAAW,SAAS,MAAM;AAChC,MAAM,iCAAiB,IAAI,IAAI;CAC3B;CACA;CACA;AACJ,CAAC;AAGD,SAAS,qBAAqB,SAAsB,MAAqB;CACrE,QAAQ,KAAK,QAAQ,IAAI,KAAK,QAAQ,CAAC,IAAI,EAAA,CAAG,MAAM,SAAS;EACzD,MAAM,QAAQ,QAAQ,oBAAoB,IAAI,CAAC,CAAC,KAAK,WAAW,OAAO,QAAQ,CAAC;EAChF,OAAO,MAAM,SAAS,MAAM,KAAK,MAAM,MAAM,SAAS,CAAC,eAAe,IAAI,IAAI,KAAK,CAAC,KAAK,WAAW,KAAK,CAAC;CAC9G,CAAC;AACL;AAEA,MAAa,uBAAwC;CACjD,OAAO,SAAS;EACZ,MAAM,UAAU,eAAsC;GAClD,IAAI,UAAU,YAAY;IACtB,MAAM,WAAW,QAAQ,WAAW;IACpC,MAAM,UAAU,SAAS,QAAQ,eAAe;IAChD,MAAM,SAAS,SAAS,sBAAsB,IAAI,WAAW,IAAI;IAOjE,IACI,CALA,QAAQ,4BAA4B,MAAM,GAC1C,GAAG,QAAQ,kBAAkB,MAAM,CAAC,CAAC,kBAAkB,CAI9C,CAAC,CAAC,MAAM,cAAc,aAC1B,qBAAqB,SAAS,QAAQ,yBAAyB,SAAS,CAAC,CAAC,GACjF;GACN;GAEA,QAAQ,OAAO,UAAU;EAC7B;EAGA,OAAO,SAAS,OAAO,OAAO,OAAO,SAAS,EAAE,QAAQ,EAAE,OAAO,OAAO,EAAE,CAAC,CAAC;CAChF;CACA,MAAM,SAAS;AACnB"}
1
+ {"version":3,"file":"promise-function-async.js","names":[],"sources":["../../../src/_internals/rules/promise-function-async.ts"],"sourcesContent":["import tseslint from '@typescript-eslint/eslint-plugin';\nimport type { Rule } from 'eslint';\nimport type {\n SignatureDeclaration,\n Type,\n TypeChecker,\n} from 'typescript';\n\nimport type { ParserServices } from './utils';\n\nconst upstream = tseslint.rules['promise-function-async'] as unknown as Rule.RuleModule;\nconst promiseMembers = new Set([\n 'catch',\n 'finally',\n 'then',\n]);\n\n// A thenable with extra members, such as Nuxt's `AsyncData`, loses those members once the function becomes async.\nfunction hasNonPromiseMembers(checker: TypeChecker, type: Type): boolean {\n return (type.isUnion() ? type.types : [type]).some((part) => {\n const names = checker.getPropertiesOfType(part).map((symbol) => symbol.getName());\n return names.includes('then') && names.some((name) => !promiseMembers.has(name) && !name.startsWith('__@'));\n });\n}\n\nexport const promiseFunctionAsync: Rule.RuleModule = {\n create(context) {\n const report = (descriptor: Rule.ReportDescriptor) => {\n if ('node' in descriptor) {\n const services = context.sourceCode.parserServices as ParserServices;\n const checker = services.program.getTypeChecker();\n const tsNode = services.esTreeNodeToTSNodeMap.get(descriptor.node) as SignatureDeclaration;\n // Overloads are what callers see, so they count alongside the implementation signature.\n const signatures = [\n checker.getSignatureFromDeclaration(tsNode),\n ...checker.getTypeAtLocation(tsNode).getCallSignatures(),\n ];\n\n if (\n signatures.some((signature) => signature\n && hasNonPromiseMembers(checker, checker.getReturnTypeOfSignature(signature)))\n ) return;\n }\n\n context.report(descriptor);\n };\n\n // The upstream rule validates that type information is available.\n return upstream.create(Object.create(context, { report: { value: report } }) as Rule.RuleContext);\n },\n meta: upstream.meta,\n};\n"],"mappings":";;AAUA,MAAM,WAAW,SAAS,MAAM;AAChC,MAAM,iCAAiB,IAAI,IAAI;CAC3B;CACA;CACA;AACJ,CAAC;AAGD,SAAS,qBAAqB,SAAsB,MAAqB;CACrE,QAAQ,KAAK,QAAQ,IAAI,KAAK,QAAQ,CAAC,IAAI,EAAA,CAAG,MAAM,SAAS;EACzD,MAAM,QAAQ,QAAQ,oBAAoB,IAAI,CAAC,CAAC,KAAK,WAAW,OAAO,QAAQ,CAAC;EAChF,OAAO,MAAM,SAAS,MAAM,KAAK,MAAM,MAAM,SAAS,CAAC,eAAe,IAAI,IAAI,KAAK,CAAC,KAAK,WAAW,KAAK,CAAC;CAC9G,CAAC;AACL;AAEA,MAAa,uBAAwC;CACjD,OAAO,SAAS;EACZ,MAAM,UAAU,eAAsC;GAClD,IAAI,UAAU,YAAY;IACtB,MAAM,WAAW,QAAQ,WAAW;IACpC,MAAM,UAAU,SAAS,QAAQ,eAAe;IAChD,MAAM,SAAS,SAAS,sBAAsB,IAAI,WAAW,IAAI;IAOjE,IACI,CALA,QAAQ,4BAA4B,MAAM,GAC1C,GAAG,QAAQ,kBAAkB,MAAM,CAAC,CAAC,kBAAkB,CAI9C,CAAC,CAAC,MAAM,cAAc,aAC1B,qBAAqB,SAAS,QAAQ,yBAAyB,SAAS,CAAC,CAAC,GACjF;GACN;GAEA,QAAQ,OAAO,UAAU;EAC7B;EAGA,OAAO,SAAS,OAAO,OAAO,OAAO,SAAS,EAAE,QAAQ,EAAE,OAAO,OAAO,EAAE,CAAC,CAAqB;CACpG;CACA,MAAM,SAAS;AACnB"}
@@ -1 +1 @@
1
- {"version":3,"file":"statement-padding.d.ts","names":[],"sources":["../../../src/_internals/rules/statement-padding.ts"],"mappings":";qBAIa,kBAAkB,KAAK"}
1
+ {"version":3,"file":"statement-padding.d.ts","names":[],"sources":["../../../src/_internals/rules/statement-padding.ts"],"mappings":";qBAyBa,kBAAkB,KAAK"}
@@ -1,4 +1,21 @@
1
1
  // src/_internals/rules/statement-padding.ts
2
+ const blockTypes = /* @__PURE__ */ new Set([
3
+ "BlockStatement",
4
+ "ClassDeclaration",
5
+ "ForInStatement",
6
+ "ForOfStatement",
7
+ "ForStatement",
8
+ "FunctionDeclaration",
9
+ "IfStatement",
10
+ "LabeledStatement",
11
+ "SwitchStatement",
12
+ "TryStatement",
13
+ "WhileStatement",
14
+ "WithStatement"
15
+ ]);
16
+ function isImportOrReexport(node) {
17
+ return node.type === "ImportDeclaration" || node.type === "ExportAllDeclaration" || node.type === "ExportNamedDeclaration" && !!node.source;
18
+ }
2
19
  const statementPadding = {
3
20
  create(context) {
4
21
  const { sourceCode } = context;
@@ -6,26 +23,13 @@ const statementPadding = {
6
23
  for (let index = 1; index < statements.length; index++) {
7
24
  const previous = statements[index - 1];
8
25
  const next = statements[index];
9
- if ([previous, next].some((node) => node.type === "ImportDeclaration" || node.type === "ExportAllDeclaration" || node.type === "ExportNamedDeclaration" && node.source)) continue;
26
+ if (isImportOrReexport(previous) || isImportOrReexport(next)) continue;
10
27
  const previousFirstToken = sourceCode.getFirstToken(previous);
11
28
  const lastToken = sourceCode.getLastToken(previous);
12
29
  const firstToken = sourceCode.getFirstToken(next);
13
30
  const isMultiline = previousFirstToken.loc.start.line !== lastToken.loc.end.line;
14
31
  const blockNode = previous.type === "ExportDefaultDeclaration" || previous.type === "ExportNamedDeclaration" ? previous.declaration : previous;
15
- const hasBlockClosing = lastToken.value === "}" && blockNode && [
16
- "BlockStatement",
17
- "ClassDeclaration",
18
- "ForInStatement",
19
- "ForOfStatement",
20
- "ForStatement",
21
- "FunctionDeclaration",
22
- "IfStatement",
23
- "LabeledStatement",
24
- "SwitchStatement",
25
- "TryStatement",
26
- "WhileStatement",
27
- "WithStatement"
28
- ].includes(blockNode.type);
32
+ const hasBlockClosing = lastToken.value === "}" && blockNode && blockTypes.has(blockNode.type);
29
33
  if (!isMultiline && !hasBlockClosing) continue;
30
34
  let previousEnd = lastToken.range[1];
31
35
  let previousEndLine = lastToken.loc.end.line;
@@ -1 +1 @@
1
- {"version":3,"file":"statement-padding.js","names":[],"sources":["../../../src/_internals/rules/statement-padding.ts"],"sourcesContent":["import type { Rule } from 'eslint';\n\ntype StatementNode = Extract<Rule.Node, { type: 'Program' }>['body'][number];\n\nexport const statementPadding: Rule.RuleModule = {\n create(context) {\n const { sourceCode } = context;\n\n function checkStatements(statements: readonly StatementNode[]): void {\n for (let index = 1; index < statements.length; index++) {\n const previous = statements[index - 1]!;\n const next = statements[index]!;\n if (\n [\n previous,\n next,\n ].some((node) =>\n node.type === 'ImportDeclaration'\n || node.type === 'ExportAllDeclaration'\n || (node.type === 'ExportNamedDeclaration' && node.source))\n ) continue;\n\n const previousFirstToken = sourceCode.getFirstToken(previous)!;\n const lastToken = sourceCode.getLastToken(previous)!;\n const firstToken = sourceCode.getFirstToken(next)!;\n const isMultiline = previousFirstToken.loc.start.line !== lastToken.loc.end.line;\n const blockNode = previous.type === 'ExportDefaultDeclaration'\n || previous.type === 'ExportNamedDeclaration'\n ? previous.declaration\n : previous;\n\n const hasBlockClosing = lastToken.value === '}' && blockNode && [\n 'BlockStatement',\n 'ClassDeclaration',\n 'ForInStatement',\n 'ForOfStatement',\n 'ForStatement',\n 'FunctionDeclaration',\n 'IfStatement',\n 'LabeledStatement',\n 'SwitchStatement',\n 'TryStatement',\n 'WhileStatement',\n 'WithStatement',\n ].includes(blockNode.type);\n\n if (!isMultiline && !hasBlockClosing) continue;\n let previousEnd = lastToken.range[1];\n let previousEndLine = lastToken.loc.end.line;\n let nextStart = firstToken.range[0];\n let nextStartLine = firstToken.loc.start.line;\n\n // Include trailing comments in the previous boundary, not leading comments of the next statement.\n for (const comment of sourceCode.getCommentsBefore(next)) {\n if (comment.loc!.start.line === previousEndLine) {\n previousEnd = comment.range![1];\n previousEndLine = comment.loc!.end.line;\n } else {\n nextStart = comment.range![0];\n nextStartLine = comment.loc!.start.line;\n break;\n }\n }\n\n if (nextStartLine > previousEndLine + 1) continue;\n const linebreakIndex = sourceCode.text.slice(previousEnd, nextStart).indexOf('\\n');\n const offset = linebreakIndex === -1 ? nextStart : previousEnd + linebreakIndex + 1;\n\n context.report({\n fix: (fixer) => fixer.insertTextBeforeRange(\n [\n offset,\n offset,\n ],\n linebreakIndex === -1 ? '\\n\\n' : '\\n',\n ),\n messageId: 'blankLine',\n node: next,\n });\n }\n }\n\n return {\n BlockStatement: (node) => checkStatements(node.body),\n Program: (node) => checkStatements(node.body),\n StaticBlock: (node) => checkStatements(node.body),\n SwitchCase: (node) => checkStatements(node.consequent),\n TSModuleBlock: (node: Rule.Node & { body: StatementNode[] }) => checkStatements(node.body),\n };\n },\n meta: {\n docs: { description: 'Separate complete multiline statements and block-ending statements with blank lines.' },\n fixable: 'whitespace',\n messages: { blankLine: 'Add a blank line between these complete statements.' },\n schema: [],\n type: 'layout',\n },\n};\n"],"mappings":";AAIA,MAAa,mBAAoC;CAC7C,OAAO,SAAS;EACZ,MAAM,EAAE,eAAe;EAEvB,SAAS,gBAAgB,YAA4C;GACjE,KAAK,IAAI,QAAQ,GAAG,QAAQ,WAAW,QAAQ,SAAS;IACpD,MAAM,WAAW,WAAW,QAAQ;IACpC,MAAM,OAAO,WAAW;IACxB,IACI,CACI,UACA,IACJ,CAAC,CAAC,MAAM,SACJ,KAAK,SAAS,uBACX,KAAK,SAAS,0BACb,KAAK,SAAS,4BAA4B,KAAK,MAAO,GAChE;IAEF,MAAM,qBAAqB,WAAW,cAAc,QAAQ;IAC5D,MAAM,YAAY,WAAW,aAAa,QAAQ;IAClD,MAAM,aAAa,WAAW,cAAc,IAAI;IAChD,MAAM,cAAc,mBAAmB,IAAI,MAAM,SAAS,UAAU,IAAI,IAAI;IAC5E,MAAM,YAAY,SAAS,SAAS,8BAC/B,SAAS,SAAS,2BACjB,SAAS,cACT;IAEN,MAAM,kBAAkB,UAAU,UAAU,OAAO,aAAa;KAC5D;KACA;KACA;KACA;KACA;KACA;KACA;KACA;KACA;KACA;KACA;KACA;IACJ,CAAC,CAAC,SAAS,UAAU,IAAI;IAEzB,IAAI,CAAC,eAAe,CAAC,iBAAiB;IACtC,IAAI,cAAc,UAAU,MAAM;IAClC,IAAI,kBAAkB,UAAU,IAAI,IAAI;IACxC,IAAI,YAAY,WAAW,MAAM;IACjC,IAAI,gBAAgB,WAAW,IAAI,MAAM;IAGzC,KAAK,MAAM,WAAW,WAAW,kBAAkB,IAAI,GACnD,IAAI,QAAQ,IAAK,MAAM,SAAS,iBAAiB;KAC7C,cAAc,QAAQ,MAAO;KAC7B,kBAAkB,QAAQ,IAAK,IAAI;IACvC,OAAO;KACH,YAAY,QAAQ,MAAO;KAC3B,gBAAgB,QAAQ,IAAK,MAAM;KACnC;IACJ;IAGJ,IAAI,gBAAgB,kBAAkB,GAAG;IACzC,MAAM,iBAAiB,WAAW,KAAK,MAAM,aAAa,SAAS,CAAC,CAAC,QAAQ,IAAI;IACjF,MAAM,SAAS,mBAAmB,KAAK,YAAY,cAAc,iBAAiB;IAElF,QAAQ,OAAO;KACX,MAAM,UAAU,MAAM,sBAClB,CACI,QACA,MACJ,GACA,mBAAmB,KAAK,SAAS,IACrC;KACA,WAAW;KACX,MAAM;IACV,CAAC;GACL;EACJ;EAEA,OAAO;GACH,iBAAiB,SAAS,gBAAgB,KAAK,IAAI;GACnD,UAAU,SAAS,gBAAgB,KAAK,IAAI;GAC5C,cAAc,SAAS,gBAAgB,KAAK,IAAI;GAChD,aAAa,SAAS,gBAAgB,KAAK,UAAU;GACrD,gBAAgB,SAAgD,gBAAgB,KAAK,IAAI;EAC7F;CACJ;CACA,MAAM;EACF,MAAM,EAAE,aAAa,uFAAuF;EAC5G,SAAS;EACT,UAAU,EAAE,WAAW,sDAAsD;EAC7E,QAAQ,CAAC;EACT,MAAM;CACV;AACJ"}
1
+ {"version":3,"file":"statement-padding.js","names":[],"sources":["../../../src/_internals/rules/statement-padding.ts"],"sourcesContent":["import type { Rule } from 'eslint';\n\ntype StatementNode = Extract<Rule.Node, { type: 'Program' }>['body'][number];\n\nconst blockTypes = new Set([\n 'BlockStatement',\n 'ClassDeclaration',\n 'ForInStatement',\n 'ForOfStatement',\n 'ForStatement',\n 'FunctionDeclaration',\n 'IfStatement',\n 'LabeledStatement',\n 'SwitchStatement',\n 'TryStatement',\n 'WhileStatement',\n 'WithStatement',\n]);\n\nfunction isImportOrReexport(node: StatementNode): boolean {\n return node.type === 'ImportDeclaration'\n || node.type === 'ExportAllDeclaration'\n || (node.type === 'ExportNamedDeclaration' && !!node.source);\n}\n\nexport const statementPadding: Rule.RuleModule = {\n create(context) {\n const { sourceCode } = context;\n\n function checkStatements(statements: readonly StatementNode[]): void {\n for (let index = 1; index < statements.length; index++) {\n const previous = statements[index - 1]!;\n const next = statements[index]!;\n if (isImportOrReexport(previous) || isImportOrReexport(next)) continue;\n const previousFirstToken = sourceCode.getFirstToken(previous)!;\n const lastToken = sourceCode.getLastToken(previous)!;\n const firstToken = sourceCode.getFirstToken(next)!;\n const isMultiline = previousFirstToken.loc.start.line !== lastToken.loc.end.line;\n const blockNode = previous.type === 'ExportDefaultDeclaration'\n || previous.type === 'ExportNamedDeclaration'\n ? previous.declaration\n : previous;\n\n const hasBlockClosing = lastToken.value === '}' && blockNode && blockTypes.has(blockNode.type);\n\n if (!isMultiline && !hasBlockClosing) continue;\n let previousEnd = lastToken.range[1];\n let previousEndLine = lastToken.loc.end.line;\n let nextStart = firstToken.range[0];\n let nextStartLine = firstToken.loc.start.line;\n\n // Include trailing comments in the previous boundary, not leading comments of the next statement.\n for (const comment of sourceCode.getCommentsBefore(next)) {\n if (comment.loc!.start.line === previousEndLine) {\n previousEnd = comment.range![1];\n previousEndLine = comment.loc!.end.line;\n } else {\n nextStart = comment.range![0];\n nextStartLine = comment.loc!.start.line;\n break;\n }\n }\n\n if (nextStartLine > previousEndLine + 1) continue;\n const linebreakIndex = sourceCode.text.slice(previousEnd, nextStart).indexOf('\\n');\n const offset = linebreakIndex === -1 ? nextStart : previousEnd + linebreakIndex + 1;\n\n context.report({\n fix: (fixer) => fixer.insertTextBeforeRange(\n [\n offset,\n offset,\n ],\n linebreakIndex === -1 ? '\\n\\n' : '\\n',\n ),\n messageId: 'blankLine',\n node: next,\n });\n }\n }\n\n return {\n BlockStatement: (node) => checkStatements(node.body),\n Program: (node) => checkStatements(node.body),\n StaticBlock: (node) => checkStatements(node.body),\n SwitchCase: (node) => checkStatements(node.consequent),\n TSModuleBlock: (node: Rule.Node & { body: StatementNode[] }) => checkStatements(node.body),\n };\n },\n meta: {\n docs: { description: 'Separate complete multiline statements and block-ending statements with blank lines.' },\n fixable: 'whitespace',\n messages: { blankLine: 'Add a blank line between these complete statements.' },\n schema: [],\n type: 'layout',\n },\n};\n"],"mappings":";AAIA,MAAM,6BAAa,IAAI,IAAI;CACvB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACJ,CAAC;AAED,SAAS,mBAAmB,MAA8B;CACtD,OAAO,KAAK,SAAS,uBAChB,KAAK,SAAS,0BACb,KAAK,SAAS,4BAA4B,CAAC,CAAC,KAAK;AAC3D;AAEA,MAAa,mBAAoC;CAC7C,OAAO,SAAS;EACZ,MAAM,EAAE,eAAe;EAEvB,SAAS,gBAAgB,YAA4C;GACjE,KAAK,IAAI,QAAQ,GAAG,QAAQ,WAAW,QAAQ,SAAS;IACpD,MAAM,WAAW,WAAW,QAAQ;IACpC,MAAM,OAAO,WAAW;IACxB,IAAI,mBAAmB,QAAQ,KAAK,mBAAmB,IAAI,GAAG;IAC9D,MAAM,qBAAqB,WAAW,cAAc,QAAQ;IAC5D,MAAM,YAAY,WAAW,aAAa,QAAQ;IAClD,MAAM,aAAa,WAAW,cAAc,IAAI;IAChD,MAAM,cAAc,mBAAmB,IAAI,MAAM,SAAS,UAAU,IAAI,IAAI;IAC5E,MAAM,YAAY,SAAS,SAAS,8BAC/B,SAAS,SAAS,2BACjB,SAAS,cACT;IAEN,MAAM,kBAAkB,UAAU,UAAU,OAAO,aAAa,WAAW,IAAI,UAAU,IAAI;IAE7F,IAAI,CAAC,eAAe,CAAC,iBAAiB;IACtC,IAAI,cAAc,UAAU,MAAM;IAClC,IAAI,kBAAkB,UAAU,IAAI,IAAI;IACxC,IAAI,YAAY,WAAW,MAAM;IACjC,IAAI,gBAAgB,WAAW,IAAI,MAAM;IAGzC,KAAK,MAAM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