@paymentsdb/sync-engine 0.0.5 → 0.0.7

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,7 +1,7 @@
1
1
  // package.json
2
2
  var package_default = {
3
3
  name: "@paymentsdb/sync-engine",
4
- version: "0.0.4",
4
+ version: "0.0.7",
5
5
  private: false,
6
6
  description: "Stripe Sync Engine to sync Stripe data to Postgres",
7
7
  type: "module",
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  package_default
3
- } from "./chunk-HXSDJSKR.js";
3
+ } from "./chunk-7DYBM7H3.js";
4
4
 
5
5
  // src/stripeSync.ts
6
6
  import Stripe3 from "stripe";
@@ -45310,6 +45310,13 @@ var StripeSync = class {
45310
45310
  listFn: (p) => this.stripe.checkout.sessions.list(p),
45311
45311
  upsertFn: (items, id) => this.upsertCheckoutSessions(items, id),
45312
45312
  supportsCreatedFilter: true
45313
+ },
45314
+ _event_catchup: {
45315
+ order: 99,
45316
+ // Always runs last — catches missed webhook events
45317
+ listFn: (_p) => Promise.resolve({ data: [], has_more: false }),
45318
+ upsertFn: async () => [],
45319
+ supportsCreatedFilter: true
45313
45320
  }
45314
45321
  };
45315
45322
  const maxOrder = Math.max(...Object.values(core).map((cfg) => cfg.order));
@@ -46076,7 +46083,8 @@ ${message}`;
46076
46083
  credit_note: "credit_notes",
46077
46084
  early_fraud_warning: "early_fraud_warnings",
46078
46085
  refund: "refunds",
46079
- checkout_sessions: "checkout_sessions"
46086
+ checkout_sessions: "checkout_sessions",
46087
+ _event_catchup: "_event_catchup"
46080
46088
  };
46081
46089
  return mapping[object] || object;
46082
46090
  }
@@ -46087,11 +46095,16 @@ ${message}`;
46087
46095
  */
46088
46096
  async fetchOnePage(object, accountId, resourceName, runStartedAt, cursor, pageCursor, params) {
46089
46097
  const limit = 100;
46090
- if (object === "payment_method" || object === "tax_id") {
46091
- this.config.logger?.warn(`processNext for ${object} requires customer context`);
46098
+ if (object === "payment_method") {
46099
+ return this.fetchOnePagePaymentMethods(accountId, resourceName, runStartedAt, cursor, pageCursor, params);
46100
+ }
46101
+ if (object === "tax_id") {
46092
46102
  await this.postgresClient.completeObjectSync(accountId, runStartedAt, resourceName);
46093
46103
  return { processed: 0, hasMore: false, runStartedAt };
46094
46104
  }
46105
+ if (object === "_event_catchup") {
46106
+ return this.fetchOnePageEventCatchup(accountId, resourceName, runStartedAt, cursor, pageCursor);
46107
+ }
46095
46108
  const config = this.resourceRegistry[object];
46096
46109
  if (!config) {
46097
46110
  throw new Error(`Unsupported object type for processNext: ${object}`);
@@ -46268,6 +46281,437 @@ ${message}`;
46268
46281
  }
46269
46282
  return { processed: entries.length, hasMore, runStartedAt };
46270
46283
  }
46284
+ /**
46285
+ * Fetch payment methods by iterating customers in batches.
46286
+ *
46287
+ * Most customers have 1-2 PMs, so processing one customer per processNext call
46288
+ * would be extremely wasteful (10,000 customers = 10,000 worker round-trips).
46289
+ * Instead, each call fetches a batch of customers (sized by maxConcurrentCustomers,
46290
+ * default 10) and lists+upserts PMs for all of them concurrently.
46291
+ *
46292
+ * Cursor semantics:
46293
+ * - cursor: max customer `created` timestamp — filters to only new customers on subsequent runs
46294
+ * - pageCursor: last processed customer ID — tracks position in customer iteration
46295
+ */
46296
+ async fetchOnePagePaymentMethods(accountId, resourceName, runStartedAt, cursor, pageCursor, params) {
46297
+ const batchSize = this.config.maxConcurrentCustomers ?? 10;
46298
+ try {
46299
+ const customerBatch = await this.findNextCustomerBatchForPmSync(
46300
+ accountId,
46301
+ pageCursor,
46302
+ cursor,
46303
+ batchSize
46304
+ );
46305
+ if (customerBatch.length === 0) {
46306
+ await this.postgresClient.completeObjectSync(accountId, runStartedAt, resourceName);
46307
+ return { processed: 0, hasMore: false, runStartedAt };
46308
+ }
46309
+ this.config.logger?.info(
46310
+ `processNext: fetching payment_methods for ${customerBatch.length} customers`
46311
+ );
46312
+ let totalProcessed = 0;
46313
+ await Promise.all(
46314
+ customerBatch.map(async (customer) => {
46315
+ const allPms = [];
46316
+ let hasMore = true;
46317
+ let startingAfter;
46318
+ while (hasMore) {
46319
+ const response = await this.stripe.paymentMethods.list({
46320
+ customer: customer.id,
46321
+ limit: 100,
46322
+ ...startingAfter ? { starting_after: startingAfter } : {}
46323
+ });
46324
+ allPms.push(...response.data);
46325
+ hasMore = response.has_more;
46326
+ if (response.data.length > 0) {
46327
+ startingAfter = response.data[response.data.length - 1].id;
46328
+ }
46329
+ }
46330
+ if (allPms.length > 0) {
46331
+ await this.upsertPaymentMethods(allPms, accountId, params?.backfillRelatedEntities);
46332
+ totalProcessed += allPms.length;
46333
+ }
46334
+ })
46335
+ );
46336
+ if (totalProcessed > 0) {
46337
+ await this.postgresClient.incrementObjectProgress(
46338
+ accountId,
46339
+ runStartedAt,
46340
+ resourceName,
46341
+ totalProcessed
46342
+ );
46343
+ }
46344
+ const maxCreated = Math.max(...customerBatch.map((c) => c.created).filter((c) => c != null));
46345
+ if (maxCreated > 0) {
46346
+ await this.postgresClient.updateObjectCursor(
46347
+ accountId,
46348
+ runStartedAt,
46349
+ resourceName,
46350
+ String(maxCreated)
46351
+ );
46352
+ }
46353
+ const lastCustomerId = customerBatch[customerBatch.length - 1].id;
46354
+ const nextBatch = await this.findNextCustomerBatchForPmSync(
46355
+ accountId,
46356
+ lastCustomerId,
46357
+ cursor,
46358
+ 1
46359
+ );
46360
+ if (nextBatch.length > 0) {
46361
+ await this.postgresClient.updateObjectPageCursor(
46362
+ accountId,
46363
+ runStartedAt,
46364
+ resourceName,
46365
+ lastCustomerId
46366
+ );
46367
+ return { processed: totalProcessed, hasMore: true, runStartedAt };
46368
+ }
46369
+ await this.postgresClient.completeObjectSync(accountId, runStartedAt, resourceName);
46370
+ return { processed: totalProcessed, hasMore: false, runStartedAt };
46371
+ } catch (error) {
46372
+ await this.postgresClient.failObjectSync(
46373
+ accountId,
46374
+ runStartedAt,
46375
+ resourceName,
46376
+ error instanceof Error ? error.message : "Unknown error"
46377
+ );
46378
+ throw error;
46379
+ }
46380
+ }
46381
+ /**
46382
+ * Fetch the next batch of non-deleted customers for PM sync.
46383
+ * Returns customer IDs and created timestamps, ordered by id ASC.
46384
+ */
46385
+ async findNextCustomerBatchForPmSync(accountId, afterCustomerId, cursor, limit) {
46386
+ let query = `SELECT id, created FROM stripe.customers WHERE _account_id = $1 AND COALESCE(deleted, false) <> true`;
46387
+ const params = [accountId];
46388
+ if (afterCustomerId) {
46389
+ params.push(afterCustomerId);
46390
+ query += ` AND id > $${params.length}`;
46391
+ }
46392
+ if (cursor && /^\d+$/.test(cursor)) {
46393
+ params.push(Number.parseInt(cursor, 10));
46394
+ query += ` AND created >= $${params.length}`;
46395
+ }
46396
+ params.push(limit);
46397
+ query += ` ORDER BY id ASC LIMIT $${params.length}`;
46398
+ const result = await this.postgresClient.query(query, params);
46399
+ return result.rows;
46400
+ }
46401
+ /**
46402
+ * Fetch one page of events from the Stripe Events API and reconcile affected entities.
46403
+ *
46404
+ * Instead of replaying events (which can resurrect deleted objects due to newest-first ordering),
46405
+ * we deduplicate by entity and re-fetch current state from Stripe for each affected entity.
46406
+ *
46407
+ * Cursor: event `created` timestamp. On first run, starts from the sync run's startedAt.
46408
+ * On subsequent runs, picks up where the last completed run left off.
46409
+ */
46410
+ async fetchOnePageEventCatchup(accountId, resourceName, runStartedAt, cursor, pageCursor) {
46411
+ try {
46412
+ let createdGte;
46413
+ if (cursor && /^\d+$/.test(cursor)) {
46414
+ createdGte = Number.parseInt(cursor, 10);
46415
+ } else {
46416
+ createdGte = Math.floor(runStartedAt.getTime() / 1e3);
46417
+ }
46418
+ const thirtyDaysAgo = Math.floor(Date.now() / 1e3) - 30 * 24 * 60 * 60;
46419
+ if (createdGte < thirtyDaysAgo) {
46420
+ this.config.logger?.warn(
46421
+ `_event_catchup: cursor ${createdGte} is older than 30 days, clamping to ${thirtyDaysAgo}`
46422
+ );
46423
+ createdGte = thirtyDaysAgo;
46424
+ }
46425
+ const listParams = {
46426
+ limit: 100,
46427
+ created: { gte: createdGte }
46428
+ };
46429
+ if (pageCursor) {
46430
+ listParams.starting_after = pageCursor;
46431
+ }
46432
+ const response = await this.stripe.events.list(listParams);
46433
+ if (response.data.length === 0) {
46434
+ await this.postgresClient.updateObjectCursor(
46435
+ accountId,
46436
+ runStartedAt,
46437
+ resourceName,
46438
+ String(createdGte)
46439
+ );
46440
+ await this.postgresClient.completeObjectSync(accountId, runStartedAt, resourceName);
46441
+ return { processed: 0, hasMore: false, runStartedAt };
46442
+ }
46443
+ const entityMap = /* @__PURE__ */ new Map();
46444
+ for (const event of response.data) {
46445
+ const obj = event.data.object;
46446
+ if (!obj?.id || !obj?.object) continue;
46447
+ const key = `${obj.object}:${obj.id}`;
46448
+ const existing = entityMap.get(key);
46449
+ if (!existing || event.created > existing.created) {
46450
+ entityMap.set(key, event);
46451
+ }
46452
+ }
46453
+ const hardDeleteEventTypes = /* @__PURE__ */ new Set([
46454
+ "product.deleted",
46455
+ "price.deleted",
46456
+ "plan.deleted",
46457
+ "customer.deleted",
46458
+ "customer.tax_id.deleted"
46459
+ ]);
46460
+ let processed = 0;
46461
+ let skipped = 0;
46462
+ const skipObjectTypes = /* @__PURE__ */ new Set(["tax_id"]);
46463
+ for (const [, event] of entityMap) {
46464
+ const obj = event.data.object;
46465
+ const eventType = event.type;
46466
+ if (skipObjectTypes.has(obj.object)) continue;
46467
+ try {
46468
+ if (!hardDeleteEventTypes.has(eventType)) {
46469
+ const tableName = eventObjectTypeToTable(obj.object);
46470
+ if (tableName) {
46471
+ const localRecord = await this.postgresClient.query(
46472
+ `SELECT "_last_synced_at" FROM stripe."${tableName}"
46473
+ WHERE id = $1 AND "_account_id" = $2 LIMIT 1`,
46474
+ [obj.id, accountId]
46475
+ );
46476
+ if (localRecord.rows.length > 0 && localRecord.rows[0]._last_synced_at != null) {
46477
+ const syncedAt = new Date(localRecord.rows[0]._last_synced_at).getTime() / 1e3;
46478
+ if (syncedAt >= event.created) {
46479
+ skipped++;
46480
+ continue;
46481
+ }
46482
+ }
46483
+ }
46484
+ }
46485
+ if (hardDeleteEventTypes.has(eventType)) {
46486
+ await this.handleEventCatchupDelete(obj.object, obj.id, accountId);
46487
+ } else {
46488
+ await this.handleEventCatchupUpsert(obj.object, obj.id, accountId);
46489
+ }
46490
+ processed++;
46491
+ } catch (err) {
46492
+ const errMsg = err instanceof Error ? err.message : String(err);
46493
+ this.config.logger?.warn(
46494
+ `_event_catchup: failed to process ${obj.object}:${obj.id} (event ${event.id}): ${errMsg}`
46495
+ );
46496
+ }
46497
+ }
46498
+ if (skipped > 0) {
46499
+ this.config.logger?.info(
46500
+ `_event_catchup: skipped ${skipped} entities already up-to-date, processed ${processed}`
46501
+ );
46502
+ }
46503
+ if (processed > 0) {
46504
+ await this.postgresClient.incrementObjectProgress(
46505
+ accountId,
46506
+ runStartedAt,
46507
+ resourceName,
46508
+ processed
46509
+ );
46510
+ }
46511
+ const maxCreated = Math.max(...response.data.map((e) => e.created));
46512
+ await this.postgresClient.updateObjectCursor(
46513
+ accountId,
46514
+ runStartedAt,
46515
+ resourceName,
46516
+ String(maxCreated)
46517
+ );
46518
+ const lastEventId = response.data[response.data.length - 1].id;
46519
+ if (response.has_more) {
46520
+ await this.postgresClient.updateObjectPageCursor(
46521
+ accountId,
46522
+ runStartedAt,
46523
+ resourceName,
46524
+ lastEventId
46525
+ );
46526
+ }
46527
+ if (!response.has_more) {
46528
+ await this.postgresClient.completeObjectSync(accountId, runStartedAt, resourceName);
46529
+ }
46530
+ return { processed, hasMore: response.has_more, runStartedAt };
46531
+ } catch (error) {
46532
+ await this.postgresClient.failObjectSync(
46533
+ accountId,
46534
+ runStartedAt,
46535
+ resourceName,
46536
+ error instanceof Error ? error.message : "Unknown error"
46537
+ );
46538
+ throw error;
46539
+ }
46540
+ }
46541
+ /**
46542
+ * Handle a delete for an entity discovered via event catch-up.
46543
+ * Maps Stripe object types to the appropriate delete method.
46544
+ */
46545
+ async handleEventCatchupDelete(objectType, entityId, accountId) {
46546
+ switch (objectType) {
46547
+ case "product":
46548
+ await this.deleteProduct(entityId);
46549
+ break;
46550
+ case "price":
46551
+ await this.deletePrice(entityId);
46552
+ break;
46553
+ case "plan":
46554
+ await this.deletePlan(entityId);
46555
+ break;
46556
+ case "customer": {
46557
+ const deletedCustomer = {
46558
+ id: entityId,
46559
+ object: "customer",
46560
+ deleted: true
46561
+ };
46562
+ await this.upsertCustomers([deletedCustomer], accountId);
46563
+ break;
46564
+ }
46565
+ case "tax_id":
46566
+ await this.deleteTaxId(entityId);
46567
+ break;
46568
+ default:
46569
+ this.config.logger?.warn(
46570
+ `_event_catchup: no delete handler for object type "${objectType}", skipping ${entityId}`
46571
+ );
46572
+ }
46573
+ }
46574
+ /**
46575
+ * Handle an upsert for an entity discovered via event catch-up.
46576
+ * Re-fetches the current state from Stripe and upserts it.
46577
+ * If the entity has been deleted (404), falls back to the delete handler.
46578
+ */
46579
+ async handleEventCatchupUpsert(objectType, entityId, accountId) {
46580
+ try {
46581
+ switch (objectType) {
46582
+ case "product": {
46583
+ const product = await this.stripe.products.retrieve(entityId);
46584
+ await this.upsertProducts([product], accountId);
46585
+ break;
46586
+ }
46587
+ case "price": {
46588
+ const price = await this.stripe.prices.retrieve(entityId);
46589
+ await this.upsertPrices([price], accountId);
46590
+ break;
46591
+ }
46592
+ case "plan": {
46593
+ const plan = await this.stripe.plans.retrieve(entityId);
46594
+ await this.upsertPlans([plan], accountId);
46595
+ break;
46596
+ }
46597
+ case "customer": {
46598
+ const customer = await this.stripe.customers.retrieve(entityId);
46599
+ await this.upsertCustomers([customer], accountId);
46600
+ break;
46601
+ }
46602
+ case "subscription": {
46603
+ const sub = await this.stripe.subscriptions.retrieve(entityId);
46604
+ await this.upsertSubscriptions([sub], accountId);
46605
+ break;
46606
+ }
46607
+ case "subscription_schedule": {
46608
+ const schedule = await this.stripe.subscriptionSchedules.retrieve(entityId);
46609
+ await this.upsertSubscriptionSchedules([schedule], accountId);
46610
+ break;
46611
+ }
46612
+ case "invoice": {
46613
+ const invoice = await this.stripe.invoices.retrieve(entityId);
46614
+ await this.upsertInvoices([invoice], accountId);
46615
+ break;
46616
+ }
46617
+ case "charge": {
46618
+ const charge = await this.stripe.charges.retrieve(entityId, {
46619
+ expand: ["balance_transaction"]
46620
+ });
46621
+ if (charge.balance_transaction && typeof charge.balance_transaction === "object") {
46622
+ await this.upsertBalanceTransactions(
46623
+ [charge.balance_transaction],
46624
+ accountId
46625
+ );
46626
+ }
46627
+ await this.upsertCharges([charge], accountId);
46628
+ break;
46629
+ }
46630
+ case "payment_intent": {
46631
+ const pi = await this.stripe.paymentIntents.retrieve(entityId);
46632
+ await this.upsertPaymentIntents([pi], accountId);
46633
+ break;
46634
+ }
46635
+ case "payment_method": {
46636
+ const pm = await this.stripe.paymentMethods.retrieve(entityId);
46637
+ await this.upsertPaymentMethods([pm], accountId);
46638
+ break;
46639
+ }
46640
+ case "setup_intent": {
46641
+ const si = await this.stripe.setupIntents.retrieve(entityId);
46642
+ await this.upsertSetupIntents([si], accountId);
46643
+ break;
46644
+ }
46645
+ case "dispute": {
46646
+ const dispute = await this.stripe.disputes.retrieve(entityId, {
46647
+ expand: ["balance_transactions"]
46648
+ });
46649
+ if (dispute.balance_transactions && Array.isArray(dispute.balance_transactions)) {
46650
+ const expandedBts = dispute.balance_transactions.filter(
46651
+ (bt) => typeof bt === "object"
46652
+ );
46653
+ if (expandedBts.length > 0) {
46654
+ await this.upsertBalanceTransactions(expandedBts, accountId);
46655
+ }
46656
+ }
46657
+ await this.upsertDisputes([dispute], accountId);
46658
+ break;
46659
+ }
46660
+ case "credit_note": {
46661
+ const cn = await this.stripe.creditNotes.retrieve(entityId);
46662
+ await this.upsertCreditNotes([cn], accountId);
46663
+ break;
46664
+ }
46665
+ case "refund": {
46666
+ const refund = await this.stripe.refunds.retrieve(entityId, {
46667
+ expand: ["balance_transaction"]
46668
+ });
46669
+ if (refund.balance_transaction && typeof refund.balance_transaction === "object") {
46670
+ await this.upsertBalanceTransactions(
46671
+ [refund.balance_transaction],
46672
+ accountId
46673
+ );
46674
+ }
46675
+ await this.upsertRefunds([refund], accountId);
46676
+ break;
46677
+ }
46678
+ case "tax_id": {
46679
+ const taxId = await this.stripe.taxIds.retrieve(entityId);
46680
+ await this.upsertTaxIds([taxId], accountId);
46681
+ break;
46682
+ }
46683
+ case "balance_transaction": {
46684
+ const bt = await this.stripe.balanceTransactions.retrieve(entityId);
46685
+ await this.upsertBalanceTransactions([bt], accountId);
46686
+ break;
46687
+ }
46688
+ case "checkout.session": {
46689
+ const session = await this.stripe.checkout.sessions.retrieve(entityId);
46690
+ await this.upsertCheckoutSessions([session], accountId);
46691
+ break;
46692
+ }
46693
+ case "radar.early_fraud_warning": {
46694
+ const efw = await this.stripe.radar.earlyFraudWarnings.retrieve(entityId);
46695
+ await this.upsertEarlyFraudWarning([efw], accountId);
46696
+ break;
46697
+ }
46698
+ default:
46699
+ this.config.logger?.warn(
46700
+ `_event_catchup: no upsert handler for object type "${objectType}", skipping ${entityId}`
46701
+ );
46702
+ }
46703
+ } catch (err) {
46704
+ const isNotFound = (err instanceof Stripe3.errors.StripeInvalidRequestError || err instanceof Stripe3.errors.StripeAPIError) && (err.code === "resource_missing" || err.statusCode === 404);
46705
+ if (isNotFound) {
46706
+ this.config.logger?.info(
46707
+ `_event_catchup: ${objectType}:${entityId} not found on Stripe, treating as deleted`
46708
+ );
46709
+ await this.handleEventCatchupDelete(objectType, entityId, accountId);
46710
+ return;
46711
+ }
46712
+ throw err;
46713
+ }
46714
+ }
46271
46715
  /**
46272
46716
  * Process all pages for all (or specified) object types until complete.
46273
46717
  *
@@ -46341,6 +46785,7 @@ ${message}`;
46341
46785
  };
46342
46786
  }
46343
46787
  applySyncBackfillResult(results, object, result) {
46788
+ if (object === "_event_catchup") return;
46344
46789
  if (this.isSigmaResource(object)) {
46345
46790
  results.sigma = results.sigma ?? {};
46346
46791
  results.sigma[object] = result;
@@ -46376,6 +46821,9 @@ ${message}`;
46376
46821
  case "setup_intent":
46377
46822
  results.setupIntents = result;
46378
46823
  break;
46824
+ case "payment_method":
46825
+ results.paymentMethods = result;
46826
+ break;
46379
46827
  case "payment_intent":
46380
46828
  results.paymentIntents = result;
46381
46829
  break;
@@ -47883,6 +48331,29 @@ function chunkArray(array, chunkSize) {
47883
48331
  }
47884
48332
  return result;
47885
48333
  }
48334
+ function eventObjectTypeToTable(objectType) {
48335
+ const mapping = {
48336
+ product: "products",
48337
+ price: "prices",
48338
+ plan: "plans",
48339
+ customer: "customers",
48340
+ subscription: "subscriptions",
48341
+ subscription_schedule: "subscription_schedules",
48342
+ invoice: "invoices",
48343
+ charge: "charges",
48344
+ balance_transaction: "balance_transactions",
48345
+ payment_intent: "payment_intents",
48346
+ payment_method: "payment_methods",
48347
+ setup_intent: "setup_intents",
48348
+ dispute: "disputes",
48349
+ credit_note: "credit_notes",
48350
+ refund: "refunds",
48351
+ tax_id: "tax_ids",
48352
+ "checkout.session": "checkout_sessions",
48353
+ "radar.early_fraud_warning": "early_fraud_warnings"
48354
+ };
48355
+ return mapping[objectType] ?? null;
48356
+ }
47886
48357
 
47887
48358
  // src/database/migrate.ts
47888
48359
  import { Client } from "pg";
@@ -3,11 +3,11 @@ import {
3
3
  StripeSync,
4
4
  createStripeWebSocketClient,
5
5
  runMigrations
6
- } from "./chunk-LB4HG4Q6.js";
6
+ } from "./chunk-IQ64IUIL.js";
7
7
  import {
8
8
  install,
9
9
  uninstall
10
- } from "./chunk-Q3AGYUHN.js";
10
+ } from "./chunk-OLHHINPH.js";
11
11
 
12
12
  // src/cli/config.ts
13
13
  import dotenv from "dotenv";
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  package_default
3
- } from "./chunk-HXSDJSKR.js";
3
+ } from "./chunk-7DYBM7H3.js";
4
4
 
5
5
  // src/supabase/supabase.ts
6
6
  import { SupabaseManagementAPI } from "supabase-management-js";