stripe-experiment-sync 1.0.12 → 1.0.15-beta.1766078819

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.
@@ -1,467 +0,0 @@
1
- import {
2
- package_default
3
- } from "./chunk-IO2EEPFD.js";
4
-
5
- // src/supabase/supabase.ts
6
- import { SupabaseManagementAPI } from "supabase-management-js";
7
-
8
- // raw-ts:/home/runner/work/sync-engine/sync-engine/packages/sync-engine/src/supabase/edge-functions/stripe-setup.ts
9
- var stripe_setup_default = "import { StripeSync, runMigrations, VERSION } from 'npm:stripe-experiment-sync'\nimport postgres from 'npm:postgres'\n\nDeno.serve(async (req) => {\n // Require authentication for both GET and POST\n const authHeader = req.headers.get('Authorization')\n if (!authHeader?.startsWith('Bearer ')) {\n return new Response('Unauthorized', { status: 401 })\n }\n\n // Handle GET requests for status\n if (req.method === 'GET') {\n const rawDbUrl = Deno.env.get('SUPABASE_DB_URL')\n if (!rawDbUrl) {\n return new Response(JSON.stringify({ error: 'SUPABASE_DB_URL not set' }), {\n status: 500,\n headers: { 'Content-Type': 'application/json' },\n })\n }\n\n const dbUrl = rawDbUrl.replace(/[?&]sslmode=[^&]*/g, '').replace(/[?&]$/, '')\n let sql\n\n try {\n sql = postgres(dbUrl, { max: 1, prepare: false })\n\n // Query installation status from schema comment\n const commentResult = await sql`\n SELECT obj_description(oid, 'pg_namespace') as comment\n FROM pg_namespace\n WHERE nspname = 'stripe'\n `\n\n const comment = commentResult[0]?.comment || null\n let installationStatus = 'not_installed'\n\n if (comment && comment.includes('stripe-sync')) {\n // Parse installation status from comment\n if (comment.includes('installation:started')) {\n installationStatus = 'installing'\n } else if (comment.includes('installation:error')) {\n installationStatus = 'error'\n } else if (comment.includes('installed')) {\n installationStatus = 'installed'\n }\n }\n\n // Query sync runs (only if schema exists)\n let syncStatus = []\n if (comment) {\n try {\n syncStatus = await sql`\n SELECT DISTINCT ON (account_id)\n account_id, started_at, closed_at, status, error_message,\n total_processed, total_objects, complete_count, error_count,\n running_count, pending_count, triggered_by, max_concurrent\n FROM stripe.sync_runs\n ORDER BY account_id, started_at DESC\n `\n } catch (err) {\n // Ignore errors if sync_runs view doesn't exist yet\n console.warn('sync_runs query failed (may not exist yet):', err)\n }\n }\n\n return new Response(\n JSON.stringify({\n package_version: VERSION,\n installation_status: installationStatus,\n sync_status: syncStatus,\n }),\n {\n status: 200,\n headers: {\n 'Content-Type': 'application/json',\n 'Cache-Control': 'no-cache, no-store, must-revalidate',\n },\n }\n )\n } catch (error) {\n console.error('Status query error:', error)\n return new Response(\n JSON.stringify({\n error: error.message,\n package_version: VERSION,\n installation_status: 'not_installed',\n }),\n {\n status: 500,\n headers: { 'Content-Type': 'application/json' },\n }\n )\n } finally {\n if (sql) await sql.end()\n }\n }\n\n // Handle POST requests for setup (existing logic)\n if (req.method !== 'POST') {\n return new Response('Method not allowed', { status: 405 })\n }\n\n let stripeSync = null\n try {\n // Get and validate database URL\n const rawDbUrl = Deno.env.get('SUPABASE_DB_URL')\n if (!rawDbUrl) {\n throw new Error('SUPABASE_DB_URL environment variable is not set')\n }\n // Remove sslmode from connection string (not supported by pg in Deno)\n const dbUrl = rawDbUrl.replace(/[?&]sslmode=[^&]*/g, '').replace(/[?&]$/, '')\n\n await runMigrations({ databaseUrl: dbUrl })\n\n stripeSync = new StripeSync({\n poolConfig: { connectionString: dbUrl, max: 2 }, // Need 2 for advisory lock + queries\n stripeSecretKey: Deno.env.get('STRIPE_SECRET_KEY'),\n })\n\n // Release any stale advisory locks from previous timeouts\n await stripeSync.postgresClient.query('SELECT pg_advisory_unlock_all()')\n\n // Construct webhook URL from SUPABASE_URL (available in all Edge Functions)\n const supabaseUrl = Deno.env.get('SUPABASE_URL')\n if (!supabaseUrl) {\n throw new Error('SUPABASE_URL environment variable is not set')\n }\n const webhookUrl = supabaseUrl + '/functions/v1/stripe-webhook'\n\n const webhook = await stripeSync.findOrCreateManagedWebhook(webhookUrl)\n\n await stripeSync.postgresClient.pool.end()\n\n return new Response(\n JSON.stringify({\n success: true,\n message: 'Setup complete',\n webhookId: webhook.id,\n }),\n {\n status: 200,\n headers: { 'Content-Type': 'application/json' },\n }\n )\n } catch (error) {\n console.error('Setup error:', error)\n // Cleanup on error\n if (stripeSync) {\n try {\n await stripeSync.postgresClient.query('SELECT pg_advisory_unlock_all()')\n await stripeSync.postgresClient.pool.end()\n } catch (cleanupErr) {\n console.warn('Cleanup failed:', cleanupErr)\n }\n }\n return new Response(JSON.stringify({ success: false, error: error.message }), {\n status: 500,\n headers: { 'Content-Type': 'application/json' },\n })\n }\n})\n";
10
-
11
- // raw-ts:/home/runner/work/sync-engine/sync-engine/packages/sync-engine/src/supabase/edge-functions/stripe-webhook.ts
12
- var stripe_webhook_default = "import { StripeSync } from 'npm:stripe-experiment-sync'\n\nDeno.serve(async (req) => {\n if (req.method !== 'POST') {\n return new Response('Method not allowed', { status: 405 })\n }\n\n const sig = req.headers.get('stripe-signature')\n if (!sig) {\n return new Response('Missing stripe-signature header', { status: 400 })\n }\n\n const rawDbUrl = Deno.env.get('SUPABASE_DB_URL')\n if (!rawDbUrl) {\n return new Response(JSON.stringify({ error: 'SUPABASE_DB_URL not set' }), { status: 500 })\n }\n const dbUrl = rawDbUrl.replace(/[?&]sslmode=[^&]*/g, '').replace(/[?&]$/, '')\n\n const stripeSync = new StripeSync({\n poolConfig: { connectionString: dbUrl, max: 1 },\n stripeSecretKey: Deno.env.get('STRIPE_SECRET_KEY')!,\n })\n\n try {\n const rawBody = new Uint8Array(await req.arrayBuffer())\n await stripeSync.processWebhook(rawBody, sig)\n return new Response(JSON.stringify({ received: true }), {\n status: 200,\n headers: { 'Content-Type': 'application/json' },\n })\n } catch (error) {\n console.error('Webhook processing error:', error)\n const isSignatureError =\n error.message?.includes('signature') || error.type === 'StripeSignatureVerificationError'\n const status = isSignatureError ? 400 : 500\n return new Response(JSON.stringify({ error: error.message }), {\n status,\n headers: { 'Content-Type': 'application/json' },\n })\n } finally {\n await stripeSync.postgresClient.pool.end()\n }\n})\n";
13
-
14
- // raw-ts:/home/runner/work/sync-engine/sync-engine/packages/sync-engine/src/supabase/edge-functions/stripe-worker.ts
15
- var stripe_worker_default = "/**\n * Stripe Sync Worker\n *\n * Triggered by pg_cron at a configurable interval (default: 60 seconds). Uses pgmq for durable work queue.\n *\n * Flow:\n * 1. Read batch of messages from pgmq (qty=10, vt=60s)\n * 2. If queue empty: enqueue all objects (continuous sync)\n * 3. Process messages in parallel (Promise.all):\n * - processNext(object)\n * - Delete message on success\n * - Re-enqueue if hasMore\n * 4. Return results summary\n *\n * Concurrency:\n * - Multiple workers can run concurrently via overlapping pg_cron triggers.\n * - Each worker processes its batch of messages in parallel (Promise.all).\n * - pgmq visibility timeout prevents duplicate message reads across workers.\n * - processNext() is idempotent (uses internal cursor tracking), so duplicate\n * processing on timeout/crash is safe.\n */\n\nimport { StripeSync } from 'npm:stripe-experiment-sync'\nimport postgres from 'npm:postgres'\n\nconst QUEUE_NAME = 'stripe_sync_work'\nconst VISIBILITY_TIMEOUT = 60 // seconds\nconst BATCH_SIZE = 10\n\nDeno.serve(async (req) => {\n const authHeader = req.headers.get('Authorization')\n if (!authHeader?.startsWith('Bearer ')) {\n return new Response('Unauthorized', { status: 401 })\n }\n\n const rawDbUrl = Deno.env.get('SUPABASE_DB_URL')\n if (!rawDbUrl) {\n return new Response(JSON.stringify({ error: 'SUPABASE_DB_URL not set' }), { status: 500 })\n }\n const dbUrl = rawDbUrl.replace(/[?&]sslmode=[^&]*/g, '').replace(/[?&]$/, '')\n\n let sql\n let stripeSync\n\n try {\n sql = postgres(dbUrl, { max: 1, prepare: false })\n } catch (error) {\n return new Response(\n JSON.stringify({\n error: 'Failed to create postgres connection',\n details: error.message,\n stack: error.stack,\n }),\n { status: 500, headers: { 'Content-Type': 'application/json' } }\n )\n }\n\n try {\n stripeSync = new StripeSync({\n poolConfig: { connectionString: dbUrl, max: 1 },\n stripeSecretKey: Deno.env.get('STRIPE_SECRET_KEY')!,\n })\n } catch (error) {\n await sql.end()\n return new Response(\n JSON.stringify({\n error: 'Failed to create StripeSync',\n details: error.message,\n stack: error.stack,\n }),\n { status: 500, headers: { 'Content-Type': 'application/json' } }\n )\n }\n\n try {\n // Read batch of messages from queue\n const messages = await sql`\n SELECT * FROM pgmq.read(${QUEUE_NAME}::text, ${VISIBILITY_TIMEOUT}::int, ${BATCH_SIZE}::int)\n `\n\n // If queue empty, enqueue all objects for continuous sync\n if (messages.length === 0) {\n // Create sync run to make enqueued work visible (status='pending')\n const { objects } = await stripeSync.joinOrCreateSyncRun('worker')\n const msgs = objects.map((object) => JSON.stringify({ object }))\n\n await sql`\n SELECT pgmq.send_batch(\n ${QUEUE_NAME}::text,\n ${sql.array(msgs)}::jsonb[]\n )\n `\n\n return new Response(JSON.stringify({ enqueued: objects.length, objects }), {\n status: 200,\n headers: { 'Content-Type': 'application/json' },\n })\n }\n\n // Process messages in parallel\n const results = await Promise.all(\n messages.map(async (msg) => {\n const { object } = msg.message as { object: string }\n\n try {\n const result = await stripeSync.processNext(object)\n\n // Delete message on success (cast to bigint to disambiguate overloaded function)\n await sql`SELECT pgmq.delete(${QUEUE_NAME}::text, ${msg.msg_id}::bigint)`\n\n // Re-enqueue if more pages\n if (result.hasMore) {\n await sql`SELECT pgmq.send(${QUEUE_NAME}::text, ${sql.json({ object })}::jsonb)`\n }\n\n return { object, ...result }\n } catch (error) {\n // Log error but continue to next message\n // Message will become visible again after visibility timeout\n console.error(`Error processing ${object}:`, error)\n return {\n object,\n processed: 0,\n hasMore: false,\n error: error.message,\n stack: error.stack,\n }\n }\n })\n )\n\n return new Response(JSON.stringify({ results }), {\n status: 200,\n headers: { 'Content-Type': 'application/json' },\n })\n } catch (error) {\n console.error('Worker error:', error)\n return new Response(JSON.stringify({ error: error.message, stack: error.stack }), {\n status: 500,\n headers: { 'Content-Type': 'application/json' },\n })\n } finally {\n if (sql) await sql.end()\n if (stripeSync) await stripeSync.postgresClient.pool.end()\n }\n})\n";
16
-
17
- // src/supabase/edge-function-code.ts
18
- var setupFunctionCode = stripe_setup_default;
19
- var webhookFunctionCode = stripe_webhook_default;
20
- var workerFunctionCode = stripe_worker_default;
21
-
22
- // src/supabase/supabase.ts
23
- import Stripe from "stripe";
24
- var STRIPE_SCHEMA_COMMENT_PREFIX = "stripe-sync";
25
- var INSTALLATION_STARTED_SUFFIX = "installation:started";
26
- var INSTALLATION_ERROR_SUFFIX = "installation:error";
27
- var INSTALLATION_INSTALLED_SUFFIX = "installed";
28
- var SupabaseSetupClient = class {
29
- api;
30
- projectRef;
31
- projectBaseUrl;
32
- constructor(options) {
33
- this.api = new SupabaseManagementAPI({
34
- accessToken: options.accessToken,
35
- baseUrl: options.managementApiBaseUrl
36
- });
37
- this.projectRef = options.projectRef;
38
- this.projectBaseUrl = options.projectBaseUrl || process.env.SUPABASE_BASE_URL || "supabase.co";
39
- }
40
- /**
41
- * Validate that the project exists and we have access
42
- */
43
- async validateProject() {
44
- const projects = await this.api.getProjects();
45
- const project = projects?.find((p) => p.id === this.projectRef);
46
- if (!project) {
47
- throw new Error(`Project ${this.projectRef} not found or you don't have access`);
48
- }
49
- return {
50
- id: project.id,
51
- name: project.name,
52
- region: project.region
53
- };
54
- }
55
- /**
56
- * Deploy an Edge Function
57
- */
58
- async deployFunction(name, code) {
59
- const functions = await this.api.listFunctions(this.projectRef);
60
- const exists = functions?.some((f) => f.slug === name);
61
- if (exists) {
62
- await this.api.updateFunction(this.projectRef, name, {
63
- body: code,
64
- verify_jwt: false
65
- });
66
- } else {
67
- await this.api.createFunction(this.projectRef, {
68
- slug: name,
69
- name,
70
- body: code,
71
- verify_jwt: false
72
- });
73
- }
74
- }
75
- /**
76
- * Set secrets for Edge Functions
77
- */
78
- async setSecrets(secrets) {
79
- await this.api.createSecrets(this.projectRef, secrets);
80
- }
81
- /**
82
- * Run SQL against the database
83
- */
84
- async runSQL(sql) {
85
- return await this.api.runQuery(this.projectRef, sql);
86
- }
87
- /**
88
- * Setup pg_cron job to invoke worker function
89
- * @param intervalSeconds - How often to run the worker (default: 60 seconds)
90
- */
91
- async setupPgCronJob(intervalSeconds = 60) {
92
- if (!Number.isInteger(intervalSeconds) || intervalSeconds < 1) {
93
- throw new Error(`Invalid interval: ${intervalSeconds}. Must be a positive integer.`);
94
- }
95
- let schedule;
96
- if (intervalSeconds < 60) {
97
- schedule = `${intervalSeconds} seconds`;
98
- } else if (intervalSeconds % 60 === 0) {
99
- const minutes = intervalSeconds / 60;
100
- if (minutes < 60) {
101
- schedule = `*/${minutes} * * * *`;
102
- } else {
103
- throw new Error(
104
- `Invalid interval: ${intervalSeconds}. Intervals >= 3600 seconds (1 hour) are not supported. Use a value between 1-3599 seconds.`
105
- );
106
- }
107
- } else {
108
- throw new Error(
109
- `Invalid interval: ${intervalSeconds}. Must be either 1-59 seconds or a multiple of 60 (e.g., 60, 120, 180).`
110
- );
111
- }
112
- const serviceRoleKey = await this.getServiceRoleKey();
113
- const escapedServiceRoleKey = serviceRoleKey.replace(/'/g, "''");
114
- const sql = `
115
- -- Enable extensions
116
- CREATE EXTENSION IF NOT EXISTS pg_cron;
117
- CREATE EXTENSION IF NOT EXISTS pg_net;
118
- CREATE EXTENSION IF NOT EXISTS pgmq;
119
-
120
- -- Create pgmq queue for sync work (idempotent)
121
- SELECT pgmq.create('stripe_sync_work')
122
- WHERE NOT EXISTS (
123
- SELECT 1 FROM pgmq.list_queues() WHERE queue_name = 'stripe_sync_work'
124
- );
125
-
126
- -- Store service role key in vault for pg_cron to use
127
- -- Delete existing secret if it exists, then create new one
128
- DELETE FROM vault.secrets WHERE name = 'stripe_sync_service_role_key';
129
- SELECT vault.create_secret('${escapedServiceRoleKey}', 'stripe_sync_service_role_key');
130
-
131
- -- Delete existing jobs if they exist
132
- SELECT cron.unschedule('stripe-sync-worker') WHERE EXISTS (
133
- SELECT 1 FROM cron.job WHERE jobname = 'stripe-sync-worker'
134
- );
135
- SELECT cron.unschedule('stripe-sync-scheduler') WHERE EXISTS (
136
- SELECT 1 FROM cron.job WHERE jobname = 'stripe-sync-scheduler'
137
- );
138
-
139
- -- Create job to invoke worker at configured interval
140
- -- Worker reads from pgmq, enqueues objects if empty, and processes sync work
141
- SELECT cron.schedule(
142
- 'stripe-sync-worker',
143
- '${schedule}',
144
- $$
145
- SELECT net.http_post(
146
- url := 'https://${this.projectRef}.${this.projectBaseUrl}/functions/v1/stripe-worker',
147
- headers := jsonb_build_object(
148
- 'Authorization', 'Bearer ' || (SELECT decrypted_secret FROM vault.decrypted_secrets WHERE name = 'stripe_sync_service_role_key')
149
- )
150
- )
151
- $$
152
- );
153
- `;
154
- await this.runSQL(sql);
155
- }
156
- /**
157
- * Get the webhook URL for this project
158
- */
159
- getWebhookUrl() {
160
- return `https://${this.projectRef}.${this.projectBaseUrl}/functions/v1/stripe-webhook`;
161
- }
162
- /**
163
- * Get the service role key for this project (needed to invoke Edge Functions)
164
- */
165
- async getServiceRoleKey() {
166
- const apiKeys = await this.api.getProjectApiKeys(this.projectRef);
167
- const serviceRoleKey = apiKeys?.find((k) => k.name === "service_role");
168
- if (!serviceRoleKey) {
169
- throw new Error("Could not find service_role API key");
170
- }
171
- return serviceRoleKey.api_key;
172
- }
173
- /**
174
- * Get the anon key for this project (needed for Realtime subscriptions)
175
- */
176
- async getAnonKey() {
177
- const apiKeys = await this.api.getProjectApiKeys(this.projectRef);
178
- const anonKey = apiKeys?.find((k) => k.name === "anon");
179
- if (!anonKey) {
180
- throw new Error("Could not find anon API key");
181
- }
182
- return anonKey.api_key;
183
- }
184
- /**
185
- * Get the project URL
186
- */
187
- getProjectUrl() {
188
- return `https://${this.projectRef}.${this.projectBaseUrl}`;
189
- }
190
- /**
191
- * Invoke an Edge Function
192
- */
193
- async invokeFunction(name, serviceRoleKey) {
194
- const url = `https://${this.projectRef}.${this.projectBaseUrl}/functions/v1/${name}`;
195
- const response = await fetch(url, {
196
- method: "POST",
197
- headers: {
198
- Authorization: `Bearer ${serviceRoleKey}`,
199
- "Content-Type": "application/json"
200
- }
201
- });
202
- if (!response.ok) {
203
- const text = await response.text();
204
- return { success: false, error: `${response.status}: ${text}` };
205
- }
206
- const result = await response.json();
207
- if (result.success === false) {
208
- return { success: false, error: result.error };
209
- }
210
- return { success: true };
211
- }
212
- /**
213
- * Check if stripe-sync is installed in the database.
214
- *
215
- * Uses the Supabase Management API to run SQL queries.
216
- * Uses duck typing (schema + migrations table) combined with comment validation.
217
- * Throws error for legacy installations to prevent accidental corruption.
218
- *
219
- * @param schema The schema name to check (defaults to 'stripe')
220
- * @returns true if properly installed with comment marker, false if not installed
221
- * @throws Error if legacy installation detected (schema exists without comment)
222
- */
223
- async isInstalled(schema = "stripe") {
224
- try {
225
- const schemaCheck = await this.runSQL(
226
- `SELECT EXISTS (
227
- SELECT 1 FROM information_schema.schemata
228
- WHERE schema_name = '${schema}'
229
- ) as schema_exists`
230
- );
231
- const schemaExists = schemaCheck[0]?.rows?.[0]?.schema_exists === true;
232
- if (!schemaExists) {
233
- return false;
234
- }
235
- const migrationsCheck = await this.runSQL(
236
- `SELECT EXISTS (
237
- SELECT 1 FROM information_schema.tables
238
- WHERE table_schema = '${schema}' AND table_name IN ('migrations', '_migrations')
239
- ) as table_exists`
240
- );
241
- const migrationsTableExists = migrationsCheck[0]?.rows?.[0]?.table_exists === true;
242
- if (!migrationsTableExists) {
243
- return false;
244
- }
245
- const commentCheck = await this.runSQL(
246
- `SELECT obj_description(oid, 'pg_namespace') as comment
247
- FROM pg_namespace
248
- WHERE nspname = '${schema}'`
249
- );
250
- const comment = commentCheck[0]?.rows?.[0]?.comment;
251
- if (!comment || !comment.includes(STRIPE_SCHEMA_COMMENT_PREFIX)) {
252
- throw new Error(
253
- `Legacy installation detected: Schema '${schema}' and migrations table exist, but missing stripe-sync comment marker. This may be a legacy installation or manually created schema. Please contact support or manually drop the schema before proceeding.`
254
- );
255
- }
256
- if (comment.includes(INSTALLATION_STARTED_SUFFIX)) {
257
- return false;
258
- }
259
- if (comment.includes(INSTALLATION_ERROR_SUFFIX)) {
260
- throw new Error(
261
- `Installation failed: Schema '${schema}' exists but installation encountered an error. Comment: ${comment}. Please uninstall and install again.`
262
- );
263
- }
264
- return true;
265
- } catch (error) {
266
- if (error instanceof Error && (error.message.includes("Legacy installation detected") || error.message.includes("Installation failed"))) {
267
- throw error;
268
- }
269
- return false;
270
- }
271
- }
272
- /**
273
- * Update installation progress comment on the stripe schema
274
- */
275
- async updateInstallationComment(message) {
276
- const escapedMessage = message.replace(/'/g, "''");
277
- await this.runSQL(`COMMENT ON SCHEMA stripe IS '${escapedMessage}'`);
278
- }
279
- /**
280
- * Delete an Edge Function
281
- */
282
- async deleteFunction(name) {
283
- try {
284
- await this.api.deleteFunction(this.projectRef, name);
285
- } catch (err) {
286
- console.warn(`Could not delete function ${name}:`, err);
287
- }
288
- }
289
- /**
290
- * Delete a secret
291
- */
292
- async deleteSecret(name) {
293
- try {
294
- await this.api.deleteSecrets(this.projectRef, [name]);
295
- } catch (err) {
296
- console.warn(`Could not delete secret ${name}:`, err);
297
- }
298
- }
299
- /**
300
- * Uninstall stripe-sync from a Supabase project
301
- * Removes all Edge Functions, secrets, database resources, and Stripe webhooks
302
- */
303
- async uninstall(stripeSecretKey) {
304
- const stripe = stripeSecretKey ? new Stripe(stripeSecretKey, { apiVersion: "2025-02-24.acacia" }) : null;
305
- try {
306
- try {
307
- const webhookResult = await this.runSQL(`
308
- SELECT id FROM stripe._managed_webhooks WHERE id IS NOT NULL
309
- `);
310
- const webhookIds = webhookResult[0]?.rows?.map((r) => r.id) || [];
311
- for (const webhookId of webhookIds) {
312
- try {
313
- await stripe?.webhookEndpoints.del(webhookId);
314
- } catch (err) {
315
- console.warn(`Could not delete Stripe webhook ${webhookId}:`, err);
316
- }
317
- }
318
- } catch (err) {
319
- console.warn("Could not query/delete webhooks:", err);
320
- }
321
- await this.deleteFunction("stripe-setup");
322
- await this.deleteFunction("stripe-webhook");
323
- await this.deleteFunction("stripe-worker");
324
- await this.deleteSecret("STRIPE_SECRET_KEY");
325
- try {
326
- await this.runSQL(`
327
- DO $$
328
- BEGIN
329
- IF EXISTS (SELECT 1 FROM cron.job WHERE jobname = 'stripe-sync-worker') THEN
330
- PERFORM cron.unschedule('stripe-sync-worker');
331
- END IF;
332
- END $$;
333
- `);
334
- } catch (err) {
335
- console.warn("Could not unschedule pg_cron job:", err);
336
- }
337
- try {
338
- await this.runSQL(`
339
- DELETE FROM vault.secrets
340
- WHERE name = 'stripe_sync_service_role_key'
341
- `);
342
- } catch (err) {
343
- console.warn("Could not delete vault secret:", err);
344
- }
345
- try {
346
- await this.runSQL(`
347
- SELECT pg_terminate_backend(pid)
348
- FROM pg_locks l
349
- JOIN pg_class c ON l.relation = c.oid
350
- JOIN pg_namespace n ON c.relnamespace = n.oid
351
- WHERE n.nspname = 'stripe'
352
- AND l.pid != pg_backend_pid()
353
- `);
354
- } catch (err) {
355
- console.warn("Could not terminate connections:", err);
356
- }
357
- let dropAttempts = 0;
358
- const maxAttempts = 3;
359
- while (dropAttempts < maxAttempts) {
360
- try {
361
- await this.runSQL(`DROP SCHEMA IF EXISTS stripe CASCADE`);
362
- break;
363
- } catch (err) {
364
- dropAttempts++;
365
- if (dropAttempts >= maxAttempts) {
366
- throw new Error(
367
- `Failed to drop schema after ${maxAttempts} attempts. There may be active connections or locks on the stripe schema. Error: ${err instanceof Error ? err.message : String(err)}`
368
- );
369
- }
370
- await new Promise((resolve) => setTimeout(resolve, 1e3));
371
- }
372
- }
373
- } catch (error) {
374
- throw new Error(`Uninstall failed: ${error instanceof Error ? error.message : String(error)}`);
375
- }
376
- }
377
- /**
378
- * Inject package version into Edge Function code
379
- */
380
- injectPackageVersion(code, version) {
381
- if (version === "latest") {
382
- return code;
383
- }
384
- return code.replace(
385
- /from ['"]npm:stripe-experiment-sync['"]/g,
386
- `from 'npm:stripe-experiment-sync@${version}'`
387
- );
388
- }
389
- async install(stripeKey, packageVersion, workerIntervalSeconds) {
390
- const trimmedStripeKey = stripeKey.trim();
391
- if (!trimmedStripeKey.startsWith("sk_") && !trimmedStripeKey.startsWith("rk_")) {
392
- throw new Error('Stripe key should start with "sk_" or "rk_"');
393
- }
394
- const version = packageVersion || "latest";
395
- try {
396
- await this.validateProject();
397
- await this.runSQL(`CREATE SCHEMA IF NOT EXISTS stripe`);
398
- await this.updateInstallationComment(
399
- `${STRIPE_SCHEMA_COMMENT_PREFIX} v${package_default.version} ${INSTALLATION_STARTED_SUFFIX}`
400
- );
401
- const versionedSetup = this.injectPackageVersion(setupFunctionCode, version);
402
- const versionedWebhook = this.injectPackageVersion(webhookFunctionCode, version);
403
- const versionedWorker = this.injectPackageVersion(workerFunctionCode, version);
404
- await this.deployFunction("stripe-setup", versionedSetup);
405
- await this.deployFunction("stripe-webhook", versionedWebhook);
406
- await this.deployFunction("stripe-worker", versionedWorker);
407
- await this.setSecrets([{ name: "STRIPE_SECRET_KEY", value: trimmedStripeKey }]);
408
- const serviceRoleKey = await this.getServiceRoleKey();
409
- const setupResult = await this.invokeFunction("stripe-setup", serviceRoleKey);
410
- if (!setupResult.success) {
411
- throw new Error(`Setup failed: ${setupResult.error}`);
412
- }
413
- await this.setupPgCronJob(workerIntervalSeconds);
414
- await this.updateInstallationComment(
415
- `${STRIPE_SCHEMA_COMMENT_PREFIX} v${package_default.version} ${INSTALLATION_INSTALLED_SUFFIX}`
416
- );
417
- } catch (error) {
418
- await this.updateInstallationComment(
419
- `${STRIPE_SCHEMA_COMMENT_PREFIX} v${package_default.version} ${INSTALLATION_ERROR_SUFFIX} - ${error instanceof Error ? error.message : String(error)}`
420
- );
421
- throw error;
422
- }
423
- }
424
- };
425
- async function install(params) {
426
- const {
427
- supabaseAccessToken,
428
- supabaseProjectRef,
429
- stripeKey,
430
- packageVersion,
431
- workerIntervalSeconds
432
- } = params;
433
- const client = new SupabaseSetupClient({
434
- accessToken: supabaseAccessToken,
435
- projectRef: supabaseProjectRef,
436
- projectBaseUrl: params.baseProjectUrl,
437
- managementApiBaseUrl: params.baseManagementApiUrl
438
- });
439
- await client.install(stripeKey, packageVersion, workerIntervalSeconds);
440
- }
441
- async function uninstall(params) {
442
- const { supabaseAccessToken, supabaseProjectRef, stripeKey } = params;
443
- const trimmedStripeKey = stripeKey && stripeKey.trim();
444
- if (trimmedStripeKey && !trimmedStripeKey.startsWith("sk_") && !trimmedStripeKey.startsWith("rk_")) {
445
- throw new Error('Stripe key should start with "sk_" or "rk_"');
446
- }
447
- const client = new SupabaseSetupClient({
448
- accessToken: supabaseAccessToken,
449
- projectRef: supabaseProjectRef,
450
- projectBaseUrl: params.baseProjectUrl,
451
- managementApiBaseUrl: params.baseManagementApiUrl
452
- });
453
- await client.uninstall(trimmedStripeKey);
454
- }
455
-
456
- export {
457
- setupFunctionCode,
458
- webhookFunctionCode,
459
- workerFunctionCode,
460
- STRIPE_SCHEMA_COMMENT_PREFIX,
461
- INSTALLATION_STARTED_SUFFIX,
462
- INSTALLATION_ERROR_SUFFIX,
463
- INSTALLATION_INSTALLED_SUFFIX,
464
- SupabaseSetupClient,
465
- install,
466
- uninstall
467
- };