permdock 0.30.0 → 0.32.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 (479) hide show
  1. package/README.md +2 -2
  2. package/dist/a2a/index.d.ts +5 -5
  3. package/dist/a2a/index.js +2 -2
  4. package/dist/{adoption-scan-EGg-hGEu.js → adoption-scan-BJMEEu7V.js} +1 -1
  5. package/dist/agent/index.d.ts +2 -2
  6. package/dist/agent/index.js +1 -1
  7. package/dist/ai-sdk/index.d.ts +4 -4
  8. package/dist/ai-sdk/index.js +3 -3
  9. package/dist/annotate-dUrBHXWa.js +183 -0
  10. package/dist/{annotate-doc-BCOCOrq_.js → annotate-doc-BA0betEO.js} +5 -4
  11. package/dist/annotate-routes-CGJy1ojp.js +30 -0
  12. package/dist/app/index.d.ts +1 -1
  13. package/dist/app/index.js +1 -1
  14. package/dist/app-peer-BnMh5lqz.js +27 -0
  15. package/dist/approval-chain-D97rgMoA.js +431 -0
  16. package/dist/{approval-normalize-Cpp8R0rY.js → approval-normalize-C6je8vWN.js} +1 -1
  17. package/dist/{approval-prompt-C-vjNZyd.d.ts → approval-prompt-yNyhQqn8.d.ts} +2 -2
  18. package/dist/approvals/index.d.ts +3 -3
  19. package/dist/approvals/index.js +3 -3
  20. package/dist/{approvals-7jHYXocE.js → approvals-Bt5IQ4wR.js} +3 -3
  21. package/dist/{arazzo-CfjZOmVG.js → arazzo-BAgh0PT6.js} +3 -3
  22. package/dist/{arazzo-yiKJ4jm0.js → arazzo-C_xK2Kaa.js} +2 -2
  23. package/dist/{args-Bc0HLiD4.js → args-BSpXxMnb.js} +2 -1
  24. package/dist/ast-CAOxvn9t.js +188 -0
  25. package/dist/ast-Dnm2TOHN.js +434 -0
  26. package/dist/astro/index.d.ts +6 -6
  27. package/dist/astro/index.js +2 -2
  28. package/dist/{audience-DauhRBNg.js → audience-CARf-b-R.js} +1 -1
  29. package/dist/authzen/index.d.ts +6 -6
  30. package/dist/authzen/index.js +3 -3
  31. package/dist/{automation-CUcWz8uu.d.ts → automation-0VF1xe4o.d.ts} +3 -3
  32. package/dist/{automation-CpPdFX91.js → automation-D58PEI7Y.js} +1 -1
  33. package/dist/baseline-file-BQoki1O_.js +148 -0
  34. package/dist/better-auth/index.d.ts +2 -2
  35. package/dist/better-auth/index.js +2 -2
  36. package/dist/better-supabase/index.d.ts +72 -19
  37. package/dist/better-supabase/index.js +156 -71
  38. package/dist/{bind-up3QptTt.js → bind-BYeoLJgN.js} +5 -4
  39. package/dist/{bind-B3MHrzw4.d.ts → bind-zQacwAOg.d.ts} +12 -7
  40. package/dist/bsb-access-Bcw6GrQm.js +74 -0
  41. package/dist/bsb-access-tags-CjeR7v7-.js +272 -0
  42. package/dist/bsb-action-keys-CYEREFMg.js +377 -0
  43. package/dist/bsb-actions-BHiyBxQZ.js +65 -0
  44. package/dist/budgets-Dpumu_Dt.js +75 -0
  45. package/dist/{build-instance-hLKYe3-E.js → build-instance-CFiegi_w.js} +1 -1
  46. package/dist/bundle-size-Ddhv_H_v.js +56 -0
  47. package/dist/bundle-size-DwZ4e1gu.js +1 -0
  48. package/dist/{capability-CVt3lpVK.d.ts → capability-BPzseilU.d.ts} +2 -2
  49. package/dist/{capability-_ZsyfYxU.js → capability-oxfxybFR.js} +1 -1
  50. package/dist/{casbin-QzddqHaV.js → casbin-BErdqy1J.js} +1 -1
  51. package/dist/{casbin-j_468wDU.js → casbin-EwdKipQs.js} +2 -2
  52. package/dist/{casl-CrltbDPa.js → casl-BSt24g-p.js} +1 -1
  53. package/dist/catalog/index.d.ts +5 -5
  54. package/dist/catalog/index.js +6 -6
  55. package/dist/{catalog-DXSP1we9.js → catalog-BExjL94D.js} +4 -4
  56. package/dist/{catalog-COoxFOoy.js → catalog-CBPFyRv7.js} +2 -2
  57. package/dist/{catalog-doc-Bp5khmCG.js → catalog-doc-D4g3nyFB.js} +5 -3
  58. package/dist/{catalog-operations-dxuOZr4J.js → catalog-operations-BqSsByIE.js} +3 -3
  59. package/dist/catalog-sR0m6x2g.js +1 -0
  60. package/dist/{challenge-CjwmjcuX.js → challenge-CRB1X3Ry.js} +1 -1
  61. package/dist/chat/index.d.ts +1 -1
  62. package/dist/chat/index.js +2 -2
  63. package/dist/chat-sdk/index.d.ts +3 -3
  64. package/dist/claims-size-B6j0Ff4Q.js +1 -0
  65. package/dist/{perf-token-dFGVP14-.js → claims-size-BsSDVD5u.js} +66 -1
  66. package/dist/claude-agent/index.d.ts +3 -3
  67. package/dist/claude-agent/index.js +2 -2
  68. package/dist/clerk/index.d.ts +3 -3
  69. package/dist/cli/bin.js +1 -1
  70. package/dist/cli/generate/watch-worker.js +2 -2
  71. package/dist/cli/index.d.ts +9 -9
  72. package/dist/cli/index.js +3 -3
  73. package/dist/cli/plugins/app.d.ts +1 -1
  74. package/dist/cli/plugins/app.js +1 -1
  75. package/dist/cli/plugins/better-supabase.d.ts +1 -1
  76. package/dist/cli/plugins/openapi.d.ts +1 -1
  77. package/dist/cli/plugins/openapi.js +2 -2
  78. package/dist/cli/plugins/powersync.d.ts +1 -1
  79. package/dist/cli/plugins/powersync.js +2 -2
  80. package/dist/cli/plugins/rls.d.ts +2 -2
  81. package/dist/cli/plugins/rls.js +1 -1
  82. package/dist/cli/plugins/schemas.d.ts +1 -1
  83. package/dist/cli/plugins/schemas.js +1 -1
  84. package/dist/cli/plugins/scim.d.ts +2 -2
  85. package/dist/cli/plugins/supabase-hook.d.ts +2 -2
  86. package/dist/cli/plugins/supabase-hook.js +1 -1
  87. package/dist/cli/plugins/supabase.d.ts +3 -3
  88. package/dist/cli/plugins/supabase.js +2 -2
  89. package/dist/cli/plugins/ui.d.ts +1 -1
  90. package/dist/cli/plugins/ui.js +1 -1
  91. package/dist/{client-subject-v89t811z.d.ts → client-subject-xCSkKD1C.d.ts} +2 -2
  92. package/dist/cloud/index.d.ts +8 -8
  93. package/dist/cloud/index.js +1 -1
  94. package/dist/{cloud-D3c4zhYr.js → cloud-DW3q3qnp.js} +3 -3
  95. package/dist/{codemod-BLTuDxFa.js → codemod-CF7NNDzA.js} +616 -392
  96. package/dist/codemod-DVDMFsTX.js +75 -0
  97. package/dist/{collect-BYPq-0JU.js → collect-CE5wK0AX.js} +3 -3
  98. package/dist/collect-CIdE3FGC.js +1 -0
  99. package/dist/{collect-BOh9Pxob.js → collect-CPimbkC5.js} +3 -3
  100. package/dist/compare-8SNJN-9U.js +12 -0
  101. package/dist/compile/index.d.ts +1 -1
  102. package/dist/{compile-B9SZiEnG.js → compile-BXKYYmT1.js} +19 -23
  103. package/dist/{compile-D8c1nFGy.d.ts → compile-tG1zkSgX.d.ts} +3 -3
  104. package/dist/{completion-CVTgFKK6.js → completion-B59uPAnZ.js} +2 -2
  105. package/dist/config-7QvEq57a.js +521 -0
  106. package/dist/{config-ClUStKUe.js → config-VCa1RLUe.js} +2 -2
  107. package/dist/config-paths-CQvGng3k.js +136 -0
  108. package/dist/{config-report-GJmQMf2K.js → config-report-CjvA6lGI.js} +7 -2
  109. package/dist/{config-shape-B6tdyBju.js → config-shape-BTojaD-H.js} +9 -2
  110. package/dist/{context-BdoA9DhS.js → context-BQHKgT1m.js} +2 -2
  111. package/dist/context-CAFddgb9.js +35 -0
  112. package/dist/convex/index.d.ts +5 -5
  113. package/dist/convex/index.js +2 -2
  114. package/dist/{core-tEfD0lwu.js → core-C5yCD-Ls.js} +6 -6
  115. package/dist/{core-CnC47rSf.d.ts → core-bf8qgaZf.d.ts} +3 -3
  116. package/dist/{coverage-DL7JCZmb.d.ts → coverage-AOeWiQ7Z.d.ts} +2 -2
  117. package/dist/{coverage-nFSMjFxH.js → coverage-C3jVYC9Y.js} +1 -1
  118. package/dist/{create-sGl1ccTp.d.ts → create-B7Xa4jSQ.d.ts} +9 -9
  119. package/dist/{create-D3oXoXxM.js → create-COQVXK6C.js} +22 -6
  120. package/dist/{create-DeQ5t8mZ.d.ts → create-Cn5EpEez.d.ts} +5 -5
  121. package/dist/{create-BsRcXm_m.d.ts → create-DHA0fhmi.d.ts} +7 -7
  122. package/dist/{create-BAMPoEga.js → create-nOWD3Joc.js} +3 -3
  123. package/dist/{credential-ke0KMQeB.js → credential-D9in5keC.js} +3 -3
  124. package/dist/{credentials-DOeqknte.js → credentials-B-hsgB4W.js} +1 -1
  125. package/dist/{credentials-BfzdL5kv.d.ts → credentials-COT-cjnP.d.ts} +3 -3
  126. package/dist/custom-role-rebuild-BK73tPib.js +181 -0
  127. package/dist/deciding-columns-DBZsrpdD.js +60 -0
  128. package/dist/deferred-sink-BZahJ8sO.js +34 -0
  129. package/dist/{define-permdock-CIxHBykk.js → define-permdock-D7aKxIax.js} +4 -4
  130. package/dist/{define-permdock-BLpQ0m95.d.ts → define-permdock-DBgwTFi1.d.ts} +6 -6
  131. package/dist/{delegation-BaUNCrE_.js → delegation-0DVVomzu.js} +3 -3
  132. package/dist/delivery/index.d.ts +4 -4
  133. package/dist/delivery/index.js +1 -1
  134. package/dist/{denied-text-D6JJTDr3.d.ts → denied-text-C_AWc0f0.d.ts} +2 -2
  135. package/dist/{describe-lAafaRQQ.d.ts → describe-AdETpWsn.d.ts} +2 -2
  136. package/dist/{diff-CXRZ6qPa.js → diff-COdwpP31.js} +7 -7
  137. package/dist/{diff-Cv9inVY5.js → diff-CW9eZy9X.js} +2 -2
  138. package/dist/{doctor-CQoP1264.js → doctor-ELj5hrVv.js} +17 -5
  139. package/dist/{doctor-Bn2BTr0N.js → doctor-ervtBRzG.js} +1624 -322
  140. package/dist/drizzle/index.d.ts +3 -3
  141. package/dist/edits-CqU8s2GC.js +69 -0
  142. package/dist/elysia/index.d.ts +5 -5
  143. package/dist/elysia/index.js +3 -3
  144. package/dist/{errors-DUJ7wLlE.d.ts → errors-COoiWqIs.d.ts} +1 -1
  145. package/dist/{evaluate-D8SdfP3h.js → evaluate-Dmd0bShm.js} +30 -31
  146. package/dist/{evaluations-BQkpE7hC.js → evaluations-DPEAu_jM.js} +2 -2
  147. package/dist/{evaluations-K9qglDP7.d.ts → evaluations-GW9j_ARq.d.ts} +3 -3
  148. package/dist/evaluator-COmATWCr.js +2 -0
  149. package/dist/{evaluator-eager-UuJK6NX_.js → evaluator-eager-CpVYslzY.js} +1 -1
  150. package/dist/eve/index.d.ts +18 -8
  151. package/dist/eve/index.js +13 -15
  152. package/dist/{execute-BLM5tpRU.js → execute-ix7AAdWg.js} +17 -41
  153. package/dist/explain-DRC9V5Qb.js +37 -0
  154. package/dist/explain-jg0KLCVt.js +74 -0
  155. package/dist/express/index.d.ts +5 -5
  156. package/dist/express/index.js +3 -3
  157. package/dist/fastify/index.d.ts +5 -5
  158. package/dist/fastify/index.js +3 -3
  159. package/dist/{fetch-adapter-gmTCu4FR.d.ts → fetch-adapter-CJncmsPg.d.ts} +4 -4
  160. package/dist/{fetch-adapter-ovZdSvlT.js → fetch-adapter-CU1DIkXu.js} +3 -3
  161. package/dist/{fields-CViS0EPC.js → fields-y_PSRCyJ.js} +3 -2
  162. package/dist/{fixtures-Bm0G0A7H.js → fixtures-3aUUP6Nx.js} +1 -1
  163. package/dist/flags-DQzNPxg1.js +204 -0
  164. package/dist/{from-snapshot-CCDF_ihX.js → from-snapshot-DGc9W4QU.js} +7 -7
  165. package/dist/{gen-02p5oEol.js → gen-8rW_AUG5.js} +16 -12
  166. package/dist/gen-BtiGMiuH.js +1 -0
  167. package/dist/{gen-kind-BMwPHJZ0.js → gen-kind-C9ikF8nb.js} +1 -1
  168. package/dist/{generate-BVcwnfoI.js → generate-BmpCt5oi.js} +4 -4
  169. package/dist/{generate-BtstB6iV.js → generate-CW7gNfLr.js} +244 -158
  170. package/dist/{generate-options-Yfh1pGyX.js → generate-options-DiR4r_sk.js} +18 -189
  171. package/dist/{grantee-BPUG6f0r.js → grantee-BSCdpIF3.js} +1 -1
  172. package/dist/{grantee-match-CFQ-LRcL.js → grantee-match-CJgQmcx4.js} +1 -1
  173. package/dist/h3/index.d.ts +4 -4
  174. package/dist/h3/index.js +3 -3
  175. package/dist/helper-calls-DHvgN9tr.js +106 -0
  176. package/dist/{helpers-DSmj6SHi.js → helpers-COh0lLc1.js} +2 -2
  177. package/dist/hono/index.d.ts +5 -5
  178. package/dist/hono/index.js +3 -3
  179. package/dist/{hook-sql-55514A9t.js → hook-sql-D-abRHut.js} +47 -225
  180. package/dist/{hosted-DUbuh0Td.d.ts → hosted-Bkw3Oyh-.d.ts} +1 -1
  181. package/dist/{hosted-DMJKJPoc.js → hosted-DZwCFrcy.js} +5 -5
  182. package/dist/{import-HzsIBAa5.js → import-BAhoTYTk.js} +1 -1
  183. package/dist/{import-Cm8kuezl.js → import-D_8tLF9g.js} +30 -46
  184. package/dist/{index-BSJoxaOi.d.ts → index-DPVeDtAO.d.ts} +5 -5
  185. package/dist/{index-D1msamx_.d.ts → index-DT3hOxA7.d.ts} +83 -14
  186. package/dist/{index-DegTwZxD.d.ts → index-DWmIuQLz.d.ts} +5 -5
  187. package/dist/{index-eaNHkELi.d.ts → index-Kj5S3IWE.d.ts} +6 -6
  188. package/dist/{index-O0qbI8Ha.d.ts → index-WOx7TBbj.d.ts} +2 -2
  189. package/dist/{index-D8A1d_Tt.d.ts → index-xShPsK8G.d.ts} +2 -2
  190. package/dist/index.d.ts +18 -18
  191. package/dist/index.js +25 -24
  192. package/dist/{init-DvsMFuau.js → init-DkRHIe8-.js} +4 -4
  193. package/dist/{init-BklKWywy.js → init-zxb0BVDJ.js} +1 -1
  194. package/dist/{instance-options-B4MD2wgl.d.ts → instance-options-DQCiBBuz.d.ts} +1 -1
  195. package/dist/{instance-snapshot-DdGOpSfN.js → instance-snapshot-D9kjL37B.js} +37 -20
  196. package/dist/{interactive-only-C_olBCPl.js → interactive-only-Dqww0ABO.js} +22 -14
  197. package/dist/jwt/index.d.ts +17 -13
  198. package/dist/jwt/index.js +14 -5
  199. package/dist/{kernel-Dn6pKMAF.js → kernel-C5akxw5n.js} +7 -7
  200. package/dist/keys-DQsHrgBM.js +42 -0
  201. package/dist/kysely/index.d.ts +3 -3
  202. package/dist/{lazy-provider-C48LDq0q.d.ts → lazy-provider-CMgFAGf8.d.ts} +1 -1
  203. package/dist/{lazy-provider-CVX534Kk.js → lazy-provider-DNVjY4n3.js} +2 -2
  204. package/dist/load-BCABUQZi.js +1 -0
  205. package/dist/{load-CZnlAyZ8.js → load-m7jmit3y.js} +1 -1
  206. package/dist/{login-CuUf-syI.js → login-C1p3gmj8.js} +1 -1
  207. package/dist/{login-BFvEcFnI.js → login-DOEZveP6.js} +4 -4
  208. package/dist/manager-chain-DdkiCw5q.js +243 -0
  209. package/dist/{manifest-BYzJF6xk.js → manifest-31igzVGQ.js} +70 -38
  210. package/dist/{manifest-Ct3eXbLR.js → manifest-B487A3po.js} +1 -1
  211. package/dist/{manifest-CRHphHxo.d.ts → manifest-DgsxeAsM.d.ts} +76 -0
  212. package/dist/{manifest-schema-Bp-eFhNZ.js → manifest-schema-D7RQbnGY.js} +90 -1
  213. package/dist/{map-error-DTi_JZT8.js → map-error-DYQbf-3Q.js} +1 -1
  214. package/dist/{may-use-Died1tNU.js → may-use-4HzzgYJ3.js} +3 -3
  215. package/dist/mcp/index.d.ts +9 -9
  216. package/dist/mcp/index.js +4 -4
  217. package/dist/{membership-filter-CSKH48eD.js → membership-filter-C7ZuhAqJ.js} +1 -1
  218. package/dist/{migrate-BcBFWFt9.js → migrate-pg-lkbDu.js} +4 -16
  219. package/dist/model-BXhr8gUI.js +329 -0
  220. package/dist/{module-values-Ddx0GLaJ.js → module-values-B09BBJIj.js} +3 -3
  221. package/dist/nest/index.d.ts +5 -5
  222. package/dist/nest/index.js +3 -3
  223. package/dist/next/index.d.ts +29 -12
  224. package/dist/next/index.js +24 -26
  225. package/dist/next/plugin.d.ts +1 -1
  226. package/dist/next/plugin.js +1 -1
  227. package/dist/node/index.d.ts +5 -5
  228. package/dist/node/index.js +2 -2
  229. package/dist/openai/index.d.ts +5 -5
  230. package/dist/openai/index.js +3 -3
  231. package/dist/openapi/index.d.ts +4 -4
  232. package/dist/openapi/index.js +3 -3
  233. package/dist/{openapi-BwZABlQO.js → openapi-BeMVHVY4.js} +6 -6
  234. package/dist/{openapi-D2dmyWZK.js → openapi-CZu6sVsP.js} +1 -1
  235. package/dist/{openapi-DNZv-nDu.js → openapi-DEGesHWH.js} +11 -4
  236. package/dist/{openapi-document-DoIe4MrZ.js → openapi-document-CEQ6jqqR.js} +1 -1
  237. package/dist/{operations-BS8ExH5A.d.ts → operations-DaEoGpMV.d.ts} +1 -1
  238. package/dist/{operations-De3F7tlf.js → operations-dJxcshJZ.js} +1 -1
  239. package/dist/{operations-B0yO77Zz.js → operations-id4vhwFN.js} +9 -3
  240. package/dist/orpc/index.d.ts +7 -7
  241. package/dist/orpc/index.js +4 -4
  242. package/dist/otel/index.d.ts +3 -3
  243. package/dist/{output-BI85V6hu.js → output-C7EPeSZj.js} +19 -2
  244. package/dist/{output-files-D5D-8-4l.js → output-files-8lfALMSU.js} +143 -11
  245. package/dist/output-files-DKWhL1IE.js +1 -0
  246. package/dist/{ownership-mprXkEHG.js → ownership-Csk9C3Js.js} +10 -6
  247. package/dist/{parse-nfHSt1Wy.js → parse-CUqZ_lLC.js} +1 -1
  248. package/dist/{parse-local-manifest-BGLWVchi.d.ts → parse-local-manifest-B92rFWnk.d.ts} +1 -1
  249. package/dist/pdp/index.d.ts +3 -3
  250. package/dist/pdp/index.js +2 -2
  251. package/dist/{permdock-Dz3yzWrp.d.ts → permdock-BShHM8OJ.d.ts} +11 -5
  252. package/dist/{permdock-BueSeg7X.js → permdock-CJPIwU1T.js} +102 -55
  253. package/dist/{permission-registry-DMYRZVcn.js → permission-registry-DstT40VS.js} +31 -1
  254. package/dist/{permissions-CQW3cr2S.js → permissions-DJ_QV9L7.js} +1 -1
  255. package/dist/{permissions-DWULToSb.d.ts → permissions-UyQD5nRN.d.ts} +1 -1
  256. package/dist/{permissions-Bj3DRIEi.js → permissions-wEkTVr_I.js} +3 -3
  257. package/dist/{pg-CA651850.js → pg-DmS5ITHu.js} +20 -1
  258. package/dist/pg-DtiDogUp.js +1 -0
  259. package/dist/{pipeline-Ct3YEKjx.js → pipeline-Bbu7uw28.js} +103 -32
  260. package/dist/{plugin-zOs9uqQj.d.ts → plugin-L3G7jPGE.d.ts} +15 -4
  261. package/dist/{policy-DFD2J5o_.js → policy-BBvhhH9X.js} +4 -4
  262. package/dist/{policy-C-Lzp3Zh.d.ts → policy-BUtwixSN.d.ts} +2 -2
  263. package/dist/{policy-DfvOwgtX.js → policy-CSOOQ3rR.js} +3 -3
  264. package/dist/{policy-bundle-pwhJJv2-.js → policy-bundle-KYI0EnrM.js} +3 -3
  265. package/dist/{policy-from-catalog-YKaTeaco.js → policy-from-catalog-_zwn1sNj.js} +12 -9
  266. package/dist/{policy-types-93NwI8iI.d.ts → policy-types-CfW4X_yX.d.ts} +155 -19
  267. package/dist/{postgrest-DyrYo_XT.d.ts → postgrest-PQ3zAOD2.d.ts} +2 -2
  268. package/dist/powersync-C1ix7CEY.js +1 -0
  269. package/dist/{powersync-D1Aog89p.js → powersync-CGvu6j5U.js} +2 -2
  270. package/dist/{powersync-CkoImqoq.js → powersync-CM6Vg4RH.js} +65 -24
  271. package/dist/prisma/index.d.ts +2 -2
  272. package/dist/program-CvarkLMS.js +10 -0
  273. package/dist/{protected-action-Dco5O_Kc.js → protected-action-BPN0NaRb.js} +1 -1
  274. package/dist/{protected-action-CEzNNtfi.d.ts → protected-action-DhCQ4bSe.d.ts} +6 -6
  275. package/dist/{provider-BYcoTKuS.js → provider-1xqxLVEz.js} +2 -2
  276. package/dist/{provider-1yWthvi5.js → provider-BV_v0JAY.js} +457 -116
  277. package/dist/{provider-C48LDq0q.d.ts → provider-CMgFAGf8.d.ts} +1 -1
  278. package/dist/{provider-store-Dq_olUjC.js → provider-store-Cf8HRNtb.js} +3 -3
  279. package/dist/{provider-with-fxHItxDh.js → provider-with-cpL9vRjC.js} +2 -2
  280. package/dist/prune-config-CdoPJIGz.js +209 -0
  281. package/dist/{pull-DD6YQ42X.js → pull-BaB401Bk.js} +4 -4
  282. package/dist/pull-Bp63vtgu.js +1 -0
  283. package/dist/{push-N-QI_ArC.js → push-DcjvEj0m.js} +5 -5
  284. package/dist/{pushed-policy-rpB6k77P.js → pushed-policy-DSjSWEAl.js} +1 -1
  285. package/dist/{pushed-policy-APjMbYdV.d.ts → pushed-policy-DcvO8NXy.d.ts} +1 -1
  286. package/dist/{conditions-ChE7zxJI.js → rbac-mblGDx-Z.js} +227 -6
  287. package/dist/react/index.d.ts +6 -6
  288. package/dist/react/index.js +3 -3
  289. package/dist/react/lazy.d.ts +6 -6
  290. package/dist/react/lazy.js +3 -3
  291. package/dist/react/provider-client-lazy.d.ts +1 -1
  292. package/dist/react/provider-client-lazy.js +1 -1
  293. package/dist/react/provider-client.d.ts +1 -1
  294. package/dist/react/provider-client.js +1 -1
  295. package/dist/react-native/index.d.ts +9 -9
  296. package/dist/react-native/index.js +8 -8
  297. package/dist/rename-BZNOV8H9.js +437 -0
  298. package/dist/replay-BCOZifwx.d.ts +3 -0
  299. package/dist/report-DCAiUc5U.js +1 -0
  300. package/dist/report-DievqWhf.js +368 -0
  301. package/dist/{request-context-CVJodWx8.js → request-context-BNVY3kZ1.js} +1 -1
  302. package/dist/resend/index.d.ts +4 -4
  303. package/dist/resolve-config-9NYYVc30.js +238 -0
  304. package/dist/{resolve-names-B0cqvJxo.js → resolve-names-Cth1UQ-8.js} +5 -5
  305. package/dist/{resolver-4qxIIHcC.js → resolver-CuIY8aFD.js} +48 -30
  306. package/dist/{retire-BNiXnbBR.js → retire-FN4aY6-n.js} +1 -1
  307. package/dist/{rls-oLdqutBO.js → rls-BtkZgaZp.js} +33 -5
  308. package/dist/{rls-c0Z9lbyp.js → rls-DUYok5e9.js} +231 -40
  309. package/dist/{rls-files-Dhtn_6LH.js → rls-files-ucAI0J5j.js} +3 -3
  310. package/dist/{rls-options-BZxfMDFo.d.ts → rls-options-BFGRmdcH.d.ts} +1 -1
  311. package/dist/{role-builder-DhsGEVq-.js → role-builder-BksM3Q9O.js} +3 -3
  312. package/dist/{roles-B29psCem.js → roles-BeNEhv7Q.js} +2 -2
  313. package/dist/{rpc-DjgxFbjK.d.ts → rpc-COnquydd.d.ts} +2 -2
  314. package/dist/{rpc-B-4IZOiU.js → rpc-D7G7IJDa.js} +1 -1
  315. package/dist/run-BjMxYYTe.js +1 -0
  316. package/dist/{run-DkviX16y.js → run-WIqPbnjD.js} +12 -11
  317. package/dist/{run-ticket-DXwrko2J.d.ts → run-ticket-Mmor5sYW.d.ts} +2 -2
  318. package/dist/{saas-CUwmgUB8.js → saas-DcqUkynn.js} +5 -5
  319. package/dist/{scan-CNhvy39j.js → scan-Badcllgg.js} +1 -1
  320. package/dist/{schema-BeY3croo.js → schema-D2OK4RrB.js} +1 -0
  321. package/dist/{schema-CwNjlLBx.js → schema-DBRKgQb4.js} +1 -1
  322. package/dist/schema-tables-Ba9LE_XB.js +185 -0
  323. package/dist/scim/index.d.ts +1 -1
  324. package/dist/seeds/index.d.ts +1 -1
  325. package/dist/seeds/index.js +1 -1
  326. package/dist/{seeds-BDTG7xl-.js → seeds-Bs44UDS3.js} +1 -1
  327. package/dist/{seeds-uG196Ev4.d.ts → seeds-Cih1ztkf.d.ts} +2 -2
  328. package/dist/server/index.d.ts +13 -12
  329. package/dist/server/index.js +7 -6
  330. package/dist/{server-Co9CYGqk.js → server-lohbasQd.js} +2 -2
  331. package/dist/{server-types-BrHOGAYx.d.ts → server-types-C2XX60aF.d.ts} +16 -9
  332. package/dist/shared-C6_T7QUo.js +76 -0
  333. package/dist/{sink-BD34OS8T.d.ts → sink-BQ_6K81r.d.ts} +4 -4
  334. package/dist/{size-BqLd5oJ4.js → size-l1pDHE2z.js} +28 -5
  335. package/dist/{skills-DrY6VdtH.js → skills-Ba9hHGO6.js} +2 -2
  336. package/dist/{skills-B74k44ml.js → skills-CTKq3o8D.js} +2 -2
  337. package/dist/{snapshot-DckMnHk8.js → snapshot-Ty0uk9wZ.js} +46 -12
  338. package/dist/{snapshot-cache-DoP3avLl.d.ts → snapshot-cache-DGvLQW0-.d.ts} +1 -1
  339. package/dist/snapshot-compact-yXFxZLPo.js +596 -0
  340. package/dist/{snapshot-empty-DZ6sZ83n.js → snapshot-empty-pKgPDcLd.js} +1 -1
  341. package/dist/{snapshot-evaluate-9RGy7J3N.js → snapshot-evaluate-DSNj2rhV.js} +5 -4
  342. package/dist/{snapshot-reads-D775amTL.js → snapshot-reads-BnAHiuoa.js} +2 -2
  343. package/dist/snapshot-requires-DfUqCLEb.js +122 -0
  344. package/dist/{snapshot-size-CHig-Nq_.js → snapshot-size-2fkXbCkP.js} +5 -15
  345. package/dist/snapshot-size-DNY1MTsV.js +1 -0
  346. package/dist/solid/index.d.ts +6 -6
  347. package/dist/solid/index.js +2 -2
  348. package/dist/solid-start/index.d.ts +6 -6
  349. package/dist/solid-start/index.js +3 -3
  350. package/dist/{sources-NQio1yFq.d.ts → sources-CjgZns7t.d.ts} +2 -2
  351. package/dist/{src-BAYcigFU.js → src-HRYn4UFj.js} +148 -15
  352. package/dist/ssf/index.d.ts +3 -3
  353. package/dist/ssf/index.js +1 -1
  354. package/dist/{standard-webhooks-B3MQihcP.d.ts → standard-webhooks-Bnnrqa6d.d.ts} +2 -2
  355. package/dist/{store-core-DyNo_BwA.d.ts → store-core-BdFcruPm.d.ts} +5 -5
  356. package/dist/{store-AH8bmaxW.js → store-n3yEN7dt.js} +2 -2
  357. package/dist/{store-options-BtHrfJUU.js → store-options-DpCQo0vB.js} +21 -12
  358. package/dist/{stores-DyFCruRC.d.ts → stores-D6MIjN_-.d.ts} +6 -6
  359. package/dist/{stores-BIMyclLg.js → stores-KpBCaY6c.js} +1 -1
  360. package/dist/{shared-Cwxy5N16.js → subject-CrldGifz.js} +1 -75
  361. package/dist/{subject-cache-BZeSj4Xf.d.ts → subject-cache-CnJcz2K_.d.ts} +14 -6
  362. package/dist/supabase/index.d.ts +9 -9
  363. package/dist/supabase/index.js +4 -4
  364. package/dist/supabase/middleware.d.ts +14 -7
  365. package/dist/supabase/middleware.js +17 -6
  366. package/dist/{supabase-CakrAxMg.js → supabase-CGiB83XQ.js} +2 -2
  367. package/dist/supabase-dir-0lxKbrYu.js +41 -0
  368. package/dist/supabase-hook-CluYxKee.js +2 -0
  369. package/dist/{supabase-hook-0q6ohTVN.js → supabase-hook-CqO_0Koh.js} +14 -9
  370. package/dist/{supabase-BzK3lplm.js → supabase-kWQlkrHw.js} +4 -4
  371. package/dist/{supabase-config-B2sDFiwy.js → supabase-schemas-BglbAG2Z.js} +223 -34
  372. package/dist/{supautils-DXzJ2E2Q.js → supautils-C85NuESf.js} +2 -2
  373. package/dist/{support-session-B8xrW28B.js → support-session-DpzcGTuV.js} +1 -1
  374. package/dist/svelte/index.d.ts +5 -5
  375. package/dist/svelte/index.js +3 -3
  376. package/dist/svelte/runtime.d.ts +3 -3
  377. package/dist/svelte/runtime.js +1 -1
  378. package/dist/svelte/source.d.ts +5 -5
  379. package/dist/svelte/source.js +2 -2
  380. package/dist/sveltekit/index.d.ts +6 -6
  381. package/dist/sveltekit/index.js +2 -2
  382. package/dist/table-reads-AnHPrBp8.js +517 -0
  383. package/dist/table-reads-BviGc0L_.js +1 -0
  384. package/dist/{tables-BDqfipr1.js → tables-CDq0HVVq.js} +82 -26
  385. package/dist/tanstack-start/index.d.ts +6 -6
  386. package/dist/tanstack-start/index.js +2 -2
  387. package/dist/tenant-check-D7g9oNVH.js +105 -0
  388. package/dist/tenant-from-path-AKTSY7uR.js +65 -0
  389. package/dist/tenant-from-path-Dq3jkqjh.d.ts +25 -0
  390. package/dist/terminal/index.d.ts +6 -6
  391. package/dist/terminal/index.js +4 -4
  392. package/dist/testing/core.d.ts +1 -1
  393. package/dist/testing/core.js +1 -1
  394. package/dist/testing/fixtures/index.d.ts +5 -5
  395. package/dist/testing/fixtures/index.js +67 -3
  396. package/dist/testing/index.d.ts +31 -30
  397. package/dist/testing/index.js +51 -45
  398. package/dist/testing/saas/index.d.ts +5 -5
  399. package/dist/testing/saas/index.js +2 -2
  400. package/dist/testing/saas/permissions.d.ts +1 -1
  401. package/dist/testing/saas/permissions.js +1 -1
  402. package/dist/trpc/index.d.ts +6 -6
  403. package/dist/trpc/index.js +3 -3
  404. package/dist/{type-helpers-DHCQEPj8.d.ts → type-helpers-CUmJFGV6.d.ts} +3 -3
  405. package/dist/{types-PS10T9UK.d.ts → types-BKnUwgvx.d.ts} +5 -5
  406. package/dist/{types-CQF-oYSz.d.ts → types-BRECeQ2n.d.ts} +4 -4
  407. package/dist/{types-OzSal_K_.d.ts → types-BhBfMdQ5.d.ts} +3 -3
  408. package/dist/{types-DONLJQjY.d.ts → types-BsRf5rKk.d.ts} +3 -3
  409. package/dist/{types-Cakw89Wx.d.ts → types-CIzXPPV-.d.ts} +2 -2
  410. package/dist/{types-CWmBZtQN.d.ts → types-CbJ5mxXv.d.ts} +7 -2
  411. package/dist/{types-4wjWMSFM.d.ts → types-CjZscT16.d.ts} +4 -4
  412. package/dist/{types-XSfi6ihL.d.ts → types-DwoRXDvN.d.ts} +2 -2
  413. package/dist/{types-config-Cq72dArb.d.ts → types-config-DNIw_Gt5.d.ts} +82 -17
  414. package/dist/{types-BFtFaI1W.d.ts → types-euUv1wsO.d.ts} +1 -1
  415. package/dist/{types-D3tjoLwT.d.ts → types-h9W3CNC_.d.ts} +5 -5
  416. package/dist/{types-run-DG1H5vrX.d.ts → types-run-Bwn1MuW0.d.ts} +1 -1
  417. package/dist/{types-BdNdMix7.d.ts → types-vKKndyxx.d.ts} +2 -2
  418. package/dist/unplugin/index.d.ts +1 -1
  419. package/dist/unplugin/index.js +1 -1
  420. package/dist/{usage-DEUKhZ1n.js → usage-CW6xhRcV.js} +7 -235
  421. package/dist/usage-Ci7Glu-H.js +1 -0
  422. package/dist/{usage-B-xheuEq.js → usage-n4V2k_a6.js} +2 -2
  423. package/dist/{validation-error-BAO1W1yk.d.ts → validation-error-P4Z9HUuP.d.ts} +1 -1
  424. package/dist/{verify-BgZapMKs.js → verify-CKzngsUH.js} +16 -104
  425. package/dist/{version-cache-BXkl7-Fz.js → version-cache-BzK8dwJy.js} +14 -10
  426. package/dist/{vocabulary-FYgI_NoI.d.ts → vocabulary-DHfKPIC5.d.ts} +7 -0
  427. package/dist/vue/index.d.ts +6 -6
  428. package/dist/vue/index.js +2 -2
  429. package/dist/{waiter-hYLJXA7r.d.ts → waiter-BqUxSRxq.d.ts} +2 -2
  430. package/dist/warm-5yxlUmBh.js +32 -0
  431. package/dist/warm-BR-mrnY-.d.ts +16 -0
  432. package/dist/{watch-Bz_iEKlB.js → watch-C12Ub7x4.js} +11 -14
  433. package/dist/{watch-BNxvqCS4.js → watch-D-5ztqN8.js} +2 -2
  434. package/dist/watch-J1PfGMfb.js +1 -0
  435. package/dist/webmcp/index.d.ts +2 -2
  436. package/dist/webmcp/index.js +2 -2
  437. package/dist/{who-can-rUSZfLvI.js → who-can-CGVpM3fZ.js} +3 -3
  438. package/dist/workflow/index.d.ts +3 -3
  439. package/dist/workflow/index.js +4 -4
  440. package/dist/workflow-sdk/index.d.ts +17 -5
  441. package/dist/workflow-sdk/index.js +3 -1
  442. package/dist/{wrap-D-KvhzaC.d.ts → wrap-D8WtzrB7.d.ts} +2 -2
  443. package/package.json +20 -16
  444. package/schemas/catalog-v2.json +6 -0
  445. package/schemas/snapshot-v2.json +557 -0
  446. package/schemas/supabase-manifest-v1.json +156 -15
  447. package/skills/permdock/SKILL.md +1 -1
  448. package/skills/permdock-agents/references/runtimes.md +1 -1
  449. package/skills/permdock-credentials/references/tokens-keys-links.md +1 -1
  450. package/skills/permdock-data/references/queries-and-rls.md +2 -2
  451. package/skills/permdock-tenancy/SKILL.md +4 -4
  452. package/skills/permdock-tenancy/references/ownership-and-custom-roles.md +1 -1
  453. package/dist/annotate-routes-BvSuEht3.js +0 -75
  454. package/dist/annotate-uZVGIRym.js +0 -25
  455. package/dist/better-supabase-DSbs4MtQ.js +0 -201
  456. package/dist/catalog-DCjJIl3n.js +0 -1
  457. package/dist/claims-size-DcjhvUv5.js +0 -58
  458. package/dist/codemod-Ob71iPQh.js +0 -35
  459. package/dist/collect-XcoQRyiA.js +0 -1
  460. package/dist/config-iyy90IOU.js +0 -143
  461. package/dist/deciding-columns-BnglEKqU.js +0 -143
  462. package/dist/evaluator-Dlhn2d7D.js +0 -2
  463. package/dist/flags-C0e-BzGW.js +0 -112
  464. package/dist/gen-C_RJoGZB.js +0 -1
  465. package/dist/grants-Dn6zwfqo.js +0 -139
  466. package/dist/load-BPzIqlGB.js +0 -1
  467. package/dist/model-B0rrUh6J.js +0 -188
  468. package/dist/output-files-aPXXhV4q.js +0 -1
  469. package/dist/powersync-f-6y8sCk.js +0 -1
  470. package/dist/pull-CT7wu2uo.js +0 -1
  471. package/dist/rbac-BJTUGJum.js +0 -90
  472. package/dist/replay-ClGIMp5p.d.ts +0 -3
  473. package/dist/run-DKUZT8Cc.js +0 -1
  474. package/dist/snapshot-compact-CwAop_6C.js +0 -119
  475. package/dist/snapshot-size-B_chu2c1.js +0 -1
  476. package/dist/supabase-hook-CcmjiBsh.js +0 -2
  477. package/dist/usage-BRjoZ-vo.js +0 -1
  478. package/dist/watch-CGLmIdld.js +0 -1
  479. package/schemas/snapshot-v1.json +0 -329
@@ -1,66 +1,85 @@
1
1
  import { c as rootScope, d as scopeList, o as normalizeMemberships, s as resolveScope } from "./scopes-B-KX9EI8.js";
2
2
  import { r as supabaseTenantClaim } from "./budget-BH81q2cj.js";
3
- import { r as runCollect } from "./collect-BOh9Pxob.js";
4
- import { t as didYouMean } from "./args-Bc0HLiD4.js";
5
- import { t as DOCS_BASE } from "./manifest-BYzJF6xk.js";
6
- import { a as nonEmptyOr, r as findingOf } from "./output-BI85V6hu.js";
3
+ import { r as runCollect } from "./collect-CPimbkC5.js";
4
+ import { t as didYouMean } from "./args-BSpXxMnb.js";
5
+ import { t as DOCS_BASE } from "./manifest-31igzVGQ.js";
6
+ import { o as nonEmptyOr, r as findingOf } from "./output-C7EPeSZj.js";
7
7
  import { t as createStyle } from "./style-CQDaLJtP.js";
8
8
  import { i as DOCTOR_REPORT_SCHEMA } from "./version-D-jWyJb9.js";
9
9
  import { a as rel, n as doctorSrcPath, o as sqlFiles$1, r as listSourceFiles } from "./files-DAR51W3J.js";
10
- import { n as pgConnector } from "./pg-CA651850.js";
11
- import { a as describeError, i as configError } from "./errors-DgLOqc6j.js";
12
- import { a as betterSupabaseInstalled, c as workspaceDirs, d as readJson, i as betterSupabaseDefaults, l as filesOf, n as betterSupabaseAuthzVersions, o as betterSupabaseTenantClaim, r as betterSupabaseConfig, t as BETTER_SUPABASE_AUTHZ_TOPIC, u as nodeFiles } from "./better-supabase-DSbs4MtQ.js";
13
- import { a as loadModule, i as loadConfiguredPolicy, n as asPolicy, s as pickNamed } from "./load-CZnlAyZ8.js";
14
- import { i as runSkillsInstall } from "./skills-B74k44ml.js";
15
- import { a as supabaseConfig, i as readSupabaseConfig, n as pd045, r as pd074 } from "./supabase-config-B2sDFiwy.js";
16
- import { d as activeSource, g as attrsPlan, i as supabaseHookManifest, n as hooklessDatabase, p as resolveSchemas, r as supabaseDatabaseManifest } from "./hook-sql-55514A9t.js";
17
- import { i as pd039, t as hookOut } from "./supabase-hook-0q6ohTVN.js";
18
- import { c as outFiles } from "./output-files-D5D-8-4l.js";
19
- import { a as guardedTables, r as unsatisfiedKinds, t as ownershipRules } from "./ownership-mprXkEHG.js";
10
+ import { r as pgConnector } from "./pg-DmS5ITHu.js";
11
+ import { a as describeError, n as CliError } from "./errors-DgLOqc6j.js";
12
+ import { S as restatedFacts, _ as workspaceDirs, b as readJson, d as betterSupabaseAuthzVersions, f as betterSupabaseConfig, g as betterSupabaseTenantClaim, h as betterSupabaseInstalled, m as betterSupabaseDefaults, o as readParsedConfig, p as betterSupabaseConfigPath, t as configFileIn, u as BETTER_SUPABASE_AUTHZ_TOPIC, v as filesOf, x as membershipDisagreements, y as nodeFiles } from "./config-7QvEq57a.js";
13
+ import { a as loadModule, i as loadConfiguredPolicy, n as asPolicy, s as pickNamed } from "./load-m7jmit3y.js";
14
+ import { i as runSkillsInstall } from "./skills-CTKq3o8D.js";
15
+ import { i as withSchemaDefaults, n as schemaDefaults, r as schemaTables } from "./schema-tables-Ba9LE_XB.js";
16
+ import { a as pd074, c as readSupabaseConfig, i as pd045, l as supabaseConfig, n as resolveSchemas, o as pd127, s as pd136, u as supabaseConfigName } from "./supabase-schemas-BglbAG2Z.js";
17
+ import { d as activeSource, i as supabaseHookManifest, n as hooklessDatabase, p as attrsPlan, r as supabaseDatabaseManifest } from "./hook-sql-D-abRHut.js";
18
+ import { i as pd039, t as hookOut } from "./supabase-hook-CqO_0Koh.js";
19
+ import { t as parseCatalog } from "./parse-CUqZ_lLC.js";
20
+ import { t as catalogPath } from "./catalog-path-bG0XxHMu.js";
21
+ import { n as bsbActions, t as answerOf } from "./bsb-actions-BHiyBxQZ.js";
22
+ import { c as outFiles } from "./output-files-8lfALMSU.js";
23
+ import { a as guardedTables, r as unsatisfiedKinds, t as ownershipRules } from "./ownership-Csk9C3Js.js";
20
24
  import { n as MIGRATION_DIRS, t as DEFAULT_SENSITIVE_ACTIONS } from "./constants-PCJiir_3.js";
21
- import { i as group, n as membershipColumns, o as sqlStatements, r as tableKey } from "./deciding-columns-BnglEKqU.js";
25
+ import { n as membershipColumns, r as tableKey } from "./deciding-columns-DBZsrpdD.js";
26
+ import { a as parseSqlFile, c as readPolicy$1, d as sqlCalls, f as stringValues, h as sqlStatements, l as readRelation, o as parseSqlLenient, p as group, r as functionArgTypes, s as parseSqlStatements, t as SqlSyntaxError } from "./ast-Dnm2TOHN.js";
27
+ import { t as applyFiles } from "./files-DuV7wRim.js";
28
+ import { o as splitIgnored } from "./verify-CKzngsUH.js";
29
+ import { a as updatedBaseline, i as readBaseline, n as baselineText, t as applyBaseline } from "./baseline-file-BQoki1O_.js";
30
+ import { n as activeTenantMismatch, t as authorizationProvider } from "./provider-BV_v0JAY.js";
22
31
  import { r as isRecord } from "./compact-C4LFuqbW.js";
23
- import { d as rowConditionMessage, f as parseIgnores, p as splitIgnored, s as ROW_CONDITION_FIX, u as helperTablePolicies } from "./verify-BgZapMKs.js";
24
- import { n as activeTenantMismatch, t as authorizationProvider } from "./provider-1yWthvi5.js";
25
- import { t as parseCatalog } from "./parse-nfHSt1Wy.js";
26
32
  import "./authz-topic-D8x24Jv-.js";
27
- import { t as catalogPath } from "./catalog-path-bG0XxHMu.js";
33
+ import { n as budgetBreaches, r as snapshotProbeOptions, t as breachText } from "./budgets-Dpumu_Dt.js";
34
+ import { a as nameOf, i as lineIndex, o as nodes, r as child, u as walk } from "./ast-CAOxvn9t.js";
35
+ import { r as parseSync, t as createVisitor } from "./optional-CaQWp9HA.js";
28
36
  import { t as canonicalJson } from "./canonical-json-BibZkXtE.js";
29
- import { c as jsonSchemaOf, i as catalogOAuthScopes } from "./catalog-doc-Bp5khmCG.js";
30
- import { a as pd010, c as pd014, d as pd038, f as pd041, i as pd008, l as pd015, n as pd001, o as pd011, p as pd057, r as pd007, s as pd013, t as runUsage, u as pd036 } from "./usage-DEUKhZ1n.js";
31
- import { c as listPermissions, h as formerKeys } from "./permission-registry-DMYRZVcn.js";
32
- import { t as resolveNames } from "./resolve-names-B0cqvJxo.js";
37
+ import { c as jsonSchemaOf, i as catalogOAuthScopes } from "./catalog-doc-D4g3nyFB.js";
38
+ import { a as pd015, i as pd014, n as ADAPTER_SPECIFIERS, o as runtimeSpecifiers, r as pd001, t as runUsage } from "./usage-CW6xhRcV.js";
39
+ import { c as listPermissions, h as formerKeys } from "./permission-registry-DstT40VS.js";
40
+ import { t as resolveNames } from "./resolve-names-Cth1UQ-8.js";
33
41
  import "./markers-C-kThnKN.js";
34
42
  import { i as qualifySqlTable, s as quoteSqlLiteral } from "./sql-T4GaBh9X.js";
35
- import { s as parseCredential } from "./credential-ke0KMQeB.js";
36
- import { u as separationConflicts } from "./policy-DFD2J5o_.js";
37
- import { T as validateCustomRole } from "./evaluate-D8SdfP3h.js";
43
+ import { s as parseCredential } from "./credential-D9in5keC.js";
44
+ import { u as separationConflicts } from "./policy-BBvhhH9X.js";
45
+ import { O as validateCustomRole } from "./evaluate-Dmd0bShm.js";
38
46
  import { d as keptKeys, r as PERMDOCK_SCHEMA } from "./sources-DnjJPGfb.js";
39
47
  import { a as quoteIdent } from "./quote-BKrTBbcH.js";
48
+ import { t as configProperty } from "./config-paths-CQvGng3k.js";
40
49
  import { o as hasConditionOp, u as isSqlFunctionField } from "./refs-Cix9Zjis.js";
41
- import { o as flattenGrantee } from "./grantee-BPUG6f0r.js";
50
+ import { o as flattenGrantee } from "./grantee-BSCdpIF3.js";
42
51
  import { u as isPrincipalRelation } from "./resource-relations-Ck5sjYQR.js";
43
- import { t as operationCoverage } from "./coverage-nFSMjFxH.js";
44
- import { r as parseSync, t as createVisitor } from "./optional-CaQWp9HA.js";
45
- import { i as snapshotSize, n as mostPrivilegedRole, t as SNAPSHOT_BUDGET_BYTES } from "./snapshot-size-CHig-Nq_.js";
52
+ import { t as operationCoverage } from "./coverage-C3jVYC9Y.js";
53
+ import { a as snapshotSize, r as mostPrivilegedRole, t as SNAPSHOT_BUDGET_BYTES } from "./snapshot-size-2fkXbCkP.js";
54
+ import { a as taggedPolicyId, o as taggedPolicyIds } from "./bsb-access-Bcw6GrQm.js";
46
55
  import { t as membershipSourcesOf } from "./sources-BbSUNmFX.js";
47
- import { n as pd110, r as pd114, t as pd109 } from "./perf-token-dFGVP14-.js";
56
+ import { a as ownedObjects, i as inReservedDir, o as shownKey, r as generatedByPermdock, s as withoutOwned, t as policyModel } from "./model-BXhr8gUI.js";
57
+ import { a as pd114, i as pd110, r as pd109 } from "./claims-size-BsSDVD5u.js";
58
+ import { t as importFromApp } from "./app-peer-BnMh5lqz.js";
59
+ import { c as rlsReport, o as policiesFor } from "./report-DievqWhf.js";
48
60
  import { a as scopeMembershipTable } from "./compile-BUKXrueE.js";
49
- import { t as policyModel } from "./model-B0rrUh6J.js";
50
- import { a as roleSources, i as powersyncOut, n as staleFiles, o as scopeSourcesOf, r as powersyncFiles, s as streamOf } from "./powersync-CkoImqoq.js";
51
- import { t as FIELD_VIEWS } from "./fields-CViS0EPC.js";
61
+ import { a as powersyncOut, c as streamOf, i as powersyncFiles, n as staleFiles, o as roleSources, s as scopeSourcesOf } from "./powersync-CM6Vg4RH.js";
62
+ import { t as parseProgram } from "./program-CvarkLMS.js";
63
+ import { t as FIELD_VIEWS } from "./fields-y_PSRCyJ.js";
64
+ import { n as restatedDefaults } from "./resolve-config-9NYYVc30.js";
52
65
  import { t as policyRowConditionKeys } from "./row-conditions-DwIJocfQ.js";
53
- import { J as policyBundle, Q as graphPlan, i as tableNames, r as tableNameOf } from "./tables-BDqfipr1.js";
54
- import { H as byKey, K as graphSqlName } from "./interactive-only-C_olBCPl.js";
55
- import { i as tableFor, n as compileGrants, t as commandFor } from "./compile-B9SZiEnG.js";
56
- import { r as contextRefs } from "./conditions-ChE7zxJI.js";
57
- import { t as CUSTOM_ROLES } from "./shared-Cwxy5N16.js";
58
- import { n as isSeeds } from "./seeds-BDTG7xl-.js";
66
+ import { J as policyBundle, Q as graphPlan, i as tableNames, r as tableNameOf } from "./tables-CDq0HVVq.js";
67
+ import { n as byKey } from "./compare-8SNJN-9U.js";
68
+ import { a as tableFor, n as commandFor, o as unmappedActions, r as compileGrants, t as INFERRED_VERBS } from "./compile-BXKYYmT1.js";
69
+ import { p as contextRefs } from "./rbac-mblGDx-Z.js";
70
+ import { c as rowConditionMessage, o as helperTablePolicies, r as ROW_CONDITION_FIX } from "./helper-calls-DHvgN9tr.js";
71
+ import { K as graphSqlName } from "./interactive-only-Dqww0ABO.js";
72
+ import { t as CUSTOM_ROLES } from "./shared-C6_T7QUo.js";
73
+ import { n as isSeeds } from "./seeds-Bs44UDS3.js";
59
74
  import { r as FIXTURES_PATH, s as seedPathsLine } from "./seed-sql-CjF7u0aX.js";
60
- import { i as buildContext, n as isRefusal, o as inheritTargets, t as generateOptions } from "./generate-options-Yfh1pGyX.js";
61
- import { n as legacyHelperNames, r as retirePlan, t as legacyHelperCalls } from "./retire-BNiXnbBR.js";
62
- import { t as supautilsRejections } from "./supautils-DXzJ2E2Q.js";
75
+ import { i as buildContext, n as isRefusal, o as inheritTargets, t as generateOptions } from "./generate-options-DiR4r_sk.js";
76
+ import { n as propertyKey } from "./edits-CqU8s2GC.js";
77
+ import { n as legacyHelperNames, r as retirePlan, t as legacyHelperCalls } from "./retire-FN4aY6-n.js";
78
+ import { t as supautilsRejections } from "./supautils-C85NuESf.js";
79
+ import { t as MANIFEST_FILE } from "./manifest-json-DMaBWmcG.js";
80
+ import { o as sharedFunctionsOf, r as manifestTableReads, t as committedManifest } from "./table-reads-AnHPrBp8.js";
63
81
  import { isDeepStrictEqual } from "node:util";
82
+ import { readFileSync } from "node:fs";
64
83
  import { dirname, join, resolve } from "node:path";
65
84
  import { pathToFileURL } from "node:url";
66
85
  import { createRequire } from "node:module";
@@ -125,6 +144,66 @@ async function readPolicy(cwd, path) {
125
144
  };
126
145
  }
127
146
  }
147
+ // src/cli/doctor/action-keys.ts
148
+ function catalogKeys(input) {
149
+ const files = filesOf(input);
150
+ const path = catalogPath(input.config, input.cwd);
151
+ if (!files.exists(path)) return void 0;
152
+ try {
153
+ return new Set(parseCatalog(files.read(path)).permissions.map(({ key }) => key));
154
+ } catch {
155
+ return;
156
+ }
157
+ }
158
+ /**
159
+ * PD123: an action better-supabase checks with the key its block derives,
160
+ * because neither the config nor the provider's `actionKeys` names one, while
161
+ * the catalog lacks that key. No role holds it, so the action is denied for
162
+ * everyone. The actions come from `listActions` in the project's
163
+ * `better-supabase/sql`; a project without better-supabase, a catalog or a
164
+ * config has nothing to check.
165
+ */
166
+ async function pd123(input) {
167
+ const path = betterSupabaseConfigPath({
168
+ cwd: input.cwd,
169
+ ...input.files === void 0 ? {} : { files: input.files },
170
+ ...input.config.betterSupabase?.config === void 0 ? {} : { path: input.config.betterSupabase.config }
171
+ });
172
+ if (path === void 0) return [];
173
+ const declared = catalogKeys(input);
174
+ if (declared === void 0) return [];
175
+ const listed = await bsbActions(input.cwd, path);
176
+ switch (listed.kind) {
177
+ case "missing": return [];
178
+ case "old": return [{
179
+ code: "PD123",
180
+ severity: "warning",
181
+ message: "the installed better-supabase has no listActions in better-supabase/sql, so PermDock cannot list the actions its blocks, record types, buckets and topics check",
182
+ fix: "install better-supabase 0.84.0 or later"
183
+ }];
184
+ case "invalid": return [{
185
+ code: "PD123",
186
+ severity: "warning",
187
+ target: rel(input.cwd, path),
188
+ message: `better-supabase refused ${rel(input.cwd, path)}, so PermDock cannot list the actions it checks: ${listed.message}`,
189
+ fix: "fix the config until better-supabase check passes"
190
+ }];
191
+ case "actions": {
192
+ const catalog = rel(input.cwd, catalogPath(input.config, input.cwd));
193
+ return listed.actions.filter((action) => action.source === "default" && (action.key === null || !declared.has(action.key))).map((action) => {
194
+ const answer = answerOf(action);
195
+ return {
196
+ code: "PD123",
197
+ severity: "error",
198
+ target: answer,
199
+ message: action.key === null ? `${answer} has no permission key: neither the config, the provider's actionKeys nor the block names one, so better-supabase denies it` : `${answer} checks ${action.key}, the key its block derives, which ${catalog} does not list, so no role holds it and better-supabase denies it`,
200
+ fix: `add "${answer}" to meta.answers of the action that decides it and run permdock collect, or declare ${action.key ?? "the key"} in the policy`
201
+ };
202
+ });
203
+ }
204
+ default: return listed;
205
+ }
206
+ }
128
207
  // src/cli/doctor/inputs.ts
129
208
  /** The configured policy, through the project's memoised load when there is one. */
130
209
  function policyOf(input) {
@@ -235,49 +314,53 @@ function reported(finding) {
235
314
  };
236
315
  }
237
316
  /**
238
- * PD017 waivers, keyed by finding id. A waiver that matches nothing stays a
239
- * finding.
240
- */
241
- function waiverReasons(config) {
242
- const reasons = /* @__PURE__ */ new Map();
243
- const entries = config.doctor?.waivers ?? [];
244
- if (!Array.isArray(entries)) return reasons;
245
- for (const entry of entries) if (isRecord(entry) && entry["code"] === "PD017" && typeof entry["key"] === "string" && typeof entry["reason"] === "string" && entry["reason"].trim() !== "") reasons.set(`PD017:${entry["key"]}`, entry["reason"]);
246
- return reasons;
247
- }
248
- /**
249
- * Splits `findings` by `doctor.ignore` and `--ignore`. An entry that matches no
250
- * finding comes back as an `ignore-stale` warning so the baseline can shrink.
251
- */
252
- function applyDoctorIgnores(findings, config, flags) {
253
- const ignores = parseIgnores(config.doctor?.ignore, "doctor.ignore", flags);
254
- const split = splitIgnored(findings, (item) => item.id, ignores);
255
- const waivers = waiverReasons(config);
256
- const kept = [];
257
- const waived = [];
258
- for (const item of split.kept) {
259
- const reason = waivers.get(item.id);
260
- if (item.code === "PD017" && reason !== void 0) waived.push({
261
- id: item.id,
262
- reason,
263
- message: item.message
264
- });
265
- else kept.push(item);
317
+ * Applies `doctor.baseline` and `--ignore` to one run. With `update` it first
318
+ * rewrites the baseline to accept this run's errors and warnings, and `wrote`
319
+ * names the file.
320
+ */
321
+ function settleBaseline(input) {
322
+ const path = input.config.doctor?.baseline;
323
+ if (path === void 0) {
324
+ if (input.update) throw new CliError("usage", "--update-baseline rewrites doctor.baseline; set it to a file such as doctor-baseline.json first");
325
+ return applyDoctorBaseline(input.findings, {
326
+ path: "doctor.baseline",
327
+ entries: []
328
+ }, input.judged, input.ignore);
266
329
  }
267
- const stale = split.stale.filter((entry) => entry.reason !== "--ignore").map((entry) => reported({
268
- code: "ignore-stale",
269
- severity: "warning",
270
- target: entry.id,
271
- message: `ignore entry ${entry.id} matches no finding`,
272
- fix: "remove it from doctor.ignore"
273
- }));
330
+ let entries = readBaseline(input.cwd, path);
331
+ if (input.update) {
332
+ entries = updatedBaseline(input.findings, entries, input.judged);
333
+ applyFiles(input.cwd, [{
334
+ path: resolve(input.cwd, path),
335
+ text: baselineText(entries)
336
+ }]);
337
+ }
338
+ const applied = applyDoctorBaseline(input.findings, {
339
+ path,
340
+ entries
341
+ }, input.judged, input.ignore);
342
+ return input.update ? {
343
+ ...applied,
344
+ wrote: path
345
+ } : applied;
346
+ }
347
+ /**
348
+ * Splits `findings` by the `doctor.baseline` entries, then by `--ignore` for
349
+ * this run. A stale or unexplained baseline entry comes back as an error.
350
+ */
351
+ function applyDoctorBaseline(findings, baseline, judged, flags) {
352
+ const applied = applyBaseline(findings, baseline.entries, judged, baseline.path);
353
+ const split = splitIgnored(applied.findings, (item) => item.id, flags.map((id) => ({
354
+ id,
355
+ reason: "--ignore"
356
+ })));
274
357
  return {
275
- findings: [...kept, ...stale],
276
- ignored: [...split.ignored.map((entry) => ({
358
+ findings: split.kept,
359
+ ignored: [...applied.accepted, ...split.ignored.map((entry) => ({
277
360
  id: entry.id,
278
361
  reason: entry.reason,
279
362
  message: entry.item.message
280
- })), ...waived]
363
+ }))]
281
364
  };
282
365
  }
283
366
  // src/cli/doctor/better-supabase.ts
@@ -307,7 +390,8 @@ function activeTenantOf(config) {
307
390
  * `switch_organization` never changes the tenant claim.
308
391
  */
309
392
  async function pd078(input) {
310
- if (input.config.supabase?.hook === void 0) return [];
393
+ const hook = input.config.supabase?.hook;
394
+ if (hook === void 0 || hook.activeTenant === "request") return [];
311
395
  const config = await betterSupabaseConfig(lookupOf(input));
312
396
  if (config === void 0) return [];
313
397
  const activeTenant = activeTenantOf(config);
@@ -325,7 +409,7 @@ async function pd078(input) {
325
409
  code: "PD078",
326
410
  severity: "warning",
327
411
  message: mismatch,
328
- fix: "set supabase.hook.activeFrom, then run permdock supabase hook generate"
412
+ fix: "set supabase.hook.activeFrom, then run permdock supabase hook generate; or, when the request resolves the tenant, set supabase.hook.activeTenant: \"request\""
329
413
  }];
330
414
  }
331
415
  function isBlockPermissionKey(value) {
@@ -481,7 +565,8 @@ async function providerOf(input) {
481
565
  const path = catalogPath(input.config, input.cwd);
482
566
  try {
483
567
  const scopes = scopeList(policy.scopes);
484
- const manifest = hooklessDatabase(input.config) ? supabaseDatabaseManifest(scopes, input.config, {}, policy) : supabaseHookManifest(scopes, input.config, {}, policy);
568
+ const config = await withSchemaDefaults(input.cwd, input.config, policy);
569
+ const manifest = hooklessDatabase(input.config) ? supabaseDatabaseManifest(scopes, config, {}, policy) : supabaseHookManifest(scopes, config, {}, policy);
485
570
  return authorizationProvider({
486
571
  manifest,
487
572
  ...files.exists(path) ? { catalog: files.read(path) } : {}
@@ -496,12 +581,17 @@ function at$1(value, ...keys) {
496
581
  return current;
497
582
  }
498
583
  /**
499
- * `value` with SQL strings compared by shape: runs of whitespace and a cast on
500
- * `null` do not change what a template calls.
584
+ * `value` in the form two equal settings share, as better-supabase's BS427
585
+ * compares them: object keys sorted, runs of whitespace collapsed, a cast on
586
+ * `null` dropped and an unquoted SQL name lower-cased.
501
587
  */
502
588
  function sqlShape(value) {
503
- if (typeof value === "string") return value.replaceAll(/\bnull::\w+/gu, "null").replaceAll(/\s+/gu, " ");
504
- return isRecord(value) ? Object.fromEntries(Object.entries(value).map(([key, entry]) => [key, sqlShape(entry)])) : value;
589
+ if (typeof value === "string") return value.replaceAll(/\bnull::\w+/gu, "null").replaceAll(/\s+/gu, " ").trim().replaceAll(/"[^"]*"|[A-Za-z_][\w$]*/gu, (token) => token.startsWith("\"") ? token : token.toLowerCase());
590
+ if (Array.isArray(value)) return value.map((item) => sqlShape(item));
591
+ return isRecord(value) ? Object.fromEntries(Object.keys(value).toSorted().map((key) => [key, sqlShape(value[key])])) : value;
592
+ }
593
+ function sameShape(a, b) {
594
+ return isDeepStrictEqual(sqlShape(a), sqlShape(b));
505
595
  }
506
596
  /**
507
597
  * The config values better-supabase would otherwise fill from the provider with
@@ -513,30 +603,63 @@ function sqlShape(value) {
513
603
  function restated(config, provider) {
514
604
  const names = [];
515
605
  const through = at$1(config, "blocks", "memberships", "options", "roleThrough");
516
- if (through !== void 0 && (provider?.roleSources ?? []).some((source) => isDeepStrictEqual(source.role.through, through))) names.push("blocks.memberships.options.roleThrough");
606
+ if (through !== void 0 && (provider?.roleSources ?? []).some((source) => sameShape(source.role.through, through))) names.push("blocks.memberships.options.roleThrough");
517
607
  const platformRoles = at$1(config, "blocks", "invitations", "options", "platformRoles");
518
- if (platformRoles !== void 0 && provider?.platformRoles !== void 0 && isDeepStrictEqual(sqlShape(platformRoles), sqlShape(provider.platformRoles))) names.push("blocks.invitations.options.platformRoles");
608
+ if (platformRoles !== void 0 && provider?.platformRoles !== void 0 && sameShape(platformRoles, provider.platformRoles)) names.push("blocks.invitations.options.platformRoles");
519
609
  if (at$1(config, "blocks", "permissions", "model") === "provider") for (const subject of ["tenant", "user"]) {
520
610
  const value = at$1(config, "blocks", "permissions", "disabled", subject);
521
611
  const supplied = provider?.suspension?.[subject];
522
- if (value !== void 0 && isDeepStrictEqual(value, supplied)) names.push(`blocks.permissions.disabled.${subject}`);
612
+ if (value !== void 0 && sameShape(value, supplied)) names.push(`blocks.permissions.disabled.${subject}`);
613
+ }
614
+ const claimsHook = at$1(config, "blocks", "impersonation", "options", "claimsHook");
615
+ if (typeof claimsHook === "string" && provider?.tokenHook !== void 0 && sameShape(claimsHook, provider.tokenHook.function)) names.push("blocks.impersonation.options.claimsHook");
616
+ const blocks = at$1(config, "blocks");
617
+ for (const [block, entry] of Object.entries(isRecord(blocks) ? blocks : {})) {
618
+ const permissions = at$1(entry, "permissions");
619
+ for (const [action, key] of Object.entries(isRecord(permissions) ? permissions : {})) {
620
+ const supplied = provider?.actionKeys?.blocks?.[block]?.[action];
621
+ if (typeof key === "string" && supplied !== void 0 && key === supplied) names.push(`blocks.${block}.permissions.${action}`);
622
+ }
523
623
  }
524
624
  return names;
525
625
  }
526
626
  /**
627
+ * A suspension written as a `"schema.table.column"` string where the provider
628
+ * supplies the `{ table, id, disabledAt }` row. They differ on a user or tenant
629
+ * with no row: the row form refuses it, the column string lets it through.
630
+ */
631
+ function suspensionForms(config, provider) {
632
+ const findings = [];
633
+ for (const subject of ["tenant", "user"]) {
634
+ const value = at$1(config, "blocks", "permissions", "disabled", subject);
635
+ const supplied = provider?.suspension?.[subject];
636
+ if (typeof value !== "string" || !isRecord(supplied)) continue;
637
+ const name = `blocks.permissions.disabled.${subject}`;
638
+ findings.push({
639
+ code: "PD094",
640
+ severity: "warning",
641
+ target: name,
642
+ message: `better-supabase config sets ${name} to the column string ${value}, and the provider supplies the row form: with the string a ${subject} with no row passes better-supabase's block functions, while PermDock's policies refuse it`,
643
+ fix: `delete ${name} from the better-supabase config, so both libraries refuse a ${subject} with no row; the rendered block functions change, so review the next migration`
644
+ });
645
+ }
646
+ return findings;
647
+ }
648
+ /**
527
649
  * PD094: the better-supabase config restates a value the provider already
528
650
  * supplies, so the two copies drift.
529
651
  */
530
652
  async function pd094(input) {
531
653
  const config = await betterSupabaseConfig(lookupOf(input));
532
654
  if (config === void 0) return [];
533
- return (at$1(config, "blocks", "memberships", "options", "roleThrough") === void 0 && at$1(config, "blocks", "permissions", "disabled") === void 0 && at$1(config, "blocks", "invitations", "options", "platformRoles") === void 0 ? [] : restated(config, await providerOf(input))).map((name) => ({
655
+ const provider = await providerOf(input);
656
+ return [...restated(config, provider).map((name) => ({
534
657
  code: "PD094",
535
658
  severity: "error",
536
659
  target: name,
537
660
  message: `better-supabase config sets ${name}, which the provider supplies`,
538
661
  fix: `delete ${name} from the better-supabase config`
539
- }));
662
+ })), ...suspensionForms(config, provider)];
540
663
  }
541
664
  const SUPABASE_FACTORY = /import\s+(?!type\b)(?:[^;'"]*?\{[^}]*\bdefinePermDock\b[^}]*\}[^;'"]*?)from\s+["']permdock\/supabase["']/u;
542
665
  /**
@@ -555,6 +678,88 @@ async function pd100(input, sources) {
555
678
  fix: "import definePermDock from permdock/better-supabase, pass it the subject options, and hand the result to permdock/supabase/middleware createPermDock"
556
679
  }));
557
680
  }
681
+ // src/cli/doctor/budgets.ts
682
+ /** PD132: the policy is over a budget in `budgets`. */
683
+ async function pd132(project) {
684
+ if (project.config.budgets === void 0) return [];
685
+ const policy = await project.policy();
686
+ if (policy === void 0) return [];
687
+ return budgetBreaches(policy, project.config).map((breach) => ({
688
+ code: "PD132",
689
+ severity: "error",
690
+ target: `budgets.${breach.budget}`,
691
+ message: breachText(breach),
692
+ fix: breach.budget === "claims" ? "narrow the roles each membership carries, or raise budgets.claims; `permdock claims size` lists the cut" : `narrow the largest part or raise budgets.${breach.budget}; \`permdock ${breach.budget === "bundle" ? "bundle" : "snapshot"} size\` lists the parts`
693
+ }));
694
+ }
695
+ function isPermDockModule(specifier) {
696
+ return typeof specifier === "string" && (specifier === "permdock" || specifier.startsWith("permdock/"));
697
+ }
698
+ function isUseClient(program) {
699
+ return (Array.isArray(program.body) ? program.body : []).some((statement) => Reflect.get(statement, "directive") === "use client");
700
+ }
701
+ /** The JSX attribute's name and its `{expression}`, when it has one. */
702
+ function jsxAttribute(node) {
703
+ const name = Reflect.get(node, "name");
704
+ const value = Reflect.get(node, "value");
705
+ if (typeof name !== "object" || name === null) return;
706
+ const label = Reflect.get(name, "name");
707
+ if (typeof label !== "string" || typeof value !== "object" || value === null) return;
708
+ const expression = Reflect.get(value, "expression");
709
+ if (typeof expression !== "object" || expression === null) return;
710
+ return {
711
+ name: label,
712
+ expression
713
+ };
714
+ }
715
+ function passedBundles(source) {
716
+ const parsed = parseSync(source.file, source.text);
717
+ if (parsed.errors.some((error) => {
718
+ return error.severity === "Error";
719
+ })) return [];
720
+ const program = parsed.program;
721
+ if (isUseClient(program)) return [];
722
+ const builders = /* @__PURE__ */ new Set();
723
+ walk(program, (node) => {
724
+ if (node.type !== "ImportDeclaration" || !isPermDockModule(node.source?.value)) return;
725
+ for (const specifier of node.specifiers ?? []) if (nameOf(specifier.imported) === "clientBundle") {
726
+ const local = nameOf(specifier.local);
727
+ if (local !== void 0) builders.add(local);
728
+ }
729
+ });
730
+ if (builders.size === 0) return [];
731
+ const isBuild = (node) => node?.type === "CallExpression" && builders.has(nameOf(node.callee) ?? "");
732
+ const bound = /* @__PURE__ */ new Set();
733
+ walk(program, (node) => {
734
+ if (node.type === "VariableDeclarator" && isBuild(node.init)) {
735
+ const name = nameOf(node.id);
736
+ if (name !== void 0) bound.add(name);
737
+ }
738
+ });
739
+ const lines = [];
740
+ walk(program, (node) => {
741
+ if (node.type !== "JSXAttribute") return;
742
+ const attribute = jsxAttribute(node);
743
+ if (attribute?.name !== "bundle") return;
744
+ const { expression } = attribute;
745
+ if (isBuild(expression) || expression.type === "Identifier" && bound.has(expression.name ?? "")) lines.push(source.text.slice(0, node.start).split("\n").length);
746
+ });
747
+ return lines;
748
+ }
749
+ /**
750
+ * PD133: a server module calls `clientBundle(policy)` and passes the result to
751
+ * a provider's `bundle` prop. The provider is a client component, so React
752
+ * serialises the bundle into every document that renders it.
753
+ */
754
+ function pd133(sources) {
755
+ return sources.flatMap((source) => passedBundles(source).map((line) => ({
756
+ code: "PD133",
757
+ severity: "warning",
758
+ target: `${source.file}:${String(line)}`,
759
+ message: `${source.file}:${String(line)} builds clientBundle(policy) in a server module and passes it as the bundle prop, so every document that renders the provider carries the whole bundle`,
760
+ fix: "generate the bundle with `permdock gen --kind bundle` and pass the clientBundle export of its \"use client\" module, which reaches the browser as a reference"
761
+ })));
762
+ }
558
763
  // src/cli/doctor/catalog.ts
559
764
  /**
560
765
  * A policy that declares `oauthScopes` against a catalog on disk without them,
@@ -705,6 +910,15 @@ function helperNames(policy, config) {
705
910
  }];
706
911
  }
707
912
  }
913
+ // src/cli/sql/bsb-module.ts
914
+ const MODULE_HEADER = /^-- better-supabase module: [^\n]*\n(?:--[^\n]*\n)*?-- @bsb-hash sha256:/u;
915
+ /**
916
+ * Whether `text` is a module file `better-supabase add` or `upgrade` writes and
917
+ * manages through its `@bsb-hash` header; doctor checks the app's SQL, not it.
918
+ */
919
+ function isBetterSupabaseModule(text) {
920
+ return MODULE_HEADER.test(text);
921
+ }
708
922
  // src/cli/doctor/declarative.ts
709
923
  const SCHEMAS = "supabase/schemas";
710
924
  const MIGRATIONS$1 = "supabase/migrations";
@@ -756,15 +970,15 @@ function generatedSchemaFiles(cwd, schemaDir, files) {
756
970
  return sqlFiles$1(cwd, [schemaDir]).filter((file) => generatedByPermDock(files.read(file)));
757
971
  }
758
972
  /**
759
- * PD068: PermDock generates for pg-delta (the default), but
760
- * `supabase/config.toml` does not set `[experimental.pgdelta] enabled = true`,
761
- * so Supabase CLI 2.x diffs the schema files with migra. migra drops the hook's
762
- * `supabase_auth_admin` grants and the helpers' privileges, and PermDock wrote
763
- * no `--grants-out` file to restore them.
973
+ * PD068: PermDock generates for pg-delta, but the Supabase project config sets
974
+ * `[experimental.pgdelta] enabled = false`, so Supabase CLI 3.x diffs the
975
+ * schema files with migra instead of its default pg-delta. migra drops the
976
+ * hook's `supabase_auth_admin` grants and the helpers' privileges, and PermDock
977
+ * wrote no `--grants-out` file to restore them.
764
978
  */
765
979
  function pd068(cwd, config, files = nodeFiles) {
766
980
  const read = readSupabaseConfig(cwd);
767
- if (read?.ok !== true || read.config.pgDelta?.enabled === true) return [];
981
+ if (read?.ok !== true || read.config.pgDelta?.enabled !== false) return [];
768
982
  const schemas = resolveSchemas(cwd, config);
769
983
  if (schemas.mode !== "pg-delta") return [];
770
984
  const [first] = generatedSchemaFiles(cwd, schemas.schemaDir, files);
@@ -772,8 +986,8 @@ function pd068(cwd, config, files = nodeFiles) {
772
986
  return [{
773
987
  code: "PD068",
774
988
  severity: "error",
775
- message: `${rel(cwd, first)} is written for pg-delta, but supabase/config.toml does not set [experimental.pgdelta] enabled = true, so the Supabase CLI diffs it with migra and drops the hook and helper grants`,
776
- fix: "add [experimental.pgdelta] with enabled = true to supabase/config.toml (Supabase CLI 2.119 or later), or set supabase.schemas: 'migra' in permdock.config.ts and regenerate with --grants-out"
989
+ message: `${rel(cwd, first)} is written for pg-delta, but ${read.file} sets [experimental.pgdelta] enabled = false, so the Supabase CLI diffs it with migra and drops the hook and helper grants`,
990
+ fix: `remove enabled = false from [experimental.pgdelta] in ${read.file} (pg-delta is the default of Supabase CLI 3.x), or set supabase.schemas: 'migra' in permdock.config.ts and regenerate with --grants-out`
777
991
  }];
778
992
  }
779
993
  /**
@@ -789,14 +1003,14 @@ function pd069(cwd, config, files = nodeFiles) {
789
1003
  if ((supabaseConfig(cwd).schemaPaths ?? []).length > 0) findings.push({
790
1004
  code: "PD069",
791
1005
  severity: "warning",
792
- message: "supabase/config.toml sets [db.migrations] schema_paths, which pg-delta does not need: it orders the schema files by their dependencies",
793
- fix: "remove schema_paths from [db.migrations] in supabase/config.toml"
1006
+ message: `${supabaseConfigName(cwd)} sets [db.migrations] schema_paths, which pg-delta does not need: it orders the schema files by their dependencies`,
1007
+ fix: `remove schema_paths from [db.migrations] in ${supabaseConfigName(cwd)}`
794
1008
  });
795
1009
  const root = join(cwd, schemas.schemaDir);
796
1010
  if (files.isDirectory(root)) for (const name of files.list(root)) {
797
1011
  if (!name.endsWith(".sql")) continue;
798
1012
  const file = join(root, name);
799
- if (files.isDirectory(file)) continue;
1013
+ if (files.isDirectory(file) || isBetterSupabaseModule(files.read(file))) continue;
800
1014
  findings.push({
801
1015
  code: "PD069",
802
1016
  severity: "warning",
@@ -839,7 +1053,7 @@ function pd043(cwd, config, files = nodeFiles) {
839
1053
  if (helpers === -1) return defined === void 0 ? [] : [{
840
1054
  code: "PD043",
841
1055
  severity: "warning",
842
- message: `${rel(cwd, defined)} defines the PermDock helpers, but schema_paths in supabase/config.toml does not list it, so supabase db diff never applies it`,
1056
+ message: `${rel(cwd, defined)} defines the PermDock helpers, but schema_paths in ${supabaseConfigName(cwd)} does not list it, so supabase db diff never applies it`,
843
1057
  fix: `add it to [db.migrations] schema_paths before every file that calls permdock_has, permitted_<scope>_ids or member_<scope>_ids`
844
1058
  }];
845
1059
  const helperFile = rel(cwd, schemas[helpers]?.file ?? "");
@@ -1183,6 +1397,45 @@ function pd092(project) {
1183
1397
  };
1184
1398
  });
1185
1399
  }
1400
+ // src/cli/doctor/membership-facts.ts
1401
+ /**
1402
+ * PD121: `rls.memberships` or `rls.suspension` says something the membership
1403
+ * sources say differently, or restates what they say.
1404
+ */
1405
+ function pd121(config) {
1406
+ const differ = membershipDisagreements(config).map((item) => ({
1407
+ code: "PD121",
1408
+ severity: "warning",
1409
+ target: `rls.memberships.scopes.${item.scope}`,
1410
+ message: item.derived === void 0 ? `rls.memberships.scopes.${item.scope} maps ${item.written.table}, and the membership source of ${item.scope} is not a table rls.memberships can describe: the helpers and the token hook read different memberships` : `rls.memberships.scopes.${item.scope} maps ${item.written.table} differently from its membership source (${item.derived.table}): the helpers and the token hook read different memberships`,
1411
+ fix: `delete rls.memberships.scopes.${item.scope}; permdock derives it from the membership source`
1412
+ }));
1413
+ const restated = restatedFacts(config).map((path) => {
1414
+ const name = path.join(".");
1415
+ return {
1416
+ code: "PD121",
1417
+ severity: "warning",
1418
+ target: name,
1419
+ message: `${name} restates what the membership sources and supabase.hook.suspension declare`,
1420
+ fix: "run permdock codemod config --prune, which removes it after checking that every generated file stays the same"
1421
+ };
1422
+ });
1423
+ return [...differ, ...restated];
1424
+ }
1425
+ /**
1426
+ * PD121 on the config file as written: the loaded config already carries the
1427
+ * tables derived from the sources.
1428
+ */
1429
+ async function pd121InProject(cwd) {
1430
+ const file = configFileIn(cwd);
1431
+ if (file === void 0) return [];
1432
+ try {
1433
+ const text = readFileSync(file, "utf8");
1434
+ return pd121((await readParsedConfig(cwd, file)).config).filter((finding) => finding.target === void 0 || configProperty(file, text, finding.target.split(".")) !== void 0);
1435
+ } catch {
1436
+ return [];
1437
+ }
1438
+ }
1186
1439
  // src/cli/doctor/next.ts
1187
1440
  const ROUTE_GLOBS = ["**/api/permdock/route.{ts,tsx,js,jsx,mjs}"];
1188
1441
  const ENDPOINT = /\bendpoint\s*(?::|=)\s*\{?\s*['"`]/u;
@@ -1375,6 +1628,66 @@ function handlerMode(source, label) {
1375
1628
  function shapeOf(path) {
1376
1629
  return path.split("/").filter((segment) => segment !== "").map((segment) => segment.startsWith("{") && segment.endsWith("}") ? "{}" : segment).join("/");
1377
1630
  }
1631
+ // src/cli/doctor/parser-pins.ts
1632
+ /** The parsers `permdock` pins exactly, because its findings depend on them. */
1633
+ const PINNED_PARSERS = ["oxc-parser", "pgsql-parser"];
1634
+ function versionOf(from, name) {
1635
+ try {
1636
+ const pkg = createRequire(from)(`${name}/package.json`);
1637
+ return isRecord(pkg) && typeof pkg["version"] === "string" ? pkg["version"] : void 0;
1638
+ } catch {
1639
+ return;
1640
+ }
1641
+ }
1642
+ /** The versions of the parsers this `permdock` copy resolves. */
1643
+ function permdockParserVersions() {
1644
+ return Object.fromEntries(PINNED_PARSERS.flatMap((name) => {
1645
+ const version = versionOf(import.meta.url, name);
1646
+ return version === void 0 ? [] : [[name, version]];
1647
+ }));
1648
+ }
1649
+ function listed(files, cwd) {
1650
+ const path = resolve(cwd, "package.json");
1651
+ if (!files.exists(path)) return {};
1652
+ let pkg;
1653
+ try {
1654
+ pkg = JSON.parse(files.read(path));
1655
+ } catch {
1656
+ return {};
1657
+ }
1658
+ const out = {};
1659
+ for (const field of [
1660
+ "dependencies",
1661
+ "devDependencies",
1662
+ "optionalDependencies"
1663
+ ]) {
1664
+ const deps = isRecord(pkg) ? pkg[field] : void 0;
1665
+ if (!isRecord(deps)) continue;
1666
+ for (const [name, spec] of Object.entries(deps)) if (typeof spec === "string") out[name] = spec;
1667
+ }
1668
+ return out;
1669
+ }
1670
+ /**
1671
+ * PD126: the app lists `oxc-parser` or `pgsql-parser` and installs another
1672
+ * version than the one `permdock` pins, so the project holds two copies.
1673
+ */
1674
+ function pd126(cwd, files = nodeFiles, own = permdockParserVersions()) {
1675
+ const deps = listed(files, cwd);
1676
+ return PINNED_PARSERS.flatMap((name) => {
1677
+ const spec = deps[name];
1678
+ const pinned = own[name];
1679
+ if (spec === void 0 || pinned === void 0) return [];
1680
+ const installed = versionOf(resolve(cwd, "package.json"), name);
1681
+ if (installed === void 0 || installed === pinned) return [];
1682
+ return [{
1683
+ code: "PD126",
1684
+ severity: "info",
1685
+ target: name,
1686
+ message: `package.json lists ${name} ${spec}, which installs ${installed}; permdock pins ${pinned}, so the project holds two copies`,
1687
+ fix: `remove ${name} from package.json: permdock depends on it at the version its findings are tested with`
1688
+ }];
1689
+ });
1690
+ }
1378
1691
  // src/cli/doctor/per-request.ts
1379
1692
  /** Factories whose answers or entries only pay off when one is shared. */
1380
1693
  const SHARED_FACTORIES = {
@@ -1612,31 +1925,66 @@ function pd111(project) {
1612
1925
  // src/cli/doctor/perf-snapshot.ts
1613
1926
  /** Memberships of the probe subject: a tenant admin with a handful of tenants. */
1614
1927
  const PROBE_TENANTS = 3;
1928
+ /** Parts PD112 names beside the largest, since no option leaves them out. */
1929
+ const NAMED_PARTS = /* @__PURE__ */ new Set([
1930
+ "typeLevel",
1931
+ "scopes",
1932
+ "requires"
1933
+ ]);
1615
1934
  /**
1616
1935
  * PD112: the compact snapshot of the most privileged role is over 64 KB of
1617
1936
  * JSON. A Next.js page that renders `PermDockProvider` serialises it into the
1618
- * Flight stream once per provider, so the size is paid on every navigation.
1937
+ * Flight stream once per provider, so the size is paid on every navigation. The
1938
+ * probe uses `omitStatic` when the project generates the `bundle` kind.
1619
1939
  */
1620
1940
  async function pd112(project) {
1621
1941
  const policy = await project.policy();
1622
1942
  if (policy === void 0) return [];
1623
1943
  const role = mostPrivilegedRole(policy);
1624
1944
  if (role === void 0) return [];
1945
+ const options = snapshotProbeOptions(project.config);
1625
1946
  const report = snapshotSize({
1626
1947
  policy,
1627
1948
  role,
1628
1949
  tenants: PROBE_TENANTS,
1629
- omitAssignable: false
1950
+ omitAssignable: false,
1951
+ ...options
1630
1952
  });
1631
1953
  if (typeof report === "string" || report.total.bytes <= 65536) return [];
1954
+ const named = report.parts.filter((part) => NAMED_PARTS.has(part.part)).map((part) => `${part.part} ${String(part.bytes)}`);
1632
1955
  return [{
1633
1956
  code: "PD112",
1634
1957
  severity: "warning",
1635
1958
  target: role,
1636
- message: `the snapshot of role '${role}' is ${String(report.total.bytes)} bytes (${String(report.total.gzip)} gzip), over ${String(SNAPSHOT_BUDGET_BYTES)}; the largest part is ${report.largest}`,
1637
- fix: "pass omitStatic with the generated bundle (`permdock gen --kind bundle`), omitAssignable when the page has no role editor, or narrow the role's grants; `permdock snapshot size` lists the parts"
1959
+ message: `the snapshot of role '${role}'${options.omitStatic ? " with omitStatic" : ""} is ${String(report.total.bytes)} bytes (${String(report.total.gzip)} gzip), over ${String(SNAPSHOT_BUDGET_BYTES)}; the largest part is ${report.largest}${named.length === 0 ? "" : `; ${named.join(", ")} bytes`}`,
1960
+ fix: options.omitStatic ? "pass omitAssignable when the page has no role editor, or narrow the role's grants; `permdock snapshot size --omit-static` lists the parts" : "pass omitStatic with the generated bundle (`permdock gen --kind bundle`), omitAssignable when the page has no role editor, or narrow the role's grants; `permdock snapshot size` lists the parts"
1638
1961
  }];
1639
1962
  }
1963
+ // src/cli/doctor/exported-duplicates.ts
1964
+ /**
1965
+ * PD095: a schema file the app or an export wrote creates a function or policy
1966
+ * a PermDock file also creates. The shadow load then applies both, and the
1967
+ * later file wins. Files in `_custom/` and `_cluster/` are left out.
1968
+ */
1969
+ async function exportedDuplicates(schemaDir, files) {
1970
+ const ownFile = /* @__PURE__ */ new Map();
1971
+ for (const file of files) if (generatedByPermdock(file.text)) for (const key of await ownedObjects([file.text])) ownFile.set(key, file.path);
1972
+ if (ownFile.size === 0) return [];
1973
+ const owned = new Set(ownFile.keys());
1974
+ const findings = [];
1975
+ for (const file of files) {
1976
+ if (generatedByPermdock(file.text) || inReservedDir(schemaDir, file.path)) continue;
1977
+ const { removed } = await withoutOwned(file.text, owned);
1978
+ for (const key of removed) findings.push({
1979
+ code: "PD095",
1980
+ severity: "error",
1981
+ target: file.path,
1982
+ message: `${file.path} and ${ownFile.get(key) ?? ""} both create ${shownKey(key)}`,
1983
+ fix: "run permdock generate, which removes the exported copy, or delete it by hand"
1984
+ });
1985
+ }
1986
+ return findings;
1987
+ }
1640
1988
  // src/cli/doctor/schema-checks.ts
1641
1989
  const SCHEMA_DIR = "supabase/schemas";
1642
1990
  const MIGRATIONS = "supabase/migrations";
@@ -1664,99 +2012,114 @@ function sqlUnder(cwd, directory, files) {
1664
2012
  walk(root);
1665
2013
  return found;
1666
2014
  }
1667
- function captured(match, index) {
1668
- const value = match[index];
1669
- if (typeof value !== "string") throw new TypeError("PermDock CLI: schema pattern matched without its group");
1670
- return value;
1671
- }
1672
- function matchStart(match) {
1673
- if (typeof match.index !== "number") throw new TypeError("PermDock CLI: schema match has no index");
1674
- return match.index;
1675
- }
2015
+ /** The last dotted part of a name: `folders` for `public.folders`. */
1676
2016
  function lastSegment(name) {
1677
- const bare = name.split(".").at(-1);
1678
- if (bare === void 0) return name;
1679
- return bare;
1680
- }
1681
- function ifNotExistsShapes(text) {
1682
- const shapes = [];
1683
- for (const match of text.matchAll(/\bcreate\s+(table|(?:unique\s+)?index|policy)\s+if\s+not\s+exists\b/giu)) {
1684
- const shape = `create ${captured(match, 1).toLowerCase().replace(/^unique\s+/u, "")} if not exists`;
1685
- if (!shapes.includes(shape)) shapes.push(shape);
2017
+ return name.split(".").at(-1) ?? name;
2018
+ }
2019
+ /** `schema.name` as written, lower case, or the bare name. */
2020
+ function dotted(parts) {
2021
+ return parts.join(".").toLowerCase();
2022
+ }
2023
+ function relationName(relation) {
2024
+ const read = readRelation(relation);
2025
+ return read === void 0 ? void 0 : dotted(read.schema === void 0 ? [read.name] : [read.schema, read.name]);
2026
+ }
2027
+ /** The body of a `do` block, from its `as` argument. */
2028
+ function doBody(statement) {
2029
+ const args = statement.node["args"];
2030
+ for (const item of Array.isArray(args) ? args : []) {
2031
+ const element = isRecord(item) ? item["DefElem"] : void 0;
2032
+ if (isRecord(element) && element["defname"] === "as") return stringValues([element["arg"]]).join("");
2033
+ }
2034
+ return "";
2035
+ }
2036
+ function ifNotExistsShape(statement) {
2037
+ if (statement.node["if_not_exists"] !== true) return;
2038
+ switch (statement.kind) {
2039
+ case "CreateStmt": return "create table if not exists";
2040
+ case "IndexStmt": return "create index if not exists";
2041
+ default: return;
1686
2042
  }
1687
- return shapes;
1688
2043
  }
1689
- function dropsTriggerBeforeCreate(text) {
1690
- return /\bdrop\s+trigger\b[^;]*;\s*create\s+(?:constraint\s+)?trigger\b/iu.test(text);
2044
+ /** The tables and functions a `grant` names; none for `on all ... in schema`. */
2045
+ function grantObjects(statement) {
2046
+ if (statement.kind !== "GrantStmt" || statement.node["targtype"] !== "ACL_TARGET_OBJECT") return [];
2047
+ const objects = statement.node["objects"];
2048
+ return (Array.isArray(objects) ? objects : []).flatMap((item) => {
2049
+ if (!isRecord(item)) return [];
2050
+ const table = relationName(item["RangeVar"]);
2051
+ if (table !== void 0) return [table];
2052
+ const routine = item["ObjectWithArgs"];
2053
+ return isRecord(routine) ? [dotted(stringValues(routine["objname"]))] : [];
2054
+ });
1691
2055
  }
1692
- function doCreates(text) {
1693
- for (const match of text.matchAll(/\bdo\s+(\$\$|\$[A-Za-z0-9_]*\$)/giu)) {
1694
- const fence = captured(match, 1);
1695
- const start = matchStart(match) + match[0].length;
1696
- const end = text.indexOf(fence, start);
1697
- const body = end === -1 ? text.slice(start) : text.slice(start, end);
1698
- if (/\bcreate\b/iu.test(body)) return true;
2056
+ /** The function, table or view a statement defines, lower case. */
2057
+ function definedName(statement) {
2058
+ switch (statement.kind) {
2059
+ case "CreateFunctionStmt": return dotted(stringValues(statement.node["funcname"]));
2060
+ case "CreateStmt": return relationName(statement.node["relation"]);
2061
+ case "ViewStmt": return relationName(statement.node["view"]);
2062
+ default: return;
1699
2063
  }
1700
- return false;
1701
2064
  }
1702
- function signatures(text) {
1703
- const counts = /* @__PURE__ */ new Map();
1704
- for (const match of text.matchAll(/\bcreate\s+(?:or\s+replace\s+)?function\s+([^\s(]+)\s*(\([^)]*\))/giu)) {
1705
- const key = `${captured(match, 1).toLowerCase()}${captured(match, 2).toLowerCase()}`;
1706
- counts.set(key, (counts.get(key) ?? 0) + 1);
2065
+ const POLICY_IF_NOT_EXISTS = /^create\s+policy\s+if\s+not\s+exists\b/iu;
2066
+ /** What pg-delta cannot diff in one schema file's statements. */
2067
+ async function schemaProblems(text) {
2068
+ const { nodes, rejected } = await parseSqlStatements(text);
2069
+ const problems = /* @__PURE__ */ new Set();
2070
+ const signatures = /* @__PURE__ */ new Set();
2071
+ const views = /* @__PURE__ */ new Set();
2072
+ for (const statement of nodes) if (statement.kind === "ViewStmt") {
2073
+ const name = relationName(statement.node["view"]);
2074
+ if (name !== void 0) views.add(name);
1707
2075
  }
1708
- return counts;
1709
- }
1710
- function viewNames(text) {
1711
- const names = /* @__PURE__ */ new Set();
1712
- for (const match of text.matchAll(/\bcreate\s+(?:or\s+replace\s+)?view\s+([^\s(]+)/giu)) names.add(captured(match, 1).replaceAll("\"", "").toLowerCase());
1713
- return names;
1714
- }
1715
- function triggerOnView(text, views) {
1716
- for (const match of text.matchAll(/\bcreate\s+(?:or\s+replace\s+)?trigger\s+\S+\s+\w+\s+on\s+([^\s;]+)/giu)) {
1717
- const target = captured(match, 1).replaceAll("\"", "").toLowerCase();
1718
- const bare = lastSegment(target);
1719
- if (views.has(target) || views.has(bare)) return true;
2076
+ for (const [index, statement] of nodes.entries()) {
2077
+ if (statement.kind === "DoStmt" && /\bcreate\b/iu.test(doBody(statement))) problems.add("a do block whose body contains create");
2078
+ if (statement.kind === "GrantStmt" && statement.node["targtype"] === "ACL_TARGET_ALL_IN_SCHEMA") problems.add("grant on all");
2079
+ if (statement.kind === "CreateFunctionStmt") {
2080
+ const signature = `${definedName(statement) ?? ""}(${(functionArgTypes(statement) ?? []).join(",")})`;
2081
+ if (signatures.has(signature)) problems.add("two definitions of one signature");
2082
+ signatures.add(signature);
2083
+ }
2084
+ const shape = ifNotExistsShape(statement);
2085
+ if (shape !== void 0) problems.add(shape);
2086
+ const next = nodes[index + 1];
2087
+ if (statement.kind === "DropStmt" && statement.node["removeType"] === "OBJECT_TRIGGER" && next?.kind === "CreateTrigStmt") problems.add("drop trigger before create trigger");
2088
+ if (statement.kind === "CreateTrigStmt") {
2089
+ const target = relationName(statement.node["relation"]);
2090
+ if (target !== void 0 && (views.has(target) || views.has(lastSegment(target)))) problems.add("a trigger on a view");
2091
+ }
1720
2092
  }
1721
- return false;
2093
+ if (rejected.some((range) => POLICY_IF_NOT_EXISTS.test(range.text))) problems.add("create policy if not exists");
2094
+ return [...problems];
1722
2095
  }
1723
- function grantedNames(text) {
2096
+ /** Each defined or granted name, with and without its schema. */
2097
+ async function ownedNames(text, granted) {
1724
2098
  const names = [];
1725
- for (const match of text.matchAll(/\bgrant\b[^;]*\bon\s+(?:table\s+|function\s+|all\s+)?([^\s(;]+)/giu)) {
1726
- const name = captured(match, 1).replaceAll("\"", "").toLowerCase();
1727
- if (name !== "" && name !== "all") names.push(name, lastSegment(name));
1728
- }
1729
- return names;
1730
- }
1731
- function definedNames(text) {
1732
- const names = /* @__PURE__ */ new Set();
1733
- for (const match of text.matchAll(/\bcreate\s+(?:or\s+replace\s+)?(?:function|table|view)\s+([^\s(]+)/giu)) {
1734
- const name = captured(match, 1).replaceAll("\"", "").toLowerCase();
1735
- names.add(name);
1736
- names.add(lastSegment(name));
2099
+ for (const statement of await parseSqlLenient(text)) {
2100
+ const found = [definedName(statement), ...granted ? grantObjects(statement) : []];
2101
+ for (const name of found) if (name !== void 0 && name !== "") names.push(name, lastSegment(name));
1737
2102
  }
1738
2103
  return names;
1739
2104
  }
1740
2105
  /**
1741
- * PD095: a schema file uses a shape pg-delta rejects, or a `-- permdock:`
2106
+ * PD095: a schema file uses a shape pg-delta rejects, another schema file
2107
+ * creates a function or policy a PermDock file creates, or a `-- permdock:`
1742
2108
  * migration repeats DDL or a grant the schema file already defines. The shapes
1743
2109
  * include `if not exists` on `create table`, `create index` and `create
1744
2110
  * policy`, and a `drop trigger` before a `create trigger`: pg-delta diffs the
1745
2111
  * file, so each is `create`, `create or replace` or nothing.
1746
2112
  */
1747
- function pd095(cwd, files) {
2113
+ async function pd095(cwd, files) {
1748
2114
  const schema = sqlUnder(cwd, SCHEMA_DIR, files).filter((file) => permdockSchema(cwd, file));
1749
- const findings = [];
2115
+ const findings = [...await exportedDuplicates(SCHEMA_DIR, sqlUnder(cwd, SCHEMA_DIR, files).map((file) => ({
2116
+ path: rel(cwd, file.path),
2117
+ text: file.text
2118
+ })))];
1750
2119
  const owned = /* @__PURE__ */ new Set();
1751
2120
  for (const file of schema) {
1752
2121
  const label = rel(cwd, file.path);
1753
- const problems = [];
1754
- if (doCreates(file.text)) problems.push("a do block whose body contains create");
1755
- if (/\bgrant\s+\S+\s+on\s+all\b/iu.test(file.text)) problems.push("grant on all");
1756
- if ([...signatures(file.text)].filter(([, count]) => count > 1).length > 0) problems.push("two definitions of one signature");
1757
- problems.push(...ifNotExistsShapes(file.text));
1758
- if (dropsTriggerBeforeCreate(file.text)) problems.push("drop trigger before create trigger");
1759
- if (triggerOnView(file.text, viewNames(file.text))) problems.push("a trigger on a view");
2122
+ const problems = await schemaProblems(file.text);
1760
2123
  if (problems.length > 0) findings.push({
1761
2124
  code: "PD095",
1762
2125
  severity: "error",
@@ -1764,13 +2127,13 @@ function pd095(cwd, files) {
1764
2127
  message: `${label} has ${problems.join(", ")}`,
1765
2128
  fix: "rewrite the schema file as plain create or replace statements pg-delta can diff"
1766
2129
  });
1767
- for (const name of definedNames(file.text)) owned.add(name);
2130
+ for (const name of await ownedNames(file.text, false)) owned.add(name);
1768
2131
  }
1769
2132
  if (owned.size === 0) return findings;
1770
2133
  for (const file of sqlUnder(cwd, MIGRATIONS, files)) {
1771
2134
  if (!/^-- permdock:[a-z0-9-]+ v\d+/u.test(file.text)) continue;
1772
2135
  const label = rel(cwd, file.path);
1773
- const repeated = [...definedNames(file.text), ...grantedNames(file.text)].filter((name) => owned.has(name));
2136
+ const repeated = (await ownedNames(file.text, true)).filter((name) => owned.has(name));
1774
2137
  if (repeated.length > 0) findings.push({
1775
2138
  code: "PD095",
1776
2139
  severity: "error",
@@ -1802,7 +2165,6 @@ function pd096(config) {
1802
2165
  }
1803
2166
  return findings;
1804
2167
  }
1805
- const POLICY_ON = /create\s+policy\s+(?:"[^"]+"|\w+)\s+on\s+((?:"[^"]+"|\w+)(?:\s*\.\s*(?:"[^"]+"|\w+))?)([^;]*);/giu;
1806
2168
  function tableId(raw) {
1807
2169
  const bare = raw.replaceAll(/[\s"]/gu, "").toLowerCase();
1808
2170
  return bare.includes(".") ? bare : `public.${bare}`;
@@ -1822,24 +2184,24 @@ function followChildren(config) {
1822
2184
  * insert, update and delete there, and permissive policies add up, so the app
1823
2185
  * policy widens them for the commands it names (`all` names every one).
1824
2186
  */
1825
- function pd101(cwd, config, files) {
2187
+ async function pd101(cwd, config, files) {
1826
2188
  const children = followChildren(config);
1827
2189
  if (children.size === 0) return [];
1828
2190
  const findings = [];
1829
2191
  for (const file of sqlUnder(cwd, SCHEMA_DIR, files)) {
1830
2192
  if (permdockSchema(cwd, file)) continue;
1831
2193
  const label = rel(cwd, file.path);
1832
- for (const match of file.text.matchAll(POLICY_ON)) {
1833
- const table = tableId(captured(match, 1));
2194
+ for (const statement of await parseSqlLenient(file.text)) {
2195
+ const policy = readPolicy$1(statement);
2196
+ if (policy === void 0 || !policy.permissive) continue;
2197
+ const table = `${policy.schema}.${policy.table}`.toLowerCase();
1834
2198
  const resource = children.get(table);
1835
- const clause = match[2] ?? "";
1836
- if (resource === void 0 || /\bas\s+restrictive\b/iu.test(clause)) continue;
1837
- const command = (/\bfor\s+(select|insert|update|delete|all)\b/iu.exec(clause)?.[1] ?? "all").toLowerCase();
2199
+ if (resource === void 0) continue;
1838
2200
  findings.push({
1839
2201
  code: "PD101",
1840
2202
  severity: "warning",
1841
2203
  target: `${label}:${table}`,
1842
- message: `${label} defines a permissive ${command} policy on ${table}, which the generated follows policies for ${resource} already allow`,
2204
+ message: `${label} defines a permissive ${policy.command} policy on ${table}, which the generated follows policies for ${resource} already allow`,
1843
2205
  fix: "delete the policy and let rls.tables.<resource>.follows decide, or drop the table from follows"
1844
2206
  });
1845
2207
  }
@@ -1848,9 +2210,8 @@ function pd101(cwd, config, files) {
1848
2210
  }
1849
2211
  // src/cli/doctor/perf-sql.ts
1850
2212
  const NAME$1 = String.raw`((?:"[^"]+"|\w+)(?:\s*\.\s*(?:"[^"]+"|\w+))?)`;
1851
- const CREATE_POLICY$1 = new RegExp(String.raw`^create\s+policy\s+("[^"]+"|\w+)\s+on\s+${NAME$1}([\s\S]*)$`, "iu");
1852
2213
  const CREATE_INDEX$1 = new RegExp(String.raw`^create\s+(?:unique\s+)?index\s+(?:concurrently\s+)?(?:if\s+not\s+exists\s+)?(?:(?:"[^"]+"|\w+)\s+)?on\s+(?:only\s+)?${NAME$1}\s*(?:using\s+\w+\s*)?\(([^)]*)\)`, "iu");
1853
- const COMMANDS = [
2214
+ const COMMANDS$1 = [
1854
2215
  "select",
1855
2216
  "insert",
1856
2217
  "update",
@@ -1876,7 +2237,7 @@ function statementsOf(cwd, config, files) {
1876
2237
  const generated = permdockSchema(cwd, {
1877
2238
  path,
1878
2239
  text
1879
- });
2240
+ }) || isBetterSupabaseModule(text);
1880
2241
  return sqlStatements(text).map((statement) => ({
1881
2242
  file: rel(cwd, path),
1882
2243
  generated,
@@ -1884,20 +2245,36 @@ function statementsOf(cwd, config, files) {
1884
2245
  }));
1885
2246
  });
1886
2247
  }
1887
- function policiesOf(statements) {
1888
- return statements.flatMap((statement) => {
1889
- const match = CREATE_POLICY$1.exec(header$1(statement.text));
1890
- if (match === null) return [];
1891
- const rest = group(match, 3);
1892
- const command = /\bfor\s+(all|select|insert|update|delete)\b/iu.exec(rest)?.[1]?.toLowerCase();
1893
- return [{
1894
- ...statement,
1895
- name: unquote$1(group(match, 1)),
1896
- table: tableKey(group(match, 2).replaceAll(/\s/gu, "")),
1897
- commands: command === void 0 || command === "all" ? COMMANDS : [command],
1898
- restrictive: /\bas\s+restrictive\b/iu.test(rest)
1899
- }];
1900
- });
2248
+ /**
2249
+ * The `create policy` statements of `statements`. A policy an `@bsb access` tag
2250
+ * of the project renders counts as generated, wherever its file is.
2251
+ */
2252
+ async function policiesOf(statements, cwd) {
2253
+ const tagged = await taggedPolicyIds(cwd);
2254
+ const out = [];
2255
+ for (const statement of statements) {
2256
+ if (!/^create\s+policy\b/iu.test(statement.text)) continue;
2257
+ let nodes;
2258
+ try {
2259
+ nodes = await parseSqlFile(statement.text);
2260
+ } catch (error) {
2261
+ if (error instanceof SqlSyntaxError) continue;
2262
+ throw error;
2263
+ }
2264
+ const policy = nodes[0] === void 0 ? void 0 : readPolicy$1(nodes[0]);
2265
+ if (policy !== void 0) {
2266
+ const table = `${policy.schema}.${policy.table}`;
2267
+ out.push({
2268
+ ...statement,
2269
+ generated: statement.generated || tagged.has(taggedPolicyId(table, policy.name)),
2270
+ name: policy.name,
2271
+ table,
2272
+ commands: policy.command === "all" ? COMMANDS$1 : [policy.command],
2273
+ restrictive: !policy.permissive
2274
+ });
2275
+ }
2276
+ }
2277
+ return out;
1901
2278
  }
1902
2279
  function lineOf(statement, text, index) {
1903
2280
  return statement.line + text.slice(0, index).split("\n").length - 1;
@@ -2002,10 +2379,10 @@ function correlatedSetCall(text, table) {
2002
2379
  * `security definer`, so the planner cannot inline them and a table scan makes
2003
2380
  * one call per row.
2004
2381
  */
2005
- function pd103(cwd, config, files = nodeFiles) {
2382
+ async function pd103(cwd, config, files = nodeFiles) {
2006
2383
  const statements = statementsOf(cwd, config, files);
2007
2384
  const helpers = setHelperBodies(statements);
2008
- return policiesOf(statements).flatMap((policy) => {
2385
+ return (await policiesOf(statements, cwd)).flatMap((policy) => {
2009
2386
  const text = header$1(policy.text);
2010
2387
  const setCall = callsSetPerRow(text, helpers);
2011
2388
  const correlated = correlatedSetCall(text, policy.table);
@@ -2026,9 +2403,9 @@ function pd103(cwd, config, files = nodeFiles) {
2026
2403
  * one of them. Postgres evaluates every permissive policy and ORs the results,
2027
2404
  * so each added policy adds a predicate to every scan.
2028
2405
  */
2029
- function pd104(cwd, config, files = nodeFiles) {
2406
+ async function pd104(cwd, config, files = nodeFiles) {
2030
2407
  const groups = /* @__PURE__ */ new Map();
2031
- for (const policy of policiesOf(statementsOf(cwd, config, files))) {
2408
+ for (const policy of await policiesOf(statementsOf(cwd, config, files), cwd)) {
2032
2409
  if (policy.restrictive) continue;
2033
2410
  for (const command of policy.commands) {
2034
2411
  const key = `${policy.table}:${command}`;
@@ -2060,7 +2437,7 @@ function indexedColumns(statements) {
2060
2437
  }
2061
2438
  return leads;
2062
2439
  }
2063
- function tableOf$1(resource, entry) {
2440
+ function tableOf(resource, entry) {
2064
2441
  if (entry === false || typeof entry === "string") return entry === false ? void 0 : tableKey(entry);
2065
2442
  if ("tableOf" in entry) return;
2066
2443
  return tableKey(entry.table ?? resource);
@@ -2068,7 +2445,7 @@ function tableOf$1(resource, entry) {
2068
2445
  function wantedIndexes(config) {
2069
2446
  const wanted = [];
2070
2447
  for (const [resource, entry] of Object.entries(config.rls?.tables ?? {})) {
2071
- const table = tableOf$1(resource, entry);
2448
+ const table = tableOf(resource, entry);
2072
2449
  if (table === void 0 || typeof entry !== "object") continue;
2073
2450
  if ("tableOf" in entry) continue;
2074
2451
  for (const [child, column] of Object.entries(entry.follows ?? {})) wanted.push({
@@ -2180,8 +2557,8 @@ const TENANT_LEAD = /\bpermitted_\w+_id_array\s*\(|\bpermitted_\w+_ids_by_permis
2180
2557
  * generated policy reads the one-argument form only where no tenant can lead
2181
2558
  * it, so it is not reported.
2182
2559
  */
2183
- function pd108(cwd, config, files = nodeFiles) {
2184
- return policiesOf(statementsOf(cwd, config, files)).flatMap((policy) => {
2560
+ async function pd108(cwd, config, files = nodeFiles) {
2561
+ return (await policiesOf(statementsOf(cwd, config, files), cwd)).flatMap((policy) => {
2185
2562
  if (policy.generated) return [];
2186
2563
  const text = header$1(policy.text);
2187
2564
  if (![...text.matchAll(ROWS_CALL)].some((call) => !group(call, 1).includes(",")) || TENANT_LEAD.test(text)) return [];
@@ -2194,6 +2571,210 @@ function pd108(cwd, config, files = nodeFiles) {
2194
2571
  }];
2195
2572
  });
2196
2573
  }
2574
+ // src/cli/doctor/policy-count.ts
2575
+ const COMMANDS = [
2576
+ "select",
2577
+ "insert",
2578
+ "update",
2579
+ "delete"
2580
+ ];
2581
+ /**
2582
+ * Whether better-supabase's doctor runs PermDock's through BS705, where BS641
2583
+ * reports the same count.
2584
+ */
2585
+ async function underBetterSupabaseDoctor(input) {
2586
+ const authorization = (await betterSupabaseConfig({
2587
+ cwd: input.cwd,
2588
+ ...input.files === void 0 ? {} : { files: input.files },
2589
+ ...input.config.betterSupabase?.config === void 0 ? {} : { path: input.config.betterSupabase.config }
2590
+ }))?.["authorization"];
2591
+ const doctor = isRecord(authorization) ? authorization["doctor"] : void 0;
2592
+ return isRecord(doctor) && Array.isArray(doctor["command"]);
2593
+ }
2594
+ /**
2595
+ * PD131: a table with more than `doctor.policies.max` policies for one command
2596
+ * and `authenticated`, better-supabase BS641's count and default.
2597
+ */
2598
+ async function pd131(input) {
2599
+ if (await underBetterSupabaseDoctor(input)) return [];
2600
+ const max = input.config.doctor?.policies?.max ?? 4;
2601
+ let report;
2602
+ try {
2603
+ report = await rlsReport({
2604
+ cwd: input.cwd,
2605
+ config: input.config
2606
+ });
2607
+ } catch (error) {
2608
+ if (error instanceof SqlSyntaxError) return [];
2609
+ throw error;
2610
+ }
2611
+ return report.tables.flatMap((table) => COMMANDS.flatMap((command) => {
2612
+ const policies = policiesFor(table, command);
2613
+ if (policies.length <= max) return [];
2614
+ const listed = policies.map((policy) => `${policy.name} (${policy.permissive ? "permissive" : "restrictive"}, ${policy.origin})`).join(", ");
2615
+ return [{
2616
+ code: "PD131",
2617
+ severity: "warning",
2618
+ target: `${table.table}:${command}`,
2619
+ message: `${table.table} has ${String(policies.length)} ${command} policies for authenticated, more than doctor.policies.max (${String(max)}): ${listed}`,
2620
+ fix: "fold the provider or app policies into fewer conditions; permdock rls report lists the helper calls each one adds per statement"
2621
+ }];
2622
+ }));
2623
+ }
2624
+ // src/cli/doctor/pg-topo.ts
2625
+ const PG_TOPO = "@supabase/pg-topo";
2626
+ function isPgTopo(value) {
2627
+ return isRecord(value) && typeof value["analyzeAndSort"] === "function";
2628
+ }
2629
+ async function loadPgTopo(cwd) {
2630
+ const loaded = await importFromApp(cwd, PG_TOPO);
2631
+ return isPgTopo(loaded) ? loaded : void 0;
2632
+ }
2633
+ function refKey(ref) {
2634
+ return `${ref.kind}:${ref.schema ?? ""}:${ref.name}:${ref.signature ?? ""}`;
2635
+ }
2636
+ /** `<input:3>` is the fourth SQL text passed to `analyzeAndSort`. */
2637
+ function fileOf(files, filePath) {
2638
+ const index = /^<input:(\d+)>$/u.exec(filePath)?.[1];
2639
+ return index === void 0 ? filePath : files[Number(index)] ?? filePath;
2640
+ }
2641
+ /** Whether every key names one function, so the keys differ only in arguments. */
2642
+ function overloadsOnly(keys) {
2643
+ return new Set(keys.map((key) => {
2644
+ const [kind, schema, name] = key.split(":");
2645
+ return kind === "function" || kind === "procedure" ? `${schema ?? ""}.${name ?? ""}` : key;
2646
+ })).size === 1 && keys.every((key) => /^(?:function|procedure):/u.test(key));
2647
+ }
2648
+ async function argTypes(sql) {
2649
+ try {
2650
+ const [node] = await parseSqlFile(sql);
2651
+ return (node === void 0 ? void 0 : functionArgTypes(node))?.join(", ");
2652
+ } catch (error) {
2653
+ if (error instanceof SqlSyntaxError) return;
2654
+ throw error;
2655
+ }
2656
+ }
2657
+ /**
2658
+ * Whether the producers of a function key declare different argument lists.
2659
+ * pg-topo 1.0.0-alpha.8 drops array bounds from a signature, so `f(text, uuid)`
2660
+ * and `f(text, uuid[])` share a key.
2661
+ */
2662
+ async function distinctOverloads(ref, producers) {
2663
+ if (ref.kind !== "function" && ref.kind !== "procedure") return false;
2664
+ const signatures = [];
2665
+ for (const node of producers) signatures.push(await argTypes(node.sql));
2666
+ return signatures.every((signature) => signature !== void 0) && new Set(signatures).size === signatures.length;
2667
+ }
2668
+ /**
2669
+ * Whether `sql` is `create schema if not exists`. Producers that all are can
2670
+ * run in any order; next to a plain `create schema` one may run first and make
2671
+ * it fail.
2672
+ */
2673
+ async function repeatable(sql) {
2674
+ try {
2675
+ const [node] = await parseSqlFile(sql);
2676
+ return node?.kind === "CreateSchemaStmt" && node.node["if_not_exists"] === true;
2677
+ } catch (error) {
2678
+ if (error instanceof SqlSyntaxError) return false;
2679
+ throw error;
2680
+ }
2681
+ }
2682
+ async function allRepeatable(producers) {
2683
+ for (const node of producers) if (!await repeatable(node.sql)) return false;
2684
+ return producers.length > 0;
2685
+ }
2686
+ function configTables(input) {
2687
+ return new Set(Object.entries(input.config.rls?.tables ?? {}).flatMap(([resource, entry]) => {
2688
+ const table = tableOf(resource, entry);
2689
+ return table === void 0 ? [] : [table];
2690
+ }));
2691
+ }
2692
+ async function duplicates(diagnostics, ordered, files, cwd) {
2693
+ const refs = /* @__PURE__ */ new Map();
2694
+ for (const diagnostic of diagnostics) {
2695
+ const ref = diagnostic.objectRefs?.[0];
2696
+ if (diagnostic.code === "DUPLICATE_PRODUCER" && diagnostic.details?.["requiredObjectKey"] === void 0 && ref !== void 0) refs.set(refKey(ref), ref);
2697
+ }
2698
+ const findings = [];
2699
+ for (const [key, ref] of refs) {
2700
+ const producers = ordered.filter((node) => node.provides.some((provided) => refKey(provided) === key));
2701
+ if (await distinctOverloads(ref, producers) || await allRepeatable(producers)) continue;
2702
+ const where = [...new Set(producers.map((node) => rel(cwd, fileOf(files, node.id.filePath))))];
2703
+ findings.push({
2704
+ code: "PD125",
2705
+ severity: "warning",
2706
+ target: key,
2707
+ message: `pg-topo: ${where.join(" and ")} each create ${ref.kind} ${ref.schema === void 0 ? "" : `${ref.schema}.`}${ref.name}, which better-supabase reports as BS722`,
2708
+ fix: "keep one statement that creates it in the schema directory"
2709
+ });
2710
+ }
2711
+ return findings;
2712
+ }
2713
+ function cycles(diagnostics, files, cwd) {
2714
+ return diagnostics.flatMap((diagnostic) => {
2715
+ if (diagnostic.code !== "CYCLE_DETECTED") return [];
2716
+ const keys = diagnostic.details?.["cycleObjectKeys"];
2717
+ const objects = Array.isArray(keys) ? keys.filter((key) => typeof key === "string") : [];
2718
+ if (objects.length > 0 && overloadsOnly(objects)) return [];
2719
+ const file = diagnostic.statementId === void 0 ? "" : `${rel(cwd, fileOf(files, diagnostic.statementId.filePath))}: `;
2720
+ return [{
2721
+ code: "PD125",
2722
+ severity: "warning",
2723
+ target: objects.join(" "),
2724
+ message: `pg-topo: ${file}${diagnostic.message} (${objects.join(", ")})`,
2725
+ fix: "split the statements, or add a -- pg-topo:requires line to the one that depends on the other"
2726
+ }];
2727
+ });
2728
+ }
2729
+ function unresolvedTables(diagnostics, input, files) {
2730
+ const tables = configTables(input);
2731
+ const seen = /* @__PURE__ */ new Set();
2732
+ return diagnostics.flatMap((diagnostic) => {
2733
+ const ref = diagnostic.objectRefs?.[0];
2734
+ if (diagnostic.code !== "UNRESOLVED_DEPENDENCY" || ref?.kind !== "table" || diagnostic.statementId === void 0) return [];
2735
+ const table = `${ref.schema ?? "public"}.${ref.name}`;
2736
+ const file = rel(input.cwd, fileOf(files, diagnostic.statementId.filePath));
2737
+ if (!tables.has(table) || seen.has(`${file}:${table}`)) return [];
2738
+ seen.add(`${file}:${table}`);
2739
+ return [{
2740
+ code: "PD125",
2741
+ severity: "warning",
2742
+ target: `${file}:${table}`,
2743
+ message: `pg-topo: ${file} reads ${table}, which rls.tables names, and no file in the schema directory creates it`,
2744
+ fix: `add create table ${table} to the schema directory, or fix the table name in rls.tables`
2745
+ }];
2746
+ });
2747
+ }
2748
+ /**
2749
+ * PD125: pg-topo's dependency analysis of the declarative schema directory. It
2750
+ * reports cycles, an object two statements create, and a table `rls.tables`
2751
+ * names that no schema file creates. Overloads of one function are left out:
2752
+ * pg-topo 1.0.0-alpha.8 cannot tell them apart. So is a schema that only
2753
+ * `create schema if not exists` statements create. Under better-supabase's
2754
+ * doctor, BS722 and BS723 report cycles and duplicates.
2755
+ */
2756
+ async function pd125(input) {
2757
+ const schemas = resolveSchemas(input.cwd, input.config);
2758
+ if (schemas.mode !== "pg-delta") return [];
2759
+ const files = sqlFiles$1(input.cwd, [schemas.schemaDir]);
2760
+ if (files.length === 0) return [];
2761
+ const topo = await loadPgTopo(input.cwd);
2762
+ if (topo === void 0) return [{
2763
+ code: "PD125",
2764
+ severity: "info",
2765
+ message: `${PG_TOPO} is not installed, so doctor does not check the dependency order of ${schemas.schemaDir}`,
2766
+ fix: `install ${PG_TOPO} as a dev dependency; better-supabase installs it`
2767
+ }];
2768
+ const read = filesOf(input);
2769
+ const result = await topo.analyzeAndSort(files.map((file) => read.read(file)));
2770
+ const unresolved = unresolvedTables(result.diagnostics, input, files);
2771
+ if (await underBetterSupabaseDoctor(input)) return unresolved;
2772
+ return [
2773
+ ...cycles(result.diagnostics, files, input.cwd),
2774
+ ...await duplicates(result.diagnostics, result.ordered, files, input.cwd),
2775
+ ...unresolved
2776
+ ];
2777
+ }
2197
2778
  // src/cli/doctor/policy.ts
2198
2779
  /**
2199
2780
  * A sensitive verb matches the action itself or a camelCase compound that
@@ -2216,27 +2797,12 @@ function excludesRequester(deny, allow) {
2216
2797
  if (deny.permission.key !== allow.permission.key) return false;
2217
2798
  return deny.role === null || deny.role === allow.role;
2218
2799
  }
2219
- /** `doctor.waivers`, checked; PD017 is the only code a waiver names. */
2220
- function waiversOf(input) {
2221
- const entries = input.config.doctor?.waivers ?? [];
2222
- if (!Array.isArray(entries)) throw configError("PermDock CLI: doctor.waivers must be a list of { code, key, reason }");
2223
- return entries.map((entry, index) => {
2224
- if (!isRecord(entry) || entry["code"] !== "PD017" || typeof entry["key"] !== "string" || entry["key"] === "" || typeof entry["reason"] !== "string" || entry["reason"].trim() === "") throw configError(`PermDock CLI: doctor.waivers[${String(index)}] needs code "PD017", a permission key and a non-empty reason`);
2225
- return {
2226
- key: entry["key"],
2227
- reason: entry["reason"]
2228
- };
2229
- });
2230
- }
2231
2800
  async function pd017(input) {
2232
2801
  if (input.config.policy === void 0) return [];
2233
2802
  const policy = await policyOf(input);
2234
2803
  if (policy === void 0) return [];
2235
2804
  const sensitive = new Set(input.config.doctor?.sensitiveActions ?? DEFAULT_SENSITIVE_ACTIONS);
2236
2805
  const denies = policy.grants.filter((grant) => grant.effect === "deny");
2237
- const waivers = waiversOf(input);
2238
- const waived = new Set(waivers.map((waiver) => waiver.key));
2239
- const matched = /* @__PURE__ */ new Set();
2240
2806
  const findings = [];
2241
2807
  const seen = /* @__PURE__ */ new Set();
2242
2808
  for (const grant of policy.grants) {
@@ -2246,22 +2812,14 @@ async function pd017(input) {
2246
2812
  if (denies.some((deny) => excludesRequester(deny, grant))) continue;
2247
2813
  if (seen.has(grant.permission.key)) continue;
2248
2814
  seen.add(grant.permission.key);
2249
- if (waived.has(grant.permission.key)) matched.add(grant.permission.key);
2250
2815
  findings.push({
2251
2816
  code: "PD017",
2252
2817
  severity: "warning",
2253
2818
  target: grant.permission.key,
2254
2819
  message: `${grant.permission.key} is a sensitive verb without approval`,
2255
- fix: "add approval: { by } on the allow, or a deny on the same leaf, or waive it in doctor.waivers with a reason"
2820
+ fix: "add approval: { by } on the allow, or a deny on the same leaf, or accept it in doctor.baseline with a reason"
2256
2821
  });
2257
2822
  }
2258
- for (const waiver of waivers) if (!matched.has(waiver.key)) findings.push({
2259
- code: "PD017",
2260
- severity: "warning",
2261
- target: `waiver:${waiver.key}`,
2262
- message: `doctor.waivers entry for ${waiver.key} matches no sensitive allow without approval`,
2263
- fix: "remove the entry from doctor.waivers"
2264
- });
2265
2823
  return findings;
2266
2824
  }
2267
2825
  async function pd024(input) {
@@ -2419,6 +2977,24 @@ function pd083(cwd, config, sources, files = nodeFiles) {
2419
2977
  fix: "run permdock supabase hook generate (with supabase.hook.api for the PostgREST wrappers) and apply the migration it writes"
2420
2978
  }];
2421
2979
  }
2980
+ // src/cli/source/calls.ts
2981
+ /**
2982
+ * The names `text` calls: `f()` gives `f`, `a.b.c()` gives `c`. Comments and
2983
+ * strings never count, so `// nativeRefresh()` calls nothing. A file that does
2984
+ * not parse calls nothing.
2985
+ */
2986
+ function calledNames(file, text) {
2987
+ const names = /* @__PURE__ */ new Set();
2988
+ const program = parseProgram(file, text);
2989
+ if (program === void 0) return names;
2990
+ walk(program, (node) => {
2991
+ if (node.type !== "CallExpression") return;
2992
+ const callee = node.callee;
2993
+ const name = callee?.type === "MemberExpression" ? nameOf(callee.property) : nameOf(callee);
2994
+ if (name !== void 0) names.add(name);
2995
+ });
2996
+ return names;
2997
+ }
2422
2998
  // src/cli/doctor/powersync.ts
2423
2999
  /**
2424
3000
  * Why each membership source of a scope the streams read through sources has no
@@ -2501,17 +3077,16 @@ function branchGaps(policy, resources) {
2501
3077
  }
2502
3078
  return findings;
2503
3079
  }
2504
- const NATIVE_REFRESH = /\bnativeRefresh\s*\(/u;
2505
- const AUTHZ_CHANGE_REFRESH = /\bauthzChangeRefresh\s*\(/u;
2506
- const REFRESH_SESSION = /\.refreshSession\s*\(/u;
2507
3080
  /**
2508
3081
  * The sources refresh the session and reconnect on an authorization change:
2509
3082
  * `nativeRefresh`, or an app bridge that calls `refreshSession()` and hands
2510
- * PermDock the refresh through `authzChangeRefresh`.
3083
+ * PermDock the refresh through `authzChangeRefresh`. A mention in a comment or
3084
+ * a string is not a call.
2511
3085
  */
2512
3086
  function wiresRefresh(sources) {
2513
- const has = (pattern) => sources.some((source) => pattern.test(source.text));
2514
- return has(NATIVE_REFRESH) || has(AUTHZ_CHANGE_REFRESH) && has(REFRESH_SESSION);
3087
+ const called = /* @__PURE__ */ new Set();
3088
+ for (const source of sources) for (const name of calledNames(source.file, source.text)) called.add(name);
3089
+ return called.has("nativeRefresh") || called.has("authzChangeRefresh") && called.has("refreshSession");
2515
3090
  }
2516
3091
  /**
2517
3092
  * PD084: a synced stream reads a token claim. PowerSync keeps the claims a
@@ -2828,12 +3403,140 @@ function pd028(cwd, config, plan, files = nodeFiles) {
2828
3403
  }
2829
3404
  return [...findings, ...memberships];
2830
3405
  }
2831
- // src/cli/doctor/rls.ts
2832
- async function pd027(input) {
2833
- if (input.config.rls === void 0 || input.config.policy === void 0) return [];
2834
- const policy = await policyOf(input);
2835
- if (policy === void 0) return [];
2836
- const findings = [];
3406
+ // src/cli/doctor/publications.ts
3407
+ /**
3408
+ * Publications whose subscribers enforce access themselves: Realtime checks
3409
+ * `realtime.messages` policies per subscriber, and PowerSync applies its sync
3410
+ * rules.
3411
+ */
3412
+ const ENFORCING = /^(?:supabase_realtime.*|powersync)$/u;
3413
+ const PUBLISHED_POLICY_TABLES = `
3414
+ select distinct pt.pubname, pt.schemaname, pt.tablename
3415
+ from pg_catalog.pg_publication_tables pt
3416
+ join pg_catalog.pg_policies p
3417
+ on p.schemaname = pt.schemaname and p.tablename = pt.tablename
3418
+ where position($1 in coalesce(p.qual, '') || ' ' || coalesce(p.with_check, '')) > 0
3419
+ order by 1, 2, 3`;
3420
+ /**
3421
+ * PD124: a table whose policies call PermDock's helpers belongs to a
3422
+ * publication. Logical replication (Supabase Pipelines, ETL, a subscriber
3423
+ * database) copies every row past row level security.
3424
+ */
3425
+ async function pd124(project) {
3426
+ const { database } = project;
3427
+ if (database === void 0 || project.config.rls === void 0) return [];
3428
+ const schema = project.config.rls.schema ?? "permdock";
3429
+ const client = await database.connect(database.url);
3430
+ try {
3431
+ return (await client.query(PUBLISHED_POLICY_TABLES, [`${schema}.`])).rows.flatMap((row) => {
3432
+ const publication = String(row["pubname"]);
3433
+ if (ENFORCING.test(publication)) return [];
3434
+ const table = `${String(row["schemaname"])}.${String(row["tablename"])}`;
3435
+ return [{
3436
+ code: "PD124",
3437
+ severity: "info",
3438
+ target: `${publication}:${table}`,
3439
+ message: `${table} carries PermDock policies and belongs to publication ${publication}; logical replication copies every row past row level security`,
3440
+ fix: `check who reads ${publication}'s destination, or remove ${table} from it with alter publication ${publication} drop table ${table}`
3441
+ }];
3442
+ });
3443
+ } finally {
3444
+ await client.end();
3445
+ }
3446
+ }
3447
+ // src/cli/doctor/repeated-version-reads.ts
3448
+ /** Options that give an instance its own cache or membership source. */
3449
+ const OWN_OPTIONS = /* @__PURE__ */ new Set([
3450
+ "memberships",
3451
+ "customRoles",
3452
+ "versions",
3453
+ "instances"
3454
+ ]);
3455
+ const BUILDERS = /* @__PURE__ */ new Set(["createPermDock", "getPermDock"]);
3456
+ function sitesOf(source) {
3457
+ const parsed = parseSync(source.file, source.text);
3458
+ if (parsed.errors.some((error) => {
3459
+ return error.severity === "Error";
3460
+ })) return {
3461
+ usesFor: false,
3462
+ builders: []
3463
+ };
3464
+ let usesFor = false;
3465
+ const builders = [];
3466
+ const program = parsed.program;
3467
+ walk(program, (node) => {
3468
+ if (node.type !== "CallExpression") return;
3469
+ const callee = node.callee;
3470
+ const name = callee?.type === "MemberExpression" ? nameOf(callee.property) : nameOf(callee);
3471
+ if (name === "permdockFor") {
3472
+ usesFor = true;
3473
+ return;
3474
+ }
3475
+ if (name === void 0 || !BUILDERS.has(name)) return;
3476
+ const own = (node.arguments ?? []).flatMap((argument) => (argument.type === "ObjectExpression" ? argument.properties ?? [] : []).map((property) => nameOf(property.key)).filter((key) => key !== void 0 && OWN_OPTIONS.has(key)));
3477
+ if (own.length > 0) builders.push({
3478
+ file: source.file,
3479
+ line: source.text.slice(0, node.start).split("\n").length,
3480
+ own
3481
+ });
3482
+ });
3483
+ return {
3484
+ usesFor,
3485
+ builders
3486
+ };
3487
+ }
3488
+ /**
3489
+ * PD130: the project calls `permdockFor` and also builds an instance with
3490
+ * `getPermDock` or `createPermDock` and its own `memberships`, `customRoles`,
3491
+ * `versions` or `instances`. That instance misses the `instanceCache` entry and
3492
+ * the version cache `permdockFor` shares, so one request reads the
3493
+ * authorization version twice.
3494
+ */
3495
+ function pd130(sources) {
3496
+ const found = sources.map(sitesOf);
3497
+ if (!found.some((entry) => entry.usesFor)) return [];
3498
+ return found.flatMap((entry) => entry.builders.map(({ file, line, own }) => ({
3499
+ code: "PD130",
3500
+ severity: "warning",
3501
+ target: `${file}:${String(line)}`,
3502
+ message: `${file}:${String(line)} builds an instance with its own ${own.join(", ")} while the project also calls permdockFor, so it never shares permdockFor's instance cache or version cache and reads the authorization version again`,
3503
+ fix: "spread permdockFor.sources() into the options, or resolve the instance with permdockFor(claims, { tenant, intent })"
3504
+ })));
3505
+ }
3506
+ // src/cli/doctor/restated-defaults.ts
3507
+ /** PD120: a config key set to the value its command uses when it is unset. */
3508
+ function pd120(config) {
3509
+ return restatedDefaults(config).map((entry) => {
3510
+ const name = entry.path.join(".");
3511
+ return {
3512
+ code: "PD120",
3513
+ severity: "warning",
3514
+ target: name,
3515
+ message: `permdock.config sets ${name} to ${JSON.stringify(entry.value)}, its default`,
3516
+ fix: "run permdock codemod config --prune, which removes it after checking that every generated file stays the same"
3517
+ };
3518
+ });
3519
+ }
3520
+ /**
3521
+ * PD120 on the config file as written: the loaded config carries values the
3522
+ * better-supabase defaults filled, which the file never set.
3523
+ */
3524
+ async function pd120InProject(cwd) {
3525
+ const file = configFileIn(cwd);
3526
+ if (file === void 0) return [];
3527
+ try {
3528
+ const text = readFileSync(file, "utf8");
3529
+ return pd120((await readParsedConfig(cwd, file)).config).filter((finding) => finding.target === void 0 || configProperty(file, text, finding.target.split(".")) !== void 0);
3530
+ } catch {
3531
+ return [];
3532
+ }
3533
+ }
3534
+ // src/cli/doctor/rls.ts
3535
+ async function pd027(input) {
3536
+ if (input.config.rls === void 0 || input.config.policy === void 0) return [];
3537
+ const policy = await policyOf(input);
3538
+ if (policy === void 0) return [];
3539
+ const findings = [];
2837
3540
  for (const grant of policy.grants) {
2838
3541
  const refs = [.../* @__PURE__ */ new Set([...contextRefs(grant.where), ...contextRefs(grant.check)])];
2839
3542
  if (refs.length === 0) continue;
@@ -3064,7 +3767,7 @@ async function pd037(input) {
3064
3767
  if (policy === void 0) return [];
3065
3768
  const conditioned = policyRowConditionKeys(policy);
3066
3769
  const findings = [];
3067
- for (const file of sqlFiles$1(input.cwd, input.config.doctor?.migrations ?? MIGRATION_DIRS)) for (const found of helperTablePolicies(files.read(file))) {
3770
+ for (const file of sqlFiles$1(input.cwd, input.config.doctor?.migrations ?? MIGRATION_DIRS)) for (const found of await helperTablePolicies(files.read(file))) {
3068
3771
  const keys = found.keys.filter((key) => conditioned.has(key));
3069
3772
  if (keys.length > 0) findings.push({
3070
3773
  code: "PD037",
@@ -3103,6 +3806,23 @@ function suggestsWrite(verb) {
3103
3806
  return next === "" || /[A-Z0-9_-]/u.test(next);
3104
3807
  });
3105
3808
  }
3809
+ /**
3810
+ * Verbs that compile to `none` because they have no `rls.actions` entry and
3811
+ * infer no command; PD071 reports the ones that read as a write.
3812
+ */
3813
+ async function pd122(input) {
3814
+ const rls = input.config.rls;
3815
+ if (rls === void 0 || input.config.policy === void 0) return [];
3816
+ const policy = await policyOf(input);
3817
+ if (policy === void 0) return [];
3818
+ const verbs = unmappedActions(policy.vocabulary.permissions, rls.actions).filter((verb) => !suggestsWrite(verb));
3819
+ return verbs.length === 0 ? [] : [{
3820
+ code: "PD122",
3821
+ severity: "info",
3822
+ message: `${verbs.join(", ")} ${verbs.length === 1 ? "has" : "have"} no rls.actions entry and infer${verbs.length === 1 ? "s" : ""} no SQL command, so ${verbs.length === 1 ? "it compiles" : "they compile"} to 'none' and add no SQL policy. Verbs that infer: ${INFERRED_VERBS}.`,
3823
+ fix: `map a verb in rls.actions only when its permission should reach a table: ${verbs[0] ?? "verb"}: "select", "insert", "update" or "delete"`
3824
+ }];
3825
+ }
3106
3826
  async function pd071(input) {
3107
3827
  const rls = input.config.rls;
3108
3828
  if (rls === void 0 || input.config.policy === void 0) return [];
@@ -3262,10 +3982,44 @@ async function pd075(input) {
3262
3982
  code: "PD075",
3263
3983
  severity: "error",
3264
3984
  message: `rls.tables maps ${[...resources].toSorted().join(" and ")} to ${table}, so the same rows carry two sets of keys and helpers`,
3265
- fix: `merge them into one resource (https://permdock.com/docs/guides/merge-resources), or list the other on the owner's also so only the owner writes ${table} policies`
3985
+ fix: `merge them into one resource, retiring each key with permdock keys rename <from> <to> (https://permdock.com/docs/guides/merge-resources), or list the other on the owner's also so only the owner writes ${table} policies`
3266
3986
  };
3267
3987
  })];
3268
3988
  }
3989
+ // src/cli/doctor/schema-tables.ts
3990
+ /**
3991
+ * PD134: a resource with no `rls.tables` entry whose table the schema files
3992
+ * create under neither its verbatim name nor its snake_case plural.
3993
+ */
3994
+ async function pd134(input) {
3995
+ if (input.config.rls === void 0) return [];
3996
+ const tables = await schemaTables(input.cwd);
3997
+ if (tables.size === 0) return [];
3998
+ const policy = await policyOf(input);
3999
+ if (policy === void 0) return [];
4000
+ return schemaDefaults(input.config, policy, tables).unknown.map(({ resource, tried }) => ({
4001
+ code: "PD134",
4002
+ severity: "info",
4003
+ target: `rls.tables.${resource}`,
4004
+ message: `no schema file creates a table for resource '${resource}' (tried ${tried.map((name) => `public.${name}`).join(" and ")}), so its policies name a table that may not exist`,
4005
+ fix: `map it in rls.tables: ${resource}: "schema.table", or ${resource}: false when it has no table`
4006
+ }));
4007
+ }
4008
+ /**
4009
+ * PD135: a pg-delta project that writes the `role_permissions` rows as data
4010
+ * migrations, where `rls.seeds: 'view'` keeps them in the declarative files.
4011
+ */
4012
+ function pd135(input) {
4013
+ const rls = input.config.rls;
4014
+ if (rls === void 0 || rls.seeds !== void 0 || rls.staticGrants === "ref" || !(input.config.supabase?.schemas === "pg-delta" || supabaseConfig(input.cwd).pgDelta?.enabled === true)) return [];
4015
+ return [{
4016
+ code: "PD135",
4017
+ severity: "info",
4018
+ target: "rls.seeds",
4019
+ message: "the project is declarative (pg-delta), and the role_permissions rows go in a data migration that grows with every policy change",
4020
+ fix: "set rls.seeds: 'view': the rows become a view in the helpers part, which pg-delta diffs like the rest of the schema"
4021
+ }];
4022
+ }
3269
4023
  // src/cli/doctor/seed-data.ts
3270
4024
  const SQL_ROOTS$1 = ["supabase/migrations", "supabase/schemas"];
3271
4025
  function defaultFindings(roles, knownRoles, scopes, permissions) {
@@ -3333,14 +4087,15 @@ async function pd097(project) {
3333
4087
  });
3334
4088
  }
3335
4089
  const seedFile = join(project.cwd, FIXTURES_PATH);
3336
- const toml = join(project.cwd, "supabase/config.toml");
4090
+ const configFile = supabaseConfigName(project.cwd);
4091
+ const config = join(project.cwd, configFile);
3337
4092
  if (project.files.exists(seedFile)) {
3338
- if (!(project.files.exists(toml) && project.files.read(toml).includes("seeds/permdock.sql"))) findings.push({
4093
+ if (!(project.files.exists(config) && project.files.read(config).includes("seeds/permdock.sql"))) findings.push({
3339
4094
  code: "PD097",
3340
4095
  severity: "warning",
3341
- target: "supabase/config.toml",
3342
- message: `supabase/config.toml does not list ${FIXTURES_PATH}. Add:\n${seedPathsLine()}`,
3343
- fix: `add the [db.seed] sql_paths line. PermDock does not edit config.toml`
4096
+ target: configFile,
4097
+ message: `${configFile} does not list ${FIXTURES_PATH}. Add:\n${seedPathsLine()}`,
4098
+ fix: `add the [db.seed] sql_paths entry. PermDock does not edit ${configFile}`
3344
4099
  });
3345
4100
  }
3346
4101
  const seeds = project.config.seeds;
@@ -3477,6 +4232,370 @@ async function pd054(input) {
3477
4232
  fix: "run permdock rls generate (for declarative schemas, --split ...,seeds --seeds-out supabase/migrations/, which writes a new migration) and apply it"
3478
4233
  }];
3479
4234
  }
4235
+ // src/cli/doctor/server-actions.ts
4236
+ const DIRECTIVE = /^(?:\s|\/\/[^\n]*\n|\/\*[\s\S]*?\*\/)*['"]use server['"]/u;
4237
+ const EXPORT = /^export\s+(?:default\s+)?(?:async\s+function\s*\*?\s*(\w+)|const\s+(\w+)\s*=)/gmu;
4238
+ const GUARD = /\b(?:protectAction|requirePermission|getPermission)\s*\(|\.assert\s*\(/u;
4239
+ /**
4240
+ * PD116: a module with a file-level `'use server'` exports a Server Action that
4241
+ * never calls `protectAction`, `requirePermission`, `getPermission` or
4242
+ * `assert`. Every export of such a module is a public POST endpoint.
4243
+ */
4244
+ function pd116(sources) {
4245
+ const findings = [];
4246
+ for (const source of sources) {
4247
+ if (!DIRECTIVE.test(source.text)) continue;
4248
+ const exports = [...source.text.matchAll(EXPORT)];
4249
+ for (const [index, match] of exports.entries()) {
4250
+ const name = match[1] ?? match[2] ?? "default";
4251
+ const start = match.index;
4252
+ const end = exports[index + 1]?.index ?? source.text.length;
4253
+ if (GUARD.test(source.text.slice(start, end))) continue;
4254
+ const line = source.text.slice(0, start).split("\n").length;
4255
+ findings.push({
4256
+ code: "PD116",
4257
+ severity: "warning",
4258
+ target: `${source.file}:${String(line)}`,
4259
+ message: `Server Action ${name} at ${source.file}:${String(line)} is exported from a 'use server' module and checks no permission: anyone who can reach the page can POST to it`,
4260
+ fix: "wrap it with protectAction(permission, { input })(handler), or call requirePermission(permission, data) first"
4261
+ });
4262
+ }
4263
+ }
4264
+ return findings;
4265
+ }
4266
+ // src/cli/doctor/source-readers.ts
4267
+ const UNTRUSTED_CLAIMS = /* @__PURE__ */ new Set([
4268
+ "user_metadata",
4269
+ "unsafeMetadata",
4270
+ "untrusted_metadata",
4271
+ "clientMetadata",
4272
+ "preferred_username"
4273
+ ]);
4274
+ const MODULE_SOURCES = /* @__PURE__ */ new Set([
4275
+ "ImportDeclaration",
4276
+ "ExportNamedDeclaration",
4277
+ "ExportAllDeclaration",
4278
+ "ImportExpression"
4279
+ ]);
4280
+ function parsedSources(sources) {
4281
+ const out = [];
4282
+ for (const source of sources) {
4283
+ const program = parseProgram(source.file, source.text);
4284
+ if (program !== void 0) out.push({
4285
+ file: source.file,
4286
+ text: source.text,
4287
+ program
4288
+ });
4289
+ }
4290
+ return out;
4291
+ }
4292
+ function unwrapped(node) {
4293
+ let current = node ?? void 0;
4294
+ while (current?.type === "TSAsExpression" || current?.type === "TSSatisfiesExpression" || current?.type === "ParenthesizedExpression") current = child(current, "expression");
4295
+ return current;
4296
+ }
4297
+ /** The value of a string literal or a template literal without expressions. */
4298
+ function stringOf(node) {
4299
+ const value = unwrapped(node);
4300
+ if (value?.type === "Literal") return typeof value.value === "string" ? value.value : void 0;
4301
+ if (value?.type !== "TemplateLiteral" || nodes(Reflect.get(value, "expressions")).length > 0) return;
4302
+ const quasi = nodes(Reflect.get(value, "quasis"))[0];
4303
+ const cooked = typeof quasi?.value === "object" && quasi.value !== null ? Reflect.get(quasi.value, "cooked") : void 0;
4304
+ return typeof cooked === "string" ? cooked : void 0;
4305
+ }
4306
+ /** The value of the property `key` of an object literal. */
4307
+ function propertyValue(object, key) {
4308
+ if (object?.type !== "ObjectExpression") return;
4309
+ const property = nodes(object.properties).find((item) => item.type === "Property" && propertyKey(item) === key);
4310
+ return property === void 0 ? void 0 : child(property, "value");
4311
+ }
4312
+ /** The properties of every object literal in `program`. */
4313
+ function properties(program) {
4314
+ const found = [];
4315
+ walk(program, (node) => {
4316
+ if (node.type === "Property") found.push(node);
4317
+ });
4318
+ return found;
4319
+ }
4320
+ /**
4321
+ * Whether a module specifier of `program` names PermDock: a `permdock` entry or
4322
+ * an app module such as `./permdock.ts` that wraps one.
4323
+ */
4324
+ function importsPermDock(program) {
4325
+ let found = false;
4326
+ walk(program, (node) => {
4327
+ const value = MODULE_SOURCES.has(node.type) ? stringOf(node.source) : void 0;
4328
+ found ||= value?.includes("permdock") === true;
4329
+ });
4330
+ return found;
4331
+ }
4332
+ /** Calls whose callee is `name` or a member named `name`, in source order. */
4333
+ function callsTo(program, names) {
4334
+ const found = [];
4335
+ walk(program, (node, _parent, ancestors) => {
4336
+ if (node.type !== "CallExpression") return;
4337
+ const callee = unwrapped(node.callee);
4338
+ const name = callee?.type === "MemberExpression" ? nameOf(callee.property) : nameOf(callee);
4339
+ if (name !== void 0 && names.has(name)) found.push({
4340
+ call: node,
4341
+ ancestors: [...ancestors]
4342
+ });
4343
+ });
4344
+ return found;
4345
+ }
4346
+ function pd007(sources) {
4347
+ const hasNever = parsedSources(sources).some(({ program }) => properties(program).some((property) => propertyKey(property) === "validate" && stringOf(child(property, "value")) === "never"));
4348
+ const hasAdapter = sources.some((source) => runtimeSpecifiers(source).some((specifier) => ADAPTER_SPECIFIERS.some((spec) => specifier === spec)));
4349
+ if (hasNever && hasAdapter) return [{
4350
+ code: "PD007",
4351
+ severity: "warning",
4352
+ message: "policy sets validate: 'never' while an HTTP, MCP or agent adapter is imported",
4353
+ fix: "use validate: 'boundary' for untrusted input"
4354
+ }];
4355
+ return [];
4356
+ }
4357
+ /** The names a module exports from its own declarations and `export { }`. */
4358
+ function exportedNames(program) {
4359
+ const names = [];
4360
+ for (const statement of nodes(program.body)) {
4361
+ if (statement.type !== "ExportNamedDeclaration") continue;
4362
+ const declaration = statement.declaration;
4363
+ if (declaration?.type === "VariableDeclaration") for (const item of nodes(declaration.declarations)) {
4364
+ const name = nameOf(item.id ?? void 0);
4365
+ if (name !== void 0) names.push(name);
4366
+ }
4367
+ else if (declaration !== null && declaration !== void 0) {
4368
+ const name = nameOf(declaration.id ?? void 0);
4369
+ if (name !== void 0) names.push(name);
4370
+ }
4371
+ if (statement.source === null || statement.source === void 0) for (const specifier of nodes(statement.specifiers)) {
4372
+ const name = nameOf(specifier.exported);
4373
+ if (name !== void 0) names.push(name);
4374
+ }
4375
+ }
4376
+ return names;
4377
+ }
4378
+ function pd008(sources) {
4379
+ const findings = [];
4380
+ for (const { file, program } of parsedSources(sources)) {
4381
+ if (!importsPermDock(program)) continue;
4382
+ const names = exportedNames(program);
4383
+ if (names.some((name) => name === "dock" || name === "ability")) findings.push({
4384
+ code: "PD008",
4385
+ severity: "warning",
4386
+ message: `${file} exports a reserved name (dock or ability)`,
4387
+ fix: "use createPermDock and permdock"
4388
+ });
4389
+ if (names.some((name) => name.startsWith("$"))) findings.push({
4390
+ code: "PD008",
4391
+ severity: "warning",
4392
+ message: `${file} exports a $ prefixed member`,
4393
+ fix: "drop the $ prefix"
4394
+ });
4395
+ }
4396
+ return findings;
4397
+ }
4398
+ /** Identifier names and the values of string literals, in source order. */
4399
+ function namesAndStrings(program) {
4400
+ const names = [];
4401
+ const strings = [];
4402
+ walk(program, (node) => {
4403
+ if (node.type === "Identifier") names.push(node.name ?? "");
4404
+ else {
4405
+ const value = node.type === "Literal" ? stringOf(node) : void 0;
4406
+ if (value !== void 0) strings.push(value);
4407
+ }
4408
+ });
4409
+ return {
4410
+ names,
4411
+ strings
4412
+ };
4413
+ }
4414
+ /**
4415
+ * PD010: a file reads an untrusted claim (`user_metadata`, …) as a member or a
4416
+ * key, and names roles or a tenant in code.
4417
+ */
4418
+ function pd010(sources) {
4419
+ const findings = [];
4420
+ for (const { file, program } of parsedSources(sources)) {
4421
+ const { names, strings } = namesAndStrings(program);
4422
+ const keys = /* @__PURE__ */ new Set([...names, ...properties(program).map((property) => propertyKey(property)).filter((key) => key !== void 0)]);
4423
+ const scoped = [...names, ...strings].some((value) => /roles|tenant/u.test(value));
4424
+ for (const claim of UNTRUSTED_CLAIMS) if (keys.has(claim) && scoped) findings.push({
4425
+ code: "PD010",
4426
+ severity: "error",
4427
+ message: `${file} reads roles or tenant from ${claim}`,
4428
+ fix: "use a server-set claim or a MembershipSource"
4429
+ });
4430
+ }
4431
+ return findings;
4432
+ }
4433
+ function pd011(sources) {
4434
+ const findings = [];
4435
+ for (const { file, program } of parsedSources(sources)) {
4436
+ const hd = properties(program).some((property) => propertyKey(property) === "tenant" && stringOf(child(property, "value")) === "hd");
4437
+ const { names, strings } = namesAndStrings(program);
4438
+ const google = strings.some((value) => value.includes("accounts.google.com")) && (names.includes("tenant") || properties(program).some((property) => propertyKey(property) === "tenant"));
4439
+ if (hd || google) findings.push({
4440
+ code: "PD011",
4441
+ severity: "warning",
4442
+ message: `${file} reads tenant from an optional issuer claim`,
4443
+ fix: "compare the claim to onboarded tenants; do not default a tenant"
4444
+ });
4445
+ }
4446
+ return findings;
4447
+ }
4448
+ function pd013(sources) {
4449
+ const findings = [];
4450
+ for (const { file, program } of parsedSources(sources)) {
4451
+ const listed = /* @__PURE__ */ new Set();
4452
+ for (const property of properties(program)) {
4453
+ const value = unwrapped(child(property, "value"));
4454
+ if (propertyKey(property) !== "algorithms" || value?.type !== "ArrayExpression") continue;
4455
+ for (const element of nodes(value.elements)) {
4456
+ const name = stringOf(element);
4457
+ if (name !== void 0) listed.add(name);
4458
+ }
4459
+ }
4460
+ if (listed.has("EdDSA")) findings.push({
4461
+ code: "PD013",
4462
+ severity: "warning",
4463
+ message: `${file} lists polymorphic EdDSA`,
4464
+ fix: "write Ed25519"
4465
+ });
4466
+ if (listed.has("none")) findings.push({
4467
+ code: "PD013",
4468
+ severity: "error",
4469
+ message: `${file} allows alg none`,
4470
+ fix: "remove none and RSA1_5 from algorithms"
4471
+ });
4472
+ }
4473
+ return findings;
4474
+ }
4475
+ const SUPABASE_SUBJECT = /* @__PURE__ */ new Set(["subjectFromSupabase", "subjectFromSupabaseSession"]);
4476
+ /**
4477
+ * The options argument of a call: `null` when it has none, `undefined` when it
4478
+ * is not an object literal.
4479
+ */
4480
+ function optionsOf(call, index) {
4481
+ const argument = nodes(call.arguments)[index];
4482
+ if (argument === void 0) return null;
4483
+ const value = unwrapped(argument);
4484
+ return value?.type === "ObjectExpression" ? value : void 0;
4485
+ }
4486
+ /**
4487
+ * The claim a `subjectFromSupabase` call reads the tenant from: `tenant` in its
4488
+ * options or their `claims`, the fallback when neither sets it, `undefined`
4489
+ * when the options or the value are not literals.
4490
+ */
4491
+ function tenantClaimOf(call, fallback) {
4492
+ const options = optionsOf(call, 1);
4493
+ if (options === null) return fallback;
4494
+ if (options === void 0) return;
4495
+ const value = propertyValue(options, "tenant") ?? propertyValue(unwrapped(propertyValue(options, "claims")), "tenant");
4496
+ return value === void 0 ? fallback : stringOf(value);
4497
+ }
4498
+ function pd038(sources, tenantClaim, fallback) {
4499
+ const findings = [];
4500
+ for (const { file, text, program } of parsedSources(sources)) {
4501
+ const lineAt = lineIndex(text);
4502
+ for (const { call } of callsTo(program, SUPABASE_SUBJECT)) {
4503
+ const read = tenantClaimOf(call, fallback);
4504
+ if (read === void 0 || read === tenantClaim) continue;
4505
+ findings.push({
4506
+ code: "PD038",
4507
+ severity: "warning",
4508
+ message: `${file}:${lineAt(call.start).line} reads the tenant from '${read}', but rls.tenantClaim is '${tenantClaim}'`,
4509
+ fix: `pass claims: { tenant: '${tenantClaim}' } or set rls.tenantClaim to '${read}'`
4510
+ });
4511
+ }
4512
+ }
4513
+ return findings;
4514
+ }
4515
+ /**
4516
+ * PD057: `rls.anonymousSignIns` is `'deny'`, so RLS refuses
4517
+ * `signInAnonymously()` users, but a `subjectFromSupabase(Session)` call maps
4518
+ * them as signed-in users. Options that are not a literal object are not read.
4519
+ */
4520
+ function pd057(sources) {
4521
+ const findings = [];
4522
+ for (const { file, text, program } of parsedSources(sources)) {
4523
+ const lineAt = lineIndex(text);
4524
+ for (const { call } of callsTo(program, SUPABASE_SUBJECT)) {
4525
+ const options = optionsOf(call, 1);
4526
+ if (options === void 0 || options !== null && stringOf(propertyValue(options, "anonymousSignIns")) === "deny") continue;
4527
+ findings.push({
4528
+ code: "PD057",
4529
+ severity: "warning",
4530
+ message: `${file}:${lineAt(call.start).line} maps anonymous sign-ins as users, but rls.anonymousSignIns is 'deny'`,
4531
+ fix: "pass anonymousSignIns: 'deny' so the subject agrees with RLS"
4532
+ });
4533
+ }
4534
+ }
4535
+ return findings;
4536
+ }
4537
+ /**
4538
+ * PD041: `exchangeCapability` signing link tokens with the project's shared JWT
4539
+ * secret.
4540
+ */
4541
+ function pd041(sources) {
4542
+ const findings = [];
4543
+ for (const { file, text, program } of parsedSources(sources)) {
4544
+ const lineAt = lineIndex(text);
4545
+ for (const { call } of callsTo(program, /* @__PURE__ */ new Set(["exchangeCapability"]))) {
4546
+ const options = optionsOf(call, 1);
4547
+ if (options === null || options === void 0 || stringOf(propertyValue(options, "alg")) !== "HS256") continue;
4548
+ findings.push({
4549
+ code: "PD041",
4550
+ severity: "warning",
4551
+ message: `${file}:${String(lineAt(call.start).line)} signs capability tokens with HS256, the project's shared JWT secret: whoever holds it can mint any user's token`,
4552
+ fix: "sign with alg: 'ES256' and the private JWK of an asymmetric Supabase signing key; keep HS256 for the local stack only"
4553
+ });
4554
+ }
4555
+ }
4556
+ return findings;
4557
+ }
4558
+ const ID_ROUTE = /^\/\S*(?::[A-Za-z_$][\w$]*|\{[A-Za-z_$][\w$]*\})/u;
4559
+ const DYNAMIC_SEGMENT = /(?:^|[\\/])(\[[^\]/\\]+\])(?=[\\/])/u;
4560
+ /**
4561
+ * The id-bearing route a `protect` call sits in: the file's dynamic segment, or
4562
+ * the route literal that is the first argument of a call around it.
4563
+ */
4564
+ function idRouteOf(file, ancestors) {
4565
+ const segment = DYNAMIC_SEGMENT.exec(file);
4566
+ if (segment !== null) return segment[1];
4567
+ for (const node of ancestors.toReversed()) {
4568
+ if (node.type !== "CallExpression") continue;
4569
+ const route = stringOf(nodes(node.arguments)[0]);
4570
+ if (route !== void 0 && ID_ROUTE.test(route)) return route;
4571
+ }
4572
+ }
4573
+ /**
4574
+ * PD036: a `protect(permission)` with no row loader on a route whose path names
4575
+ * an object id (BOLA, OWASP API1).
4576
+ */
4577
+ function pd036(sources) {
4578
+ const findings = [];
4579
+ for (const { file, text, program } of parsedSources(sources)) {
4580
+ if (!importsPermDock(program)) continue;
4581
+ const lineAt = lineIndex(text);
4582
+ for (const { call, ancestors } of callsTo(program, /* @__PURE__ */ new Set(["protect"]))) {
4583
+ const args = nodes(call.arguments);
4584
+ const only = args[0];
4585
+ if (args.length !== 1 || only === void 0 || only.type === "Literal" && only.value === null) continue;
4586
+ const route = idRouteOf(file, ancestors);
4587
+ if (route === void 0) continue;
4588
+ const permission = text.slice(only.start, only.end);
4589
+ findings.push({
4590
+ code: "PD036",
4591
+ severity: "warning",
4592
+ message: `${file}:${String(lineAt(call.start).line)} protects ${route} with ${permission} and no row loader, so the check never sees the row the id names (BOLA, OWASP API1)`,
4593
+ fix: "pass a loader that fetches the row by the id: protect(permission, (request) => load(request))"
4594
+ });
4595
+ }
4596
+ }
4597
+ return findings;
4598
+ }
3480
4599
  // src/cli/doctor/sql.ts
3481
4600
  /** Supabase's `[api] schemas` when `config.toml` sets none. */
3482
4601
  const API_SCHEMAS = ["public", "graphql_public"];
@@ -3492,6 +4611,38 @@ function isSupabase(files, cwd, config) {
3492
4611
  function migrationStatements(files, cwd, config) {
3493
4612
  return sqlFiles$1(cwd, config.doctor?.migrations ?? MIGRATION_DIRS).flatMap((file) => sqlStatements(files.read(file)).map((statement) => Object.assign({ file: rel(cwd, file) }, statement)));
3494
4613
  }
4614
+ /**
4615
+ * The `create policy` statements of `paths`, read through the SQL layer. A file
4616
+ * libpg_query rejects adds none; PD045 and the schema readers report it.
4617
+ */
4618
+ async function filePolicies(files, cwd, paths) {
4619
+ const out = [];
4620
+ for (const file of paths) {
4621
+ let nodes;
4622
+ try {
4623
+ nodes = await parseSqlFile(files.read(file));
4624
+ } catch (error) {
4625
+ if (error instanceof SqlSyntaxError) continue;
4626
+ throw error;
4627
+ }
4628
+ for (const node of nodes) {
4629
+ const policy = readPolicy$1(node);
4630
+ if (policy !== void 0) out.push({
4631
+ ...policy,
4632
+ file: rel(cwd, file),
4633
+ line: node.line,
4634
+ text: node.text
4635
+ });
4636
+ }
4637
+ }
4638
+ return out;
4639
+ }
4640
+ function migrationPolicies(files, cwd, config) {
4641
+ return filePolicies(files, cwd, sqlFiles$1(cwd, config.doctor?.migrations ?? MIGRATION_DIRS));
4642
+ }
4643
+ function policyTable(policy) {
4644
+ return `${policy.schema}.${policy.table}`.toLowerCase();
4645
+ }
3495
4646
  /** The schema of a `tableKey`, which always names one. */
3496
4647
  function schemaOf(key) {
3497
4648
  return key.slice(0, key.indexOf("."));
@@ -3504,13 +4655,13 @@ function unquote(name) {
3504
4655
  * API exposes, so PostgREST serves them as RPCs.
3505
4656
  */
3506
4657
  function pd046(cwd, config, files = nodeFiles) {
3507
- if (!files.exists(join(cwd, "supabase/config.toml"))) return [];
4658
+ if (!files.exists(join(cwd, supabaseConfigName(cwd)))) return [];
3508
4659
  const schema = config.rls?.schema ?? config.rls?.rbac?.schema ?? "permdock";
3509
4660
  if (!(supabaseConfig(cwd).apiSchemas ?? API_SCHEMAS).includes(schema)) return [];
3510
4661
  return [{
3511
4662
  code: "PD046",
3512
4663
  severity: "warning",
3513
- message: `the PermDock helper schema ${schema} is in [api] schemas in supabase/config.toml, so the Data API serves its security definer helpers as RPCs`,
4664
+ message: `the PermDock helper schema ${schema} is in [api] schemas in ${supabaseConfigName(cwd)}, so the Data API serves its security definer helpers as RPCs`,
3514
4665
  fix: schema === "public" ? `drop rls.schema: 'public' so the helpers move to the private ${PERMDOCK_SCHEMA} schema, regenerate with permdock rls generate, and keep ${PERMDOCK_SCHEMA} out of [api] schemas` : `remove ${schema} from [api] schemas; policies reach the helpers through grant usage, not the Data API`
3515
4666
  }];
3516
4667
  }
@@ -3677,23 +4828,19 @@ function pd050(cwd, config, files = nodeFiles) {
3677
4828
  fix: `alter table ${key} enable row level security; permdock rls generate writes its policies`
3678
4829
  }));
3679
4830
  }
3680
- const CREATE_POLICY = new RegExp(String.raw`^create\s+policy\s+${IDENT}\s+on\s+${NAME}([\s\S]*)$`, "iu");
3681
- const UNWRAPPED_AUTH = /(?<!\bselect\s{1,20})\bauth\.(uid|jwt)\s*\(\s*\)/giu;
3682
4831
  /**
3683
4832
  * PD051: a policy that calls `auth.uid()` or `auth.jwt()` bare, so Postgres
3684
4833
  * runs it once per row.
3685
4834
  */
3686
- function pd051(cwd, config, files = nodeFiles) {
4835
+ async function pd051(cwd, config, files = nodeFiles) {
3687
4836
  if (!isSupabase(files, cwd, config)) return [];
3688
- return migrationStatements(files, cwd, config).flatMap((statement) => {
3689
- const policy = CREATE_POLICY.exec(statement.text);
3690
- if (policy === null) return [];
3691
- const calls = [...new Set([...group(policy, 3).matchAll(UNWRAPPED_AUTH)].map((match) => `auth.${group(match, 1).toLowerCase()}()`))];
4837
+ return (await migrationPolicies(files, cwd, config)).flatMap((policy) => {
4838
+ const calls = [...new Set([...sqlCalls(policy.using), ...sqlCalls(policy.check)].filter(({ name, inSubquery }) => !inSubquery && name.length === 2 && name[0] === "auth" && (name[1] === "uid" || name[1] === "jwt")).map(({ name }) => `auth.${String(name[1])}()`))];
3692
4839
  const [first] = calls;
3693
4840
  return first === void 0 ? [] : [{
3694
4841
  code: "PD051",
3695
4842
  severity: "warning",
3696
- message: `${statement.file}:${String(statement.line)} policy ${unquote(group(policy, 1))} on ${tableKey(group(policy, 2))} calls ${calls.join(" and ")} once per row`,
4843
+ message: `${policy.file}:${String(policy.line)} policy ${policy.name} on ${policyTable(policy)} calls ${calls.join(" and ")} once per row`,
3697
4844
  fix: `wrap each call as (select ${first}) so Postgres evaluates it once per statement (Supabase advisor auth_rls_initplan)`
3698
4845
  }];
3699
4846
  });
@@ -3702,19 +4849,14 @@ function pd051(cwd, config, files = nodeFiles) {
3702
4849
  * PD052: an update policy without `with check`, so nothing states what a row
3703
4850
  * may become.
3704
4851
  */
3705
- function pd052(cwd, config, files = nodeFiles) {
4852
+ async function pd052(cwd, config, files = nodeFiles) {
3706
4853
  if (!isSupabase(files, cwd, config)) return [];
3707
- return migrationStatements(files, cwd, config).flatMap((statement) => {
3708
- const policy = CREATE_POLICY.exec(statement.text);
3709
- const rest = policy?.[3] ?? "";
3710
- if (policy === null || !/\bfor\s+update\b/iu.test(rest) || /\bwith\s+check\b/iu.test(rest)) return [];
3711
- return [{
3712
- code: "PD052",
3713
- severity: "warning",
3714
- message: `${statement.file}:${String(statement.line)} update policy ${unquote(group(policy, 1))} on ${tableKey(group(policy, 2))} has no with check, so Postgres checks the new row against using alone`,
3715
- fix: "add with check (...) stating what the updated row must satisfy, such as the same tenant and owner test, so an update cannot move a row out of what the user may write"
3716
- }];
3717
- });
4854
+ return (await migrationPolicies(files, cwd, config)).filter((policy) => policy.command === "update" && policy.check === void 0).map((policy) => ({
4855
+ code: "PD052",
4856
+ severity: "warning",
4857
+ message: `${policy.file}:${String(policy.line)} update policy ${policy.name} on ${policyTable(policy)} has no with check, so Postgres checks the new row against using alone`,
4858
+ fix: "add with check (...) stating what the updated row must satisfy, such as the same tenant and owner test, so an update cannot move a row out of what the user may write"
4859
+ }));
3718
4860
  }
3719
4861
  /** Top-level comma-separated parts of a parenthesised list. */
3720
4862
  function topLevelParts(body) {
@@ -3936,44 +5078,29 @@ function pd089(cwd, config, files = nodeFiles) {
3936
5078
  }];
3937
5079
  });
3938
5080
  }
3939
- const POLICY_COMMAND = /\bfor\s+(all|select|insert|update|delete)\b/iu;
3940
- const ACTOR_GUARD_CALL = /\bpermdock_actor_may_write\s*\(/iu;
3941
5081
  /** The expression `rls generate` inlined into the policies of 0.24 and earlier. */
3942
5082
  const INLINED_ACTOR_GUARD = /'act'[\s\S]*'read_only'/iu;
3943
- function inlinesActorGuard(text) {
3944
- return INLINED_ACTOR_GUARD.test(text.replaceAll("\"", ""));
5083
+ function guarded(policy) {
5084
+ return [...sqlCalls(policy.using), ...sqlCalls(policy.check)].some(({ name }) => name.at(-1) === "permdock_actor_may_write") || INLINED_ACTOR_GUARD.test(policy.text.replaceAll("\"", ""));
3945
5085
  }
3946
5086
  const WRITE_COMMANDS = [
3947
5087
  "insert",
3948
5088
  "update",
3949
5089
  "delete"
3950
5090
  ];
3951
- function policyStatements(statements) {
3952
- return statements.flatMap((statement) => {
3953
- const match = CREATE_POLICY.exec(header(statement.text));
3954
- if (match === null) return [];
3955
- const command = POLICY_COMMAND.exec(group(match, 3))?.[1]?.toLowerCase();
3956
- return [{
3957
- ...statement,
3958
- name: unquote(group(match, 1)),
3959
- table: tableKey(group(match, 2)),
3960
- commands: command === void 0 || command === "all" ? WRITE_COMMANDS : [command],
3961
- guarded: ACTOR_GUARD_CALL.test(statement.text) || inlinesActorGuard(statement.text)
3962
- }];
3963
- });
5091
+ function writeCommands(policy) {
5092
+ return policy.command === "all" ? WRITE_COMMANDS : [policy.command];
3964
5093
  }
3965
5094
  /**
3966
- * The statements PD090 reads: the migration folders, plus the declarative
3967
- * schemas and `rls.out`, which `doctor.migrations` does not drop.
5095
+ * The files PD090 reads: the migration folders, plus the declarative schemas
5096
+ * and `rls.out`, which `doctor.migrations` does not drop.
3968
5097
  */
3969
- function guardStatements(files, cwd, config) {
3970
- const out = config.rls?.out;
3971
- const entries = [
5098
+ function guardFiles(cwd, config) {
5099
+ return [...new Set(sqlFiles$1(cwd, [
3972
5100
  ...config.doctor?.migrations ?? MIGRATION_DIRS,
3973
5101
  "supabase/schemas",
3974
- ...outFiles(out)
3975
- ];
3976
- return [...new Set(sqlFiles$1(cwd, entries))].flatMap((file) => sqlStatements(files.read(file)).map((statement) => Object.assign({ file: rel(cwd, file) }, statement)));
5102
+ ...outFiles(config.rls?.out)
5103
+ ]))];
3977
5104
  }
3978
5105
  /**
3979
5106
  * PD090: a hand-written policy calls `permdock_actor_may_write()`, or inlines
@@ -3981,13 +5108,14 @@ function guardStatements(files, cwd, config) {
3981
5108
  * `permdock rls generate` already writes a restrictive `*_read_only_actors`
3982
5109
  * policy, so the guard runs twice.
3983
5110
  */
3984
- function pd090(cwd, config, files = nodeFiles) {
3985
- const policies = policyStatements(guardStatements(files, cwd, config));
3986
- const generated = new Set(policies.filter((policy) => policy.name.endsWith("_read_only_actors")).flatMap((policy) => policy.commands.map((command) => `${policy.table}:${command}`)));
3987
- return policies.filter((policy) => !policy.name.endsWith("_read_only_actors")).filter((policy) => policy.guarded && policy.commands.some((command) => generated.has(`${policy.table}:${command}`))).map((policy) => ({
5111
+ async function pd090(cwd, config, files = nodeFiles) {
5112
+ const tagged = await taggedPolicyIds(cwd);
5113
+ const policies = (await filePolicies(files, cwd, guardFiles(cwd, config))).filter((policy) => !tagged.has(taggedPolicyId(policyTable(policy), policy.name)));
5114
+ const generated = new Set(policies.filter((policy) => policy.name.endsWith("_read_only_actors")).flatMap((policy) => writeCommands(policy).map((command) => `${policyTable(policy)}:${command}`)));
5115
+ return policies.filter((policy) => !policy.name.endsWith("_read_only_actors")).filter((policy) => guarded(policy) && writeCommands(policy).some((command) => generated.has(`${policyTable(policy)}:${command}`))).map((policy) => ({
3988
5116
  code: "PD090",
3989
5117
  severity: "warning",
3990
- message: `${policy.file}:${String(policy.line)} policy ${policy.name} on ${policy.table} repeats the permdock_actor_may_write() guard of the generated read-only actor policy`,
5118
+ message: `${policy.file}:${String(policy.line)} policy ${policy.name} on ${policyTable(policy)} repeats the permdock_actor_may_write() guard of the generated read-only actor policy`,
3991
5119
  fix: "remove the permdock_actor_may_write() call from the hand-written policy; the restrictive policy applies to it already"
3992
5120
  }));
3993
5121
  }
@@ -4010,10 +5138,6 @@ function pd093(cwd, config, files = nodeFiles) {
4010
5138
  }
4011
5139
  // src/cli/doctor/supabase-checklist.ts
4012
5140
  const SQL_ROOTS = ["supabase/schemas", "supabase/migrations"];
4013
- const POLICY = /create\s+policy\s+(?:"[^"]+"|\w+)\s+on\s+((?:"[^"]+"|\w+)(?:\s*\.\s*(?:"[^"]+"|\w+))?)([^;]*);/giu;
4014
- function tableOf(raw) {
4015
- return raw.replaceAll(/[\s"]/gu, "").toLowerCase();
4016
- }
4017
5141
  function sqlTexts(cwd, files) {
4018
5142
  const found = [];
4019
5143
  const walk = (dir) => {
@@ -4034,14 +5158,14 @@ function sqlTexts(cwd, files) {
4034
5158
  * the row before it updates it, so the update matches nothing and returns zero
4035
5159
  * rows without an error.
4036
5160
  */
4037
- function pd099(cwd, files) {
5161
+ async function pd099(cwd, files) {
4038
5162
  const commands = /* @__PURE__ */ new Map();
4039
- for (const text of sqlTexts(cwd, files)) for (const match of text.matchAll(POLICY)) {
4040
- const table = tableOf(match[1] ?? "");
4041
- const clause = match[2] ?? "";
4042
- const command = /\bfor\s+(select|insert|update|delete|all)\b/iu.exec(clause)?.[1];
5163
+ for (const text of sqlTexts(cwd, files)) for (const statement of await parseSqlLenient(text)) {
5164
+ const policy = readPolicy$1(statement);
5165
+ if (policy === void 0) continue;
5166
+ const table = `${policy.schema}.${policy.table}`.toLowerCase();
4043
5167
  const set = commands.get(table) ?? /* @__PURE__ */ new Set();
4044
- set.add((command ?? "all").toLowerCase());
5168
+ set.add(policy.command);
4045
5169
  commands.set(table, set);
4046
5170
  }
4047
5171
  return [...commands].filter(([, set]) => set.has("update") && !set.has("select") && !set.has("all")).map(([table]) => ({
@@ -4166,6 +5290,65 @@ async function pd061(input) {
4166
5290
  return findings;
4167
5291
  });
4168
5292
  }
5293
+ // src/cli/doctor/table-reads.ts
5294
+ /**
5295
+ * PD128: `permdock.manifest.json` marks a table `tenant` in `rls.tableReads`,
5296
+ * and the select policies the schema files, migrations and `rls.out` define now
5297
+ * make it `row`. better-supabase would share one cache entry between holders
5298
+ * who read different rows.
5299
+ */
5300
+ async function pd128(input) {
5301
+ const manifest = committedManifest(input.cwd);
5302
+ const recorded = manifest?.rls.tableReads;
5303
+ if (manifest === void 0 || recorded === void 0) return [];
5304
+ const current = await manifestTableReads(input.cwd, input.config, manifest);
5305
+ const now = new Map(current.map((read) => [read.table, read]));
5306
+ return recorded.flatMap((read) => {
5307
+ if (read.share !== "tenant") return [];
5308
+ const found = now.get(read.table);
5309
+ if (found?.share === "tenant") return [];
5310
+ const why = found === void 0 ? "no schema file creates it" : `its select policies are row-scoped (${(found.rules ?? []).join(", ")})`;
5311
+ return [{
5312
+ code: "PD128",
5313
+ severity: "error",
5314
+ target: `${MANIFEST_FILE}:rls.tableReads:${read.table}`,
5315
+ message: `${MANIFEST_FILE} marks ${read.table} share: 'tenant', but ${why}`,
5316
+ fix: "run permdock generate to rewrite the manifest, or restore the select policy to <column> in (select permitted_<scope>_ids_by_permission('<key>'))"
5317
+ }];
5318
+ });
5319
+ }
5320
+ /**
5321
+ * PD137: `permdock.manifest.json` lists a function in `rls.sharedFunctions`,
5322
+ * and the schema files now define it so that better-supabase's BS430 would
5323
+ * refuse it: it reads a `row` table, reads the caller, is no longer `stable`
5324
+ * and `security invoker`, or no longer exists. A tenant cache entry that calls
5325
+ * it would be served to callers who read different rows.
5326
+ */
5327
+ async function pd137(input) {
5328
+ const manifest = committedManifest(input.cwd);
5329
+ const recorded = manifest?.rls.sharedFunctions;
5330
+ if (manifest === void 0 || recorded === void 0 || recorded.length === 0) return [];
5331
+ const reads = await manifestTableReads(input.cwd, input.config, manifest);
5332
+ const now = new Map(reads.map((read) => [read.table, read]));
5333
+ const valid = new Set((await sharedFunctionsOf({
5334
+ cwd: input.cwd,
5335
+ config: input.config,
5336
+ schema: manifest.rls.schema,
5337
+ tableReads: reads
5338
+ })).map((entry) => entry.function));
5339
+ return recorded.flatMap((entry) => {
5340
+ if (valid.has(entry.function)) return [];
5341
+ const rows = entry.tables.filter((table) => now.get(table)?.share !== "tenant");
5342
+ const why = rows.length > 0 ? `it reads ${rows.join(", ")}, which ${rows.length === 1 ? "is" : "are"} not a tenant table` : "the schema files no longer define it as a stable, security invoker SQL function that reads no caller";
5343
+ return [{
5344
+ code: "PD137",
5345
+ severity: "error",
5346
+ target: `${MANIFEST_FILE}:rls.sharedFunctions:${entry.function}`,
5347
+ message: `${MANIFEST_FILE} lists ${entry.function} in rls.sharedFunctions, but ${why}`,
5348
+ fix: "run permdock supabase inspect --out to rewrite the list, or restore the function"
5349
+ }];
5350
+ });
5351
+ }
4169
5352
  const DOCTOR_CHECKS = [
4170
5353
  {
4171
5354
  code: "PD001",
@@ -4373,6 +5556,21 @@ const DOCTOR_CHECKS = [
4373
5556
  groups: ["rls"],
4374
5557
  run: pd071
4375
5558
  },
5559
+ {
5560
+ code: "PD122",
5561
+ groups: ["rls"],
5562
+ run: pd122
5563
+ },
5564
+ {
5565
+ code: "PD134",
5566
+ groups: ["rls"],
5567
+ run: pd134
5568
+ },
5569
+ {
5570
+ code: "PD135",
5571
+ groups: ["rls"],
5572
+ run: pd135
5573
+ },
4376
5574
  {
4377
5575
  code: "PD072",
4378
5576
  groups: ["rls"],
@@ -4501,6 +5699,16 @@ const DOCTOR_CHECKS = [
4501
5699
  groups: ["supabase"],
4502
5700
  run: (project) => pd045(project.cwd)
4503
5701
  },
5702
+ {
5703
+ code: "PD136",
5704
+ groups: ["supabase"],
5705
+ run: (project) => pd136(project.cwd)
5706
+ },
5707
+ {
5708
+ code: "PD127",
5709
+ groups: ["supabase", "rls"],
5710
+ run: (project) => pd127(project.cwd, project.config)
5711
+ },
4504
5712
  {
4505
5713
  code: "PD074",
4506
5714
  groups: ["supabase", "helpers"],
@@ -4550,6 +5758,7 @@ const DOCTOR_CHECKS = [
4550
5758
  },
4551
5759
  {
4552
5760
  code: "PD085",
5761
+ database: true,
4553
5762
  groups: ["supabase", "hook"],
4554
5763
  when: (config) => config.supabase?.hook !== void 0,
4555
5764
  run: pd085
@@ -4597,11 +5806,21 @@ const DOCTOR_CHECKS = [
4597
5806
  groups: ["project"],
4598
5807
  run: pd092
4599
5808
  },
5809
+ {
5810
+ code: "PD126",
5811
+ groups: ["project"],
5812
+ run: (project) => pd126(project.cwd, project.files)
5813
+ },
4600
5814
  {
4601
5815
  code: "PD094",
4602
5816
  groups: ["better-supabase"],
4603
5817
  run: pd094
4604
5818
  },
5819
+ {
5820
+ code: "PD123",
5821
+ groups: ["better-supabase"],
5822
+ run: pd123
5823
+ },
4605
5824
  {
4606
5825
  code: "PD095",
4607
5826
  groups: ["rls", "supabase"],
@@ -4682,6 +5901,7 @@ const DOCTOR_CHECKS = [
4682
5901
  },
4683
5902
  {
4684
5903
  code: "PD110",
5904
+ database: true,
4685
5905
  groups: [
4686
5906
  "supabase",
4687
5907
  "hook",
@@ -4720,6 +5940,21 @@ const DOCTOR_CHECKS = [
4720
5940
  when: (config) => config.policy !== void 0,
4721
5941
  run: pd112
4722
5942
  },
5943
+ {
5944
+ code: "PD132",
5945
+ groups: ["snapshot", "performance"],
5946
+ when: (config) => config.budgets !== void 0,
5947
+ run: pd132
5948
+ },
5949
+ {
5950
+ code: "PD133",
5951
+ groups: [
5952
+ "next",
5953
+ "snapshot",
5954
+ "performance"
5955
+ ],
5956
+ run: (project) => pd133(project.sources())
5957
+ },
4723
5958
  {
4724
5959
  code: "PD113",
4725
5960
  groups: ["supabase", "jwt"],
@@ -4730,10 +5965,65 @@ const DOCTOR_CHECKS = [
4730
5965
  groups: ["next", "endpoint"],
4731
5966
  run: pd044
4732
5967
  },
5968
+ {
5969
+ code: "PD116",
5970
+ groups: ["next", "actions"],
5971
+ run: (project) => pd116(project.sources())
5972
+ },
4733
5973
  {
4734
5974
  code: "PD065",
4735
5975
  groups: ["react-native", "endpoint"],
4736
5976
  run: pd065
5977
+ },
5978
+ {
5979
+ code: "PD130",
5980
+ groups: [
5981
+ "next",
5982
+ "supabase",
5983
+ "performance"
5984
+ ],
5985
+ run: (project) => pd130(project.sources())
5986
+ },
5987
+ {
5988
+ code: "PD131",
5989
+ groups: [
5990
+ "rls",
5991
+ "supabase",
5992
+ "performance"
5993
+ ],
5994
+ run: pd131
5995
+ },
5996
+ {
5997
+ code: "PD128",
5998
+ groups: ["rls", "supabase"],
5999
+ run: pd128
6000
+ },
6001
+ {
6002
+ code: "PD137",
6003
+ groups: ["rls", "supabase"],
6004
+ run: pd137
6005
+ },
6006
+ {
6007
+ code: "PD125",
6008
+ groups: ["supabase", "sql"],
6009
+ run: pd125
6010
+ },
6011
+ {
6012
+ code: "PD124",
6013
+ database: true,
6014
+ groups: ["supabase", "rls"],
6015
+ run: pd124
6016
+ },
6017
+ {
6018
+ code: "PD120",
6019
+ groups: ["project"],
6020
+ run: (project) => pd120InProject(project.cwd)
6021
+ },
6022
+ {
6023
+ code: "PD121",
6024
+ groups: ["rls", "supabase"],
6025
+ when: (config) => config.rls !== void 0,
6026
+ run: (project) => pd121InProject(project.cwd)
4737
6027
  }
4738
6028
  ];
4739
6029
  /**
@@ -4784,11 +6074,23 @@ async function runDoctor(input) {
4784
6074
  });
4785
6075
  const selected = (check) => wanted.size === 0 || wanted.has(check.code.toLowerCase()) || check.groups.some((group) => wanted.has(group));
4786
6076
  const collected = [];
6077
+ const judged = /* @__PURE__ */ new Set();
4787
6078
  for (const check of DOCTOR_CHECKS) {
4788
6079
  if (check.when !== void 0 && !check.when(input.config)) continue;
4789
- if (selected(check)) collected.push(...dedupe(await check.run(project)));
6080
+ if (selected(check)) {
6081
+ if (check.database === void 0 || input.db !== void 0) judged.add(check.code);
6082
+ collected.push(...dedupe(await check.run(project)));
6083
+ }
4790
6084
  }
4791
- const { findings, ignored } = applyDoctorIgnores(collected.map(reported), input.config, input.ignore ?? []);
6085
+ const { findings, ignored, wrote } = settleBaseline({
6086
+ cwd: input.cwd,
6087
+ config: input.config,
6088
+ findings: collected.map(reported),
6089
+ judged: (code) => judged.has(code),
6090
+ ignore: input.ignore ?? [],
6091
+ update: input.updateBaseline === true
6092
+ });
6093
+ if (wrote !== void 0) fixed.push(`baseline: ${wrote}`);
4792
6094
  const errors = findings.filter((item) => item.severity === "error").length;
4793
6095
  const warnings = findings.filter((item) => item.severity === "warning").length;
4794
6096
  const report = {
@@ -4881,7 +6183,7 @@ async function supabaseSetup(input) {
4881
6183
  if (policy === void 0) return [];
4882
6184
  let manifest;
4883
6185
  try {
4884
- manifest = supabaseHookManifest(scopeList(policy.scopes), input.config, { out: hookOut(input.cwd, input.config) }, policy);
6186
+ manifest = supabaseHookManifest(scopeList(policy.scopes), await withSchemaDefaults(input.cwd, input.config, policy), { out: hookOut(input.cwd, input.config) }, policy);
4885
6187
  } catch {
4886
6188
  return [];
4887
6189
  }