stripe-experiment-sync 1.0.1 → 1.0.3

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.
@@ -0,0 +1,483 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/supabase/index.ts
31
+ var supabase_exports = {};
32
+ __export(supabase_exports, {
33
+ SupabaseDeployClient: () => SupabaseDeployClient,
34
+ install: () => install,
35
+ setupFunctionCode: () => setupFunctionCode,
36
+ uninstall: () => uninstall,
37
+ webhookFunctionCode: () => webhookFunctionCode,
38
+ workerFunctionCode: () => workerFunctionCode
39
+ });
40
+ module.exports = __toCommonJS(supabase_exports);
41
+
42
+ // src/supabase/supabase.ts
43
+ var import_supabase_management_js = require("supabase-management-js");
44
+
45
+ // raw-ts:/home/runner/work/stripe-sync-engine/stripe-sync-engine/packages/sync-engine/src/supabase/edge-functions/stripe-setup.ts
46
+ var stripe_setup_default = "import { StripeSync, runMigrations } 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 authHeader = req.headers.get('Authorization')\n if (!authHeader?.startsWith('Bearer ')) {\n return new Response('Unauthorized', { status: 401 })\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";
47
+
48
+ // raw-ts:/home/runner/work/stripe-sync-engine/stripe-sync-engine/packages/sync-engine/src/supabase/edge-functions/stripe-webhook.ts
49
+ 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";
50
+
51
+ // raw-ts:/home/runner/work/stripe-sync-engine/stripe-sync-engine/packages/sync-engine/src/supabase/edge-functions/stripe-worker.ts
52
+ var stripe_worker_default = "/**\n * Stripe Sync Worker\n *\n * Triggered by pg_cron every 10 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 const objects = stripeSync.getSupportedSyncObjects()\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";
53
+
54
+ // src/supabase/edge-function-code.ts
55
+ var setupFunctionCode = stripe_setup_default;
56
+ var webhookFunctionCode = stripe_webhook_default;
57
+ var workerFunctionCode = stripe_worker_default;
58
+
59
+ // package.json
60
+ var package_default = {
61
+ name: "stripe-experiment-sync",
62
+ version: "1.0.3",
63
+ private: false,
64
+ description: "Stripe Sync Engine to sync Stripe data to Postgres",
65
+ type: "module",
66
+ main: "./dist/index.cjs",
67
+ bin: "./dist/cli/index.cjs",
68
+ exports: {
69
+ ".": {
70
+ types: "./dist/index.d.ts",
71
+ import: "./dist/index.js",
72
+ require: "./dist/index.cjs"
73
+ },
74
+ "./supabase": {
75
+ types: "./dist/supabase/index.d.ts",
76
+ import: "./dist/supabase/index.js",
77
+ require: "./dist/supabase/index.cjs"
78
+ }
79
+ },
80
+ scripts: {
81
+ clean: "rimraf dist",
82
+ prebuild: "npm run clean",
83
+ build: "tsup src/index.ts src/supabase/index.ts --format esm,cjs --dts --shims && cp -r src/database/migrations dist/migrations",
84
+ lint: "eslint src --ext .ts",
85
+ test: "vitest"
86
+ },
87
+ files: [
88
+ "dist"
89
+ ],
90
+ dependencies: {
91
+ pg: "^8.16.3",
92
+ "pg-node-migrations": "0.0.8",
93
+ "supabase-management-js": "^0.1.6",
94
+ ws: "^8.18.0",
95
+ yesql: "^7.0.0"
96
+ },
97
+ peerDependencies: {
98
+ stripe: "> 11"
99
+ },
100
+ devDependencies: {
101
+ "@types/node": "^24.10.1",
102
+ "@types/pg": "^8.15.5",
103
+ "@types/ws": "^8.5.13",
104
+ "@types/yesql": "^4.1.4",
105
+ "@vitest/ui": "^4.0.9",
106
+ vitest: "^3.2.4"
107
+ },
108
+ repository: {
109
+ type: "git",
110
+ url: "https://github.com/tx-stripe/stripe-sync-engine.git"
111
+ },
112
+ homepage: "https://github.com/tx-stripe/stripe-sync-engine#readme",
113
+ bugs: {
114
+ url: "https://github.com/tx-stripe/stripe-sync-engine/issues"
115
+ },
116
+ keywords: [
117
+ "stripe",
118
+ "postgres",
119
+ "sync",
120
+ "webhooks",
121
+ "supabase",
122
+ "billing",
123
+ "database",
124
+ "typescript"
125
+ ],
126
+ author: "Supabase <https://supabase.com/>"
127
+ };
128
+
129
+ // src/supabase/supabase.ts
130
+ var import_stripe = __toESM(require("stripe"), 1);
131
+ var SupabaseDeployClient = class {
132
+ api;
133
+ projectRef;
134
+ baseUrl;
135
+ constructor(options) {
136
+ this.api = new import_supabase_management_js.SupabaseManagementAPI({ accessToken: options.accessToken });
137
+ this.projectRef = options.projectRef;
138
+ this.baseUrl = options.baseUrl || process.env.SUPABASE_BASE_URL || "supabase.co";
139
+ }
140
+ /**
141
+ * Validate that the project exists and we have access
142
+ */
143
+ async validateProject() {
144
+ const projects = await this.api.getProjects();
145
+ const project = projects?.find((p) => p.id === this.projectRef);
146
+ if (!project) {
147
+ throw new Error(`Project ${this.projectRef} not found or you don't have access`);
148
+ }
149
+ return {
150
+ id: project.id,
151
+ name: project.name,
152
+ region: project.region
153
+ };
154
+ }
155
+ /**
156
+ * Deploy an Edge Function
157
+ */
158
+ async deployFunction(name, code) {
159
+ const functions = await this.api.listFunctions(this.projectRef);
160
+ const exists = functions?.some((f) => f.slug === name);
161
+ if (exists) {
162
+ await this.api.updateFunction(this.projectRef, name, {
163
+ body: code,
164
+ verify_jwt: false
165
+ });
166
+ } else {
167
+ await this.api.createFunction(this.projectRef, {
168
+ slug: name,
169
+ name,
170
+ body: code,
171
+ verify_jwt: false
172
+ });
173
+ }
174
+ }
175
+ /**
176
+ * Set secrets for Edge Functions
177
+ */
178
+ async setSecrets(secrets) {
179
+ await this.api.createSecrets(this.projectRef, secrets);
180
+ }
181
+ /**
182
+ * Run SQL against the database
183
+ */
184
+ async runSQL(sql) {
185
+ return await this.api.runQuery(this.projectRef, sql);
186
+ }
187
+ /**
188
+ * Setup pg_cron job to invoke worker function
189
+ */
190
+ async setupPgCronJob() {
191
+ const serviceRoleKey = await this.getServiceRoleKey();
192
+ const escapedServiceRoleKey = serviceRoleKey.replace(/'/g, "''");
193
+ const sql = `
194
+ -- Enable extensions
195
+ CREATE EXTENSION IF NOT EXISTS pg_cron;
196
+ CREATE EXTENSION IF NOT EXISTS pg_net;
197
+ CREATE EXTENSION IF NOT EXISTS pgmq;
198
+
199
+ -- Create pgmq queue for sync work (idempotent)
200
+ SELECT pgmq.create('stripe_sync_work')
201
+ WHERE NOT EXISTS (
202
+ SELECT 1 FROM pgmq.list_queues() WHERE queue_name = 'stripe_sync_work'
203
+ );
204
+
205
+ -- Store service role key in vault for pg_cron to use
206
+ -- Delete existing secret if it exists, then create new one
207
+ DELETE FROM vault.secrets WHERE name = 'stripe_sync_service_role_key';
208
+ SELECT vault.create_secret('${escapedServiceRoleKey}', 'stripe_sync_service_role_key');
209
+
210
+ -- Delete existing jobs if they exist
211
+ SELECT cron.unschedule('stripe-sync-worker') WHERE EXISTS (
212
+ SELECT 1 FROM cron.job WHERE jobname = 'stripe-sync-worker'
213
+ );
214
+ SELECT cron.unschedule('stripe-sync-scheduler') WHERE EXISTS (
215
+ SELECT 1 FROM cron.job WHERE jobname = 'stripe-sync-scheduler'
216
+ );
217
+
218
+ -- Create job to invoke worker every 10 seconds
219
+ -- Worker reads from pgmq, enqueues objects if empty, and processes sync work
220
+ SELECT cron.schedule(
221
+ 'stripe-sync-worker',
222
+ '10 seconds',
223
+ $$
224
+ SELECT net.http_post(
225
+ url := 'https://${this.projectRef}.${this.baseUrl}/functions/v1/stripe-worker',
226
+ headers := jsonb_build_object(
227
+ 'Authorization', 'Bearer ' || (SELECT decrypted_secret FROM vault.decrypted_secrets WHERE name = 'stripe_sync_service_role_key')
228
+ )
229
+ )
230
+ $$
231
+ );
232
+ `;
233
+ await this.runSQL(sql);
234
+ }
235
+ /**
236
+ * Get the webhook URL for this project
237
+ */
238
+ getWebhookUrl() {
239
+ return `https://${this.projectRef}.${this.baseUrl}/functions/v1/stripe-webhook`;
240
+ }
241
+ /**
242
+ * Get the service role key for this project (needed to invoke Edge Functions)
243
+ */
244
+ async getServiceRoleKey() {
245
+ const apiKeys = await this.api.getProjectApiKeys(this.projectRef);
246
+ const serviceRoleKey = apiKeys?.find((k) => k.name === "service_role");
247
+ if (!serviceRoleKey) {
248
+ throw new Error("Could not find service_role API key");
249
+ }
250
+ return serviceRoleKey.api_key;
251
+ }
252
+ /**
253
+ * Get the anon key for this project (needed for Realtime subscriptions)
254
+ */
255
+ async getAnonKey() {
256
+ const apiKeys = await this.api.getProjectApiKeys(this.projectRef);
257
+ const anonKey = apiKeys?.find((k) => k.name === "anon");
258
+ if (!anonKey) {
259
+ throw new Error("Could not find anon API key");
260
+ }
261
+ return anonKey.api_key;
262
+ }
263
+ /**
264
+ * Get the project URL
265
+ */
266
+ getProjectUrl() {
267
+ return `https://${this.projectRef}.${this.baseUrl}`;
268
+ }
269
+ /**
270
+ * Invoke an Edge Function
271
+ */
272
+ async invokeFunction(name, serviceRoleKey) {
273
+ const url = `https://${this.projectRef}.${this.baseUrl}/functions/v1/${name}`;
274
+ const response = await fetch(url, {
275
+ method: "POST",
276
+ headers: {
277
+ Authorization: `Bearer ${serviceRoleKey}`,
278
+ "Content-Type": "application/json"
279
+ }
280
+ });
281
+ if (!response.ok) {
282
+ const text = await response.text();
283
+ return { success: false, error: `${response.status}: ${text}` };
284
+ }
285
+ const result = await response.json();
286
+ if (result.success === false) {
287
+ return { success: false, error: result.error };
288
+ }
289
+ return { success: true };
290
+ }
291
+ /**
292
+ * Check if stripe-sync is installed in the database.
293
+ *
294
+ * Uses the Supabase Management API to run SQL queries.
295
+ * Uses duck typing (schema + migrations table) combined with comment validation.
296
+ * Throws error for legacy installations to prevent accidental corruption.
297
+ *
298
+ * @param schema The schema name to check (defaults to 'stripe')
299
+ * @returns true if properly installed with comment marker, false if not installed
300
+ * @throws Error if legacy installation detected (schema exists without comment)
301
+ */
302
+ async isInstalled(schema = "stripe") {
303
+ try {
304
+ const schemaCheck = await this.runSQL(
305
+ `SELECT EXISTS (
306
+ SELECT 1 FROM information_schema.schemata
307
+ WHERE schema_name = '${schema}'
308
+ ) as schema_exists`
309
+ );
310
+ const schemaExists = schemaCheck[0]?.rows?.[0]?.schema_exists === true;
311
+ if (!schemaExists) {
312
+ return false;
313
+ }
314
+ const migrationsCheck = await this.runSQL(
315
+ `SELECT EXISTS (
316
+ SELECT 1 FROM information_schema.tables
317
+ WHERE table_schema = '${schema}' AND table_name IN ('migrations', '_migrations')
318
+ ) as table_exists`
319
+ );
320
+ const migrationsTableExists = migrationsCheck[0]?.rows?.[0]?.table_exists === true;
321
+ if (!migrationsTableExists) {
322
+ return false;
323
+ }
324
+ const commentCheck = await this.runSQL(
325
+ `SELECT obj_description(oid, 'pg_namespace') as comment
326
+ FROM pg_namespace
327
+ WHERE nspname = '${schema}'`
328
+ );
329
+ const comment = commentCheck[0]?.rows?.[0]?.comment;
330
+ if (!comment || !comment.includes("stripe-sync")) {
331
+ throw new Error(
332
+ `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.`
333
+ );
334
+ }
335
+ if (comment.includes("installation:started")) {
336
+ return false;
337
+ }
338
+ if (comment.includes("installation:error")) {
339
+ throw new Error(
340
+ `Installation failed: Schema '${schema}' exists but installation encountered an error. Comment: ${comment}. Please uninstall and install again.`
341
+ );
342
+ }
343
+ return true;
344
+ } catch (error) {
345
+ if (error instanceof Error && (error.message.includes("Legacy installation detected") || error.message.includes("Installation failed"))) {
346
+ throw error;
347
+ }
348
+ return false;
349
+ }
350
+ }
351
+ /**
352
+ * Update installation progress comment on the stripe schema
353
+ */
354
+ async updateInstallationComment(message) {
355
+ const escapedMessage = message.replace(/'/g, "''");
356
+ await this.runSQL(`COMMENT ON SCHEMA stripe IS '${escapedMessage}'`);
357
+ }
358
+ /**
359
+ * Delete an Edge Function
360
+ */
361
+ async deleteFunction(name) {
362
+ try {
363
+ await this.api.deleteFunction(this.projectRef, name);
364
+ } catch (err) {
365
+ console.warn(`Could not delete function ${name}:`, err);
366
+ }
367
+ }
368
+ /**
369
+ * Delete a secret
370
+ */
371
+ async deleteSecret(name) {
372
+ try {
373
+ await this.api.deleteSecrets(this.projectRef, [name]);
374
+ } catch (err) {
375
+ console.warn(`Could not delete secret ${name}:`, err);
376
+ }
377
+ }
378
+ /**
379
+ * Uninstall stripe-sync from a Supabase project
380
+ * Removes all Edge Functions, secrets, database resources, and Stripe webhooks
381
+ */
382
+ async uninstall(stripeSecretKey) {
383
+ const stripe = new import_stripe.default(stripeSecretKey, { apiVersion: "2025-05-28.basil" });
384
+ try {
385
+ try {
386
+ const webhookResult = await this.runSQL(`
387
+ SELECT id FROM stripe._managed_webhooks WHERE id IS NOT NULL
388
+ `);
389
+ const webhookIds = webhookResult[0]?.rows?.map((r) => r.id) || [];
390
+ for (const webhookId of webhookIds) {
391
+ try {
392
+ await stripe.webhookEndpoints.del(webhookId);
393
+ } catch (err) {
394
+ console.warn(`Could not delete Stripe webhook ${webhookId}:`, err);
395
+ }
396
+ }
397
+ } catch (err) {
398
+ console.warn("Could not query/delete webhooks:", err);
399
+ }
400
+ await this.deleteFunction("stripe-setup");
401
+ await this.deleteFunction("stripe-webhook");
402
+ await this.deleteFunction("stripe-worker");
403
+ await this.deleteSecret("STRIPE_SECRET_KEY");
404
+ try {
405
+ await this.runSQL(`
406
+ SELECT cron.unschedule('stripe-sync-worker')
407
+ WHERE EXISTS (
408
+ SELECT 1 FROM cron.job WHERE jobname = 'stripe-sync-worker'
409
+ )
410
+ `);
411
+ } catch (err) {
412
+ console.warn("Could not unschedule pg_cron job:", err);
413
+ }
414
+ try {
415
+ await this.runSQL(`
416
+ DELETE FROM vault.secrets
417
+ WHERE name = 'stripe_sync_service_role_key'
418
+ `);
419
+ } catch (err) {
420
+ console.warn("Could not delete vault secret:", err);
421
+ }
422
+ await this.runSQL(`DROP SCHEMA IF EXISTS stripe CASCADE`);
423
+ } catch (error) {
424
+ throw new Error(`Uninstall failed: ${error instanceof Error ? error.message : String(error)}`);
425
+ }
426
+ }
427
+ };
428
+ async function install(params) {
429
+ const { supabaseAccessToken, supabaseProjectRef, stripeKey } = params;
430
+ const trimmedStripeKey = stripeKey.trim();
431
+ if (!trimmedStripeKey.startsWith("sk_") && !trimmedStripeKey.startsWith("rk_")) {
432
+ throw new Error('Stripe key should start with "sk_" or "rk_"');
433
+ }
434
+ const client = new SupabaseDeployClient({
435
+ accessToken: supabaseAccessToken,
436
+ projectRef: supabaseProjectRef
437
+ });
438
+ try {
439
+ await client.validateProject();
440
+ await client.runSQL(`CREATE SCHEMA IF NOT EXISTS stripe`);
441
+ await client.updateInstallationComment(`stripe-sync v${package_default.version} installation:started`);
442
+ await client.deployFunction("stripe-setup", setupFunctionCode);
443
+ await client.deployFunction("stripe-webhook", webhookFunctionCode);
444
+ await client.deployFunction("stripe-worker", workerFunctionCode);
445
+ await client.setSecrets([{ name: "STRIPE_SECRET_KEY", value: trimmedStripeKey }]);
446
+ const serviceRoleKey = await client.getServiceRoleKey();
447
+ const setupResult = await client.invokeFunction("stripe-setup", serviceRoleKey);
448
+ if (!setupResult.success) {
449
+ throw new Error(`Setup failed: ${setupResult.error}`);
450
+ }
451
+ try {
452
+ await client.setupPgCronJob();
453
+ } catch {
454
+ }
455
+ await client.updateInstallationComment(`stripe-sync v${package_default.version} installed`);
456
+ } catch (error) {
457
+ await client.updateInstallationComment(
458
+ `stripe-sync v${package_default.version} installation:error - ${error instanceof Error ? error.message : String(error)}`
459
+ );
460
+ throw error;
461
+ }
462
+ }
463
+ async function uninstall(params) {
464
+ const { supabaseAccessToken, supabaseProjectRef, stripeKey } = params;
465
+ const trimmedStripeKey = stripeKey.trim();
466
+ if (!trimmedStripeKey.startsWith("sk_") && !trimmedStripeKey.startsWith("rk_")) {
467
+ throw new Error('Stripe key should start with "sk_" or "rk_"');
468
+ }
469
+ const client = new SupabaseDeployClient({
470
+ accessToken: supabaseAccessToken,
471
+ projectRef: supabaseProjectRef
472
+ });
473
+ await client.uninstall(trimmedStripeKey);
474
+ }
475
+ // Annotate the CommonJS export names for ESM import in node:
476
+ 0 && (module.exports = {
477
+ SupabaseDeployClient,
478
+ install,
479
+ setupFunctionCode,
480
+ uninstall,
481
+ webhookFunctionCode,
482
+ workerFunctionCode
483
+ });
@@ -0,0 +1,107 @@
1
+ interface DeployClientOptions {
2
+ accessToken: string;
3
+ projectRef: string;
4
+ baseUrl?: string;
5
+ }
6
+ interface ProjectInfo {
7
+ id: string;
8
+ name: string;
9
+ region: string;
10
+ }
11
+ declare class SupabaseDeployClient {
12
+ private api;
13
+ private projectRef;
14
+ private baseUrl;
15
+ constructor(options: DeployClientOptions);
16
+ /**
17
+ * Validate that the project exists and we have access
18
+ */
19
+ validateProject(): Promise<ProjectInfo>;
20
+ /**
21
+ * Deploy an Edge Function
22
+ */
23
+ deployFunction(name: string, code: string): Promise<void>;
24
+ /**
25
+ * Set secrets for Edge Functions
26
+ */
27
+ setSecrets(secrets: {
28
+ name: string;
29
+ value: string;
30
+ }[]): Promise<void>;
31
+ /**
32
+ * Run SQL against the database
33
+ */
34
+ runSQL(sql: string): Promise<unknown>;
35
+ /**
36
+ * Setup pg_cron job to invoke worker function
37
+ */
38
+ setupPgCronJob(): Promise<void>;
39
+ /**
40
+ * Get the webhook URL for this project
41
+ */
42
+ getWebhookUrl(): string;
43
+ /**
44
+ * Get the service role key for this project (needed to invoke Edge Functions)
45
+ */
46
+ getServiceRoleKey(): Promise<string>;
47
+ /**
48
+ * Get the anon key for this project (needed for Realtime subscriptions)
49
+ */
50
+ getAnonKey(): Promise<string>;
51
+ /**
52
+ * Get the project URL
53
+ */
54
+ getProjectUrl(): string;
55
+ /**
56
+ * Invoke an Edge Function
57
+ */
58
+ invokeFunction(name: string, serviceRoleKey: string): Promise<{
59
+ success: boolean;
60
+ error?: string;
61
+ }>;
62
+ /**
63
+ * Check if stripe-sync is installed in the database.
64
+ *
65
+ * Uses the Supabase Management API to run SQL queries.
66
+ * Uses duck typing (schema + migrations table) combined with comment validation.
67
+ * Throws error for legacy installations to prevent accidental corruption.
68
+ *
69
+ * @param schema The schema name to check (defaults to 'stripe')
70
+ * @returns true if properly installed with comment marker, false if not installed
71
+ * @throws Error if legacy installation detected (schema exists without comment)
72
+ */
73
+ isInstalled(schema?: string): Promise<boolean>;
74
+ /**
75
+ * Update installation progress comment on the stripe schema
76
+ */
77
+ updateInstallationComment(message: string): Promise<void>;
78
+ /**
79
+ * Delete an Edge Function
80
+ */
81
+ deleteFunction(name: string): Promise<void>;
82
+ /**
83
+ * Delete a secret
84
+ */
85
+ deleteSecret(name: string): Promise<void>;
86
+ /**
87
+ * Uninstall stripe-sync from a Supabase project
88
+ * Removes all Edge Functions, secrets, database resources, and Stripe webhooks
89
+ */
90
+ uninstall(stripeSecretKey: string): Promise<void>;
91
+ }
92
+ declare function install(params: {
93
+ supabaseAccessToken: string;
94
+ supabaseProjectRef: string;
95
+ stripeKey: string;
96
+ }): Promise<void>;
97
+ declare function uninstall(params: {
98
+ supabaseAccessToken: string;
99
+ supabaseProjectRef: string;
100
+ stripeKey: string;
101
+ }): Promise<void>;
102
+
103
+ declare const setupFunctionCode: string;
104
+ declare const webhookFunctionCode: string;
105
+ declare const workerFunctionCode: string;
106
+
107
+ export { type DeployClientOptions, type ProjectInfo, SupabaseDeployClient, install, setupFunctionCode, uninstall, webhookFunctionCode, workerFunctionCode };