better-auth-streampay 3.2.0 → 3.3.1

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.
package/dist/index.cjs CHANGED
@@ -658,6 +658,15 @@ function isTerminalSubscriptionStatus(status) {
658
658
  function isCheckoutSuccessStatus(status) {
659
659
  return status !== void 0 && CHECKOUT_SUCCESS_STATUSES.has(status);
660
660
  }
661
+ function subscriptionSlotKey(referenceType, referenceId, group) {
662
+ const tuple = JSON.stringify([referenceType, referenceId, group ?? null]);
663
+ return `sp_slot_v1_${crypto.createHash("sha256").update(tuple).digest("hex")}`;
664
+ }
665
+ var UPGRADE_IDEMPOTENCY_WINDOW_MS = 15 * 60 * 1e3;
666
+ var PLAN_NAME_METADATA_KEY = "streampay_plugin_plan_name";
667
+ var REFERENCE_ID_METADATA_KEY = "streampay_plugin_reference_id";
668
+ var REFERENCE_TYPE_METADATA_KEY = "streampay_plugin_reference_type";
669
+ var SUBSCRIPTION_ROW_ID_METADATA_KEY = "streampay_plugin_subscription_row_id";
661
670
 
662
671
  // src/plugins/subscriptions/reconcile.ts
663
672
  var SUBSCRIPTION_MODEL = "subscription";
@@ -679,25 +688,38 @@ function reconcileProjectionAgainstExisting(existing, projection, options = {})
679
688
  function projectSubscriptionAgainstExisting(existing, stream) {
680
689
  return reconcileProjectionAgainstExisting(existing, projectSubscriptionFields(stream, existing));
681
690
  }
691
+ function liveSlotKey(existing, projected) {
692
+ if (isTerminalSubscriptionStatus(projected.status ?? existing.status)) return null;
693
+ return subscriptionSlotKey(
694
+ existing.referenceType ?? "user",
695
+ existing.referenceId,
696
+ projected.group === void 0 ? existing.group : projected.group
697
+ );
698
+ }
682
699
  async function persistSubscriptionProjection(adapter, existing, projection, log, source) {
683
700
  const stale = existing.providerUpdatedAt instanceof Date && projection.providerUpdatedAt instanceof Date && projection.providerUpdatedAt.getTime() < existing.providerUpdatedAt.getTime();
684
- if (!stale) {
685
- const updated = await adapter.update({
686
- model: SUBSCRIPTION_MODEL,
687
- update: projection,
688
- where: [
689
- { field: "id", value: existing.id },
690
- { field: "providerUpdatedAt", value: existing.providerUpdatedAt ?? null },
691
- { field: "streampaySubscriptionId", value: existing.streampaySubscriptionId ?? null },
692
- { field: "streampayConsumerId", value: existing.streampayConsumerId ?? null },
693
- { field: "status", value: existing.status },
694
- { field: "billingStatus", value: existing.billingStatus }
695
- ]
696
- });
697
- if (updated) return updated;
698
- }
701
+ const slotKey = liveSlotKey(existing, projection);
702
+ const movesSlot = slotKey !== null && existing.activeSlotKey !== slotKey;
703
+ const slotHolder = movesSlot ? await adapter.findOne({
704
+ model: SUBSCRIPTION_MODEL,
705
+ where: [{ field: "activeSlotKey", value: slotKey }]
706
+ }) : null;
707
+ const updated = stale || slotHolder ? null : await adapter.update({
708
+ model: SUBSCRIPTION_MODEL,
709
+ update: movesSlot ? { ...projection, activeSlotKey: slotKey } : projection,
710
+ where: [
711
+ { field: "id", value: existing.id },
712
+ { field: "providerUpdatedAt", value: existing.providerUpdatedAt ?? null },
713
+ { field: "streampaySubscriptionId", value: existing.streampaySubscriptionId ?? null },
714
+ { field: "streampayConsumerId", value: existing.streampayConsumerId ?? null },
715
+ { field: "status", value: existing.status },
716
+ { field: "billingStatus", value: existing.billingStatus },
717
+ { field: "renewedCycleNumber", value: existing.renewedCycleNumber ?? null }
718
+ ]
719
+ });
720
+ if (updated) return updated;
699
721
  log.warn(
700
- `${source}: retained newer local subscription state for row=${existing.id}. The provider action is not rolled back.`
722
+ slotHolder ? `${source}: StreamPay reports row=${existing.id} live, but row=${slotHolder.id} holds its billing slot. The next webhook reconciles it.` : `${source}: retained newer local subscription state for row=${existing.id}. The provider action is not rolled back.`
701
723
  );
702
724
  return adapter.findOne({
703
725
  model: SUBSCRIPTION_MODEL,
@@ -760,6 +782,11 @@ function projectSubscriptionFields(sub, existing) {
760
782
  periodStart,
761
783
  periodEnd,
762
784
  currentCycleNumber: sub.current_cycle_number ?? null,
785
+ // Only renewal evidence advances the baseline. Other writers only initialize it, so they can
786
+ // neither absorb a renewal nor roll back one that was just delivered.
787
+ ...existing?.renewedCycleNumber == null ? {
788
+ renewedCycleNumber: existing?.currentCycleNumber ?? (existing?.streampaySubscriptionId ? sub.current_cycle_number ?? null : firstLinkRenewalBaseline(sub.current_cycle_number))
789
+ } : {},
763
790
  trialStart: (sub.trial_end ? parseDate(sub.started_at) ?? periodStart : null) ?? existing?.trialStart ?? null,
764
791
  trialEnd: parseDate(sub.trial_end),
765
792
  cancelAtPeriodEnd: Boolean(sub.cancel_at_period_end),
@@ -774,6 +801,9 @@ function projectSubscriptionFields(sub, existing) {
774
801
  updatedAt: /* @__PURE__ */ new Date()
775
802
  };
776
803
  }
804
+ function firstLinkRenewalBaseline(currentCycle) {
805
+ return typeof currentCycle === "number" ? Math.min(currentCycle, 1) : null;
806
+ }
777
807
  function parseDate(value) {
778
808
  if (!value) return null;
779
809
  const normalized = /[T ]/.test(value) && !/(?:Z|[+-]\d{2}:?\d{2})$/i.test(value) ? `${value}Z` : value;
@@ -993,15 +1023,6 @@ function freezePaginationConflict(message) {
993
1023
  message
994
1024
  });
995
1025
  }
996
- function subscriptionSlotKey(referenceType, referenceId, group) {
997
- const tuple = JSON.stringify([referenceType, referenceId, group ?? null]);
998
- return `sp_slot_v1_${crypto.createHash("sha256").update(tuple).digest("hex")}`;
999
- }
1000
- var UPGRADE_IDEMPOTENCY_WINDOW_MS = 15 * 60 * 1e3;
1001
- var PLAN_NAME_METADATA_KEY = "streampay_plugin_plan_name";
1002
- var REFERENCE_ID_METADATA_KEY = "streampay_plugin_reference_id";
1003
- var REFERENCE_TYPE_METADATA_KEY = "streampay_plugin_reference_type";
1004
- var SUBSCRIPTION_ROW_ID_METADATA_KEY = "streampay_plugin_subscription_row_id";
1005
1026
 
1006
1027
  // src/plugins/subscriptions/sync.ts
1007
1028
  var SUBSCRIPTION_MODEL2 = "subscription";
@@ -1029,6 +1050,9 @@ function isUniqueConstraintError(err) {
1029
1050
  }
1030
1051
  var WEBHOOK_PROCESSING_LEASE_MS = 2 * 60 * 1e3;
1031
1052
  var WEBHOOK_RETRY_DELAYS_MS = [5, 30, 120, 360, 720].map((minutes) => minutes * 60 * 1e3);
1053
+ function hasLiveLease(row, now) {
1054
+ return row.lockedAt instanceof Date && now.getTime() - row.lockedAt.getTime() < WEBHOOK_PROCESSING_LEASE_MS;
1055
+ }
1032
1056
  var WebhookEventInProgressError = class extends Error {
1033
1057
  constructor(eventType) {
1034
1058
  super(`Webhook ${eventType} is already being processed; retry later.`);
@@ -1113,7 +1137,7 @@ async function claimOrAdvanceWebhookEvent(ctx, payload, rawBody, signatureHeader
1113
1137
  );
1114
1138
  return { action: "skip", reason: "dead_letter" };
1115
1139
  }
1116
- if (existing.lockedAt instanceof Date && now.getTime() - existing.lockedAt.getTime() < WEBHOOK_PROCESSING_LEASE_MS) {
1140
+ if (hasLiveLease(existing, now)) {
1117
1141
  logger(ctx).info(
1118
1142
  `webhook ${payload.event_type} (${eventId}) is already being processed \u2014 skipping concurrent delivery.`
1119
1143
  );
@@ -1129,15 +1153,15 @@ async function claimOrAdvanceWebhookEvent(ctx, payload, rawBody, signatureHeader
1129
1153
  lastAttemptAt: now,
1130
1154
  deadLetteredAt: now,
1131
1155
  nextAttemptAt: null,
1132
- rawPayload: rawBody,
1133
- signatureHeader,
1156
+ ...rawBody !== null ? { rawPayload: rawBody, signatureHeader } : {},
1134
1157
  lockedAt: null,
1135
1158
  lockedBy: null
1136
1159
  },
1137
1160
  where: [
1138
1161
  { field: "id", value: existing.id },
1139
1162
  { field: "status", value: "pending" },
1140
- { field: "lockedAt", value: existing.lockedAt ?? null }
1163
+ { field: "lockedAt", value: existing.lockedAt ?? null },
1164
+ { field: "attemptCount", value: existing.attemptCount ?? null }
1141
1165
  ]
1142
1166
  });
1143
1167
  return updated2 ? { action: "dead_letter", row: updated2 } : { action: "skip", reason: "in_progress" };
@@ -1149,19 +1173,21 @@ async function claimOrAdvanceWebhookEvent(ctx, payload, rawBody, signatureHeader
1149
1173
  lastAttemptAt: now,
1150
1174
  nextAttemptAt: null,
1151
1175
  lockedAt: now,
1152
- lockedBy: lockId
1176
+ lockedBy: lockId,
1177
+ ...rawBody !== null ? { rawPayload: rawBody, signatureHeader } : {}
1153
1178
  },
1154
1179
  where: [
1155
1180
  { field: "id", value: existing.id },
1156
1181
  { field: "status", value: "pending" },
1157
- { field: "lockedAt", value: existing.lockedAt ?? null }
1182
+ { field: "lockedAt", value: existing.lockedAt ?? null },
1183
+ { field: "attemptCount", value: existing.attemptCount ?? null }
1158
1184
  ]
1159
1185
  });
1160
1186
  return updated ? { action: "process", row: updated } : { action: "skip", reason: "in_progress" };
1161
1187
  }
1162
1188
  async function claimWebhookEventForReplay(ctx, row) {
1163
1189
  const now = /* @__PURE__ */ new Date();
1164
- if (row.lockedAt instanceof Date && now.getTime() - row.lockedAt.getTime() < WEBHOOK_PROCESSING_LEASE_MS) {
1190
+ if (hasLiveLease(row, now)) {
1165
1191
  return null;
1166
1192
  }
1167
1193
  return ctx.context.adapter.update({
@@ -1179,30 +1205,71 @@ async function claimWebhookEventForReplay(ctx, row) {
1179
1205
  where: [
1180
1206
  { field: "id", value: row.id },
1181
1207
  { field: "status", value: row.status },
1182
- { field: "lockedAt", value: row.lockedAt ?? null }
1208
+ { field: "lockedAt", value: row.lockedAt ?? null },
1209
+ { field: "attemptCount", value: row.attemptCount ?? null }
1183
1210
  ]
1184
1211
  });
1185
1212
  }
1186
- async function markWebhookEventCompleted(ctx, rowId, lockId) {
1213
+ function isStillDueWebhookEvent(row, selectedAttemptCount, now) {
1214
+ const retryDue = row.nextAttemptAt instanceof Date && row.nextAttemptAt <= now;
1215
+ const leaseAbandoned = row.lockedAt instanceof Date && !hasLiveLease(row, now);
1216
+ return row.status === "pending" && row.attemptCount === selectedAttemptCount && (retryDue || leaseAbandoned);
1217
+ }
1218
+ async function parkUnreplayableWebhookEvent(ctx, row, reason) {
1219
+ if (row.status !== "pending" || hasLiveLease(row, /* @__PURE__ */ new Date())) return;
1187
1220
  await ctx.context.adapter.update({
1188
1221
  model: WEBHOOK_EVENT_MODEL,
1189
1222
  update: {
1190
- status: "completed",
1191
- completedAt: /* @__PURE__ */ new Date(),
1192
1223
  nextAttemptAt: null,
1193
1224
  lockedAt: null,
1194
1225
  lockedBy: null,
1195
- rawPayload: null,
1196
- signatureHeader: null,
1197
- lastError: null,
1198
- lastErrorCode: null
1226
+ lastError: reason,
1227
+ lastErrorCode: "UNREPLAYABLE_PAYLOAD"
1199
1228
  },
1229
+ where: [
1230
+ { field: "id", value: row.id },
1231
+ { field: "status", value: "pending" },
1232
+ { field: "lockedAt", value: row.lockedAt ?? null },
1233
+ { field: "attemptCount", value: row.attemptCount ?? null }
1234
+ ]
1235
+ });
1236
+ }
1237
+ function completedWebhookEventFields() {
1238
+ return {
1239
+ status: "completed",
1240
+ completedAt: /* @__PURE__ */ new Date(),
1241
+ nextAttemptAt: null,
1242
+ lockedAt: null,
1243
+ lockedBy: null,
1244
+ rawPayload: null,
1245
+ signatureHeader: null,
1246
+ lastError: null,
1247
+ lastErrorCode: null
1248
+ };
1249
+ }
1250
+ async function markWebhookEventCompleted(ctx, rowId, lockId) {
1251
+ await ctx.context.adapter.update({
1252
+ model: WEBHOOK_EVENT_MODEL,
1253
+ update: completedWebhookEventFields(),
1200
1254
  where: [
1201
1255
  { field: "id", value: rowId },
1202
1256
  ...lockId ? [{ field: "lockedBy", value: lockId }] : []
1203
1257
  ]
1204
1258
  });
1205
1259
  }
1260
+ async function completeUnchangedWebhookEvent(ctx, row) {
1261
+ const updated = await ctx.context.adapter.update({
1262
+ model: WEBHOOK_EVENT_MODEL,
1263
+ update: completedWebhookEventFields(),
1264
+ where: [
1265
+ { field: "id", value: row.id },
1266
+ { field: "status", value: row.status },
1267
+ { field: "lockedAt", value: row.lockedAt ?? null },
1268
+ { field: "attemptCount", value: row.attemptCount ?? null }
1269
+ ]
1270
+ });
1271
+ return updated !== null;
1272
+ }
1206
1273
  async function recordWebhookEventFailure(ctx, rowId, rawBody, signatureHeader, err, lockId, deadLetter = false) {
1207
1274
  const lastError = err instanceof Error ? err.message : String(err);
1208
1275
  const sdkError = readSdkErrorFields(err);
@@ -1321,12 +1388,41 @@ var SubscriptionCorrelationError = class extends Error {
1321
1388
  this.name = "SubscriptionCorrelationError";
1322
1389
  }
1323
1390
  };
1391
+ function providerStateConfirmsEvent(eventType, stream) {
1392
+ switch (eventType) {
1393
+ case "SUBSCRIPTION_CREATED":
1394
+ return true;
1395
+ case "SUBSCRIPTION_ACTIVATED":
1396
+ case "SUBSCRIPTION_UNFREEZE_NOW":
1397
+ return stream.status === "ACTIVE" || stream.status === "TRIALING";
1398
+ case "SUBSCRIPTION_CANCELED":
1399
+ return stream.status === "CANCELED";
1400
+ case "SUBSCRIPTION_INACTIVATED":
1401
+ return stream.status === "INACTIVE";
1402
+ case "SUBSCRIPTION_CANCEL_AT_PERIOD_END":
1403
+ return Boolean(stream.cancel_at_period_end) && !isTerminalSubscriptionStatus(toLocalStatus(stream.status));
1404
+ case "SUBSCRIPTION_FROZEN":
1405
+ case "SUBSCRIPTION_FREEZE_NOW":
1406
+ return stream.status === "FROZEN";
1407
+ case "SUBSCRIPTION_PLAN_CHANGE_SCHEDULED":
1408
+ return Boolean(stream.pending_change);
1409
+ case "SUBSCRIPTION_PLAN_CHANGE_CANCELED":
1410
+ return !stream.pending_change;
1411
+ default:
1412
+ return false;
1413
+ }
1414
+ }
1324
1415
  async function takeSlotFromReservation(ctx, client, slotKey, ownerRowId, streampaySubscriptionId) {
1325
1416
  const holder = await ctx.context.adapter.findOne({
1326
1417
  model: SUBSCRIPTION_MODEL2,
1327
1418
  where: [{ field: "activeSlotKey", value: slotKey }]
1328
1419
  });
1329
1420
  if (!holder || holder.id === ownerRowId) return;
1421
+ if (holder.streampaySubscriptionId === streampaySubscriptionId) {
1422
+ throw new Error(
1423
+ `StreamPay sub=${streampaySubscriptionId} was linked to row=${holder.id} concurrently. Retry delivery.`
1424
+ );
1425
+ }
1330
1426
  if (holder.status !== "incomplete" || holder.streampaySubscriptionId) {
1331
1427
  throw new SubscriptionCorrelationError(
1332
1428
  `StreamPay sub=${streampaySubscriptionId} needs the billing slot held by live row=${holder.id} (${holder.status}). Resolve the duplicate subscription, then replay.`
@@ -1401,7 +1497,8 @@ async function updateReconciledSubscription(ctx, client, existing, projected, st
1401
1497
  { field: "streampaySubscriptionId", value: existing.streampaySubscriptionId ?? null },
1402
1498
  { field: "streampayConsumerId", value: existing.streampayConsumerId ?? null },
1403
1499
  { field: "status", value: existing.status },
1404
- { field: "billingStatus", value: existing.billingStatus }
1500
+ { field: "billingStatus", value: existing.billingStatus },
1501
+ { field: "renewedCycleNumber", value: existing.renewedCycleNumber ?? null }
1405
1502
  ]
1406
1503
  });
1407
1504
  if (!updated) {
@@ -1411,7 +1508,7 @@ async function updateReconciledSubscription(ctx, client, existing, projected, st
1411
1508
  }
1412
1509
  return updated;
1413
1510
  }
1414
- async function reconcileFromStreamPay(ctx, payload, client, plans) {
1511
+ async function reconcileFromStreamPay(ctx, payload, client, plans, prefetched) {
1415
1512
  const streampaySubscriptionId = payload.entity_id;
1416
1513
  if (!streampaySubscriptionId) {
1417
1514
  logger(ctx).warn(`webhook ${payload.event_type} has no entity_id \u2014 cannot reconcile.`);
@@ -1419,7 +1516,7 @@ async function reconcileFromStreamPay(ctx, payload, client, plans) {
1419
1516
  }
1420
1517
  let stream;
1421
1518
  try {
1422
- stream = await client.getSubscription(streampaySubscriptionId);
1519
+ stream = prefetched ?? await client.getSubscription(streampaySubscriptionId);
1423
1520
  } catch (err) {
1424
1521
  const msg = err instanceof Error ? err.message : String(err);
1425
1522
  logger(ctx).error(
@@ -1436,15 +1533,16 @@ async function reconcileFromStreamPay(ctx, payload, client, plans) {
1436
1533
  const eventIsStale = Boolean(
1437
1534
  eventAt && existing?.providerUpdatedAt instanceof Date && eventAt.getTime() < existing.providerUpdatedAt.getTime()
1438
1535
  );
1439
- if (!eventIsStale && payload.event_type === "SUBSCRIPTION_CYCLE_RENEWAL_FAILED" && projected.status === "active") {
1536
+ const eventApplies = !eventIsStale || providerStateConfirmsEvent(payload.event_type, stream);
1537
+ if (eventApplies && payload.event_type === "SUBSCRIPTION_CYCLE_RENEWAL_FAILED" && projected.status === "active") {
1440
1538
  projected.status = "past_due";
1441
1539
  projected.billingStatus = "past_due";
1442
1540
  }
1443
- const schedulesCancellation = !eventIsStale && payload.event_type === "SUBSCRIPTION_CANCEL_AT_PERIOD_END" && Boolean(stream.cancel_at_period_end);
1541
+ const schedulesCancellation = eventApplies && payload.event_type === "SUBSCRIPTION_CANCEL_AT_PERIOD_END" && Boolean(stream.cancel_at_period_end);
1444
1542
  if (schedulesCancellation) {
1445
1543
  projected.cancelAt = parseDate(stream.current_period_end);
1446
1544
  }
1447
- const confirmsCancellation = !eventIsStale && payload.event_type === "SUBSCRIPTION_CANCELED" && projected.status === "canceled";
1545
+ const confirmsCancellation = eventApplies && payload.event_type === "SUBSCRIPTION_CANCELED" && projected.status === "canceled";
1448
1546
  if (confirmsCancellation) {
1449
1547
  projected.activeSlotKey = null;
1450
1548
  }
@@ -1453,17 +1551,13 @@ async function reconcileFromStreamPay(ctx, payload, client, plans) {
1453
1551
  stampCancelScheduled: schedulesCancellation,
1454
1552
  stampCanceled: confirmsCancellation
1455
1553
  });
1554
+ if (schedulesCancellation && eventAt && existing?.cancelAtPeriodEnd && !existing.cancelScheduledAt) {
1555
+ projected.cancelScheduledAt = eventAt;
1556
+ }
1456
1557
  if (existing) {
1457
- const projectedStatus = projected.status ?? existing.status;
1458
- if (!isTerminalSubscriptionStatus(projectedStatus)) {
1459
- const desiredSlotKey = subscriptionSlotKey(
1460
- existing.referenceType ?? "user",
1461
- existing.referenceId,
1462
- projected.group === void 0 ? existing.group : projected.group
1463
- );
1464
- if (existing.activeSlotKey !== desiredSlotKey) {
1465
- projected.activeSlotKey = desiredSlotKey;
1466
- }
1558
+ const slotKey = liveSlotKey(existing, projected);
1559
+ if (slotKey && existing.activeSlotKey !== slotKey) {
1560
+ projected.activeSlotKey = slotKey;
1467
1561
  }
1468
1562
  const updated = await updateReconciledSubscription(
1469
1563
  ctx,
@@ -1472,7 +1566,7 @@ async function reconcileFromStreamPay(ctx, payload, client, plans) {
1472
1566
  projected,
1473
1567
  streampaySubscriptionId
1474
1568
  );
1475
- if (eventIsStale) {
1569
+ if (!eventApplies) {
1476
1570
  logger(ctx).info(
1477
1571
  `webhook ${payload.event_type}: ignored stale lifecycle callback for sub=${streampaySubscriptionId}.`
1478
1572
  );
@@ -1601,7 +1695,8 @@ async function syncWebhookPayload(ctx, payload, client, plans, callbacks, option
1601
1695
  retryOnCallbackError,
1602
1696
  options.retryingRenewalCallback === true || claim.row?.lastError?.startsWith(
1603
1697
  "Subscription callback onSubscriptionRenewed failed:"
1604
- ) === true
1698
+ ) === true,
1699
+ options.inboxEnabled ?? dedupe
1605
1700
  );
1606
1701
  } else {
1607
1702
  const { row, stream } = await reconcileFromStreamPay(ctx, payload, client, plans);
@@ -1633,7 +1728,59 @@ async function syncWebhookPayload(ctx, payload, client, plans, callbacks, option
1633
1728
  throw err;
1634
1729
  }
1635
1730
  }
1636
- async function handleRenewalEvidence(ctx, payload, client, plans, callbacks, retryOnCallbackError, retryingRenewalCallback) {
1731
+ async function releaseLockOfCompletedRenewal(ctx, subscriptionRowId, lockEventId) {
1732
+ const owner = await ctx.context.adapter.findOne({
1733
+ model: WEBHOOK_EVENT_MODEL,
1734
+ where: [{ field: "eventId", value: lockEventId }]
1735
+ });
1736
+ if (owner?.status !== "completed") return false;
1737
+ const released = await ctx.context.adapter.update({
1738
+ model: SUBSCRIPTION_MODEL2,
1739
+ update: { renewalCallbackEventId: null },
1740
+ where: [
1741
+ { field: "id", value: subscriptionRowId },
1742
+ { field: "renewalCallbackEventId", value: lockEventId }
1743
+ ]
1744
+ });
1745
+ if (released) {
1746
+ logger(ctx).warn(
1747
+ `released renewal callback lock of completed event ${lockEventId} for row=${subscriptionRowId}.`
1748
+ );
1749
+ }
1750
+ return released !== null;
1751
+ }
1752
+ async function linkCheckoutFromRenewalEvidence(ctx, payload, client, plans, stream) {
1753
+ const paymentLinkId = stream.latest_invoice?.payment_link_id;
1754
+ if (!paymentLinkId || !stream.id) return null;
1755
+ const reservation = await ctx.context.adapter.findOne({
1756
+ model: SUBSCRIPTION_MODEL2,
1757
+ where: [{ field: "streampayPaymentLinkId", value: paymentLinkId }]
1758
+ });
1759
+ if (!reservation) return null;
1760
+ const link = await client.getPaymentLink(paymentLinkId);
1761
+ const { row } = await reconcileFromStreamPay(
1762
+ ctx,
1763
+ {
1764
+ ...payload,
1765
+ entity_id: stream.id,
1766
+ data: {
1767
+ metadata: link.custom_metadata ?? {},
1768
+ payment_link: { id: paymentLinkId, url: "" }
1769
+ }
1770
+ },
1771
+ client,
1772
+ plans,
1773
+ stream
1774
+ );
1775
+ if (row) {
1776
+ logger(ctx).warn(
1777
+ `webhook ${payload.event_type}: linked checkout row=${row.id} to StreamPay sub=${stream.id} from renewal evidence.`
1778
+ );
1779
+ return row;
1780
+ }
1781
+ return findSubscriptionByStreampayId(ctx, stream.id);
1782
+ }
1783
+ async function handleRenewalEvidence(ctx, payload, client, plans, callbacks, retryOnCallbackError, retryingRenewalCallback, inboxEnabled) {
1637
1784
  const invoiceId = payload.data?.invoice?.id ?? payload.entity_id;
1638
1785
  if (!invoiceId) return;
1639
1786
  let subscriptionId = payload.entity_type === "SUBSCRIPTION" ? payload.entity_id : null;
@@ -1659,33 +1806,61 @@ async function handleRenewalEvidence(ctx, payload, client, plans, callbacks, ret
1659
1806
  logger(ctx).error(`${payload.event_type}: getSubscription(${subscriptionId}) failed: ${msg}`);
1660
1807
  throw err;
1661
1808
  }
1662
- const existing = await findSubscriptionByStreampayId(ctx, subscriptionId);
1809
+ const existing = await findSubscriptionByStreampayId(ctx, subscriptionId) ?? await linkCheckoutFromRenewalEvidence(ctx, payload, client, plans, stream);
1663
1810
  if (!existing) return;
1664
1811
  const eventAt = parseDate(payload.timestamp);
1665
1812
  const eventIsStale = Boolean(
1666
1813
  eventAt && existing.providerUpdatedAt instanceof Date && eventAt.getTime() < existing.providerUpdatedAt.getTime()
1667
1814
  );
1815
+ const evidenceInvoiceId = payload.data?.invoice?.id ?? (payload.entity_type === "INVOICE" ? payload.entity_id : null);
1816
+ const settlesLatestInvoice = stream.latest_invoice?.status === "COMPLETED" && (evidenceInvoiceId === null || stream.latest_invoice.id === evidenceInvoiceId);
1817
+ const evidenceApplies = !eventIsStale || settlesLatestInvoice;
1668
1818
  const projected = {
1669
1819
  ...projectSubscriptionFields(stream, existing),
1670
1820
  ...projectPlanFields(stream, plans),
1671
- ...eventIsStale ? existing.billingStatus === "past_due" && toLocalStatus(stream.status) === "active" ? { status: "past_due", billingStatus: "past_due" } : {} : { billingStatus: "current" }
1821
+ ...evidenceApplies ? { billingStatus: "current" } : existing.billingStatus === "past_due" && toLocalStatus(stream.status) === "active" ? { status: "past_due", billingStatus: "past_due" } : {}
1672
1822
  };
1823
+ const slotKey = liveSlotKey(existing, projected);
1824
+ if (slotKey && existing.activeSlotKey !== slotKey) {
1825
+ projected.activeSlotKey = slotKey;
1826
+ }
1673
1827
  const previousPeriodEnd = existing.periodEnd?.getTime() ?? null;
1674
1828
  const projectedPeriodEnd = projected.periodEnd?.getTime() ?? null;
1675
1829
  const periodAdvanced = previousPeriodEnd !== null && projectedPeriodEnd !== null && projectedPeriodEnd > previousPeriodEnd;
1676
- const cycleAdvanced = existing.currentCycleNumber !== null && existing.currentCycleNumber !== void 0 && projected.currentCycleNumber !== null && projected.currentCycleNumber !== void 0 && projected.currentCycleNumber > existing.currentCycleNumber;
1830
+ const renewedCycle = existing.renewedCycleNumber ?? existing.currentCycleNumber ?? null;
1831
+ const projectedCycle = projected.currentCycleNumber ?? null;
1832
+ const tracksCycles = renewedCycle !== null && projectedCycle !== null;
1833
+ const renewalAdvanced = tracksCycles ? projectedCycle > renewedCycle : periodAdvanced;
1677
1834
  const eventId = extractEventId(payload);
1678
- const pendingCallback = existing.renewalCallbackEventId ?? null;
1835
+ let pendingCallback = existing.renewalCallbackEventId ?? null;
1836
+ if (pendingCallback && pendingCallback !== eventId) {
1837
+ const released = inboxEnabled && await releaseLockOfCompletedRenewal(ctx, existing.id, pendingCallback);
1838
+ if (!released) {
1839
+ throw new Error(
1840
+ `Subscription renewal callback ${pendingCallback} is pending; retry delivery.`
1841
+ );
1842
+ }
1843
+ pendingCallback = null;
1844
+ }
1679
1845
  if (!pendingCallback && existing.providerUpdatedAt instanceof Date && projected.providerUpdatedAt instanceof Date && projected.providerUpdatedAt.getTime() < existing.providerUpdatedAt.getTime()) {
1680
1846
  throw new Error(
1681
1847
  `StreamPay returned stale subscription state for sub=${subscriptionId}; retry delivery.`
1682
1848
  );
1683
1849
  }
1684
- if (pendingCallback && pendingCallback !== eventId) {
1685
- throw new Error(`Subscription renewal callback ${pendingCallback} is pending; retry delivery.`);
1850
+ if (!pendingCallback && projected.activeSlotKey && projected.activeSlotKey !== existing.activeSlotKey) {
1851
+ await takeSlotFromReservation(
1852
+ ctx,
1853
+ client,
1854
+ projected.activeSlotKey,
1855
+ existing.id,
1856
+ subscriptionId
1857
+ );
1686
1858
  }
1687
- const deliverCallback = pendingCallback === eventId && pendingCallback !== null || !eventIsStale && (periodAdvanced || cycleAdvanced || retryingRenewalCallback);
1859
+ const deliverCallback = pendingCallback === eventId && pendingCallback !== null || evidenceApplies && (renewalAdvanced || retryingRenewalCallback);
1688
1860
  const callbackOwner = deliverCallback && callbacks.onSubscriptionRenewed ? eventId : null;
1861
+ if (deliverCallback && renewalAdvanced && projectedCycle !== null) {
1862
+ projected.renewedCycleNumber = projectedCycle;
1863
+ }
1689
1864
  const updated = await ctx.context.adapter.update({
1690
1865
  model: SUBSCRIPTION_MODEL2,
1691
1866
  // Recovery must retain the pending cycle, even if Stream has already advanced again.
@@ -1694,6 +1869,7 @@ async function handleRenewalEvidence(ctx, payload, client, plans, callbacks, ret
1694
1869
  { field: "id", value: existing.id },
1695
1870
  { field: "periodEnd", value: existing.periodEnd ?? null },
1696
1871
  { field: "currentCycleNumber", value: existing.currentCycleNumber ?? null },
1872
+ { field: "renewedCycleNumber", value: existing.renewedCycleNumber ?? null },
1697
1873
  { field: "renewalCallbackEventId", value: pendingCallback },
1698
1874
  { field: "providerUpdatedAt", value: existing.providerUpdatedAt ?? null },
1699
1875
  { field: "status", value: existing.status },
@@ -1706,8 +1882,8 @@ async function handleRenewalEvidence(ctx, payload, client, plans, callbacks, ret
1706
1882
  }
1707
1883
  const latest = await findSubscriptionByStreampayId(ctx, subscriptionId);
1708
1884
  const anotherCallbackOwner = latest?.renewalCallbackEventId;
1709
- const desiredCycleAdvanced = (periodAdvanced || cycleAdvanced) && (!periodAdvanced || (latest?.periodEnd?.getTime() ?? 0) >= (projectedPeriodEnd ?? 0)) && (!cycleAdvanced || (latest?.currentCycleNumber ?? 0) >= (projected.currentCycleNumber ?? 0));
1710
- if (anotherCallbackOwner && anotherCallbackOwner !== eventId && desiredCycleAdvanced) return;
1885
+ const renewalClaimedElsewhere = renewalAdvanced && (tracksCycles ? (latest?.renewedCycleNumber ?? 0) >= projectedCycle : (latest?.periodEnd?.getTime() ?? 0) >= (projectedPeriodEnd ?? 0));
1886
+ if (anotherCallbackOwner && anotherCallbackOwner !== eventId && renewalClaimedElsewhere) return;
1711
1887
  throw new Error(`Subscription changed during renewal reconciliation; retry delivery.`);
1712
1888
  }
1713
1889
  const row = updated;
@@ -2795,6 +2971,12 @@ function buildWebhookEventsEndpoints(adminOptions, registry) {
2795
2971
  message: `Webhook event ${ctx.params.eventId} not found.`
2796
2972
  });
2797
2973
  }
2974
+ const inProgress = new api.APIError("CONFLICT", {
2975
+ code: $ERROR_CODES.WEBHOOK_REPLAY_IN_PROGRESS.code,
2976
+ message: `Webhook event ${ctx.params.eventId} is being processed. Retry after its lease expires.`
2977
+ });
2978
+ if (row.status === "pending" && hasLiveLease(row, /* @__PURE__ */ new Date())) throw inProgress;
2979
+ if (!await completeUnchangedWebhookEvent({ context: { adapter } }, row)) throw inProgress;
2798
2980
  if (registry?.subscriptionWebhookSync && !eventId.startsWith("handlers:") && (row.eventType === "INVOICE_COMPLETED" || row.eventType === "SUBSCRIPTION_CYCLE_RENEWED_SUCCESSFULLY")) {
2799
2981
  const subscription = await adapter.findOne({
2800
2982
  model: "subscription",
@@ -2811,7 +2993,6 @@ function buildWebhookEventsEndpoints(adminOptions, registry) {
2811
2993
  });
2812
2994
  }
2813
2995
  }
2814
- await markWebhookEventCompleted({ context: { adapter } }, row.id);
2815
2996
  return ctx.json({ discarded: true, eventId });
2816
2997
  }
2817
2998
  )
@@ -3396,7 +3577,8 @@ var SUBSCRIPTION_MODEL4 = "subscription";
3396
3577
  async function recoverCheckoutUrl(client, row) {
3397
3578
  if (!row.streampayPaymentLinkId) return { kind: "expired" };
3398
3579
  try {
3399
- const url = client.getPaymentUrl(await client.getPaymentLink(row.streampayPaymentLinkId));
3580
+ const link = await client.getPaymentLink(row.streampayPaymentLinkId);
3581
+ const url = link.status === "INACTIVE" ? null : client.getPaymentUrl(link);
3400
3582
  return url ? { kind: "recovered", url } : { kind: "expired" };
3401
3583
  } catch (err) {
3402
3584
  if (readSdkErrorFields(err).status === 404) return { kind: "expired" };
@@ -3477,7 +3659,9 @@ async function resumeOrReserveCheckoutSlot(args) {
3477
3659
  });
3478
3660
  if (!reserved) throw err;
3479
3661
  if (reserved.status !== "incomplete") throw subscriptionAlreadyActiveError();
3480
- if (matchesCheckout(reserved)) {
3662
+ const reservationIsStale = !(reserved.createdAt instanceof Date) || now - reserved.createdAt.getTime() >= UPGRADE_IDEMPOTENCY_WINDOW_MS;
3663
+ let linkExpired = false;
3664
+ if (!reservationIsStale && matchesCheckout(reserved)) {
3481
3665
  let recovery;
3482
3666
  try {
3483
3667
  recovery = await recoverCheckoutUrl(client, reserved);
@@ -3494,10 +3678,10 @@ async function resumeOrReserveCheckoutSlot(args) {
3494
3678
  if (recovery.kind === "recovered") {
3495
3679
  return { kind: "recovered", row: reserved, url: recovery.url };
3496
3680
  }
3681
+ linkExpired = Boolean(reserved.streampayPaymentLinkId);
3497
3682
  }
3498
- const reservationIsStale = !(reserved.createdAt instanceof Date) || now - reserved.createdAt.getTime() >= UPGRADE_IDEMPOTENCY_WINDOW_MS;
3499
- if (!reservationIsStale) throw checkoutInProgressError();
3500
- if (reserved.streampayPaymentLinkId) {
3683
+ if (!reservationIsStale && !linkExpired) throw checkoutInProgressError();
3684
+ if (reservationIsStale && reserved.streampayPaymentLinkId) {
3501
3685
  try {
3502
3686
  await deactivatePaymentLink(client, reserved.streampayPaymentLinkId, log);
3503
3687
  } catch (deactivationError) {
@@ -3517,7 +3701,8 @@ async function resumeOrReserveCheckoutSlot(args) {
3517
3701
  where: [
3518
3702
  { field: "id", value: reserved.id },
3519
3703
  { field: "status", value: "incomplete" },
3520
- { field: "activeSlotKey", value: activeSlotKey }
3704
+ { field: "activeSlotKey", value: activeSlotKey },
3705
+ { field: "streampayPaymentLinkId", value: reserved.streampayPaymentLinkId ?? null }
3521
3706
  ]
3522
3707
  });
3523
3708
  if (!released) throw checkoutInProgressError();
@@ -4994,6 +5179,11 @@ var subscriptionTable = {
4994
5179
  type: "number",
4995
5180
  required: false
4996
5181
  },
5182
+ renewedCycleNumber: {
5183
+ type: "number",
5184
+ required: false,
5185
+ input: false
5186
+ },
4997
5187
  renewalCallbackEventId: {
4998
5188
  type: "string",
4999
5189
  required: false,
@@ -5208,9 +5398,9 @@ function subscriptions(subsOptions) {
5208
5398
  }
5209
5399
  };
5210
5400
  if (dedupeEnabled) {
5211
- registry.replayWebhookEvent = async (ctx, eventId) => {
5401
+ registry.replayWebhookEvent = async (ctx, eventId, replayOptions) => {
5212
5402
  if (eventId.startsWith("handlers:") && registry.replayWebhookHandler) {
5213
- return registry.replayWebhookHandler(ctx, eventId);
5403
+ return registry.replayWebhookHandler(ctx, eventId, replayOptions);
5214
5404
  }
5215
5405
  const syncCtx = {
5216
5406
  context: ctx.context
@@ -5225,23 +5415,29 @@ function subscriptions(subsOptions) {
5225
5415
  message: `Webhook event ${eventId} not found.`
5226
5416
  });
5227
5417
  }
5228
- if (!row.rawPayload) {
5229
- throw new api.APIError("BAD_REQUEST", {
5230
- message: `Webhook event ${eventId} has no rawPayload \u2014 nothing to replay (already completed cleanly?).`
5418
+ if (replayOptions?.dueAttemptCount !== void 0 && !isStillDueWebhookEvent(row, replayOptions.dueAttemptCount, /* @__PURE__ */ new Date())) {
5419
+ throw new api.APIError("CONFLICT", {
5420
+ code: $ERROR_CODES.WEBHOOK_REPLAY_IN_PROGRESS.code,
5421
+ message: `Webhook event ${eventId} is no longer due.`
5231
5422
  });
5232
5423
  }
5424
+ const unreplayable = async (message) => {
5425
+ await parkUnreplayableWebhookEvent(syncCtx, row, message);
5426
+ throw new api.APIError("BAD_REQUEST", { message });
5427
+ };
5428
+ if (!row.rawPayload) {
5429
+ return unreplayable(
5430
+ `Webhook event ${eventId} has no rawPayload \u2014 nothing to replay (already completed cleanly?).`
5431
+ );
5432
+ }
5233
5433
  let parsedPayload;
5234
5434
  try {
5235
5435
  parsedPayload = JSON.parse(row.rawPayload);
5236
5436
  } catch {
5237
- throw new api.APIError("BAD_REQUEST", {
5238
- message: `Webhook event ${eventId} has malformed stored JSON.`
5239
- });
5437
+ return unreplayable(`Webhook event ${eventId} has malformed stored JSON.`);
5240
5438
  }
5241
5439
  if (!isStreamPayWebhookEnvelope(parsedPayload) || !isKnownStreamPayWebhookPayload(parsedPayload)) {
5242
- throw new api.APIError("BAD_REQUEST", {
5243
- message: `Webhook event ${eventId} has an invalid stored payload.`
5244
- });
5440
+ return unreplayable(`Webhook event ${eventId} has an invalid stored payload.`);
5245
5441
  }
5246
5442
  const payload = parsedPayload;
5247
5443
  const plans = await plansRef();
@@ -5256,6 +5452,7 @@ function subscriptions(subsOptions) {
5256
5452
  try {
5257
5453
  await syncWebhookPayload(syncCtx, payload, options.client, plans, subsOptions, {
5258
5454
  dedupe: false,
5455
+ inboxEnabled: true,
5259
5456
  retryOnCallbackError: subsOptions.retryOnCallbackError !== false,
5260
5457
  retryingRenewalCallback: claimed.lastError?.startsWith(
5261
5458
  "Subscription callback onSubscriptionRenewed failed:"
@@ -5472,7 +5669,7 @@ var webhooks = (webhooksOptions) => {
5472
5669
  return (_options, registry) => {
5473
5670
  const { secret, toleranceSeconds, deduplicate = false, ...handlers } = webhooksOptions;
5474
5671
  if (deduplicate && registry) {
5475
- registry.replayWebhookHandler = async (ctx, eventId) => {
5672
+ registry.replayWebhookHandler = async (ctx, eventId, replayOptions) => {
5476
5673
  const syncContext = { context: ctx.context };
5477
5674
  const row = await syncContext.context.adapter.findOne({
5478
5675
  model: WEBHOOK_EVENT_MODEL,
@@ -5480,20 +5677,21 @@ var webhooks = (webhooksOptions) => {
5480
5677
  });
5481
5678
  if (!eventId.startsWith("handlers:") || !row)
5482
5679
  throw new api.APIError("NOT_FOUND", { message: "Webhook callback event not found." });
5483
- if (!row.rawPayload)
5484
- throw new api.APIError("BAD_REQUEST", { message: "Webhook callback has no stored payload." });
5680
+ if (replayOptions?.dueAttemptCount !== void 0 && !isStillDueWebhookEvent(row, replayOptions.dueAttemptCount, /* @__PURE__ */ new Date()))
5681
+ throw new api.APIError("CONFLICT", { message: "Webhook callback is no longer due." });
5682
+ const unreplayable = async (message) => {
5683
+ await parkUnreplayableWebhookEvent(syncContext, row, message);
5684
+ throw new api.APIError("BAD_REQUEST", { message });
5685
+ };
5686
+ if (!row.rawPayload) return unreplayable("Webhook callback has no stored payload.");
5485
5687
  let payload;
5486
5688
  try {
5487
5689
  payload = JSON.parse(row.rawPayload);
5488
5690
  } catch {
5489
- throw new api.APIError("BAD_REQUEST", {
5490
- message: "Stored webhook payload is not valid JSON."
5491
- });
5691
+ return unreplayable("Stored webhook payload is not valid JSON.");
5492
5692
  }
5493
5693
  if (!isStreamPayWebhookEnvelope(payload))
5494
- throw new api.APIError("BAD_REQUEST", {
5495
- message: "Stored webhook payload is not a valid event envelope."
5496
- });
5694
+ return unreplayable("Stored webhook payload is not a valid event envelope.");
5497
5695
  const previousStatus = row.status;
5498
5696
  const claimed = await claimWebhookEventForReplay(syncContext, row);
5499
5697
  if (!claimed?.lockedBy)
@@ -5641,7 +5839,7 @@ var webhooks = (webhooksOptions) => {
5641
5839
  const failed = [];
5642
5840
  for (const row of due) {
5643
5841
  try {
5644
- await replay(ctx, row.eventId);
5842
+ await replay(ctx, row.eventId, { dueAttemptCount: row.attemptCount });
5645
5843
  succeeded.push(row.eventId);
5646
5844
  } catch (err) {
5647
5845
  if (err instanceof api.APIError && err.status === "CONFLICT") continue;
@@ -5782,7 +5980,7 @@ var onUserDelete = (options) => async (user, context) => {
5782
5980
 
5783
5981
  // package.json
5784
5982
  var package_default = {
5785
- version: "3.2.0"};
5983
+ version: "3.3.1"};
5786
5984
 
5787
5985
  // src/version.ts
5788
5986
  var version = package_default.version;