better-auth-streampay 3.1.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),
@@ -877,15 +902,120 @@ function projectPlanFields(sub, plans) {
877
902
  pendingSeatsEffectiveAt: pendingSeats === null ? null : pendingEffectiveAt
878
903
  };
879
904
  }
880
- function subscriptionSlotKey(referenceType, referenceId, group) {
881
- const tuple = JSON.stringify([referenceType, referenceId, group ?? null]);
882
- return `sp_slot_v1_${createHash("sha256").update(tuple).digest("hex")}`;
905
+
906
+ // src/plugins/subscriptions/lifecycle.ts
907
+ function isAlreadyCanceledFreezeError(err) {
908
+ const sdkError = readSdkErrorFields(err);
909
+ const envelope = readEnvelope(sdkError.body);
910
+ return sdkError.status === 403 && envelope?.code === "STREAM_ERROR" && envelope.additionalInfo === "Cannot delete non-latest freeze entry.";
911
+ }
912
+ async function deactivatePaymentLink(client, paymentLinkId, log) {
913
+ if (!client.updatePaymentLinkStatus) {
914
+ log.warn(
915
+ `payment link=${paymentLinkId} stays payable: client does not implement updatePaymentLinkStatus.`
916
+ );
917
+ return;
918
+ }
919
+ try {
920
+ await client.updatePaymentLinkStatus(paymentLinkId, { status: "INACTIVE" });
921
+ } catch (err) {
922
+ if (readSdkErrorFields(err).status !== 404) throw err;
923
+ }
924
+ }
925
+ function subscriptionCouponIds(stream) {
926
+ return couponIdsFromMetadata(stream.coupon_calculation_metadata);
927
+ }
928
+ function couponIdsFromMetadata(metadata) {
929
+ const coupons = [];
930
+ for (const coupon of metadata?.coupons ?? []) {
931
+ if (coupon.coupon_id) coupons.push(coupon.coupon_id);
932
+ }
933
+ return coupons;
934
+ }
935
+ function subscriptionItemsForUpdate(stream, currentProductId, targetProductId, targetSeats) {
936
+ if (!stream.items?.length) {
937
+ throw invalidProviderItems("StreamPay returned a subscription without any items.");
938
+ }
939
+ const subscriptionCoupons = new Set(subscriptionCouponIds(stream));
940
+ let matches = 0;
941
+ const items = stream.items.map((item) => {
942
+ const productId = subscriptionItemProductId(item);
943
+ const quantity = item.quantity ?? 1;
944
+ if (!productId || !Number.isSafeInteger(quantity) || quantity < 1) {
945
+ throw invalidProviderItems("StreamPay returned an invalid subscription item.");
946
+ }
947
+ const isPlanItem = productId === currentProductId;
948
+ if (isPlanItem) matches += 1;
949
+ const itemCoupons = couponIdsFromMetadata(item.coupon_calculation_metadata).filter(
950
+ (couponId) => !subscriptionCoupons.has(couponId)
951
+ );
952
+ return {
953
+ product_id: isPlanItem ? targetProductId : productId,
954
+ quantity: isPlanItem ? targetSeats : quantity,
955
+ ...itemCoupons.length > 0 ? { coupons: itemCoupons } : {}
956
+ };
957
+ });
958
+ if (matches !== 1) {
959
+ throw invalidProviderItems(
960
+ `Expected exactly one plan item for product "${currentProductId}", received ${matches}.`
961
+ );
962
+ }
963
+ return items;
964
+ }
965
+ function invalidProviderItems(message) {
966
+ return new APIError("INTERNAL_SERVER_ERROR", {
967
+ code: $ERROR_CODES.SUBSCRIPTION_INVALID_STATE.code,
968
+ message
969
+ });
970
+ }
971
+ function configuredPlanForSubscription(subscription, plans) {
972
+ const matches = plans.list.filter(
973
+ (plan) => subscription.items?.some((item) => subscriptionItemProductId(item) === plan.productId)
974
+ );
975
+ if (matches.length > 1) {
976
+ throw invalidProviderItems(
977
+ "StreamPay returned a subscription containing multiple configured plan products."
978
+ );
979
+ }
980
+ return matches[0];
981
+ }
982
+ async function findSubscriptionFreeze(client, options, subscriptionId, matches) {
983
+ const listPage = options.listSubscriptionFreezes;
984
+ if (!listPage) {
985
+ const response = await client.listSubscriptionFreezes(subscriptionId);
986
+ return {
987
+ freeze: response.data?.find(matches),
988
+ hasMore: response.pagination?.has_next_page ?? false
989
+ };
990
+ }
991
+ const seenIds = /* @__PURE__ */ new Set();
992
+ for (let page = 1; page <= 100; page++) {
993
+ const response = await listPage(subscriptionId, { page, limit: 100 });
994
+ const pagination = response.pagination;
995
+ if (!Array.isArray(response.data) || !pagination || pagination.current_page !== page || typeof pagination.has_next_page !== "boolean") {
996
+ throw freezePaginationConflict("StreamPay returned invalid freeze pagination.");
997
+ }
998
+ let advanced = false;
999
+ for (const freeze2 of response.data) {
1000
+ if (freeze2.id && !seenIds.has(freeze2.id)) {
1001
+ seenIds.add(freeze2.id);
1002
+ advanced = true;
1003
+ }
1004
+ }
1005
+ if (!advanced && (pagination.has_next_page || response.data.length > 0)) {
1006
+ throw freezePaginationConflict("StreamPay freeze pagination returned no new entries.");
1007
+ }
1008
+ const freeze = response.data.find(matches);
1009
+ if (freeze || !pagination.has_next_page) return { freeze, hasMore: false };
1010
+ }
1011
+ throw freezePaginationConflict("StreamPay freeze pagination exceeded 100 pages.");
1012
+ }
1013
+ function freezePaginationConflict(message) {
1014
+ return new APIError("CONFLICT", {
1015
+ code: $ERROR_CODES.SUBSCRIPTION_INVALID_STATE.code,
1016
+ message
1017
+ });
883
1018
  }
884
- var UPGRADE_IDEMPOTENCY_WINDOW_MS = 15 * 60 * 1e3;
885
- var PLAN_NAME_METADATA_KEY = "streampay_plugin_plan_name";
886
- var REFERENCE_ID_METADATA_KEY = "streampay_plugin_reference_id";
887
- var REFERENCE_TYPE_METADATA_KEY = "streampay_plugin_reference_type";
888
- var SUBSCRIPTION_ROW_ID_METADATA_KEY = "streampay_plugin_subscription_row_id";
889
1019
 
890
1020
  // src/plugins/subscriptions/sync.ts
891
1021
  var SUBSCRIPTION_MODEL2 = "subscription";
@@ -913,6 +1043,9 @@ function isUniqueConstraintError(err) {
913
1043
  }
914
1044
  var WEBHOOK_PROCESSING_LEASE_MS = 2 * 60 * 1e3;
915
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
+ }
916
1049
  var WebhookEventInProgressError = class extends Error {
917
1050
  constructor(eventType) {
918
1051
  super(`Webhook ${eventType} is already being processed; retry later.`);
@@ -997,7 +1130,7 @@ async function claimOrAdvanceWebhookEvent(ctx, payload, rawBody, signatureHeader
997
1130
  );
998
1131
  return { action: "skip", reason: "dead_letter" };
999
1132
  }
1000
- if (existing.lockedAt instanceof Date && now.getTime() - existing.lockedAt.getTime() < WEBHOOK_PROCESSING_LEASE_MS) {
1133
+ if (hasLiveLease(existing, now)) {
1001
1134
  logger(ctx).info(
1002
1135
  `webhook ${payload.event_type} (${eventId}) is already being processed \u2014 skipping concurrent delivery.`
1003
1136
  );
@@ -1013,15 +1146,15 @@ async function claimOrAdvanceWebhookEvent(ctx, payload, rawBody, signatureHeader
1013
1146
  lastAttemptAt: now,
1014
1147
  deadLetteredAt: now,
1015
1148
  nextAttemptAt: null,
1016
- rawPayload: rawBody,
1017
- signatureHeader,
1149
+ ...rawBody !== null ? { rawPayload: rawBody, signatureHeader } : {},
1018
1150
  lockedAt: null,
1019
1151
  lockedBy: null
1020
1152
  },
1021
1153
  where: [
1022
1154
  { field: "id", value: existing.id },
1023
1155
  { field: "status", value: "pending" },
1024
- { field: "lockedAt", value: existing.lockedAt ?? null }
1156
+ { field: "lockedAt", value: existing.lockedAt ?? null },
1157
+ { field: "attemptCount", value: existing.attemptCount ?? null }
1025
1158
  ]
1026
1159
  });
1027
1160
  return updated2 ? { action: "dead_letter", row: updated2 } : { action: "skip", reason: "in_progress" };
@@ -1033,19 +1166,21 @@ async function claimOrAdvanceWebhookEvent(ctx, payload, rawBody, signatureHeader
1033
1166
  lastAttemptAt: now,
1034
1167
  nextAttemptAt: null,
1035
1168
  lockedAt: now,
1036
- lockedBy: lockId
1169
+ lockedBy: lockId,
1170
+ ...rawBody !== null ? { rawPayload: rawBody, signatureHeader } : {}
1037
1171
  },
1038
1172
  where: [
1039
1173
  { field: "id", value: existing.id },
1040
1174
  { field: "status", value: "pending" },
1041
- { field: "lockedAt", value: existing.lockedAt ?? null }
1175
+ { field: "lockedAt", value: existing.lockedAt ?? null },
1176
+ { field: "attemptCount", value: existing.attemptCount ?? null }
1042
1177
  ]
1043
1178
  });
1044
1179
  return updated ? { action: "process", row: updated } : { action: "skip", reason: "in_progress" };
1045
1180
  }
1046
1181
  async function claimWebhookEventForReplay(ctx, row) {
1047
1182
  const now = /* @__PURE__ */ new Date();
1048
- if (row.lockedAt instanceof Date && now.getTime() - row.lockedAt.getTime() < WEBHOOK_PROCESSING_LEASE_MS) {
1183
+ if (hasLiveLease(row, now)) {
1049
1184
  return null;
1050
1185
  }
1051
1186
  return ctx.context.adapter.update({
@@ -1063,30 +1198,71 @@ async function claimWebhookEventForReplay(ctx, row) {
1063
1198
  where: [
1064
1199
  { field: "id", value: row.id },
1065
1200
  { field: "status", value: row.status },
1066
- { field: "lockedAt", value: row.lockedAt ?? null }
1201
+ { field: "lockedAt", value: row.lockedAt ?? null },
1202
+ { field: "attemptCount", value: row.attemptCount ?? null }
1067
1203
  ]
1068
1204
  });
1069
1205
  }
1070
- 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;
1071
1213
  await ctx.context.adapter.update({
1072
1214
  model: WEBHOOK_EVENT_MODEL,
1073
1215
  update: {
1074
- status: "completed",
1075
- completedAt: /* @__PURE__ */ new Date(),
1076
1216
  nextAttemptAt: null,
1077
1217
  lockedAt: null,
1078
1218
  lockedBy: null,
1079
- rawPayload: null,
1080
- signatureHeader: null,
1081
- lastError: null,
1082
- lastErrorCode: null
1219
+ lastError: reason,
1220
+ lastErrorCode: "UNREPLAYABLE_PAYLOAD"
1083
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(),
1084
1247
  where: [
1085
1248
  { field: "id", value: rowId },
1086
1249
  ...lockId ? [{ field: "lockedBy", value: lockId }] : []
1087
1250
  ]
1088
1251
  });
1089
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
+ }
1090
1266
  async function recordWebhookEventFailure(ctx, rowId, rawBody, signatureHeader, err, lockId, deadLetter = false) {
1091
1267
  const lastError = err instanceof Error ? err.message : String(err);
1092
1268
  const sdkError = readSdkErrorFields(err);
@@ -1205,12 +1381,106 @@ var SubscriptionCorrelationError = class extends Error {
1205
1381
  this.name = "SubscriptionCorrelationError";
1206
1382
  }
1207
1383
  };
1208
- async function updateReconciledSubscription(ctx, existing, projected, streampaySubscriptionId) {
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
+ }
1408
+ async function takeSlotFromReservation(ctx, client, slotKey, ownerRowId, streampaySubscriptionId) {
1409
+ const holder = await ctx.context.adapter.findOne({
1410
+ model: SUBSCRIPTION_MODEL2,
1411
+ where: [{ field: "activeSlotKey", value: slotKey }]
1412
+ });
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
+ }
1419
+ if (holder.status !== "incomplete" || holder.streampaySubscriptionId) {
1420
+ throw new SubscriptionCorrelationError(
1421
+ `StreamPay sub=${streampaySubscriptionId} needs the billing slot held by live row=${holder.id} (${holder.status}). Resolve the duplicate subscription, then replay.`
1422
+ );
1423
+ }
1424
+ if (holder.streampayPaymentLinkId) {
1425
+ try {
1426
+ await deactivatePaymentLink(client, holder.streampayPaymentLinkId, logger(ctx));
1427
+ } catch (err) {
1428
+ const message = err instanceof Error ? err.message : String(err);
1429
+ logger(ctx).error(
1430
+ `payment link=${holder.streampayPaymentLinkId} of released row=${holder.id} could not be deactivated and may still be paid; deactivate it manually: ${message}`
1431
+ );
1432
+ }
1433
+ }
1434
+ const released = await ctx.context.adapter.update({
1435
+ model: SUBSCRIPTION_MODEL2,
1436
+ update: { status: "incomplete_expired", activeSlotKey: null, updatedAt: /* @__PURE__ */ new Date() },
1437
+ where: [
1438
+ { field: "id", value: holder.id },
1439
+ { field: "status", value: "incomplete" },
1440
+ { field: "activeSlotKey", value: slotKey },
1441
+ { field: "streampayPaymentLinkId", value: holder.streampayPaymentLinkId ?? null }
1442
+ ]
1443
+ });
1444
+ if (!released) {
1445
+ throw new Error(`Checkout reservation row=${holder.id} changed while releasing its slot.`);
1446
+ }
1447
+ logger(ctx).warn(
1448
+ `released checkout reservation row=${holder.id} for paid StreamPay sub=${streampaySubscriptionId}.`
1449
+ );
1450
+ }
1451
+ async function linkReservedRow(ctx, client, row, projected, metadataReferenceType, streampaySubscriptionId) {
1452
+ const activeSlotKey = projected.activeSlotKey === null ? null : row.activeSlotKey ?? subscriptionSlotKey(
1453
+ row.referenceType ?? metadataReferenceType ?? "user",
1454
+ row.referenceId,
1455
+ projected.group === void 0 ? row.group : projected.group
1456
+ );
1457
+ return updateReconciledSubscription(
1458
+ ctx,
1459
+ client,
1460
+ row,
1461
+ {
1462
+ ...projected,
1463
+ billingStatus: row.billingStatus ?? "current",
1464
+ ...activeSlotKey === null ? {} : { activeSlotKey }
1465
+ },
1466
+ streampaySubscriptionId
1467
+ );
1468
+ }
1469
+ async function updateReconciledSubscription(ctx, client, existing, projected, streampaySubscriptionId) {
1209
1470
  if (existing.providerUpdatedAt instanceof Date && projected.providerUpdatedAt instanceof Date && projected.providerUpdatedAt.getTime() < existing.providerUpdatedAt.getTime()) {
1210
1471
  throw new Error(
1211
1472
  `StreamPay returned stale subscription state for sub=${streampaySubscriptionId}. Retry reconciliation.`
1212
1473
  );
1213
1474
  }
1475
+ if (projected.activeSlotKey && projected.activeSlotKey !== existing.activeSlotKey) {
1476
+ await takeSlotFromReservation(
1477
+ ctx,
1478
+ client,
1479
+ projected.activeSlotKey,
1480
+ existing.id,
1481
+ streampaySubscriptionId
1482
+ );
1483
+ }
1214
1484
  const updated = await ctx.context.adapter.update({
1215
1485
  model: SUBSCRIPTION_MODEL2,
1216
1486
  update: projected,
@@ -1220,7 +1490,8 @@ async function updateReconciledSubscription(ctx, existing, projected, streampayS
1220
1490
  { field: "streampaySubscriptionId", value: existing.streampaySubscriptionId ?? null },
1221
1491
  { field: "streampayConsumerId", value: existing.streampayConsumerId ?? null },
1222
1492
  { field: "status", value: existing.status },
1223
- { field: "billingStatus", value: existing.billingStatus }
1493
+ { field: "billingStatus", value: existing.billingStatus },
1494
+ { field: "renewedCycleNumber", value: existing.renewedCycleNumber ?? null }
1224
1495
  ]
1225
1496
  });
1226
1497
  if (!updated) {
@@ -1255,15 +1526,16 @@ async function reconcileFromStreamPay(ctx, payload, client, plans) {
1255
1526
  const eventIsStale = Boolean(
1256
1527
  eventAt && existing?.providerUpdatedAt instanceof Date && eventAt.getTime() < existing.providerUpdatedAt.getTime()
1257
1528
  );
1258
- 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") {
1259
1531
  projected.status = "past_due";
1260
1532
  projected.billingStatus = "past_due";
1261
1533
  }
1262
- 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);
1263
1535
  if (schedulesCancellation) {
1264
1536
  projected.cancelAt = parseDate(stream.current_period_end);
1265
1537
  }
1266
- const confirmsCancellation = !eventIsStale && payload.event_type === "SUBSCRIPTION_CANCELED" && projected.status === "canceled";
1538
+ const confirmsCancellation = eventApplies && payload.event_type === "SUBSCRIPTION_CANCELED" && projected.status === "canceled";
1267
1539
  if (confirmsCancellation) {
1268
1540
  projected.activeSlotKey = null;
1269
1541
  }
@@ -1272,25 +1544,22 @@ async function reconcileFromStreamPay(ctx, payload, client, plans) {
1272
1544
  stampCancelScheduled: schedulesCancellation,
1273
1545
  stampCanceled: confirmsCancellation
1274
1546
  });
1547
+ if (schedulesCancellation && eventAt && existing?.cancelAtPeriodEnd && !existing.cancelScheduledAt) {
1548
+ projected.cancelScheduledAt = eventAt;
1549
+ }
1275
1550
  if (existing) {
1276
- const projectedStatus = projected.status ?? existing.status;
1277
- if (!isTerminalSubscriptionStatus(projectedStatus)) {
1278
- const desiredSlotKey = subscriptionSlotKey(
1279
- existing.referenceType ?? "user",
1280
- existing.referenceId,
1281
- projected.group === void 0 ? existing.group : projected.group
1282
- );
1283
- if (existing.activeSlotKey !== desiredSlotKey) {
1284
- projected.activeSlotKey = desiredSlotKey;
1285
- }
1551
+ const slotKey = liveSlotKey(existing, projected);
1552
+ if (slotKey && existing.activeSlotKey !== slotKey) {
1553
+ projected.activeSlotKey = slotKey;
1286
1554
  }
1287
1555
  const updated = await updateReconciledSubscription(
1288
1556
  ctx,
1557
+ client,
1289
1558
  existing,
1290
1559
  projected,
1291
1560
  streampaySubscriptionId
1292
1561
  );
1293
- if (eventIsStale) {
1562
+ if (!eventApplies) {
1294
1563
  logger(ctx).info(
1295
1564
  `webhook ${payload.event_type}: ignored stale lifecycle callback for sub=${streampaySubscriptionId}.`
1296
1565
  );
@@ -1319,21 +1588,12 @@ async function reconcileFromStreamPay(ctx, payload, client, plans) {
1319
1588
  `webhook ${payload.event_type}: referenced subscription row=${localRowId} is missing; rebuilding from signed metadata.`
1320
1589
  );
1321
1590
  } else if (metadataRow.referenceId === referenceId && (!metadataReferenceType || (metadataRow.referenceType ?? "user") === metadataReferenceType) && metadataRow.plan === planName && (!metadataRow.streampayConsumerId || !stream.organization_consumer_id || metadataRow.streampayConsumerId === stream.organization_consumer_id) && (!metadataRow.streampaySubscriptionId || metadataRow.streampaySubscriptionId === streampaySubscriptionId) && (!metadataRow.streampayPaymentLinkId || !paymentLinkId || metadataRow.streampayPaymentLinkId === paymentLinkId)) {
1322
- const projectedWithSlot = {
1323
- ...projected,
1324
- billingStatus: metadataRow.billingStatus ?? "current",
1325
- ...projected.activeSlotKey === null ? {} : {
1326
- activeSlotKey: metadataRow.activeSlotKey ?? subscriptionSlotKey(
1327
- metadataRow.referenceType ?? metadataReferenceType ?? "user",
1328
- metadataRow.referenceId,
1329
- projected.group === void 0 ? metadataRow.group : projected.group
1330
- )
1331
- }
1332
- };
1333
- const updated = await updateReconciledSubscription(
1591
+ const updated = await linkReservedRow(
1334
1592
  ctx,
1593
+ client,
1335
1594
  metadataRow,
1336
- projectedWithSlot,
1595
+ projected,
1596
+ metadataReferenceType,
1337
1597
  streampaySubscriptionId
1338
1598
  );
1339
1599
  return { row: updated, stream };
@@ -1356,30 +1616,22 @@ async function reconcileFromStreamPay(ctx, payload, client, plans) {
1356
1616
  stream.organization_consumer_id ?? null
1357
1617
  );
1358
1618
  if (incomplete) {
1359
- const projectedWithSlot = {
1360
- ...projected,
1361
- billingStatus: incomplete.billingStatus ?? "current",
1362
- ...projected.activeSlotKey === null ? {} : {
1363
- activeSlotKey: incomplete.activeSlotKey ?? subscriptionSlotKey(
1364
- incomplete.referenceType ?? metadataReferenceType ?? "user",
1365
- incomplete.referenceId,
1366
- projected.group === void 0 ? incomplete.group : projected.group
1367
- )
1368
- }
1369
- };
1370
- const updated = await updateReconciledSubscription(
1619
+ const updated = await linkReservedRow(
1371
1620
  ctx,
1621
+ client,
1372
1622
  incomplete,
1373
- projectedWithSlot,
1623
+ projected,
1624
+ metadataReferenceType,
1374
1625
  streampaySubscriptionId
1375
1626
  );
1376
- return {
1377
- row: updated,
1378
- stream
1379
- };
1627
+ return { row: updated, stream };
1380
1628
  }
1381
1629
  const plan = plans.byName.get(planName);
1382
1630
  const referenceType = metadataReferenceType ?? "custom";
1631
+ const activeSlotKey = isTerminalSubscriptionStatus(projected.status) ? null : subscriptionSlotKey(referenceType, referenceId, plan?.group);
1632
+ if (activeSlotKey) {
1633
+ await takeSlotFromReservation(ctx, client, activeSlotKey, null, streampaySubscriptionId);
1634
+ }
1383
1635
  const row = await ctx.context.adapter.create({
1384
1636
  model: SUBSCRIPTION_MODEL2,
1385
1637
  data: {
@@ -1388,7 +1640,7 @@ async function reconcileFromStreamPay(ctx, payload, client, plans) {
1388
1640
  ...projected,
1389
1641
  referenceId,
1390
1642
  referenceType,
1391
- activeSlotKey: isTerminalSubscriptionStatus(projected.status) ? null : subscriptionSlotKey(referenceType, referenceId, plan?.group),
1643
+ activeSlotKey,
1392
1644
  streampayPaymentLinkId: paymentLinkId,
1393
1645
  plan: planName,
1394
1646
  planVersion: plan?.version ?? null,
@@ -1436,7 +1688,8 @@ async function syncWebhookPayload(ctx, payload, client, plans, callbacks, option
1436
1688
  retryOnCallbackError,
1437
1689
  options.retryingRenewalCallback === true || claim.row?.lastError?.startsWith(
1438
1690
  "Subscription callback onSubscriptionRenewed failed:"
1439
- ) === true
1691
+ ) === true,
1692
+ options.inboxEnabled ?? dedupe
1440
1693
  );
1441
1694
  } else {
1442
1695
  const { row, stream } = await reconcileFromStreamPay(ctx, payload, client, plans);
@@ -1468,7 +1721,28 @@ async function syncWebhookPayload(ctx, payload, client, plans, callbacks, option
1468
1721
  throw err;
1469
1722
  }
1470
1723
  }
1471
- 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) {
1472
1746
  const invoiceId = payload.data?.invoice?.id ?? payload.entity_id;
1473
1747
  if (!invoiceId) return;
1474
1748
  let subscriptionId = payload.entity_type === "SUBSCRIPTION" ? payload.entity_id : null;
@@ -1500,27 +1774,55 @@ async function handleRenewalEvidence(ctx, payload, client, plans, callbacks, ret
1500
1774
  const eventIsStale = Boolean(
1501
1775
  eventAt && existing.providerUpdatedAt instanceof Date && eventAt.getTime() < existing.providerUpdatedAt.getTime()
1502
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;
1503
1780
  const projected = {
1504
1781
  ...projectSubscriptionFields(stream, existing),
1505
1782
  ...projectPlanFields(stream, plans),
1506
- ...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" } : {}
1507
1784
  };
1785
+ const slotKey = liveSlotKey(existing, projected);
1786
+ if (slotKey && existing.activeSlotKey !== slotKey) {
1787
+ projected.activeSlotKey = slotKey;
1788
+ }
1508
1789
  const previousPeriodEnd = existing.periodEnd?.getTime() ?? null;
1509
1790
  const projectedPeriodEnd = projected.periodEnd?.getTime() ?? null;
1510
1791
  const periodAdvanced = previousPeriodEnd !== null && projectedPeriodEnd !== null && projectedPeriodEnd > previousPeriodEnd;
1511
- 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;
1512
1796
  const eventId = extractEventId(payload);
1513
- 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
+ }
1514
1807
  if (!pendingCallback && existing.providerUpdatedAt instanceof Date && projected.providerUpdatedAt instanceof Date && projected.providerUpdatedAt.getTime() < existing.providerUpdatedAt.getTime()) {
1515
1808
  throw new Error(
1516
1809
  `StreamPay returned stale subscription state for sub=${subscriptionId}; retry delivery.`
1517
1810
  );
1518
1811
  }
1519
- if (pendingCallback && pendingCallback !== eventId) {
1520
- 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
+ );
1521
1820
  }
1522
- const deliverCallback = pendingCallback === eventId && pendingCallback !== null || !eventIsStale && (periodAdvanced || cycleAdvanced || retryingRenewalCallback);
1821
+ const deliverCallback = pendingCallback === eventId && pendingCallback !== null || evidenceApplies && (renewalAdvanced || retryingRenewalCallback);
1523
1822
  const callbackOwner = deliverCallback && callbacks.onSubscriptionRenewed ? eventId : null;
1823
+ if (deliverCallback && renewalAdvanced && projectedCycle !== null) {
1824
+ projected.renewedCycleNumber = projectedCycle;
1825
+ }
1524
1826
  const updated = await ctx.context.adapter.update({
1525
1827
  model: SUBSCRIPTION_MODEL2,
1526
1828
  // Recovery must retain the pending cycle, even if Stream has already advanced again.
@@ -1529,6 +1831,7 @@ async function handleRenewalEvidence(ctx, payload, client, plans, callbacks, ret
1529
1831
  { field: "id", value: existing.id },
1530
1832
  { field: "periodEnd", value: existing.periodEnd ?? null },
1531
1833
  { field: "currentCycleNumber", value: existing.currentCycleNumber ?? null },
1834
+ { field: "renewedCycleNumber", value: existing.renewedCycleNumber ?? null },
1532
1835
  { field: "renewalCallbackEventId", value: pendingCallback },
1533
1836
  { field: "providerUpdatedAt", value: existing.providerUpdatedAt ?? null },
1534
1837
  { field: "status", value: existing.status },
@@ -1541,8 +1844,8 @@ async function handleRenewalEvidence(ctx, payload, client, plans, callbacks, ret
1541
1844
  }
1542
1845
  const latest = await findSubscriptionByStreampayId(ctx, subscriptionId);
1543
1846
  const anotherCallbackOwner = latest?.renewalCallbackEventId;
1544
- const desiredCycleAdvanced = (periodAdvanced || cycleAdvanced) && (!periodAdvanced || (latest?.periodEnd?.getTime() ?? 0) >= (projectedPeriodEnd ?? 0)) && (!cycleAdvanced || (latest?.currentCycleNumber ?? 0) >= (projected.currentCycleNumber ?? 0));
1545
- 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;
1546
1849
  throw new Error(`Subscription changed during renewal reconciliation; retry delivery.`);
1547
1850
  }
1548
1851
  const row = updated;
@@ -2630,6 +2933,12 @@ function buildWebhookEventsEndpoints(adminOptions, registry) {
2630
2933
  message: `Webhook event ${ctx.params.eventId} not found.`
2631
2934
  });
2632
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;
2633
2942
  if (registry?.subscriptionWebhookSync && !eventId.startsWith("handlers:") && (row.eventType === "INVOICE_COMPLETED" || row.eventType === "SUBSCRIPTION_CYCLE_RENEWED_SUCCESSFULLY")) {
2634
2943
  const subscription = await adapter.findOne({
2635
2944
  model: "subscription",
@@ -2646,7 +2955,6 @@ function buildWebhookEventsEndpoints(adminOptions, registry) {
2646
2955
  });
2647
2956
  }
2648
2957
  }
2649
- await markWebhookEventCompleted({ context: { adapter } }, row.id);
2650
2958
  return ctx.json({ discarded: true, eventId });
2651
2959
  }
2652
2960
  )
@@ -3231,7 +3539,8 @@ var SUBSCRIPTION_MODEL4 = "subscription";
3231
3539
  async function recoverCheckoutUrl(client, row) {
3232
3540
  if (!row.streampayPaymentLinkId) return { kind: "expired" };
3233
3541
  try {
3234
- 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);
3235
3544
  return url ? { kind: "recovered", url } : { kind: "expired" };
3236
3545
  } catch (err) {
3237
3546
  if (readSdkErrorFields(err).status === 404) return { kind: "expired" };
@@ -3258,6 +3567,12 @@ function checkoutInProgressError() {
3258
3567
  message: "A subscription checkout is already being created for this plan group."
3259
3568
  });
3260
3569
  }
3570
+ function subscriptionAlreadyActiveError() {
3571
+ return new APIError("CONFLICT", {
3572
+ code: $ERROR_CODES.SUBSCRIPTION_ALREADY_ACTIVE.code,
3573
+ message: "An active subscription already exists for this plan group."
3574
+ });
3575
+ }
3261
3576
  async function resumeOrReserveCheckoutSlot(args) {
3262
3577
  const { client, adapter, candidates, activeSlotKey, planName, seats, now, log } = args;
3263
3578
  const matchesCheckout = (row2) => row2.plan === planName && (row2.seats ?? 1) === seats;
@@ -3304,8 +3619,11 @@ async function resumeOrReserveCheckoutSlot(args) {
3304
3619
  model: SUBSCRIPTION_MODEL4,
3305
3620
  where: [{ field: "activeSlotKey", value: activeSlotKey }]
3306
3621
  });
3307
- if (reserved?.status !== "incomplete") throw err;
3308
- if (matchesCheckout(reserved)) {
3622
+ if (!reserved) throw err;
3623
+ if (reserved.status !== "incomplete") throw subscriptionAlreadyActiveError();
3624
+ const reservationIsStale = !(reserved.createdAt instanceof Date) || now - reserved.createdAt.getTime() >= UPGRADE_IDEMPOTENCY_WINDOW_MS;
3625
+ let linkExpired = false;
3626
+ if (!reservationIsStale && matchesCheckout(reserved)) {
3309
3627
  let recovery;
3310
3628
  try {
3311
3629
  recovery = await recoverCheckoutUrl(client, reserved);
@@ -3322,16 +3640,31 @@ async function resumeOrReserveCheckoutSlot(args) {
3322
3640
  if (recovery.kind === "recovered") {
3323
3641
  return { kind: "recovered", row: reserved, url: recovery.url };
3324
3642
  }
3643
+ linkExpired = Boolean(reserved.streampayPaymentLinkId);
3644
+ }
3645
+ if (!reservationIsStale && !linkExpired) throw checkoutInProgressError();
3646
+ if (reservationIsStale && reserved.streampayPaymentLinkId) {
3647
+ try {
3648
+ await deactivatePaymentLink(client, reserved.streampayPaymentLinkId, log);
3649
+ } catch (deactivationError) {
3650
+ toAPIError(
3651
+ {
3652
+ logPrefix: `deactivate stale checkout link=${reserved.streampayPaymentLinkId} failed for row=${reserved.id}:`,
3653
+ userMessage: "Unable to replace the previous subscription checkout."
3654
+ },
3655
+ deactivationError,
3656
+ log
3657
+ );
3658
+ }
3325
3659
  }
3326
- const reservationIsStale = !(reserved.createdAt instanceof Date) || now - reserved.createdAt.getTime() >= UPGRADE_IDEMPOTENCY_WINDOW_MS;
3327
- if (!reservationIsStale) throw checkoutInProgressError();
3328
3660
  const released = await adapter.update({
3329
3661
  model: SUBSCRIPTION_MODEL4,
3330
3662
  update: { status: "incomplete_expired", activeSlotKey: null, updatedAt: /* @__PURE__ */ new Date() },
3331
3663
  where: [
3332
3664
  { field: "id", value: reserved.id },
3333
3665
  { field: "status", value: "incomplete" },
3334
- { field: "activeSlotKey", value: activeSlotKey }
3666
+ { field: "activeSlotKey", value: activeSlotKey },
3667
+ { field: "streampayPaymentLinkId", value: reserved.streampayPaymentLinkId ?? null }
3335
3668
  ]
3336
3669
  });
3337
3670
  if (!released) throw checkoutInProgressError();
@@ -3348,105 +3681,6 @@ async function resumeOrReserveCheckoutSlot(args) {
3348
3681
  }
3349
3682
  return { kind: "reserved", row, consumerId };
3350
3683
  }
3351
- function isAlreadyCanceledFreezeError(err) {
3352
- const sdkError = readSdkErrorFields(err);
3353
- const envelope = readEnvelope(sdkError.body);
3354
- return sdkError.status === 403 && envelope?.code === "STREAM_ERROR" && envelope.additionalInfo === "Cannot delete non-latest freeze entry.";
3355
- }
3356
- function subscriptionCouponIds(stream) {
3357
- return couponIdsFromMetadata(stream.coupon_calculation_metadata);
3358
- }
3359
- function couponIdsFromMetadata(metadata) {
3360
- const coupons = [];
3361
- for (const coupon of metadata?.coupons ?? []) {
3362
- if (coupon.coupon_id) coupons.push(coupon.coupon_id);
3363
- }
3364
- return coupons;
3365
- }
3366
- function subscriptionItemsForUpdate(stream, currentProductId, targetProductId, targetSeats) {
3367
- if (!stream.items?.length) {
3368
- throw invalidProviderItems("StreamPay returned a subscription without any items.");
3369
- }
3370
- const subscriptionCoupons = new Set(subscriptionCouponIds(stream));
3371
- let matches = 0;
3372
- const items = stream.items.map((item) => {
3373
- const productId = subscriptionItemProductId(item);
3374
- const quantity = item.quantity ?? 1;
3375
- if (!productId || !Number.isSafeInteger(quantity) || quantity < 1) {
3376
- throw invalidProviderItems("StreamPay returned an invalid subscription item.");
3377
- }
3378
- const isPlanItem = productId === currentProductId;
3379
- if (isPlanItem) matches += 1;
3380
- const itemCoupons = couponIdsFromMetadata(item.coupon_calculation_metadata).filter(
3381
- (couponId) => !subscriptionCoupons.has(couponId)
3382
- );
3383
- return {
3384
- product_id: isPlanItem ? targetProductId : productId,
3385
- quantity: isPlanItem ? targetSeats : quantity,
3386
- ...itemCoupons.length > 0 ? { coupons: itemCoupons } : {}
3387
- };
3388
- });
3389
- if (matches !== 1) {
3390
- throw invalidProviderItems(
3391
- `Expected exactly one plan item for product "${currentProductId}", received ${matches}.`
3392
- );
3393
- }
3394
- return items;
3395
- }
3396
- function invalidProviderItems(message) {
3397
- return new APIError("INTERNAL_SERVER_ERROR", {
3398
- code: $ERROR_CODES.SUBSCRIPTION_INVALID_STATE.code,
3399
- message
3400
- });
3401
- }
3402
- function configuredPlanForSubscription(subscription, plans) {
3403
- const matches = plans.list.filter(
3404
- (plan) => subscription.items?.some((item) => subscriptionItemProductId(item) === plan.productId)
3405
- );
3406
- if (matches.length > 1) {
3407
- throw invalidProviderItems(
3408
- "StreamPay returned a subscription containing multiple configured plan products."
3409
- );
3410
- }
3411
- return matches[0];
3412
- }
3413
- async function findSubscriptionFreeze(client, options, subscriptionId, matches) {
3414
- const listPage = options.listSubscriptionFreezes;
3415
- if (!listPage) {
3416
- const response = await client.listSubscriptionFreezes(subscriptionId);
3417
- return {
3418
- freeze: response.data?.find(matches),
3419
- hasMore: response.pagination?.has_next_page ?? false
3420
- };
3421
- }
3422
- const seenIds = /* @__PURE__ */ new Set();
3423
- for (let page = 1; page <= 100; page++) {
3424
- const response = await listPage(subscriptionId, { page, limit: 100 });
3425
- const pagination = response.pagination;
3426
- if (!Array.isArray(response.data) || !pagination || pagination.current_page !== page || typeof pagination.has_next_page !== "boolean") {
3427
- throw freezePaginationConflict("StreamPay returned invalid freeze pagination.");
3428
- }
3429
- let advanced = false;
3430
- for (const freeze2 of response.data) {
3431
- if (freeze2.id && !seenIds.has(freeze2.id)) {
3432
- seenIds.add(freeze2.id);
3433
- advanced = true;
3434
- }
3435
- }
3436
- if (!advanced && (pagination.has_next_page || response.data.length > 0)) {
3437
- throw freezePaginationConflict("StreamPay freeze pagination returned no new entries.");
3438
- }
3439
- const freeze = response.data.find(matches);
3440
- if (freeze || !pagination.has_next_page) return { freeze, hasMore: false };
3441
- }
3442
- throw freezePaginationConflict("StreamPay freeze pagination exceeded 100 pages.");
3443
- }
3444
- function freezePaginationConflict(message) {
3445
- return new APIError("CONFLICT", {
3446
- code: $ERROR_CODES.SUBSCRIPTION_INVALID_STATE.code,
3447
- message
3448
- });
3449
- }
3450
3684
  var SUBSCRIPTION_INTERVALS = ["WEEK", "MONTH", "QUARTER", "YEAR"];
3451
3685
  var PlanSchema = z.object({
3452
3686
  name: z.string().min(1, "every plan must have a non-empty `name`."),
@@ -4111,6 +4345,24 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
4111
4345
  `failed to persist payment link=${paymentLinkId} for row=${row.id}: ${message}. Protected checkout metadata will reconcile the row from the webhook.`
4112
4346
  );
4113
4347
  }
4348
+ if (updatedRow?.status === "incomplete_expired") {
4349
+ getLogger(ctx).warn(
4350
+ `checkout reservation row=${row.id} was released while payment link=${paymentLinkId} was created; deactivating the link.`
4351
+ );
4352
+ try {
4353
+ await deactivatePaymentLink(client, paymentLinkId, getLogger(ctx));
4354
+ } catch (deactivationError) {
4355
+ toAPIError(
4356
+ {
4357
+ logPrefix: `deactivate orphaned checkout link=${paymentLinkId} failed for row=${row.id}:`,
4358
+ userMessage: "Failed to start subscription checkout."
4359
+ },
4360
+ deactivationError,
4361
+ getLogger(ctx)
4362
+ );
4363
+ }
4364
+ throw checkoutInProgressError();
4365
+ }
4114
4366
  return ctx.json({
4115
4367
  subscriptionId: updatedRow?.id ?? row.id,
4116
4368
  url,
@@ -4889,6 +5141,11 @@ var subscriptionTable = {
4889
5141
  type: "number",
4890
5142
  required: false
4891
5143
  },
5144
+ renewedCycleNumber: {
5145
+ type: "number",
5146
+ required: false,
5147
+ input: false
5148
+ },
4892
5149
  renewalCallbackEventId: {
4893
5150
  type: "string",
4894
5151
  required: false,
@@ -5120,26 +5377,33 @@ function subscriptions(subsOptions) {
5120
5377
  message: `Webhook event ${eventId} not found.`
5121
5378
  });
5122
5379
  }
5123
- if (!row.rawPayload) {
5124
- throw new APIError("BAD_REQUEST", {
5125
- 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.`
5126
5384
  });
5127
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
+ }
5128
5395
  let parsedPayload;
5129
5396
  try {
5130
5397
  parsedPayload = JSON.parse(row.rawPayload);
5131
5398
  } catch {
5132
- throw new APIError("BAD_REQUEST", {
5133
- message: `Webhook event ${eventId} has malformed stored JSON.`
5134
- });
5399
+ return unreplayable(`Webhook event ${eventId} has malformed stored JSON.`);
5135
5400
  }
5136
5401
  if (!isStreamPayWebhookEnvelope(parsedPayload) || !isKnownStreamPayWebhookPayload(parsedPayload)) {
5137
- throw new APIError("BAD_REQUEST", {
5138
- message: `Webhook event ${eventId} has an invalid stored payload.`
5139
- });
5402
+ return unreplayable(`Webhook event ${eventId} has an invalid stored payload.`);
5140
5403
  }
5141
5404
  const payload = parsedPayload;
5142
5405
  const plans = await plansRef();
5406
+ const previousStatus = row.status;
5143
5407
  const claimed = await claimWebhookEventForReplay(syncCtx, row);
5144
5408
  if (!claimed?.lockedBy) {
5145
5409
  throw new APIError("CONFLICT", {
@@ -5150,6 +5414,8 @@ function subscriptions(subsOptions) {
5150
5414
  try {
5151
5415
  await syncWebhookPayload(syncCtx, payload, options.client, plans, subsOptions, {
5152
5416
  dedupe: false,
5417
+ inboxEnabled: true,
5418
+ retryOnCallbackError: subsOptions.retryOnCallbackError !== false,
5153
5419
  retryingRenewalCallback: claimed.lastError?.startsWith(
5154
5420
  "Subscription callback onSubscriptionRenewed failed:"
5155
5421
  ) === true
@@ -5165,7 +5431,7 @@ function subscriptions(subsOptions) {
5165
5431
  null,
5166
5432
  err,
5167
5433
  claimed.lockedBy,
5168
- !replayOptions?.retryUntilExhausted || classifyWebhookFailure(err) === "PERMANENT" || claimed.attemptCount >= maxAttempts
5434
+ previousStatus === "dead_letter" || classifyWebhookFailure(err) === "PERMANENT" || claimed.attemptCount >= maxAttempts
5169
5435
  );
5170
5436
  throw err;
5171
5437
  }
@@ -5373,20 +5639,22 @@ var webhooks = (webhooksOptions) => {
5373
5639
  });
5374
5640
  if (!eventId.startsWith("handlers:") || !row)
5375
5641
  throw new APIError("NOT_FOUND", { message: "Webhook callback event not found." });
5376
- if (!row.rawPayload)
5377
- 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.");
5378
5649
  let payload;
5379
5650
  try {
5380
5651
  payload = JSON.parse(row.rawPayload);
5381
5652
  } catch {
5382
- throw new APIError("BAD_REQUEST", {
5383
- message: "Stored webhook payload is not valid JSON."
5384
- });
5653
+ return unreplayable("Stored webhook payload is not valid JSON.");
5385
5654
  }
5386
5655
  if (!isStreamPayWebhookEnvelope(payload))
5387
- throw new APIError("BAD_REQUEST", {
5388
- message: "Stored webhook payload is not a valid event envelope."
5389
- });
5656
+ return unreplayable("Stored webhook payload is not a valid event envelope.");
5657
+ const previousStatus = row.status;
5390
5658
  const claimed = await claimWebhookEventForReplay(syncContext, row);
5391
5659
  if (!claimed?.lockedBy)
5392
5660
  throw new APIError("CONFLICT", {
@@ -5403,7 +5671,7 @@ var webhooks = (webhooksOptions) => {
5403
5671
  row.signatureHeader,
5404
5672
  err,
5405
5673
  claimed.lockedBy,
5406
- !replayOptions?.retryUntilExhausted || claimed.attemptCount >= DEFAULT_MAX_WEBHOOK_ATTEMPTS
5674
+ previousStatus === "dead_letter" || claimed.attemptCount >= DEFAULT_MAX_WEBHOOK_ATTEMPTS
5407
5675
  );
5408
5676
  throw err;
5409
5677
  }
@@ -5533,7 +5801,7 @@ var webhooks = (webhooksOptions) => {
5533
5801
  const failed = [];
5534
5802
  for (const row of due) {
5535
5803
  try {
5536
- await replay(ctx, row.eventId, { retryUntilExhausted: true });
5804
+ await replay(ctx, row.eventId, { dueAttemptCount: row.attemptCount });
5537
5805
  succeeded.push(row.eventId);
5538
5806
  } catch (err) {
5539
5807
  if (err instanceof APIError && err.status === "CONFLICT") continue;
@@ -5674,7 +5942,7 @@ var onUserDelete = (options) => async (user, context) => {
5674
5942
 
5675
5943
  // package.json
5676
5944
  var package_default = {
5677
- version: "3.1.0"};
5945
+ version: "3.3.0"};
5678
5946
 
5679
5947
  // src/version.ts
5680
5948
  var version = package_default.version;