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/client.d.cts CHANGED
@@ -1,7 +1,7 @@
1
- import { s as streampay, E as ErrorCodeEntry } from './streampay-Cfl70SR_.cjs';
2
- export { $ as $ERROR_CODES, S as StreamPayErrorCode } from './streampay-Cfl70SR_.cjs';
3
- import '@streamsdk/typescript';
1
+ import { s as streampay, E as ErrorCodeEntry } from './streampay-uhs67tYl.cjs';
2
+ export { $ as $ERROR_CODES, S as StreamPayErrorCode } from './streampay-uhs67tYl.cjs';
4
3
  import 'better-auth';
4
+ import '@streamsdk/typescript';
5
5
  import 'zod';
6
6
  import 'zod/v4/core';
7
7
 
package/dist/client.d.ts CHANGED
@@ -1,7 +1,7 @@
1
- import { s as streampay, E as ErrorCodeEntry } from './streampay-Cfl70SR_.js';
2
- export { $ as $ERROR_CODES, S as StreamPayErrorCode } from './streampay-Cfl70SR_.js';
3
- import '@streamsdk/typescript';
1
+ import { s as streampay, E as ErrorCodeEntry } from './streampay-uhs67tYl.js';
2
+ export { $ as $ERROR_CODES, S as StreamPayErrorCode } from './streampay-uhs67tYl.js';
4
3
  import 'better-auth';
4
+ import '@streamsdk/typescript';
5
5
  import 'zod';
6
6
  import 'zod/v4/core';
7
7
 
package/dist/index.cjs CHANGED
@@ -249,6 +249,82 @@ function readValidationDetails(body) {
249
249
  return entries;
250
250
  }
251
251
 
252
+ // src/utils/parse-error.ts
253
+ function parseStreamPayError(err) {
254
+ const { status, requestId, body, message: fallbackMessage } = readSdkErrorFields(err);
255
+ const envelope = readEnvelope(body);
256
+ if (envelope && (envelope.code !== void 0 || envelope.message !== void 0)) {
257
+ return {
258
+ status,
259
+ code: envelope.code,
260
+ requestId,
261
+ message: envelope.message ?? fallbackMessage,
262
+ additionalInfo: envelope.additionalInfo,
263
+ validationErrors: []
264
+ };
265
+ }
266
+ const validationErrors = readValidationDetails(body).map((entry) => ({
267
+ loc: entry.loc,
268
+ message: entry.msg,
269
+ type: entry.type
270
+ }));
271
+ return {
272
+ status,
273
+ code: void 0,
274
+ requestId,
275
+ message: fallbackMessage,
276
+ additionalInfo: void 0,
277
+ validationErrors
278
+ };
279
+ }
280
+
281
+ // src/utils/errors.ts
282
+ function statusToAPIErrorStatus(status) {
283
+ switch (status) {
284
+ case 400:
285
+ return "BAD_REQUEST";
286
+ case 401:
287
+ return "UNAUTHORIZED";
288
+ case 403:
289
+ return "FORBIDDEN";
290
+ case 404:
291
+ return "NOT_FOUND";
292
+ case 409:
293
+ return "CONFLICT";
294
+ case 422:
295
+ return "UNPROCESSABLE_ENTITY";
296
+ case 429:
297
+ return "TOO_MANY_REQUESTS";
298
+ default:
299
+ return "INTERNAL_SERVER_ERROR";
300
+ }
301
+ }
302
+ function toAPIError(messageOrConfig, err, logger2) {
303
+ if (err instanceof api.APIError) throw err;
304
+ const { logPrefix, userMessage } = typeof messageOrConfig === "string" ? { logPrefix: messageOrConfig, userMessage: messageOrConfig } : messageOrConfig;
305
+ const parsed = parseStreamPayError(err);
306
+ const tail = [
307
+ parsed.status !== void 0 ? `status=${parsed.status}` : void 0,
308
+ parsed.code ? `code=${parsed.code}` : void 0,
309
+ parsed.requestId ? `request_id=${parsed.requestId}` : void 0
310
+ ].filter((segment) => segment !== void 0);
311
+ const validationSummary = parsed.validationErrors.length > 0 ? ` validation=${parsed.validationErrors.map((issue) => `${issue.loc.join(".")}: ${issue.message}`).join(" | ")}` : "";
312
+ const logDetail = (tail.length > 0 ? `${parsed.message} [${tail.join(" ")}]` : parsed.message) + validationSummary;
313
+ logger2.error(`${logPrefix} ${logDetail}`);
314
+ throw new api.APIError(statusToAPIErrorStatus(parsed.status), {
315
+ code: mapToErrorCode(parsed.code, parsed.status),
316
+ message: userMessage
317
+ });
318
+ }
319
+ function rejectUnauthorized(user, anonymousMessage) {
320
+ if (!user) {
321
+ throw new api.APIError("UNAUTHORIZED", { message: "Session user is missing." });
322
+ }
323
+ if (user.isAnonymous) {
324
+ throw new api.APIError("UNAUTHORIZED", { message: anonymousMessage });
325
+ }
326
+ }
327
+
252
328
  // src/utils/format-error.ts
253
329
  function formatStreamPayError(err) {
254
330
  const { body, message: fallback } = readSdkErrorFields(err);
@@ -288,6 +364,46 @@ function scopedLogger(logger2) {
288
364
  function getLogger(ctx) {
289
365
  return scopedLogger(ctx.context.logger);
290
366
  }
367
+ async function getCurrentConsumerUser(ctx, user) {
368
+ if (!user.streampayConsumerId) return user;
369
+ if (!ctx.context.adapter) {
370
+ throw new api.APIError("INTERNAL_SERVER_ERROR", { message: "Consumer storage is unavailable." });
371
+ }
372
+ const current = await ctx.context.adapter.findOne({
373
+ model: "user",
374
+ where: [{ field: "id", value: user.id }]
375
+ });
376
+ if (!current || current.id !== user.id) {
377
+ throw new api.APIError("UNAUTHORIZED", { message: "The account no longer exists." });
378
+ }
379
+ if (current.streampayConsumerId != null && typeof current.streampayConsumerId !== "string") {
380
+ throw new api.APIError("INTERNAL_SERVER_ERROR", { message: "Invalid stored consumer link." });
381
+ }
382
+ return { ...user, streampayConsumerId: current.streampayConsumerId ?? null };
383
+ }
384
+ function asSessionUser(user) {
385
+ if (user === null || typeof user !== "object") return null;
386
+ if (!("id" in user) || typeof user.id !== "string") return null;
387
+ const result = { id: user.id };
388
+ if ("email" in user && typeof user.email === "string") {
389
+ result.email = user.email;
390
+ }
391
+ if ("name" in user && typeof user.name === "string") {
392
+ result.name = user.name;
393
+ }
394
+ if ("isAnonymous" in user && user.isAnonymous === true) {
395
+ result.isAnonymous = true;
396
+ }
397
+ if ("streampayConsumerId" in user) {
398
+ const value = user.streampayConsumerId;
399
+ if (typeof value === "string") {
400
+ result.streampayConsumerId = value;
401
+ } else if (value === null) {
402
+ result.streampayConsumerId = null;
403
+ }
404
+ }
405
+ return result;
406
+ }
291
407
 
292
408
  // src/utils/ensure-consumer.ts
293
409
  function canClaimBy(mode, identifier) {
@@ -330,6 +446,7 @@ async function resolveDuplicateConsumer(options, createPayload, context) {
330
446
  return existing.id;
331
447
  }
332
448
  async function ensureConsumerForUser(options, ctx, user) {
449
+ user = await getCurrentConsumerUser(ctx, user);
333
450
  if (user.streampayConsumerId) {
334
451
  return { consumerId: user.streampayConsumerId, created: false };
335
452
  }
@@ -369,10 +486,25 @@ async function ensureConsumerForUser(options, ctx, user) {
369
486
  if (isDuplicateConsumerError(err)) {
370
487
  const reusedId = await resolveDuplicateConsumer(options, payload, ctx);
371
488
  if (reusedId) {
372
- await assertConsumerUnclaimed(ctx, reusedId, user.id);
489
+ await persistConsumerId(ctx, user.id, reusedId);
373
490
  try {
374
491
  await options.client.updateConsumer(reusedId, { external_id: user.id });
375
492
  } catch (backfillErr) {
493
+ try {
494
+ if (!ctx.context.adapter.update) throw consumerLinkUnavailable();
495
+ await ctx.context.adapter.update({
496
+ model: "user",
497
+ where: [
498
+ { field: "id", value: user.id },
499
+ { field: "streampayConsumerId", value: reusedId }
500
+ ],
501
+ update: { streampayConsumerId: null }
502
+ });
503
+ } catch (clearErr) {
504
+ getLogger(ctx).error(
505
+ `consumer claim cleanup failed for user=${user.id} consumer=${reusedId}: ${formatStreamPayError(clearErr)}`
506
+ );
507
+ }
376
508
  getLogger(ctx).error(
377
509
  `consumer external_id backfill failed for user=${user.id} consumer=${reusedId}: ${formatStreamPayError(backfillErr)}`
378
510
  );
@@ -381,16 +513,34 @@ async function ensureConsumerForUser(options, ctx, user) {
381
513
  message: "StreamPay consumer linking failed. Please try again."
382
514
  });
383
515
  }
384
- await persistConsumerId(ctx, user.id, reusedId);
385
516
  return { consumerId: reusedId, created: false };
386
517
  }
387
518
  }
388
- getLogger(ctx).error(
389
- `consumer creation failed for user=${user.id}: ${formatStreamPayError(err)}`
519
+ const { status } = readSdkErrorFields(err);
520
+ const transient = status !== void 0 && status >= 500 || status === void 0 && err instanceof TypeError;
521
+ let recoveredId = null;
522
+ if (transient) {
523
+ try {
524
+ recoveredId = await findConsumerByExternalId(options.client, { externalId: user.id });
525
+ } catch (searchErr) {
526
+ getLogger(ctx).warn(
527
+ `consumer recovery search failed for user=${user.id}: ${formatStreamPayError(searchErr)}`
528
+ );
529
+ }
530
+ }
531
+ if (recoveredId) {
532
+ await persistConsumerId(ctx, user.id, recoveredId);
533
+ getLogger(ctx).warn(`consumer recovered after failed creation for user=${user.id}`);
534
+ return { consumerId: recoveredId, created: false };
535
+ }
536
+ toAPIError(
537
+ {
538
+ logPrefix: `consumer creation failed for user=${user.id}:`,
539
+ userMessage: "StreamPay consumer provisioning failed. Please try again."
540
+ },
541
+ err,
542
+ getLogger(ctx)
390
543
  );
391
- throw new api.APIError("INTERNAL_SERVER_ERROR", {
392
- message: "StreamPay consumer provisioning failed. Please try again."
393
- });
394
544
  }
395
545
  }
396
546
  function consumerLinkUnavailable() {
@@ -401,9 +551,15 @@ function consumerLinkUnavailable() {
401
551
  }
402
552
  async function findConsumerOwner(ctx, consumerId) {
403
553
  try {
554
+ const where = [{ field: "streampayConsumerId", value: consumerId }];
555
+ if (ctx.context.internalAdapter?.listUsers) {
556
+ const owners = await ctx.context.internalAdapter.listUsers(1, 0, void 0, where);
557
+ return owners[0] ?? null;
558
+ }
559
+ if (!ctx.context.adapter) throw consumerLinkUnavailable();
404
560
  return await ctx.context.adapter.findOne({
405
561
  model: "user",
406
- where: [{ field: "streampayConsumerId", value: consumerId }]
562
+ where
407
563
  });
408
564
  } catch (err) {
409
565
  getLogger(ctx).error(
@@ -440,107 +596,6 @@ async function persistConsumerId(ctx, userId, consumerId) {
440
596
  }
441
597
  }
442
598
 
443
- // src/utils/parse-error.ts
444
- function parseStreamPayError(err) {
445
- const { status, requestId, body, message: fallbackMessage } = readSdkErrorFields(err);
446
- const envelope = readEnvelope(body);
447
- if (envelope && (envelope.code !== void 0 || envelope.message !== void 0)) {
448
- return {
449
- status,
450
- code: envelope.code,
451
- requestId,
452
- message: envelope.message ?? fallbackMessage,
453
- additionalInfo: envelope.additionalInfo,
454
- validationErrors: []
455
- };
456
- }
457
- const validationErrors = readValidationDetails(body).map((entry) => ({
458
- loc: entry.loc,
459
- message: entry.msg,
460
- type: entry.type
461
- }));
462
- return {
463
- status,
464
- code: void 0,
465
- requestId,
466
- message: fallbackMessage,
467
- additionalInfo: void 0,
468
- validationErrors
469
- };
470
- }
471
-
472
- // src/utils/errors.ts
473
- function statusToAPIErrorStatus(status) {
474
- switch (status) {
475
- case 400:
476
- return "BAD_REQUEST";
477
- case 401:
478
- return "UNAUTHORIZED";
479
- case 403:
480
- return "FORBIDDEN";
481
- case 404:
482
- return "NOT_FOUND";
483
- case 409:
484
- return "CONFLICT";
485
- case 422:
486
- return "UNPROCESSABLE_ENTITY";
487
- case 429:
488
- return "TOO_MANY_REQUESTS";
489
- default:
490
- return "INTERNAL_SERVER_ERROR";
491
- }
492
- }
493
- function toAPIError(messageOrConfig, err, logger2) {
494
- if (err instanceof api.APIError) throw err;
495
- const { logPrefix, userMessage } = typeof messageOrConfig === "string" ? { logPrefix: messageOrConfig, userMessage: messageOrConfig } : messageOrConfig;
496
- const parsed = parseStreamPayError(err);
497
- const tail = [
498
- parsed.status !== void 0 ? `status=${parsed.status}` : void 0,
499
- parsed.code ? `code=${parsed.code}` : void 0,
500
- parsed.requestId ? `request_id=${parsed.requestId}` : void 0
501
- ].filter((segment) => segment !== void 0);
502
- const validationSummary = parsed.validationErrors.length > 0 ? ` validation=${parsed.validationErrors.map((issue) => `${issue.loc.join(".")}: ${issue.message}`).join(" | ")}` : "";
503
- const logDetail = (tail.length > 0 ? `${parsed.message} [${tail.join(" ")}]` : parsed.message) + validationSummary;
504
- logger2.error(`${logPrefix} ${logDetail}`);
505
- throw new api.APIError(statusToAPIErrorStatus(parsed.status), {
506
- code: mapToErrorCode(parsed.code, parsed.status),
507
- message: userMessage
508
- });
509
- }
510
- function rejectUnauthorized(user, anonymousMessage) {
511
- if (!user) {
512
- throw new api.APIError("UNAUTHORIZED", { message: "Session user is missing." });
513
- }
514
- if (user.isAnonymous) {
515
- throw new api.APIError("UNAUTHORIZED", { message: anonymousMessage });
516
- }
517
- }
518
-
519
- // src/utils/session.ts
520
- function asSessionUser(user) {
521
- if (user === null || typeof user !== "object") return null;
522
- if (!("id" in user) || typeof user.id !== "string") return null;
523
- const result = { id: user.id };
524
- if ("email" in user && typeof user.email === "string") {
525
- result.email = user.email;
526
- }
527
- if ("name" in user && typeof user.name === "string") {
528
- result.name = user.name;
529
- }
530
- if ("isAnonymous" in user && user.isAnonymous === true) {
531
- result.isAnonymous = true;
532
- }
533
- if ("streampayConsumerId" in user) {
534
- const value = user.streampayConsumerId;
535
- if (typeof value === "string") {
536
- result.streampayConsumerId = value;
537
- } else if (value === null) {
538
- result.streampayConsumerId = null;
539
- }
540
- }
541
- return result;
542
- }
543
-
544
599
  // src/plugins/subscriptions/status.ts
545
600
  var SUBSCRIPTION_STATUSES = [
546
601
  "incomplete",
@@ -2876,9 +2931,10 @@ var paginationQuery = zod.z.object({
2876
2931
  page: zod.z.coerce.number().int().min(1).max(Number.MAX_SAFE_INTEGER).optional(),
2877
2932
  size: zod.z.coerce.number().int().min(1).max(100).optional()
2878
2933
  });
2879
- async function getConsumerIdOrNull(client, user) {
2934
+ async function getConsumerIdOrNull(ctx, client, user) {
2880
2935
  rejectUnauthorized(user, "Anonymous users cannot access the billing portal.");
2881
- if (user.streampayConsumerId) return user.streampayConsumerId;
2936
+ const current = await getCurrentConsumerUser(ctx, user);
2937
+ if (current.streampayConsumerId) return current.streampayConsumerId;
2882
2938
  return findConsumerByExternalId(client, { externalId: user.id });
2883
2939
  }
2884
2940
  var portal = ({ pageSize, createSession } = {}) => (options) => {
@@ -2893,6 +2949,7 @@ var portal = ({ pageSize, createSession } = {}) => (options) => {
2893
2949
  ctx.setHeader("cache-control", "no-store");
2894
2950
  try {
2895
2951
  const consumerId = await getConsumerIdOrNull(
2952
+ ctx,
2896
2953
  client,
2897
2954
  asSessionUser(ctx.context.session?.user)
2898
2955
  );
@@ -2920,7 +2977,7 @@ var portal = ({ pageSize, createSession } = {}) => (options) => {
2920
2977
  async (ctx) => {
2921
2978
  const user = asSessionUser(ctx.context.session?.user);
2922
2979
  try {
2923
- const consumerId = await getConsumerIdOrNull(client, user);
2980
+ const consumerId = await getConsumerIdOrNull(ctx, client, user);
2924
2981
  if (!consumerId) return ctx.json({ hasConsumer: false, consumer: null });
2925
2982
  const consumer = await client.getConsumer(consumerId);
2926
2983
  return ctx.json({ hasConsumer: true, consumer });
@@ -2935,7 +2992,7 @@ var portal = ({ pageSize, createSession } = {}) => (options) => {
2935
2992
  async (ctx) => {
2936
2993
  const user = asSessionUser(ctx.context.session?.user);
2937
2994
  try {
2938
- const consumerId = await getConsumerIdOrNull(client, user);
2995
+ const consumerId = await getConsumerIdOrNull(ctx, client, user);
2939
2996
  if (!consumerId) return ctx.json({ hasConsumer: false, data: [] });
2940
2997
  const response = await client.listSubscriptions({
2941
2998
  organization_consumer_id: consumerId,
@@ -2958,7 +3015,7 @@ var portal = ({ pageSize, createSession } = {}) => (options) => {
2958
3015
  async (ctx) => {
2959
3016
  const user = asSessionUser(ctx.context.session?.user);
2960
3017
  try {
2961
- const consumerId = await getConsumerIdOrNull(client, user);
3018
+ const consumerId = await getConsumerIdOrNull(ctx, client, user);
2962
3019
  if (!consumerId) return ctx.json({ hasConsumer: false, data: [] });
2963
3020
  const response = await client.listInvoices({
2964
3021
  organization_consumer_id: consumerId,
@@ -5412,9 +5469,6 @@ var webhooks = (webhooksOptions) => {
5412
5469
  };
5413
5470
  };
5414
5471
  var isAnonymous = (user) => "isAnonymous" in user && user.isAnonymous === true;
5415
- function hasInternalAdapter(ctx) {
5416
- 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";
5417
- }
5418
5472
  var onBeforeUserCreate = (options) => async (user, context) => {
5419
5473
  if (!context || !options.createConsumerOnSignUp) return void 0;
5420
5474
  if (isAnonymous(user)) return void 0;
@@ -5444,6 +5498,7 @@ var onBeforeUserCreate = (options) => async (user, context) => {
5444
5498
  if (isDuplicateConsumerError(err)) {
5445
5499
  const reusedId = await resolveDuplicateConsumer(options, createPayload, context);
5446
5500
  if (reusedId) {
5501
+ await assertConsumerUnclaimed(context, reusedId);
5447
5502
  return { data: { streampayConsumerId: reusedId } };
5448
5503
  }
5449
5504
  }
@@ -5492,10 +5547,15 @@ var onUserUpdate = (options) => async (user, context) => {
5492
5547
  getLogger(context).error(
5493
5548
  `consumer ${sessionUser.streampayConsumerId} not found for user=${sessionUser.id}; clearing stale link for re-provisioning.`
5494
5549
  );
5495
- if (hasInternalAdapter(context)) {
5550
+ if (typeof context.context.adapter?.update === "function") {
5496
5551
  try {
5497
- await context.context.internalAdapter.updateUser(sessionUser.id, {
5498
- streampayConsumerId: null
5552
+ await context.context.adapter.update({
5553
+ model: "user",
5554
+ where: [
5555
+ { field: "id", value: sessionUser.id },
5556
+ { field: "streampayConsumerId", value: sessionUser.streampayConsumerId }
5557
+ ],
5558
+ update: { streampayConsumerId: null }
5499
5559
  });
5500
5560
  } catch (clearErr) {
5501
5561
  getLogger(context).error(
@@ -5527,7 +5587,7 @@ var onUserDelete = (options) => async (user, context) => {
5527
5587
 
5528
5588
  // package.json
5529
5589
  var package_default = {
5530
- version: "3.0.0"};
5590
+ version: "3.0.2"};
5531
5591
 
5532
5592
  // src/version.ts
5533
5593
  var version = package_default.version;