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