better-auth-streampay 3.2.0 → 3.3.0

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,9 @@ 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 ? { renewedCycleNumber: existing?.currentCycleNumber ?? sub.current_cycle_number ?? null } : {},
763
788
  trialStart: (sub.trial_end ? parseDate(sub.started_at) ?? periodStart : null) ?? existing?.trialStart ?? null,
764
789
  trialEnd: parseDate(sub.trial_end),
765
790
  cancelAtPeriodEnd: Boolean(sub.cancel_at_period_end),
@@ -993,15 +1018,6 @@ function freezePaginationConflict(message) {
993
1018
  message
994
1019
  });
995
1020
  }
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
1021
 
1006
1022
  // src/plugins/subscriptions/sync.ts
1007
1023
  var SUBSCRIPTION_MODEL2 = "subscription";
@@ -1029,6 +1045,9 @@ function isUniqueConstraintError(err) {
1029
1045
  }
1030
1046
  var WEBHOOK_PROCESSING_LEASE_MS = 2 * 60 * 1e3;
1031
1047
  var WEBHOOK_RETRY_DELAYS_MS = [5, 30, 120, 360, 720].map((minutes) => minutes * 60 * 1e3);
1048
+ function hasLiveLease(row, now) {
1049
+ return row.lockedAt instanceof Date && now.getTime() - row.lockedAt.getTime() < WEBHOOK_PROCESSING_LEASE_MS;
1050
+ }
1032
1051
  var WebhookEventInProgressError = class extends Error {
1033
1052
  constructor(eventType) {
1034
1053
  super(`Webhook ${eventType} is already being processed; retry later.`);
@@ -1113,7 +1132,7 @@ async function claimOrAdvanceWebhookEvent(ctx, payload, rawBody, signatureHeader
1113
1132
  );
1114
1133
  return { action: "skip", reason: "dead_letter" };
1115
1134
  }
1116
- if (existing.lockedAt instanceof Date && now.getTime() - existing.lockedAt.getTime() < WEBHOOK_PROCESSING_LEASE_MS) {
1135
+ if (hasLiveLease(existing, now)) {
1117
1136
  logger(ctx).info(
1118
1137
  `webhook ${payload.event_type} (${eventId}) is already being processed \u2014 skipping concurrent delivery.`
1119
1138
  );
@@ -1129,15 +1148,15 @@ async function claimOrAdvanceWebhookEvent(ctx, payload, rawBody, signatureHeader
1129
1148
  lastAttemptAt: now,
1130
1149
  deadLetteredAt: now,
1131
1150
  nextAttemptAt: null,
1132
- rawPayload: rawBody,
1133
- signatureHeader,
1151
+ ...rawBody !== null ? { rawPayload: rawBody, signatureHeader } : {},
1134
1152
  lockedAt: null,
1135
1153
  lockedBy: null
1136
1154
  },
1137
1155
  where: [
1138
1156
  { field: "id", value: existing.id },
1139
1157
  { field: "status", value: "pending" },
1140
- { field: "lockedAt", value: existing.lockedAt ?? null }
1158
+ { field: "lockedAt", value: existing.lockedAt ?? null },
1159
+ { field: "attemptCount", value: existing.attemptCount ?? null }
1141
1160
  ]
1142
1161
  });
1143
1162
  return updated2 ? { action: "dead_letter", row: updated2 } : { action: "skip", reason: "in_progress" };
@@ -1149,19 +1168,21 @@ async function claimOrAdvanceWebhookEvent(ctx, payload, rawBody, signatureHeader
1149
1168
  lastAttemptAt: now,
1150
1169
  nextAttemptAt: null,
1151
1170
  lockedAt: now,
1152
- lockedBy: lockId
1171
+ lockedBy: lockId,
1172
+ ...rawBody !== null ? { rawPayload: rawBody, signatureHeader } : {}
1153
1173
  },
1154
1174
  where: [
1155
1175
  { field: "id", value: existing.id },
1156
1176
  { field: "status", value: "pending" },
1157
- { field: "lockedAt", value: existing.lockedAt ?? null }
1177
+ { field: "lockedAt", value: existing.lockedAt ?? null },
1178
+ { field: "attemptCount", value: existing.attemptCount ?? null }
1158
1179
  ]
1159
1180
  });
1160
1181
  return updated ? { action: "process", row: updated } : { action: "skip", reason: "in_progress" };
1161
1182
  }
1162
1183
  async function claimWebhookEventForReplay(ctx, row) {
1163
1184
  const now = /* @__PURE__ */ new Date();
1164
- if (row.lockedAt instanceof Date && now.getTime() - row.lockedAt.getTime() < WEBHOOK_PROCESSING_LEASE_MS) {
1185
+ if (hasLiveLease(row, now)) {
1165
1186
  return null;
1166
1187
  }
1167
1188
  return ctx.context.adapter.update({
@@ -1179,30 +1200,71 @@ async function claimWebhookEventForReplay(ctx, row) {
1179
1200
  where: [
1180
1201
  { field: "id", value: row.id },
1181
1202
  { field: "status", value: row.status },
1182
- { field: "lockedAt", value: row.lockedAt ?? null }
1203
+ { field: "lockedAt", value: row.lockedAt ?? null },
1204
+ { field: "attemptCount", value: row.attemptCount ?? null }
1183
1205
  ]
1184
1206
  });
1185
1207
  }
1186
- async function markWebhookEventCompleted(ctx, rowId, lockId) {
1208
+ function isStillDueWebhookEvent(row, selectedAttemptCount, now) {
1209
+ const retryDue = row.nextAttemptAt instanceof Date && row.nextAttemptAt <= now;
1210
+ const leaseAbandoned = row.lockedAt instanceof Date && !hasLiveLease(row, now);
1211
+ return row.status === "pending" && row.attemptCount === selectedAttemptCount && (retryDue || leaseAbandoned);
1212
+ }
1213
+ async function parkUnreplayableWebhookEvent(ctx, row, reason) {
1214
+ if (row.status !== "pending" || hasLiveLease(row, /* @__PURE__ */ new Date())) return;
1187
1215
  await ctx.context.adapter.update({
1188
1216
  model: WEBHOOK_EVENT_MODEL,
1189
1217
  update: {
1190
- status: "completed",
1191
- completedAt: /* @__PURE__ */ new Date(),
1192
1218
  nextAttemptAt: null,
1193
1219
  lockedAt: null,
1194
1220
  lockedBy: null,
1195
- rawPayload: null,
1196
- signatureHeader: null,
1197
- lastError: null,
1198
- lastErrorCode: null
1221
+ lastError: reason,
1222
+ lastErrorCode: "UNREPLAYABLE_PAYLOAD"
1199
1223
  },
1224
+ where: [
1225
+ { field: "id", value: row.id },
1226
+ { field: "status", value: "pending" },
1227
+ { field: "lockedAt", value: row.lockedAt ?? null },
1228
+ { field: "attemptCount", value: row.attemptCount ?? null }
1229
+ ]
1230
+ });
1231
+ }
1232
+ function completedWebhookEventFields() {
1233
+ return {
1234
+ status: "completed",
1235
+ completedAt: /* @__PURE__ */ new Date(),
1236
+ nextAttemptAt: null,
1237
+ lockedAt: null,
1238
+ lockedBy: null,
1239
+ rawPayload: null,
1240
+ signatureHeader: null,
1241
+ lastError: null,
1242
+ lastErrorCode: null
1243
+ };
1244
+ }
1245
+ async function markWebhookEventCompleted(ctx, rowId, lockId) {
1246
+ await ctx.context.adapter.update({
1247
+ model: WEBHOOK_EVENT_MODEL,
1248
+ update: completedWebhookEventFields(),
1200
1249
  where: [
1201
1250
  { field: "id", value: rowId },
1202
1251
  ...lockId ? [{ field: "lockedBy", value: lockId }] : []
1203
1252
  ]
1204
1253
  });
1205
1254
  }
1255
+ async function completeUnchangedWebhookEvent(ctx, row) {
1256
+ const updated = await ctx.context.adapter.update({
1257
+ model: WEBHOOK_EVENT_MODEL,
1258
+ update: completedWebhookEventFields(),
1259
+ where: [
1260
+ { field: "id", value: row.id },
1261
+ { field: "status", value: row.status },
1262
+ { field: "lockedAt", value: row.lockedAt ?? null },
1263
+ { field: "attemptCount", value: row.attemptCount ?? null }
1264
+ ]
1265
+ });
1266
+ return updated !== null;
1267
+ }
1206
1268
  async function recordWebhookEventFailure(ctx, rowId, rawBody, signatureHeader, err, lockId, deadLetter = false) {
1207
1269
  const lastError = err instanceof Error ? err.message : String(err);
1208
1270
  const sdkError = readSdkErrorFields(err);
@@ -1321,12 +1383,41 @@ var SubscriptionCorrelationError = class extends Error {
1321
1383
  this.name = "SubscriptionCorrelationError";
1322
1384
  }
1323
1385
  };
1386
+ function providerStateConfirmsEvent(eventType, stream) {
1387
+ switch (eventType) {
1388
+ case "SUBSCRIPTION_CREATED":
1389
+ return true;
1390
+ case "SUBSCRIPTION_ACTIVATED":
1391
+ case "SUBSCRIPTION_UNFREEZE_NOW":
1392
+ return stream.status === "ACTIVE" || stream.status === "TRIALING";
1393
+ case "SUBSCRIPTION_CANCELED":
1394
+ return stream.status === "CANCELED";
1395
+ case "SUBSCRIPTION_INACTIVATED":
1396
+ return stream.status === "INACTIVE";
1397
+ case "SUBSCRIPTION_CANCEL_AT_PERIOD_END":
1398
+ return Boolean(stream.cancel_at_period_end) && !isTerminalSubscriptionStatus(toLocalStatus(stream.status));
1399
+ case "SUBSCRIPTION_FROZEN":
1400
+ case "SUBSCRIPTION_FREEZE_NOW":
1401
+ return stream.status === "FROZEN";
1402
+ case "SUBSCRIPTION_PLAN_CHANGE_SCHEDULED":
1403
+ return Boolean(stream.pending_change);
1404
+ case "SUBSCRIPTION_PLAN_CHANGE_CANCELED":
1405
+ return !stream.pending_change;
1406
+ default:
1407
+ return false;
1408
+ }
1409
+ }
1324
1410
  async function takeSlotFromReservation(ctx, client, slotKey, ownerRowId, streampaySubscriptionId) {
1325
1411
  const holder = await ctx.context.adapter.findOne({
1326
1412
  model: SUBSCRIPTION_MODEL2,
1327
1413
  where: [{ field: "activeSlotKey", value: slotKey }]
1328
1414
  });
1329
1415
  if (!holder || holder.id === ownerRowId) return;
1416
+ if (holder.streampaySubscriptionId === streampaySubscriptionId) {
1417
+ throw new Error(
1418
+ `StreamPay sub=${streampaySubscriptionId} was linked to row=${holder.id} concurrently. Retry delivery.`
1419
+ );
1420
+ }
1330
1421
  if (holder.status !== "incomplete" || holder.streampaySubscriptionId) {
1331
1422
  throw new SubscriptionCorrelationError(
1332
1423
  `StreamPay sub=${streampaySubscriptionId} needs the billing slot held by live row=${holder.id} (${holder.status}). Resolve the duplicate subscription, then replay.`
@@ -1401,7 +1492,8 @@ async function updateReconciledSubscription(ctx, client, existing, projected, st
1401
1492
  { field: "streampaySubscriptionId", value: existing.streampaySubscriptionId ?? null },
1402
1493
  { field: "streampayConsumerId", value: existing.streampayConsumerId ?? null },
1403
1494
  { field: "status", value: existing.status },
1404
- { field: "billingStatus", value: existing.billingStatus }
1495
+ { field: "billingStatus", value: existing.billingStatus },
1496
+ { field: "renewedCycleNumber", value: existing.renewedCycleNumber ?? null }
1405
1497
  ]
1406
1498
  });
1407
1499
  if (!updated) {
@@ -1436,15 +1528,16 @@ async function reconcileFromStreamPay(ctx, payload, client, plans) {
1436
1528
  const eventIsStale = Boolean(
1437
1529
  eventAt && existing?.providerUpdatedAt instanceof Date && eventAt.getTime() < existing.providerUpdatedAt.getTime()
1438
1530
  );
1439
- if (!eventIsStale && payload.event_type === "SUBSCRIPTION_CYCLE_RENEWAL_FAILED" && projected.status === "active") {
1531
+ const eventApplies = !eventIsStale || providerStateConfirmsEvent(payload.event_type, stream);
1532
+ if (eventApplies && payload.event_type === "SUBSCRIPTION_CYCLE_RENEWAL_FAILED" && projected.status === "active") {
1440
1533
  projected.status = "past_due";
1441
1534
  projected.billingStatus = "past_due";
1442
1535
  }
1443
- const schedulesCancellation = !eventIsStale && payload.event_type === "SUBSCRIPTION_CANCEL_AT_PERIOD_END" && Boolean(stream.cancel_at_period_end);
1536
+ const schedulesCancellation = eventApplies && payload.event_type === "SUBSCRIPTION_CANCEL_AT_PERIOD_END" && Boolean(stream.cancel_at_period_end);
1444
1537
  if (schedulesCancellation) {
1445
1538
  projected.cancelAt = parseDate(stream.current_period_end);
1446
1539
  }
1447
- const confirmsCancellation = !eventIsStale && payload.event_type === "SUBSCRIPTION_CANCELED" && projected.status === "canceled";
1540
+ const confirmsCancellation = eventApplies && payload.event_type === "SUBSCRIPTION_CANCELED" && projected.status === "canceled";
1448
1541
  if (confirmsCancellation) {
1449
1542
  projected.activeSlotKey = null;
1450
1543
  }
@@ -1453,17 +1546,13 @@ async function reconcileFromStreamPay(ctx, payload, client, plans) {
1453
1546
  stampCancelScheduled: schedulesCancellation,
1454
1547
  stampCanceled: confirmsCancellation
1455
1548
  });
1549
+ if (schedulesCancellation && eventAt && existing?.cancelAtPeriodEnd && !existing.cancelScheduledAt) {
1550
+ projected.cancelScheduledAt = eventAt;
1551
+ }
1456
1552
  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
- }
1553
+ const slotKey = liveSlotKey(existing, projected);
1554
+ if (slotKey && existing.activeSlotKey !== slotKey) {
1555
+ projected.activeSlotKey = slotKey;
1467
1556
  }
1468
1557
  const updated = await updateReconciledSubscription(
1469
1558
  ctx,
@@ -1472,7 +1561,7 @@ async function reconcileFromStreamPay(ctx, payload, client, plans) {
1472
1561
  projected,
1473
1562
  streampaySubscriptionId
1474
1563
  );
1475
- if (eventIsStale) {
1564
+ if (!eventApplies) {
1476
1565
  logger(ctx).info(
1477
1566
  `webhook ${payload.event_type}: ignored stale lifecycle callback for sub=${streampaySubscriptionId}.`
1478
1567
  );
@@ -1601,7 +1690,8 @@ async function syncWebhookPayload(ctx, payload, client, plans, callbacks, option
1601
1690
  retryOnCallbackError,
1602
1691
  options.retryingRenewalCallback === true || claim.row?.lastError?.startsWith(
1603
1692
  "Subscription callback onSubscriptionRenewed failed:"
1604
- ) === true
1693
+ ) === true,
1694
+ options.inboxEnabled ?? dedupe
1605
1695
  );
1606
1696
  } else {
1607
1697
  const { row, stream } = await reconcileFromStreamPay(ctx, payload, client, plans);
@@ -1633,7 +1723,28 @@ async function syncWebhookPayload(ctx, payload, client, plans, callbacks, option
1633
1723
  throw err;
1634
1724
  }
1635
1725
  }
1636
- async function handleRenewalEvidence(ctx, payload, client, plans, callbacks, retryOnCallbackError, retryingRenewalCallback) {
1726
+ async function releaseLockOfCompletedRenewal(ctx, subscriptionRowId, lockEventId) {
1727
+ const owner = await ctx.context.adapter.findOne({
1728
+ model: WEBHOOK_EVENT_MODEL,
1729
+ where: [{ field: "eventId", value: lockEventId }]
1730
+ });
1731
+ if (owner?.status !== "completed") return false;
1732
+ const released = await ctx.context.adapter.update({
1733
+ model: SUBSCRIPTION_MODEL2,
1734
+ update: { renewalCallbackEventId: null },
1735
+ where: [
1736
+ { field: "id", value: subscriptionRowId },
1737
+ { field: "renewalCallbackEventId", value: lockEventId }
1738
+ ]
1739
+ });
1740
+ if (released) {
1741
+ logger(ctx).warn(
1742
+ `released renewal callback lock of completed event ${lockEventId} for row=${subscriptionRowId}.`
1743
+ );
1744
+ }
1745
+ return released !== null;
1746
+ }
1747
+ async function handleRenewalEvidence(ctx, payload, client, plans, callbacks, retryOnCallbackError, retryingRenewalCallback, inboxEnabled) {
1637
1748
  const invoiceId = payload.data?.invoice?.id ?? payload.entity_id;
1638
1749
  if (!invoiceId) return;
1639
1750
  let subscriptionId = payload.entity_type === "SUBSCRIPTION" ? payload.entity_id : null;
@@ -1665,27 +1776,55 @@ async function handleRenewalEvidence(ctx, payload, client, plans, callbacks, ret
1665
1776
  const eventIsStale = Boolean(
1666
1777
  eventAt && existing.providerUpdatedAt instanceof Date && eventAt.getTime() < existing.providerUpdatedAt.getTime()
1667
1778
  );
1779
+ const evidenceInvoiceId = payload.data?.invoice?.id ?? (payload.entity_type === "INVOICE" ? payload.entity_id : null);
1780
+ const settlesLatestInvoice = stream.latest_invoice?.status === "COMPLETED" && (evidenceInvoiceId === null || stream.latest_invoice.id === evidenceInvoiceId);
1781
+ const evidenceApplies = !eventIsStale || settlesLatestInvoice;
1668
1782
  const projected = {
1669
1783
  ...projectSubscriptionFields(stream, existing),
1670
1784
  ...projectPlanFields(stream, plans),
1671
- ...eventIsStale ? existing.billingStatus === "past_due" && toLocalStatus(stream.status) === "active" ? { status: "past_due", billingStatus: "past_due" } : {} : { billingStatus: "current" }
1785
+ ...evidenceApplies ? { billingStatus: "current" } : existing.billingStatus === "past_due" && toLocalStatus(stream.status) === "active" ? { status: "past_due", billingStatus: "past_due" } : {}
1672
1786
  };
1787
+ const slotKey = liveSlotKey(existing, projected);
1788
+ if (slotKey && existing.activeSlotKey !== slotKey) {
1789
+ projected.activeSlotKey = slotKey;
1790
+ }
1673
1791
  const previousPeriodEnd = existing.periodEnd?.getTime() ?? null;
1674
1792
  const projectedPeriodEnd = projected.periodEnd?.getTime() ?? null;
1675
1793
  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;
1794
+ const renewedCycle = existing.renewedCycleNumber ?? existing.currentCycleNumber ?? null;
1795
+ const projectedCycle = projected.currentCycleNumber ?? null;
1796
+ const tracksCycles = renewedCycle !== null && projectedCycle !== null;
1797
+ const renewalAdvanced = tracksCycles ? projectedCycle > renewedCycle : periodAdvanced;
1677
1798
  const eventId = extractEventId(payload);
1678
- const pendingCallback = existing.renewalCallbackEventId ?? null;
1799
+ let pendingCallback = existing.renewalCallbackEventId ?? null;
1800
+ if (pendingCallback && pendingCallback !== eventId) {
1801
+ const released = inboxEnabled && await releaseLockOfCompletedRenewal(ctx, existing.id, pendingCallback);
1802
+ if (!released) {
1803
+ throw new Error(
1804
+ `Subscription renewal callback ${pendingCallback} is pending; retry delivery.`
1805
+ );
1806
+ }
1807
+ pendingCallback = null;
1808
+ }
1679
1809
  if (!pendingCallback && existing.providerUpdatedAt instanceof Date && projected.providerUpdatedAt instanceof Date && projected.providerUpdatedAt.getTime() < existing.providerUpdatedAt.getTime()) {
1680
1810
  throw new Error(
1681
1811
  `StreamPay returned stale subscription state for sub=${subscriptionId}; retry delivery.`
1682
1812
  );
1683
1813
  }
1684
- if (pendingCallback && pendingCallback !== eventId) {
1685
- throw new Error(`Subscription renewal callback ${pendingCallback} is pending; retry delivery.`);
1814
+ if (!pendingCallback && projected.activeSlotKey && projected.activeSlotKey !== existing.activeSlotKey) {
1815
+ await takeSlotFromReservation(
1816
+ ctx,
1817
+ client,
1818
+ projected.activeSlotKey,
1819
+ existing.id,
1820
+ subscriptionId
1821
+ );
1686
1822
  }
1687
- const deliverCallback = pendingCallback === eventId && pendingCallback !== null || !eventIsStale && (periodAdvanced || cycleAdvanced || retryingRenewalCallback);
1823
+ const deliverCallback = pendingCallback === eventId && pendingCallback !== null || evidenceApplies && (renewalAdvanced || retryingRenewalCallback);
1688
1824
  const callbackOwner = deliverCallback && callbacks.onSubscriptionRenewed ? eventId : null;
1825
+ if (deliverCallback && renewalAdvanced && projectedCycle !== null) {
1826
+ projected.renewedCycleNumber = projectedCycle;
1827
+ }
1689
1828
  const updated = await ctx.context.adapter.update({
1690
1829
  model: SUBSCRIPTION_MODEL2,
1691
1830
  // Recovery must retain the pending cycle, even if Stream has already advanced again.
@@ -1694,6 +1833,7 @@ async function handleRenewalEvidence(ctx, payload, client, plans, callbacks, ret
1694
1833
  { field: "id", value: existing.id },
1695
1834
  { field: "periodEnd", value: existing.periodEnd ?? null },
1696
1835
  { field: "currentCycleNumber", value: existing.currentCycleNumber ?? null },
1836
+ { field: "renewedCycleNumber", value: existing.renewedCycleNumber ?? null },
1697
1837
  { field: "renewalCallbackEventId", value: pendingCallback },
1698
1838
  { field: "providerUpdatedAt", value: existing.providerUpdatedAt ?? null },
1699
1839
  { field: "status", value: existing.status },
@@ -1706,8 +1846,8 @@ async function handleRenewalEvidence(ctx, payload, client, plans, callbacks, ret
1706
1846
  }
1707
1847
  const latest = await findSubscriptionByStreampayId(ctx, subscriptionId);
1708
1848
  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;
1849
+ const renewalClaimedElsewhere = renewalAdvanced && (tracksCycles ? (latest?.renewedCycleNumber ?? 0) >= projectedCycle : (latest?.periodEnd?.getTime() ?? 0) >= (projectedPeriodEnd ?? 0));
1850
+ if (anotherCallbackOwner && anotherCallbackOwner !== eventId && renewalClaimedElsewhere) return;
1711
1851
  throw new Error(`Subscription changed during renewal reconciliation; retry delivery.`);
1712
1852
  }
1713
1853
  const row = updated;
@@ -2795,6 +2935,12 @@ function buildWebhookEventsEndpoints(adminOptions, registry) {
2795
2935
  message: `Webhook event ${ctx.params.eventId} not found.`
2796
2936
  });
2797
2937
  }
2938
+ const inProgress = new api.APIError("CONFLICT", {
2939
+ code: $ERROR_CODES.WEBHOOK_REPLAY_IN_PROGRESS.code,
2940
+ message: `Webhook event ${ctx.params.eventId} is being processed. Retry after its lease expires.`
2941
+ });
2942
+ if (row.status === "pending" && hasLiveLease(row, /* @__PURE__ */ new Date())) throw inProgress;
2943
+ if (!await completeUnchangedWebhookEvent({ context: { adapter } }, row)) throw inProgress;
2798
2944
  if (registry?.subscriptionWebhookSync && !eventId.startsWith("handlers:") && (row.eventType === "INVOICE_COMPLETED" || row.eventType === "SUBSCRIPTION_CYCLE_RENEWED_SUCCESSFULLY")) {
2799
2945
  const subscription = await adapter.findOne({
2800
2946
  model: "subscription",
@@ -2811,7 +2957,6 @@ function buildWebhookEventsEndpoints(adminOptions, registry) {
2811
2957
  });
2812
2958
  }
2813
2959
  }
2814
- await markWebhookEventCompleted({ context: { adapter } }, row.id);
2815
2960
  return ctx.json({ discarded: true, eventId });
2816
2961
  }
2817
2962
  )
@@ -3396,7 +3541,8 @@ var SUBSCRIPTION_MODEL4 = "subscription";
3396
3541
  async function recoverCheckoutUrl(client, row) {
3397
3542
  if (!row.streampayPaymentLinkId) return { kind: "expired" };
3398
3543
  try {
3399
- const url = client.getPaymentUrl(await client.getPaymentLink(row.streampayPaymentLinkId));
3544
+ const link = await client.getPaymentLink(row.streampayPaymentLinkId);
3545
+ const url = link.status === "INACTIVE" ? null : client.getPaymentUrl(link);
3400
3546
  return url ? { kind: "recovered", url } : { kind: "expired" };
3401
3547
  } catch (err) {
3402
3548
  if (readSdkErrorFields(err).status === 404) return { kind: "expired" };
@@ -3477,7 +3623,9 @@ async function resumeOrReserveCheckoutSlot(args) {
3477
3623
  });
3478
3624
  if (!reserved) throw err;
3479
3625
  if (reserved.status !== "incomplete") throw subscriptionAlreadyActiveError();
3480
- if (matchesCheckout(reserved)) {
3626
+ const reservationIsStale = !(reserved.createdAt instanceof Date) || now - reserved.createdAt.getTime() >= UPGRADE_IDEMPOTENCY_WINDOW_MS;
3627
+ let linkExpired = false;
3628
+ if (!reservationIsStale && matchesCheckout(reserved)) {
3481
3629
  let recovery;
3482
3630
  try {
3483
3631
  recovery = await recoverCheckoutUrl(client, reserved);
@@ -3494,10 +3642,10 @@ async function resumeOrReserveCheckoutSlot(args) {
3494
3642
  if (recovery.kind === "recovered") {
3495
3643
  return { kind: "recovered", row: reserved, url: recovery.url };
3496
3644
  }
3645
+ linkExpired = Boolean(reserved.streampayPaymentLinkId);
3497
3646
  }
3498
- const reservationIsStale = !(reserved.createdAt instanceof Date) || now - reserved.createdAt.getTime() >= UPGRADE_IDEMPOTENCY_WINDOW_MS;
3499
- if (!reservationIsStale) throw checkoutInProgressError();
3500
- if (reserved.streampayPaymentLinkId) {
3647
+ if (!reservationIsStale && !linkExpired) throw checkoutInProgressError();
3648
+ if (reservationIsStale && reserved.streampayPaymentLinkId) {
3501
3649
  try {
3502
3650
  await deactivatePaymentLink(client, reserved.streampayPaymentLinkId, log);
3503
3651
  } catch (deactivationError) {
@@ -3517,7 +3665,8 @@ async function resumeOrReserveCheckoutSlot(args) {
3517
3665
  where: [
3518
3666
  { field: "id", value: reserved.id },
3519
3667
  { field: "status", value: "incomplete" },
3520
- { field: "activeSlotKey", value: activeSlotKey }
3668
+ { field: "activeSlotKey", value: activeSlotKey },
3669
+ { field: "streampayPaymentLinkId", value: reserved.streampayPaymentLinkId ?? null }
3521
3670
  ]
3522
3671
  });
3523
3672
  if (!released) throw checkoutInProgressError();
@@ -4994,6 +5143,11 @@ var subscriptionTable = {
4994
5143
  type: "number",
4995
5144
  required: false
4996
5145
  },
5146
+ renewedCycleNumber: {
5147
+ type: "number",
5148
+ required: false,
5149
+ input: false
5150
+ },
4997
5151
  renewalCallbackEventId: {
4998
5152
  type: "string",
4999
5153
  required: false,
@@ -5208,9 +5362,9 @@ function subscriptions(subsOptions) {
5208
5362
  }
5209
5363
  };
5210
5364
  if (dedupeEnabled) {
5211
- registry.replayWebhookEvent = async (ctx, eventId) => {
5365
+ registry.replayWebhookEvent = async (ctx, eventId, replayOptions) => {
5212
5366
  if (eventId.startsWith("handlers:") && registry.replayWebhookHandler) {
5213
- return registry.replayWebhookHandler(ctx, eventId);
5367
+ return registry.replayWebhookHandler(ctx, eventId, replayOptions);
5214
5368
  }
5215
5369
  const syncCtx = {
5216
5370
  context: ctx.context
@@ -5225,23 +5379,29 @@ function subscriptions(subsOptions) {
5225
5379
  message: `Webhook event ${eventId} not found.`
5226
5380
  });
5227
5381
  }
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?).`
5382
+ if (replayOptions?.dueAttemptCount !== void 0 && !isStillDueWebhookEvent(row, replayOptions.dueAttemptCount, /* @__PURE__ */ new Date())) {
5383
+ throw new api.APIError("CONFLICT", {
5384
+ code: $ERROR_CODES.WEBHOOK_REPLAY_IN_PROGRESS.code,
5385
+ message: `Webhook event ${eventId} is no longer due.`
5231
5386
  });
5232
5387
  }
5388
+ const unreplayable = async (message) => {
5389
+ await parkUnreplayableWebhookEvent(syncCtx, row, message);
5390
+ throw new api.APIError("BAD_REQUEST", { message });
5391
+ };
5392
+ if (!row.rawPayload) {
5393
+ return unreplayable(
5394
+ `Webhook event ${eventId} has no rawPayload \u2014 nothing to replay (already completed cleanly?).`
5395
+ );
5396
+ }
5233
5397
  let parsedPayload;
5234
5398
  try {
5235
5399
  parsedPayload = JSON.parse(row.rawPayload);
5236
5400
  } catch {
5237
- throw new api.APIError("BAD_REQUEST", {
5238
- message: `Webhook event ${eventId} has malformed stored JSON.`
5239
- });
5401
+ return unreplayable(`Webhook event ${eventId} has malformed stored JSON.`);
5240
5402
  }
5241
5403
  if (!isStreamPayWebhookEnvelope(parsedPayload) || !isKnownStreamPayWebhookPayload(parsedPayload)) {
5242
- throw new api.APIError("BAD_REQUEST", {
5243
- message: `Webhook event ${eventId} has an invalid stored payload.`
5244
- });
5404
+ return unreplayable(`Webhook event ${eventId} has an invalid stored payload.`);
5245
5405
  }
5246
5406
  const payload = parsedPayload;
5247
5407
  const plans = await plansRef();
@@ -5256,6 +5416,7 @@ function subscriptions(subsOptions) {
5256
5416
  try {
5257
5417
  await syncWebhookPayload(syncCtx, payload, options.client, plans, subsOptions, {
5258
5418
  dedupe: false,
5419
+ inboxEnabled: true,
5259
5420
  retryOnCallbackError: subsOptions.retryOnCallbackError !== false,
5260
5421
  retryingRenewalCallback: claimed.lastError?.startsWith(
5261
5422
  "Subscription callback onSubscriptionRenewed failed:"
@@ -5472,7 +5633,7 @@ var webhooks = (webhooksOptions) => {
5472
5633
  return (_options, registry) => {
5473
5634
  const { secret, toleranceSeconds, deduplicate = false, ...handlers } = webhooksOptions;
5474
5635
  if (deduplicate && registry) {
5475
- registry.replayWebhookHandler = async (ctx, eventId) => {
5636
+ registry.replayWebhookHandler = async (ctx, eventId, replayOptions) => {
5476
5637
  const syncContext = { context: ctx.context };
5477
5638
  const row = await syncContext.context.adapter.findOne({
5478
5639
  model: WEBHOOK_EVENT_MODEL,
@@ -5480,20 +5641,21 @@ var webhooks = (webhooksOptions) => {
5480
5641
  });
5481
5642
  if (!eventId.startsWith("handlers:") || !row)
5482
5643
  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." });
5644
+ if (replayOptions?.dueAttemptCount !== void 0 && !isStillDueWebhookEvent(row, replayOptions.dueAttemptCount, /* @__PURE__ */ new Date()))
5645
+ throw new api.APIError("CONFLICT", { message: "Webhook callback is no longer due." });
5646
+ const unreplayable = async (message) => {
5647
+ await parkUnreplayableWebhookEvent(syncContext, row, message);
5648
+ throw new api.APIError("BAD_REQUEST", { message });
5649
+ };
5650
+ if (!row.rawPayload) return unreplayable("Webhook callback has no stored payload.");
5485
5651
  let payload;
5486
5652
  try {
5487
5653
  payload = JSON.parse(row.rawPayload);
5488
5654
  } catch {
5489
- throw new api.APIError("BAD_REQUEST", {
5490
- message: "Stored webhook payload is not valid JSON."
5491
- });
5655
+ return unreplayable("Stored webhook payload is not valid JSON.");
5492
5656
  }
5493
5657
  if (!isStreamPayWebhookEnvelope(payload))
5494
- throw new api.APIError("BAD_REQUEST", {
5495
- message: "Stored webhook payload is not a valid event envelope."
5496
- });
5658
+ return unreplayable("Stored webhook payload is not a valid event envelope.");
5497
5659
  const previousStatus = row.status;
5498
5660
  const claimed = await claimWebhookEventForReplay(syncContext, row);
5499
5661
  if (!claimed?.lockedBy)
@@ -5641,7 +5803,7 @@ var webhooks = (webhooksOptions) => {
5641
5803
  const failed = [];
5642
5804
  for (const row of due) {
5643
5805
  try {
5644
- await replay(ctx, row.eventId);
5806
+ await replay(ctx, row.eventId, { dueAttemptCount: row.attemptCount });
5645
5807
  succeeded.push(row.eventId);
5646
5808
  } catch (err) {
5647
5809
  if (err instanceof api.APIError && err.status === "CONFLICT") continue;
@@ -5782,7 +5944,7 @@ var onUserDelete = (options) => async (user, context) => {
5782
5944
 
5783
5945
  // package.json
5784
5946
  var package_default = {
5785
- version: "3.2.0"};
5947
+ version: "3.3.0"};
5786
5948
 
5787
5949
  // src/version.ts
5788
5950
  var version = package_default.version;