better-auth-streampay 3.0.2 → 3.2.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/client.d.cts CHANGED
@@ -1,5 +1,5 @@
1
- import { s as streampay, E as ErrorCodeEntry } from './streampay-uhs67tYl.cjs';
2
- export { $ as $ERROR_CODES, S as StreamPayErrorCode } from './streampay-uhs67tYl.cjs';
1
+ import { s as streampay, E as ErrorCodeEntry } from './streampay-B7cFK2CP.cjs';
2
+ export { $ as $ERROR_CODES, S as StreamPayErrorCode } from './streampay-B7cFK2CP.cjs';
3
3
  import 'better-auth';
4
4
  import '@streamsdk/typescript';
5
5
  import 'zod';
package/dist/client.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { s as streampay, E as ErrorCodeEntry } from './streampay-uhs67tYl.js';
2
- export { $ as $ERROR_CODES, S as StreamPayErrorCode } from './streampay-uhs67tYl.js';
1
+ import { s as streampay, E as ErrorCodeEntry } from './streampay-B7cFK2CP.js';
2
+ export { $ as $ERROR_CODES, S as StreamPayErrorCode } from './streampay-B7cFK2CP.js';
3
3
  import 'better-auth';
4
4
  import '@streamsdk/typescript';
5
5
  import 'zod';
package/dist/index.cjs CHANGED
@@ -879,6 +879,120 @@ function projectPlanFields(sub, plans) {
879
879
  pendingSeatsEffectiveAt: pendingSeats === null ? null : pendingEffectiveAt
880
880
  };
881
881
  }
882
+
883
+ // src/plugins/subscriptions/lifecycle.ts
884
+ function isAlreadyCanceledFreezeError(err) {
885
+ const sdkError = readSdkErrorFields(err);
886
+ const envelope = readEnvelope(sdkError.body);
887
+ return sdkError.status === 403 && envelope?.code === "STREAM_ERROR" && envelope.additionalInfo === "Cannot delete non-latest freeze entry.";
888
+ }
889
+ async function deactivatePaymentLink(client, paymentLinkId, log) {
890
+ if (!client.updatePaymentLinkStatus) {
891
+ log.warn(
892
+ `payment link=${paymentLinkId} stays payable: client does not implement updatePaymentLinkStatus.`
893
+ );
894
+ return;
895
+ }
896
+ try {
897
+ await client.updatePaymentLinkStatus(paymentLinkId, { status: "INACTIVE" });
898
+ } catch (err) {
899
+ if (readSdkErrorFields(err).status !== 404) throw err;
900
+ }
901
+ }
902
+ function subscriptionCouponIds(stream) {
903
+ return couponIdsFromMetadata(stream.coupon_calculation_metadata);
904
+ }
905
+ function couponIdsFromMetadata(metadata) {
906
+ const coupons = [];
907
+ for (const coupon of metadata?.coupons ?? []) {
908
+ if (coupon.coupon_id) coupons.push(coupon.coupon_id);
909
+ }
910
+ return coupons;
911
+ }
912
+ function subscriptionItemsForUpdate(stream, currentProductId, targetProductId, targetSeats) {
913
+ if (!stream.items?.length) {
914
+ throw invalidProviderItems("StreamPay returned a subscription without any items.");
915
+ }
916
+ const subscriptionCoupons = new Set(subscriptionCouponIds(stream));
917
+ let matches = 0;
918
+ const items = stream.items.map((item) => {
919
+ const productId = subscriptionItemProductId(item);
920
+ const quantity = item.quantity ?? 1;
921
+ if (!productId || !Number.isSafeInteger(quantity) || quantity < 1) {
922
+ throw invalidProviderItems("StreamPay returned an invalid subscription item.");
923
+ }
924
+ const isPlanItem = productId === currentProductId;
925
+ if (isPlanItem) matches += 1;
926
+ const itemCoupons = couponIdsFromMetadata(item.coupon_calculation_metadata).filter(
927
+ (couponId) => !subscriptionCoupons.has(couponId)
928
+ );
929
+ return {
930
+ product_id: isPlanItem ? targetProductId : productId,
931
+ quantity: isPlanItem ? targetSeats : quantity,
932
+ ...itemCoupons.length > 0 ? { coupons: itemCoupons } : {}
933
+ };
934
+ });
935
+ if (matches !== 1) {
936
+ throw invalidProviderItems(
937
+ `Expected exactly one plan item for product "${currentProductId}", received ${matches}.`
938
+ );
939
+ }
940
+ return items;
941
+ }
942
+ function invalidProviderItems(message) {
943
+ return new api.APIError("INTERNAL_SERVER_ERROR", {
944
+ code: $ERROR_CODES.SUBSCRIPTION_INVALID_STATE.code,
945
+ message
946
+ });
947
+ }
948
+ function configuredPlanForSubscription(subscription, plans) {
949
+ const matches = plans.list.filter(
950
+ (plan) => subscription.items?.some((item) => subscriptionItemProductId(item) === plan.productId)
951
+ );
952
+ if (matches.length > 1) {
953
+ throw invalidProviderItems(
954
+ "StreamPay returned a subscription containing multiple configured plan products."
955
+ );
956
+ }
957
+ return matches[0];
958
+ }
959
+ async function findSubscriptionFreeze(client, options, subscriptionId, matches) {
960
+ const listPage = options.listSubscriptionFreezes;
961
+ if (!listPage) {
962
+ const response = await client.listSubscriptionFreezes(subscriptionId);
963
+ return {
964
+ freeze: response.data?.find(matches),
965
+ hasMore: response.pagination?.has_next_page ?? false
966
+ };
967
+ }
968
+ const seenIds = /* @__PURE__ */ new Set();
969
+ for (let page = 1; page <= 100; page++) {
970
+ const response = await listPage(subscriptionId, { page, limit: 100 });
971
+ const pagination = response.pagination;
972
+ if (!Array.isArray(response.data) || !pagination || pagination.current_page !== page || typeof pagination.has_next_page !== "boolean") {
973
+ throw freezePaginationConflict("StreamPay returned invalid freeze pagination.");
974
+ }
975
+ let advanced = false;
976
+ for (const freeze2 of response.data) {
977
+ if (freeze2.id && !seenIds.has(freeze2.id)) {
978
+ seenIds.add(freeze2.id);
979
+ advanced = true;
980
+ }
981
+ }
982
+ if (!advanced && (pagination.has_next_page || response.data.length > 0)) {
983
+ throw freezePaginationConflict("StreamPay freeze pagination returned no new entries.");
984
+ }
985
+ const freeze = response.data.find(matches);
986
+ if (freeze || !pagination.has_next_page) return { freeze, hasMore: false };
987
+ }
988
+ throw freezePaginationConflict("StreamPay freeze pagination exceeded 100 pages.");
989
+ }
990
+ function freezePaginationConflict(message) {
991
+ return new api.APIError("CONFLICT", {
992
+ code: $ERROR_CODES.SUBSCRIPTION_INVALID_STATE.code,
993
+ message
994
+ });
995
+ }
882
996
  function subscriptionSlotKey(referenceType, referenceId, group) {
883
997
  const tuple = JSON.stringify([referenceType, referenceId, group ?? null]);
884
998
  return `sp_slot_v1_${crypto.createHash("sha256").update(tuple).digest("hex")}`;
@@ -915,6 +1029,40 @@ function isUniqueConstraintError(err) {
915
1029
  }
916
1030
  var WEBHOOK_PROCESSING_LEASE_MS = 2 * 60 * 1e3;
917
1031
  var WEBHOOK_RETRY_DELAYS_MS = [5, 30, 120, 360, 720].map((minutes) => minutes * 60 * 1e3);
1032
+ var WebhookEventInProgressError = class extends Error {
1033
+ constructor(eventType) {
1034
+ super(`Webhook ${eventType} is already being processed; retry later.`);
1035
+ this.name = "WebhookEventInProgressError";
1036
+ }
1037
+ };
1038
+ async function findDueWebhookEvents(ctx, now, limit) {
1039
+ const [retryDue, abandoned] = await Promise.all([
1040
+ ctx.context.adapter.findMany({
1041
+ model: WEBHOOK_EVENT_MODEL,
1042
+ where: [
1043
+ { field: "status", value: "pending" },
1044
+ { field: "nextAttemptAt", operator: "lte", value: now }
1045
+ ],
1046
+ limit,
1047
+ sortBy: { field: "nextAttemptAt", direction: "asc" }
1048
+ }),
1049
+ ctx.context.adapter.findMany({
1050
+ model: WEBHOOK_EVENT_MODEL,
1051
+ where: [
1052
+ { field: "status", value: "pending" },
1053
+ {
1054
+ field: "lockedAt",
1055
+ operator: "lt",
1056
+ value: new Date(now.getTime() - WEBHOOK_PROCESSING_LEASE_MS)
1057
+ }
1058
+ ],
1059
+ limit,
1060
+ sortBy: { field: "lockedAt", direction: "asc" }
1061
+ })
1062
+ ]);
1063
+ const byId = new Map([...retryDue, ...abandoned].map((row) => [row.id, row]));
1064
+ return [...byId.values()].slice(0, limit);
1065
+ }
918
1066
  async function claimOrAdvanceWebhookEvent(ctx, payload, rawBody, signatureHeader, maxAttempts, scope) {
919
1067
  const sourceEventId = extractEventId(payload);
920
1068
  const eventId = sourceEventId && (scope ? `${scope}:${sourceEventId}` : sourceEventId);
@@ -1173,12 +1321,77 @@ var SubscriptionCorrelationError = class extends Error {
1173
1321
  this.name = "SubscriptionCorrelationError";
1174
1322
  }
1175
1323
  };
1176
- async function updateReconciledSubscription(ctx, existing, projected, streampaySubscriptionId) {
1324
+ async function takeSlotFromReservation(ctx, client, slotKey, ownerRowId, streampaySubscriptionId) {
1325
+ const holder = await ctx.context.adapter.findOne({
1326
+ model: SUBSCRIPTION_MODEL2,
1327
+ where: [{ field: "activeSlotKey", value: slotKey }]
1328
+ });
1329
+ if (!holder || holder.id === ownerRowId) return;
1330
+ if (holder.status !== "incomplete" || holder.streampaySubscriptionId) {
1331
+ throw new SubscriptionCorrelationError(
1332
+ `StreamPay sub=${streampaySubscriptionId} needs the billing slot held by live row=${holder.id} (${holder.status}). Resolve the duplicate subscription, then replay.`
1333
+ );
1334
+ }
1335
+ if (holder.streampayPaymentLinkId) {
1336
+ try {
1337
+ await deactivatePaymentLink(client, holder.streampayPaymentLinkId, logger(ctx));
1338
+ } catch (err) {
1339
+ const message = err instanceof Error ? err.message : String(err);
1340
+ logger(ctx).error(
1341
+ `payment link=${holder.streampayPaymentLinkId} of released row=${holder.id} could not be deactivated and may still be paid; deactivate it manually: ${message}`
1342
+ );
1343
+ }
1344
+ }
1345
+ const released = await ctx.context.adapter.update({
1346
+ model: SUBSCRIPTION_MODEL2,
1347
+ update: { status: "incomplete_expired", activeSlotKey: null, updatedAt: /* @__PURE__ */ new Date() },
1348
+ where: [
1349
+ { field: "id", value: holder.id },
1350
+ { field: "status", value: "incomplete" },
1351
+ { field: "activeSlotKey", value: slotKey },
1352
+ { field: "streampayPaymentLinkId", value: holder.streampayPaymentLinkId ?? null }
1353
+ ]
1354
+ });
1355
+ if (!released) {
1356
+ throw new Error(`Checkout reservation row=${holder.id} changed while releasing its slot.`);
1357
+ }
1358
+ logger(ctx).warn(
1359
+ `released checkout reservation row=${holder.id} for paid StreamPay sub=${streampaySubscriptionId}.`
1360
+ );
1361
+ }
1362
+ async function linkReservedRow(ctx, client, row, projected, metadataReferenceType, streampaySubscriptionId) {
1363
+ const activeSlotKey = projected.activeSlotKey === null ? null : row.activeSlotKey ?? subscriptionSlotKey(
1364
+ row.referenceType ?? metadataReferenceType ?? "user",
1365
+ row.referenceId,
1366
+ projected.group === void 0 ? row.group : projected.group
1367
+ );
1368
+ return updateReconciledSubscription(
1369
+ ctx,
1370
+ client,
1371
+ row,
1372
+ {
1373
+ ...projected,
1374
+ billingStatus: row.billingStatus ?? "current",
1375
+ ...activeSlotKey === null ? {} : { activeSlotKey }
1376
+ },
1377
+ streampaySubscriptionId
1378
+ );
1379
+ }
1380
+ async function updateReconciledSubscription(ctx, client, existing, projected, streampaySubscriptionId) {
1177
1381
  if (existing.providerUpdatedAt instanceof Date && projected.providerUpdatedAt instanceof Date && projected.providerUpdatedAt.getTime() < existing.providerUpdatedAt.getTime()) {
1178
1382
  throw new Error(
1179
1383
  `StreamPay returned stale subscription state for sub=${streampaySubscriptionId}. Retry reconciliation.`
1180
1384
  );
1181
1385
  }
1386
+ if (projected.activeSlotKey && projected.activeSlotKey !== existing.activeSlotKey) {
1387
+ await takeSlotFromReservation(
1388
+ ctx,
1389
+ client,
1390
+ projected.activeSlotKey,
1391
+ existing.id,
1392
+ streampaySubscriptionId
1393
+ );
1394
+ }
1182
1395
  const updated = await ctx.context.adapter.update({
1183
1396
  model: SUBSCRIPTION_MODEL2,
1184
1397
  update: projected,
@@ -1254,6 +1467,7 @@ async function reconcileFromStreamPay(ctx, payload, client, plans) {
1254
1467
  }
1255
1468
  const updated = await updateReconciledSubscription(
1256
1469
  ctx,
1470
+ client,
1257
1471
  existing,
1258
1472
  projected,
1259
1473
  streampaySubscriptionId
@@ -1287,21 +1501,12 @@ async function reconcileFromStreamPay(ctx, payload, client, plans) {
1287
1501
  `webhook ${payload.event_type}: referenced subscription row=${localRowId} is missing; rebuilding from signed metadata.`
1288
1502
  );
1289
1503
  } 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)) {
1290
- const projectedWithSlot = {
1291
- ...projected,
1292
- billingStatus: metadataRow.billingStatus ?? "current",
1293
- ...projected.activeSlotKey === null ? {} : {
1294
- activeSlotKey: metadataRow.activeSlotKey ?? subscriptionSlotKey(
1295
- metadataRow.referenceType ?? metadataReferenceType ?? "user",
1296
- metadataRow.referenceId,
1297
- projected.group === void 0 ? metadataRow.group : projected.group
1298
- )
1299
- }
1300
- };
1301
- const updated = await updateReconciledSubscription(
1504
+ const updated = await linkReservedRow(
1302
1505
  ctx,
1506
+ client,
1303
1507
  metadataRow,
1304
- projectedWithSlot,
1508
+ projected,
1509
+ metadataReferenceType,
1305
1510
  streampaySubscriptionId
1306
1511
  );
1307
1512
  return { row: updated, stream };
@@ -1324,30 +1529,22 @@ async function reconcileFromStreamPay(ctx, payload, client, plans) {
1324
1529
  stream.organization_consumer_id ?? null
1325
1530
  );
1326
1531
  if (incomplete) {
1327
- const projectedWithSlot = {
1328
- ...projected,
1329
- billingStatus: incomplete.billingStatus ?? "current",
1330
- ...projected.activeSlotKey === null ? {} : {
1331
- activeSlotKey: incomplete.activeSlotKey ?? subscriptionSlotKey(
1332
- incomplete.referenceType ?? metadataReferenceType ?? "user",
1333
- incomplete.referenceId,
1334
- projected.group === void 0 ? incomplete.group : projected.group
1335
- )
1336
- }
1337
- };
1338
- const updated = await updateReconciledSubscription(
1532
+ const updated = await linkReservedRow(
1339
1533
  ctx,
1534
+ client,
1340
1535
  incomplete,
1341
- projectedWithSlot,
1536
+ projected,
1537
+ metadataReferenceType,
1342
1538
  streampaySubscriptionId
1343
1539
  );
1344
- return {
1345
- row: updated,
1346
- stream
1347
- };
1540
+ return { row: updated, stream };
1348
1541
  }
1349
1542
  const plan = plans.byName.get(planName);
1350
1543
  const referenceType = metadataReferenceType ?? "custom";
1544
+ const activeSlotKey = isTerminalSubscriptionStatus(projected.status) ? null : subscriptionSlotKey(referenceType, referenceId, plan?.group);
1545
+ if (activeSlotKey) {
1546
+ await takeSlotFromReservation(ctx, client, activeSlotKey, null, streampaySubscriptionId);
1547
+ }
1351
1548
  const row = await ctx.context.adapter.create({
1352
1549
  model: SUBSCRIPTION_MODEL2,
1353
1550
  data: {
@@ -1356,7 +1553,7 @@ async function reconcileFromStreamPay(ctx, payload, client, plans) {
1356
1553
  ...projected,
1357
1554
  referenceId,
1358
1555
  referenceType,
1359
- activeSlotKey: isTerminalSubscriptionStatus(projected.status) ? null : subscriptionSlotKey(referenceType, referenceId, plan?.group),
1556
+ activeSlotKey,
1360
1557
  streampayPaymentLinkId: paymentLinkId,
1361
1558
  plan: planName,
1362
1559
  planVersion: plan?.version ?? null,
@@ -1380,6 +1577,9 @@ async function syncWebhookPayload(ctx, payload, client, plans, callbacks, option
1380
1577
  let claim = { action: "process", row: null };
1381
1578
  if (dedupe) {
1382
1579
  claim = await claimOrAdvanceWebhookEvent(ctx, payload, rawBody, signatureHeader, maxAttempts);
1580
+ if (claim.action === "skip" && claim.reason === "in_progress") {
1581
+ throw new WebhookEventInProgressError(payload.event_type);
1582
+ }
1383
1583
  if (claim.action === "skip") return;
1384
1584
  if (claim.action === "dead_letter") {
1385
1585
  logger(ctx).warn(
@@ -3223,6 +3423,12 @@ function checkoutInProgressError() {
3223
3423
  message: "A subscription checkout is already being created for this plan group."
3224
3424
  });
3225
3425
  }
3426
+ function subscriptionAlreadyActiveError() {
3427
+ return new api.APIError("CONFLICT", {
3428
+ code: $ERROR_CODES.SUBSCRIPTION_ALREADY_ACTIVE.code,
3429
+ message: "An active subscription already exists for this plan group."
3430
+ });
3431
+ }
3226
3432
  async function resumeOrReserveCheckoutSlot(args) {
3227
3433
  const { client, adapter, candidates, activeSlotKey, planName, seats, now, log } = args;
3228
3434
  const matchesCheckout = (row2) => row2.plan === planName && (row2.seats ?? 1) === seats;
@@ -3269,7 +3475,8 @@ async function resumeOrReserveCheckoutSlot(args) {
3269
3475
  model: SUBSCRIPTION_MODEL4,
3270
3476
  where: [{ field: "activeSlotKey", value: activeSlotKey }]
3271
3477
  });
3272
- if (reserved?.status !== "incomplete") throw err;
3478
+ if (!reserved) throw err;
3479
+ if (reserved.status !== "incomplete") throw subscriptionAlreadyActiveError();
3273
3480
  if (matchesCheckout(reserved)) {
3274
3481
  let recovery;
3275
3482
  try {
@@ -3290,6 +3497,20 @@ async function resumeOrReserveCheckoutSlot(args) {
3290
3497
  }
3291
3498
  const reservationIsStale = !(reserved.createdAt instanceof Date) || now - reserved.createdAt.getTime() >= UPGRADE_IDEMPOTENCY_WINDOW_MS;
3292
3499
  if (!reservationIsStale) throw checkoutInProgressError();
3500
+ if (reserved.streampayPaymentLinkId) {
3501
+ try {
3502
+ await deactivatePaymentLink(client, reserved.streampayPaymentLinkId, log);
3503
+ } catch (deactivationError) {
3504
+ toAPIError(
3505
+ {
3506
+ logPrefix: `deactivate stale checkout link=${reserved.streampayPaymentLinkId} failed for row=${reserved.id}:`,
3507
+ userMessage: "Unable to replace the previous subscription checkout."
3508
+ },
3509
+ deactivationError,
3510
+ log
3511
+ );
3512
+ }
3513
+ }
3293
3514
  const released = await adapter.update({
3294
3515
  model: SUBSCRIPTION_MODEL4,
3295
3516
  update: { status: "incomplete_expired", activeSlotKey: null, updatedAt: /* @__PURE__ */ new Date() },
@@ -3313,105 +3534,6 @@ async function resumeOrReserveCheckoutSlot(args) {
3313
3534
  }
3314
3535
  return { kind: "reserved", row, consumerId };
3315
3536
  }
3316
- function isAlreadyCanceledFreezeError(err) {
3317
- const sdkError = readSdkErrorFields(err);
3318
- const envelope = readEnvelope(sdkError.body);
3319
- return sdkError.status === 403 && envelope?.code === "STREAM_ERROR" && envelope.additionalInfo === "Cannot delete non-latest freeze entry.";
3320
- }
3321
- function subscriptionCouponIds(stream) {
3322
- return couponIdsFromMetadata(stream.coupon_calculation_metadata);
3323
- }
3324
- function couponIdsFromMetadata(metadata) {
3325
- const coupons = [];
3326
- for (const coupon of metadata?.coupons ?? []) {
3327
- if (coupon.coupon_id) coupons.push(coupon.coupon_id);
3328
- }
3329
- return coupons;
3330
- }
3331
- function subscriptionItemsForUpdate(stream, currentProductId, targetProductId, targetSeats) {
3332
- if (!stream.items?.length) {
3333
- throw invalidProviderItems("StreamPay returned a subscription without any items.");
3334
- }
3335
- const subscriptionCoupons = new Set(subscriptionCouponIds(stream));
3336
- let matches = 0;
3337
- const items = stream.items.map((item) => {
3338
- const productId = subscriptionItemProductId(item);
3339
- const quantity = item.quantity ?? 1;
3340
- if (!productId || !Number.isSafeInteger(quantity) || quantity < 1) {
3341
- throw invalidProviderItems("StreamPay returned an invalid subscription item.");
3342
- }
3343
- const isPlanItem = productId === currentProductId;
3344
- if (isPlanItem) matches += 1;
3345
- const itemCoupons = couponIdsFromMetadata(item.coupon_calculation_metadata).filter(
3346
- (couponId) => !subscriptionCoupons.has(couponId)
3347
- );
3348
- return {
3349
- product_id: isPlanItem ? targetProductId : productId,
3350
- quantity: isPlanItem ? targetSeats : quantity,
3351
- ...itemCoupons.length > 0 ? { coupons: itemCoupons } : {}
3352
- };
3353
- });
3354
- if (matches !== 1) {
3355
- throw invalidProviderItems(
3356
- `Expected exactly one plan item for product "${currentProductId}", received ${matches}.`
3357
- );
3358
- }
3359
- return items;
3360
- }
3361
- function invalidProviderItems(message) {
3362
- return new api.APIError("INTERNAL_SERVER_ERROR", {
3363
- code: $ERROR_CODES.SUBSCRIPTION_INVALID_STATE.code,
3364
- message
3365
- });
3366
- }
3367
- function configuredPlanForSubscription(subscription, plans) {
3368
- const matches = plans.list.filter(
3369
- (plan) => subscription.items?.some((item) => subscriptionItemProductId(item) === plan.productId)
3370
- );
3371
- if (matches.length > 1) {
3372
- throw invalidProviderItems(
3373
- "StreamPay returned a subscription containing multiple configured plan products."
3374
- );
3375
- }
3376
- return matches[0];
3377
- }
3378
- async function findSubscriptionFreeze(client, options, subscriptionId, matches) {
3379
- const listPage = options.listSubscriptionFreezes;
3380
- if (!listPage) {
3381
- const response = await client.listSubscriptionFreezes(subscriptionId);
3382
- return {
3383
- freeze: response.data?.find(matches),
3384
- hasMore: response.pagination?.has_next_page ?? false
3385
- };
3386
- }
3387
- const seenIds = /* @__PURE__ */ new Set();
3388
- for (let page = 1; page <= 100; page++) {
3389
- const response = await listPage(subscriptionId, { page, limit: 100 });
3390
- const pagination = response.pagination;
3391
- if (!Array.isArray(response.data) || !pagination || pagination.current_page !== page || typeof pagination.has_next_page !== "boolean") {
3392
- throw freezePaginationConflict("StreamPay returned invalid freeze pagination.");
3393
- }
3394
- let advanced = false;
3395
- for (const freeze2 of response.data) {
3396
- if (freeze2.id && !seenIds.has(freeze2.id)) {
3397
- seenIds.add(freeze2.id);
3398
- advanced = true;
3399
- }
3400
- }
3401
- if (!advanced && (pagination.has_next_page || response.data.length > 0)) {
3402
- throw freezePaginationConflict("StreamPay freeze pagination returned no new entries.");
3403
- }
3404
- const freeze = response.data.find(matches);
3405
- if (freeze || !pagination.has_next_page) return { freeze, hasMore: false };
3406
- }
3407
- throw freezePaginationConflict("StreamPay freeze pagination exceeded 100 pages.");
3408
- }
3409
- function freezePaginationConflict(message) {
3410
- return new api.APIError("CONFLICT", {
3411
- code: $ERROR_CODES.SUBSCRIPTION_INVALID_STATE.code,
3412
- message
3413
- });
3414
- }
3415
3537
  var SUBSCRIPTION_INTERVALS = ["WEEK", "MONTH", "QUARTER", "YEAR"];
3416
3538
  var PlanSchema = zod.z.object({
3417
3539
  name: zod.z.string().min(1, "every plan must have a non-empty `name`."),
@@ -4076,6 +4198,24 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
4076
4198
  `failed to persist payment link=${paymentLinkId} for row=${row.id}: ${message}. Protected checkout metadata will reconcile the row from the webhook.`
4077
4199
  );
4078
4200
  }
4201
+ if (updatedRow?.status === "incomplete_expired") {
4202
+ getLogger(ctx).warn(
4203
+ `checkout reservation row=${row.id} was released while payment link=${paymentLinkId} was created; deactivating the link.`
4204
+ );
4205
+ try {
4206
+ await deactivatePaymentLink(client, paymentLinkId, getLogger(ctx));
4207
+ } catch (deactivationError) {
4208
+ toAPIError(
4209
+ {
4210
+ logPrefix: `deactivate orphaned checkout link=${paymentLinkId} failed for row=${row.id}:`,
4211
+ userMessage: "Failed to start subscription checkout."
4212
+ },
4213
+ deactivationError,
4214
+ getLogger(ctx)
4215
+ );
4216
+ }
4217
+ throw checkoutInProgressError();
4218
+ }
4079
4219
  return ctx.json({
4080
4220
  subscriptionId: updatedRow?.id ?? row.id,
4081
4221
  url,
@@ -5105,6 +5245,7 @@ function subscriptions(subsOptions) {
5105
5245
  }
5106
5246
  const payload = parsedPayload;
5107
5247
  const plans = await plansRef();
5248
+ const previousStatus = row.status;
5108
5249
  const claimed = await claimWebhookEventForReplay(syncCtx, row);
5109
5250
  if (!claimed?.lockedBy) {
5110
5251
  throw new api.APIError("CONFLICT", {
@@ -5115,6 +5256,7 @@ function subscriptions(subsOptions) {
5115
5256
  try {
5116
5257
  await syncWebhookPayload(syncCtx, payload, options.client, plans, subsOptions, {
5117
5258
  dedupe: false,
5259
+ retryOnCallbackError: subsOptions.retryOnCallbackError !== false,
5118
5260
  retryingRenewalCallback: claimed.lastError?.startsWith(
5119
5261
  "Subscription callback onSubscriptionRenewed failed:"
5120
5262
  ) === true
@@ -5122,6 +5264,7 @@ function subscriptions(subsOptions) {
5122
5264
  await markWebhookEventCompleted(syncCtx, claimed.id, claimed.lockedBy);
5123
5265
  return { replayed: true, eventId };
5124
5266
  } catch (err) {
5267
+ const maxAttempts = subsOptions.maxWebhookAttempts ?? DEFAULT_MAX_WEBHOOK_ATTEMPTS;
5125
5268
  await recordWebhookEventFailure(
5126
5269
  syncCtx,
5127
5270
  claimed.id,
@@ -5129,7 +5272,7 @@ function subscriptions(subsOptions) {
5129
5272
  null,
5130
5273
  err,
5131
5274
  claimed.lockedBy,
5132
- true
5275
+ previousStatus === "dead_letter" || classifyWebhookFailure(err) === "PERMANENT" || claimed.attemptCount >= maxAttempts
5133
5276
  );
5134
5277
  throw err;
5135
5278
  }
@@ -5308,6 +5451,13 @@ function verifyWebhookOrThrow(input) {
5308
5451
  }
5309
5452
 
5310
5453
  // src/plugins/webhooks.ts
5454
+ var DEFAULT_DUE_WEBHOOK_BATCH = 25;
5455
+ var ProcessDueWebhookEventsBody = zod.z.object({ limit: zod.z.number().int().min(1).max(100).optional() }).optional();
5456
+ function inProgressError() {
5457
+ return new api.APIError("SERVICE_UNAVAILABLE", {
5458
+ message: "Webhook event is already being processed. Retry later."
5459
+ });
5460
+ }
5311
5461
  function toErrorCode(reason) {
5312
5462
  return reason === "MISSING_HEADER" || reason === "INVALID_SIGNATURE" || reason === "EXPIRED" ? "UNAUTHORIZED" : "BAD_REQUEST";
5313
5463
  }
@@ -5344,6 +5494,7 @@ var webhooks = (webhooksOptions) => {
5344
5494
  throw new api.APIError("BAD_REQUEST", {
5345
5495
  message: "Stored webhook payload is not a valid event envelope."
5346
5496
  });
5497
+ const previousStatus = row.status;
5347
5498
  const claimed = await claimWebhookEventForReplay(syncContext, row);
5348
5499
  if (!claimed?.lockedBy)
5349
5500
  throw new api.APIError("CONFLICT", {
@@ -5360,7 +5511,7 @@ var webhooks = (webhooksOptions) => {
5360
5511
  row.signatureHeader,
5361
5512
  err,
5362
5513
  claimed.lockedBy,
5363
- true
5514
+ previousStatus === "dead_letter" || claimed.attemptCount >= DEFAULT_MAX_WEBHOOK_ATTEMPTS
5364
5515
  );
5365
5516
  throw err;
5366
5517
  }
@@ -5422,6 +5573,7 @@ var webhooks = (webhooksOptions) => {
5422
5573
  signatureHeader
5423
5574
  });
5424
5575
  } catch (err) {
5576
+ if (err instanceof WebhookEventInProgressError) throw inProgressError();
5425
5577
  const message = err instanceof Error ? err.message : String(err);
5426
5578
  logger2.error(`subscription sync failed: ${message}`);
5427
5579
  throw new api.APIError("INTERNAL_SERVER_ERROR", {
@@ -5438,6 +5590,7 @@ var webhooks = (webhooksOptions) => {
5438
5590
  DEFAULT_MAX_WEBHOOK_ATTEMPTS,
5439
5591
  "handlers"
5440
5592
  ) : null;
5593
+ if (claim?.action === "skip" && claim.reason === "in_progress") throw inProgressError();
5441
5594
  if (claim && claim.action !== "process") return ctx.json({ received: true });
5442
5595
  const row = claim?.action === "process" ? claim.row : null;
5443
5596
  try {
@@ -5463,6 +5616,48 @@ var webhooks = (webhooksOptions) => {
5463
5616
  }
5464
5617
  return ctx.json({ received: true });
5465
5618
  }
5619
+ ),
5620
+ processDueStreampayWebhookEvents: api.createAuthEndpoint(
5621
+ "/streampay/webhooks/process-due",
5622
+ {
5623
+ method: "POST",
5624
+ body: ProcessDueWebhookEventsBody,
5625
+ metadata: { SERVER_ONLY: true }
5626
+ },
5627
+ async (ctx) => {
5628
+ const replay = registry?.replayWebhookEvent;
5629
+ if (!replay) {
5630
+ throw new api.APIError("BAD_REQUEST", {
5631
+ message: "Retry processing requires the webhook inbox: enable subscriptions or webhooks({ deduplicate: true })."
5632
+ });
5633
+ }
5634
+ const syncContext = { context: ctx.context };
5635
+ const due = await findDueWebhookEvents(
5636
+ syncContext,
5637
+ /* @__PURE__ */ new Date(),
5638
+ ctx.body?.limit ?? DEFAULT_DUE_WEBHOOK_BATCH
5639
+ );
5640
+ const succeeded = [];
5641
+ const failed = [];
5642
+ for (const row of due) {
5643
+ try {
5644
+ await replay(ctx, row.eventId);
5645
+ succeeded.push(row.eventId);
5646
+ } catch (err) {
5647
+ if (err instanceof api.APIError && err.status === "CONFLICT") continue;
5648
+ failed.push({
5649
+ eventId: row.eventId,
5650
+ error: err instanceof Error ? err.message : String(err)
5651
+ });
5652
+ }
5653
+ }
5654
+ if (failed.length > 0) {
5655
+ getLogger(ctx).error(
5656
+ `webhook retry: ${failed.length} of ${due.length} due events failed again`
5657
+ );
5658
+ }
5659
+ return ctx.json({ succeeded, failed });
5660
+ }
5466
5661
  )
5467
5662
  }
5468
5663
  };
@@ -5587,7 +5782,7 @@ var onUserDelete = (options) => async (user, context) => {
5587
5782
 
5588
5783
  // package.json
5589
5784
  var package_default = {
5590
- version: "3.0.2"};
5785
+ version: "3.2.0"};
5591
5786
 
5592
5787
  // src/version.ts
5593
5788
  var version = package_default.version;