better-auth-streampay 1.3.0 → 2.1.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
@@ -22,6 +22,8 @@ var $ERROR_CODES = defineErrorCodes({
22
22
  FORBIDDEN: "You do not have permission to perform this action.",
23
23
  NOT_FOUND: "The requested resource was not found.",
24
24
  CONSUMER_DUPLICATE: "A consumer with one of the provided identifiers already exists.",
25
+ STREAMPAY_CONSUMER_LINK_CONFLICT: "This StreamPay consumer is already linked to another account.",
26
+ STREAMPAY_CONSUMER_LINK_WRITE_FAILED: "The StreamPay consumer link could not be saved.",
25
27
  CONSUMER_HAS_ONGOING_ACTIVITY: "The consumer has ongoing invoices or active subscriptions and cannot be modified.",
26
28
  INVOICE_INVALID_STATE: "The invoice is in a state that forbids this action.",
27
29
  PAYMENT_DUPLICATE: "A payment with the same information already exists.",
@@ -33,12 +35,24 @@ var $ERROR_CODES = defineErrorCodes({
33
35
  PAYMENT_METHOD_INVALID: "The supplied payment method is invalid for this flow.",
34
36
  PRODUCT_LOCKED: "The product is referenced by a finalized invoice and cannot be modified.",
35
37
  COUPON_LOCKED: "The coupon is referenced by a finalized invoice and cannot be modified.",
38
+ CHECKOUT_CLIENT_FIELDS_FORBIDDEN: "Checkout fields must be resolved by the server.",
36
39
  SUBSCRIPTION_NOT_FOUND: "The subscription does not exist.",
37
40
  SUBSCRIPTION_PLAN_NOT_FOUND: "The requested subscription plan is not configured.",
38
41
  SUBSCRIPTION_ALREADY_ACTIVE: "An active subscription already exists for this plan group.",
42
+ SUBSCRIPTION_CHECKOUT_IN_PROGRESS: "A subscription checkout is already being created for this plan group.",
43
+ SUBSCRIPTION_ALREADY_CANCELED: "The subscription is already canceled.",
44
+ SUBSCRIPTION_ALREADY_FROZEN: "The subscription is already frozen.",
45
+ SUBSCRIPTION_EXPIRED: "The subscription has expired.",
46
+ SUBSCRIPTION_ALREADY_SCHEDULED_CANCEL: "The subscription is already scheduled to cancel at period end.",
47
+ SUBSCRIPTION_ALREADY_ON_PLAN: "The subscription is already on the requested plan.",
48
+ SUBSCRIPTION_IMMEDIATE_CANCEL_UNSUPPORTED: "StreamPay does not support immediate cancellation for active subscriptions.",
49
+ SUBSCRIPTION_PERIOD_END_CANCEL_UNSUPPORTED: "StreamPay only supports period-end cancellation for active subscriptions.",
50
+ SUBSCRIPTION_PLAN_GROUP_MISMATCH: "Subscription plan changes must stay within the same configured plan group.",
51
+ SUBSCRIPTION_PLAN_CHANGE_ALREADY_SCHEDULED: "A different plan change is already scheduled for this subscription.",
39
52
  SUBSCRIPTION_INVALID_STATE: "The subscription is in a state that forbids this action.",
40
53
  SUBSCRIPTION_FREEZE_NOT_ACTIVE: "No active freeze period was found for this subscription.",
41
54
  SUBSCRIPTION_REFERENCE_NOT_AUTHORIZED: "You are not authorized to act on this subscription reference.",
55
+ WEBHOOK_REPLAY_IN_PROGRESS: "This webhook event is already being replayed.",
42
56
  UNKNOWN: "An unexpected error occurred."
43
57
  });
44
58
  var RAW_CODE_MAP = {
@@ -85,10 +99,10 @@ var RAW_CODE_MAP = {
85
99
  COUPON_USED_IN_FINALIZED_INVOICE: "COUPON_LOCKED",
86
100
  SUBSCRIPTION_ALREADY_ACTIVE: "SUBSCRIPTION_ALREADY_ACTIVE",
87
101
  SUBSCRIPTION_NOT_FOUND: "SUBSCRIPTION_NOT_FOUND",
88
- SUBSCRIPTION_ALREADY_CANCELED: "SUBSCRIPTION_INVALID_STATE",
89
- SUBSCRIPTION_ALREADY_FROZEN: "SUBSCRIPTION_INVALID_STATE",
102
+ SUBSCRIPTION_ALREADY_CANCELED: "SUBSCRIPTION_ALREADY_CANCELED",
103
+ SUBSCRIPTION_ALREADY_FROZEN: "SUBSCRIPTION_ALREADY_FROZEN",
90
104
  SUBSCRIPTION_NOT_FROZEN: "SUBSCRIPTION_FREEZE_NOT_ACTIVE",
91
- SUBSCRIPTION_EXPIRED: "SUBSCRIPTION_INVALID_STATE"
105
+ SUBSCRIPTION_EXPIRED: "SUBSCRIPTION_EXPIRED"
92
106
  };
93
107
  function mapToErrorCode(rawCode, status) {
94
108
  if (rawCode && rawCode in RAW_CODE_MAP) {
@@ -316,6 +330,7 @@ async function ensureConsumerForUser(options, ctx, user) {
316
330
  name: user.name || user.email,
317
331
  email: user.email,
318
332
  external_id: user.id,
333
+ consumer_type: "INDIVIDUAL",
319
334
  ...extras
320
335
  };
321
336
  try {
@@ -332,12 +347,17 @@ async function ensureConsumerForUser(options, ctx, user) {
332
347
  if (isDuplicateConsumerError(err)) {
333
348
  const reusedId = await resolveDuplicateConsumer(options, payload, ctx);
334
349
  if (reusedId) {
350
+ await assertConsumerUnclaimed(ctx, reusedId, user.id);
335
351
  try {
336
352
  await options.client.updateConsumer(reusedId, { external_id: user.id });
337
353
  } catch (backfillErr) {
338
354
  getLogger(ctx).error(
339
355
  `consumer external_id backfill failed for user=${user.id} consumer=${reusedId}: ${formatStreamPayError(backfillErr)}`
340
356
  );
357
+ throw new api.APIError("INTERNAL_SERVER_ERROR", {
358
+ code: "STREAMPAY_CONSUMER_LINK_WRITE_FAILED",
359
+ message: "StreamPay consumer linking failed. Please try again."
360
+ });
341
361
  }
342
362
  await persistConsumerId(ctx, user.id, reusedId);
343
363
  return { consumerId: reusedId, created: false };
@@ -351,7 +371,40 @@ async function ensureConsumerForUser(options, ctx, user) {
351
371
  });
352
372
  }
353
373
  }
374
+ function consumerLinkUnavailable() {
375
+ return new api.APIError("INTERNAL_SERVER_ERROR", {
376
+ code: "STREAMPAY_CONSUMER_LINK_WRITE_FAILED",
377
+ message: "StreamPay consumer linking failed. Please try again."
378
+ });
379
+ }
380
+ async function findConsumerOwner(ctx, consumerId) {
381
+ try {
382
+ return await ctx.context.adapter.findOne({
383
+ model: "user",
384
+ where: [{ field: "streampayConsumerId", value: consumerId }]
385
+ });
386
+ } catch (err) {
387
+ getLogger(ctx).error(
388
+ `consumer ownership check failed for consumer=${consumerId}: ${formatStreamPayError(err)}`
389
+ );
390
+ throw consumerLinkUnavailable();
391
+ }
392
+ }
393
+ async function assertConsumerUnclaimed(ctx, consumerId, userId) {
394
+ const owner = await findConsumerOwner(ctx, consumerId);
395
+ if (!owner) return;
396
+ if (typeof owner.id !== "string") {
397
+ getLogger(ctx).error(`consumer ownership check returned a user without an id: ${consumerId}`);
398
+ throw consumerLinkUnavailable();
399
+ }
400
+ if (owner.id === userId) return;
401
+ throw new api.APIError("CONFLICT", {
402
+ code: "STREAMPAY_CONSUMER_LINK_CONFLICT",
403
+ message: "This StreamPay consumer is already linked to another account."
404
+ });
405
+ }
354
406
  async function persistConsumerId(ctx, userId, consumerId) {
407
+ await assertConsumerUnclaimed(ctx, consumerId, userId);
355
408
  try {
356
409
  await ctx.context.internalAdapter.updateUser(userId, {
357
410
  streampayConsumerId: consumerId
@@ -360,6 +413,8 @@ async function persistConsumerId(ctx, userId, consumerId) {
360
413
  getLogger(ctx).error(
361
414
  `consumer link write failed for user=${userId}: ${formatStreamPayError(err)}`
362
415
  );
416
+ await assertConsumerUnclaimed(ctx, consumerId, userId);
417
+ throw consumerLinkUnavailable();
363
418
  }
364
419
  }
365
420
 
@@ -464,24 +519,39 @@ function asSessionUser(user) {
464
519
  return result;
465
520
  }
466
521
 
467
- // src/utils/amount.ts
468
- var StreamPayAmount = {
469
- toHalalat(sar) {
470
- const asNumber = typeof sar === "string" ? Number(sar) : sar;
471
- if (!Number.isFinite(asNumber)) {
472
- throw new RangeError(`StreamPayAmount.toHalalat: invalid SAR value ${String(sar)}`);
473
- }
474
- return Math.round(asNumber * 100);
475
- },
476
- toSAR(halalat) {
477
- if (!Number.isFinite(halalat) || !Number.isInteger(halalat)) {
478
- throw new RangeError(`StreamPayAmount.toSAR: expected integer halalat, got ${halalat}`);
479
- }
480
- return (halalat / 100).toFixed(2);
481
- }
482
- };
483
-
484
- // src/plugins/subscriptions/types.ts
522
+ // src/plugins/subscriptions/status.ts
523
+ var SUBSCRIPTION_STATUSES = [
524
+ "incomplete",
525
+ "incomplete_expired",
526
+ "trial_pending",
527
+ "trialing",
528
+ "active",
529
+ "inactive",
530
+ "expired",
531
+ "canceled",
532
+ "frozen",
533
+ "past_due"
534
+ ];
535
+ var DEFAULT_ACCESS_STATUSES = ["active", "trialing", "frozen", "past_due"];
536
+ var MANAGEABLE_STATUSES = /* @__PURE__ */ new Set([
537
+ "active",
538
+ "trial_pending",
539
+ "trialing",
540
+ "frozen",
541
+ "past_due"
542
+ ]);
543
+ var TERMINAL_STATUSES = /* @__PURE__ */ new Set([
544
+ "incomplete_expired",
545
+ "inactive",
546
+ "expired",
547
+ "canceled"
548
+ ]);
549
+ var CHECKOUT_SUCCESS_STATUSES = /* @__PURE__ */ new Set([
550
+ "ACTIVE",
551
+ "TRIALING",
552
+ "TRIAL_PENDING",
553
+ "FROZEN"
554
+ ]);
485
555
  function toLocalStatus(status) {
486
556
  switch (status) {
487
557
  case "ACTIVE":
@@ -494,16 +564,200 @@ function toLocalStatus(status) {
494
564
  return "canceled";
495
565
  case "FROZEN":
496
566
  return "frozen";
567
+ case "TRIALING":
568
+ return "trialing";
569
+ case "TRIAL_PENDING":
570
+ return "trial_pending";
497
571
  default:
498
572
  return "incomplete";
499
573
  }
500
574
  }
575
+ function isManageableSubscriptionStatus(status) {
576
+ return MANAGEABLE_STATUSES.has(status);
577
+ }
578
+ function isTerminalSubscriptionStatus(status) {
579
+ return status !== void 0 && TERMINAL_STATUSES.has(status);
580
+ }
581
+ function isCheckoutSuccessStatus(status) {
582
+ return status !== void 0 && CHECKOUT_SUCCESS_STATUSES.has(status);
583
+ }
584
+
585
+ // src/plugins/subscriptions/reconcile.ts
586
+ var SUBSCRIPTION_MODEL = "subscription";
587
+ function reconcileProjectionAgainstExisting(existing, projection, options = {}) {
588
+ const projected = { ...projection };
589
+ if (existing?.billingStatus === "past_due" && projected.status === "active") {
590
+ projected.status = "past_due";
591
+ projected.billingStatus = "past_due";
592
+ }
593
+ const lifecycleAt = options.lifecycleAt === void 0 ? /* @__PURE__ */ new Date() : options.lifecycleAt;
594
+ if (options.stampCancelScheduled !== false && !existing?.cancelAtPeriodEnd && projected.cancelAtPeriodEnd && lifecycleAt) {
595
+ projected.cancelScheduledAt = lifecycleAt;
596
+ }
597
+ if (options.stampCanceled !== false && projected.status === "canceled" && !existing?.canceledAt && lifecycleAt) {
598
+ projected.canceledAt = lifecycleAt;
599
+ }
600
+ return projected;
601
+ }
602
+ function projectSubscriptionAgainstExisting(existing, stream) {
603
+ return reconcileProjectionAgainstExisting(existing, projectSubscriptionFields(stream));
604
+ }
605
+ async function applySubscriptionProjection(adapter, stream, log, source) {
606
+ const streampaySubscriptionId = stream?.id;
607
+ if (!stream || !streampaySubscriptionId) return;
608
+ try {
609
+ const existing = await adapter.findOne({
610
+ model: SUBSCRIPTION_MODEL,
611
+ where: [{ field: "streampaySubscriptionId", value: streampaySubscriptionId }]
612
+ });
613
+ if (!existing) return;
614
+ await adapter.update({
615
+ model: SUBSCRIPTION_MODEL,
616
+ update: projectSubscriptionAgainstExisting(existing, stream),
617
+ where: [{ field: "id", value: existing.id }]
618
+ });
619
+ } catch (err) {
620
+ const message = err instanceof Error ? err.message : String(err);
621
+ log.warn(
622
+ `${source}: project for sub=${streampaySubscriptionId} failed (${message}). Local row will reconcile on next webhook.`
623
+ );
624
+ }
625
+ }
626
+ async function syncSubscriptionFromUpstream(client, adapter, streampaySubscriptionId, log, source, prefetched) {
627
+ let stream = prefetched;
628
+ if (!stream) {
629
+ try {
630
+ stream = await client.getSubscription(streampaySubscriptionId);
631
+ } catch (err) {
632
+ const message = err instanceof Error ? err.message : String(err);
633
+ log.warn(
634
+ `${source}: getSubscription(${streampaySubscriptionId}) failed (${message}). Local row will reconcile on next webhook.`
635
+ );
636
+ return;
637
+ }
638
+ }
639
+ await applySubscriptionProjection(adapter, stream, log, source);
640
+ }
641
+ function projectSubscriptionFields(sub) {
642
+ const status = toLocalStatus(sub.status);
643
+ const terminal = isTerminalSubscriptionStatus(status);
644
+ const periodStart = parseDate(sub.current_period_start);
645
+ const periodEnd = parseDate(sub.current_period_end);
646
+ return {
647
+ streampaySubscriptionId: sub.id ?? null,
648
+ streampayConsumerId: sub.organization_consumer_id ?? null,
649
+ amountInSmallestUnit: typeof sub.amount_in_smallest_unit === "number" ? sub.amount_in_smallest_unit : amountToSmallestUnit(sub.amount, sub.currency),
650
+ originalAmountInSmallestUnit: typeof sub.original_amount_in_smallest_unit === "number" ? sub.original_amount_in_smallest_unit : amountToSmallestUnit(sub.original_amount, sub.currency),
651
+ currency: sub.currency ?? null,
652
+ billingInterval: sub.recurring_interval ?? null,
653
+ billingIntervalCount: sub.recurring_interval_count ?? null,
654
+ status,
655
+ providerStatus: sub.status ?? null,
656
+ periodStart,
657
+ periodEnd,
658
+ currentCycleNumber: sub.current_cycle_number ?? null,
659
+ trialStart: sub.trial_end ? parseDate(sub.started_at) ?? periodStart : null,
660
+ trialEnd: parseDate(sub.trial_end),
661
+ cancelAtPeriodEnd: Boolean(sub.cancel_at_period_end),
662
+ cancelAt: sub.cancel_at_period_end ? periodEnd : null,
663
+ ...sub.cancel_at_period_end ? {} : { cancelScheduledAt: null },
664
+ endedAt: parseDate(sub.ended_at),
665
+ frozenAt: sub.status === "FROZEN" ? parseDate(sub.latest_freeze?.freeze_start_datetime) : null,
666
+ freezeEndAt: sub.status === "FROZEN" ? parseDate(sub.latest_freeze?.freeze_end_datetime) : null,
667
+ providerUpdatedAt: parseDate(sub.updated_at),
668
+ syncedAt: /* @__PURE__ */ new Date(),
669
+ ...terminal ? { activeSlotKey: null } : {},
670
+ updatedAt: /* @__PURE__ */ new Date()
671
+ };
672
+ }
673
+ function parseDate(value) {
674
+ if (!value) return null;
675
+ const date = new Date(value);
676
+ return Number.isNaN(date.getTime()) ? null : date;
677
+ }
678
+ function minorUnitExponent(currency) {
679
+ switch (currency) {
680
+ case "BHD":
681
+ case "KWD":
682
+ case "OMR":
683
+ return 3;
684
+ case "SAR":
685
+ case "USD":
686
+ case "EUR":
687
+ case "GBP":
688
+ case "AED":
689
+ case "QAR":
690
+ return 2;
691
+ default:
692
+ return null;
693
+ }
694
+ }
695
+ function amountToSmallestUnit(value, currency) {
696
+ if (!value) return null;
697
+ const exponent = minorUnitExponent(currency);
698
+ if (exponent === null) return null;
699
+ const match = /^([+-]?)(\d+)(?:\.(\d+))?$/.exec(value);
700
+ if (!match) return null;
701
+ const [, sign, integer, fraction = ""] = match;
702
+ if (!integer) return null;
703
+ const excessFraction = fraction.slice(exponent);
704
+ if (excessFraction && !/^0+$/.test(excessFraction)) return null;
705
+ const normalizedFraction = fraction.slice(0, exponent).padEnd(exponent, "0");
706
+ const factor = 10n ** BigInt(exponent);
707
+ const unsigned = BigInt(integer) * factor + BigInt(normalizedFraction || "0");
708
+ const signed = sign === "-" ? -unsigned : unsigned;
709
+ const numeric = Number(signed);
710
+ return Number.isSafeInteger(numeric) ? numeric : null;
711
+ }
712
+ var SubscriptionItemSchema = zod.z.object({
713
+ product: zod.z.object({ id: zod.z.string() }).passthrough().optional(),
714
+ product_id: zod.z.string().optional()
715
+ }).passthrough();
716
+ function subscriptionItemProductId(item) {
717
+ const parsed = SubscriptionItemSchema.safeParse(item);
718
+ if (!parsed.success) return null;
719
+ return parsed.data.product?.id ?? parsed.data.product_id ?? null;
720
+ }
721
+ function inferPlanFromItems(sub, plans) {
722
+ if (!Array.isArray(sub.items)) return null;
723
+ return inferPlanFromItemList(sub.items, plans);
724
+ }
725
+ function inferPlanFromItemList(items, plans) {
726
+ const productIds = new Set(
727
+ items.map(subscriptionItemProductId).filter((id) => Boolean(id))
728
+ );
729
+ return plans.list.find((plan) => productIds.has(plan.productId))?.name ?? null;
730
+ }
731
+ function projectPlanFields(sub, plans) {
732
+ const currentPlan = inferPlanFromItems(sub, plans);
733
+ const currentProductId = subscriptionItemProductId(sub.items?.[0]);
734
+ const pendingPlan = Array.isArray(sub.pending_change?.target_items) ? inferPlanFromItemList(sub.pending_change.target_items, plans) : null;
735
+ const pendingProductId = subscriptionItemProductId(sub.pending_change?.target_items?.[0]);
736
+ const configuredCurrent = currentPlan ? plans.byName.get(currentPlan) : void 0;
737
+ return {
738
+ ...currentPlan ? {
739
+ plan: currentPlan,
740
+ planVersion: configuredCurrent?.version ?? null,
741
+ productId: currentProductId,
742
+ group: configuredCurrent?.group ?? null
743
+ } : currentProductId ? { productId: currentProductId } : {},
744
+ pendingPlan,
745
+ pendingProductId,
746
+ pendingPlanEffectiveAt: parseDate(sub.pending_change?.effective_at)
747
+ };
748
+ }
749
+ function subscriptionSlotKey(referenceType, referenceId, group) {
750
+ const tuple = JSON.stringify([referenceType, referenceId, group ?? null]);
751
+ return `sp_slot_v1_${crypto.createHash("sha256").update(tuple).digest("hex")}`;
752
+ }
501
753
  var UPGRADE_IDEMPOTENCY_WINDOW_MS = 15 * 60 * 1e3;
502
754
  var PLAN_NAME_METADATA_KEY = "streampay_plugin_plan_name";
503
755
  var REFERENCE_ID_METADATA_KEY = "streampay_plugin_reference_id";
756
+ var REFERENCE_TYPE_METADATA_KEY = "streampay_plugin_reference_type";
757
+ var SUBSCRIPTION_ROW_ID_METADATA_KEY = "streampay_plugin_subscription_row_id";
504
758
 
505
759
  // src/plugins/subscriptions/sync.ts
506
- var SUBSCRIPTION_MODEL = "subscription";
760
+ var SUBSCRIPTION_MODEL2 = "subscription";
507
761
  var WEBHOOK_EVENT_MODEL = "streampayWebhookEvent";
508
762
  function logger(ctx) {
509
763
  return scopedLogger(ctx.context.logger);
@@ -526,6 +780,8 @@ function isUniqueConstraintError(err) {
526
780
  }
527
781
  return false;
528
782
  }
783
+ var WEBHOOK_PROCESSING_LEASE_MS = 2 * 60 * 1e3;
784
+ var WEBHOOK_RETRY_DELAYS_MS = [5, 30, 120, 360, 720].map((minutes) => minutes * 60 * 1e3);
529
785
  async function claimOrAdvanceWebhookEvent(ctx, payload, rawBody, signatureHeader, maxAttempts) {
530
786
  const eventId = extractEventId(payload);
531
787
  if (!eventId) {
@@ -535,6 +791,7 @@ async function claimOrAdvanceWebhookEvent(ctx, payload, rawBody, signatureHeader
535
791
  return { action: "process", row: null };
536
792
  }
537
793
  const now = /* @__PURE__ */ new Date();
794
+ const lockId = crypto.randomUUID();
538
795
  try {
539
796
  const inserted = await ctx.context.adapter.create({
540
797
  model: WEBHOOK_EVENT_MODEL,
@@ -543,8 +800,10 @@ async function claimOrAdvanceWebhookEvent(ctx, payload, rawBody, signatureHeader
543
800
  eventType: payload.event_type,
544
801
  status: "pending",
545
802
  attemptCount: 1,
546
- processedAt: now,
547
- firstSeenAt: now
803
+ receivedAt: now,
804
+ lastAttemptAt: now,
805
+ lockedAt: now,
806
+ lockedBy: lockId
548
807
  }
549
808
  });
550
809
  return { action: "process", row: inserted };
@@ -571,6 +830,12 @@ async function claimOrAdvanceWebhookEvent(ctx, payload, rawBody, signatureHeader
571
830
  );
572
831
  return { action: "skip", reason: "dead_letter" };
573
832
  }
833
+ if (existing.lockedAt instanceof Date && now.getTime() - existing.lockedAt.getTime() < WEBHOOK_PROCESSING_LEASE_MS) {
834
+ logger(ctx).info(
835
+ `webhook ${payload.event_type} (${eventId}) is already being processed \u2014 skipping concurrent delivery.`
836
+ );
837
+ return { action: "skip", reason: "in_progress" };
838
+ }
574
839
  const nextAttempt = (existing.attemptCount ?? 0) + 1;
575
840
  if (nextAttempt > maxAttempts) {
576
841
  const updated2 = await ctx.context.adapter.update({
@@ -578,48 +843,114 @@ async function claimOrAdvanceWebhookEvent(ctx, payload, rawBody, signatureHeader
578
843
  update: {
579
844
  status: "dead_letter",
580
845
  attemptCount: nextAttempt,
581
- processedAt: now,
846
+ lastAttemptAt: now,
847
+ deadLetteredAt: now,
848
+ nextAttemptAt: null,
582
849
  rawPayload: rawBody,
583
- signatureHeader
850
+ signatureHeader,
851
+ lockedAt: null,
852
+ lockedBy: null
584
853
  },
585
- where: [{ field: "id", value: existing.id }]
854
+ where: [
855
+ { field: "id", value: existing.id },
856
+ { field: "status", value: "pending" },
857
+ { field: "lockedAt", value: existing.lockedAt ?? null }
858
+ ]
586
859
  });
587
- return { action: "dead_letter", row: updated2 ?? existing };
860
+ return updated2 ? { action: "dead_letter", row: updated2 } : { action: "skip", reason: "in_progress" };
588
861
  }
589
862
  const updated = await ctx.context.adapter.update({
590
863
  model: WEBHOOK_EVENT_MODEL,
591
864
  update: {
592
865
  attemptCount: nextAttempt,
593
- processedAt: now
866
+ lastAttemptAt: now,
867
+ nextAttemptAt: null,
868
+ lockedAt: now,
869
+ lockedBy: lockId
594
870
  },
595
- where: [{ field: "id", value: existing.id }]
871
+ where: [
872
+ { field: "id", value: existing.id },
873
+ { field: "status", value: "pending" },
874
+ { field: "lockedAt", value: existing.lockedAt ?? null }
875
+ ]
876
+ });
877
+ return updated ? { action: "process", row: updated } : { action: "skip", reason: "in_progress" };
878
+ }
879
+ async function claimWebhookEventForReplay(ctx, row) {
880
+ const now = /* @__PURE__ */ new Date();
881
+ if (row.lockedAt instanceof Date && now.getTime() - row.lockedAt.getTime() < WEBHOOK_PROCESSING_LEASE_MS) {
882
+ return null;
883
+ }
884
+ return ctx.context.adapter.update({
885
+ model: WEBHOOK_EVENT_MODEL,
886
+ update: {
887
+ status: "pending",
888
+ attemptCount: (row.attemptCount ?? 0) + 1,
889
+ lastAttemptAt: now,
890
+ nextAttemptAt: null,
891
+ completedAt: null,
892
+ deadLetteredAt: null,
893
+ lockedAt: now,
894
+ lockedBy: crypto.randomUUID()
895
+ },
896
+ where: [
897
+ { field: "id", value: row.id },
898
+ { field: "status", value: row.status },
899
+ { field: "lockedAt", value: row.lockedAt ?? null }
900
+ ]
596
901
  });
597
- return { action: "process", row: updated ?? existing };
598
902
  }
599
- async function markWebhookEventCompleted(ctx, rowId) {
903
+ async function markWebhookEventCompleted(ctx, rowId, lockId) {
600
904
  await ctx.context.adapter.update({
601
905
  model: WEBHOOK_EVENT_MODEL,
602
906
  update: {
603
907
  status: "completed",
604
- processedAt: /* @__PURE__ */ new Date(),
908
+ completedAt: /* @__PURE__ */ new Date(),
909
+ nextAttemptAt: null,
910
+ lockedAt: null,
911
+ lockedBy: null,
605
912
  rawPayload: null,
606
913
  signatureHeader: null,
607
- lastError: null
914
+ lastError: null,
915
+ lastErrorCode: null
608
916
  },
609
- where: [{ field: "id", value: rowId }]
917
+ where: [
918
+ { field: "id", value: rowId },
919
+ ...lockId ? [{ field: "lockedBy", value: lockId }] : []
920
+ ]
610
921
  });
611
922
  }
612
- async function recordWebhookEventFailure(ctx, rowId, rawBody, signatureHeader, err) {
923
+ async function recordWebhookEventFailure(ctx, rowId, rawBody, signatureHeader, err, lockId, deadLetter = false) {
613
924
  const lastError = err instanceof Error ? err.message : String(err);
925
+ const sdkError = readSdkErrorFields(err);
926
+ const lastErrorCode = readEnvelope(sdkError.body)?.code ?? (sdkError.status !== void 0 ? `HTTP_${sdkError.status}` : err instanceof Error ? err.name : "UNKNOWN");
927
+ const row = await ctx.context.adapter.findOne({
928
+ model: WEBHOOK_EVENT_MODEL,
929
+ where: [
930
+ { field: "id", value: rowId },
931
+ ...lockId ? [{ field: "lockedBy", value: lockId }] : []
932
+ ]
933
+ });
934
+ const attemptCount = row?.attemptCount ?? 1;
935
+ const retryDelay = WEBHOOK_RETRY_DELAYS_MS[Math.min(attemptCount - 1, WEBHOOK_RETRY_DELAYS_MS.length - 1)];
936
+ const now = /* @__PURE__ */ new Date();
614
937
  await ctx.context.adapter.update({
615
938
  model: WEBHOOK_EVENT_MODEL,
616
939
  update: {
617
- processedAt: /* @__PURE__ */ new Date(),
940
+ ...deadLetter ? { status: "dead_letter", deadLetteredAt: now } : {},
941
+ lastAttemptAt: now,
942
+ nextAttemptAt: deadLetter || retryDelay === void 0 ? null : new Date(now.getTime() + retryDelay),
943
+ lockedAt: null,
944
+ lockedBy: null,
618
945
  lastError,
946
+ lastErrorCode,
619
947
  ...rawBody !== null ? { rawPayload: rawBody } : {},
620
948
  ...signatureHeader !== null ? { signatureHeader } : {}
621
949
  },
622
- where: [{ field: "id", value: rowId }]
950
+ where: [
951
+ { field: "id", value: rowId },
952
+ ...lockId ? [{ field: "lockedBy", value: lockId }] : []
953
+ ]
623
954
  });
624
955
  }
625
956
  function extractEventId(payload) {
@@ -631,92 +962,44 @@ function readMetadataString(data, key) {
631
962
  const value = data.metadata[key];
632
963
  return typeof value === "string" && value.length > 0 ? value : null;
633
964
  }
965
+ function readReferenceType(data) {
966
+ const value = readMetadataString(data, REFERENCE_TYPE_METADATA_KEY);
967
+ return value === "user" || value === "organization" || value === "custom" ? value : null;
968
+ }
634
969
  async function findSubscriptionByStreampayId(ctx, streampaySubscriptionId) {
635
970
  return ctx.context.adapter.findOne({
636
- model: SUBSCRIPTION_MODEL,
971
+ model: SUBSCRIPTION_MODEL2,
637
972
  where: [{ field: "streampaySubscriptionId", value: streampaySubscriptionId }]
638
973
  });
639
974
  }
640
- async function applySubscriptionProjection(adapter, stream, log, source) {
641
- const streampaySubscriptionId = stream?.id;
642
- if (!stream || !streampaySubscriptionId) return;
643
- try {
644
- const existing = await adapter.findOne({
645
- model: SUBSCRIPTION_MODEL,
646
- where: [{ field: "streampaySubscriptionId", value: streampaySubscriptionId }]
647
- });
648
- if (!existing) return;
649
- await adapter.update({
650
- model: SUBSCRIPTION_MODEL,
651
- update: projectSubscriptionFields(stream),
652
- where: [{ field: "id", value: existing.id }]
653
- });
654
- } catch (err) {
655
- const msg = err instanceof Error ? err.message : String(err);
656
- log.warn(
657
- `${source}: project for sub=${streampaySubscriptionId} failed (${msg}). Local row will reconcile on next webhook.`
658
- );
659
- }
660
- }
661
- async function syncSubscriptionFromUpstream(client, adapter, streampaySubscriptionId, log, source) {
662
- let stream;
663
- try {
664
- stream = await client.getSubscription(streampaySubscriptionId);
665
- } catch (err) {
666
- const msg = err instanceof Error ? err.message : String(err);
667
- log.warn(
668
- `${source}: getSubscription(${streampaySubscriptionId}) failed (${msg}). Local row will reconcile on next webhook.`
669
- );
670
- return;
671
- }
672
- await applySubscriptionProjection(adapter, stream, log, source);
673
- }
674
- async function findIncompleteRow(ctx, referenceId, plan) {
975
+ async function findIncompleteRow(ctx, referenceId, referenceType, plan, paymentLinkId) {
675
976
  const candidates = await ctx.context.adapter.findMany({
676
- model: SUBSCRIPTION_MODEL,
977
+ model: SUBSCRIPTION_MODEL2,
677
978
  where: [
678
979
  { field: "referenceId", value: referenceId },
679
980
  { field: "plan", value: plan },
680
981
  { field: "status", value: "incomplete" }
681
982
  ]
682
983
  });
683
- if (candidates.length === 0) return null;
684
- return candidates.reduce(
685
- (newest, candidate) => candidate.createdAt > newest.createdAt ? candidate : newest
686
- );
687
- }
688
- function projectSubscriptionFields(sub) {
689
- return {
690
- streampaySubscriptionId: sub.id ?? null,
691
- streampayConsumerId: sub.organization_consumer_id ?? null,
692
- amountHalalat: amountToHalalat(sub.amount),
693
- currency: sub.currency ?? null,
694
- billingInterval: sub.recurring_interval ?? null,
695
- billingIntervalCount: sub.recurring_interval_count ?? null,
696
- status: toLocalStatus(sub.status),
697
- periodStart: parseDate(sub.current_period_start),
698
- periodEnd: parseDate(sub.current_period_end),
699
- cancelAtPeriodEnd: Boolean(sub.cancel_at_period_end),
700
- endedAt: parseDate(sub.ended_at),
701
- frozenAt: sub.status === "FROZEN" ? parseDate(sub.latest_freeze?.freeze_start_datetime) : null,
702
- freezeEndAt: sub.status === "FROZEN" ? parseDate(sub.latest_freeze?.freeze_end_datetime) : null,
703
- updatedAt: /* @__PURE__ */ new Date()
704
- };
705
- }
706
- function parseDate(value) {
707
- if (!value) return null;
708
- const d = new Date(value);
709
- return Number.isNaN(d.getTime()) ? null : d;
710
- }
711
- function amountToHalalat(value) {
712
- if (!value) return null;
713
- try {
714
- return StreamPayAmount.toHalalat(value);
715
- } catch {
984
+ const scopedCandidates = referenceType ? candidates.filter((candidate) => (candidate.referenceType ?? "user") === referenceType) : candidates;
985
+ if (scopedCandidates.length === 0) return null;
986
+ if (paymentLinkId) {
987
+ const exact = scopedCandidates.find(
988
+ (candidate) => candidate.streampayPaymentLinkId === paymentLinkId
989
+ );
990
+ if (exact) return exact;
991
+ }
992
+ if (!referenceType && new Set(scopedCandidates.map((candidate) => candidate.referenceType ?? "user")).size > 1) {
716
993
  return null;
717
994
  }
995
+ return scopedCandidates.reduce((newest, candidate) => {
996
+ const candidateTime = candidate.createdAt?.getTime() ?? Number.NEGATIVE_INFINITY;
997
+ const newestTime = newest.createdAt?.getTime() ?? Number.NEGATIVE_INFINITY;
998
+ return candidateTime > newestTime ? candidate : newest;
999
+ });
718
1000
  }
719
1001
  async function resolveRowUser(ctx, row) {
1002
+ if ((row.referenceType ?? "user") !== "user") return null;
720
1003
  const findUserById = ctx.context.internalAdapter?.findUserById;
721
1004
  if (!findUserById) return null;
722
1005
  try {
@@ -726,15 +1009,33 @@ async function resolveRowUser(ctx, row) {
726
1009
  return null;
727
1010
  }
728
1011
  }
729
- async function fireCallback(ctx, callback, data, callbackName) {
1012
+ async function fireCallback(ctx, callback, data, callbackName, retryOnError) {
730
1013
  if (!callback) return;
731
1014
  try {
732
1015
  await callback(data);
733
1016
  } catch (err) {
734
1017
  const msg = err instanceof Error ? err.message : String(err);
735
1018
  logger(ctx).error(`subscription callback ${callbackName} failed: ${msg}`);
1019
+ if (retryOnError) {
1020
+ throw new SubscriptionCallbackDeliveryError(callbackName, err);
1021
+ }
736
1022
  }
737
1023
  }
1024
+ var SubscriptionCallbackDeliveryError = class extends Error {
1025
+ callbackName;
1026
+ constructor(callbackName, cause) {
1027
+ const message = cause instanceof Error ? cause.message : String(cause);
1028
+ super(`Subscription callback ${callbackName} failed: ${message}`);
1029
+ this.name = "SubscriptionCallbackDeliveryError";
1030
+ this.callbackName = callbackName;
1031
+ }
1032
+ };
1033
+ var SubscriptionCorrelationError = class extends Error {
1034
+ constructor(message) {
1035
+ super(message);
1036
+ this.name = "SubscriptionCorrelationError";
1037
+ }
1038
+ };
738
1039
  async function reconcileFromStreamPay(ctx, payload, client, plans) {
739
1040
  const streampaySubscriptionId = payload.entity_id;
740
1041
  if (!streampaySubscriptionId) {
@@ -752,66 +1053,155 @@ async function reconcileFromStreamPay(ctx, payload, client, plans) {
752
1053
  throw err;
753
1054
  }
754
1055
  const existing = await findSubscriptionByStreampayId(ctx, streampaySubscriptionId);
755
- const projected = projectSubscriptionFields(stream);
756
- if (payload.event_type === "SUBSCRIPTION_CYCLE_RENEWAL_FAILED" && projected.status === "active") {
1056
+ let projected = {
1057
+ ...projectSubscriptionFields(stream),
1058
+ ...projectPlanFields(stream, plans)
1059
+ };
1060
+ const eventAt = parseDate(payload.timestamp);
1061
+ const eventIsStale = Boolean(
1062
+ eventAt && existing?.providerUpdatedAt instanceof Date && eventAt.getTime() < existing.providerUpdatedAt.getTime()
1063
+ );
1064
+ if (!eventIsStale && payload.event_type === "SUBSCRIPTION_CYCLE_RENEWAL_FAILED" && projected.status === "active") {
757
1065
  projected.status = "past_due";
1066
+ projected.billingStatus = "past_due";
1067
+ }
1068
+ const schedulesCancellation = !eventIsStale && payload.event_type === "SUBSCRIPTION_CANCEL_AT_PERIOD_END" && Boolean(stream.cancel_at_period_end);
1069
+ if (schedulesCancellation) {
1070
+ projected.cancelAt = parseDate(stream.current_period_end);
758
1071
  }
1072
+ const confirmsCancellation = !eventIsStale && payload.event_type === "SUBSCRIPTION_CANCELED" && projected.status === "canceled";
1073
+ if (confirmsCancellation) {
1074
+ projected.activeSlotKey = null;
1075
+ }
1076
+ projected = reconcileProjectionAgainstExisting(existing, projected, {
1077
+ lifecycleAt: eventAt,
1078
+ stampCancelScheduled: schedulesCancellation,
1079
+ stampCanceled: confirmsCancellation
1080
+ });
759
1081
  if (existing) {
1082
+ const projectedStatus = projected.status ?? existing.status;
1083
+ if (!isTerminalSubscriptionStatus(projectedStatus)) {
1084
+ const desiredSlotKey = subscriptionSlotKey(
1085
+ existing.referenceType ?? "user",
1086
+ existing.referenceId,
1087
+ projected.group === void 0 ? existing.group : projected.group
1088
+ );
1089
+ if (existing.activeSlotKey !== desiredSlotKey) {
1090
+ projected.activeSlotKey = desiredSlotKey;
1091
+ }
1092
+ }
760
1093
  const updated = await ctx.context.adapter.update({
761
- model: SUBSCRIPTION_MODEL,
1094
+ model: SUBSCRIPTION_MODEL2,
762
1095
  update: projected,
763
1096
  where: [{ field: "id", value: existing.id }]
764
1097
  });
1098
+ if (eventIsStale) {
1099
+ logger(ctx).info(
1100
+ `webhook ${payload.event_type}: ignored stale lifecycle callback for sub=${streampaySubscriptionId}.`
1101
+ );
1102
+ return { row: null, stream };
1103
+ }
765
1104
  return { row: updated ?? { ...existing, ...projected }, stream };
766
1105
  }
767
1106
  const planName = readMetadataString(payload.data, PLAN_NAME_METADATA_KEY) ?? inferPlanFromItems(stream, plans);
768
1107
  const referenceId = readMetadataString(payload.data, REFERENCE_ID_METADATA_KEY);
1108
+ const metadataReferenceType = readReferenceType(payload.data);
769
1109
  if (!planName || !referenceId) {
770
1110
  logger(ctx).warn(
771
1111
  `webhook ${payload.event_type}: cannot link sub=${streampaySubscriptionId} \u2014 missing plan_name (${planName}) or reference_id (${referenceId}) metadata.`
772
1112
  );
773
1113
  return { row: null, stream };
774
1114
  }
775
- const incomplete = await findIncompleteRow(ctx, referenceId, planName);
1115
+ const paymentLinkId = stream.latest_invoice?.payment_link_id ?? payload.data?.payment_link?.id ?? null;
1116
+ const localRowId = readMetadataString(payload.data, SUBSCRIPTION_ROW_ID_METADATA_KEY);
1117
+ if (localRowId) {
1118
+ const metadataRow = await ctx.context.adapter.findOne({
1119
+ model: SUBSCRIPTION_MODEL2,
1120
+ where: [{ field: "id", value: localRowId }]
1121
+ });
1122
+ if (!metadataRow) {
1123
+ logger(ctx).warn(
1124
+ `webhook ${payload.event_type}: referenced subscription row=${localRowId} is missing; rebuilding from signed metadata.`
1125
+ );
1126
+ } else if (metadataRow.referenceId === referenceId && (!metadataReferenceType || (metadataRow.referenceType ?? "user") === metadataReferenceType) && metadataRow.plan === planName && (!metadataRow.streampaySubscriptionId || metadataRow.streampaySubscriptionId === streampaySubscriptionId) && (!metadataRow.streampayPaymentLinkId || !paymentLinkId || metadataRow.streampayPaymentLinkId === paymentLinkId)) {
1127
+ const projectedWithSlot = {
1128
+ ...projected,
1129
+ billingStatus: metadataRow.billingStatus ?? "current",
1130
+ ...projected.activeSlotKey === null ? {} : {
1131
+ activeSlotKey: metadataRow.activeSlotKey ?? subscriptionSlotKey(
1132
+ metadataRow.referenceType ?? metadataReferenceType ?? "user",
1133
+ metadataRow.referenceId,
1134
+ projected.group === void 0 ? metadataRow.group : projected.group
1135
+ )
1136
+ }
1137
+ };
1138
+ const updated = await ctx.context.adapter.update({
1139
+ model: SUBSCRIPTION_MODEL2,
1140
+ update: projectedWithSlot,
1141
+ where: [{ field: "id", value: metadataRow.id }]
1142
+ });
1143
+ return { row: updated ?? { ...metadataRow, ...projectedWithSlot }, stream };
1144
+ }
1145
+ if (metadataRow) {
1146
+ logger(ctx).warn(
1147
+ `webhook ${payload.event_type}: ignored unsafe subscription row correlation for row=${localRowId}.`
1148
+ );
1149
+ throw new SubscriptionCorrelationError(
1150
+ `Webhook ${payload.event_type} failed protected subscription correlation for row=${localRowId}.`
1151
+ );
1152
+ }
1153
+ }
1154
+ const incomplete = await findIncompleteRow(
1155
+ ctx,
1156
+ referenceId,
1157
+ metadataReferenceType,
1158
+ planName,
1159
+ paymentLinkId
1160
+ );
776
1161
  if (incomplete) {
1162
+ const projectedWithSlot = {
1163
+ ...projected,
1164
+ billingStatus: incomplete.billingStatus ?? "current",
1165
+ ...projected.activeSlotKey === null ? {} : {
1166
+ activeSlotKey: incomplete.activeSlotKey ?? subscriptionSlotKey(
1167
+ incomplete.referenceType ?? metadataReferenceType ?? "user",
1168
+ incomplete.referenceId,
1169
+ projected.group === void 0 ? incomplete.group : projected.group
1170
+ )
1171
+ }
1172
+ };
777
1173
  const updated = await ctx.context.adapter.update({
778
- model: SUBSCRIPTION_MODEL,
779
- update: projected,
1174
+ model: SUBSCRIPTION_MODEL2,
1175
+ update: projectedWithSlot,
780
1176
  where: [{ field: "id", value: incomplete.id }]
781
1177
  });
782
1178
  return {
783
- row: updated ?? { ...incomplete, ...projected },
1179
+ row: updated ?? { ...incomplete, ...projectedWithSlot },
784
1180
  stream
785
1181
  };
786
1182
  }
787
1183
  const plan = plans.byName.get(planName);
1184
+ const referenceType = metadataReferenceType ?? "custom";
788
1185
  const row = await ctx.context.adapter.create({
789
- model: SUBSCRIPTION_MODEL,
1186
+ model: SUBSCRIPTION_MODEL2,
790
1187
  data: {
1188
+ cancelScheduledAt: null,
1189
+ canceledAt: null,
791
1190
  ...projected,
792
1191
  referenceId,
1192
+ referenceType,
1193
+ activeSlotKey: isTerminalSubscriptionStatus(projected.status) ? null : subscriptionSlotKey(referenceType, referenceId, plan?.group),
1194
+ streampayPaymentLinkId: paymentLinkId,
793
1195
  plan: planName,
1196
+ planVersion: plan?.version ?? null,
1197
+ productId: plan?.productId ?? subscriptionItemProductId(stream.items?.[0]),
794
1198
  group: plan?.group ?? null,
1199
+ billingStatus: "current",
795
1200
  createdAt: /* @__PURE__ */ new Date()
796
1201
  }
797
1202
  });
798
1203
  return { row, stream };
799
1204
  }
800
- var SubscriptionItemSchema = zod.z.object({
801
- product: zod.z.object({ id: zod.z.string() }).passthrough().optional(),
802
- product_id: zod.z.string().optional()
803
- }).passthrough();
804
- function subscriptionItemProductId(item) {
805
- const parsed = SubscriptionItemSchema.safeParse(item);
806
- if (!parsed.success) return null;
807
- return parsed.data.product?.id ?? parsed.data.product_id ?? null;
808
- }
809
- function inferPlanFromItems(sub, plans) {
810
- const first = Array.isArray(sub.items) ? sub.items[0] : void 0;
811
- const productId = subscriptionItemProductId(first);
812
- if (!productId) return null;
813
- return plans.list.find((plan) => plan.productId === productId)?.name ?? null;
814
- }
815
1205
  async function syncWebhookPayload(ctx, payload, client, plans, callbacks, options = {}) {
816
1206
  if (payload.entity_type !== "SUBSCRIPTION" && payload.event_type !== "INVOICE_COMPLETED") {
817
1207
  return;
@@ -820,6 +1210,7 @@ async function syncWebhookPayload(ctx, payload, client, plans, callbacks, option
820
1210
  const rawBody = options.rawBody ?? null;
821
1211
  const signatureHeader = options.signatureHeader ?? null;
822
1212
  const maxAttempts = Math.max(1, options.maxAttempts ?? DEFAULT_MAX_WEBHOOK_ATTEMPTS);
1213
+ const retryOnCallbackError = options.retryOnCallbackError !== false;
823
1214
  let claim = { action: "process", row: null };
824
1215
  if (dedupe) {
825
1216
  claim = await claimOrAdvanceWebhookEvent(ctx, payload, rawBody, signatureHeader, maxAttempts);
@@ -832,9 +1223,20 @@ async function syncWebhookPayload(ctx, payload, client, plans, callbacks, option
832
1223
  }
833
1224
  }
834
1225
  const trackedRowId = claim.row?.id ?? null;
1226
+ const trackedLockId = claim.row?.lockedBy ?? void 0;
835
1227
  try {
836
1228
  if (payload.event_type === "INVOICE_COMPLETED") {
837
- await handleInvoiceCompleted(ctx, payload, client, plans, callbacks);
1229
+ await handleInvoiceCompleted(
1230
+ ctx,
1231
+ payload,
1232
+ client,
1233
+ plans,
1234
+ callbacks,
1235
+ retryOnCallbackError,
1236
+ options.retryingRenewalCallback === true || claim.row?.lastError?.startsWith(
1237
+ "Subscription callback onSubscriptionRenewed failed:"
1238
+ ) === true
1239
+ );
838
1240
  } else {
839
1241
  const { row, stream } = await reconcileFromStreamPay(ctx, payload, client, plans);
840
1242
  if (row) {
@@ -845,18 +1247,27 @@ async function syncWebhookPayload(ctx, payload, client, plans, callbacks, option
845
1247
  user,
846
1248
  event: payload
847
1249
  };
848
- await dispatchSubscriptionCallback(ctx, payload, data, callbacks);
1250
+ await dispatchSubscriptionCallback(ctx, payload, data, callbacks, retryOnCallbackError);
849
1251
  }
850
1252
  }
851
- if (trackedRowId) await markWebhookEventCompleted(ctx, trackedRowId);
1253
+ if (trackedRowId) await markWebhookEventCompleted(ctx, trackedRowId, trackedLockId);
852
1254
  } catch (err) {
853
1255
  if (trackedRowId) {
854
- await recordWebhookEventFailure(ctx, trackedRowId, rawBody, signatureHeader, err);
1256
+ const deadLetter = classifyWebhookFailure(err) === "PERMANENT" || (claim.row?.attemptCount ?? 0) >= maxAttempts;
1257
+ await recordWebhookEventFailure(
1258
+ ctx,
1259
+ trackedRowId,
1260
+ rawBody,
1261
+ signatureHeader,
1262
+ err,
1263
+ trackedLockId,
1264
+ deadLetter
1265
+ );
855
1266
  }
856
1267
  throw err;
857
1268
  }
858
1269
  }
859
- async function handleInvoiceCompleted(ctx, payload, client, _plans, callbacks) {
1270
+ async function handleInvoiceCompleted(ctx, payload, client, plans, callbacks, retryOnCallbackError, retryingRenewalCallback) {
860
1271
  const invoiceId = payload.data?.invoice?.id ?? payload.entity_id;
861
1272
  if (!invoiceId) return;
862
1273
  let subscriptionId = null;
@@ -882,46 +1293,172 @@ async function handleInvoiceCompleted(ctx, payload, client, _plans, callbacks) {
882
1293
  }
883
1294
  const existing = await findSubscriptionByStreampayId(ctx, subscriptionId);
884
1295
  if (!existing) return;
885
- const projected = projectSubscriptionFields(stream);
1296
+ const eventAt = parseDate(payload.timestamp);
1297
+ const eventIsStale = Boolean(
1298
+ eventAt && existing.providerUpdatedAt instanceof Date && eventAt.getTime() < existing.providerUpdatedAt.getTime()
1299
+ );
1300
+ const projected = {
1301
+ ...projectSubscriptionFields(stream),
1302
+ ...projectPlanFields(stream, plans),
1303
+ ...eventIsStale ? existing.billingStatus === "past_due" && toLocalStatus(stream.status) === "active" ? { status: "past_due", billingStatus: "past_due" } : {} : { billingStatus: "current" }
1304
+ };
1305
+ const previousPeriodEnd = existing.periodEnd?.getTime() ?? null;
1306
+ const projectedPeriodEnd = projected.periodEnd?.getTime() ?? null;
1307
+ const periodAdvanced = previousPeriodEnd !== null && projectedPeriodEnd !== null && projectedPeriodEnd > previousPeriodEnd;
1308
+ const cycleAdvanced = existing.currentCycleNumber !== null && existing.currentCycleNumber !== void 0 && projected.currentCycleNumber !== null && projected.currentCycleNumber !== void 0 && projected.currentCycleNumber > existing.currentCycleNumber;
886
1309
  const updated = await ctx.context.adapter.update({
887
- model: SUBSCRIPTION_MODEL,
1310
+ model: SUBSCRIPTION_MODEL2,
888
1311
  update: projected,
889
1312
  where: [{ field: "id", value: existing.id }]
890
1313
  });
891
1314
  const row = updated ?? { ...existing, ...projected };
892
1315
  const user = await resolveRowUser(ctx, row);
893
- await fireCallback(
894
- ctx,
895
- callbacks.onSubscriptionRenewed,
896
- { subscription: row, streampaySubscription: stream, user, event: payload },
897
- "onSubscriptionRenewed"
898
- );
1316
+ if (!eventIsStale && (periodAdvanced || cycleAdvanced || retryingRenewalCallback)) {
1317
+ await fireCallback(
1318
+ ctx,
1319
+ callbacks.onSubscriptionRenewed,
1320
+ { subscription: row, streampaySubscription: stream, user, event: payload },
1321
+ "onSubscriptionRenewed",
1322
+ retryOnCallbackError
1323
+ );
1324
+ }
899
1325
  }
900
- async function dispatchSubscriptionCallback(ctx, payload, data, callbacks) {
1326
+ async function dispatchSubscriptionCallback(ctx, payload, data, callbacks, retryOnCallbackError) {
901
1327
  switch (payload.event_type) {
902
1328
  case "SUBSCRIPTION_CREATED":
903
- await fireCallback(ctx, callbacks.onSubscriptionCreated, data, "onSubscriptionCreated");
1329
+ await fireCallback(
1330
+ ctx,
1331
+ callbacks.onSubscriptionCreated,
1332
+ data,
1333
+ "onSubscriptionCreated",
1334
+ retryOnCallbackError
1335
+ );
904
1336
  return;
905
1337
  case "SUBSCRIPTION_ACTIVATED":
906
- await fireCallback(ctx, callbacks.onSubscriptionActivated, data, "onSubscriptionActivated");
907
- return;
908
- case "SUBSCRIPTION_CANCELED":
909
- await fireCallback(ctx, callbacks.onSubscriptionCanceled, data, "onSubscriptionCanceled");
1338
+ await fireCallback(
1339
+ ctx,
1340
+ callbacks.onSubscriptionActivated,
1341
+ data,
1342
+ "onSubscriptionActivated",
1343
+ retryOnCallbackError
1344
+ );
1345
+ return;
1346
+ case "SUBSCRIPTION_CANCELED":
1347
+ await fireCallback(
1348
+ ctx,
1349
+ callbacks.onSubscriptionCanceled,
1350
+ data,
1351
+ "onSubscriptionCanceled",
1352
+ retryOnCallbackError
1353
+ );
1354
+ return;
1355
+ case "SUBSCRIPTION_INACTIVATED":
1356
+ await fireCallback(
1357
+ ctx,
1358
+ callbacks.onSubscriptionInactivated,
1359
+ data,
1360
+ "onSubscriptionInactivated",
1361
+ retryOnCallbackError
1362
+ );
1363
+ return;
1364
+ case "SUBSCRIPTION_CANCEL_AT_PERIOD_END":
1365
+ await fireCallback(
1366
+ ctx,
1367
+ callbacks.onSubscriptionCancelScheduled,
1368
+ data,
1369
+ "onSubscriptionCancelScheduled",
1370
+ retryOnCallbackError
1371
+ );
910
1372
  return;
911
1373
  case "SUBSCRIPTION_FROZEN":
912
1374
  case "SUBSCRIPTION_FREEZE_NOW":
913
- await fireCallback(ctx, callbacks.onSubscriptionFrozen, data, "onSubscriptionFrozen");
1375
+ await fireCallback(
1376
+ ctx,
1377
+ callbacks.onSubscriptionFrozen,
1378
+ data,
1379
+ "onSubscriptionFrozen",
1380
+ retryOnCallbackError
1381
+ );
914
1382
  return;
915
1383
  case "SUBSCRIPTION_UNFREEZE_NOW":
1384
+ await fireCallback(
1385
+ ctx,
1386
+ callbacks.onSubscriptionResumed,
1387
+ data,
1388
+ "onSubscriptionResumed",
1389
+ retryOnCallbackError
1390
+ );
1391
+ return;
1392
+ case "SUBSCRIPTION_UNFREEZE_FUTURE":
1393
+ await fireCallback(
1394
+ ctx,
1395
+ callbacks.onSubscriptionUnfreezeScheduled,
1396
+ data,
1397
+ "onSubscriptionUnfreezeScheduled",
1398
+ retryOnCallbackError
1399
+ );
1400
+ return;
916
1401
  case "SUBSCRIPTION_FREEZE_CANCEL":
917
- await fireCallback(ctx, callbacks.onSubscriptionResumed, data, "onSubscriptionResumed");
1402
+ await fireCallback(
1403
+ ctx,
1404
+ callbacks.onSubscriptionFreezeCanceled,
1405
+ data,
1406
+ "onSubscriptionFreezeCanceled",
1407
+ retryOnCallbackError
1408
+ );
918
1409
  return;
919
1410
  case "SUBSCRIPTION_CYCLE_RENEWAL_FAILED":
920
1411
  await fireCallback(
921
1412
  ctx,
922
1413
  callbacks.onSubscriptionPaymentFailed,
923
1414
  data,
924
- "onSubscriptionPaymentFailed"
1415
+ "onSubscriptionPaymentFailed",
1416
+ retryOnCallbackError
1417
+ );
1418
+ return;
1419
+ case "SUBSCRIPTION_PLAN_CHANGE_SCHEDULED":
1420
+ await fireCallback(
1421
+ ctx,
1422
+ callbacks.onSubscriptionPlanChangeScheduled,
1423
+ data,
1424
+ "onSubscriptionPlanChangeScheduled",
1425
+ retryOnCallbackError
1426
+ );
1427
+ return;
1428
+ case "SUBSCRIPTION_PLAN_CHANGE_CANCELED":
1429
+ await fireCallback(
1430
+ ctx,
1431
+ callbacks.onSubscriptionPlanChangeCanceled,
1432
+ data,
1433
+ "onSubscriptionPlanChangeCanceled",
1434
+ retryOnCallbackError
1435
+ );
1436
+ return;
1437
+ case "SUBSCRIPTION_PLAN_CHANGED":
1438
+ await fireCallback(
1439
+ ctx,
1440
+ callbacks.onSubscriptionPlanChanged,
1441
+ data,
1442
+ "onSubscriptionPlanChanged",
1443
+ retryOnCallbackError
1444
+ );
1445
+ return;
1446
+ case "SUBSCRIPTION_PLAN_CHANGE_INVOICE_REISSUED":
1447
+ await fireCallback(
1448
+ ctx,
1449
+ callbacks.onSubscriptionPlanChangeInvoiceReissued,
1450
+ data,
1451
+ "onSubscriptionPlanChangeInvoiceReissued",
1452
+ retryOnCallbackError
1453
+ );
1454
+ return;
1455
+ case "SUBSCRIPTION_PLAN_UPDATED":
1456
+ await fireCallback(
1457
+ ctx,
1458
+ callbacks.onSubscriptionPlanUpdated,
1459
+ data,
1460
+ "onSubscriptionPlanUpdated",
1461
+ retryOnCallbackError
925
1462
  );
926
1463
  return;
927
1464
  default:
@@ -929,6 +1466,7 @@ async function dispatchSubscriptionCallback(ctx, payload, data, callbacks) {
929
1466
  }
930
1467
  }
931
1468
  function classifyWebhookFailure(err) {
1469
+ if (err instanceof SubscriptionCorrelationError) return "PERMANENT";
932
1470
  const { status } = readSdkErrorFields(err);
933
1471
  if (status === void 0) return "TRANSIENT";
934
1472
  if (status === 404 || status === 429) return "TRANSIENT";
@@ -972,7 +1510,12 @@ function getAdapter(ctx) {
972
1510
  }
973
1511
  return adapter;
974
1512
  }
975
- var ForwardedBody = zod.z.object({}).passthrough();
1513
+ function forwardedBody() {
1514
+ return zod.z.custom(
1515
+ (value) => value !== null && typeof value === "object" && !Array.isArray(value),
1516
+ "Expected an object body."
1517
+ );
1518
+ }
976
1519
  var PaymentsListQuery = zod.z.object({
977
1520
  page: zod.z.coerce.number().int().positive().optional(),
978
1521
  size: zod.z.coerce.number().int().positive().max(100).optional(),
@@ -993,7 +1536,7 @@ function buildPaymentsEndpoints(client, adminOptions) {
993
1536
  "/admin/streampay/payments/:id/refund",
994
1537
  {
995
1538
  method: "POST",
996
- body: ForwardedBody,
1539
+ body: forwardedBody(),
997
1540
  use: [api.sessionMiddleware]
998
1541
  },
999
1542
  async (ctx) => {
@@ -1067,7 +1610,7 @@ function buildSubscriptionsEndpoints(client, adminOptions) {
1067
1610
  "/admin/streampay/subscriptions",
1068
1611
  {
1069
1612
  method: "POST",
1070
- body: ForwardedBody,
1613
+ body: forwardedBody(),
1071
1614
  use: [api.sessionMiddleware]
1072
1615
  },
1073
1616
  async (ctx) => {
@@ -1085,7 +1628,7 @@ function buildSubscriptionsEndpoints(client, adminOptions) {
1085
1628
  "/admin/streampay/subscriptions/:id",
1086
1629
  {
1087
1630
  method: "PATCH",
1088
- body: ForwardedBody,
1631
+ body: forwardedBody(),
1089
1632
  use: [api.sessionMiddleware]
1090
1633
  },
1091
1634
  async (ctx) => {
@@ -1167,7 +1710,7 @@ function buildSubscriptionsEndpoints(client, adminOptions) {
1167
1710
  "/admin/streampay/subscriptions/:id/cancel",
1168
1711
  {
1169
1712
  method: "POST",
1170
- body: ForwardedBody,
1713
+ body: forwardedBody(),
1171
1714
  use: [api.sessionMiddleware]
1172
1715
  },
1173
1716
  async (ctx) => {
@@ -1199,7 +1742,7 @@ function buildSubscriptionsEndpoints(client, adminOptions) {
1199
1742
  "/admin/streampay/subscriptions/:id/freeze",
1200
1743
  {
1201
1744
  method: "POST",
1202
- body: ForwardedBody,
1745
+ body: forwardedBody(),
1203
1746
  use: [api.sessionMiddleware]
1204
1747
  },
1205
1748
  async (ctx) => {
@@ -1252,7 +1795,7 @@ function buildSubscriptionsEndpoints(client, adminOptions) {
1252
1795
  "/admin/streampay/subscriptions/:id/freeze/:freezeId",
1253
1796
  {
1254
1797
  method: "PUT",
1255
- body: ForwardedBody,
1798
+ body: forwardedBody(),
1256
1799
  use: [api.sessionMiddleware]
1257
1800
  },
1258
1801
  async (ctx) => {
@@ -1362,7 +1905,7 @@ function buildConsumersEndpoints(client, adminOptions) {
1362
1905
  "/admin/streampay/consumers/:id",
1363
1906
  {
1364
1907
  method: "PATCH",
1365
- body: ForwardedBody,
1908
+ body: forwardedBody(),
1366
1909
  use: [api.sessionMiddleware]
1367
1910
  },
1368
1911
  async (ctx) => {
@@ -1481,7 +2024,7 @@ function buildProductsEndpoints(client, adminOptions) {
1481
2024
  "/admin/streampay/products",
1482
2025
  {
1483
2026
  method: "POST",
1484
- body: ForwardedBody,
2027
+ body: forwardedBody(),
1485
2028
  use: [api.sessionMiddleware]
1486
2029
  },
1487
2030
  async (ctx) => {
@@ -1539,7 +2082,7 @@ function buildProductsEndpoints(client, adminOptions) {
1539
2082
  "/admin/streampay/products/:id",
1540
2083
  {
1541
2084
  method: "PUT",
1542
- body: ForwardedBody,
2085
+ body: forwardedBody(),
1543
2086
  use: [api.sessionMiddleware]
1544
2087
  },
1545
2088
  async (ctx) => {
@@ -1587,7 +2130,7 @@ function buildCouponsEndpoints(client, adminOptions) {
1587
2130
  "/admin/streampay/coupons",
1588
2131
  {
1589
2132
  method: "POST",
1590
- body: ForwardedBody,
2133
+ body: forwardedBody(),
1591
2134
  use: [api.sessionMiddleware]
1592
2135
  },
1593
2136
  async (ctx) => {
@@ -1645,7 +2188,7 @@ function buildCouponsEndpoints(client, adminOptions) {
1645
2188
  "/admin/streampay/coupons/:id",
1646
2189
  {
1647
2190
  method: "PUT",
1648
- body: ForwardedBody,
2191
+ body: forwardedBody(),
1649
2192
  use: [api.sessionMiddleware]
1650
2193
  },
1651
2194
  async (ctx) => {
@@ -1756,7 +2299,7 @@ function buildWebhookEventsEndpoints(adminOptions, registry) {
1756
2299
  ...where.length > 0 ? { where } : {},
1757
2300
  limit: size,
1758
2301
  offset: (page - 1) * size,
1759
- sortBy: { field: "processedAt", direction: "desc" }
2302
+ sortBy: { field: "receivedAt", direction: "desc" }
1760
2303
  }),
1761
2304
  adapter.count({
1762
2305
  model: WEBHOOK_EVENT_MODEL,
@@ -1859,15 +2402,15 @@ var admin = (adminOptions = {}) => (options, registry) => {
1859
2402
  var RelativeOrAbsoluteUrl = zod.z.string().refine((val) => val.startsWith("/") || URL.canParse(val), {
1860
2403
  message: "Must be a valid URL or a relative path starting with /"
1861
2404
  });
1862
- var CheckoutBody = zod.z.object({
2405
+ var CheckoutRequestBody = zod.z.object({
1863
2406
  products: zod.z.union([
1864
2407
  zod.z.array(
1865
2408
  zod.z.object({
1866
2409
  productId: zod.z.string().uuid(),
1867
2410
  quantity: zod.z.number().int().positive().optional()
1868
2411
  })
1869
- ).nonempty("`products` must contain at least one item."),
1870
- zod.z.array(zod.z.string().uuid()).nonempty("`products` must contain at least one item."),
2412
+ ).min(1, "`products` must contain at least one item."),
2413
+ zod.z.array(zod.z.string().uuid()).min(1, "`products` must contain at least one item."),
1871
2414
  zod.z.string().uuid()
1872
2415
  ]).optional(),
1873
2416
  slug: zod.z.string().optional(),
@@ -1881,10 +2424,26 @@ var CheckoutBody = zod.z.object({
1881
2424
  validUntil: zod.z.string().datetime().optional(),
1882
2425
  couponIds: zod.z.array(zod.z.string().uuid()).optional(),
1883
2426
  redirect: zod.z.coerce.boolean().optional()
1884
- }).refine((data) => data.slug !== void 0 || data.products !== void 0, {
1885
- message: "Either `slug` or `products` is required.",
1886
- path: ["products"]
1887
2427
  });
2428
+ var CheckoutBody = CheckoutRequestBody.refine(
2429
+ (data) => data.slug !== void 0 || data.products !== void 0,
2430
+ {
2431
+ message: "Either `slug` or `products` is required.",
2432
+ path: ["products"]
2433
+ }
2434
+ );
2435
+ var SERVER_ONLY_CHECKOUT_FIELDS = [
2436
+ "products",
2437
+ "slug",
2438
+ "name",
2439
+ "description",
2440
+ "metadata",
2441
+ "successUrl",
2442
+ "failureUrl",
2443
+ "maxNumberOfPayments",
2444
+ "validUntil",
2445
+ "couponIds"
2446
+ ];
1888
2447
  function buildItem(productId, quantity) {
1889
2448
  return {
1890
2449
  product_id: productId,
@@ -1909,6 +2468,69 @@ async function resolveProducts(body, options) {
1909
2468
  (entry) => typeof entry === "string" ? buildItem(entry, 1) : buildItem(entry.productId, entry.quantity ?? 1)
1910
2469
  );
1911
2470
  }
2471
+ function rejectUntrustedClientFields(body) {
2472
+ const supplied = SERVER_ONLY_CHECKOUT_FIELDS.filter(
2473
+ (field) => Object.hasOwn(body, field) && body[field] !== void 0
2474
+ );
2475
+ if (supplied.length === 0) return;
2476
+ throw new api.APIError("BAD_REQUEST", {
2477
+ code: "CHECKOUT_CLIENT_FIELDS_FORBIDDEN",
2478
+ message: "Checkout product and payment fields must be resolved by the server."
2479
+ });
2480
+ }
2481
+ function mergeCheckoutOverrides(body, overrides) {
2482
+ const effective = { ...body };
2483
+ if (overrides.products !== void 0) {
2484
+ effective.products = overrides.products;
2485
+ delete effective.slug;
2486
+ }
2487
+ if (overrides.name !== void 0) effective.name = overrides.name;
2488
+ if (overrides.description !== void 0) effective.description = overrides.description;
2489
+ if (overrides.successUrl !== void 0) effective.successUrl = overrides.successUrl;
2490
+ if (overrides.failureUrl !== void 0) effective.failureUrl = overrides.failureUrl;
2491
+ if (overrides.maxNumberOfPayments !== void 0) {
2492
+ effective.maxNumberOfPayments = overrides.maxNumberOfPayments;
2493
+ }
2494
+ if (overrides.validUntil !== void 0) effective.validUntil = overrides.validUntil;
2495
+ if (overrides.couponIds !== void 0) effective.couponIds = overrides.couponIds;
2496
+ if (overrides.referenceId !== void 0) effective.referenceId = overrides.referenceId;
2497
+ if (overrides.metadata !== void 0) {
2498
+ effective.metadata = { ...body.metadata ?? {}, ...overrides.metadata };
2499
+ }
2500
+ return effective;
2501
+ }
2502
+ function validateEffectiveCheckout(body, logger2) {
2503
+ const parsed = CheckoutBody.safeParse(body);
2504
+ if (parsed.success) return parsed.data;
2505
+ const invalidPaths = [
2506
+ ...new Set(
2507
+ parsed.error.issues.map((issue) => issue.path.length > 0 ? issue.path.join(".") : "<root>")
2508
+ )
2509
+ ].join(", ");
2510
+ logger2.error(`resolved checkout validation failed at: ${invalidPaths}`);
2511
+ throw new api.APIError("INTERNAL_SERVER_ERROR", {
2512
+ message: "Checkout resolution produced invalid parameters."
2513
+ });
2514
+ }
2515
+ function checkoutUser(rawUser, user) {
2516
+ if (!user || rawUser === null || typeof rawUser !== "object") return null;
2517
+ return { ...rawUser, ...user };
2518
+ }
2519
+ async function deactivatePaymentLinkBestEffort(client, paymentLinkId, logger2) {
2520
+ if (!client.updatePaymentLinkStatus) {
2521
+ logger2.error(
2522
+ `checkout compensation unavailable for payment_link=${paymentLinkId}: client does not implement updatePaymentLinkStatus`
2523
+ );
2524
+ return;
2525
+ }
2526
+ try {
2527
+ await client.updatePaymentLinkStatus(paymentLinkId, { status: "INACTIVE" });
2528
+ } catch (err) {
2529
+ logger2.error(
2530
+ `checkout compensation failed for payment_link=${paymentLinkId}: ${formatStreamPayError(err)}`
2531
+ );
2532
+ }
2533
+ }
1912
2534
  function resolveRedirectUrl(urlOrPath, request, baseURL) {
1913
2535
  if (!urlOrPath) return void 0;
1914
2536
  return new URL(urlOrPath, request?.url ?? baseURL).toString();
@@ -1918,98 +2540,157 @@ async function resolveConsumerId(options, ctx, user) {
1918
2540
  const { consumerId } = await ensureConsumerForUser(options, ctx, user);
1919
2541
  return consumerId;
1920
2542
  }
1921
- var checkout = (checkoutOptions = {}) => (options) => {
1922
- const client = options.client;
1923
- return {
1924
- endpoints: {
1925
- checkout: api.createAuthEndpoint(
1926
- "/checkout",
1927
- {
1928
- method: "POST",
1929
- body: CheckoutBody
1930
- },
1931
- async (ctx) => {
1932
- const session = await api.getSessionFromCtx(ctx);
1933
- const sessionUser = asSessionUser(session?.user);
1934
- if (checkoutOptions.authenticatedUsersOnly) {
1935
- if (!sessionUser) {
1936
- throw new api.APIError("UNAUTHORIZED", {
1937
- message: "You must be logged in to checkout."
1938
- });
2543
+ var checkout = (checkoutOptions = {}) => {
2544
+ return (options) => {
2545
+ const client = options.client;
2546
+ return {
2547
+ endpoints: {
2548
+ checkout: api.createAuthEndpoint(
2549
+ "/checkout",
2550
+ {
2551
+ method: "POST",
2552
+ body: checkoutOptions.resolveCheckout ? CheckoutRequestBody : CheckoutBody
2553
+ },
2554
+ async (ctx) => {
2555
+ const session = await api.getSessionFromCtx(ctx);
2556
+ const sessionUser = asSessionUser(session?.user);
2557
+ const user = checkoutUser(session?.user, sessionUser);
2558
+ if (checkoutOptions.authenticatedUsersOnly) {
2559
+ if (!sessionUser) {
2560
+ throw new api.APIError("UNAUTHORIZED", {
2561
+ message: "You must be logged in to checkout."
2562
+ });
2563
+ }
2564
+ if (sessionUser.isAnonymous) {
2565
+ throw new api.APIError("UNAUTHORIZED", {
2566
+ message: "Anonymous users cannot checkout."
2567
+ });
2568
+ }
1939
2569
  }
1940
- if (sessionUser.isAnonymous) {
1941
- throw new api.APIError("UNAUTHORIZED", {
1942
- message: "Anonymous users cannot checkout."
1943
- });
2570
+ if (checkoutOptions.resolveCheckout) {
2571
+ rejectUntrustedClientFields(ctx.body);
1944
2572
  }
1945
- }
1946
- const items = await resolveProducts(ctx.body, checkoutOptions);
1947
- const consumerId = await resolveConsumerId(options, ctx, sessionUser);
1948
- const successUrl = resolveRedirectUrl(
1949
- ctx.body.successUrl ?? checkoutOptions.successUrl,
1950
- ctx.request,
1951
- ctx.context.baseURL
1952
- );
1953
- const failureUrl = resolveRedirectUrl(
1954
- ctx.body.failureUrl ?? checkoutOptions.failureUrl,
1955
- ctx.request,
1956
- ctx.context.baseURL
1957
- );
1958
- const customMetadata = (() => {
1959
- const base = ctx.body.metadata ?? {};
1960
- const merged = ctx.body.referenceId ? { referenceId: ctx.body.referenceId, ...base } : base;
1961
- return Object.keys(merged).length > 0 ? merged : null;
1962
- })();
1963
- const payload = {
1964
- name: ctx.body.name ?? `Checkout ${(/* @__PURE__ */ new Date()).toISOString()}`,
1965
- description: ctx.body.description ?? null,
1966
- items
1967
- };
1968
- if (consumerId !== null) payload.organization_consumer_id = consumerId;
1969
- if (successUrl) payload.success_redirect_url = successUrl;
1970
- if (failureUrl) payload.failure_redirect_url = failureUrl;
1971
- if (ctx.body.maxNumberOfPayments !== void 0) {
1972
- payload.max_number_of_payments = ctx.body.maxNumberOfPayments;
1973
- }
1974
- if (ctx.body.validUntil !== void 0) {
1975
- payload.valid_until = ctx.body.validUntil;
1976
- }
1977
- if (ctx.body.couponIds && ctx.body.couponIds.length > 0) {
1978
- payload.coupons = ctx.body.couponIds;
1979
- }
1980
- if (customMetadata !== null) payload.custom_metadata = customMetadata;
1981
- if (checkoutOptions.customFields) {
1982
- payload.custom_fields = checkoutOptions.customFields;
1983
- }
1984
- if (checkoutOptions.contactInformationType) {
1985
- payload.contact_information_type = checkoutOptions.contactInformationType;
1986
- }
1987
- try {
1988
- const link = await client.createPaymentLink(payload);
1989
- const url = client.getPaymentUrl(link);
1990
- if (!url) {
1991
- throw new api.APIError("INTERNAL_SERVER_ERROR", {
1992
- message: "StreamPay payment link created but no URL was returned."
1993
- });
2573
+ let effective = ctx.body;
2574
+ if (checkoutOptions.resolveCheckout) {
2575
+ let overrides;
2576
+ try {
2577
+ overrides = await checkoutOptions.resolveCheckout({ user, body: ctx.body }, ctx);
2578
+ } catch (err) {
2579
+ if (err instanceof api.APIError) throw err;
2580
+ getLogger(ctx).error(`resolveCheckout failed: ${formatStreamPayError(err)}`);
2581
+ throw new api.APIError("INTERNAL_SERVER_ERROR", {
2582
+ message: "Checkout resolution failed."
2583
+ });
2584
+ }
2585
+ effective = mergeCheckoutOverrides(ctx.body, overrides);
1994
2586
  }
1995
- return ctx.json({
1996
- url,
1997
- id: link.id ?? null,
1998
- redirect: ctx.body.redirect ?? true
1999
- });
2000
- } catch (err) {
2001
- toAPIError(
2002
- {
2003
- logPrefix: "checkout creation failed:",
2004
- userMessage: "StreamPay checkout creation failed."
2005
- },
2006
- err,
2007
- getLogger(ctx)
2587
+ effective = validateEffectiveCheckout(effective, getLogger(ctx));
2588
+ const items = await resolveProducts(effective, checkoutOptions);
2589
+ const consumerId = await resolveConsumerId(options, ctx, sessionUser);
2590
+ const successUrl = resolveRedirectUrl(
2591
+ effective.successUrl ?? checkoutOptions.successUrl,
2592
+ ctx.request,
2593
+ ctx.context.baseURL
2008
2594
  );
2595
+ const failureUrl = resolveRedirectUrl(
2596
+ effective.failureUrl ?? checkoutOptions.failureUrl,
2597
+ ctx.request,
2598
+ ctx.context.baseURL
2599
+ );
2600
+ const customMetadata = (() => {
2601
+ const merged = { ...effective.metadata ?? {} };
2602
+ if (effective.referenceId !== void 0) {
2603
+ merged.referenceId = effective.referenceId;
2604
+ }
2605
+ return Object.keys(merged).length > 0 ? merged : null;
2606
+ })();
2607
+ const payload = {
2608
+ name: effective.name ?? `Checkout ${(/* @__PURE__ */ new Date()).toISOString()}`,
2609
+ description: effective.description ?? null,
2610
+ currency: checkoutOptions.currency ?? "SAR",
2611
+ items
2612
+ };
2613
+ if (consumerId !== null) payload.organization_consumer_id = consumerId;
2614
+ if (successUrl) payload.success_redirect_url = successUrl;
2615
+ if (failureUrl) payload.failure_redirect_url = failureUrl;
2616
+ if (effective.maxNumberOfPayments !== void 0) {
2617
+ payload.max_number_of_payments = effective.maxNumberOfPayments;
2618
+ }
2619
+ if (effective.validUntil !== void 0) {
2620
+ payload.valid_until = effective.validUntil;
2621
+ }
2622
+ if (effective.couponIds && effective.couponIds.length > 0) {
2623
+ payload.coupons = effective.couponIds;
2624
+ }
2625
+ if (customMetadata !== null) payload.custom_metadata = customMetadata;
2626
+ if (checkoutOptions.customFields) {
2627
+ payload.custom_fields = checkoutOptions.customFields;
2628
+ }
2629
+ if (checkoutOptions.contactInformationType) {
2630
+ payload.contact_information_type = checkoutOptions.contactInformationType;
2631
+ }
2632
+ try {
2633
+ const link = await client.createPaymentLink(payload);
2634
+ const paymentLinkId = typeof link.id === "string" && link.id.length > 0 ? link.id : null;
2635
+ let url;
2636
+ try {
2637
+ const resolvedUrl = client.getPaymentUrl(link);
2638
+ if (!resolvedUrl) {
2639
+ throw new api.APIError("INTERNAL_SERVER_ERROR", {
2640
+ message: "StreamPay payment link created but no URL was returned."
2641
+ });
2642
+ }
2643
+ url = resolvedUrl;
2644
+ if (checkoutOptions.onCheckoutCreated) {
2645
+ if (!paymentLinkId) {
2646
+ throw new api.APIError("INTERNAL_SERVER_ERROR", {
2647
+ message: "StreamPay payment link created but no id was returned."
2648
+ });
2649
+ }
2650
+ try {
2651
+ const callbackData = {
2652
+ user,
2653
+ paymentLinkId,
2654
+ url,
2655
+ payload
2656
+ };
2657
+ if (effective.referenceId !== void 0) {
2658
+ callbackData.referenceId = effective.referenceId;
2659
+ }
2660
+ await checkoutOptions.onCheckoutCreated(callbackData, ctx);
2661
+ } catch (err) {
2662
+ if (err instanceof api.APIError) throw err;
2663
+ getLogger(ctx).error(`onCheckoutCreated failed: ${formatStreamPayError(err)}`);
2664
+ throw new api.APIError("INTERNAL_SERVER_ERROR", {
2665
+ message: "Checkout persistence failed."
2666
+ });
2667
+ }
2668
+ }
2669
+ } catch (err) {
2670
+ if (paymentLinkId) {
2671
+ await deactivatePaymentLinkBestEffort(client, paymentLinkId, getLogger(ctx));
2672
+ }
2673
+ throw err;
2674
+ }
2675
+ return ctx.json({
2676
+ url,
2677
+ id: paymentLinkId,
2678
+ redirect: ctx.body.redirect ?? true
2679
+ });
2680
+ } catch (err) {
2681
+ toAPIError(
2682
+ {
2683
+ logPrefix: "checkout creation failed:",
2684
+ userMessage: "StreamPay checkout creation failed."
2685
+ },
2686
+ err,
2687
+ getLogger(ctx)
2688
+ );
2689
+ }
2009
2690
  }
2010
- }
2011
- )
2012
- }
2691
+ )
2692
+ }
2693
+ };
2013
2694
  };
2014
2695
  };
2015
2696
  var DEFAULT_PAGE_SIZE = 100;
@@ -2083,32 +2764,329 @@ function clampPageSize(size) {
2083
2764
  if (!size || !Number.isFinite(size) || size < 1) return DEFAULT_PAGE_SIZE;
2084
2765
  return Math.min(Math.floor(size), 100);
2085
2766
  }
2767
+ var STREAMPAY_EVENT_ENTITY_TYPES = {
2768
+ PAYMENT_SUCCEEDED: "PAYMENT",
2769
+ PAYMENT_FAILED: "PAYMENT",
2770
+ PAYMENT_CANCELED: "PAYMENT",
2771
+ PAYMENT_REFUNDED: "PAYMENT",
2772
+ PAYMENT_MARKED_AS_PAID: "PAYMENT",
2773
+ INVOICE_CREATED: "INVOICE",
2774
+ INVOICE_SENT: "INVOICE",
2775
+ INVOICE_ACCEPTED: "INVOICE",
2776
+ INVOICE_REJECTED: "INVOICE",
2777
+ INVOICE_COMPLETED: "INVOICE",
2778
+ INVOICE_CANCELED: "INVOICE",
2779
+ INVOICE_UPDATED: "INVOICE",
2780
+ SUBSCRIPTION_CREATED: "SUBSCRIPTION",
2781
+ SUBSCRIPTION_ACTIVATED: "SUBSCRIPTION",
2782
+ SUBSCRIPTION_INACTIVATED: "SUBSCRIPTION",
2783
+ SUBSCRIPTION_CANCELED: "SUBSCRIPTION",
2784
+ SUBSCRIPTION_FROZEN: "SUBSCRIPTION",
2785
+ SUBSCRIPTION_CYCLE_RENEWAL_FAILED: "SUBSCRIPTION",
2786
+ SUBSCRIPTION_CANCEL_AT_PERIOD_END: "SUBSCRIPTION",
2787
+ SUBSCRIPTION_FREEZE_NOW: "SUBSCRIPTION",
2788
+ SUBSCRIPTION_UNFREEZE_NOW: "SUBSCRIPTION",
2789
+ SUBSCRIPTION_UNFREEZE_FUTURE: "SUBSCRIPTION",
2790
+ SUBSCRIPTION_FREEZE_CANCEL: "SUBSCRIPTION",
2791
+ SUBSCRIPTION_PLAN_CHANGE_SCHEDULED: "SUBSCRIPTION",
2792
+ SUBSCRIPTION_PLAN_CHANGE_CANCELED: "SUBSCRIPTION",
2793
+ SUBSCRIPTION_PLAN_CHANGED: "SUBSCRIPTION",
2794
+ SUBSCRIPTION_PLAN_CHANGE_INVOICE_REISSUED: "SUBSCRIPTION",
2795
+ SUBSCRIPTION_PLAN_UPDATED: "SUBSCRIPTION",
2796
+ PAYMENT_LINK_PAY_ATTEMPT_FAILED: "PAYMENT_LINK"
2797
+ };
2798
+ function eventTypesForEntity(entityType) {
2799
+ return Object.entries(STREAMPAY_EVENT_ENTITY_TYPES).filter(([, entity]) => entity === entityType).map(([event]) => event);
2800
+ }
2801
+ var STREAMPAY_PAYMENT_EVENT_TYPES = eventTypesForEntity("PAYMENT");
2802
+ var STREAMPAY_INVOICE_EVENT_TYPES = eventTypesForEntity("INVOICE");
2803
+ var STREAMPAY_SUBSCRIPTION_EVENT_TYPES = eventTypesForEntity("SUBSCRIPTION");
2804
+ var STREAMPAY_PAYMENT_LINK_EVENT_TYPES = eventTypesForEntity("PAYMENT_LINK");
2805
+ var STREAMPAY_EVENT_TYPES = Object.keys(
2806
+ STREAMPAY_EVENT_ENTITY_TYPES
2807
+ );
2808
+ var StreamPayWebhookEnvelopeSchema = zod.z.object({
2809
+ event_type: zod.z.string().min(1),
2810
+ entity_type: zod.z.string().min(1),
2811
+ entity_id: zod.z.string().min(1),
2812
+ entity_url: zod.z.string(),
2813
+ status: zod.z.string(),
2814
+ timestamp: zod.z.string().min(1),
2815
+ data: zod.z.record(zod.z.string(), zod.z.unknown())
2816
+ });
2817
+ function isStreamPayWebhookEnvelope(value) {
2818
+ return StreamPayWebhookEnvelopeSchema.safeParse(value).success;
2819
+ }
2820
+ function isStreamPayEventType(value) {
2821
+ return Object.hasOwn(STREAMPAY_EVENT_ENTITY_TYPES, value);
2822
+ }
2823
+ function isKnownStreamPayWebhookPayload(payload) {
2824
+ return isStreamPayEventType(payload.event_type) && payload.entity_type === STREAMPAY_EVENT_ENTITY_TYPES[payload.event_type];
2825
+ }
2826
+ var SUBSCRIPTION_MODEL3 = "subscription";
2827
+ function requireUser(ctx) {
2828
+ const user = asSessionUser(ctx.context.session?.user);
2829
+ if (!user) {
2830
+ throw new api.APIError("UNAUTHORIZED", {
2831
+ message: "Subscription endpoints require an authenticated session."
2832
+ });
2833
+ }
2834
+ if (user.isAnonymous) {
2835
+ throw new api.APIError("UNAUTHORIZED", {
2836
+ message: "Anonymous users cannot manage subscriptions."
2837
+ });
2838
+ }
2839
+ return user;
2840
+ }
2841
+ function resolveReference(user, query) {
2842
+ const referenceId = query?.referenceId ?? user.id;
2843
+ return {
2844
+ referenceId,
2845
+ referenceType: query?.referenceType ?? (referenceId === user.id ? "user" : "custom")
2846
+ };
2847
+ }
2848
+ async function authorizeReference(ctx, user, referenceId, referenceType, action, subsOptions) {
2849
+ if (referenceType === "user" && referenceId === user.id) return;
2850
+ if (!subsOptions.authorizeReference) {
2851
+ throw new api.APIError("FORBIDDEN", {
2852
+ code: $ERROR_CODES.FORBIDDEN.code,
2853
+ message: "Cross-account subscription actions require an `authorizeReference` callback."
2854
+ });
2855
+ }
2856
+ const authorized = await subsOptions.authorizeReference(
2857
+ { user, referenceId, referenceType, action },
2858
+ ctx
2859
+ );
2860
+ if (!authorized) {
2861
+ throw new api.APIError("FORBIDDEN", {
2862
+ code: $ERROR_CODES.SUBSCRIPTION_REFERENCE_NOT_AUTHORIZED.code,
2863
+ message: "Not authorized for this subscription reference."
2864
+ });
2865
+ }
2866
+ }
2867
+ function getAdapter2(ctx) {
2868
+ const adapter = ctx.context.adapter;
2869
+ if (!adapter) {
2870
+ throw new api.APIError("INTERNAL_SERVER_ERROR", {
2871
+ message: "Better Auth adapter is not available on the request context."
2872
+ });
2873
+ }
2874
+ return adapter;
2875
+ }
2876
+ async function findOwnedSubscription(ctx, user, subscriptionId, subsOptions, action) {
2877
+ const adapter = getAdapter2(ctx);
2878
+ const localRow = await adapter.findOne({
2879
+ model: SUBSCRIPTION_MODEL3,
2880
+ where: [{ field: "id", value: subscriptionId }]
2881
+ });
2882
+ const row = localRow ?? await adapter.findOne({
2883
+ model: SUBSCRIPTION_MODEL3,
2884
+ where: [{ field: "streampaySubscriptionId", value: subscriptionId }]
2885
+ });
2886
+ if (!row) {
2887
+ throw new api.APIError("NOT_FOUND", {
2888
+ code: $ERROR_CODES.SUBSCRIPTION_NOT_FOUND.code,
2889
+ message: "Subscription not found."
2890
+ });
2891
+ }
2892
+ await authorizeReference(
2893
+ ctx,
2894
+ user,
2895
+ row.referenceId,
2896
+ row.referenceType ?? "user",
2897
+ action,
2898
+ subsOptions
2899
+ );
2900
+ return row;
2901
+ }
2902
+ async function requireConfirmedOwnedSubscription(ctx, subscriptionId, subsOptions, action) {
2903
+ const user = requireUser(ctx);
2904
+ const adapter = getAdapter2(ctx);
2905
+ const row = await findOwnedSubscription(ctx, user, subscriptionId, subsOptions, action);
2906
+ if (!row.streampaySubscriptionId) {
2907
+ throw new api.APIError("BAD_REQUEST", {
2908
+ code: $ERROR_CODES.SUBSCRIPTION_INVALID_STATE.code,
2909
+ message: "Subscription has not been confirmed by StreamPay yet."
2910
+ });
2911
+ }
2912
+ return {
2913
+ adapter,
2914
+ row,
2915
+ streampaySubscriptionId: row.streampaySubscriptionId
2916
+ };
2917
+ }
2918
+ var SUBSCRIPTION_MODEL4 = "subscription";
2919
+ async function recoverCheckoutUrl(client, row) {
2920
+ if (!row.streampayPaymentLinkId) return { kind: "expired" };
2921
+ try {
2922
+ const url = client.getPaymentUrl(await client.getPaymentLink(row.streampayPaymentLinkId));
2923
+ return url ? { kind: "recovered", url } : { kind: "expired" };
2924
+ } catch (err) {
2925
+ if (readSdkErrorFields(err).status === 404) return { kind: "expired" };
2926
+ throw err;
2927
+ }
2928
+ }
2929
+ async function deleteReservedSubscription(adapter, rowId, log, reason) {
2930
+ try {
2931
+ await adapter.delete({
2932
+ model: SUBSCRIPTION_MODEL4,
2933
+ where: [{ field: "id", value: rowId }]
2934
+ });
2935
+ } catch (err) {
2936
+ const message = err instanceof Error ? err.message : String(err);
2937
+ log.error(`${reason}: failed to release reserved subscription row=${rowId}: ${message}`);
2938
+ }
2939
+ }
2940
+ function checkoutInProgressError() {
2941
+ return new api.APIError("CONFLICT", {
2942
+ code: $ERROR_CODES.SUBSCRIPTION_CHECKOUT_IN_PROGRESS.code,
2943
+ message: "A subscription checkout is already being created for this plan group."
2944
+ });
2945
+ }
2946
+ async function resumeOrReserveCheckoutSlot(args) {
2947
+ const { client, adapter, candidates, activeSlotKey, planName, now, log } = args;
2948
+ const reuseCandidate = candidates.find(
2949
+ (row2) => row2.plan === planName && row2.status === "incomplete" && Boolean(row2.streampayPaymentLinkId) && row2.createdAt instanceof Date && now - row2.createdAt.getTime() < UPGRADE_IDEMPOTENCY_WINDOW_MS
2950
+ );
2951
+ if (reuseCandidate) {
2952
+ let recovery;
2953
+ try {
2954
+ recovery = await recoverCheckoutUrl(client, reuseCandidate);
2955
+ } catch (err) {
2956
+ toAPIError(
2957
+ {
2958
+ logPrefix: `resume subscription checkout failed for row=${reuseCandidate.id}:`,
2959
+ userMessage: "Unable to resume subscription checkout."
2960
+ },
2961
+ err,
2962
+ log
2963
+ );
2964
+ }
2965
+ if (recovery.kind === "recovered") {
2966
+ return { kind: "recovered", row: reuseCandidate, url: recovery.url };
2967
+ }
2968
+ await adapter.update({
2969
+ model: SUBSCRIPTION_MODEL4,
2970
+ update: { status: "incomplete_expired", activeSlotKey: null, updatedAt: /* @__PURE__ */ new Date() },
2971
+ where: [{ field: "id", value: reuseCandidate.id }]
2972
+ });
2973
+ }
2974
+ const { data: reservationData, consumerId } = await args.createReservation();
2975
+ let row;
2976
+ try {
2977
+ row = await adapter.create({
2978
+ model: SUBSCRIPTION_MODEL4,
2979
+ data: reservationData
2980
+ });
2981
+ } catch (err) {
2982
+ if (!isUniqueConstraintError(err)) throw err;
2983
+ const reserved = await adapter.findOne({
2984
+ model: SUBSCRIPTION_MODEL4,
2985
+ where: [{ field: "activeSlotKey", value: activeSlotKey }]
2986
+ });
2987
+ if (reserved?.status !== "incomplete") throw err;
2988
+ let recovery;
2989
+ try {
2990
+ recovery = await recoverCheckoutUrl(client, reserved);
2991
+ } catch (recoveryError) {
2992
+ toAPIError(
2993
+ {
2994
+ logPrefix: `resume concurrent subscription checkout failed for row=${reserved.id}:`,
2995
+ userMessage: "Unable to resume subscription checkout."
2996
+ },
2997
+ recoveryError,
2998
+ log
2999
+ );
3000
+ }
3001
+ if (recovery.kind === "recovered") {
3002
+ return { kind: "recovered", row: reserved, url: recovery.url };
3003
+ }
3004
+ const reservationIsStale = !(reserved.createdAt instanceof Date) || now - reserved.createdAt.getTime() >= UPGRADE_IDEMPOTENCY_WINDOW_MS;
3005
+ if (!reservationIsStale) throw checkoutInProgressError();
3006
+ const released = await adapter.update({
3007
+ model: SUBSCRIPTION_MODEL4,
3008
+ update: { status: "incomplete_expired", activeSlotKey: null, updatedAt: /* @__PURE__ */ new Date() },
3009
+ where: [
3010
+ { field: "id", value: reserved.id },
3011
+ { field: "activeSlotKey", value: activeSlotKey }
3012
+ ]
3013
+ });
3014
+ if (!released) throw checkoutInProgressError();
3015
+ try {
3016
+ row = await adapter.create({
3017
+ model: SUBSCRIPTION_MODEL4,
3018
+ data: reservationData
3019
+ });
3020
+ } catch (retryError) {
3021
+ if (!isUniqueConstraintError(retryError)) throw retryError;
3022
+ throw checkoutInProgressError();
3023
+ }
3024
+ log.warn(`released stale checkout reservation row=${reserved.id} for plan=${planName}.`);
3025
+ }
3026
+ return { kind: "reserved", row, consumerId };
3027
+ }
3028
+
3029
+ // src/plugins/subscriptions/lifecycle.ts
3030
+ function isAlreadyCanceledFreezeError(err) {
3031
+ const sdkError = readSdkErrorFields(err);
3032
+ const envelope = readEnvelope(sdkError.body);
3033
+ return sdkError.status === 403 && envelope?.code === "STREAM_ERROR" && envelope.additionalInfo === "Cannot delete non-latest freeze entry.";
3034
+ }
3035
+ function subscriptionCouponIds(stream) {
3036
+ const coupons = [];
3037
+ for (const coupon of stream.coupon_calculation_metadata?.coupons ?? []) {
3038
+ if (coupon.coupon_id) coupons.push(coupon.coupon_id);
3039
+ }
3040
+ return coupons;
3041
+ }
3042
+ function configuredPlanForSubscription(subscription, plans) {
3043
+ return plans.list.find(
3044
+ (plan) => subscription.items?.some((item) => subscriptionItemProductId(item) === plan.productId)
3045
+ );
3046
+ }
3047
+ var SUBSCRIPTION_INTERVALS = ["WEEK", "MONTH", "QUARTER", "YEAR"];
2086
3048
  var PlanSchema = zod.z.object({
2087
3049
  name: zod.z.string().min(1, "every plan must have a non-empty `name`."),
2088
3050
  productId: zod.z.string().min(1, "missing a non-empty `productId`."),
2089
- priceHalalat: zod.z.number({ error: "must have a non-negative numeric `priceHalalat`." }).refine((n) => Number.isFinite(n) && n >= 0, {
2090
- message: "must have a non-negative numeric `priceHalalat`."
2091
- }),
2092
- billingInterval: zod.z.enum(["WEEK", "MONTH", "QUARTER", "YEAR"], {
2093
- error: () => "has invalid `billingInterval`. Expected one of: WEEK, MONTH, QUARTER, YEAR."
2094
- }),
3051
+ priceInSmallestUnit: zod.z.custom(
3052
+ (value) => typeof value === "number" && Number.isSafeInteger(value) && value >= 0,
3053
+ "must have a non-negative safe-integer `priceInSmallestUnit`."
3054
+ ),
3055
+ currency: zod.z.enum(["SAR", "USD", "EUR", "GBP", "AED", "BHD", "KWD", "OMR", "QAR"]).optional(),
3056
+ version: zod.z.string().min(1, "has an empty `version`.").optional(),
3057
+ billingInterval: zod.z.custom(
3058
+ (value) => typeof value === "string" && SUBSCRIPTION_INTERVALS.some((interval) => interval === value),
3059
+ "has invalid `billingInterval`. Expected one of: WEEK, MONTH, QUARTER, YEAR."
3060
+ ),
2095
3061
  billingIntervalCount: zod.z.number().refine((n) => Number.isInteger(n) && n >= 1, {
2096
3062
  message: "has invalid `billingIntervalCount` \u2014 must be a positive integer."
2097
3063
  }).optional(),
2098
- group: zod.z.string().optional(),
3064
+ trialPeriodDays: zod.z.number().refine((n) => Number.isInteger(n) && n >= 1 && n <= 365, {
3065
+ message: "has invalid `trialPeriodDays` \u2014 must be an integer from 1 to 365."
3066
+ }).optional(),
3067
+ group: zod.z.string().min(1, "has an empty `group`.").optional(),
2099
3068
  limits: zod.z.record(zod.z.string(), zod.z.unknown()).optional()
2100
3069
  });
2101
3070
  var PlansSchema = zod.z.array(PlanSchema).nonempty("`plans` resolved to an empty list. Provide at least one plan.").superRefine((plans, ctx) => {
2102
- const seen = /* @__PURE__ */ new Set();
3071
+ const seenNames = /* @__PURE__ */ new Set();
3072
+ const seenProductIds = /* @__PURE__ */ new Set();
2103
3073
  for (const [index, plan] of plans.entries()) {
2104
- if (seen.has(plan.name)) {
3074
+ if (seenNames.has(plan.name)) {
2105
3075
  ctx.addIssue({
2106
3076
  code: "custom",
2107
3077
  path: [index, "name"],
2108
3078
  message: `duplicate plan name "${plan.name}" \u2014 plan names must be unique.`
2109
3079
  });
2110
3080
  }
2111
- seen.add(plan.name);
3081
+ seenNames.add(plan.name);
3082
+ if (seenProductIds.has(plan.productId)) {
3083
+ ctx.addIssue({
3084
+ code: "custom",
3085
+ path: [index, "productId"],
3086
+ message: `duplicate productId "${plan.productId}" \u2014 webhook plan inference requires unique product IDs.`
3087
+ });
3088
+ }
3089
+ seenProductIds.add(plan.productId);
2112
3090
  }
2113
3091
  });
2114
3092
  function validatePlansShape(plans) {
@@ -2146,16 +3124,19 @@ function createPlanResolver(plans) {
2146
3124
  }
2147
3125
  };
2148
3126
  }
2149
- function hasFeature(subscription, plan, feature) {
3127
+ function hasSubscriptionAccess(subscription, accessStatuses = DEFAULT_ACCESS_STATUSES) {
3128
+ return accessStatuses.includes(subscription.status);
3129
+ }
3130
+ function hasFeature(subscription, plan, feature, accessStatuses = DEFAULT_ACCESS_STATUSES) {
2150
3131
  if (!plan?.limits) return false;
2151
- if (subscription.status !== "active" && subscription.status !== "frozen") return false;
3132
+ if (!hasSubscriptionAccess(subscription, accessStatuses)) return false;
2152
3133
  const value = plan.limits[feature];
2153
3134
  if (typeof value === "boolean") return value;
2154
3135
  if (typeof value === "number") return value > 0;
2155
3136
  return Boolean(value);
2156
3137
  }
2157
- function checkLimit(subscription, plan, feature, requested) {
2158
- if (!plan?.limits || subscription.status !== "active" && subscription.status !== "frozen") {
3138
+ function checkLimit(subscription, plan, feature, requested, accessStatuses = DEFAULT_ACCESS_STATUSES) {
3139
+ if (!plan?.limits || !hasSubscriptionAccess(subscription, accessStatuses)) {
2159
3140
  return { allowed: false, limit: 0, remaining: 0 };
2160
3141
  }
2161
3142
  const raw = plan.limits[feature];
@@ -2166,121 +3147,194 @@ function checkLimit(subscription, plan, feature, requested) {
2166
3147
  return { allowed, limit, remaining };
2167
3148
  }
2168
3149
 
3150
+ // src/plugins/subscriptions/reads.ts
3151
+ var SUBSCRIPTION_MODEL5 = "subscription";
3152
+ var ReferenceQueryFields = {
3153
+ referenceId: zod.z.string().min(1).optional(),
3154
+ referenceType: zod.z.enum(["user", "organization", "custom"]).optional()
3155
+ };
3156
+ var ListQuery = zod.z.object(ReferenceQueryFields).optional();
3157
+ var CurrentQuery = zod.z.object({
3158
+ ...ReferenceQueryFields,
3159
+ group: zod.z.string().min(1).optional()
3160
+ }).optional();
3161
+ var HasFeatureQuery = zod.z.object({
3162
+ ...ReferenceQueryFields,
3163
+ feature: zod.z.string().min(1),
3164
+ group: zod.z.string().min(1).optional()
3165
+ });
3166
+ var CheckLimitQuery = zod.z.object({
3167
+ ...ReferenceQueryFields,
3168
+ feature: zod.z.string().min(1),
3169
+ count: zod.z.coerce.number().int().min(0),
3170
+ group: zod.z.string().min(1).optional()
3171
+ });
3172
+ async function resolveLiveSubscription(ctx, query, subsOptions, accessStatuses) {
3173
+ const user = requireUser(ctx);
3174
+ const reference = resolveReference(user, query);
3175
+ await authorizeReference(
3176
+ ctx,
3177
+ user,
3178
+ reference.referenceId,
3179
+ reference.referenceType,
3180
+ "read",
3181
+ subsOptions
3182
+ );
3183
+ const rows = await getAdapter2(ctx).findMany({
3184
+ model: SUBSCRIPTION_MODEL5,
3185
+ where: [
3186
+ { field: "referenceId", value: reference.referenceId },
3187
+ { field: "referenceType", value: reference.referenceType },
3188
+ { field: "group", value: query.group ?? null }
3189
+ ]
3190
+ });
3191
+ return rows.find((row) => hasSubscriptionAccess(row, accessStatuses)) ?? null;
3192
+ }
3193
+ function buildSubscriptionReadEndpoints(subsOptions, plansRef) {
3194
+ const accessStatuses = subsOptions.accessStatuses ?? DEFAULT_ACCESS_STATUSES;
3195
+ return {
3196
+ listSubscriptions: api.createAuthEndpoint(
3197
+ "/subscription/list",
3198
+ {
3199
+ method: "GET",
3200
+ query: ListQuery,
3201
+ use: [api.sessionMiddleware]
3202
+ },
3203
+ async (ctx) => {
3204
+ const user = requireUser(ctx);
3205
+ const reference = resolveReference(user, ctx.query);
3206
+ await authorizeReference(
3207
+ ctx,
3208
+ user,
3209
+ reference.referenceId,
3210
+ reference.referenceType,
3211
+ "read",
3212
+ subsOptions
3213
+ );
3214
+ const rows = await getAdapter2(ctx).findMany({
3215
+ model: SUBSCRIPTION_MODEL5,
3216
+ where: [
3217
+ { field: "referenceId", value: reference.referenceId },
3218
+ { field: "referenceType", value: reference.referenceType }
3219
+ ]
3220
+ });
3221
+ const plans = await plansRef();
3222
+ return ctx.json(
3223
+ rows.map((row) => ({
3224
+ ...row,
3225
+ plan: plans.byName.get(row.plan) ?? null
3226
+ }))
3227
+ );
3228
+ }
3229
+ ),
3230
+ currentSubscription: api.createAuthEndpoint(
3231
+ "/subscription/current",
3232
+ {
3233
+ method: "GET",
3234
+ query: CurrentQuery,
3235
+ use: [api.sessionMiddleware]
3236
+ },
3237
+ async (ctx) => {
3238
+ const live = await resolveLiveSubscription(
3239
+ ctx,
3240
+ ctx.query ?? {},
3241
+ subsOptions,
3242
+ accessStatuses
3243
+ );
3244
+ if (!live) return ctx.json(null);
3245
+ const plans = await plansRef();
3246
+ return ctx.json({ ...live, plan: plans.byName.get(live.plan) ?? null });
3247
+ }
3248
+ ),
3249
+ hasSubscriptionFeature: api.createAuthEndpoint(
3250
+ "/subscription/has-feature",
3251
+ {
3252
+ method: "GET",
3253
+ query: HasFeatureQuery,
3254
+ use: [api.sessionMiddleware]
3255
+ },
3256
+ async (ctx) => {
3257
+ const live = await resolveLiveSubscription(ctx, ctx.query, subsOptions, accessStatuses);
3258
+ if (!live) return ctx.json({ hasFeature: false });
3259
+ const plan = (await plansRef()).byName.get(live.plan);
3260
+ return ctx.json({
3261
+ hasFeature: hasFeature(live, plan, ctx.query.feature, accessStatuses)
3262
+ });
3263
+ }
3264
+ ),
3265
+ checkSubscriptionLimit: api.createAuthEndpoint(
3266
+ "/subscription/check-limit",
3267
+ {
3268
+ method: "GET",
3269
+ query: CheckLimitQuery,
3270
+ use: [api.sessionMiddleware]
3271
+ },
3272
+ async (ctx) => {
3273
+ const live = await resolveLiveSubscription(ctx, ctx.query, subsOptions, accessStatuses);
3274
+ if (!live) return ctx.json({ allowed: false, limit: 0, remaining: 0 });
3275
+ const plan = (await plansRef()).byName.get(live.plan);
3276
+ return ctx.json(checkLimit(live, plan, ctx.query.feature, ctx.query.count, accessStatuses));
3277
+ }
3278
+ )
3279
+ };
3280
+ }
3281
+
2169
3282
  // src/plugins/subscriptions/endpoints.ts
2170
- var SUBSCRIPTION_MODEL2 = "subscription";
3283
+ var SUBSCRIPTION_MODEL6 = "subscription";
2171
3284
  var UpgradeBody = zod.z.object({
2172
3285
  plan: zod.z.string().min(1),
2173
3286
  referenceId: zod.z.string().min(1).optional(),
3287
+ referenceType: zod.z.enum(["user", "organization", "custom"]).optional(),
2174
3288
  successUrl: zod.z.string().url().optional(),
2175
3289
  failureUrl: zod.z.string().url().optional()
2176
3290
  });
2177
3291
  var SuccessQuery = zod.z.object({
2178
- subscriptionId: zod.z.string().uuid(),
2179
- callbackURL: zod.z.string().url().optional()
3292
+ subscriptionId: zod.z.string().min(1)
2180
3293
  });
2181
3294
  var CancelBody = zod.z.object({
2182
- subscriptionId: zod.z.string().uuid(),
3295
+ subscriptionId: zod.z.string().min(1),
2183
3296
  cancelRelatedInvoices: zod.z.boolean().optional(),
2184
3297
  cancelAtPeriodEnd: zod.z.boolean().optional()
2185
3298
  });
2186
3299
  var ChangePlanBody = zod.z.object({
2187
- plan: zod.z.string().min(1),
2188
- mode: zod.z.enum(["at_period_end", "immediate"]).optional(),
2189
- successUrl: zod.z.string().url().optional(),
2190
- failureUrl: zod.z.string().url().optional()
2191
- });
3300
+ subscriptionId: zod.z.string().min(1),
3301
+ plan: zod.z.string().min(1)
3302
+ }).strict();
2192
3303
  var FreezeBody = zod.z.object({
2193
- subscriptionId: zod.z.string().uuid(),
3304
+ subscriptionId: zod.z.string().min(1),
2194
3305
  freezeStartDatetime: zod.z.string().datetime(),
2195
3306
  freezeEndDatetime: zod.z.string().datetime().nullable().optional(),
2196
3307
  notes: zod.z.string().optional()
2197
3308
  });
2198
3309
  var UnfreezeBody = zod.z.object({
2199
- subscriptionId: zod.z.string().uuid()
3310
+ subscriptionId: zod.z.string().min(1)
2200
3311
  });
2201
- var CurrentQuery = zod.z.object({
2202
- group: zod.z.string().min(1).optional()
2203
- }).optional();
2204
- var HasFeatureQuery = zod.z.object({
2205
- feature: zod.z.string().min(1),
2206
- group: zod.z.string().min(1).optional()
3312
+ var CancelFreezeBody = zod.z.object({
3313
+ subscriptionId: zod.z.string().min(1),
3314
+ freezeId: zod.z.string().min(1)
2207
3315
  });
2208
- var CheckLimitQuery = zod.z.object({
2209
- feature: zod.z.string().min(1),
2210
- count: zod.z.coerce.number().int().min(0),
2211
- group: zod.z.string().min(1).optional()
2212
- });
2213
- function requireUser(ctx) {
2214
- const user = asSessionUser(ctx.context.session?.user);
2215
- if (!user) {
2216
- throw new api.APIError("UNAUTHORIZED", {
2217
- message: "Subscription endpoints require an authenticated session."
2218
- });
2219
- }
2220
- if (user.isAnonymous) {
2221
- throw new api.APIError("UNAUTHORIZED", {
2222
- message: "Anonymous users cannot manage subscriptions."
2223
- });
2224
- }
2225
- return user;
2226
- }
2227
- async function authorizeReference(ctx, user, referenceId, action, subsOptions) {
2228
- if (referenceId === user.id) return;
2229
- if (!subsOptions.authorizeReference) {
2230
- throw new api.APIError("FORBIDDEN", {
2231
- code: $ERROR_CODES.FORBIDDEN.code,
2232
- message: "Cross-account subscription actions require an `authorizeReference` callback."
2233
- });
2234
- }
2235
- const ok = await subsOptions.authorizeReference({ user, referenceId, action }, ctx);
2236
- if (!ok) {
2237
- throw new api.APIError("FORBIDDEN", {
2238
- code: "SUBSCRIPTION_REFERENCE_NOT_AUTHORIZED",
2239
- message: "Not authorized for this subscription reference."
2240
- });
2241
- }
2242
- }
2243
- function getAdapter2(ctx) {
2244
- const adapter = ctx.context.adapter;
2245
- if (!adapter) {
2246
- throw new api.APIError("INTERNAL_SERVER_ERROR", {
2247
- message: "Better Auth adapter is not available on the request context."
2248
- });
3316
+ var SUCCESS_RECONCILIATION_CLOCK_SKEW_MS = 5 * 60 * 1e3;
3317
+ function isCheckoutSubscriptionCandidate(subscription, row, productId) {
3318
+ if (subscription.organization_consumer_id !== row.streampayConsumerId) return false;
3319
+ if (!isCheckoutSuccessStatus(subscription.status)) return false;
3320
+ if (!subscription.items?.some((item) => subscriptionItemProductId(item) === productId)) {
3321
+ return false;
2249
3322
  }
2250
- return adapter;
2251
- }
2252
- function echoSubscriptionPatch(stream) {
2253
- const items = [];
2254
- for (const item of stream.items ?? []) {
2255
- const productId = item.product?.id;
2256
- const quantity = item.quantity;
2257
- if (!productId || quantity === void 0) continue;
2258
- items.push({ product_id: productId, quantity });
3323
+ const upstreamPaymentLinkId = subscription.latest_invoice?.payment_link_id;
3324
+ if (row.streampayPaymentLinkId && upstreamPaymentLinkId && upstreamPaymentLinkId !== row.streampayPaymentLinkId) {
3325
+ return false;
2259
3326
  }
2260
- const coupons = [];
2261
- for (const c of stream.coupon_calculation_metadata?.coupons ?? []) {
2262
- if (c.coupon_id) coupons.push(c.coupon_id);
3327
+ if (row.streampayPaymentLinkId && upstreamPaymentLinkId === row.streampayPaymentLinkId) {
3328
+ return true;
2263
3329
  }
2264
- return { items, coupons };
2265
- }
2266
- async function findOwnedSubscription(ctx, user, streampaySubscriptionId, subsOptions, action) {
2267
- const adapter = getAdapter2(ctx);
2268
- const row = await adapter.findOne({
2269
- model: SUBSCRIPTION_MODEL2,
2270
- where: [{ field: "streampaySubscriptionId", value: streampaySubscriptionId }]
2271
- });
2272
- if (!row) {
2273
- throw new api.APIError("NOT_FOUND", {
2274
- code: "SUBSCRIPTION_NOT_FOUND",
2275
- message: "Subscription not found."
2276
- });
2277
- }
2278
- await authorizeReference(ctx, user, row.referenceId, action, subsOptions);
2279
- return row;
3330
+ if (!subscription.created_at || !(row.createdAt instanceof Date)) return false;
3331
+ const createdAt = new Date(subscription.created_at).getTime();
3332
+ return Number.isFinite(createdAt) && createdAt >= row.createdAt.getTime() - SUCCESS_RECONCILIATION_CLOCK_SKEW_MS;
2280
3333
  }
2281
3334
  function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
2282
3335
  const client = options.client;
2283
3336
  return {
3337
+ ...buildSubscriptionReadEndpoints(subsOptions, plansRef),
2284
3338
  upgradeSubscription: api.createAuthEndpoint(
2285
3339
  "/subscription/upgrade",
2286
3340
  {
@@ -2291,58 +3345,134 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
2291
3345
  async (ctx) => {
2292
3346
  const user = requireUser(ctx);
2293
3347
  const referenceId = ctx.body.referenceId ?? user.id;
2294
- await authorizeReference(ctx, user, referenceId, "upgrade", subsOptions);
3348
+ const referenceType = ctx.body.referenceType ?? (referenceId === user.id ? "user" : "custom");
3349
+ await authorizeReference(ctx, user, referenceId, referenceType, "upgrade", subsOptions);
2295
3350
  const plans = await plansRef();
2296
3351
  const plan = plans.byName.get(ctx.body.plan);
2297
3352
  if (!plan) {
2298
3353
  throw new api.APIError("NOT_FOUND", {
2299
- code: "SUBSCRIPTION_PLAN_NOT_FOUND",
3354
+ code: $ERROR_CODES.SUBSCRIPTION_PLAN_NOT_FOUND.code,
2300
3355
  message: `Plan "${ctx.body.plan}" is not configured.`
2301
3356
  });
2302
3357
  }
2303
3358
  const adapter = getAdapter2(ctx);
2304
3359
  const existingActive = await adapter.findMany({
2305
- model: SUBSCRIPTION_MODEL2,
3360
+ model: SUBSCRIPTION_MODEL6,
2306
3361
  where: [
2307
3362
  { field: "referenceId", value: referenceId },
2308
- ...plan.group ? [{ field: "group", value: plan.group }] : []
3363
+ { field: "referenceType", value: referenceType },
3364
+ { field: "group", value: plan.group ?? null }
2309
3365
  ]
2310
3366
  });
2311
- const liveActive = existingActive.find(
2312
- (row2) => row2.status === "active" || row2.status === "frozen" || row2.status === "past_due"
3367
+ const defaultTrialEligible = !existingActive.some(
3368
+ (row2) => row2.trialStart instanceof Date || row2.trialEnd instanceof Date || row2.status === "trial_pending" || row2.status === "trialing"
2313
3369
  );
3370
+ const trialEligible = plan.trialPeriodDays === void 0 ? false : subsOptions.isTrialEligible ? await subsOptions.isTrialEligible(
3371
+ {
3372
+ user,
3373
+ referenceId,
3374
+ referenceType,
3375
+ plan,
3376
+ previousSubscriptions: existingActive,
3377
+ defaultEligible: defaultTrialEligible
3378
+ },
3379
+ ctx
3380
+ ) : defaultTrialEligible;
3381
+ const liveActive = existingActive.find((row2) => isManageableSubscriptionStatus(row2.status));
2314
3382
  if (liveActive) {
2315
3383
  throw new api.APIError("CONFLICT", {
2316
- code: "SUBSCRIPTION_ALREADY_ACTIVE",
2317
- message: plan.group ? `An active subscription already exists in plan group "${plan.group}". Cancel it before upgrading.` : "An active subscription already exists. Cancel it before upgrading."
3384
+ code: $ERROR_CODES.SUBSCRIPTION_ALREADY_ACTIVE.code,
3385
+ message: plan.group ? `An active subscription already exists in plan group "${plan.group}". Use the change-plan endpoint to move it.` : "An active subscription already exists. Use the change-plan endpoint to move it."
2318
3386
  });
2319
3387
  }
2320
- const now = Date.now();
2321
- const reuseCandidate = existingActive.find(
2322
- (row2) => row2.plan === plan.name && row2.status === "incomplete" && row2.createdAt instanceof Date && now - row2.createdAt.getTime() < UPGRADE_IDEMPOTENCY_WINDOW_MS
2323
- );
2324
- if (reuseCandidate) {
3388
+ const activeSlotKey = subscriptionSlotKey(referenceType, referenceId, plan.group);
3389
+ const reservation = await resumeOrReserveCheckoutSlot({
3390
+ client,
3391
+ adapter,
3392
+ candidates: existingActive,
3393
+ activeSlotKey,
3394
+ planName: plan.name,
3395
+ now: Date.now(),
3396
+ log: getLogger(ctx),
3397
+ createReservation: async () => {
3398
+ const { consumerId: consumerId2 } = await ensureConsumerForUser(
3399
+ options,
3400
+ { context: ctx.context },
3401
+ user
3402
+ );
3403
+ return {
3404
+ consumerId: consumerId2,
3405
+ data: {
3406
+ referenceId,
3407
+ referenceType,
3408
+ activeSlotKey,
3409
+ streampaySubscriptionId: null,
3410
+ plan: plan.name,
3411
+ planVersion: plan.version ?? null,
3412
+ productId: plan.productId,
3413
+ group: plan.group ?? null,
3414
+ streampayConsumerId: consumerId2,
3415
+ streampayPaymentLinkId: null,
3416
+ status: "incomplete",
3417
+ providerStatus: null,
3418
+ billingStatus: "current",
3419
+ amountInSmallestUnit: plan.priceInSmallestUnit,
3420
+ originalAmountInSmallestUnit: plan.priceInSmallestUnit,
3421
+ currency: plan.currency ?? "SAR",
3422
+ billingInterval: plan.billingInterval,
3423
+ billingIntervalCount: plan.billingIntervalCount ?? 1,
3424
+ periodStart: null,
3425
+ periodEnd: null,
3426
+ currentCycleNumber: null,
3427
+ trialStart: null,
3428
+ trialEnd: null,
3429
+ cancelAtPeriodEnd: false,
3430
+ cancelAt: null,
3431
+ cancelScheduledAt: null,
3432
+ canceledAt: null,
3433
+ pendingPlan: null,
3434
+ pendingProductId: null,
3435
+ pendingPlanEffectiveAt: null,
3436
+ endedAt: null,
3437
+ frozenAt: null,
3438
+ freezeEndAt: null,
3439
+ providerUpdatedAt: null,
3440
+ syncedAt: null,
3441
+ createdAt: /* @__PURE__ */ new Date(),
3442
+ updatedAt: /* @__PURE__ */ new Date()
3443
+ }
3444
+ };
3445
+ }
3446
+ });
3447
+ if (reservation.kind === "recovered") {
2325
3448
  return ctx.json({
2326
- subscriptionId: reuseCandidate.id,
3449
+ subscriptionId: reservation.row.id,
3450
+ url: reservation.url,
3451
+ redirect: true,
2327
3452
  reused: true,
2328
- status: reuseCandidate.status,
2329
- plan: reuseCandidate.plan
3453
+ status: reservation.row.status,
3454
+ plan: reservation.row.plan
2330
3455
  });
2331
3456
  }
2332
- const ensureCtx = { context: ctx.context };
2333
- const { consumerId } = await ensureConsumerForUser(options, ensureCtx, user);
3457
+ const { row, consumerId } = reservation;
2334
3458
  const linkInput = {
2335
3459
  name: `Subscription \u2014 ${plan.name}`,
3460
+ currency: plan.currency ?? "SAR",
2336
3461
  items: [{ product_id: plan.productId, quantity: 1, allow_custom_quantity: false }],
2337
3462
  max_number_of_payments: 1,
2338
3463
  organization_consumer_id: consumerId,
2339
3464
  custom_metadata: {
2340
3465
  [PLAN_NAME_METADATA_KEY]: plan.name,
2341
- [REFERENCE_ID_METADATA_KEY]: referenceId
3466
+ [REFERENCE_ID_METADATA_KEY]: referenceId,
3467
+ [REFERENCE_TYPE_METADATA_KEY]: referenceType,
3468
+ [SUBSCRIPTION_ROW_ID_METADATA_KEY]: row.id
2342
3469
  }
2343
3470
  };
2344
3471
  if (ctx.body.successUrl) linkInput.success_redirect_url = ctx.body.successUrl;
2345
3472
  if (ctx.body.failureUrl) linkInput.failure_redirect_url = ctx.body.failureUrl;
3473
+ if (plan.trialPeriodDays !== void 0 && trialEligible) {
3474
+ linkInput.trial_period_days = plan.trialPeriodDays;
3475
+ }
2346
3476
  let url;
2347
3477
  let paymentLinkId;
2348
3478
  try {
@@ -2355,6 +3485,12 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
2355
3485
  paymentLinkId = link.id;
2356
3486
  url = client.getPaymentUrl(link);
2357
3487
  } catch (err) {
3488
+ await deleteReservedSubscription(
3489
+ adapter,
3490
+ row.id,
3491
+ getLogger(ctx),
3492
+ "createPaymentLink cleanup"
3493
+ );
2358
3494
  toAPIError(
2359
3495
  {
2360
3496
  logPrefix: `upgradeSubscription failed for plan=${plan.name} ref=${referenceId}:`,
@@ -2366,29 +3502,51 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
2366
3502
  }
2367
3503
  if (!url) {
2368
3504
  getLogger(ctx).error(`createPaymentLink returned link=${paymentLinkId} with no url.`);
3505
+ try {
3506
+ await adapter.update({
3507
+ model: SUBSCRIPTION_MODEL6,
3508
+ update: {
3509
+ streampayPaymentLinkId: paymentLinkId,
3510
+ status: "incomplete_expired",
3511
+ activeSlotKey: null,
3512
+ updatedAt: /* @__PURE__ */ new Date()
3513
+ },
3514
+ where: [{ field: "id", value: row.id }]
3515
+ });
3516
+ } catch (persistenceError) {
3517
+ const message = persistenceError instanceof Error ? persistenceError.message : String(persistenceError);
3518
+ getLogger(ctx).error(
3519
+ `failed to mark unusable payment link=${paymentLinkId} expired for row=${row.id}: ${message}`
3520
+ );
3521
+ await deleteReservedSubscription(
3522
+ adapter,
3523
+ row.id,
3524
+ getLogger(ctx),
3525
+ "unusable payment link cleanup"
3526
+ );
3527
+ }
2369
3528
  throw new api.APIError("INTERNAL_SERVER_ERROR", {
2370
3529
  message: "Payment link was created but no URL was returned."
2371
3530
  });
2372
3531
  }
2373
- const row = await adapter.create({
2374
- model: SUBSCRIPTION_MODEL2,
2375
- data: {
2376
- referenceId,
2377
- plan: plan.name,
2378
- group: plan.group ?? null,
2379
- streampayConsumerId: consumerId,
2380
- status: "incomplete",
2381
- amountHalalat: plan.priceHalalat,
2382
- currency: "SAR",
2383
- billingInterval: plan.billingInterval,
2384
- billingIntervalCount: plan.billingIntervalCount ?? 1,
2385
- cancelAtPeriodEnd: false,
2386
- createdAt: /* @__PURE__ */ new Date(),
2387
- updatedAt: /* @__PURE__ */ new Date()
2388
- }
2389
- });
3532
+ let updatedRow = null;
3533
+ try {
3534
+ updatedRow = await adapter.update({
3535
+ model: SUBSCRIPTION_MODEL6,
3536
+ update: {
3537
+ streampayPaymentLinkId: paymentLinkId,
3538
+ updatedAt: /* @__PURE__ */ new Date()
3539
+ },
3540
+ where: [{ field: "id", value: row.id }]
3541
+ });
3542
+ } catch (persistenceError) {
3543
+ const message = persistenceError instanceof Error ? persistenceError.message : String(persistenceError);
3544
+ getLogger(ctx).error(
3545
+ `failed to persist payment link=${paymentLinkId} for row=${row.id}: ${message}. Protected checkout metadata will reconcile the row from the webhook.`
3546
+ );
3547
+ }
2390
3548
  return ctx.json({
2391
- subscriptionId: row.id,
3549
+ subscriptionId: updatedRow?.id ?? row.id,
2392
3550
  url,
2393
3551
  redirect: true,
2394
3552
  reused: false,
@@ -2408,16 +3566,23 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
2408
3566
  const user = requireUser(ctx);
2409
3567
  const adapter = getAdapter2(ctx);
2410
3568
  const row = await adapter.findOne({
2411
- model: SUBSCRIPTION_MODEL2,
3569
+ model: SUBSCRIPTION_MODEL6,
2412
3570
  where: [{ field: "id", value: ctx.query.subscriptionId }]
2413
3571
  });
2414
3572
  if (!row) {
2415
3573
  throw new api.APIError("NOT_FOUND", {
2416
- code: "SUBSCRIPTION_NOT_FOUND",
3574
+ code: $ERROR_CODES.SUBSCRIPTION_NOT_FOUND.code,
2417
3575
  message: "Subscription not found."
2418
3576
  });
2419
3577
  }
2420
- await authorizeReference(ctx, user, row.referenceId, "read", subsOptions);
3578
+ await authorizeReference(
3579
+ ctx,
3580
+ user,
3581
+ row.referenceId,
3582
+ row.referenceType ?? "user",
3583
+ "read",
3584
+ subsOptions
3585
+ );
2421
3586
  if (row.status !== "incomplete") {
2422
3587
  return ctx.json({
2423
3588
  subscription: row,
@@ -2436,28 +3601,31 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
2436
3601
  );
2437
3602
  return ctx.json({ subscription: row, synced: false });
2438
3603
  }
2439
- const list = await client.listSubscriptions({ page: 1, size: 100 });
2440
- const match = list.data?.find(
2441
- (sub) => sub.organization_consumer_id === row.streampayConsumerId && sub.status !== "CANCELED" && Array.isArray(sub.items) && sub.items.some((item) => subscriptionItemProductId(item) === plan.productId)
2442
- );
3604
+ let page = 1;
3605
+ let match;
3606
+ do {
3607
+ const list = await client.listSubscriptions({
3608
+ page,
3609
+ size: 100,
3610
+ organization_consumer_id: row.streampayConsumerId
3611
+ });
3612
+ match = list.data?.find(
3613
+ (sub) => isCheckoutSubscriptionCandidate(sub, row, plan.productId)
3614
+ );
3615
+ if (match || !list.pagination?.has_next_page) break;
3616
+ page += 1;
3617
+ } while (page <= 1e3);
2443
3618
  if (!match?.id) {
2444
3619
  return ctx.json({ subscription: row, synced: false });
2445
3620
  }
2446
3621
  const updated = await adapter.update({
2447
- model: SUBSCRIPTION_MODEL2,
3622
+ model: SUBSCRIPTION_MODEL6,
2448
3623
  update: {
2449
- streampaySubscriptionId: match.id,
2450
- status: match.status === "ACTIVE" ? "active" : "incomplete",
2451
- periodStart: match.current_period_start ? new Date(match.current_period_start) : null,
2452
- periodEnd: match.current_period_end ? new Date(match.current_period_end) : null,
2453
- amountHalalat: (() => {
2454
- if (!match.amount) return row.amountHalalat;
2455
- try {
2456
- return StreamPayAmount.toHalalat(match.amount);
2457
- } catch {
2458
- return row.amountHalalat;
2459
- }
2460
- })(),
3624
+ ...projectSubscriptionFields(match),
3625
+ planVersion: plan.version ?? null,
3626
+ productId: plan.productId,
3627
+ billingStatus: "current",
3628
+ activeSlotKey: row.activeSlotKey ?? subscriptionSlotKey(row.referenceType ?? "user", row.referenceId, row.group),
2461
3629
  updatedAt: /* @__PURE__ */ new Date()
2462
3630
  },
2463
3631
  where: [{ field: "id", value: row.id }]
@@ -2480,72 +3648,53 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
2480
3648
  use: [api.sessionMiddleware]
2481
3649
  },
2482
3650
  async (ctx) => {
2483
- const user = requireUser(ctx);
2484
- const adapter = getAdapter2(ctx);
2485
- const row = await findOwnedSubscription(
3651
+ const { adapter, row } = await requireConfirmedOwnedSubscription(
2486
3652
  ctx,
2487
- user,
2488
3653
  ctx.body.subscriptionId,
2489
3654
  subsOptions,
2490
3655
  "cancel"
2491
3656
  );
2492
- if (row.status === "canceled") {
2493
- throw new api.APIError("BAD_REQUEST", {
2494
- code: "SUBSCRIPTION_ALREADY_CANCELED",
2495
- message: "Subscription is already canceled."
2496
- });
2497
- }
2498
- if (row.cancelAtPeriodEnd) {
2499
- throw new api.APIError("BAD_REQUEST", {
2500
- code: "SUBSCRIPTION_ALREADY_SCHEDULED_CANCEL",
2501
- message: "Subscription is already scheduled to cancel at period end."
2502
- });
2503
- }
2504
- if (!row.streampaySubscriptionId) {
2505
- throw new api.APIError("BAD_REQUEST", {
2506
- code: "SUBSCRIPTION_INVALID_STATE",
2507
- message: "Subscription has not been confirmed by StreamPay yet."
2508
- });
2509
- }
2510
- if (ctx.body.cancelAtPeriodEnd) {
2511
- try {
2512
- const stream = await client.getSubscription(row.streampaySubscriptionId);
2513
- const patch = {
2514
- ...echoSubscriptionPatch(stream),
2515
- until_cycle_number: stream.current_cycle_number ?? 1
2516
- };
2517
- const result = await client.updateSubscription(row.streampaySubscriptionId, patch);
2518
- await adapter.update({
2519
- model: SUBSCRIPTION_MODEL2,
2520
- update: {
2521
- cancelAtPeriodEnd: true,
2522
- updatedAt: /* @__PURE__ */ new Date()
2523
- },
2524
- where: [{ field: "id", value: row.id }]
2525
- });
2526
- return ctx.json(result);
2527
- } catch (err) {
2528
- toAPIError(
2529
- {
2530
- logPrefix: `cancelAtPeriodEnd failed for row=${row.id}:`,
2531
- userMessage: "Subscription cancel-at-period-end failed."
2532
- },
2533
- err,
2534
- getLogger(ctx)
2535
- );
2536
- }
2537
- }
2538
3657
  const payload = {
2539
3658
  cancel_related_invoices: ctx.body.cancelRelatedInvoices ?? false
2540
3659
  };
2541
3660
  try {
3661
+ const stream = await client.getSubscription(row.streampaySubscriptionId);
3662
+ if (stream.status === "CANCELED") {
3663
+ await adapter.update({
3664
+ model: SUBSCRIPTION_MODEL6,
3665
+ update: projectSubscriptionAgainstExisting(row, stream),
3666
+ where: [{ field: "id", value: row.id }]
3667
+ });
3668
+ return ctx.json(stream);
3669
+ }
3670
+ if (ctx.body.cancelAtPeriodEnd === false && stream.status === "ACTIVE") {
3671
+ throw new api.APIError("BAD_REQUEST", {
3672
+ code: $ERROR_CODES.SUBSCRIPTION_IMMEDIATE_CANCEL_UNSUPPORTED.code,
3673
+ message: "StreamPay cancels active subscriptions at period end. Immediate cancellation is only available for inactive or trial subscriptions."
3674
+ });
3675
+ }
3676
+ if (stream.cancel_at_period_end && !ctx.body.cancelRelatedInvoices) {
3677
+ await adapter.update({
3678
+ model: SUBSCRIPTION_MODEL6,
3679
+ update: projectSubscriptionAgainstExisting(row, stream),
3680
+ where: [{ field: "id", value: row.id }]
3681
+ });
3682
+ return ctx.json(stream);
3683
+ }
3684
+ if (ctx.body.cancelAtPeriodEnd === true && stream.status !== "ACTIVE") {
3685
+ throw new api.APIError("BAD_REQUEST", {
3686
+ code: $ERROR_CODES.SUBSCRIPTION_PERIOD_END_CANCEL_UNSUPPORTED.code,
3687
+ message: "StreamPay only schedules period-end cancellation for active subscriptions. This subscription would be canceled immediately."
3688
+ });
3689
+ }
2542
3690
  const result = await client.cancelSubscription(row.streampaySubscriptionId, payload);
2543
3691
  await syncSubscriptionFromUpstream(
2544
3692
  client,
2545
3693
  adapter,
2546
3694
  row.streampaySubscriptionId,
2547
3695
  getLogger(ctx),
2548
- "cancelSubscription"
3696
+ "cancelSubscription",
3697
+ result
2549
3698
  );
2550
3699
  return ctx.json(result);
2551
3700
  } catch (err) {
@@ -2568,150 +3717,102 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
2568
3717
  use: [api.sessionMiddleware]
2569
3718
  },
2570
3719
  async (ctx) => {
2571
- const user = requireUser(ctx);
2572
- const adapter = getAdapter2(ctx);
3720
+ const { adapter, row } = await requireConfirmedOwnedSubscription(
3721
+ ctx,
3722
+ ctx.body.subscriptionId,
3723
+ subsOptions,
3724
+ "change-plan"
3725
+ );
2573
3726
  const plans = await plansRef();
2574
3727
  const nextPlan = plans.byName.get(ctx.body.plan);
2575
3728
  if (!nextPlan) {
2576
3729
  throw new api.APIError("NOT_FOUND", {
2577
- code: "SUBSCRIPTION_PLAN_NOT_FOUND",
3730
+ code: $ERROR_CODES.SUBSCRIPTION_PLAN_NOT_FOUND.code,
2578
3731
  message: `Plan "${ctx.body.plan}" is not configured.`
2579
3732
  });
2580
3733
  }
2581
- const existing = await adapter.findMany({
2582
- model: SUBSCRIPTION_MODEL2,
2583
- where: [
2584
- { field: "referenceId", value: user.id },
2585
- ...nextPlan.group ? [{ field: "group", value: nextPlan.group }] : []
2586
- ]
2587
- });
2588
- const row = existing.find(
2589
- (r) => r.status === "active" || r.status === "frozen" || r.status === "past_due"
2590
- );
2591
- if (!row) {
2592
- throw new api.APIError("NOT_FOUND", {
2593
- code: "SUBSCRIPTION_NOT_FOUND",
2594
- message: "No active subscription to change plan from."
2595
- });
2596
- }
2597
- await authorizeReference(ctx, user, row.referenceId, "change-plan", subsOptions);
2598
- if (!row.streampaySubscriptionId) {
2599
- throw new api.APIError("BAD_REQUEST", {
2600
- code: "SUBSCRIPTION_INVALID_STATE",
2601
- message: "Subscription has not been confirmed by StreamPay yet."
2602
- });
2603
- }
2604
- if (row.plan === nextPlan.name) {
2605
- throw new api.APIError("BAD_REQUEST", {
2606
- code: "SUBSCRIPTION_ALREADY_ON_PLAN",
2607
- message: `Already on plan "${nextPlan.name}".`
2608
- });
2609
- }
2610
- const mode = ctx.body.mode ?? "at_period_end";
2611
- if (mode === "immediate") {
2612
- try {
2613
- const stream = await client.getSubscription(row.streampaySubscriptionId);
2614
- const existingCoupons = [];
2615
- for (const c of stream.coupon_calculation_metadata?.coupons ?? []) {
2616
- if (c.coupon_id) existingCoupons.push(c.coupon_id);
2617
- }
2618
- const patch = {
2619
- items: [{ product_id: nextPlan.productId, quantity: 1 }],
2620
- coupons: existingCoupons
2621
- };
2622
- const result = await client.updateSubscription(row.streampaySubscriptionId, patch);
3734
+ try {
3735
+ const stream = await client.getSubscription(row.streampaySubscriptionId);
3736
+ const currentPlan = configuredPlanForSubscription(stream, plans);
3737
+ const currentGroup = currentPlan?.group ?? row.group;
3738
+ if (currentGroup !== (nextPlan.group ?? null)) {
3739
+ throw new api.APIError("BAD_REQUEST", {
3740
+ code: $ERROR_CODES.SUBSCRIPTION_PLAN_GROUP_MISMATCH.code,
3741
+ message: "A subscription can only change to another plan in the same configured group."
3742
+ });
3743
+ }
3744
+ if (stream.cancel_at_period_end) {
3745
+ throw new api.APIError("CONFLICT", {
3746
+ code: $ERROR_CODES.SUBSCRIPTION_ALREADY_SCHEDULED_CANCEL.code,
3747
+ message: "The subscription is scheduled to cancel. Uncancel it before scheduling a plan change."
3748
+ });
3749
+ }
3750
+ const currentProductIsRequestedPlan = stream.items?.some(
3751
+ (item) => subscriptionItemProductId(item) === nextPlan.productId
3752
+ );
3753
+ if (currentProductIsRequestedPlan && !stream.pending_change) {
3754
+ throw new api.APIError("BAD_REQUEST", {
3755
+ code: $ERROR_CODES.SUBSCRIPTION_ALREADY_ON_PLAN.code,
3756
+ message: `Already on plan "${nextPlan.name}".`
3757
+ });
3758
+ }
3759
+ const pendingTargets = stream.pending_change?.target_items ?? [];
3760
+ const pendingTargetIsRequestedPlan = pendingTargets.some(
3761
+ (item) => subscriptionItemProductId(item) === nextPlan.productId
3762
+ );
3763
+ if (pendingTargetIsRequestedPlan) {
2623
3764
  await adapter.update({
2624
- model: SUBSCRIPTION_MODEL2,
3765
+ model: SUBSCRIPTION_MODEL6,
2625
3766
  update: {
2626
- plan: nextPlan.name,
2627
- group: nextPlan.group ?? null,
2628
- updatedAt: /* @__PURE__ */ new Date()
3767
+ ...projectSubscriptionAgainstExisting(row, stream),
3768
+ pendingPlan: nextPlan.name,
3769
+ pendingProductId: nextPlan.productId,
3770
+ pendingPlanEffectiveAt: stream.pending_change?.effective_at ? new Date(stream.pending_change.effective_at) : null
2629
3771
  },
2630
3772
  where: [{ field: "id", value: row.id }]
2631
3773
  });
2632
- await syncSubscriptionFromUpstream(
2633
- client,
2634
- adapter,
2635
- row.streampaySubscriptionId,
2636
- getLogger(ctx),
2637
- "changeSubscriptionPlan"
2638
- );
2639
3774
  return ctx.json({
2640
- mode: "immediate",
2641
- subscription: result,
2642
- plan: nextPlan.name
3775
+ mode: "at_period_end",
3776
+ subscriptionId: row.id,
3777
+ plan: nextPlan.name,
3778
+ effectiveAt: stream.pending_change?.effective_at ?? null,
3779
+ pendingChange: stream.pending_change,
3780
+ reused: true
3781
+ });
3782
+ }
3783
+ if (stream.pending_change) {
3784
+ throw new api.APIError("CONFLICT", {
3785
+ code: $ERROR_CODES.SUBSCRIPTION_PLAN_CHANGE_ALREADY_SCHEDULED.code,
3786
+ message: "A different plan change is already scheduled. Cancel it before scheduling another."
2643
3787
  });
2644
- } catch (err) {
2645
- toAPIError(
2646
- {
2647
- logPrefix: `change-plan (immediate) failed for row=${row.id}:`,
2648
- userMessage: "Plan change failed."
2649
- },
2650
- err,
2651
- getLogger(ctx)
2652
- );
2653
3788
  }
2654
- }
2655
- try {
2656
- const stream = await client.getSubscription(row.streampaySubscriptionId);
2657
3789
  const patch = {
2658
- ...echoSubscriptionPatch(stream),
2659
- until_cycle_number: stream.current_cycle_number ?? 1
3790
+ items: [{ product_id: nextPlan.productId, quantity: 1 }],
3791
+ coupons: subscriptionCouponIds(stream),
3792
+ recurring_interval: nextPlan.billingInterval,
3793
+ recurring_interval_count: nextPlan.billingIntervalCount ?? 1
2660
3794
  };
2661
- await client.updateSubscription(row.streampaySubscriptionId, patch);
3795
+ const result = await client.updateSubscription(row.streampaySubscriptionId, patch);
3796
+ const effectiveAt = result.pending_change?.effective_at ?? result.current_period_end ?? null;
2662
3797
  await adapter.update({
2663
- model: SUBSCRIPTION_MODEL2,
3798
+ model: SUBSCRIPTION_MODEL6,
2664
3799
  update: {
2665
- cancelAtPeriodEnd: true,
3800
+ ...projectSubscriptionAgainstExisting(row, result),
3801
+ pendingPlan: nextPlan.name,
3802
+ pendingProductId: nextPlan.productId,
3803
+ pendingPlanEffectiveAt: effectiveAt ? new Date(effectiveAt) : null,
2666
3804
  updatedAt: /* @__PURE__ */ new Date()
2667
3805
  },
2668
3806
  where: [{ field: "id", value: row.id }]
2669
3807
  });
2670
- const ensureCtx = { context: ctx.context };
2671
- const { consumerId } = await ensureConsumerForUser(options, ensureCtx, user);
2672
- const linkInput = {
2673
- name: `Plan change \u2014 ${nextPlan.name}`,
2674
- items: [
2675
- {
2676
- product_id: nextPlan.productId,
2677
- quantity: 1,
2678
- allow_custom_quantity: false
2679
- }
2680
- ],
2681
- max_number_of_payments: 1,
2682
- organization_consumer_id: consumerId,
2683
- custom_metadata: {
2684
- [PLAN_NAME_METADATA_KEY]: nextPlan.name,
2685
- [REFERENCE_ID_METADATA_KEY]: user.id
2686
- }
2687
- };
2688
- if (ctx.body.successUrl) linkInput.success_redirect_url = ctx.body.successUrl;
2689
- if (ctx.body.failureUrl) linkInput.failure_redirect_url = ctx.body.failureUrl;
2690
- const link = await client.createPaymentLink(linkInput);
2691
- const url = client.getPaymentUrl(link);
2692
- const nextRow = await adapter.create({
2693
- model: SUBSCRIPTION_MODEL2,
2694
- data: {
2695
- referenceId: user.id,
2696
- plan: nextPlan.name,
2697
- group: nextPlan.group ?? null,
2698
- streampayConsumerId: consumerId,
2699
- status: "incomplete",
2700
- amountHalalat: nextPlan.priceHalalat,
2701
- currency: "SAR",
2702
- billingInterval: nextPlan.billingInterval,
2703
- billingIntervalCount: nextPlan.billingIntervalCount ?? 1,
2704
- cancelAtPeriodEnd: false,
2705
- createdAt: /* @__PURE__ */ new Date(),
2706
- updatedAt: /* @__PURE__ */ new Date()
2707
- }
2708
- });
2709
3808
  return ctx.json({
2710
3809
  mode: "at_period_end",
2711
- currentSubscriptionId: row.id,
2712
- nextSubscriptionId: nextRow.id,
2713
- url,
2714
- plan: nextPlan.name
3810
+ subscriptionId: row.id,
3811
+ plan: nextPlan.name,
3812
+ effectiveAt,
3813
+ pendingChange: result.pending_change ?? null,
3814
+ subscription: result,
3815
+ reused: false
2715
3816
  });
2716
3817
  } catch (err) {
2717
3818
  toAPIError(
@@ -2725,35 +3826,95 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
2725
3826
  }
2726
3827
  }
2727
3828
  ),
2728
- freezeSubscription: api.createAuthEndpoint(
2729
- "/subscription/freeze",
3829
+ cancelSubscriptionPlanChange: api.createAuthEndpoint(
3830
+ "/subscription/change-plan/cancel",
2730
3831
  {
2731
3832
  method: "POST",
2732
- body: FreezeBody,
3833
+ body: UnfreezeBody,
2733
3834
  use: [api.sessionMiddleware]
2734
3835
  },
2735
3836
  async (ctx) => {
2736
- const user = requireUser(ctx);
2737
- const adapter = getAdapter2(ctx);
2738
- const row = await findOwnedSubscription(
3837
+ const { adapter, row } = await requireConfirmedOwnedSubscription(
2739
3838
  ctx,
2740
- user,
2741
3839
  ctx.body.subscriptionId,
2742
3840
  subsOptions,
2743
- "freeze"
3841
+ "cancel-plan-change"
2744
3842
  );
2745
- if (row.status !== "active") {
2746
- throw new api.APIError("BAD_REQUEST", {
2747
- code: "SUBSCRIPTION_INVALID_STATE",
2748
- message: "Only active subscriptions can be frozen."
3843
+ try {
3844
+ await client.deletePendingSubscriptionChange(row.streampaySubscriptionId);
3845
+ const stream = await client.getSubscription(row.streampaySubscriptionId);
3846
+ await adapter.update({
3847
+ model: SUBSCRIPTION_MODEL6,
3848
+ update: {
3849
+ ...projectSubscriptionAgainstExisting(row, stream),
3850
+ pendingPlan: null,
3851
+ pendingProductId: null,
3852
+ pendingPlanEffectiveAt: null
3853
+ },
3854
+ where: [{ field: "id", value: row.id }]
2749
3855
  });
3856
+ return ctx.json({ canceled: true, subscription: stream });
3857
+ } catch (err) {
3858
+ toAPIError(
3859
+ {
3860
+ logPrefix: `cancel plan change failed for row=${row.id}:`,
3861
+ userMessage: "Canceling the scheduled plan change failed."
3862
+ },
3863
+ err,
3864
+ getLogger(ctx)
3865
+ );
2750
3866
  }
2751
- if (!row.streampaySubscriptionId) {
2752
- throw new api.APIError("BAD_REQUEST", {
2753
- code: "SUBSCRIPTION_INVALID_STATE",
2754
- message: "Subscription has not been confirmed by StreamPay yet."
3867
+ }
3868
+ ),
3869
+ uncancelSubscription: api.createAuthEndpoint(
3870
+ "/subscription/uncancel",
3871
+ {
3872
+ method: "POST",
3873
+ body: UnfreezeBody,
3874
+ use: [api.sessionMiddleware]
3875
+ },
3876
+ async (ctx) => {
3877
+ const { adapter, row } = await requireConfirmedOwnedSubscription(
3878
+ ctx,
3879
+ ctx.body.subscriptionId,
3880
+ subsOptions,
3881
+ "uncancel"
3882
+ );
3883
+ try {
3884
+ await client.uncancelSubscription(row.streampaySubscriptionId);
3885
+ const stream = await client.getSubscription(row.streampaySubscriptionId);
3886
+ await adapter.update({
3887
+ model: SUBSCRIPTION_MODEL6,
3888
+ update: projectSubscriptionAgainstExisting(row, stream),
3889
+ where: [{ field: "id", value: row.id }]
2755
3890
  });
3891
+ return ctx.json({ uncanceled: true, subscription: stream });
3892
+ } catch (err) {
3893
+ toAPIError(
3894
+ {
3895
+ logPrefix: `uncancel subscription failed for row=${row.id}:`,
3896
+ userMessage: "Restoring subscription renewal failed."
3897
+ },
3898
+ err,
3899
+ getLogger(ctx)
3900
+ );
2756
3901
  }
3902
+ }
3903
+ ),
3904
+ freezeSubscription: api.createAuthEndpoint(
3905
+ "/subscription/freeze",
3906
+ {
3907
+ method: "POST",
3908
+ body: FreezeBody,
3909
+ use: [api.sessionMiddleware]
3910
+ },
3911
+ async (ctx) => {
3912
+ const { adapter, row } = await requireConfirmedOwnedSubscription(
3913
+ ctx,
3914
+ ctx.body.subscriptionId,
3915
+ subsOptions,
3916
+ "freeze"
3917
+ );
2757
3918
  const payload = {
2758
3919
  freeze_start_datetime: ctx.body.freezeStartDatetime
2759
3920
  };
@@ -2793,27 +3954,12 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
2793
3954
  use: [api.sessionMiddleware]
2794
3955
  },
2795
3956
  async (ctx) => {
2796
- const user = requireUser(ctx);
2797
- const adapter = getAdapter2(ctx);
2798
- const row = await findOwnedSubscription(
3957
+ const { adapter, row } = await requireConfirmedOwnedSubscription(
2799
3958
  ctx,
2800
- user,
2801
3959
  ctx.body.subscriptionId,
2802
3960
  subsOptions,
2803
3961
  "unfreeze"
2804
3962
  );
2805
- if (row.status !== "frozen") {
2806
- throw new api.APIError("BAD_REQUEST", {
2807
- code: "SUBSCRIPTION_NOT_FROZEN",
2808
- message: "Subscription is not currently frozen."
2809
- });
2810
- }
2811
- if (!row.streampaySubscriptionId) {
2812
- throw new api.APIError("BAD_REQUEST", {
2813
- code: "SUBSCRIPTION_INVALID_STATE",
2814
- message: "Subscription has not been confirmed by StreamPay yet."
2815
- });
2816
- }
2817
3963
  const nowMs = Date.now();
2818
3964
  try {
2819
3965
  const freezes = await client.listSubscriptionFreezes(row.streampaySubscriptionId);
@@ -2825,130 +3971,79 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
2825
3971
  });
2826
3972
  if (!active?.id || !active.freeze_start_datetime) {
2827
3973
  throw new api.APIError("BAD_REQUEST", {
2828
- code: "SUBSCRIPTION_NOT_FROZEN",
2829
- message: "No active freeze period found to cancel."
2830
- });
2831
- }
2832
- await client.updateSubscriptionFreeze(row.streampaySubscriptionId, active.id, {
2833
- freeze_start_datetime: active.freeze_start_datetime,
2834
- freeze_end_datetime: new Date(nowMs).toISOString(),
2835
- notes: active.notes ?? null
2836
- });
2837
- await syncSubscriptionFromUpstream(
2838
- client,
2839
- adapter,
2840
- row.streampaySubscriptionId,
2841
- getLogger(ctx),
2842
- "unfreezeSubscription"
2843
- );
2844
- return ctx.json({ unfrozen: true });
2845
- } catch (err) {
2846
- toAPIError(
2847
- {
2848
- logPrefix: `unfreezeSubscription failed for row=${row.id}:`,
2849
- userMessage: "Subscription unfreeze failed."
2850
- },
2851
- err,
2852
- getLogger(ctx)
2853
- );
2854
- }
2855
- }
2856
- ),
2857
- listSubscriptions: api.createAuthEndpoint(
2858
- "/subscription/list",
2859
- {
2860
- method: "GET",
2861
- use: [api.sessionMiddleware]
2862
- },
2863
- async (ctx) => {
2864
- const user = requireUser(ctx);
2865
- const adapter = getAdapter2(ctx);
2866
- const rows = await adapter.findMany({
2867
- model: SUBSCRIPTION_MODEL2,
2868
- where: [{ field: "referenceId", value: user.id }]
2869
- });
2870
- const plans = await plansRef();
2871
- return ctx.json(
2872
- rows.map((row) => ({
2873
- ...row,
2874
- plan: plans.byName.get(row.plan) ?? null
2875
- }))
2876
- );
2877
- }
2878
- ),
2879
- currentSubscription: api.createAuthEndpoint(
2880
- "/subscription/current",
2881
- {
2882
- method: "GET",
2883
- query: CurrentQuery,
2884
- use: [api.sessionMiddleware]
2885
- },
2886
- async (ctx) => {
2887
- const user = requireUser(ctx);
2888
- const adapter = getAdapter2(ctx);
2889
- const where = [
2890
- { field: "referenceId", value: user.id }
2891
- ];
2892
- if (ctx.query?.group) {
2893
- where.push({ field: "group", value: ctx.query.group });
2894
- }
2895
- const rows = await adapter.findMany({
2896
- model: SUBSCRIPTION_MODEL2,
2897
- where
2898
- });
2899
- const live = rows.find(
2900
- (row) => row.status === "active" || row.status === "frozen" || row.status === "past_due"
2901
- );
2902
- if (!live) return ctx.json(null);
2903
- const plans = await plansRef();
2904
- return ctx.json({
2905
- ...live,
2906
- plan: plans.byName.get(live.plan) ?? null
2907
- });
2908
- }
2909
- ),
2910
- hasSubscriptionFeature: api.createAuthEndpoint(
2911
- "/subscription/has-feature",
2912
- {
2913
- method: "GET",
2914
- query: HasFeatureQuery,
2915
- use: [api.sessionMiddleware]
2916
- },
2917
- async (ctx) => {
2918
- const user = requireUser(ctx);
2919
- const adapter = getAdapter2(ctx);
2920
- const where = [
2921
- { field: "referenceId", value: user.id }
2922
- ];
2923
- if (ctx.query.group) where.push({ field: "group", value: ctx.query.group });
2924
- const rows = await adapter.findMany({ model: SUBSCRIPTION_MODEL2, where });
2925
- const plans = await plansRef();
2926
- const live = rows.find((row) => row.status === "active" || row.status === "frozen");
2927
- if (!live) return ctx.json({ hasFeature: false });
2928
- const plan = plans.byName.get(live.plan);
2929
- return ctx.json({ hasFeature: hasFeature(live, plan, ctx.query.feature) });
3974
+ code: $ERROR_CODES.SUBSCRIPTION_FREEZE_NOT_ACTIVE.code,
3975
+ message: "No active freeze period found to cancel."
3976
+ });
3977
+ }
3978
+ await client.updateSubscriptionFreeze(row.streampaySubscriptionId, active.id, {
3979
+ freeze_start_datetime: active.freeze_start_datetime,
3980
+ freeze_end_datetime: new Date(nowMs).toISOString(),
3981
+ notes: active.notes ?? null
3982
+ });
3983
+ await syncSubscriptionFromUpstream(
3984
+ client,
3985
+ adapter,
3986
+ row.streampaySubscriptionId,
3987
+ getLogger(ctx),
3988
+ "unfreezeSubscription"
3989
+ );
3990
+ return ctx.json({ unfrozen: true });
3991
+ } catch (err) {
3992
+ toAPIError(
3993
+ {
3994
+ logPrefix: `unfreezeSubscription failed for row=${row.id}:`,
3995
+ userMessage: "Subscription unfreeze failed."
3996
+ },
3997
+ err,
3998
+ getLogger(ctx)
3999
+ );
4000
+ }
2930
4001
  }
2931
4002
  ),
2932
- checkSubscriptionLimit: api.createAuthEndpoint(
2933
- "/subscription/check-limit",
4003
+ cancelSubscriptionFreeze: api.createAuthEndpoint(
4004
+ "/subscription/freeze/cancel",
2934
4005
  {
2935
- method: "GET",
2936
- query: CheckLimitQuery,
4006
+ method: "POST",
4007
+ body: CancelFreezeBody,
2937
4008
  use: [api.sessionMiddleware]
2938
4009
  },
2939
4010
  async (ctx) => {
2940
- const user = requireUser(ctx);
2941
- const adapter = getAdapter2(ctx);
2942
- const where = [
2943
- { field: "referenceId", value: user.id }
2944
- ];
2945
- if (ctx.query.group) where.push({ field: "group", value: ctx.query.group });
2946
- const rows = await adapter.findMany({ model: SUBSCRIPTION_MODEL2, where });
2947
- const plans = await plansRef();
2948
- const live = rows.find((row) => row.status === "active" || row.status === "frozen");
2949
- if (!live) return ctx.json({ allowed: false, limit: 0, remaining: 0 });
2950
- const plan = plans.byName.get(live.plan);
2951
- return ctx.json(checkLimit(live, plan, ctx.query.feature, ctx.query.count));
4011
+ const { adapter, row } = await requireConfirmedOwnedSubscription(
4012
+ ctx,
4013
+ ctx.body.subscriptionId,
4014
+ subsOptions,
4015
+ "cancel-freeze"
4016
+ );
4017
+ try {
4018
+ const freezes = await client.listSubscriptionFreezes(row.streampaySubscriptionId);
4019
+ if (!freezes.data?.some((freeze) => freeze.id === ctx.body.freezeId)) {
4020
+ return ctx.json({ canceled: true, freezeId: ctx.body.freezeId, reused: true });
4021
+ }
4022
+ await client.deleteSubscriptionFreeze(row.streampaySubscriptionId, ctx.body.freezeId);
4023
+ await syncSubscriptionFromUpstream(
4024
+ client,
4025
+ adapter,
4026
+ row.streampaySubscriptionId,
4027
+ getLogger(ctx),
4028
+ "cancelSubscriptionFreeze"
4029
+ );
4030
+ return ctx.json({ canceled: true, freezeId: ctx.body.freezeId, reused: false });
4031
+ } catch (err) {
4032
+ if (isAlreadyCanceledFreezeError(err)) {
4033
+ getLogger(ctx).info(
4034
+ `cancel subscription freeze reused provider tombstone for row=${row.id} freeze=${ctx.body.freezeId}.`
4035
+ );
4036
+ return ctx.json({ canceled: true, freezeId: ctx.body.freezeId, reused: true });
4037
+ }
4038
+ toAPIError(
4039
+ {
4040
+ logPrefix: `cancel subscription freeze failed for row=${row.id}:`,
4041
+ userMessage: "Canceling the subscription freeze failed."
4042
+ },
4043
+ err,
4044
+ getLogger(ctx)
4045
+ );
4046
+ }
2952
4047
  }
2953
4048
  )
2954
4049
  };
@@ -2961,6 +4056,19 @@ var subscriptionTable = {
2961
4056
  referenceId: {
2962
4057
  type: "string",
2963
4058
  required: true,
4059
+ input: false,
4060
+ index: true
4061
+ },
4062
+ referenceType: {
4063
+ type: "string",
4064
+ required: false,
4065
+ defaultValue: "user",
4066
+ input: false
4067
+ },
4068
+ activeSlotKey: {
4069
+ type: "string",
4070
+ required: false,
4071
+ unique: true,
2964
4072
  input: false
2965
4073
  },
2966
4074
  streampaySubscriptionId: {
@@ -2972,17 +4080,38 @@ var subscriptionTable = {
2972
4080
  streampayConsumerId: {
2973
4081
  type: "string",
2974
4082
  required: false,
4083
+ input: false,
4084
+ index: true
4085
+ },
4086
+ streampayPaymentLinkId: {
4087
+ type: "string",
4088
+ required: false,
4089
+ unique: true,
2975
4090
  input: false
2976
4091
  },
2977
4092
  plan: {
2978
4093
  type: "string",
2979
4094
  required: true
2980
4095
  },
4096
+ planVersion: {
4097
+ type: "string",
4098
+ required: false
4099
+ },
4100
+ productId: {
4101
+ type: "string",
4102
+ required: false,
4103
+ index: true
4104
+ },
2981
4105
  group: {
2982
4106
  type: "string",
4107
+ required: false,
4108
+ index: true
4109
+ },
4110
+ amountInSmallestUnit: {
4111
+ type: "number",
2983
4112
  required: false
2984
4113
  },
2985
- amountHalalat: {
4114
+ originalAmountInSmallestUnit: {
2986
4115
  type: "number",
2987
4116
  required: false
2988
4117
  },
@@ -3003,7 +4132,18 @@ var subscriptionTable = {
3003
4132
  status: {
3004
4133
  type: "string",
3005
4134
  required: false,
3006
- defaultValue: "incomplete"
4135
+ defaultValue: "incomplete",
4136
+ index: true
4137
+ },
4138
+ providerStatus: {
4139
+ type: "string",
4140
+ required: false
4141
+ },
4142
+ billingStatus: {
4143
+ type: "string",
4144
+ required: false,
4145
+ defaultValue: "current",
4146
+ index: true
3007
4147
  },
3008
4148
  periodStart: {
3009
4149
  type: "date",
@@ -3013,11 +4153,48 @@ var subscriptionTable = {
3013
4153
  type: "date",
3014
4154
  required: false
3015
4155
  },
4156
+ currentCycleNumber: {
4157
+ type: "number",
4158
+ required: false
4159
+ },
4160
+ trialStart: {
4161
+ type: "date",
4162
+ required: false
4163
+ },
4164
+ trialEnd: {
4165
+ type: "date",
4166
+ required: false
4167
+ },
3016
4168
  cancelAtPeriodEnd: {
3017
4169
  type: "boolean",
3018
4170
  required: false,
3019
4171
  defaultValue: false
3020
4172
  },
4173
+ cancelAt: {
4174
+ type: "date",
4175
+ required: false
4176
+ },
4177
+ cancelScheduledAt: {
4178
+ type: "date",
4179
+ required: false
4180
+ },
4181
+ canceledAt: {
4182
+ type: "date",
4183
+ required: false
4184
+ },
4185
+ pendingPlan: {
4186
+ type: "string",
4187
+ required: false
4188
+ },
4189
+ pendingProductId: {
4190
+ type: "string",
4191
+ required: false,
4192
+ index: true
4193
+ },
4194
+ pendingPlanEffectiveAt: {
4195
+ type: "date",
4196
+ required: false
4197
+ },
3021
4198
  endedAt: {
3022
4199
  type: "date",
3023
4200
  required: false
@@ -3029,6 +4206,26 @@ var subscriptionTable = {
3029
4206
  freezeEndAt: {
3030
4207
  type: "date",
3031
4208
  required: false
4209
+ },
4210
+ providerUpdatedAt: {
4211
+ type: "date",
4212
+ required: false
4213
+ },
4214
+ syncedAt: {
4215
+ type: "date",
4216
+ required: false,
4217
+ index: true
4218
+ },
4219
+ createdAt: {
4220
+ type: "date",
4221
+ required: false,
4222
+ input: false
4223
+ },
4224
+ updatedAt: {
4225
+ type: "date",
4226
+ required: false,
4227
+ input: false,
4228
+ index: true
3032
4229
  }
3033
4230
  }
3034
4231
  }
@@ -3045,15 +4242,44 @@ var webhookEventTable = {
3045
4242
  type: "string",
3046
4243
  required: true
3047
4244
  },
3048
- processedAt: {
4245
+ receivedAt: {
3049
4246
  type: "date",
3050
4247
  required: true,
3051
4248
  index: true
3052
4249
  },
4250
+ lastAttemptAt: {
4251
+ type: "date",
4252
+ required: false,
4253
+ index: true
4254
+ },
4255
+ nextAttemptAt: {
4256
+ type: "date",
4257
+ required: false,
4258
+ index: true
4259
+ },
4260
+ completedAt: {
4261
+ type: "date",
4262
+ required: false,
4263
+ index: true
4264
+ },
4265
+ deadLetteredAt: {
4266
+ type: "date",
4267
+ required: false,
4268
+ index: true
4269
+ },
4270
+ lockedAt: {
4271
+ type: "date",
4272
+ required: false,
4273
+ index: true
4274
+ },
4275
+ lockedBy: {
4276
+ type: "string",
4277
+ required: false
4278
+ },
3053
4279
  status: {
3054
4280
  type: "string",
3055
4281
  required: false,
3056
- defaultValue: "completed",
4282
+ defaultValue: "pending",
3057
4283
  index: true
3058
4284
  },
3059
4285
  attemptCount: {
@@ -3061,10 +4287,6 @@ var webhookEventTable = {
3061
4287
  required: false,
3062
4288
  defaultValue: 1
3063
4289
  },
3064
- firstSeenAt: {
3065
- type: "date",
3066
- required: false
3067
- },
3068
4290
  rawPayload: {
3069
4291
  type: "string",
3070
4292
  required: false
@@ -3076,6 +4298,11 @@ var webhookEventTable = {
3076
4298
  lastError: {
3077
4299
  type: "string",
3078
4300
  required: false
4301
+ },
4302
+ lastErrorCode: {
4303
+ type: "string",
4304
+ required: false,
4305
+ index: true
3079
4306
  }
3080
4307
  }
3081
4308
  }
@@ -3092,17 +4319,18 @@ function subscriptions(subsOptions) {
3092
4319
  } else if (typeof subsOptions.plans !== "function") {
3093
4320
  throw new TypeError("subscriptions(): `plans` must be an array or an async factory function.");
3094
4321
  }
3095
- const flags = subsOptions;
3096
- if (flags.enableSubscriptionTable === false && flags.enableWebhookEventTable === true) {
3097
- throw new TypeError(
3098
- "subscriptions(): `enableWebhookEventTable: true` requires `enableSubscriptionTable: true` \u2014 the event lifecycle table is part of the subscription sync pipeline."
3099
- );
4322
+ if (subsOptions.maxWebhookAttempts !== void 0 && (!Number.isInteger(subsOptions.maxWebhookAttempts) || subsOptions.maxWebhookAttempts < 1)) {
4323
+ throw new TypeError("subscriptions(): `maxWebhookAttempts` must be a positive integer.");
4324
+ }
4325
+ for (const status of subsOptions.accessStatuses ?? []) {
4326
+ if (!SUBSCRIPTION_STATUSES.includes(status)) {
4327
+ throw new TypeError(`subscriptions(): invalid access status "${status}".`);
4328
+ }
3100
4329
  }
3101
- const tableEnabled = subsOptions.enableSubscriptionTable !== false;
3102
4330
  const dedupeEnabled = subsOptions.enableWebhookEventTable !== false;
3103
4331
  return (options, registry) => {
3104
4332
  const resolvePlans = createPlanResolver(subsOptions.plans);
3105
- if (registry && tableEnabled) {
4333
+ if (registry) {
3106
4334
  registry.subscriptionWebhookSync = async (ctx, payload, meta) => {
3107
4335
  const syncCtx = {
3108
4336
  context: ctx.context
@@ -3115,7 +4343,8 @@ function subscriptions(subsOptions) {
3115
4343
  signatureHeader: meta?.signatureHeader ?? null,
3116
4344
  ...subsOptions.maxWebhookAttempts !== void 0 && {
3117
4345
  maxAttempts: subsOptions.maxWebhookAttempts
3118
- }
4346
+ },
4347
+ retryOnCallbackError: subsOptions.retryOnCallbackError !== false
3119
4348
  });
3120
4349
  } catch (err) {
3121
4350
  if (classifyWebhookFailure(err) === "PERMANENT") {
@@ -3148,28 +4377,59 @@ function subscriptions(subsOptions) {
3148
4377
  message: `Webhook event ${eventId} has no rawPayload \u2014 nothing to replay (already completed cleanly?).`
3149
4378
  });
3150
4379
  }
3151
- const payload = JSON.parse(row.rawPayload);
4380
+ let parsedPayload;
4381
+ try {
4382
+ parsedPayload = JSON.parse(row.rawPayload);
4383
+ } catch {
4384
+ throw new api.APIError("BAD_REQUEST", {
4385
+ message: `Webhook event ${eventId} has malformed stored JSON.`
4386
+ });
4387
+ }
4388
+ if (!isStreamPayWebhookEnvelope(parsedPayload) || !isKnownStreamPayWebhookPayload(parsedPayload)) {
4389
+ throw new api.APIError("BAD_REQUEST", {
4390
+ message: `Webhook event ${eventId} has an invalid stored payload.`
4391
+ });
4392
+ }
4393
+ const payload = parsedPayload;
3152
4394
  const plans = await resolvePlans();
4395
+ const claimed = await claimWebhookEventForReplay(syncCtx, row);
4396
+ if (!claimed?.lockedBy) {
4397
+ throw new api.APIError("CONFLICT", {
4398
+ code: $ERROR_CODES.WEBHOOK_REPLAY_IN_PROGRESS.code,
4399
+ message: `Webhook event ${eventId} is already being replayed.`
4400
+ });
4401
+ }
3153
4402
  try {
3154
4403
  await syncWebhookPayload(syncCtx, payload, options.client, plans, subsOptions, {
3155
- dedupe: false
4404
+ dedupe: false,
4405
+ retryingRenewalCallback: claimed.lastError?.startsWith(
4406
+ "Subscription callback onSubscriptionRenewed failed:"
4407
+ ) === true
3156
4408
  });
3157
- await markWebhookEventCompleted(syncCtx, row.id);
4409
+ await markWebhookEventCompleted(syncCtx, claimed.id, claimed.lockedBy);
3158
4410
  return { replayed: true, eventId };
3159
4411
  } catch (err) {
3160
- await recordWebhookEventFailure(syncCtx, row.id, null, null, err);
4412
+ await recordWebhookEventFailure(
4413
+ syncCtx,
4414
+ claimed.id,
4415
+ null,
4416
+ null,
4417
+ err,
4418
+ claimed.lockedBy,
4419
+ true
4420
+ );
3161
4421
  throw err;
3162
4422
  }
3163
4423
  };
3164
4424
  }
3165
4425
  }
3166
4426
  const schema = {
3167
- ...tableEnabled ? subscriptionTable : {},
3168
- ...tableEnabled && dedupeEnabled ? webhookEventTable : {}
4427
+ ...subscriptionTable,
4428
+ ...dedupeEnabled ? webhookEventTable : {}
3169
4429
  };
3170
4430
  return {
3171
4431
  endpoints: buildSubscriptionEndpoints(options, subsOptions, resolvePlans),
3172
- ...Object.keys(schema).length > 0 ? { schema } : {}
4432
+ schema
3173
4433
  };
3174
4434
  };
3175
4435
  }
@@ -3177,6 +4437,7 @@ function subscriptions(subsOptions) {
3177
4437
  // src/webhooks/dispatcher.ts
3178
4438
  async function dispatchWebhook(payload, handlers) {
3179
4439
  if (handlers.onPayload) await handlers.onPayload(payload);
4440
+ if (!isKnownStreamPayWebhookPayload(payload)) return;
3180
4441
  switch (payload.event_type) {
3181
4442
  case "PAYMENT_SUCCEEDED":
3182
4443
  await handlers.onPaymentSucceeded?.(payload);
@@ -3247,6 +4508,21 @@ async function dispatchWebhook(payload, handlers) {
3247
4508
  case "SUBSCRIPTION_FREEZE_CANCEL":
3248
4509
  await handlers.onSubscriptionFreezeCancel?.(payload);
3249
4510
  return;
4511
+ case "SUBSCRIPTION_PLAN_CHANGE_SCHEDULED":
4512
+ await handlers.onSubscriptionPlanChangeScheduled?.(payload);
4513
+ return;
4514
+ case "SUBSCRIPTION_PLAN_CHANGE_CANCELED":
4515
+ await handlers.onSubscriptionPlanChangeCanceled?.(payload);
4516
+ return;
4517
+ case "SUBSCRIPTION_PLAN_CHANGED":
4518
+ await handlers.onSubscriptionPlanChanged?.(payload);
4519
+ return;
4520
+ case "SUBSCRIPTION_PLAN_CHANGE_INVOICE_REISSUED":
4521
+ await handlers.onSubscriptionPlanChangeInvoiceReissued?.(payload);
4522
+ return;
4523
+ case "SUBSCRIPTION_PLAN_UPDATED":
4524
+ await handlers.onSubscriptionPlanUpdated?.(payload);
4525
+ return;
3250
4526
  case "PAYMENT_LINK_PAY_ATTEMPT_FAILED":
3251
4527
  await handlers.onPaymentLinkPayAttemptFailed?.(payload);
3252
4528
  return;
@@ -3285,7 +4561,9 @@ function verifyWebhook(input) {
3285
4561
  const { rawBody, signatureHeader } = input;
3286
4562
  const toleranceSeconds = input.toleranceSeconds ?? 300;
3287
4563
  const now = input.now ?? (() => Math.floor(Date.now() / 1e3));
3288
- const secrets = typeof input.secret === "string" ? [input.secret] : input.secret;
4564
+ const secrets = (typeof input.secret === "string" ? [input.secret] : input.secret).filter(
4565
+ (secret) => secret.length > 0
4566
+ );
3289
4567
  if (!signatureHeader) return { ok: false, reason: "MISSING_HEADER" };
3290
4568
  const parsed = parseSignatureHeader(signatureHeader);
3291
4569
  if (!parsed) return { ok: false, reason: "MALFORMED_HEADER" };
@@ -3311,95 +4589,93 @@ function verifyWebhookOrThrow(input) {
3311
4589
  }
3312
4590
 
3313
4591
  // src/plugins/webhooks.ts
3314
- function isStreamPayWebhookPayload(value) {
3315
- if (!value || typeof value !== "object") return false;
3316
- return "event_type" in value && typeof value.event_type === "string";
3317
- }
3318
4592
  function toErrorCode(reason) {
3319
4593
  return reason === "MISSING_HEADER" || reason === "INVALID_SIGNATURE" || reason === "EXPIRED" ? "UNAUTHORIZED" : "BAD_REQUEST";
3320
4594
  }
3321
- var webhooks = (webhooksOptions) => (_options, registry) => {
3322
- const { secret, toleranceSeconds, ...handlers } = webhooksOptions;
3323
- return {
3324
- endpoints: {
3325
- streampayWebhooks: api.createAuthEndpoint(
3326
- "/streampay/webhooks",
3327
- {
3328
- method: "POST",
3329
- metadata: { isAction: false },
3330
- cloneRequest: true
3331
- },
3332
- async (ctx) => {
3333
- const logger2 = getLogger(ctx);
3334
- const hasSecret = typeof secret === "string" ? secret.length > 0 : secret.some((s) => s.length > 0);
3335
- if (!hasSecret) {
3336
- logger2.error("webhook secret is not configured.");
3337
- throw new api.APIError("INTERNAL_SERVER_ERROR", {
3338
- message: "StreamPay webhook secret is not configured."
3339
- });
3340
- }
3341
- if (!ctx.request) {
3342
- throw new api.APIError("BAD_REQUEST", { message: "Missing request body." });
3343
- }
3344
- const rawBody = await ctx.request.text();
3345
- const signatureHeader = ctx.request.headers.get("x-webhook-signature");
3346
- try {
3347
- verifyWebhookOrThrow({
3348
- secret,
3349
- rawBody,
3350
- signatureHeader,
3351
- toleranceSeconds: toleranceSeconds ?? 300
3352
- });
3353
- } catch (err) {
3354
- if (err instanceof StreamPayWebhookError) {
3355
- logger2.warn(`webhook rejected: ${err.reason}`);
3356
- throw new api.APIError(toErrorCode(err.reason), {
3357
- message: `Webhook verification failed: ${err.reason}`
3358
- });
4595
+ var webhooks = (webhooksOptions) => {
4596
+ const configuredSecrets = typeof webhooksOptions.secret === "string" ? [webhooksOptions.secret] : webhooksOptions.secret;
4597
+ if (configuredSecrets.length === 0 || configuredSecrets.some((secret) => secret.length === 0)) {
4598
+ throw new TypeError("webhooks(): `secret` must contain only non-empty values.");
4599
+ }
4600
+ if (webhooksOptions.toleranceSeconds !== void 0 && (!Number.isFinite(webhooksOptions.toleranceSeconds) || webhooksOptions.toleranceSeconds < 0)) {
4601
+ throw new TypeError("webhooks(): `toleranceSeconds` must be a non-negative number.");
4602
+ }
4603
+ return (_options, registry) => {
4604
+ const { secret, toleranceSeconds, ...handlers } = webhooksOptions;
4605
+ return {
4606
+ endpoints: {
4607
+ streampayWebhooks: api.createAuthEndpoint(
4608
+ "/streampay/webhooks",
4609
+ {
4610
+ method: "POST",
4611
+ metadata: { isAction: false },
4612
+ cloneRequest: true
4613
+ },
4614
+ async (ctx) => {
4615
+ const logger2 = getLogger(ctx);
4616
+ if (!ctx.request) {
4617
+ throw new api.APIError("BAD_REQUEST", { message: "Missing request body." });
3359
4618
  }
3360
- throw err;
3361
- }
3362
- let parsed;
3363
- try {
3364
- parsed = JSON.parse(rawBody);
3365
- } catch {
3366
- throw new api.APIError("BAD_REQUEST", {
3367
- message: "Webhook body is not valid JSON."
3368
- });
3369
- }
3370
- if (!isStreamPayWebhookPayload(parsed)) {
3371
- throw new api.APIError("BAD_REQUEST", {
3372
- message: "Webhook body is missing `event_type`."
3373
- });
3374
- }
3375
- const payload = parsed;
3376
- if (registry?.subscriptionWebhookSync) {
4619
+ const rawBody = await ctx.request.text();
4620
+ const signatureHeader = ctx.request.headers.get("x-webhook-signature");
3377
4621
  try {
3378
- await registry.subscriptionWebhookSync(ctx, payload, {
4622
+ verifyWebhookOrThrow({
4623
+ secret,
3379
4624
  rawBody,
3380
- signatureHeader
4625
+ signatureHeader,
4626
+ toleranceSeconds: toleranceSeconds ?? 300
4627
+ });
4628
+ } catch (err) {
4629
+ if (err instanceof StreamPayWebhookError) {
4630
+ logger2.warn(`webhook rejected: ${err.reason}`);
4631
+ throw new api.APIError(toErrorCode(err.reason), {
4632
+ message: `Webhook verification failed: ${err.reason}`
4633
+ });
4634
+ }
4635
+ throw err;
4636
+ }
4637
+ let parsed;
4638
+ try {
4639
+ parsed = JSON.parse(rawBody);
4640
+ } catch {
4641
+ throw new api.APIError("BAD_REQUEST", {
4642
+ message: "Webhook body is not valid JSON."
3381
4643
  });
4644
+ }
4645
+ if (!isStreamPayWebhookEnvelope(parsed)) {
4646
+ throw new api.APIError("BAD_REQUEST", {
4647
+ message: "Webhook body is not a valid StreamPay event envelope."
4648
+ });
4649
+ }
4650
+ const payload = parsed;
4651
+ if (registry?.subscriptionWebhookSync && isKnownStreamPayWebhookPayload(payload)) {
4652
+ try {
4653
+ await registry.subscriptionWebhookSync(ctx, payload, {
4654
+ rawBody,
4655
+ signatureHeader
4656
+ });
4657
+ } catch (err) {
4658
+ const message = err instanceof Error ? err.message : String(err);
4659
+ logger2.error(`subscription sync failed: ${message}`);
4660
+ throw new api.APIError("INTERNAL_SERVER_ERROR", {
4661
+ message: "Webhook sync failed. See server logs."
4662
+ });
4663
+ }
4664
+ }
4665
+ try {
4666
+ await dispatchWebhook(payload, handlers);
3382
4667
  } catch (err) {
3383
4668
  const message = err instanceof Error ? err.message : String(err);
3384
- logger2.error(`subscription sync failed: ${message}`);
4669
+ logger2.error(`webhook handler failed: ${message}`);
3385
4670
  throw new api.APIError("INTERNAL_SERVER_ERROR", {
3386
- message: "Webhook sync failed. See server logs."
4671
+ message: "Webhook handler failed. See server logs."
3387
4672
  });
3388
4673
  }
4674
+ return ctx.json({ received: true });
3389
4675
  }
3390
- try {
3391
- await dispatchWebhook(payload, handlers);
3392
- } catch (err) {
3393
- const message = err instanceof Error ? err.message : String(err);
3394
- logger2.error(`webhook handler failed: ${message}`);
3395
- throw new api.APIError("INTERNAL_SERVER_ERROR", {
3396
- message: "Webhook handler failed. See server logs."
3397
- });
3398
- }
3399
- return ctx.json({ received: true });
3400
- }
3401
- )
3402
- }
4676
+ )
4677
+ }
4678
+ };
3403
4679
  };
3404
4680
  };
3405
4681
  var isAnonymous = (user) => "isAnonymous" in user && user.isAnonymous === true;
@@ -3418,6 +4694,7 @@ var onBeforeUserCreate = (options) => async (user, context) => {
3418
4694
  const createPayload = {
3419
4695
  name: user.name || user.email,
3420
4696
  email: user.email,
4697
+ consumer_type: "INDIVIDUAL",
3421
4698
  ...extras
3422
4699
  };
3423
4700
  try {
@@ -3516,7 +4793,7 @@ var onUserDelete = (options) => async (user, context) => {
3516
4793
 
3517
4794
  // package.json
3518
4795
  var package_default = {
3519
- version: "1.3.0"};
4796
+ version: "2.1.0"};
3520
4797
 
3521
4798
  // src/version.ts
3522
4799
  var version = package_default.version;
@@ -3543,7 +4820,8 @@ var streampay = (options) => {
3543
4820
  streampayConsumerId: {
3544
4821
  type: "string",
3545
4822
  required: false,
3546
- input: false
4823
+ input: false,
4824
+ unique: true
3547
4825
  }
3548
4826
  }
3549
4827
  },
@@ -3572,53 +4850,40 @@ var streampay = (options) => {
3572
4850
  };
3573
4851
  };
3574
4852
 
3575
- // src/webhooks/events.ts
3576
- var STREAMPAY_PAYMENT_EVENT_TYPES = [
3577
- "PAYMENT_SUCCEEDED",
3578
- "PAYMENT_FAILED",
3579
- "PAYMENT_CANCELED",
3580
- "PAYMENT_REFUNDED",
3581
- "PAYMENT_MARKED_AS_PAID"
3582
- ];
3583
- var STREAMPAY_INVOICE_EVENT_TYPES = [
3584
- "INVOICE_CREATED",
3585
- "INVOICE_SENT",
3586
- "INVOICE_ACCEPTED",
3587
- "INVOICE_REJECTED",
3588
- "INVOICE_COMPLETED",
3589
- "INVOICE_CANCELED",
3590
- "INVOICE_UPDATED"
3591
- ];
3592
- var STREAMPAY_SUBSCRIPTION_EVENT_TYPES = [
3593
- "SUBSCRIPTION_CREATED",
3594
- "SUBSCRIPTION_ACTIVATED",
3595
- "SUBSCRIPTION_INACTIVATED",
3596
- "SUBSCRIPTION_CANCELED",
3597
- "SUBSCRIPTION_FROZEN",
3598
- "SUBSCRIPTION_CYCLE_RENEWAL_FAILED",
3599
- "SUBSCRIPTION_CANCEL_AT_PERIOD_END",
3600
- "SUBSCRIPTION_FREEZE_NOW",
3601
- "SUBSCRIPTION_UNFREEZE_NOW",
3602
- "SUBSCRIPTION_UNFREEZE_FUTURE",
3603
- "SUBSCRIPTION_FREEZE_CANCEL"
3604
- ];
3605
- var STREAMPAY_PAYMENT_LINK_EVENT_TYPES = ["PAYMENT_LINK_PAY_ATTEMPT_FAILED"];
3606
- var STREAMPAY_EVENT_TYPES = [
3607
- ...STREAMPAY_PAYMENT_EVENT_TYPES,
3608
- ...STREAMPAY_INVOICE_EVENT_TYPES,
3609
- ...STREAMPAY_SUBSCRIPTION_EVENT_TYPES,
3610
- ...STREAMPAY_PAYMENT_LINK_EVENT_TYPES
3611
- ];
4853
+ // src/utils/amount.ts
4854
+ var StreamPayAmount = {
4855
+ toHalalat(sar) {
4856
+ const asNumber = typeof sar === "string" ? Number(sar) : sar;
4857
+ if (!Number.isFinite(asNumber)) {
4858
+ throw new RangeError(`StreamPayAmount.toHalalat: invalid SAR value ${String(sar)}`);
4859
+ }
4860
+ const absoluteHalalat = Math.round(Number(`${Math.abs(asNumber)}e2`));
4861
+ const halalat = Math.sign(asNumber) * absoluteHalalat;
4862
+ if (!Number.isSafeInteger(halalat)) {
4863
+ throw new RangeError(`StreamPayAmount.toHalalat: SAR value is outside the safe range`);
4864
+ }
4865
+ return halalat;
4866
+ },
4867
+ toSAR(halalat) {
4868
+ if (!Number.isFinite(halalat) || !Number.isInteger(halalat)) {
4869
+ throw new RangeError(`StreamPayAmount.toSAR: expected integer halalat, got ${halalat}`);
4870
+ }
4871
+ return (halalat / 100).toFixed(2);
4872
+ }
4873
+ };
3612
4874
 
3613
4875
  exports.$ERROR_CODES = $ERROR_CODES;
3614
4876
  exports.CheckoutBody = CheckoutBody;
4877
+ exports.DEFAULT_ACCESS_STATUSES = DEFAULT_ACCESS_STATUSES;
3615
4878
  exports.PLAN_NAME_METADATA_KEY = PLAN_NAME_METADATA_KEY;
3616
4879
  exports.REFERENCE_ID_METADATA_KEY = REFERENCE_ID_METADATA_KEY;
4880
+ exports.REFERENCE_TYPE_METADATA_KEY = REFERENCE_TYPE_METADATA_KEY;
3617
4881
  exports.STREAMPAY_EVENT_TYPES = STREAMPAY_EVENT_TYPES;
3618
4882
  exports.STREAMPAY_INVOICE_EVENT_TYPES = STREAMPAY_INVOICE_EVENT_TYPES;
3619
4883
  exports.STREAMPAY_PAYMENT_EVENT_TYPES = STREAMPAY_PAYMENT_EVENT_TYPES;
3620
4884
  exports.STREAMPAY_PAYMENT_LINK_EVENT_TYPES = STREAMPAY_PAYMENT_LINK_EVENT_TYPES;
3621
4885
  exports.STREAMPAY_SUBSCRIPTION_EVENT_TYPES = STREAMPAY_SUBSCRIPTION_EVENT_TYPES;
4886
+ exports.SUBSCRIPTION_ROW_ID_METADATA_KEY = SUBSCRIPTION_ROW_ID_METADATA_KEY;
3622
4887
  exports.StreamPayAmount = StreamPayAmount;
3623
4888
  exports.StreamPayWebhookError = StreamPayWebhookError;
3624
4889
  exports.admin = admin;
@@ -3630,11 +4895,15 @@ exports.findConsumerByExternalId = findConsumerByExternalId;
3630
4895
  exports.findConsumerByIdentifiers = findConsumerByIdentifiers;
3631
4896
  exports.formatStreamPayError = formatStreamPayError;
3632
4897
  exports.hasFeature = hasFeature;
4898
+ exports.hasSubscriptionAccess = hasSubscriptionAccess;
4899
+ exports.isKnownStreamPayWebhookPayload = isKnownStreamPayWebhookPayload;
4900
+ exports.isStreamPayWebhookEnvelope = isStreamPayWebhookEnvelope;
3633
4901
  exports.mapToErrorCode = mapToErrorCode;
3634
4902
  exports.parseStreamPayError = parseStreamPayError;
3635
4903
  exports.portal = portal;
3636
4904
  exports.streampay = streampay;
3637
4905
  exports.subscriptionSchema = subscriptionSchema;
4906
+ exports.subscriptionSlotKey = subscriptionSlotKey;
3638
4907
  exports.subscriptions = subscriptions;
3639
4908
  exports.syncWebhookPayload = syncWebhookPayload;
3640
4909
  exports.verifyWebhook = verifyWebhook;