better-auth-streampay 2.2.1 → 3.0.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
@@ -162,13 +162,33 @@ async function findConsumerByIdentifiers(client, identifiers) {
162
162
  return null;
163
163
  }
164
164
  async function searchExact(client, term, predicate) {
165
- const response = await client.listConsumers({
166
- search_term: term,
167
- page: 1,
168
- size: SEARCH_PAGE_SIZE
169
- });
170
- const items = response.data ?? [];
171
- return items.find(predicate) ?? null;
165
+ const seenIds = /* @__PURE__ */ new Set();
166
+ for (let page = 1; ; page++) {
167
+ const response = await client.listConsumers({
168
+ search_term: term,
169
+ page,
170
+ limit: SEARCH_PAGE_SIZE
171
+ });
172
+ const items = response.data ?? [];
173
+ const pagination = response.pagination;
174
+ if (pagination?.current_page !== void 0 && pagination.current_page !== page) {
175
+ throw new Error("Consumer search pagination did not advance to the requested page.");
176
+ }
177
+ const hit = items.find(predicate);
178
+ if (hit) return hit;
179
+ const hasNext = pagination?.has_next_page ?? (pagination?.max_page !== void 0 ? page < pagination.max_page : items.length === SEARCH_PAGE_SIZE);
180
+ if (!hasNext) return null;
181
+ let advanced = false;
182
+ for (const item of items) {
183
+ if (item.id && !seenIds.has(item.id)) {
184
+ seenIds.add(item.id);
185
+ advanced = true;
186
+ }
187
+ }
188
+ if (!advanced || page === Number.MAX_SAFE_INTEGER) {
189
+ throw new Error("Consumer search pagination returned no new consumers.");
190
+ }
191
+ }
172
192
  }
173
193
  var ErrorShape = z.object({
174
194
  code: z.string().optional(),
@@ -327,11 +347,11 @@ async function ensureConsumerForUser(options, ctx, user) {
327
347
  if (user.name !== void 0) userForParams.name = user.name;
328
348
  const extras = options.getConsumerCreateParams ? await options.getConsumerCreateParams({ user: userForParams }) : {};
329
349
  const payload = {
350
+ consumer_type: "INDIVIDUAL",
351
+ ...extras,
330
352
  name: user.name || user.email,
331
353
  email: user.email,
332
- external_id: user.id,
333
- consumer_type: "INDIVIDUAL",
334
- ...extras
354
+ external_id: user.id
335
355
  };
336
356
  try {
337
357
  const consumer = await options.client.createConsumer(payload);
@@ -600,7 +620,32 @@ function reconcileProjectionAgainstExisting(existing, projection, options = {})
600
620
  return projected;
601
621
  }
602
622
  function projectSubscriptionAgainstExisting(existing, stream) {
603
- return reconcileProjectionAgainstExisting(existing, projectSubscriptionFields(stream));
623
+ return reconcileProjectionAgainstExisting(existing, projectSubscriptionFields(stream, existing));
624
+ }
625
+ async function persistSubscriptionProjection(adapter, existing, projection, log, source) {
626
+ const stale = existing.providerUpdatedAt instanceof Date && projection.providerUpdatedAt instanceof Date && projection.providerUpdatedAt.getTime() < existing.providerUpdatedAt.getTime();
627
+ if (!stale) {
628
+ const updated = await adapter.update({
629
+ model: SUBSCRIPTION_MODEL,
630
+ update: projection,
631
+ where: [
632
+ { field: "id", value: existing.id },
633
+ { field: "providerUpdatedAt", value: existing.providerUpdatedAt ?? null },
634
+ { field: "streampaySubscriptionId", value: existing.streampaySubscriptionId ?? null },
635
+ { field: "streampayConsumerId", value: existing.streampayConsumerId ?? null },
636
+ { field: "status", value: existing.status },
637
+ { field: "billingStatus", value: existing.billingStatus }
638
+ ]
639
+ });
640
+ if (updated) return updated;
641
+ }
642
+ log.warn(
643
+ `${source}: retained newer local subscription state for row=${existing.id}. The provider action is not rolled back.`
644
+ );
645
+ return adapter.findOne({
646
+ model: SUBSCRIPTION_MODEL,
647
+ where: [{ field: "id", value: existing.id }]
648
+ });
604
649
  }
605
650
  async function applySubscriptionProjection(adapter, stream, log, source) {
606
651
  const streampaySubscriptionId = stream?.id;
@@ -611,11 +656,13 @@ async function applySubscriptionProjection(adapter, stream, log, source) {
611
656
  where: [{ field: "streampaySubscriptionId", value: streampaySubscriptionId }]
612
657
  });
613
658
  if (!existing) return;
614
- await adapter.update({
615
- model: SUBSCRIPTION_MODEL,
616
- update: projectSubscriptionAgainstExisting(existing, stream),
617
- where: [{ field: "id", value: existing.id }]
618
- });
659
+ await persistSubscriptionProjection(
660
+ adapter,
661
+ existing,
662
+ projectSubscriptionAgainstExisting(existing, stream),
663
+ log,
664
+ source
665
+ );
619
666
  } catch (err) {
620
667
  const message = err instanceof Error ? err.message : String(err);
621
668
  log.warn(
@@ -638,7 +685,7 @@ async function syncSubscriptionFromUpstream(client, adapter, streampaySubscripti
638
685
  }
639
686
  await applySubscriptionProjection(adapter, stream, log, source);
640
687
  }
641
- function projectSubscriptionFields(sub) {
688
+ function projectSubscriptionFields(sub, existing) {
642
689
  const status = toLocalStatus(sub.status);
643
690
  const terminal = isTerminalSubscriptionStatus(status);
644
691
  const periodStart = parseDate(sub.current_period_start);
@@ -656,7 +703,7 @@ function projectSubscriptionFields(sub) {
656
703
  periodStart,
657
704
  periodEnd,
658
705
  currentCycleNumber: sub.current_cycle_number ?? null,
659
- trialStart: sub.trial_end ? parseDate(sub.started_at) ?? periodStart : null,
706
+ trialStart: (sub.trial_end ? parseDate(sub.started_at) ?? periodStart : null) ?? existing?.trialStart ?? null,
660
707
  trialEnd: parseDate(sub.trial_end),
661
708
  cancelAtPeriodEnd: Boolean(sub.cancel_at_period_end),
662
709
  cancelAt: sub.cancel_at_period_end ? periodEnd : null,
@@ -760,6 +807,7 @@ function projectPlanFields(sub, plans) {
760
807
  const pendingEffectiveAt = parseDate(sub.pending_change?.effective_at);
761
808
  const planChanges = Boolean(inferredPendingPlan) && (inferredPendingPlan !== currentPlan || pendingProductId !== currentProductId);
762
809
  return {
810
+ catalogMapped: Boolean(currentPlan),
763
811
  ...currentPlan ? {
764
812
  plan: currentPlan,
765
813
  planVersion: configuredCurrent?.version ?? null,
@@ -810,8 +858,9 @@ function isUniqueConstraintError(err) {
810
858
  }
811
859
  var WEBHOOK_PROCESSING_LEASE_MS = 2 * 60 * 1e3;
812
860
  var WEBHOOK_RETRY_DELAYS_MS = [5, 30, 120, 360, 720].map((minutes) => minutes * 60 * 1e3);
813
- async function claimOrAdvanceWebhookEvent(ctx, payload, rawBody, signatureHeader, maxAttempts) {
814
- const eventId = extractEventId(payload);
861
+ async function claimOrAdvanceWebhookEvent(ctx, payload, rawBody, signatureHeader, maxAttempts, scope) {
862
+ const sourceEventId = extractEventId(payload);
863
+ const eventId = sourceEventId && (scope ? `${scope}:${sourceEventId}` : sourceEventId);
815
864
  if (!eventId) {
816
865
  logger(ctx).warn(
817
866
  `webhook ${payload.event_type}: missing entity_id/timestamp \u2014 processing without dedupe.`
@@ -831,7 +880,9 @@ async function claimOrAdvanceWebhookEvent(ctx, payload, rawBody, signatureHeader
831
880
  receivedAt: now,
832
881
  lastAttemptAt: now,
833
882
  lockedAt: now,
834
- lockedBy: lockId
883
+ lockedBy: lockId,
884
+ rawPayload: rawBody,
885
+ signatureHeader
835
886
  }
836
887
  });
837
888
  return { action: "process", row: inserted };
@@ -843,10 +894,9 @@ async function claimOrAdvanceWebhookEvent(ctx, payload, rawBody, signatureHeader
843
894
  where: [{ field: "eventId", value: eventId }]
844
895
  });
845
896
  if (!existing) {
846
- logger(ctx).warn(
847
- `webhook ${payload.event_type} (${eventId}): unique conflict but row missing, processing without tracking.`
897
+ throw new Error(
898
+ `Webhook inbox row missing after unique conflict for ${eventId}; retry delivery.`
848
899
  );
849
- return { action: "process", row: null };
850
900
  }
851
901
  if (existing.status === "completed") {
852
902
  logger(ctx).info(`webhook ${payload.event_type} (${eventId}) already completed \u2014 skipping.`);
@@ -1000,7 +1050,7 @@ async function findSubscriptionByStreampayId(ctx, streampaySubscriptionId) {
1000
1050
  where: [{ field: "streampaySubscriptionId", value: streampaySubscriptionId }]
1001
1051
  });
1002
1052
  }
1003
- async function findIncompleteRow(ctx, referenceId, referenceType, plan, paymentLinkId) {
1053
+ async function findIncompleteRow(ctx, referenceId, referenceType, plan, paymentLinkId, consumerId) {
1004
1054
  const candidates = await ctx.context.adapter.findMany({
1005
1055
  model: SUBSCRIPTION_MODEL2,
1006
1056
  where: [
@@ -1009,13 +1059,15 @@ async function findIncompleteRow(ctx, referenceId, referenceType, plan, paymentL
1009
1059
  { field: "status", value: "incomplete" }
1010
1060
  ]
1011
1061
  });
1012
- const scopedCandidates = referenceType ? candidates.filter((candidate) => (candidate.referenceType ?? "user") === referenceType) : candidates;
1062
+ const scopedCandidates = candidates.filter(
1063
+ (candidate) => (!referenceType || (candidate.referenceType ?? "user") === referenceType) && (!consumerId || !candidate.streampayConsumerId || candidate.streampayConsumerId === consumerId)
1064
+ );
1013
1065
  if (scopedCandidates.length === 0) return null;
1014
1066
  if (paymentLinkId) {
1015
1067
  const exact = scopedCandidates.find(
1016
1068
  (candidate) => candidate.streampayPaymentLinkId === paymentLinkId
1017
1069
  );
1018
- if (exact) return exact;
1070
+ return exact ?? null;
1019
1071
  }
1020
1072
  if (!referenceType && new Set(scopedCandidates.map((candidate) => candidate.referenceType ?? "user")).size > 1) {
1021
1073
  return null;
@@ -1064,6 +1116,31 @@ var SubscriptionCorrelationError = class extends Error {
1064
1116
  this.name = "SubscriptionCorrelationError";
1065
1117
  }
1066
1118
  };
1119
+ async function updateReconciledSubscription(ctx, existing, projected, streampaySubscriptionId) {
1120
+ if (existing.providerUpdatedAt instanceof Date && projected.providerUpdatedAt instanceof Date && projected.providerUpdatedAt.getTime() < existing.providerUpdatedAt.getTime()) {
1121
+ throw new Error(
1122
+ `StreamPay returned stale subscription state for sub=${streampaySubscriptionId}. Retry reconciliation.`
1123
+ );
1124
+ }
1125
+ const updated = await ctx.context.adapter.update({
1126
+ model: SUBSCRIPTION_MODEL2,
1127
+ update: projected,
1128
+ where: [
1129
+ { field: "id", value: existing.id },
1130
+ { field: "providerUpdatedAt", value: existing.providerUpdatedAt ?? null },
1131
+ { field: "streampaySubscriptionId", value: existing.streampaySubscriptionId ?? null },
1132
+ { field: "streampayConsumerId", value: existing.streampayConsumerId ?? null },
1133
+ { field: "status", value: existing.status },
1134
+ { field: "billingStatus", value: existing.billingStatus }
1135
+ ]
1136
+ });
1137
+ if (!updated) {
1138
+ throw new Error(
1139
+ `Subscription state changed during reconciliation for sub=${streampaySubscriptionId}. Retry delivery.`
1140
+ );
1141
+ }
1142
+ return updated;
1143
+ }
1067
1144
  async function reconcileFromStreamPay(ctx, payload, client, plans) {
1068
1145
  const streampaySubscriptionId = payload.entity_id;
1069
1146
  if (!streampaySubscriptionId) {
@@ -1082,7 +1159,7 @@ async function reconcileFromStreamPay(ctx, payload, client, plans) {
1082
1159
  }
1083
1160
  const existing = await findSubscriptionByStreampayId(ctx, streampaySubscriptionId);
1084
1161
  let projected = {
1085
- ...projectSubscriptionFields(stream),
1162
+ ...projectSubscriptionFields(stream, existing),
1086
1163
  ...projectPlanFields(stream, plans)
1087
1164
  };
1088
1165
  const eventAt = parseDate(payload.timestamp);
@@ -1118,18 +1195,19 @@ async function reconcileFromStreamPay(ctx, payload, client, plans) {
1118
1195
  projected.activeSlotKey = desiredSlotKey;
1119
1196
  }
1120
1197
  }
1121
- const updated = await ctx.context.adapter.update({
1122
- model: SUBSCRIPTION_MODEL2,
1123
- update: projected,
1124
- where: [{ field: "id", value: existing.id }]
1125
- });
1198
+ const updated = await updateReconciledSubscription(
1199
+ ctx,
1200
+ existing,
1201
+ projected,
1202
+ streampaySubscriptionId
1203
+ );
1126
1204
  if (eventIsStale) {
1127
1205
  logger(ctx).info(
1128
1206
  `webhook ${payload.event_type}: ignored stale lifecycle callback for sub=${streampaySubscriptionId}.`
1129
1207
  );
1130
1208
  return { row: null, stream };
1131
1209
  }
1132
- return { row: updated ?? { ...existing, ...projected }, stream };
1210
+ return { row: updated, stream };
1133
1211
  }
1134
1212
  const planName = readMetadataString(payload.data, PLAN_NAME_METADATA_KEY) ?? inferPlanFromItems(stream, plans);
1135
1213
  const referenceId = readMetadataString(payload.data, REFERENCE_ID_METADATA_KEY);
@@ -1151,7 +1229,7 @@ async function reconcileFromStreamPay(ctx, payload, client, plans) {
1151
1229
  logger(ctx).warn(
1152
1230
  `webhook ${payload.event_type}: referenced subscription row=${localRowId} is missing; rebuilding from signed metadata.`
1153
1231
  );
1154
- } else if (metadataRow.referenceId === referenceId && (!metadataReferenceType || (metadataRow.referenceType ?? "user") === metadataReferenceType) && metadataRow.plan === planName && (!metadataRow.streampaySubscriptionId || metadataRow.streampaySubscriptionId === streampaySubscriptionId) && (!metadataRow.streampayPaymentLinkId || !paymentLinkId || metadataRow.streampayPaymentLinkId === paymentLinkId)) {
1232
+ } 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)) {
1155
1233
  const projectedWithSlot = {
1156
1234
  ...projected,
1157
1235
  billingStatus: metadataRow.billingStatus ?? "current",
@@ -1163,12 +1241,13 @@ async function reconcileFromStreamPay(ctx, payload, client, plans) {
1163
1241
  )
1164
1242
  }
1165
1243
  };
1166
- const updated = await ctx.context.adapter.update({
1167
- model: SUBSCRIPTION_MODEL2,
1168
- update: projectedWithSlot,
1169
- where: [{ field: "id", value: metadataRow.id }]
1170
- });
1171
- return { row: updated ?? { ...metadataRow, ...projectedWithSlot }, stream };
1244
+ const updated = await updateReconciledSubscription(
1245
+ ctx,
1246
+ metadataRow,
1247
+ projectedWithSlot,
1248
+ streampaySubscriptionId
1249
+ );
1250
+ return { row: updated, stream };
1172
1251
  }
1173
1252
  if (metadataRow) {
1174
1253
  logger(ctx).warn(
@@ -1184,7 +1263,8 @@ async function reconcileFromStreamPay(ctx, payload, client, plans) {
1184
1263
  referenceId,
1185
1264
  metadataReferenceType,
1186
1265
  planName,
1187
- paymentLinkId
1266
+ paymentLinkId,
1267
+ stream.organization_consumer_id ?? null
1188
1268
  );
1189
1269
  if (incomplete) {
1190
1270
  const projectedWithSlot = {
@@ -1198,13 +1278,14 @@ async function reconcileFromStreamPay(ctx, payload, client, plans) {
1198
1278
  )
1199
1279
  }
1200
1280
  };
1201
- const updated = await ctx.context.adapter.update({
1202
- model: SUBSCRIPTION_MODEL2,
1203
- update: projectedWithSlot,
1204
- where: [{ field: "id", value: incomplete.id }]
1205
- });
1281
+ const updated = await updateReconciledSubscription(
1282
+ ctx,
1283
+ incomplete,
1284
+ projectedWithSlot,
1285
+ streampaySubscriptionId
1286
+ );
1206
1287
  return {
1207
- row: updated ?? { ...incomplete, ...projectedWithSlot },
1288
+ row: updated,
1208
1289
  stream
1209
1290
  };
1210
1291
  }
@@ -1253,8 +1334,8 @@ async function syncWebhookPayload(ctx, payload, client, plans, callbacks, option
1253
1334
  const trackedRowId = claim.row?.id ?? null;
1254
1335
  const trackedLockId = claim.row?.lockedBy ?? void 0;
1255
1336
  try {
1256
- if (payload.event_type === "INVOICE_COMPLETED") {
1257
- await handleInvoiceCompleted(
1337
+ if (payload.event_type === "INVOICE_COMPLETED" || payload.event_type === "SUBSCRIPTION_CYCLE_RENEWED_SUCCESSFULLY") {
1338
+ await handleRenewalEvidence(
1258
1339
  ctx,
1259
1340
  payload,
1260
1341
  client,
@@ -1295,20 +1376,22 @@ async function syncWebhookPayload(ctx, payload, client, plans, callbacks, option
1295
1376
  throw err;
1296
1377
  }
1297
1378
  }
1298
- async function handleInvoiceCompleted(ctx, payload, client, plans, callbacks, retryOnCallbackError, retryingRenewalCallback) {
1379
+ async function handleRenewalEvidence(ctx, payload, client, plans, callbacks, retryOnCallbackError, retryingRenewalCallback) {
1299
1380
  const invoiceId = payload.data?.invoice?.id ?? payload.entity_id;
1300
1381
  if (!invoiceId) return;
1301
- let subscriptionId = null;
1302
- try {
1303
- const invoice = await client.getInvoice(invoiceId);
1304
- if (invoice && typeof invoice === "object" && "subscription_id" in invoice) {
1305
- const subId = invoice.subscription_id;
1306
- if (typeof subId === "string" && subId.length > 0) subscriptionId = subId;
1382
+ let subscriptionId = payload.entity_type === "SUBSCRIPTION" ? payload.entity_id : null;
1383
+ if (!subscriptionId) {
1384
+ try {
1385
+ const invoice = await client.getInvoice(invoiceId);
1386
+ if (invoice && typeof invoice === "object" && "subscription_id" in invoice) {
1387
+ const subId = invoice.subscription_id;
1388
+ if (typeof subId === "string" && subId.length > 0) subscriptionId = subId;
1389
+ }
1390
+ } catch (err) {
1391
+ const msg = err instanceof Error ? err.message : String(err);
1392
+ logger(ctx).error(`${payload.event_type}: getInvoice(${invoiceId}) failed: ${msg}`);
1393
+ throw err;
1307
1394
  }
1308
- } catch (err) {
1309
- const msg = err instanceof Error ? err.message : String(err);
1310
- logger(ctx).error(`INVOICE_COMPLETED: getInvoice(${invoiceId}) failed: ${msg}`);
1311
- throw err;
1312
1395
  }
1313
1396
  if (!subscriptionId) return;
1314
1397
  let stream;
@@ -1316,7 +1399,7 @@ async function handleInvoiceCompleted(ctx, payload, client, plans, callbacks, re
1316
1399
  stream = await client.getSubscription(subscriptionId);
1317
1400
  } catch (err) {
1318
1401
  const msg = err instanceof Error ? err.message : String(err);
1319
- logger(ctx).error(`INVOICE_COMPLETED: getSubscription(${subscriptionId}) failed: ${msg}`);
1402
+ logger(ctx).error(`${payload.event_type}: getSubscription(${subscriptionId}) failed: ${msg}`);
1320
1403
  throw err;
1321
1404
  }
1322
1405
  const existing = await findSubscriptionByStreampayId(ctx, subscriptionId);
@@ -1326,7 +1409,7 @@ async function handleInvoiceCompleted(ctx, payload, client, plans, callbacks, re
1326
1409
  eventAt && existing.providerUpdatedAt instanceof Date && eventAt.getTime() < existing.providerUpdatedAt.getTime()
1327
1410
  );
1328
1411
  const projected = {
1329
- ...projectSubscriptionFields(stream),
1412
+ ...projectSubscriptionFields(stream, existing),
1330
1413
  ...projectPlanFields(stream, plans),
1331
1414
  ...eventIsStale ? existing.billingStatus === "past_due" && toLocalStatus(stream.status) === "active" ? { status: "past_due", billingStatus: "past_due" } : {} : { billingStatus: "current" }
1332
1415
  };
@@ -1334,14 +1417,45 @@ async function handleInvoiceCompleted(ctx, payload, client, plans, callbacks, re
1334
1417
  const projectedPeriodEnd = projected.periodEnd?.getTime() ?? null;
1335
1418
  const periodAdvanced = previousPeriodEnd !== null && projectedPeriodEnd !== null && projectedPeriodEnd > previousPeriodEnd;
1336
1419
  const cycleAdvanced = existing.currentCycleNumber !== null && existing.currentCycleNumber !== void 0 && projected.currentCycleNumber !== null && projected.currentCycleNumber !== void 0 && projected.currentCycleNumber > existing.currentCycleNumber;
1420
+ const eventId = extractEventId(payload);
1421
+ const pendingCallback = existing.renewalCallbackEventId ?? null;
1422
+ if (!pendingCallback && existing.providerUpdatedAt instanceof Date && projected.providerUpdatedAt instanceof Date && projected.providerUpdatedAt.getTime() < existing.providerUpdatedAt.getTime()) {
1423
+ throw new Error(
1424
+ `StreamPay returned stale subscription state for sub=${subscriptionId}; retry delivery.`
1425
+ );
1426
+ }
1427
+ if (pendingCallback && pendingCallback !== eventId) {
1428
+ throw new Error(`Subscription renewal callback ${pendingCallback} is pending; retry delivery.`);
1429
+ }
1430
+ const deliverCallback = pendingCallback === eventId && pendingCallback !== null || !eventIsStale && (periodAdvanced || cycleAdvanced || retryingRenewalCallback);
1431
+ const callbackOwner = deliverCallback && callbacks.onSubscriptionRenewed ? eventId : null;
1337
1432
  const updated = await ctx.context.adapter.update({
1338
1433
  model: SUBSCRIPTION_MODEL2,
1339
- update: projected,
1340
- where: [{ field: "id", value: existing.id }]
1434
+ // Recovery must retain the pending cycle, even if Stream has already advanced again.
1435
+ update: pendingCallback ? { renewalCallbackEventId: callbackOwner } : { ...projected, renewalCallbackEventId: callbackOwner },
1436
+ where: [
1437
+ { field: "id", value: existing.id },
1438
+ { field: "periodEnd", value: existing.periodEnd ?? null },
1439
+ { field: "currentCycleNumber", value: existing.currentCycleNumber ?? null },
1440
+ { field: "renewalCallbackEventId", value: pendingCallback },
1441
+ { field: "providerUpdatedAt", value: existing.providerUpdatedAt ?? null },
1442
+ { field: "status", value: existing.status },
1443
+ { field: "billingStatus", value: existing.billingStatus }
1444
+ ]
1341
1445
  });
1342
- const row = updated ?? { ...existing, ...projected };
1446
+ if (!updated) {
1447
+ if (pendingCallback && pendingCallback === eventId) {
1448
+ throw new Error(`Subscription cycle changed during callback recovery; retry delivery.`);
1449
+ }
1450
+ const latest = await findSubscriptionByStreampayId(ctx, subscriptionId);
1451
+ const anotherCallbackOwner = latest?.renewalCallbackEventId;
1452
+ const desiredCycleAdvanced = (periodAdvanced || cycleAdvanced) && (!periodAdvanced || (latest?.periodEnd?.getTime() ?? 0) >= (projectedPeriodEnd ?? 0)) && (!cycleAdvanced || (latest?.currentCycleNumber ?? 0) >= (projected.currentCycleNumber ?? 0));
1453
+ if (anotherCallbackOwner && anotherCallbackOwner !== eventId && desiredCycleAdvanced) return;
1454
+ throw new Error(`Subscription changed during renewal reconciliation; retry delivery.`);
1455
+ }
1456
+ const row = updated;
1343
1457
  const user = await resolveRowUser(ctx, row);
1344
- if (!eventIsStale && (periodAdvanced || cycleAdvanced || retryingRenewalCallback)) {
1458
+ if (deliverCallback) {
1345
1459
  await fireCallback(
1346
1460
  ctx,
1347
1461
  callbacks.onSubscriptionRenewed,
@@ -1349,6 +1463,16 @@ async function handleInvoiceCompleted(ctx, payload, client, plans, callbacks, re
1349
1463
  "onSubscriptionRenewed",
1350
1464
  retryOnCallbackError
1351
1465
  );
1466
+ if (callbackOwner) {
1467
+ await ctx.context.adapter.update({
1468
+ model: SUBSCRIPTION_MODEL2,
1469
+ update: { renewalCallbackEventId: null },
1470
+ where: [
1471
+ { field: "id", value: row.id },
1472
+ { field: "renewalCallbackEventId", value: callbackOwner }
1473
+ ]
1474
+ });
1475
+ }
1352
1476
  }
1353
1477
  }
1354
1478
  async function dispatchSubscriptionCallback(ctx, payload, data, callbacks, retryOnCallbackError) {
@@ -1545,16 +1669,16 @@ function forwardedBody() {
1545
1669
  );
1546
1670
  }
1547
1671
  var PaymentsListQuery = z.object({
1548
- page: z.coerce.number().int().positive().optional(),
1672
+ page: z.coerce.number().int().positive().max(Number.MAX_SAFE_INTEGER).optional(),
1549
1673
  size: z.coerce.number().int().positive().max(100).optional(),
1550
1674
  invoice_id: z.string().uuid().optional()
1551
1675
  }).passthrough();
1552
1676
  var PaginationOnlyQuery = z.object({
1553
- page: z.coerce.number().int().positive().optional(),
1677
+ page: z.coerce.number().int().positive().max(Number.MAX_SAFE_INTEGER).optional(),
1554
1678
  size: z.coerce.number().int().positive().max(100).optional()
1555
1679
  }).passthrough();
1556
1680
  var ConsumersListQuery = z.object({
1557
- page: z.coerce.number().int().positive().optional(),
1681
+ page: z.coerce.number().int().positive().max(Number.MAX_SAFE_INTEGER).optional(),
1558
1682
  size: z.coerce.number().int().positive().max(100).optional(),
1559
1683
  search_term: z.string().optional()
1560
1684
  }).passthrough();
@@ -1600,7 +1724,7 @@ function buildPaymentsEndpoints(client, adminOptions) {
1600
1724
  await requireAdmin(ctx, adminOptions);
1601
1725
  const params = {};
1602
1726
  if (ctx.query.page !== void 0) params.page = ctx.query.page;
1603
- if (ctx.query.size !== void 0) params.size = ctx.query.size;
1727
+ if (ctx.query.size !== void 0) params.limit = ctx.query.size;
1604
1728
  if (ctx.query.invoice_id !== void 0) params.invoice_id = ctx.query.invoice_id;
1605
1729
  try {
1606
1730
  const response = await client.listPayments(params);
@@ -1705,7 +1829,7 @@ function buildSubscriptionsEndpoints(client, adminOptions) {
1705
1829
  await requireAdmin(ctx, adminOptions);
1706
1830
  const params = {};
1707
1831
  if (ctx.query.page !== void 0) params.page = ctx.query.page;
1708
- if (ctx.query.size !== void 0) params.size = ctx.query.size;
1832
+ if (ctx.query.size !== void 0) params.limit = ctx.query.size;
1709
1833
  try {
1710
1834
  const response = await client.listSubscriptions(params);
1711
1835
  return ctx.json(response);
@@ -1899,7 +2023,7 @@ function buildConsumersEndpoints(client, adminOptions) {
1899
2023
  await requireAdmin(ctx, adminOptions);
1900
2024
  const params = {};
1901
2025
  if (ctx.query.page !== void 0) params.page = ctx.query.page;
1902
- if (ctx.query.size !== void 0) params.size = ctx.query.size;
2026
+ if (ctx.query.size !== void 0) params.limit = ctx.query.size;
1903
2027
  if (ctx.query.search_term !== void 0) params.search_term = ctx.query.search_term;
1904
2028
  try {
1905
2029
  const response = await client.listConsumers(params);
@@ -1962,19 +2086,6 @@ function buildConsumersEndpoints(client, adminOptions) {
1962
2086
  async (ctx) => {
1963
2087
  await requireAdmin(ctx, adminOptions);
1964
2088
  const consumerId = ctx.params.id;
1965
- let externalId;
1966
- try {
1967
- const consumer = await client.getConsumer(consumerId);
1968
- if (typeof consumer.external_id === "string" && consumer.external_id.length > 0) {
1969
- externalId = consumer.external_id;
1970
- }
1971
- } catch (err) {
1972
- toAPIError(
1973
- `StreamPay getConsumer failed for consumer=${consumerId}:`,
1974
- err,
1975
- getLogger(ctx)
1976
- );
1977
- }
1978
2089
  try {
1979
2090
  await client.deleteConsumer(consumerId);
1980
2091
  } catch (err) {
@@ -1986,16 +2097,26 @@ function buildConsumersEndpoints(client, adminOptions) {
1986
2097
  );
1987
2098
  }
1988
2099
  }
1989
- if (externalId) {
1990
- try {
1991
- await ctx.context.internalAdapter.updateUser(externalId, {
1992
- streampayConsumerId: null
2100
+ try {
2101
+ const adapter = getAdapter(ctx);
2102
+ const user = await adapter.findOne({
2103
+ model: "user",
2104
+ where: [{ field: "streampayConsumerId", value: consumerId }]
2105
+ });
2106
+ if (user) {
2107
+ await adapter.update({
2108
+ model: "user",
2109
+ update: { streampayConsumerId: null },
2110
+ where: [
2111
+ { field: "id", value: user.id },
2112
+ { field: "streampayConsumerId", value: consumerId }
2113
+ ]
1993
2114
  });
1994
- } catch (err) {
1995
- getLogger(ctx).error(
1996
- `StreamPay admin delete: link clear failed for user=${externalId} consumer=${consumerId}: ${formatStreamPayError(err)}`
1997
- );
1998
2115
  }
2116
+ } catch (err) {
2117
+ getLogger(ctx).error(
2118
+ `StreamPay admin delete: link clear failed for consumer=${consumerId}: ${formatStreamPayError(err)}`
2119
+ );
1999
2120
  }
2000
2121
  return ctx.json({ deleted: true });
2001
2122
  }
@@ -2015,7 +2136,7 @@ function buildInvoicesEndpoints(client, adminOptions) {
2015
2136
  await requireAdmin(ctx, adminOptions);
2016
2137
  const params = {};
2017
2138
  if (ctx.query.page !== void 0) params.page = ctx.query.page;
2018
- if (ctx.query.size !== void 0) params.size = ctx.query.size;
2139
+ if (ctx.query.size !== void 0) params.limit = ctx.query.size;
2019
2140
  try {
2020
2141
  const response = await client.listInvoices(params);
2021
2142
  return ctx.json(response);
@@ -2077,7 +2198,7 @@ function buildProductsEndpoints(client, adminOptions) {
2077
2198
  await requireAdmin(ctx, adminOptions);
2078
2199
  const params = {};
2079
2200
  if (ctx.query.page !== void 0) params.page = ctx.query.page;
2080
- if (ctx.query.size !== void 0) params.size = ctx.query.size;
2201
+ if (ctx.query.size !== void 0) params.limit = ctx.query.size;
2081
2202
  try {
2082
2203
  const response = await client.listProducts(params);
2083
2204
  return ctx.json(response);
@@ -2183,7 +2304,7 @@ function buildCouponsEndpoints(client, adminOptions) {
2183
2304
  await requireAdmin(ctx, adminOptions);
2184
2305
  const params = {};
2185
2306
  if (ctx.query.page !== void 0) params.page = ctx.query.page;
2186
- if (ctx.query.size !== void 0) params.size = ctx.query.size;
2307
+ if (ctx.query.size !== void 0) params.limit = ctx.query.size;
2187
2308
  try {
2188
2309
  const response = await client.listCoupons(params);
2189
2310
  return ctx.json(response);
@@ -2267,7 +2388,7 @@ function buildPaymentLinksEndpoints(client, adminOptions) {
2267
2388
  await requireAdmin(ctx, adminOptions);
2268
2389
  const params = {};
2269
2390
  if (ctx.query.page !== void 0) params.page = ctx.query.page;
2270
- if (ctx.query.size !== void 0) params.size = ctx.query.size;
2391
+ if (ctx.query.size !== void 0) params.limit = ctx.query.size;
2271
2392
  try {
2272
2393
  const response = await client.listPaymentLinks(params);
2273
2394
  return ctx.json(response);
@@ -2301,9 +2422,16 @@ function buildPaymentLinksEndpoints(client, adminOptions) {
2301
2422
  var WebhookEventsListQuery = z.object({
2302
2423
  status: z.enum(["pending", "completed", "dead_letter"]).optional(),
2303
2424
  eventType: z.string().optional(),
2304
- page: z.coerce.number().int().positive().optional(),
2425
+ page: z.coerce.number().int().positive().max(Number.MAX_SAFE_INTEGER).optional(),
2305
2426
  size: z.coerce.number().int().positive().max(100).optional()
2306
2427
  }).passthrough();
2428
+ function decodeWebhookEventId(value) {
2429
+ try {
2430
+ return decodeURIComponent(value);
2431
+ } catch {
2432
+ throw new APIError("BAD_REQUEST", { message: "Invalid webhook event identifier." });
2433
+ }
2434
+ }
2307
2435
  function buildWebhookEventsEndpoints(adminOptions, registry) {
2308
2436
  return {
2309
2437
  adminListWebhookEvents: createAuthEndpoint(
@@ -2348,7 +2476,7 @@ function buildWebhookEventsEndpoints(adminOptions, registry) {
2348
2476
  const adapter = getAdapter(ctx);
2349
2477
  const row = await adapter.findOne({
2350
2478
  model: WEBHOOK_EVENT_MODEL,
2351
- where: [{ field: "eventId", value: ctx.params.eventId }]
2479
+ where: [{ field: "eventId", value: decodeWebhookEventId(ctx.params.eventId) }]
2352
2480
  });
2353
2481
  if (!row) {
2354
2482
  throw new APIError("NOT_FOUND", {
@@ -2370,11 +2498,14 @@ function buildWebhookEventsEndpoints(adminOptions, registry) {
2370
2498
  await requireAdmin(ctx, adminOptions);
2371
2499
  if (!registry?.replayWebhookEvent) {
2372
2500
  throw new APIError("BAD_REQUEST", {
2373
- message: "Replay unavailable \u2014 `subscriptions()` plugin must be in `use` and `enableWebhookEventTable` left enabled."
2501
+ message: "Replay unavailable \u2014 enable the subscriptions webhook inbox or webhooks({ deduplicate: true })."
2374
2502
  });
2375
2503
  }
2376
2504
  try {
2377
- const result = await registry.replayWebhookEvent(ctx, ctx.params.eventId);
2505
+ const result = await registry.replayWebhookEvent(
2506
+ ctx,
2507
+ decodeWebhookEventId(ctx.params.eventId)
2508
+ );
2378
2509
  return ctx.json(result);
2379
2510
  } catch (err) {
2380
2511
  if (err instanceof APIError) throw err;
@@ -2396,9 +2527,10 @@ function buildWebhookEventsEndpoints(adminOptions, registry) {
2396
2527
  async (ctx) => {
2397
2528
  await requireAdmin(ctx, adminOptions);
2398
2529
  const adapter = getAdapter(ctx);
2530
+ const eventId = decodeWebhookEventId(ctx.params.eventId);
2399
2531
  const row = await adapter.findOne({
2400
2532
  model: WEBHOOK_EVENT_MODEL,
2401
- where: [{ field: "eventId", value: ctx.params.eventId }]
2533
+ where: [{ field: "eventId", value: eventId }]
2402
2534
  });
2403
2535
  if (!row) {
2404
2536
  throw new APIError("NOT_FOUND", {
@@ -2406,8 +2538,24 @@ function buildWebhookEventsEndpoints(adminOptions, registry) {
2406
2538
  message: `Webhook event ${ctx.params.eventId} not found.`
2407
2539
  });
2408
2540
  }
2541
+ if (registry?.subscriptionWebhookSync && !eventId.startsWith("handlers:") && (row.eventType === "INVOICE_COMPLETED" || row.eventType === "SUBSCRIPTION_CYCLE_RENEWED_SUCCESSFULLY")) {
2542
+ const subscription = await adapter.findOne({
2543
+ model: "subscription",
2544
+ where: [{ field: "renewalCallbackEventId", value: eventId }]
2545
+ });
2546
+ if (subscription) {
2547
+ await adapter.update({
2548
+ model: "subscription",
2549
+ update: { renewalCallbackEventId: null },
2550
+ where: [
2551
+ { field: "id", value: subscription.id },
2552
+ { field: "renewalCallbackEventId", value: eventId }
2553
+ ]
2554
+ });
2555
+ }
2556
+ }
2409
2557
  await markWebhookEventCompleted({ context: { adapter } }, row.id);
2410
- return ctx.json({ discarded: true, eventId: ctx.params.eventId });
2558
+ return ctx.json({ discarded: true, eventId });
2411
2559
  }
2412
2560
  )
2413
2561
  };
@@ -2435,21 +2583,21 @@ var CheckoutRequestBody = z.object({
2435
2583
  z.array(
2436
2584
  z.object({
2437
2585
  productId: z.string().uuid(),
2438
- quantity: z.number().int().positive().optional()
2586
+ quantity: z.number().int().positive().safe().optional()
2439
2587
  })
2440
2588
  ).min(1, "`products` must contain at least one item."),
2441
2589
  z.array(z.string().uuid()).min(1, "`products` must contain at least one item."),
2442
2590
  z.string().uuid()
2443
2591
  ]).optional(),
2444
- slug: z.string().optional(),
2592
+ slug: z.string().min(1).optional(),
2445
2593
  referenceId: z.string().optional(),
2446
2594
  name: z.string().min(1).optional(),
2447
2595
  description: z.string().optional(),
2448
- metadata: z.record(z.string(), z.union([z.string(), z.number(), z.boolean()])).optional(),
2596
+ metadata: z.record(z.string(), z.union([z.string(), z.number().finite(), z.boolean()])).optional(),
2449
2597
  successUrl: RelativeOrAbsoluteUrl.optional(),
2450
2598
  failureUrl: RelativeOrAbsoluteUrl.optional(),
2451
- maxNumberOfPayments: z.number().int().positive().optional(),
2452
- validUntil: z.string().datetime().optional(),
2599
+ maxNumberOfPayments: z.number().int().positive().safe().optional(),
2600
+ validUntil: z.string().datetime({ offset: true }).optional(),
2453
2601
  couponIds: z.array(z.string().uuid()).optional(),
2454
2602
  redirect: z.coerce.boolean().optional()
2455
2603
  });
@@ -2722,24 +2870,56 @@ var checkout = (checkoutOptions = {}) => {
2722
2870
  };
2723
2871
  };
2724
2872
  var DEFAULT_PAGE_SIZE = 100;
2873
+ var paginationQuery = z.object({
2874
+ page: z.coerce.number().int().min(1).max(Number.MAX_SAFE_INTEGER).optional(),
2875
+ size: z.coerce.number().int().min(1).max(100).optional()
2876
+ });
2725
2877
  async function getConsumerIdOrNull(client, user) {
2726
2878
  rejectUnauthorized(user, "Anonymous users cannot access the billing portal.");
2727
2879
  if (user.streampayConsumerId) return user.streampayConsumerId;
2728
2880
  return findConsumerByExternalId(client, { externalId: user.id });
2729
2881
  }
2730
- var portal = ({ pageSize } = {}) => (options) => {
2882
+ var portal = ({ pageSize, createSession } = {}) => (options) => {
2731
2883
  const client = options.client;
2732
2884
  const size = clampPageSize(pageSize);
2733
2885
  return {
2734
2886
  endpoints: {
2887
+ portalSession: createAuthEndpoint(
2888
+ "/consumer/portal/session",
2889
+ { method: "POST", use: [sessionMiddleware] },
2890
+ async (ctx) => {
2891
+ ctx.setHeader("cache-control", "no-store");
2892
+ try {
2893
+ const consumerId = await getConsumerIdOrNull(
2894
+ client,
2895
+ asSessionUser(ctx.context.session?.user)
2896
+ );
2897
+ if (!consumerId)
2898
+ throw new APIError("NOT_FOUND", {
2899
+ message: "No StreamPay consumer is linked to this account."
2900
+ });
2901
+ if (!createSession)
2902
+ throw new APIError("NOT_FOUND", {
2903
+ message: "Hosted customer portal is not configured."
2904
+ });
2905
+ const session = await createSession({ organization_consumer_id: consumerId });
2906
+ const url = new URL(session.url);
2907
+ if (url.protocol !== "https:" || url.username || url.password)
2908
+ throw new Error("Invalid hosted portal URL.");
2909
+ return ctx.json({ url: url.href });
2910
+ } catch (err) {
2911
+ toAPIError("StreamPay createPortalSession failed.", err, getLogger(ctx));
2912
+ }
2913
+ }
2914
+ ),
2735
2915
  state: createAuthEndpoint(
2736
2916
  "/consumer/state",
2737
2917
  { method: "GET", use: [sessionMiddleware] },
2738
2918
  async (ctx) => {
2739
2919
  const user = asSessionUser(ctx.context.session?.user);
2740
- const consumerId = await getConsumerIdOrNull(client, user);
2741
- if (!consumerId) return ctx.json({ hasConsumer: false, consumer: null });
2742
2920
  try {
2921
+ const consumerId = await getConsumerIdOrNull(client, user);
2922
+ if (!consumerId) return ctx.json({ hasConsumer: false, consumer: null });
2743
2923
  const consumer = await client.getConsumer(consumerId);
2744
2924
  return ctx.json({ hasConsumer: true, consumer });
2745
2925
  } catch (err) {
@@ -2749,18 +2929,22 @@ var portal = ({ pageSize } = {}) => (options) => {
2749
2929
  ),
2750
2930
  subscriptions: createAuthEndpoint(
2751
2931
  "/consumer/subscriptions/list",
2752
- { method: "GET", use: [sessionMiddleware] },
2932
+ { method: "GET", use: [sessionMiddleware], query: paginationQuery },
2753
2933
  async (ctx) => {
2754
2934
  const user = asSessionUser(ctx.context.session?.user);
2755
- const consumerId = await getConsumerIdOrNull(client, user);
2756
- if (!consumerId) return ctx.json({ hasConsumer: false, data: [] });
2757
2935
  try {
2936
+ const consumerId = await getConsumerIdOrNull(client, user);
2937
+ if (!consumerId) return ctx.json({ hasConsumer: false, data: [] });
2758
2938
  const response = await client.listSubscriptions({
2759
2939
  organization_consumer_id: consumerId,
2760
- page: 1,
2761
- size
2940
+ page: ctx.query?.page ?? 1,
2941
+ limit: ctx.query?.size ?? size
2942
+ });
2943
+ return ctx.json({
2944
+ hasConsumer: true,
2945
+ data: response.data ?? [],
2946
+ pagination: response.pagination
2762
2947
  });
2763
- return ctx.json({ hasConsumer: true, data: response.data ?? [] });
2764
2948
  } catch (err) {
2765
2949
  toAPIError("StreamPay listSubscriptions failed.", err, getLogger(ctx));
2766
2950
  }
@@ -2768,18 +2952,22 @@ var portal = ({ pageSize } = {}) => (options) => {
2768
2952
  ),
2769
2953
  invoices: createAuthEndpoint(
2770
2954
  "/consumer/invoices/list",
2771
- { method: "GET", use: [sessionMiddleware] },
2955
+ { method: "GET", use: [sessionMiddleware], query: paginationQuery },
2772
2956
  async (ctx) => {
2773
2957
  const user = asSessionUser(ctx.context.session?.user);
2774
- const consumerId = await getConsumerIdOrNull(client, user);
2775
- if (!consumerId) return ctx.json({ hasConsumer: false, data: [] });
2776
2958
  try {
2959
+ const consumerId = await getConsumerIdOrNull(client, user);
2960
+ if (!consumerId) return ctx.json({ hasConsumer: false, data: [] });
2777
2961
  const response = await client.listInvoices({
2778
2962
  organization_consumer_id: consumerId,
2779
- page: 1,
2780
- size
2963
+ page: ctx.query?.page ?? 1,
2964
+ limit: ctx.query?.size ?? size
2965
+ });
2966
+ return ctx.json({
2967
+ hasConsumer: true,
2968
+ data: response.data ?? [],
2969
+ pagination: response.pagination
2781
2970
  });
2782
- return ctx.json({ hasConsumer: true, data: response.data ?? [] });
2783
2971
  } catch (err) {
2784
2972
  toAPIError("StreamPay listInvoices failed.", err, getLogger(ctx));
2785
2973
  }
@@ -2797,6 +2985,7 @@ var STREAMPAY_EVENT_ENTITY_TYPES = {
2797
2985
  PAYMENT_FAILED: "PAYMENT",
2798
2986
  PAYMENT_CANCELED: "PAYMENT",
2799
2987
  PAYMENT_REFUNDED: "PAYMENT",
2988
+ PAYMENT_PARTIALLY_REFUNDED: "PAYMENT",
2800
2989
  PAYMENT_MARKED_AS_PAID: "PAYMENT",
2801
2990
  INVOICE_CREATED: "INVOICE",
2802
2991
  INVOICE_SENT: "INVOICE",
@@ -2811,6 +3000,7 @@ var STREAMPAY_EVENT_ENTITY_TYPES = {
2811
3000
  SUBSCRIPTION_CANCELED: "SUBSCRIPTION",
2812
3001
  SUBSCRIPTION_FROZEN: "SUBSCRIPTION",
2813
3002
  SUBSCRIPTION_CYCLE_RENEWAL_FAILED: "SUBSCRIPTION",
3003
+ SUBSCRIPTION_CYCLE_RENEWED_SUCCESSFULLY: "SUBSCRIPTION",
2814
3004
  SUBSCRIPTION_CANCEL_AT_PERIOD_END: "SUBSCRIPTION",
2815
3005
  SUBSCRIPTION_FREEZE_NOW: "SUBSCRIPTION",
2816
3006
  SUBSCRIPTION_UNFREEZE_NOW: "SUBSCRIPTION",
@@ -2958,7 +3148,10 @@ async function deleteReservedSubscription(adapter, rowId, log, reason) {
2958
3148
  try {
2959
3149
  await adapter.delete({
2960
3150
  model: SUBSCRIPTION_MODEL4,
2961
- where: [{ field: "id", value: rowId }]
3151
+ where: [
3152
+ { field: "id", value: rowId },
3153
+ { field: "status", value: "incomplete" }
3154
+ ]
2962
3155
  });
2963
3156
  } catch (err) {
2964
3157
  const message = err instanceof Error ? err.message : String(err);
@@ -2994,11 +3187,15 @@ async function resumeOrReserveCheckoutSlot(args) {
2994
3187
  if (recovery.kind === "recovered") {
2995
3188
  return { kind: "recovered", row: reuseCandidate, url: recovery.url };
2996
3189
  }
2997
- await adapter.update({
3190
+ const released = await adapter.update({
2998
3191
  model: SUBSCRIPTION_MODEL4,
2999
3192
  update: { status: "incomplete_expired", activeSlotKey: null, updatedAt: /* @__PURE__ */ new Date() },
3000
- where: [{ field: "id", value: reuseCandidate.id }]
3193
+ where: [
3194
+ { field: "id", value: reuseCandidate.id },
3195
+ { field: "status", value: "incomplete" }
3196
+ ]
3001
3197
  });
3198
+ if (!released) throw checkoutInProgressError();
3002
3199
  }
3003
3200
  const { data: reservationData, consumerId } = await args.createReservation();
3004
3201
  let row;
@@ -3039,6 +3236,7 @@ async function resumeOrReserveCheckoutSlot(args) {
3039
3236
  update: { status: "incomplete_expired", activeSlotKey: null, updatedAt: /* @__PURE__ */ new Date() },
3040
3237
  where: [
3041
3238
  { field: "id", value: reserved.id },
3239
+ { field: "status", value: "incomplete" },
3042
3240
  { field: "activeSlotKey", value: activeSlotKey }
3043
3241
  ]
3044
3242
  });
@@ -3118,6 +3316,43 @@ function configuredPlanForSubscription(subscription, plans) {
3118
3316
  }
3119
3317
  return matches[0];
3120
3318
  }
3319
+ async function findSubscriptionFreeze(client, options, subscriptionId, matches) {
3320
+ const listPage = options.listSubscriptionFreezes;
3321
+ if (!listPage) {
3322
+ const response = await client.listSubscriptionFreezes(subscriptionId);
3323
+ return {
3324
+ freeze: response.data?.find(matches),
3325
+ hasMore: response.pagination?.has_next_page ?? false
3326
+ };
3327
+ }
3328
+ const seenIds = /* @__PURE__ */ new Set();
3329
+ for (let page = 1; page <= 100; page++) {
3330
+ const response = await listPage(subscriptionId, { page, limit: 100 });
3331
+ const pagination = response.pagination;
3332
+ if (!Array.isArray(response.data) || !pagination || pagination.current_page !== page || typeof pagination.has_next_page !== "boolean") {
3333
+ throw freezePaginationConflict("StreamPay returned invalid freeze pagination.");
3334
+ }
3335
+ let advanced = false;
3336
+ for (const freeze2 of response.data) {
3337
+ if (freeze2.id && !seenIds.has(freeze2.id)) {
3338
+ seenIds.add(freeze2.id);
3339
+ advanced = true;
3340
+ }
3341
+ }
3342
+ if (!advanced && (pagination.has_next_page || response.data.length > 0)) {
3343
+ throw freezePaginationConflict("StreamPay freeze pagination returned no new entries.");
3344
+ }
3345
+ const freeze = response.data.find(matches);
3346
+ if (freeze || !pagination.has_next_page) return { freeze, hasMore: false };
3347
+ }
3348
+ throw freezePaginationConflict("StreamPay freeze pagination exceeded 100 pages.");
3349
+ }
3350
+ function freezePaginationConflict(message) {
3351
+ return new APIError("CONFLICT", {
3352
+ code: $ERROR_CODES.SUBSCRIPTION_INVALID_STATE.code,
3353
+ message
3354
+ });
3355
+ }
3121
3356
  var SUBSCRIPTION_INTERVALS = ["WEEK", "MONTH", "QUARTER", "YEAR"];
3122
3357
  var PlanSchema = z.object({
3123
3358
  name: z.string().min(1, "every plan must have a non-empty `name`."),
@@ -3222,7 +3457,7 @@ async function resolvePlans(plans) {
3222
3457
  return buildIndex(list);
3223
3458
  }
3224
3459
  function hasSubscriptionAccess(subscription, accessStatuses = DEFAULT_ACCESS_STATUSES) {
3225
- return accessStatuses.includes(subscription.status);
3460
+ return subscription.catalogMapped !== false && accessStatuses.includes(subscription.status);
3226
3461
  }
3227
3462
  function hasFeature(subscription, plan, feature, accessStatuses = DEFAULT_ACCESS_STATUSES) {
3228
3463
  if (!plan?.limits) return false;
@@ -3238,9 +3473,11 @@ function checkLimit(subscription, plan, feature, requested, accessStatuses = DEF
3238
3473
  }
3239
3474
  const raw = plan.limits[feature];
3240
3475
  const limit = typeof raw === "number" && Number.isFinite(raw) ? raw : 0;
3241
- const normalizedRequested = Number.isFinite(requested) && requested >= 0 ? requested : 0;
3242
- const allowed = normalizedRequested <= limit;
3243
- const remaining = Math.max(0, limit - normalizedRequested);
3476
+ if (!Number.isSafeInteger(requested) || requested < 0) {
3477
+ return { allowed: false, limit, remaining: 0 };
3478
+ }
3479
+ const allowed = requested <= limit;
3480
+ const remaining = Math.max(0, limit - requested);
3244
3481
  return { allowed, limit, remaining };
3245
3482
  }
3246
3483
 
@@ -3263,7 +3500,7 @@ var HasFeatureQuery = z.object({
3263
3500
  var CheckLimitQuery = z.object({
3264
3501
  ...ReferenceQueryFields,
3265
3502
  feature: z.string().min(1),
3266
- count: z.coerce.number().int().min(0),
3503
+ count: z.coerce.number().int().min(0).max(Number.MAX_SAFE_INTEGER),
3267
3504
  group: z.string().min(1).optional()
3268
3505
  });
3269
3506
  function presentSubscription(row, plans) {
@@ -3272,7 +3509,7 @@ function presentSubscription(row, plans) {
3272
3509
  // The column is nullable during safe rolling migrations. Keep the public
3273
3510
  // contract stable while applications backfill legacy rows to one seat.
3274
3511
  seats: row.seats ?? 1,
3275
- plan: plans.byName.get(row.plan) ?? null
3512
+ plan: row.catalogMapped === false ? null : plans.byName.get(row.plan) ?? null
3276
3513
  };
3277
3514
  }
3278
3515
  async function resolveLiveSubscription(ctx, query, subsOptions, accessStatuses) {
@@ -3455,8 +3692,8 @@ var UpdateSeatsBody = z.object({
3455
3692
  }).strict();
3456
3693
  var FreezeBody = z.object({
3457
3694
  subscriptionId: z.string().min(1),
3458
- freezeStartDatetime: z.string().datetime(),
3459
- freezeEndDatetime: z.string().datetime().nullable().optional(),
3695
+ freezeStartDatetime: z.string().datetime({ offset: true }),
3696
+ freezeEndDatetime: z.string().datetime({ offset: true }).nullable().optional(),
3460
3697
  notes: z.string().optional()
3461
3698
  });
3462
3699
  var UnfreezeBody = z.object({
@@ -3504,9 +3741,10 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
3504
3741
  const plans = await plansRef();
3505
3742
  const current = await client.getSubscription(row.streampaySubscriptionId);
3506
3743
  if (!current.pending_change) {
3507
- await adapter.update({
3508
- model: SUBSCRIPTION_MODEL6,
3509
- update: {
3744
+ await persistSubscriptionProjection(
3745
+ adapter,
3746
+ row,
3747
+ {
3510
3748
  ...projectSubscriptionAgainstExisting(row, current),
3511
3749
  ...projectPlanFields(current, plans),
3512
3750
  pendingPlan: null,
@@ -3515,15 +3753,17 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
3515
3753
  pendingSeats: null,
3516
3754
  pendingSeatsEffectiveAt: null
3517
3755
  },
3518
- where: [{ field: "id", value: row.id }]
3519
- });
3756
+ getLogger(ctx),
3757
+ "subscription endpoint"
3758
+ );
3520
3759
  return ctx.json({ canceled: true, reused: true, subscription: current });
3521
3760
  }
3522
3761
  await client.deletePendingSubscriptionChange(row.streampaySubscriptionId);
3523
3762
  const stream = await client.getSubscription(row.streampaySubscriptionId);
3524
- await adapter.update({
3525
- model: SUBSCRIPTION_MODEL6,
3526
- update: {
3763
+ await persistSubscriptionProjection(
3764
+ adapter,
3765
+ row,
3766
+ {
3527
3767
  ...projectSubscriptionAgainstExisting(row, stream),
3528
3768
  ...projectPlanFields(stream, plans),
3529
3769
  pendingPlan: null,
@@ -3532,8 +3772,9 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
3532
3772
  pendingSeats: null,
3533
3773
  pendingSeatsEffectiveAt: null
3534
3774
  },
3535
- where: [{ field: "id", value: row.id }]
3536
- });
3775
+ getLogger(ctx),
3776
+ "subscription endpoint"
3777
+ );
3537
3778
  return ctx.json({ canceled: true, reused: false, subscription: stream });
3538
3779
  } catch (err) {
3539
3780
  toAPIError(
@@ -3732,7 +3973,11 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
3732
3973
  activeSlotKey: null,
3733
3974
  updatedAt: /* @__PURE__ */ new Date()
3734
3975
  },
3735
- where: [{ field: "id", value: row.id }]
3976
+ where: [
3977
+ { field: "id", value: row.id },
3978
+ { field: "status", value: "incomplete" },
3979
+ { field: "streampayConsumerId", value: consumerId }
3980
+ ]
3736
3981
  });
3737
3982
  } catch (persistenceError) {
3738
3983
  const message = persistenceError instanceof Error ? persistenceError.message : String(persistenceError);
@@ -3758,7 +4003,13 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
3758
4003
  streampayPaymentLinkId: paymentLinkId,
3759
4004
  updatedAt: /* @__PURE__ */ new Date()
3760
4005
  },
3761
- where: [{ field: "id", value: row.id }]
4006
+ where: [
4007
+ { field: "id", value: row.id },
4008
+ { field: "referenceId", value: referenceId },
4009
+ { field: "referenceType", value: referenceType },
4010
+ { field: "streampayConsumerId", value: consumerId },
4011
+ { field: "streampayPaymentLinkId", value: null }
4012
+ ]
3762
4013
  });
3763
4014
  } catch (persistenceError) {
3764
4015
  const message = persistenceError instanceof Error ? persistenceError.message : String(persistenceError);
@@ -3840,10 +4091,11 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
3840
4091
  if (!match?.id) {
3841
4092
  return ctx.json({ subscription: row, synced: false });
3842
4093
  }
3843
- const updated = await adapter.update({
3844
- model: SUBSCRIPTION_MODEL6,
3845
- update: {
3846
- ...projectSubscriptionFields(match),
4094
+ const updated = await persistSubscriptionProjection(
4095
+ adapter,
4096
+ row,
4097
+ {
4098
+ ...projectSubscriptionFields(match, row),
3847
4099
  ...projectPlanFields(match, plans),
3848
4100
  planVersion: plan.version ?? null,
3849
4101
  productId: plan.productId,
@@ -3851,9 +4103,10 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
3851
4103
  activeSlotKey: row.activeSlotKey ?? subscriptionSlotKey(row.referenceType ?? "user", row.referenceId, row.group),
3852
4104
  updatedAt: /* @__PURE__ */ new Date()
3853
4105
  },
3854
- where: [{ field: "id", value: row.id }]
3855
- });
3856
- return ctx.json({ subscription: updated ?? row, synced: true });
4106
+ getLogger(ctx),
4107
+ "subscription endpoint"
4108
+ );
4109
+ return ctx.json({ subscription: updated, synced: updated !== null });
3857
4110
  } catch (err) {
3858
4111
  toAPIError(
3859
4112
  `subscriptionSuccess fallback sync failed for row=${row.id}:`,
@@ -3883,11 +4136,13 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
3883
4136
  try {
3884
4137
  const stream = await client.getSubscription(row.streampaySubscriptionId);
3885
4138
  if (stream.status === "CANCELED") {
3886
- await adapter.update({
3887
- model: SUBSCRIPTION_MODEL6,
3888
- update: projectSubscriptionAgainstExisting(row, stream),
3889
- where: [{ field: "id", value: row.id }]
3890
- });
4139
+ await persistSubscriptionProjection(
4140
+ adapter,
4141
+ row,
4142
+ projectSubscriptionAgainstExisting(row, stream),
4143
+ getLogger(ctx),
4144
+ "subscription endpoint"
4145
+ );
3891
4146
  return ctx.json(stream);
3892
4147
  }
3893
4148
  if (ctx.body.cancelAtPeriodEnd === false && stream.status === "ACTIVE") {
@@ -3897,11 +4152,13 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
3897
4152
  });
3898
4153
  }
3899
4154
  if (stream.cancel_at_period_end && !ctx.body.cancelRelatedInvoices) {
3900
- await adapter.update({
3901
- model: SUBSCRIPTION_MODEL6,
3902
- update: projectSubscriptionAgainstExisting(row, stream),
3903
- where: [{ field: "id", value: row.id }]
3904
- });
4155
+ await persistSubscriptionProjection(
4156
+ adapter,
4157
+ row,
4158
+ projectSubscriptionAgainstExisting(row, stream),
4159
+ getLogger(ctx),
4160
+ "subscription endpoint"
4161
+ );
3905
4162
  return ctx.json(stream);
3906
4163
  }
3907
4164
  if (ctx.body.cancelAtPeriodEnd === true && stream.status !== "ACTIVE") {
@@ -3995,9 +4252,10 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
3995
4252
  const pendingTargetMatches = Boolean(pendingTarget) && (subscriptionItemQuantity(pendingTarget) ?? 1) === nextSeats;
3996
4253
  if (pendingTargetMatches) {
3997
4254
  const effectiveAt2 = stream.pending_change?.effective_at ?? null;
3998
- await adapter.update({
3999
- model: SUBSCRIPTION_MODEL6,
4000
- update: {
4255
+ await persistSubscriptionProjection(
4256
+ adapter,
4257
+ row,
4258
+ {
4001
4259
  ...projectSubscriptionAgainstExisting(row, stream),
4002
4260
  ...projectPlanFields(stream, plans),
4003
4261
  pendingPlan: currentPlan.productId === nextPlan.productId ? null : nextPlan.name,
@@ -4006,8 +4264,9 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
4006
4264
  pendingSeats: nextSeats,
4007
4265
  pendingSeatsEffectiveAt: parseDate(effectiveAt2)
4008
4266
  },
4009
- where: [{ field: "id", value: row.id }]
4010
- });
4267
+ getLogger(ctx),
4268
+ "subscription endpoint"
4269
+ );
4011
4270
  return ctx.json({
4012
4271
  mode: "at_period_end",
4013
4272
  subscriptionId: row.id,
@@ -4039,15 +4298,17 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
4039
4298
  const pending = Boolean(result.pending_change);
4040
4299
  const effectiveAt = result.pending_change?.effective_at ?? null;
4041
4300
  const planProjection = projectPlanFields(result, plans);
4042
- await adapter.update({
4043
- model: SUBSCRIPTION_MODEL6,
4044
- update: {
4301
+ await persistSubscriptionProjection(
4302
+ adapter,
4303
+ row,
4304
+ {
4045
4305
  ...projectSubscriptionAgainstExisting(row, result),
4046
4306
  ...planProjection,
4047
4307
  updatedAt: /* @__PURE__ */ new Date()
4048
4308
  },
4049
- where: [{ field: "id", value: row.id }]
4050
- });
4309
+ getLogger(ctx),
4310
+ "subscription endpoint"
4311
+ );
4051
4312
  const providerPlan = pending ? planProjection.pendingPlan ?? planProjection.plan ?? row.plan : planProjection.plan ?? row.plan;
4052
4313
  const providerSeats = pending ? planProjection.pendingSeats ?? nextSeats : planProjection.seats ?? row.seats ?? nextSeats;
4053
4314
  return ctx.json({
@@ -4113,14 +4374,16 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
4113
4374
  if (stream.pending_change) {
4114
4375
  if (pendingTarget && (subscriptionItemQuantity(pendingTarget) ?? 1) === seats) {
4115
4376
  const effectiveAt2 = stream.pending_change.effective_at ?? null;
4116
- await adapter.update({
4117
- model: SUBSCRIPTION_MODEL6,
4118
- update: {
4377
+ await persistSubscriptionProjection(
4378
+ adapter,
4379
+ row,
4380
+ {
4119
4381
  ...projectSubscriptionAgainstExisting(row, stream),
4120
4382
  ...projectPlanFields(stream, plans)
4121
4383
  },
4122
- where: [{ field: "id", value: row.id }]
4123
- });
4384
+ getLogger(ctx),
4385
+ "subscription endpoint"
4386
+ );
4124
4387
  return ctx.json({
4125
4388
  mode: "at_period_end",
4126
4389
  subscriptionId: row.id,
@@ -4136,14 +4399,16 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
4136
4399
  });
4137
4400
  }
4138
4401
  if (currentSeats === seats) {
4139
- await adapter.update({
4140
- model: SUBSCRIPTION_MODEL6,
4141
- update: {
4402
+ await persistSubscriptionProjection(
4403
+ adapter,
4404
+ row,
4405
+ {
4142
4406
  ...projectSubscriptionAgainstExisting(row, stream),
4143
4407
  ...projectPlanFields(stream, plans)
4144
4408
  },
4145
- where: [{ field: "id", value: row.id }]
4146
- });
4409
+ getLogger(ctx),
4410
+ "subscription endpoint"
4411
+ );
4147
4412
  return ctx.json({
4148
4413
  mode: "current",
4149
4414
  subscriptionId: row.id,
@@ -4161,15 +4426,17 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
4161
4426
  const pending = Boolean(result.pending_change);
4162
4427
  const effectiveAt = result.pending_change?.effective_at ?? null;
4163
4428
  const planProjection = projectPlanFields(result, plans);
4164
- await adapter.update({
4165
- model: SUBSCRIPTION_MODEL6,
4166
- update: {
4429
+ await persistSubscriptionProjection(
4430
+ adapter,
4431
+ row,
4432
+ {
4167
4433
  ...projectSubscriptionAgainstExisting(row, result),
4168
4434
  ...planProjection,
4169
4435
  updatedAt: /* @__PURE__ */ new Date()
4170
4436
  },
4171
- where: [{ field: "id", value: row.id }]
4172
- });
4437
+ getLogger(ctx),
4438
+ "subscription endpoint"
4439
+ );
4173
4440
  const providerSeats = pending ? planProjection.pendingSeats ?? seats : planProjection.seats ?? row.seats ?? seats;
4174
4441
  return ctx.json({
4175
4442
  mode: pending ? "at_period_end" : "immediate",
@@ -4213,11 +4480,13 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
4213
4480
  try {
4214
4481
  await client.uncancelSubscription(row.streampaySubscriptionId);
4215
4482
  const stream = await client.getSubscription(row.streampaySubscriptionId);
4216
- await adapter.update({
4217
- model: SUBSCRIPTION_MODEL6,
4218
- update: projectSubscriptionAgainstExisting(row, stream),
4219
- where: [{ field: "id", value: row.id }]
4220
- });
4483
+ await persistSubscriptionProjection(
4484
+ adapter,
4485
+ row,
4486
+ projectSubscriptionAgainstExisting(row, stream),
4487
+ getLogger(ctx),
4488
+ "subscription endpoint"
4489
+ );
4221
4490
  return ctx.json({ uncanceled: true, subscription: stream });
4222
4491
  } catch (err) {
4223
4492
  toAPIError(
@@ -4292,13 +4561,30 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
4292
4561
  );
4293
4562
  const nowMs = Date.now();
4294
4563
  try {
4295
- const freezes = await client.listSubscriptionFreezes(row.streampaySubscriptionId);
4296
- const active = freezes.data?.find((freeze) => {
4564
+ const isActiveFreeze = (freeze) => {
4297
4565
  if (!freeze.id || !freeze.freeze_start_datetime) return false;
4298
4566
  const start = parseDate(freeze.freeze_start_datetime)?.getTime();
4299
4567
  const end = freeze.freeze_end_datetime ? parseDate(freeze.freeze_end_datetime)?.getTime() : Number.POSITIVE_INFINITY;
4300
- return start !== void 0 && end !== void 0 && start <= nowMs && nowMs <= end;
4301
- });
4568
+ return start !== void 0 && end !== void 0 && start <= nowMs && nowMs < end;
4569
+ };
4570
+ const result = await findSubscriptionFreeze(
4571
+ client,
4572
+ subsOptions,
4573
+ row.streampaySubscriptionId,
4574
+ isActiveFreeze
4575
+ );
4576
+ let active = result.freeze;
4577
+ if (!active && result.hasMore) {
4578
+ const stream = await client.getSubscription(row.streampaySubscriptionId);
4579
+ if (stream.status === "FROZEN" && stream.latest_freeze && isActiveFreeze(stream.latest_freeze)) {
4580
+ active = stream.latest_freeze;
4581
+ } else {
4582
+ throw new APIError("CONFLICT", {
4583
+ code: $ERROR_CODES.SUBSCRIPTION_INVALID_STATE.code,
4584
+ message: "StreamPay returned more freeze pages than the SDK can read. Unable to verify the active freeze."
4585
+ });
4586
+ }
4587
+ }
4302
4588
  if (!active?.id || !active.freeze_start_datetime) {
4303
4589
  throw new APIError("BAD_REQUEST", {
4304
4590
  code: $ERROR_CODES.SUBSCRIPTION_FREEZE_NOT_ACTIVE.code,
@@ -4345,8 +4631,19 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
4345
4631
  "cancel-freeze"
4346
4632
  );
4347
4633
  try {
4348
- const freezes = await client.listSubscriptionFreezes(row.streampaySubscriptionId);
4349
- if (!freezes.data?.some((freeze) => freeze.id === ctx.body.freezeId)) {
4634
+ const result = await findSubscriptionFreeze(
4635
+ client,
4636
+ subsOptions,
4637
+ row.streampaySubscriptionId,
4638
+ (freeze) => freeze.id === ctx.body.freezeId
4639
+ );
4640
+ if (!result.freeze) {
4641
+ if (result.hasMore) {
4642
+ throw new APIError("CONFLICT", {
4643
+ code: $ERROR_CODES.SUBSCRIPTION_INVALID_STATE.code,
4644
+ message: "StreamPay returned more freeze pages than the SDK can read. Unable to verify whether this freeze was canceled."
4645
+ });
4646
+ }
4350
4647
  return ctx.json({ canceled: true, freezeId: ctx.body.freezeId, reused: true });
4351
4648
  }
4352
4649
  await client.deleteSubscriptionFreeze(row.streampaySubscriptionId, ctx.body.freezeId);
@@ -4423,6 +4720,12 @@ var subscriptionTable = {
4423
4720
  type: "string",
4424
4721
  required: true
4425
4722
  },
4723
+ catalogMapped: {
4724
+ type: "boolean",
4725
+ required: false,
4726
+ defaultValue: true,
4727
+ input: false
4728
+ },
4426
4729
  planVersion: {
4427
4730
  type: "string",
4428
4731
  required: false
@@ -4492,6 +4795,11 @@ var subscriptionTable = {
4492
4795
  type: "number",
4493
4796
  required: false
4494
4797
  },
4798
+ renewalCallbackEventId: {
4799
+ type: "string",
4800
+ required: false,
4801
+ input: false
4802
+ },
4495
4803
  trialStart: {
4496
4804
  type: "date",
4497
4805
  required: false
@@ -4702,6 +5010,9 @@ function subscriptions(subsOptions) {
4702
5010
  };
4703
5011
  if (dedupeEnabled) {
4704
5012
  registry.replayWebhookEvent = async (ctx, eventId) => {
5013
+ if (eventId.startsWith("handlers:") && registry.replayWebhookHandler) {
5014
+ return registry.replayWebhookHandler(ctx, eventId);
5015
+ }
4705
5016
  const syncCtx = {
4706
5017
  context: ctx.context
4707
5018
  };
@@ -4794,6 +5105,9 @@ async function dispatchWebhook(payload, handlers) {
4794
5105
  case "PAYMENT_REFUNDED":
4795
5106
  await handlers.onPaymentRefunded?.(payload);
4796
5107
  return;
5108
+ case "PAYMENT_PARTIALLY_REFUNDED":
5109
+ await handlers.onPaymentPartiallyRefunded?.(payload);
5110
+ return;
4797
5111
  case "PAYMENT_MARKED_AS_PAID":
4798
5112
  await handlers.onPaymentMarkedAsPaid?.(payload);
4799
5113
  return;
@@ -4836,6 +5150,9 @@ async function dispatchWebhook(payload, handlers) {
4836
5150
  case "SUBSCRIPTION_CYCLE_RENEWAL_FAILED":
4837
5151
  await handlers.onSubscriptionCycleRenewalFailed?.(payload);
4838
5152
  return;
5153
+ case "SUBSCRIPTION_CYCLE_RENEWED_SUCCESSFULLY":
5154
+ await handlers.onSubscriptionCycleRenewedSuccessfully?.(payload);
5155
+ return;
4839
5156
  case "SUBSCRIPTION_CANCEL_AT_PERIOD_END":
4840
5157
  await handlers.onSubscriptionCancelAtPeriodEnd?.(payload);
4841
5158
  return;
@@ -4944,8 +5261,56 @@ var webhooks = (webhooksOptions) => {
4944
5261
  throw new TypeError("webhooks(): `toleranceSeconds` must be a non-negative number.");
4945
5262
  }
4946
5263
  return (_options, registry) => {
4947
- const { secret, toleranceSeconds, ...handlers } = webhooksOptions;
5264
+ const { secret, toleranceSeconds, deduplicate = false, ...handlers } = webhooksOptions;
5265
+ if (deduplicate && registry) {
5266
+ registry.replayWebhookHandler = async (ctx, eventId) => {
5267
+ const syncContext = { context: ctx.context };
5268
+ const row = await syncContext.context.adapter.findOne({
5269
+ model: WEBHOOK_EVENT_MODEL,
5270
+ where: [{ field: "eventId", value: eventId }]
5271
+ });
5272
+ if (!eventId.startsWith("handlers:") || !row)
5273
+ throw new APIError("NOT_FOUND", { message: "Webhook callback event not found." });
5274
+ if (!row.rawPayload)
5275
+ throw new APIError("BAD_REQUEST", { message: "Webhook callback has no stored payload." });
5276
+ let payload;
5277
+ try {
5278
+ payload = JSON.parse(row.rawPayload);
5279
+ } catch {
5280
+ throw new APIError("BAD_REQUEST", {
5281
+ message: "Stored webhook payload is not valid JSON."
5282
+ });
5283
+ }
5284
+ if (!isStreamPayWebhookEnvelope(payload))
5285
+ throw new APIError("BAD_REQUEST", {
5286
+ message: "Stored webhook payload is not a valid event envelope."
5287
+ });
5288
+ const claimed = await claimWebhookEventForReplay(syncContext, row);
5289
+ if (!claimed?.lockedBy)
5290
+ throw new APIError("CONFLICT", {
5291
+ message: "Webhook callback is already being processed."
5292
+ });
5293
+ try {
5294
+ await dispatchWebhook(payload, handlers);
5295
+ await markWebhookEventCompleted(syncContext, claimed.id, claimed.lockedBy);
5296
+ } catch (err) {
5297
+ await recordWebhookEventFailure(
5298
+ syncContext,
5299
+ claimed.id,
5300
+ row.rawPayload,
5301
+ row.signatureHeader,
5302
+ err,
5303
+ claimed.lockedBy,
5304
+ true
5305
+ );
5306
+ throw err;
5307
+ }
5308
+ return { replayed: true, eventId };
5309
+ };
5310
+ registry.replayWebhookEvent ??= registry.replayWebhookHandler;
5311
+ }
4948
5312
  return {
5313
+ schema: deduplicate ? webhookEventTable : {},
4949
5314
  endpoints: {
4950
5315
  streampayWebhooks: createAuthEndpoint(
4951
5316
  "/streampay/webhooks",
@@ -5005,9 +5370,32 @@ var webhooks = (webhooksOptions) => {
5005
5370
  });
5006
5371
  }
5007
5372
  }
5373
+ const syncContext = { context: ctx.context };
5374
+ const claim = deduplicate ? await claimOrAdvanceWebhookEvent(
5375
+ syncContext,
5376
+ payload,
5377
+ rawBody,
5378
+ signatureHeader,
5379
+ DEFAULT_MAX_WEBHOOK_ATTEMPTS,
5380
+ "handlers"
5381
+ ) : null;
5382
+ if (claim && claim.action !== "process") return ctx.json({ received: true });
5383
+ const row = claim?.action === "process" ? claim.row : null;
5008
5384
  try {
5009
5385
  await dispatchWebhook(payload, handlers);
5386
+ if (row)
5387
+ await markWebhookEventCompleted(syncContext, row.id, row.lockedBy ?? void 0);
5010
5388
  } catch (err) {
5389
+ if (row)
5390
+ await recordWebhookEventFailure(
5391
+ syncContext,
5392
+ row.id,
5393
+ rawBody,
5394
+ signatureHeader,
5395
+ err,
5396
+ row.lockedBy ?? void 0,
5397
+ row.attemptCount >= DEFAULT_MAX_WEBHOOK_ATTEMPTS
5398
+ );
5011
5399
  const message = err instanceof Error ? err.message : String(err);
5012
5400
  logger2.error(`webhook handler failed: ${message}`);
5013
5401
  throw new APIError("INTERNAL_SERVER_ERROR", {
@@ -5035,11 +5423,12 @@ var onBeforeUserCreate = (options) => async (user, context) => {
5035
5423
  }
5036
5424
  const extras = options.getConsumerCreateParams ? await options.getConsumerCreateParams({ user }) : {};
5037
5425
  const createPayload = {
5038
- name: user.name || user.email,
5039
- email: user.email,
5040
5426
  consumer_type: "INDIVIDUAL",
5041
- ...extras
5427
+ ...extras,
5428
+ name: user.name || user.email,
5429
+ email: user.email
5042
5430
  };
5431
+ delete createPayload.external_id;
5043
5432
  try {
5044
5433
  const consumer = await options.client.createConsumer(createPayload);
5045
5434
  if (!consumer.id) {
@@ -5136,7 +5525,7 @@ var onUserDelete = (options) => async (user, context) => {
5136
5525
 
5137
5526
  // package.json
5138
5527
  var package_default = {
5139
- version: "2.2.1"};
5528
+ version: "3.0.0"};
5140
5529
 
5141
5530
  // src/version.ts
5142
5531
  var version = package_default.version;