better-auth-streampay 3.0.0 → 3.0.2

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.d.cts CHANGED
@@ -1,5 +1,5 @@
1
- import { a as StreamPayClient } from './streampay-Cfl70SR_.cjs';
2
- export { $ as $ERROR_CODES, A as AdminOptions, b as AuthorizeReferenceContext, C as CheckoutBody, c as CheckoutCreatedContext, d as CheckoutOptions, e as CheckoutOverrides, f as CheckoutParams, g as CheckoutResolutionContext, h as ClaimExistingConsumerBy, i as ClaimExistingConsumerIdentifier, j as ConsumerCreateOverrides, D as DEFAULT_ACCESS_STATUSES, F as FeatureKey, L as LimitCheckResult, P as PLAN_NAME_METADATA_KEY, k as PluginAdapter, l as PortalOptions, R as REFERENCE_ID_METADATA_KEY, m as REFERENCE_TYPE_METADATA_KEY, n as ResolvedPlans, o as STREAMPAY_EVENT_TYPES, p as STREAMPAY_INVOICE_EVENT_TYPES, q as STREAMPAY_PAYMENT_EVENT_TYPES, r as STREAMPAY_PAYMENT_LINK_EVENT_TYPES, t as STREAMPAY_SUBSCRIPTION_EVENT_TYPES, u as SUBSCRIPTION_ROW_ID_METADATA_KEY, v as StreamPayCustomFieldDefinition, w as StreamPayCustomFieldsSchema, x as StreamPayEndpoints, y as StreamPayEntityType, S as StreamPayErrorCode, z as StreamPayEventType, B as StreamPayHookContext, G as StreamPayInvoiceEventType, H as StreamPayOptions, I as StreamPayPaymentEventType, J as StreamPayPaymentLinkEventType, K as StreamPayPlan, M as StreamPayPlanLike, N as StreamPayPlugin, O as StreamPayPluginRegistry, Q as StreamPayPlugins, T as StreamPayProduct, U as StreamPaySeatBilling, V as StreamPaySubscriptionEventType, W as StreamPayWebhookData, X as StreamPayWebhookEnvelope, Y as StreamPayWebhookPayload, Z as Subscription, _ as SubscriptionBillingStatus, a0 as SubscriptionCallback, a1 as SubscriptionCallbackData, a2 as SubscriptionCallbacks, a3 as SubscriptionReferenceType, a4 as SubscriptionStatus, a5 as SubscriptionsOptions, a6 as SyncContext, a7 as TrialEligibilityContext, a8 as WebhookEnvelopeHandler, a9 as WebhookHandler, aa as WebhookHandlers, ab as WebhookSyncFailure, ac as WebhooksOptions, ad as admin, ae as checkLimit, af as checkout, ag as classifyWebhookFailure, ah as dispatchWebhook, ai as hasFeature, aj as hasSubscriptionAccess, ak as isKnownStreamPayWebhookPayload, al as isStreamPayWebhookEnvelope, am as mapToErrorCode, an as portal, s as streampay, ao as subscriptionSlotKey, ap as subscriptions, aq as syncWebhookPayload, ar as webhooks } from './streampay-Cfl70SR_.cjs';
1
+ import { a as StreamPayClient } from './streampay-uhs67tYl.cjs';
2
+ export { $ as $ERROR_CODES, A as AdminOptions, b as AuthorizeReferenceContext, C as CheckoutBody, c as CheckoutCreatedContext, d as CheckoutOptions, e as CheckoutOverrides, f as CheckoutParams, g as CheckoutResolutionContext, h as ClaimExistingConsumerBy, i as ClaimExistingConsumerIdentifier, j as ConsumerCreateOverrides, D as DEFAULT_ACCESS_STATUSES, F as FeatureKey, L as LimitCheckResult, P as PLAN_NAME_METADATA_KEY, k as PluginAdapter, l as PortalOptions, R as REFERENCE_ID_METADATA_KEY, m as REFERENCE_TYPE_METADATA_KEY, n as ResolvedPlans, o as STREAMPAY_EVENT_TYPES, p as STREAMPAY_INVOICE_EVENT_TYPES, q as STREAMPAY_PAYMENT_EVENT_TYPES, r as STREAMPAY_PAYMENT_LINK_EVENT_TYPES, t as STREAMPAY_SUBSCRIPTION_EVENT_TYPES, u as SUBSCRIPTION_ROW_ID_METADATA_KEY, v as StreamPayCustomFieldDefinition, w as StreamPayCustomFieldsSchema, x as StreamPayEndpoints, y as StreamPayEntityType, S as StreamPayErrorCode, z as StreamPayEventType, B as StreamPayHookContext, G as StreamPayInvoiceEventType, H as StreamPayOptions, I as StreamPayPaymentEventType, J as StreamPayPaymentLinkEventType, K as StreamPayPlan, M as StreamPayPlanLike, N as StreamPayPlugin, O as StreamPayPluginRegistry, Q as StreamPayPlugins, T as StreamPayProduct, U as StreamPaySeatBilling, V as StreamPaySubscriptionEventType, W as StreamPayWebhookData, X as StreamPayWebhookEnvelope, Y as StreamPayWebhookPayload, Z as Subscription, _ as SubscriptionBillingStatus, a0 as SubscriptionCallback, a1 as SubscriptionCallbackData, a2 as SubscriptionCallbacks, a3 as SubscriptionReferenceType, a4 as SubscriptionStatus, a5 as SubscriptionsOptions, a6 as SyncContext, a7 as TrialEligibilityContext, a8 as WebhookEnvelopeHandler, a9 as WebhookHandler, aa as WebhookHandlers, ab as WebhookSyncFailure, ac as WebhooksOptions, ad as admin, ae as checkLimit, af as checkout, ag as classifyWebhookFailure, ah as dispatchWebhook, ai as hasFeature, aj as hasSubscriptionAccess, ak as isKnownStreamPayWebhookPayload, al as isStreamPayWebhookEnvelope, am as mapToErrorCode, an as portal, s as streampay, ao as subscriptionSlotKey, ap as subscriptions, aq as syncWebhookPayload, ar as webhooks } from './streampay-uhs67tYl.cjs';
3
3
  import { InvoiceDetailed, PaymentResponse, ConsumerResponse } from '@streamsdk/typescript';
4
4
  import 'better-auth';
5
5
  import 'zod';
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { a as StreamPayClient } from './streampay-Cfl70SR_.js';
2
- export { $ as $ERROR_CODES, A as AdminOptions, b as AuthorizeReferenceContext, C as CheckoutBody, c as CheckoutCreatedContext, d as CheckoutOptions, e as CheckoutOverrides, f as CheckoutParams, g as CheckoutResolutionContext, h as ClaimExistingConsumerBy, i as ClaimExistingConsumerIdentifier, j as ConsumerCreateOverrides, D as DEFAULT_ACCESS_STATUSES, F as FeatureKey, L as LimitCheckResult, P as PLAN_NAME_METADATA_KEY, k as PluginAdapter, l as PortalOptions, R as REFERENCE_ID_METADATA_KEY, m as REFERENCE_TYPE_METADATA_KEY, n as ResolvedPlans, o as STREAMPAY_EVENT_TYPES, p as STREAMPAY_INVOICE_EVENT_TYPES, q as STREAMPAY_PAYMENT_EVENT_TYPES, r as STREAMPAY_PAYMENT_LINK_EVENT_TYPES, t as STREAMPAY_SUBSCRIPTION_EVENT_TYPES, u as SUBSCRIPTION_ROW_ID_METADATA_KEY, v as StreamPayCustomFieldDefinition, w as StreamPayCustomFieldsSchema, x as StreamPayEndpoints, y as StreamPayEntityType, S as StreamPayErrorCode, z as StreamPayEventType, B as StreamPayHookContext, G as StreamPayInvoiceEventType, H as StreamPayOptions, I as StreamPayPaymentEventType, J as StreamPayPaymentLinkEventType, K as StreamPayPlan, M as StreamPayPlanLike, N as StreamPayPlugin, O as StreamPayPluginRegistry, Q as StreamPayPlugins, T as StreamPayProduct, U as StreamPaySeatBilling, V as StreamPaySubscriptionEventType, W as StreamPayWebhookData, X as StreamPayWebhookEnvelope, Y as StreamPayWebhookPayload, Z as Subscription, _ as SubscriptionBillingStatus, a0 as SubscriptionCallback, a1 as SubscriptionCallbackData, a2 as SubscriptionCallbacks, a3 as SubscriptionReferenceType, a4 as SubscriptionStatus, a5 as SubscriptionsOptions, a6 as SyncContext, a7 as TrialEligibilityContext, a8 as WebhookEnvelopeHandler, a9 as WebhookHandler, aa as WebhookHandlers, ab as WebhookSyncFailure, ac as WebhooksOptions, ad as admin, ae as checkLimit, af as checkout, ag as classifyWebhookFailure, ah as dispatchWebhook, ai as hasFeature, aj as hasSubscriptionAccess, ak as isKnownStreamPayWebhookPayload, al as isStreamPayWebhookEnvelope, am as mapToErrorCode, an as portal, s as streampay, ao as subscriptionSlotKey, ap as subscriptions, aq as syncWebhookPayload, ar as webhooks } from './streampay-Cfl70SR_.js';
1
+ import { a as StreamPayClient } from './streampay-uhs67tYl.js';
2
+ export { $ as $ERROR_CODES, A as AdminOptions, b as AuthorizeReferenceContext, C as CheckoutBody, c as CheckoutCreatedContext, d as CheckoutOptions, e as CheckoutOverrides, f as CheckoutParams, g as CheckoutResolutionContext, h as ClaimExistingConsumerBy, i as ClaimExistingConsumerIdentifier, j as ConsumerCreateOverrides, D as DEFAULT_ACCESS_STATUSES, F as FeatureKey, L as LimitCheckResult, P as PLAN_NAME_METADATA_KEY, k as PluginAdapter, l as PortalOptions, R as REFERENCE_ID_METADATA_KEY, m as REFERENCE_TYPE_METADATA_KEY, n as ResolvedPlans, o as STREAMPAY_EVENT_TYPES, p as STREAMPAY_INVOICE_EVENT_TYPES, q as STREAMPAY_PAYMENT_EVENT_TYPES, r as STREAMPAY_PAYMENT_LINK_EVENT_TYPES, t as STREAMPAY_SUBSCRIPTION_EVENT_TYPES, u as SUBSCRIPTION_ROW_ID_METADATA_KEY, v as StreamPayCustomFieldDefinition, w as StreamPayCustomFieldsSchema, x as StreamPayEndpoints, y as StreamPayEntityType, S as StreamPayErrorCode, z as StreamPayEventType, B as StreamPayHookContext, G as StreamPayInvoiceEventType, H as StreamPayOptions, I as StreamPayPaymentEventType, J as StreamPayPaymentLinkEventType, K as StreamPayPlan, M as StreamPayPlanLike, N as StreamPayPlugin, O as StreamPayPluginRegistry, Q as StreamPayPlugins, T as StreamPayProduct, U as StreamPaySeatBilling, V as StreamPaySubscriptionEventType, W as StreamPayWebhookData, X as StreamPayWebhookEnvelope, Y as StreamPayWebhookPayload, Z as Subscription, _ as SubscriptionBillingStatus, a0 as SubscriptionCallback, a1 as SubscriptionCallbackData, a2 as SubscriptionCallbacks, a3 as SubscriptionReferenceType, a4 as SubscriptionStatus, a5 as SubscriptionsOptions, a6 as SyncContext, a7 as TrialEligibilityContext, a8 as WebhookEnvelopeHandler, a9 as WebhookHandler, aa as WebhookHandlers, ab as WebhookSyncFailure, ac as WebhooksOptions, ad as admin, ae as checkLimit, af as checkout, ag as classifyWebhookFailure, ah as dispatchWebhook, ai as hasFeature, aj as hasSubscriptionAccess, ak as isKnownStreamPayWebhookPayload, al as isStreamPayWebhookEnvelope, am as mapToErrorCode, an as portal, s as streampay, ao as subscriptionSlotKey, ap as subscriptions, aq as syncWebhookPayload, ar as webhooks } from './streampay-uhs67tYl.js';
3
3
  import { InvoiceDetailed, PaymentResponse, ConsumerResponse } from '@streamsdk/typescript';
4
4
  import 'better-auth';
5
5
  import 'zod';
package/dist/index.js CHANGED
@@ -247,6 +247,82 @@ function readValidationDetails(body) {
247
247
  return entries;
248
248
  }
249
249
 
250
+ // src/utils/parse-error.ts
251
+ function parseStreamPayError(err) {
252
+ const { status, requestId, body, message: fallbackMessage } = readSdkErrorFields(err);
253
+ const envelope = readEnvelope(body);
254
+ if (envelope && (envelope.code !== void 0 || envelope.message !== void 0)) {
255
+ return {
256
+ status,
257
+ code: envelope.code,
258
+ requestId,
259
+ message: envelope.message ?? fallbackMessage,
260
+ additionalInfo: envelope.additionalInfo,
261
+ validationErrors: []
262
+ };
263
+ }
264
+ const validationErrors = readValidationDetails(body).map((entry) => ({
265
+ loc: entry.loc,
266
+ message: entry.msg,
267
+ type: entry.type
268
+ }));
269
+ return {
270
+ status,
271
+ code: void 0,
272
+ requestId,
273
+ message: fallbackMessage,
274
+ additionalInfo: void 0,
275
+ validationErrors
276
+ };
277
+ }
278
+
279
+ // src/utils/errors.ts
280
+ function statusToAPIErrorStatus(status) {
281
+ switch (status) {
282
+ case 400:
283
+ return "BAD_REQUEST";
284
+ case 401:
285
+ return "UNAUTHORIZED";
286
+ case 403:
287
+ return "FORBIDDEN";
288
+ case 404:
289
+ return "NOT_FOUND";
290
+ case 409:
291
+ return "CONFLICT";
292
+ case 422:
293
+ return "UNPROCESSABLE_ENTITY";
294
+ case 429:
295
+ return "TOO_MANY_REQUESTS";
296
+ default:
297
+ return "INTERNAL_SERVER_ERROR";
298
+ }
299
+ }
300
+ function toAPIError(messageOrConfig, err, logger2) {
301
+ if (err instanceof APIError) throw err;
302
+ const { logPrefix, userMessage } = typeof messageOrConfig === "string" ? { logPrefix: messageOrConfig, userMessage: messageOrConfig } : messageOrConfig;
303
+ const parsed = parseStreamPayError(err);
304
+ const tail = [
305
+ parsed.status !== void 0 ? `status=${parsed.status}` : void 0,
306
+ parsed.code ? `code=${parsed.code}` : void 0,
307
+ parsed.requestId ? `request_id=${parsed.requestId}` : void 0
308
+ ].filter((segment) => segment !== void 0);
309
+ const validationSummary = parsed.validationErrors.length > 0 ? ` validation=${parsed.validationErrors.map((issue) => `${issue.loc.join(".")}: ${issue.message}`).join(" | ")}` : "";
310
+ const logDetail = (tail.length > 0 ? `${parsed.message} [${tail.join(" ")}]` : parsed.message) + validationSummary;
311
+ logger2.error(`${logPrefix} ${logDetail}`);
312
+ throw new APIError(statusToAPIErrorStatus(parsed.status), {
313
+ code: mapToErrorCode(parsed.code, parsed.status),
314
+ message: userMessage
315
+ });
316
+ }
317
+ function rejectUnauthorized(user, anonymousMessage) {
318
+ if (!user) {
319
+ throw new APIError("UNAUTHORIZED", { message: "Session user is missing." });
320
+ }
321
+ if (user.isAnonymous) {
322
+ throw new APIError("UNAUTHORIZED", { message: anonymousMessage });
323
+ }
324
+ }
325
+
250
326
  // src/utils/format-error.ts
251
327
  function formatStreamPayError(err) {
252
328
  const { body, message: fallback } = readSdkErrorFields(err);
@@ -286,6 +362,46 @@ function scopedLogger(logger2) {
286
362
  function getLogger(ctx) {
287
363
  return scopedLogger(ctx.context.logger);
288
364
  }
365
+ async function getCurrentConsumerUser(ctx, user) {
366
+ if (!user.streampayConsumerId) return user;
367
+ if (!ctx.context.adapter) {
368
+ throw new APIError("INTERNAL_SERVER_ERROR", { message: "Consumer storage is unavailable." });
369
+ }
370
+ const current = await ctx.context.adapter.findOne({
371
+ model: "user",
372
+ where: [{ field: "id", value: user.id }]
373
+ });
374
+ if (!current || current.id !== user.id) {
375
+ throw new APIError("UNAUTHORIZED", { message: "The account no longer exists." });
376
+ }
377
+ if (current.streampayConsumerId != null && typeof current.streampayConsumerId !== "string") {
378
+ throw new APIError("INTERNAL_SERVER_ERROR", { message: "Invalid stored consumer link." });
379
+ }
380
+ return { ...user, streampayConsumerId: current.streampayConsumerId ?? null };
381
+ }
382
+ function asSessionUser(user) {
383
+ if (user === null || typeof user !== "object") return null;
384
+ if (!("id" in user) || typeof user.id !== "string") return null;
385
+ const result = { id: user.id };
386
+ if ("email" in user && typeof user.email === "string") {
387
+ result.email = user.email;
388
+ }
389
+ if ("name" in user && typeof user.name === "string") {
390
+ result.name = user.name;
391
+ }
392
+ if ("isAnonymous" in user && user.isAnonymous === true) {
393
+ result.isAnonymous = true;
394
+ }
395
+ if ("streampayConsumerId" in user) {
396
+ const value = user.streampayConsumerId;
397
+ if (typeof value === "string") {
398
+ result.streampayConsumerId = value;
399
+ } else if (value === null) {
400
+ result.streampayConsumerId = null;
401
+ }
402
+ }
403
+ return result;
404
+ }
289
405
 
290
406
  // src/utils/ensure-consumer.ts
291
407
  function canClaimBy(mode, identifier) {
@@ -328,6 +444,7 @@ async function resolveDuplicateConsumer(options, createPayload, context) {
328
444
  return existing.id;
329
445
  }
330
446
  async function ensureConsumerForUser(options, ctx, user) {
447
+ user = await getCurrentConsumerUser(ctx, user);
331
448
  if (user.streampayConsumerId) {
332
449
  return { consumerId: user.streampayConsumerId, created: false };
333
450
  }
@@ -367,10 +484,25 @@ async function ensureConsumerForUser(options, ctx, user) {
367
484
  if (isDuplicateConsumerError(err)) {
368
485
  const reusedId = await resolveDuplicateConsumer(options, payload, ctx);
369
486
  if (reusedId) {
370
- await assertConsumerUnclaimed(ctx, reusedId, user.id);
487
+ await persistConsumerId(ctx, user.id, reusedId);
371
488
  try {
372
489
  await options.client.updateConsumer(reusedId, { external_id: user.id });
373
490
  } catch (backfillErr) {
491
+ try {
492
+ if (!ctx.context.adapter.update) throw consumerLinkUnavailable();
493
+ await ctx.context.adapter.update({
494
+ model: "user",
495
+ where: [
496
+ { field: "id", value: user.id },
497
+ { field: "streampayConsumerId", value: reusedId }
498
+ ],
499
+ update: { streampayConsumerId: null }
500
+ });
501
+ } catch (clearErr) {
502
+ getLogger(ctx).error(
503
+ `consumer claim cleanup failed for user=${user.id} consumer=${reusedId}: ${formatStreamPayError(clearErr)}`
504
+ );
505
+ }
374
506
  getLogger(ctx).error(
375
507
  `consumer external_id backfill failed for user=${user.id} consumer=${reusedId}: ${formatStreamPayError(backfillErr)}`
376
508
  );
@@ -379,16 +511,34 @@ async function ensureConsumerForUser(options, ctx, user) {
379
511
  message: "StreamPay consumer linking failed. Please try again."
380
512
  });
381
513
  }
382
- await persistConsumerId(ctx, user.id, reusedId);
383
514
  return { consumerId: reusedId, created: false };
384
515
  }
385
516
  }
386
- getLogger(ctx).error(
387
- `consumer creation failed for user=${user.id}: ${formatStreamPayError(err)}`
517
+ const { status } = readSdkErrorFields(err);
518
+ const transient = status !== void 0 && status >= 500 || status === void 0 && err instanceof TypeError;
519
+ let recoveredId = null;
520
+ if (transient) {
521
+ try {
522
+ recoveredId = await findConsumerByExternalId(options.client, { externalId: user.id });
523
+ } catch (searchErr) {
524
+ getLogger(ctx).warn(
525
+ `consumer recovery search failed for user=${user.id}: ${formatStreamPayError(searchErr)}`
526
+ );
527
+ }
528
+ }
529
+ if (recoveredId) {
530
+ await persistConsumerId(ctx, user.id, recoveredId);
531
+ getLogger(ctx).warn(`consumer recovered after failed creation for user=${user.id}`);
532
+ return { consumerId: recoveredId, created: false };
533
+ }
534
+ toAPIError(
535
+ {
536
+ logPrefix: `consumer creation failed for user=${user.id}:`,
537
+ userMessage: "StreamPay consumer provisioning failed. Please try again."
538
+ },
539
+ err,
540
+ getLogger(ctx)
388
541
  );
389
- throw new APIError("INTERNAL_SERVER_ERROR", {
390
- message: "StreamPay consumer provisioning failed. Please try again."
391
- });
392
542
  }
393
543
  }
394
544
  function consumerLinkUnavailable() {
@@ -399,9 +549,15 @@ function consumerLinkUnavailable() {
399
549
  }
400
550
  async function findConsumerOwner(ctx, consumerId) {
401
551
  try {
552
+ const where = [{ field: "streampayConsumerId", value: consumerId }];
553
+ if (ctx.context.internalAdapter?.listUsers) {
554
+ const owners = await ctx.context.internalAdapter.listUsers(1, 0, void 0, where);
555
+ return owners[0] ?? null;
556
+ }
557
+ if (!ctx.context.adapter) throw consumerLinkUnavailable();
402
558
  return await ctx.context.adapter.findOne({
403
559
  model: "user",
404
- where: [{ field: "streampayConsumerId", value: consumerId }]
560
+ where
405
561
  });
406
562
  } catch (err) {
407
563
  getLogger(ctx).error(
@@ -438,107 +594,6 @@ async function persistConsumerId(ctx, userId, consumerId) {
438
594
  }
439
595
  }
440
596
 
441
- // src/utils/parse-error.ts
442
- function parseStreamPayError(err) {
443
- const { status, requestId, body, message: fallbackMessage } = readSdkErrorFields(err);
444
- const envelope = readEnvelope(body);
445
- if (envelope && (envelope.code !== void 0 || envelope.message !== void 0)) {
446
- return {
447
- status,
448
- code: envelope.code,
449
- requestId,
450
- message: envelope.message ?? fallbackMessage,
451
- additionalInfo: envelope.additionalInfo,
452
- validationErrors: []
453
- };
454
- }
455
- const validationErrors = readValidationDetails(body).map((entry) => ({
456
- loc: entry.loc,
457
- message: entry.msg,
458
- type: entry.type
459
- }));
460
- return {
461
- status,
462
- code: void 0,
463
- requestId,
464
- message: fallbackMessage,
465
- additionalInfo: void 0,
466
- validationErrors
467
- };
468
- }
469
-
470
- // src/utils/errors.ts
471
- function statusToAPIErrorStatus(status) {
472
- switch (status) {
473
- case 400:
474
- return "BAD_REQUEST";
475
- case 401:
476
- return "UNAUTHORIZED";
477
- case 403:
478
- return "FORBIDDEN";
479
- case 404:
480
- return "NOT_FOUND";
481
- case 409:
482
- return "CONFLICT";
483
- case 422:
484
- return "UNPROCESSABLE_ENTITY";
485
- case 429:
486
- return "TOO_MANY_REQUESTS";
487
- default:
488
- return "INTERNAL_SERVER_ERROR";
489
- }
490
- }
491
- function toAPIError(messageOrConfig, err, logger2) {
492
- if (err instanceof APIError) throw err;
493
- const { logPrefix, userMessage } = typeof messageOrConfig === "string" ? { logPrefix: messageOrConfig, userMessage: messageOrConfig } : messageOrConfig;
494
- const parsed = parseStreamPayError(err);
495
- const tail = [
496
- parsed.status !== void 0 ? `status=${parsed.status}` : void 0,
497
- parsed.code ? `code=${parsed.code}` : void 0,
498
- parsed.requestId ? `request_id=${parsed.requestId}` : void 0
499
- ].filter((segment) => segment !== void 0);
500
- const validationSummary = parsed.validationErrors.length > 0 ? ` validation=${parsed.validationErrors.map((issue) => `${issue.loc.join(".")}: ${issue.message}`).join(" | ")}` : "";
501
- const logDetail = (tail.length > 0 ? `${parsed.message} [${tail.join(" ")}]` : parsed.message) + validationSummary;
502
- logger2.error(`${logPrefix} ${logDetail}`);
503
- throw new APIError(statusToAPIErrorStatus(parsed.status), {
504
- code: mapToErrorCode(parsed.code, parsed.status),
505
- message: userMessage
506
- });
507
- }
508
- function rejectUnauthorized(user, anonymousMessage) {
509
- if (!user) {
510
- throw new APIError("UNAUTHORIZED", { message: "Session user is missing." });
511
- }
512
- if (user.isAnonymous) {
513
- throw new APIError("UNAUTHORIZED", { message: anonymousMessage });
514
- }
515
- }
516
-
517
- // src/utils/session.ts
518
- function asSessionUser(user) {
519
- if (user === null || typeof user !== "object") return null;
520
- if (!("id" in user) || typeof user.id !== "string") return null;
521
- const result = { id: user.id };
522
- if ("email" in user && typeof user.email === "string") {
523
- result.email = user.email;
524
- }
525
- if ("name" in user && typeof user.name === "string") {
526
- result.name = user.name;
527
- }
528
- if ("isAnonymous" in user && user.isAnonymous === true) {
529
- result.isAnonymous = true;
530
- }
531
- if ("streampayConsumerId" in user) {
532
- const value = user.streampayConsumerId;
533
- if (typeof value === "string") {
534
- result.streampayConsumerId = value;
535
- } else if (value === null) {
536
- result.streampayConsumerId = null;
537
- }
538
- }
539
- return result;
540
- }
541
-
542
597
  // src/plugins/subscriptions/status.ts
543
598
  var SUBSCRIPTION_STATUSES = [
544
599
  "incomplete",
@@ -2874,9 +2929,10 @@ var paginationQuery = z.object({
2874
2929
  page: z.coerce.number().int().min(1).max(Number.MAX_SAFE_INTEGER).optional(),
2875
2930
  size: z.coerce.number().int().min(1).max(100).optional()
2876
2931
  });
2877
- async function getConsumerIdOrNull(client, user) {
2932
+ async function getConsumerIdOrNull(ctx, client, user) {
2878
2933
  rejectUnauthorized(user, "Anonymous users cannot access the billing portal.");
2879
- if (user.streampayConsumerId) return user.streampayConsumerId;
2934
+ const current = await getCurrentConsumerUser(ctx, user);
2935
+ if (current.streampayConsumerId) return current.streampayConsumerId;
2880
2936
  return findConsumerByExternalId(client, { externalId: user.id });
2881
2937
  }
2882
2938
  var portal = ({ pageSize, createSession } = {}) => (options) => {
@@ -2891,6 +2947,7 @@ var portal = ({ pageSize, createSession } = {}) => (options) => {
2891
2947
  ctx.setHeader("cache-control", "no-store");
2892
2948
  try {
2893
2949
  const consumerId = await getConsumerIdOrNull(
2950
+ ctx,
2894
2951
  client,
2895
2952
  asSessionUser(ctx.context.session?.user)
2896
2953
  );
@@ -2918,7 +2975,7 @@ var portal = ({ pageSize, createSession } = {}) => (options) => {
2918
2975
  async (ctx) => {
2919
2976
  const user = asSessionUser(ctx.context.session?.user);
2920
2977
  try {
2921
- const consumerId = await getConsumerIdOrNull(client, user);
2978
+ const consumerId = await getConsumerIdOrNull(ctx, client, user);
2922
2979
  if (!consumerId) return ctx.json({ hasConsumer: false, consumer: null });
2923
2980
  const consumer = await client.getConsumer(consumerId);
2924
2981
  return ctx.json({ hasConsumer: true, consumer });
@@ -2933,7 +2990,7 @@ var portal = ({ pageSize, createSession } = {}) => (options) => {
2933
2990
  async (ctx) => {
2934
2991
  const user = asSessionUser(ctx.context.session?.user);
2935
2992
  try {
2936
- const consumerId = await getConsumerIdOrNull(client, user);
2993
+ const consumerId = await getConsumerIdOrNull(ctx, client, user);
2937
2994
  if (!consumerId) return ctx.json({ hasConsumer: false, data: [] });
2938
2995
  const response = await client.listSubscriptions({
2939
2996
  organization_consumer_id: consumerId,
@@ -2956,7 +3013,7 @@ var portal = ({ pageSize, createSession } = {}) => (options) => {
2956
3013
  async (ctx) => {
2957
3014
  const user = asSessionUser(ctx.context.session?.user);
2958
3015
  try {
2959
- const consumerId = await getConsumerIdOrNull(client, user);
3016
+ const consumerId = await getConsumerIdOrNull(ctx, client, user);
2960
3017
  if (!consumerId) return ctx.json({ hasConsumer: false, data: [] });
2961
3018
  const response = await client.listInvoices({
2962
3019
  organization_consumer_id: consumerId,
@@ -5410,9 +5467,6 @@ var webhooks = (webhooksOptions) => {
5410
5467
  };
5411
5468
  };
5412
5469
  var isAnonymous = (user) => "isAnonymous" in user && user.isAnonymous === true;
5413
- function hasInternalAdapter(ctx) {
5414
- return "internalAdapter" in ctx.context && ctx.context.internalAdapter !== null && typeof ctx.context.internalAdapter === "object" && "updateUser" in ctx.context.internalAdapter && typeof ctx.context.internalAdapter.updateUser === "function";
5415
- }
5416
5470
  var onBeforeUserCreate = (options) => async (user, context) => {
5417
5471
  if (!context || !options.createConsumerOnSignUp) return void 0;
5418
5472
  if (isAnonymous(user)) return void 0;
@@ -5442,6 +5496,7 @@ var onBeforeUserCreate = (options) => async (user, context) => {
5442
5496
  if (isDuplicateConsumerError(err)) {
5443
5497
  const reusedId = await resolveDuplicateConsumer(options, createPayload, context);
5444
5498
  if (reusedId) {
5499
+ await assertConsumerUnclaimed(context, reusedId);
5445
5500
  return { data: { streampayConsumerId: reusedId } };
5446
5501
  }
5447
5502
  }
@@ -5490,10 +5545,15 @@ var onUserUpdate = (options) => async (user, context) => {
5490
5545
  getLogger(context).error(
5491
5546
  `consumer ${sessionUser.streampayConsumerId} not found for user=${sessionUser.id}; clearing stale link for re-provisioning.`
5492
5547
  );
5493
- if (hasInternalAdapter(context)) {
5548
+ if (typeof context.context.adapter?.update === "function") {
5494
5549
  try {
5495
- await context.context.internalAdapter.updateUser(sessionUser.id, {
5496
- streampayConsumerId: null
5550
+ await context.context.adapter.update({
5551
+ model: "user",
5552
+ where: [
5553
+ { field: "id", value: sessionUser.id },
5554
+ { field: "streampayConsumerId", value: sessionUser.streampayConsumerId }
5555
+ ],
5556
+ update: { streampayConsumerId: null }
5497
5557
  });
5498
5558
  } catch (clearErr) {
5499
5559
  getLogger(context).error(
@@ -5525,7 +5585,7 @@ var onUserDelete = (options) => async (user, context) => {
5525
5585
 
5526
5586
  // package.json
5527
5587
  var package_default = {
5528
- version: "3.0.0"};
5588
+ version: "3.0.2"};
5529
5589
 
5530
5590
  // src/version.ts
5531
5591
  var version = package_default.version;