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.js CHANGED
@@ -656,6 +656,15 @@ function isTerminalSubscriptionStatus(status) {
656
656
  function isCheckoutSuccessStatus(status) {
657
657
  return status !== void 0 && CHECKOUT_SUCCESS_STATUSES.has(status);
658
658
  }
659
+ function subscriptionSlotKey(referenceType, referenceId, group) {
660
+ const tuple = JSON.stringify([referenceType, referenceId, group ?? null]);
661
+ return `sp_slot_v1_${createHash("sha256").update(tuple).digest("hex")}`;
662
+ }
663
+ var UPGRADE_IDEMPOTENCY_WINDOW_MS = 15 * 60 * 1e3;
664
+ var PLAN_NAME_METADATA_KEY = "streampay_plugin_plan_name";
665
+ var REFERENCE_ID_METADATA_KEY = "streampay_plugin_reference_id";
666
+ var REFERENCE_TYPE_METADATA_KEY = "streampay_plugin_reference_type";
667
+ var SUBSCRIPTION_ROW_ID_METADATA_KEY = "streampay_plugin_subscription_row_id";
659
668
 
660
669
  // src/plugins/subscriptions/reconcile.ts
661
670
  var SUBSCRIPTION_MODEL = "subscription";
@@ -677,25 +686,38 @@ function reconcileProjectionAgainstExisting(existing, projection, options = {})
677
686
  function projectSubscriptionAgainstExisting(existing, stream) {
678
687
  return reconcileProjectionAgainstExisting(existing, projectSubscriptionFields(stream, existing));
679
688
  }
689
+ function liveSlotKey(existing, projected) {
690
+ if (isTerminalSubscriptionStatus(projected.status ?? existing.status)) return null;
691
+ return subscriptionSlotKey(
692
+ existing.referenceType ?? "user",
693
+ existing.referenceId,
694
+ projected.group === void 0 ? existing.group : projected.group
695
+ );
696
+ }
680
697
  async function persistSubscriptionProjection(adapter, existing, projection, log, source) {
681
698
  const stale = existing.providerUpdatedAt instanceof Date && projection.providerUpdatedAt instanceof Date && projection.providerUpdatedAt.getTime() < existing.providerUpdatedAt.getTime();
682
- if (!stale) {
683
- const updated = await adapter.update({
684
- model: SUBSCRIPTION_MODEL,
685
- update: projection,
686
- where: [
687
- { field: "id", value: existing.id },
688
- { field: "providerUpdatedAt", value: existing.providerUpdatedAt ?? null },
689
- { field: "streampaySubscriptionId", value: existing.streampaySubscriptionId ?? null },
690
- { field: "streampayConsumerId", value: existing.streampayConsumerId ?? null },
691
- { field: "status", value: existing.status },
692
- { field: "billingStatus", value: existing.billingStatus }
693
- ]
694
- });
695
- if (updated) return updated;
696
- }
699
+ const slotKey = liveSlotKey(existing, projection);
700
+ const movesSlot = slotKey !== null && existing.activeSlotKey !== slotKey;
701
+ const slotHolder = movesSlot ? await adapter.findOne({
702
+ model: SUBSCRIPTION_MODEL,
703
+ where: [{ field: "activeSlotKey", value: slotKey }]
704
+ }) : null;
705
+ const updated = stale || slotHolder ? null : await adapter.update({
706
+ model: SUBSCRIPTION_MODEL,
707
+ update: movesSlot ? { ...projection, activeSlotKey: slotKey } : projection,
708
+ where: [
709
+ { field: "id", value: existing.id },
710
+ { field: "providerUpdatedAt", value: existing.providerUpdatedAt ?? null },
711
+ { field: "streampaySubscriptionId", value: existing.streampaySubscriptionId ?? null },
712
+ { field: "streampayConsumerId", value: existing.streampayConsumerId ?? null },
713
+ { field: "status", value: existing.status },
714
+ { field: "billingStatus", value: existing.billingStatus },
715
+ { field: "renewedCycleNumber", value: existing.renewedCycleNumber ?? null }
716
+ ]
717
+ });
718
+ if (updated) return updated;
697
719
  log.warn(
698
- `${source}: retained newer local subscription state for row=${existing.id}. The provider action is not rolled back.`
720
+ 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.`
699
721
  );
700
722
  return adapter.findOne({
701
723
  model: SUBSCRIPTION_MODEL,
@@ -758,6 +780,9 @@ function projectSubscriptionFields(sub, existing) {
758
780
  periodStart,
759
781
  periodEnd,
760
782
  currentCycleNumber: sub.current_cycle_number ?? null,
783
+ // Only renewal evidence advances the baseline. Other writers only initialize it, so they can
784
+ // neither absorb a renewal nor roll back one that was just delivered.
785
+ ...existing?.renewedCycleNumber == null ? { renewedCycleNumber: existing?.currentCycleNumber ?? sub.current_cycle_number ?? null } : {},
761
786
  trialStart: (sub.trial_end ? parseDate(sub.started_at) ?? periodStart : null) ?? existing?.trialStart ?? null,
762
787
  trialEnd: parseDate(sub.trial_end),
763
788
  cancelAtPeriodEnd: Boolean(sub.cancel_at_period_end),
@@ -991,15 +1016,6 @@ function freezePaginationConflict(message) {
991
1016
  message
992
1017
  });
993
1018
  }
994
- function subscriptionSlotKey(referenceType, referenceId, group) {
995
- const tuple = JSON.stringify([referenceType, referenceId, group ?? null]);
996
- return `sp_slot_v1_${createHash("sha256").update(tuple).digest("hex")}`;
997
- }
998
- var UPGRADE_IDEMPOTENCY_WINDOW_MS = 15 * 60 * 1e3;
999
- var PLAN_NAME_METADATA_KEY = "streampay_plugin_plan_name";
1000
- var REFERENCE_ID_METADATA_KEY = "streampay_plugin_reference_id";
1001
- var REFERENCE_TYPE_METADATA_KEY = "streampay_plugin_reference_type";
1002
- var SUBSCRIPTION_ROW_ID_METADATA_KEY = "streampay_plugin_subscription_row_id";
1003
1019
 
1004
1020
  // src/plugins/subscriptions/sync.ts
1005
1021
  var SUBSCRIPTION_MODEL2 = "subscription";
@@ -1027,6 +1043,9 @@ function isUniqueConstraintError(err) {
1027
1043
  }
1028
1044
  var WEBHOOK_PROCESSING_LEASE_MS = 2 * 60 * 1e3;
1029
1045
  var WEBHOOK_RETRY_DELAYS_MS = [5, 30, 120, 360, 720].map((minutes) => minutes * 60 * 1e3);
1046
+ function hasLiveLease(row, now) {
1047
+ return row.lockedAt instanceof Date && now.getTime() - row.lockedAt.getTime() < WEBHOOK_PROCESSING_LEASE_MS;
1048
+ }
1030
1049
  var WebhookEventInProgressError = class extends Error {
1031
1050
  constructor(eventType) {
1032
1051
  super(`Webhook ${eventType} is already being processed; retry later.`);
@@ -1111,7 +1130,7 @@ async function claimOrAdvanceWebhookEvent(ctx, payload, rawBody, signatureHeader
1111
1130
  );
1112
1131
  return { action: "skip", reason: "dead_letter" };
1113
1132
  }
1114
- if (existing.lockedAt instanceof Date && now.getTime() - existing.lockedAt.getTime() < WEBHOOK_PROCESSING_LEASE_MS) {
1133
+ if (hasLiveLease(existing, now)) {
1115
1134
  logger(ctx).info(
1116
1135
  `webhook ${payload.event_type} (${eventId}) is already being processed \u2014 skipping concurrent delivery.`
1117
1136
  );
@@ -1127,15 +1146,15 @@ async function claimOrAdvanceWebhookEvent(ctx, payload, rawBody, signatureHeader
1127
1146
  lastAttemptAt: now,
1128
1147
  deadLetteredAt: now,
1129
1148
  nextAttemptAt: null,
1130
- rawPayload: rawBody,
1131
- signatureHeader,
1149
+ ...rawBody !== null ? { rawPayload: rawBody, signatureHeader } : {},
1132
1150
  lockedAt: null,
1133
1151
  lockedBy: null
1134
1152
  },
1135
1153
  where: [
1136
1154
  { field: "id", value: existing.id },
1137
1155
  { field: "status", value: "pending" },
1138
- { field: "lockedAt", value: existing.lockedAt ?? null }
1156
+ { field: "lockedAt", value: existing.lockedAt ?? null },
1157
+ { field: "attemptCount", value: existing.attemptCount ?? null }
1139
1158
  ]
1140
1159
  });
1141
1160
  return updated2 ? { action: "dead_letter", row: updated2 } : { action: "skip", reason: "in_progress" };
@@ -1147,19 +1166,21 @@ async function claimOrAdvanceWebhookEvent(ctx, payload, rawBody, signatureHeader
1147
1166
  lastAttemptAt: now,
1148
1167
  nextAttemptAt: null,
1149
1168
  lockedAt: now,
1150
- lockedBy: lockId
1169
+ lockedBy: lockId,
1170
+ ...rawBody !== null ? { rawPayload: rawBody, signatureHeader } : {}
1151
1171
  },
1152
1172
  where: [
1153
1173
  { field: "id", value: existing.id },
1154
1174
  { field: "status", value: "pending" },
1155
- { field: "lockedAt", value: existing.lockedAt ?? null }
1175
+ { field: "lockedAt", value: existing.lockedAt ?? null },
1176
+ { field: "attemptCount", value: existing.attemptCount ?? null }
1156
1177
  ]
1157
1178
  });
1158
1179
  return updated ? { action: "process", row: updated } : { action: "skip", reason: "in_progress" };
1159
1180
  }
1160
1181
  async function claimWebhookEventForReplay(ctx, row) {
1161
1182
  const now = /* @__PURE__ */ new Date();
1162
- if (row.lockedAt instanceof Date && now.getTime() - row.lockedAt.getTime() < WEBHOOK_PROCESSING_LEASE_MS) {
1183
+ if (hasLiveLease(row, now)) {
1163
1184
  return null;
1164
1185
  }
1165
1186
  return ctx.context.adapter.update({
@@ -1177,30 +1198,71 @@ async function claimWebhookEventForReplay(ctx, row) {
1177
1198
  where: [
1178
1199
  { field: "id", value: row.id },
1179
1200
  { field: "status", value: row.status },
1180
- { field: "lockedAt", value: row.lockedAt ?? null }
1201
+ { field: "lockedAt", value: row.lockedAt ?? null },
1202
+ { field: "attemptCount", value: row.attemptCount ?? null }
1181
1203
  ]
1182
1204
  });
1183
1205
  }
1184
- async function markWebhookEventCompleted(ctx, rowId, lockId) {
1206
+ function isStillDueWebhookEvent(row, selectedAttemptCount, now) {
1207
+ const retryDue = row.nextAttemptAt instanceof Date && row.nextAttemptAt <= now;
1208
+ const leaseAbandoned = row.lockedAt instanceof Date && !hasLiveLease(row, now);
1209
+ return row.status === "pending" && row.attemptCount === selectedAttemptCount && (retryDue || leaseAbandoned);
1210
+ }
1211
+ async function parkUnreplayableWebhookEvent(ctx, row, reason) {
1212
+ if (row.status !== "pending" || hasLiveLease(row, /* @__PURE__ */ new Date())) return;
1185
1213
  await ctx.context.adapter.update({
1186
1214
  model: WEBHOOK_EVENT_MODEL,
1187
1215
  update: {
1188
- status: "completed",
1189
- completedAt: /* @__PURE__ */ new Date(),
1190
1216
  nextAttemptAt: null,
1191
1217
  lockedAt: null,
1192
1218
  lockedBy: null,
1193
- rawPayload: null,
1194
- signatureHeader: null,
1195
- lastError: null,
1196
- lastErrorCode: null
1219
+ lastError: reason,
1220
+ lastErrorCode: "UNREPLAYABLE_PAYLOAD"
1197
1221
  },
1222
+ where: [
1223
+ { field: "id", value: row.id },
1224
+ { field: "status", value: "pending" },
1225
+ { field: "lockedAt", value: row.lockedAt ?? null },
1226
+ { field: "attemptCount", value: row.attemptCount ?? null }
1227
+ ]
1228
+ });
1229
+ }
1230
+ function completedWebhookEventFields() {
1231
+ return {
1232
+ status: "completed",
1233
+ completedAt: /* @__PURE__ */ new Date(),
1234
+ nextAttemptAt: null,
1235
+ lockedAt: null,
1236
+ lockedBy: null,
1237
+ rawPayload: null,
1238
+ signatureHeader: null,
1239
+ lastError: null,
1240
+ lastErrorCode: null
1241
+ };
1242
+ }
1243
+ async function markWebhookEventCompleted(ctx, rowId, lockId) {
1244
+ await ctx.context.adapter.update({
1245
+ model: WEBHOOK_EVENT_MODEL,
1246
+ update: completedWebhookEventFields(),
1198
1247
  where: [
1199
1248
  { field: "id", value: rowId },
1200
1249
  ...lockId ? [{ field: "lockedBy", value: lockId }] : []
1201
1250
  ]
1202
1251
  });
1203
1252
  }
1253
+ async function completeUnchangedWebhookEvent(ctx, row) {
1254
+ const updated = await ctx.context.adapter.update({
1255
+ model: WEBHOOK_EVENT_MODEL,
1256
+ update: completedWebhookEventFields(),
1257
+ where: [
1258
+ { field: "id", value: row.id },
1259
+ { field: "status", value: row.status },
1260
+ { field: "lockedAt", value: row.lockedAt ?? null },
1261
+ { field: "attemptCount", value: row.attemptCount ?? null }
1262
+ ]
1263
+ });
1264
+ return updated !== null;
1265
+ }
1204
1266
  async function recordWebhookEventFailure(ctx, rowId, rawBody, signatureHeader, err, lockId, deadLetter = false) {
1205
1267
  const lastError = err instanceof Error ? err.message : String(err);
1206
1268
  const sdkError = readSdkErrorFields(err);
@@ -1319,12 +1381,41 @@ var SubscriptionCorrelationError = class extends Error {
1319
1381
  this.name = "SubscriptionCorrelationError";
1320
1382
  }
1321
1383
  };
1384
+ function providerStateConfirmsEvent(eventType, stream) {
1385
+ switch (eventType) {
1386
+ case "SUBSCRIPTION_CREATED":
1387
+ return true;
1388
+ case "SUBSCRIPTION_ACTIVATED":
1389
+ case "SUBSCRIPTION_UNFREEZE_NOW":
1390
+ return stream.status === "ACTIVE" || stream.status === "TRIALING";
1391
+ case "SUBSCRIPTION_CANCELED":
1392
+ return stream.status === "CANCELED";
1393
+ case "SUBSCRIPTION_INACTIVATED":
1394
+ return stream.status === "INACTIVE";
1395
+ case "SUBSCRIPTION_CANCEL_AT_PERIOD_END":
1396
+ return Boolean(stream.cancel_at_period_end) && !isTerminalSubscriptionStatus(toLocalStatus(stream.status));
1397
+ case "SUBSCRIPTION_FROZEN":
1398
+ case "SUBSCRIPTION_FREEZE_NOW":
1399
+ return stream.status === "FROZEN";
1400
+ case "SUBSCRIPTION_PLAN_CHANGE_SCHEDULED":
1401
+ return Boolean(stream.pending_change);
1402
+ case "SUBSCRIPTION_PLAN_CHANGE_CANCELED":
1403
+ return !stream.pending_change;
1404
+ default:
1405
+ return false;
1406
+ }
1407
+ }
1322
1408
  async function takeSlotFromReservation(ctx, client, slotKey, ownerRowId, streampaySubscriptionId) {
1323
1409
  const holder = await ctx.context.adapter.findOne({
1324
1410
  model: SUBSCRIPTION_MODEL2,
1325
1411
  where: [{ field: "activeSlotKey", value: slotKey }]
1326
1412
  });
1327
1413
  if (!holder || holder.id === ownerRowId) return;
1414
+ if (holder.streampaySubscriptionId === streampaySubscriptionId) {
1415
+ throw new Error(
1416
+ `StreamPay sub=${streampaySubscriptionId} was linked to row=${holder.id} concurrently. Retry delivery.`
1417
+ );
1418
+ }
1328
1419
  if (holder.status !== "incomplete" || holder.streampaySubscriptionId) {
1329
1420
  throw new SubscriptionCorrelationError(
1330
1421
  `StreamPay sub=${streampaySubscriptionId} needs the billing slot held by live row=${holder.id} (${holder.status}). Resolve the duplicate subscription, then replay.`
@@ -1399,7 +1490,8 @@ async function updateReconciledSubscription(ctx, client, existing, projected, st
1399
1490
  { field: "streampaySubscriptionId", value: existing.streampaySubscriptionId ?? null },
1400
1491
  { field: "streampayConsumerId", value: existing.streampayConsumerId ?? null },
1401
1492
  { field: "status", value: existing.status },
1402
- { field: "billingStatus", value: existing.billingStatus }
1493
+ { field: "billingStatus", value: existing.billingStatus },
1494
+ { field: "renewedCycleNumber", value: existing.renewedCycleNumber ?? null }
1403
1495
  ]
1404
1496
  });
1405
1497
  if (!updated) {
@@ -1434,15 +1526,16 @@ async function reconcileFromStreamPay(ctx, payload, client, plans) {
1434
1526
  const eventIsStale = Boolean(
1435
1527
  eventAt && existing?.providerUpdatedAt instanceof Date && eventAt.getTime() < existing.providerUpdatedAt.getTime()
1436
1528
  );
1437
- if (!eventIsStale && payload.event_type === "SUBSCRIPTION_CYCLE_RENEWAL_FAILED" && projected.status === "active") {
1529
+ const eventApplies = !eventIsStale || providerStateConfirmsEvent(payload.event_type, stream);
1530
+ if (eventApplies && payload.event_type === "SUBSCRIPTION_CYCLE_RENEWAL_FAILED" && projected.status === "active") {
1438
1531
  projected.status = "past_due";
1439
1532
  projected.billingStatus = "past_due";
1440
1533
  }
1441
- const schedulesCancellation = !eventIsStale && payload.event_type === "SUBSCRIPTION_CANCEL_AT_PERIOD_END" && Boolean(stream.cancel_at_period_end);
1534
+ const schedulesCancellation = eventApplies && payload.event_type === "SUBSCRIPTION_CANCEL_AT_PERIOD_END" && Boolean(stream.cancel_at_period_end);
1442
1535
  if (schedulesCancellation) {
1443
1536
  projected.cancelAt = parseDate(stream.current_period_end);
1444
1537
  }
1445
- const confirmsCancellation = !eventIsStale && payload.event_type === "SUBSCRIPTION_CANCELED" && projected.status === "canceled";
1538
+ const confirmsCancellation = eventApplies && payload.event_type === "SUBSCRIPTION_CANCELED" && projected.status === "canceled";
1446
1539
  if (confirmsCancellation) {
1447
1540
  projected.activeSlotKey = null;
1448
1541
  }
@@ -1451,17 +1544,13 @@ async function reconcileFromStreamPay(ctx, payload, client, plans) {
1451
1544
  stampCancelScheduled: schedulesCancellation,
1452
1545
  stampCanceled: confirmsCancellation
1453
1546
  });
1547
+ if (schedulesCancellation && eventAt && existing?.cancelAtPeriodEnd && !existing.cancelScheduledAt) {
1548
+ projected.cancelScheduledAt = eventAt;
1549
+ }
1454
1550
  if (existing) {
1455
- const projectedStatus = projected.status ?? existing.status;
1456
- if (!isTerminalSubscriptionStatus(projectedStatus)) {
1457
- const desiredSlotKey = subscriptionSlotKey(
1458
- existing.referenceType ?? "user",
1459
- existing.referenceId,
1460
- projected.group === void 0 ? existing.group : projected.group
1461
- );
1462
- if (existing.activeSlotKey !== desiredSlotKey) {
1463
- projected.activeSlotKey = desiredSlotKey;
1464
- }
1551
+ const slotKey = liveSlotKey(existing, projected);
1552
+ if (slotKey && existing.activeSlotKey !== slotKey) {
1553
+ projected.activeSlotKey = slotKey;
1465
1554
  }
1466
1555
  const updated = await updateReconciledSubscription(
1467
1556
  ctx,
@@ -1470,7 +1559,7 @@ async function reconcileFromStreamPay(ctx, payload, client, plans) {
1470
1559
  projected,
1471
1560
  streampaySubscriptionId
1472
1561
  );
1473
- if (eventIsStale) {
1562
+ if (!eventApplies) {
1474
1563
  logger(ctx).info(
1475
1564
  `webhook ${payload.event_type}: ignored stale lifecycle callback for sub=${streampaySubscriptionId}.`
1476
1565
  );
@@ -1599,7 +1688,8 @@ async function syncWebhookPayload(ctx, payload, client, plans, callbacks, option
1599
1688
  retryOnCallbackError,
1600
1689
  options.retryingRenewalCallback === true || claim.row?.lastError?.startsWith(
1601
1690
  "Subscription callback onSubscriptionRenewed failed:"
1602
- ) === true
1691
+ ) === true,
1692
+ options.inboxEnabled ?? dedupe
1603
1693
  );
1604
1694
  } else {
1605
1695
  const { row, stream } = await reconcileFromStreamPay(ctx, payload, client, plans);
@@ -1631,7 +1721,28 @@ async function syncWebhookPayload(ctx, payload, client, plans, callbacks, option
1631
1721
  throw err;
1632
1722
  }
1633
1723
  }
1634
- async function handleRenewalEvidence(ctx, payload, client, plans, callbacks, retryOnCallbackError, retryingRenewalCallback) {
1724
+ async function releaseLockOfCompletedRenewal(ctx, subscriptionRowId, lockEventId) {
1725
+ const owner = await ctx.context.adapter.findOne({
1726
+ model: WEBHOOK_EVENT_MODEL,
1727
+ where: [{ field: "eventId", value: lockEventId }]
1728
+ });
1729
+ if (owner?.status !== "completed") return false;
1730
+ const released = await ctx.context.adapter.update({
1731
+ model: SUBSCRIPTION_MODEL2,
1732
+ update: { renewalCallbackEventId: null },
1733
+ where: [
1734
+ { field: "id", value: subscriptionRowId },
1735
+ { field: "renewalCallbackEventId", value: lockEventId }
1736
+ ]
1737
+ });
1738
+ if (released) {
1739
+ logger(ctx).warn(
1740
+ `released renewal callback lock of completed event ${lockEventId} for row=${subscriptionRowId}.`
1741
+ );
1742
+ }
1743
+ return released !== null;
1744
+ }
1745
+ async function handleRenewalEvidence(ctx, payload, client, plans, callbacks, retryOnCallbackError, retryingRenewalCallback, inboxEnabled) {
1635
1746
  const invoiceId = payload.data?.invoice?.id ?? payload.entity_id;
1636
1747
  if (!invoiceId) return;
1637
1748
  let subscriptionId = payload.entity_type === "SUBSCRIPTION" ? payload.entity_id : null;
@@ -1663,27 +1774,55 @@ async function handleRenewalEvidence(ctx, payload, client, plans, callbacks, ret
1663
1774
  const eventIsStale = Boolean(
1664
1775
  eventAt && existing.providerUpdatedAt instanceof Date && eventAt.getTime() < existing.providerUpdatedAt.getTime()
1665
1776
  );
1777
+ const evidenceInvoiceId = payload.data?.invoice?.id ?? (payload.entity_type === "INVOICE" ? payload.entity_id : null);
1778
+ const settlesLatestInvoice = stream.latest_invoice?.status === "COMPLETED" && (evidenceInvoiceId === null || stream.latest_invoice.id === evidenceInvoiceId);
1779
+ const evidenceApplies = !eventIsStale || settlesLatestInvoice;
1666
1780
  const projected = {
1667
1781
  ...projectSubscriptionFields(stream, existing),
1668
1782
  ...projectPlanFields(stream, plans),
1669
- ...eventIsStale ? existing.billingStatus === "past_due" && toLocalStatus(stream.status) === "active" ? { status: "past_due", billingStatus: "past_due" } : {} : { billingStatus: "current" }
1783
+ ...evidenceApplies ? { billingStatus: "current" } : existing.billingStatus === "past_due" && toLocalStatus(stream.status) === "active" ? { status: "past_due", billingStatus: "past_due" } : {}
1670
1784
  };
1785
+ const slotKey = liveSlotKey(existing, projected);
1786
+ if (slotKey && existing.activeSlotKey !== slotKey) {
1787
+ projected.activeSlotKey = slotKey;
1788
+ }
1671
1789
  const previousPeriodEnd = existing.periodEnd?.getTime() ?? null;
1672
1790
  const projectedPeriodEnd = projected.periodEnd?.getTime() ?? null;
1673
1791
  const periodAdvanced = previousPeriodEnd !== null && projectedPeriodEnd !== null && projectedPeriodEnd > previousPeriodEnd;
1674
- const cycleAdvanced = existing.currentCycleNumber !== null && existing.currentCycleNumber !== void 0 && projected.currentCycleNumber !== null && projected.currentCycleNumber !== void 0 && projected.currentCycleNumber > existing.currentCycleNumber;
1792
+ const renewedCycle = existing.renewedCycleNumber ?? existing.currentCycleNumber ?? null;
1793
+ const projectedCycle = projected.currentCycleNumber ?? null;
1794
+ const tracksCycles = renewedCycle !== null && projectedCycle !== null;
1795
+ const renewalAdvanced = tracksCycles ? projectedCycle > renewedCycle : periodAdvanced;
1675
1796
  const eventId = extractEventId(payload);
1676
- const pendingCallback = existing.renewalCallbackEventId ?? null;
1797
+ let pendingCallback = existing.renewalCallbackEventId ?? null;
1798
+ if (pendingCallback && pendingCallback !== eventId) {
1799
+ const released = inboxEnabled && await releaseLockOfCompletedRenewal(ctx, existing.id, pendingCallback);
1800
+ if (!released) {
1801
+ throw new Error(
1802
+ `Subscription renewal callback ${pendingCallback} is pending; retry delivery.`
1803
+ );
1804
+ }
1805
+ pendingCallback = null;
1806
+ }
1677
1807
  if (!pendingCallback && existing.providerUpdatedAt instanceof Date && projected.providerUpdatedAt instanceof Date && projected.providerUpdatedAt.getTime() < existing.providerUpdatedAt.getTime()) {
1678
1808
  throw new Error(
1679
1809
  `StreamPay returned stale subscription state for sub=${subscriptionId}; retry delivery.`
1680
1810
  );
1681
1811
  }
1682
- if (pendingCallback && pendingCallback !== eventId) {
1683
- throw new Error(`Subscription renewal callback ${pendingCallback} is pending; retry delivery.`);
1812
+ if (!pendingCallback && projected.activeSlotKey && projected.activeSlotKey !== existing.activeSlotKey) {
1813
+ await takeSlotFromReservation(
1814
+ ctx,
1815
+ client,
1816
+ projected.activeSlotKey,
1817
+ existing.id,
1818
+ subscriptionId
1819
+ );
1684
1820
  }
1685
- const deliverCallback = pendingCallback === eventId && pendingCallback !== null || !eventIsStale && (periodAdvanced || cycleAdvanced || retryingRenewalCallback);
1821
+ const deliverCallback = pendingCallback === eventId && pendingCallback !== null || evidenceApplies && (renewalAdvanced || retryingRenewalCallback);
1686
1822
  const callbackOwner = deliverCallback && callbacks.onSubscriptionRenewed ? eventId : null;
1823
+ if (deliverCallback && renewalAdvanced && projectedCycle !== null) {
1824
+ projected.renewedCycleNumber = projectedCycle;
1825
+ }
1687
1826
  const updated = await ctx.context.adapter.update({
1688
1827
  model: SUBSCRIPTION_MODEL2,
1689
1828
  // Recovery must retain the pending cycle, even if Stream has already advanced again.
@@ -1692,6 +1831,7 @@ async function handleRenewalEvidence(ctx, payload, client, plans, callbacks, ret
1692
1831
  { field: "id", value: existing.id },
1693
1832
  { field: "periodEnd", value: existing.periodEnd ?? null },
1694
1833
  { field: "currentCycleNumber", value: existing.currentCycleNumber ?? null },
1834
+ { field: "renewedCycleNumber", value: existing.renewedCycleNumber ?? null },
1695
1835
  { field: "renewalCallbackEventId", value: pendingCallback },
1696
1836
  { field: "providerUpdatedAt", value: existing.providerUpdatedAt ?? null },
1697
1837
  { field: "status", value: existing.status },
@@ -1704,8 +1844,8 @@ async function handleRenewalEvidence(ctx, payload, client, plans, callbacks, ret
1704
1844
  }
1705
1845
  const latest = await findSubscriptionByStreampayId(ctx, subscriptionId);
1706
1846
  const anotherCallbackOwner = latest?.renewalCallbackEventId;
1707
- const desiredCycleAdvanced = (periodAdvanced || cycleAdvanced) && (!periodAdvanced || (latest?.periodEnd?.getTime() ?? 0) >= (projectedPeriodEnd ?? 0)) && (!cycleAdvanced || (latest?.currentCycleNumber ?? 0) >= (projected.currentCycleNumber ?? 0));
1708
- if (anotherCallbackOwner && anotherCallbackOwner !== eventId && desiredCycleAdvanced) return;
1847
+ const renewalClaimedElsewhere = renewalAdvanced && (tracksCycles ? (latest?.renewedCycleNumber ?? 0) >= projectedCycle : (latest?.periodEnd?.getTime() ?? 0) >= (projectedPeriodEnd ?? 0));
1848
+ if (anotherCallbackOwner && anotherCallbackOwner !== eventId && renewalClaimedElsewhere) return;
1709
1849
  throw new Error(`Subscription changed during renewal reconciliation; retry delivery.`);
1710
1850
  }
1711
1851
  const row = updated;
@@ -2793,6 +2933,12 @@ function buildWebhookEventsEndpoints(adminOptions, registry) {
2793
2933
  message: `Webhook event ${ctx.params.eventId} not found.`
2794
2934
  });
2795
2935
  }
2936
+ const inProgress = new APIError("CONFLICT", {
2937
+ code: $ERROR_CODES.WEBHOOK_REPLAY_IN_PROGRESS.code,
2938
+ message: `Webhook event ${ctx.params.eventId} is being processed. Retry after its lease expires.`
2939
+ });
2940
+ if (row.status === "pending" && hasLiveLease(row, /* @__PURE__ */ new Date())) throw inProgress;
2941
+ if (!await completeUnchangedWebhookEvent({ context: { adapter } }, row)) throw inProgress;
2796
2942
  if (registry?.subscriptionWebhookSync && !eventId.startsWith("handlers:") && (row.eventType === "INVOICE_COMPLETED" || row.eventType === "SUBSCRIPTION_CYCLE_RENEWED_SUCCESSFULLY")) {
2797
2943
  const subscription = await adapter.findOne({
2798
2944
  model: "subscription",
@@ -2809,7 +2955,6 @@ function buildWebhookEventsEndpoints(adminOptions, registry) {
2809
2955
  });
2810
2956
  }
2811
2957
  }
2812
- await markWebhookEventCompleted({ context: { adapter } }, row.id);
2813
2958
  return ctx.json({ discarded: true, eventId });
2814
2959
  }
2815
2960
  )
@@ -3394,7 +3539,8 @@ var SUBSCRIPTION_MODEL4 = "subscription";
3394
3539
  async function recoverCheckoutUrl(client, row) {
3395
3540
  if (!row.streampayPaymentLinkId) return { kind: "expired" };
3396
3541
  try {
3397
- const url = client.getPaymentUrl(await client.getPaymentLink(row.streampayPaymentLinkId));
3542
+ const link = await client.getPaymentLink(row.streampayPaymentLinkId);
3543
+ const url = link.status === "INACTIVE" ? null : client.getPaymentUrl(link);
3398
3544
  return url ? { kind: "recovered", url } : { kind: "expired" };
3399
3545
  } catch (err) {
3400
3546
  if (readSdkErrorFields(err).status === 404) return { kind: "expired" };
@@ -3475,7 +3621,9 @@ async function resumeOrReserveCheckoutSlot(args) {
3475
3621
  });
3476
3622
  if (!reserved) throw err;
3477
3623
  if (reserved.status !== "incomplete") throw subscriptionAlreadyActiveError();
3478
- if (matchesCheckout(reserved)) {
3624
+ const reservationIsStale = !(reserved.createdAt instanceof Date) || now - reserved.createdAt.getTime() >= UPGRADE_IDEMPOTENCY_WINDOW_MS;
3625
+ let linkExpired = false;
3626
+ if (!reservationIsStale && matchesCheckout(reserved)) {
3479
3627
  let recovery;
3480
3628
  try {
3481
3629
  recovery = await recoverCheckoutUrl(client, reserved);
@@ -3492,10 +3640,10 @@ async function resumeOrReserveCheckoutSlot(args) {
3492
3640
  if (recovery.kind === "recovered") {
3493
3641
  return { kind: "recovered", row: reserved, url: recovery.url };
3494
3642
  }
3643
+ linkExpired = Boolean(reserved.streampayPaymentLinkId);
3495
3644
  }
3496
- const reservationIsStale = !(reserved.createdAt instanceof Date) || now - reserved.createdAt.getTime() >= UPGRADE_IDEMPOTENCY_WINDOW_MS;
3497
- if (!reservationIsStale) throw checkoutInProgressError();
3498
- if (reserved.streampayPaymentLinkId) {
3645
+ if (!reservationIsStale && !linkExpired) throw checkoutInProgressError();
3646
+ if (reservationIsStale && reserved.streampayPaymentLinkId) {
3499
3647
  try {
3500
3648
  await deactivatePaymentLink(client, reserved.streampayPaymentLinkId, log);
3501
3649
  } catch (deactivationError) {
@@ -3515,7 +3663,8 @@ async function resumeOrReserveCheckoutSlot(args) {
3515
3663
  where: [
3516
3664
  { field: "id", value: reserved.id },
3517
3665
  { field: "status", value: "incomplete" },
3518
- { field: "activeSlotKey", value: activeSlotKey }
3666
+ { field: "activeSlotKey", value: activeSlotKey },
3667
+ { field: "streampayPaymentLinkId", value: reserved.streampayPaymentLinkId ?? null }
3519
3668
  ]
3520
3669
  });
3521
3670
  if (!released) throw checkoutInProgressError();
@@ -4992,6 +5141,11 @@ var subscriptionTable = {
4992
5141
  type: "number",
4993
5142
  required: false
4994
5143
  },
5144
+ renewedCycleNumber: {
5145
+ type: "number",
5146
+ required: false,
5147
+ input: false
5148
+ },
4995
5149
  renewalCallbackEventId: {
4996
5150
  type: "string",
4997
5151
  required: false,
@@ -5206,9 +5360,9 @@ function subscriptions(subsOptions) {
5206
5360
  }
5207
5361
  };
5208
5362
  if (dedupeEnabled) {
5209
- registry.replayWebhookEvent = async (ctx, eventId) => {
5363
+ registry.replayWebhookEvent = async (ctx, eventId, replayOptions) => {
5210
5364
  if (eventId.startsWith("handlers:") && registry.replayWebhookHandler) {
5211
- return registry.replayWebhookHandler(ctx, eventId);
5365
+ return registry.replayWebhookHandler(ctx, eventId, replayOptions);
5212
5366
  }
5213
5367
  const syncCtx = {
5214
5368
  context: ctx.context
@@ -5223,23 +5377,29 @@ function subscriptions(subsOptions) {
5223
5377
  message: `Webhook event ${eventId} not found.`
5224
5378
  });
5225
5379
  }
5226
- if (!row.rawPayload) {
5227
- throw new APIError("BAD_REQUEST", {
5228
- message: `Webhook event ${eventId} has no rawPayload \u2014 nothing to replay (already completed cleanly?).`
5380
+ if (replayOptions?.dueAttemptCount !== void 0 && !isStillDueWebhookEvent(row, replayOptions.dueAttemptCount, /* @__PURE__ */ new Date())) {
5381
+ throw new APIError("CONFLICT", {
5382
+ code: $ERROR_CODES.WEBHOOK_REPLAY_IN_PROGRESS.code,
5383
+ message: `Webhook event ${eventId} is no longer due.`
5229
5384
  });
5230
5385
  }
5386
+ const unreplayable = async (message) => {
5387
+ await parkUnreplayableWebhookEvent(syncCtx, row, message);
5388
+ throw new APIError("BAD_REQUEST", { message });
5389
+ };
5390
+ if (!row.rawPayload) {
5391
+ return unreplayable(
5392
+ `Webhook event ${eventId} has no rawPayload \u2014 nothing to replay (already completed cleanly?).`
5393
+ );
5394
+ }
5231
5395
  let parsedPayload;
5232
5396
  try {
5233
5397
  parsedPayload = JSON.parse(row.rawPayload);
5234
5398
  } catch {
5235
- throw new APIError("BAD_REQUEST", {
5236
- message: `Webhook event ${eventId} has malformed stored JSON.`
5237
- });
5399
+ return unreplayable(`Webhook event ${eventId} has malformed stored JSON.`);
5238
5400
  }
5239
5401
  if (!isStreamPayWebhookEnvelope(parsedPayload) || !isKnownStreamPayWebhookPayload(parsedPayload)) {
5240
- throw new APIError("BAD_REQUEST", {
5241
- message: `Webhook event ${eventId} has an invalid stored payload.`
5242
- });
5402
+ return unreplayable(`Webhook event ${eventId} has an invalid stored payload.`);
5243
5403
  }
5244
5404
  const payload = parsedPayload;
5245
5405
  const plans = await plansRef();
@@ -5254,6 +5414,7 @@ function subscriptions(subsOptions) {
5254
5414
  try {
5255
5415
  await syncWebhookPayload(syncCtx, payload, options.client, plans, subsOptions, {
5256
5416
  dedupe: false,
5417
+ inboxEnabled: true,
5257
5418
  retryOnCallbackError: subsOptions.retryOnCallbackError !== false,
5258
5419
  retryingRenewalCallback: claimed.lastError?.startsWith(
5259
5420
  "Subscription callback onSubscriptionRenewed failed:"
@@ -5470,7 +5631,7 @@ var webhooks = (webhooksOptions) => {
5470
5631
  return (_options, registry) => {
5471
5632
  const { secret, toleranceSeconds, deduplicate = false, ...handlers } = webhooksOptions;
5472
5633
  if (deduplicate && registry) {
5473
- registry.replayWebhookHandler = async (ctx, eventId) => {
5634
+ registry.replayWebhookHandler = async (ctx, eventId, replayOptions) => {
5474
5635
  const syncContext = { context: ctx.context };
5475
5636
  const row = await syncContext.context.adapter.findOne({
5476
5637
  model: WEBHOOK_EVENT_MODEL,
@@ -5478,20 +5639,21 @@ var webhooks = (webhooksOptions) => {
5478
5639
  });
5479
5640
  if (!eventId.startsWith("handlers:") || !row)
5480
5641
  throw new APIError("NOT_FOUND", { message: "Webhook callback event not found." });
5481
- if (!row.rawPayload)
5482
- throw new APIError("BAD_REQUEST", { message: "Webhook callback has no stored payload." });
5642
+ if (replayOptions?.dueAttemptCount !== void 0 && !isStillDueWebhookEvent(row, replayOptions.dueAttemptCount, /* @__PURE__ */ new Date()))
5643
+ throw new APIError("CONFLICT", { message: "Webhook callback is no longer due." });
5644
+ const unreplayable = async (message) => {
5645
+ await parkUnreplayableWebhookEvent(syncContext, row, message);
5646
+ throw new APIError("BAD_REQUEST", { message });
5647
+ };
5648
+ if (!row.rawPayload) return unreplayable("Webhook callback has no stored payload.");
5483
5649
  let payload;
5484
5650
  try {
5485
5651
  payload = JSON.parse(row.rawPayload);
5486
5652
  } catch {
5487
- throw new APIError("BAD_REQUEST", {
5488
- message: "Stored webhook payload is not valid JSON."
5489
- });
5653
+ return unreplayable("Stored webhook payload is not valid JSON.");
5490
5654
  }
5491
5655
  if (!isStreamPayWebhookEnvelope(payload))
5492
- throw new APIError("BAD_REQUEST", {
5493
- message: "Stored webhook payload is not a valid event envelope."
5494
- });
5656
+ return unreplayable("Stored webhook payload is not a valid event envelope.");
5495
5657
  const previousStatus = row.status;
5496
5658
  const claimed = await claimWebhookEventForReplay(syncContext, row);
5497
5659
  if (!claimed?.lockedBy)
@@ -5639,7 +5801,7 @@ var webhooks = (webhooksOptions) => {
5639
5801
  const failed = [];
5640
5802
  for (const row of due) {
5641
5803
  try {
5642
- await replay(ctx, row.eventId);
5804
+ await replay(ctx, row.eventId, { dueAttemptCount: row.attemptCount });
5643
5805
  succeeded.push(row.eventId);
5644
5806
  } catch (err) {
5645
5807
  if (err instanceof APIError && err.status === "CONFLICT") continue;
@@ -5780,7 +5942,7 @@ var onUserDelete = (options) => async (user, context) => {
5780
5942
 
5781
5943
  // package.json
5782
5944
  var package_default = {
5783
- version: "3.2.0"};
5945
+ version: "3.3.0"};
5784
5946
 
5785
5947
  // src/version.ts
5786
5948
  var version = package_default.version;