better-auth-streampay 1.2.0 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -42,35 +42,27 @@ var $ERROR_CODES = defineErrorCodes({
42
42
  UNKNOWN: "An unexpected error occurred."
43
43
  });
44
44
  var RAW_CODE_MAP = {
45
- // Validation
46
45
  INVALID_PARAMETERS: "VALIDATION_ERROR",
47
- // Permissions
48
46
  PERMISSION_FORBIDDEN: "FORBIDDEN",
49
47
  BRANCH_ACCESS_DENIED: "FORBIDDEN",
50
48
  BRANCH_NOT_FOUND: "NOT_FOUND",
51
- // Consumer
52
49
  DUPLICATE_CONSUMER: "CONSUMER_DUPLICATE",
53
50
  DUPLICATE_CARD_TOKEN: "CONSUMER_DUPLICATE",
54
51
  CONSUMER_HAS_ONGOING_INVOICES: "CONSUMER_HAS_ONGOING_ACTIVITY",
55
52
  CONSUMER_HAS_ONGOING_SUBSCRIPTIONS: "CONSUMER_HAS_ONGOING_ACTIVITY",
56
- // Invoice state
57
53
  INVOICE_FINALISED: "INVOICE_INVALID_STATE",
58
54
  INVOICE_INVALID_STATUS: "INVOICE_INVALID_STATE",
59
55
  INVOICE_CONSENT_CONSUMED: "INVOICE_INVALID_STATE",
60
56
  INVOICE_CONSENT_EXPIRED: "INVOICE_INVALID_STATE",
61
57
  INVOICE_TOTAL_MISMATCH_PAYMENT_AMOUNT_SUM: "INVOICE_INVALID_STATE",
62
58
  INVOICE_PAYMENT_COUNT_NOT_MATCHED: "INVOICE_INVALID_STATE",
63
- // Payment state / duplicates
64
59
  DUPLICATE_PAYMENT: "PAYMENT_DUPLICATE",
65
60
  PAYMENT_IN_PROGRESS: "PAYMENT_INVALID_STATE",
66
61
  PAYMENT_FINALIZED: "PAYMENT_INVALID_STATE",
67
62
  PAYMEND_UNPAID: "PAYMENT_INVALID_STATE",
68
- // sic — upstream typo we inherit
69
63
  INVALID_STATUS: "PAYMENT_INVALID_STATE",
70
- // Refund outcomes
71
64
  PAYMENT_REFUNDED_ALREADY: "PAYMENT_ALREADY_REFUNDED",
72
65
  PAYMENT_REFUNDED_FAILED: "PAYMENT_REFUND_FAILED",
73
- // Gateway — declined (do not auto-retry; user must take action)
74
66
  PAYMENT_GATEWAY_DECLINED: "PAYMENT_GATEWAY_DECLINED",
75
67
  INSUFFICIENT_FUNDS: "PAYMENT_GATEWAY_DECLINED",
76
68
  MOYASAR_PAYMENT_INFO_MISMATCH: "PAYMENT_GATEWAY_DECLINED",
@@ -79,23 +71,18 @@ var RAW_CODE_MAP = {
79
71
  MOYASAR_FORBIDDEN: "PAYMENT_GATEWAY_DECLINED",
80
72
  MOYASAR_NOT_FOUND: "PAYMENT_GATEWAY_DECLINED",
81
73
  MOYASAR_METHOD_NOT_ALLOWED: "PAYMENT_GATEWAY_DECLINED",
82
- // Gateway — transient (safe to retry with backoff)
83
74
  MOYASAR_TIMEOUT: "PAYMENT_GATEWAY_UNAVAILABLE",
84
75
  MOYASAR_TOO_MANY_REQUESTS: "PAYMENT_GATEWAY_UNAVAILABLE",
85
76
  MOYASAR_INTERNAL_SERVER_ERROR: "PAYMENT_GATEWAY_UNAVAILABLE",
86
77
  MOYASAR_SERVICE_UNAVAILABLE: "PAYMENT_GATEWAY_UNAVAILABLE",
87
- // Payment method identity
88
78
  MOYASAR_INVALID_CARD_TOKEN: "PAYMENT_METHOD_INVALID",
89
79
  MANUAL_INVOICE_CARD_ID: "PAYMENT_METHOD_INVALID",
90
80
  ONE_OFF_INVALID_PAYMENT_FLOW: "PAYMENT_METHOD_INVALID",
91
81
  ONE_OFF_CARD_ID: "PAYMENT_METHOD_INVALID",
92
82
  AUTO_INVOICE_MISSING_CARD_ID: "PAYMENT_METHOD_INVALID",
93
83
  PAYMENT_FLOW_NOT_ALLOWED: "PAYMENT_METHOD_INVALID",
94
- // Catalog
95
84
  PRODUCT_USED_IN_FINALIZED_INVOICE: "PRODUCT_LOCKED",
96
85
  COUPON_USED_IN_FINALIZED_INVOICE: "COUPON_LOCKED",
97
- // Subscription state — these fire from the upstream API when the
98
- // caller attempts an action the current subscription state forbids.
99
86
  SUBSCRIPTION_ALREADY_ACTIVE: "SUBSCRIPTION_ALREADY_ACTIVE",
100
87
  SUBSCRIPTION_NOT_FOUND: "SUBSCRIPTION_NOT_FOUND",
101
88
  SUBSCRIPTION_ALREADY_CANCELED: "SUBSCRIPTION_INVALID_STATE",
@@ -121,9 +108,21 @@ async function findConsumerByExternalId(client, { externalId }) {
121
108
  const hit = await searchExact(client, externalId, (c) => c.external_id === externalId);
122
109
  return hit?.id ?? null;
123
110
  }
111
+ function sameEmail(a, b) {
112
+ if (!a || !b) return false;
113
+ return a.trim().toLowerCase() === b.trim().toLowerCase();
114
+ }
115
+ function samePhone(a, b) {
116
+ if (!a || !b) return false;
117
+ return a.trim() === b.trim();
118
+ }
124
119
  async function findConsumerByIdentifiers(client, identifiers) {
125
120
  if (identifiers.email) {
126
- const hit = await searchExact(client, identifiers.email, (c) => c.email === identifiers.email);
121
+ const hit = await searchExact(
122
+ client,
123
+ identifiers.email,
124
+ (c) => sameEmail(c.email, identifiers.email)
125
+ );
127
126
  if (hit) return hit;
128
127
  }
129
128
  if (identifiers.phone_number) {
@@ -240,15 +239,21 @@ function formatStreamPayError(err) {
240
239
  }
241
240
  }
242
241
 
243
- // src/utils/ensure-consumer.ts
244
- function sameEmail(a, b) {
245
- if (!a || !b) return false;
246
- return a.trim().toLowerCase() === b.trim().toLowerCase();
242
+ // src/utils/logger.ts
243
+ var PLUGIN_PREFIX = "[streampay]";
244
+ function scopedLogger(logger2) {
245
+ return {
246
+ error: (message) => logger2.error(`${PLUGIN_PREFIX} ${message}`),
247
+ warn: (message) => logger2.warn(`${PLUGIN_PREFIX} ${message}`),
248
+ info: (message) => logger2.info(`${PLUGIN_PREFIX} ${message}`),
249
+ debug: (message) => logger2.debug(`${PLUGIN_PREFIX} ${message}`)
250
+ };
247
251
  }
248
- function samePhone(a, b) {
249
- if (!a || !b) return false;
250
- return a.trim() === b.trim();
252
+ function getLogger(ctx) {
253
+ return scopedLogger(ctx.context.logger);
251
254
  }
255
+
256
+ // src/utils/ensure-consumer.ts
252
257
  function canClaimBy(mode, identifier) {
253
258
  return mode?.includes(identifier) ?? false;
254
259
  }
@@ -278,8 +283,8 @@ async function resolveDuplicateConsumer(options, createPayload, context) {
278
283
  if (canClaimBy(options.claimExistingConsumerBy, "phone") && samePhone(existing.phone_number, createPayload.phone_number)) {
279
284
  return existing.id;
280
285
  }
281
- context.context.logger.error(
282
- `StreamPay duplicate: consumer ${existing.id} is already linked to external_id=${existing.external_id}`
286
+ getLogger(context).error(
287
+ `duplicate: consumer ${existing.id} is already linked to external_id=${existing.external_id}`
283
288
  );
284
289
  throw new api.APIError("CONFLICT", {
285
290
  code: "CONSUMER_DUPLICATE_LINKED",
@@ -330,16 +335,16 @@ async function ensureConsumerForUser(options, ctx, user) {
330
335
  try {
331
336
  await options.client.updateConsumer(reusedId, { external_id: user.id });
332
337
  } catch (backfillErr) {
333
- ctx.context.logger.error(
334
- `StreamPay consumer external_id backfill failed for user=${user.id} consumer=${reusedId}: ${formatStreamPayError(backfillErr)}`
338
+ getLogger(ctx).error(
339
+ `consumer external_id backfill failed for user=${user.id} consumer=${reusedId}: ${formatStreamPayError(backfillErr)}`
335
340
  );
336
341
  }
337
342
  await persistConsumerId(ctx, user.id, reusedId);
338
343
  return { consumerId: reusedId, created: false };
339
344
  }
340
345
  }
341
- ctx.context.logger.error(
342
- `StreamPay consumer creation failed for user=${user.id}: ${formatStreamPayError(err)}`
346
+ getLogger(ctx).error(
347
+ `consumer creation failed for user=${user.id}: ${formatStreamPayError(err)}`
343
348
  );
344
349
  throw new api.APIError("INTERNAL_SERVER_ERROR", {
345
350
  message: "StreamPay consumer provisioning failed. Please try again."
@@ -352,8 +357,8 @@ async function persistConsumerId(ctx, userId, consumerId) {
352
357
  streampayConsumerId: consumerId
353
358
  });
354
359
  } catch (err) {
355
- ctx.context.logger.error(
356
- `StreamPay consumer link write failed for user=${userId}: ${formatStreamPayError(err)}`
360
+ getLogger(ctx).error(
361
+ `consumer link write failed for user=${userId}: ${formatStreamPayError(err)}`
357
362
  );
358
363
  }
359
364
  }
@@ -408,7 +413,7 @@ function statusToAPIErrorStatus(status) {
408
413
  return "INTERNAL_SERVER_ERROR";
409
414
  }
410
415
  }
411
- function toAPIError(messageOrConfig, err, logger) {
416
+ function toAPIError(messageOrConfig, err, logger2) {
412
417
  if (err instanceof api.APIError) throw err;
413
418
  const { logPrefix, userMessage } = typeof messageOrConfig === "string" ? { logPrefix: messageOrConfig, userMessage: messageOrConfig } : messageOrConfig;
414
419
  const parsed = parseStreamPayError(err);
@@ -419,7 +424,7 @@ function toAPIError(messageOrConfig, err, logger) {
419
424
  ].filter((segment) => segment !== void 0);
420
425
  const validationSummary = parsed.validationErrors.length > 0 ? ` validation=${parsed.validationErrors.map((issue) => `${issue.loc.join(".")}: ${issue.message}`).join(" | ")}` : "";
421
426
  const logDetail = (tail.length > 0 ? `${parsed.message} [${tail.join(" ")}]` : parsed.message) + validationSummary;
422
- logger.error(`${logPrefix} ${logDetail}`);
427
+ logger2.error(`${logPrefix} ${logDetail}`);
423
428
  throw new api.APIError(statusToAPIErrorStatus(parsed.status), {
424
429
  code: mapToErrorCode(parsed.code, parsed.status),
425
430
  message: userMessage
@@ -500,19 +505,32 @@ var REFERENCE_ID_METADATA_KEY = "streampay_plugin_reference_id";
500
505
  // src/plugins/subscriptions/sync.ts
501
506
  var SUBSCRIPTION_MODEL = "subscription";
502
507
  var WEBHOOK_EVENT_MODEL = "streampayWebhookEvent";
503
- var DEFAULT_MAX_WEBHOOK_ATTEMPTS = 10;
504
- function isUniqueConstraintError(err) {
508
+ function logger(ctx) {
509
+ return scopedLogger(ctx.context.logger);
510
+ }
511
+ var DEFAULT_MAX_WEBHOOK_ATTEMPTS = 5;
512
+ var MAX_CAUSE_DEPTH = 5;
513
+ function matchesUniqueMarker(err) {
505
514
  if (!err || typeof err !== "object") return false;
506
515
  const message = "message" in err && typeof err.message === "string" ? err.message : "";
507
516
  if (/unique/i.test(message) || /duplicate/i.test(message)) return true;
508
517
  const code = "code" in err && typeof err.code === "string" ? err.code : "";
509
518
  return code === "P2002" || code === "23505" || code === "SQLITE_CONSTRAINT_UNIQUE";
510
519
  }
520
+ function isUniqueConstraintError(err) {
521
+ let current = err;
522
+ for (let depth = 0; depth <= MAX_CAUSE_DEPTH; depth++) {
523
+ if (matchesUniqueMarker(current)) return true;
524
+ if (!current || typeof current !== "object" || !("cause" in current)) return false;
525
+ current = current.cause;
526
+ }
527
+ return false;
528
+ }
511
529
  async function claimOrAdvanceWebhookEvent(ctx, payload, rawBody, signatureHeader, maxAttempts) {
512
530
  const eventId = extractEventId(payload);
513
531
  if (!eventId) {
514
- ctx.context.logger.warn(
515
- `StreamPay webhook ${payload.event_type}: missing entity_id/timestamp \u2014 processing without dedupe.`
532
+ logger(ctx).warn(
533
+ `webhook ${payload.event_type}: missing entity_id/timestamp \u2014 processing without dedupe.`
516
534
  );
517
535
  return { action: "process", row: null };
518
536
  }
@@ -538,20 +556,18 @@ async function claimOrAdvanceWebhookEvent(ctx, payload, rawBody, signatureHeader
538
556
  where: [{ field: "eventId", value: eventId }]
539
557
  });
540
558
  if (!existing) {
541
- ctx.context.logger.warn(
542
- `StreamPay webhook ${payload.event_type} (${eventId}): unique conflict but row missing, processing without tracking.`
559
+ logger(ctx).warn(
560
+ `webhook ${payload.event_type} (${eventId}): unique conflict but row missing, processing without tracking.`
543
561
  );
544
562
  return { action: "process", row: null };
545
563
  }
546
564
  if (existing.status === "completed") {
547
- ctx.context.logger.info(
548
- `StreamPay webhook ${payload.event_type} (${eventId}) already completed \u2014 skipping.`
549
- );
565
+ logger(ctx).info(`webhook ${payload.event_type} (${eventId}) already completed \u2014 skipping.`);
550
566
  return { action: "skip", reason: "completed" };
551
567
  }
552
568
  if (existing.status === "dead_letter") {
553
- ctx.context.logger.warn(
554
- `StreamPay webhook ${payload.event_type} (${eventId}) already dead-lettered \u2014 skipping (replay manually).`
569
+ logger(ctx).warn(
570
+ `webhook ${payload.event_type} (${eventId}) already dead-lettered \u2014 skipping (replay manually).`
555
571
  );
556
572
  return { action: "skip", reason: "dead_letter" };
557
573
  }
@@ -621,7 +637,7 @@ async function findSubscriptionByStreampayId(ctx, streampaySubscriptionId) {
621
637
  where: [{ field: "streampaySubscriptionId", value: streampaySubscriptionId }]
622
638
  });
623
639
  }
624
- async function applySubscriptionProjection(adapter, stream, logger, source) {
640
+ async function applySubscriptionProjection(adapter, stream, log, source) {
625
641
  const streampaySubscriptionId = stream?.id;
626
642
  if (!stream || !streampaySubscriptionId) return;
627
643
  try {
@@ -637,23 +653,23 @@ async function applySubscriptionProjection(adapter, stream, logger, source) {
637
653
  });
638
654
  } catch (err) {
639
655
  const msg = err instanceof Error ? err.message : String(err);
640
- logger.warn(
641
- `StreamPay ${source}: project for sub=${streampaySubscriptionId} failed (${msg}). Local row will reconcile on next webhook.`
656
+ log.warn(
657
+ `${source}: project for sub=${streampaySubscriptionId} failed (${msg}). Local row will reconcile on next webhook.`
642
658
  );
643
659
  }
644
660
  }
645
- async function syncSubscriptionFromUpstream(client, adapter, streampaySubscriptionId, logger, source) {
661
+ async function syncSubscriptionFromUpstream(client, adapter, streampaySubscriptionId, log, source) {
646
662
  let stream;
647
663
  try {
648
664
  stream = await client.getSubscription(streampaySubscriptionId);
649
665
  } catch (err) {
650
666
  const msg = err instanceof Error ? err.message : String(err);
651
- logger.warn(
652
- `StreamPay ${source}: getSubscription(${streampaySubscriptionId}) failed (${msg}). Local row will reconcile on next webhook.`
667
+ log.warn(
668
+ `${source}: getSubscription(${streampaySubscriptionId}) failed (${msg}). Local row will reconcile on next webhook.`
653
669
  );
654
670
  return;
655
671
  }
656
- await applySubscriptionProjection(adapter, stream, logger, source);
672
+ await applySubscriptionProjection(adapter, stream, log, source);
657
673
  }
658
674
  async function findIncompleteRow(ctx, referenceId, plan) {
659
675
  const candidates = await ctx.context.adapter.findMany({
@@ -716,15 +732,13 @@ async function fireCallback(ctx, callback, data, callbackName) {
716
732
  await callback(data);
717
733
  } catch (err) {
718
734
  const msg = err instanceof Error ? err.message : String(err);
719
- ctx.context.logger.error(`StreamPay subscription callback ${callbackName} failed: ${msg}`);
735
+ logger(ctx).error(`subscription callback ${callbackName} failed: ${msg}`);
720
736
  }
721
737
  }
722
738
  async function reconcileFromStreamPay(ctx, payload, client, plans) {
723
739
  const streampaySubscriptionId = payload.entity_id;
724
740
  if (!streampaySubscriptionId) {
725
- ctx.context.logger.warn(
726
- `StreamPay webhook ${payload.event_type} has no entity_id \u2014 cannot reconcile.`
727
- );
741
+ logger(ctx).warn(`webhook ${payload.event_type} has no entity_id \u2014 cannot reconcile.`);
728
742
  return { row: null, stream: null };
729
743
  }
730
744
  let stream;
@@ -732,13 +746,16 @@ async function reconcileFromStreamPay(ctx, payload, client, plans) {
732
746
  stream = await client.getSubscription(streampaySubscriptionId);
733
747
  } catch (err) {
734
748
  const msg = err instanceof Error ? err.message : String(err);
735
- ctx.context.logger.error(
736
- `StreamPay webhook ${payload.event_type}: getSubscription(${streampaySubscriptionId}) failed: ${msg}`
749
+ logger(ctx).error(
750
+ `webhook ${payload.event_type}: getSubscription(${streampaySubscriptionId}) failed: ${msg}`
737
751
  );
738
752
  throw err;
739
753
  }
740
754
  const existing = await findSubscriptionByStreampayId(ctx, streampaySubscriptionId);
741
755
  const projected = projectSubscriptionFields(stream);
756
+ if (payload.event_type === "SUBSCRIPTION_CYCLE_RENEWAL_FAILED" && projected.status === "active") {
757
+ projected.status = "past_due";
758
+ }
742
759
  if (existing) {
743
760
  const updated = await ctx.context.adapter.update({
744
761
  model: SUBSCRIPTION_MODEL,
@@ -750,8 +767,8 @@ async function reconcileFromStreamPay(ctx, payload, client, plans) {
750
767
  const planName = readMetadataString(payload.data, PLAN_NAME_METADATA_KEY) ?? inferPlanFromItems(stream, plans);
751
768
  const referenceId = readMetadataString(payload.data, REFERENCE_ID_METADATA_KEY);
752
769
  if (!planName || !referenceId) {
753
- ctx.context.logger.warn(
754
- `StreamPay webhook ${payload.event_type}: cannot link sub=${streampaySubscriptionId} \u2014 missing plan_name (${planName}) or reference_id (${referenceId}) metadata.`
770
+ logger(ctx).warn(
771
+ `webhook ${payload.event_type}: cannot link sub=${streampaySubscriptionId} \u2014 missing plan_name (${planName}) or reference_id (${referenceId}) metadata.`
755
772
  );
756
773
  return { row: null, stream };
757
774
  }
@@ -784,11 +801,14 @@ var SubscriptionItemSchema = zod.z.object({
784
801
  product: zod.z.object({ id: zod.z.string() }).passthrough().optional(),
785
802
  product_id: zod.z.string().optional()
786
803
  }).passthrough();
804
+ function subscriptionItemProductId(item) {
805
+ const parsed = SubscriptionItemSchema.safeParse(item);
806
+ if (!parsed.success) return null;
807
+ return parsed.data.product?.id ?? parsed.data.product_id ?? null;
808
+ }
787
809
  function inferPlanFromItems(sub, plans) {
788
810
  const first = Array.isArray(sub.items) ? sub.items[0] : void 0;
789
- const parsed = SubscriptionItemSchema.safeParse(first);
790
- if (!parsed.success) return null;
791
- const productId = parsed.data.product?.id ?? parsed.data.product_id;
811
+ const productId = subscriptionItemProductId(first);
792
812
  if (!productId) return null;
793
813
  return plans.list.find((plan) => plan.productId === productId)?.name ?? null;
794
814
  }
@@ -805,8 +825,8 @@ async function syncWebhookPayload(ctx, payload, client, plans, callbacks, option
805
825
  claim = await claimOrAdvanceWebhookEvent(ctx, payload, rawBody, signatureHeader, maxAttempts);
806
826
  if (claim.action === "skip") return;
807
827
  if (claim.action === "dead_letter") {
808
- ctx.context.logger.warn(
809
- `StreamPay webhook ${payload.event_type} (${claim.row.eventId}) dead-lettered after ${claim.row.attemptCount} attempts. Replay manually.`
828
+ logger(ctx).warn(
829
+ `webhook ${payload.event_type} (${claim.row.eventId}) dead-lettered after ${claim.row.attemptCount} attempts. Replay manually.`
810
830
  );
811
831
  return;
812
832
  }
@@ -848,9 +868,7 @@ async function handleInvoiceCompleted(ctx, payload, client, _plans, callbacks) {
848
868
  }
849
869
  } catch (err) {
850
870
  const msg = err instanceof Error ? err.message : String(err);
851
- ctx.context.logger.error(
852
- `StreamPay INVOICE_COMPLETED: getInvoice(${invoiceId}) failed: ${msg}`
853
- );
871
+ logger(ctx).error(`INVOICE_COMPLETED: getInvoice(${invoiceId}) failed: ${msg}`);
854
872
  throw err;
855
873
  }
856
874
  if (!subscriptionId) return;
@@ -859,19 +877,18 @@ async function handleInvoiceCompleted(ctx, payload, client, _plans, callbacks) {
859
877
  stream = await client.getSubscription(subscriptionId);
860
878
  } catch (err) {
861
879
  const msg = err instanceof Error ? err.message : String(err);
862
- ctx.context.logger.error(
863
- `StreamPay INVOICE_COMPLETED: getSubscription(${subscriptionId}) failed: ${msg}`
864
- );
880
+ logger(ctx).error(`INVOICE_COMPLETED: getSubscription(${subscriptionId}) failed: ${msg}`);
865
881
  throw err;
866
882
  }
867
883
  const existing = await findSubscriptionByStreampayId(ctx, subscriptionId);
868
884
  if (!existing) return;
885
+ const projected = projectSubscriptionFields(stream);
869
886
  const updated = await ctx.context.adapter.update({
870
887
  model: SUBSCRIPTION_MODEL,
871
- update: projectSubscriptionFields(stream),
888
+ update: projected,
872
889
  where: [{ field: "id", value: existing.id }]
873
890
  });
874
- const row = updated ?? { ...existing, ...projectSubscriptionFields(stream) };
891
+ const row = updated ?? { ...existing, ...projected };
875
892
  const user = await resolveRowUser(ctx, row);
876
893
  await fireCallback(
877
894
  ctx,
@@ -913,9 +930,9 @@ async function dispatchSubscriptionCallback(ctx, payload, data, callbacks) {
913
930
  }
914
931
  function classifyWebhookFailure(err) {
915
932
  const { status } = readSdkErrorFields(err);
916
- if (status !== void 0 && status >= 400 && status < 500 && status !== 429) {
917
- return "PERMANENT";
918
- }
933
+ if (status === void 0) return "TRANSIENT";
934
+ if (status === 404 || status === 429) return "TRANSIENT";
935
+ if (status >= 400 && status < 500) return "PERMANENT";
919
936
  return "TRANSIENT";
920
937
  }
921
938
 
@@ -996,7 +1013,7 @@ function buildPaymentsEndpoints(client, adminOptions) {
996
1013
  userMessage: "StreamPay refund failed."
997
1014
  },
998
1015
  err,
999
- ctx.context.logger
1016
+ getLogger(ctx)
1000
1017
  );
1001
1018
  }
1002
1019
  }
@@ -1018,7 +1035,7 @@ function buildPaymentsEndpoints(client, adminOptions) {
1018
1035
  const response = await client.listPayments(params);
1019
1036
  return ctx.json(response);
1020
1037
  } catch (err) {
1021
- toAPIError("StreamPay listPayments failed.", err, ctx.context.logger);
1038
+ toAPIError("StreamPay listPayments failed.", err, getLogger(ctx));
1022
1039
  }
1023
1040
  }
1024
1041
  ),
@@ -1037,7 +1054,7 @@ function buildPaymentsEndpoints(client, adminOptions) {
1037
1054
  toAPIError(
1038
1055
  `StreamPay getPayment failed for payment=${ctx.params.id}:`,
1039
1056
  err,
1040
- ctx.context.logger
1057
+ getLogger(ctx)
1041
1058
  );
1042
1059
  }
1043
1060
  }
@@ -1060,7 +1077,7 @@ function buildSubscriptionsEndpoints(client, adminOptions) {
1060
1077
  const subscription = await client.createSubscription(input);
1061
1078
  return ctx.json(subscription);
1062
1079
  } catch (err) {
1063
- toAPIError("StreamPay createSubscription failed.", err, ctx.context.logger);
1080
+ toAPIError("StreamPay createSubscription failed.", err, getLogger(ctx));
1064
1081
  }
1065
1082
  }
1066
1083
  ),
@@ -1083,7 +1100,7 @@ function buildSubscriptionsEndpoints(client, adminOptions) {
1083
1100
  toAPIError(
1084
1101
  `StreamPay getSubscription failed for subscription=${subscriptionId}:`,
1085
1102
  err,
1086
- ctx.context.logger
1103
+ getLogger(ctx)
1087
1104
  );
1088
1105
  }
1089
1106
  await adminOptions.onPlanChange({ user, subscriptionId, current, patch });
@@ -1093,7 +1110,7 @@ function buildSubscriptionsEndpoints(client, adminOptions) {
1093
1110
  await applySubscriptionProjection(
1094
1111
  getAdapter(ctx),
1095
1112
  subscription,
1096
- ctx.context.logger,
1113
+ getLogger(ctx),
1097
1114
  "adminUpdateSubscription"
1098
1115
  );
1099
1116
  return ctx.json(subscription);
@@ -1101,7 +1118,7 @@ function buildSubscriptionsEndpoints(client, adminOptions) {
1101
1118
  toAPIError(
1102
1119
  `StreamPay updateSubscription failed for subscription=${subscriptionId}:`,
1103
1120
  err,
1104
- ctx.context.logger
1121
+ getLogger(ctx)
1105
1122
  );
1106
1123
  }
1107
1124
  }
@@ -1122,7 +1139,7 @@ function buildSubscriptionsEndpoints(client, adminOptions) {
1122
1139
  const response = await client.listSubscriptions(params);
1123
1140
  return ctx.json(response);
1124
1141
  } catch (err) {
1125
- toAPIError("StreamPay listSubscriptions failed.", err, ctx.context.logger);
1142
+ toAPIError("StreamPay listSubscriptions failed.", err, getLogger(ctx));
1126
1143
  }
1127
1144
  }
1128
1145
  ),
@@ -1141,19 +1158,11 @@ function buildSubscriptionsEndpoints(client, adminOptions) {
1141
1158
  toAPIError(
1142
1159
  `StreamPay getSubscription failed for subscription=${ctx.params.id}:`,
1143
1160
  err,
1144
- ctx.context.logger
1161
+ getLogger(ctx)
1145
1162
  );
1146
1163
  }
1147
1164
  }
1148
1165
  ),
1149
- /**
1150
- * Immediate cancel from admin. Unlike the consumer `/subscription/cancel`,
1151
- * this one bypasses the local ownership check — an admin can cancel
1152
- * any subscription by StreamPay id. Mirrors the SDK's
1153
- * `SubscriptionCancel` body shape verbatim (only
1154
- * `cancel_related_invoices`; no period-end flag — StreamPay doesn't
1155
- * expose one on this endpoint).
1156
- */
1157
1166
  adminCancelSubscription: api.createAuthEndpoint(
1158
1167
  "/admin/streampay/subscriptions/:id/cancel",
1159
1168
  {
@@ -1170,7 +1179,7 @@ function buildSubscriptionsEndpoints(client, adminOptions) {
1170
1179
  await applySubscriptionProjection(
1171
1180
  getAdapter(ctx),
1172
1181
  result,
1173
- ctx.context.logger,
1182
+ getLogger(ctx),
1174
1183
  "adminCancelSubscription"
1175
1184
  );
1176
1185
  return ctx.json(result);
@@ -1181,16 +1190,11 @@ function buildSubscriptionsEndpoints(client, adminOptions) {
1181
1190
  userMessage: "StreamPay subscription cancellation failed."
1182
1191
  },
1183
1192
  err,
1184
- ctx.context.logger
1193
+ getLogger(ctx)
1185
1194
  );
1186
1195
  }
1187
1196
  }
1188
1197
  ),
1189
- /**
1190
- * Admin-initiated freeze. Creates a new freeze window on a
1191
- * subscription. Body matches `FreezeSubscriptionCreateRequest`
1192
- * from the SDK. Returns the created `FreezeSubscriptionBase`.
1193
- */
1194
1198
  adminFreezeSubscription: api.createAuthEndpoint(
1195
1199
  "/admin/streampay/subscriptions/:id/freeze",
1196
1200
  {
@@ -1208,7 +1212,7 @@ function buildSubscriptionsEndpoints(client, adminOptions) {
1208
1212
  client,
1209
1213
  getAdapter(ctx),
1210
1214
  subscriptionId,
1211
- ctx.context.logger,
1215
+ getLogger(ctx),
1212
1216
  "adminFreezeSubscription"
1213
1217
  );
1214
1218
  return ctx.json(freeze);
@@ -1219,17 +1223,11 @@ function buildSubscriptionsEndpoints(client, adminOptions) {
1219
1223
  userMessage: "StreamPay subscription freeze failed."
1220
1224
  },
1221
1225
  err,
1222
- ctx.context.logger
1226
+ getLogger(ctx)
1223
1227
  );
1224
1228
  }
1225
1229
  }
1226
1230
  ),
1227
- /**
1228
- * List all freeze windows attached to a subscription. Useful for
1229
- * UIs that show "this sub is frozen X times" or for the
1230
- * adminDeleteFreeze / adminUpdateFreeze flows below that need a
1231
- * freeze id.
1232
- */
1233
1231
  adminListSubscriptionFreezes: api.createAuthEndpoint(
1234
1232
  "/admin/streampay/subscriptions/:id/freeze",
1235
1233
  {
@@ -1245,18 +1243,11 @@ function buildSubscriptionsEndpoints(client, adminOptions) {
1245
1243
  toAPIError(
1246
1244
  `StreamPay listSubscriptionFreezes failed for subscription=${ctx.params.id}:`,
1247
1245
  err,
1248
- ctx.context.logger
1246
+ getLogger(ctx)
1249
1247
  );
1250
1248
  }
1251
1249
  }
1252
1250
  ),
1253
- /**
1254
- * Update an existing freeze window (shift start/end, change notes).
1255
- * Matches SDK's `updateSubscriptionFreeze` which takes
1256
- * `FreezeSubscriptionUpdateRequest` — note that
1257
- * `freeze_start_datetime` is REQUIRED on update even if it doesn't
1258
- * change (per OpenAPI schema).
1259
- */
1260
1251
  adminUpdateSubscriptionFreeze: api.createAuthEndpoint(
1261
1252
  "/admin/streampay/subscriptions/:id/freeze/:freezeId",
1262
1253
  {
@@ -1274,7 +1265,7 @@ function buildSubscriptionsEndpoints(client, adminOptions) {
1274
1265
  client,
1275
1266
  getAdapter(ctx),
1276
1267
  subscriptionId,
1277
- ctx.context.logger,
1268
+ getLogger(ctx),
1278
1269
  "adminUpdateSubscriptionFreeze"
1279
1270
  );
1280
1271
  return ctx.json(freeze);
@@ -1285,20 +1276,11 @@ function buildSubscriptionsEndpoints(client, adminOptions) {
1285
1276
  userMessage: "StreamPay freeze update failed."
1286
1277
  },
1287
1278
  err,
1288
- ctx.context.logger
1279
+ getLogger(ctx)
1289
1280
  );
1290
1281
  }
1291
1282
  }
1292
1283
  ),
1293
- /**
1294
- * Delete (unfreeze) a specific freeze window. This is how you
1295
- * "unfreeze" as an admin: find the active freeze id via
1296
- * adminListSubscriptionFreezes, then DELETE it.
1297
- *
1298
- * Returns `{ deleted: true }` on success — the SDK's
1299
- * `deleteSubscriptionFreeze` returns `void`, so we synthesize a
1300
- * response body for client feedback.
1301
- */
1302
1284
  adminDeleteSubscriptionFreeze: api.createAuthEndpoint(
1303
1285
  "/admin/streampay/subscriptions/:id/freeze/:freezeId",
1304
1286
  {
@@ -1315,7 +1297,7 @@ function buildSubscriptionsEndpoints(client, adminOptions) {
1315
1297
  client,
1316
1298
  getAdapter(ctx),
1317
1299
  subscriptionId,
1318
- ctx.context.logger,
1300
+ getLogger(ctx),
1319
1301
  "adminDeleteSubscriptionFreeze"
1320
1302
  );
1321
1303
  return ctx.json({ deleted: true });
@@ -1326,7 +1308,7 @@ function buildSubscriptionsEndpoints(client, adminOptions) {
1326
1308
  userMessage: "StreamPay freeze delete failed."
1327
1309
  },
1328
1310
  err,
1329
- ctx.context.logger
1311
+ getLogger(ctx)
1330
1312
  );
1331
1313
  }
1332
1314
  }
@@ -1352,7 +1334,7 @@ function buildConsumersEndpoints(client, adminOptions) {
1352
1334
  const response = await client.listConsumers(params);
1353
1335
  return ctx.json(response);
1354
1336
  } catch (err) {
1355
- toAPIError("StreamPay listConsumers failed.", err, ctx.context.logger);
1337
+ toAPIError("StreamPay listConsumers failed.", err, getLogger(ctx));
1356
1338
  }
1357
1339
  }
1358
1340
  ),
@@ -1371,7 +1353,7 @@ function buildConsumersEndpoints(client, adminOptions) {
1371
1353
  toAPIError(
1372
1354
  `StreamPay getConsumer failed for consumer=${ctx.params.id}:`,
1373
1355
  err,
1374
- ctx.context.logger
1356
+ getLogger(ctx)
1375
1357
  );
1376
1358
  }
1377
1359
  }
@@ -1394,14 +1376,11 @@ function buildConsumersEndpoints(client, adminOptions) {
1394
1376
  toAPIError(
1395
1377
  `StreamPay updateConsumer failed for consumer=${consumerId}:`,
1396
1378
  err,
1397
- ctx.context.logger
1379
+ getLogger(ctx)
1398
1380
  );
1399
1381
  }
1400
1382
  }
1401
1383
  ),
1402
- // Delete on StreamPay AND clear the `streampayConsumerId` link so
1403
- // the next checkout lazy-creates instead of 404'ing. deleteConsumer
1404
- // 404 is treated as success (race); a failed link-clear only logs.
1405
1384
  adminDeleteConsumer: api.createAuthEndpoint(
1406
1385
  "/admin/streampay/consumers/:id",
1407
1386
  {
@@ -1422,7 +1401,7 @@ function buildConsumersEndpoints(client, adminOptions) {
1422
1401
  toAPIError(
1423
1402
  `StreamPay getConsumer failed for consumer=${consumerId}:`,
1424
1403
  err,
1425
- ctx.context.logger
1404
+ getLogger(ctx)
1426
1405
  );
1427
1406
  }
1428
1407
  try {
@@ -1432,7 +1411,7 @@ function buildConsumersEndpoints(client, adminOptions) {
1432
1411
  toAPIError(
1433
1412
  `StreamPay deleteConsumer failed for consumer=${consumerId}:`,
1434
1413
  err,
1435
- ctx.context.logger
1414
+ getLogger(ctx)
1436
1415
  );
1437
1416
  }
1438
1417
  }
@@ -1442,7 +1421,7 @@ function buildConsumersEndpoints(client, adminOptions) {
1442
1421
  streampayConsumerId: null
1443
1422
  });
1444
1423
  } catch (err) {
1445
- ctx.context.logger.error(
1424
+ getLogger(ctx).error(
1446
1425
  `StreamPay admin delete: link clear failed for user=${externalId} consumer=${consumerId}: ${formatStreamPayError(err)}`
1447
1426
  );
1448
1427
  }
@@ -1470,7 +1449,7 @@ function buildInvoicesEndpoints(client, adminOptions) {
1470
1449
  const response = await client.listInvoices(params);
1471
1450
  return ctx.json(response);
1472
1451
  } catch (err) {
1473
- toAPIError("StreamPay listInvoices failed.", err, ctx.context.logger);
1452
+ toAPIError("StreamPay listInvoices failed.", err, getLogger(ctx));
1474
1453
  }
1475
1454
  }
1476
1455
  ),
@@ -1489,7 +1468,7 @@ function buildInvoicesEndpoints(client, adminOptions) {
1489
1468
  toAPIError(
1490
1469
  `StreamPay getInvoice failed for invoice=${ctx.params.id}:`,
1491
1470
  err,
1492
- ctx.context.logger
1471
+ getLogger(ctx)
1493
1472
  );
1494
1473
  }
1495
1474
  }
@@ -1512,7 +1491,7 @@ function buildProductsEndpoints(client, adminOptions) {
1512
1491
  const product = await client.createProduct(input);
1513
1492
  return ctx.json(product);
1514
1493
  } catch (err) {
1515
- toAPIError("StreamPay createProduct failed.", err, ctx.context.logger);
1494
+ toAPIError("StreamPay createProduct failed.", err, getLogger(ctx));
1516
1495
  }
1517
1496
  }
1518
1497
  ),
@@ -1532,7 +1511,7 @@ function buildProductsEndpoints(client, adminOptions) {
1532
1511
  const response = await client.listProducts(params);
1533
1512
  return ctx.json(response);
1534
1513
  } catch (err) {
1535
- toAPIError("StreamPay listProducts failed.", err, ctx.context.logger);
1514
+ toAPIError("StreamPay listProducts failed.", err, getLogger(ctx));
1536
1515
  }
1537
1516
  }
1538
1517
  ),
@@ -1551,7 +1530,7 @@ function buildProductsEndpoints(client, adminOptions) {
1551
1530
  toAPIError(
1552
1531
  `StreamPay getProduct failed for product=${ctx.params.id}:`,
1553
1532
  err,
1554
- ctx.context.logger
1533
+ getLogger(ctx)
1555
1534
  );
1556
1535
  }
1557
1536
  }
@@ -1574,7 +1553,7 @@ function buildProductsEndpoints(client, adminOptions) {
1574
1553
  toAPIError(
1575
1554
  `StreamPay updateProduct failed for product=${productId}:`,
1576
1555
  err,
1577
- ctx.context.logger
1556
+ getLogger(ctx)
1578
1557
  );
1579
1558
  }
1580
1559
  }
@@ -1595,7 +1574,7 @@ function buildProductsEndpoints(client, adminOptions) {
1595
1574
  toAPIError(
1596
1575
  `StreamPay deleteProduct failed for product=${ctx.params.id}:`,
1597
1576
  err,
1598
- ctx.context.logger
1577
+ getLogger(ctx)
1599
1578
  );
1600
1579
  }
1601
1580
  }
@@ -1618,7 +1597,7 @@ function buildCouponsEndpoints(client, adminOptions) {
1618
1597
  const coupon = await client.createCoupon(input);
1619
1598
  return ctx.json(coupon);
1620
1599
  } catch (err) {
1621
- toAPIError("StreamPay createCoupon failed.", err, ctx.context.logger);
1600
+ toAPIError("StreamPay createCoupon failed.", err, getLogger(ctx));
1622
1601
  }
1623
1602
  }
1624
1603
  ),
@@ -1638,7 +1617,7 @@ function buildCouponsEndpoints(client, adminOptions) {
1638
1617
  const response = await client.listCoupons(params);
1639
1618
  return ctx.json(response);
1640
1619
  } catch (err) {
1641
- toAPIError("StreamPay listCoupons failed.", err, ctx.context.logger);
1620
+ toAPIError("StreamPay listCoupons failed.", err, getLogger(ctx));
1642
1621
  }
1643
1622
  }
1644
1623
  ),
@@ -1657,7 +1636,7 @@ function buildCouponsEndpoints(client, adminOptions) {
1657
1636
  toAPIError(
1658
1637
  `StreamPay getCoupon failed for coupon=${ctx.params.id}:`,
1659
1638
  err,
1660
- ctx.context.logger
1639
+ getLogger(ctx)
1661
1640
  );
1662
1641
  }
1663
1642
  }
@@ -1677,11 +1656,7 @@ function buildCouponsEndpoints(client, adminOptions) {
1677
1656
  const coupon = await client.updateCoupon(couponId, patch);
1678
1657
  return ctx.json(coupon);
1679
1658
  } catch (err) {
1680
- toAPIError(
1681
- `StreamPay updateCoupon failed for coupon=${couponId}:`,
1682
- err,
1683
- ctx.context.logger
1684
- );
1659
+ toAPIError(`StreamPay updateCoupon failed for coupon=${couponId}:`, err, getLogger(ctx));
1685
1660
  }
1686
1661
  }
1687
1662
  ),
@@ -1701,7 +1676,7 @@ function buildCouponsEndpoints(client, adminOptions) {
1701
1676
  toAPIError(
1702
1677
  `StreamPay deleteCoupon failed for coupon=${ctx.params.id}:`,
1703
1678
  err,
1704
- ctx.context.logger
1679
+ getLogger(ctx)
1705
1680
  );
1706
1681
  }
1707
1682
  }
@@ -1726,7 +1701,7 @@ function buildPaymentLinksEndpoints(client, adminOptions) {
1726
1701
  const response = await client.listPaymentLinks(params);
1727
1702
  return ctx.json(response);
1728
1703
  } catch (err) {
1729
- toAPIError("StreamPay listPaymentLinks failed.", err, ctx.context.logger);
1704
+ toAPIError("StreamPay listPaymentLinks failed.", err, getLogger(ctx));
1730
1705
  }
1731
1706
  }
1732
1707
  ),
@@ -1745,7 +1720,7 @@ function buildPaymentLinksEndpoints(client, adminOptions) {
1745
1720
  toAPIError(
1746
1721
  `StreamPay getPaymentLink failed for payment_link=${ctx.params.id}:`,
1747
1722
  err,
1748
- ctx.context.logger
1723
+ getLogger(ctx)
1749
1724
  );
1750
1725
  }
1751
1726
  }
@@ -1835,7 +1810,7 @@ function buildWebhookEventsEndpoints(adminOptions, registry) {
1835
1810
  toAPIError(
1836
1811
  `StreamPay replayWebhookEvent failed for event=${ctx.params.eventId}:`,
1837
1812
  err,
1838
- ctx.context.logger
1813
+ getLogger(ctx)
1839
1814
  );
1840
1815
  }
1841
1816
  }
@@ -1897,7 +1872,6 @@ var CheckoutBody = zod.z.object({
1897
1872
  ]).optional(),
1898
1873
  slug: zod.z.string().optional(),
1899
1874
  referenceId: zod.z.string().optional(),
1900
- consumerId: zod.z.string().uuid().optional(),
1901
1875
  name: zod.z.string().min(1).optional(),
1902
1876
  description: zod.z.string().optional(),
1903
1877
  metadata: zod.z.record(zod.z.string(), zod.z.union([zod.z.string(), zod.z.number(), zod.z.boolean()])).optional(),
@@ -1939,8 +1913,7 @@ function resolveRedirectUrl(urlOrPath, request, baseURL) {
1939
1913
  if (!urlOrPath) return void 0;
1940
1914
  return new URL(urlOrPath, request?.url ?? baseURL).toString();
1941
1915
  }
1942
- async function resolveConsumerId(options, ctx, body, user) {
1943
- if (body.consumerId) return body.consumerId;
1916
+ async function resolveConsumerId(options, ctx, user) {
1944
1917
  if (!user || user.isAnonymous) return null;
1945
1918
  const { consumerId } = await ensureConsumerForUser(options, ctx, user);
1946
1919
  return consumerId;
@@ -1971,7 +1944,7 @@ var checkout = (checkoutOptions = {}) => (options) => {
1971
1944
  }
1972
1945
  }
1973
1946
  const items = await resolveProducts(ctx.body, checkoutOptions);
1974
- const consumerId = await resolveConsumerId(options, ctx, ctx.body, sessionUser);
1947
+ const consumerId = await resolveConsumerId(options, ctx, sessionUser);
1975
1948
  const successUrl = resolveRedirectUrl(
1976
1949
  ctx.body.successUrl ?? checkoutOptions.successUrl,
1977
1950
  ctx.request,
@@ -2027,11 +2000,11 @@ var checkout = (checkoutOptions = {}) => (options) => {
2027
2000
  } catch (err) {
2028
2001
  toAPIError(
2029
2002
  {
2030
- logPrefix: "StreamPay checkout creation failed:",
2003
+ logPrefix: "checkout creation failed:",
2031
2004
  userMessage: "StreamPay checkout creation failed."
2032
2005
  },
2033
2006
  err,
2034
- ctx.context.logger
2007
+ getLogger(ctx)
2035
2008
  );
2036
2009
  }
2037
2010
  }
@@ -2061,7 +2034,7 @@ var portal = ({ pageSize } = {}) => (options) => {
2061
2034
  const consumer = await client.getConsumer(consumerId);
2062
2035
  return ctx.json({ hasConsumer: true, consumer });
2063
2036
  } catch (err) {
2064
- toAPIError("StreamPay getConsumer failed.", err, ctx.context.logger);
2037
+ toAPIError("StreamPay getConsumer failed.", err, getLogger(ctx));
2065
2038
  }
2066
2039
  }
2067
2040
  ),
@@ -2080,7 +2053,7 @@ var portal = ({ pageSize } = {}) => (options) => {
2080
2053
  });
2081
2054
  return ctx.json({ hasConsumer: true, data: response.data ?? [] });
2082
2055
  } catch (err) {
2083
- toAPIError("StreamPay listSubscriptions failed.", err, ctx.context.logger);
2056
+ toAPIError("StreamPay listSubscriptions failed.", err, getLogger(ctx));
2084
2057
  }
2085
2058
  }
2086
2059
  ),
@@ -2099,7 +2072,7 @@ var portal = ({ pageSize } = {}) => (options) => {
2099
2072
  });
2100
2073
  return ctx.json({ hasConsumer: true, data: response.data ?? [] });
2101
2074
  } catch (err) {
2102
- toAPIError("StreamPay listInvoices failed.", err, ctx.context.logger);
2075
+ toAPIError("StreamPay listInvoices failed.", err, getLogger(ctx));
2103
2076
  }
2104
2077
  }
2105
2078
  )
@@ -2208,33 +2181,10 @@ var SuccessQuery = zod.z.object({
2208
2181
  var CancelBody = zod.z.object({
2209
2182
  subscriptionId: zod.z.string().uuid(),
2210
2183
  cancelRelatedInvoices: zod.z.boolean().optional(),
2211
- /**
2212
- * When `true`, schedule the cancellation to take effect at the end
2213
- * of the current billing period instead of terminating immediately.
2214
- * Implemented via StreamPay's `PATCH /subscriptions/:id` with
2215
- * `until_cycle_number = current_cycle_number` (see OpenAPI
2216
- * `SubscriptionUpdate.until_cycle_number`). The customer retains
2217
- * access through `periodEnd`; status stays `active` until the
2218
- * `SUBSCRIPTION_CANCEL_AT_PERIOD_END` webhook lands.
2219
- */
2220
2184
  cancelAtPeriodEnd: zod.z.boolean().optional()
2221
2185
  });
2222
2186
  var ChangePlanBody = zod.z.object({
2223
- /** Target plan name, must be declared in `subscriptions({ plans })`. */
2224
2187
  plan: zod.z.string().min(1),
2225
- /**
2226
- * `at_period_end` (default) — old plan keeps serving until
2227
- * `periodEnd`, then the new plan's payment link is presented via a
2228
- * freshly spawned `incomplete` row. Safer. Customer pays only what
2229
- * they would on a normal renewal cycle.
2230
- *
2231
- * `immediate` — PATCH the existing StreamPay subscription's items
2232
- * to the new plan's productId. No proration — StreamPay does not
2233
- * expose proration on PATCH. The current cycle's paid invoice is
2234
- * NOT refunded; the customer starts paying the new price from the
2235
- * next cycle. Use for "upgrade now, I'll pay more later" UX where
2236
- * proration is acceptable.
2237
- */
2238
2188
  mode: zod.z.enum(["at_period_end", "immediate"]).optional(),
2239
2189
  successUrl: zod.z.string().url().optional(),
2240
2190
  failureUrl: zod.z.string().url().optional()
@@ -2407,17 +2357,15 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
2407
2357
  } catch (err) {
2408
2358
  toAPIError(
2409
2359
  {
2410
- logPrefix: `StreamPay upgradeSubscription failed for plan=${plan.name} ref=${referenceId}:`,
2360
+ logPrefix: `upgradeSubscription failed for plan=${plan.name} ref=${referenceId}:`,
2411
2361
  userMessage: "Failed to start subscription checkout."
2412
2362
  },
2413
2363
  err,
2414
- ctx.context.logger
2364
+ getLogger(ctx)
2415
2365
  );
2416
2366
  }
2417
2367
  if (!url) {
2418
- ctx.context.logger.error(
2419
- `StreamPay createPaymentLink returned link=${paymentLinkId} with no url.`
2420
- );
2368
+ getLogger(ctx).error(`createPaymentLink returned link=${paymentLinkId} with no url.`);
2421
2369
  throw new api.APIError("INTERNAL_SERVER_ERROR", {
2422
2370
  message: "Payment link was created but no URL was returned."
2423
2371
  });
@@ -2480,12 +2428,17 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
2480
2428
  return ctx.json({ subscription: row, synced: false });
2481
2429
  }
2482
2430
  try {
2431
+ const plans = await plansRef();
2432
+ const plan = plans.byName.get(row.plan);
2433
+ if (!plan) {
2434
+ getLogger(ctx).warn(
2435
+ `subscriptionSuccess: plan "${row.plan}" is no longer configured \u2014 skipping fallback sync for row=${row.id}.`
2436
+ );
2437
+ return ctx.json({ subscription: row, synced: false });
2438
+ }
2483
2439
  const list = await client.listSubscriptions({ page: 1, size: 100 });
2484
2440
  const match = list.data?.find(
2485
- (sub) => sub.organization_consumer_id === row.streampayConsumerId && Array.isArray(sub.items) && sub.items.some((item) => {
2486
- 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;
2487
- return typeof productId === "string" && productId.length > 0 && row.plan && sub.status !== "CANCELED";
2488
- })
2441
+ (sub) => sub.organization_consumer_id === row.streampayConsumerId && sub.status !== "CANCELED" && Array.isArray(sub.items) && sub.items.some((item) => subscriptionItemProductId(item) === plan.productId)
2489
2442
  );
2490
2443
  if (!match?.id) {
2491
2444
  return ctx.json({ subscription: row, synced: false });
@@ -2512,9 +2465,9 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
2512
2465
  return ctx.json({ subscription: updated ?? row, synced: true });
2513
2466
  } catch (err) {
2514
2467
  toAPIError(
2515
- `StreamPay subscriptionSuccess fallback sync failed for row=${row.id}:`,
2468
+ `subscriptionSuccess fallback sync failed for row=${row.id}:`,
2516
2469
  err,
2517
- ctx.context.logger
2470
+ getLogger(ctx)
2518
2471
  );
2519
2472
  }
2520
2473
  }
@@ -2574,11 +2527,11 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
2574
2527
  } catch (err) {
2575
2528
  toAPIError(
2576
2529
  {
2577
- logPrefix: `StreamPay cancelAtPeriodEnd failed for row=${row.id}:`,
2530
+ logPrefix: `cancelAtPeriodEnd failed for row=${row.id}:`,
2578
2531
  userMessage: "Subscription cancel-at-period-end failed."
2579
2532
  },
2580
2533
  err,
2581
- ctx.context.logger
2534
+ getLogger(ctx)
2582
2535
  );
2583
2536
  }
2584
2537
  }
@@ -2591,18 +2544,18 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
2591
2544
  client,
2592
2545
  adapter,
2593
2546
  row.streampaySubscriptionId,
2594
- ctx.context.logger,
2547
+ getLogger(ctx),
2595
2548
  "cancelSubscription"
2596
2549
  );
2597
2550
  return ctx.json(result);
2598
2551
  } catch (err) {
2599
2552
  toAPIError(
2600
2553
  {
2601
- logPrefix: `StreamPay cancelSubscription failed for row=${row.id}:`,
2554
+ logPrefix: `cancelSubscription failed for row=${row.id}:`,
2602
2555
  userMessage: "Subscription cancellation failed."
2603
2556
  },
2604
2557
  err,
2605
- ctx.context.logger
2558
+ getLogger(ctx)
2606
2559
  );
2607
2560
  }
2608
2561
  }
@@ -2680,7 +2633,7 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
2680
2633
  client,
2681
2634
  adapter,
2682
2635
  row.streampaySubscriptionId,
2683
- ctx.context.logger,
2636
+ getLogger(ctx),
2684
2637
  "changeSubscriptionPlan"
2685
2638
  );
2686
2639
  return ctx.json({
@@ -2691,11 +2644,11 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
2691
2644
  } catch (err) {
2692
2645
  toAPIError(
2693
2646
  {
2694
- logPrefix: `StreamPay change-plan (immediate) failed for row=${row.id}:`,
2647
+ logPrefix: `change-plan (immediate) failed for row=${row.id}:`,
2695
2648
  userMessage: "Plan change failed."
2696
2649
  },
2697
2650
  err,
2698
- ctx.context.logger
2651
+ getLogger(ctx)
2699
2652
  );
2700
2653
  }
2701
2654
  }
@@ -2763,11 +2716,11 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
2763
2716
  } catch (err) {
2764
2717
  toAPIError(
2765
2718
  {
2766
- logPrefix: `StreamPay change-plan (at_period_end) failed for row=${row.id}:`,
2719
+ logPrefix: `change-plan (at_period_end) failed for row=${row.id}:`,
2767
2720
  userMessage: "Plan change scheduling failed."
2768
2721
  },
2769
2722
  err,
2770
- ctx.context.logger
2723
+ getLogger(ctx)
2771
2724
  );
2772
2725
  }
2773
2726
  }
@@ -2816,18 +2769,18 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
2816
2769
  client,
2817
2770
  adapter,
2818
2771
  row.streampaySubscriptionId,
2819
- ctx.context.logger,
2772
+ getLogger(ctx),
2820
2773
  "freezeSubscription"
2821
2774
  );
2822
2775
  return ctx.json(freeze);
2823
2776
  } catch (err) {
2824
2777
  toAPIError(
2825
2778
  {
2826
- logPrefix: `StreamPay freezeSubscription failed for row=${row.id}:`,
2779
+ logPrefix: `freezeSubscription failed for row=${row.id}:`,
2827
2780
  userMessage: "Subscription freeze failed."
2828
2781
  },
2829
2782
  err,
2830
- ctx.context.logger
2783
+ getLogger(ctx)
2831
2784
  );
2832
2785
  }
2833
2786
  }
@@ -2885,18 +2838,18 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
2885
2838
  client,
2886
2839
  adapter,
2887
2840
  row.streampaySubscriptionId,
2888
- ctx.context.logger,
2841
+ getLogger(ctx),
2889
2842
  "unfreezeSubscription"
2890
2843
  );
2891
2844
  return ctx.json({ unfrozen: true });
2892
2845
  } catch (err) {
2893
2846
  toAPIError(
2894
2847
  {
2895
- logPrefix: `StreamPay unfreezeSubscription failed for row=${row.id}:`,
2848
+ logPrefix: `unfreezeSubscription failed for row=${row.id}:`,
2896
2849
  userMessage: "Subscription unfreeze failed."
2897
2850
  },
2898
2851
  err,
2899
- ctx.context.logger
2852
+ getLogger(ctx)
2900
2853
  );
2901
2854
  }
2902
2855
  }
@@ -3092,14 +3045,11 @@ var webhookEventTable = {
3092
3045
  type: "string",
3093
3046
  required: true
3094
3047
  },
3095
- /** Last activity (insert/retry/completion/dead-letter).
3096
- * For `completed` = finished-at; for `pending` = last attempt. */
3097
3048
  processedAt: {
3098
3049
  type: "date",
3099
3050
  required: true,
3100
3051
  index: true
3101
3052
  },
3102
- /** Defaults to `completed` so pre-state-machine rows still dedupe. */
3103
3053
  status: {
3104
3054
  type: "string",
3105
3055
  required: false,
@@ -3170,8 +3120,8 @@ function subscriptions(subsOptions) {
3170
3120
  } catch (err) {
3171
3121
  if (classifyWebhookFailure(err) === "PERMANENT") {
3172
3122
  const msg = err instanceof Error ? err.message : String(err);
3173
- ctx.context.logger.warn(
3174
- `StreamPay subscription sync: permanent failure on event=${payload.event_type} entity=${payload.entity_id}: ${msg}`
3123
+ getLogger(ctx).warn(
3124
+ `subscription sync: permanent failure on event=${payload.event_type} entity=${payload.entity_id}: ${msg}`
3175
3125
  );
3176
3126
  return;
3177
3127
  }
@@ -3228,7 +3178,6 @@ function subscriptions(subsOptions) {
3228
3178
  async function dispatchWebhook(payload, handlers) {
3229
3179
  if (handlers.onPayload) await handlers.onPayload(payload);
3230
3180
  switch (payload.event_type) {
3231
- // Payment
3232
3181
  case "PAYMENT_SUCCEEDED":
3233
3182
  await handlers.onPaymentSucceeded?.(payload);
3234
3183
  return;
@@ -3244,7 +3193,6 @@ async function dispatchWebhook(payload, handlers) {
3244
3193
  case "PAYMENT_MARKED_AS_PAID":
3245
3194
  await handlers.onPaymentMarkedAsPaid?.(payload);
3246
3195
  return;
3247
- // Invoice
3248
3196
  case "INVOICE_CREATED":
3249
3197
  await handlers.onInvoiceCreated?.(payload);
3250
3198
  return;
@@ -3266,7 +3214,6 @@ async function dispatchWebhook(payload, handlers) {
3266
3214
  case "INVOICE_UPDATED":
3267
3215
  await handlers.onInvoiceUpdated?.(payload);
3268
3216
  return;
3269
- // Subscription
3270
3217
  case "SUBSCRIPTION_CREATED":
3271
3218
  await handlers.onSubscriptionCreated?.(payload);
3272
3219
  return;
@@ -3300,7 +3247,6 @@ async function dispatchWebhook(payload, handlers) {
3300
3247
  case "SUBSCRIPTION_FREEZE_CANCEL":
3301
3248
  await handlers.onSubscriptionFreezeCancel?.(payload);
3302
3249
  return;
3303
- // Payment Link
3304
3250
  case "PAYMENT_LINK_PAY_ATTEMPT_FAILED":
3305
3251
  await handlers.onPaymentLinkPayAttemptFailed?.(payload);
3306
3252
  return;
@@ -3384,9 +3330,10 @@ var webhooks = (webhooksOptions) => (_options, registry) => {
3384
3330
  cloneRequest: true
3385
3331
  },
3386
3332
  async (ctx) => {
3333
+ const logger2 = getLogger(ctx);
3387
3334
  const hasSecret = typeof secret === "string" ? secret.length > 0 : secret.some((s) => s.length > 0);
3388
3335
  if (!hasSecret) {
3389
- ctx.context.logger.error("StreamPay webhook secret is not configured.");
3336
+ logger2.error("webhook secret is not configured.");
3390
3337
  throw new api.APIError("INTERNAL_SERVER_ERROR", {
3391
3338
  message: "StreamPay webhook secret is not configured."
3392
3339
  });
@@ -3405,7 +3352,7 @@ var webhooks = (webhooksOptions) => (_options, registry) => {
3405
3352
  });
3406
3353
  } catch (err) {
3407
3354
  if (err instanceof StreamPayWebhookError) {
3408
- ctx.context.logger.warn(`StreamPay webhook rejected: ${err.reason}`);
3355
+ logger2.warn(`webhook rejected: ${err.reason}`);
3409
3356
  throw new api.APIError(toErrorCode(err.reason), {
3410
3357
  message: `Webhook verification failed: ${err.reason}`
3411
3358
  });
@@ -3434,7 +3381,7 @@ var webhooks = (webhooksOptions) => (_options, registry) => {
3434
3381
  });
3435
3382
  } catch (err) {
3436
3383
  const message = err instanceof Error ? err.message : String(err);
3437
- ctx.context.logger.error(`StreamPay subscription sync failed: ${message}`);
3384
+ logger2.error(`subscription sync failed: ${message}`);
3438
3385
  throw new api.APIError("INTERNAL_SERVER_ERROR", {
3439
3386
  message: "Webhook sync failed. See server logs."
3440
3387
  });
@@ -3444,7 +3391,7 @@ var webhooks = (webhooksOptions) => (_options, registry) => {
3444
3391
  await dispatchWebhook(payload, handlers);
3445
3392
  } catch (err) {
3446
3393
  const message = err instanceof Error ? err.message : String(err);
3447
- ctx.context.logger.error(`StreamPay webhook handler failed: ${message}`);
3394
+ logger2.error(`webhook handler failed: ${message}`);
3448
3395
  throw new api.APIError("INTERNAL_SERVER_ERROR", {
3449
3396
  message: "Webhook handler failed. See server logs."
3450
3397
  });
@@ -3489,8 +3436,8 @@ var onBeforeUserCreate = (options) => async (user, context) => {
3489
3436
  return { data: { streampayConsumerId: reusedId } };
3490
3437
  }
3491
3438
  }
3492
- context.context.logger.error(
3493
- `StreamPay consumer creation failed for user=${user.id ?? "<pre-insert>"}: ${formatStreamPayError(err)}`
3439
+ getLogger(context).error(
3440
+ `consumer creation failed for user=${user.id ?? "<pre-insert>"}: ${formatStreamPayError(err)}`
3494
3441
  );
3495
3442
  throw new api.APIError("INTERNAL_SERVER_ERROR", {
3496
3443
  message: "StreamPay consumer provisioning failed. Please try again."
@@ -3507,8 +3454,8 @@ var onAfterUserCreate = (options) => async (user, context) => {
3507
3454
  external_id: sessionUser.id
3508
3455
  });
3509
3456
  } catch (err) {
3510
- context.context.logger.error(
3511
- `StreamPay consumer external_id link failed for user=${sessionUser.id} consumer=${sessionUser.streampayConsumerId}: ${formatStreamPayError(err)}`
3457
+ getLogger(context).error(
3458
+ `consumer external_id link failed for user=${sessionUser.id} consumer=${sessionUser.streampayConsumerId}: ${formatStreamPayError(err)}`
3512
3459
  );
3513
3460
  }
3514
3461
  };
@@ -3531,8 +3478,8 @@ var onUserUpdate = (options) => async (user, context) => {
3531
3478
  await options.client.updateConsumer(sessionUser.streampayConsumerId, patch);
3532
3479
  } catch (err) {
3533
3480
  if (isNotFoundError(err)) {
3534
- context.context.logger.error(
3535
- `StreamPay consumer ${sessionUser.streampayConsumerId} not found for user=${sessionUser.id}; clearing stale link for re-provisioning.`
3481
+ getLogger(context).error(
3482
+ `consumer ${sessionUser.streampayConsumerId} not found for user=${sessionUser.id}; clearing stale link for re-provisioning.`
3536
3483
  );
3537
3484
  if (hasInternalAdapter(context)) {
3538
3485
  try {
@@ -3540,15 +3487,15 @@ var onUserUpdate = (options) => async (user, context) => {
3540
3487
  streampayConsumerId: null
3541
3488
  });
3542
3489
  } catch (clearErr) {
3543
- context.context.logger.error(
3544
- `StreamPay stale-link clear failed for user=${sessionUser.id}: ${formatStreamPayError(clearErr)}`
3490
+ getLogger(context).error(
3491
+ `stale-link clear failed for user=${sessionUser.id}: ${formatStreamPayError(clearErr)}`
3545
3492
  );
3546
3493
  }
3547
3494
  }
3548
3495
  return;
3549
3496
  }
3550
- context.context.logger.error(
3551
- `StreamPay consumer update failed for user=${sessionUser.id} consumer=${sessionUser.streampayConsumerId}: ${formatStreamPayError(err)}`
3497
+ getLogger(context).error(
3498
+ `consumer update failed for user=${sessionUser.id} consumer=${sessionUser.streampayConsumerId}: ${formatStreamPayError(err)}`
3552
3499
  );
3553
3500
  }
3554
3501
  };
@@ -3561,15 +3508,15 @@ var onUserDelete = (options) => async (user, context) => {
3561
3508
  await options.client.deleteConsumer(sessionUser.streampayConsumerId);
3562
3509
  } catch (err) {
3563
3510
  if (isNotFoundError(err)) return;
3564
- context.context.logger.error(
3565
- `StreamPay consumer delete failed for user=${sessionUser.id} consumer=${sessionUser.streampayConsumerId}: ${formatStreamPayError(err)}`
3511
+ getLogger(context).error(
3512
+ `consumer delete failed for user=${sessionUser.id} consumer=${sessionUser.streampayConsumerId}: ${formatStreamPayError(err)}`
3566
3513
  );
3567
3514
  }
3568
3515
  };
3569
3516
 
3570
3517
  // package.json
3571
3518
  var package_default = {
3572
- version: "1.2.0"};
3519
+ version: "1.3.0"};
3573
3520
 
3574
3521
  // src/version.ts
3575
3522
  var version = package_default.version;