better-auth-streampay 2.2.1 → 3.0.1

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(),
@@ -268,6 +288,46 @@ function scopedLogger(logger2) {
268
288
  function getLogger(ctx) {
269
289
  return scopedLogger(ctx.context.logger);
270
290
  }
291
+ async function getCurrentConsumerUser(ctx, user) {
292
+ if (!user.streampayConsumerId) return user;
293
+ if (!ctx.context.adapter) {
294
+ throw new api.APIError("INTERNAL_SERVER_ERROR", { message: "Consumer storage is unavailable." });
295
+ }
296
+ const current = await ctx.context.adapter.findOne({
297
+ model: "user",
298
+ where: [{ field: "id", value: user.id }]
299
+ });
300
+ if (!current || current.id !== user.id) {
301
+ throw new api.APIError("UNAUTHORIZED", { message: "The account no longer exists." });
302
+ }
303
+ if (current.streampayConsumerId != null && typeof current.streampayConsumerId !== "string") {
304
+ throw new api.APIError("INTERNAL_SERVER_ERROR", { message: "Invalid stored consumer link." });
305
+ }
306
+ return { ...user, streampayConsumerId: current.streampayConsumerId ?? null };
307
+ }
308
+ function asSessionUser(user) {
309
+ if (user === null || typeof user !== "object") return null;
310
+ if (!("id" in user) || typeof user.id !== "string") return null;
311
+ const result = { id: user.id };
312
+ if ("email" in user && typeof user.email === "string") {
313
+ result.email = user.email;
314
+ }
315
+ if ("name" in user && typeof user.name === "string") {
316
+ result.name = user.name;
317
+ }
318
+ if ("isAnonymous" in user && user.isAnonymous === true) {
319
+ result.isAnonymous = true;
320
+ }
321
+ if ("streampayConsumerId" in user) {
322
+ const value = user.streampayConsumerId;
323
+ if (typeof value === "string") {
324
+ result.streampayConsumerId = value;
325
+ } else if (value === null) {
326
+ result.streampayConsumerId = null;
327
+ }
328
+ }
329
+ return result;
330
+ }
271
331
 
272
332
  // src/utils/ensure-consumer.ts
273
333
  function canClaimBy(mode, identifier) {
@@ -310,6 +370,7 @@ async function resolveDuplicateConsumer(options, createPayload, context) {
310
370
  return existing.id;
311
371
  }
312
372
  async function ensureConsumerForUser(options, ctx, user) {
373
+ user = await getCurrentConsumerUser(ctx, user);
313
374
  if (user.streampayConsumerId) {
314
375
  return { consumerId: user.streampayConsumerId, created: false };
315
376
  }
@@ -329,11 +390,11 @@ async function ensureConsumerForUser(options, ctx, user) {
329
390
  if (user.name !== void 0) userForParams.name = user.name;
330
391
  const extras = options.getConsumerCreateParams ? await options.getConsumerCreateParams({ user: userForParams }) : {};
331
392
  const payload = {
393
+ consumer_type: "INDIVIDUAL",
394
+ ...extras,
332
395
  name: user.name || user.email,
333
396
  email: user.email,
334
- external_id: user.id,
335
- consumer_type: "INDIVIDUAL",
336
- ...extras
397
+ external_id: user.id
337
398
  };
338
399
  try {
339
400
  const consumer = await options.client.createConsumer(payload);
@@ -349,10 +410,25 @@ async function ensureConsumerForUser(options, ctx, user) {
349
410
  if (isDuplicateConsumerError(err)) {
350
411
  const reusedId = await resolveDuplicateConsumer(options, payload, ctx);
351
412
  if (reusedId) {
352
- await assertConsumerUnclaimed(ctx, reusedId, user.id);
413
+ await persistConsumerId(ctx, user.id, reusedId);
353
414
  try {
354
415
  await options.client.updateConsumer(reusedId, { external_id: user.id });
355
416
  } catch (backfillErr) {
417
+ try {
418
+ if (!ctx.context.adapter.update) throw consumerLinkUnavailable();
419
+ await ctx.context.adapter.update({
420
+ model: "user",
421
+ where: [
422
+ { field: "id", value: user.id },
423
+ { field: "streampayConsumerId", value: reusedId }
424
+ ],
425
+ update: { streampayConsumerId: null }
426
+ });
427
+ } catch (clearErr) {
428
+ getLogger(ctx).error(
429
+ `consumer claim cleanup failed for user=${user.id} consumer=${reusedId}: ${formatStreamPayError(clearErr)}`
430
+ );
431
+ }
356
432
  getLogger(ctx).error(
357
433
  `consumer external_id backfill failed for user=${user.id} consumer=${reusedId}: ${formatStreamPayError(backfillErr)}`
358
434
  );
@@ -361,7 +437,6 @@ async function ensureConsumerForUser(options, ctx, user) {
361
437
  message: "StreamPay consumer linking failed. Please try again."
362
438
  });
363
439
  }
364
- await persistConsumerId(ctx, user.id, reusedId);
365
440
  return { consumerId: reusedId, created: false };
366
441
  }
367
442
  }
@@ -381,9 +456,15 @@ function consumerLinkUnavailable() {
381
456
  }
382
457
  async function findConsumerOwner(ctx, consumerId) {
383
458
  try {
459
+ const where = [{ field: "streampayConsumerId", value: consumerId }];
460
+ if (ctx.context.internalAdapter?.listUsers) {
461
+ const owners = await ctx.context.internalAdapter.listUsers(1, 0, void 0, where);
462
+ return owners[0] ?? null;
463
+ }
464
+ if (!ctx.context.adapter) throw consumerLinkUnavailable();
384
465
  return await ctx.context.adapter.findOne({
385
466
  model: "user",
386
- where: [{ field: "streampayConsumerId", value: consumerId }]
467
+ where
387
468
  });
388
469
  } catch (err) {
389
470
  getLogger(ctx).error(
@@ -496,31 +577,6 @@ function rejectUnauthorized(user, anonymousMessage) {
496
577
  }
497
578
  }
498
579
 
499
- // src/utils/session.ts
500
- function asSessionUser(user) {
501
- if (user === null || typeof user !== "object") return null;
502
- if (!("id" in user) || typeof user.id !== "string") return null;
503
- const result = { id: user.id };
504
- if ("email" in user && typeof user.email === "string") {
505
- result.email = user.email;
506
- }
507
- if ("name" in user && typeof user.name === "string") {
508
- result.name = user.name;
509
- }
510
- if ("isAnonymous" in user && user.isAnonymous === true) {
511
- result.isAnonymous = true;
512
- }
513
- if ("streampayConsumerId" in user) {
514
- const value = user.streampayConsumerId;
515
- if (typeof value === "string") {
516
- result.streampayConsumerId = value;
517
- } else if (value === null) {
518
- result.streampayConsumerId = null;
519
- }
520
- }
521
- return result;
522
- }
523
-
524
580
  // src/plugins/subscriptions/status.ts
525
581
  var SUBSCRIPTION_STATUSES = [
526
582
  "incomplete",
@@ -602,7 +658,32 @@ function reconcileProjectionAgainstExisting(existing, projection, options = {})
602
658
  return projected;
603
659
  }
604
660
  function projectSubscriptionAgainstExisting(existing, stream) {
605
- return reconcileProjectionAgainstExisting(existing, projectSubscriptionFields(stream));
661
+ return reconcileProjectionAgainstExisting(existing, projectSubscriptionFields(stream, existing));
662
+ }
663
+ async function persistSubscriptionProjection(adapter, existing, projection, log, source) {
664
+ const stale = existing.providerUpdatedAt instanceof Date && projection.providerUpdatedAt instanceof Date && projection.providerUpdatedAt.getTime() < existing.providerUpdatedAt.getTime();
665
+ if (!stale) {
666
+ const updated = await adapter.update({
667
+ model: SUBSCRIPTION_MODEL,
668
+ update: projection,
669
+ where: [
670
+ { field: "id", value: existing.id },
671
+ { field: "providerUpdatedAt", value: existing.providerUpdatedAt ?? null },
672
+ { field: "streampaySubscriptionId", value: existing.streampaySubscriptionId ?? null },
673
+ { field: "streampayConsumerId", value: existing.streampayConsumerId ?? null },
674
+ { field: "status", value: existing.status },
675
+ { field: "billingStatus", value: existing.billingStatus }
676
+ ]
677
+ });
678
+ if (updated) return updated;
679
+ }
680
+ log.warn(
681
+ `${source}: retained newer local subscription state for row=${existing.id}. The provider action is not rolled back.`
682
+ );
683
+ return adapter.findOne({
684
+ model: SUBSCRIPTION_MODEL,
685
+ where: [{ field: "id", value: existing.id }]
686
+ });
606
687
  }
607
688
  async function applySubscriptionProjection(adapter, stream, log, source) {
608
689
  const streampaySubscriptionId = stream?.id;
@@ -613,11 +694,13 @@ async function applySubscriptionProjection(adapter, stream, log, source) {
613
694
  where: [{ field: "streampaySubscriptionId", value: streampaySubscriptionId }]
614
695
  });
615
696
  if (!existing) return;
616
- await adapter.update({
617
- model: SUBSCRIPTION_MODEL,
618
- update: projectSubscriptionAgainstExisting(existing, stream),
619
- where: [{ field: "id", value: existing.id }]
620
- });
697
+ await persistSubscriptionProjection(
698
+ adapter,
699
+ existing,
700
+ projectSubscriptionAgainstExisting(existing, stream),
701
+ log,
702
+ source
703
+ );
621
704
  } catch (err) {
622
705
  const message = err instanceof Error ? err.message : String(err);
623
706
  log.warn(
@@ -640,7 +723,7 @@ async function syncSubscriptionFromUpstream(client, adapter, streampaySubscripti
640
723
  }
641
724
  await applySubscriptionProjection(adapter, stream, log, source);
642
725
  }
643
- function projectSubscriptionFields(sub) {
726
+ function projectSubscriptionFields(sub, existing) {
644
727
  const status = toLocalStatus(sub.status);
645
728
  const terminal = isTerminalSubscriptionStatus(status);
646
729
  const periodStart = parseDate(sub.current_period_start);
@@ -658,7 +741,7 @@ function projectSubscriptionFields(sub) {
658
741
  periodStart,
659
742
  periodEnd,
660
743
  currentCycleNumber: sub.current_cycle_number ?? null,
661
- trialStart: sub.trial_end ? parseDate(sub.started_at) ?? periodStart : null,
744
+ trialStart: (sub.trial_end ? parseDate(sub.started_at) ?? periodStart : null) ?? existing?.trialStart ?? null,
662
745
  trialEnd: parseDate(sub.trial_end),
663
746
  cancelAtPeriodEnd: Boolean(sub.cancel_at_period_end),
664
747
  cancelAt: sub.cancel_at_period_end ? periodEnd : null,
@@ -762,6 +845,7 @@ function projectPlanFields(sub, plans) {
762
845
  const pendingEffectiveAt = parseDate(sub.pending_change?.effective_at);
763
846
  const planChanges = Boolean(inferredPendingPlan) && (inferredPendingPlan !== currentPlan || pendingProductId !== currentProductId);
764
847
  return {
848
+ catalogMapped: Boolean(currentPlan),
765
849
  ...currentPlan ? {
766
850
  plan: currentPlan,
767
851
  planVersion: configuredCurrent?.version ?? null,
@@ -812,8 +896,9 @@ function isUniqueConstraintError(err) {
812
896
  }
813
897
  var WEBHOOK_PROCESSING_LEASE_MS = 2 * 60 * 1e3;
814
898
  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);
899
+ async function claimOrAdvanceWebhookEvent(ctx, payload, rawBody, signatureHeader, maxAttempts, scope) {
900
+ const sourceEventId = extractEventId(payload);
901
+ const eventId = sourceEventId && (scope ? `${scope}:${sourceEventId}` : sourceEventId);
817
902
  if (!eventId) {
818
903
  logger(ctx).warn(
819
904
  `webhook ${payload.event_type}: missing entity_id/timestamp \u2014 processing without dedupe.`
@@ -833,7 +918,9 @@ async function claimOrAdvanceWebhookEvent(ctx, payload, rawBody, signatureHeader
833
918
  receivedAt: now,
834
919
  lastAttemptAt: now,
835
920
  lockedAt: now,
836
- lockedBy: lockId
921
+ lockedBy: lockId,
922
+ rawPayload: rawBody,
923
+ signatureHeader
837
924
  }
838
925
  });
839
926
  return { action: "process", row: inserted };
@@ -845,10 +932,9 @@ async function claimOrAdvanceWebhookEvent(ctx, payload, rawBody, signatureHeader
845
932
  where: [{ field: "eventId", value: eventId }]
846
933
  });
847
934
  if (!existing) {
848
- logger(ctx).warn(
849
- `webhook ${payload.event_type} (${eventId}): unique conflict but row missing, processing without tracking.`
935
+ throw new Error(
936
+ `Webhook inbox row missing after unique conflict for ${eventId}; retry delivery.`
850
937
  );
851
- return { action: "process", row: null };
852
938
  }
853
939
  if (existing.status === "completed") {
854
940
  logger(ctx).info(`webhook ${payload.event_type} (${eventId}) already completed \u2014 skipping.`);
@@ -1002,7 +1088,7 @@ async function findSubscriptionByStreampayId(ctx, streampaySubscriptionId) {
1002
1088
  where: [{ field: "streampaySubscriptionId", value: streampaySubscriptionId }]
1003
1089
  });
1004
1090
  }
1005
- async function findIncompleteRow(ctx, referenceId, referenceType, plan, paymentLinkId) {
1091
+ async function findIncompleteRow(ctx, referenceId, referenceType, plan, paymentLinkId, consumerId) {
1006
1092
  const candidates = await ctx.context.adapter.findMany({
1007
1093
  model: SUBSCRIPTION_MODEL2,
1008
1094
  where: [
@@ -1011,13 +1097,15 @@ async function findIncompleteRow(ctx, referenceId, referenceType, plan, paymentL
1011
1097
  { field: "status", value: "incomplete" }
1012
1098
  ]
1013
1099
  });
1014
- const scopedCandidates = referenceType ? candidates.filter((candidate) => (candidate.referenceType ?? "user") === referenceType) : candidates;
1100
+ const scopedCandidates = candidates.filter(
1101
+ (candidate) => (!referenceType || (candidate.referenceType ?? "user") === referenceType) && (!consumerId || !candidate.streampayConsumerId || candidate.streampayConsumerId === consumerId)
1102
+ );
1015
1103
  if (scopedCandidates.length === 0) return null;
1016
1104
  if (paymentLinkId) {
1017
1105
  const exact = scopedCandidates.find(
1018
1106
  (candidate) => candidate.streampayPaymentLinkId === paymentLinkId
1019
1107
  );
1020
- if (exact) return exact;
1108
+ return exact ?? null;
1021
1109
  }
1022
1110
  if (!referenceType && new Set(scopedCandidates.map((candidate) => candidate.referenceType ?? "user")).size > 1) {
1023
1111
  return null;
@@ -1066,6 +1154,31 @@ var SubscriptionCorrelationError = class extends Error {
1066
1154
  this.name = "SubscriptionCorrelationError";
1067
1155
  }
1068
1156
  };
1157
+ async function updateReconciledSubscription(ctx, existing, projected, streampaySubscriptionId) {
1158
+ if (existing.providerUpdatedAt instanceof Date && projected.providerUpdatedAt instanceof Date && projected.providerUpdatedAt.getTime() < existing.providerUpdatedAt.getTime()) {
1159
+ throw new Error(
1160
+ `StreamPay returned stale subscription state for sub=${streampaySubscriptionId}. Retry reconciliation.`
1161
+ );
1162
+ }
1163
+ const updated = await ctx.context.adapter.update({
1164
+ model: SUBSCRIPTION_MODEL2,
1165
+ update: projected,
1166
+ where: [
1167
+ { field: "id", value: existing.id },
1168
+ { field: "providerUpdatedAt", value: existing.providerUpdatedAt ?? null },
1169
+ { field: "streampaySubscriptionId", value: existing.streampaySubscriptionId ?? null },
1170
+ { field: "streampayConsumerId", value: existing.streampayConsumerId ?? null },
1171
+ { field: "status", value: existing.status },
1172
+ { field: "billingStatus", value: existing.billingStatus }
1173
+ ]
1174
+ });
1175
+ if (!updated) {
1176
+ throw new Error(
1177
+ `Subscription state changed during reconciliation for sub=${streampaySubscriptionId}. Retry delivery.`
1178
+ );
1179
+ }
1180
+ return updated;
1181
+ }
1069
1182
  async function reconcileFromStreamPay(ctx, payload, client, plans) {
1070
1183
  const streampaySubscriptionId = payload.entity_id;
1071
1184
  if (!streampaySubscriptionId) {
@@ -1084,7 +1197,7 @@ async function reconcileFromStreamPay(ctx, payload, client, plans) {
1084
1197
  }
1085
1198
  const existing = await findSubscriptionByStreampayId(ctx, streampaySubscriptionId);
1086
1199
  let projected = {
1087
- ...projectSubscriptionFields(stream),
1200
+ ...projectSubscriptionFields(stream, existing),
1088
1201
  ...projectPlanFields(stream, plans)
1089
1202
  };
1090
1203
  const eventAt = parseDate(payload.timestamp);
@@ -1120,18 +1233,19 @@ async function reconcileFromStreamPay(ctx, payload, client, plans) {
1120
1233
  projected.activeSlotKey = desiredSlotKey;
1121
1234
  }
1122
1235
  }
1123
- const updated = await ctx.context.adapter.update({
1124
- model: SUBSCRIPTION_MODEL2,
1125
- update: projected,
1126
- where: [{ field: "id", value: existing.id }]
1127
- });
1236
+ const updated = await updateReconciledSubscription(
1237
+ ctx,
1238
+ existing,
1239
+ projected,
1240
+ streampaySubscriptionId
1241
+ );
1128
1242
  if (eventIsStale) {
1129
1243
  logger(ctx).info(
1130
1244
  `webhook ${payload.event_type}: ignored stale lifecycle callback for sub=${streampaySubscriptionId}.`
1131
1245
  );
1132
1246
  return { row: null, stream };
1133
1247
  }
1134
- return { row: updated ?? { ...existing, ...projected }, stream };
1248
+ return { row: updated, stream };
1135
1249
  }
1136
1250
  const planName = readMetadataString(payload.data, PLAN_NAME_METADATA_KEY) ?? inferPlanFromItems(stream, plans);
1137
1251
  const referenceId = readMetadataString(payload.data, REFERENCE_ID_METADATA_KEY);
@@ -1153,7 +1267,7 @@ async function reconcileFromStreamPay(ctx, payload, client, plans) {
1153
1267
  logger(ctx).warn(
1154
1268
  `webhook ${payload.event_type}: referenced subscription row=${localRowId} is missing; rebuilding from signed metadata.`
1155
1269
  );
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)) {
1270
+ } 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
1271
  const projectedWithSlot = {
1158
1272
  ...projected,
1159
1273
  billingStatus: metadataRow.billingStatus ?? "current",
@@ -1165,12 +1279,13 @@ async function reconcileFromStreamPay(ctx, payload, client, plans) {
1165
1279
  )
1166
1280
  }
1167
1281
  };
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 };
1282
+ const updated = await updateReconciledSubscription(
1283
+ ctx,
1284
+ metadataRow,
1285
+ projectedWithSlot,
1286
+ streampaySubscriptionId
1287
+ );
1288
+ return { row: updated, stream };
1174
1289
  }
1175
1290
  if (metadataRow) {
1176
1291
  logger(ctx).warn(
@@ -1186,7 +1301,8 @@ async function reconcileFromStreamPay(ctx, payload, client, plans) {
1186
1301
  referenceId,
1187
1302
  metadataReferenceType,
1188
1303
  planName,
1189
- paymentLinkId
1304
+ paymentLinkId,
1305
+ stream.organization_consumer_id ?? null
1190
1306
  );
1191
1307
  if (incomplete) {
1192
1308
  const projectedWithSlot = {
@@ -1200,13 +1316,14 @@ async function reconcileFromStreamPay(ctx, payload, client, plans) {
1200
1316
  )
1201
1317
  }
1202
1318
  };
1203
- const updated = await ctx.context.adapter.update({
1204
- model: SUBSCRIPTION_MODEL2,
1205
- update: projectedWithSlot,
1206
- where: [{ field: "id", value: incomplete.id }]
1207
- });
1319
+ const updated = await updateReconciledSubscription(
1320
+ ctx,
1321
+ incomplete,
1322
+ projectedWithSlot,
1323
+ streampaySubscriptionId
1324
+ );
1208
1325
  return {
1209
- row: updated ?? { ...incomplete, ...projectedWithSlot },
1326
+ row: updated,
1210
1327
  stream
1211
1328
  };
1212
1329
  }
@@ -1255,8 +1372,8 @@ async function syncWebhookPayload(ctx, payload, client, plans, callbacks, option
1255
1372
  const trackedRowId = claim.row?.id ?? null;
1256
1373
  const trackedLockId = claim.row?.lockedBy ?? void 0;
1257
1374
  try {
1258
- if (payload.event_type === "INVOICE_COMPLETED") {
1259
- await handleInvoiceCompleted(
1375
+ if (payload.event_type === "INVOICE_COMPLETED" || payload.event_type === "SUBSCRIPTION_CYCLE_RENEWED_SUCCESSFULLY") {
1376
+ await handleRenewalEvidence(
1260
1377
  ctx,
1261
1378
  payload,
1262
1379
  client,
@@ -1297,20 +1414,22 @@ async function syncWebhookPayload(ctx, payload, client, plans, callbacks, option
1297
1414
  throw err;
1298
1415
  }
1299
1416
  }
1300
- async function handleInvoiceCompleted(ctx, payload, client, plans, callbacks, retryOnCallbackError, retryingRenewalCallback) {
1417
+ async function handleRenewalEvidence(ctx, payload, client, plans, callbacks, retryOnCallbackError, retryingRenewalCallback) {
1301
1418
  const invoiceId = payload.data?.invoice?.id ?? payload.entity_id;
1302
1419
  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;
1420
+ let subscriptionId = payload.entity_type === "SUBSCRIPTION" ? payload.entity_id : null;
1421
+ if (!subscriptionId) {
1422
+ try {
1423
+ const invoice = await client.getInvoice(invoiceId);
1424
+ if (invoice && typeof invoice === "object" && "subscription_id" in invoice) {
1425
+ const subId = invoice.subscription_id;
1426
+ if (typeof subId === "string" && subId.length > 0) subscriptionId = subId;
1427
+ }
1428
+ } catch (err) {
1429
+ const msg = err instanceof Error ? err.message : String(err);
1430
+ logger(ctx).error(`${payload.event_type}: getInvoice(${invoiceId}) failed: ${msg}`);
1431
+ throw err;
1309
1432
  }
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
1433
  }
1315
1434
  if (!subscriptionId) return;
1316
1435
  let stream;
@@ -1318,7 +1437,7 @@ async function handleInvoiceCompleted(ctx, payload, client, plans, callbacks, re
1318
1437
  stream = await client.getSubscription(subscriptionId);
1319
1438
  } catch (err) {
1320
1439
  const msg = err instanceof Error ? err.message : String(err);
1321
- logger(ctx).error(`INVOICE_COMPLETED: getSubscription(${subscriptionId}) failed: ${msg}`);
1440
+ logger(ctx).error(`${payload.event_type}: getSubscription(${subscriptionId}) failed: ${msg}`);
1322
1441
  throw err;
1323
1442
  }
1324
1443
  const existing = await findSubscriptionByStreampayId(ctx, subscriptionId);
@@ -1328,7 +1447,7 @@ async function handleInvoiceCompleted(ctx, payload, client, plans, callbacks, re
1328
1447
  eventAt && existing.providerUpdatedAt instanceof Date && eventAt.getTime() < existing.providerUpdatedAt.getTime()
1329
1448
  );
1330
1449
  const projected = {
1331
- ...projectSubscriptionFields(stream),
1450
+ ...projectSubscriptionFields(stream, existing),
1332
1451
  ...projectPlanFields(stream, plans),
1333
1452
  ...eventIsStale ? existing.billingStatus === "past_due" && toLocalStatus(stream.status) === "active" ? { status: "past_due", billingStatus: "past_due" } : {} : { billingStatus: "current" }
1334
1453
  };
@@ -1336,14 +1455,45 @@ async function handleInvoiceCompleted(ctx, payload, client, plans, callbacks, re
1336
1455
  const projectedPeriodEnd = projected.periodEnd?.getTime() ?? null;
1337
1456
  const periodAdvanced = previousPeriodEnd !== null && projectedPeriodEnd !== null && projectedPeriodEnd > previousPeriodEnd;
1338
1457
  const cycleAdvanced = existing.currentCycleNumber !== null && existing.currentCycleNumber !== void 0 && projected.currentCycleNumber !== null && projected.currentCycleNumber !== void 0 && projected.currentCycleNumber > existing.currentCycleNumber;
1458
+ const eventId = extractEventId(payload);
1459
+ const pendingCallback = existing.renewalCallbackEventId ?? null;
1460
+ if (!pendingCallback && existing.providerUpdatedAt instanceof Date && projected.providerUpdatedAt instanceof Date && projected.providerUpdatedAt.getTime() < existing.providerUpdatedAt.getTime()) {
1461
+ throw new Error(
1462
+ `StreamPay returned stale subscription state for sub=${subscriptionId}; retry delivery.`
1463
+ );
1464
+ }
1465
+ if (pendingCallback && pendingCallback !== eventId) {
1466
+ throw new Error(`Subscription renewal callback ${pendingCallback} is pending; retry delivery.`);
1467
+ }
1468
+ const deliverCallback = pendingCallback === eventId && pendingCallback !== null || !eventIsStale && (periodAdvanced || cycleAdvanced || retryingRenewalCallback);
1469
+ const callbackOwner = deliverCallback && callbacks.onSubscriptionRenewed ? eventId : null;
1339
1470
  const updated = await ctx.context.adapter.update({
1340
1471
  model: SUBSCRIPTION_MODEL2,
1341
- update: projected,
1342
- where: [{ field: "id", value: existing.id }]
1472
+ // Recovery must retain the pending cycle, even if Stream has already advanced again.
1473
+ update: pendingCallback ? { renewalCallbackEventId: callbackOwner } : { ...projected, renewalCallbackEventId: callbackOwner },
1474
+ where: [
1475
+ { field: "id", value: existing.id },
1476
+ { field: "periodEnd", value: existing.periodEnd ?? null },
1477
+ { field: "currentCycleNumber", value: existing.currentCycleNumber ?? null },
1478
+ { field: "renewalCallbackEventId", value: pendingCallback },
1479
+ { field: "providerUpdatedAt", value: existing.providerUpdatedAt ?? null },
1480
+ { field: "status", value: existing.status },
1481
+ { field: "billingStatus", value: existing.billingStatus }
1482
+ ]
1343
1483
  });
1344
- const row = updated ?? { ...existing, ...projected };
1484
+ if (!updated) {
1485
+ if (pendingCallback && pendingCallback === eventId) {
1486
+ throw new Error(`Subscription cycle changed during callback recovery; retry delivery.`);
1487
+ }
1488
+ const latest = await findSubscriptionByStreampayId(ctx, subscriptionId);
1489
+ const anotherCallbackOwner = latest?.renewalCallbackEventId;
1490
+ const desiredCycleAdvanced = (periodAdvanced || cycleAdvanced) && (!periodAdvanced || (latest?.periodEnd?.getTime() ?? 0) >= (projectedPeriodEnd ?? 0)) && (!cycleAdvanced || (latest?.currentCycleNumber ?? 0) >= (projected.currentCycleNumber ?? 0));
1491
+ if (anotherCallbackOwner && anotherCallbackOwner !== eventId && desiredCycleAdvanced) return;
1492
+ throw new Error(`Subscription changed during renewal reconciliation; retry delivery.`);
1493
+ }
1494
+ const row = updated;
1345
1495
  const user = await resolveRowUser(ctx, row);
1346
- if (!eventIsStale && (periodAdvanced || cycleAdvanced || retryingRenewalCallback)) {
1496
+ if (deliverCallback) {
1347
1497
  await fireCallback(
1348
1498
  ctx,
1349
1499
  callbacks.onSubscriptionRenewed,
@@ -1351,6 +1501,16 @@ async function handleInvoiceCompleted(ctx, payload, client, plans, callbacks, re
1351
1501
  "onSubscriptionRenewed",
1352
1502
  retryOnCallbackError
1353
1503
  );
1504
+ if (callbackOwner) {
1505
+ await ctx.context.adapter.update({
1506
+ model: SUBSCRIPTION_MODEL2,
1507
+ update: { renewalCallbackEventId: null },
1508
+ where: [
1509
+ { field: "id", value: row.id },
1510
+ { field: "renewalCallbackEventId", value: callbackOwner }
1511
+ ]
1512
+ });
1513
+ }
1354
1514
  }
1355
1515
  }
1356
1516
  async function dispatchSubscriptionCallback(ctx, payload, data, callbacks, retryOnCallbackError) {
@@ -1547,16 +1707,16 @@ function forwardedBody() {
1547
1707
  );
1548
1708
  }
1549
1709
  var PaymentsListQuery = zod.z.object({
1550
- page: zod.z.coerce.number().int().positive().optional(),
1710
+ page: zod.z.coerce.number().int().positive().max(Number.MAX_SAFE_INTEGER).optional(),
1551
1711
  size: zod.z.coerce.number().int().positive().max(100).optional(),
1552
1712
  invoice_id: zod.z.string().uuid().optional()
1553
1713
  }).passthrough();
1554
1714
  var PaginationOnlyQuery = zod.z.object({
1555
- page: zod.z.coerce.number().int().positive().optional(),
1715
+ page: zod.z.coerce.number().int().positive().max(Number.MAX_SAFE_INTEGER).optional(),
1556
1716
  size: zod.z.coerce.number().int().positive().max(100).optional()
1557
1717
  }).passthrough();
1558
1718
  var ConsumersListQuery = zod.z.object({
1559
- page: zod.z.coerce.number().int().positive().optional(),
1719
+ page: zod.z.coerce.number().int().positive().max(Number.MAX_SAFE_INTEGER).optional(),
1560
1720
  size: zod.z.coerce.number().int().positive().max(100).optional(),
1561
1721
  search_term: zod.z.string().optional()
1562
1722
  }).passthrough();
@@ -1602,7 +1762,7 @@ function buildPaymentsEndpoints(client, adminOptions) {
1602
1762
  await requireAdmin(ctx, adminOptions);
1603
1763
  const params = {};
1604
1764
  if (ctx.query.page !== void 0) params.page = ctx.query.page;
1605
- if (ctx.query.size !== void 0) params.size = ctx.query.size;
1765
+ if (ctx.query.size !== void 0) params.limit = ctx.query.size;
1606
1766
  if (ctx.query.invoice_id !== void 0) params.invoice_id = ctx.query.invoice_id;
1607
1767
  try {
1608
1768
  const response = await client.listPayments(params);
@@ -1707,7 +1867,7 @@ function buildSubscriptionsEndpoints(client, adminOptions) {
1707
1867
  await requireAdmin(ctx, adminOptions);
1708
1868
  const params = {};
1709
1869
  if (ctx.query.page !== void 0) params.page = ctx.query.page;
1710
- if (ctx.query.size !== void 0) params.size = ctx.query.size;
1870
+ if (ctx.query.size !== void 0) params.limit = ctx.query.size;
1711
1871
  try {
1712
1872
  const response = await client.listSubscriptions(params);
1713
1873
  return ctx.json(response);
@@ -1901,7 +2061,7 @@ function buildConsumersEndpoints(client, adminOptions) {
1901
2061
  await requireAdmin(ctx, adminOptions);
1902
2062
  const params = {};
1903
2063
  if (ctx.query.page !== void 0) params.page = ctx.query.page;
1904
- if (ctx.query.size !== void 0) params.size = ctx.query.size;
2064
+ if (ctx.query.size !== void 0) params.limit = ctx.query.size;
1905
2065
  if (ctx.query.search_term !== void 0) params.search_term = ctx.query.search_term;
1906
2066
  try {
1907
2067
  const response = await client.listConsumers(params);
@@ -1964,19 +2124,6 @@ function buildConsumersEndpoints(client, adminOptions) {
1964
2124
  async (ctx) => {
1965
2125
  await requireAdmin(ctx, adminOptions);
1966
2126
  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
2127
  try {
1981
2128
  await client.deleteConsumer(consumerId);
1982
2129
  } catch (err) {
@@ -1988,16 +2135,26 @@ function buildConsumersEndpoints(client, adminOptions) {
1988
2135
  );
1989
2136
  }
1990
2137
  }
1991
- if (externalId) {
1992
- try {
1993
- await ctx.context.internalAdapter.updateUser(externalId, {
1994
- streampayConsumerId: null
2138
+ try {
2139
+ const adapter = getAdapter(ctx);
2140
+ const user = await adapter.findOne({
2141
+ model: "user",
2142
+ where: [{ field: "streampayConsumerId", value: consumerId }]
2143
+ });
2144
+ if (user) {
2145
+ await adapter.update({
2146
+ model: "user",
2147
+ update: { streampayConsumerId: null },
2148
+ where: [
2149
+ { field: "id", value: user.id },
2150
+ { field: "streampayConsumerId", value: consumerId }
2151
+ ]
1995
2152
  });
1996
- } catch (err) {
1997
- getLogger(ctx).error(
1998
- `StreamPay admin delete: link clear failed for user=${externalId} consumer=${consumerId}: ${formatStreamPayError(err)}`
1999
- );
2000
2153
  }
2154
+ } catch (err) {
2155
+ getLogger(ctx).error(
2156
+ `StreamPay admin delete: link clear failed for consumer=${consumerId}: ${formatStreamPayError(err)}`
2157
+ );
2001
2158
  }
2002
2159
  return ctx.json({ deleted: true });
2003
2160
  }
@@ -2017,7 +2174,7 @@ function buildInvoicesEndpoints(client, adminOptions) {
2017
2174
  await requireAdmin(ctx, adminOptions);
2018
2175
  const params = {};
2019
2176
  if (ctx.query.page !== void 0) params.page = ctx.query.page;
2020
- if (ctx.query.size !== void 0) params.size = ctx.query.size;
2177
+ if (ctx.query.size !== void 0) params.limit = ctx.query.size;
2021
2178
  try {
2022
2179
  const response = await client.listInvoices(params);
2023
2180
  return ctx.json(response);
@@ -2079,7 +2236,7 @@ function buildProductsEndpoints(client, adminOptions) {
2079
2236
  await requireAdmin(ctx, adminOptions);
2080
2237
  const params = {};
2081
2238
  if (ctx.query.page !== void 0) params.page = ctx.query.page;
2082
- if (ctx.query.size !== void 0) params.size = ctx.query.size;
2239
+ if (ctx.query.size !== void 0) params.limit = ctx.query.size;
2083
2240
  try {
2084
2241
  const response = await client.listProducts(params);
2085
2242
  return ctx.json(response);
@@ -2185,7 +2342,7 @@ function buildCouponsEndpoints(client, adminOptions) {
2185
2342
  await requireAdmin(ctx, adminOptions);
2186
2343
  const params = {};
2187
2344
  if (ctx.query.page !== void 0) params.page = ctx.query.page;
2188
- if (ctx.query.size !== void 0) params.size = ctx.query.size;
2345
+ if (ctx.query.size !== void 0) params.limit = ctx.query.size;
2189
2346
  try {
2190
2347
  const response = await client.listCoupons(params);
2191
2348
  return ctx.json(response);
@@ -2269,7 +2426,7 @@ function buildPaymentLinksEndpoints(client, adminOptions) {
2269
2426
  await requireAdmin(ctx, adminOptions);
2270
2427
  const params = {};
2271
2428
  if (ctx.query.page !== void 0) params.page = ctx.query.page;
2272
- if (ctx.query.size !== void 0) params.size = ctx.query.size;
2429
+ if (ctx.query.size !== void 0) params.limit = ctx.query.size;
2273
2430
  try {
2274
2431
  const response = await client.listPaymentLinks(params);
2275
2432
  return ctx.json(response);
@@ -2303,9 +2460,16 @@ function buildPaymentLinksEndpoints(client, adminOptions) {
2303
2460
  var WebhookEventsListQuery = zod.z.object({
2304
2461
  status: zod.z.enum(["pending", "completed", "dead_letter"]).optional(),
2305
2462
  eventType: zod.z.string().optional(),
2306
- page: zod.z.coerce.number().int().positive().optional(),
2463
+ page: zod.z.coerce.number().int().positive().max(Number.MAX_SAFE_INTEGER).optional(),
2307
2464
  size: zod.z.coerce.number().int().positive().max(100).optional()
2308
2465
  }).passthrough();
2466
+ function decodeWebhookEventId(value) {
2467
+ try {
2468
+ return decodeURIComponent(value);
2469
+ } catch {
2470
+ throw new api.APIError("BAD_REQUEST", { message: "Invalid webhook event identifier." });
2471
+ }
2472
+ }
2309
2473
  function buildWebhookEventsEndpoints(adminOptions, registry) {
2310
2474
  return {
2311
2475
  adminListWebhookEvents: api.createAuthEndpoint(
@@ -2350,7 +2514,7 @@ function buildWebhookEventsEndpoints(adminOptions, registry) {
2350
2514
  const adapter = getAdapter(ctx);
2351
2515
  const row = await adapter.findOne({
2352
2516
  model: WEBHOOK_EVENT_MODEL,
2353
- where: [{ field: "eventId", value: ctx.params.eventId }]
2517
+ where: [{ field: "eventId", value: decodeWebhookEventId(ctx.params.eventId) }]
2354
2518
  });
2355
2519
  if (!row) {
2356
2520
  throw new api.APIError("NOT_FOUND", {
@@ -2372,11 +2536,14 @@ function buildWebhookEventsEndpoints(adminOptions, registry) {
2372
2536
  await requireAdmin(ctx, adminOptions);
2373
2537
  if (!registry?.replayWebhookEvent) {
2374
2538
  throw new api.APIError("BAD_REQUEST", {
2375
- message: "Replay unavailable \u2014 `subscriptions()` plugin must be in `use` and `enableWebhookEventTable` left enabled."
2539
+ message: "Replay unavailable \u2014 enable the subscriptions webhook inbox or webhooks({ deduplicate: true })."
2376
2540
  });
2377
2541
  }
2378
2542
  try {
2379
- const result = await registry.replayWebhookEvent(ctx, ctx.params.eventId);
2543
+ const result = await registry.replayWebhookEvent(
2544
+ ctx,
2545
+ decodeWebhookEventId(ctx.params.eventId)
2546
+ );
2380
2547
  return ctx.json(result);
2381
2548
  } catch (err) {
2382
2549
  if (err instanceof api.APIError) throw err;
@@ -2398,9 +2565,10 @@ function buildWebhookEventsEndpoints(adminOptions, registry) {
2398
2565
  async (ctx) => {
2399
2566
  await requireAdmin(ctx, adminOptions);
2400
2567
  const adapter = getAdapter(ctx);
2568
+ const eventId = decodeWebhookEventId(ctx.params.eventId);
2401
2569
  const row = await adapter.findOne({
2402
2570
  model: WEBHOOK_EVENT_MODEL,
2403
- where: [{ field: "eventId", value: ctx.params.eventId }]
2571
+ where: [{ field: "eventId", value: eventId }]
2404
2572
  });
2405
2573
  if (!row) {
2406
2574
  throw new api.APIError("NOT_FOUND", {
@@ -2408,8 +2576,24 @@ function buildWebhookEventsEndpoints(adminOptions, registry) {
2408
2576
  message: `Webhook event ${ctx.params.eventId} not found.`
2409
2577
  });
2410
2578
  }
2579
+ if (registry?.subscriptionWebhookSync && !eventId.startsWith("handlers:") && (row.eventType === "INVOICE_COMPLETED" || row.eventType === "SUBSCRIPTION_CYCLE_RENEWED_SUCCESSFULLY")) {
2580
+ const subscription = await adapter.findOne({
2581
+ model: "subscription",
2582
+ where: [{ field: "renewalCallbackEventId", value: eventId }]
2583
+ });
2584
+ if (subscription) {
2585
+ await adapter.update({
2586
+ model: "subscription",
2587
+ update: { renewalCallbackEventId: null },
2588
+ where: [
2589
+ { field: "id", value: subscription.id },
2590
+ { field: "renewalCallbackEventId", value: eventId }
2591
+ ]
2592
+ });
2593
+ }
2594
+ }
2411
2595
  await markWebhookEventCompleted({ context: { adapter } }, row.id);
2412
- return ctx.json({ discarded: true, eventId: ctx.params.eventId });
2596
+ return ctx.json({ discarded: true, eventId });
2413
2597
  }
2414
2598
  )
2415
2599
  };
@@ -2437,21 +2621,21 @@ var CheckoutRequestBody = zod.z.object({
2437
2621
  zod.z.array(
2438
2622
  zod.z.object({
2439
2623
  productId: zod.z.string().uuid(),
2440
- quantity: zod.z.number().int().positive().optional()
2624
+ quantity: zod.z.number().int().positive().safe().optional()
2441
2625
  })
2442
2626
  ).min(1, "`products` must contain at least one item."),
2443
2627
  zod.z.array(zod.z.string().uuid()).min(1, "`products` must contain at least one item."),
2444
2628
  zod.z.string().uuid()
2445
2629
  ]).optional(),
2446
- slug: zod.z.string().optional(),
2630
+ slug: zod.z.string().min(1).optional(),
2447
2631
  referenceId: zod.z.string().optional(),
2448
2632
  name: zod.z.string().min(1).optional(),
2449
2633
  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(),
2634
+ metadata: zod.z.record(zod.z.string(), zod.z.union([zod.z.string(), zod.z.number().finite(), zod.z.boolean()])).optional(),
2451
2635
  successUrl: RelativeOrAbsoluteUrl.optional(),
2452
2636
  failureUrl: RelativeOrAbsoluteUrl.optional(),
2453
- maxNumberOfPayments: zod.z.number().int().positive().optional(),
2454
- validUntil: zod.z.string().datetime().optional(),
2637
+ maxNumberOfPayments: zod.z.number().int().positive().safe().optional(),
2638
+ validUntil: zod.z.string().datetime({ offset: true }).optional(),
2455
2639
  couponIds: zod.z.array(zod.z.string().uuid()).optional(),
2456
2640
  redirect: zod.z.coerce.boolean().optional()
2457
2641
  });
@@ -2724,24 +2908,58 @@ var checkout = (checkoutOptions = {}) => {
2724
2908
  };
2725
2909
  };
2726
2910
  var DEFAULT_PAGE_SIZE = 100;
2727
- async function getConsumerIdOrNull(client, user) {
2911
+ var paginationQuery = zod.z.object({
2912
+ page: zod.z.coerce.number().int().min(1).max(Number.MAX_SAFE_INTEGER).optional(),
2913
+ size: zod.z.coerce.number().int().min(1).max(100).optional()
2914
+ });
2915
+ async function getConsumerIdOrNull(ctx, client, user) {
2728
2916
  rejectUnauthorized(user, "Anonymous users cannot access the billing portal.");
2729
- if (user.streampayConsumerId) return user.streampayConsumerId;
2917
+ const current = await getCurrentConsumerUser(ctx, user);
2918
+ if (current.streampayConsumerId) return current.streampayConsumerId;
2730
2919
  return findConsumerByExternalId(client, { externalId: user.id });
2731
2920
  }
2732
- var portal = ({ pageSize } = {}) => (options) => {
2921
+ var portal = ({ pageSize, createSession } = {}) => (options) => {
2733
2922
  const client = options.client;
2734
2923
  const size = clampPageSize(pageSize);
2735
2924
  return {
2736
2925
  endpoints: {
2926
+ portalSession: api.createAuthEndpoint(
2927
+ "/consumer/portal/session",
2928
+ { method: "POST", use: [api.sessionMiddleware] },
2929
+ async (ctx) => {
2930
+ ctx.setHeader("cache-control", "no-store");
2931
+ try {
2932
+ const consumerId = await getConsumerIdOrNull(
2933
+ ctx,
2934
+ client,
2935
+ asSessionUser(ctx.context.session?.user)
2936
+ );
2937
+ if (!consumerId)
2938
+ throw new api.APIError("NOT_FOUND", {
2939
+ message: "No StreamPay consumer is linked to this account."
2940
+ });
2941
+ if (!createSession)
2942
+ throw new api.APIError("NOT_FOUND", {
2943
+ message: "Hosted customer portal is not configured."
2944
+ });
2945
+ const session = await createSession({ organization_consumer_id: consumerId });
2946
+ const url = new URL(session.url);
2947
+ if (url.protocol !== "https:" || url.username || url.password)
2948
+ throw new Error("Invalid hosted portal URL.");
2949
+ return ctx.json({ url: url.href });
2950
+ } catch (err) {
2951
+ toAPIError("StreamPay createPortalSession failed.", err, getLogger(ctx));
2952
+ }
2953
+ }
2954
+ ),
2737
2955
  state: api.createAuthEndpoint(
2738
2956
  "/consumer/state",
2739
2957
  { method: "GET", use: [api.sessionMiddleware] },
2740
2958
  async (ctx) => {
2741
2959
  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
2960
  try {
2961
+ const consumerId = await getConsumerIdOrNull(ctx, client, user);
2962
+ if (!consumerId) return ctx.json({ hasConsumer: false, consumer: null });
2745
2963
  const consumer = await client.getConsumer(consumerId);
2746
2964
  return ctx.json({ hasConsumer: true, consumer });
2747
2965
  } catch (err) {
@@ -2751,18 +2969,22 @@ var portal = ({ pageSize } = {}) => (options) => {
2751
2969
  ),
2752
2970
  subscriptions: api.createAuthEndpoint(
2753
2971
  "/consumer/subscriptions/list",
2754
- { method: "GET", use: [api.sessionMiddleware] },
2972
+ { method: "GET", use: [api.sessionMiddleware], query: paginationQuery },
2755
2973
  async (ctx) => {
2756
2974
  const user = asSessionUser(ctx.context.session?.user);
2757
- const consumerId = await getConsumerIdOrNull(client, user);
2758
- if (!consumerId) return ctx.json({ hasConsumer: false, data: [] });
2759
2975
  try {
2976
+ const consumerId = await getConsumerIdOrNull(ctx, client, user);
2977
+ if (!consumerId) return ctx.json({ hasConsumer: false, data: [] });
2760
2978
  const response = await client.listSubscriptions({
2761
2979
  organization_consumer_id: consumerId,
2762
- page: 1,
2763
- size
2980
+ page: ctx.query?.page ?? 1,
2981
+ limit: ctx.query?.size ?? size
2982
+ });
2983
+ return ctx.json({
2984
+ hasConsumer: true,
2985
+ data: response.data ?? [],
2986
+ pagination: response.pagination
2764
2987
  });
2765
- return ctx.json({ hasConsumer: true, data: response.data ?? [] });
2766
2988
  } catch (err) {
2767
2989
  toAPIError("StreamPay listSubscriptions failed.", err, getLogger(ctx));
2768
2990
  }
@@ -2770,18 +2992,22 @@ var portal = ({ pageSize } = {}) => (options) => {
2770
2992
  ),
2771
2993
  invoices: api.createAuthEndpoint(
2772
2994
  "/consumer/invoices/list",
2773
- { method: "GET", use: [api.sessionMiddleware] },
2995
+ { method: "GET", use: [api.sessionMiddleware], query: paginationQuery },
2774
2996
  async (ctx) => {
2775
2997
  const user = asSessionUser(ctx.context.session?.user);
2776
- const consumerId = await getConsumerIdOrNull(client, user);
2777
- if (!consumerId) return ctx.json({ hasConsumer: false, data: [] });
2778
2998
  try {
2999
+ const consumerId = await getConsumerIdOrNull(ctx, client, user);
3000
+ if (!consumerId) return ctx.json({ hasConsumer: false, data: [] });
2779
3001
  const response = await client.listInvoices({
2780
3002
  organization_consumer_id: consumerId,
2781
- page: 1,
2782
- size
3003
+ page: ctx.query?.page ?? 1,
3004
+ limit: ctx.query?.size ?? size
3005
+ });
3006
+ return ctx.json({
3007
+ hasConsumer: true,
3008
+ data: response.data ?? [],
3009
+ pagination: response.pagination
2783
3010
  });
2784
- return ctx.json({ hasConsumer: true, data: response.data ?? [] });
2785
3011
  } catch (err) {
2786
3012
  toAPIError("StreamPay listInvoices failed.", err, getLogger(ctx));
2787
3013
  }
@@ -2799,6 +3025,7 @@ var STREAMPAY_EVENT_ENTITY_TYPES = {
2799
3025
  PAYMENT_FAILED: "PAYMENT",
2800
3026
  PAYMENT_CANCELED: "PAYMENT",
2801
3027
  PAYMENT_REFUNDED: "PAYMENT",
3028
+ PAYMENT_PARTIALLY_REFUNDED: "PAYMENT",
2802
3029
  PAYMENT_MARKED_AS_PAID: "PAYMENT",
2803
3030
  INVOICE_CREATED: "INVOICE",
2804
3031
  INVOICE_SENT: "INVOICE",
@@ -2813,6 +3040,7 @@ var STREAMPAY_EVENT_ENTITY_TYPES = {
2813
3040
  SUBSCRIPTION_CANCELED: "SUBSCRIPTION",
2814
3041
  SUBSCRIPTION_FROZEN: "SUBSCRIPTION",
2815
3042
  SUBSCRIPTION_CYCLE_RENEWAL_FAILED: "SUBSCRIPTION",
3043
+ SUBSCRIPTION_CYCLE_RENEWED_SUCCESSFULLY: "SUBSCRIPTION",
2816
3044
  SUBSCRIPTION_CANCEL_AT_PERIOD_END: "SUBSCRIPTION",
2817
3045
  SUBSCRIPTION_FREEZE_NOW: "SUBSCRIPTION",
2818
3046
  SUBSCRIPTION_UNFREEZE_NOW: "SUBSCRIPTION",
@@ -2960,7 +3188,10 @@ async function deleteReservedSubscription(adapter, rowId, log, reason) {
2960
3188
  try {
2961
3189
  await adapter.delete({
2962
3190
  model: SUBSCRIPTION_MODEL4,
2963
- where: [{ field: "id", value: rowId }]
3191
+ where: [
3192
+ { field: "id", value: rowId },
3193
+ { field: "status", value: "incomplete" }
3194
+ ]
2964
3195
  });
2965
3196
  } catch (err) {
2966
3197
  const message = err instanceof Error ? err.message : String(err);
@@ -2996,11 +3227,15 @@ async function resumeOrReserveCheckoutSlot(args) {
2996
3227
  if (recovery.kind === "recovered") {
2997
3228
  return { kind: "recovered", row: reuseCandidate, url: recovery.url };
2998
3229
  }
2999
- await adapter.update({
3230
+ const released = await adapter.update({
3000
3231
  model: SUBSCRIPTION_MODEL4,
3001
3232
  update: { status: "incomplete_expired", activeSlotKey: null, updatedAt: /* @__PURE__ */ new Date() },
3002
- where: [{ field: "id", value: reuseCandidate.id }]
3233
+ where: [
3234
+ { field: "id", value: reuseCandidate.id },
3235
+ { field: "status", value: "incomplete" }
3236
+ ]
3003
3237
  });
3238
+ if (!released) throw checkoutInProgressError();
3004
3239
  }
3005
3240
  const { data: reservationData, consumerId } = await args.createReservation();
3006
3241
  let row;
@@ -3041,6 +3276,7 @@ async function resumeOrReserveCheckoutSlot(args) {
3041
3276
  update: { status: "incomplete_expired", activeSlotKey: null, updatedAt: /* @__PURE__ */ new Date() },
3042
3277
  where: [
3043
3278
  { field: "id", value: reserved.id },
3279
+ { field: "status", value: "incomplete" },
3044
3280
  { field: "activeSlotKey", value: activeSlotKey }
3045
3281
  ]
3046
3282
  });
@@ -3120,6 +3356,43 @@ function configuredPlanForSubscription(subscription, plans) {
3120
3356
  }
3121
3357
  return matches[0];
3122
3358
  }
3359
+ async function findSubscriptionFreeze(client, options, subscriptionId, matches) {
3360
+ const listPage = options.listSubscriptionFreezes;
3361
+ if (!listPage) {
3362
+ const response = await client.listSubscriptionFreezes(subscriptionId);
3363
+ return {
3364
+ freeze: response.data?.find(matches),
3365
+ hasMore: response.pagination?.has_next_page ?? false
3366
+ };
3367
+ }
3368
+ const seenIds = /* @__PURE__ */ new Set();
3369
+ for (let page = 1; page <= 100; page++) {
3370
+ const response = await listPage(subscriptionId, { page, limit: 100 });
3371
+ const pagination = response.pagination;
3372
+ if (!Array.isArray(response.data) || !pagination || pagination.current_page !== page || typeof pagination.has_next_page !== "boolean") {
3373
+ throw freezePaginationConflict("StreamPay returned invalid freeze pagination.");
3374
+ }
3375
+ let advanced = false;
3376
+ for (const freeze2 of response.data) {
3377
+ if (freeze2.id && !seenIds.has(freeze2.id)) {
3378
+ seenIds.add(freeze2.id);
3379
+ advanced = true;
3380
+ }
3381
+ }
3382
+ if (!advanced && (pagination.has_next_page || response.data.length > 0)) {
3383
+ throw freezePaginationConflict("StreamPay freeze pagination returned no new entries.");
3384
+ }
3385
+ const freeze = response.data.find(matches);
3386
+ if (freeze || !pagination.has_next_page) return { freeze, hasMore: false };
3387
+ }
3388
+ throw freezePaginationConflict("StreamPay freeze pagination exceeded 100 pages.");
3389
+ }
3390
+ function freezePaginationConflict(message) {
3391
+ return new api.APIError("CONFLICT", {
3392
+ code: $ERROR_CODES.SUBSCRIPTION_INVALID_STATE.code,
3393
+ message
3394
+ });
3395
+ }
3123
3396
  var SUBSCRIPTION_INTERVALS = ["WEEK", "MONTH", "QUARTER", "YEAR"];
3124
3397
  var PlanSchema = zod.z.object({
3125
3398
  name: zod.z.string().min(1, "every plan must have a non-empty `name`."),
@@ -3224,7 +3497,7 @@ async function resolvePlans(plans) {
3224
3497
  return buildIndex(list);
3225
3498
  }
3226
3499
  function hasSubscriptionAccess(subscription, accessStatuses = DEFAULT_ACCESS_STATUSES) {
3227
- return accessStatuses.includes(subscription.status);
3500
+ return subscription.catalogMapped !== false && accessStatuses.includes(subscription.status);
3228
3501
  }
3229
3502
  function hasFeature(subscription, plan, feature, accessStatuses = DEFAULT_ACCESS_STATUSES) {
3230
3503
  if (!plan?.limits) return false;
@@ -3240,9 +3513,11 @@ function checkLimit(subscription, plan, feature, requested, accessStatuses = DEF
3240
3513
  }
3241
3514
  const raw = plan.limits[feature];
3242
3515
  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);
3516
+ if (!Number.isSafeInteger(requested) || requested < 0) {
3517
+ return { allowed: false, limit, remaining: 0 };
3518
+ }
3519
+ const allowed = requested <= limit;
3520
+ const remaining = Math.max(0, limit - requested);
3246
3521
  return { allowed, limit, remaining };
3247
3522
  }
3248
3523
 
@@ -3265,7 +3540,7 @@ var HasFeatureQuery = zod.z.object({
3265
3540
  var CheckLimitQuery = zod.z.object({
3266
3541
  ...ReferenceQueryFields,
3267
3542
  feature: zod.z.string().min(1),
3268
- count: zod.z.coerce.number().int().min(0),
3543
+ count: zod.z.coerce.number().int().min(0).max(Number.MAX_SAFE_INTEGER),
3269
3544
  group: zod.z.string().min(1).optional()
3270
3545
  });
3271
3546
  function presentSubscription(row, plans) {
@@ -3274,7 +3549,7 @@ function presentSubscription(row, plans) {
3274
3549
  // The column is nullable during safe rolling migrations. Keep the public
3275
3550
  // contract stable while applications backfill legacy rows to one seat.
3276
3551
  seats: row.seats ?? 1,
3277
- plan: plans.byName.get(row.plan) ?? null
3552
+ plan: row.catalogMapped === false ? null : plans.byName.get(row.plan) ?? null
3278
3553
  };
3279
3554
  }
3280
3555
  async function resolveLiveSubscription(ctx, query, subsOptions, accessStatuses) {
@@ -3457,8 +3732,8 @@ var UpdateSeatsBody = zod.z.object({
3457
3732
  }).strict();
3458
3733
  var FreezeBody = zod.z.object({
3459
3734
  subscriptionId: zod.z.string().min(1),
3460
- freezeStartDatetime: zod.z.string().datetime(),
3461
- freezeEndDatetime: zod.z.string().datetime().nullable().optional(),
3735
+ freezeStartDatetime: zod.z.string().datetime({ offset: true }),
3736
+ freezeEndDatetime: zod.z.string().datetime({ offset: true }).nullable().optional(),
3462
3737
  notes: zod.z.string().optional()
3463
3738
  });
3464
3739
  var UnfreezeBody = zod.z.object({
@@ -3506,9 +3781,10 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
3506
3781
  const plans = await plansRef();
3507
3782
  const current = await client.getSubscription(row.streampaySubscriptionId);
3508
3783
  if (!current.pending_change) {
3509
- await adapter.update({
3510
- model: SUBSCRIPTION_MODEL6,
3511
- update: {
3784
+ await persistSubscriptionProjection(
3785
+ adapter,
3786
+ row,
3787
+ {
3512
3788
  ...projectSubscriptionAgainstExisting(row, current),
3513
3789
  ...projectPlanFields(current, plans),
3514
3790
  pendingPlan: null,
@@ -3517,15 +3793,17 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
3517
3793
  pendingSeats: null,
3518
3794
  pendingSeatsEffectiveAt: null
3519
3795
  },
3520
- where: [{ field: "id", value: row.id }]
3521
- });
3796
+ getLogger(ctx),
3797
+ "subscription endpoint"
3798
+ );
3522
3799
  return ctx.json({ canceled: true, reused: true, subscription: current });
3523
3800
  }
3524
3801
  await client.deletePendingSubscriptionChange(row.streampaySubscriptionId);
3525
3802
  const stream = await client.getSubscription(row.streampaySubscriptionId);
3526
- await adapter.update({
3527
- model: SUBSCRIPTION_MODEL6,
3528
- update: {
3803
+ await persistSubscriptionProjection(
3804
+ adapter,
3805
+ row,
3806
+ {
3529
3807
  ...projectSubscriptionAgainstExisting(row, stream),
3530
3808
  ...projectPlanFields(stream, plans),
3531
3809
  pendingPlan: null,
@@ -3534,8 +3812,9 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
3534
3812
  pendingSeats: null,
3535
3813
  pendingSeatsEffectiveAt: null
3536
3814
  },
3537
- where: [{ field: "id", value: row.id }]
3538
- });
3815
+ getLogger(ctx),
3816
+ "subscription endpoint"
3817
+ );
3539
3818
  return ctx.json({ canceled: true, reused: false, subscription: stream });
3540
3819
  } catch (err) {
3541
3820
  toAPIError(
@@ -3734,7 +4013,11 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
3734
4013
  activeSlotKey: null,
3735
4014
  updatedAt: /* @__PURE__ */ new Date()
3736
4015
  },
3737
- where: [{ field: "id", value: row.id }]
4016
+ where: [
4017
+ { field: "id", value: row.id },
4018
+ { field: "status", value: "incomplete" },
4019
+ { field: "streampayConsumerId", value: consumerId }
4020
+ ]
3738
4021
  });
3739
4022
  } catch (persistenceError) {
3740
4023
  const message = persistenceError instanceof Error ? persistenceError.message : String(persistenceError);
@@ -3760,7 +4043,13 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
3760
4043
  streampayPaymentLinkId: paymentLinkId,
3761
4044
  updatedAt: /* @__PURE__ */ new Date()
3762
4045
  },
3763
- where: [{ field: "id", value: row.id }]
4046
+ where: [
4047
+ { field: "id", value: row.id },
4048
+ { field: "referenceId", value: referenceId },
4049
+ { field: "referenceType", value: referenceType },
4050
+ { field: "streampayConsumerId", value: consumerId },
4051
+ { field: "streampayPaymentLinkId", value: null }
4052
+ ]
3764
4053
  });
3765
4054
  } catch (persistenceError) {
3766
4055
  const message = persistenceError instanceof Error ? persistenceError.message : String(persistenceError);
@@ -3842,10 +4131,11 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
3842
4131
  if (!match?.id) {
3843
4132
  return ctx.json({ subscription: row, synced: false });
3844
4133
  }
3845
- const updated = await adapter.update({
3846
- model: SUBSCRIPTION_MODEL6,
3847
- update: {
3848
- ...projectSubscriptionFields(match),
4134
+ const updated = await persistSubscriptionProjection(
4135
+ adapter,
4136
+ row,
4137
+ {
4138
+ ...projectSubscriptionFields(match, row),
3849
4139
  ...projectPlanFields(match, plans),
3850
4140
  planVersion: plan.version ?? null,
3851
4141
  productId: plan.productId,
@@ -3853,9 +4143,10 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
3853
4143
  activeSlotKey: row.activeSlotKey ?? subscriptionSlotKey(row.referenceType ?? "user", row.referenceId, row.group),
3854
4144
  updatedAt: /* @__PURE__ */ new Date()
3855
4145
  },
3856
- where: [{ field: "id", value: row.id }]
3857
- });
3858
- return ctx.json({ subscription: updated ?? row, synced: true });
4146
+ getLogger(ctx),
4147
+ "subscription endpoint"
4148
+ );
4149
+ return ctx.json({ subscription: updated, synced: updated !== null });
3859
4150
  } catch (err) {
3860
4151
  toAPIError(
3861
4152
  `subscriptionSuccess fallback sync failed for row=${row.id}:`,
@@ -3885,11 +4176,13 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
3885
4176
  try {
3886
4177
  const stream = await client.getSubscription(row.streampaySubscriptionId);
3887
4178
  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
- });
4179
+ await persistSubscriptionProjection(
4180
+ adapter,
4181
+ row,
4182
+ projectSubscriptionAgainstExisting(row, stream),
4183
+ getLogger(ctx),
4184
+ "subscription endpoint"
4185
+ );
3893
4186
  return ctx.json(stream);
3894
4187
  }
3895
4188
  if (ctx.body.cancelAtPeriodEnd === false && stream.status === "ACTIVE") {
@@ -3899,11 +4192,13 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
3899
4192
  });
3900
4193
  }
3901
4194
  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
- });
4195
+ await persistSubscriptionProjection(
4196
+ adapter,
4197
+ row,
4198
+ projectSubscriptionAgainstExisting(row, stream),
4199
+ getLogger(ctx),
4200
+ "subscription endpoint"
4201
+ );
3907
4202
  return ctx.json(stream);
3908
4203
  }
3909
4204
  if (ctx.body.cancelAtPeriodEnd === true && stream.status !== "ACTIVE") {
@@ -3997,9 +4292,10 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
3997
4292
  const pendingTargetMatches = Boolean(pendingTarget) && (subscriptionItemQuantity(pendingTarget) ?? 1) === nextSeats;
3998
4293
  if (pendingTargetMatches) {
3999
4294
  const effectiveAt2 = stream.pending_change?.effective_at ?? null;
4000
- await adapter.update({
4001
- model: SUBSCRIPTION_MODEL6,
4002
- update: {
4295
+ await persistSubscriptionProjection(
4296
+ adapter,
4297
+ row,
4298
+ {
4003
4299
  ...projectSubscriptionAgainstExisting(row, stream),
4004
4300
  ...projectPlanFields(stream, plans),
4005
4301
  pendingPlan: currentPlan.productId === nextPlan.productId ? null : nextPlan.name,
@@ -4008,8 +4304,9 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
4008
4304
  pendingSeats: nextSeats,
4009
4305
  pendingSeatsEffectiveAt: parseDate(effectiveAt2)
4010
4306
  },
4011
- where: [{ field: "id", value: row.id }]
4012
- });
4307
+ getLogger(ctx),
4308
+ "subscription endpoint"
4309
+ );
4013
4310
  return ctx.json({
4014
4311
  mode: "at_period_end",
4015
4312
  subscriptionId: row.id,
@@ -4041,15 +4338,17 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
4041
4338
  const pending = Boolean(result.pending_change);
4042
4339
  const effectiveAt = result.pending_change?.effective_at ?? null;
4043
4340
  const planProjection = projectPlanFields(result, plans);
4044
- await adapter.update({
4045
- model: SUBSCRIPTION_MODEL6,
4046
- update: {
4341
+ await persistSubscriptionProjection(
4342
+ adapter,
4343
+ row,
4344
+ {
4047
4345
  ...projectSubscriptionAgainstExisting(row, result),
4048
4346
  ...planProjection,
4049
4347
  updatedAt: /* @__PURE__ */ new Date()
4050
4348
  },
4051
- where: [{ field: "id", value: row.id }]
4052
- });
4349
+ getLogger(ctx),
4350
+ "subscription endpoint"
4351
+ );
4053
4352
  const providerPlan = pending ? planProjection.pendingPlan ?? planProjection.plan ?? row.plan : planProjection.plan ?? row.plan;
4054
4353
  const providerSeats = pending ? planProjection.pendingSeats ?? nextSeats : planProjection.seats ?? row.seats ?? nextSeats;
4055
4354
  return ctx.json({
@@ -4115,14 +4414,16 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
4115
4414
  if (stream.pending_change) {
4116
4415
  if (pendingTarget && (subscriptionItemQuantity(pendingTarget) ?? 1) === seats) {
4117
4416
  const effectiveAt2 = stream.pending_change.effective_at ?? null;
4118
- await adapter.update({
4119
- model: SUBSCRIPTION_MODEL6,
4120
- update: {
4417
+ await persistSubscriptionProjection(
4418
+ adapter,
4419
+ row,
4420
+ {
4121
4421
  ...projectSubscriptionAgainstExisting(row, stream),
4122
4422
  ...projectPlanFields(stream, plans)
4123
4423
  },
4124
- where: [{ field: "id", value: row.id }]
4125
- });
4424
+ getLogger(ctx),
4425
+ "subscription endpoint"
4426
+ );
4126
4427
  return ctx.json({
4127
4428
  mode: "at_period_end",
4128
4429
  subscriptionId: row.id,
@@ -4138,14 +4439,16 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
4138
4439
  });
4139
4440
  }
4140
4441
  if (currentSeats === seats) {
4141
- await adapter.update({
4142
- model: SUBSCRIPTION_MODEL6,
4143
- update: {
4442
+ await persistSubscriptionProjection(
4443
+ adapter,
4444
+ row,
4445
+ {
4144
4446
  ...projectSubscriptionAgainstExisting(row, stream),
4145
4447
  ...projectPlanFields(stream, plans)
4146
4448
  },
4147
- where: [{ field: "id", value: row.id }]
4148
- });
4449
+ getLogger(ctx),
4450
+ "subscription endpoint"
4451
+ );
4149
4452
  return ctx.json({
4150
4453
  mode: "current",
4151
4454
  subscriptionId: row.id,
@@ -4163,15 +4466,17 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
4163
4466
  const pending = Boolean(result.pending_change);
4164
4467
  const effectiveAt = result.pending_change?.effective_at ?? null;
4165
4468
  const planProjection = projectPlanFields(result, plans);
4166
- await adapter.update({
4167
- model: SUBSCRIPTION_MODEL6,
4168
- update: {
4469
+ await persistSubscriptionProjection(
4470
+ adapter,
4471
+ row,
4472
+ {
4169
4473
  ...projectSubscriptionAgainstExisting(row, result),
4170
4474
  ...planProjection,
4171
4475
  updatedAt: /* @__PURE__ */ new Date()
4172
4476
  },
4173
- where: [{ field: "id", value: row.id }]
4174
- });
4477
+ getLogger(ctx),
4478
+ "subscription endpoint"
4479
+ );
4175
4480
  const providerSeats = pending ? planProjection.pendingSeats ?? seats : planProjection.seats ?? row.seats ?? seats;
4176
4481
  return ctx.json({
4177
4482
  mode: pending ? "at_period_end" : "immediate",
@@ -4215,11 +4520,13 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
4215
4520
  try {
4216
4521
  await client.uncancelSubscription(row.streampaySubscriptionId);
4217
4522
  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
- });
4523
+ await persistSubscriptionProjection(
4524
+ adapter,
4525
+ row,
4526
+ projectSubscriptionAgainstExisting(row, stream),
4527
+ getLogger(ctx),
4528
+ "subscription endpoint"
4529
+ );
4223
4530
  return ctx.json({ uncanceled: true, subscription: stream });
4224
4531
  } catch (err) {
4225
4532
  toAPIError(
@@ -4294,13 +4601,30 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
4294
4601
  );
4295
4602
  const nowMs = Date.now();
4296
4603
  try {
4297
- const freezes = await client.listSubscriptionFreezes(row.streampaySubscriptionId);
4298
- const active = freezes.data?.find((freeze) => {
4604
+ const isActiveFreeze = (freeze) => {
4299
4605
  if (!freeze.id || !freeze.freeze_start_datetime) return false;
4300
4606
  const start = parseDate(freeze.freeze_start_datetime)?.getTime();
4301
4607
  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
- });
4608
+ return start !== void 0 && end !== void 0 && start <= nowMs && nowMs < end;
4609
+ };
4610
+ const result = await findSubscriptionFreeze(
4611
+ client,
4612
+ subsOptions,
4613
+ row.streampaySubscriptionId,
4614
+ isActiveFreeze
4615
+ );
4616
+ let active = result.freeze;
4617
+ if (!active && result.hasMore) {
4618
+ const stream = await client.getSubscription(row.streampaySubscriptionId);
4619
+ if (stream.status === "FROZEN" && stream.latest_freeze && isActiveFreeze(stream.latest_freeze)) {
4620
+ active = stream.latest_freeze;
4621
+ } else {
4622
+ throw new api.APIError("CONFLICT", {
4623
+ code: $ERROR_CODES.SUBSCRIPTION_INVALID_STATE.code,
4624
+ message: "StreamPay returned more freeze pages than the SDK can read. Unable to verify the active freeze."
4625
+ });
4626
+ }
4627
+ }
4304
4628
  if (!active?.id || !active.freeze_start_datetime) {
4305
4629
  throw new api.APIError("BAD_REQUEST", {
4306
4630
  code: $ERROR_CODES.SUBSCRIPTION_FREEZE_NOT_ACTIVE.code,
@@ -4347,8 +4671,19 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
4347
4671
  "cancel-freeze"
4348
4672
  );
4349
4673
  try {
4350
- const freezes = await client.listSubscriptionFreezes(row.streampaySubscriptionId);
4351
- if (!freezes.data?.some((freeze) => freeze.id === ctx.body.freezeId)) {
4674
+ const result = await findSubscriptionFreeze(
4675
+ client,
4676
+ subsOptions,
4677
+ row.streampaySubscriptionId,
4678
+ (freeze) => freeze.id === ctx.body.freezeId
4679
+ );
4680
+ if (!result.freeze) {
4681
+ if (result.hasMore) {
4682
+ throw new api.APIError("CONFLICT", {
4683
+ code: $ERROR_CODES.SUBSCRIPTION_INVALID_STATE.code,
4684
+ message: "StreamPay returned more freeze pages than the SDK can read. Unable to verify whether this freeze was canceled."
4685
+ });
4686
+ }
4352
4687
  return ctx.json({ canceled: true, freezeId: ctx.body.freezeId, reused: true });
4353
4688
  }
4354
4689
  await client.deleteSubscriptionFreeze(row.streampaySubscriptionId, ctx.body.freezeId);
@@ -4425,6 +4760,12 @@ var subscriptionTable = {
4425
4760
  type: "string",
4426
4761
  required: true
4427
4762
  },
4763
+ catalogMapped: {
4764
+ type: "boolean",
4765
+ required: false,
4766
+ defaultValue: true,
4767
+ input: false
4768
+ },
4428
4769
  planVersion: {
4429
4770
  type: "string",
4430
4771
  required: false
@@ -4494,6 +4835,11 @@ var subscriptionTable = {
4494
4835
  type: "number",
4495
4836
  required: false
4496
4837
  },
4838
+ renewalCallbackEventId: {
4839
+ type: "string",
4840
+ required: false,
4841
+ input: false
4842
+ },
4497
4843
  trialStart: {
4498
4844
  type: "date",
4499
4845
  required: false
@@ -4704,6 +5050,9 @@ function subscriptions(subsOptions) {
4704
5050
  };
4705
5051
  if (dedupeEnabled) {
4706
5052
  registry.replayWebhookEvent = async (ctx, eventId) => {
5053
+ if (eventId.startsWith("handlers:") && registry.replayWebhookHandler) {
5054
+ return registry.replayWebhookHandler(ctx, eventId);
5055
+ }
4707
5056
  const syncCtx = {
4708
5057
  context: ctx.context
4709
5058
  };
@@ -4796,6 +5145,9 @@ async function dispatchWebhook(payload, handlers) {
4796
5145
  case "PAYMENT_REFUNDED":
4797
5146
  await handlers.onPaymentRefunded?.(payload);
4798
5147
  return;
5148
+ case "PAYMENT_PARTIALLY_REFUNDED":
5149
+ await handlers.onPaymentPartiallyRefunded?.(payload);
5150
+ return;
4799
5151
  case "PAYMENT_MARKED_AS_PAID":
4800
5152
  await handlers.onPaymentMarkedAsPaid?.(payload);
4801
5153
  return;
@@ -4838,6 +5190,9 @@ async function dispatchWebhook(payload, handlers) {
4838
5190
  case "SUBSCRIPTION_CYCLE_RENEWAL_FAILED":
4839
5191
  await handlers.onSubscriptionCycleRenewalFailed?.(payload);
4840
5192
  return;
5193
+ case "SUBSCRIPTION_CYCLE_RENEWED_SUCCESSFULLY":
5194
+ await handlers.onSubscriptionCycleRenewedSuccessfully?.(payload);
5195
+ return;
4841
5196
  case "SUBSCRIPTION_CANCEL_AT_PERIOD_END":
4842
5197
  await handlers.onSubscriptionCancelAtPeriodEnd?.(payload);
4843
5198
  return;
@@ -4946,8 +5301,56 @@ var webhooks = (webhooksOptions) => {
4946
5301
  throw new TypeError("webhooks(): `toleranceSeconds` must be a non-negative number.");
4947
5302
  }
4948
5303
  return (_options, registry) => {
4949
- const { secret, toleranceSeconds, ...handlers } = webhooksOptions;
5304
+ const { secret, toleranceSeconds, deduplicate = false, ...handlers } = webhooksOptions;
5305
+ if (deduplicate && registry) {
5306
+ registry.replayWebhookHandler = async (ctx, eventId) => {
5307
+ const syncContext = { context: ctx.context };
5308
+ const row = await syncContext.context.adapter.findOne({
5309
+ model: WEBHOOK_EVENT_MODEL,
5310
+ where: [{ field: "eventId", value: eventId }]
5311
+ });
5312
+ if (!eventId.startsWith("handlers:") || !row)
5313
+ throw new api.APIError("NOT_FOUND", { message: "Webhook callback event not found." });
5314
+ if (!row.rawPayload)
5315
+ throw new api.APIError("BAD_REQUEST", { message: "Webhook callback has no stored payload." });
5316
+ let payload;
5317
+ try {
5318
+ payload = JSON.parse(row.rawPayload);
5319
+ } catch {
5320
+ throw new api.APIError("BAD_REQUEST", {
5321
+ message: "Stored webhook payload is not valid JSON."
5322
+ });
5323
+ }
5324
+ if (!isStreamPayWebhookEnvelope(payload))
5325
+ throw new api.APIError("BAD_REQUEST", {
5326
+ message: "Stored webhook payload is not a valid event envelope."
5327
+ });
5328
+ const claimed = await claimWebhookEventForReplay(syncContext, row);
5329
+ if (!claimed?.lockedBy)
5330
+ throw new api.APIError("CONFLICT", {
5331
+ message: "Webhook callback is already being processed."
5332
+ });
5333
+ try {
5334
+ await dispatchWebhook(payload, handlers);
5335
+ await markWebhookEventCompleted(syncContext, claimed.id, claimed.lockedBy);
5336
+ } catch (err) {
5337
+ await recordWebhookEventFailure(
5338
+ syncContext,
5339
+ claimed.id,
5340
+ row.rawPayload,
5341
+ row.signatureHeader,
5342
+ err,
5343
+ claimed.lockedBy,
5344
+ true
5345
+ );
5346
+ throw err;
5347
+ }
5348
+ return { replayed: true, eventId };
5349
+ };
5350
+ registry.replayWebhookEvent ??= registry.replayWebhookHandler;
5351
+ }
4950
5352
  return {
5353
+ schema: deduplicate ? webhookEventTable : {},
4951
5354
  endpoints: {
4952
5355
  streampayWebhooks: api.createAuthEndpoint(
4953
5356
  "/streampay/webhooks",
@@ -5007,9 +5410,32 @@ var webhooks = (webhooksOptions) => {
5007
5410
  });
5008
5411
  }
5009
5412
  }
5413
+ const syncContext = { context: ctx.context };
5414
+ const claim = deduplicate ? await claimOrAdvanceWebhookEvent(
5415
+ syncContext,
5416
+ payload,
5417
+ rawBody,
5418
+ signatureHeader,
5419
+ DEFAULT_MAX_WEBHOOK_ATTEMPTS,
5420
+ "handlers"
5421
+ ) : null;
5422
+ if (claim && claim.action !== "process") return ctx.json({ received: true });
5423
+ const row = claim?.action === "process" ? claim.row : null;
5010
5424
  try {
5011
5425
  await dispatchWebhook(payload, handlers);
5426
+ if (row)
5427
+ await markWebhookEventCompleted(syncContext, row.id, row.lockedBy ?? void 0);
5012
5428
  } catch (err) {
5429
+ if (row)
5430
+ await recordWebhookEventFailure(
5431
+ syncContext,
5432
+ row.id,
5433
+ rawBody,
5434
+ signatureHeader,
5435
+ err,
5436
+ row.lockedBy ?? void 0,
5437
+ row.attemptCount >= DEFAULT_MAX_WEBHOOK_ATTEMPTS
5438
+ );
5013
5439
  const message = err instanceof Error ? err.message : String(err);
5014
5440
  logger2.error(`webhook handler failed: ${message}`);
5015
5441
  throw new api.APIError("INTERNAL_SERVER_ERROR", {
@@ -5024,9 +5450,6 @@ var webhooks = (webhooksOptions) => {
5024
5450
  };
5025
5451
  };
5026
5452
  var isAnonymous = (user) => "isAnonymous" in user && user.isAnonymous === true;
5027
- function hasInternalAdapter(ctx) {
5028
- return "internalAdapter" in ctx.context && ctx.context.internalAdapter !== null && typeof ctx.context.internalAdapter === "object" && "updateUser" in ctx.context.internalAdapter && typeof ctx.context.internalAdapter.updateUser === "function";
5029
- }
5030
5453
  var onBeforeUserCreate = (options) => async (user, context) => {
5031
5454
  if (!context || !options.createConsumerOnSignUp) return void 0;
5032
5455
  if (isAnonymous(user)) return void 0;
@@ -5037,11 +5460,12 @@ var onBeforeUserCreate = (options) => async (user, context) => {
5037
5460
  }
5038
5461
  const extras = options.getConsumerCreateParams ? await options.getConsumerCreateParams({ user }) : {};
5039
5462
  const createPayload = {
5040
- name: user.name || user.email,
5041
- email: user.email,
5042
5463
  consumer_type: "INDIVIDUAL",
5043
- ...extras
5464
+ ...extras,
5465
+ name: user.name || user.email,
5466
+ email: user.email
5044
5467
  };
5468
+ delete createPayload.external_id;
5045
5469
  try {
5046
5470
  const consumer = await options.client.createConsumer(createPayload);
5047
5471
  if (!consumer.id) {
@@ -5055,6 +5479,7 @@ var onBeforeUserCreate = (options) => async (user, context) => {
5055
5479
  if (isDuplicateConsumerError(err)) {
5056
5480
  const reusedId = await resolveDuplicateConsumer(options, createPayload, context);
5057
5481
  if (reusedId) {
5482
+ await assertConsumerUnclaimed(context, reusedId);
5058
5483
  return { data: { streampayConsumerId: reusedId } };
5059
5484
  }
5060
5485
  }
@@ -5103,10 +5528,15 @@ var onUserUpdate = (options) => async (user, context) => {
5103
5528
  getLogger(context).error(
5104
5529
  `consumer ${sessionUser.streampayConsumerId} not found for user=${sessionUser.id}; clearing stale link for re-provisioning.`
5105
5530
  );
5106
- if (hasInternalAdapter(context)) {
5531
+ if (typeof context.context.adapter?.update === "function") {
5107
5532
  try {
5108
- await context.context.internalAdapter.updateUser(sessionUser.id, {
5109
- streampayConsumerId: null
5533
+ await context.context.adapter.update({
5534
+ model: "user",
5535
+ where: [
5536
+ { field: "id", value: sessionUser.id },
5537
+ { field: "streampayConsumerId", value: sessionUser.streampayConsumerId }
5538
+ ],
5539
+ update: { streampayConsumerId: null }
5110
5540
  });
5111
5541
  } catch (clearErr) {
5112
5542
  getLogger(context).error(
@@ -5138,7 +5568,7 @@ var onUserDelete = (options) => async (user, context) => {
5138
5568
 
5139
5569
  // package.json
5140
5570
  var package_default = {
5141
- version: "2.2.1"};
5571
+ version: "3.0.1"};
5142
5572
 
5143
5573
  // src/version.ts
5144
5574
  var version = package_default.version;