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