@myrialabs/clopen 0.4.38 → 0.4.39

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 (114) hide show
  1. package/backend/auth/permissions.ts +25 -0
  2. package/backend/chat/stream-manager.ts +1 -1
  3. package/backend/database/crypto/secret-columns.ts +5 -1
  4. package/backend/database/migrations/075_create_deploy_bindings.ts +54 -0
  5. package/backend/database/migrations/076_remove_memory_code_graph.ts +229 -0
  6. package/backend/database/migrations/077_create_integration_db_links.ts +150 -0
  7. package/backend/database/migrations/index.ts +21 -0
  8. package/backend/database/queries/db-client-connection-queries.ts +19 -0
  9. package/backend/database/queries/deploy-queries.ts +124 -0
  10. package/backend/database/queries/graph-queries.ts +291 -247
  11. package/backend/database/queries/index.ts +4 -0
  12. package/backend/database/queries/integration-db-link-queries.ts +168 -0
  13. package/backend/database/queries/integration-queries.ts +34 -6
  14. package/backend/db-client/integrations/index.ts +37 -0
  15. package/backend/db-client/integrations/links.ts +533 -0
  16. package/backend/db-client/integrations/projector.test.ts +280 -0
  17. package/backend/db-client/integrations/projector.ts +256 -0
  18. package/backend/db-client/integrations/supabase-service.ts +266 -0
  19. package/backend/db-client/providers/registry.ts +27 -0
  20. package/backend/db-client/providers/supabase/adapter.ts +500 -0
  21. package/backend/db-client/providers/supabase/api-types.ts +92 -0
  22. package/backend/db-client/providers/supabase/apply-migration.ts +104 -0
  23. package/backend/db-client/providers/supabase/client.ts +259 -0
  24. package/backend/db-client/providers/supabase/features.ts +502 -0
  25. package/backend/db-client/providers/supabase/local.test.ts +78 -0
  26. package/backend/db-client/providers/supabase/local.ts +137 -0
  27. package/backend/db-client/providers/types.ts +137 -0
  28. package/backend/deployments/bindings.test.ts +43 -0
  29. package/backend/deployments/bindings.ts +216 -0
  30. package/backend/deployments/index.ts +53 -0
  31. package/backend/deployments/log-streams.ts +214 -0
  32. package/backend/deployments/prompts.ts +70 -0
  33. package/backend/deployments/providers/vercel/adapter.ts +757 -0
  34. package/backend/deployments/providers/vercel/build-logs.test.ts +80 -0
  35. package/backend/deployments/providers/vercel/build-logs.ts +211 -0
  36. package/backend/deployments/providers/vercel/client.ts +203 -0
  37. package/backend/deployments/providers/vercel/list.test.ts +624 -0
  38. package/backend/deployments/providers/vercel/normalise.test.ts +115 -0
  39. package/backend/deployments/providers/vercel/normalise.ts +113 -0
  40. package/backend/deployments/providers/vercel/types.ts +104 -0
  41. package/backend/deployments/registry.ts +27 -0
  42. package/backend/deployments/service.ts +458 -0
  43. package/backend/deployments/types.ts +278 -0
  44. package/backend/index.ts +4 -0
  45. package/backend/integrations/projections/index.ts +0 -0
  46. package/backend/integrations/projections/mcp-projector.ts +7 -3
  47. package/backend/integrations/projections/types.ts +21 -9
  48. package/backend/integrations/registry/index.ts +5 -1
  49. package/backend/integrations/registry/providers/supabase.ts +61 -0
  50. package/backend/integrations/registry/providers/vercel.ts +46 -0
  51. package/backend/mcp/internal/servers/memory-graph/description.ts +3 -3
  52. package/backend/mcp/internal/servers/memory-graph/runner.ts +4 -9
  53. package/backend/mcp/internal/servers/memory-graph/schema.ts +0 -4
  54. package/backend/memory/README.md +57 -34
  55. package/backend/memory/compose.test.ts +3 -3
  56. package/backend/memory/compose.ts +6 -9
  57. package/backend/memory/config.ts +0 -5
  58. package/backend/memory/consolidate.ts +1 -2
  59. package/backend/memory/context.test.ts +8 -54
  60. package/backend/memory/context.ts +19 -25
  61. package/backend/memory/extract/episodic.ts +10 -12
  62. package/backend/memory/extract/index.ts +23 -52
  63. package/backend/memory/extract/scheduler.ts +3 -6
  64. package/backend/memory/index.ts +6 -5
  65. package/backend/memory/invalidate.ts +36 -48
  66. package/backend/memory/layout.ts +319 -130
  67. package/backend/memory/retention.ts +12 -42
  68. package/backend/memory/retrieval.eval.test.ts +2 -2
  69. package/backend/memory/retrieval.test.ts +228 -183
  70. package/backend/memory/retrieval.ts +22 -21
  71. package/backend/memory/revise.test.ts +62 -116
  72. package/backend/memory/revise.ts +0 -1
  73. package/backend/memory/view.ts +8 -5
  74. package/backend/snapshot/helpers.ts +35 -41
  75. package/backend/snapshot/snapshot-service.ts +90 -0
  76. package/backend/snapshot/turn-changes.test.ts +163 -0
  77. package/backend/snapshot/turn-changes.ts +131 -0
  78. package/backend/ws/db-client/accounts.ts +225 -0
  79. package/backend/ws/db-client/connections.ts +34 -3
  80. package/backend/ws/db-client/context.ts +37 -0
  81. package/backend/ws/db-client/index.ts +20 -1
  82. package/backend/ws/db-client/supabase.ts +188 -0
  83. package/backend/ws/deployments/actions.ts +360 -0
  84. package/backend/ws/deployments/context.ts +43 -0
  85. package/backend/ws/deployments/crud.ts +152 -0
  86. package/backend/ws/deployments/index.ts +15 -0
  87. package/backend/ws/deployments/schemas.ts +183 -0
  88. package/backend/ws/index.ts +6 -2
  89. package/backend/ws/memory/crud.ts +4 -16
  90. package/backend/ws/snapshot/changes.ts +279 -0
  91. package/backend/ws/snapshot/index.ts +4 -3
  92. package/dist/assets/{index-CyH7fSbR.js → index-BrF6nqld.js} +1 -1
  93. package/dist/assets/{index-DSHIANSy.js → index-C8Gi-b6U.js} +1 -1
  94. package/dist/assets/main-Bd3gb79F.css +1 -0
  95. package/dist/assets/main-Bo1hD7mt.js +1191 -0
  96. package/dist/index.html +2 -2
  97. package/package.json +1 -1
  98. package/shared/constants/tool-icons.ts +9 -0
  99. package/shared/types/db-client/connection.ts +6 -0
  100. package/shared/types/db-client/index.ts +2 -0
  101. package/shared/types/db-client/integrations.ts +174 -0
  102. package/shared/types/db-client/supabase.ts +131 -0
  103. package/shared/types/deployments.ts +382 -0
  104. package/shared/types/memory.ts +34 -51
  105. package/shared/types/ui/components.ts +1 -1
  106. package/shared/utils/diff-calculator.test.ts +89 -0
  107. package/shared/utils/diff-calculator.ts +30 -65
  108. package/shared/utils/logger.ts +1 -0
  109. package/backend/memory/extract/languages.ts +0 -176
  110. package/backend/memory/extract/structural.test.ts +0 -215
  111. package/backend/memory/extract/structural.ts +0 -364
  112. package/backend/ws/snapshot/content.ts +0 -85
  113. package/dist/assets/main-D2IOjftb.css +0 -1
  114. package/dist/assets/main-DM-tHKbW.js +0 -1152
@@ -0,0 +1,500 @@
1
+ /**
2
+ * Supabase as a database provider.
3
+ *
4
+ * Three facts about Supabase shape everything below, and all three were checked
5
+ * against the published API document rather than assumed:
6
+ *
7
+ * 1. **The password cannot be read back.** There is no GET for a project's
8
+ * database password — only a PATCH that changes it. So a link asks for it
9
+ * once and stores it, and `resolveEndpoint` never pretends to know it.
10
+ * 2. **Direct connections are IPv6-only on projects created since 2024**,
11
+ * unless the account pays for an IPv4 add-on. A default of "direct" would
12
+ * therefore fail on most new projects with a DNS-shaped error that says
13
+ * nothing about the cause, so the pooler is the default and direct is an
14
+ * explicit choice that says why it might not work.
15
+ * 3. **Transaction mode does not support prepared statements.** Our Postgres
16
+ * driver is `Bun.sql`, which prepares, so transaction mode (port 6543) is
17
+ * offered but is not the default and says what it costs. Session mode on the
18
+ * pooler host is the one combination that is both reachable and compatible.
19
+ *
20
+ * The pooler host is NOT derivable from the project ref — it encodes the
21
+ * region — so it is fetched from `/config/database/pooler` at link time and
22
+ * stored on the link.
23
+ */
24
+
25
+ import type {
26
+ DbProviderAdapter,
27
+ DbProviderContext,
28
+ DbProviderEndpoint
29
+ } from '../types';
30
+ import type {
31
+ DbProviderCreateGroup,
32
+ DbProviderCreateOptions,
33
+ DbProviderInfo,
34
+ DbRemoteDatabase
35
+ } from '$shared/types/db-client';
36
+ import type { IntegrationStatus } from '$shared/types/integrations';
37
+ import type { SupabaseApiOrganization, SupabaseApiPoolerConfig, SupabaseApiProject } from './api-types';
38
+ import { SUPABASE_SLOW_TIMEOUT_MS, SupabaseError, supabaseRequest, type SupabaseCredentials } from './client';
39
+ import { debug } from '$shared/utils/logger';
40
+
41
+ export const SUPABASE_PROVIDER_ID = 'supabase';
42
+
43
+ /** Connection modes, in the order the dialog offers them. */
44
+ export const SUPABASE_MODES = {
45
+ poolerSession: 'pooler-session',
46
+ poolerTransaction: 'pooler-transaction',
47
+ direct: 'direct'
48
+ } as const;
49
+
50
+ /** Supavisor listens for session mode on 5432 and transaction mode on 6543. */
51
+ const POOLER_SESSION_PORT = 5432;
52
+ const POOLER_TRANSACTION_PORT = 6543;
53
+ const DIRECT_PORT = 5432;
54
+
55
+ export function supabaseCredentialsOf(context: DbProviderContext): SupabaseCredentials {
56
+ const accessToken = (context.credentials.accessToken ?? '').trim();
57
+ if (!accessToken) {
58
+ throw new SupabaseError(
59
+ 'This Supabase account has no access token. Reconnect it in Settings → Integrations.',
60
+ 401,
61
+ 'auth'
62
+ );
63
+ }
64
+ return { accessToken };
65
+ }
66
+
67
+ /**
68
+ * The one state a project can actually be connected to in.
69
+ *
70
+ * Everything else — `COMING_UP`, `PAUSED`, `RESTORING` — looks like an ordinary
71
+ * row in a list and refuses every connection, which is why readiness is
72
+ * reported rather than inferred from the row existing.
73
+ */
74
+ const READY_STATUS = 'ACTIVE_HEALTHY';
75
+
76
+ /**
77
+ * Regions, taken from the `region` enum in the published API document.
78
+ *
79
+ * Hard-coded deliberately. The live source is `GET /v1/projects/available-regions`,
80
+ * which is marked BETA, requires an organisation slug and answers with a nested
81
+ * recommendation structure — a lot of surface to depend on for a list of AWS
82
+ * regions that has changed a handful of times in five years. If a region is
83
+ * missing here the user can still create the project in Supabase's dashboard and
84
+ * link it, which is a far smaller failure than a beta endpoint changing shape.
85
+ */
86
+ const REGIONS: { value: string; label: string }[] = [
87
+ { value: 'us-east-1', label: 'US East (N. Virginia)' },
88
+ { value: 'us-east-2', label: 'US East (Ohio)' },
89
+ { value: 'us-west-1', label: 'US West (N. California)' },
90
+ { value: 'us-west-2', label: 'US West (Oregon)' },
91
+ { value: 'ca-central-1', label: 'Canada (Central)' },
92
+ { value: 'sa-east-1', label: 'South America (São Paulo)' },
93
+ { value: 'eu-west-1', label: 'Europe (Ireland)' },
94
+ { value: 'eu-west-2', label: 'Europe (London)' },
95
+ { value: 'eu-west-3', label: 'Europe (Paris)' },
96
+ { value: 'eu-central-1', label: 'Europe (Frankfurt)' },
97
+ { value: 'eu-central-2', label: 'Europe (Zurich)' },
98
+ { value: 'eu-north-1', label: 'Europe (Stockholm)' },
99
+ { value: 'ap-south-1', label: 'Asia Pacific (Mumbai)' },
100
+ { value: 'ap-southeast-1', label: 'Asia Pacific (Singapore)' },
101
+ { value: 'ap-southeast-2', label: 'Asia Pacific (Sydney)' },
102
+ { value: 'ap-northeast-1', label: 'Asia Pacific (Tokyo)' },
103
+ { value: 'ap-northeast-2', label: 'Asia Pacific (Seoul)' },
104
+ { value: 'ap-east-1', label: 'Asia Pacific (Hong Kong)' }
105
+ ];
106
+
107
+ /**
108
+ * A password for a project we are creating.
109
+ *
110
+ * Generated rather than asked for, and never shown: the user has no reason to
111
+ * type it, and Clopen stores it sealed the moment the project exists. Base64url
112
+ * of 24 random bytes clears Supabase's strength rules without needing to know
113
+ * what they are, and carries no characters that need escaping in a connection
114
+ * string.
115
+ */
116
+ function generatePassword(): string {
117
+ const bytes = new Uint8Array(24);
118
+ crypto.getRandomValues(bytes);
119
+ return btoa(String.fromCharCode(...bytes)).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
120
+ }
121
+
122
+ /** A project that is not running cannot be connected to, and says so. */
123
+ function statusDetail(project: SupabaseApiProject): string {
124
+ const parts = [project.region];
125
+ if (project.status && project.status !== 'ACTIVE_HEALTHY') {
126
+ parts.push(project.status.toLowerCase().replace(/_/g, ' '));
127
+ }
128
+ return parts.filter(Boolean).join(' · ');
129
+ }
130
+
131
+ export async function listSupabaseProjects(context: DbProviderContext): Promise<SupabaseApiProject[]> {
132
+ return supabaseRequest<SupabaseApiProject[]>(supabaseCredentialsOf(context), '/v1/projects');
133
+ }
134
+
135
+ /**
136
+ * The primary database's pooler configuration.
137
+ *
138
+ * The endpoint answers with an array — a project with read replicas has one
139
+ * entry each — and the primary is the one this surface connects to. Picking the
140
+ * first entry regardless would silently connect a read replica on some projects.
141
+ */
142
+ async function poolerConfig(
143
+ credentials: SupabaseCredentials,
144
+ ref: string
145
+ ): Promise<SupabaseApiPoolerConfig | null> {
146
+ const configs = await supabaseRequest<SupabaseApiPoolerConfig[]>(
147
+ credentials,
148
+ `/v1/projects/${encodeURIComponent(ref)}/config/database/pooler`
149
+ );
150
+ if (!Array.isArray(configs) || configs.length === 0) return null;
151
+ return configs.find((entry) => entry.database_type === 'PRIMARY') ?? configs[0];
152
+ }
153
+
154
+ export const supabaseDbAdapter: DbProviderAdapter = {
155
+ provider: SUPABASE_PROVIDER_ID,
156
+ driver: 'postgres',
157
+
158
+ info(): DbProviderInfo {
159
+ return {
160
+ id: SUPABASE_PROVIDER_ID,
161
+ name: 'Supabase',
162
+ driver: 'postgres',
163
+ description: 'Pick a project this token can reach.',
164
+ // Session mode is correct for this client in every case the other two
165
+ // are not, so it is the silent default and both escape hatches are
166
+ // marked advanced. Transaction mode is genuinely a trap here — our
167
+ // driver prepares statements — and a direct connection is IPv6-only on
168
+ // projects created since 2024; offering all three up front asked the
169
+ // user to choose between one right answer and two ways to fail.
170
+ modes: [
171
+ {
172
+ id: SUPABASE_MODES.poolerSession,
173
+ label: 'Pooler (session)',
174
+ help: 'Works over IPv4. The right choice unless the pooler is unavailable.',
175
+ isDefault: true
176
+ },
177
+ {
178
+ id: SUPABASE_MODES.poolerTransaction,
179
+ label: 'Pooler (transaction)',
180
+ help: 'Breaks prepared statements, which this client uses.',
181
+ isAdvanced: true
182
+ },
183
+ {
184
+ id: SUPABASE_MODES.direct,
185
+ label: 'Direct',
186
+ help: 'IPv6 only on projects created since 2024.',
187
+ isAdvanced: true
188
+ }
189
+ ],
190
+ secretFields: [
191
+ {
192
+ name: 'password',
193
+ label: 'Database password',
194
+ placeholder: 'Project database password',
195
+ help: 'Project Settings → Database. Supabase cannot read it back, so it is stored here, encrypted.',
196
+ isRequired: true
197
+ }
198
+ ]
199
+ };
200
+ },
201
+
202
+ async listDatabases(context: DbProviderContext): Promise<DbRemoteDatabase[]> {
203
+ const credentials = supabaseCredentialsOf(context);
204
+ // The organisation is fetched ALONGSIDE the projects, not for each of
205
+ // them: a project carries only its org's slug, and an account with a
206
+ // dozen projects in two organisations would otherwise ask twelve times
207
+ // for two answers. A token without Organizations Read still gets a list —
208
+ // it simply falls back to the slug the project already reported.
209
+ const [projects, organizations] = await Promise.all([
210
+ listSupabaseProjects(context),
211
+ supabaseRequest<SupabaseApiOrganization[]>(credentials, '/v1/organizations').catch((error) => {
212
+ debug.warn('db-client', 'Could not name Supabase organizations:', error);
213
+ return [] as SupabaseApiOrganization[];
214
+ })
215
+ ]);
216
+
217
+ const names = new Map<string, string>();
218
+ for (const organization of organizations ?? []) {
219
+ if (organization?.slug) names.set(organization.slug, organization.name || organization.slug);
220
+ }
221
+
222
+ return projects.map((project) => ({
223
+ ref: project.ref || project.id,
224
+ name: project.name,
225
+ detail: statusDetail(project),
226
+ group: project.organization_slug
227
+ ? names.get(project.organization_slug) ?? project.organization_slug
228
+ : null,
229
+ status: project.status ?? null,
230
+ isReady: project.status === READY_STATUS,
231
+ isLinked: false
232
+ }));
233
+ },
234
+
235
+ async resolveEndpoint(
236
+ context: DbProviderContext,
237
+ target: { remoteRef: string; mode: string }
238
+ ): Promise<DbProviderEndpoint> {
239
+ const credentials = supabaseCredentialsOf(context);
240
+ const ref = target.remoteRef;
241
+
242
+ if (target.mode === SUPABASE_MODES.direct) {
243
+ // The direct host is REPORTED per project rather than derived:
244
+ // `db.<ref>.supabase.co` is a convention, not a guarantee, and a project
245
+ // on a custom or older domain would be sent somewhere that does not
246
+ // resolve. The convention is only the fallback.
247
+ const project = await supabaseRequest<SupabaseApiProject>(
248
+ credentials,
249
+ `/v1/projects/${encodeURIComponent(ref)}`
250
+ );
251
+ const host = project?.database?.host ?? `db.${ref}.supabase.co`;
252
+ return {
253
+ host,
254
+ port: DIRECT_PORT,
255
+ username: 'postgres',
256
+ database: 'postgres',
257
+ // Supabase terminates TLS on every endpoint, but its certificate is
258
+ // issued by its own CA, so demanding verification without also
259
+ // shipping that CA would refuse every connection. `require` is the
260
+ // honest setting: encrypted, not pinned.
261
+ sslMode: 'require',
262
+ options: { supabase: { ref, mode: target.mode } }
263
+ };
264
+ }
265
+
266
+ const pooler = await poolerConfig(credentials, ref);
267
+ if (!pooler) {
268
+ throw new SupabaseError(
269
+ `Supabase did not report a pooler for ${ref}. Choose a direct connection instead, or check the project is running.`,
270
+ 404,
271
+ 'config'
272
+ );
273
+ }
274
+
275
+ const isTransaction = target.mode === SUPABASE_MODES.poolerTransaction;
276
+ return {
277
+ host: pooler.db_host,
278
+ // The reported port belongs to whichever mode the project is configured
279
+ // for, so it is only trusted when it matches the mode being asked for.
280
+ port: isTransaction ? POOLER_TRANSACTION_PORT : POOLER_SESSION_PORT,
281
+ // `postgres.<ref>` — the pooler routes on the username, so the plain
282
+ // `postgres` that works on a direct connection fails here.
283
+ username: pooler.db_user || `postgres.${ref}`,
284
+ database: pooler.db_name || 'postgres',
285
+ sslMode: 'require',
286
+ options: { supabase: { ref, mode: target.mode } }
287
+ };
288
+ },
289
+
290
+ async createOptions(context: DbProviderContext): Promise<DbProviderCreateOptions> {
291
+ const credentials = supabaseCredentialsOf(context);
292
+
293
+ // Listed organisations are trusted; derived ones are CHECKED but still
294
+ // offered when the check cannot confirm them.
295
+ //
296
+ // Three facts, all confirmed against a live scoped token, and each one
297
+ // killed a simpler design:
298
+ //
299
+ // 1. `/v1/organizations` answers `[]` with a 200 for a token that plainly
300
+ // reaches projects, so it is not the last word.
301
+ // 2. A project's `organization_slug` names where that project lives, not
302
+ // somewhere this token may act — `/v1/organizations/{slug}` 403s for
303
+ // an organisation the user is merely a member of. Offering those
304
+ // unmarked produced a 403 after the form was filled in.
305
+ // 3. But reading and writing are SEPARATE permissions: the same token
306
+ // that cannot read an organisation successfully created one. So
307
+ // dropping every unverifiable candidate removed a capability that
308
+ // works, which is its own kind of wrong.
309
+ //
310
+ // Hence: verify, and mark rather than hide. The caller decides how loudly
311
+ // to say "this might fail", and a 403 now names the missing permission.
312
+ const [listed, projects] = await Promise.all([
313
+ supabaseRequest<SupabaseApiOrganization[]>(credentials, '/v1/organizations').catch((error) => {
314
+ debug.warn('db-client', 'Could not list Supabase organizations:', error);
315
+ return [] as SupabaseApiOrganization[];
316
+ }),
317
+ supabaseRequest<SupabaseApiProject[]>(credentials, '/v1/projects').catch(() => [] as SupabaseApiProject[])
318
+ ]);
319
+
320
+ const groups = new Map<string, DbProviderCreateGroup>();
321
+ for (const organization of listed ?? []) {
322
+ if (!organization?.slug) continue;
323
+ groups.set(organization.slug, {
324
+ value: organization.slug,
325
+ label: organization.name || organization.slug
326
+ });
327
+ }
328
+
329
+ const candidates = new Set<string>();
330
+ for (const project of projects ?? []) {
331
+ const slug = project.organization_slug;
332
+ // Only a slug is usable: `organization_id` is deprecated and the create
333
+ // endpoint takes the slug.
334
+ if (slug && !groups.has(slug)) candidates.add(slug);
335
+ }
336
+
337
+ await Promise.all(
338
+ [...candidates].map(async (slug) => {
339
+ try {
340
+ const organization = await supabaseRequest<SupabaseApiOrganization>(
341
+ credentials,
342
+ `/v1/organizations/${encodeURIComponent(slug)}`
343
+ );
344
+ groups.set(slug, { value: slug, label: organization?.name || slug });
345
+ } catch {
346
+ groups.set(slug, {
347
+ value: slug,
348
+ label: slug,
349
+ detail: 'unverified',
350
+ isUnverified: true
351
+ });
352
+ }
353
+ })
354
+ );
355
+
356
+ debug.log(
357
+ 'db-client',
358
+ `Supabase create options: ${listed?.length ?? 0} listed, ${candidates.size} derived, ${groups.size} offered`
359
+ );
360
+
361
+ return {
362
+ groupLabel: 'Organisation',
363
+ groups: [...groups.values()],
364
+ regionLabel: 'Region',
365
+ regions: REGIONS,
366
+ // Names the consequence rather than asking "are you sure". Creating a
367
+ // project provisions real infrastructure against a real quota, and the
368
+ // plan lives on the organisation, so which one is picked decides
369
+ // whether this is free.
370
+ notice:
371
+ 'This provisions a real Postgres database on Supabase. It counts against the organisation\'s project quota and its plan decides what it costs.',
372
+ // Shown INSTEAD of the form when nothing is usable. The two real causes
373
+ // are named because the fix differs: one is a token problem, the other
374
+ // is a membership problem, and "Forbidden" distinguishes neither.
375
+ // Short, and one instruction. The long version listed three ways out at
376
+ // once and ended on "link it here", which named no action the reader
377
+ // could take from where they were standing.
378
+ emptyGroupsNotice:
379
+ 'This token reaches no organisation — create one, or regenerate the token with Organizations Read.',
380
+ canCreateGroup: true,
381
+ createGroupNotice: 'A new organisation is a billing entity and starts on the free plan.'
382
+ };
383
+ },
384
+
385
+ /**
386
+ * Create an organisation.
387
+ *
388
+ * `POST /v1/organizations` takes a name and nothing else — no plan, no
389
+ * region — and answers with the slug the create-project call needs. It is a
390
+ * billing entity, so the dialog names that before the button; new
391
+ * organisations start on the free plan.
392
+ */
393
+ async createGroup(
394
+ context: DbProviderContext,
395
+ input: { name: string }
396
+ ): Promise<{ value: string; label: string }> {
397
+ const created = await supabaseRequest<SupabaseApiOrganization>(
398
+ supabaseCredentialsOf(context),
399
+ '/v1/organizations',
400
+ { method: 'POST', body: { name: input.name.trim() } }
401
+ );
402
+ if (!created?.slug) {
403
+ throw new SupabaseError(
404
+ 'Supabase created the organisation but did not report its slug, so it cannot be used here yet. It will appear after a refresh.',
405
+ 502,
406
+ 'error'
407
+ );
408
+ }
409
+ return { value: created.slug, label: created.name || created.slug };
410
+ },
411
+
412
+ async createDatabase(
413
+ context: DbProviderContext,
414
+ input: { name: string; group: string; region: string }
415
+ ): Promise<{ ref: string; secrets: Record<string, string> }> {
416
+ const password = generatePassword();
417
+ const created = await supabaseRequest<SupabaseApiProject>(
418
+ supabaseCredentialsOf(context),
419
+ '/v1/projects',
420
+ {
421
+ method: 'POST',
422
+ body: {
423
+ name: input.name,
424
+ organization_slug: input.group,
425
+ db_pass: password,
426
+ // `region_selection` rather than the older `region` string, which
427
+ // the API document marks deprecated. The shape is the documented
428
+ // one: a discriminated object, not a bare code.
429
+ region_selection: { type: 'specific', code: input.region }
430
+ },
431
+ // Provisioning is real work upstream, and aborting at the read budget
432
+ // would report a timeout for a project that now exists.
433
+ timeoutMs: SUPABASE_SLOW_TIMEOUT_MS
434
+ }
435
+ );
436
+
437
+ const ref = created?.ref || created?.id;
438
+ if (!ref) {
439
+ throw new SupabaseError(
440
+ 'Supabase accepted the project but did not report its ref, so it cannot be linked automatically. It will be in the list once it finishes provisioning.',
441
+ 502,
442
+ 'error'
443
+ );
444
+ }
445
+ return { ref, secrets: { password } };
446
+ },
447
+
448
+ /**
449
+ * Delete a project.
450
+ *
451
+ * Irreversible, and the API offers no undo — there is no trash. The confirm
452
+ * that guards it names the database rather than asking "are you sure",
453
+ * because the name is the thing someone can check against what they meant.
454
+ */
455
+ async deleteDatabase(context: DbProviderContext, remoteRef: string): Promise<void> {
456
+ await supabaseRequest(
457
+ supabaseCredentialsOf(context),
458
+ `/v1/projects/${encodeURIComponent(remoteRef)}`,
459
+ { method: 'DELETE', timeoutMs: SUPABASE_SLOW_TIMEOUT_MS }
460
+ );
461
+ },
462
+
463
+ /**
464
+ * Rename a project.
465
+ *
466
+ * `PATCH /v1/projects/{ref}` takes a name and nothing else — it is the only
467
+ * field of a project the Management API lets us change. Organisations have
468
+ * no PATCH at all, which is why this adapter renames databases and not
469
+ * groups.
470
+ */
471
+ async renameDatabase(context: DbProviderContext, remoteRef: string, name: string): Promise<void> {
472
+ await supabaseRequest(
473
+ supabaseCredentialsOf(context),
474
+ `/v1/projects/${encodeURIComponent(remoteRef)}`,
475
+ { method: 'PATCH', body: { name } }
476
+ );
477
+ },
478
+
479
+ async probe(context: DbProviderContext): Promise<{ status: IntegrationStatus; detail: string | null }> {
480
+ try {
481
+ const projects = await listSupabaseProjects(context);
482
+ if (projects.length === 0) {
483
+ return {
484
+ status: 'needs_config',
485
+ detail: 'The token works but reaches no projects — check which Supabase user it belongs to.'
486
+ };
487
+ }
488
+ const plural = projects.length === 1 ? 'project' : 'projects';
489
+ return { status: 'ok', detail: `${projects.length} ${plural} reachable` };
490
+ } catch (error) {
491
+ if (error instanceof SupabaseError) {
492
+ const status: IntegrationStatus = error.kind === 'auth'
493
+ ? 'needs_auth'
494
+ : error.kind === 'config' ? 'needs_config' : 'error';
495
+ return { status, detail: error.message };
496
+ }
497
+ return { status: 'error', detail: error instanceof Error ? error.message : String(error) };
498
+ }
499
+ }
500
+ };
@@ -0,0 +1,92 @@
1
+ /**
2
+ * The shapes the Supabase Management API actually returns.
3
+ *
4
+ * Transcribed from the published OpenAPI document, narrowed to the fields this
5
+ * surface reads. Everything optional is optional because the document says so —
6
+ * a field marked required there is still declared optional here when reading it
7
+ * wrong would produce a confident wrong answer rather than a missing one.
8
+ */
9
+
10
+ export interface SupabaseApiProject {
11
+ id: string;
12
+ ref: string;
13
+ name: string;
14
+ region: string;
15
+ status: string;
16
+ organization_id?: string;
17
+ organization_slug?: string;
18
+ created_at?: string;
19
+ database?: {
20
+ host: string;
21
+ version: string;
22
+ postgres_engine?: string;
23
+ release_channel?: string;
24
+ };
25
+ }
26
+
27
+ /**
28
+ * Supavisor, Supabase's connection pooler.
29
+ *
30
+ * The endpoint answers with an ARRAY — one entry per database, so a project
31
+ * with a read replica has more than one. `connection_string` is treated as a
32
+ * template and never mined for a password: the API cannot hand the password
33
+ * back, so anything password-shaped in there is a placeholder.
34
+ */
35
+ export interface SupabaseApiPoolerConfig {
36
+ identifier: string;
37
+ database_type: 'PRIMARY' | 'READ_REPLICA';
38
+ db_user: string;
39
+ db_host: string;
40
+ db_port: number;
41
+ db_name: string;
42
+ connection_string?: string;
43
+ pool_mode?: 'transaction' | 'session';
44
+ default_pool_size?: number | null;
45
+ max_client_conn?: number | null;
46
+ is_using_scram_auth?: boolean;
47
+ }
48
+
49
+ export interface SupabaseApiFunction {
50
+ id: string;
51
+ slug: string;
52
+ name: string;
53
+ status: string;
54
+ version?: number;
55
+ /** Epoch milliseconds, not an ISO string. */
56
+ created_at?: number;
57
+ updated_at?: number;
58
+ verify_jwt?: boolean;
59
+ entrypoint_path?: string;
60
+ }
61
+
62
+ export interface SupabaseApiAdvisorResponse {
63
+ lints?: SupabaseApiLint[];
64
+ }
65
+
66
+ export interface SupabaseApiLint {
67
+ name?: string;
68
+ title?: string;
69
+ level?: string;
70
+ facing?: string;
71
+ description?: string;
72
+ detail?: string;
73
+ remediation?: string;
74
+ categories?: string[];
75
+ metadata?: Record<string, unknown> | null;
76
+ cache_key?: string;
77
+ }
78
+
79
+ export interface SupabaseApiTypes {
80
+ types: string;
81
+ }
82
+
83
+ export interface SupabaseApiMigration {
84
+ version: string;
85
+ name?: string;
86
+ }
87
+
88
+ export interface SupabaseApiOrganization {
89
+ id: string;
90
+ slug: string;
91
+ name: string;
92
+ }
@@ -0,0 +1,104 @@
1
+ /**
2
+ * Applying a pending migration.
3
+ *
4
+ * The one write path in the Supabase surface, and it goes over SQL rather than
5
+ * through `POST /v1/projects/{ref}/database/migrations`. Two reasons, in order
6
+ * of weight: the SQL path is the only one that also works for a `supabase start`
7
+ * stack, so there is one implementation instead of two; and it is exactly what
8
+ * `supabase db push` does — run the file, then record the version in the CLI's
9
+ * own bookkeeping table — so a migration applied from here is indistinguishable
10
+ * from one applied from the terminal.
11
+ *
12
+ * Everything happens in ONE transaction: Postgres rolls DDL back like anything
13
+ * else, so a migration that fails half way leaves nothing behind, and the
14
+ * version is only recorded if the SQL that earns it succeeded.
15
+ *
16
+ * The known limit is `CREATE INDEX CONCURRENTLY`, which Postgres refuses inside
17
+ * a transaction. The provider's own error says so plainly and is passed through
18
+ * rather than rewritten, because the fix — run that one statement by hand — is
19
+ * something only the user can decide on.
20
+ */
21
+
22
+ import type { DbClientDriverAdapter, DbClientTxContext } from '../../drivers/types';
23
+ import { debug } from '$shared/utils/logger';
24
+
25
+ const SCHEMA = 'supabase_migrations';
26
+ const TABLE = 'schema_migrations';
27
+
28
+ /**
29
+ * Make sure the CLI's bookkeeping table exists, in the shape the CLI uses.
30
+ *
31
+ * A project that has only ever been changed through the dashboard has no such
32
+ * table, and a project created by an older CLI has the table without its later
33
+ * columns — which is why each column is added separately and idempotently
34
+ * rather than the whole thing being created in one shot and assumed complete.
35
+ */
36
+ async function ensureBookkeeping(tx: DbClientTxContext): Promise<void> {
37
+ await tx.executeWrite(`CREATE SCHEMA IF NOT EXISTS ${SCHEMA}`);
38
+ await tx.executeWrite(`
39
+ CREATE TABLE IF NOT EXISTS ${SCHEMA}.${TABLE} (
40
+ version text NOT NULL PRIMARY KEY
41
+ )
42
+ `);
43
+ await tx.executeWrite(`ALTER TABLE ${SCHEMA}.${TABLE} ADD COLUMN IF NOT EXISTS statements text[]`);
44
+ await tx.executeWrite(`ALTER TABLE ${SCHEMA}.${TABLE} ADD COLUMN IF NOT EXISTS name text`);
45
+ }
46
+
47
+ export interface ApplyMigrationInput {
48
+ adapter: DbClientDriverAdapter;
49
+ version: string;
50
+ name: string | null;
51
+ sql: string;
52
+ }
53
+
54
+ export interface ApplyMigrationResult {
55
+ version: string;
56
+ /** Milliseconds the whole transaction took, for the report line. */
57
+ durationMs: number;
58
+ }
59
+
60
+ export async function applyMigration(input: ApplyMigrationInput): Promise<ApplyMigrationResult> {
61
+ const { adapter, version, name, sql } = input;
62
+
63
+ if (!adapter.withTransaction) {
64
+ throw new Error('This connection cannot run a transaction, so a migration cannot be applied safely from here');
65
+ }
66
+ if (!sql.trim()) {
67
+ throw new Error(`Migration ${version} is empty`);
68
+ }
69
+
70
+ const started = performance.now();
71
+
72
+ await adapter.withTransaction(async (tx) => {
73
+ await ensureBookkeeping(tx);
74
+
75
+ // Guard INSIDE the transaction. Checking before it opens would leave a gap
76
+ // where two people apply the same migration at once and both see it
77
+ // pending; the primary key would then reject the second write after its
78
+ // SQL had already run.
79
+ const existing = await tx.executeRead(
80
+ `SELECT version FROM ${SCHEMA}.${TABLE} WHERE version = '${version.replace(/'/g, "''")}'`
81
+ );
82
+ if (existing.rows.length > 0) {
83
+ throw new Error(`Migration ${version} is already recorded as applied`);
84
+ }
85
+
86
+ // The whole file as one statement. Bun's SQL sends a parameterless query
87
+ // over the simple protocol, which is what allows the several statements a
88
+ // migration normally contains; splitting it here would have to understand
89
+ // dollar-quoted function bodies, and getting that wrong truncates a
90
+ // function definition mid-way.
91
+ await tx.executeWrite(sql);
92
+
93
+ const escapedVersion = version.replace(/'/g, "''");
94
+ const escapedName = name ? `'${name.replace(/'/g, "''")}'` : 'NULL';
95
+ await tx.executeWrite(`
96
+ INSERT INTO ${SCHEMA}.${TABLE} (version, name)
97
+ VALUES ('${escapedVersion}', ${escapedName})
98
+ `);
99
+ });
100
+
101
+ const durationMs = Math.round(performance.now() - started);
102
+ debug.log('db-client', `Applied Supabase migration ${version} in ${durationMs}ms`);
103
+ return { version, durationMs };
104
+ }