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