@akal/supaforge 0.0.31 → 0.0.33

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 (79) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +29 -11
  3. package/dist/base-command.d.ts +1 -0
  4. package/dist/base-command.js +2 -2
  5. package/dist/{chunk-BHYLBKYD.js → chunk-2SELREHW.js} +5 -5
  6. package/dist/{chunk-5Z3SAIQS.js → chunk-3HGAV5CC.js} +97 -831
  7. package/dist/{chunk-XMYMIURR.js → chunk-4IVN7QVY.js} +119 -39
  8. package/dist/{chunk-NXRSAVRU.js → chunk-6LJERPUN.js} +28 -7
  9. package/dist/{chunk-4OU7KO5Y.js → chunk-6Q7MHFBM.js} +2 -2
  10. package/dist/{chunk-PARSNTBD.js → chunk-7NAZGZPV.js} +56 -25
  11. package/dist/{chunk-VOXZWQ3N.js → chunk-BUOWHE36.js} +372 -9
  12. package/dist/{chunk-TQJSQLWA.js → chunk-DMIWAJRB.js} +38 -10
  13. package/dist/{chunk-LQXF65MC.js → chunk-GEHPTPNZ.js} +3 -3
  14. package/dist/chunk-GZREXCQZ.js +207 -0
  15. package/dist/{chunk-YVDSR4GM.js → chunk-MIRLB5JM.js} +51 -23
  16. package/dist/{chunk-KIFJGON5.js → chunk-NTUASFQ3.js} +2 -2
  17. package/dist/{chunk-5QQBTLWO.js → chunk-ORQJVE57.js} +3 -3
  18. package/dist/{chunk-VMTBLHN2.js → chunk-SC2XHGIS.js} +2 -2
  19. package/dist/{chunk-X6V2GGDZ.js → chunk-SQPCWGQO.js} +388 -64
  20. package/dist/chunk-UWAVXC57.js +916 -0
  21. package/dist/commands/clone.js +10 -10
  22. package/dist/commands/diff.d.ts +16 -0
  23. package/dist/commands/diff.js +11 -12
  24. package/dist/commands/hukam.js +11 -12
  25. package/dist/commands/mcp.d.ts +1 -0
  26. package/dist/commands/mcp.js +18 -9
  27. package/dist/commands/migrate/baseline.js +3 -3
  28. package/dist/commands/migrate/create.js +5 -6
  29. package/dist/commands/migrate/list.js +4 -4
  30. package/dist/commands/migrate/run.js +5 -6
  31. package/dist/commands/report.js +3 -3
  32. package/dist/commands/restore.js +11 -13
  33. package/dist/commands/snapshot.js +6 -8
  34. package/dist/commands/sync.js +11 -12
  35. package/dist/index.d.ts +5 -0
  36. package/dist/index.js +16 -16
  37. package/package.json +10 -8
  38. package/bin/dev.js +0 -10
  39. package/dist/base-command.js.map +0 -1
  40. package/dist/chunk-4OU7KO5Y.js.map +0 -1
  41. package/dist/chunk-5QQBTLWO.js.map +0 -1
  42. package/dist/chunk-5Z3SAIQS.js.map +0 -1
  43. package/dist/chunk-6WAMNZLO.js.map +0 -1
  44. package/dist/chunk-BHYLBKYD.js.map +0 -1
  45. package/dist/chunk-BLKJWDTL.js.map +0 -1
  46. package/dist/chunk-DQQ5E563.js.map +0 -1
  47. package/dist/chunk-G2DIPIYU.js.map +0 -1
  48. package/dist/chunk-H5MJ5DFX.js +0 -16
  49. package/dist/chunk-H5MJ5DFX.js.map +0 -1
  50. package/dist/chunk-KIFJGON5.js.map +0 -1
  51. package/dist/chunk-LQXF65MC.js.map +0 -1
  52. package/dist/chunk-NXRSAVRU.js.map +0 -1
  53. package/dist/chunk-PARSNTBD.js.map +0 -1
  54. package/dist/chunk-RRMI5CZD.js +0 -376
  55. package/dist/chunk-RRMI5CZD.js.map +0 -1
  56. package/dist/chunk-SF3YA42C.js +0 -506
  57. package/dist/chunk-SF3YA42C.js.map +0 -1
  58. package/dist/chunk-TQJSQLWA.js.map +0 -1
  59. package/dist/chunk-VMTBLHN2.js.map +0 -1
  60. package/dist/chunk-VOXZWQ3N.js.map +0 -1
  61. package/dist/chunk-X6V2GGDZ.js.map +0 -1
  62. package/dist/chunk-XMYMIURR.js.map +0 -1
  63. package/dist/chunk-YVDSR4GM.js.map +0 -1
  64. package/dist/commands/clone.js.map +0 -1
  65. package/dist/commands/diff.js.map +0 -1
  66. package/dist/commands/help.js.map +0 -1
  67. package/dist/commands/hukam.js.map +0 -1
  68. package/dist/commands/init.js.map +0 -1
  69. package/dist/commands/mcp.js.map +0 -1
  70. package/dist/commands/migrate/baseline.js.map +0 -1
  71. package/dist/commands/migrate/create.js.map +0 -1
  72. package/dist/commands/migrate/list.js.map +0 -1
  73. package/dist/commands/migrate/run.js.map +0 -1
  74. package/dist/commands/report.js.map +0 -1
  75. package/dist/commands/restore.js.map +0 -1
  76. package/dist/commands/snapshot.js.map +0 -1
  77. package/dist/commands/sync.js.map +0 -1
  78. package/dist/help.js.map +0 -1
  79. package/dist/index.js.map +0 -1
@@ -0,0 +1,916 @@
1
+ import {
2
+ bareName,
3
+ createdPolicies,
4
+ createdTriggers,
5
+ createsOnlyPolicies,
6
+ createsOnlyTriggers,
7
+ destructiveReason,
8
+ identifierMatcher,
9
+ orderStatements,
10
+ parseStatements,
11
+ referencedTables,
12
+ sqlSkeleton
13
+ } from "./chunk-BUOWHE36.js";
14
+ import {
15
+ isCommentOnly,
16
+ splitSqlStatements
17
+ } from "./chunk-G2DIPIYU.js";
18
+ import {
19
+ globToRegExp,
20
+ matchesGlob,
21
+ parseFlagList
22
+ } from "./chunk-DQQ5E563.js";
23
+ import {
24
+ Check,
25
+ errMsg,
26
+ pgClientConfig,
27
+ pgQuery,
28
+ quoteName
29
+ } from "./chunk-SQPCWGQO.js";
30
+ import {
31
+ SUPABASE_PLATFORM_SCHEMAS
32
+ } from "./chunk-6WAMNZLO.js";
33
+
34
+ // src/utils/table-filter.ts
35
+ var parseTableList = parseFlagList;
36
+ function resolveTableFilter(config, cli = {}) {
37
+ const cliTables = parseTableList(cli.tables);
38
+ const cliExclude = parseTableList(cli.excludeTables);
39
+ const configTables = Array.isArray(config?.checks?.tables) ? config.checks.tables : [];
40
+ const configExclude = Array.isArray(config?.checks?.excludeTables) ? config.checks.excludeTables : [];
41
+ const tables = cliTables.length > 0 ? cliTables : parseTableList(configTables);
42
+ const excludeTables = [.../* @__PURE__ */ new Set([...parseTableList(configExclude), ...cliExclude])];
43
+ const filter = {};
44
+ if (tables.length > 0) filter.tables = tables;
45
+ if (excludeTables.length > 0) filter.excludeTables = excludeTables;
46
+ return filter;
47
+ }
48
+ function isFiltered(filter) {
49
+ return Boolean(filter?.tables?.length || filter?.excludeTables?.length);
50
+ }
51
+ function describeTableFilter(filter) {
52
+ if (!isFiltered(filter)) return null;
53
+ const parts = [];
54
+ if (filter?.tables?.length) parts.push(`only ${filter.tables.join(", ")}`);
55
+ if (filter?.excludeTables?.length) parts.push(`excluding ${filter.excludeTables.join(", ")}`);
56
+ return `Scoped to ${parts.join(", ")} \u2014 applies to the schema and data checks; other layers are unfiltered.`;
57
+ }
58
+ function matchesPattern(name, pattern) {
59
+ const candidates = [name.toLowerCase()];
60
+ const dot = name.indexOf(".");
61
+ if (dot !== -1) candidates.push(name.slice(dot + 1).toLowerCase());
62
+ const rx = globToRegExp(pattern.toLowerCase());
63
+ return candidates.some((c) => rx.test(c));
64
+ }
65
+ function applyTableFilter(names, filter) {
66
+ if (!isFiltered(filter)) return names;
67
+ let out = names;
68
+ if (filter?.tables?.length) {
69
+ out = out.filter((n) => filter.tables.some((p) => matchesPattern(n, p)));
70
+ }
71
+ if (filter?.excludeTables?.length) {
72
+ out = out.filter((n) => !filter.excludeTables.some((p) => matchesPattern(n, p)));
73
+ }
74
+ return out;
75
+ }
76
+
77
+ // src/types/drift.ts
78
+ var CHECK_NAMES = [
79
+ "schema",
80
+ "rls",
81
+ "rls-coverage",
82
+ "edge-functions",
83
+ "storage",
84
+ "auth",
85
+ "cron",
86
+ "data",
87
+ "webhooks",
88
+ "realtime",
89
+ "vault",
90
+ "extensions",
91
+ "migrations",
92
+ "roles"
93
+ ];
94
+ var CHECK_META = {
95
+ "schema": { number: 1, emoji: "\u{1F5C4}\uFE0F", label: "Schema" },
96
+ "rls": { number: 2, emoji: "\u{1F512}", label: "RLS Policies" },
97
+ "rls-coverage": { number: 3, emoji: "\u{1F6E1}\uFE0F", label: "RLS Coverage" },
98
+ "edge-functions": { number: 4, emoji: "\u26A1", label: "Edge Functions" },
99
+ "storage": { number: 5, emoji: "\u{1FAA3}", label: "Storage" },
100
+ "auth": { number: 6, emoji: "\u{1F511}", label: "Auth Config" },
101
+ "cron": { number: 7, emoji: "\u23F0", label: "Cron Jobs" },
102
+ "data": { number: 8, emoji: "\u{1F5C3}\uFE0F", label: "Reference Data" },
103
+ "webhooks": { number: 9, emoji: "\u26A1\u{1F517}", label: "Webhooks" },
104
+ "realtime": { number: 10, emoji: "\u{1F4E1}", label: "Realtime Publications" },
105
+ "vault": { number: 11, emoji: "\u{1F510}", label: "Vault Secrets" },
106
+ "extensions": { number: 12, emoji: "\u{1F9E9}", label: "Postgres Extensions" },
107
+ "migrations": { number: 13, emoji: "\u{1F4CB}", label: "Migration History" },
108
+ "roles": { number: 14, emoji: "\u{1F464}", label: "Postgres Roles & Grants" }
109
+ };
110
+ var CHECK_KIND = {
111
+ "schema": "comparison",
112
+ "rls": "comparison",
113
+ "rls-coverage": "posture",
114
+ "edge-functions": "comparison",
115
+ "storage": "comparison",
116
+ "auth": "comparison",
117
+ "cron": "comparison",
118
+ "data": "comparison",
119
+ "webhooks": "comparison",
120
+ "realtime": "comparison",
121
+ "vault": "comparison",
122
+ "extensions": "comparison",
123
+ "migrations": "posture",
124
+ "roles": "comparison"
125
+ };
126
+ function isComparisonCheck(name) {
127
+ return CHECK_KIND[name] === "comparison";
128
+ }
129
+
130
+ // src/promote.ts
131
+ import pg from "pg";
132
+
133
+ // src/pg-errors.ts
134
+ var ABSENT_ON_TARGET = /* @__PURE__ */ new Set(["42P01", "42883", "3F000", "42704"]);
135
+ var UNDEFINED_COLUMN = "42703";
136
+ var EXTENSION_UNAVAILABLE = /* @__PURE__ */ new Set(["0A000", "58P01"]);
137
+ function sqlState(err) {
138
+ const code = err?.code;
139
+ return typeof code === "string" ? code : void 0;
140
+ }
141
+
142
+ // src/promote.ts
143
+ function outOfScopeReason(sql, filter) {
144
+ if (!isFiltered(filter)) return null;
145
+ const referenced = referencedTables(sql);
146
+ if (referenced.length === 0) return null;
147
+ const excluded = referenced.filter((t) => applyTableFilter([t], filter).length === 0);
148
+ if (excluded.length === 0) return null;
149
+ const names = excluded.map((t) => `'${t}'`).join(", ");
150
+ const flag = filter?.tables?.length ? "--tables" : "--exclude-tables";
151
+ const noun = excluded.length === 1 ? "table" : "tables";
152
+ return `Depends on ${noun} ${names}, excluded by ${flag}`;
153
+ }
154
+ function isSelected(issueId, only) {
155
+ if (!only?.length) return true;
156
+ return only.some((pattern) => matchesGlob(issueId, pattern));
157
+ }
158
+ function withDefaultGrantRevokes(scanResult, only) {
159
+ if (!only?.length) return only;
160
+ const issues = scanResult.checks.flatMap((c) => c.issues);
161
+ const created = new Set(issues.filter((i) => i.sql?.up && isSelected(i.id, only)).flatMap((i) => relationsCreatedBy(i.sql.up)));
162
+ if (created.size === 0) return only;
163
+ const companions = issues.filter((i) => i.id.startsWith("roles-grant-default-") && [...created].some((rel) => rel.endsWith("(") ? i.id.toLowerCase().includes(`.${rel}`) : i.id.toLowerCase().endsWith(`.${rel}`))).map((i) => i.id);
164
+ return [...only, ...companions];
165
+ }
166
+ function relationsCreatedBy(sql) {
167
+ const statements = parseStatements(sql);
168
+ if (!statements) return [];
169
+ return statements.flatMap(({ kind, node }) => {
170
+ if (kind === "CreateFunctionStmt") {
171
+ const parts = (node.funcname ?? []).map((n) => n.String?.sval ?? "");
172
+ const name = parts.at(-1);
173
+ return name ? [`${(parts.length > 1 ? parts.at(-2) : "public").toLowerCase()}.${name.toLowerCase()}(`] : [];
174
+ }
175
+ const rel = kind === "CreateStmt" ? node.relation : kind === "ViewStmt" ? node.view : kind === "CreateTableAsStmt" ? node.into?.rel : void 0;
176
+ return rel?.relname ? [`${(rel.schemaname || "public").toLowerCase()}.${String(rel.relname).toLowerCase()}`] : [];
177
+ });
178
+ }
179
+ function classifyIssue(issue, options, recreatedPolicies = /* @__PURE__ */ new Set()) {
180
+ if (!isSelected(issue.id, options.only)) {
181
+ return { kind: "skip", reason: "Not selected by --only" };
182
+ }
183
+ if (issue.manualOnly) return { kind: "skip", reason: issue.manualOnly };
184
+ if (!issue.sql?.up) {
185
+ if (issue.action?.method === "DELETE" && !options.allowDestructive) {
186
+ return { kind: "skip", reason: `Destructive \u2014 ${issue.action.label}; re-run with --allow-destructive to apply` };
187
+ }
188
+ if (issue.action) return { kind: "api", action: issue.action };
189
+ return { kind: "skip", reason: issue.manualOnly ?? "No SQL fix or API action available" };
190
+ }
191
+ if (!options.allowDestructive) {
192
+ const why = issue.destructive ?? destructiveReason(issue.sql.up, recreatedPolicies);
193
+ if (why) {
194
+ return { kind: "skip", reason: `Destructive \u2014 ${why}; re-run with --allow-destructive to apply` };
195
+ }
196
+ }
197
+ const outOfScope = outOfScopeReason(issue.sql.up, options.tableFilter);
198
+ if (outOfScope) return { kind: "skip", reason: outOfScope };
199
+ return { kind: "sql", sql: issue.sql.up };
200
+ }
201
+ function policiesCreatedBySelectedFixes(checks, options) {
202
+ const created = /* @__PURE__ */ new Set();
203
+ for (const check of checks) {
204
+ const askedForExplicitly = options.checks?.includes(check.check) ?? false;
205
+ if (!isComparisonCheck(check.check) && !options.applyPosture && !askedForExplicitly) continue;
206
+ for (const issue of check.issues) {
207
+ const sql = issue.sql?.up;
208
+ if (!sql || !isSelected(issue.id, options.only)) continue;
209
+ if (!options.allowDestructive && destructiveReason(sql)) continue;
210
+ if (outOfScopeReason(sql, options.tableFilter)) continue;
211
+ for (const key of createdPolicies(sql)) created.add(key);
212
+ }
213
+ }
214
+ return created;
215
+ }
216
+ function planWork(scanResult, options = {}) {
217
+ options = { ...options, only: withDefaultGrantRevokes(scanResult, options.only) };
218
+ const plan = { sqlStatements: [], apiActions: [], skipped: [] };
219
+ const relevant = scanResult.checks.filter(
220
+ (c) => c.status === "drifted" && (!options.checks || options.checks.includes(c.check))
221
+ );
222
+ const recreatedPolicies = policiesCreatedBySelectedFixes(relevant, options);
223
+ const keptBack = [];
224
+ for (const checkResult of relevant) {
225
+ const askedForExplicitly = options.checks?.includes(checkResult.check) ?? false;
226
+ if (!isComparisonCheck(checkResult.check) && !options.applyPosture && !askedForExplicitly) {
227
+ for (const issue of checkResult.issues) {
228
+ plan.skipped.push({
229
+ check: checkResult.check,
230
+ issueId: issue.id,
231
+ reason: "Posture finding about the target, not drift from the source \u2014 applying it would create drift. Use --apply-posture to apply anyway."
232
+ });
233
+ }
234
+ continue;
235
+ }
236
+ for (const issue of checkResult.issues) {
237
+ const at = { check: checkResult.check, issueId: issue.id };
238
+ const outcome = classifyIssue(issue, options, recreatedPolicies);
239
+ if (outcome.kind === "sql") plan.sqlStatements.push({ ...at, sql: outcome.sql });
240
+ else if (outcome.kind === "api") plan.apiActions.push({ ...at, action: outcome.action });
241
+ else {
242
+ plan.skipped.push({ ...at, reason: outcome.reason });
243
+ if (outcome.reason.startsWith("Destructive") && issue.sql?.down) {
244
+ keptBack.push({ issueId: issue.id, definition: issue.sql.down });
245
+ }
246
+ }
247
+ }
248
+ }
249
+ plan.sqlStatements = holdBackDropsStillInUse(plan.sqlStatements, keptBack, plan.skipped, downsOf(relevant));
250
+ const dbdiffOrder = new Map(plan.sqlStatements.filter((s) => s.check === "schema").map((s, i) => [s, i]));
251
+ plan.sqlStatements = orderStatements(plan.sqlStatements, (s) => s.sql, (s) => dbdiffOrder.get(s));
252
+ plan.sqlStatements = dropDuplicateObjectFixes(plan.sqlStatements, plan.skipped);
253
+ return plan;
254
+ }
255
+ var DROPS_SUPPORTING_OBJECT = /^\s*DROP\s+(?:TYPE|DOMAIN|FUNCTION|PROCEDURE|ROUTINE|SEQUENCE)\s+(?:IF\s+EXISTS\s+)?((?:"[^"]+"|[\w$]+)(?:\s*\.\s*(?:"[^"]+"|[\w$]+))?)/i;
256
+ function holdBackDropsStillInUse(statements, keptBack, skipped, downs = /* @__PURE__ */ new Map()) {
257
+ const kept = keptBack.map((k) => ({ issueId: k.issueId, skeleton: sqlSkeleton(k.definition) }));
258
+ let remaining = statements;
259
+ for (let changed = kept.length > 0; changed; ) {
260
+ changed = false;
261
+ remaining = remaining.filter((statement) => {
262
+ const names = droppedSupportingObjects(statement.sql);
263
+ if (names.length === 0) return true;
264
+ const user = kept.find((k) => names.some((n) => identifierMatcher(bareName(n)).test(k.skeleton)));
265
+ if (!user) return true;
266
+ skipped.push({
267
+ check: statement.check,
268
+ issueId: statement.issueId,
269
+ reason: `Still used by what ${user.issueId} keeps, which is held back as destructive; re-run with --allow-destructive to apply both`
270
+ });
271
+ const definition = downs.get(statement.issueId);
272
+ if (definition) kept.push({ issueId: user.issueId, skeleton: sqlSkeleton(definition) });
273
+ changed = true;
274
+ return false;
275
+ });
276
+ }
277
+ return remaining;
278
+ }
279
+ function droppedSupportingObjects(sql) {
280
+ const parts = splitSqlStatements(sql).filter((s) => !isCommentOnly(s));
281
+ const names = parts.map((s) => DROPS_SUPPORTING_OBJECT.exec(sqlSkeleton(s))?.[1]);
282
+ return names.length > 0 && names.every((n) => n !== void 0) ? names : [];
283
+ }
284
+ function downsOf(checks) {
285
+ const downs = /* @__PURE__ */ new Map();
286
+ for (const check of checks) {
287
+ for (const issue of check.issues) {
288
+ if (issue.sql?.down) downs.set(issue.id, issue.sql.down);
289
+ }
290
+ }
291
+ return downs;
292
+ }
293
+ function dropDuplicateObjectFixes(statements, skipped) {
294
+ const kinds = [
295
+ { what: "policy", created: createdPolicies, onlyThis: createsOnlyPolicies, seen: /* @__PURE__ */ new Set() },
296
+ { what: "trigger", created: createdTriggers, onlyThis: createsOnlyTriggers, seen: /* @__PURE__ */ new Set() }
297
+ ];
298
+ const kept = [];
299
+ for (const statement of statements) {
300
+ const duplicate = kinds.find((kind) => {
301
+ const names = kind.created(statement.sql);
302
+ return names.length > 0 && names.every((n) => kind.seen.has(n)) && kind.onlyThis(statement.sql);
303
+ });
304
+ if (duplicate) {
305
+ skipped.push({
306
+ check: statement.check,
307
+ issueId: statement.issueId,
308
+ reason: `Already created by the schema fix for the same ${duplicate.what}`
309
+ });
310
+ continue;
311
+ }
312
+ for (const kind of kinds) {
313
+ for (const name of kind.created(statement.sql)) kind.seen.add(name);
314
+ }
315
+ kept.push(statement);
316
+ }
317
+ return kept;
318
+ }
319
+ async function executeSql(dbUrl, statements, result, transactional) {
320
+ if (statements.length === 0) return;
321
+ const client = new pg.Client(pgClientConfig(dbUrl));
322
+ await client.connect();
323
+ try {
324
+ if (transactional) await runInTransaction(client, statements, result);
325
+ else await runIndependently(client, statements, result);
326
+ } finally {
327
+ await client.end();
328
+ }
329
+ }
330
+ async function runLikeApply(dbUrl, statements) {
331
+ const result = { applied: [], skipped: [], errors: [] };
332
+ await executeSql(dbUrl, statements, result, true);
333
+ return result;
334
+ }
335
+ async function runIndependently(client, statements, result) {
336
+ for (const stmt of statements) {
337
+ try {
338
+ await client.query(stmt.sql);
339
+ result.applied.push({ check: stmt.check, issueId: stmt.issueId, sql: stmt.sql });
340
+ } catch (err) {
341
+ result.errors.push({ check: stmt.check, issueId: stmt.issueId, error: errMsg(err) });
342
+ }
343
+ }
344
+ }
345
+ function isEnumValueAddition(sql) {
346
+ const statements = splitSqlStatements(sql).filter((s) => !isCommentOnly(s));
347
+ return statements.length > 0 && statements.every((s) => /^\s*ALTER\s+TYPE\s+\S+\s+ADD\s+VALUE\b/i.test(sqlSkeleton(s)));
348
+ }
349
+ async function runInTransaction(client, statements, result) {
350
+ const additions = statements.filter((s) => isEnumValueAddition(s.sql));
351
+ const rest = statements.filter((s) => !isEnumValueAddition(s.sql));
352
+ if (additions.length > 0 && !await runBatch(client, additions, result)) return;
353
+ await runBatch(client, rest, result);
354
+ }
355
+ function unmetDependency(sql, err) {
356
+ const code = sqlState(err);
357
+ if (!code) return void 0;
358
+ if (/^\s*CREATE\s+EXTENSION\b/i.test(sqlSkeleton(sql))) {
359
+ return EXTENSION_UNAVAILABLE.has(code) ? "this server does not ship it" : void 0;
360
+ }
361
+ if (ABSENT_ON_TARGET.has(code) || code === UNDEFINED_COLUMN) {
362
+ return "it needs something the target does not have";
363
+ }
364
+ return void 0;
365
+ }
366
+ async function runBatch(client, statements, result) {
367
+ if (statements.length === 0) return true;
368
+ const done = [];
369
+ await client.query("BEGIN");
370
+ let pending = statements;
371
+ let unmet = [];
372
+ while (pending.length > 0) {
373
+ unmet = [];
374
+ for (const stmt of pending) {
375
+ await client.query("SAVEPOINT sf_fix");
376
+ try {
377
+ await client.query(stmt.sql);
378
+ await client.query("RELEASE SAVEPOINT sf_fix");
379
+ done.push({ check: stmt.check, issueId: stmt.issueId, sql: stmt.sql });
380
+ } catch (err) {
381
+ const why = unmetDependency(stmt.sql, err);
382
+ if (why && await client.query("ROLLBACK TO SAVEPOINT sf_fix").then(() => true, () => false)) {
383
+ unmet.push({ stmt, err, why });
384
+ continue;
385
+ }
386
+ await client.query("ROLLBACK").catch(() => {
387
+ });
388
+ result.errors.push({ check: stmt.check, issueId: stmt.issueId, error: errMsg(err) });
389
+ result.rolledBack = [...result.rolledBack ?? [], ...done];
390
+ return false;
391
+ }
392
+ }
393
+ if (unmet.length === pending.length) break;
394
+ pending = unmet.map((u) => u.stmt);
395
+ }
396
+ await client.query("COMMIT");
397
+ result.applied.push(...done);
398
+ for (const { stmt, err, why } of unmet) {
399
+ result.errors.push({
400
+ check: stmt.check,
401
+ issueId: stmt.issueId,
402
+ error: `${errMsg(err)} \u2014 not applied: ${why}. The other fixes were.`
403
+ });
404
+ }
405
+ return true;
406
+ }
407
+ async function executeApiActions(actions, fetchFn, result) {
408
+ for (const act of actions) {
409
+ try {
410
+ const init = {
411
+ method: act.action.method,
412
+ headers: { "Content-Type": "application/json", ...act.action.headers }
413
+ };
414
+ if (act.action.body !== void 0) {
415
+ init.body = JSON.stringify(act.action.body);
416
+ }
417
+ const res = await fetchFn(act.action.url, init);
418
+ if (!res.ok) {
419
+ const text = await res.text().catch(() => res.statusText);
420
+ throw new Error(`${act.action.method} ${act.action.url} \u2192 ${res.status}: ${text}`);
421
+ }
422
+ result.applied.push({ check: act.check, issueId: act.issueId, action: act.action.label });
423
+ } catch (err) {
424
+ result.errors.push({ check: act.check, issueId: act.issueId, error: errMsg(err) });
425
+ }
426
+ }
427
+ }
428
+ async function promote(options) {
429
+ const {
430
+ dbUrl,
431
+ scanResult,
432
+ checks,
433
+ dryRun = false,
434
+ allowDestructive = false,
435
+ tableFilter,
436
+ only,
437
+ applyPosture = false,
438
+ transactional = true,
439
+ fetchFn = globalThis.fetch.bind(globalThis)
440
+ } = options;
441
+ const { sqlStatements, apiActions, skipped } = planWork(scanResult, {
442
+ checks,
443
+ allowDestructive,
444
+ tableFilter,
445
+ only,
446
+ applyPosture
447
+ });
448
+ const result = { applied: [], skipped, errors: [] };
449
+ if (dryRun) {
450
+ for (const stmt of sqlStatements) {
451
+ result.applied.push({ check: stmt.check, issueId: stmt.issueId, sql: stmt.sql });
452
+ }
453
+ for (const act of apiActions) {
454
+ result.applied.push({ check: act.check, issueId: act.issueId, action: act.action.label });
455
+ }
456
+ return result;
457
+ }
458
+ await executeSql(dbUrl, sqlStatements, result, transactional);
459
+ if (result.rolledBack) {
460
+ for (const act of apiActions) {
461
+ result.skipped.push({
462
+ check: act.check,
463
+ issueId: act.issueId,
464
+ reason: "Not attempted \u2014 the SQL fixes were rolled back"
465
+ });
466
+ }
467
+ return result;
468
+ }
469
+ await executeApiActions(apiActions, fetchFn, result);
470
+ return result;
471
+ }
472
+
473
+ // src/checks/roles.ts
474
+ var PLATFORM_ROLES = [
475
+ "postgres",
476
+ "supabase_admin",
477
+ "authenticator",
478
+ "supabase_auth_admin",
479
+ "supabase_storage_admin",
480
+ "dashboard_user",
481
+ "pgbouncer",
482
+ "supavisor",
483
+ // Created by Supabase's own images for Edge Functions, Realtime, read
484
+ // replicas and logical replication. Diffing a project against plain
485
+ // PostgreSQL offered to create all four on the target.
486
+ "supabase_functions_admin",
487
+ "supabase_realtime_admin",
488
+ "supabase_read_only_user",
489
+ "supabase_replication_admin"
490
+ ];
491
+ var API_ROLES = ["anon", "authenticated", "service_role"];
492
+ var quoted = (names) => names.map((n) => `'${n.replace(/'/g, "''")}'`).join(", ");
493
+ var ROLES_SQL = `
494
+ SELECT
495
+ rolname, rolsuper, rolinherit, rolcreaterole, rolcreatedb,
496
+ rolcanlogin, rolreplication, rolbypassrls, rolconnlimit,
497
+ rolvaliduntil::text AS rolvaliduntil
498
+ FROM pg_roles
499
+ WHERE NOT (rolname LIKE 'pg_%')
500
+ AND rolname NOT IN (${quoted([...PLATFORM_ROLES, ...API_ROLES])})
501
+ AND rolname <> current_user
502
+ ORDER BY rolname
503
+ `;
504
+ function grantSchemaFilter(ignoreSchemas) {
505
+ const excluded = [.../* @__PURE__ */ new Set([...SUPABASE_PLATFORM_SCHEMAS, ...ignoreSchemas])];
506
+ return `NOT IN (${quoted(excluded)})`;
507
+ }
508
+ var grantsSql = (ignoreSchemas) => `
509
+ SELECT CASE WHEN a.grantee = 0 THEN 'PUBLIC' ELSE pg_get_userbyid(a.grantee) END AS grantee,
510
+ n.nspname AS table_schema, c.relname AS table_name,
511
+ a.privilege_type, a.is_grantable,
512
+ CASE c.relkind WHEN 'S' THEN 'sequence' ELSE 'table' END AS object_kind
513
+ FROM pg_class c
514
+ JOIN pg_namespace n ON n.oid = c.relnamespace
515
+ CROSS JOIN LATERAL aclexplode(c.relacl) a
516
+ WHERE c.relacl IS NOT NULL
517
+ AND c.relkind IN ('r', 'p', 'v', 'm', 'f', 'S')
518
+ AND a.grantee <> c.relowner
519
+ AND n.nspname ${grantSchemaFilter(ignoreSchemas)}
520
+ AND (a.grantee = 0 OR pg_get_userbyid(a.grantee) NOT IN (${quoted(PLATFORM_ROLES)}))
521
+ AND (a.grantee = 0 OR pg_get_userbyid(a.grantee) NOT LIKE 'pg_%')
522
+ ORDER BY 1, 2, 3, 4
523
+ `;
524
+ var columnGrantsSql = (ignoreSchemas) => `
525
+ SELECT CASE WHEN a.grantee = 0 THEN 'PUBLIC' ELSE pg_get_userbyid(a.grantee) END AS grantee,
526
+ n.nspname AS table_schema, c.relname AS table_name, att.attname AS column_name,
527
+ a.privilege_type, a.is_grantable
528
+ FROM pg_attribute att
529
+ JOIN pg_class c ON c.oid = att.attrelid
530
+ JOIN pg_namespace n ON n.oid = c.relnamespace
531
+ CROSS JOIN LATERAL aclexplode(att.attacl) a
532
+ WHERE att.attacl IS NOT NULL AND att.attnum > 0 AND NOT att.attisdropped
533
+ AND c.relkind IN ('r', 'p', 'v', 'm', 'f')
534
+ AND a.grantee <> c.relowner
535
+ AND n.nspname ${grantSchemaFilter(ignoreSchemas)}
536
+ AND (a.grantee = 0 OR pg_get_userbyid(a.grantee) NOT IN (${quoted(PLATFORM_ROLES)}))
537
+ AND (a.grantee = 0 OR pg_get_userbyid(a.grantee) NOT LIKE 'pg_%')
538
+ ORDER BY 1, 2, 3, 4, 5
539
+ `;
540
+ var functionGrantsSql = (ignoreSchemas) => `
541
+ SELECT CASE WHEN a.grantee = 0 THEN 'PUBLIC' ELSE pg_get_userbyid(a.grantee) END AS grantee,
542
+ n.nspname AS table_schema, p.proname AS table_name,
543
+ pg_get_function_identity_arguments(p.oid) AS args,
544
+ CASE p.prokind WHEN 'p' THEN 'procedure' ELSE 'function' END AS object_kind,
545
+ a.privilege_type, a.is_grantable
546
+ FROM pg_proc p
547
+ JOIN pg_namespace n ON n.oid = p.pronamespace
548
+ CROSS JOIN LATERAL aclexplode(coalesce(p.proacl, acldefault('f', p.proowner))) a
549
+ WHERE a.grantee <> p.proowner
550
+ AND n.nspname ${grantSchemaFilter(ignoreSchemas)}
551
+ AND NOT EXISTS (SELECT 1 FROM pg_depend d WHERE d.classid = 'pg_proc'::regclass AND d.objid = p.oid AND d.deptype = 'e')
552
+ AND (a.grantee = 0 OR pg_get_userbyid(a.grantee) NOT IN (${quoted(PLATFORM_ROLES)}))
553
+ AND (a.grantee = 0 OR pg_get_userbyid(a.grantee) NOT LIKE 'pg_%')
554
+ ORDER BY 1, 2, 3, 4, 6
555
+ `;
556
+ var routinesSql = (ignoreSchemas) => `
557
+ SELECT n.nspname AS table_schema, p.proname AS table_name,
558
+ pg_get_function_identity_arguments(p.oid) AS args,
559
+ CASE p.prokind WHEN 'p' THEN 'procedure' ELSE 'function' END AS object_kind
560
+ FROM pg_proc p JOIN pg_namespace n ON n.oid = p.pronamespace
561
+ WHERE n.nspname ${grantSchemaFilter(ignoreSchemas)}
562
+ AND NOT EXISTS (SELECT 1 FROM pg_depend d WHERE d.classid = 'pg_proc'::regclass AND d.objid = p.oid AND d.deptype = 'e')
563
+ `;
564
+ var relationsSql = (ignoreSchemas) => `
565
+ SELECT n.nspname AS table_schema, c.relname AS table_name,
566
+ CASE c.relkind WHEN 'S' THEN 'sequence' ELSE 'table' END AS object_kind
567
+ FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace
568
+ WHERE c.relkind IN ('r', 'p', 'v', 'm', 'f', 'S')
569
+ AND n.nspname ${grantSchemaFilter(ignoreSchemas)}
570
+ `;
571
+ var DEFAULT_GRANTS_SQL = `
572
+ SELECT CASE d.defaclobjtype WHEN 'S' THEN 'sequence' WHEN 'f' THEN 'function' ELSE 'table' END AS object_kind,
573
+ n.nspname AS table_schema,
574
+ CASE WHEN a.grantee = 0 THEN 'PUBLIC' ELSE pg_get_userbyid(a.grantee) END AS grantee,
575
+ a.privilege_type, a.is_grantable
576
+ FROM pg_default_acl d
577
+ LEFT JOIN pg_namespace n ON n.oid = d.defaclnamespace
578
+ CROSS JOIN LATERAL aclexplode(d.defaclacl) a
579
+ WHERE d.defaclobjtype IN ('r', 'S', 'f') AND d.defaclrole = current_user::regrole::oid
580
+ AND a.grantee <> d.defaclrole
581
+ UNION ALL
582
+ SELECT 'function', NULL, 'PUBLIC', 'EXECUTE', false
583
+ WHERE NOT EXISTS (
584
+ SELECT 1 FROM pg_default_acl d
585
+ WHERE d.defaclobjtype = 'f' AND d.defaclnamespace = 0 AND d.defaclrole = current_user::regrole::oid)
586
+ `;
587
+ function objectKey(o) {
588
+ const routine = o.object_kind === "function" || o.object_kind === "procedure";
589
+ return `${routine ? "routine" : o.object_kind ?? "table"}:${o.table_schema}.${o.table_name}${routine ? `(${o.args ?? ""})` : ""}`;
590
+ }
591
+ function defaultKind(kind) {
592
+ return kind === "procedure" ? "function" : kind ?? "table";
593
+ }
594
+ function grantedByDefault(relations, defaults) {
595
+ const present = new Set(relations.map(objectKey));
596
+ const granted = new Set(defaults.map((d) => `${defaultKind(d.object_kind)}|${d.table_schema ?? "*"}|${d.grantee}|${d.privilege_type}|${Boolean(d.is_grantable)}`));
597
+ return (g) => !g.column_name && !present.has(objectKey(g)) && [g.table_schema, "*"].some((schema) => granted.has(`${defaultKind(g.object_kind)}|${schema}|${g.grantee}|${g.privilege_type}|${Boolean(g.is_grantable)}`));
598
+ }
599
+ function defaultGrantsToRevoke(sourceRelations, targetRelations, defaults, sourceGrants) {
600
+ const present = new Set(targetRelations.map(objectKey));
601
+ const held = new Set(sourceGrants.filter((g) => !g.column_name).map((g) => `${objectKey(g)}|${g.grantee}|${g.privilege_type}`));
602
+ const issues = [];
603
+ for (const rel of sourceRelations) {
604
+ if (present.has(objectKey(rel))) continue;
605
+ const name = `${rel.table_schema}.${rel.table_name}`;
606
+ const extra = /* @__PURE__ */ new Map();
607
+ for (const d of defaults) {
608
+ if (defaultKind(d.object_kind) !== defaultKind(rel.object_kind)) continue;
609
+ if (d.table_schema !== null && d.table_schema !== rel.table_schema) continue;
610
+ if (held.has(`${objectKey(rel)}|${d.grantee}|${d.privilege_type}`)) continue;
611
+ extra.set(d.grantee, (extra.get(d.grantee) ?? /* @__PURE__ */ new Set()).add(d.privilege_type));
612
+ }
613
+ for (const [grantee, privileges] of [...extra].sort(([a], [b]) => a.localeCompare(b))) {
614
+ const gs = [...privileges].sort().map((privilege_type) => ({
615
+ grantee,
616
+ table_schema: rel.table_schema,
617
+ table_name: rel.table_name,
618
+ privilege_type,
619
+ is_grantable: false,
620
+ ...rel.object_kind && rel.object_kind !== "table" ? { object_kind: rel.object_kind } : {},
621
+ ...rel.args !== void 0 ? { args: rel.args } : {}
622
+ }));
623
+ const routine = rel.object_kind === "function" || rel.object_kind === "procedure";
624
+ issues.push({
625
+ // Tables keep the id they have always had; others say what they are.
626
+ id: `roles-grant-default-${grantee}.${name}${routine ? `(${rel.args ?? ""})` : ""}`,
627
+ check: "roles",
628
+ severity: extraGrantSeverity(grantee),
629
+ title: `Default grants to take back: ${describeGroup(gs)}`,
630
+ description: `Creating ${describeObject(gs[0])} on the target gives ${grantee} what its default privileges grant. The source does not grant "${describeGroup(gs)}", so it is revoked once it exists.`,
631
+ targetValue: gs,
632
+ sql: {
633
+ up: `REVOKE ${groupTarget(gs)} FROM ${granteeSql(grantee)};`,
634
+ down: `GRANT ${groupTarget(gs)} TO ${granteeSql(grantee)};`
635
+ }
636
+ });
637
+ }
638
+ }
639
+ return issues;
640
+ }
641
+ var OPEN_GRANTEES = /* @__PURE__ */ new Set(["anon", "authenticated", "PUBLIC"]);
642
+ function extraGrantSeverity(grantee) {
643
+ return OPEN_GRANTEES.has(grantee) ? "critical" : "warning";
644
+ }
645
+ var RolesCheck = class extends Check {
646
+ constructor(queryFn = pgQuery) {
647
+ super();
648
+ this.queryFn = queryFn;
649
+ }
650
+ name = "roles";
651
+ async scan(ctx) {
652
+ const ignore = ctx.config.ignoreSchemas ?? [];
653
+ const version = async (url) => Number((await this.queryFn(url, `SELECT current_setting('server_version_num') AS v`))[0]?.v ?? 0);
654
+ const [
655
+ sourceRoles,
656
+ targetRoles,
657
+ sourceGrants,
658
+ targetGrants,
659
+ sourceColumns,
660
+ targetColumns,
661
+ sourceVersion,
662
+ targetVersion,
663
+ sourceRelations,
664
+ targetRelations,
665
+ targetDefaults,
666
+ sourceRoutineGrants,
667
+ targetRoutineGrants,
668
+ sourceRoutines,
669
+ targetRoutines
670
+ ] = await Promise.all([
671
+ this.queryFn(ctx.source.dbUrl, ROLES_SQL),
672
+ this.queryFn(ctx.target.dbUrl, ROLES_SQL),
673
+ this.queryFn(ctx.source.dbUrl, grantsSql(ignore)),
674
+ this.queryFn(ctx.target.dbUrl, grantsSql(ignore)),
675
+ this.queryFn(ctx.source.dbUrl, columnGrantsSql(ignore)),
676
+ this.queryFn(ctx.target.dbUrl, columnGrantsSql(ignore)),
677
+ version(ctx.source.dbUrl),
678
+ version(ctx.target.dbUrl),
679
+ this.queryFn(ctx.source.dbUrl, relationsSql(ignore)),
680
+ this.queryFn(ctx.target.dbUrl, relationsSql(ignore)),
681
+ this.queryFn(ctx.target.dbUrl, DEFAULT_GRANTS_SQL),
682
+ this.queryFn(ctx.source.dbUrl, functionGrantsSql(ignore)),
683
+ this.queryFn(ctx.target.dbUrl, functionGrantsSql(ignore)),
684
+ this.queryFn(ctx.source.dbUrl, routinesSql(ignore)),
685
+ this.queryFn(ctx.target.dbUrl, routinesSql(ignore))
686
+ ]);
687
+ const sourceObjects = [...sourceRelations ?? [], ...sourceRoutines ?? []];
688
+ const targetObjects = [...targetRelations ?? [], ...targetRoutines ?? []];
689
+ const sourceAll = [...sourceGrants ?? [], ...sourceRoutineGrants ?? []];
690
+ const inSource = new Set(sourceObjects.map(objectKey));
691
+ const targetAll = [...targetGrants ?? [], ...targetRoutineGrants ?? []].filter((g) => !g.object_kind || g.object_kind === "table" || inSource.has(objectKey(g)));
692
+ const comparable = comparablePrivileges(sourceVersion, targetVersion);
693
+ const byDefault = grantedByDefault(targetObjects, targetDefaults ?? []);
694
+ return [
695
+ ...diffRoles(sourceRoles, targetRoles),
696
+ ...diffGrants(
697
+ [...sourceAll, ...sourceColumns ?? []].filter((g) => comparable(g) && !byDefault(g)),
698
+ [...targetAll, ...targetColumns ?? []].filter(comparable)
699
+ ),
700
+ ...defaultGrantsToRevoke(
701
+ sourceObjects,
702
+ targetObjects,
703
+ (targetDefaults ?? []).filter((d) => comparable(d)),
704
+ sourceAll
705
+ )
706
+ ];
707
+ }
708
+ };
709
+ function roleAttrs(r) {
710
+ const attrs = [];
711
+ if (r.rolsuper) attrs.push("SUPERUSER");
712
+ if (r.rolinherit) attrs.push("INHERIT");
713
+ if (r.rolcreaterole) attrs.push("CREATEROLE");
714
+ if (r.rolcreatedb) attrs.push("CREATEDB");
715
+ if (r.rolcanlogin) attrs.push("LOGIN");
716
+ if (r.rolreplication) attrs.push("REPLICATION");
717
+ if (r.rolbypassrls) attrs.push("BYPASSRLS");
718
+ if (r.rolconnlimit >= 0) attrs.push(`CONNECTION LIMIT ${r.rolconnlimit}`);
719
+ if (r.rolvaliduntil) attrs.push(`VALID UNTIL '${r.rolvaliduntil}'`);
720
+ return attrs.length > 0 ? attrs.join(" ") : "NOLOGIN";
721
+ }
722
+ function rolesEqual(a, b) {
723
+ return a.rolsuper === b.rolsuper && a.rolinherit === b.rolinherit && a.rolcreaterole === b.rolcreaterole && a.rolcreatedb === b.rolcreatedb && a.rolcanlogin === b.rolcanlogin && a.rolreplication === b.rolreplication && a.rolbypassrls === b.rolbypassrls && a.rolconnlimit === b.rolconnlimit && a.rolvaliduntil === b.rolvaliduntil;
724
+ }
725
+ function diffRoles(source, target) {
726
+ const issues = [];
727
+ const sourceMap = new Map(source.map((r) => [r.rolname, r]));
728
+ const targetMap = new Map(target.map((r) => [r.rolname, r]));
729
+ for (const [name, sr] of sourceMap) {
730
+ if (!targetMap.has(name)) {
731
+ issues.push({
732
+ id: `roles-missing-${name}`,
733
+ check: "roles",
734
+ severity: "critical",
735
+ title: `Missing role: ${name}`,
736
+ description: `Role "${name}" exists in source but is missing from target. Any RLS policies or grants referencing this role will be silently ineffective.`,
737
+ sourceValue: sr,
738
+ sql: {
739
+ up: `CREATE ROLE ${quoteName(name)} ${roleAttrs(sr)};`,
740
+ down: `DROP ROLE IF EXISTS ${quoteName(name)};`
741
+ }
742
+ });
743
+ }
744
+ }
745
+ for (const [name, tr] of targetMap) {
746
+ if (!sourceMap.has(name)) {
747
+ issues.push({
748
+ id: `roles-extra-${name}`,
749
+ check: "roles",
750
+ severity: "warning",
751
+ title: `Extra role: ${name}`,
752
+ description: `Role "${name}" exists in target but not in source.`,
753
+ targetValue: tr,
754
+ sql: {
755
+ up: `DROP ROLE IF EXISTS ${quoteName(name)};`,
756
+ down: `CREATE ROLE ${quoteName(name)} ${roleAttrs(tr)};`
757
+ }
758
+ });
759
+ }
760
+ }
761
+ for (const [name, sr] of sourceMap) {
762
+ const tr = targetMap.get(name);
763
+ if (tr && !rolesEqual(sr, tr)) {
764
+ issues.push({
765
+ id: `roles-modified-${name}`,
766
+ check: "roles",
767
+ severity: "warning",
768
+ title: `Modified role: ${name}`,
769
+ description: `Role "${name}" has different attributes between source and target.`,
770
+ sourceValue: sr,
771
+ targetValue: tr,
772
+ sql: {
773
+ up: `ALTER ROLE ${quoteName(name)} ${roleAttrs(sr)};`,
774
+ down: `ALTER ROLE ${quoteName(name)} ${roleAttrs(tr)};`
775
+ }
776
+ });
777
+ }
778
+ }
779
+ return issues;
780
+ }
781
+ function grantKey(g) {
782
+ const column = g.column_name ? `.${g.column_name}` : "";
783
+ const routine = g.object_kind === "function" || g.object_kind === "procedure";
784
+ return `${g.grantee}.${g.table_schema}.${g.table_name}${routine ? `(${g.args ?? ""})` : ""}${column}.${g.privilege_type}`;
785
+ }
786
+ function objectSql(g) {
787
+ const name = `${quoteName(g.table_schema)}.${quoteName(g.table_name)}`;
788
+ switch (g.object_kind) {
789
+ case "sequence":
790
+ return `SEQUENCE ${name}`;
791
+ case "function":
792
+ return `FUNCTION ${name}(${g.args ?? ""})`;
793
+ case "procedure":
794
+ return `PROCEDURE ${name}(${g.args ?? ""})`;
795
+ default:
796
+ return name;
797
+ }
798
+ }
799
+ function describeObject(g) {
800
+ const name = `${g.table_schema}.${g.table_name}`;
801
+ switch (g.object_kind) {
802
+ case "sequence":
803
+ return `sequence ${name}`;
804
+ case "function":
805
+ return `function ${name}(${g.args ?? ""})`;
806
+ case "procedure":
807
+ return `procedure ${name}(${g.args ?? ""})`;
808
+ default:
809
+ return name;
810
+ }
811
+ }
812
+ function granteeSql(grantee) {
813
+ return grantee === "PUBLIC" ? "PUBLIC" : `"${grantee.replace(/"/g, '""')}"`;
814
+ }
815
+ function grantTarget(g) {
816
+ const column = g.column_name ? ` ("${g.column_name.replace(/"/g, '""')}")` : "";
817
+ return `${g.privilege_type}${column} ON ${objectSql(g)}`;
818
+ }
819
+ function describeGrant(g) {
820
+ const column = g.column_name ? `(${g.column_name}) ` : "";
821
+ return `${g.privilege_type} ${column}ON ${describeObject(g)} TO ${g.grantee}`;
822
+ }
823
+ var grantSql = (g, withOption = g.is_grantable) => `GRANT ${grantTarget(g)} TO ${granteeSql(g.grantee)}${withOption ? " WITH GRANT OPTION" : ""};`;
824
+ function comparablePrivileges(sourceVersion, targetVersion) {
825
+ const both = Math.min(sourceVersion || Infinity, targetVersion || Infinity);
826
+ return (g) => g.privilege_type !== "MAINTAIN" || both >= 17e4;
827
+ }
828
+ function grouped(grants) {
829
+ const groups = /* @__PURE__ */ new Map();
830
+ for (const g of grants) {
831
+ const key = `${grantKey(g).replace(/\.[^.]+$/, "")}.${Boolean(g.is_grantable)}`;
832
+ groups.set(key, [...groups.get(key) ?? [], g]);
833
+ }
834
+ return [...groups.values()];
835
+ }
836
+ function groupTarget(gs) {
837
+ const column = gs[0].column_name ? ` ("${gs[0].column_name.replace(/"/g, '""')}")` : "";
838
+ return `${gs.map((g) => `${g.privilege_type}${column}`).join(", ")} ON ${objectSql(gs[0])}`;
839
+ }
840
+ function describeGroup(gs) {
841
+ const column = gs[0].column_name ? `(${gs[0].column_name}) ` : "";
842
+ return `${gs.map((g) => g.privilege_type).join(", ")} ${column}ON ${describeObject(gs[0])} TO ${gs[0].grantee}`;
843
+ }
844
+ var groupKey = (gs) => grantKey(gs[0]).replace(/\.[^.]+$/, "");
845
+ function diffGrants(source, target) {
846
+ const issues = [];
847
+ const sourceMap = new Map(source.map((g) => [grantKey(g), g]));
848
+ const targetMap = new Map(target.map((g) => [grantKey(g), g]));
849
+ const missing = [...sourceMap].filter(([key]) => !targetMap.has(key)).map(([, g]) => g);
850
+ for (const gs of grouped(missing)) {
851
+ const plural = gs.length > 1 ? "s" : "";
852
+ issues.push({
853
+ id: `roles-grant-missing-${groupKey(gs)}`,
854
+ check: "roles",
855
+ severity: "warning",
856
+ title: `Missing grant${plural}: ${describeGroup(gs)}`,
857
+ description: `Grant${plural} "${describeGroup(gs)}" ${gs.length > 1 ? "are" : "is"} missing from target.`,
858
+ sourceValue: gs.length > 1 ? gs : gs[0],
859
+ sql: {
860
+ up: `GRANT ${groupTarget(gs)} TO ${granteeSql(gs[0].grantee)}${gs[0].is_grantable ? " WITH GRANT OPTION" : ""};`,
861
+ down: `REVOKE ${groupTarget(gs)} FROM ${granteeSql(gs[0].grantee)};`
862
+ }
863
+ });
864
+ }
865
+ for (const [key, sg] of sourceMap) {
866
+ const tg = targetMap.get(key);
867
+ if (tg && Boolean(sg.is_grantable) !== Boolean(tg.is_grantable)) {
868
+ const revokeOption = `REVOKE GRANT OPTION FOR ${grantTarget(sg)} FROM ${granteeSql(sg.grantee)};`;
869
+ issues.push({
870
+ id: `roles-grant-option-${key}`,
871
+ check: "roles",
872
+ severity: "warning",
873
+ title: `Grant option differs: ${describeGrant(sg)}`,
874
+ description: `"${describeGrant(sg)}" is held ${sg.is_grantable ? "with" : "without"} the grant option in source and ${tg.is_grantable ? "with" : "without"} it in target.`,
875
+ sourceValue: sg,
876
+ targetValue: tg,
877
+ sql: sg.is_grantable ? { up: grantSql(sg, true), down: revokeOption } : { up: revokeOption, down: grantSql(tg, true) }
878
+ });
879
+ }
880
+ }
881
+ const extra = [...targetMap].filter(([key]) => !sourceMap.has(key)).map(([, g]) => g);
882
+ for (const gs of grouped(extra)) {
883
+ const plural = gs.length > 1 ? "s" : "";
884
+ issues.push({
885
+ id: `roles-grant-extra-${groupKey(gs)}`,
886
+ check: "roles",
887
+ severity: extraGrantSeverity(gs[0].grantee),
888
+ title: `Extra grant${plural}: ${describeGroup(gs)}`,
889
+ description: `Grant${plural} "${describeGroup(gs)}" exist${gs.length > 1 ? "" : "s"} in target but not in source.`,
890
+ targetValue: gs.length > 1 ? gs : gs[0],
891
+ sql: {
892
+ up: `REVOKE ${groupTarget(gs)} FROM ${granteeSql(gs[0].grantee)};`,
893
+ down: `GRANT ${groupTarget(gs)} TO ${granteeSql(gs[0].grantee)}${gs[0].is_grantable ? " WITH GRANT OPTION" : ""};`
894
+ }
895
+ });
896
+ }
897
+ return issues;
898
+ }
899
+
900
+ export {
901
+ resolveTableFilter,
902
+ isFiltered,
903
+ describeTableFilter,
904
+ applyTableFilter,
905
+ CHECK_NAMES,
906
+ CHECK_META,
907
+ isComparisonCheck,
908
+ PLATFORM_ROLES,
909
+ RolesCheck,
910
+ ABSENT_ON_TARGET,
911
+ EXTENSION_UNAVAILABLE,
912
+ planWork,
913
+ runLikeApply,
914
+ promote
915
+ };
916
+ //# sourceMappingURL=chunk-UWAVXC57.js.map