better-auth-streampay 1.2.1 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -36,41 +36,44 @@ var $ERROR_CODES = defineErrorCodes({
36
36
  SUBSCRIPTION_NOT_FOUND: "The subscription does not exist.",
37
37
  SUBSCRIPTION_PLAN_NOT_FOUND: "The requested subscription plan is not configured.",
38
38
  SUBSCRIPTION_ALREADY_ACTIVE: "An active subscription already exists for this plan group.",
39
+ SUBSCRIPTION_CHECKOUT_IN_PROGRESS: "A subscription checkout is already being created for this plan group.",
40
+ SUBSCRIPTION_ALREADY_CANCELED: "The subscription is already canceled.",
41
+ SUBSCRIPTION_ALREADY_FROZEN: "The subscription is already frozen.",
42
+ SUBSCRIPTION_EXPIRED: "The subscription has expired.",
43
+ SUBSCRIPTION_ALREADY_SCHEDULED_CANCEL: "The subscription is already scheduled to cancel at period end.",
44
+ SUBSCRIPTION_ALREADY_ON_PLAN: "The subscription is already on the requested plan.",
45
+ SUBSCRIPTION_IMMEDIATE_CANCEL_UNSUPPORTED: "StreamPay does not support immediate cancellation for active subscriptions.",
46
+ SUBSCRIPTION_PERIOD_END_CANCEL_UNSUPPORTED: "StreamPay only supports period-end cancellation for active subscriptions.",
47
+ SUBSCRIPTION_PLAN_GROUP_MISMATCH: "Subscription plan changes must stay within the same configured plan group.",
48
+ SUBSCRIPTION_PLAN_CHANGE_ALREADY_SCHEDULED: "A different plan change is already scheduled for this subscription.",
39
49
  SUBSCRIPTION_INVALID_STATE: "The subscription is in a state that forbids this action.",
40
50
  SUBSCRIPTION_FREEZE_NOT_ACTIVE: "No active freeze period was found for this subscription.",
41
51
  SUBSCRIPTION_REFERENCE_NOT_AUTHORIZED: "You are not authorized to act on this subscription reference.",
52
+ WEBHOOK_REPLAY_IN_PROGRESS: "This webhook event is already being replayed.",
42
53
  UNKNOWN: "An unexpected error occurred."
43
54
  });
44
55
  var RAW_CODE_MAP = {
45
- // Validation
46
56
  INVALID_PARAMETERS: "VALIDATION_ERROR",
47
- // Permissions
48
57
  PERMISSION_FORBIDDEN: "FORBIDDEN",
49
58
  BRANCH_ACCESS_DENIED: "FORBIDDEN",
50
59
  BRANCH_NOT_FOUND: "NOT_FOUND",
51
- // Consumer
52
60
  DUPLICATE_CONSUMER: "CONSUMER_DUPLICATE",
53
61
  DUPLICATE_CARD_TOKEN: "CONSUMER_DUPLICATE",
54
62
  CONSUMER_HAS_ONGOING_INVOICES: "CONSUMER_HAS_ONGOING_ACTIVITY",
55
63
  CONSUMER_HAS_ONGOING_SUBSCRIPTIONS: "CONSUMER_HAS_ONGOING_ACTIVITY",
56
- // Invoice state
57
64
  INVOICE_FINALISED: "INVOICE_INVALID_STATE",
58
65
  INVOICE_INVALID_STATUS: "INVOICE_INVALID_STATE",
59
66
  INVOICE_CONSENT_CONSUMED: "INVOICE_INVALID_STATE",
60
67
  INVOICE_CONSENT_EXPIRED: "INVOICE_INVALID_STATE",
61
68
  INVOICE_TOTAL_MISMATCH_PAYMENT_AMOUNT_SUM: "INVOICE_INVALID_STATE",
62
69
  INVOICE_PAYMENT_COUNT_NOT_MATCHED: "INVOICE_INVALID_STATE",
63
- // Payment state / duplicates
64
70
  DUPLICATE_PAYMENT: "PAYMENT_DUPLICATE",
65
71
  PAYMENT_IN_PROGRESS: "PAYMENT_INVALID_STATE",
66
72
  PAYMENT_FINALIZED: "PAYMENT_INVALID_STATE",
67
73
  PAYMEND_UNPAID: "PAYMENT_INVALID_STATE",
68
- // sic — upstream typo we inherit
69
74
  INVALID_STATUS: "PAYMENT_INVALID_STATE",
70
- // Refund outcomes
71
75
  PAYMENT_REFUNDED_ALREADY: "PAYMENT_ALREADY_REFUNDED",
72
76
  PAYMENT_REFUNDED_FAILED: "PAYMENT_REFUND_FAILED",
73
- // Gateway — declined (do not auto-retry; user must take action)
74
77
  PAYMENT_GATEWAY_DECLINED: "PAYMENT_GATEWAY_DECLINED",
75
78
  INSUFFICIENT_FUNDS: "PAYMENT_GATEWAY_DECLINED",
76
79
  MOYASAR_PAYMENT_INFO_MISMATCH: "PAYMENT_GATEWAY_DECLINED",
@@ -79,29 +82,24 @@ var RAW_CODE_MAP = {
79
82
  MOYASAR_FORBIDDEN: "PAYMENT_GATEWAY_DECLINED",
80
83
  MOYASAR_NOT_FOUND: "PAYMENT_GATEWAY_DECLINED",
81
84
  MOYASAR_METHOD_NOT_ALLOWED: "PAYMENT_GATEWAY_DECLINED",
82
- // Gateway — transient (safe to retry with backoff)
83
85
  MOYASAR_TIMEOUT: "PAYMENT_GATEWAY_UNAVAILABLE",
84
86
  MOYASAR_TOO_MANY_REQUESTS: "PAYMENT_GATEWAY_UNAVAILABLE",
85
87
  MOYASAR_INTERNAL_SERVER_ERROR: "PAYMENT_GATEWAY_UNAVAILABLE",
86
88
  MOYASAR_SERVICE_UNAVAILABLE: "PAYMENT_GATEWAY_UNAVAILABLE",
87
- // Payment method identity
88
89
  MOYASAR_INVALID_CARD_TOKEN: "PAYMENT_METHOD_INVALID",
89
90
  MANUAL_INVOICE_CARD_ID: "PAYMENT_METHOD_INVALID",
90
91
  ONE_OFF_INVALID_PAYMENT_FLOW: "PAYMENT_METHOD_INVALID",
91
92
  ONE_OFF_CARD_ID: "PAYMENT_METHOD_INVALID",
92
93
  AUTO_INVOICE_MISSING_CARD_ID: "PAYMENT_METHOD_INVALID",
93
94
  PAYMENT_FLOW_NOT_ALLOWED: "PAYMENT_METHOD_INVALID",
94
- // Catalog
95
95
  PRODUCT_USED_IN_FINALIZED_INVOICE: "PRODUCT_LOCKED",
96
96
  COUPON_USED_IN_FINALIZED_INVOICE: "COUPON_LOCKED",
97
- // Subscription state — these fire from the upstream API when the
98
- // caller attempts an action the current subscription state forbids.
99
97
  SUBSCRIPTION_ALREADY_ACTIVE: "SUBSCRIPTION_ALREADY_ACTIVE",
100
98
  SUBSCRIPTION_NOT_FOUND: "SUBSCRIPTION_NOT_FOUND",
101
- SUBSCRIPTION_ALREADY_CANCELED: "SUBSCRIPTION_INVALID_STATE",
102
- SUBSCRIPTION_ALREADY_FROZEN: "SUBSCRIPTION_INVALID_STATE",
99
+ SUBSCRIPTION_ALREADY_CANCELED: "SUBSCRIPTION_ALREADY_CANCELED",
100
+ SUBSCRIPTION_ALREADY_FROZEN: "SUBSCRIPTION_ALREADY_FROZEN",
103
101
  SUBSCRIPTION_NOT_FROZEN: "SUBSCRIPTION_FREEZE_NOT_ACTIVE",
104
- SUBSCRIPTION_EXPIRED: "SUBSCRIPTION_INVALID_STATE"
102
+ SUBSCRIPTION_EXPIRED: "SUBSCRIPTION_EXPIRED"
105
103
  };
106
104
  function mapToErrorCode(rawCode, status) {
107
105
  if (rawCode && rawCode in RAW_CODE_MAP) {
@@ -121,9 +119,21 @@ async function findConsumerByExternalId(client, { externalId }) {
121
119
  const hit = await searchExact(client, externalId, (c) => c.external_id === externalId);
122
120
  return hit?.id ?? null;
123
121
  }
122
+ function sameEmail(a, b) {
123
+ if (!a || !b) return false;
124
+ return a.trim().toLowerCase() === b.trim().toLowerCase();
125
+ }
126
+ function samePhone(a, b) {
127
+ if (!a || !b) return false;
128
+ return a.trim() === b.trim();
129
+ }
124
130
  async function findConsumerByIdentifiers(client, identifiers) {
125
131
  if (identifiers.email) {
126
- const hit = await searchExact(client, identifiers.email, (c) => c.email === identifiers.email);
132
+ const hit = await searchExact(
133
+ client,
134
+ identifiers.email,
135
+ (c) => sameEmail(c.email, identifiers.email)
136
+ );
127
137
  if (hit) return hit;
128
138
  }
129
139
  if (identifiers.phone_number) {
@@ -255,14 +265,6 @@ function getLogger(ctx) {
255
265
  }
256
266
 
257
267
  // src/utils/ensure-consumer.ts
258
- function sameEmail(a, b) {
259
- if (!a || !b) return false;
260
- return a.trim().toLowerCase() === b.trim().toLowerCase();
261
- }
262
- function samePhone(a, b) {
263
- if (!a || !b) return false;
264
- return a.trim() === b.trim();
265
- }
266
268
  function canClaimBy(mode, identifier) {
267
269
  return mode?.includes(identifier) ?? false;
268
270
  }
@@ -325,6 +327,7 @@ async function ensureConsumerForUser(options, ctx, user) {
325
327
  name: user.name || user.email,
326
328
  email: user.email,
327
329
  external_id: user.id,
330
+ consumer_type: "INDIVIDUAL",
328
331
  ...extras
329
332
  };
330
333
  try {
@@ -473,24 +476,39 @@ function asSessionUser(user) {
473
476
  return result;
474
477
  }
475
478
 
476
- // src/utils/amount.ts
477
- var StreamPayAmount = {
478
- toHalalat(sar) {
479
- const asNumber = typeof sar === "string" ? Number(sar) : sar;
480
- if (!Number.isFinite(asNumber)) {
481
- throw new RangeError(`StreamPayAmount.toHalalat: invalid SAR value ${String(sar)}`);
482
- }
483
- return Math.round(asNumber * 100);
484
- },
485
- toSAR(halalat) {
486
- if (!Number.isFinite(halalat) || !Number.isInteger(halalat)) {
487
- throw new RangeError(`StreamPayAmount.toSAR: expected integer halalat, got ${halalat}`);
488
- }
489
- return (halalat / 100).toFixed(2);
490
- }
491
- };
492
-
493
- // src/plugins/subscriptions/types.ts
479
+ // src/plugins/subscriptions/status.ts
480
+ var SUBSCRIPTION_STATUSES = [
481
+ "incomplete",
482
+ "incomplete_expired",
483
+ "trial_pending",
484
+ "trialing",
485
+ "active",
486
+ "inactive",
487
+ "expired",
488
+ "canceled",
489
+ "frozen",
490
+ "past_due"
491
+ ];
492
+ var DEFAULT_ACCESS_STATUSES = ["active", "trialing", "frozen", "past_due"];
493
+ var MANAGEABLE_STATUSES = /* @__PURE__ */ new Set([
494
+ "active",
495
+ "trial_pending",
496
+ "trialing",
497
+ "frozen",
498
+ "past_due"
499
+ ]);
500
+ var TERMINAL_STATUSES = /* @__PURE__ */ new Set([
501
+ "incomplete_expired",
502
+ "inactive",
503
+ "expired",
504
+ "canceled"
505
+ ]);
506
+ var CHECKOUT_SUCCESS_STATUSES = /* @__PURE__ */ new Set([
507
+ "ACTIVE",
508
+ "TRIALING",
509
+ "TRIAL_PENDING",
510
+ "FROZEN"
511
+ ]);
494
512
  function toLocalStatus(status) {
495
513
  switch (status) {
496
514
  case "ACTIVE":
@@ -503,21 +521,205 @@ function toLocalStatus(status) {
503
521
  return "canceled";
504
522
  case "FROZEN":
505
523
  return "frozen";
524
+ case "TRIALING":
525
+ return "trialing";
526
+ case "TRIAL_PENDING":
527
+ return "trial_pending";
506
528
  default:
507
529
  return "incomplete";
508
530
  }
509
531
  }
532
+ function isManageableSubscriptionStatus(status) {
533
+ return MANAGEABLE_STATUSES.has(status);
534
+ }
535
+ function isTerminalSubscriptionStatus(status) {
536
+ return status !== void 0 && TERMINAL_STATUSES.has(status);
537
+ }
538
+ function isCheckoutSuccessStatus(status) {
539
+ return status !== void 0 && CHECKOUT_SUCCESS_STATUSES.has(status);
540
+ }
541
+
542
+ // src/plugins/subscriptions/reconcile.ts
543
+ var SUBSCRIPTION_MODEL = "subscription";
544
+ function reconcileProjectionAgainstExisting(existing, projection, options = {}) {
545
+ const projected = { ...projection };
546
+ if (existing?.billingStatus === "past_due" && projected.status === "active") {
547
+ projected.status = "past_due";
548
+ projected.billingStatus = "past_due";
549
+ }
550
+ const lifecycleAt = options.lifecycleAt === void 0 ? /* @__PURE__ */ new Date() : options.lifecycleAt;
551
+ if (options.stampCancelScheduled !== false && !existing?.cancelAtPeriodEnd && projected.cancelAtPeriodEnd && lifecycleAt) {
552
+ projected.cancelScheduledAt = lifecycleAt;
553
+ }
554
+ if (options.stampCanceled !== false && projected.status === "canceled" && !existing?.canceledAt && lifecycleAt) {
555
+ projected.canceledAt = lifecycleAt;
556
+ }
557
+ return projected;
558
+ }
559
+ function projectSubscriptionAgainstExisting(existing, stream) {
560
+ return reconcileProjectionAgainstExisting(existing, projectSubscriptionFields(stream));
561
+ }
562
+ async function applySubscriptionProjection(adapter, stream, log, source) {
563
+ const streampaySubscriptionId = stream?.id;
564
+ if (!stream || !streampaySubscriptionId) return;
565
+ try {
566
+ const existing = await adapter.findOne({
567
+ model: SUBSCRIPTION_MODEL,
568
+ where: [{ field: "streampaySubscriptionId", value: streampaySubscriptionId }]
569
+ });
570
+ if (!existing) return;
571
+ await adapter.update({
572
+ model: SUBSCRIPTION_MODEL,
573
+ update: projectSubscriptionAgainstExisting(existing, stream),
574
+ where: [{ field: "id", value: existing.id }]
575
+ });
576
+ } catch (err) {
577
+ const message = err instanceof Error ? err.message : String(err);
578
+ log.warn(
579
+ `${source}: project for sub=${streampaySubscriptionId} failed (${message}). Local row will reconcile on next webhook.`
580
+ );
581
+ }
582
+ }
583
+ async function syncSubscriptionFromUpstream(client, adapter, streampaySubscriptionId, log, source, prefetched) {
584
+ let stream = prefetched;
585
+ if (!stream) {
586
+ try {
587
+ stream = await client.getSubscription(streampaySubscriptionId);
588
+ } catch (err) {
589
+ const message = err instanceof Error ? err.message : String(err);
590
+ log.warn(
591
+ `${source}: getSubscription(${streampaySubscriptionId}) failed (${message}). Local row will reconcile on next webhook.`
592
+ );
593
+ return;
594
+ }
595
+ }
596
+ await applySubscriptionProjection(adapter, stream, log, source);
597
+ }
598
+ function projectSubscriptionFields(sub) {
599
+ const status = toLocalStatus(sub.status);
600
+ const terminal = isTerminalSubscriptionStatus(status);
601
+ const periodStart = parseDate(sub.current_period_start);
602
+ const periodEnd = parseDate(sub.current_period_end);
603
+ return {
604
+ streampaySubscriptionId: sub.id ?? null,
605
+ streampayConsumerId: sub.organization_consumer_id ?? null,
606
+ amountInSmallestUnit: typeof sub.amount_in_smallest_unit === "number" ? sub.amount_in_smallest_unit : amountToSmallestUnit(sub.amount, sub.currency),
607
+ originalAmountInSmallestUnit: typeof sub.original_amount_in_smallest_unit === "number" ? sub.original_amount_in_smallest_unit : amountToSmallestUnit(sub.original_amount, sub.currency),
608
+ currency: sub.currency ?? null,
609
+ billingInterval: sub.recurring_interval ?? null,
610
+ billingIntervalCount: sub.recurring_interval_count ?? null,
611
+ status,
612
+ providerStatus: sub.status ?? null,
613
+ periodStart,
614
+ periodEnd,
615
+ currentCycleNumber: sub.current_cycle_number ?? null,
616
+ trialStart: sub.trial_end ? parseDate(sub.started_at) ?? periodStart : null,
617
+ trialEnd: parseDate(sub.trial_end),
618
+ cancelAtPeriodEnd: Boolean(sub.cancel_at_period_end),
619
+ cancelAt: sub.cancel_at_period_end ? periodEnd : null,
620
+ ...sub.cancel_at_period_end ? {} : { cancelScheduledAt: null },
621
+ endedAt: parseDate(sub.ended_at),
622
+ frozenAt: sub.status === "FROZEN" ? parseDate(sub.latest_freeze?.freeze_start_datetime) : null,
623
+ freezeEndAt: sub.status === "FROZEN" ? parseDate(sub.latest_freeze?.freeze_end_datetime) : null,
624
+ providerUpdatedAt: parseDate(sub.updated_at),
625
+ syncedAt: /* @__PURE__ */ new Date(),
626
+ ...terminal ? { activeSlotKey: null } : {},
627
+ updatedAt: /* @__PURE__ */ new Date()
628
+ };
629
+ }
630
+ function parseDate(value) {
631
+ if (!value) return null;
632
+ const date = new Date(value);
633
+ return Number.isNaN(date.getTime()) ? null : date;
634
+ }
635
+ function minorUnitExponent(currency) {
636
+ switch (currency) {
637
+ case "BHD":
638
+ case "KWD":
639
+ case "OMR":
640
+ return 3;
641
+ case "SAR":
642
+ case "USD":
643
+ case "EUR":
644
+ case "GBP":
645
+ case "AED":
646
+ case "QAR":
647
+ return 2;
648
+ default:
649
+ return null;
650
+ }
651
+ }
652
+ function amountToSmallestUnit(value, currency) {
653
+ if (!value) return null;
654
+ const exponent = minorUnitExponent(currency);
655
+ if (exponent === null) return null;
656
+ const match = /^([+-]?)(\d+)(?:\.(\d+))?$/.exec(value);
657
+ if (!match) return null;
658
+ const [, sign, integer, fraction = ""] = match;
659
+ if (!integer) return null;
660
+ const excessFraction = fraction.slice(exponent);
661
+ if (excessFraction && !/^0+$/.test(excessFraction)) return null;
662
+ const normalizedFraction = fraction.slice(0, exponent).padEnd(exponent, "0");
663
+ const factor = 10n ** BigInt(exponent);
664
+ const unsigned = BigInt(integer) * factor + BigInt(normalizedFraction || "0");
665
+ const signed = sign === "-" ? -unsigned : unsigned;
666
+ const numeric = Number(signed);
667
+ return Number.isSafeInteger(numeric) ? numeric : null;
668
+ }
669
+ var SubscriptionItemSchema = zod.z.object({
670
+ product: zod.z.object({ id: zod.z.string() }).passthrough().optional(),
671
+ product_id: zod.z.string().optional()
672
+ }).passthrough();
673
+ function subscriptionItemProductId(item) {
674
+ const parsed = SubscriptionItemSchema.safeParse(item);
675
+ if (!parsed.success) return null;
676
+ return parsed.data.product?.id ?? parsed.data.product_id ?? null;
677
+ }
678
+ function inferPlanFromItems(sub, plans) {
679
+ if (!Array.isArray(sub.items)) return null;
680
+ return inferPlanFromItemList(sub.items, plans);
681
+ }
682
+ function inferPlanFromItemList(items, plans) {
683
+ const productIds = new Set(
684
+ items.map(subscriptionItemProductId).filter((id) => Boolean(id))
685
+ );
686
+ return plans.list.find((plan) => productIds.has(plan.productId))?.name ?? null;
687
+ }
688
+ function projectPlanFields(sub, plans) {
689
+ const currentPlan = inferPlanFromItems(sub, plans);
690
+ const currentProductId = subscriptionItemProductId(sub.items?.[0]);
691
+ const pendingPlan = Array.isArray(sub.pending_change?.target_items) ? inferPlanFromItemList(sub.pending_change.target_items, plans) : null;
692
+ const pendingProductId = subscriptionItemProductId(sub.pending_change?.target_items?.[0]);
693
+ const configuredCurrent = currentPlan ? plans.byName.get(currentPlan) : void 0;
694
+ return {
695
+ ...currentPlan ? {
696
+ plan: currentPlan,
697
+ planVersion: configuredCurrent?.version ?? null,
698
+ productId: currentProductId,
699
+ group: configuredCurrent?.group ?? null
700
+ } : currentProductId ? { productId: currentProductId } : {},
701
+ pendingPlan,
702
+ pendingProductId,
703
+ pendingPlanEffectiveAt: parseDate(sub.pending_change?.effective_at)
704
+ };
705
+ }
706
+ function subscriptionSlotKey(referenceType, referenceId, group) {
707
+ const tuple = JSON.stringify([referenceType, referenceId, group ?? null]);
708
+ return `sp_slot_v1_${crypto.createHash("sha256").update(tuple).digest("hex")}`;
709
+ }
510
710
  var UPGRADE_IDEMPOTENCY_WINDOW_MS = 15 * 60 * 1e3;
511
711
  var PLAN_NAME_METADATA_KEY = "streampay_plugin_plan_name";
512
712
  var REFERENCE_ID_METADATA_KEY = "streampay_plugin_reference_id";
713
+ var REFERENCE_TYPE_METADATA_KEY = "streampay_plugin_reference_type";
714
+ var SUBSCRIPTION_ROW_ID_METADATA_KEY = "streampay_plugin_subscription_row_id";
513
715
 
514
716
  // src/plugins/subscriptions/sync.ts
515
- var SUBSCRIPTION_MODEL = "subscription";
717
+ var SUBSCRIPTION_MODEL2 = "subscription";
516
718
  var WEBHOOK_EVENT_MODEL = "streampayWebhookEvent";
517
719
  function logger(ctx) {
518
720
  return scopedLogger(ctx.context.logger);
519
721
  }
520
- var DEFAULT_MAX_WEBHOOK_ATTEMPTS = 10;
722
+ var DEFAULT_MAX_WEBHOOK_ATTEMPTS = 5;
521
723
  var MAX_CAUSE_DEPTH = 5;
522
724
  function matchesUniqueMarker(err) {
523
725
  if (!err || typeof err !== "object") return false;
@@ -535,6 +737,8 @@ function isUniqueConstraintError(err) {
535
737
  }
536
738
  return false;
537
739
  }
740
+ var WEBHOOK_PROCESSING_LEASE_MS = 2 * 60 * 1e3;
741
+ var WEBHOOK_RETRY_DELAYS_MS = [5, 30, 120, 360, 720].map((minutes) => minutes * 60 * 1e3);
538
742
  async function claimOrAdvanceWebhookEvent(ctx, payload, rawBody, signatureHeader, maxAttempts) {
539
743
  const eventId = extractEventId(payload);
540
744
  if (!eventId) {
@@ -544,6 +748,7 @@ async function claimOrAdvanceWebhookEvent(ctx, payload, rawBody, signatureHeader
544
748
  return { action: "process", row: null };
545
749
  }
546
750
  const now = /* @__PURE__ */ new Date();
751
+ const lockId = crypto.randomUUID();
547
752
  try {
548
753
  const inserted = await ctx.context.adapter.create({
549
754
  model: WEBHOOK_EVENT_MODEL,
@@ -552,8 +757,10 @@ async function claimOrAdvanceWebhookEvent(ctx, payload, rawBody, signatureHeader
552
757
  eventType: payload.event_type,
553
758
  status: "pending",
554
759
  attemptCount: 1,
555
- processedAt: now,
556
- firstSeenAt: now
760
+ receivedAt: now,
761
+ lastAttemptAt: now,
762
+ lockedAt: now,
763
+ lockedBy: lockId
557
764
  }
558
765
  });
559
766
  return { action: "process", row: inserted };
@@ -580,6 +787,12 @@ async function claimOrAdvanceWebhookEvent(ctx, payload, rawBody, signatureHeader
580
787
  );
581
788
  return { action: "skip", reason: "dead_letter" };
582
789
  }
790
+ if (existing.lockedAt instanceof Date && now.getTime() - existing.lockedAt.getTime() < WEBHOOK_PROCESSING_LEASE_MS) {
791
+ logger(ctx).info(
792
+ `webhook ${payload.event_type} (${eventId}) is already being processed \u2014 skipping concurrent delivery.`
793
+ );
794
+ return { action: "skip", reason: "in_progress" };
795
+ }
583
796
  const nextAttempt = (existing.attemptCount ?? 0) + 1;
584
797
  if (nextAttempt > maxAttempts) {
585
798
  const updated2 = await ctx.context.adapter.update({
@@ -587,48 +800,114 @@ async function claimOrAdvanceWebhookEvent(ctx, payload, rawBody, signatureHeader
587
800
  update: {
588
801
  status: "dead_letter",
589
802
  attemptCount: nextAttempt,
590
- processedAt: now,
803
+ lastAttemptAt: now,
804
+ deadLetteredAt: now,
805
+ nextAttemptAt: null,
591
806
  rawPayload: rawBody,
592
- signatureHeader
807
+ signatureHeader,
808
+ lockedAt: null,
809
+ lockedBy: null
593
810
  },
594
- where: [{ field: "id", value: existing.id }]
811
+ where: [
812
+ { field: "id", value: existing.id },
813
+ { field: "status", value: "pending" },
814
+ { field: "lockedAt", value: existing.lockedAt ?? null }
815
+ ]
595
816
  });
596
- return { action: "dead_letter", row: updated2 ?? existing };
817
+ return updated2 ? { action: "dead_letter", row: updated2 } : { action: "skip", reason: "in_progress" };
597
818
  }
598
819
  const updated = await ctx.context.adapter.update({
599
820
  model: WEBHOOK_EVENT_MODEL,
600
821
  update: {
601
822
  attemptCount: nextAttempt,
602
- processedAt: now
823
+ lastAttemptAt: now,
824
+ nextAttemptAt: null,
825
+ lockedAt: now,
826
+ lockedBy: lockId
603
827
  },
604
- where: [{ field: "id", value: existing.id }]
828
+ where: [
829
+ { field: "id", value: existing.id },
830
+ { field: "status", value: "pending" },
831
+ { field: "lockedAt", value: existing.lockedAt ?? null }
832
+ ]
833
+ });
834
+ return updated ? { action: "process", row: updated } : { action: "skip", reason: "in_progress" };
835
+ }
836
+ async function claimWebhookEventForReplay(ctx, row) {
837
+ const now = /* @__PURE__ */ new Date();
838
+ if (row.lockedAt instanceof Date && now.getTime() - row.lockedAt.getTime() < WEBHOOK_PROCESSING_LEASE_MS) {
839
+ return null;
840
+ }
841
+ return ctx.context.adapter.update({
842
+ model: WEBHOOK_EVENT_MODEL,
843
+ update: {
844
+ status: "pending",
845
+ attemptCount: (row.attemptCount ?? 0) + 1,
846
+ lastAttemptAt: now,
847
+ nextAttemptAt: null,
848
+ completedAt: null,
849
+ deadLetteredAt: null,
850
+ lockedAt: now,
851
+ lockedBy: crypto.randomUUID()
852
+ },
853
+ where: [
854
+ { field: "id", value: row.id },
855
+ { field: "status", value: row.status },
856
+ { field: "lockedAt", value: row.lockedAt ?? null }
857
+ ]
605
858
  });
606
- return { action: "process", row: updated ?? existing };
607
859
  }
608
- async function markWebhookEventCompleted(ctx, rowId) {
860
+ async function markWebhookEventCompleted(ctx, rowId, lockId) {
609
861
  await ctx.context.adapter.update({
610
862
  model: WEBHOOK_EVENT_MODEL,
611
863
  update: {
612
864
  status: "completed",
613
- processedAt: /* @__PURE__ */ new Date(),
865
+ completedAt: /* @__PURE__ */ new Date(),
866
+ nextAttemptAt: null,
867
+ lockedAt: null,
868
+ lockedBy: null,
614
869
  rawPayload: null,
615
870
  signatureHeader: null,
616
- lastError: null
871
+ lastError: null,
872
+ lastErrorCode: null
617
873
  },
618
- where: [{ field: "id", value: rowId }]
874
+ where: [
875
+ { field: "id", value: rowId },
876
+ ...lockId ? [{ field: "lockedBy", value: lockId }] : []
877
+ ]
619
878
  });
620
879
  }
621
- async function recordWebhookEventFailure(ctx, rowId, rawBody, signatureHeader, err) {
880
+ async function recordWebhookEventFailure(ctx, rowId, rawBody, signatureHeader, err, lockId, deadLetter = false) {
622
881
  const lastError = err instanceof Error ? err.message : String(err);
882
+ const sdkError = readSdkErrorFields(err);
883
+ const lastErrorCode = readEnvelope(sdkError.body)?.code ?? (sdkError.status !== void 0 ? `HTTP_${sdkError.status}` : err instanceof Error ? err.name : "UNKNOWN");
884
+ const row = await ctx.context.adapter.findOne({
885
+ model: WEBHOOK_EVENT_MODEL,
886
+ where: [
887
+ { field: "id", value: rowId },
888
+ ...lockId ? [{ field: "lockedBy", value: lockId }] : []
889
+ ]
890
+ });
891
+ const attemptCount = row?.attemptCount ?? 1;
892
+ const retryDelay = WEBHOOK_RETRY_DELAYS_MS[Math.min(attemptCount - 1, WEBHOOK_RETRY_DELAYS_MS.length - 1)];
893
+ const now = /* @__PURE__ */ new Date();
623
894
  await ctx.context.adapter.update({
624
895
  model: WEBHOOK_EVENT_MODEL,
625
896
  update: {
626
- processedAt: /* @__PURE__ */ new Date(),
897
+ ...deadLetter ? { status: "dead_letter", deadLetteredAt: now } : {},
898
+ lastAttemptAt: now,
899
+ nextAttemptAt: deadLetter || retryDelay === void 0 ? null : new Date(now.getTime() + retryDelay),
900
+ lockedAt: null,
901
+ lockedBy: null,
627
902
  lastError,
903
+ lastErrorCode,
628
904
  ...rawBody !== null ? { rawPayload: rawBody } : {},
629
905
  ...signatureHeader !== null ? { signatureHeader } : {}
630
906
  },
631
- where: [{ field: "id", value: rowId }]
907
+ where: [
908
+ { field: "id", value: rowId },
909
+ ...lockId ? [{ field: "lockedBy", value: lockId }] : []
910
+ ]
632
911
  });
633
912
  }
634
913
  function extractEventId(payload) {
@@ -640,92 +919,44 @@ function readMetadataString(data, key) {
640
919
  const value = data.metadata[key];
641
920
  return typeof value === "string" && value.length > 0 ? value : null;
642
921
  }
922
+ function readReferenceType(data) {
923
+ const value = readMetadataString(data, REFERENCE_TYPE_METADATA_KEY);
924
+ return value === "user" || value === "organization" || value === "custom" ? value : null;
925
+ }
643
926
  async function findSubscriptionByStreampayId(ctx, streampaySubscriptionId) {
644
927
  return ctx.context.adapter.findOne({
645
- model: SUBSCRIPTION_MODEL,
928
+ model: SUBSCRIPTION_MODEL2,
646
929
  where: [{ field: "streampaySubscriptionId", value: streampaySubscriptionId }]
647
930
  });
648
931
  }
649
- async function applySubscriptionProjection(adapter, stream, log, source) {
650
- const streampaySubscriptionId = stream?.id;
651
- if (!stream || !streampaySubscriptionId) return;
652
- try {
653
- const existing = await adapter.findOne({
654
- model: SUBSCRIPTION_MODEL,
655
- where: [{ field: "streampaySubscriptionId", value: streampaySubscriptionId }]
656
- });
657
- if (!existing) return;
658
- await adapter.update({
659
- model: SUBSCRIPTION_MODEL,
660
- update: projectSubscriptionFields(stream),
661
- where: [{ field: "id", value: existing.id }]
662
- });
663
- } catch (err) {
664
- const msg = err instanceof Error ? err.message : String(err);
665
- log.warn(
666
- `${source}: project for sub=${streampaySubscriptionId} failed (${msg}). Local row will reconcile on next webhook.`
667
- );
668
- }
669
- }
670
- async function syncSubscriptionFromUpstream(client, adapter, streampaySubscriptionId, log, source) {
671
- let stream;
672
- try {
673
- stream = await client.getSubscription(streampaySubscriptionId);
674
- } catch (err) {
675
- const msg = err instanceof Error ? err.message : String(err);
676
- log.warn(
677
- `${source}: getSubscription(${streampaySubscriptionId}) failed (${msg}). Local row will reconcile on next webhook.`
678
- );
679
- return;
680
- }
681
- await applySubscriptionProjection(adapter, stream, log, source);
682
- }
683
- async function findIncompleteRow(ctx, referenceId, plan) {
932
+ async function findIncompleteRow(ctx, referenceId, referenceType, plan, paymentLinkId) {
684
933
  const candidates = await ctx.context.adapter.findMany({
685
- model: SUBSCRIPTION_MODEL,
934
+ model: SUBSCRIPTION_MODEL2,
686
935
  where: [
687
936
  { field: "referenceId", value: referenceId },
688
937
  { field: "plan", value: plan },
689
938
  { field: "status", value: "incomplete" }
690
939
  ]
691
940
  });
692
- if (candidates.length === 0) return null;
693
- return candidates.reduce(
694
- (newest, candidate) => candidate.createdAt > newest.createdAt ? candidate : newest
695
- );
696
- }
697
- function projectSubscriptionFields(sub) {
698
- return {
699
- streampaySubscriptionId: sub.id ?? null,
700
- streampayConsumerId: sub.organization_consumer_id ?? null,
701
- amountHalalat: amountToHalalat(sub.amount),
702
- currency: sub.currency ?? null,
703
- billingInterval: sub.recurring_interval ?? null,
704
- billingIntervalCount: sub.recurring_interval_count ?? null,
705
- status: toLocalStatus(sub.status),
706
- periodStart: parseDate(sub.current_period_start),
707
- periodEnd: parseDate(sub.current_period_end),
708
- cancelAtPeriodEnd: Boolean(sub.cancel_at_period_end),
709
- endedAt: parseDate(sub.ended_at),
710
- frozenAt: sub.status === "FROZEN" ? parseDate(sub.latest_freeze?.freeze_start_datetime) : null,
711
- freezeEndAt: sub.status === "FROZEN" ? parseDate(sub.latest_freeze?.freeze_end_datetime) : null,
712
- updatedAt: /* @__PURE__ */ new Date()
713
- };
714
- }
715
- function parseDate(value) {
716
- if (!value) return null;
717
- const d = new Date(value);
718
- return Number.isNaN(d.getTime()) ? null : d;
719
- }
720
- function amountToHalalat(value) {
721
- if (!value) return null;
722
- try {
723
- return StreamPayAmount.toHalalat(value);
724
- } catch {
941
+ const scopedCandidates = referenceType ? candidates.filter((candidate) => (candidate.referenceType ?? "user") === referenceType) : candidates;
942
+ if (scopedCandidates.length === 0) return null;
943
+ if (paymentLinkId) {
944
+ const exact = scopedCandidates.find(
945
+ (candidate) => candidate.streampayPaymentLinkId === paymentLinkId
946
+ );
947
+ if (exact) return exact;
948
+ }
949
+ if (!referenceType && new Set(scopedCandidates.map((candidate) => candidate.referenceType ?? "user")).size > 1) {
725
950
  return null;
726
951
  }
952
+ return scopedCandidates.reduce((newest, candidate) => {
953
+ const candidateTime = candidate.createdAt?.getTime() ?? Number.NEGATIVE_INFINITY;
954
+ const newestTime = newest.createdAt?.getTime() ?? Number.NEGATIVE_INFINITY;
955
+ return candidateTime > newestTime ? candidate : newest;
956
+ });
727
957
  }
728
958
  async function resolveRowUser(ctx, row) {
959
+ if ((row.referenceType ?? "user") !== "user") return null;
729
960
  const findUserById = ctx.context.internalAdapter?.findUserById;
730
961
  if (!findUserById) return null;
731
962
  try {
@@ -735,15 +966,33 @@ async function resolveRowUser(ctx, row) {
735
966
  return null;
736
967
  }
737
968
  }
738
- async function fireCallback(ctx, callback, data, callbackName) {
969
+ async function fireCallback(ctx, callback, data, callbackName, retryOnError) {
739
970
  if (!callback) return;
740
971
  try {
741
972
  await callback(data);
742
973
  } catch (err) {
743
974
  const msg = err instanceof Error ? err.message : String(err);
744
975
  logger(ctx).error(`subscription callback ${callbackName} failed: ${msg}`);
976
+ if (retryOnError) {
977
+ throw new SubscriptionCallbackDeliveryError(callbackName, err);
978
+ }
745
979
  }
746
980
  }
981
+ var SubscriptionCallbackDeliveryError = class extends Error {
982
+ callbackName;
983
+ constructor(callbackName, cause) {
984
+ const message = cause instanceof Error ? cause.message : String(cause);
985
+ super(`Subscription callback ${callbackName} failed: ${message}`);
986
+ this.name = "SubscriptionCallbackDeliveryError";
987
+ this.callbackName = callbackName;
988
+ }
989
+ };
990
+ var SubscriptionCorrelationError = class extends Error {
991
+ constructor(message) {
992
+ super(message);
993
+ this.name = "SubscriptionCorrelationError";
994
+ }
995
+ };
747
996
  async function reconcileFromStreamPay(ctx, payload, client, plans) {
748
997
  const streampaySubscriptionId = payload.entity_id;
749
998
  if (!streampaySubscriptionId) {
@@ -761,60 +1010,155 @@ async function reconcileFromStreamPay(ctx, payload, client, plans) {
761
1010
  throw err;
762
1011
  }
763
1012
  const existing = await findSubscriptionByStreampayId(ctx, streampaySubscriptionId);
764
- const projected = projectSubscriptionFields(stream);
1013
+ let projected = {
1014
+ ...projectSubscriptionFields(stream),
1015
+ ...projectPlanFields(stream, plans)
1016
+ };
1017
+ const eventAt = parseDate(payload.timestamp);
1018
+ const eventIsStale = Boolean(
1019
+ eventAt && existing?.providerUpdatedAt instanceof Date && eventAt.getTime() < existing.providerUpdatedAt.getTime()
1020
+ );
1021
+ if (!eventIsStale && payload.event_type === "SUBSCRIPTION_CYCLE_RENEWAL_FAILED" && projected.status === "active") {
1022
+ projected.status = "past_due";
1023
+ projected.billingStatus = "past_due";
1024
+ }
1025
+ const schedulesCancellation = !eventIsStale && payload.event_type === "SUBSCRIPTION_CANCEL_AT_PERIOD_END" && Boolean(stream.cancel_at_period_end);
1026
+ if (schedulesCancellation) {
1027
+ projected.cancelAt = parseDate(stream.current_period_end);
1028
+ }
1029
+ const confirmsCancellation = !eventIsStale && payload.event_type === "SUBSCRIPTION_CANCELED" && projected.status === "canceled";
1030
+ if (confirmsCancellation) {
1031
+ projected.activeSlotKey = null;
1032
+ }
1033
+ projected = reconcileProjectionAgainstExisting(existing, projected, {
1034
+ lifecycleAt: eventAt,
1035
+ stampCancelScheduled: schedulesCancellation,
1036
+ stampCanceled: confirmsCancellation
1037
+ });
765
1038
  if (existing) {
1039
+ const projectedStatus = projected.status ?? existing.status;
1040
+ if (!isTerminalSubscriptionStatus(projectedStatus)) {
1041
+ const desiredSlotKey = subscriptionSlotKey(
1042
+ existing.referenceType ?? "user",
1043
+ existing.referenceId,
1044
+ projected.group === void 0 ? existing.group : projected.group
1045
+ );
1046
+ if (existing.activeSlotKey !== desiredSlotKey) {
1047
+ projected.activeSlotKey = desiredSlotKey;
1048
+ }
1049
+ }
766
1050
  const updated = await ctx.context.adapter.update({
767
- model: SUBSCRIPTION_MODEL,
1051
+ model: SUBSCRIPTION_MODEL2,
768
1052
  update: projected,
769
1053
  where: [{ field: "id", value: existing.id }]
770
1054
  });
1055
+ if (eventIsStale) {
1056
+ logger(ctx).info(
1057
+ `webhook ${payload.event_type}: ignored stale lifecycle callback for sub=${streampaySubscriptionId}.`
1058
+ );
1059
+ return { row: null, stream };
1060
+ }
771
1061
  return { row: updated ?? { ...existing, ...projected }, stream };
772
1062
  }
773
1063
  const planName = readMetadataString(payload.data, PLAN_NAME_METADATA_KEY) ?? inferPlanFromItems(stream, plans);
774
1064
  const referenceId = readMetadataString(payload.data, REFERENCE_ID_METADATA_KEY);
1065
+ const metadataReferenceType = readReferenceType(payload.data);
775
1066
  if (!planName || !referenceId) {
776
1067
  logger(ctx).warn(
777
1068
  `webhook ${payload.event_type}: cannot link sub=${streampaySubscriptionId} \u2014 missing plan_name (${planName}) or reference_id (${referenceId}) metadata.`
778
1069
  );
779
1070
  return { row: null, stream };
780
1071
  }
781
- const incomplete = await findIncompleteRow(ctx, referenceId, planName);
1072
+ const paymentLinkId = stream.latest_invoice?.payment_link_id ?? payload.data?.payment_link?.id ?? null;
1073
+ const localRowId = readMetadataString(payload.data, SUBSCRIPTION_ROW_ID_METADATA_KEY);
1074
+ if (localRowId) {
1075
+ const metadataRow = await ctx.context.adapter.findOne({
1076
+ model: SUBSCRIPTION_MODEL2,
1077
+ where: [{ field: "id", value: localRowId }]
1078
+ });
1079
+ if (!metadataRow) {
1080
+ logger(ctx).warn(
1081
+ `webhook ${payload.event_type}: referenced subscription row=${localRowId} is missing; rebuilding from signed metadata.`
1082
+ );
1083
+ } else if (metadataRow.referenceId === referenceId && (!metadataReferenceType || (metadataRow.referenceType ?? "user") === metadataReferenceType) && metadataRow.plan === planName && (!metadataRow.streampaySubscriptionId || metadataRow.streampaySubscriptionId === streampaySubscriptionId) && (!metadataRow.streampayPaymentLinkId || !paymentLinkId || metadataRow.streampayPaymentLinkId === paymentLinkId)) {
1084
+ const projectedWithSlot = {
1085
+ ...projected,
1086
+ billingStatus: metadataRow.billingStatus ?? "current",
1087
+ ...projected.activeSlotKey === null ? {} : {
1088
+ activeSlotKey: metadataRow.activeSlotKey ?? subscriptionSlotKey(
1089
+ metadataRow.referenceType ?? metadataReferenceType ?? "user",
1090
+ metadataRow.referenceId,
1091
+ projected.group === void 0 ? metadataRow.group : projected.group
1092
+ )
1093
+ }
1094
+ };
1095
+ const updated = await ctx.context.adapter.update({
1096
+ model: SUBSCRIPTION_MODEL2,
1097
+ update: projectedWithSlot,
1098
+ where: [{ field: "id", value: metadataRow.id }]
1099
+ });
1100
+ return { row: updated ?? { ...metadataRow, ...projectedWithSlot }, stream };
1101
+ }
1102
+ if (metadataRow) {
1103
+ logger(ctx).warn(
1104
+ `webhook ${payload.event_type}: ignored unsafe subscription row correlation for row=${localRowId}.`
1105
+ );
1106
+ throw new SubscriptionCorrelationError(
1107
+ `Webhook ${payload.event_type} failed protected subscription correlation for row=${localRowId}.`
1108
+ );
1109
+ }
1110
+ }
1111
+ const incomplete = await findIncompleteRow(
1112
+ ctx,
1113
+ referenceId,
1114
+ metadataReferenceType,
1115
+ planName,
1116
+ paymentLinkId
1117
+ );
782
1118
  if (incomplete) {
1119
+ const projectedWithSlot = {
1120
+ ...projected,
1121
+ billingStatus: incomplete.billingStatus ?? "current",
1122
+ ...projected.activeSlotKey === null ? {} : {
1123
+ activeSlotKey: incomplete.activeSlotKey ?? subscriptionSlotKey(
1124
+ incomplete.referenceType ?? metadataReferenceType ?? "user",
1125
+ incomplete.referenceId,
1126
+ projected.group === void 0 ? incomplete.group : projected.group
1127
+ )
1128
+ }
1129
+ };
783
1130
  const updated = await ctx.context.adapter.update({
784
- model: SUBSCRIPTION_MODEL,
785
- update: projected,
1131
+ model: SUBSCRIPTION_MODEL2,
1132
+ update: projectedWithSlot,
786
1133
  where: [{ field: "id", value: incomplete.id }]
787
1134
  });
788
1135
  return {
789
- row: updated ?? { ...incomplete, ...projected },
1136
+ row: updated ?? { ...incomplete, ...projectedWithSlot },
790
1137
  stream
791
1138
  };
792
1139
  }
793
1140
  const plan = plans.byName.get(planName);
1141
+ const referenceType = metadataReferenceType ?? "custom";
794
1142
  const row = await ctx.context.adapter.create({
795
- model: SUBSCRIPTION_MODEL,
1143
+ model: SUBSCRIPTION_MODEL2,
796
1144
  data: {
1145
+ cancelScheduledAt: null,
1146
+ canceledAt: null,
797
1147
  ...projected,
798
1148
  referenceId,
1149
+ referenceType,
1150
+ activeSlotKey: isTerminalSubscriptionStatus(projected.status) ? null : subscriptionSlotKey(referenceType, referenceId, plan?.group),
1151
+ streampayPaymentLinkId: paymentLinkId,
799
1152
  plan: planName,
1153
+ planVersion: plan?.version ?? null,
1154
+ productId: plan?.productId ?? subscriptionItemProductId(stream.items?.[0]),
800
1155
  group: plan?.group ?? null,
1156
+ billingStatus: "current",
801
1157
  createdAt: /* @__PURE__ */ new Date()
802
1158
  }
803
1159
  });
804
1160
  return { row, stream };
805
1161
  }
806
- var SubscriptionItemSchema = zod.z.object({
807
- product: zod.z.object({ id: zod.z.string() }).passthrough().optional(),
808
- product_id: zod.z.string().optional()
809
- }).passthrough();
810
- function inferPlanFromItems(sub, plans) {
811
- const first = Array.isArray(sub.items) ? sub.items[0] : void 0;
812
- const parsed = SubscriptionItemSchema.safeParse(first);
813
- if (!parsed.success) return null;
814
- const productId = parsed.data.product?.id ?? parsed.data.product_id;
815
- if (!productId) return null;
816
- return plans.list.find((plan) => plan.productId === productId)?.name ?? null;
817
- }
818
1162
  async function syncWebhookPayload(ctx, payload, client, plans, callbacks, options = {}) {
819
1163
  if (payload.entity_type !== "SUBSCRIPTION" && payload.event_type !== "INVOICE_COMPLETED") {
820
1164
  return;
@@ -823,6 +1167,7 @@ async function syncWebhookPayload(ctx, payload, client, plans, callbacks, option
823
1167
  const rawBody = options.rawBody ?? null;
824
1168
  const signatureHeader = options.signatureHeader ?? null;
825
1169
  const maxAttempts = Math.max(1, options.maxAttempts ?? DEFAULT_MAX_WEBHOOK_ATTEMPTS);
1170
+ const retryOnCallbackError = options.retryOnCallbackError !== false;
826
1171
  let claim = { action: "process", row: null };
827
1172
  if (dedupe) {
828
1173
  claim = await claimOrAdvanceWebhookEvent(ctx, payload, rawBody, signatureHeader, maxAttempts);
@@ -835,9 +1180,20 @@ async function syncWebhookPayload(ctx, payload, client, plans, callbacks, option
835
1180
  }
836
1181
  }
837
1182
  const trackedRowId = claim.row?.id ?? null;
1183
+ const trackedLockId = claim.row?.lockedBy ?? void 0;
838
1184
  try {
839
1185
  if (payload.event_type === "INVOICE_COMPLETED") {
840
- await handleInvoiceCompleted(ctx, payload, client, plans, callbacks);
1186
+ await handleInvoiceCompleted(
1187
+ ctx,
1188
+ payload,
1189
+ client,
1190
+ plans,
1191
+ callbacks,
1192
+ retryOnCallbackError,
1193
+ options.retryingRenewalCallback === true || claim.row?.lastError?.startsWith(
1194
+ "Subscription callback onSubscriptionRenewed failed:"
1195
+ ) === true
1196
+ );
841
1197
  } else {
842
1198
  const { row, stream } = await reconcileFromStreamPay(ctx, payload, client, plans);
843
1199
  if (row) {
@@ -848,18 +1204,27 @@ async function syncWebhookPayload(ctx, payload, client, plans, callbacks, option
848
1204
  user,
849
1205
  event: payload
850
1206
  };
851
- await dispatchSubscriptionCallback(ctx, payload, data, callbacks);
1207
+ await dispatchSubscriptionCallback(ctx, payload, data, callbacks, retryOnCallbackError);
852
1208
  }
853
1209
  }
854
- if (trackedRowId) await markWebhookEventCompleted(ctx, trackedRowId);
1210
+ if (trackedRowId) await markWebhookEventCompleted(ctx, trackedRowId, trackedLockId);
855
1211
  } catch (err) {
856
1212
  if (trackedRowId) {
857
- await recordWebhookEventFailure(ctx, trackedRowId, rawBody, signatureHeader, err);
1213
+ const deadLetter = classifyWebhookFailure(err) === "PERMANENT" || (claim.row?.attemptCount ?? 0) >= maxAttempts;
1214
+ await recordWebhookEventFailure(
1215
+ ctx,
1216
+ trackedRowId,
1217
+ rawBody,
1218
+ signatureHeader,
1219
+ err,
1220
+ trackedLockId,
1221
+ deadLetter
1222
+ );
858
1223
  }
859
1224
  throw err;
860
1225
  }
861
1226
  }
862
- async function handleInvoiceCompleted(ctx, payload, client, _plans, callbacks) {
1227
+ async function handleInvoiceCompleted(ctx, payload, client, plans, callbacks, retryOnCallbackError, retryingRenewalCallback) {
863
1228
  const invoiceId = payload.data?.invoice?.id ?? payload.entity_id;
864
1229
  if (!invoiceId) return;
865
1230
  let subscriptionId = null;
@@ -885,45 +1250,172 @@ async function handleInvoiceCompleted(ctx, payload, client, _plans, callbacks) {
885
1250
  }
886
1251
  const existing = await findSubscriptionByStreampayId(ctx, subscriptionId);
887
1252
  if (!existing) return;
1253
+ const eventAt = parseDate(payload.timestamp);
1254
+ const eventIsStale = Boolean(
1255
+ eventAt && existing.providerUpdatedAt instanceof Date && eventAt.getTime() < existing.providerUpdatedAt.getTime()
1256
+ );
1257
+ const projected = {
1258
+ ...projectSubscriptionFields(stream),
1259
+ ...projectPlanFields(stream, plans),
1260
+ ...eventIsStale ? existing.billingStatus === "past_due" && toLocalStatus(stream.status) === "active" ? { status: "past_due", billingStatus: "past_due" } : {} : { billingStatus: "current" }
1261
+ };
1262
+ const previousPeriodEnd = existing.periodEnd?.getTime() ?? null;
1263
+ const projectedPeriodEnd = projected.periodEnd?.getTime() ?? null;
1264
+ const periodAdvanced = previousPeriodEnd !== null && projectedPeriodEnd !== null && projectedPeriodEnd > previousPeriodEnd;
1265
+ const cycleAdvanced = existing.currentCycleNumber !== null && existing.currentCycleNumber !== void 0 && projected.currentCycleNumber !== null && projected.currentCycleNumber !== void 0 && projected.currentCycleNumber > existing.currentCycleNumber;
888
1266
  const updated = await ctx.context.adapter.update({
889
- model: SUBSCRIPTION_MODEL,
890
- update: projectSubscriptionFields(stream),
1267
+ model: SUBSCRIPTION_MODEL2,
1268
+ update: projected,
891
1269
  where: [{ field: "id", value: existing.id }]
892
1270
  });
893
- const row = updated ?? { ...existing, ...projectSubscriptionFields(stream) };
1271
+ const row = updated ?? { ...existing, ...projected };
894
1272
  const user = await resolveRowUser(ctx, row);
895
- await fireCallback(
896
- ctx,
897
- callbacks.onSubscriptionRenewed,
898
- { subscription: row, streampaySubscription: stream, user, event: payload },
899
- "onSubscriptionRenewed"
900
- );
1273
+ if (!eventIsStale && (periodAdvanced || cycleAdvanced || retryingRenewalCallback)) {
1274
+ await fireCallback(
1275
+ ctx,
1276
+ callbacks.onSubscriptionRenewed,
1277
+ { subscription: row, streampaySubscription: stream, user, event: payload },
1278
+ "onSubscriptionRenewed",
1279
+ retryOnCallbackError
1280
+ );
1281
+ }
901
1282
  }
902
- async function dispatchSubscriptionCallback(ctx, payload, data, callbacks) {
1283
+ async function dispatchSubscriptionCallback(ctx, payload, data, callbacks, retryOnCallbackError) {
903
1284
  switch (payload.event_type) {
904
1285
  case "SUBSCRIPTION_CREATED":
905
- await fireCallback(ctx, callbacks.onSubscriptionCreated, data, "onSubscriptionCreated");
1286
+ await fireCallback(
1287
+ ctx,
1288
+ callbacks.onSubscriptionCreated,
1289
+ data,
1290
+ "onSubscriptionCreated",
1291
+ retryOnCallbackError
1292
+ );
906
1293
  return;
907
1294
  case "SUBSCRIPTION_ACTIVATED":
908
- await fireCallback(ctx, callbacks.onSubscriptionActivated, data, "onSubscriptionActivated");
1295
+ await fireCallback(
1296
+ ctx,
1297
+ callbacks.onSubscriptionActivated,
1298
+ data,
1299
+ "onSubscriptionActivated",
1300
+ retryOnCallbackError
1301
+ );
909
1302
  return;
910
1303
  case "SUBSCRIPTION_CANCELED":
911
- await fireCallback(ctx, callbacks.onSubscriptionCanceled, data, "onSubscriptionCanceled");
1304
+ await fireCallback(
1305
+ ctx,
1306
+ callbacks.onSubscriptionCanceled,
1307
+ data,
1308
+ "onSubscriptionCanceled",
1309
+ retryOnCallbackError
1310
+ );
1311
+ return;
1312
+ case "SUBSCRIPTION_INACTIVATED":
1313
+ await fireCallback(
1314
+ ctx,
1315
+ callbacks.onSubscriptionInactivated,
1316
+ data,
1317
+ "onSubscriptionInactivated",
1318
+ retryOnCallbackError
1319
+ );
1320
+ return;
1321
+ case "SUBSCRIPTION_CANCEL_AT_PERIOD_END":
1322
+ await fireCallback(
1323
+ ctx,
1324
+ callbacks.onSubscriptionCancelScheduled,
1325
+ data,
1326
+ "onSubscriptionCancelScheduled",
1327
+ retryOnCallbackError
1328
+ );
912
1329
  return;
913
1330
  case "SUBSCRIPTION_FROZEN":
914
1331
  case "SUBSCRIPTION_FREEZE_NOW":
915
- await fireCallback(ctx, callbacks.onSubscriptionFrozen, data, "onSubscriptionFrozen");
1332
+ await fireCallback(
1333
+ ctx,
1334
+ callbacks.onSubscriptionFrozen,
1335
+ data,
1336
+ "onSubscriptionFrozen",
1337
+ retryOnCallbackError
1338
+ );
916
1339
  return;
917
1340
  case "SUBSCRIPTION_UNFREEZE_NOW":
1341
+ await fireCallback(
1342
+ ctx,
1343
+ callbacks.onSubscriptionResumed,
1344
+ data,
1345
+ "onSubscriptionResumed",
1346
+ retryOnCallbackError
1347
+ );
1348
+ return;
1349
+ case "SUBSCRIPTION_UNFREEZE_FUTURE":
1350
+ await fireCallback(
1351
+ ctx,
1352
+ callbacks.onSubscriptionUnfreezeScheduled,
1353
+ data,
1354
+ "onSubscriptionUnfreezeScheduled",
1355
+ retryOnCallbackError
1356
+ );
1357
+ return;
918
1358
  case "SUBSCRIPTION_FREEZE_CANCEL":
919
- await fireCallback(ctx, callbacks.onSubscriptionResumed, data, "onSubscriptionResumed");
1359
+ await fireCallback(
1360
+ ctx,
1361
+ callbacks.onSubscriptionFreezeCanceled,
1362
+ data,
1363
+ "onSubscriptionFreezeCanceled",
1364
+ retryOnCallbackError
1365
+ );
920
1366
  return;
921
1367
  case "SUBSCRIPTION_CYCLE_RENEWAL_FAILED":
922
1368
  await fireCallback(
923
1369
  ctx,
924
1370
  callbacks.onSubscriptionPaymentFailed,
925
1371
  data,
926
- "onSubscriptionPaymentFailed"
1372
+ "onSubscriptionPaymentFailed",
1373
+ retryOnCallbackError
1374
+ );
1375
+ return;
1376
+ case "SUBSCRIPTION_PLAN_CHANGE_SCHEDULED":
1377
+ await fireCallback(
1378
+ ctx,
1379
+ callbacks.onSubscriptionPlanChangeScheduled,
1380
+ data,
1381
+ "onSubscriptionPlanChangeScheduled",
1382
+ retryOnCallbackError
1383
+ );
1384
+ return;
1385
+ case "SUBSCRIPTION_PLAN_CHANGE_CANCELED":
1386
+ await fireCallback(
1387
+ ctx,
1388
+ callbacks.onSubscriptionPlanChangeCanceled,
1389
+ data,
1390
+ "onSubscriptionPlanChangeCanceled",
1391
+ retryOnCallbackError
1392
+ );
1393
+ return;
1394
+ case "SUBSCRIPTION_PLAN_CHANGED":
1395
+ await fireCallback(
1396
+ ctx,
1397
+ callbacks.onSubscriptionPlanChanged,
1398
+ data,
1399
+ "onSubscriptionPlanChanged",
1400
+ retryOnCallbackError
1401
+ );
1402
+ return;
1403
+ case "SUBSCRIPTION_PLAN_CHANGE_INVOICE_REISSUED":
1404
+ await fireCallback(
1405
+ ctx,
1406
+ callbacks.onSubscriptionPlanChangeInvoiceReissued,
1407
+ data,
1408
+ "onSubscriptionPlanChangeInvoiceReissued",
1409
+ retryOnCallbackError
1410
+ );
1411
+ return;
1412
+ case "SUBSCRIPTION_PLAN_UPDATED":
1413
+ await fireCallback(
1414
+ ctx,
1415
+ callbacks.onSubscriptionPlanUpdated,
1416
+ data,
1417
+ "onSubscriptionPlanUpdated",
1418
+ retryOnCallbackError
927
1419
  );
928
1420
  return;
929
1421
  default:
@@ -931,10 +1423,11 @@ async function dispatchSubscriptionCallback(ctx, payload, data, callbacks) {
931
1423
  }
932
1424
  }
933
1425
  function classifyWebhookFailure(err) {
1426
+ if (err instanceof SubscriptionCorrelationError) return "PERMANENT";
934
1427
  const { status } = readSdkErrorFields(err);
935
- if (status !== void 0 && status >= 400 && status < 500 && status !== 429) {
936
- return "PERMANENT";
937
- }
1428
+ if (status === void 0) return "TRANSIENT";
1429
+ if (status === 404 || status === 429) return "TRANSIENT";
1430
+ if (status >= 400 && status < 500) return "PERMANENT";
938
1431
  return "TRANSIENT";
939
1432
  }
940
1433
 
@@ -974,7 +1467,12 @@ function getAdapter(ctx) {
974
1467
  }
975
1468
  return adapter;
976
1469
  }
977
- var ForwardedBody = zod.z.object({}).passthrough();
1470
+ function forwardedBody() {
1471
+ return zod.z.custom(
1472
+ (value) => value !== null && typeof value === "object" && !Array.isArray(value),
1473
+ "Expected an object body."
1474
+ );
1475
+ }
978
1476
  var PaymentsListQuery = zod.z.object({
979
1477
  page: zod.z.coerce.number().int().positive().optional(),
980
1478
  size: zod.z.coerce.number().int().positive().max(100).optional(),
@@ -995,7 +1493,7 @@ function buildPaymentsEndpoints(client, adminOptions) {
995
1493
  "/admin/streampay/payments/:id/refund",
996
1494
  {
997
1495
  method: "POST",
998
- body: ForwardedBody,
1496
+ body: forwardedBody(),
999
1497
  use: [api.sessionMiddleware]
1000
1498
  },
1001
1499
  async (ctx) => {
@@ -1069,7 +1567,7 @@ function buildSubscriptionsEndpoints(client, adminOptions) {
1069
1567
  "/admin/streampay/subscriptions",
1070
1568
  {
1071
1569
  method: "POST",
1072
- body: ForwardedBody,
1570
+ body: forwardedBody(),
1073
1571
  use: [api.sessionMiddleware]
1074
1572
  },
1075
1573
  async (ctx) => {
@@ -1087,7 +1585,7 @@ function buildSubscriptionsEndpoints(client, adminOptions) {
1087
1585
  "/admin/streampay/subscriptions/:id",
1088
1586
  {
1089
1587
  method: "PATCH",
1090
- body: ForwardedBody,
1588
+ body: forwardedBody(),
1091
1589
  use: [api.sessionMiddleware]
1092
1590
  },
1093
1591
  async (ctx) => {
@@ -1165,19 +1663,11 @@ function buildSubscriptionsEndpoints(client, adminOptions) {
1165
1663
  }
1166
1664
  }
1167
1665
  ),
1168
- /**
1169
- * Immediate cancel from admin. Unlike the consumer `/subscription/cancel`,
1170
- * this one bypasses the local ownership check — an admin can cancel
1171
- * any subscription by StreamPay id. Mirrors the SDK's
1172
- * `SubscriptionCancel` body shape verbatim (only
1173
- * `cancel_related_invoices`; no period-end flag — StreamPay doesn't
1174
- * expose one on this endpoint).
1175
- */
1176
1666
  adminCancelSubscription: api.createAuthEndpoint(
1177
1667
  "/admin/streampay/subscriptions/:id/cancel",
1178
1668
  {
1179
1669
  method: "POST",
1180
- body: ForwardedBody,
1670
+ body: forwardedBody(),
1181
1671
  use: [api.sessionMiddleware]
1182
1672
  },
1183
1673
  async (ctx) => {
@@ -1205,16 +1695,11 @@ function buildSubscriptionsEndpoints(client, adminOptions) {
1205
1695
  }
1206
1696
  }
1207
1697
  ),
1208
- /**
1209
- * Admin-initiated freeze. Creates a new freeze window on a
1210
- * subscription. Body matches `FreezeSubscriptionCreateRequest`
1211
- * from the SDK. Returns the created `FreezeSubscriptionBase`.
1212
- */
1213
1698
  adminFreezeSubscription: api.createAuthEndpoint(
1214
1699
  "/admin/streampay/subscriptions/:id/freeze",
1215
1700
  {
1216
1701
  method: "POST",
1217
- body: ForwardedBody,
1702
+ body: forwardedBody(),
1218
1703
  use: [api.sessionMiddleware]
1219
1704
  },
1220
1705
  async (ctx) => {
@@ -1243,12 +1728,6 @@ function buildSubscriptionsEndpoints(client, adminOptions) {
1243
1728
  }
1244
1729
  }
1245
1730
  ),
1246
- /**
1247
- * List all freeze windows attached to a subscription. Useful for
1248
- * UIs that show "this sub is frozen X times" or for the
1249
- * adminDeleteFreeze / adminUpdateFreeze flows below that need a
1250
- * freeze id.
1251
- */
1252
1731
  adminListSubscriptionFreezes: api.createAuthEndpoint(
1253
1732
  "/admin/streampay/subscriptions/:id/freeze",
1254
1733
  {
@@ -1269,18 +1748,11 @@ function buildSubscriptionsEndpoints(client, adminOptions) {
1269
1748
  }
1270
1749
  }
1271
1750
  ),
1272
- /**
1273
- * Update an existing freeze window (shift start/end, change notes).
1274
- * Matches SDK's `updateSubscriptionFreeze` which takes
1275
- * `FreezeSubscriptionUpdateRequest` — note that
1276
- * `freeze_start_datetime` is REQUIRED on update even if it doesn't
1277
- * change (per OpenAPI schema).
1278
- */
1279
1751
  adminUpdateSubscriptionFreeze: api.createAuthEndpoint(
1280
1752
  "/admin/streampay/subscriptions/:id/freeze/:freezeId",
1281
1753
  {
1282
1754
  method: "PUT",
1283
- body: ForwardedBody,
1755
+ body: forwardedBody(),
1284
1756
  use: [api.sessionMiddleware]
1285
1757
  },
1286
1758
  async (ctx) => {
@@ -1309,15 +1781,6 @@ function buildSubscriptionsEndpoints(client, adminOptions) {
1309
1781
  }
1310
1782
  }
1311
1783
  ),
1312
- /**
1313
- * Delete (unfreeze) a specific freeze window. This is how you
1314
- * "unfreeze" as an admin: find the active freeze id via
1315
- * adminListSubscriptionFreezes, then DELETE it.
1316
- *
1317
- * Returns `{ deleted: true }` on success — the SDK's
1318
- * `deleteSubscriptionFreeze` returns `void`, so we synthesize a
1319
- * response body for client feedback.
1320
- */
1321
1784
  adminDeleteSubscriptionFreeze: api.createAuthEndpoint(
1322
1785
  "/admin/streampay/subscriptions/:id/freeze/:freezeId",
1323
1786
  {
@@ -1399,7 +1862,7 @@ function buildConsumersEndpoints(client, adminOptions) {
1399
1862
  "/admin/streampay/consumers/:id",
1400
1863
  {
1401
1864
  method: "PATCH",
1402
- body: ForwardedBody,
1865
+ body: forwardedBody(),
1403
1866
  use: [api.sessionMiddleware]
1404
1867
  },
1405
1868
  async (ctx) => {
@@ -1418,9 +1881,6 @@ function buildConsumersEndpoints(client, adminOptions) {
1418
1881
  }
1419
1882
  }
1420
1883
  ),
1421
- // Delete on StreamPay AND clear the `streampayConsumerId` link so
1422
- // the next checkout lazy-creates instead of 404'ing. deleteConsumer
1423
- // 404 is treated as success (race); a failed link-clear only logs.
1424
1884
  adminDeleteConsumer: api.createAuthEndpoint(
1425
1885
  "/admin/streampay/consumers/:id",
1426
1886
  {
@@ -1521,7 +1981,7 @@ function buildProductsEndpoints(client, adminOptions) {
1521
1981
  "/admin/streampay/products",
1522
1982
  {
1523
1983
  method: "POST",
1524
- body: ForwardedBody,
1984
+ body: forwardedBody(),
1525
1985
  use: [api.sessionMiddleware]
1526
1986
  },
1527
1987
  async (ctx) => {
@@ -1579,7 +2039,7 @@ function buildProductsEndpoints(client, adminOptions) {
1579
2039
  "/admin/streampay/products/:id",
1580
2040
  {
1581
2041
  method: "PUT",
1582
- body: ForwardedBody,
2042
+ body: forwardedBody(),
1583
2043
  use: [api.sessionMiddleware]
1584
2044
  },
1585
2045
  async (ctx) => {
@@ -1627,7 +2087,7 @@ function buildCouponsEndpoints(client, adminOptions) {
1627
2087
  "/admin/streampay/coupons",
1628
2088
  {
1629
2089
  method: "POST",
1630
- body: ForwardedBody,
2090
+ body: forwardedBody(),
1631
2091
  use: [api.sessionMiddleware]
1632
2092
  },
1633
2093
  async (ctx) => {
@@ -1685,7 +2145,7 @@ function buildCouponsEndpoints(client, adminOptions) {
1685
2145
  "/admin/streampay/coupons/:id",
1686
2146
  {
1687
2147
  method: "PUT",
1688
- body: ForwardedBody,
2148
+ body: forwardedBody(),
1689
2149
  use: [api.sessionMiddleware]
1690
2150
  },
1691
2151
  async (ctx) => {
@@ -1796,7 +2256,7 @@ function buildWebhookEventsEndpoints(adminOptions, registry) {
1796
2256
  ...where.length > 0 ? { where } : {},
1797
2257
  limit: size,
1798
2258
  offset: (page - 1) * size,
1799
- sortBy: { field: "processedAt", direction: "desc" }
2259
+ sortBy: { field: "receivedAt", direction: "desc" }
1800
2260
  }),
1801
2261
  adapter.count({
1802
2262
  model: WEBHOOK_EVENT_MODEL,
@@ -1912,7 +2372,6 @@ var CheckoutBody = zod.z.object({
1912
2372
  ]).optional(),
1913
2373
  slug: zod.z.string().optional(),
1914
2374
  referenceId: zod.z.string().optional(),
1915
- consumerId: zod.z.string().uuid().optional(),
1916
2375
  name: zod.z.string().min(1).optional(),
1917
2376
  description: zod.z.string().optional(),
1918
2377
  metadata: zod.z.record(zod.z.string(), zod.z.union([zod.z.string(), zod.z.number(), zod.z.boolean()])).optional(),
@@ -1954,8 +2413,7 @@ function resolveRedirectUrl(urlOrPath, request, baseURL) {
1954
2413
  if (!urlOrPath) return void 0;
1955
2414
  return new URL(urlOrPath, request?.url ?? baseURL).toString();
1956
2415
  }
1957
- async function resolveConsumerId(options, ctx, body, user) {
1958
- if (body.consumerId) return body.consumerId;
2416
+ async function resolveConsumerId(options, ctx, user) {
1959
2417
  if (!user || user.isAnonymous) return null;
1960
2418
  const { consumerId } = await ensureConsumerForUser(options, ctx, user);
1961
2419
  return consumerId;
@@ -1986,7 +2444,7 @@ var checkout = (checkoutOptions = {}) => (options) => {
1986
2444
  }
1987
2445
  }
1988
2446
  const items = await resolveProducts(ctx.body, checkoutOptions);
1989
- const consumerId = await resolveConsumerId(options, ctx, ctx.body, sessionUser);
2447
+ const consumerId = await resolveConsumerId(options, ctx, sessionUser);
1990
2448
  const successUrl = resolveRedirectUrl(
1991
2449
  ctx.body.successUrl ?? checkoutOptions.successUrl,
1992
2450
  ctx.request,
@@ -2005,6 +2463,7 @@ var checkout = (checkoutOptions = {}) => (options) => {
2005
2463
  const payload = {
2006
2464
  name: ctx.body.name ?? `Checkout ${(/* @__PURE__ */ new Date()).toISOString()}`,
2007
2465
  description: ctx.body.description ?? null,
2466
+ currency: checkoutOptions.currency ?? "SAR",
2008
2467
  items
2009
2468
  };
2010
2469
  if (consumerId !== null) payload.organization_consumer_id = consumerId;
@@ -2125,32 +2584,329 @@ function clampPageSize(size) {
2125
2584
  if (!size || !Number.isFinite(size) || size < 1) return DEFAULT_PAGE_SIZE;
2126
2585
  return Math.min(Math.floor(size), 100);
2127
2586
  }
2587
+ var STREAMPAY_EVENT_ENTITY_TYPES = {
2588
+ PAYMENT_SUCCEEDED: "PAYMENT",
2589
+ PAYMENT_FAILED: "PAYMENT",
2590
+ PAYMENT_CANCELED: "PAYMENT",
2591
+ PAYMENT_REFUNDED: "PAYMENT",
2592
+ PAYMENT_MARKED_AS_PAID: "PAYMENT",
2593
+ INVOICE_CREATED: "INVOICE",
2594
+ INVOICE_SENT: "INVOICE",
2595
+ INVOICE_ACCEPTED: "INVOICE",
2596
+ INVOICE_REJECTED: "INVOICE",
2597
+ INVOICE_COMPLETED: "INVOICE",
2598
+ INVOICE_CANCELED: "INVOICE",
2599
+ INVOICE_UPDATED: "INVOICE",
2600
+ SUBSCRIPTION_CREATED: "SUBSCRIPTION",
2601
+ SUBSCRIPTION_ACTIVATED: "SUBSCRIPTION",
2602
+ SUBSCRIPTION_INACTIVATED: "SUBSCRIPTION",
2603
+ SUBSCRIPTION_CANCELED: "SUBSCRIPTION",
2604
+ SUBSCRIPTION_FROZEN: "SUBSCRIPTION",
2605
+ SUBSCRIPTION_CYCLE_RENEWAL_FAILED: "SUBSCRIPTION",
2606
+ SUBSCRIPTION_CANCEL_AT_PERIOD_END: "SUBSCRIPTION",
2607
+ SUBSCRIPTION_FREEZE_NOW: "SUBSCRIPTION",
2608
+ SUBSCRIPTION_UNFREEZE_NOW: "SUBSCRIPTION",
2609
+ SUBSCRIPTION_UNFREEZE_FUTURE: "SUBSCRIPTION",
2610
+ SUBSCRIPTION_FREEZE_CANCEL: "SUBSCRIPTION",
2611
+ SUBSCRIPTION_PLAN_CHANGE_SCHEDULED: "SUBSCRIPTION",
2612
+ SUBSCRIPTION_PLAN_CHANGE_CANCELED: "SUBSCRIPTION",
2613
+ SUBSCRIPTION_PLAN_CHANGED: "SUBSCRIPTION",
2614
+ SUBSCRIPTION_PLAN_CHANGE_INVOICE_REISSUED: "SUBSCRIPTION",
2615
+ SUBSCRIPTION_PLAN_UPDATED: "SUBSCRIPTION",
2616
+ PAYMENT_LINK_PAY_ATTEMPT_FAILED: "PAYMENT_LINK"
2617
+ };
2618
+ function eventTypesForEntity(entityType) {
2619
+ return Object.entries(STREAMPAY_EVENT_ENTITY_TYPES).filter(([, entity]) => entity === entityType).map(([event]) => event);
2620
+ }
2621
+ var STREAMPAY_PAYMENT_EVENT_TYPES = eventTypesForEntity("PAYMENT");
2622
+ var STREAMPAY_INVOICE_EVENT_TYPES = eventTypesForEntity("INVOICE");
2623
+ var STREAMPAY_SUBSCRIPTION_EVENT_TYPES = eventTypesForEntity("SUBSCRIPTION");
2624
+ var STREAMPAY_PAYMENT_LINK_EVENT_TYPES = eventTypesForEntity("PAYMENT_LINK");
2625
+ var STREAMPAY_EVENT_TYPES = Object.keys(
2626
+ STREAMPAY_EVENT_ENTITY_TYPES
2627
+ );
2628
+ var StreamPayWebhookEnvelopeSchema = zod.z.object({
2629
+ event_type: zod.z.string().min(1),
2630
+ entity_type: zod.z.string().min(1),
2631
+ entity_id: zod.z.string().min(1),
2632
+ entity_url: zod.z.string(),
2633
+ status: zod.z.string(),
2634
+ timestamp: zod.z.string().min(1),
2635
+ data: zod.z.record(zod.z.string(), zod.z.unknown())
2636
+ });
2637
+ function isStreamPayWebhookEnvelope(value) {
2638
+ return StreamPayWebhookEnvelopeSchema.safeParse(value).success;
2639
+ }
2640
+ function isStreamPayEventType(value) {
2641
+ return Object.hasOwn(STREAMPAY_EVENT_ENTITY_TYPES, value);
2642
+ }
2643
+ function isKnownStreamPayWebhookPayload(payload) {
2644
+ return isStreamPayEventType(payload.event_type) && payload.entity_type === STREAMPAY_EVENT_ENTITY_TYPES[payload.event_type];
2645
+ }
2646
+ var SUBSCRIPTION_MODEL3 = "subscription";
2647
+ function requireUser(ctx) {
2648
+ const user = asSessionUser(ctx.context.session?.user);
2649
+ if (!user) {
2650
+ throw new api.APIError("UNAUTHORIZED", {
2651
+ message: "Subscription endpoints require an authenticated session."
2652
+ });
2653
+ }
2654
+ if (user.isAnonymous) {
2655
+ throw new api.APIError("UNAUTHORIZED", {
2656
+ message: "Anonymous users cannot manage subscriptions."
2657
+ });
2658
+ }
2659
+ return user;
2660
+ }
2661
+ function resolveReference(user, query) {
2662
+ const referenceId = query?.referenceId ?? user.id;
2663
+ return {
2664
+ referenceId,
2665
+ referenceType: query?.referenceType ?? (referenceId === user.id ? "user" : "custom")
2666
+ };
2667
+ }
2668
+ async function authorizeReference(ctx, user, referenceId, referenceType, action, subsOptions) {
2669
+ if (referenceType === "user" && referenceId === user.id) return;
2670
+ if (!subsOptions.authorizeReference) {
2671
+ throw new api.APIError("FORBIDDEN", {
2672
+ code: $ERROR_CODES.FORBIDDEN.code,
2673
+ message: "Cross-account subscription actions require an `authorizeReference` callback."
2674
+ });
2675
+ }
2676
+ const authorized = await subsOptions.authorizeReference(
2677
+ { user, referenceId, referenceType, action },
2678
+ ctx
2679
+ );
2680
+ if (!authorized) {
2681
+ throw new api.APIError("FORBIDDEN", {
2682
+ code: $ERROR_CODES.SUBSCRIPTION_REFERENCE_NOT_AUTHORIZED.code,
2683
+ message: "Not authorized for this subscription reference."
2684
+ });
2685
+ }
2686
+ }
2687
+ function getAdapter2(ctx) {
2688
+ const adapter = ctx.context.adapter;
2689
+ if (!adapter) {
2690
+ throw new api.APIError("INTERNAL_SERVER_ERROR", {
2691
+ message: "Better Auth adapter is not available on the request context."
2692
+ });
2693
+ }
2694
+ return adapter;
2695
+ }
2696
+ async function findOwnedSubscription(ctx, user, subscriptionId, subsOptions, action) {
2697
+ const adapter = getAdapter2(ctx);
2698
+ const localRow = await adapter.findOne({
2699
+ model: SUBSCRIPTION_MODEL3,
2700
+ where: [{ field: "id", value: subscriptionId }]
2701
+ });
2702
+ const row = localRow ?? await adapter.findOne({
2703
+ model: SUBSCRIPTION_MODEL3,
2704
+ where: [{ field: "streampaySubscriptionId", value: subscriptionId }]
2705
+ });
2706
+ if (!row) {
2707
+ throw new api.APIError("NOT_FOUND", {
2708
+ code: $ERROR_CODES.SUBSCRIPTION_NOT_FOUND.code,
2709
+ message: "Subscription not found."
2710
+ });
2711
+ }
2712
+ await authorizeReference(
2713
+ ctx,
2714
+ user,
2715
+ row.referenceId,
2716
+ row.referenceType ?? "user",
2717
+ action,
2718
+ subsOptions
2719
+ );
2720
+ return row;
2721
+ }
2722
+ async function requireConfirmedOwnedSubscription(ctx, subscriptionId, subsOptions, action) {
2723
+ const user = requireUser(ctx);
2724
+ const adapter = getAdapter2(ctx);
2725
+ const row = await findOwnedSubscription(ctx, user, subscriptionId, subsOptions, action);
2726
+ if (!row.streampaySubscriptionId) {
2727
+ throw new api.APIError("BAD_REQUEST", {
2728
+ code: $ERROR_CODES.SUBSCRIPTION_INVALID_STATE.code,
2729
+ message: "Subscription has not been confirmed by StreamPay yet."
2730
+ });
2731
+ }
2732
+ return {
2733
+ adapter,
2734
+ row,
2735
+ streampaySubscriptionId: row.streampaySubscriptionId
2736
+ };
2737
+ }
2738
+ var SUBSCRIPTION_MODEL4 = "subscription";
2739
+ async function recoverCheckoutUrl(client, row) {
2740
+ if (!row.streampayPaymentLinkId) return { kind: "expired" };
2741
+ try {
2742
+ const url = client.getPaymentUrl(await client.getPaymentLink(row.streampayPaymentLinkId));
2743
+ return url ? { kind: "recovered", url } : { kind: "expired" };
2744
+ } catch (err) {
2745
+ if (readSdkErrorFields(err).status === 404) return { kind: "expired" };
2746
+ throw err;
2747
+ }
2748
+ }
2749
+ async function deleteReservedSubscription(adapter, rowId, log, reason) {
2750
+ try {
2751
+ await adapter.delete({
2752
+ model: SUBSCRIPTION_MODEL4,
2753
+ where: [{ field: "id", value: rowId }]
2754
+ });
2755
+ } catch (err) {
2756
+ const message = err instanceof Error ? err.message : String(err);
2757
+ log.error(`${reason}: failed to release reserved subscription row=${rowId}: ${message}`);
2758
+ }
2759
+ }
2760
+ function checkoutInProgressError() {
2761
+ return new api.APIError("CONFLICT", {
2762
+ code: $ERROR_CODES.SUBSCRIPTION_CHECKOUT_IN_PROGRESS.code,
2763
+ message: "A subscription checkout is already being created for this plan group."
2764
+ });
2765
+ }
2766
+ async function resumeOrReserveCheckoutSlot(args) {
2767
+ const { client, adapter, candidates, activeSlotKey, planName, now, log } = args;
2768
+ const reuseCandidate = candidates.find(
2769
+ (row2) => row2.plan === planName && row2.status === "incomplete" && Boolean(row2.streampayPaymentLinkId) && row2.createdAt instanceof Date && now - row2.createdAt.getTime() < UPGRADE_IDEMPOTENCY_WINDOW_MS
2770
+ );
2771
+ if (reuseCandidate) {
2772
+ let recovery;
2773
+ try {
2774
+ recovery = await recoverCheckoutUrl(client, reuseCandidate);
2775
+ } catch (err) {
2776
+ toAPIError(
2777
+ {
2778
+ logPrefix: `resume subscription checkout failed for row=${reuseCandidate.id}:`,
2779
+ userMessage: "Unable to resume subscription checkout."
2780
+ },
2781
+ err,
2782
+ log
2783
+ );
2784
+ }
2785
+ if (recovery.kind === "recovered") {
2786
+ return { kind: "recovered", row: reuseCandidate, url: recovery.url };
2787
+ }
2788
+ await adapter.update({
2789
+ model: SUBSCRIPTION_MODEL4,
2790
+ update: { status: "incomplete_expired", activeSlotKey: null, updatedAt: /* @__PURE__ */ new Date() },
2791
+ where: [{ field: "id", value: reuseCandidate.id }]
2792
+ });
2793
+ }
2794
+ const { data: reservationData, consumerId } = await args.createReservation();
2795
+ let row;
2796
+ try {
2797
+ row = await adapter.create({
2798
+ model: SUBSCRIPTION_MODEL4,
2799
+ data: reservationData
2800
+ });
2801
+ } catch (err) {
2802
+ if (!isUniqueConstraintError(err)) throw err;
2803
+ const reserved = await adapter.findOne({
2804
+ model: SUBSCRIPTION_MODEL4,
2805
+ where: [{ field: "activeSlotKey", value: activeSlotKey }]
2806
+ });
2807
+ if (reserved?.status !== "incomplete") throw err;
2808
+ let recovery;
2809
+ try {
2810
+ recovery = await recoverCheckoutUrl(client, reserved);
2811
+ } catch (recoveryError) {
2812
+ toAPIError(
2813
+ {
2814
+ logPrefix: `resume concurrent subscription checkout failed for row=${reserved.id}:`,
2815
+ userMessage: "Unable to resume subscription checkout."
2816
+ },
2817
+ recoveryError,
2818
+ log
2819
+ );
2820
+ }
2821
+ if (recovery.kind === "recovered") {
2822
+ return { kind: "recovered", row: reserved, url: recovery.url };
2823
+ }
2824
+ const reservationIsStale = !(reserved.createdAt instanceof Date) || now - reserved.createdAt.getTime() >= UPGRADE_IDEMPOTENCY_WINDOW_MS;
2825
+ if (!reservationIsStale) throw checkoutInProgressError();
2826
+ const released = await adapter.update({
2827
+ model: SUBSCRIPTION_MODEL4,
2828
+ update: { status: "incomplete_expired", activeSlotKey: null, updatedAt: /* @__PURE__ */ new Date() },
2829
+ where: [
2830
+ { field: "id", value: reserved.id },
2831
+ { field: "activeSlotKey", value: activeSlotKey }
2832
+ ]
2833
+ });
2834
+ if (!released) throw checkoutInProgressError();
2835
+ try {
2836
+ row = await adapter.create({
2837
+ model: SUBSCRIPTION_MODEL4,
2838
+ data: reservationData
2839
+ });
2840
+ } catch (retryError) {
2841
+ if (!isUniqueConstraintError(retryError)) throw retryError;
2842
+ throw checkoutInProgressError();
2843
+ }
2844
+ log.warn(`released stale checkout reservation row=${reserved.id} for plan=${planName}.`);
2845
+ }
2846
+ return { kind: "reserved", row, consumerId };
2847
+ }
2848
+
2849
+ // src/plugins/subscriptions/lifecycle.ts
2850
+ function isAlreadyCanceledFreezeError(err) {
2851
+ const sdkError = readSdkErrorFields(err);
2852
+ const envelope = readEnvelope(sdkError.body);
2853
+ return sdkError.status === 403 && envelope?.code === "STREAM_ERROR" && envelope.additionalInfo === "Cannot delete non-latest freeze entry.";
2854
+ }
2855
+ function subscriptionCouponIds(stream) {
2856
+ const coupons = [];
2857
+ for (const coupon of stream.coupon_calculation_metadata?.coupons ?? []) {
2858
+ if (coupon.coupon_id) coupons.push(coupon.coupon_id);
2859
+ }
2860
+ return coupons;
2861
+ }
2862
+ function configuredPlanForSubscription(subscription, plans) {
2863
+ return plans.list.find(
2864
+ (plan) => subscription.items?.some((item) => subscriptionItemProductId(item) === plan.productId)
2865
+ );
2866
+ }
2867
+ var SUBSCRIPTION_INTERVALS = ["WEEK", "MONTH", "QUARTER", "YEAR"];
2128
2868
  var PlanSchema = zod.z.object({
2129
2869
  name: zod.z.string().min(1, "every plan must have a non-empty `name`."),
2130
2870
  productId: zod.z.string().min(1, "missing a non-empty `productId`."),
2131
- priceHalalat: zod.z.number({ error: "must have a non-negative numeric `priceHalalat`." }).refine((n) => Number.isFinite(n) && n >= 0, {
2132
- message: "must have a non-negative numeric `priceHalalat`."
2133
- }),
2134
- billingInterval: zod.z.enum(["WEEK", "MONTH", "QUARTER", "YEAR"], {
2135
- error: () => "has invalid `billingInterval`. Expected one of: WEEK, MONTH, QUARTER, YEAR."
2136
- }),
2871
+ priceInSmallestUnit: zod.z.custom(
2872
+ (value) => typeof value === "number" && Number.isSafeInteger(value) && value >= 0,
2873
+ "must have a non-negative safe-integer `priceInSmallestUnit`."
2874
+ ),
2875
+ currency: zod.z.enum(["SAR", "USD", "EUR", "GBP", "AED", "BHD", "KWD", "OMR", "QAR"]).optional(),
2876
+ version: zod.z.string().min(1, "has an empty `version`.").optional(),
2877
+ billingInterval: zod.z.custom(
2878
+ (value) => typeof value === "string" && SUBSCRIPTION_INTERVALS.some((interval) => interval === value),
2879
+ "has invalid `billingInterval`. Expected one of: WEEK, MONTH, QUARTER, YEAR."
2880
+ ),
2137
2881
  billingIntervalCount: zod.z.number().refine((n) => Number.isInteger(n) && n >= 1, {
2138
2882
  message: "has invalid `billingIntervalCount` \u2014 must be a positive integer."
2139
2883
  }).optional(),
2140
- group: zod.z.string().optional(),
2884
+ trialPeriodDays: zod.z.number().refine((n) => Number.isInteger(n) && n >= 1 && n <= 365, {
2885
+ message: "has invalid `trialPeriodDays` \u2014 must be an integer from 1 to 365."
2886
+ }).optional(),
2887
+ group: zod.z.string().min(1, "has an empty `group`.").optional(),
2141
2888
  limits: zod.z.record(zod.z.string(), zod.z.unknown()).optional()
2142
2889
  });
2143
2890
  var PlansSchema = zod.z.array(PlanSchema).nonempty("`plans` resolved to an empty list. Provide at least one plan.").superRefine((plans, ctx) => {
2144
- const seen = /* @__PURE__ */ new Set();
2891
+ const seenNames = /* @__PURE__ */ new Set();
2892
+ const seenProductIds = /* @__PURE__ */ new Set();
2145
2893
  for (const [index, plan] of plans.entries()) {
2146
- if (seen.has(plan.name)) {
2894
+ if (seenNames.has(plan.name)) {
2147
2895
  ctx.addIssue({
2148
2896
  code: "custom",
2149
2897
  path: [index, "name"],
2150
2898
  message: `duplicate plan name "${plan.name}" \u2014 plan names must be unique.`
2151
2899
  });
2152
2900
  }
2153
- seen.add(plan.name);
2901
+ seenNames.add(plan.name);
2902
+ if (seenProductIds.has(plan.productId)) {
2903
+ ctx.addIssue({
2904
+ code: "custom",
2905
+ path: [index, "productId"],
2906
+ message: `duplicate productId "${plan.productId}" \u2014 webhook plan inference requires unique product IDs.`
2907
+ });
2908
+ }
2909
+ seenProductIds.add(plan.productId);
2154
2910
  }
2155
2911
  });
2156
2912
  function validatePlansShape(plans) {
@@ -2188,16 +2944,19 @@ function createPlanResolver(plans) {
2188
2944
  }
2189
2945
  };
2190
2946
  }
2191
- function hasFeature(subscription, plan, feature) {
2947
+ function hasSubscriptionAccess(subscription, accessStatuses = DEFAULT_ACCESS_STATUSES) {
2948
+ return accessStatuses.includes(subscription.status);
2949
+ }
2950
+ function hasFeature(subscription, plan, feature, accessStatuses = DEFAULT_ACCESS_STATUSES) {
2192
2951
  if (!plan?.limits) return false;
2193
- if (subscription.status !== "active" && subscription.status !== "frozen") return false;
2952
+ if (!hasSubscriptionAccess(subscription, accessStatuses)) return false;
2194
2953
  const value = plan.limits[feature];
2195
2954
  if (typeof value === "boolean") return value;
2196
2955
  if (typeof value === "number") return value > 0;
2197
2956
  return Boolean(value);
2198
2957
  }
2199
- function checkLimit(subscription, plan, feature, requested) {
2200
- if (!plan?.limits || subscription.status !== "active" && subscription.status !== "frozen") {
2958
+ function checkLimit(subscription, plan, feature, requested, accessStatuses = DEFAULT_ACCESS_STATUSES) {
2959
+ if (!plan?.limits || !hasSubscriptionAccess(subscription, accessStatuses)) {
2201
2960
  return { allowed: false, limit: 0, remaining: 0 };
2202
2961
  }
2203
2962
  const raw = plan.limits[feature];
@@ -2208,144 +2967,194 @@ function checkLimit(subscription, plan, feature, requested) {
2208
2967
  return { allowed, limit, remaining };
2209
2968
  }
2210
2969
 
2211
- // src/plugins/subscriptions/endpoints.ts
2212
- var SUBSCRIPTION_MODEL2 = "subscription";
2213
- var UpgradeBody = zod.z.object({
2214
- plan: zod.z.string().min(1),
2970
+ // src/plugins/subscriptions/reads.ts
2971
+ var SUBSCRIPTION_MODEL5 = "subscription";
2972
+ var ReferenceQueryFields = {
2215
2973
  referenceId: zod.z.string().min(1).optional(),
2216
- successUrl: zod.z.string().url().optional(),
2217
- failureUrl: zod.z.string().url().optional()
2218
- });
2219
- var SuccessQuery = zod.z.object({
2220
- subscriptionId: zod.z.string().uuid(),
2221
- callbackURL: zod.z.string().url().optional()
2222
- });
2223
- var CancelBody = zod.z.object({
2224
- subscriptionId: zod.z.string().uuid(),
2225
- cancelRelatedInvoices: zod.z.boolean().optional(),
2226
- /**
2227
- * When `true`, schedule the cancellation to take effect at the end
2228
- * of the current billing period instead of terminating immediately.
2229
- * Implemented via StreamPay's `PATCH /subscriptions/:id` with
2230
- * `until_cycle_number = current_cycle_number` (see OpenAPI
2231
- * `SubscriptionUpdate.until_cycle_number`). The customer retains
2232
- * access through `periodEnd`; status stays `active` until the
2233
- * `SUBSCRIPTION_CANCEL_AT_PERIOD_END` webhook lands.
2234
- */
2235
- cancelAtPeriodEnd: zod.z.boolean().optional()
2236
- });
2237
- var ChangePlanBody = zod.z.object({
2238
- /** Target plan name, must be declared in `subscriptions({ plans })`. */
2239
- plan: zod.z.string().min(1),
2240
- /**
2241
- * `at_period_end` (default) — old plan keeps serving until
2242
- * `periodEnd`, then the new plan's payment link is presented via a
2243
- * freshly spawned `incomplete` row. Safer. Customer pays only what
2244
- * they would on a normal renewal cycle.
2245
- *
2246
- * `immediate` — PATCH the existing StreamPay subscription's items
2247
- * to the new plan's productId. No proration — StreamPay does not
2248
- * expose proration on PATCH. The current cycle's paid invoice is
2249
- * NOT refunded; the customer starts paying the new price from the
2250
- * next cycle. Use for "upgrade now, I'll pay more later" UX where
2251
- * proration is acceptable.
2252
- */
2253
- mode: zod.z.enum(["at_period_end", "immediate"]).optional(),
2254
- successUrl: zod.z.string().url().optional(),
2255
- failureUrl: zod.z.string().url().optional()
2256
- });
2257
- var FreezeBody = zod.z.object({
2258
- subscriptionId: zod.z.string().uuid(),
2259
- freezeStartDatetime: zod.z.string().datetime(),
2260
- freezeEndDatetime: zod.z.string().datetime().nullable().optional(),
2261
- notes: zod.z.string().optional()
2262
- });
2263
- var UnfreezeBody = zod.z.object({
2264
- subscriptionId: zod.z.string().uuid()
2265
- });
2974
+ referenceType: zod.z.enum(["user", "organization", "custom"]).optional()
2975
+ };
2976
+ var ListQuery = zod.z.object(ReferenceQueryFields).optional();
2266
2977
  var CurrentQuery = zod.z.object({
2978
+ ...ReferenceQueryFields,
2267
2979
  group: zod.z.string().min(1).optional()
2268
2980
  }).optional();
2269
2981
  var HasFeatureQuery = zod.z.object({
2982
+ ...ReferenceQueryFields,
2270
2983
  feature: zod.z.string().min(1),
2271
2984
  group: zod.z.string().min(1).optional()
2272
2985
  });
2273
2986
  var CheckLimitQuery = zod.z.object({
2987
+ ...ReferenceQueryFields,
2274
2988
  feature: zod.z.string().min(1),
2275
2989
  count: zod.z.coerce.number().int().min(0),
2276
2990
  group: zod.z.string().min(1).optional()
2277
2991
  });
2278
- function requireUser(ctx) {
2279
- const user = asSessionUser(ctx.context.session?.user);
2280
- if (!user) {
2281
- throw new api.APIError("UNAUTHORIZED", {
2282
- message: "Subscription endpoints require an authenticated session."
2283
- });
2284
- }
2285
- if (user.isAnonymous) {
2286
- throw new api.APIError("UNAUTHORIZED", {
2287
- message: "Anonymous users cannot manage subscriptions."
2288
- });
2289
- }
2290
- return user;
2291
- }
2292
- async function authorizeReference(ctx, user, referenceId, action, subsOptions) {
2293
- if (referenceId === user.id) return;
2294
- if (!subsOptions.authorizeReference) {
2295
- throw new api.APIError("FORBIDDEN", {
2296
- code: $ERROR_CODES.FORBIDDEN.code,
2297
- message: "Cross-account subscription actions require an `authorizeReference` callback."
2298
- });
2299
- }
2300
- const ok = await subsOptions.authorizeReference({ user, referenceId, action }, ctx);
2301
- if (!ok) {
2302
- throw new api.APIError("FORBIDDEN", {
2303
- code: "SUBSCRIPTION_REFERENCE_NOT_AUTHORIZED",
2304
- message: "Not authorized for this subscription reference."
2305
- });
2306
- }
2307
- }
2308
- function getAdapter2(ctx) {
2309
- const adapter = ctx.context.adapter;
2310
- if (!adapter) {
2311
- throw new api.APIError("INTERNAL_SERVER_ERROR", {
2312
- message: "Better Auth adapter is not available on the request context."
2313
- });
2314
- }
2315
- return adapter;
2316
- }
2317
- function echoSubscriptionPatch(stream) {
2318
- const items = [];
2319
- for (const item of stream.items ?? []) {
2320
- const productId = item.product?.id;
2321
- const quantity = item.quantity;
2322
- if (!productId || quantity === void 0) continue;
2323
- items.push({ product_id: productId, quantity });
2324
- }
2325
- const coupons = [];
2326
- for (const c of stream.coupon_calculation_metadata?.coupons ?? []) {
2327
- if (c.coupon_id) coupons.push(c.coupon_id);
2328
- }
2329
- return { items, coupons };
2330
- }
2331
- async function findOwnedSubscription(ctx, user, streampaySubscriptionId, subsOptions, action) {
2332
- const adapter = getAdapter2(ctx);
2333
- const row = await adapter.findOne({
2334
- model: SUBSCRIPTION_MODEL2,
2335
- where: [{ field: "streampaySubscriptionId", value: streampaySubscriptionId }]
2992
+ async function resolveLiveSubscription(ctx, query, subsOptions, accessStatuses) {
2993
+ const user = requireUser(ctx);
2994
+ const reference = resolveReference(user, query);
2995
+ await authorizeReference(
2996
+ ctx,
2997
+ user,
2998
+ reference.referenceId,
2999
+ reference.referenceType,
3000
+ "read",
3001
+ subsOptions
3002
+ );
3003
+ const rows = await getAdapter2(ctx).findMany({
3004
+ model: SUBSCRIPTION_MODEL5,
3005
+ where: [
3006
+ { field: "referenceId", value: reference.referenceId },
3007
+ { field: "referenceType", value: reference.referenceType },
3008
+ { field: "group", value: query.group ?? null }
3009
+ ]
2336
3010
  });
2337
- if (!row) {
2338
- throw new api.APIError("NOT_FOUND", {
2339
- code: "SUBSCRIPTION_NOT_FOUND",
2340
- message: "Subscription not found."
2341
- });
2342
- }
2343
- await authorizeReference(ctx, user, row.referenceId, action, subsOptions);
2344
- return row;
3011
+ return rows.find((row) => hasSubscriptionAccess(row, accessStatuses)) ?? null;
2345
3012
  }
2346
- function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
3013
+ function buildSubscriptionReadEndpoints(subsOptions, plansRef) {
3014
+ const accessStatuses = subsOptions.accessStatuses ?? DEFAULT_ACCESS_STATUSES;
3015
+ return {
3016
+ listSubscriptions: api.createAuthEndpoint(
3017
+ "/subscription/list",
3018
+ {
3019
+ method: "GET",
3020
+ query: ListQuery,
3021
+ use: [api.sessionMiddleware]
3022
+ },
3023
+ async (ctx) => {
3024
+ const user = requireUser(ctx);
3025
+ const reference = resolveReference(user, ctx.query);
3026
+ await authorizeReference(
3027
+ ctx,
3028
+ user,
3029
+ reference.referenceId,
3030
+ reference.referenceType,
3031
+ "read",
3032
+ subsOptions
3033
+ );
3034
+ const rows = await getAdapter2(ctx).findMany({
3035
+ model: SUBSCRIPTION_MODEL5,
3036
+ where: [
3037
+ { field: "referenceId", value: reference.referenceId },
3038
+ { field: "referenceType", value: reference.referenceType }
3039
+ ]
3040
+ });
3041
+ const plans = await plansRef();
3042
+ return ctx.json(
3043
+ rows.map((row) => ({
3044
+ ...row,
3045
+ plan: plans.byName.get(row.plan) ?? null
3046
+ }))
3047
+ );
3048
+ }
3049
+ ),
3050
+ currentSubscription: api.createAuthEndpoint(
3051
+ "/subscription/current",
3052
+ {
3053
+ method: "GET",
3054
+ query: CurrentQuery,
3055
+ use: [api.sessionMiddleware]
3056
+ },
3057
+ async (ctx) => {
3058
+ const live = await resolveLiveSubscription(
3059
+ ctx,
3060
+ ctx.query ?? {},
3061
+ subsOptions,
3062
+ accessStatuses
3063
+ );
3064
+ if (!live) return ctx.json(null);
3065
+ const plans = await plansRef();
3066
+ return ctx.json({ ...live, plan: plans.byName.get(live.plan) ?? null });
3067
+ }
3068
+ ),
3069
+ hasSubscriptionFeature: api.createAuthEndpoint(
3070
+ "/subscription/has-feature",
3071
+ {
3072
+ method: "GET",
3073
+ query: HasFeatureQuery,
3074
+ use: [api.sessionMiddleware]
3075
+ },
3076
+ async (ctx) => {
3077
+ const live = await resolveLiveSubscription(ctx, ctx.query, subsOptions, accessStatuses);
3078
+ if (!live) return ctx.json({ hasFeature: false });
3079
+ const plan = (await plansRef()).byName.get(live.plan);
3080
+ return ctx.json({
3081
+ hasFeature: hasFeature(live, plan, ctx.query.feature, accessStatuses)
3082
+ });
3083
+ }
3084
+ ),
3085
+ checkSubscriptionLimit: api.createAuthEndpoint(
3086
+ "/subscription/check-limit",
3087
+ {
3088
+ method: "GET",
3089
+ query: CheckLimitQuery,
3090
+ use: [api.sessionMiddleware]
3091
+ },
3092
+ async (ctx) => {
3093
+ const live = await resolveLiveSubscription(ctx, ctx.query, subsOptions, accessStatuses);
3094
+ if (!live) return ctx.json({ allowed: false, limit: 0, remaining: 0 });
3095
+ const plan = (await plansRef()).byName.get(live.plan);
3096
+ return ctx.json(checkLimit(live, plan, ctx.query.feature, ctx.query.count, accessStatuses));
3097
+ }
3098
+ )
3099
+ };
3100
+ }
3101
+
3102
+ // src/plugins/subscriptions/endpoints.ts
3103
+ var SUBSCRIPTION_MODEL6 = "subscription";
3104
+ var UpgradeBody = zod.z.object({
3105
+ plan: zod.z.string().min(1),
3106
+ referenceId: zod.z.string().min(1).optional(),
3107
+ referenceType: zod.z.enum(["user", "organization", "custom"]).optional(),
3108
+ successUrl: zod.z.string().url().optional(),
3109
+ failureUrl: zod.z.string().url().optional()
3110
+ });
3111
+ var SuccessQuery = zod.z.object({
3112
+ subscriptionId: zod.z.string().min(1)
3113
+ });
3114
+ var CancelBody = zod.z.object({
3115
+ subscriptionId: zod.z.string().min(1),
3116
+ cancelRelatedInvoices: zod.z.boolean().optional(),
3117
+ cancelAtPeriodEnd: zod.z.boolean().optional()
3118
+ });
3119
+ var ChangePlanBody = zod.z.object({
3120
+ subscriptionId: zod.z.string().min(1),
3121
+ plan: zod.z.string().min(1)
3122
+ }).strict();
3123
+ var FreezeBody = zod.z.object({
3124
+ subscriptionId: zod.z.string().min(1),
3125
+ freezeStartDatetime: zod.z.string().datetime(),
3126
+ freezeEndDatetime: zod.z.string().datetime().nullable().optional(),
3127
+ notes: zod.z.string().optional()
3128
+ });
3129
+ var UnfreezeBody = zod.z.object({
3130
+ subscriptionId: zod.z.string().min(1)
3131
+ });
3132
+ var CancelFreezeBody = zod.z.object({
3133
+ subscriptionId: zod.z.string().min(1),
3134
+ freezeId: zod.z.string().min(1)
3135
+ });
3136
+ var SUCCESS_RECONCILIATION_CLOCK_SKEW_MS = 5 * 60 * 1e3;
3137
+ function isCheckoutSubscriptionCandidate(subscription, row, productId) {
3138
+ if (subscription.organization_consumer_id !== row.streampayConsumerId) return false;
3139
+ if (!isCheckoutSuccessStatus(subscription.status)) return false;
3140
+ if (!subscription.items?.some((item) => subscriptionItemProductId(item) === productId)) {
3141
+ return false;
3142
+ }
3143
+ const upstreamPaymentLinkId = subscription.latest_invoice?.payment_link_id;
3144
+ if (row.streampayPaymentLinkId && upstreamPaymentLinkId && upstreamPaymentLinkId !== row.streampayPaymentLinkId) {
3145
+ return false;
3146
+ }
3147
+ if (row.streampayPaymentLinkId && upstreamPaymentLinkId === row.streampayPaymentLinkId) {
3148
+ return true;
3149
+ }
3150
+ if (!subscription.created_at || !(row.createdAt instanceof Date)) return false;
3151
+ const createdAt = new Date(subscription.created_at).getTime();
3152
+ return Number.isFinite(createdAt) && createdAt >= row.createdAt.getTime() - SUCCESS_RECONCILIATION_CLOCK_SKEW_MS;
3153
+ }
3154
+ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
2347
3155
  const client = options.client;
2348
3156
  return {
3157
+ ...buildSubscriptionReadEndpoints(subsOptions, plansRef),
2349
3158
  upgradeSubscription: api.createAuthEndpoint(
2350
3159
  "/subscription/upgrade",
2351
3160
  {
@@ -2356,58 +3165,134 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
2356
3165
  async (ctx) => {
2357
3166
  const user = requireUser(ctx);
2358
3167
  const referenceId = ctx.body.referenceId ?? user.id;
2359
- await authorizeReference(ctx, user, referenceId, "upgrade", subsOptions);
3168
+ const referenceType = ctx.body.referenceType ?? (referenceId === user.id ? "user" : "custom");
3169
+ await authorizeReference(ctx, user, referenceId, referenceType, "upgrade", subsOptions);
2360
3170
  const plans = await plansRef();
2361
3171
  const plan = plans.byName.get(ctx.body.plan);
2362
3172
  if (!plan) {
2363
3173
  throw new api.APIError("NOT_FOUND", {
2364
- code: "SUBSCRIPTION_PLAN_NOT_FOUND",
3174
+ code: $ERROR_CODES.SUBSCRIPTION_PLAN_NOT_FOUND.code,
2365
3175
  message: `Plan "${ctx.body.plan}" is not configured.`
2366
3176
  });
2367
3177
  }
2368
3178
  const adapter = getAdapter2(ctx);
2369
3179
  const existingActive = await adapter.findMany({
2370
- model: SUBSCRIPTION_MODEL2,
3180
+ model: SUBSCRIPTION_MODEL6,
2371
3181
  where: [
2372
3182
  { field: "referenceId", value: referenceId },
2373
- ...plan.group ? [{ field: "group", value: plan.group }] : []
3183
+ { field: "referenceType", value: referenceType },
3184
+ { field: "group", value: plan.group ?? null }
2374
3185
  ]
2375
3186
  });
2376
- const liveActive = existingActive.find(
2377
- (row2) => row2.status === "active" || row2.status === "frozen" || row2.status === "past_due"
3187
+ const defaultTrialEligible = !existingActive.some(
3188
+ (row2) => row2.trialStart instanceof Date || row2.trialEnd instanceof Date || row2.status === "trial_pending" || row2.status === "trialing"
2378
3189
  );
3190
+ const trialEligible = plan.trialPeriodDays === void 0 ? false : subsOptions.isTrialEligible ? await subsOptions.isTrialEligible(
3191
+ {
3192
+ user,
3193
+ referenceId,
3194
+ referenceType,
3195
+ plan,
3196
+ previousSubscriptions: existingActive,
3197
+ defaultEligible: defaultTrialEligible
3198
+ },
3199
+ ctx
3200
+ ) : defaultTrialEligible;
3201
+ const liveActive = existingActive.find((row2) => isManageableSubscriptionStatus(row2.status));
2379
3202
  if (liveActive) {
2380
3203
  throw new api.APIError("CONFLICT", {
2381
- code: "SUBSCRIPTION_ALREADY_ACTIVE",
2382
- 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."
3204
+ code: $ERROR_CODES.SUBSCRIPTION_ALREADY_ACTIVE.code,
3205
+ 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."
2383
3206
  });
2384
3207
  }
2385
- const now = Date.now();
2386
- const reuseCandidate = existingActive.find(
2387
- (row2) => row2.plan === plan.name && row2.status === "incomplete" && row2.createdAt instanceof Date && now - row2.createdAt.getTime() < UPGRADE_IDEMPOTENCY_WINDOW_MS
2388
- );
2389
- if (reuseCandidate) {
3208
+ const activeSlotKey = subscriptionSlotKey(referenceType, referenceId, plan.group);
3209
+ const reservation = await resumeOrReserveCheckoutSlot({
3210
+ client,
3211
+ adapter,
3212
+ candidates: existingActive,
3213
+ activeSlotKey,
3214
+ planName: plan.name,
3215
+ now: Date.now(),
3216
+ log: getLogger(ctx),
3217
+ createReservation: async () => {
3218
+ const { consumerId: consumerId2 } = await ensureConsumerForUser(
3219
+ options,
3220
+ { context: ctx.context },
3221
+ user
3222
+ );
3223
+ return {
3224
+ consumerId: consumerId2,
3225
+ data: {
3226
+ referenceId,
3227
+ referenceType,
3228
+ activeSlotKey,
3229
+ streampaySubscriptionId: null,
3230
+ plan: plan.name,
3231
+ planVersion: plan.version ?? null,
3232
+ productId: plan.productId,
3233
+ group: plan.group ?? null,
3234
+ streampayConsumerId: consumerId2,
3235
+ streampayPaymentLinkId: null,
3236
+ status: "incomplete",
3237
+ providerStatus: null,
3238
+ billingStatus: "current",
3239
+ amountInSmallestUnit: plan.priceInSmallestUnit,
3240
+ originalAmountInSmallestUnit: plan.priceInSmallestUnit,
3241
+ currency: plan.currency ?? "SAR",
3242
+ billingInterval: plan.billingInterval,
3243
+ billingIntervalCount: plan.billingIntervalCount ?? 1,
3244
+ periodStart: null,
3245
+ periodEnd: null,
3246
+ currentCycleNumber: null,
3247
+ trialStart: null,
3248
+ trialEnd: null,
3249
+ cancelAtPeriodEnd: false,
3250
+ cancelAt: null,
3251
+ cancelScheduledAt: null,
3252
+ canceledAt: null,
3253
+ pendingPlan: null,
3254
+ pendingProductId: null,
3255
+ pendingPlanEffectiveAt: null,
3256
+ endedAt: null,
3257
+ frozenAt: null,
3258
+ freezeEndAt: null,
3259
+ providerUpdatedAt: null,
3260
+ syncedAt: null,
3261
+ createdAt: /* @__PURE__ */ new Date(),
3262
+ updatedAt: /* @__PURE__ */ new Date()
3263
+ }
3264
+ };
3265
+ }
3266
+ });
3267
+ if (reservation.kind === "recovered") {
2390
3268
  return ctx.json({
2391
- subscriptionId: reuseCandidate.id,
3269
+ subscriptionId: reservation.row.id,
3270
+ url: reservation.url,
3271
+ redirect: true,
2392
3272
  reused: true,
2393
- status: reuseCandidate.status,
2394
- plan: reuseCandidate.plan
3273
+ status: reservation.row.status,
3274
+ plan: reservation.row.plan
2395
3275
  });
2396
3276
  }
2397
- const ensureCtx = { context: ctx.context };
2398
- const { consumerId } = await ensureConsumerForUser(options, ensureCtx, user);
3277
+ const { row, consumerId } = reservation;
2399
3278
  const linkInput = {
2400
3279
  name: `Subscription \u2014 ${plan.name}`,
3280
+ currency: plan.currency ?? "SAR",
2401
3281
  items: [{ product_id: plan.productId, quantity: 1, allow_custom_quantity: false }],
2402
3282
  max_number_of_payments: 1,
2403
3283
  organization_consumer_id: consumerId,
2404
3284
  custom_metadata: {
2405
3285
  [PLAN_NAME_METADATA_KEY]: plan.name,
2406
- [REFERENCE_ID_METADATA_KEY]: referenceId
3286
+ [REFERENCE_ID_METADATA_KEY]: referenceId,
3287
+ [REFERENCE_TYPE_METADATA_KEY]: referenceType,
3288
+ [SUBSCRIPTION_ROW_ID_METADATA_KEY]: row.id
2407
3289
  }
2408
3290
  };
2409
3291
  if (ctx.body.successUrl) linkInput.success_redirect_url = ctx.body.successUrl;
2410
3292
  if (ctx.body.failureUrl) linkInput.failure_redirect_url = ctx.body.failureUrl;
3293
+ if (plan.trialPeriodDays !== void 0 && trialEligible) {
3294
+ linkInput.trial_period_days = plan.trialPeriodDays;
3295
+ }
2411
3296
  let url;
2412
3297
  let paymentLinkId;
2413
3298
  try {
@@ -2420,6 +3305,12 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
2420
3305
  paymentLinkId = link.id;
2421
3306
  url = client.getPaymentUrl(link);
2422
3307
  } catch (err) {
3308
+ await deleteReservedSubscription(
3309
+ adapter,
3310
+ row.id,
3311
+ getLogger(ctx),
3312
+ "createPaymentLink cleanup"
3313
+ );
2423
3314
  toAPIError(
2424
3315
  {
2425
3316
  logPrefix: `upgradeSubscription failed for plan=${plan.name} ref=${referenceId}:`,
@@ -2431,29 +3322,51 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
2431
3322
  }
2432
3323
  if (!url) {
2433
3324
  getLogger(ctx).error(`createPaymentLink returned link=${paymentLinkId} with no url.`);
3325
+ try {
3326
+ await adapter.update({
3327
+ model: SUBSCRIPTION_MODEL6,
3328
+ update: {
3329
+ streampayPaymentLinkId: paymentLinkId,
3330
+ status: "incomplete_expired",
3331
+ activeSlotKey: null,
3332
+ updatedAt: /* @__PURE__ */ new Date()
3333
+ },
3334
+ where: [{ field: "id", value: row.id }]
3335
+ });
3336
+ } catch (persistenceError) {
3337
+ const message = persistenceError instanceof Error ? persistenceError.message : String(persistenceError);
3338
+ getLogger(ctx).error(
3339
+ `failed to mark unusable payment link=${paymentLinkId} expired for row=${row.id}: ${message}`
3340
+ );
3341
+ await deleteReservedSubscription(
3342
+ adapter,
3343
+ row.id,
3344
+ getLogger(ctx),
3345
+ "unusable payment link cleanup"
3346
+ );
3347
+ }
2434
3348
  throw new api.APIError("INTERNAL_SERVER_ERROR", {
2435
3349
  message: "Payment link was created but no URL was returned."
2436
3350
  });
2437
3351
  }
2438
- const row = await adapter.create({
2439
- model: SUBSCRIPTION_MODEL2,
2440
- data: {
2441
- referenceId,
2442
- plan: plan.name,
2443
- group: plan.group ?? null,
2444
- streampayConsumerId: consumerId,
2445
- status: "incomplete",
2446
- amountHalalat: plan.priceHalalat,
2447
- currency: "SAR",
2448
- billingInterval: plan.billingInterval,
2449
- billingIntervalCount: plan.billingIntervalCount ?? 1,
2450
- cancelAtPeriodEnd: false,
2451
- createdAt: /* @__PURE__ */ new Date(),
2452
- updatedAt: /* @__PURE__ */ new Date()
2453
- }
2454
- });
3352
+ let updatedRow = null;
3353
+ try {
3354
+ updatedRow = await adapter.update({
3355
+ model: SUBSCRIPTION_MODEL6,
3356
+ update: {
3357
+ streampayPaymentLinkId: paymentLinkId,
3358
+ updatedAt: /* @__PURE__ */ new Date()
3359
+ },
3360
+ where: [{ field: "id", value: row.id }]
3361
+ });
3362
+ } catch (persistenceError) {
3363
+ const message = persistenceError instanceof Error ? persistenceError.message : String(persistenceError);
3364
+ getLogger(ctx).error(
3365
+ `failed to persist payment link=${paymentLinkId} for row=${row.id}: ${message}. Protected checkout metadata will reconcile the row from the webhook.`
3366
+ );
3367
+ }
2455
3368
  return ctx.json({
2456
- subscriptionId: row.id,
3369
+ subscriptionId: updatedRow?.id ?? row.id,
2457
3370
  url,
2458
3371
  redirect: true,
2459
3372
  reused: false,
@@ -2473,16 +3386,23 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
2473
3386
  const user = requireUser(ctx);
2474
3387
  const adapter = getAdapter2(ctx);
2475
3388
  const row = await adapter.findOne({
2476
- model: SUBSCRIPTION_MODEL2,
3389
+ model: SUBSCRIPTION_MODEL6,
2477
3390
  where: [{ field: "id", value: ctx.query.subscriptionId }]
2478
3391
  });
2479
3392
  if (!row) {
2480
3393
  throw new api.APIError("NOT_FOUND", {
2481
- code: "SUBSCRIPTION_NOT_FOUND",
3394
+ code: $ERROR_CODES.SUBSCRIPTION_NOT_FOUND.code,
2482
3395
  message: "Subscription not found."
2483
3396
  });
2484
3397
  }
2485
- await authorizeReference(ctx, user, row.referenceId, "read", subsOptions);
3398
+ await authorizeReference(
3399
+ ctx,
3400
+ user,
3401
+ row.referenceId,
3402
+ row.referenceType ?? "user",
3403
+ "read",
3404
+ subsOptions
3405
+ );
2486
3406
  if (row.status !== "incomplete") {
2487
3407
  return ctx.json({
2488
3408
  subscription: row,
@@ -2493,31 +3413,39 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
2493
3413
  return ctx.json({ subscription: row, synced: false });
2494
3414
  }
2495
3415
  try {
2496
- const list = await client.listSubscriptions({ page: 1, size: 100 });
2497
- const match = list.data?.find(
2498
- (sub) => sub.organization_consumer_id === row.streampayConsumerId && Array.isArray(sub.items) && sub.items.some((item) => {
2499
- const productId = typeof item === "object" && item && "product" in item && item.product && typeof item.product === "object" && "id" in item.product ? item.product.id : typeof item === "object" && item && "product_id" in item ? item.product_id : null;
2500
- return typeof productId === "string" && productId.length > 0 && row.plan && sub.status !== "CANCELED";
2501
- })
2502
- );
3416
+ const plans = await plansRef();
3417
+ const plan = plans.byName.get(row.plan);
3418
+ if (!plan) {
3419
+ getLogger(ctx).warn(
3420
+ `subscriptionSuccess: plan "${row.plan}" is no longer configured \u2014 skipping fallback sync for row=${row.id}.`
3421
+ );
3422
+ return ctx.json({ subscription: row, synced: false });
3423
+ }
3424
+ let page = 1;
3425
+ let match;
3426
+ do {
3427
+ const list = await client.listSubscriptions({
3428
+ page,
3429
+ size: 100,
3430
+ organization_consumer_id: row.streampayConsumerId
3431
+ });
3432
+ match = list.data?.find(
3433
+ (sub) => isCheckoutSubscriptionCandidate(sub, row, plan.productId)
3434
+ );
3435
+ if (match || !list.pagination?.has_next_page) break;
3436
+ page += 1;
3437
+ } while (page <= 1e3);
2503
3438
  if (!match?.id) {
2504
3439
  return ctx.json({ subscription: row, synced: false });
2505
3440
  }
2506
3441
  const updated = await adapter.update({
2507
- model: SUBSCRIPTION_MODEL2,
3442
+ model: SUBSCRIPTION_MODEL6,
2508
3443
  update: {
2509
- streampaySubscriptionId: match.id,
2510
- status: match.status === "ACTIVE" ? "active" : "incomplete",
2511
- periodStart: match.current_period_start ? new Date(match.current_period_start) : null,
2512
- periodEnd: match.current_period_end ? new Date(match.current_period_end) : null,
2513
- amountHalalat: (() => {
2514
- if (!match.amount) return row.amountHalalat;
2515
- try {
2516
- return StreamPayAmount.toHalalat(match.amount);
2517
- } catch {
2518
- return row.amountHalalat;
2519
- }
2520
- })(),
3444
+ ...projectSubscriptionFields(match),
3445
+ planVersion: plan.version ?? null,
3446
+ productId: plan.productId,
3447
+ billingStatus: "current",
3448
+ activeSlotKey: row.activeSlotKey ?? subscriptionSlotKey(row.referenceType ?? "user", row.referenceId, row.group),
2521
3449
  updatedAt: /* @__PURE__ */ new Date()
2522
3450
  },
2523
3451
  where: [{ field: "id", value: row.id }]
@@ -2540,72 +3468,53 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
2540
3468
  use: [api.sessionMiddleware]
2541
3469
  },
2542
3470
  async (ctx) => {
2543
- const user = requireUser(ctx);
2544
- const adapter = getAdapter2(ctx);
2545
- const row = await findOwnedSubscription(
3471
+ const { adapter, row } = await requireConfirmedOwnedSubscription(
2546
3472
  ctx,
2547
- user,
2548
3473
  ctx.body.subscriptionId,
2549
3474
  subsOptions,
2550
3475
  "cancel"
2551
3476
  );
2552
- if (row.status === "canceled") {
2553
- throw new api.APIError("BAD_REQUEST", {
2554
- code: "SUBSCRIPTION_ALREADY_CANCELED",
2555
- message: "Subscription is already canceled."
2556
- });
2557
- }
2558
- if (row.cancelAtPeriodEnd) {
2559
- throw new api.APIError("BAD_REQUEST", {
2560
- code: "SUBSCRIPTION_ALREADY_SCHEDULED_CANCEL",
2561
- message: "Subscription is already scheduled to cancel at period end."
2562
- });
2563
- }
2564
- if (!row.streampaySubscriptionId) {
2565
- throw new api.APIError("BAD_REQUEST", {
2566
- code: "SUBSCRIPTION_INVALID_STATE",
2567
- message: "Subscription has not been confirmed by StreamPay yet."
2568
- });
2569
- }
2570
- if (ctx.body.cancelAtPeriodEnd) {
2571
- try {
2572
- const stream = await client.getSubscription(row.streampaySubscriptionId);
2573
- const patch = {
2574
- ...echoSubscriptionPatch(stream),
2575
- until_cycle_number: stream.current_cycle_number ?? 1
2576
- };
2577
- const result = await client.updateSubscription(row.streampaySubscriptionId, patch);
2578
- await adapter.update({
2579
- model: SUBSCRIPTION_MODEL2,
2580
- update: {
2581
- cancelAtPeriodEnd: true,
2582
- updatedAt: /* @__PURE__ */ new Date()
2583
- },
2584
- where: [{ field: "id", value: row.id }]
2585
- });
2586
- return ctx.json(result);
2587
- } catch (err) {
2588
- toAPIError(
2589
- {
2590
- logPrefix: `cancelAtPeriodEnd failed for row=${row.id}:`,
2591
- userMessage: "Subscription cancel-at-period-end failed."
2592
- },
2593
- err,
2594
- getLogger(ctx)
2595
- );
2596
- }
2597
- }
2598
3477
  const payload = {
2599
3478
  cancel_related_invoices: ctx.body.cancelRelatedInvoices ?? false
2600
3479
  };
2601
3480
  try {
3481
+ const stream = await client.getSubscription(row.streampaySubscriptionId);
3482
+ if (stream.status === "CANCELED") {
3483
+ await adapter.update({
3484
+ model: SUBSCRIPTION_MODEL6,
3485
+ update: projectSubscriptionAgainstExisting(row, stream),
3486
+ where: [{ field: "id", value: row.id }]
3487
+ });
3488
+ return ctx.json(stream);
3489
+ }
3490
+ if (ctx.body.cancelAtPeriodEnd === false && stream.status === "ACTIVE") {
3491
+ throw new api.APIError("BAD_REQUEST", {
3492
+ code: $ERROR_CODES.SUBSCRIPTION_IMMEDIATE_CANCEL_UNSUPPORTED.code,
3493
+ message: "StreamPay cancels active subscriptions at period end. Immediate cancellation is only available for inactive or trial subscriptions."
3494
+ });
3495
+ }
3496
+ if (stream.cancel_at_period_end && !ctx.body.cancelRelatedInvoices) {
3497
+ await adapter.update({
3498
+ model: SUBSCRIPTION_MODEL6,
3499
+ update: projectSubscriptionAgainstExisting(row, stream),
3500
+ where: [{ field: "id", value: row.id }]
3501
+ });
3502
+ return ctx.json(stream);
3503
+ }
3504
+ if (ctx.body.cancelAtPeriodEnd === true && stream.status !== "ACTIVE") {
3505
+ throw new api.APIError("BAD_REQUEST", {
3506
+ code: $ERROR_CODES.SUBSCRIPTION_PERIOD_END_CANCEL_UNSUPPORTED.code,
3507
+ message: "StreamPay only schedules period-end cancellation for active subscriptions. This subscription would be canceled immediately."
3508
+ });
3509
+ }
2602
3510
  const result = await client.cancelSubscription(row.streampaySubscriptionId, payload);
2603
3511
  await syncSubscriptionFromUpstream(
2604
3512
  client,
2605
3513
  adapter,
2606
3514
  row.streampaySubscriptionId,
2607
3515
  getLogger(ctx),
2608
- "cancelSubscription"
3516
+ "cancelSubscription",
3517
+ result
2609
3518
  );
2610
3519
  return ctx.json(result);
2611
3520
  } catch (err) {
@@ -2628,150 +3537,102 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
2628
3537
  use: [api.sessionMiddleware]
2629
3538
  },
2630
3539
  async (ctx) => {
2631
- const user = requireUser(ctx);
2632
- const adapter = getAdapter2(ctx);
3540
+ const { adapter, row } = await requireConfirmedOwnedSubscription(
3541
+ ctx,
3542
+ ctx.body.subscriptionId,
3543
+ subsOptions,
3544
+ "change-plan"
3545
+ );
2633
3546
  const plans = await plansRef();
2634
3547
  const nextPlan = plans.byName.get(ctx.body.plan);
2635
3548
  if (!nextPlan) {
2636
3549
  throw new api.APIError("NOT_FOUND", {
2637
- code: "SUBSCRIPTION_PLAN_NOT_FOUND",
3550
+ code: $ERROR_CODES.SUBSCRIPTION_PLAN_NOT_FOUND.code,
2638
3551
  message: `Plan "${ctx.body.plan}" is not configured.`
2639
3552
  });
2640
3553
  }
2641
- const existing = await adapter.findMany({
2642
- model: SUBSCRIPTION_MODEL2,
2643
- where: [
2644
- { field: "referenceId", value: user.id },
2645
- ...nextPlan.group ? [{ field: "group", value: nextPlan.group }] : []
2646
- ]
2647
- });
2648
- const row = existing.find(
2649
- (r) => r.status === "active" || r.status === "frozen" || r.status === "past_due"
2650
- );
2651
- if (!row) {
2652
- throw new api.APIError("NOT_FOUND", {
2653
- code: "SUBSCRIPTION_NOT_FOUND",
2654
- message: "No active subscription to change plan from."
2655
- });
2656
- }
2657
- await authorizeReference(ctx, user, row.referenceId, "change-plan", subsOptions);
2658
- if (!row.streampaySubscriptionId) {
2659
- throw new api.APIError("BAD_REQUEST", {
2660
- code: "SUBSCRIPTION_INVALID_STATE",
2661
- message: "Subscription has not been confirmed by StreamPay yet."
2662
- });
2663
- }
2664
- if (row.plan === nextPlan.name) {
2665
- throw new api.APIError("BAD_REQUEST", {
2666
- code: "SUBSCRIPTION_ALREADY_ON_PLAN",
2667
- message: `Already on plan "${nextPlan.name}".`
2668
- });
2669
- }
2670
- const mode = ctx.body.mode ?? "at_period_end";
2671
- if (mode === "immediate") {
2672
- try {
2673
- const stream = await client.getSubscription(row.streampaySubscriptionId);
2674
- const existingCoupons = [];
2675
- for (const c of stream.coupon_calculation_metadata?.coupons ?? []) {
2676
- if (c.coupon_id) existingCoupons.push(c.coupon_id);
2677
- }
2678
- const patch = {
2679
- items: [{ product_id: nextPlan.productId, quantity: 1 }],
2680
- coupons: existingCoupons
2681
- };
2682
- const result = await client.updateSubscription(row.streampaySubscriptionId, patch);
3554
+ try {
3555
+ const stream = await client.getSubscription(row.streampaySubscriptionId);
3556
+ const currentPlan = configuredPlanForSubscription(stream, plans);
3557
+ const currentGroup = currentPlan?.group ?? row.group;
3558
+ if (currentGroup !== (nextPlan.group ?? null)) {
3559
+ throw new api.APIError("BAD_REQUEST", {
3560
+ code: $ERROR_CODES.SUBSCRIPTION_PLAN_GROUP_MISMATCH.code,
3561
+ message: "A subscription can only change to another plan in the same configured group."
3562
+ });
3563
+ }
3564
+ if (stream.cancel_at_period_end) {
3565
+ throw new api.APIError("CONFLICT", {
3566
+ code: $ERROR_CODES.SUBSCRIPTION_ALREADY_SCHEDULED_CANCEL.code,
3567
+ message: "The subscription is scheduled to cancel. Uncancel it before scheduling a plan change."
3568
+ });
3569
+ }
3570
+ const currentProductIsRequestedPlan = stream.items?.some(
3571
+ (item) => subscriptionItemProductId(item) === nextPlan.productId
3572
+ );
3573
+ if (currentProductIsRequestedPlan && !stream.pending_change) {
3574
+ throw new api.APIError("BAD_REQUEST", {
3575
+ code: $ERROR_CODES.SUBSCRIPTION_ALREADY_ON_PLAN.code,
3576
+ message: `Already on plan "${nextPlan.name}".`
3577
+ });
3578
+ }
3579
+ const pendingTargets = stream.pending_change?.target_items ?? [];
3580
+ const pendingTargetIsRequestedPlan = pendingTargets.some(
3581
+ (item) => subscriptionItemProductId(item) === nextPlan.productId
3582
+ );
3583
+ if (pendingTargetIsRequestedPlan) {
2683
3584
  await adapter.update({
2684
- model: SUBSCRIPTION_MODEL2,
3585
+ model: SUBSCRIPTION_MODEL6,
2685
3586
  update: {
2686
- plan: nextPlan.name,
2687
- group: nextPlan.group ?? null,
2688
- updatedAt: /* @__PURE__ */ new Date()
3587
+ ...projectSubscriptionAgainstExisting(row, stream),
3588
+ pendingPlan: nextPlan.name,
3589
+ pendingProductId: nextPlan.productId,
3590
+ pendingPlanEffectiveAt: stream.pending_change?.effective_at ? new Date(stream.pending_change.effective_at) : null
2689
3591
  },
2690
3592
  where: [{ field: "id", value: row.id }]
2691
3593
  });
2692
- await syncSubscriptionFromUpstream(
2693
- client,
2694
- adapter,
2695
- row.streampaySubscriptionId,
2696
- getLogger(ctx),
2697
- "changeSubscriptionPlan"
2698
- );
2699
3594
  return ctx.json({
2700
- mode: "immediate",
2701
- subscription: result,
2702
- plan: nextPlan.name
3595
+ mode: "at_period_end",
3596
+ subscriptionId: row.id,
3597
+ plan: nextPlan.name,
3598
+ effectiveAt: stream.pending_change?.effective_at ?? null,
3599
+ pendingChange: stream.pending_change,
3600
+ reused: true
3601
+ });
3602
+ }
3603
+ if (stream.pending_change) {
3604
+ throw new api.APIError("CONFLICT", {
3605
+ code: $ERROR_CODES.SUBSCRIPTION_PLAN_CHANGE_ALREADY_SCHEDULED.code,
3606
+ message: "A different plan change is already scheduled. Cancel it before scheduling another."
2703
3607
  });
2704
- } catch (err) {
2705
- toAPIError(
2706
- {
2707
- logPrefix: `change-plan (immediate) failed for row=${row.id}:`,
2708
- userMessage: "Plan change failed."
2709
- },
2710
- err,
2711
- getLogger(ctx)
2712
- );
2713
3608
  }
2714
- }
2715
- try {
2716
- const stream = await client.getSubscription(row.streampaySubscriptionId);
2717
3609
  const patch = {
2718
- ...echoSubscriptionPatch(stream),
2719
- until_cycle_number: stream.current_cycle_number ?? 1
3610
+ items: [{ product_id: nextPlan.productId, quantity: 1 }],
3611
+ coupons: subscriptionCouponIds(stream),
3612
+ recurring_interval: nextPlan.billingInterval,
3613
+ recurring_interval_count: nextPlan.billingIntervalCount ?? 1
2720
3614
  };
2721
- await client.updateSubscription(row.streampaySubscriptionId, patch);
3615
+ const result = await client.updateSubscription(row.streampaySubscriptionId, patch);
3616
+ const effectiveAt = result.pending_change?.effective_at ?? result.current_period_end ?? null;
2722
3617
  await adapter.update({
2723
- model: SUBSCRIPTION_MODEL2,
3618
+ model: SUBSCRIPTION_MODEL6,
2724
3619
  update: {
2725
- cancelAtPeriodEnd: true,
3620
+ ...projectSubscriptionAgainstExisting(row, result),
3621
+ pendingPlan: nextPlan.name,
3622
+ pendingProductId: nextPlan.productId,
3623
+ pendingPlanEffectiveAt: effectiveAt ? new Date(effectiveAt) : null,
2726
3624
  updatedAt: /* @__PURE__ */ new Date()
2727
3625
  },
2728
3626
  where: [{ field: "id", value: row.id }]
2729
3627
  });
2730
- const ensureCtx = { context: ctx.context };
2731
- const { consumerId } = await ensureConsumerForUser(options, ensureCtx, user);
2732
- const linkInput = {
2733
- name: `Plan change \u2014 ${nextPlan.name}`,
2734
- items: [
2735
- {
2736
- product_id: nextPlan.productId,
2737
- quantity: 1,
2738
- allow_custom_quantity: false
2739
- }
2740
- ],
2741
- max_number_of_payments: 1,
2742
- organization_consumer_id: consumerId,
2743
- custom_metadata: {
2744
- [PLAN_NAME_METADATA_KEY]: nextPlan.name,
2745
- [REFERENCE_ID_METADATA_KEY]: user.id
2746
- }
2747
- };
2748
- if (ctx.body.successUrl) linkInput.success_redirect_url = ctx.body.successUrl;
2749
- if (ctx.body.failureUrl) linkInput.failure_redirect_url = ctx.body.failureUrl;
2750
- const link = await client.createPaymentLink(linkInput);
2751
- const url = client.getPaymentUrl(link);
2752
- const nextRow = await adapter.create({
2753
- model: SUBSCRIPTION_MODEL2,
2754
- data: {
2755
- referenceId: user.id,
2756
- plan: nextPlan.name,
2757
- group: nextPlan.group ?? null,
2758
- streampayConsumerId: consumerId,
2759
- status: "incomplete",
2760
- amountHalalat: nextPlan.priceHalalat,
2761
- currency: "SAR",
2762
- billingInterval: nextPlan.billingInterval,
2763
- billingIntervalCount: nextPlan.billingIntervalCount ?? 1,
2764
- cancelAtPeriodEnd: false,
2765
- createdAt: /* @__PURE__ */ new Date(),
2766
- updatedAt: /* @__PURE__ */ new Date()
2767
- }
2768
- });
2769
3628
  return ctx.json({
2770
3629
  mode: "at_period_end",
2771
- currentSubscriptionId: row.id,
2772
- nextSubscriptionId: nextRow.id,
2773
- url,
2774
- plan: nextPlan.name
3630
+ subscriptionId: row.id,
3631
+ plan: nextPlan.name,
3632
+ effectiveAt,
3633
+ pendingChange: result.pending_change ?? null,
3634
+ subscription: result,
3635
+ reused: false
2775
3636
  });
2776
3637
  } catch (err) {
2777
3638
  toAPIError(
@@ -2785,35 +3646,95 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
2785
3646
  }
2786
3647
  }
2787
3648
  ),
2788
- freezeSubscription: api.createAuthEndpoint(
2789
- "/subscription/freeze",
3649
+ cancelSubscriptionPlanChange: api.createAuthEndpoint(
3650
+ "/subscription/change-plan/cancel",
2790
3651
  {
2791
3652
  method: "POST",
2792
- body: FreezeBody,
3653
+ body: UnfreezeBody,
2793
3654
  use: [api.sessionMiddleware]
2794
3655
  },
2795
3656
  async (ctx) => {
2796
- const user = requireUser(ctx);
2797
- const adapter = getAdapter2(ctx);
2798
- const row = await findOwnedSubscription(
3657
+ const { adapter, row } = await requireConfirmedOwnedSubscription(
2799
3658
  ctx,
2800
- user,
2801
3659
  ctx.body.subscriptionId,
2802
3660
  subsOptions,
2803
- "freeze"
3661
+ "cancel-plan-change"
2804
3662
  );
2805
- if (row.status !== "active") {
2806
- throw new api.APIError("BAD_REQUEST", {
2807
- code: "SUBSCRIPTION_INVALID_STATE",
2808
- message: "Only active subscriptions can be frozen."
3663
+ try {
3664
+ await client.deletePendingSubscriptionChange(row.streampaySubscriptionId);
3665
+ const stream = await client.getSubscription(row.streampaySubscriptionId);
3666
+ await adapter.update({
3667
+ model: SUBSCRIPTION_MODEL6,
3668
+ update: {
3669
+ ...projectSubscriptionAgainstExisting(row, stream),
3670
+ pendingPlan: null,
3671
+ pendingProductId: null,
3672
+ pendingPlanEffectiveAt: null
3673
+ },
3674
+ where: [{ field: "id", value: row.id }]
2809
3675
  });
3676
+ return ctx.json({ canceled: true, subscription: stream });
3677
+ } catch (err) {
3678
+ toAPIError(
3679
+ {
3680
+ logPrefix: `cancel plan change failed for row=${row.id}:`,
3681
+ userMessage: "Canceling the scheduled plan change failed."
3682
+ },
3683
+ err,
3684
+ getLogger(ctx)
3685
+ );
2810
3686
  }
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."
3687
+ }
3688
+ ),
3689
+ uncancelSubscription: api.createAuthEndpoint(
3690
+ "/subscription/uncancel",
3691
+ {
3692
+ method: "POST",
3693
+ body: UnfreezeBody,
3694
+ use: [api.sessionMiddleware]
3695
+ },
3696
+ async (ctx) => {
3697
+ const { adapter, row } = await requireConfirmedOwnedSubscription(
3698
+ ctx,
3699
+ ctx.body.subscriptionId,
3700
+ subsOptions,
3701
+ "uncancel"
3702
+ );
3703
+ try {
3704
+ await client.uncancelSubscription(row.streampaySubscriptionId);
3705
+ const stream = await client.getSubscription(row.streampaySubscriptionId);
3706
+ await adapter.update({
3707
+ model: SUBSCRIPTION_MODEL6,
3708
+ update: projectSubscriptionAgainstExisting(row, stream),
3709
+ where: [{ field: "id", value: row.id }]
2815
3710
  });
3711
+ return ctx.json({ uncanceled: true, subscription: stream });
3712
+ } catch (err) {
3713
+ toAPIError(
3714
+ {
3715
+ logPrefix: `uncancel subscription failed for row=${row.id}:`,
3716
+ userMessage: "Restoring subscription renewal failed."
3717
+ },
3718
+ err,
3719
+ getLogger(ctx)
3720
+ );
2816
3721
  }
3722
+ }
3723
+ ),
3724
+ freezeSubscription: api.createAuthEndpoint(
3725
+ "/subscription/freeze",
3726
+ {
3727
+ method: "POST",
3728
+ body: FreezeBody,
3729
+ use: [api.sessionMiddleware]
3730
+ },
3731
+ async (ctx) => {
3732
+ const { adapter, row } = await requireConfirmedOwnedSubscription(
3733
+ ctx,
3734
+ ctx.body.subscriptionId,
3735
+ subsOptions,
3736
+ "freeze"
3737
+ );
2817
3738
  const payload = {
2818
3739
  freeze_start_datetime: ctx.body.freezeStartDatetime
2819
3740
  };
@@ -2853,27 +3774,12 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
2853
3774
  use: [api.sessionMiddleware]
2854
3775
  },
2855
3776
  async (ctx) => {
2856
- const user = requireUser(ctx);
2857
- const adapter = getAdapter2(ctx);
2858
- const row = await findOwnedSubscription(
3777
+ const { adapter, row } = await requireConfirmedOwnedSubscription(
2859
3778
  ctx,
2860
- user,
2861
3779
  ctx.body.subscriptionId,
2862
3780
  subsOptions,
2863
3781
  "unfreeze"
2864
3782
  );
2865
- if (row.status !== "frozen") {
2866
- throw new api.APIError("BAD_REQUEST", {
2867
- code: "SUBSCRIPTION_NOT_FROZEN",
2868
- message: "Subscription is not currently frozen."
2869
- });
2870
- }
2871
- if (!row.streampaySubscriptionId) {
2872
- throw new api.APIError("BAD_REQUEST", {
2873
- code: "SUBSCRIPTION_INVALID_STATE",
2874
- message: "Subscription has not been confirmed by StreamPay yet."
2875
- });
2876
- }
2877
3783
  const nowMs = Date.now();
2878
3784
  try {
2879
3785
  const freezes = await client.listSubscriptionFreezes(row.streampaySubscriptionId);
@@ -2885,147 +3791,79 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
2885
3791
  });
2886
3792
  if (!active?.id || !active.freeze_start_datetime) {
2887
3793
  throw new api.APIError("BAD_REQUEST", {
2888
- code: "SUBSCRIPTION_NOT_FROZEN",
3794
+ code: $ERROR_CODES.SUBSCRIPTION_FREEZE_NOT_ACTIVE.code,
2889
3795
  message: "No active freeze period found to cancel."
2890
- });
2891
- }
2892
- await client.updateSubscriptionFreeze(row.streampaySubscriptionId, active.id, {
2893
- freeze_start_datetime: active.freeze_start_datetime,
2894
- freeze_end_datetime: new Date(nowMs).toISOString(),
2895
- notes: active.notes ?? null
2896
- });
2897
- await syncSubscriptionFromUpstream(
2898
- client,
2899
- adapter,
2900
- row.streampaySubscriptionId,
2901
- getLogger(ctx),
2902
- "unfreezeSubscription"
2903
- );
2904
- return ctx.json({ unfrozen: true });
2905
- } catch (err) {
2906
- toAPIError(
2907
- {
2908
- logPrefix: `unfreezeSubscription failed for row=${row.id}:`,
2909
- userMessage: "Subscription unfreeze failed."
2910
- },
2911
- err,
2912
- getLogger(ctx)
2913
- );
2914
- }
2915
- }
2916
- ),
2917
- listSubscriptions: api.createAuthEndpoint(
2918
- "/subscription/list",
2919
- {
2920
- method: "GET",
2921
- use: [api.sessionMiddleware]
2922
- },
2923
- async (ctx) => {
2924
- const user = requireUser(ctx);
2925
- const adapter = getAdapter2(ctx);
2926
- const rows = await adapter.findMany({
2927
- model: SUBSCRIPTION_MODEL2,
2928
- where: [{ field: "referenceId", value: user.id }]
2929
- });
2930
- const plans = await plansRef();
2931
- return ctx.json(
2932
- rows.map((row) => ({
2933
- ...row,
2934
- plan: plans.byName.get(row.plan) ?? null
2935
- }))
2936
- );
2937
- }
2938
- ),
2939
- /**
2940
- * Returns the user's current billable subscription, or `null` if
2941
- * none. **Intentionally filters out `incomplete`, `canceled`,
2942
- * `expired`, and `inactive` rows** — only `active | frozen |
2943
- * past_due` are surfaced, since those are the statuses that
2944
- * represent a *live* entitlement.
2945
- *
2946
- * Notable consequence: between `/subscription/upgrade` (creates
2947
- * an `incomplete` row + payment link) and the
2948
- * `SUBSCRIPTION_ACTIVATED` webhook landing, this endpoint
2949
- * returns `null`. If you want to render "your subscription is
2950
- * being activated" during that window, call `/subscription/list`
2951
- * and filter for `status === "incomplete"` yourself.
2952
- *
2953
- * Pass `?group=<name>` to scope to a single plan group when the
2954
- * app declares multiple concurrent subscriptions per user.
2955
- */
2956
- currentSubscription: api.createAuthEndpoint(
2957
- "/subscription/current",
2958
- {
2959
- method: "GET",
2960
- query: CurrentQuery,
2961
- use: [api.sessionMiddleware]
2962
- },
2963
- async (ctx) => {
2964
- const user = requireUser(ctx);
2965
- const adapter = getAdapter2(ctx);
2966
- const where = [
2967
- { field: "referenceId", value: user.id }
2968
- ];
2969
- if (ctx.query?.group) {
2970
- where.push({ field: "group", value: ctx.query.group });
2971
- }
2972
- const rows = await adapter.findMany({
2973
- model: SUBSCRIPTION_MODEL2,
2974
- where
2975
- });
2976
- const live = rows.find(
2977
- (row) => row.status === "active" || row.status === "frozen" || row.status === "past_due"
2978
- );
2979
- if (!live) return ctx.json(null);
2980
- const plans = await plansRef();
2981
- return ctx.json({
2982
- ...live,
2983
- plan: plans.byName.get(live.plan) ?? null
2984
- });
2985
- }
2986
- ),
2987
- hasSubscriptionFeature: api.createAuthEndpoint(
2988
- "/subscription/has-feature",
2989
- {
2990
- method: "GET",
2991
- query: HasFeatureQuery,
2992
- use: [api.sessionMiddleware]
2993
- },
2994
- async (ctx) => {
2995
- const user = requireUser(ctx);
2996
- const adapter = getAdapter2(ctx);
2997
- const where = [
2998
- { field: "referenceId", value: user.id }
2999
- ];
3000
- if (ctx.query.group) where.push({ field: "group", value: ctx.query.group });
3001
- const rows = await adapter.findMany({ model: SUBSCRIPTION_MODEL2, where });
3002
- const plans = await plansRef();
3003
- const live = rows.find((row) => row.status === "active" || row.status === "frozen");
3004
- if (!live) return ctx.json({ hasFeature: false });
3005
- const plan = plans.byName.get(live.plan);
3006
- return ctx.json({ hasFeature: hasFeature(live, plan, ctx.query.feature) });
3796
+ });
3797
+ }
3798
+ await client.updateSubscriptionFreeze(row.streampaySubscriptionId, active.id, {
3799
+ freeze_start_datetime: active.freeze_start_datetime,
3800
+ freeze_end_datetime: new Date(nowMs).toISOString(),
3801
+ notes: active.notes ?? null
3802
+ });
3803
+ await syncSubscriptionFromUpstream(
3804
+ client,
3805
+ adapter,
3806
+ row.streampaySubscriptionId,
3807
+ getLogger(ctx),
3808
+ "unfreezeSubscription"
3809
+ );
3810
+ return ctx.json({ unfrozen: true });
3811
+ } catch (err) {
3812
+ toAPIError(
3813
+ {
3814
+ logPrefix: `unfreezeSubscription failed for row=${row.id}:`,
3815
+ userMessage: "Subscription unfreeze failed."
3816
+ },
3817
+ err,
3818
+ getLogger(ctx)
3819
+ );
3820
+ }
3007
3821
  }
3008
3822
  ),
3009
- checkSubscriptionLimit: api.createAuthEndpoint(
3010
- "/subscription/check-limit",
3823
+ cancelSubscriptionFreeze: api.createAuthEndpoint(
3824
+ "/subscription/freeze/cancel",
3011
3825
  {
3012
- method: "GET",
3013
- query: CheckLimitQuery,
3826
+ method: "POST",
3827
+ body: CancelFreezeBody,
3014
3828
  use: [api.sessionMiddleware]
3015
3829
  },
3016
3830
  async (ctx) => {
3017
- const user = requireUser(ctx);
3018
- const adapter = getAdapter2(ctx);
3019
- const where = [
3020
- { field: "referenceId", value: user.id }
3021
- ];
3022
- if (ctx.query.group) where.push({ field: "group", value: ctx.query.group });
3023
- const rows = await adapter.findMany({ model: SUBSCRIPTION_MODEL2, where });
3024
- const plans = await plansRef();
3025
- const live = rows.find((row) => row.status === "active" || row.status === "frozen");
3026
- if (!live) return ctx.json({ allowed: false, limit: 0, remaining: 0 });
3027
- const plan = plans.byName.get(live.plan);
3028
- return ctx.json(checkLimit(live, plan, ctx.query.feature, ctx.query.count));
3831
+ const { adapter, row } = await requireConfirmedOwnedSubscription(
3832
+ ctx,
3833
+ ctx.body.subscriptionId,
3834
+ subsOptions,
3835
+ "cancel-freeze"
3836
+ );
3837
+ try {
3838
+ const freezes = await client.listSubscriptionFreezes(row.streampaySubscriptionId);
3839
+ if (!freezes.data?.some((freeze) => freeze.id === ctx.body.freezeId)) {
3840
+ return ctx.json({ canceled: true, freezeId: ctx.body.freezeId, reused: true });
3841
+ }
3842
+ await client.deleteSubscriptionFreeze(row.streampaySubscriptionId, ctx.body.freezeId);
3843
+ await syncSubscriptionFromUpstream(
3844
+ client,
3845
+ adapter,
3846
+ row.streampaySubscriptionId,
3847
+ getLogger(ctx),
3848
+ "cancelSubscriptionFreeze"
3849
+ );
3850
+ return ctx.json({ canceled: true, freezeId: ctx.body.freezeId, reused: false });
3851
+ } catch (err) {
3852
+ if (isAlreadyCanceledFreezeError(err)) {
3853
+ getLogger(ctx).info(
3854
+ `cancel subscription freeze reused provider tombstone for row=${row.id} freeze=${ctx.body.freezeId}.`
3855
+ );
3856
+ return ctx.json({ canceled: true, freezeId: ctx.body.freezeId, reused: true });
3857
+ }
3858
+ toAPIError(
3859
+ {
3860
+ logPrefix: `cancel subscription freeze failed for row=${row.id}:`,
3861
+ userMessage: "Canceling the subscription freeze failed."
3862
+ },
3863
+ err,
3864
+ getLogger(ctx)
3865
+ );
3866
+ }
3029
3867
  }
3030
3868
  )
3031
3869
  };
@@ -3038,6 +3876,19 @@ var subscriptionTable = {
3038
3876
  referenceId: {
3039
3877
  type: "string",
3040
3878
  required: true,
3879
+ input: false,
3880
+ index: true
3881
+ },
3882
+ referenceType: {
3883
+ type: "string",
3884
+ required: false,
3885
+ defaultValue: "user",
3886
+ input: false
3887
+ },
3888
+ activeSlotKey: {
3889
+ type: "string",
3890
+ required: false,
3891
+ unique: true,
3041
3892
  input: false
3042
3893
  },
3043
3894
  streampaySubscriptionId: {
@@ -3049,17 +3900,38 @@ var subscriptionTable = {
3049
3900
  streampayConsumerId: {
3050
3901
  type: "string",
3051
3902
  required: false,
3903
+ input: false,
3904
+ index: true
3905
+ },
3906
+ streampayPaymentLinkId: {
3907
+ type: "string",
3908
+ required: false,
3909
+ unique: true,
3052
3910
  input: false
3053
3911
  },
3054
3912
  plan: {
3055
3913
  type: "string",
3056
3914
  required: true
3057
3915
  },
3916
+ planVersion: {
3917
+ type: "string",
3918
+ required: false
3919
+ },
3920
+ productId: {
3921
+ type: "string",
3922
+ required: false,
3923
+ index: true
3924
+ },
3058
3925
  group: {
3059
3926
  type: "string",
3927
+ required: false,
3928
+ index: true
3929
+ },
3930
+ amountInSmallestUnit: {
3931
+ type: "number",
3060
3932
  required: false
3061
3933
  },
3062
- amountHalalat: {
3934
+ originalAmountInSmallestUnit: {
3063
3935
  type: "number",
3064
3936
  required: false
3065
3937
  },
@@ -3080,7 +3952,18 @@ var subscriptionTable = {
3080
3952
  status: {
3081
3953
  type: "string",
3082
3954
  required: false,
3083
- defaultValue: "incomplete"
3955
+ defaultValue: "incomplete",
3956
+ index: true
3957
+ },
3958
+ providerStatus: {
3959
+ type: "string",
3960
+ required: false
3961
+ },
3962
+ billingStatus: {
3963
+ type: "string",
3964
+ required: false,
3965
+ defaultValue: "current",
3966
+ index: true
3084
3967
  },
3085
3968
  periodStart: {
3086
3969
  type: "date",
@@ -3090,11 +3973,48 @@ var subscriptionTable = {
3090
3973
  type: "date",
3091
3974
  required: false
3092
3975
  },
3976
+ currentCycleNumber: {
3977
+ type: "number",
3978
+ required: false
3979
+ },
3980
+ trialStart: {
3981
+ type: "date",
3982
+ required: false
3983
+ },
3984
+ trialEnd: {
3985
+ type: "date",
3986
+ required: false
3987
+ },
3093
3988
  cancelAtPeriodEnd: {
3094
3989
  type: "boolean",
3095
3990
  required: false,
3096
3991
  defaultValue: false
3097
3992
  },
3993
+ cancelAt: {
3994
+ type: "date",
3995
+ required: false
3996
+ },
3997
+ cancelScheduledAt: {
3998
+ type: "date",
3999
+ required: false
4000
+ },
4001
+ canceledAt: {
4002
+ type: "date",
4003
+ required: false
4004
+ },
4005
+ pendingPlan: {
4006
+ type: "string",
4007
+ required: false
4008
+ },
4009
+ pendingProductId: {
4010
+ type: "string",
4011
+ required: false,
4012
+ index: true
4013
+ },
4014
+ pendingPlanEffectiveAt: {
4015
+ type: "date",
4016
+ required: false
4017
+ },
3098
4018
  endedAt: {
3099
4019
  type: "date",
3100
4020
  required: false
@@ -3106,6 +4026,26 @@ var subscriptionTable = {
3106
4026
  freezeEndAt: {
3107
4027
  type: "date",
3108
4028
  required: false
4029
+ },
4030
+ providerUpdatedAt: {
4031
+ type: "date",
4032
+ required: false
4033
+ },
4034
+ syncedAt: {
4035
+ type: "date",
4036
+ required: false,
4037
+ index: true
4038
+ },
4039
+ createdAt: {
4040
+ type: "date",
4041
+ required: false,
4042
+ input: false
4043
+ },
4044
+ updatedAt: {
4045
+ type: "date",
4046
+ required: false,
4047
+ input: false,
4048
+ index: true
3109
4049
  }
3110
4050
  }
3111
4051
  }
@@ -3122,18 +4062,44 @@ var webhookEventTable = {
3122
4062
  type: "string",
3123
4063
  required: true
3124
4064
  },
3125
- /** Last activity (insert/retry/completion/dead-letter).
3126
- * For `completed` = finished-at; for `pending` = last attempt. */
3127
- processedAt: {
4065
+ receivedAt: {
3128
4066
  type: "date",
3129
4067
  required: true,
3130
4068
  index: true
3131
4069
  },
3132
- /** Defaults to `completed` so pre-state-machine rows still dedupe. */
4070
+ lastAttemptAt: {
4071
+ type: "date",
4072
+ required: false,
4073
+ index: true
4074
+ },
4075
+ nextAttemptAt: {
4076
+ type: "date",
4077
+ required: false,
4078
+ index: true
4079
+ },
4080
+ completedAt: {
4081
+ type: "date",
4082
+ required: false,
4083
+ index: true
4084
+ },
4085
+ deadLetteredAt: {
4086
+ type: "date",
4087
+ required: false,
4088
+ index: true
4089
+ },
4090
+ lockedAt: {
4091
+ type: "date",
4092
+ required: false,
4093
+ index: true
4094
+ },
4095
+ lockedBy: {
4096
+ type: "string",
4097
+ required: false
4098
+ },
3133
4099
  status: {
3134
4100
  type: "string",
3135
4101
  required: false,
3136
- defaultValue: "completed",
4102
+ defaultValue: "pending",
3137
4103
  index: true
3138
4104
  },
3139
4105
  attemptCount: {
@@ -3141,10 +4107,6 @@ var webhookEventTable = {
3141
4107
  required: false,
3142
4108
  defaultValue: 1
3143
4109
  },
3144
- firstSeenAt: {
3145
- type: "date",
3146
- required: false
3147
- },
3148
4110
  rawPayload: {
3149
4111
  type: "string",
3150
4112
  required: false
@@ -3156,6 +4118,11 @@ var webhookEventTable = {
3156
4118
  lastError: {
3157
4119
  type: "string",
3158
4120
  required: false
4121
+ },
4122
+ lastErrorCode: {
4123
+ type: "string",
4124
+ required: false,
4125
+ index: true
3159
4126
  }
3160
4127
  }
3161
4128
  }
@@ -3172,17 +4139,18 @@ function subscriptions(subsOptions) {
3172
4139
  } else if (typeof subsOptions.plans !== "function") {
3173
4140
  throw new TypeError("subscriptions(): `plans` must be an array or an async factory function.");
3174
4141
  }
3175
- const flags = subsOptions;
3176
- if (flags.enableSubscriptionTable === false && flags.enableWebhookEventTable === true) {
3177
- throw new TypeError(
3178
- "subscriptions(): `enableWebhookEventTable: true` requires `enableSubscriptionTable: true` \u2014 the event lifecycle table is part of the subscription sync pipeline."
3179
- );
4142
+ if (subsOptions.maxWebhookAttempts !== void 0 && (!Number.isInteger(subsOptions.maxWebhookAttempts) || subsOptions.maxWebhookAttempts < 1)) {
4143
+ throw new TypeError("subscriptions(): `maxWebhookAttempts` must be a positive integer.");
4144
+ }
4145
+ for (const status of subsOptions.accessStatuses ?? []) {
4146
+ if (!SUBSCRIPTION_STATUSES.includes(status)) {
4147
+ throw new TypeError(`subscriptions(): invalid access status "${status}".`);
4148
+ }
3180
4149
  }
3181
- const tableEnabled = subsOptions.enableSubscriptionTable !== false;
3182
4150
  const dedupeEnabled = subsOptions.enableWebhookEventTable !== false;
3183
4151
  return (options, registry) => {
3184
4152
  const resolvePlans = createPlanResolver(subsOptions.plans);
3185
- if (registry && tableEnabled) {
4153
+ if (registry) {
3186
4154
  registry.subscriptionWebhookSync = async (ctx, payload, meta) => {
3187
4155
  const syncCtx = {
3188
4156
  context: ctx.context
@@ -3195,7 +4163,8 @@ function subscriptions(subsOptions) {
3195
4163
  signatureHeader: meta?.signatureHeader ?? null,
3196
4164
  ...subsOptions.maxWebhookAttempts !== void 0 && {
3197
4165
  maxAttempts: subsOptions.maxWebhookAttempts
3198
- }
4166
+ },
4167
+ retryOnCallbackError: subsOptions.retryOnCallbackError !== false
3199
4168
  });
3200
4169
  } catch (err) {
3201
4170
  if (classifyWebhookFailure(err) === "PERMANENT") {
@@ -3228,28 +4197,59 @@ function subscriptions(subsOptions) {
3228
4197
  message: `Webhook event ${eventId} has no rawPayload \u2014 nothing to replay (already completed cleanly?).`
3229
4198
  });
3230
4199
  }
3231
- const payload = JSON.parse(row.rawPayload);
4200
+ let parsedPayload;
4201
+ try {
4202
+ parsedPayload = JSON.parse(row.rawPayload);
4203
+ } catch {
4204
+ throw new api.APIError("BAD_REQUEST", {
4205
+ message: `Webhook event ${eventId} has malformed stored JSON.`
4206
+ });
4207
+ }
4208
+ if (!isStreamPayWebhookEnvelope(parsedPayload) || !isKnownStreamPayWebhookPayload(parsedPayload)) {
4209
+ throw new api.APIError("BAD_REQUEST", {
4210
+ message: `Webhook event ${eventId} has an invalid stored payload.`
4211
+ });
4212
+ }
4213
+ const payload = parsedPayload;
3232
4214
  const plans = await resolvePlans();
4215
+ const claimed = await claimWebhookEventForReplay(syncCtx, row);
4216
+ if (!claimed?.lockedBy) {
4217
+ throw new api.APIError("CONFLICT", {
4218
+ code: $ERROR_CODES.WEBHOOK_REPLAY_IN_PROGRESS.code,
4219
+ message: `Webhook event ${eventId} is already being replayed.`
4220
+ });
4221
+ }
3233
4222
  try {
3234
4223
  await syncWebhookPayload(syncCtx, payload, options.client, plans, subsOptions, {
3235
- dedupe: false
4224
+ dedupe: false,
4225
+ retryingRenewalCallback: claimed.lastError?.startsWith(
4226
+ "Subscription callback onSubscriptionRenewed failed:"
4227
+ ) === true
3236
4228
  });
3237
- await markWebhookEventCompleted(syncCtx, row.id);
4229
+ await markWebhookEventCompleted(syncCtx, claimed.id, claimed.lockedBy);
3238
4230
  return { replayed: true, eventId };
3239
4231
  } catch (err) {
3240
- await recordWebhookEventFailure(syncCtx, row.id, null, null, err);
4232
+ await recordWebhookEventFailure(
4233
+ syncCtx,
4234
+ claimed.id,
4235
+ null,
4236
+ null,
4237
+ err,
4238
+ claimed.lockedBy,
4239
+ true
4240
+ );
3241
4241
  throw err;
3242
4242
  }
3243
4243
  };
3244
4244
  }
3245
4245
  }
3246
4246
  const schema = {
3247
- ...tableEnabled ? subscriptionTable : {},
3248
- ...tableEnabled && dedupeEnabled ? webhookEventTable : {}
4247
+ ...subscriptionTable,
4248
+ ...dedupeEnabled ? webhookEventTable : {}
3249
4249
  };
3250
4250
  return {
3251
4251
  endpoints: buildSubscriptionEndpoints(options, subsOptions, resolvePlans),
3252
- ...Object.keys(schema).length > 0 ? { schema } : {}
4252
+ schema
3253
4253
  };
3254
4254
  };
3255
4255
  }
@@ -3257,8 +4257,8 @@ function subscriptions(subsOptions) {
3257
4257
  // src/webhooks/dispatcher.ts
3258
4258
  async function dispatchWebhook(payload, handlers) {
3259
4259
  if (handlers.onPayload) await handlers.onPayload(payload);
4260
+ if (!isKnownStreamPayWebhookPayload(payload)) return;
3260
4261
  switch (payload.event_type) {
3261
- // Payment
3262
4262
  case "PAYMENT_SUCCEEDED":
3263
4263
  await handlers.onPaymentSucceeded?.(payload);
3264
4264
  return;
@@ -3274,7 +4274,6 @@ async function dispatchWebhook(payload, handlers) {
3274
4274
  case "PAYMENT_MARKED_AS_PAID":
3275
4275
  await handlers.onPaymentMarkedAsPaid?.(payload);
3276
4276
  return;
3277
- // Invoice
3278
4277
  case "INVOICE_CREATED":
3279
4278
  await handlers.onInvoiceCreated?.(payload);
3280
4279
  return;
@@ -3296,7 +4295,6 @@ async function dispatchWebhook(payload, handlers) {
3296
4295
  case "INVOICE_UPDATED":
3297
4296
  await handlers.onInvoiceUpdated?.(payload);
3298
4297
  return;
3299
- // Subscription
3300
4298
  case "SUBSCRIPTION_CREATED":
3301
4299
  await handlers.onSubscriptionCreated?.(payload);
3302
4300
  return;
@@ -3330,7 +4328,21 @@ async function dispatchWebhook(payload, handlers) {
3330
4328
  case "SUBSCRIPTION_FREEZE_CANCEL":
3331
4329
  await handlers.onSubscriptionFreezeCancel?.(payload);
3332
4330
  return;
3333
- // Payment Link
4331
+ case "SUBSCRIPTION_PLAN_CHANGE_SCHEDULED":
4332
+ await handlers.onSubscriptionPlanChangeScheduled?.(payload);
4333
+ return;
4334
+ case "SUBSCRIPTION_PLAN_CHANGE_CANCELED":
4335
+ await handlers.onSubscriptionPlanChangeCanceled?.(payload);
4336
+ return;
4337
+ case "SUBSCRIPTION_PLAN_CHANGED":
4338
+ await handlers.onSubscriptionPlanChanged?.(payload);
4339
+ return;
4340
+ case "SUBSCRIPTION_PLAN_CHANGE_INVOICE_REISSUED":
4341
+ await handlers.onSubscriptionPlanChangeInvoiceReissued?.(payload);
4342
+ return;
4343
+ case "SUBSCRIPTION_PLAN_UPDATED":
4344
+ await handlers.onSubscriptionPlanUpdated?.(payload);
4345
+ return;
3334
4346
  case "PAYMENT_LINK_PAY_ATTEMPT_FAILED":
3335
4347
  await handlers.onPaymentLinkPayAttemptFailed?.(payload);
3336
4348
  return;
@@ -3369,7 +4381,9 @@ function verifyWebhook(input) {
3369
4381
  const { rawBody, signatureHeader } = input;
3370
4382
  const toleranceSeconds = input.toleranceSeconds ?? 300;
3371
4383
  const now = input.now ?? (() => Math.floor(Date.now() / 1e3));
3372
- const secrets = typeof input.secret === "string" ? [input.secret] : input.secret;
4384
+ const secrets = (typeof input.secret === "string" ? [input.secret] : input.secret).filter(
4385
+ (secret) => secret.length > 0
4386
+ );
3373
4387
  if (!signatureHeader) return { ok: false, reason: "MISSING_HEADER" };
3374
4388
  const parsed = parseSignatureHeader(signatureHeader);
3375
4389
  if (!parsed) return { ok: false, reason: "MALFORMED_HEADER" };
@@ -3395,95 +4409,93 @@ function verifyWebhookOrThrow(input) {
3395
4409
  }
3396
4410
 
3397
4411
  // src/plugins/webhooks.ts
3398
- function isStreamPayWebhookPayload(value) {
3399
- if (!value || typeof value !== "object") return false;
3400
- return "event_type" in value && typeof value.event_type === "string";
3401
- }
3402
4412
  function toErrorCode(reason) {
3403
4413
  return reason === "MISSING_HEADER" || reason === "INVALID_SIGNATURE" || reason === "EXPIRED" ? "UNAUTHORIZED" : "BAD_REQUEST";
3404
4414
  }
3405
- var webhooks = (webhooksOptions) => (_options, registry) => {
3406
- const { secret, toleranceSeconds, ...handlers } = webhooksOptions;
3407
- return {
3408
- endpoints: {
3409
- streampayWebhooks: api.createAuthEndpoint(
3410
- "/streampay/webhooks",
3411
- {
3412
- method: "POST",
3413
- metadata: { isAction: false },
3414
- cloneRequest: true
3415
- },
3416
- async (ctx) => {
3417
- const logger2 = getLogger(ctx);
3418
- const hasSecret = typeof secret === "string" ? secret.length > 0 : secret.some((s) => s.length > 0);
3419
- if (!hasSecret) {
3420
- logger2.error("webhook secret is not configured.");
3421
- throw new api.APIError("INTERNAL_SERVER_ERROR", {
3422
- message: "StreamPay webhook secret is not configured."
3423
- });
3424
- }
3425
- if (!ctx.request) {
3426
- throw new api.APIError("BAD_REQUEST", { message: "Missing request body." });
3427
- }
3428
- const rawBody = await ctx.request.text();
3429
- const signatureHeader = ctx.request.headers.get("x-webhook-signature");
3430
- try {
3431
- verifyWebhookOrThrow({
3432
- secret,
3433
- rawBody,
3434
- signatureHeader,
3435
- toleranceSeconds: toleranceSeconds ?? 300
3436
- });
3437
- } catch (err) {
3438
- if (err instanceof StreamPayWebhookError) {
3439
- logger2.warn(`webhook rejected: ${err.reason}`);
3440
- throw new api.APIError(toErrorCode(err.reason), {
3441
- message: `Webhook verification failed: ${err.reason}`
3442
- });
4415
+ var webhooks = (webhooksOptions) => {
4416
+ const configuredSecrets = typeof webhooksOptions.secret === "string" ? [webhooksOptions.secret] : webhooksOptions.secret;
4417
+ if (configuredSecrets.length === 0 || configuredSecrets.some((secret) => secret.length === 0)) {
4418
+ throw new TypeError("webhooks(): `secret` must contain only non-empty values.");
4419
+ }
4420
+ if (webhooksOptions.toleranceSeconds !== void 0 && (!Number.isFinite(webhooksOptions.toleranceSeconds) || webhooksOptions.toleranceSeconds < 0)) {
4421
+ throw new TypeError("webhooks(): `toleranceSeconds` must be a non-negative number.");
4422
+ }
4423
+ return (_options, registry) => {
4424
+ const { secret, toleranceSeconds, ...handlers } = webhooksOptions;
4425
+ return {
4426
+ endpoints: {
4427
+ streampayWebhooks: api.createAuthEndpoint(
4428
+ "/streampay/webhooks",
4429
+ {
4430
+ method: "POST",
4431
+ metadata: { isAction: false },
4432
+ cloneRequest: true
4433
+ },
4434
+ async (ctx) => {
4435
+ const logger2 = getLogger(ctx);
4436
+ if (!ctx.request) {
4437
+ throw new api.APIError("BAD_REQUEST", { message: "Missing request body." });
3443
4438
  }
3444
- throw err;
3445
- }
3446
- let parsed;
3447
- try {
3448
- parsed = JSON.parse(rawBody);
3449
- } catch {
3450
- throw new api.APIError("BAD_REQUEST", {
3451
- message: "Webhook body is not valid JSON."
3452
- });
3453
- }
3454
- if (!isStreamPayWebhookPayload(parsed)) {
3455
- throw new api.APIError("BAD_REQUEST", {
3456
- message: "Webhook body is missing `event_type`."
3457
- });
3458
- }
3459
- const payload = parsed;
3460
- if (registry?.subscriptionWebhookSync) {
4439
+ const rawBody = await ctx.request.text();
4440
+ const signatureHeader = ctx.request.headers.get("x-webhook-signature");
3461
4441
  try {
3462
- await registry.subscriptionWebhookSync(ctx, payload, {
4442
+ verifyWebhookOrThrow({
4443
+ secret,
3463
4444
  rawBody,
3464
- signatureHeader
4445
+ signatureHeader,
4446
+ toleranceSeconds: toleranceSeconds ?? 300
4447
+ });
4448
+ } catch (err) {
4449
+ if (err instanceof StreamPayWebhookError) {
4450
+ logger2.warn(`webhook rejected: ${err.reason}`);
4451
+ throw new api.APIError(toErrorCode(err.reason), {
4452
+ message: `Webhook verification failed: ${err.reason}`
4453
+ });
4454
+ }
4455
+ throw err;
4456
+ }
4457
+ let parsed;
4458
+ try {
4459
+ parsed = JSON.parse(rawBody);
4460
+ } catch {
4461
+ throw new api.APIError("BAD_REQUEST", {
4462
+ message: "Webhook body is not valid JSON."
3465
4463
  });
4464
+ }
4465
+ if (!isStreamPayWebhookEnvelope(parsed)) {
4466
+ throw new api.APIError("BAD_REQUEST", {
4467
+ message: "Webhook body is not a valid StreamPay event envelope."
4468
+ });
4469
+ }
4470
+ const payload = parsed;
4471
+ if (registry?.subscriptionWebhookSync && isKnownStreamPayWebhookPayload(payload)) {
4472
+ try {
4473
+ await registry.subscriptionWebhookSync(ctx, payload, {
4474
+ rawBody,
4475
+ signatureHeader
4476
+ });
4477
+ } catch (err) {
4478
+ const message = err instanceof Error ? err.message : String(err);
4479
+ logger2.error(`subscription sync failed: ${message}`);
4480
+ throw new api.APIError("INTERNAL_SERVER_ERROR", {
4481
+ message: "Webhook sync failed. See server logs."
4482
+ });
4483
+ }
4484
+ }
4485
+ try {
4486
+ await dispatchWebhook(payload, handlers);
3466
4487
  } catch (err) {
3467
4488
  const message = err instanceof Error ? err.message : String(err);
3468
- logger2.error(`subscription sync failed: ${message}`);
4489
+ logger2.error(`webhook handler failed: ${message}`);
3469
4490
  throw new api.APIError("INTERNAL_SERVER_ERROR", {
3470
- message: "Webhook sync failed. See server logs."
4491
+ message: "Webhook handler failed. See server logs."
3471
4492
  });
3472
4493
  }
4494
+ return ctx.json({ received: true });
3473
4495
  }
3474
- try {
3475
- await dispatchWebhook(payload, handlers);
3476
- } catch (err) {
3477
- const message = err instanceof Error ? err.message : String(err);
3478
- logger2.error(`webhook handler failed: ${message}`);
3479
- throw new api.APIError("INTERNAL_SERVER_ERROR", {
3480
- message: "Webhook handler failed. See server logs."
3481
- });
3482
- }
3483
- return ctx.json({ received: true });
3484
- }
3485
- )
3486
- }
4496
+ )
4497
+ }
4498
+ };
3487
4499
  };
3488
4500
  };
3489
4501
  var isAnonymous = (user) => "isAnonymous" in user && user.isAnonymous === true;
@@ -3502,6 +4514,7 @@ var onBeforeUserCreate = (options) => async (user, context) => {
3502
4514
  const createPayload = {
3503
4515
  name: user.name || user.email,
3504
4516
  email: user.email,
4517
+ consumer_type: "INDIVIDUAL",
3505
4518
  ...extras
3506
4519
  };
3507
4520
  try {
@@ -3600,7 +4613,7 @@ var onUserDelete = (options) => async (user, context) => {
3600
4613
 
3601
4614
  // package.json
3602
4615
  var package_default = {
3603
- version: "1.2.1"};
4616
+ version: "2.0.0"};
3604
4617
 
3605
4618
  // src/version.ts
3606
4619
  var version = package_default.version;
@@ -3656,53 +4669,40 @@ var streampay = (options) => {
3656
4669
  };
3657
4670
  };
3658
4671
 
3659
- // src/webhooks/events.ts
3660
- var STREAMPAY_PAYMENT_EVENT_TYPES = [
3661
- "PAYMENT_SUCCEEDED",
3662
- "PAYMENT_FAILED",
3663
- "PAYMENT_CANCELED",
3664
- "PAYMENT_REFUNDED",
3665
- "PAYMENT_MARKED_AS_PAID"
3666
- ];
3667
- var STREAMPAY_INVOICE_EVENT_TYPES = [
3668
- "INVOICE_CREATED",
3669
- "INVOICE_SENT",
3670
- "INVOICE_ACCEPTED",
3671
- "INVOICE_REJECTED",
3672
- "INVOICE_COMPLETED",
3673
- "INVOICE_CANCELED",
3674
- "INVOICE_UPDATED"
3675
- ];
3676
- var STREAMPAY_SUBSCRIPTION_EVENT_TYPES = [
3677
- "SUBSCRIPTION_CREATED",
3678
- "SUBSCRIPTION_ACTIVATED",
3679
- "SUBSCRIPTION_INACTIVATED",
3680
- "SUBSCRIPTION_CANCELED",
3681
- "SUBSCRIPTION_FROZEN",
3682
- "SUBSCRIPTION_CYCLE_RENEWAL_FAILED",
3683
- "SUBSCRIPTION_CANCEL_AT_PERIOD_END",
3684
- "SUBSCRIPTION_FREEZE_NOW",
3685
- "SUBSCRIPTION_UNFREEZE_NOW",
3686
- "SUBSCRIPTION_UNFREEZE_FUTURE",
3687
- "SUBSCRIPTION_FREEZE_CANCEL"
3688
- ];
3689
- var STREAMPAY_PAYMENT_LINK_EVENT_TYPES = ["PAYMENT_LINK_PAY_ATTEMPT_FAILED"];
3690
- var STREAMPAY_EVENT_TYPES = [
3691
- ...STREAMPAY_PAYMENT_EVENT_TYPES,
3692
- ...STREAMPAY_INVOICE_EVENT_TYPES,
3693
- ...STREAMPAY_SUBSCRIPTION_EVENT_TYPES,
3694
- ...STREAMPAY_PAYMENT_LINK_EVENT_TYPES
3695
- ];
4672
+ // src/utils/amount.ts
4673
+ var StreamPayAmount = {
4674
+ toHalalat(sar) {
4675
+ const asNumber = typeof sar === "string" ? Number(sar) : sar;
4676
+ if (!Number.isFinite(asNumber)) {
4677
+ throw new RangeError(`StreamPayAmount.toHalalat: invalid SAR value ${String(sar)}`);
4678
+ }
4679
+ const absoluteHalalat = Math.round(Number(`${Math.abs(asNumber)}e2`));
4680
+ const halalat = Math.sign(asNumber) * absoluteHalalat;
4681
+ if (!Number.isSafeInteger(halalat)) {
4682
+ throw new RangeError(`StreamPayAmount.toHalalat: SAR value is outside the safe range`);
4683
+ }
4684
+ return halalat;
4685
+ },
4686
+ toSAR(halalat) {
4687
+ if (!Number.isFinite(halalat) || !Number.isInteger(halalat)) {
4688
+ throw new RangeError(`StreamPayAmount.toSAR: expected integer halalat, got ${halalat}`);
4689
+ }
4690
+ return (halalat / 100).toFixed(2);
4691
+ }
4692
+ };
3696
4693
 
3697
4694
  exports.$ERROR_CODES = $ERROR_CODES;
3698
4695
  exports.CheckoutBody = CheckoutBody;
4696
+ exports.DEFAULT_ACCESS_STATUSES = DEFAULT_ACCESS_STATUSES;
3699
4697
  exports.PLAN_NAME_METADATA_KEY = PLAN_NAME_METADATA_KEY;
3700
4698
  exports.REFERENCE_ID_METADATA_KEY = REFERENCE_ID_METADATA_KEY;
4699
+ exports.REFERENCE_TYPE_METADATA_KEY = REFERENCE_TYPE_METADATA_KEY;
3701
4700
  exports.STREAMPAY_EVENT_TYPES = STREAMPAY_EVENT_TYPES;
3702
4701
  exports.STREAMPAY_INVOICE_EVENT_TYPES = STREAMPAY_INVOICE_EVENT_TYPES;
3703
4702
  exports.STREAMPAY_PAYMENT_EVENT_TYPES = STREAMPAY_PAYMENT_EVENT_TYPES;
3704
4703
  exports.STREAMPAY_PAYMENT_LINK_EVENT_TYPES = STREAMPAY_PAYMENT_LINK_EVENT_TYPES;
3705
4704
  exports.STREAMPAY_SUBSCRIPTION_EVENT_TYPES = STREAMPAY_SUBSCRIPTION_EVENT_TYPES;
4705
+ exports.SUBSCRIPTION_ROW_ID_METADATA_KEY = SUBSCRIPTION_ROW_ID_METADATA_KEY;
3706
4706
  exports.StreamPayAmount = StreamPayAmount;
3707
4707
  exports.StreamPayWebhookError = StreamPayWebhookError;
3708
4708
  exports.admin = admin;
@@ -3714,11 +4714,15 @@ exports.findConsumerByExternalId = findConsumerByExternalId;
3714
4714
  exports.findConsumerByIdentifiers = findConsumerByIdentifiers;
3715
4715
  exports.formatStreamPayError = formatStreamPayError;
3716
4716
  exports.hasFeature = hasFeature;
4717
+ exports.hasSubscriptionAccess = hasSubscriptionAccess;
4718
+ exports.isKnownStreamPayWebhookPayload = isKnownStreamPayWebhookPayload;
4719
+ exports.isStreamPayWebhookEnvelope = isStreamPayWebhookEnvelope;
3717
4720
  exports.mapToErrorCode = mapToErrorCode;
3718
4721
  exports.parseStreamPayError = parseStreamPayError;
3719
4722
  exports.portal = portal;
3720
4723
  exports.streampay = streampay;
3721
4724
  exports.subscriptionSchema = subscriptionSchema;
4725
+ exports.subscriptionSlotKey = subscriptionSlotKey;
3722
4726
  exports.subscriptions = subscriptions;
3723
4727
  exports.syncWebhookPayload = syncWebhookPayload;
3724
4728
  exports.verifyWebhook = verifyWebhook;