@prairielearn/eslint-plugin 4.1.0 → 4.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/dist/index.d.ts +15 -10
  3. package/dist/index.d.ts.map +1 -1
  4. package/dist/index.js +20 -21
  5. package/dist/index.js.map +1 -1
  6. package/dist/rules/aws-client-mandatory-config.d.ts.map +1 -1
  7. package/dist/rules/aws-client-mandatory-config.js +4 -6
  8. package/dist/rules/aws-client-mandatory-config.js.map +1 -1
  9. package/dist/rules/aws-client-shared-config.d.ts.map +1 -1
  10. package/dist/rules/aws-client-shared-config.js +4 -6
  11. package/dist/rules/aws-client-shared-config.js.map +1 -1
  12. package/dist/rules/html-no-duplicate-id.d.ts +10 -0
  13. package/dist/rules/html-no-duplicate-id.d.ts.map +1 -0
  14. package/dist/rules/html-no-duplicate-id.js +54 -0
  15. package/dist/rules/html-no-duplicate-id.js.map +1 -0
  16. package/dist/rules/jsx-no-dollar-interpolation.d.ts.map +1 -1
  17. package/dist/rules/jsx-no-dollar-interpolation.js +2 -4
  18. package/dist/rules/jsx-no-dollar-interpolation.js.map +1 -1
  19. package/dist/rules/no-current-target-in-callback.d.ts.map +1 -1
  20. package/dist/rules/no-current-target-in-callback.js +2 -4
  21. package/dist/rules/no-current-target-in-callback.js.map +1 -1
  22. package/dist/rules/no-hydrate-reslocals.d.ts.map +1 -1
  23. package/dist/rules/no-hydrate-reslocals.js +2 -4
  24. package/dist/rules/no-hydrate-reslocals.js.map +1 -1
  25. package/dist/rules/no-unused-sql-blocks.d.ts.map +1 -1
  26. package/dist/rules/no-unused-sql-blocks.js +4 -39
  27. package/dist/rules/no-unused-sql-blocks.js.map +1 -1
  28. package/dist/rules/require-trpc-permission-middleware.d.ts +4 -0
  29. package/dist/rules/require-trpc-permission-middleware.d.ts.map +1 -0
  30. package/dist/rules/require-trpc-permission-middleware.js +133 -0
  31. package/dist/rules/require-trpc-permission-middleware.js.map +1 -0
  32. package/dist/rules/safe-db-types.d.ts +1 -1
  33. package/dist/rules/safe-db-types.d.ts.map +1 -1
  34. package/dist/rules/safe-db-types.js +6 -40
  35. package/dist/rules/safe-db-types.js.map +1 -1
  36. package/dist/tests/aws-client-mandatory-config.test.d.ts.map +1 -1
  37. package/dist/tests/aws-client-mandatory-config.test.js +8 -13
  38. package/dist/tests/aws-client-mandatory-config.test.js.map +1 -1
  39. package/dist/tests/aws-client-shared-config.test.d.ts.map +1 -1
  40. package/dist/tests/aws-client-shared-config.test.js +8 -13
  41. package/dist/tests/aws-client-shared-config.test.js.map +1 -1
  42. package/dist/tests/html-no-duplicate-id.test.d.ts +2 -0
  43. package/dist/tests/html-no-duplicate-id.test.d.ts.map +1 -0
  44. package/dist/tests/html-no-duplicate-id.test.js +54 -0
  45. package/dist/tests/html-no-duplicate-id.test.js.map +1 -0
  46. package/dist/tests/jsx-no-dollar-interpolation.test.d.ts.map +1 -1
  47. package/dist/tests/jsx-no-dollar-interpolation.test.js +8 -13
  48. package/dist/tests/jsx-no-dollar-interpolation.test.js.map +1 -1
  49. package/dist/tests/no-current-target-in-callback.test.js +8 -13
  50. package/dist/tests/no-current-target-in-callback.test.js.map +1 -1
  51. package/dist/tests/no-hydrate-reslocals.test.d.ts.map +1 -1
  52. package/dist/tests/no-hydrate-reslocals.test.js +8 -13
  53. package/dist/tests/no-hydrate-reslocals.test.js.map +1 -1
  54. package/dist/tests/require-trpc-permission-middleware.test.d.ts +2 -0
  55. package/dist/tests/require-trpc-permission-middleware.test.d.ts.map +1 -0
  56. package/dist/tests/require-trpc-permission-middleware.test.js +106 -0
  57. package/dist/tests/require-trpc-permission-middleware.test.js.map +1 -0
  58. package/dist/utils.js +1 -4
  59. package/dist/utils.js.map +1 -1
  60. package/package.json +11 -10
  61. package/src/index.ts +7 -1
  62. package/src/rules/html-no-duplicate-id.ts +76 -0
  63. package/src/rules/require-trpc-permission-middleware.ts +168 -0
  64. package/src/tests/aws-client-mandatory-config.test.ts +1 -1
  65. package/src/tests/aws-client-shared-config.test.ts +1 -1
  66. package/src/tests/html-no-duplicate-id.test.ts +57 -0
  67. package/src/tests/jsx-no-dollar-interpolation.test.ts +1 -1
  68. package/src/tests/no-hydrate-reslocals.test.ts +1 -1
  69. package/src/tests/require-trpc-permission-middleware.test.ts +109 -0
  70. package/tsconfig.json +1 -7
@@ -1 +1 @@
1
- {"version":3,"file":"no-current-target-in-callback.js","sourceRoot":"","sources":["../../src/rules/no-current-target-in-callback.ts"],"names":[],"mappings":";;AAAA,oDAAsE;AAEtE;;;;;;;;;;;;;;;GAeG;kBACY,mBAAW,CAAC,WAAW,CAAC,WAAW,CAAC;IACjD,IAAI,EAAE;QACJ,IAAI,EAAE,SAAS;QACf,QAAQ,EAAE;YACR,yBAAyB,EACvB,oMAAoM;SACvM;QACD,MAAM,EAAE,EAAE;KACX;IACD,cAAc,EAAE,EAAE;IAElB,MAAM,CAAC,OAAO;QACZ,MAAM,qBAAqB,GAAG,IAAI,GAAG,EAAsC,CAAC;QAC5E,MAAM,WAAW,GAAG,OAAO,CAAC,UAAU,CAAC,WAAW,CAAC;QAEnD,SAAS,cAAc,CACrB,IAAmB;YAKnB,OAAO,CACL,IAAI,CAAC,IAAI,KAAK,yBAAyB;gBACvC,IAAI,CAAC,IAAI,KAAK,oBAAoB;gBAClC,IAAI,CAAC,IAAI,KAAK,qBAAqB,CACpC,CAAC;QACJ,CAAC;QAED,SAAS,MAAM,CAAC,KAAc;YAC5B,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,MAAM,IAAI,KAAK,CAAC;QACxE,CAAC;QAED,SAAS,aAAa,CAAC,IAAmB;YACxC,MAAM,QAAQ,GAAoB,EAAE,CAAC;YAErC,KAAK,MAAM,GAAG,IAAI,WAAW,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,EAAE,EAAE,CAAC;gBAC/C,MAAM,KAAK,GAAY,IAAI,C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GAAG,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC;gBAEpC,+BAA+B;gBAC/B,MAAM,kBAAkB,GAAG,sBAAsB,CAAC,IAAI,CAAC,CAAC;gBACxD,IAAI,CAAC,kBAAkB;oBAAE,OAAO;gBAEhC,wEAAwE;gBACxE,KAAK,MAAM,CAAC,YAAY,EAAE,UAAU,CAAC,IAAI,qBAAqB,EAAE,CAAC;oBAC/D,iDAAiD;oBACjD,IAAI,UAAU,KAAK,UAAU,CAAC,IAAI;wBAAE,SAAS;oBAE7C,IACE,wBAAwB,CAAC,IAAI,EAAE,YAAY,CAAC;wBAC5C,2BAA2B,CAAC,IAAI,EAAE,YAAY,CAAC,EAC/C,CAAC;wBACD,OAAO,CAAC,MAAM,CAAC;4BACb,IAAI;4BACJ,SAAS,EAAE,2BAA2B;yBACvC,CAAC,CAAC;wBACH,OAAO;oBACT,CAAC;gBACH,CAAC;YACH,CAAC;YAED,uCAAuC;YACvC,sEAAsE,EAAE,CACtE,IAAsC,EACtC,EAAE;gBACF,qBAAqB,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;YACrC,CAAC;YACD,iEAAiE,EAAE,CACjE,IAAiC,EACjC,EAAE;gBACF,qBAAqB,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;YACrC,CAAC;YACD,8BAA8B,CAAC,IAAsC;gBACnE,qBAAqB,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;YACrC,CAAC;YACD,yBAAyB,CAAC,IAAiC;gBACzD,qBAAqB,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;YACrC,CAAC;YACD,0BAA0B,CAAC,IAAkC;gBAC3D,qBAAqB,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;YACrC,CAAC;SACF,CAAC;IACJ,CAAC;CACF,CAAC","sourcesContent":["import { ESLintUtils, type TSESTree } from '@typescript-eslint/utils';\n\n/**\n * This rule detects when `event.currentTarget` is accessed after an `await` or\n * inside a callback passed to a likely deferred API within a React event\n * handler. Those callbacks may run after the handler returns, at which point\n * `currentTarget` may already be nullified.\n *\n * Bad:\n * ```tsx\n * onChange={(e) => setChecks((c) => ({ ...c, value: e.currentTarget.checked }))}\n * ```\n *\n * Good:\n * ```tsx\n * onChange={({ currentTarget }) => setChecks((c) => ({ ...c, value: currentTarget.checked }))}\n * ```\n */\nexport default ESLintUtils.RuleCreator.withoutDocs({\n meta: {\n type: 'problem',\n messages: {\n noCurrentTargetInCallback:\n 'Accessing event.currentTarget after an async boundary may fail because currentTarget can be nullified before the access runs. Destructure currentTarget at the start of the event handler instead.',\n },\n schema: [],\n },\n defaultOptions: [],\n\n create(context) {\n const trackedEventFunctions = new Map<TSESTree.Node, TSESTree.Identifier>();\n const visitorKeys = context.sourceCode.visitorKeys;\n\n function isFunctionLike(\n node: TSESTree.Node,\n ): node is\n | TSESTree.ArrowFunctionExpression\n | TSESTree.FunctionExpression\n | TSESTree.FunctionDeclaration {\n return (\n node.type === 'ArrowFunctionExpression' ||\n node.type === 'FunctionExpression' ||\n node.type === 'FunctionDeclaration'\n );\n }\n\n function isNode(value: unknown): value is TSESTree.Node {\n return typeof value === 'object' && value !== null && 'type' in value;\n }\n\n function getChildNodes(node: TSESTree.Node): TSESTree.Node[] {\n const children: TSESTree.Node[] = [];\n\n for (const key of visitorKeys[node.type] ?? []) {\n const value: unknown = node[key as keyof TSESTree.Node];\n\n if (Array.isArray(value)) {\n for (const child of value) {\n if (isNode(child)) {\n children.push(child);\n }\n }\n } else if (isNode(value)) {\n children.push(value);\n }\n }\n\n return children;\n }\n\n function isKnownDeferredCallee(callee: TSESTree.Expression | TSESTree.Super): boolean {\n if (callee.type === 'Super') {\n return false;\n }\n\n if (callee.type === 'Identifier') {\n return (\n // e.g. setTimeout, setInterval, setImmediate, etc.\n /^set[A-Z0-9_]/.test(callee.name) ||\n callee.name === 'queueMicrotask' ||\n callee.name === 'requestAnimationFrame' ||\n callee.name === 'requestIdleCallback'\n );\n }\n\n if (callee.type === 'MemberExpression' && callee.property.type === 'Identifier') {\n return (\n callee.property.name === 'then' ||\n callee.property.name === 'catch' ||\n callee.property.name === 'finally'\n );\n }\n\n return false;\n }\n\n function isKnownEventBoundaryCallback(\n callExpression: TSESTree.CallExpression,\n callbackIndex: number,\n ): boolean {\n if (callbackIndex !== 0) {\n return false;\n }\n\n if (\n callExpression.callee.type === 'Identifier' &&\n callExpression.callee.name === 'handleSubmit'\n ) {\n // react-hook-form invokes this callback after its own submit handling,\n // so treat it as an event boundary like other deferred callbacks.\n return true;\n }\n\n return false;\n }\n\n /**\n * Check if a node is inside a nested function that is passed to a callback\n * API that may invoke it after the event handler returns.\n */\n function isInsideDeferredCallback(\n node: TSESTree.Node,\n eventHandlerFunction: TSESTree.Node,\n ): boolean {\n // Check if the event handler itself is in a deferred/boundary context\n const handlerParent = eventHandlerFunction.parent;\n if (handlerParent?.type === 'CallExpression') {\n const callbackIndex = handlerParent.arguments.indexOf(\n eventHandlerFunction as TSESTree.CallExpressionArgument,\n );\n if (\n callbackIndex !== -1 &&\n (isKnownDeferredCallee(handlerParent.callee) ||\n isKnownEventBoundaryCallback(handlerParent, callbackIndex))\n ) {\n return true;\n }\n }\n\n let current: TSESTree.Node | undefined = node;\n\n while (current && current !== eventHandlerFunction) {\n if (isFunctionLike(current)) {\n const parent = current.parent;\n if (current.type !== 'FunctionDeclaration' && parent?.type === 'CallExpression') {\n const callbackIndex = parent.arguments.indexOf(current);\n if (\n callbackIndex !== -1 &&\n (isKnownDeferredCallee(parent.callee) ||\n isKnownEventBoundaryCallback(parent, callbackIndex))\n ) {\n return true;\n }\n }\n }\n current = current.parent;\n }\n\n return false;\n }\n\n /** Check if the function contains an await before this access, ignoring nested functions */\n function hasPriorAwaitInSameFunction(\n node: TSESTree.Node,\n eventHandlerFunction: TSESTree.Node,\n ): boolean {\n if (\n !('body' in eventHandlerFunction) ||\n !eventHandlerFunction.body ||\n Array.isArray(eventHandlerFunction.body)\n ) {\n return false;\n }\n\n let foundPriorAwait = false;\n\n const visit = (current: TSESTree.Node) => {\n if (foundPriorAwait || current.range[0] >= node.range[0]) {\n return;\n }\n\n if (current !== eventHandlerFunction && isFunctionLike(current)) {\n return;\n }\n\n if (current.type === 'AwaitExpression') {\n foundPriorAwait = true;\n return;\n }\n\n for (const child of getChildNodes(current)) {\n visit(child);\n if (foundPriorAwait) {\n return;\n }\n }\n };\n\n visit(eventHandlerFunction.body);\n return foundPriorAwait;\n }\n\n /** Find the function that contains this node */\n function findContainingFunction(\n node: TSESTree.Node,\n ):\n | TSESTree.ArrowFunctionExpression\n | TSESTree.FunctionExpression\n | TSESTree.FunctionDeclaration\n | null {\n let current: TSESTree.Node | undefined = node.parent;\n\n while (current) {\n if (isFunctionLike(current)) {\n return current;\n }\n current = current.parent;\n }\n\n return null;\n }\n\n /** Check if a function is a JSX event handler */\n function isJSXEventHandler(\n func:\n | TSESTree.ArrowFunctionExpression\n | TSESTree.FunctionExpression\n | TSESTree.FunctionDeclaration,\n ): boolean {\n const parent = func.parent;\n\n // Check for JSX attribute like onChange={...}\n if (parent?.type === 'JSXExpressionContainer') {\n const jsxAttribute = parent.parent;\n if (jsxAttribute?.type === 'JSXAttribute') {\n const attrName = jsxAttribute.name.type === 'JSXIdentifier' ? jsxAttribute.name.name : '';\n // Match common event handler patterns\n return /^on[A-Z]/.test(attrName);\n }\n }\n\n return false;\n }\n\n /** Get the first parameter of an event handler if it looks like an event */\n function getEventParameter(\n func:\n | TSESTree.ArrowFunctionExpression\n | TSESTree.FunctionExpression\n | TSESTree.FunctionDeclaration,\n ): TSESTree.Identifier | null {\n const firstParam = func.params[0];\n\n if (!firstParam) return null;\n\n // Simple identifier parameter like (e) => ...\n if (firstParam.type === 'Identifier') {\n return firstParam;\n }\n\n return null;\n }\n\n function isReactEventType(typeAnnotation: TSESTree.TypeNode): boolean {\n if (typeAnnotation.type === 'TSTypeReference') {\n if (\n typeAnnotation.typeName.type === 'TSQualifiedName' &&\n typeAnnotation.typeName.left.type === 'Identifier' &&\n typeAnnotation.typeName.left.name === 'React' &&\n typeAnnotation.typeName.right.type === 'Identifier' &&\n typeAnnotation.typeName.right.name.endsWith('Event')\n ) {\n return true;\n }\n\n if (\n typeAnnotation.typeName.type === 'Identifier' &&\n (typeAnnotation.typeName.name === 'SyntheticEvent' ||\n typeAnnotation.typeName.name.endsWith('Event'))\n ) {\n return true;\n }\n }\n\n return false;\n }\n\n function isTypedReactEventHandler(\n func:\n | TSESTree.ArrowFunctionExpression\n | TSESTree.FunctionExpression\n | TSESTree.FunctionDeclaration,\n ): boolean {\n const firstParam = func.params[0];\n if (!firstParam || firstParam.type !== 'Identifier' || !firstParam.typeAnnotation) {\n return false;\n }\n\n return isReactEventType(firstParam.typeAnnotation.typeAnnotation);\n }\n\n function trackIfEventHandler(\n node:\n | TSESTree.ArrowFunctionExpression\n | TSESTree.FunctionExpression\n | TSESTree.FunctionDeclaration,\n ) {\n if (isJSXEventHandler(node) || isTypedReactEventHandler(node)) {\n const eventParam = getEventParameter(node);\n if (eventParam) {\n trackedEventFunctions.set(node, eventParam);\n }\n return;\n }\n\n // react-hook-form: handleSubmit((_data, e) => { ... })\n // The event is the second parameter, and the entire callback is deferred.\n const parent = node.parent;\n if (\n parent?.type === 'CallExpression' &&\n parent.arguments[0] === node &&\n isKnownEventBoundaryCallback(parent, 0)\n ) {\n const secondParam = node.params[1];\n if (secondParam?.type === 'Identifier') {\n trackedEventFunctions.set(node, secondParam);\n }\n }\n }\n\n return {\n // When we enter a JSX event handler, track its event parameter\n 'JSXAttribute > JSXExpressionContainer > ArrowFunctionExpression': (\n node: TSESTree.ArrowFunctionExpression,\n ) => {\n trackIfEventHandler(node);\n },\n 'JSXAttribute > JSXExpressionContainer > FunctionExpression': (\n node: TSESTree.FunctionExpression,\n ) => {\n trackIfEventHandler(node);\n },\n ArrowFunctionExpression(node: TSESTree.ArrowFunctionExpression) {\n trackIfEventHandler(node);\n },\n FunctionExpression(node: TSESTree.FunctionExpression) {\n trackIfEventHandler(node);\n },\n FunctionDeclaration(node: TSESTree.FunctionDeclaration) {\n trackIfEventHandler(node);\n },\n\n // Check for .currentTarget access\n MemberExpression(node) {\n // Only check for .currentTarget property access\n if (node.property.type !== 'Identifier' || node.property.name !== 'currentTarget') {\n return;\n }\n\n // Check if the object is an identifier (like `e` in `e.currentTarget`)\n if (node.object.type !== 'Identifier') {\n return;\n }\n\n const objectName = node.object.name;\n\n // Find the containing function\n const containingFunction = findContainingFunction(node);\n if (!containingFunction) return;\n\n // Check each tracked event handler to see if this access is problematic\n for (const [eventHandler, eventParam] of trackedEventFunctions) {\n // Check if this is accessing the event parameter\n if (objectName !== eventParam.name) continue;\n\n if (\n isInsideDeferredCallback(node, eventHandler) ||\n hasPriorAwaitInSameFunction(node, eventHandler)\n ) {\n context.report({\n node,\n messageId: 'noCurrentTargetInCallback',\n });\n return;\n }\n }\n },\n\n // Clean up when leaving event handlers\n 'JSXAttribute > JSXExpressionContainer > ArrowFunctionExpression:exit': (\n node: TSESTree.ArrowFunctionExpression,\n ) => {\n trackedEventFunctions.delete(node);\n },\n 'JSXAttribute > JSXExpressionContainer > FunctionExpression:exit': (\n node: TSESTree.FunctionExpression,\n ) => {\n trackedEventFunctions.delete(node);\n },\n 'ArrowFunctionExpression:exit'(node: TSESTree.ArrowFunctionExpression) {\n trackedEventFunctions.delete(node);\n },\n 'FunctionExpression:exit'(node: TSESTree.FunctionExpression) {\n trackedEventFunctions.delete(node);\n },\n 'FunctionDeclaration:exit'(node: TSESTree.FunctionDeclaration) {\n trackedEventFunctions.delete(node);\n },\n };\n },\n});\n"]}
1
+ {"version":3,"file":"no-current-target-in-callback.js","sourceRoot":"","sources":["../../src/rules/no-current-target-in-callback.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAiB,MAAM,0BAA0B,CAAC;AAEtE;;;;;;;;;;;;;;;GAeG;AACH,eAAe,WAAW,CAAC,WAAW,CAAC,WAAW,CAAC;IACjD,IAAI,EAAE;QACJ,IAAI,EAAE,SAAS;QACf,QAAQ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AS,EAAE,2BAA2B;yBACvC,CAAC,CAAC;wBACH,OAAO;oBACT,CAAC;gBACH,CAAC;YACH,CAAC;YAED,uCAAuC;YACvC,sEAAsE,EAAE,CACtE,IAAsC,EACtC,EAAE;gBACF,qBAAqB,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;YACrC,CAAC;YACD,iEAAiE,EAAE,CACjE,IAAiC,EACjC,EAAE;gBACF,qBAAqB,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;YACrC,CAAC;YACD,8BAA8B,CAAC,IAAsC;gBACnE,qBAAqB,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;YACrC,CAAC;YACD,yBAAyB,CAAC,IAAiC;gBACzD,qBAAqB,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;YACrC,CAAC;YACD,0BAA0B,CAAC,IAAkC;gBAC3D,qBAAqB,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;YACrC,CAAC;SACF,CAAC;IACJ,CAAC;CACF,CAAC,CAAC","sourcesContent":["import { ESLintUtils, type TSESTree } from '@typescript-eslint/utils';\n\n/**\n * This rule detects when `event.currentTarget` is accessed after an `await` or\n * inside a callback passed to a likely deferred API within a React event\n * handler. Those callbacks may run after the handler returns, at which point\n * `currentTarget` may already be nullified.\n *\n * Bad:\n * ```tsx\n * onChange={(e) => setChecks((c) => ({ ...c, value: e.currentTarget.checked }))}\n * ```\n *\n * Good:\n * ```tsx\n * onChange={({ currentTarget }) => setChecks((c) => ({ ...c, value: currentTarget.checked }))}\n * ```\n */\nexport default ESLintUtils.RuleCreator.withoutDocs({\n meta: {\n type: 'problem',\n messages: {\n noCurrentTargetInCallback:\n 'Accessing event.currentTarget after an async boundary may fail because currentTarget can be nullified before the access runs. Destructure currentTarget at the start of the event handler instead.',\n },\n schema: [],\n },\n defaultOptions: [],\n\n create(context) {\n const trackedEventFunctions = new Map<TSESTree.Node, TSESTree.Identifier>();\n const visitorKeys = context.sourceCode.visitorKeys;\n\n function isFunctionLike(\n node: TSESTree.Node,\n ): node is\n | TSESTree.ArrowFunctionExpression\n | TSESTree.FunctionExpression\n | TSESTree.FunctionDeclaration {\n return (\n node.type === 'ArrowFunctionExpression' ||\n node.type === 'FunctionExpression' ||\n node.type === 'FunctionDeclaration'\n );\n }\n\n function isNode(value: unknown): value is TSESTree.Node {\n return typeof value === 'object' && value !== null && 'type' in value;\n }\n\n function getChildNodes(node: TSESTree.Node): TSESTree.Node[] {\n const children: TSESTree.Node[] = [];\n\n for (const key of visitorKeys[node.type] ?? []) {\n const value: unknown = node[key as keyof TSESTree.Node];\n\n if (Array.isArray(value)) {\n for (const child of value) {\n if (isNode(child)) {\n children.push(child);\n }\n }\n } else if (isNode(value)) {\n children.push(value);\n }\n }\n\n return children;\n }\n\n function isKnownDeferredCallee(callee: TSESTree.Expression | TSESTree.Super): boolean {\n if (callee.type === 'Super') {\n return false;\n }\n\n if (callee.type === 'Identifier') {\n return (\n // e.g. setTimeout, setInterval, setImmediate, etc.\n /^set[A-Z0-9_]/.test(callee.name) ||\n callee.name === 'queueMicrotask' ||\n callee.name === 'requestAnimationFrame' ||\n callee.name === 'requestIdleCallback'\n );\n }\n\n if (callee.type === 'MemberExpression' && callee.property.type === 'Identifier') {\n return (\n callee.property.name === 'then' ||\n callee.property.name === 'catch' ||\n callee.property.name === 'finally'\n );\n }\n\n return false;\n }\n\n function isKnownEventBoundaryCallback(\n callExpression: TSESTree.CallExpression,\n callbackIndex: number,\n ): boolean {\n if (callbackIndex !== 0) {\n return false;\n }\n\n if (\n callExpression.callee.type === 'Identifier' &&\n callExpression.callee.name === 'handleSubmit'\n ) {\n // react-hook-form invokes this callback after its own submit handling,\n // so treat it as an event boundary like other deferred callbacks.\n return true;\n }\n\n return false;\n }\n\n /**\n * Check if a node is inside a nested function that is passed to a callback\n * API that may invoke it after the event handler returns.\n */\n function isInsideDeferredCallback(\n node: TSESTree.Node,\n eventHandlerFunction: TSESTree.Node,\n ): boolean {\n // Check if the event handler itself is in a deferred/boundary context\n const handlerParent = eventHandlerFunction.parent;\n if (handlerParent?.type === 'CallExpression') {\n const callbackIndex = handlerParent.arguments.indexOf(\n eventHandlerFunction as TSESTree.CallExpressionArgument,\n );\n if (\n callbackIndex !== -1 &&\n (isKnownDeferredCallee(handlerParent.callee) ||\n isKnownEventBoundaryCallback(handlerParent, callbackIndex))\n ) {\n return true;\n }\n }\n\n let current: TSESTree.Node | undefined = node;\n\n while (current && current !== eventHandlerFunction) {\n if (isFunctionLike(current)) {\n const parent = current.parent;\n if (current.type !== 'FunctionDeclaration' && parent?.type === 'CallExpression') {\n const callbackIndex = parent.arguments.indexOf(current);\n if (\n callbackIndex !== -1 &&\n (isKnownDeferredCallee(parent.callee) ||\n isKnownEventBoundaryCallback(parent, callbackIndex))\n ) {\n return true;\n }\n }\n }\n current = current.parent;\n }\n\n return false;\n }\n\n /** Check if the function contains an await before this access, ignoring nested functions */\n function hasPriorAwaitInSameFunction(\n node: TSESTree.Node,\n eventHandlerFunction: TSESTree.Node,\n ): boolean {\n if (\n !('body' in eventHandlerFunction) ||\n !eventHandlerFunction.body ||\n Array.isArray(eventHandlerFunction.body)\n ) {\n return false;\n }\n\n let foundPriorAwait = false;\n\n const visit = (current: TSESTree.Node) => {\n if (foundPriorAwait || current.range[0] >= node.range[0]) {\n return;\n }\n\n if (current !== eventHandlerFunction && isFunctionLike(current)) {\n return;\n }\n\n if (current.type === 'AwaitExpression') {\n foundPriorAwait = true;\n return;\n }\n\n for (const child of getChildNodes(current)) {\n visit(child);\n if (foundPriorAwait) {\n return;\n }\n }\n };\n\n visit(eventHandlerFunction.body);\n return foundPriorAwait;\n }\n\n /** Find the function that contains this node */\n function findContainingFunction(\n node: TSESTree.Node,\n ):\n | TSESTree.ArrowFunctionExpression\n | TSESTree.FunctionExpression\n | TSESTree.FunctionDeclaration\n | null {\n let current: TSESTree.Node | undefined = node.parent;\n\n while (current) {\n if (isFunctionLike(current)) {\n return current;\n }\n current = current.parent;\n }\n\n return null;\n }\n\n /** Check if a function is a JSX event handler */\n function isJSXEventHandler(\n func:\n | TSESTree.ArrowFunctionExpression\n | TSESTree.FunctionExpression\n | TSESTree.FunctionDeclaration,\n ): boolean {\n const parent = func.parent;\n\n // Check for JSX attribute like onChange={...}\n if (parent?.type === 'JSXExpressionContainer') {\n const jsxAttribute = parent.parent;\n if (jsxAttribute?.type === 'JSXAttribute') {\n const attrName = jsxAttribute.name.type === 'JSXIdentifier' ? jsxAttribute.name.name : '';\n // Match common event handler patterns\n return /^on[A-Z]/.test(attrName);\n }\n }\n\n return false;\n }\n\n /** Get the first parameter of an event handler if it looks like an event */\n function getEventParameter(\n func:\n | TSESTree.ArrowFunctionExpression\n | TSESTree.FunctionExpression\n | TSESTree.FunctionDeclaration,\n ): TSESTree.Identifier | null {\n const firstParam = func.params[0];\n\n if (!firstParam) return null;\n\n // Simple identifier parameter like (e) => ...\n if (firstParam.type === 'Identifier') {\n return firstParam;\n }\n\n return null;\n }\n\n function isReactEventType(typeAnnotation: TSESTree.TypeNode): boolean {\n if (typeAnnotation.type === 'TSTypeReference') {\n if (\n typeAnnotation.typeName.type === 'TSQualifiedName' &&\n typeAnnotation.typeName.left.type === 'Identifier' &&\n typeAnnotation.typeName.left.name === 'React' &&\n typeAnnotation.typeName.right.type === 'Identifier' &&\n typeAnnotation.typeName.right.name.endsWith('Event')\n ) {\n return true;\n }\n\n if (\n typeAnnotation.typeName.type === 'Identifier' &&\n (typeAnnotation.typeName.name === 'SyntheticEvent' ||\n typeAnnotation.typeName.name.endsWith('Event'))\n ) {\n return true;\n }\n }\n\n return false;\n }\n\n function isTypedReactEventHandler(\n func:\n | TSESTree.ArrowFunctionExpression\n | TSESTree.FunctionExpression\n | TSESTree.FunctionDeclaration,\n ): boolean {\n const firstParam = func.params[0];\n if (!firstParam || firstParam.type !== 'Identifier' || !firstParam.typeAnnotation) {\n return false;\n }\n\n return isReactEventType(firstParam.typeAnnotation.typeAnnotation);\n }\n\n function trackIfEventHandler(\n node:\n | TSESTree.ArrowFunctionExpression\n | TSESTree.FunctionExpression\n | TSESTree.FunctionDeclaration,\n ) {\n if (isJSXEventHandler(node) || isTypedReactEventHandler(node)) {\n const eventParam = getEventParameter(node);\n if (eventParam) {\n trackedEventFunctions.set(node, eventParam);\n }\n return;\n }\n\n // react-hook-form: handleSubmit((_data, e) => { ... })\n // The event is the second parameter, and the entire callback is deferred.\n const parent = node.parent;\n if (\n parent?.type === 'CallExpression' &&\n parent.arguments[0] === node &&\n isKnownEventBoundaryCallback(parent, 0)\n ) {\n const secondParam = node.params[1];\n if (secondParam?.type === 'Identifier') {\n trackedEventFunctions.set(node, secondParam);\n }\n }\n }\n\n return {\n // When we enter a JSX event handler, track its event parameter\n 'JSXAttribute > JSXExpressionContainer > ArrowFunctionExpression': (\n node: TSESTree.ArrowFunctionExpression,\n ) => {\n trackIfEventHandler(node);\n },\n 'JSXAttribute > JSXExpressionContainer > FunctionExpression': (\n node: TSESTree.FunctionExpression,\n ) => {\n trackIfEventHandler(node);\n },\n ArrowFunctionExpression(node: TSESTree.ArrowFunctionExpression) {\n trackIfEventHandler(node);\n },\n FunctionExpression(node: TSESTree.FunctionExpression) {\n trackIfEventHandler(node);\n },\n FunctionDeclaration(node: TSESTree.FunctionDeclaration) {\n trackIfEventHandler(node);\n },\n\n // Check for .currentTarget access\n MemberExpression(node) {\n // Only check for .currentTarget property access\n if (node.property.type !== 'Identifier' || node.property.name !== 'currentTarget') {\n return;\n }\n\n // Check if the object is an identifier (like `e` in `e.currentTarget`)\n if (node.object.type !== 'Identifier') {\n return;\n }\n\n const objectName = node.object.name;\n\n // Find the containing function\n const containingFunction = findContainingFunction(node);\n if (!containingFunction) return;\n\n // Check each tracked event handler to see if this access is problematic\n for (const [eventHandler, eventParam] of trackedEventFunctions) {\n // Check if this is accessing the event parameter\n if (objectName !== eventParam.name) continue;\n\n if (\n isInsideDeferredCallback(node, eventHandler) ||\n hasPriorAwaitInSameFunction(node, eventHandler)\n ) {\n context.report({\n node,\n messageId: 'noCurrentTargetInCallback',\n });\n return;\n }\n }\n },\n\n // Clean up when leaving event handlers\n 'JSXAttribute > JSXExpressionContainer > ArrowFunctionExpression:exit': (\n node: TSESTree.ArrowFunctionExpression,\n ) => {\n trackedEventFunctions.delete(node);\n },\n 'JSXAttribute > JSXExpressionContainer > FunctionExpression:exit': (\n node: TSESTree.FunctionExpression,\n ) => {\n trackedEventFunctions.delete(node);\n },\n 'ArrowFunctionExpression:exit'(node: TSESTree.ArrowFunctionExpression) {\n trackedEventFunctions.delete(node);\n },\n 'FunctionExpression:exit'(node: TSESTree.FunctionExpression) {\n trackedEventFunctions.delete(node);\n },\n 'FunctionDeclaration:exit'(node: TSESTree.FunctionDeclaration) {\n trackedEventFunctions.delete(node);\n },\n };\n },\n});\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"no-hydrate-reslocals.d.ts","sourceRoot":"","sources":["../../src/rules/no-hydrate-reslocals.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAiB,MAAM,0BAA0B,CAAC;;AA4CtE,wBAyDG","sourcesContent":["import { ESLintUtils, type TSESTree } from '@typescript-eslint/utils';\n\n/**\n * All props on a hydrated component are serialized with superjson and shipped\n * to the browser. Passing `resLocals` or `locals` (or spreading them) would\n * leak the entire server-side `res.locals` object — CSRF tokens, auth data,\n * authz objects, full DB rows, etc.\n *\n * This rule forbids those prop names (and `{...res.locals}` / `{...resLocals}`\n * / `{...locals}` spreads) on the child of `<Hydrate>` and on the JSX argument\n * to `hydrateHtml(...)`. Extract the specific fields you need (e.g. via\n * `extractPageContext`) and pass them as individual props instead.\n */\n\nconst HYDRATE_COMPONENT_NAME = 'Hydrate';\nconst HYDRATE_FUNCTION_NAME = 'hydrateHtml';\nconst FORBIDDEN_NAMES = new Set(['resLocals', 'locals']);\n\nfunction extractSingleJsxChild(children: TSESTree.JSXChild[]): TSESTree.JSXElement | null {\n const nonWhitespace = children.filter((child) => {\n if (child.type === 'JSXText') return child.value.trim().length > 0;\n return true;\n });\n if (nonWhitespace.length !== 1 || nonWhitespace[0].type !== 'JSXElement') {\n return null;\n }\n return nonWhitespace[0];\n}\n\nfunction spreadArgumentDescribesResLocals(argument: TSESTree.Expression): boolean {\n if (argument.type === 'Identifier') {\n return FORBIDDEN_NAMES.has(argument.name);\n }\n if (\n argument.type === 'MemberExpression' &&\n !argument.computed &&\n argument.property.type === 'Identifier' &&\n argument.property.name === 'locals'\n ) {\n return true;\n }\n return false;\n}\n\nexport default ESLintUtils.RuleCreator.withoutDocs({\n meta: {\n type: 'problem',\n messages: {\n forbiddenProp:\n 'Do not pass \"{{name}}\" to a hydrated component; props are serialized and sent to the client, so this would leak the full server-side res.locals. Pass the specific fields the component needs instead.',\n forbiddenSpread:\n 'Do not spread res.locals onto a hydrated component; props are serialized and sent to the client. Pass the specific fields the component needs instead.',\n },\n schema: [],\n },\n defaultOptions: [],\n\n create(context) {\n function checkHydratedElement(element: TSESTree.JSXElement) {\n for (const attribute of element.openingElement.attributes) {\n if (attribute.type === 'JSXAttribute') {\n if (attribute.name.type === 'JSXIdentifier' && FORBIDDEN_NAMES.has(attribute.name.name)) {\n context.report({\n node: attribute,\n messageId: 'forbiddenProp',\n data: { name: attribute.name.name },\n });\n }\n } else if (attribute.type === 'JSXSpreadAttribute') {\n if (spreadArgumentDescribesResLocals(attribute.argument)) {\n context.report({\n node: attribute,\n messageId: 'forbiddenSpread',\n });\n }\n }\n }\n }\n\n return {\n JSXElement(node) {\n const opening = node.openingElement.name;\n if (opening.type !== 'JSXIdentifier' || opening.name !== HYDRATE_COMPONENT_NAME) return;\n\n const child = extractSingleJsxChild(node.children);\n if (!child) return;\n\n checkHydratedElement(child);\n },\n\n CallExpression(node) {\n if (node.callee.type !== 'Identifier' || node.callee.name !== HYDRATE_FUNCTION_NAME) return;\n if (node.arguments.length === 0) return;\n\n const arg = node.arguments[0];\n if (arg.type !== 'JSXElement') return;\n\n checkHydratedElement(arg);\n },\n };\n },\n});\n"]}
1
+ {"version":3,"file":"no-hydrate-reslocals.d.ts","sourceRoot":"","sources":["../../src/rules/no-hydrate-reslocals.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAiB,MAAM,0BAA0B,CAAC","sourcesContent":["import { ESLintUtils, type TSESTree } from '@typescript-eslint/utils';\n\n/**\n * All props on a hydrated component are serialized with superjson and shipped\n * to the browser. Passing `resLocals` or `locals` (or spreading them) would\n * leak the entire server-side `res.locals` object — CSRF tokens, auth data,\n * authz objects, full DB rows, etc.\n *\n * This rule forbids those prop names (and `{...res.locals}` / `{...resLocals}`\n * / `{...locals}` spreads) on the child of `<Hydrate>` and on the JSX argument\n * to `hydrateHtml(...)`. Extract the specific fields you need (e.g. via\n * `extractPageContext`) and pass them as individual props instead.\n */\n\nconst HYDRATE_COMPONENT_NAME = 'Hydrate';\nconst HYDRATE_FUNCTION_NAME = 'hydrateHtml';\nconst FORBIDDEN_NAMES = new Set(['resLocals', 'locals']);\n\nfunction extractSingleJsxChild(children: TSESTree.JSXChild[]): TSESTree.JSXElement | null {\n const nonWhitespace = children.filter((child) => {\n if (child.type === 'JSXText') return child.value.trim().length > 0;\n return true;\n });\n if (nonWhitespace.length !== 1 || nonWhitespace[0].type !== 'JSXElement') {\n return null;\n }\n return nonWhitespace[0];\n}\n\nfunction spreadArgumentDescribesResLocals(argument: TSESTree.Expression): boolean {\n if (argument.type === 'Identifier') {\n return FORBIDDEN_NAMES.has(argument.name);\n }\n if (\n argument.type === 'MemberExpression' &&\n !argument.computed &&\n argument.property.type === 'Identifier' &&\n argument.property.name === 'locals'\n ) {\n return true;\n }\n return false;\n}\n\nexport default ESLintUtils.RuleCreator.withoutDocs({\n meta: {\n type: 'problem',\n messages: {\n forbiddenProp:\n 'Do not pass \"{{name}}\" to a hydrated component; props are serialized and sent to the client, so this would leak the full server-side res.locals. Pass the specific fields the component needs instead.',\n forbiddenSpread:\n 'Do not spread res.locals onto a hydrated component; props are serialized and sent to the client. Pass the specific fields the component needs instead.',\n },\n schema: [],\n },\n defaultOptions: [],\n\n create(context) {\n function checkHydratedElement(element: TSESTree.JSXElement) {\n for (const attribute of element.openingElement.attributes) {\n if (attribute.type === 'JSXAttribute') {\n if (attribute.name.type === 'JSXIdentifier' && FORBIDDEN_NAMES.has(attribute.name.name)) {\n context.report({\n node: attribute,\n messageId: 'forbiddenProp',\n data: { name: attribute.name.name },\n });\n }\n } else if (attribute.type === 'JSXSpreadAttribute') {\n if (spreadArgumentDescribesResLocals(attribute.argument)) {\n context.report({\n node: attribute,\n messageId: 'forbiddenSpread',\n });\n }\n }\n }\n }\n\n return {\n JSXElement(node) {\n const opening = node.openingElement.name;\n if (opening.type !== 'JSXIdentifier' || opening.name !== HYDRATE_COMPONENT_NAME) return;\n\n const child = extractSingleJsxChild(node.children);\n if (!child) return;\n\n checkHydratedElement(child);\n },\n\n CallExpression(node) {\n if (node.callee.type !== 'Identifier' || node.callee.name !== HYDRATE_FUNCTION_NAME) return;\n if (node.arguments.length === 0) return;\n\n const arg = node.arguments[0];\n if (arg.type !== 'JSXElement') return;\n\n checkHydratedElement(arg);\n },\n };\n },\n});\n"]}
@@ -1,6 +1,4 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- const utils_1 = require("@typescript-eslint/utils");
1
+ import { ESLintUtils } from '@typescript-eslint/utils';
4
2
  /**
5
3
  * All props on a hydrated component are serialized with superjson and shipped
6
4
  * to the browser. Passing `resLocals` or `locals` (or spreading them) would
@@ -38,7 +36,7 @@ function spreadArgumentDescribesResLocals(argument) {
38
36
  }
39
37
  return false;
40
38
  }
41
- exports.default = utils_1.ESLintUtils.RuleCreator.withoutDocs({
39
+ export default ESLintUtils.RuleCreator.withoutDocs({
42
40
  meta: {
43
41
  type: 'problem',
44
42
  messages: {
@@ -1 +1 @@
1
- {"version":3,"file":"no-hydrate-reslocals.js","sourceRoot":"","sources":["../../src/rules/no-hydrate-reslocals.ts"],"names":[],"mappings":";;AAAA,oDAAsE;AAEtE;;;;;;;;;;GAUG;AAE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AAM,CAAC,IAAI,KAAK,YAAY,IAAI,IAAI,CAAC,MAAM,CAAC,IAAI,KAAK,qBAAqB;oBAAE,OAAO;gBAC5F,IAAI,IAAI,CAAC,SAAS,CAAC,MAAM,KAAK,CAAC;oBAAE,OAAO;gBAExC,MAAM,GAAG,GAAG,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC;gBAC9B,IAAI,GAAG,CAAC,IAAI,KAAK,YAAY;oBAAE,OAAO;gBAEtC,oBAAoB,CAAC,GAAG,CAAC,CAAC;YAC5B,CAAC;SACF,CAAC;IACJ,CAAC;CACF,CAAC","sourcesContent":["import { ESLintUtils, type TSESTree } from '@typescript-eslint/utils';\n\n/**\n * All props on a hydrated component are serialized with superjson and shipped\n * to the browser. Passing `resLocals` or `locals` (or spreading them) would\n * leak the entire server-side `res.locals` object — CSRF tokens, auth data,\n * authz objects, full DB rows, etc.\n *\n * This rule forbids those prop names (and `{...res.locals}` / `{...resLocals}`\n * / `{...locals}` spreads) on the child of `<Hydrate>` and on the JSX argument\n * to `hydrateHtml(...)`. Extract the specific fields you need (e.g. via\n * `extractPageContext`) and pass them as individual props instead.\n */\n\nconst HYDRATE_COMPONENT_NAME = 'Hydrate';\nconst HYDRATE_FUNCTION_NAME = 'hydrateHtml';\nconst FORBIDDEN_NAMES = new Set(['resLocals', 'locals']);\n\nfunction extractSingleJsxChild(children: TSESTree.JSXChild[]): TSESTree.JSXElement | null {\n const nonWhitespace = children.filter((child) => {\n if (child.type === 'JSXText') return child.value.trim().length > 0;\n return true;\n });\n if (nonWhitespace.length !== 1 || nonWhitespace[0].type !== 'JSXElement') {\n return null;\n }\n return nonWhitespace[0];\n}\n\nfunction spreadArgumentDescribesResLocals(argument: TSESTree.Expression): boolean {\n if (argument.type === 'Identifier') {\n return FORBIDDEN_NAMES.has(argument.name);\n }\n if (\n argument.type === 'MemberExpression' &&\n !argument.computed &&\n argument.property.type === 'Identifier' &&\n argument.property.name === 'locals'\n ) {\n return true;\n }\n return false;\n}\n\nexport default ESLintUtils.RuleCreator.withoutDocs({\n meta: {\n type: 'problem',\n messages: {\n forbiddenProp:\n 'Do not pass \"{{name}}\" to a hydrated component; props are serialized and sent to the client, so this would leak the full server-side res.locals. Pass the specific fields the component needs instead.',\n forbiddenSpread:\n 'Do not spread res.locals onto a hydrated component; props are serialized and sent to the client. Pass the specific fields the component needs instead.',\n },\n schema: [],\n },\n defaultOptions: [],\n\n create(context) {\n function checkHydratedElement(element: TSESTree.JSXElement) {\n for (const attribute of element.openingElement.attributes) {\n if (attribute.type === 'JSXAttribute') {\n if (attribute.name.type === 'JSXIdentifier' && FORBIDDEN_NAMES.has(attribute.name.name)) {\n context.report({\n node: attribute,\n messageId: 'forbiddenProp',\n data: { name: attribute.name.name },\n });\n }\n } else if (attribute.type === 'JSXSpreadAttribute') {\n if (spreadArgumentDescribesResLocals(attribute.argument)) {\n context.report({\n node: attribute,\n messageId: 'forbiddenSpread',\n });\n }\n }\n }\n }\n\n return {\n JSXElement(node) {\n const opening = node.openingElement.name;\n if (opening.type !== 'JSXIdentifier' || opening.name !== HYDRATE_COMPONENT_NAME) return;\n\n const child = extractSingleJsxChild(node.children);\n if (!child) return;\n\n checkHydratedElement(child);\n },\n\n CallExpression(node) {\n if (node.callee.type !== 'Identifier' || node.callee.name !== HYDRATE_FUNCTION_NAME) return;\n if (node.arguments.length === 0) return;\n\n const arg = node.arguments[0];\n if (arg.type !== 'JSXElement') return;\n\n checkHydratedElement(arg);\n },\n };\n },\n});\n"]}
1
+ {"version":3,"file":"no-hydrate-reslocals.js","sourceRoot":"","sources":["../../src/rules/no-hydrate-reslocals.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAiB,MAAM,0BAA0B,CAAC;AAEtE;;;;;;;;;;GAUG;AAEH,MAAM,sBAAsB,GAAG,SAAS,CAAC;AACzC,MAAM,qBAAqB,GAAG,aAAa,CAAC;AAC5C,MAAM,eAAe,GAAG,IAAI,GAAG,CAAC,CAAC,WAAW,E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AC,MAAM,KAAK,CAAC;oBAAE,OAAO;gBAExC,MAAM,GAAG,GAAG,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC;gBAC9B,IAAI,GAAG,CAAC,IAAI,KAAK,YAAY;oBAAE,OAAO;gBAEtC,oBAAoB,CAAC,GAAG,CAAC,CAAC;YAC5B,CAAC;SACF,CAAC;IACJ,CAAC;CACF,CAAC,CAAC","sourcesContent":["import { ESLintUtils, type TSESTree } from '@typescript-eslint/utils';\n\n/**\n * All props on a hydrated component are serialized with superjson and shipped\n * to the browser. Passing `resLocals` or `locals` (or spreading them) would\n * leak the entire server-side `res.locals` object — CSRF tokens, auth data,\n * authz objects, full DB rows, etc.\n *\n * This rule forbids those prop names (and `{...res.locals}` / `{...resLocals}`\n * / `{...locals}` spreads) on the child of `<Hydrate>` and on the JSX argument\n * to `hydrateHtml(...)`. Extract the specific fields you need (e.g. via\n * `extractPageContext`) and pass them as individual props instead.\n */\n\nconst HYDRATE_COMPONENT_NAME = 'Hydrate';\nconst HYDRATE_FUNCTION_NAME = 'hydrateHtml';\nconst FORBIDDEN_NAMES = new Set(['resLocals', 'locals']);\n\nfunction extractSingleJsxChild(children: TSESTree.JSXChild[]): TSESTree.JSXElement | null {\n const nonWhitespace = children.filter((child) => {\n if (child.type === 'JSXText') return child.value.trim().length > 0;\n return true;\n });\n if (nonWhitespace.length !== 1 || nonWhitespace[0].type !== 'JSXElement') {\n return null;\n }\n return nonWhitespace[0];\n}\n\nfunction spreadArgumentDescribesResLocals(argument: TSESTree.Expression): boolean {\n if (argument.type === 'Identifier') {\n return FORBIDDEN_NAMES.has(argument.name);\n }\n if (\n argument.type === 'MemberExpression' &&\n !argument.computed &&\n argument.property.type === 'Identifier' &&\n argument.property.name === 'locals'\n ) {\n return true;\n }\n return false;\n}\n\nexport default ESLintUtils.RuleCreator.withoutDocs({\n meta: {\n type: 'problem',\n messages: {\n forbiddenProp:\n 'Do not pass \"{{name}}\" to a hydrated component; props are serialized and sent to the client, so this would leak the full server-side res.locals. Pass the specific fields the component needs instead.',\n forbiddenSpread:\n 'Do not spread res.locals onto a hydrated component; props are serialized and sent to the client. Pass the specific fields the component needs instead.',\n },\n schema: [],\n },\n defaultOptions: [],\n\n create(context) {\n function checkHydratedElement(element: TSESTree.JSXElement) {\n for (const attribute of element.openingElement.attributes) {\n if (attribute.type === 'JSXAttribute') {\n if (attribute.name.type === 'JSXIdentifier' && FORBIDDEN_NAMES.has(attribute.name.name)) {\n context.report({\n node: attribute,\n messageId: 'forbiddenProp',\n data: { name: attribute.name.name },\n });\n }\n } else if (attribute.type === 'JSXSpreadAttribute') {\n if (spreadArgumentDescribesResLocals(attribute.argument)) {\n context.report({\n node: attribute,\n messageId: 'forbiddenSpread',\n });\n }\n }\n }\n }\n\n return {\n JSXElement(node) {\n const opening = node.openingElement.name;\n if (opening.type !== 'JSXIdentifier' || opening.name !== HYDRATE_COMPONENT_NAME) return;\n\n const child = extractSingleJsxChild(node.children);\n if (!child) return;\n\n checkHydratedElement(child);\n },\n\n CallExpression(node) {\n if (node.callee.type !== 'Identifier' || node.callee.name !== HYDRATE_FUNCTION_NAME) return;\n if (node.arguments.length === 0) return;\n\n const arg = node.arguments[0];\n if (arg.type !== 'JSXElement') return;\n\n checkHydratedElement(arg);\n },\n };\n },\n});\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"no-unused-sql-blocks.d.ts","sourceRoot":"","sources":["../../src/rules/no-unused-sql-blocks.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,WAAW,EAAE,MAAM,0BAA0B,CAAC;;AAsBvD,wBAuCG","sourcesContent":["import * as fs from 'fs';\nimport * as path from 'path';\n\nimport { ESLintUtils } from '@typescript-eslint/utils';\n\nfunction extractSqlBlockDefinitions(sqlContent: string): Set<string> {\n const regex = / *-- *BLOCK +([^ \\n]+) */g;\n const defs = new Set<string>();\n let match;\n while ((match = regex.exec(sqlContent)) !== null) {\n defs.add(match[1]);\n }\n return defs;\n}\n\nfunction extractSqlBlockReferences(tsContent: string): Set<string> {\n const regex = /sql\\.([a-zA-Z0-9_]+)/g;\n const refs = new Set<string>();\n let match;\n while ((match = regex.exec(tsContent)) !== null) {\n refs.add(match[1]);\n }\n return refs;\n}\n\nexport default ESLintUtils.RuleCreator.withoutDocs({\n meta: {\n type: 'problem',\n messages: {\n unusedSqlBlock:\n 'SQL block \"{{block}}\" in \"{{sqlFile}}\" is not used in this file and should be deleted.',\n },\n schema: [],\n },\n defaultOptions: [],\n create(context) {\n const components = path.parse(context.filename);\n components.ext = '.sql';\n const sqlFile = path.join(components.dir, components.name) + components.ext;\n if (!fs.existsSync(sqlFile)) return {};\n const tsContent = fs.readFileSync(context.filename, 'utf8');\n const sqlContent = fs.readFileSync(sqlFile, 'utf8');\n\n const usedBlocks = extractSqlBlockReferences(tsContent);\n const definedBlocks = extractSqlBlockDefinitions(sqlContent);\n\n const unusedBlocks = [...definedBlocks].filter((block) => !usedBlocks.has(block));\n\n return {\n Program(node) {\n for (const block of unusedBlocks) {\n context.report({\n node,\n loc: {\n start: { line: 1, column: 1 },\n end: { line: 2, column: 0 },\n },\n messageId: 'unusedSqlBlock',\n data: { block, sqlFile: path.basename(sqlFile) },\n });\n }\n },\n };\n },\n});\n"]}
1
+ {"version":3,"file":"no-unused-sql-blocks.d.ts","sourceRoot":"","sources":["../../src/rules/no-unused-sql-blocks.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,WAAW,EAAE,MAAM,0BAA0B,CAAC","sourcesContent":["import * as fs from 'fs';\nimport * as path from 'path';\n\nimport { ESLintUtils } from '@typescript-eslint/utils';\n\nfunction extractSqlBlockDefinitions(sqlContent: string): Set<string> {\n const regex = / *-- *BLOCK +([^ \\n]+) */g;\n const defs = new Set<string>();\n let match;\n while ((match = regex.exec(sqlContent)) !== null) {\n defs.add(match[1]);\n }\n return defs;\n}\n\nfunction extractSqlBlockReferences(tsContent: string): Set<string> {\n const regex = /sql\\.([a-zA-Z0-9_]+)/g;\n const refs = new Set<string>();\n let match;\n while ((match = regex.exec(tsContent)) !== null) {\n refs.add(match[1]);\n }\n return refs;\n}\n\nexport default ESLintUtils.RuleCreator.withoutDocs({\n meta: {\n type: 'problem',\n messages: {\n unusedSqlBlock:\n 'SQL block \"{{block}}\" in \"{{sqlFile}}\" is not used in this file and should be deleted.',\n },\n schema: [],\n },\n defaultOptions: [],\n create(context) {\n const components = path.parse(context.filename);\n components.ext = '.sql';\n const sqlFile = path.join(components.dir, components.name) + components.ext;\n if (!fs.existsSync(sqlFile)) return {};\n const tsContent = fs.readFileSync(context.filename, 'utf8');\n const sqlContent = fs.readFileSync(sqlFile, 'utf8');\n\n const usedBlocks = extractSqlBlockReferences(tsContent);\n const definedBlocks = extractSqlBlockDefinitions(sqlContent);\n\n const unusedBlocks = [...definedBlocks].filter((block) => !usedBlocks.has(block));\n\n return {\n Program(node) {\n for (const block of unusedBlocks) {\n context.report({\n node,\n loc: {\n start: { line: 1, column: 1 },\n end: { line: 2, column: 0 },\n },\n messageId: 'unusedSqlBlock',\n data: { block, sqlFile: path.basename(sqlFile) },\n });\n }\n },\n };\n },\n});\n"]}
@@ -1,41 +1,6 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || (function () {
19
- var ownKeys = function(o) {
20
- ownKeys = Object.getOwnPropertyNames || function (o) {
21
- var ar = [];
22
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
- return ar;
24
- };
25
- return ownKeys(o);
26
- };
27
- return function (mod) {
28
- if (mod && mod.__esModule) return mod;
29
- var result = {};
30
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
- __setModuleDefault(result, mod);
32
- return result;
33
- };
34
- })();
35
- Object.defineProperty(exports, "__esModule", { value: true });
36
- const fs = __importStar(require("fs"));
37
- const path = __importStar(require("path"));
38
- const utils_1 = require("@typescript-eslint/utils");
1
+ import * as fs from 'fs';
2
+ import * as path from 'path';
3
+ import { ESLintUtils } from '@typescript-eslint/utils';
39
4
  function extractSqlBlockDefinitions(sqlContent) {
40
5
  const regex = / *-- *BLOCK +([^ \n]+) */g;
41
6
  const defs = new Set();
@@ -54,7 +19,7 @@ function extractSqlBlockReferences(tsContent) {
54
19
  }
55
20
  return refs;
56
21
  }
57
- exports.default = utils_1.ESLintUtils.RuleCreator.withoutDocs({
22
+ export default ESLintUtils.RuleCreator.withoutDocs({
58
23
  meta: {
59
24
  type: 'problem',
60
25
  messages: {
@@ -1 +1 @@
1
- {"version":3,"file":"no-unused-sql-blocks.js","sourceRoot":"","sources":["../../src/rules/no-unused-sql-blocks.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,MAAY,EAAE,+BAAW;AACzB,MAAY,IAAI,iCAAa;AAE7B,oDAAuD;AAEvD,SAAS,0BAA0B,CAAC,UAAkB;IACpD,MAAM,KAAK,GAAG,2BAA2B,CAAC;IAC1C,MAAM,IAAI,GAAG,IAAI,GAAG,EAAU,CAAC;IAC/B,IAAI,KAAK,CAAC;IACV,OAAO,CAAC,KAAK,GAAG,KAAK,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC,KAAK,IAAI,EAAE,CAAC;QACjD,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,C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CAAC;QAE7D,MAAM,YAAY,GAAG,CAAC,GAAG,aAAa,CAAC,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC,UAAU,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC;QAElF,OAAO;YACL,OAAO,CAAC,IAAI;gBACV,KAAK,MAAM,KAAK,IAAI,YAAY,EAAE,CAAC;oBACjC,OAAO,CAAC,MAAM,CAAC;wBACb,IAAI;wBACJ,GAAG,EAAE;4BACH,KAAK,EAAE,EAAE,IAAI,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE;4BAC7B,GAAG,EAAE,EAAE,IAAI,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE;yBAC5B;wBACD,SAAS,EAAE,gBAAgB;wBAC3B,IAAI,EAAE,EAAE,KAAK,EAAE,OAAO,EAAE,IAAI,CAAC,QAAQ,CAAC,OAAO,CAAC,EAAE;qBACjD,CAAC,CAAC;gBACL,CAAC;YACH,CAAC;SACF,CAAC;IACJ,CAAC;CACF,CAAC","sourcesContent":["import * as fs from 'fs';\nimport * as path from 'path';\n\nimport { ESLintUtils } from '@typescript-eslint/utils';\n\nfunction extractSqlBlockDefinitions(sqlContent: string): Set<string> {\n const regex = / *-- *BLOCK +([^ \\n]+) */g;\n const defs = new Set<string>();\n let match;\n while ((match = regex.exec(sqlContent)) !== null) {\n defs.add(match[1]);\n }\n return defs;\n}\n\nfunction extractSqlBlockReferences(tsContent: string): Set<string> {\n const regex = /sql\\.([a-zA-Z0-9_]+)/g;\n const refs = new Set<string>();\n let match;\n while ((match = regex.exec(tsContent)) !== null) {\n refs.add(match[1]);\n }\n return refs;\n}\n\nexport default ESLintUtils.RuleCreator.withoutDocs({\n meta: {\n type: 'problem',\n messages: {\n unusedSqlBlock:\n 'SQL block \"{{block}}\" in \"{{sqlFile}}\" is not used in this file and should be deleted.',\n },\n schema: [],\n },\n defaultOptions: [],\n create(context) {\n const components = path.parse(context.filename);\n components.ext = '.sql';\n const sqlFile = path.join(components.dir, components.name) + components.ext;\n if (!fs.existsSync(sqlFile)) return {};\n const tsContent = fs.readFileSync(context.filename, 'utf8');\n const sqlContent = fs.readFileSync(sqlFile, 'utf8');\n\n const usedBlocks = extractSqlBlockReferences(tsContent);\n const definedBlocks = extractSqlBlockDefinitions(sqlContent);\n\n const unusedBlocks = [...definedBlocks].filter((block) => !usedBlocks.has(block));\n\n return {\n Program(node) {\n for (const block of unusedBlocks) {\n context.report({\n node,\n loc: {\n start: { line: 1, column: 1 },\n end: { line: 2, column: 0 },\n },\n messageId: 'unusedSqlBlock',\n data: { block, sqlFile: path.basename(sqlFile) },\n });\n }\n },\n };\n },\n});\n"]}
1
+ {"version":3,"file":"no-unused-sql-blocks.js","sourceRoot":"","sources":["../../src/rules/no-unused-sql-blocks.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,IAAI,CAAC;AACzB,OAAO,KAAK,IAAI,MAAM,MAAM,CAAC;AAE7B,OAAO,EAAE,WAAW,EAAE,MAAM,0BAA0B,CAAC;AAEvD,SAAS,0BAA0B,CAAC,UAAkB;IACpD,MAAM,KAAK,GAAG,2BAA2B,CAAC;IAC1C,MAAM,IAAI,GAAG,IAAI,GAAG,EAAU,CAAC;IAC/B,IAAI,KAAK,CAAC;IACV,OAAO,CAAC,KAAK,GAAG,KAAK,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC,KAAK,IAAI,EAAE,CAAC;QACjD,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC;IACrB,CAAC;IACD,OAAO,IAAI,CAAC;AACd,CAAC;AAED,SAAS,yBAAyB,CAAC,SAAiB;IAClD,MAAM,KAAK,GAAG,uBAAuB,CAAC;IACtC,MAAM,IAAI,GAAG,IAAI,GAAG,EAAU,CAAC;IAC/B,IAAI,KAAK,CAAC;IACV,OAAO,CAAC,KAAK,GAAG,KAAK,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,KA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IAAI;wBACJ,GAAG,EAAE;4BACH,KAAK,EAAE,EAAE,IAAI,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE;4BAC7B,GAAG,EAAE,EAAE,IAAI,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE;yBAC5B;wBACD,SAAS,EAAE,gBAAgB;wBAC3B,IAAI,EAAE,EAAE,KAAK,EAAE,OAAO,EAAE,IAAI,CAAC,QAAQ,CAAC,OAAO,CAAC,EAAE;qBACjD,CAAC,CAAC;gBACL,CAAC;YACH,CAAC;SACF,CAAC;IACJ,CAAC;CACF,CAAC,CAAC","sourcesContent":["import * as fs from 'fs';\nimport * as path from 'path';\n\nimport { ESLintUtils } from '@typescript-eslint/utils';\n\nfunction extractSqlBlockDefinitions(sqlContent: string): Set<string> {\n const regex = / *-- *BLOCK +([^ \\n]+) */g;\n const defs = new Set<string>();\n let match;\n while ((match = regex.exec(sqlContent)) !== null) {\n defs.add(match[1]);\n }\n return defs;\n}\n\nfunction extractSqlBlockReferences(tsContent: string): Set<string> {\n const regex = /sql\\.([a-zA-Z0-9_]+)/g;\n const refs = new Set<string>();\n let match;\n while ((match = regex.exec(tsContent)) !== null) {\n refs.add(match[1]);\n }\n return refs;\n}\n\nexport default ESLintUtils.RuleCreator.withoutDocs({\n meta: {\n type: 'problem',\n messages: {\n unusedSqlBlock:\n 'SQL block \"{{block}}\" in \"{{sqlFile}}\" is not used in this file and should be deleted.',\n },\n schema: [],\n },\n defaultOptions: [],\n create(context) {\n const components = path.parse(context.filename);\n components.ext = '.sql';\n const sqlFile = path.join(components.dir, components.name) + components.ext;\n if (!fs.existsSync(sqlFile)) return {};\n const tsContent = fs.readFileSync(context.filename, 'utf8');\n const sqlContent = fs.readFileSync(sqlFile, 'utf8');\n\n const usedBlocks = extractSqlBlockReferences(tsContent);\n const definedBlocks = extractSqlBlockDefinitions(sqlContent);\n\n const unusedBlocks = [...definedBlocks].filter((block) => !usedBlocks.has(block));\n\n return {\n Program(node) {\n for (const block of unusedBlocks) {\n context.report({\n node,\n loc: {\n start: { line: 1, column: 1 },\n end: { line: 2, column: 0 },\n },\n messageId: 'unusedSqlBlock',\n data: { block, sqlFile: path.basename(sqlFile) },\n });\n }\n },\n };\n },\n});\n"]}
@@ -0,0 +1,4 @@
1
+ import { ESLintUtils } from '@typescript-eslint/utils';
2
+ declare const _default: ESLintUtils.RuleModule<"missingPermissionMiddleware", [], unknown, ESLintUtils.RuleListener>;
3
+ export default _default;
4
+ //# sourceMappingURL=require-trpc-permission-middleware.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"require-trpc-permission-middleware.d.ts","sourceRoot":"","sources":["../../src/rules/require-trpc-permission-middleware.ts"],"names":[],"mappings":"AAAA,OAAO,EAAY,WAAW,EAAgC,MAAM,0BAA0B,CAAC","sourcesContent":["import { ASTUtils, ESLintUtils, type TSESLint, type TSESTree } from '@typescript-eslint/utils';\n\nconst { findVariable } = ASTUtils;\n\n/**\n * tRPC procedures must enforce their own authorization via a `require*`\n * permission middleware in the chain.\n * Individual procedures often need stricter permissions than the page they're\n * mounted under (e.g. an Edit-only mutation under a route that allows View).\n * Requiring an explicit permission middleware per procedure makes the\n * authz gate visible at the call site and helps prevent missing permission checks.\n *\n * Bad:\n * ```ts\n * const list = t.procedure.query(async ({ ctx }) => { ... });\n * ```\n *\n * Good:\n * ```ts\n * const list = t.procedure.use(requireCoursePermissionEdit).query(...);\n * ```\n *\n * Recognized permission middlewares:\n * - requireCoursePermissionPreview / View / Edit / Own\n * - requireCourseInstancePermissionPreview / View / Edit / Own\n * - requireAdministrator\n *\n * Feature gates like `requireEnhancedAccessControl` and `requireAiGradingFeature`\n * don't count — they must be paired with a permission middleware.\n *\n * The rule follows intermediate procedure-base variables so patterns like\n * `const protected = t.procedure.use(...); ...; protected.query(...)` are\n * checked end-to-end.\n */\n\n// TODO: This list requires manual maintenance. We should consider making feature gates\n// not use the `require` prefix, and then we can use a more generic pattern here.\nconst PERMISSION_MIDDLEWARE_PATTERN =\n /^require(Course|CourseInstance)Permission(Preview|View|Edit|Own)$|^requireAdministrator$/;\nconst TERMINAL_METHODS = new Set(['query', 'mutation', 'subscription']);\n\nfunction unwrapMemberObject(expr: TSESTree.Expression): TSESTree.Expression {\n return expr.type === 'TSNonNullExpression' || expr.type === 'TSAsExpression'\n ? unwrapMemberObject(expr.expression)\n : expr;\n}\n\nfunction isTProcedure(expr: TSESTree.Expression): boolean {\n return (\n expr.type === 'MemberExpression' &&\n !expr.computed &&\n expr.property.type === 'Identifier' &&\n expr.property.name === 'procedure' &&\n expr.object.type === 'Identifier' &&\n expr.object.name === 't'\n );\n}\n\ninterface ChainInfo {\n matchesTProcedure: boolean;\n middlewares: string[];\n}\n\n/**\n * Walks back through a chain like `expr.use(A).input(B).use(C)` collecting\n * `.use(...)` argument identifiers. If the base of the chain is `t.procedure`,\n * returns the collected middlewares. If the base is a variable, follows the\n * variable's initializer (e.g. `const protected = t.procedure.use(X)`).\n */\nfunction getProcedureChainInfo(\n expr: TSESTree.Expression,\n scope: TSESLint.Scope.Scope,\n visited: Set<TSESTree.Node>,\n): ChainInfo {\n if (visited.has(expr)) return { matchesTProcedure: false, middlewares: [] };\n visited.add(expr);\n\n const middlewares: string[] = [];\n let cursor: TSESTree.Expression = expr;\n\n while (cursor.type === 'CallExpression') {\n const callee = cursor.callee;\n if (\n callee.type !== 'MemberExpression' ||\n callee.computed ||\n callee.property.type !== 'Identifier'\n ) {\n return { matchesTProcedure: false, middlewares: [] };\n }\n if (callee.property.name === 'use' && cursor.arguments[0]?.type === 'Identifier') {\n middlewares.push(cursor.arguments[0].name);\n }\n cursor = callee.object;\n }\n\n cursor = unwrapMemberObject(cursor);\n\n if (isTProcedure(cursor)) {\n return { matchesTProcedure: true, middlewares };\n }\n\n // Follow an intermediate procedure-base variable defined in the same module:\n // const protectedProcedure = t.procedure.use(...);\n // protectedProcedure.query(...);\n if (cursor.type === 'Identifier') {\n const variable = findVariable(scope, cursor);\n if (variable && variable.defs.length === 1) {\n const def = variable.defs[0];\n if (\n def.node.type === 'VariableDeclarator' &&\n def.node.init &&\n // Conservative: only follow `const` bindings to avoid stale data\n // from let/var rebinding.\n def.parent?.type === 'VariableDeclaration' &&\n def.parent.kind === 'const'\n ) {\n const upstream = getProcedureChainInfo(def.node.init, scope, visited);\n if (upstream.matchesTProcedure) {\n return {\n matchesTProcedure: true,\n middlewares: [...middlewares, ...upstream.middlewares],\n };\n }\n }\n }\n }\n\n return { matchesTProcedure: false, middlewares: [] };\n}\n\nexport default ESLintUtils.RuleCreator.withoutDocs({\n meta: {\n type: 'problem',\n messages: {\n missingPermissionMiddleware:\n 'tRPC procedure must call .use() with a permission middleware (e.g. requireCoursePermissionEdit)',\n },\n schema: [],\n },\n defaultOptions: [],\n\n create(context) {\n return {\n CallExpression(node) {\n if (\n node.callee.type !== 'MemberExpression' ||\n node.callee.computed ||\n node.callee.property.type !== 'Identifier' ||\n !TERMINAL_METHODS.has(node.callee.property.name)\n ) {\n return;\n }\n\n const scope = context.sourceCode.getScope(node);\n const info = getProcedureChainInfo(node.callee.object, scope, new Set());\n\n if (!info.matchesTProcedure) return;\n\n const hasPermissionGate = info.middlewares.some((name) =>\n PERMISSION_MIDDLEWARE_PATTERN.test(name),\n );\n if (!hasPermissionGate) {\n context.report({ node, messageId: 'missingPermissionMiddleware' });\n }\n },\n };\n },\n});\n"]}
@@ -0,0 +1,133 @@
1
+ import { ASTUtils, ESLintUtils } from '@typescript-eslint/utils';
2
+ const { findVariable } = ASTUtils;
3
+ /**
4
+ * tRPC procedures must enforce their own authorization via a `require*`
5
+ * permission middleware in the chain.
6
+ * Individual procedures often need stricter permissions than the page they're
7
+ * mounted under (e.g. an Edit-only mutation under a route that allows View).
8
+ * Requiring an explicit permission middleware per procedure makes the
9
+ * authz gate visible at the call site and helps prevent missing permission checks.
10
+ *
11
+ * Bad:
12
+ * ```ts
13
+ * const list = t.procedure.query(async ({ ctx }) => { ... });
14
+ * ```
15
+ *
16
+ * Good:
17
+ * ```ts
18
+ * const list = t.procedure.use(requireCoursePermissionEdit).query(...);
19
+ * ```
20
+ *
21
+ * Recognized permission middlewares:
22
+ * - requireCoursePermissionPreview / View / Edit / Own
23
+ * - requireCourseInstancePermissionPreview / View / Edit / Own
24
+ * - requireAdministrator
25
+ *
26
+ * Feature gates like `requireEnhancedAccessControl` and `requireAiGradingFeature`
27
+ * don't count — they must be paired with a permission middleware.
28
+ *
29
+ * The rule follows intermediate procedure-base variables so patterns like
30
+ * `const protected = t.procedure.use(...); ...; protected.query(...)` are
31
+ * checked end-to-end.
32
+ */
33
+ // TODO: This list requires manual maintenance. We should consider making feature gates
34
+ // not use the `require` prefix, and then we can use a more generic pattern here.
35
+ const PERMISSION_MIDDLEWARE_PATTERN = /^require(Course|CourseInstance)Permission(Preview|View|Edit|Own)$|^requireAdministrator$/;
36
+ const TERMINAL_METHODS = new Set(['query', 'mutation', 'subscription']);
37
+ function unwrapMemberObject(expr) {
38
+ return expr.type === 'TSNonNullExpression' || expr.type === 'TSAsExpression'
39
+ ? unwrapMemberObject(expr.expression)
40
+ : expr;
41
+ }
42
+ function isTProcedure(expr) {
43
+ return (expr.type === 'MemberExpression' &&
44
+ !expr.computed &&
45
+ expr.property.type === 'Identifier' &&
46
+ expr.property.name === 'procedure' &&
47
+ expr.object.type === 'Identifier' &&
48
+ expr.object.name === 't');
49
+ }
50
+ /**
51
+ * Walks back through a chain like `expr.use(A).input(B).use(C)` collecting
52
+ * `.use(...)` argument identifiers. If the base of the chain is `t.procedure`,
53
+ * returns the collected middlewares. If the base is a variable, follows the
54
+ * variable's initializer (e.g. `const protected = t.procedure.use(X)`).
55
+ */
56
+ function getProcedureChainInfo(expr, scope, visited) {
57
+ if (visited.has(expr))
58
+ return { matchesTProcedure: false, middlewares: [] };
59
+ visited.add(expr);
60
+ const middlewares = [];
61
+ let cursor = expr;
62
+ while (cursor.type === 'CallExpression') {
63
+ const callee = cursor.callee;
64
+ if (callee.type !== 'MemberExpression' ||
65
+ callee.computed ||
66
+ callee.property.type !== 'Identifier') {
67
+ return { matchesTProcedure: false, middlewares: [] };
68
+ }
69
+ if (callee.property.name === 'use' && cursor.arguments[0]?.type === 'Identifier') {
70
+ middlewares.push(cursor.arguments[0].name);
71
+ }
72
+ cursor = callee.object;
73
+ }
74
+ cursor = unwrapMemberObject(cursor);
75
+ if (isTProcedure(cursor)) {
76
+ return { matchesTProcedure: true, middlewares };
77
+ }
78
+ // Follow an intermediate procedure-base variable defined in the same module:
79
+ // const protectedProcedure = t.procedure.use(...);
80
+ // protectedProcedure.query(...);
81
+ if (cursor.type === 'Identifier') {
82
+ const variable = findVariable(scope, cursor);
83
+ if (variable && variable.defs.length === 1) {
84
+ const def = variable.defs[0];
85
+ if (def.node.type === 'VariableDeclarator' &&
86
+ def.node.init &&
87
+ // Conservative: only follow `const` bindings to avoid stale data
88
+ // from let/var rebinding.
89
+ def.parent?.type === 'VariableDeclaration' &&
90
+ def.parent.kind === 'const') {
91
+ const upstream = getProcedureChainInfo(def.node.init, scope, visited);
92
+ if (upstream.matchesTProcedure) {
93
+ return {
94
+ matchesTProcedure: true,
95
+ middlewares: [...middlewares, ...upstream.middlewares],
96
+ };
97
+ }
98
+ }
99
+ }
100
+ }
101
+ return { matchesTProcedure: false, middlewares: [] };
102
+ }
103
+ export default ESLintUtils.RuleCreator.withoutDocs({
104
+ meta: {
105
+ type: 'problem',
106
+ messages: {
107
+ missingPermissionMiddleware: 'tRPC procedure must call .use() with a permission middleware (e.g. requireCoursePermissionEdit)',
108
+ },
109
+ schema: [],
110
+ },
111
+ defaultOptions: [],
112
+ create(context) {
113
+ return {
114
+ CallExpression(node) {
115
+ if (node.callee.type !== 'MemberExpression' ||
116
+ node.callee.computed ||
117
+ node.callee.property.type !== 'Identifier' ||
118
+ !TERMINAL_METHODS.has(node.callee.property.name)) {
119
+ return;
120
+ }
121
+ const scope = context.sourceCode.getScope(node);
122
+ const info = getProcedureChainInfo(node.callee.object, scope, new Set());
123
+ if (!info.matchesTProcedure)
124
+ return;
125
+ const hasPermissionGate = info.middlewares.some((name) => PERMISSION_MIDDLEWARE_PATTERN.test(name));
126
+ if (!hasPermissionGate) {
127
+ context.report({ node, messageId: 'missingPermissionMiddleware' });
128
+ }
129
+ },
130
+ };
131
+ },
132
+ });
133
+ //# sourceMappingURL=require-trpc-permission-middleware.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"require-trpc-permission-middleware.js","sourceRoot":"","sources":["../../src/rules/require-trpc-permission-middleware.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,WAAW,EAAgC,MAAM,0BAA0B,CAAC;AAE/F,MAAM,EAAE,YAAY,EAAE,GAAG,QAAQ,CAAC;AAElC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AAEH,uFAAuF;AACvF,iFAAiF;AACjF,MAAM,6BAA6B,GACjC,0FAA0F,CAAC;AAC7F,MAAM,gBAAgB,GAAG,IAAI,GAAG,CAAC,CAAC,OAAO,EAAE,UAAU,EAAE,cAAc,CAAC,CAAC,CAAC;AAExE,SAAS,kBAAkB,CAAC,IAAyB;IACnD,OAAO,IAAI,CAAC,IAAI,KAAK,qBAAqB,IAAI,IAAI,CAAC,IAAI,KAAK,gBAAgB;QAC1E,CAAC,CAAC,kBAAkB,CAAC,IAAI,CAAC,UAAU,CAAC;QACrC,CAAC,CAAC,IAAI,CAAC;AACX,CAAC;AAED,SAAS,YAAY,CAAC,IAAyB;IAC7C,OAAO,CACL,IAAI,CAAC,IAAI,KAAK,kBAAkB;QAChC,CAAC,IAAI,CAAC,QAAQ;QACd,IAAI,CAAC,QAAQ,CAAC,IAAI,KAAK,YAAY;QACnC,IAAI,CAAC,QAAQ,CAAC,IAAI,KAAK,WAAW;QAClC,IAAI,CAAC,MAAM,CAAC,IAAI,KAAK,YAAY;QACjC,IAAI,CAAC,MAAM,CAAC,IAAI,KAAK,GAAG,CACzB,CAAC;AACJ,CAAC;AAOD;;;;;GAKG;AACH,SAAS,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,CAAC,gBAAgB,CAAC,GAAG,CAAC,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,EAChD,CAAC;oBACD,OAAO;gBACT,CAAC;gBAED,MAAM,KAAK,GAAG,OAAO,CAAC,UAAU,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC;gBAChD,MAAM,IAAI,GAAG,qBAAqB,CAAC,IAAI,CAAC,MAAM,CAAC,MAAM,EAAE,KAAK,EAAE,IAAI,GAAG,EAAE,CAAC,CAAC;gBAEzE,IAAI,CAAC,IAAI,CAAC,iBAAiB;oBAAE,OAAO;gBAEpC,MAAM,iBAAiB,GAAG,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,EAAE,CACvD,6BAA6B,CAAC,IAAI,CAAC,IAAI,CAAC,CACzC,CAAC;gBACF,IAAI,CAAC,iBAAiB,EAAE,CAAC;oBACvB,OAAO,CAAC,MAAM,CAAC,EAAE,IAAI,EAAE,SAAS,EAAE,6BAA6B,EAAE,CAAC,CAAC;gBACrE,CAAC;YACH,CAAC;SACF,CAAC;IACJ,CAAC;CACF,CAAC,CAAC","sourcesContent":["import { ASTUtils, ESLintUtils, type TSESLint, type TSESTree } from '@typescript-eslint/utils';\n\nconst { findVariable } = ASTUtils;\n\n/**\n * tRPC procedures must enforce their own authorization via a `require*`\n * permission middleware in the chain.\n * Individual procedures often need stricter permissions than the page they're\n * mounted under (e.g. an Edit-only mutation under a route that allows View).\n * Requiring an explicit permission middleware per procedure makes the\n * authz gate visible at the call site and helps prevent missing permission checks.\n *\n * Bad:\n * ```ts\n * const list = t.procedure.query(async ({ ctx }) => { ... });\n * ```\n *\n * Good:\n * ```ts\n * const list = t.procedure.use(requireCoursePermissionEdit).query(...);\n * ```\n *\n * Recognized permission middlewares:\n * - requireCoursePermissionPreview / View / Edit / Own\n * - requireCourseInstancePermissionPreview / View / Edit / Own\n * - requireAdministrator\n *\n * Feature gates like `requireEnhancedAccessControl` and `requireAiGradingFeature`\n * don't count — they must be paired with a permission middleware.\n *\n * The rule follows intermediate procedure-base variables so patterns like\n * `const protected = t.procedure.use(...); ...; protected.query(...)` are\n * checked end-to-end.\n */\n\n// TODO: This list requires manual maintenance. We should consider making feature gates\n// not use the `require` prefix, and then we can use a more generic pattern here.\nconst PERMISSION_MIDDLEWARE_PATTERN =\n /^require(Course|CourseInstance)Permission(Preview|View|Edit|Own)$|^requireAdministrator$/;\nconst TERMINAL_METHODS = new Set(['query', 'mutation', 'subscription']);\n\nfunction unwrapMemberObject(expr: TSESTree.Expression): TSESTree.Expression {\n return expr.type === 'TSNonNullExpression' || expr.type === 'TSAsExpression'\n ? unwrapMemberObject(expr.expression)\n : expr;\n}\n\nfunction isTProcedure(expr: TSESTree.Expression): boolean {\n return (\n expr.type === 'MemberExpression' &&\n !expr.computed &&\n expr.property.type === 'Identifier' &&\n expr.property.name === 'procedure' &&\n expr.object.type === 'Identifier' &&\n expr.object.name === 't'\n );\n}\n\ninterface ChainInfo {\n matchesTProcedure: boolean;\n middlewares: string[];\n}\n\n/**\n * Walks back through a chain like `expr.use(A).input(B).use(C)` collecting\n * `.use(...)` argument identifiers. If the base of the chain is `t.procedure`,\n * returns the collected middlewares. If the base is a variable, follows the\n * variable's initializer (e.g. `const protected = t.procedure.use(X)`).\n */\nfunction getProcedureChainInfo(\n expr: TSESTree.Expression,\n scope: TSESLint.Scope.Scope,\n visited: Set<TSESTree.Node>,\n): ChainInfo {\n if (visited.has(expr)) return { matchesTProcedure: false, middlewares: [] };\n visited.add(expr);\n\n const middlewares: string[] = [];\n let cursor: TSESTree.Expression = expr;\n\n while (cursor.type === 'CallExpression') {\n const callee = cursor.callee;\n if (\n callee.type !== 'MemberExpression' ||\n callee.computed ||\n callee.property.type !== 'Identifier'\n ) {\n return { matchesTProcedure: false, middlewares: [] };\n }\n if (callee.property.name === 'use' && cursor.arguments[0]?.type === 'Identifier') {\n middlewares.push(cursor.arguments[0].name);\n }\n cursor = callee.object;\n }\n\n cursor = unwrapMemberObject(cursor);\n\n if (isTProcedure(cursor)) {\n return { matchesTProcedure: true, middlewares };\n }\n\n // Follow an intermediate procedure-base variable defined in the same module:\n // const protectedProcedure = t.procedure.use(...);\n // protectedProcedure.query(...);\n if (cursor.type === 'Identifier') {\n const variable = findVariable(scope, cursor);\n if (variable && variable.defs.length === 1) {\n const def = variable.defs[0];\n if (\n def.node.type === 'VariableDeclarator' &&\n def.node.init &&\n // Conservative: only follow `const` bindings to avoid stale data\n // from let/var rebinding.\n def.parent?.type === 'VariableDeclaration' &&\n def.parent.kind === 'const'\n ) {\n const upstream = getProcedureChainInfo(def.node.init, scope, visited);\n if (upstream.matchesTProcedure) {\n return {\n matchesTProcedure: true,\n middlewares: [...middlewares, ...upstream.middlewares],\n };\n }\n }\n }\n }\n\n return { matchesTProcedure: false, middlewares: [] };\n}\n\nexport default ESLintUtils.RuleCreator.withoutDocs({\n meta: {\n type: 'problem',\n messages: {\n missingPermissionMiddleware:\n 'tRPC procedure must call .use() with a permission middleware (e.g. requireCoursePermissionEdit)',\n },\n schema: [],\n },\n defaultOptions: [],\n\n create(context) {\n return {\n CallExpression(node) {\n if (\n node.callee.type !== 'MemberExpression' ||\n node.callee.computed ||\n node.callee.property.type !== 'Identifier' ||\n !TERMINAL_METHODS.has(node.callee.property.name)\n ) {\n return;\n }\n\n const scope = context.sourceCode.getScope(node);\n const info = getProcedureChainInfo(node.callee.object, scope, new Set());\n\n if (!info.matchesTProcedure) return;\n\n const hasPermissionGate = info.middlewares.some((name) =>\n PERMISSION_MIDDLEWARE_PATTERN.test(name),\n );\n if (!hasPermissionGate) {\n context.report({ node, messageId: 'missingPermissionMiddleware' });\n }\n },\n };\n },\n});\n"]}
@@ -1,6 +1,6 @@
1
1
  import { ESLintUtils } from '@typescript-eslint/utils';
2
2
  declare const _default: ESLintUtils.RuleModule<"spreadAttributes" | "unsafeTypes", [({
3
- allowDbTypes?: (string | RegExp)[] | undefined;
3
+ allowDbTypes?: (string | RegExp)[];
4
4
  } | undefined)?], unknown, ESLintUtils.RuleListener>;
5
5
  export default _default;
6
6
  //# sourceMappingURL=safe-db-types.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"safe-db-types.d.ts","sourceRoot":"","sources":["../../src/rules/safe-db-types.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,WAAW,EAAE,MAAM,0BAA0B,CAAC;;;;AAifvD,wBAsGG","sourcesContent":["import { type TSESTree } from '@typescript-eslint/types';\nimport { ESLintUtils } from '@typescript-eslint/utils';\nimport * as ts from 'typescript';\n\nconst HYDRATE_FUNCTION_NAME = 'hydrateHtml';\nconst HYDRATE_COMPONENT_NAME = 'Hydrate';\n\n/**\n * Check if a variable declaration is a Zod schema that uses schemas from db-types.ts\n * For example: const RubricDataSchema = RubricSchema.extend({...})\n */\nfunction checkZodSchemaForDbTypes(\n declaration: ts.VariableDeclaration,\n typeChecker: ts.TypeChecker,\n): string[] {\n const violations: string[] = [];\n\n if (!declaration.initializer) return violations;\n\n // Walk the expression tree to find all identifiers\n const findIdentifiers = (node: ts.Node): void => {\n // Check property access expressions like RubricSchema.extend() or InstanceQuestionSchema.shape\n if (ts.isPropertyAccessExpression(node)) {\n const objectSymbol = typeChecker.getSymbolAtLocation(node.expression);\n if (objectSymbol) {\n const aliasedSymbol =\n objectSymbol.flags & ts.SymbolFlags.Alias\n ? typeChecker.getAliasedSymbol(objectSymbol)\n : objectSymbol;\n const decls = aliasedSymbol.getDeclarations();\n if (decls && decls.length > 0) {\n const sourceFile = decls[0].getSourceFile();\n if (sourceFile.fileName.endsWith('/db-types.ts')) {\n violations.push(aliasedSymbol.getName());\n }\n }\n }\n }\n\n // Check spread elements in object literals (e.g., ...SomeSchema.shape)\n if (ts.isSpreadAssignment(node)) {\n // The expression being spread (e.g., SomeSchema.shape)\n const spreadExpr = node.expression;\n\n // Check if it's a property access (e.g., accessing .shape)\n if (ts.isPropertyAccessExpression(spreadExpr)) {\n const objectSymbol = typeChecker.getSymbolAtLocation(spreadExpr.expression);\n if (objectSymbol) {\n const aliasedSymbol =\n objectSymbol.flags & ts.SymbolFlags.Alias\n ? typeChecker.getAliasedSymbol(objectSymbol)\n : objectSymbol;\n const decls = aliasedSymbol.getDeclarations();\n if (decls && decls.length > 0) {\n const sourceFile = decls[0].getSourceFile();\n if (sourceFile.fileName.endsWith('/db-types.ts')) {\n violations.push(aliasedSymbol.getName());\n } else {\n // The schema is defined locally, check if IT uses db-types\n for (const decl of decls) {\n if (ts.isVariableDeclaration(decl)) {\n // Recursively check the local schema\n const nestedViolations = checkZodSchemaForDbTypes(decl, typeChecker);\n violations.push(...nestedViolations);\n }\n }\n }\n }\n }\n }\n // Also check if the spread is a direct identifier (e.g., ...someObject)\n else if (ts.isIdentifier(spreadExpr)) {\n const spreadSymbol = typeChecker.getSymbolAtLocation(spreadExpr);\n if (spreadSymbol) {\n const aliasedSymbol =\n spreadSymbol.flags & ts.SymbolFlags.Alias\n ? typeChecker.getAliasedSymbol(spreadSymbol)\n : spreadSymbol;\n const decls = aliasedSymbol.getDeclarations();\n if (decls && decls.length > 0) {\n const sourceFile = decls[0].getSourceFile();\n if (sourceFile.fileName.endsWith('/db-types.ts')) {\n violations.push(aliasedSymbol.getName());\n }\n }\n }\n }\n }\n\n // Check call expressions for arguments\n if (ts.isCallExpression(node)) {\n for (const arg of node.arguments) {\n // Check if argument is an identifier (e.g., RubricItemSchema)\n if (ts.isIdentifier(arg)) {\n const argSymbol = typeChecker.getSymbolAtLocation(arg);\n if (argSymbol) {\n const aliasedSymbol =\n argSymbol.flags & ts.SymbolFlags.Alias\n ? typeChecker.getAliasedSymbol(argSymbol)\n : argSymbol;\n const decls = aliasedSymbol.getDeclarations();\n if (decls && decls.length > 0) {\n const sourceFile = decls[0].getSourceFile();\n if (sourceFile.fileName.endsWith('/db-types.ts')) {\n violations.push(aliasedSymbol.getName());\n }\n }\n }\n }\n }\n }\n\n // Check object literal property assignments (e.g., { rubric: RubricSchema })\n if (ts.isPropertyAssignment(node) && ts.isIdentifier(node.initializer)) {\n const identifier = node.initializer;\n const symbol = typeChecker.getSymbolAtLocation(identifier);\n if (symbol) {\n const aliasedSymbol =\n symbol.flags & ts.SymbolFlags.Alias ? typeChecker.getAliasedSymbol(symbol) : symbol;\n const decls = aliasedSymbol.getDeclarations();\n if (decls && decls.length > 0) {\n const sourceFile = decls[0].getSourceFile();\n if (sourceFile.fileName.endsWith('/db-types.ts')) {\n violations.push(aliasedSymbol.getName());\n }\n }\n }\n }\n\n ts.forEachChild(node, findIdentifiers);\n };\n\n findIdentifiers(declaration.initializer);\n return violations;\n}\n\n/**\n * Check if a type node is z.infer<typeof SchemaName> and if SchemaName uses db-types\n * Returns the names of db-types that the schema depends on\n */\nfunction checkForZodInferPattern(typeNode: ts.TypeNode, typeChecker: ts.TypeChecker): string[] {\n // Check if this is a type reference with type arguments\n if (!ts.isTypeReferenceNode(typeNode)) return [];\n\n // Check if the type reference is named (e.g., \"infer\" from z.infer)\n const typeName = typeNode.typeName;\n if (!ts.isQualifiedName(typeName)) return [];\n\n // Check if it's z.infer or similar pattern\n // The pattern is: z.infer<typeof SchemaName>\n const typeArgs = typeNode.typeArguments;\n if (!typeArgs || typeArgs.length !== 1) return [];\n\n const typeArg = typeArgs[0];\n\n // Check if the type argument is a typeof expression\n if (!ts.isTypeQueryNode(typeArg)) return [];\n\n // Get the schema name from typeof X\n const exprName = typeArg.exprName;\n if (!ts.isIdentifier(exprName)) return [];\n\n // Now find the schema variable declaration\n const schemaSymbol = typeChecker.getSymbolAtLocation(exprName);\n if (!schemaSymbol) return [];\n\n // Check if this is an imported symbol (alias) - follow it to the original\n const symbolToCheck =\n schemaSymbol.flags & ts.SymbolFlags.Alias\n ? typeChecker.getAliasedSymbol(schemaSymbol)\n : schemaSymbol;\n\n const schemaDecls = symbolToCheck.getDeclarations();\n if (!schemaDecls || schemaDecls.length === 0) return [];\n\n // Check if it's a variable declaration\n for (const decl of schemaDecls) {\n if (ts.isVariableDeclaration(decl)) {\n // If the schema is defined in safe-db-types.ts, it's safe by definition\n const sourceFile = decl.getSourceFile();\n if (sourceFile.fileName.endsWith('/safe-db-types.ts')) {\n return [];\n }\n\n // Use our existing helper to check if the schema uses db-types\n return checkZodSchemaForDbTypes(decl, typeChecker);\n }\n }\n\n return [];\n}\n\nfunction extractChild(children: TSESTree.JSXChild[]): TSESTree.JSXElement | null {\n const nonWhitespaceChildren = children.filter((child) => {\n if (child.type === 'JSXText') {\n return child.value.trim().length > 0;\n }\n return true;\n });\n\n if (nonWhitespaceChildren.length !== 1 || nonWhitespaceChildren[0].type !== 'JSXElement') {\n return null;\n }\n\n return nonWhitespaceChildren[0];\n}\n\n/**\n * Check if a TypeScript type node references a type from db-types.ts\n * This checks the actual source code type annotation, not the resolved type.\n * Follows type aliases (imports) to their original declaration.\n * Returns all unsafe type names found.\n */\nfunction checkTypeNodeForDbTypes(\n typeNode: ts.TypeNode,\n typeChecker: ts.TypeChecker,\n visited = new Set<ts.TypeNode>(),\n): string[] {\n if (visited.has(typeNode)) return [];\n visited.add(typeNode);\n\n const violations: string[] = [];\n\n // Check type references (e.g., User, Course, AuthnProvider)\n if (ts.isTypeReferenceNode(typeNode)) {\n const typeName = typeNode.typeName;\n const symbol = typeChecker.getSymbolAtLocation(typeName);\n\n if (symbol) {\n // Check if this is an imported symbol (alias) - follow it to the original\n const symbolToCheck =\n symbol.flags & ts.SymbolFlags.Alias ? typeChecker.getAliasedSymbol(symbol) : symbol;\n\n const declarations = symbolToCheck.getDeclarations();\n if (declarations && declarations.length > 0) {\n for (const decl of declarations) {\n const sourceFile = decl.getSourceFile();\n if (sourceFile.fileName.endsWith('/db-types.ts')) {\n // Found a type from db-types.ts!\n violations.push(symbolToCheck.getName());\n } else {\n // If it's a type alias or interface defined locally, check its properties\n if (ts.isTypeAliasDeclaration(decl) && decl.type) {\n // Special case: Check if this is z.infer<typeof XxxSchema>\n const zodSchemaViolations = checkForZodInferPattern(decl.type, typeChecker);\n violations.push(...zodSchemaViolations);\n\n // Also check the type itself\n const nestedViolations = checkTypeNodeForDbTypes(decl.type, typeChecker, visited);\n violations.push(...nestedViolations);\n } else if (ts.isInterfaceDeclaration(decl)) {\n // Check interface members\n for (const member of decl.members) {\n if (ts.isPropertySignature(member) && member.type) {\n const nestedViolations = checkTypeNodeForDbTypes(\n member.type,\n typeChecker,\n visited,\n );\n violations.push(...nestedViolations);\n }\n }\n }\n }\n }\n }\n }\n\n // Check type arguments (e.g., Array<User>, Promise<Course>)\n if (typeNode.typeArguments) {\n for (const typeArg of typeNode.typeArguments) {\n const nestedViolations = checkTypeNodeForDbTypes(typeArg, typeChecker, visited);\n violations.push(...nestedViolations);\n }\n }\n }\n\n // Check array types (e.g., User[])\n if (ts.isArrayTypeNode(typeNode)) {\n const nestedViolations = checkTypeNodeForDbTypes(typeNode.elementType, typeChecker, visited);\n violations.push(...nestedViolations);\n }\n\n // Check union types (e.g., User | null)\n if (ts.isUnionTypeNode(typeNode)) {\n for (const type of typeNode.types) {\n const nestedViolations = checkTypeNodeForDbTypes(type, typeChecker, visited);\n violations.push(...nestedViolations);\n }\n }\n\n // Check intersection types (e.g., User & { extra: string })\n if (ts.isIntersectionTypeNode(typeNode)) {\n for (const type of typeNode.types) {\n const nestedViolations = checkTypeNodeForDbTypes(type, typeChecker, visited);\n violations.push(...nestedViolations);\n }\n }\n\n // Check object type literals and their properties\n if (ts.isTypeLiteralNode(typeNode)) {\n for (const member of typeNode.members) {\n if (ts.isPropertySignature(member) && member.type) {\n const nestedViolations = checkTypeNodeForDbTypes(member.type, typeChecker, visited);\n violations.push(...nestedViolations);\n }\n }\n }\n\n // Check indexed access types (e.g., User['name'])\n // These are safe! We're only extracting a specific property, not passing the whole object.\n // So we DON'T recurse into the object type for indexed access.\n if (ts.isIndexedAccessTypeNode(typeNode)) {\n // Do not check - indexed access is safe\n }\n\n return violations;\n}\n\n/**\n * Check if a type name is in the allowlist of safe types\n */\nfunction isTypeInAllowlist(typeName: string, allowlist: (string | RegExp)[]): boolean {\n return allowlist.some((pattern) => {\n if (typeof pattern === 'string') {\n return typeName === pattern;\n }\n return pattern.test(typeName);\n });\n}\n\n/**\n * Check the props of a component for unsafe types from db-types.ts\n */\nfunction checkComponentProps({\n context,\n typeChecker,\n componentSymbol,\n tsComponentNode,\n jsxElement,\n reportNode,\n allowlist,\n}: {\n context: ReturnType<typeof ESLintUtils.RuleCreator.withoutDocs>['create'] extends (\n context: infer C,\n ) => any\n ? C\n : never;\n typeChecker: ts.TypeChecker;\n componentSymbol: ts.Symbol;\n tsComponentNode: ts.Node;\n jsxElement: TSESTree.JSXElement;\n reportNode: TSESTree.Node;\n allowlist: (string | RegExp)[];\n}): void {\n const childOpeningElement = jsxElement.openingElement;\n\n // Get the component's type (function or class component)\n const componentType = typeChecker.getTypeOfSymbolAtLocation(componentSymbol, tsComponentNode);\n const signatures = componentType.getCallSignatures();\n\n if (signatures.length === 0) return;\n\n // Get the first parameter (props) of the component function\n const propsParam = signatures[0].getParameters()[0];\n if (!propsParam) return;\n\n const propsDeclaration = propsParam.valueDeclaration;\n\n if (!propsDeclaration || !ts.isParameter(propsDeclaration)) return;\n\n // Get the type annotation node from the props parameter\n const propsTypeNode = propsDeclaration.type;\n if (!propsTypeNode) return;\n\n // Check each property in the props type\n if (ts.isTypeLiteralNode(propsTypeNode)) {\n // Inline props object: { foo: string; bar: number }\n for (const member of propsTypeNode.members) {\n if (ts.isPropertySignature(member) && member.type && member.name) {\n if (!ts.isIdentifier(member.name)) continue;\n\n const propName = member.name.text;\n const violations = checkTypeNodeForDbTypes(member.type, typeChecker);\n\n if (violations.length > 0) {\n // Find the JSX attribute for this prop\n const attribute = childOpeningElement.attributes.find(\n (attr) =>\n attr.type === 'JSXAttribute' &&\n attr.name.type === 'JSXIdentifier' &&\n attr.name.name === propName,\n );\n\n for (const typeName of violations) {\n if (isTypeInAllowlist(typeName, allowlist)) continue;\n\n context.report({\n node: attribute || reportNode,\n messageId: 'unsafeTypes',\n data: { propName, typeName },\n });\n }\n }\n }\n }\n } else if (ts.isTypeReferenceNode(propsTypeNode)) {\n // Props is a type reference (e.g., interface or type alias)\n const symbol = typeChecker.getSymbolAtLocation(propsTypeNode.typeName);\n if (symbol) {\n const resolvedSymbol =\n symbol.flags & ts.SymbolFlags.Alias ? typeChecker.getAliasedSymbol(symbol) : symbol;\n const declarations = resolvedSymbol.getDeclarations();\n\n if (declarations && declarations.length > 0) {\n for (const decl of declarations) {\n if (ts.isInterfaceDeclaration(decl) || ts.isTypeLiteralNode(decl)) {\n const members = ts.isInterfaceDeclaration(decl) ? decl.members : decl.members;\n\n for (const member of members) {\n if (ts.isPropertySignature(member) && member.type && member.name) {\n if (!ts.isIdentifier(member.name)) continue;\n\n const propName = member.name.text;\n const violations = checkTypeNodeForDbTypes(member.type, typeChecker);\n\n if (violations.length > 0) {\n // Find the JSX attribute for this prop\n const attribute = childOpeningElement.attributes.find(\n (attr) =>\n attr.type === 'JSXAttribute' &&\n attr.name.type === 'JSXIdentifier' &&\n attr.name.name === propName,\n );\n\n for (const typeName of violations) {\n if (isTypeInAllowlist(typeName, allowlist)) continue;\n\n context.report({\n node: attribute || reportNode,\n messageId: 'unsafeTypes',\n data: { propName, typeName },\n });\n }\n }\n }\n }\n } else if (ts.isTypeAliasDeclaration(decl) && decl.type) {\n // Type alias might be an inline object type\n if (ts.isTypeLiteralNode(decl.type)) {\n for (const member of decl.type.members) {\n if (ts.isPropertySignature(member) && member.type && member.name) {\n if (!ts.isIdentifier(member.name)) continue;\n\n const propName = member.name.text;\n const violations = checkTypeNodeForDbTypes(member.type, typeChecker);\n\n if (violations.length > 0) {\n // Find the JSX attribute for this prop\n const attribute = childOpeningElement.attributes.find(\n (attr) =>\n attr.type === 'JSXAttribute' &&\n attr.name.type === 'JSXIdentifier' &&\n attr.name.name === propName,\n );\n\n for (const typeName of violations) {\n if (isTypeInAllowlist(typeName, allowlist)) continue;\n\n context.report({\n node: attribute || reportNode,\n messageId: 'unsafeTypes',\n data: { propName, typeName },\n });\n }\n }\n }\n }\n }\n }\n }\n }\n }\n }\n\n // Check for spread attributes\n const attributes = childOpeningElement.attributes;\n for (const attr of attributes) {\n if (attr.type === 'JSXSpreadAttribute') {\n context.report({\n node: reportNode,\n messageId: 'spreadAttributes',\n });\n continue;\n }\n }\n}\n\nexport default ESLintUtils.RuleCreator.withoutDocs<\n [{ allowDbTypes?: (string | RegExp)[] }?],\n 'spreadAttributes' | 'unsafeTypes'\n>({\n meta: {\n type: 'problem',\n messages: {\n spreadAttributes: 'Spread attributes are not allowed in Hydrate children.',\n unsafeTypes:\n 'Prop \"{{propName}}\" uses type \"{{typeName}}\" which is derived from db-types.ts. Use safe-db-types.ts instead.',\n },\n schema: [\n {\n type: 'object',\n properties: {\n allowDbTypes: {\n type: 'array',\n items: {\n type: 'string',\n },\n },\n },\n additionalProperties: false,\n },\n ],\n },\n defaultOptions: [{}],\n create(context) {\n const options = context.options[0] || {};\n const allowlist = options.allowDbTypes || [];\n return {\n JSXElement(node) {\n const openingElementNameExpression = node.openingElement.name;\n if (openingElementNameExpression.type !== 'JSXIdentifier') return;\n\n const elementName = openingElementNameExpression.name;\n if (elementName !== HYDRATE_COMPONENT_NAME) return;\n\n const child = extractChild(node.children);\n if (!child) return;\n\n // Get the component being rendered\n const childOpeningElement = child.openingElement;\n const childElementName = childOpeningElement.name;\n\n if (childElementName.type !== 'JSXIdentifier') return;\n\n // Get the component's type to inspect its props\n const services = ESLintUtils.getParserServices(context);\n const typeChecker = services.program.getTypeChecker();\n const tsChildNode = services.esTreeNodeToTSNodeMap.get(childElementName);\n const componentSymbol = typeChecker.getSymbolAtLocation(tsChildNode);\n\n if (!componentSymbol) return;\n\n checkComponentProps({\n context,\n typeChecker,\n componentSymbol,\n tsComponentNode: tsChildNode,\n jsxElement: child,\n reportNode: child,\n allowlist,\n });\n },\n\n CallExpression(node) {\n // Check for hydrateHtml(<Component ... />, props?) calls\n if (node.callee.type !== 'Identifier' || node.callee.name !== HYDRATE_FUNCTION_NAME) return;\n\n // Should have at least one argument, the first is JSX element.\n if (node.arguments.length === 0) return;\n\n const arg = node.arguments[0];\n if (arg.type !== 'JSXElement') return;\n\n const jsxElement = arg;\n const openingElement = jsxElement.openingElement;\n const elementName = openingElement.name;\n\n if (elementName.type !== 'JSXIdentifier') return;\n\n // Get the component's type to inspect its props\n const services = ESLintUtils.getParserServices(context);\n const typeChecker = services.program.getTypeChecker();\n const tsElementNode = services.esTreeNodeToTSNodeMap.get(elementName);\n const componentSymbol = typeChecker.getSymbolAtLocation(tsElementNode);\n\n if (!componentSymbol) return;\n\n checkComponentProps({\n context,\n typeChecker,\n componentSymbol,\n tsComponentNode: tsElementNode,\n jsxElement,\n reportNode: node,\n allowlist,\n });\n },\n };\n },\n});\n"]}
1
+ {"version":3,"file":"safe-db-types.d.ts","sourceRoot":"","sources":["../../src/rules/safe-db-types.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,WAAW,EAAE,MAAM,0BAA0B,CAAC;;mBAkfnC,CAAC,MAAM,GAAG,MAAM,CAAC,EAAE","sourcesContent":["import { type TSESTree } from '@typescript-eslint/types';\nimport { ESLintUtils } from '@typescript-eslint/utils';\nimport * as ts from 'typescript';\n\nconst HYDRATE_FUNCTION_NAME = 'hydrateHtml';\nconst HYDRATE_COMPONENT_NAME = 'Hydrate';\n\n/**\n * Check if a variable declaration is a Zod schema that uses schemas from db-types.ts\n * For example: const RubricDataSchema = RubricSchema.extend({...})\n */\nfunction checkZodSchemaForDbTypes(\n declaration: ts.VariableDeclaration,\n typeChecker: ts.TypeChecker,\n): string[] {\n const violations: string[] = [];\n\n if (!declaration.initializer) return violations;\n\n // Walk the expression tree to find all identifiers\n const findIdentifiers = (node: ts.Node): void => {\n // Check property access expressions like RubricSchema.extend() or InstanceQuestionSchema.shape\n if (ts.isPropertyAccessExpression(node)) {\n const objectSymbol = typeChecker.getSymbolAtLocation(node.expression);\n if (objectSymbol) {\n const aliasedSymbol =\n objectSymbol.flags & ts.SymbolFlags.Alias\n ? typeChecker.getAliasedSymbol(objectSymbol)\n : objectSymbol;\n const decls = aliasedSymbol.getDeclarations();\n if (decls && decls.length > 0) {\n const sourceFile = decls[0].getSourceFile();\n if (sourceFile.fileName.endsWith('/db-types.ts')) {\n violations.push(aliasedSymbol.getName());\n }\n }\n }\n }\n\n // Check spread elements in object literals (e.g., ...SomeSchema.shape)\n if (ts.isSpreadAssignment(node)) {\n // The expression being spread (e.g., SomeSchema.shape)\n const spreadExpr = node.expression;\n\n // Check if it's a property access (e.g., accessing .shape)\n if (ts.isPropertyAccessExpression(spreadExpr)) {\n const objectSymbol = typeChecker.getSymbolAtLocation(spreadExpr.expression);\n if (objectSymbol) {\n const aliasedSymbol =\n objectSymbol.flags & ts.SymbolFlags.Alias\n ? typeChecker.getAliasedSymbol(objectSymbol)\n : objectSymbol;\n const decls = aliasedSymbol.getDeclarations();\n if (decls && decls.length > 0) {\n const sourceFile = decls[0].getSourceFile();\n if (sourceFile.fileName.endsWith('/db-types.ts')) {\n violations.push(aliasedSymbol.getName());\n } else {\n // The schema is defined locally, check if IT uses db-types\n for (const decl of decls) {\n if (ts.isVariableDeclaration(decl)) {\n // Recursively check the local schema\n const nestedViolations = checkZodSchemaForDbTypes(decl, typeChecker);\n violations.push(...nestedViolations);\n }\n }\n }\n }\n }\n }\n // Also check if the spread is a direct identifier (e.g., ...someObject)\n else if (ts.isIdentifier(spreadExpr)) {\n const spreadSymbol = typeChecker.getSymbolAtLocation(spreadExpr);\n if (spreadSymbol) {\n const aliasedSymbol =\n spreadSymbol.flags & ts.SymbolFlags.Alias\n ? typeChecker.getAliasedSymbol(spreadSymbol)\n : spreadSymbol;\n const decls = aliasedSymbol.getDeclarations();\n if (decls && decls.length > 0) {\n const sourceFile = decls[0].getSourceFile();\n if (sourceFile.fileName.endsWith('/db-types.ts')) {\n violations.push(aliasedSymbol.getName());\n }\n }\n }\n }\n }\n\n // Check call expressions for arguments\n if (ts.isCallExpression(node)) {\n for (const arg of node.arguments) {\n // Check if argument is an identifier (e.g., RubricItemSchema)\n if (ts.isIdentifier(arg)) {\n const argSymbol = typeChecker.getSymbolAtLocation(arg);\n if (argSymbol) {\n const aliasedSymbol =\n argSymbol.flags & ts.SymbolFlags.Alias\n ? typeChecker.getAliasedSymbol(argSymbol)\n : argSymbol;\n const decls = aliasedSymbol.getDeclarations();\n if (decls && decls.length > 0) {\n const sourceFile = decls[0].getSourceFile();\n if (sourceFile.fileName.endsWith('/db-types.ts')) {\n violations.push(aliasedSymbol.getName());\n }\n }\n }\n }\n }\n }\n\n // Check object literal property assignments (e.g., { rubric: RubricSchema })\n if (ts.isPropertyAssignment(node) && ts.isIdentifier(node.initializer)) {\n const identifier = node.initializer;\n const symbol = typeChecker.getSymbolAtLocation(identifier);\n if (symbol) {\n const aliasedSymbol =\n symbol.flags & ts.SymbolFlags.Alias ? typeChecker.getAliasedSymbol(symbol) : symbol;\n const decls = aliasedSymbol.getDeclarations();\n if (decls && decls.length > 0) {\n const sourceFile = decls[0].getSourceFile();\n if (sourceFile.fileName.endsWith('/db-types.ts')) {\n violations.push(aliasedSymbol.getName());\n }\n }\n }\n }\n\n ts.forEachChild(node, findIdentifiers);\n };\n\n findIdentifiers(declaration.initializer);\n return violations;\n}\n\n/**\n * Check if a type node is z.infer<typeof SchemaName> and if SchemaName uses db-types\n * Returns the names of db-types that the schema depends on\n */\nfunction checkForZodInferPattern(typeNode: ts.TypeNode, typeChecker: ts.TypeChecker): string[] {\n // Check if this is a type reference with type arguments\n if (!ts.isTypeReferenceNode(typeNode)) return [];\n\n // Check if the type reference is named (e.g., \"infer\" from z.infer)\n const typeName = typeNode.typeName;\n if (!ts.isQualifiedName(typeName)) return [];\n\n // Check if it's z.infer or similar pattern\n // The pattern is: z.infer<typeof SchemaName>\n const typeArgs = typeNode.typeArguments;\n if (!typeArgs || typeArgs.length !== 1) return [];\n\n const typeArg = typeArgs[0];\n\n // Check if the type argument is a typeof expression\n if (!ts.isTypeQueryNode(typeArg)) return [];\n\n // Get the schema name from typeof X\n const exprName = typeArg.exprName;\n if (!ts.isIdentifier(exprName)) return [];\n\n // Now find the schema variable declaration\n const schemaSymbol = typeChecker.getSymbolAtLocation(exprName);\n if (!schemaSymbol) return [];\n\n // Check if this is an imported symbol (alias) - follow it to the original\n const symbolToCheck =\n schemaSymbol.flags & ts.SymbolFlags.Alias\n ? typeChecker.getAliasedSymbol(schemaSymbol)\n : schemaSymbol;\n\n const schemaDecls = symbolToCheck.getDeclarations();\n if (!schemaDecls || schemaDecls.length === 0) return [];\n\n // Check if it's a variable declaration\n for (const decl of schemaDecls) {\n if (ts.isVariableDeclaration(decl)) {\n // If the schema is defined in safe-db-types.ts, it's safe by definition\n const sourceFile = decl.getSourceFile();\n if (sourceFile.fileName.endsWith('/safe-db-types.ts')) {\n return [];\n }\n\n // Use our existing helper to check if the schema uses db-types\n return checkZodSchemaForDbTypes(decl, typeChecker);\n }\n }\n\n return [];\n}\n\nfunction extractChild(children: TSESTree.JSXChild[]): TSESTree.JSXElement | null {\n const nonWhitespaceChildren = children.filter((child) => {\n if (child.type === 'JSXText') {\n return child.value.trim().length > 0;\n }\n return true;\n });\n\n if (nonWhitespaceChildren.length !== 1 || nonWhitespaceChildren[0].type !== 'JSXElement') {\n return null;\n }\n\n return nonWhitespaceChildren[0];\n}\n\n/**\n * Check if a TypeScript type node references a type from db-types.ts\n * This checks the actual source code type annotation, not the resolved type.\n * Follows type aliases (imports) to their original declaration.\n * Returns all unsafe type names found.\n */\nfunction checkTypeNodeForDbTypes(\n typeNode: ts.TypeNode,\n typeChecker: ts.TypeChecker,\n visited = new Set<ts.TypeNode>(),\n): string[] {\n if (visited.has(typeNode)) return [];\n visited.add(typeNode);\n\n const violations: string[] = [];\n\n // Check type references (e.g., User, Course, AuthnProvider)\n if (ts.isTypeReferenceNode(typeNode)) {\n const typeName = typeNode.typeName;\n const symbol = typeChecker.getSymbolAtLocation(typeName);\n\n if (symbol) {\n // Check if this is an imported symbol (alias) - follow it to the original\n const symbolToCheck =\n symbol.flags & ts.SymbolFlags.Alias ? typeChecker.getAliasedSymbol(symbol) : symbol;\n\n const declarations = symbolToCheck.getDeclarations();\n if (declarations && declarations.length > 0) {\n for (const decl of declarations) {\n const sourceFile = decl.getSourceFile();\n if (sourceFile.fileName.endsWith('/db-types.ts')) {\n // Found a type from db-types.ts!\n violations.push(symbolToCheck.getName());\n } else {\n // If it's a type alias or interface defined locally, check its properties\n if (ts.isTypeAliasDeclaration(decl) && decl.type) {\n // Special case: Check if this is z.infer<typeof XxxSchema>\n const zodSchemaViolations = checkForZodInferPattern(decl.type, typeChecker);\n violations.push(...zodSchemaViolations);\n\n // Also check the type itself\n const nestedViolations = checkTypeNodeForDbTypes(decl.type, typeChecker, visited);\n violations.push(...nestedViolations);\n } else if (ts.isInterfaceDeclaration(decl)) {\n // Check interface members\n for (const member of decl.members) {\n if (ts.isPropertySignature(member) && member.type) {\n const nestedViolations = checkTypeNodeForDbTypes(\n member.type,\n typeChecker,\n visited,\n );\n violations.push(...nestedViolations);\n }\n }\n }\n }\n }\n }\n }\n\n // Check type arguments (e.g., Array<User>, Promise<Course>)\n if (typeNode.typeArguments) {\n for (const typeArg of typeNode.typeArguments) {\n const nestedViolations = checkTypeNodeForDbTypes(typeArg, typeChecker, visited);\n violations.push(...nestedViolations);\n }\n }\n }\n\n // Check array types (e.g., User[])\n if (ts.isArrayTypeNode(typeNode)) {\n const nestedViolations = checkTypeNodeForDbTypes(typeNode.elementType, typeChecker, visited);\n violations.push(...nestedViolations);\n }\n\n // Check union types (e.g., User | null)\n if (ts.isUnionTypeNode(typeNode)) {\n for (const type of typeNode.types) {\n const nestedViolations = checkTypeNodeForDbTypes(type, typeChecker, visited);\n violations.push(...nestedViolations);\n }\n }\n\n // Check intersection types (e.g., User & { extra: string })\n if (ts.isIntersectionTypeNode(typeNode)) {\n for (const type of typeNode.types) {\n const nestedViolations = checkTypeNodeForDbTypes(type, typeChecker, visited);\n violations.push(...nestedViolations);\n }\n }\n\n // Check object type literals and their properties\n if (ts.isTypeLiteralNode(typeNode)) {\n for (const member of typeNode.members) {\n if (ts.isPropertySignature(member) && member.type) {\n const nestedViolations = checkTypeNodeForDbTypes(member.type, typeChecker, visited);\n violations.push(...nestedViolations);\n }\n }\n }\n\n // Check indexed access types (e.g., User['name'])\n // These are safe! We're only extracting a specific property, not passing the whole object.\n // So we DON'T recurse into the object type for indexed access.\n if (ts.isIndexedAccessTypeNode(typeNode)) {\n // Do not check - indexed access is safe\n }\n\n return violations;\n}\n\n/**\n * Check if a type name is in the allowlist of safe types\n */\nfunction isTypeInAllowlist(typeName: string, allowlist: (string | RegExp)[]): boolean {\n return allowlist.some((pattern) => {\n if (typeof pattern === 'string') {\n return typeName === pattern;\n }\n return pattern.test(typeName);\n });\n}\n\n/**\n * Check the props of a component for unsafe types from db-types.ts\n */\nfunction checkComponentProps({\n context,\n typeChecker,\n componentSymbol,\n tsComponentNode,\n jsxElement,\n reportNode,\n allowlist,\n}: {\n context: ReturnType<typeof ESLintUtils.RuleCreator.withoutDocs>['create'] extends (\n context: infer C,\n ) => any\n ? C\n : never;\n typeChecker: ts.TypeChecker;\n componentSymbol: ts.Symbol;\n tsComponentNode: ts.Node;\n jsxElement: TSESTree.JSXElement;\n reportNode: TSESTree.Node;\n allowlist: (string | RegExp)[];\n}): void {\n const childOpeningElement = jsxElement.openingElement;\n\n // Get the component's type (function or class component)\n const componentType = typeChecker.getTypeOfSymbolAtLocation(componentSymbol, tsComponentNode);\n const signatures = componentType.getCallSignatures();\n\n if (signatures.length === 0) return;\n\n // Get the first parameter (props) of the component function\n const propsParam = signatures[0].getParameters()[0];\n if (!propsParam) return;\n\n const propsDeclaration = propsParam.valueDeclaration;\n\n if (!propsDeclaration || !ts.isParameter(propsDeclaration)) return;\n\n // Get the type annotation node from the props parameter\n const propsTypeNode = propsDeclaration.type;\n if (!propsTypeNode) return;\n\n // Check each property in the props type\n if (ts.isTypeLiteralNode(propsTypeNode)) {\n // Inline props object: { foo: string; bar: number }\n for (const member of propsTypeNode.members) {\n if (ts.isPropertySignature(member) && member.type && member.name) {\n if (!ts.isIdentifier(member.name)) continue;\n\n const propName = member.name.text;\n const violations = checkTypeNodeForDbTypes(member.type, typeChecker);\n\n if (violations.length > 0) {\n // Find the JSX attribute for this prop\n const attribute = childOpeningElement.attributes.find(\n (attr) =>\n attr.type === 'JSXAttribute' &&\n attr.name.type === 'JSXIdentifier' &&\n attr.name.name === propName,\n );\n\n for (const typeName of violations) {\n if (isTypeInAllowlist(typeName, allowlist)) continue;\n\n context.report({\n node: attribute || reportNode,\n messageId: 'unsafeTypes',\n data: { propName, typeName },\n });\n }\n }\n }\n }\n } else if (ts.isTypeReferenceNode(propsTypeNode)) {\n // Props is a type reference (e.g., interface or type alias)\n const symbol = typeChecker.getSymbolAtLocation(propsTypeNode.typeName);\n if (symbol) {\n const resolvedSymbol =\n symbol.flags & ts.SymbolFlags.Alias ? typeChecker.getAliasedSymbol(symbol) : symbol;\n const declarations = resolvedSymbol.getDeclarations();\n\n if (declarations && declarations.length > 0) {\n for (const decl of declarations) {\n if (ts.isInterfaceDeclaration(decl) || ts.isTypeLiteralNode(decl)) {\n const members = ts.isInterfaceDeclaration(decl) ? decl.members : decl.members;\n\n for (const member of members) {\n if (ts.isPropertySignature(member) && member.type && member.name) {\n if (!ts.isIdentifier(member.name)) continue;\n\n const propName = member.name.text;\n const violations = checkTypeNodeForDbTypes(member.type, typeChecker);\n\n if (violations.length > 0) {\n // Find the JSX attribute for this prop\n const attribute = childOpeningElement.attributes.find(\n (attr) =>\n attr.type === 'JSXAttribute' &&\n attr.name.type === 'JSXIdentifier' &&\n attr.name.name === propName,\n );\n\n for (const typeName of violations) {\n if (isTypeInAllowlist(typeName, allowlist)) continue;\n\n context.report({\n node: attribute || reportNode,\n messageId: 'unsafeTypes',\n data: { propName, typeName },\n });\n }\n }\n }\n }\n } else if (ts.isTypeAliasDeclaration(decl) && decl.type) {\n // Type alias might be an inline object type\n if (ts.isTypeLiteralNode(decl.type)) {\n for (const member of decl.type.members) {\n if (ts.isPropertySignature(member) && member.type && member.name) {\n if (!ts.isIdentifier(member.name)) continue;\n\n const propName = member.name.text;\n const violations = checkTypeNodeForDbTypes(member.type, typeChecker);\n\n if (violations.length > 0) {\n // Find the JSX attribute for this prop\n const attribute = childOpeningElement.attributes.find(\n (attr) =>\n attr.type === 'JSXAttribute' &&\n attr.name.type === 'JSXIdentifier' &&\n attr.name.name === propName,\n );\n\n for (const typeName of violations) {\n if (isTypeInAllowlist(typeName, allowlist)) continue;\n\n context.report({\n node: attribute || reportNode,\n messageId: 'unsafeTypes',\n data: { propName, typeName },\n });\n }\n }\n }\n }\n }\n }\n }\n }\n }\n }\n\n // Check for spread attributes\n const attributes = childOpeningElement.attributes;\n for (const attr of attributes) {\n if (attr.type === 'JSXSpreadAttribute') {\n context.report({\n node: reportNode,\n messageId: 'spreadAttributes',\n });\n continue;\n }\n }\n}\n\nexport default ESLintUtils.RuleCreator.withoutDocs<\n [{ allowDbTypes?: (string | RegExp)[] }?],\n 'spreadAttributes' | 'unsafeTypes'\n>({\n meta: {\n type: 'problem',\n messages: {\n spreadAttributes: 'Spread attributes are not allowed in Hydrate children.',\n unsafeTypes:\n 'Prop \"{{propName}}\" uses type \"{{typeName}}\" which is derived from db-types.ts. Use safe-db-types.ts instead.',\n },\n schema: [\n {\n type: 'object',\n properties: {\n allowDbTypes: {\n type: 'array',\n items: {\n type: 'string',\n },\n },\n },\n additionalProperties: false,\n },\n ],\n },\n defaultOptions: [{}],\n create(context) {\n const options = context.options[0] || {};\n const allowlist = options.allowDbTypes || [];\n return {\n JSXElement(node) {\n const openingElementNameExpression = node.openingElement.name;\n if (openingElementNameExpression.type !== 'JSXIdentifier') return;\n\n const elementName = openingElementNameExpression.name;\n if (elementName !== HYDRATE_COMPONENT_NAME) return;\n\n const child = extractChild(node.children);\n if (!child) return;\n\n // Get the component being rendered\n const childOpeningElement = child.openingElement;\n const childElementName = childOpeningElement.name;\n\n if (childElementName.type !== 'JSXIdentifier') return;\n\n // Get the component's type to inspect its props\n const services = ESLintUtils.getParserServices(context);\n const typeChecker = services.program.getTypeChecker();\n const tsChildNode = services.esTreeNodeToTSNodeMap.get(childElementName);\n const componentSymbol = typeChecker.getSymbolAtLocation(tsChildNode);\n\n if (!componentSymbol) return;\n\n checkComponentProps({\n context,\n typeChecker,\n componentSymbol,\n tsComponentNode: tsChildNode,\n jsxElement: child,\n reportNode: child,\n allowlist,\n });\n },\n\n CallExpression(node) {\n // Check for hydrateHtml(<Component ... />, props?) calls\n if (node.callee.type !== 'Identifier' || node.callee.name !== HYDRATE_FUNCTION_NAME) return;\n\n // Should have at least one argument, the first is JSX element.\n if (node.arguments.length === 0) return;\n\n const arg = node.arguments[0];\n if (arg.type !== 'JSXElement') return;\n\n const jsxElement = arg;\n const openingElement = jsxElement.openingElement;\n const elementName = openingElement.name;\n\n if (elementName.type !== 'JSXIdentifier') return;\n\n // Get the component's type to inspect its props\n const services = ESLintUtils.getParserServices(context);\n const typeChecker = services.program.getTypeChecker();\n const tsElementNode = services.esTreeNodeToTSNodeMap.get(elementName);\n const componentSymbol = typeChecker.getSymbolAtLocation(tsElementNode);\n\n if (!componentSymbol) return;\n\n checkComponentProps({\n context,\n typeChecker,\n componentSymbol,\n tsComponentNode: tsElementNode,\n jsxElement,\n reportNode: node,\n allowlist,\n });\n },\n };\n },\n});\n"]}