better-auth-streampay 3.1.0 → 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/index.d.cts CHANGED
@@ -1,5 +1,5 @@
1
- import { a as StreamPayClient } from './streampay-Bij1FvXa.cjs';
2
- export { $ as $ERROR_CODES, A as AdminOptions, b as AuthorizeReferenceContext, C as CheckoutBody, c as CheckoutCreatedContext, d as CheckoutOptions, e as CheckoutOverrides, f as CheckoutParams, g as CheckoutResolutionContext, h as ClaimExistingConsumerBy, i as ClaimExistingConsumerIdentifier, j as ConsumerCreateOverrides, D as DEFAULT_ACCESS_STATUSES, F as FeatureKey, L as LimitCheckResult, P as PLAN_NAME_METADATA_KEY, k as PluginAdapter, l as PortalOptions, R as REFERENCE_ID_METADATA_KEY, m as REFERENCE_TYPE_METADATA_KEY, n as ResolvedPlans, o as STREAMPAY_EVENT_TYPES, p as STREAMPAY_INVOICE_EVENT_TYPES, q as STREAMPAY_PAYMENT_EVENT_TYPES, r as STREAMPAY_PAYMENT_LINK_EVENT_TYPES, t as STREAMPAY_SUBSCRIPTION_EVENT_TYPES, u as SUBSCRIPTION_ROW_ID_METADATA_KEY, v as StreamPayCustomFieldDefinition, w as StreamPayCustomFieldsSchema, x as StreamPayEndpoints, y as StreamPayEntityType, S as StreamPayErrorCode, z as StreamPayEventType, B as StreamPayHookContext, G as StreamPayInvoiceEventType, H as StreamPayOptions, I as StreamPayPaymentEventType, J as StreamPayPaymentLinkEventType, K as StreamPayPlan, M as StreamPayPlanLike, N as StreamPayPlugin, O as StreamPayPluginRegistry, Q as StreamPayPlugins, T as StreamPayProduct, U as StreamPaySeatBilling, V as StreamPaySubscriptionEventType, W as StreamPayWebhookData, X as StreamPayWebhookEnvelope, Y as StreamPayWebhookPayload, Z as Subscription, _ as SubscriptionBillingStatus, a0 as SubscriptionCallback, a1 as SubscriptionCallbackData, a2 as SubscriptionCallbacks, a3 as SubscriptionReferenceType, a4 as SubscriptionStatus, a5 as SubscriptionsOptions, a6 as SyncContext, a7 as TrialEligibilityContext, a8 as WebhookEnvelopeHandler, a9 as WebhookHandler, aa as WebhookHandlers, ab as WebhookSyncFailure, ac as WebhooksOptions, ad as admin, ae as checkLimit, af as checkout, ag as classifyWebhookFailure, ah as dispatchWebhook, ai as hasFeature, aj as hasSubscriptionAccess, ak as isKnownStreamPayWebhookPayload, al as isStreamPayWebhookEnvelope, am as mapToErrorCode, an as portal, s as streampay, ao as subscriptionSlotKey, ap as subscriptions, aq as syncWebhookPayload, ar as webhooks } from './streampay-Bij1FvXa.cjs';
1
+ import { a as StreamPayClient } from './streampay-B7cFK2CP.cjs';
2
+ export { $ as $ERROR_CODES, A as AdminOptions, b as AuthorizeReferenceContext, C as CheckoutBody, c as CheckoutCreatedContext, d as CheckoutOptions, e as CheckoutOverrides, f as CheckoutParams, g as CheckoutResolutionContext, h as ClaimExistingConsumerBy, i as ClaimExistingConsumerIdentifier, j as ConsumerCreateOverrides, D as DEFAULT_ACCESS_STATUSES, F as FeatureKey, L as LimitCheckResult, P as PLAN_NAME_METADATA_KEY, k as PluginAdapter, l as PortalOptions, R as REFERENCE_ID_METADATA_KEY, m as REFERENCE_TYPE_METADATA_KEY, n as ResolvedPlans, o as STREAMPAY_EVENT_TYPES, p as STREAMPAY_INVOICE_EVENT_TYPES, q as STREAMPAY_PAYMENT_EVENT_TYPES, r as STREAMPAY_PAYMENT_LINK_EVENT_TYPES, t as STREAMPAY_SUBSCRIPTION_EVENT_TYPES, u as SUBSCRIPTION_ROW_ID_METADATA_KEY, v as StreamPayCustomFieldDefinition, w as StreamPayCustomFieldsSchema, x as StreamPayEndpoints, y as StreamPayEntityType, S as StreamPayErrorCode, z as StreamPayEventType, B as StreamPayHookContext, G as StreamPayInvoiceEventType, H as StreamPayOptions, I as StreamPayPaymentEventType, J as StreamPayPaymentLinkEventType, K as StreamPayPlan, M as StreamPayPlanLike, N as StreamPayPlugin, O as StreamPayPluginRegistry, Q as StreamPayPlugins, T as StreamPayProduct, U as StreamPaySeatBilling, V as StreamPaySubscriptionEventType, W as StreamPayWebhookData, X as StreamPayWebhookEnvelope, Y as StreamPayWebhookPayload, Z as Subscription, _ as SubscriptionBillingStatus, a0 as SubscriptionCallback, a1 as SubscriptionCallbackData, a2 as SubscriptionCallbacks, a3 as SubscriptionReferenceType, a4 as SubscriptionStatus, a5 as SubscriptionsOptions, a6 as SyncContext, a7 as TrialEligibilityContext, a8 as WebhookEnvelopeHandler, a9 as WebhookHandler, aa as WebhookHandlers, ab as WebhookSyncFailure, ac as WebhooksOptions, ad as admin, ae as checkLimit, af as checkout, ag as classifyWebhookFailure, ah as dispatchWebhook, ai as hasFeature, aj as hasSubscriptionAccess, ak as isKnownStreamPayWebhookPayload, al as isStreamPayWebhookEnvelope, am as mapToErrorCode, an as portal, s as streampay, ao as subscriptionSlotKey, ap as subscriptions, aq as syncWebhookPayload, ar as webhooks } from './streampay-B7cFK2CP.cjs';
3
3
  import { InvoiceDetailed, PaymentResponse, ConsumerResponse } from '@streamsdk/typescript';
4
4
  import 'better-auth';
5
5
  import 'zod';
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { a as StreamPayClient } from './streampay-Bij1FvXa.js';
2
- export { $ as $ERROR_CODES, A as AdminOptions, b as AuthorizeReferenceContext, C as CheckoutBody, c as CheckoutCreatedContext, d as CheckoutOptions, e as CheckoutOverrides, f as CheckoutParams, g as CheckoutResolutionContext, h as ClaimExistingConsumerBy, i as ClaimExistingConsumerIdentifier, j as ConsumerCreateOverrides, D as DEFAULT_ACCESS_STATUSES, F as FeatureKey, L as LimitCheckResult, P as PLAN_NAME_METADATA_KEY, k as PluginAdapter, l as PortalOptions, R as REFERENCE_ID_METADATA_KEY, m as REFERENCE_TYPE_METADATA_KEY, n as ResolvedPlans, o as STREAMPAY_EVENT_TYPES, p as STREAMPAY_INVOICE_EVENT_TYPES, q as STREAMPAY_PAYMENT_EVENT_TYPES, r as STREAMPAY_PAYMENT_LINK_EVENT_TYPES, t as STREAMPAY_SUBSCRIPTION_EVENT_TYPES, u as SUBSCRIPTION_ROW_ID_METADATA_KEY, v as StreamPayCustomFieldDefinition, w as StreamPayCustomFieldsSchema, x as StreamPayEndpoints, y as StreamPayEntityType, S as StreamPayErrorCode, z as StreamPayEventType, B as StreamPayHookContext, G as StreamPayInvoiceEventType, H as StreamPayOptions, I as StreamPayPaymentEventType, J as StreamPayPaymentLinkEventType, K as StreamPayPlan, M as StreamPayPlanLike, N as StreamPayPlugin, O as StreamPayPluginRegistry, Q as StreamPayPlugins, T as StreamPayProduct, U as StreamPaySeatBilling, V as StreamPaySubscriptionEventType, W as StreamPayWebhookData, X as StreamPayWebhookEnvelope, Y as StreamPayWebhookPayload, Z as Subscription, _ as SubscriptionBillingStatus, a0 as SubscriptionCallback, a1 as SubscriptionCallbackData, a2 as SubscriptionCallbacks, a3 as SubscriptionReferenceType, a4 as SubscriptionStatus, a5 as SubscriptionsOptions, a6 as SyncContext, a7 as TrialEligibilityContext, a8 as WebhookEnvelopeHandler, a9 as WebhookHandler, aa as WebhookHandlers, ab as WebhookSyncFailure, ac as WebhooksOptions, ad as admin, ae as checkLimit, af as checkout, ag as classifyWebhookFailure, ah as dispatchWebhook, ai as hasFeature, aj as hasSubscriptionAccess, ak as isKnownStreamPayWebhookPayload, al as isStreamPayWebhookEnvelope, am as mapToErrorCode, an as portal, s as streampay, ao as subscriptionSlotKey, ap as subscriptions, aq as syncWebhookPayload, ar as webhooks } from './streampay-Bij1FvXa.js';
1
+ import { a as StreamPayClient } from './streampay-B7cFK2CP.js';
2
+ export { $ as $ERROR_CODES, A as AdminOptions, b as AuthorizeReferenceContext, C as CheckoutBody, c as CheckoutCreatedContext, d as CheckoutOptions, e as CheckoutOverrides, f as CheckoutParams, g as CheckoutResolutionContext, h as ClaimExistingConsumerBy, i as ClaimExistingConsumerIdentifier, j as ConsumerCreateOverrides, D as DEFAULT_ACCESS_STATUSES, F as FeatureKey, L as LimitCheckResult, P as PLAN_NAME_METADATA_KEY, k as PluginAdapter, l as PortalOptions, R as REFERENCE_ID_METADATA_KEY, m as REFERENCE_TYPE_METADATA_KEY, n as ResolvedPlans, o as STREAMPAY_EVENT_TYPES, p as STREAMPAY_INVOICE_EVENT_TYPES, q as STREAMPAY_PAYMENT_EVENT_TYPES, r as STREAMPAY_PAYMENT_LINK_EVENT_TYPES, t as STREAMPAY_SUBSCRIPTION_EVENT_TYPES, u as SUBSCRIPTION_ROW_ID_METADATA_KEY, v as StreamPayCustomFieldDefinition, w as StreamPayCustomFieldsSchema, x as StreamPayEndpoints, y as StreamPayEntityType, S as StreamPayErrorCode, z as StreamPayEventType, B as StreamPayHookContext, G as StreamPayInvoiceEventType, H as StreamPayOptions, I as StreamPayPaymentEventType, J as StreamPayPaymentLinkEventType, K as StreamPayPlan, M as StreamPayPlanLike, N as StreamPayPlugin, O as StreamPayPluginRegistry, Q as StreamPayPlugins, T as StreamPayProduct, U as StreamPaySeatBilling, V as StreamPaySubscriptionEventType, W as StreamPayWebhookData, X as StreamPayWebhookEnvelope, Y as StreamPayWebhookPayload, Z as Subscription, _ as SubscriptionBillingStatus, a0 as SubscriptionCallback, a1 as SubscriptionCallbackData, a2 as SubscriptionCallbacks, a3 as SubscriptionReferenceType, a4 as SubscriptionStatus, a5 as SubscriptionsOptions, a6 as SyncContext, a7 as TrialEligibilityContext, a8 as WebhookEnvelopeHandler, a9 as WebhookHandler, aa as WebhookHandlers, ab as WebhookSyncFailure, ac as WebhooksOptions, ad as admin, ae as checkLimit, af as checkout, ag as classifyWebhookFailure, ah as dispatchWebhook, ai as hasFeature, aj as hasSubscriptionAccess, ak as isKnownStreamPayWebhookPayload, al as isStreamPayWebhookEnvelope, am as mapToErrorCode, an as portal, s as streampay, ao as subscriptionSlotKey, ap as subscriptions, aq as syncWebhookPayload, ar as webhooks } from './streampay-B7cFK2CP.js';
3
3
  import { InvoiceDetailed, PaymentResponse, ConsumerResponse } from '@streamsdk/typescript';
4
4
  import 'better-auth';
5
5
  import 'zod';
package/dist/index.js CHANGED
@@ -877,6 +877,120 @@ function projectPlanFields(sub, plans) {
877
877
  pendingSeatsEffectiveAt: pendingSeats === null ? null : pendingEffectiveAt
878
878
  };
879
879
  }
880
+
881
+ // src/plugins/subscriptions/lifecycle.ts
882
+ function isAlreadyCanceledFreezeError(err) {
883
+ const sdkError = readSdkErrorFields(err);
884
+ const envelope = readEnvelope(sdkError.body);
885
+ return sdkError.status === 403 && envelope?.code === "STREAM_ERROR" && envelope.additionalInfo === "Cannot delete non-latest freeze entry.";
886
+ }
887
+ async function deactivatePaymentLink(client, paymentLinkId, log) {
888
+ if (!client.updatePaymentLinkStatus) {
889
+ log.warn(
890
+ `payment link=${paymentLinkId} stays payable: client does not implement updatePaymentLinkStatus.`
891
+ );
892
+ return;
893
+ }
894
+ try {
895
+ await client.updatePaymentLinkStatus(paymentLinkId, { status: "INACTIVE" });
896
+ } catch (err) {
897
+ if (readSdkErrorFields(err).status !== 404) throw err;
898
+ }
899
+ }
900
+ function subscriptionCouponIds(stream) {
901
+ return couponIdsFromMetadata(stream.coupon_calculation_metadata);
902
+ }
903
+ function couponIdsFromMetadata(metadata) {
904
+ const coupons = [];
905
+ for (const coupon of metadata?.coupons ?? []) {
906
+ if (coupon.coupon_id) coupons.push(coupon.coupon_id);
907
+ }
908
+ return coupons;
909
+ }
910
+ function subscriptionItemsForUpdate(stream, currentProductId, targetProductId, targetSeats) {
911
+ if (!stream.items?.length) {
912
+ throw invalidProviderItems("StreamPay returned a subscription without any items.");
913
+ }
914
+ const subscriptionCoupons = new Set(subscriptionCouponIds(stream));
915
+ let matches = 0;
916
+ const items = stream.items.map((item) => {
917
+ const productId = subscriptionItemProductId(item);
918
+ const quantity = item.quantity ?? 1;
919
+ if (!productId || !Number.isSafeInteger(quantity) || quantity < 1) {
920
+ throw invalidProviderItems("StreamPay returned an invalid subscription item.");
921
+ }
922
+ const isPlanItem = productId === currentProductId;
923
+ if (isPlanItem) matches += 1;
924
+ const itemCoupons = couponIdsFromMetadata(item.coupon_calculation_metadata).filter(
925
+ (couponId) => !subscriptionCoupons.has(couponId)
926
+ );
927
+ return {
928
+ product_id: isPlanItem ? targetProductId : productId,
929
+ quantity: isPlanItem ? targetSeats : quantity,
930
+ ...itemCoupons.length > 0 ? { coupons: itemCoupons } : {}
931
+ };
932
+ });
933
+ if (matches !== 1) {
934
+ throw invalidProviderItems(
935
+ `Expected exactly one plan item for product "${currentProductId}", received ${matches}.`
936
+ );
937
+ }
938
+ return items;
939
+ }
940
+ function invalidProviderItems(message) {
941
+ return new APIError("INTERNAL_SERVER_ERROR", {
942
+ code: $ERROR_CODES.SUBSCRIPTION_INVALID_STATE.code,
943
+ message
944
+ });
945
+ }
946
+ function configuredPlanForSubscription(subscription, plans) {
947
+ const matches = plans.list.filter(
948
+ (plan) => subscription.items?.some((item) => subscriptionItemProductId(item) === plan.productId)
949
+ );
950
+ if (matches.length > 1) {
951
+ throw invalidProviderItems(
952
+ "StreamPay returned a subscription containing multiple configured plan products."
953
+ );
954
+ }
955
+ return matches[0];
956
+ }
957
+ async function findSubscriptionFreeze(client, options, subscriptionId, matches) {
958
+ const listPage = options.listSubscriptionFreezes;
959
+ if (!listPage) {
960
+ const response = await client.listSubscriptionFreezes(subscriptionId);
961
+ return {
962
+ freeze: response.data?.find(matches),
963
+ hasMore: response.pagination?.has_next_page ?? false
964
+ };
965
+ }
966
+ const seenIds = /* @__PURE__ */ new Set();
967
+ for (let page = 1; page <= 100; page++) {
968
+ const response = await listPage(subscriptionId, { page, limit: 100 });
969
+ const pagination = response.pagination;
970
+ if (!Array.isArray(response.data) || !pagination || pagination.current_page !== page || typeof pagination.has_next_page !== "boolean") {
971
+ throw freezePaginationConflict("StreamPay returned invalid freeze pagination.");
972
+ }
973
+ let advanced = false;
974
+ for (const freeze2 of response.data) {
975
+ if (freeze2.id && !seenIds.has(freeze2.id)) {
976
+ seenIds.add(freeze2.id);
977
+ advanced = true;
978
+ }
979
+ }
980
+ if (!advanced && (pagination.has_next_page || response.data.length > 0)) {
981
+ throw freezePaginationConflict("StreamPay freeze pagination returned no new entries.");
982
+ }
983
+ const freeze = response.data.find(matches);
984
+ if (freeze || !pagination.has_next_page) return { freeze, hasMore: false };
985
+ }
986
+ throw freezePaginationConflict("StreamPay freeze pagination exceeded 100 pages.");
987
+ }
988
+ function freezePaginationConflict(message) {
989
+ return new APIError("CONFLICT", {
990
+ code: $ERROR_CODES.SUBSCRIPTION_INVALID_STATE.code,
991
+ message
992
+ });
993
+ }
880
994
  function subscriptionSlotKey(referenceType, referenceId, group) {
881
995
  const tuple = JSON.stringify([referenceType, referenceId, group ?? null]);
882
996
  return `sp_slot_v1_${createHash("sha256").update(tuple).digest("hex")}`;
@@ -1205,12 +1319,77 @@ var SubscriptionCorrelationError = class extends Error {
1205
1319
  this.name = "SubscriptionCorrelationError";
1206
1320
  }
1207
1321
  };
1208
- async function updateReconciledSubscription(ctx, existing, projected, streampaySubscriptionId) {
1322
+ async function takeSlotFromReservation(ctx, client, slotKey, ownerRowId, streampaySubscriptionId) {
1323
+ const holder = await ctx.context.adapter.findOne({
1324
+ model: SUBSCRIPTION_MODEL2,
1325
+ where: [{ field: "activeSlotKey", value: slotKey }]
1326
+ });
1327
+ if (!holder || holder.id === ownerRowId) return;
1328
+ if (holder.status !== "incomplete" || holder.streampaySubscriptionId) {
1329
+ throw new SubscriptionCorrelationError(
1330
+ `StreamPay sub=${streampaySubscriptionId} needs the billing slot held by live row=${holder.id} (${holder.status}). Resolve the duplicate subscription, then replay.`
1331
+ );
1332
+ }
1333
+ if (holder.streampayPaymentLinkId) {
1334
+ try {
1335
+ await deactivatePaymentLink(client, holder.streampayPaymentLinkId, logger(ctx));
1336
+ } catch (err) {
1337
+ const message = err instanceof Error ? err.message : String(err);
1338
+ logger(ctx).error(
1339
+ `payment link=${holder.streampayPaymentLinkId} of released row=${holder.id} could not be deactivated and may still be paid; deactivate it manually: ${message}`
1340
+ );
1341
+ }
1342
+ }
1343
+ const released = await ctx.context.adapter.update({
1344
+ model: SUBSCRIPTION_MODEL2,
1345
+ update: { status: "incomplete_expired", activeSlotKey: null, updatedAt: /* @__PURE__ */ new Date() },
1346
+ where: [
1347
+ { field: "id", value: holder.id },
1348
+ { field: "status", value: "incomplete" },
1349
+ { field: "activeSlotKey", value: slotKey },
1350
+ { field: "streampayPaymentLinkId", value: holder.streampayPaymentLinkId ?? null }
1351
+ ]
1352
+ });
1353
+ if (!released) {
1354
+ throw new Error(`Checkout reservation row=${holder.id} changed while releasing its slot.`);
1355
+ }
1356
+ logger(ctx).warn(
1357
+ `released checkout reservation row=${holder.id} for paid StreamPay sub=${streampaySubscriptionId}.`
1358
+ );
1359
+ }
1360
+ async function linkReservedRow(ctx, client, row, projected, metadataReferenceType, streampaySubscriptionId) {
1361
+ const activeSlotKey = projected.activeSlotKey === null ? null : row.activeSlotKey ?? subscriptionSlotKey(
1362
+ row.referenceType ?? metadataReferenceType ?? "user",
1363
+ row.referenceId,
1364
+ projected.group === void 0 ? row.group : projected.group
1365
+ );
1366
+ return updateReconciledSubscription(
1367
+ ctx,
1368
+ client,
1369
+ row,
1370
+ {
1371
+ ...projected,
1372
+ billingStatus: row.billingStatus ?? "current",
1373
+ ...activeSlotKey === null ? {} : { activeSlotKey }
1374
+ },
1375
+ streampaySubscriptionId
1376
+ );
1377
+ }
1378
+ async function updateReconciledSubscription(ctx, client, existing, projected, streampaySubscriptionId) {
1209
1379
  if (existing.providerUpdatedAt instanceof Date && projected.providerUpdatedAt instanceof Date && projected.providerUpdatedAt.getTime() < existing.providerUpdatedAt.getTime()) {
1210
1380
  throw new Error(
1211
1381
  `StreamPay returned stale subscription state for sub=${streampaySubscriptionId}. Retry reconciliation.`
1212
1382
  );
1213
1383
  }
1384
+ if (projected.activeSlotKey && projected.activeSlotKey !== existing.activeSlotKey) {
1385
+ await takeSlotFromReservation(
1386
+ ctx,
1387
+ client,
1388
+ projected.activeSlotKey,
1389
+ existing.id,
1390
+ streampaySubscriptionId
1391
+ );
1392
+ }
1214
1393
  const updated = await ctx.context.adapter.update({
1215
1394
  model: SUBSCRIPTION_MODEL2,
1216
1395
  update: projected,
@@ -1286,6 +1465,7 @@ async function reconcileFromStreamPay(ctx, payload, client, plans) {
1286
1465
  }
1287
1466
  const updated = await updateReconciledSubscription(
1288
1467
  ctx,
1468
+ client,
1289
1469
  existing,
1290
1470
  projected,
1291
1471
  streampaySubscriptionId
@@ -1319,21 +1499,12 @@ async function reconcileFromStreamPay(ctx, payload, client, plans) {
1319
1499
  `webhook ${payload.event_type}: referenced subscription row=${localRowId} is missing; rebuilding from signed metadata.`
1320
1500
  );
1321
1501
  } 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(
1502
+ const updated = await linkReservedRow(
1334
1503
  ctx,
1504
+ client,
1335
1505
  metadataRow,
1336
- projectedWithSlot,
1506
+ projected,
1507
+ metadataReferenceType,
1337
1508
  streampaySubscriptionId
1338
1509
  );
1339
1510
  return { row: updated, stream };
@@ -1356,30 +1527,22 @@ async function reconcileFromStreamPay(ctx, payload, client, plans) {
1356
1527
  stream.organization_consumer_id ?? null
1357
1528
  );
1358
1529
  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(
1530
+ const updated = await linkReservedRow(
1371
1531
  ctx,
1532
+ client,
1372
1533
  incomplete,
1373
- projectedWithSlot,
1534
+ projected,
1535
+ metadataReferenceType,
1374
1536
  streampaySubscriptionId
1375
1537
  );
1376
- return {
1377
- row: updated,
1378
- stream
1379
- };
1538
+ return { row: updated, stream };
1380
1539
  }
1381
1540
  const plan = plans.byName.get(planName);
1382
1541
  const referenceType = metadataReferenceType ?? "custom";
1542
+ const activeSlotKey = isTerminalSubscriptionStatus(projected.status) ? null : subscriptionSlotKey(referenceType, referenceId, plan?.group);
1543
+ if (activeSlotKey) {
1544
+ await takeSlotFromReservation(ctx, client, activeSlotKey, null, streampaySubscriptionId);
1545
+ }
1383
1546
  const row = await ctx.context.adapter.create({
1384
1547
  model: SUBSCRIPTION_MODEL2,
1385
1548
  data: {
@@ -1388,7 +1551,7 @@ async function reconcileFromStreamPay(ctx, payload, client, plans) {
1388
1551
  ...projected,
1389
1552
  referenceId,
1390
1553
  referenceType,
1391
- activeSlotKey: isTerminalSubscriptionStatus(projected.status) ? null : subscriptionSlotKey(referenceType, referenceId, plan?.group),
1554
+ activeSlotKey,
1392
1555
  streampayPaymentLinkId: paymentLinkId,
1393
1556
  plan: planName,
1394
1557
  planVersion: plan?.version ?? null,
@@ -3258,6 +3421,12 @@ function checkoutInProgressError() {
3258
3421
  message: "A subscription checkout is already being created for this plan group."
3259
3422
  });
3260
3423
  }
3424
+ function subscriptionAlreadyActiveError() {
3425
+ return new APIError("CONFLICT", {
3426
+ code: $ERROR_CODES.SUBSCRIPTION_ALREADY_ACTIVE.code,
3427
+ message: "An active subscription already exists for this plan group."
3428
+ });
3429
+ }
3261
3430
  async function resumeOrReserveCheckoutSlot(args) {
3262
3431
  const { client, adapter, candidates, activeSlotKey, planName, seats, now, log } = args;
3263
3432
  const matchesCheckout = (row2) => row2.plan === planName && (row2.seats ?? 1) === seats;
@@ -3304,7 +3473,8 @@ async function resumeOrReserveCheckoutSlot(args) {
3304
3473
  model: SUBSCRIPTION_MODEL4,
3305
3474
  where: [{ field: "activeSlotKey", value: activeSlotKey }]
3306
3475
  });
3307
- if (reserved?.status !== "incomplete") throw err;
3476
+ if (!reserved) throw err;
3477
+ if (reserved.status !== "incomplete") throw subscriptionAlreadyActiveError();
3308
3478
  if (matchesCheckout(reserved)) {
3309
3479
  let recovery;
3310
3480
  try {
@@ -3325,6 +3495,20 @@ async function resumeOrReserveCheckoutSlot(args) {
3325
3495
  }
3326
3496
  const reservationIsStale = !(reserved.createdAt instanceof Date) || now - reserved.createdAt.getTime() >= UPGRADE_IDEMPOTENCY_WINDOW_MS;
3327
3497
  if (!reservationIsStale) throw checkoutInProgressError();
3498
+ if (reserved.streampayPaymentLinkId) {
3499
+ try {
3500
+ await deactivatePaymentLink(client, reserved.streampayPaymentLinkId, log);
3501
+ } catch (deactivationError) {
3502
+ toAPIError(
3503
+ {
3504
+ logPrefix: `deactivate stale checkout link=${reserved.streampayPaymentLinkId} failed for row=${reserved.id}:`,
3505
+ userMessage: "Unable to replace the previous subscription checkout."
3506
+ },
3507
+ deactivationError,
3508
+ log
3509
+ );
3510
+ }
3511
+ }
3328
3512
  const released = await adapter.update({
3329
3513
  model: SUBSCRIPTION_MODEL4,
3330
3514
  update: { status: "incomplete_expired", activeSlotKey: null, updatedAt: /* @__PURE__ */ new Date() },
@@ -3348,105 +3532,6 @@ async function resumeOrReserveCheckoutSlot(args) {
3348
3532
  }
3349
3533
  return { kind: "reserved", row, consumerId };
3350
3534
  }
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
3535
  var SUBSCRIPTION_INTERVALS = ["WEEK", "MONTH", "QUARTER", "YEAR"];
3451
3536
  var PlanSchema = z.object({
3452
3537
  name: z.string().min(1, "every plan must have a non-empty `name`."),
@@ -4111,6 +4196,24 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
4111
4196
  `failed to persist payment link=${paymentLinkId} for row=${row.id}: ${message}. Protected checkout metadata will reconcile the row from the webhook.`
4112
4197
  );
4113
4198
  }
4199
+ if (updatedRow?.status === "incomplete_expired") {
4200
+ getLogger(ctx).warn(
4201
+ `checkout reservation row=${row.id} was released while payment link=${paymentLinkId} was created; deactivating the link.`
4202
+ );
4203
+ try {
4204
+ await deactivatePaymentLink(client, paymentLinkId, getLogger(ctx));
4205
+ } catch (deactivationError) {
4206
+ toAPIError(
4207
+ {
4208
+ logPrefix: `deactivate orphaned checkout link=${paymentLinkId} failed for row=${row.id}:`,
4209
+ userMessage: "Failed to start subscription checkout."
4210
+ },
4211
+ deactivationError,
4212
+ getLogger(ctx)
4213
+ );
4214
+ }
4215
+ throw checkoutInProgressError();
4216
+ }
4114
4217
  return ctx.json({
4115
4218
  subscriptionId: updatedRow?.id ?? row.id,
4116
4219
  url,
@@ -5103,9 +5206,9 @@ function subscriptions(subsOptions) {
5103
5206
  }
5104
5207
  };
5105
5208
  if (dedupeEnabled) {
5106
- registry.replayWebhookEvent = async (ctx, eventId, replayOptions) => {
5209
+ registry.replayWebhookEvent = async (ctx, eventId) => {
5107
5210
  if (eventId.startsWith("handlers:") && registry.replayWebhookHandler) {
5108
- return registry.replayWebhookHandler(ctx, eventId, replayOptions);
5211
+ return registry.replayWebhookHandler(ctx, eventId);
5109
5212
  }
5110
5213
  const syncCtx = {
5111
5214
  context: ctx.context
@@ -5140,6 +5243,7 @@ function subscriptions(subsOptions) {
5140
5243
  }
5141
5244
  const payload = parsedPayload;
5142
5245
  const plans = await plansRef();
5246
+ const previousStatus = row.status;
5143
5247
  const claimed = await claimWebhookEventForReplay(syncCtx, row);
5144
5248
  if (!claimed?.lockedBy) {
5145
5249
  throw new APIError("CONFLICT", {
@@ -5150,6 +5254,7 @@ function subscriptions(subsOptions) {
5150
5254
  try {
5151
5255
  await syncWebhookPayload(syncCtx, payload, options.client, plans, subsOptions, {
5152
5256
  dedupe: false,
5257
+ retryOnCallbackError: subsOptions.retryOnCallbackError !== false,
5153
5258
  retryingRenewalCallback: claimed.lastError?.startsWith(
5154
5259
  "Subscription callback onSubscriptionRenewed failed:"
5155
5260
  ) === true
@@ -5165,7 +5270,7 @@ function subscriptions(subsOptions) {
5165
5270
  null,
5166
5271
  err,
5167
5272
  claimed.lockedBy,
5168
- !replayOptions?.retryUntilExhausted || classifyWebhookFailure(err) === "PERMANENT" || claimed.attemptCount >= maxAttempts
5273
+ previousStatus === "dead_letter" || classifyWebhookFailure(err) === "PERMANENT" || claimed.attemptCount >= maxAttempts
5169
5274
  );
5170
5275
  throw err;
5171
5276
  }
@@ -5365,7 +5470,7 @@ var webhooks = (webhooksOptions) => {
5365
5470
  return (_options, registry) => {
5366
5471
  const { secret, toleranceSeconds, deduplicate = false, ...handlers } = webhooksOptions;
5367
5472
  if (deduplicate && registry) {
5368
- registry.replayWebhookHandler = async (ctx, eventId, replayOptions) => {
5473
+ registry.replayWebhookHandler = async (ctx, eventId) => {
5369
5474
  const syncContext = { context: ctx.context };
5370
5475
  const row = await syncContext.context.adapter.findOne({
5371
5476
  model: WEBHOOK_EVENT_MODEL,
@@ -5387,6 +5492,7 @@ var webhooks = (webhooksOptions) => {
5387
5492
  throw new APIError("BAD_REQUEST", {
5388
5493
  message: "Stored webhook payload is not a valid event envelope."
5389
5494
  });
5495
+ const previousStatus = row.status;
5390
5496
  const claimed = await claimWebhookEventForReplay(syncContext, row);
5391
5497
  if (!claimed?.lockedBy)
5392
5498
  throw new APIError("CONFLICT", {
@@ -5403,7 +5509,7 @@ var webhooks = (webhooksOptions) => {
5403
5509
  row.signatureHeader,
5404
5510
  err,
5405
5511
  claimed.lockedBy,
5406
- !replayOptions?.retryUntilExhausted || claimed.attemptCount >= DEFAULT_MAX_WEBHOOK_ATTEMPTS
5512
+ previousStatus === "dead_letter" || claimed.attemptCount >= DEFAULT_MAX_WEBHOOK_ATTEMPTS
5407
5513
  );
5408
5514
  throw err;
5409
5515
  }
@@ -5533,7 +5639,7 @@ var webhooks = (webhooksOptions) => {
5533
5639
  const failed = [];
5534
5640
  for (const row of due) {
5535
5641
  try {
5536
- await replay(ctx, row.eventId, { retryUntilExhausted: true });
5642
+ await replay(ctx, row.eventId);
5537
5643
  succeeded.push(row.eventId);
5538
5644
  } catch (err) {
5539
5645
  if (err instanceof APIError && err.status === "CONFLICT") continue;
@@ -5674,7 +5780,7 @@ var onUserDelete = (options) => async (user, context) => {
5674
5780
 
5675
5781
  // package.json
5676
5782
  var package_default = {
5677
- version: "3.1.0"};
5783
+ version: "3.2.0"};
5678
5784
 
5679
5785
  // src/version.ts
5680
5786
  var version = package_default.version;