better-supabase 0.4.0 → 0.5.1

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 (180) hide show
  1. package/README.md +135 -16
  2. package/dist/actor-DaJjqD5R.d.ts +43 -0
  3. package/dist/channel-FQW-CnGR.d.ts +70 -0
  4. package/dist/cli/bin.js +1 -1
  5. package/dist/cli/codemod-DqV7612m.js +388 -0
  6. package/dist/cli/{config-D9R0o1LH.js → config-CPVpXP5I.js} +78 -8
  7. package/dist/cli/{config-SSKSTUl2.js → config-dtoekM0v.js} +1 -1
  8. package/dist/cli/{read-sets-CMa29t9a.js → diff-SjkO5rNr.js} +1 -220
  9. package/dist/cli/{dist-CFgGknmZ.js → dist-DBPdlPYK.js} +4 -4
  10. package/dist/cli/{dist-B1MvLv-M.js → dist-DreZ24Sz.js} +1 -1
  11. package/dist/cli/{dist-Du7VnEUG.js → dist-xn4wlboc.js} +112 -1
  12. package/dist/cli/{doctor-BOym3mbL.js → doctor-C_A-KEAz.js} +533 -50
  13. package/dist/cli/{env-BZ0uy8XK.js → env-DmKv_G4A.js} +1 -1
  14. package/dist/cli/gen-CIdSQZad.js +2 -0
  15. package/dist/cli/{gen-Ccn_p90L.js → gen-CjElD1Vw.js} +321 -88
  16. package/dist/cli/index.d.ts +1 -1
  17. package/dist/cli/index.js +4 -4
  18. package/dist/cli/{init-ClnxRYBF.js → init-DMa6M7hV.js} +2 -2
  19. package/dist/cli/{introspect-DxqfkVIv.js → introspect-BKlaIu_M.js} +2 -2
  20. package/dist/cli/{openapi-8WHjxiTJ.js → openapi-Cp5Fyta-.js} +1 -1
  21. package/dist/cli/read-sets-VQcPgxU9.js +436 -0
  22. package/dist/cli/{run-CP20LKk_.js → run-Bo_NLT5n.js} +16 -12
  23. package/dist/cli/{seed-5J6eu_Xg.js → seed-CUlqWh-8.js} +1 -1
  24. package/dist/cli/sql-CVx-1O8G.js +373 -0
  25. package/dist/cli/{version-5mW_8sY1.js → version-BCtlgDQx.js} +1 -1
  26. package/dist/client/index.d.ts +1 -1
  27. package/dist/client/index.js +3 -10
  28. package/dist/clone-BfgmLU90.js +21 -0
  29. package/dist/{compiler-DB3aSFOA.d.ts → compiler-BXH_aZ7N.d.ts} +2 -2
  30. package/dist/config/index.d.ts +4 -4
  31. package/dist/config/index.js +4 -4
  32. package/dist/{config-C1CYcm6o.d.ts → config-Bv7gvfzC.d.ts} +185 -11
  33. package/dist/{config-CbvFmGD8.js → config-DreERlKo.js} +1 -1
  34. package/dist/{define-CRS2MRV3.d.ts → define-Bp_BZa5h.d.ts} +11 -7
  35. package/dist/{define-Bh0AqTik.js → define-cNKzqwL_.js} +202 -16
  36. package/dist/edge/index.d.ts +16 -5
  37. package/dist/edge/index.js +10 -7
  38. package/dist/{entitlements-Dm-FHpNH.d.ts → entitlements-BiJZ4t49.d.ts} +1 -1
  39. package/dist/env/index.d.ts +2 -2
  40. package/dist/env/index.js +34 -1
  41. package/dist/{errors-L0xK41y_.js → errors-DtwXa6b8.js} +1 -0
  42. package/dist/events/index.d.ts +3 -2
  43. package/dist/events/index.js +65 -12
  44. package/dist/events-aIO7vsIk.d.ts +230 -0
  45. package/dist/{result-CqEsbgYs.d.ts → executor-BunPOO-k.d.ts} +200 -1
  46. package/dist/{executor-CZ7ImRiD.d.ts → executor-Cghdstwu.d.ts} +1 -2
  47. package/dist/{executor-CVt6dD0B.js → executor-XycESQPH.js} +3 -3
  48. package/dist/hono/index.d.ts +17 -6
  49. package/dist/hono/index.js +40 -5
  50. package/dist/impersonation-BgSHAYLf.js +133 -0
  51. package/dist/{resolve-BAqQcwMW.d.ts → impersonation-BmePsuxz.d.ts} +36 -6
  52. package/dist/{index-BhHEC04r.d.ts → index-C7f8cOBM.d.ts} +2 -2
  53. package/dist/{index-Dy6kuF0P.d.ts → index-CLg87OBW.d.ts} +6 -1
  54. package/dist/{index-Cf-D2jk1.d.ts → index-CWMDdEr4.d.ts} +2 -2
  55. package/dist/{index-D5IfUIDh.d.ts → index-DOESKG27.d.ts} +33 -8
  56. package/dist/{index-DFmOpBGC.d.ts → index-DgILJRXj.d.ts} +35 -9
  57. package/dist/{index-RlLXd8dL.d.ts → index-DmXSxbLi.d.ts} +4 -4
  58. package/dist/{index-BBdvo-5d.d.ts → index-Dp2VDwog.d.ts} +49 -6
  59. package/dist/{index-528Ugmyp.d.ts → index-SaTsEfGP.d.ts} +76 -8
  60. package/dist/{index-BAy4tsAP.d.ts → index-fag8VJZ2.d.ts} +3 -4
  61. package/dist/index.d.ts +30 -13
  62. package/dist/index.js +10 -9
  63. package/dist/jobs/index.d.ts +147 -101
  64. package/dist/jobs/index.js +744 -237
  65. package/dist/{json-schema-DP6V7cbr.js → json-schema-m1fiwKgN.js} +22 -1
  66. package/dist/kit-events-CTFDfSwb.js +60 -0
  67. package/dist/kit-transport-B82k1djG.d.ts +33 -0
  68. package/dist/kit-transport-DJlHQUBU.js +55 -0
  69. package/dist/{config-BpxDfnbg.js → kits-CGLLrNPd.js} +37 -9
  70. package/dist/list/index.d.ts +1 -1
  71. package/dist/{live-BHakSWWo.d.ts → live-D9W2M5aO.d.ts} +6 -5
  72. package/dist/mcp/index.d.ts +25 -8
  73. package/dist/mcp/index.js +23 -14
  74. package/dist/{mfa-C7MNQ1Ob.d.ts → mfa-Cu96oJdw.d.ts} +2 -16
  75. package/dist/next/index.d.ts +31 -10
  76. package/dist/next/index.js +136 -27
  77. package/dist/notifications/index.d.ts +162 -0
  78. package/dist/notifications/index.js +264 -0
  79. package/dist/openapi/index.d.ts +1 -1
  80. package/dist/openapi/index.js +2 -2
  81. package/dist/orgs/index.d.ts +132 -0
  82. package/dist/orgs/index.js +245 -0
  83. package/dist/orpc/index.d.ts +28 -8
  84. package/dist/orpc/index.js +16 -3
  85. package/dist/otel/index.d.ts +21 -2
  86. package/dist/otel/index.js +50 -9
  87. package/dist/permdock-sql-C2Inc6Xc.d.ts +29 -0
  88. package/dist/permdock-sql-DgOfeixi.js +51 -0
  89. package/dist/plugin-DwARMuQp.js +59 -0
  90. package/dist/{plugin-bNhvJwRh.d.ts → plugin-o144f322.d.ts} +17 -5
  91. package/dist/plugins/actor/index.d.ts +5 -2
  92. package/dist/plugins/actor/index.js +22 -8
  93. package/dist/plugins/rules/index.d.ts +2 -2
  94. package/dist/plugins/rules/index.js +15 -10
  95. package/dist/plugins/soft-delete/index.d.ts +3 -3
  96. package/dist/plugins/soft-delete/index.js +14 -5
  97. package/dist/plugins/tenant/index.d.ts +2 -2
  98. package/dist/plugins/tenant/index.js +38 -20
  99. package/dist/plugins/timestamps/index.d.ts +1 -1
  100. package/dist/plugins/timestamps/index.js +4 -3
  101. package/dist/plugins/validation/index.d.ts +2 -2
  102. package/dist/plugins/validation/index.js +26 -6
  103. package/dist/{pool-DFwEQwmN.d.ts → pool-C9voM4Kw.d.ts} +17 -6
  104. package/dist/postgres/index.d.ts +5 -5
  105. package/dist/postgres/index.js +20 -11
  106. package/dist/{postgrest-Bc-0Xw62.d.ts → postgrest-CruYKAvV.d.ts} +1 -1
  107. package/dist/{problem-BihjPR0t.js → problem-BW1KhzSG.js} +2 -1
  108. package/dist/{problem-U8UEKccv.d.ts → problem-Blxe8S31.d.ts} +1 -1
  109. package/dist/query/index.d.ts +2 -2
  110. package/dist/query/index.js +3 -3
  111. package/dist/{query-BMMSWbI7.js → query-CCbo44lG.js} +2 -2
  112. package/dist/queue-BYUCjr59.d.ts +252 -0
  113. package/dist/react/index.d.ts +8 -7
  114. package/dist/react/index.js +4 -3
  115. package/dist/react/server.d.ts +14 -3
  116. package/dist/react/server.js +10 -2
  117. package/dist/react/session.d.ts +7 -1
  118. package/dist/react/session.js +9 -1
  119. package/dist/{react-CQHMaESR.js → react-C_s7kiNz.js} +103 -11
  120. package/dist/{read-set-FWK8qQ58.js → read-set-DQFt1N_Y.js} +22 -1
  121. package/dist/realtime/index.d.ts +3 -3
  122. package/dist/realtime/index.js +5 -4
  123. package/dist/{refresh-BwYkyNOQ.d.ts → refresh-CFPX0Qft.d.ts} +1 -1
  124. package/dist/{resource-BJcaIfxi.d.ts → resource-DNRFP7KR.d.ts} +5 -5
  125. package/dist/{resource-My_y-Syh.js → resource-mqfJW4YF.js} +22 -7
  126. package/dist/respond-BR1fJWOB.d.ts +377 -0
  127. package/dist/{result-Bj6yt33D.js → result-BKiliPY7.js} +1 -1
  128. package/dist/server/index.d.ts +15 -12
  129. package/dist/server/index.js +11 -17
  130. package/dist/{server-BA75B0mT.js → server-B1mZ7CgQ.js} +259 -37
  131. package/dist/{shared-DnoCdMDr.js → shared-D1dRUrAg.js} +16 -2
  132. package/dist/signers-Cc6r98SW.d.ts +162 -0
  133. package/dist/{simplify-Cqvfr9dj.js → simplify-_0oUKqCd.js} +4 -115
  134. package/dist/sql/index.d.ts +283 -11
  135. package/dist/sql/index.js +8705 -775
  136. package/dist/{sql-B34HU2DI.js → sql-Coh6n4cC.js} +9 -2
  137. package/dist/ssr/index.d.ts +4 -4
  138. package/dist/ssr/index.js +1 -2
  139. package/dist/{standard-BRyBGTtp.js → standard-D7r6dMUu.js} +6 -3
  140. package/dist/{standard-BsaCYQJc.d.ts → standard-J4YgMOLm.d.ts} +1 -1
  141. package/dist/{stats-C_YxA2r1.js → stats-Bqob3WqT.js} +4 -4
  142. package/dist/storage/index.d.ts +4 -4
  143. package/dist/storage/index.js +155 -26
  144. package/dist/support-CEPwlw2G.d.ts +89 -0
  145. package/dist/support-view-B8SlToQX.d.ts +17 -0
  146. package/dist/support-view-g4YLBeqX.js +18 -0
  147. package/dist/support-wHnK6zp-.js +293 -0
  148. package/dist/{permdock-sql-C4KFzLc9.js → template-TxrGI5jR.js} +2 -31
  149. package/dist/{temporal-BwshQk0W.js → temporal-CVlIV2DZ.js} +17 -4
  150. package/dist/{temporal-required-CBNHT6ni.js → temporal-required-CAt4Dc9Z.js} +2 -2
  151. package/dist/testing/index.d.ts +132 -10
  152. package/dist/testing/index.js +476 -8
  153. package/dist/{types-DONv9SHN.d.ts → types-Dnf_wRDz.d.ts} +26 -3
  154. package/dist/user-change-CHFEUro1.js +49 -0
  155. package/dist/{webhooks-Bh_Jf_-l.js → verify-Ce49ETPz.js} +5 -5
  156. package/dist/{version-Bmf7_FzM.js → version-DOYTYwHP.js} +1 -1
  157. package/dist/{mfa-byfjruR9.js → view-Bn6HNKUe.js} +97 -98
  158. package/dist/{view-B64o81wp.d.ts → view-CbgObAeb.d.ts} +22 -31
  159. package/dist/webhooks/index.d.ts +135 -4
  160. package/dist/webhooks/index.js +588 -2
  161. package/dist/wire-D2dT86vi.js +35 -0
  162. package/package.json +27 -19
  163. package/schemas/config-v1.json +131 -1
  164. package/schemas/doctor-report-v1.json +11 -0
  165. package/skills/better-supabase/SKILL.md +9 -6
  166. package/skills/better-supabase/references/plugins.md +6 -3
  167. package/skills/better-supabase/references/troubleshooting.md +1 -0
  168. package/skills/better-supabase-api/SKILL.md +9 -2
  169. package/skills/better-supabase-api/references/adapters.md +11 -8
  170. package/skills/better-supabase-auth/SKILL.md +18 -7
  171. package/skills/better-supabase-auth/references/permdock.md +78 -11
  172. package/dist/cli/gen-D5cLCULx.js +0 -2
  173. package/dist/cli/sql-D4VbqmXi.js +0 -199
  174. package/dist/events-B21UOhvP.d.ts +0 -84
  175. package/dist/executor-B5IoUxLE.d.ts +0 -195
  176. package/dist/invalidate-CgxmRamI.js +0 -24
  177. package/dist/permdock-sql-DImJULY-.d.ts +0 -17
  178. package/dist/plugin-BqR6wKMB.js +0 -23
  179. package/dist/respond-DgIbdrt8.d.ts +0 -194
  180. package/dist/view-BrJI2LKp.js +0 -45
@@ -0,0 +1,436 @@
1
+ import { i as importModule } from "./config-CPVpXP5I.js";
2
+ import { resolve } from "node:path";
3
+ import { existsSync } from "node:fs";
4
+ import { readFile } from "node:fs/promises";
5
+ import { KIT_ID_TYPES, compileReadSets, kitIdType, permdockKeyStatus } from "better-supabase/sql";
6
+ import { isReadSet } from "better-supabase";
7
+ //#region src/cli/permdock.ts
8
+ const PERMDOCK_CONFIGS = [
9
+ "permdock.config.ts",
10
+ "permdock.config.mts",
11
+ "permdock.config.js",
12
+ "permdock.config.mjs"
13
+ ];
14
+ /** The PermDock config file in `root`, if there is one. */
15
+ function permdockConfig(root) {
16
+ return PERMDOCK_CONFIGS.find((file) => existsSync(resolve(root, file)));
17
+ }
18
+ const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
19
+ const isString = (value) => typeof value === "string";
20
+ const strings = (value) => Array.isArray(value) ? value.filter(isString) : [];
21
+ const column = (value) => isRecord(value) && isString(value["column"]) ? { column: value["column"] } : void 0;
22
+ function manifestValue(value, accept) {
23
+ if (!isRecord(value)) return void 0;
24
+ if (isString(value["column"])) return { column: value["column"] };
25
+ return accept(value["value"]) ? { value: value["value"] } : void 0;
26
+ }
27
+ const roleValue = (value) => isString(value) || Array.isArray(value) && value.every(isString);
28
+ function membership(value) {
29
+ if (!isRecord(value) || !isString(value["table"])) return void 0;
30
+ const user = column(value["user"]);
31
+ const id = column(value["id"]);
32
+ const scope = manifestValue(value["scope"], isString);
33
+ if (!user || !id || !scope) return void 0;
34
+ const role = manifestValue(value["role"], roleValue);
35
+ const expiresAt = column(value["expiresAt"]);
36
+ return {
37
+ table: value["table"],
38
+ user,
39
+ scope,
40
+ id,
41
+ ...role ? { role } : {},
42
+ ...expiresAt ? { expiresAt } : {},
43
+ columns: strings(value["columns"])
44
+ };
45
+ }
46
+ /** Reads a parsed manifest; throws with the reason when it isn't version 1. */
47
+ function parseManifest(json) {
48
+ if (!isRecord(json)) throw new TypeError("not a JSON object");
49
+ if (json["version"] !== 1) throw new TypeError(`version ${String(json["version"])} is not supported (this release reads version 1)`);
50
+ const hook = json["hook"];
51
+ const rls = json["rls"];
52
+ if (isRecord(rls) && rls["mode"] !== "jwt" && rls["mode"] !== "database") throw new TypeError(`rls.mode ${JSON.stringify(rls["mode"])} is not supported (this release reads "jwt" and "database")`);
53
+ const budget = isRecord(json["budget"]) ? json["budget"]["bytes"] : void 0;
54
+ return {
55
+ version: 1,
56
+ ...typeof budget === "number" ? { budget } : {},
57
+ ...isRecord(hook) && isString(hook["schema"]) && isString(hook["function"]) ? { hook: {
58
+ schema: hook["schema"],
59
+ function: hook["function"]
60
+ } } : {},
61
+ ...isString(json["tenantClaim"]) ? { tenantClaim: json["tenantClaim"] } : {},
62
+ claims: (Array.isArray(json["claims"]) ? json["claims"] : []).flatMap((claim) => isRecord(claim) && isString(claim["name"]) && isString(claim["source"]) ? [{
63
+ name: claim["name"],
64
+ source: claim["source"]
65
+ }] : []),
66
+ memberships: (Array.isArray(json["memberships"]) ? json["memberships"] : []).flatMap((entry) => {
67
+ const parsed = membership(entry);
68
+ return parsed ? [parsed] : [];
69
+ }),
70
+ ...isRecord(rls) && isString(rls["schema"]) ? { rls: {
71
+ schema: rls["schema"],
72
+ mode: rls["mode"] === "jwt" ? "jwt" : "database",
73
+ ...isString(rls["tenantClaim"]) ? { tenantClaim: rls["tenantClaim"] } : {},
74
+ scopes: (Array.isArray(rls["scopes"]) ? rls["scopes"] : []).flatMap((scope) => isRecord(scope) && isString(scope["name"]) ? [{
75
+ name: scope["name"],
76
+ ...isString(scope["type"]) ? { type: scope["type"] } : {},
77
+ ...isString(scope["within"]) ? { within: scope["within"] } : {}
78
+ }] : []),
79
+ helpers: (Array.isArray(rls["helpers"]) ? rls["helpers"] : []).flatMap((helper) => isRecord(helper) && isString(helper["name"]) && isString(helper["args"]) && isString(helper["returns"]) ? [{
80
+ name: helper["name"],
81
+ args: helper["args"],
82
+ returns: helper["returns"],
83
+ execute: strings(helper["execute"])
84
+ }] : []),
85
+ ...Array.isArray(rls["memberships"]) ? { memberships: rls["memberships"].flatMap((entry) => {
86
+ const parsed = membership(entry);
87
+ return parsed ? [parsed] : [];
88
+ }) } : {}
89
+ } } : {},
90
+ decidingColumns: strings(json["decidingColumns"])
91
+ };
92
+ }
93
+ /**
94
+ * The keys of a parsed `permissions.catalog.json`, each with its scope and
95
+ * its `rowConditions` flag when it is a boolean. A non-boolean flag is
96
+ * dropped, so `permdockKeyStatus` reads the key as unknown. Throws unless
97
+ * the catalog is version 1.
98
+ */
99
+ function parseCatalog(json) {
100
+ if (!isRecord(json) || !Array.isArray(json["permissions"])) throw new TypeError("has no permissions array");
101
+ if (json["version"] !== 1) throw new TypeError(`version ${String(json["version"])} is not supported (this release reads version 1)`);
102
+ return { permissions: json["permissions"].flatMap((permission) => {
103
+ if (!isRecord(permission) || !isString(permission["key"])) return [];
104
+ const flag = permission["rowConditions"];
105
+ const scope = permission["scope"];
106
+ return [{
107
+ key: permission["key"],
108
+ ...typeof flag === "boolean" ? { rowConditions: flag } : {},
109
+ ...isString(scope) ? { scope } : {}
110
+ }];
111
+ }) };
112
+ }
113
+ async function readJson(root, path) {
114
+ const absolute = resolve(root, path);
115
+ if (!existsSync(absolute)) return { missing: true };
116
+ try {
117
+ return { json: JSON.parse(await readFile(absolute, "utf8")) };
118
+ } catch (cause) {
119
+ return { problem: `${path}: ${cause instanceof Error ? cause.message : String(cause)}` };
120
+ }
121
+ }
122
+ /**
123
+ * Reads PermDock's JSON outputs: the manifest `permdock supabase inspect
124
+ * --out` writes and the catalog `permdock catalog` writes. Nothing is
125
+ * imported from PermDock. Returns `undefined` when the project has neither a
126
+ * PermDock config nor a manifest.
127
+ */
128
+ async function readPermdock(root, paths) {
129
+ const config = permdockConfig(root);
130
+ const problems = [];
131
+ const manifestFile = await readJson(root, paths.manifest);
132
+ let manifest;
133
+ if ("json" in manifestFile) try {
134
+ manifest = parseManifest(manifestFile.json);
135
+ } catch (cause) {
136
+ problems.push(`${paths.manifest}: ${cause instanceof Error ? cause.message : String(cause)}`);
137
+ }
138
+ else if ("problem" in manifestFile) problems.push(manifestFile.problem);
139
+ if (!config && !manifest && "missing" in manifestFile) return void 0;
140
+ const catalogFile = await readJson(root, paths.catalog);
141
+ let catalog;
142
+ if ("json" in catalogFile) try {
143
+ catalog = parseCatalog(catalogFile.json);
144
+ } catch (cause) {
145
+ problems.push(`${paths.catalog}: ${cause instanceof Error ? cause.message : String(cause)}`);
146
+ }
147
+ else if ("problem" in catalogFile) problems.push(catalogFile.problem);
148
+ return {
149
+ ...config ? { config } : {},
150
+ manifestPath: paths.manifest,
151
+ ...manifest ? { manifest } : {},
152
+ catalogPath: paths.catalog,
153
+ ...catalog ? { catalog } : {},
154
+ problems
155
+ };
156
+ }
157
+ /** How findings name the PermDock project: its config file or its manifest. */
158
+ const permdockSource = (project) => project.config ?? project.manifestPath;
159
+ const HOOK_MARKER = /^--\s*permdock:hook\s+v(\d+)([^\n]*)$/m;
160
+ const GRANTS_MARKER = /^--\s*permdock:grants\s+v(\d+)([^\n]*)$/m;
161
+ function markerFields(rest) {
162
+ const fields = /* @__PURE__ */ new Map();
163
+ for (const match of rest.matchAll(/(\w+)=(\S*)/g)) fields.set(match[1], match[2]);
164
+ return fields;
165
+ }
166
+ /** The `-- permdock:hook v1 schema=... tenant=... budget=... claims=...` line PermDock's hook file starts with. */
167
+ function parseHookMarker(sql) {
168
+ const match = HOOK_MARKER.exec(sql);
169
+ if (!match) return void 0;
170
+ const fields = markerFields(match[2]);
171
+ const budget = Number(fields.get("budget"));
172
+ const schema = fields.get("schema");
173
+ const tenantClaim = fields.get("tenant");
174
+ return {
175
+ version: Number(match[1]),
176
+ ...schema ? { schema } : {},
177
+ ...tenantClaim ? { tenantClaim } : {},
178
+ ...Number.isFinite(budget) && fields.has("budget") ? { budget } : {},
179
+ claims: (fields.get("claims") ?? "").split(",").filter(Boolean)
180
+ };
181
+ }
182
+ /** The `-- permdock:grants v1 schema=...` line of the migration `--grants-out` writes. */
183
+ function parseGrantsMarker(sql) {
184
+ const match = GRANTS_MARKER.exec(sql);
185
+ if (!match) return void 0;
186
+ const schema = markerFields(match[2]).get("schema");
187
+ return {
188
+ version: Number(match[1]),
189
+ ...schema ? { schema } : {}
190
+ };
191
+ }
192
+ /**
193
+ * The PermDock scope tenants are: `explicit`, which must be one of the
194
+ * manifest's `rls.scopes`, else the one scope without `within`. A missing or
195
+ * unreadable manifest, no `rls` block, no root scope or several, and a scope
196
+ * without a type this kit renders are invalid rather than a guess.
197
+ */
198
+ function manifestScope(project, explicit, reader) {
199
+ const { subject, helpers, setting, optOut } = reader;
200
+ if (!project.manifest) {
201
+ const problem = project.problems.find((entry) => entry.startsWith(project.manifestPath));
202
+ return {
203
+ kind: "invalid",
204
+ problem: problem ? `Could not read PermDock's manifest: ${problem}. Run \`permdock supabase inspect --out\` with a current PermDock, ${optOut}` : `${permdockSource(project)} is a PermDock project, but there is no ${project.manifestPath}. Run \`permdock supabase inspect --out\`, ${optOut}`
205
+ };
206
+ }
207
+ const rls = project.manifest.rls;
208
+ if (!rls) return {
209
+ kind: "invalid",
210
+ problem: `${project.manifestPath} has no rls block, so ${subject} can't find PermDock's ${helpers}. Run \`permdock rls generate\`, then \`permdock supabase inspect --out\`, ${optOut}`
211
+ };
212
+ const names = rls.scopes.map((scope) => scope.name).join(", ") || "none";
213
+ let scope;
214
+ if (explicit === void 0) {
215
+ const roots = rls.scopes.filter((entry) => entry.within === void 0);
216
+ if (roots.length !== 1) return {
217
+ kind: "invalid",
218
+ problem: `${project.manifestPath} has no single root scope (${roots.map((entry) => entry.name).join(", ") || "none"}), so ${subject} can't tell which scope tenants are. Set ${setting}: { scope } to one of ${names}.`
219
+ };
220
+ scope = roots[0].name;
221
+ } else {
222
+ scope = explicit;
223
+ if (!rls.scopes.some((entry) => entry.name === scope)) return {
224
+ kind: "invalid",
225
+ problem: `${setting}.scope is "${scope}", but ${project.manifestPath} has the scopes ${names}. Set ${setting}: { scope } to one of them, or remove it to use the root scope.`
226
+ };
227
+ }
228
+ const declared = rls.scopes.find((entry) => entry.name === scope)?.type;
229
+ if (declared === void 0) return {
230
+ kind: "invalid",
231
+ problem: `${project.manifestPath} gives scope "${scope}" no type, so ${subject} can't tell its id type. Run \`permdock supabase inspect --out\` with a current PermDock.`
232
+ };
233
+ const idType = kitIdType(declared);
234
+ if (idType === void 0) return {
235
+ kind: "invalid",
236
+ problem: `${project.manifestPath} gives scope "${scope}" the type ${declared}, but ${subject} renders only ${KIT_ID_TYPES.join(", ").replace(/, (?=[^,]*$)/, " or ")} ids.`
237
+ };
238
+ return {
239
+ kind: "ok",
240
+ manifest: project.manifest,
241
+ rls,
242
+ scope,
243
+ idType
244
+ };
245
+ }
246
+ /**
247
+ * The membership tables PermDock's `member_<scope>_ids_for` reads for
248
+ * `scope`: the manifest's `rls.memberships` that can cover it (a scope
249
+ * column, or a fixed scope equal to `scope`). A manifest from a PermDock
250
+ * without `rls.memberships` falls back to the hook's sources.
251
+ */
252
+ function scopeMemberships(manifest, scope) {
253
+ const rls = manifest.rls?.memberships;
254
+ return {
255
+ sources: (rls ?? manifest.memberships).filter((source) => !("value" in source.scope) || source.scope.value === scope),
256
+ from: rls === void 0 ? "hook" : "rls"
257
+ };
258
+ }
259
+ /**
260
+ * PermDock mode, when the project uses PermDock and `entitlements.permdock`
261
+ * is not `false`. The scope is `entitlements.permdock.scope`, which must be
262
+ * one of the manifest's `rls.scopes`, else the one scope without `within`.
263
+ * No root scope, or more than one, is invalid rather than a guess. A
264
+ * PermDock project without a readable manifest or without its `rls` block
265
+ * is invalid too, so the module never falls back to `tenant` on its own.
266
+ * Memberships come from `rls.memberships`, the tables PermDock's helpers
267
+ * read, and from the hook's sources only when the manifest has none.
268
+ */
269
+ function entitlementsMode(config, project) {
270
+ const setting = config.entitlements.permdock;
271
+ if (setting === false || !project) return { kind: "tenant" };
272
+ const chosen = manifestScope(project, setting.scope, {
273
+ subject: "the entitlements module",
274
+ helpers: "membership helpers",
275
+ setting: "entitlements.permdock",
276
+ optOut: "or set entitlements.permdock: false to keep the tenant module's memberships."
277
+ });
278
+ if (chosen.kind === "invalid") return chosen;
279
+ return {
280
+ kind: "permdock",
281
+ permdock: {
282
+ schema: chosen.rls.schema,
283
+ scope: chosen.scope,
284
+ idType: chosen.idType,
285
+ memberships: scopeMemberships(chosen.manifest, chosen.scope).sources.map((source) => ({
286
+ table: source.table,
287
+ userColumn: source.user.column,
288
+ scope: source.scope,
289
+ idColumn: source.id.column
290
+ }))
291
+ }
292
+ };
293
+ }
294
+ /**
295
+ * The `permdock` access model's helpers, read from the manifest whatever
296
+ * `entitlements` says: `rls.schema`, the root scope (or
297
+ * `kits.access.permdock.scope`, which the manifest must declare) and that
298
+ * scope's id type. `off` when another model is chosen. Without a PermDock
299
+ * project or a usable manifest the model is invalid, never a default.
300
+ */
301
+ function accessPermdockMode(config, project) {
302
+ const access = config.kits.access;
303
+ if (access?.model !== "permdock") return { kind: "off" };
304
+ const optOut = "or choose another kits.access.model.";
305
+ if (!project) return {
306
+ kind: "invalid",
307
+ problem: `kits.access.model is "permdock", but there is no PermDock project here (no permdock.config.ts and no manifest). Run \`permdock supabase inspect --out\` to write the manifest, ${optOut}`
308
+ };
309
+ const chosen = manifestScope(project, access.permdock?.scope, {
310
+ subject: "the permdock access model",
311
+ helpers: "permission helpers",
312
+ setting: "kits.access.permdock",
313
+ optOut
314
+ });
315
+ if (chosen.kind === "invalid") return chosen;
316
+ const schema = access.permdock?.schema;
317
+ if (schema !== void 0 && schema !== chosen.rls.schema) return {
318
+ kind: "invalid",
319
+ problem: `kits.access.permdock.schema is "${schema}", but ${project.manifestPath} puts PermDock's helpers in "${chosen.rls.schema}". Set it to "${chosen.rls.schema}", or remove it to use the manifest's.`
320
+ };
321
+ const idType = access.idType === void 0 ? void 0 : kitIdType(access.idType);
322
+ if (idType !== void 0 && idType !== chosen.idType) return {
323
+ kind: "invalid",
324
+ problem: `kits.access.idType is "${access.idType}", but ${project.manifestPath} gives scope "${chosen.scope}" the type ${chosen.idType}. Set kits.access.idType to "${chosen.idType}", or remove it to use the manifest's.`
325
+ };
326
+ return {
327
+ kind: "permdock",
328
+ access: {
329
+ schema: chosen.rls.schema,
330
+ scope: chosen.scope,
331
+ idType: chosen.idType
332
+ }
333
+ };
334
+ }
335
+ const ROW_CONDITIONS_FIX = "Use the policies `permdock rls generate` writes for it, or a permission whose catalog entry has rowConditions: false.";
336
+ const REGENERATE_FIX = "Regenerate it with a current `permdock catalog`, which writes rowConditions for every permission.";
337
+ /**
338
+ * Why the SQL helpers can't be trusted with `key`, or `undefined` when the
339
+ * catalog marks it `rowConditions: false`. An entry without the flag and a
340
+ * key the catalog doesn't list are unknown, so they count as unsafe.
341
+ */
342
+ function unsafeKey(catalog, key, catalogPath) {
343
+ const status = permdockKeyStatus(catalog, key);
344
+ switch (status) {
345
+ case "scope-only": return;
346
+ case "row-conditions": return {
347
+ status,
348
+ reason: `has row conditions in ${catalogPath}`,
349
+ fix: ROW_CONDITIONS_FIX
350
+ };
351
+ case "no-flag": return {
352
+ status,
353
+ reason: `has no rowConditions flag in ${catalogPath}, so whether it has row conditions is unknown`,
354
+ fix: REGENERATE_FIX
355
+ };
356
+ case "missing": return {
357
+ status,
358
+ reason: `is not in ${catalogPath}`,
359
+ fix: REGENERATE_FIX
360
+ };
361
+ default: return status;
362
+ }
363
+ }
364
+ /**
365
+ * Checks the keys the kit modules pass to PermDock's helpers against
366
+ * `permissions.catalog.json`, with the statuses bucket policies use: only
367
+ * `rowConditions: false` passes. A missing or unreadable catalog is a
368
+ * problem too, since every key is then unknown.
369
+ */
370
+ function kitKeyProblems(project, keys, access) {
371
+ if (keys.length === 0) return [];
372
+ const catalog = project.catalog;
373
+ if (!catalog) {
374
+ const unreadable = project.problems.find((problem) => problem.startsWith(project.catalogPath));
375
+ return [{
376
+ target: project.catalogPath,
377
+ message: unreadable ? `Could not read PermDock's catalog: ${unreadable}. The permdock access model passes ${keys.length} kit permission keys to PermDock's helpers, so whether they have row conditions is unknown. Run \`permdock catalog\` with a current PermDock.` : `The permdock access model passes ${keys.length} kit permission keys to PermDock's helpers, but there is no ${project.catalogPath}, so whether they have row conditions is unknown. Run \`permdock catalog\`, or set permdock.catalog in the config.`
378
+ }];
379
+ }
380
+ return keys.flatMap((entry) => {
381
+ const problem = unsafeKey(catalog, entry.key, project.catalogPath);
382
+ if (!problem) return [];
383
+ const helper = entry.scope === "platform" ? `${access.schema}.permdock_has` : `${access.schema}.permitted_${access.scope}_ids`;
384
+ const setting = `kits.${entry.module}.permissions.${entry.action}`;
385
+ const fix = problem.status === "row-conditions" ? `PermDock's SQL helpers check role and scope, not row conditions, so the module would grant it everywhere in the scope. Set ${setting} to a permission whose catalog entry has rowConditions: false.` : `${problem.fix} If PermDock doesn't define it, set ${setting} to a key the catalog lists.`;
386
+ return [{
387
+ target: setting,
388
+ message: `The ${entry.module} module checks "${entry.key}" (${entry.action}) with ${helper}, but it ${problem.reason}. ${fix}`
389
+ }];
390
+ });
391
+ }
392
+ /** A helper the `permdock` access model calls, as `schema.name`, and the role it runs as. */
393
+ const accessRequirements = (access) => [{
394
+ helper: `${access.schema}.permitted_${access.scope}_ids`,
395
+ role: "authenticated"
396
+ }, {
397
+ helper: `${access.schema}.permdock_has`,
398
+ role: "authenticated"
399
+ }];
400
+ /**
401
+ * The helpers the `entitlements` module calls for the chosen scope:
402
+ * `member_<scope>_ids` from `has_entitlement` as `authenticated`, and
403
+ * `member_<scope>_ids_for` from `feature_claims`, which PermDock's hook runs
404
+ * as `supabase_auth_admin`.
405
+ */
406
+ const entitlementRequirements = (permdock) => [{
407
+ kind: "member",
408
+ helper: `${permdock.schema}.member_${permdock.scope}_ids`,
409
+ caller: "has_entitlement",
410
+ role: "authenticated"
411
+ }, {
412
+ kind: "member-for",
413
+ helper: `${permdock.schema}.member_${permdock.scope}_ids_for`,
414
+ caller: "feature_claims",
415
+ role: "supabase_auth_admin"
416
+ }];
417
+ //#endregion
418
+ //#region src/cli/read-sets.ts
419
+ /** Every read set exported by the modules in `config.readSets`. */
420
+ async function loadReadSets(config) {
421
+ const sets = [];
422
+ for (const entry of config.readSets) {
423
+ const loaded = await importModule(resolve(config.root, entry));
424
+ const found = Object.values(loaded).filter(isReadSet);
425
+ if (found.length === 0) throw new Error(`${entry} exports no read set (defineReadSet)`);
426
+ for (const set of found) if (!sets.includes(set)) sets.push(set);
427
+ }
428
+ return sets;
429
+ }
430
+ /** The compiled functions for `config.readSets`; empty when none are configured. */
431
+ async function compiledReadSets(config) {
432
+ if (config.readSets.length === 0) return [];
433
+ return compileReadSets(await loadReadSets(config));
434
+ }
435
+ //#endregion
436
+ export { entitlementsMode as a, parseHookMarker as c, scopeMemberships as d, unsafeKey as f, entitlementRequirements as i, permdockSource as l, accessPermdockMode as n, kitKeyProblems as o, accessRequirements as r, parseGrantsMarker as s, compiledReadSets as t, readPermdock as u };
@@ -2,7 +2,7 @@ import { n as __toESM } from "./rolldown-runtime-BPOCksWG.js";
2
2
  import { c as parseArgs$2, i as joinRepeated, l as renderUsage, n as cliContext, o as listArgs, s as defineCommand, t as GLOBAL_ARGS, u as runCommand } from "./command-CK14fP91.js";
3
3
  import { n as CliError, r as toCliError } from "./errors-4v4DTtda.js";
4
4
  import { n as highlight, r as painter } from "./style-C0NFdJRL.js";
5
- import { t as VERSION } from "./version-5mW_8sY1.js";
5
+ import { t as VERSION } from "./version-BCtlgDQx.js";
6
6
  import { stripVTControlCharacters } from "node:util";
7
7
  import { resolve } from "node:path";
8
8
  //#region src/cli/legacy.ts
@@ -134,11 +134,11 @@ function renderError(error, options) {
134
134
  //#region src/cli/run.ts
135
135
  const COMMANDS = /* @__PURE__ */ new Map([
136
136
  ["init", {
137
- load: () => import("./init-ClnxRYBF.js").then((m) => m.initCommand),
137
+ load: () => import("./init-DMa6M7hV.js").then((m) => m.initCommand),
138
138
  description: "Writes better-supabase.config.ts, src/lib/supabase/index.ts and glue for the frameworks in package.json"
139
139
  }],
140
140
  ["add", {
141
- load: () => import("./init-ClnxRYBF.js").then((m) => m.addCommand),
141
+ load: () => import("./init-DMa6M7hV.js").then((m) => m.addCommand),
142
142
  description: "Adds glue for an integration to an existing project"
143
143
  }],
144
144
  ["env", {
@@ -154,28 +154,32 @@ const COMMANDS = /* @__PURE__ */ new Map([
154
154
  description: "Installs the Agent Skills that ship with this version of better-supabase"
155
155
  }],
156
156
  ["gen", {
157
- load: () => import("./gen-D5cLCULx.js").then((m) => m.genCommand),
157
+ load: () => import("./gen-CIdSQZad.js").then((m) => m.genCommand),
158
158
  description: "Writes database.types.ts, generated.ts and its metadata module from the database"
159
159
  }],
160
160
  ["introspect", {
161
- load: () => import("./introspect-DxqfkVIv.js").then((m) => m.introspectCommand),
161
+ load: () => import("./introspect-BKlaIu_M.js").then((m) => m.introspectCommand),
162
162
  description: "Saves the database schema as a snapshot for offline gen"
163
163
  }],
164
164
  ["openapi", {
165
- load: () => import("./openapi-8WHjxiTJ.js").then((m) => m.openapiCommand),
165
+ load: () => import("./openapi-Cp5Fyta-.js").then((m) => m.openapiCommand),
166
166
  description: "Writes the document your createOpenApi() module exports, so CI can check it for drift"
167
167
  }],
168
168
  ["seed", {
169
- load: () => import("./seed-5J6eu_Xg.js").then((m) => m.seedCommand),
169
+ load: () => import("./seed-CUlqWh-8.js").then((m) => m.seedCommand),
170
170
  description: "Renders the fixtures from defineSeed() (better-supabase/testing) to SQL"
171
171
  }],
172
172
  ["doctor", {
173
- load: () => import("./doctor-BOym3mbL.js").then((m) => m.doctorCommand),
173
+ load: () => import("./doctor-C_A-KEAz.js").then((m) => m.doctorCommand),
174
174
  description: "Checks RLS, indexes, drift, auth config and env files; exits 1 on errors, or on warnings with --strict"
175
175
  }],
176
176
  ["sql", {
177
- load: () => import("./sql-D4VbqmXi.js").then((m) => m.sqlCommand),
178
- description: "Lists, adds, syncs and prints SQL kit modules"
177
+ load: () => import("./sql-CVx-1O8G.js").then((m) => m.sqlCommand),
178
+ description: "Lists, adds, syncs, upgrades and prints SQL kit modules"
179
+ }],
180
+ ["codemod", {
181
+ load: () => import("./codemod-DqV7612m.js").then((m) => m.codemodCommand),
182
+ description: "Rewrites imports and calls for renamed better-supabase APIs"
179
183
  }]
180
184
  ]);
181
185
  function registerCommand(name, command, help) {
@@ -308,8 +312,8 @@ async function run(argv, options = {}) {
308
312
  try {
309
313
  const [loaded, { loadConfig }, { parseEnv }] = await Promise.all([
310
314
  load(),
311
- import("./config-SSKSTUl2.js"),
312
- import("./env-BZ0uy8XK.js")
315
+ import("./config-dtoekM0v.js"),
316
+ import("./env-DmKv_G4A.js")
313
317
  ]);
314
318
  command = loaded;
315
319
  const globals = parseArgs$2(rest, GLOBAL_ARGS);
@@ -1,6 +1,6 @@
1
1
  import { r as defineCliCommand } from "./command-CK14fP91.js";
2
2
  import { r as writeIfChanged, t as display } from "./io-k41_z-jT.js";
3
- import { r as importExport, s as stdinDatabaseUrl, t as databaseUrl } from "./config-D9R0o1LH.js";
3
+ import { r as importExport, s as stdinDatabaseUrl, t as databaseUrl } from "./config-CPVpXP5I.js";
4
4
  import { n as withSpinner } from "./prompts-BNcNfAve.js";
5
5
  import { t as connect } from "./db-DOBPt660.js";
6
6
  import { resolve } from "node:path";