better-auth-streampay 3.0.2 → 3.1.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.d.cts CHANGED
@@ -1,5 +1,5 @@
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';
1
+ import { a as StreamPayClient } from './streampay-Bij1FvXa.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-Bij1FvXa.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-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';
1
+ import { a as StreamPayClient } from './streampay-Bij1FvXa.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-Bij1FvXa.js';
3
3
  import { InvoiceDetailed, PaymentResponse, ConsumerResponse } from '@streamsdk/typescript';
4
4
  import 'better-auth';
5
5
  import 'zod';
package/dist/index.js CHANGED
@@ -913,6 +913,40 @@ function isUniqueConstraintError(err) {
913
913
  }
914
914
  var WEBHOOK_PROCESSING_LEASE_MS = 2 * 60 * 1e3;
915
915
  var WEBHOOK_RETRY_DELAYS_MS = [5, 30, 120, 360, 720].map((minutes) => minutes * 60 * 1e3);
916
+ var WebhookEventInProgressError = class extends Error {
917
+ constructor(eventType) {
918
+ super(`Webhook ${eventType} is already being processed; retry later.`);
919
+ this.name = "WebhookEventInProgressError";
920
+ }
921
+ };
922
+ async function findDueWebhookEvents(ctx, now, limit) {
923
+ const [retryDue, abandoned] = await Promise.all([
924
+ ctx.context.adapter.findMany({
925
+ model: WEBHOOK_EVENT_MODEL,
926
+ where: [
927
+ { field: "status", value: "pending" },
928
+ { field: "nextAttemptAt", operator: "lte", value: now }
929
+ ],
930
+ limit,
931
+ sortBy: { field: "nextAttemptAt", direction: "asc" }
932
+ }),
933
+ ctx.context.adapter.findMany({
934
+ model: WEBHOOK_EVENT_MODEL,
935
+ where: [
936
+ { field: "status", value: "pending" },
937
+ {
938
+ field: "lockedAt",
939
+ operator: "lt",
940
+ value: new Date(now.getTime() - WEBHOOK_PROCESSING_LEASE_MS)
941
+ }
942
+ ],
943
+ limit,
944
+ sortBy: { field: "lockedAt", direction: "asc" }
945
+ })
946
+ ]);
947
+ const byId = new Map([...retryDue, ...abandoned].map((row) => [row.id, row]));
948
+ return [...byId.values()].slice(0, limit);
949
+ }
916
950
  async function claimOrAdvanceWebhookEvent(ctx, payload, rawBody, signatureHeader, maxAttempts, scope) {
917
951
  const sourceEventId = extractEventId(payload);
918
952
  const eventId = sourceEventId && (scope ? `${scope}:${sourceEventId}` : sourceEventId);
@@ -1378,6 +1412,9 @@ async function syncWebhookPayload(ctx, payload, client, plans, callbacks, option
1378
1412
  let claim = { action: "process", row: null };
1379
1413
  if (dedupe) {
1380
1414
  claim = await claimOrAdvanceWebhookEvent(ctx, payload, rawBody, signatureHeader, maxAttempts);
1415
+ if (claim.action === "skip" && claim.reason === "in_progress") {
1416
+ throw new WebhookEventInProgressError(payload.event_type);
1417
+ }
1381
1418
  if (claim.action === "skip") return;
1382
1419
  if (claim.action === "dead_letter") {
1383
1420
  logger(ctx).warn(
@@ -5066,9 +5103,9 @@ function subscriptions(subsOptions) {
5066
5103
  }
5067
5104
  };
5068
5105
  if (dedupeEnabled) {
5069
- registry.replayWebhookEvent = async (ctx, eventId) => {
5106
+ registry.replayWebhookEvent = async (ctx, eventId, replayOptions) => {
5070
5107
  if (eventId.startsWith("handlers:") && registry.replayWebhookHandler) {
5071
- return registry.replayWebhookHandler(ctx, eventId);
5108
+ return registry.replayWebhookHandler(ctx, eventId, replayOptions);
5072
5109
  }
5073
5110
  const syncCtx = {
5074
5111
  context: ctx.context
@@ -5120,6 +5157,7 @@ function subscriptions(subsOptions) {
5120
5157
  await markWebhookEventCompleted(syncCtx, claimed.id, claimed.lockedBy);
5121
5158
  return { replayed: true, eventId };
5122
5159
  } catch (err) {
5160
+ const maxAttempts = subsOptions.maxWebhookAttempts ?? DEFAULT_MAX_WEBHOOK_ATTEMPTS;
5123
5161
  await recordWebhookEventFailure(
5124
5162
  syncCtx,
5125
5163
  claimed.id,
@@ -5127,7 +5165,7 @@ function subscriptions(subsOptions) {
5127
5165
  null,
5128
5166
  err,
5129
5167
  claimed.lockedBy,
5130
- true
5168
+ !replayOptions?.retryUntilExhausted || classifyWebhookFailure(err) === "PERMANENT" || claimed.attemptCount >= maxAttempts
5131
5169
  );
5132
5170
  throw err;
5133
5171
  }
@@ -5306,6 +5344,13 @@ function verifyWebhookOrThrow(input) {
5306
5344
  }
5307
5345
 
5308
5346
  // src/plugins/webhooks.ts
5347
+ var DEFAULT_DUE_WEBHOOK_BATCH = 25;
5348
+ var ProcessDueWebhookEventsBody = z.object({ limit: z.number().int().min(1).max(100).optional() }).optional();
5349
+ function inProgressError() {
5350
+ return new APIError("SERVICE_UNAVAILABLE", {
5351
+ message: "Webhook event is already being processed. Retry later."
5352
+ });
5353
+ }
5309
5354
  function toErrorCode(reason) {
5310
5355
  return reason === "MISSING_HEADER" || reason === "INVALID_SIGNATURE" || reason === "EXPIRED" ? "UNAUTHORIZED" : "BAD_REQUEST";
5311
5356
  }
@@ -5320,7 +5365,7 @@ var webhooks = (webhooksOptions) => {
5320
5365
  return (_options, registry) => {
5321
5366
  const { secret, toleranceSeconds, deduplicate = false, ...handlers } = webhooksOptions;
5322
5367
  if (deduplicate && registry) {
5323
- registry.replayWebhookHandler = async (ctx, eventId) => {
5368
+ registry.replayWebhookHandler = async (ctx, eventId, replayOptions) => {
5324
5369
  const syncContext = { context: ctx.context };
5325
5370
  const row = await syncContext.context.adapter.findOne({
5326
5371
  model: WEBHOOK_EVENT_MODEL,
@@ -5358,7 +5403,7 @@ var webhooks = (webhooksOptions) => {
5358
5403
  row.signatureHeader,
5359
5404
  err,
5360
5405
  claimed.lockedBy,
5361
- true
5406
+ !replayOptions?.retryUntilExhausted || claimed.attemptCount >= DEFAULT_MAX_WEBHOOK_ATTEMPTS
5362
5407
  );
5363
5408
  throw err;
5364
5409
  }
@@ -5420,6 +5465,7 @@ var webhooks = (webhooksOptions) => {
5420
5465
  signatureHeader
5421
5466
  });
5422
5467
  } catch (err) {
5468
+ if (err instanceof WebhookEventInProgressError) throw inProgressError();
5423
5469
  const message = err instanceof Error ? err.message : String(err);
5424
5470
  logger2.error(`subscription sync failed: ${message}`);
5425
5471
  throw new APIError("INTERNAL_SERVER_ERROR", {
@@ -5436,6 +5482,7 @@ var webhooks = (webhooksOptions) => {
5436
5482
  DEFAULT_MAX_WEBHOOK_ATTEMPTS,
5437
5483
  "handlers"
5438
5484
  ) : null;
5485
+ if (claim?.action === "skip" && claim.reason === "in_progress") throw inProgressError();
5439
5486
  if (claim && claim.action !== "process") return ctx.json({ received: true });
5440
5487
  const row = claim?.action === "process" ? claim.row : null;
5441
5488
  try {
@@ -5461,6 +5508,48 @@ var webhooks = (webhooksOptions) => {
5461
5508
  }
5462
5509
  return ctx.json({ received: true });
5463
5510
  }
5511
+ ),
5512
+ processDueStreampayWebhookEvents: createAuthEndpoint(
5513
+ "/streampay/webhooks/process-due",
5514
+ {
5515
+ method: "POST",
5516
+ body: ProcessDueWebhookEventsBody,
5517
+ metadata: { SERVER_ONLY: true }
5518
+ },
5519
+ async (ctx) => {
5520
+ const replay = registry?.replayWebhookEvent;
5521
+ if (!replay) {
5522
+ throw new APIError("BAD_REQUEST", {
5523
+ message: "Retry processing requires the webhook inbox: enable subscriptions or webhooks({ deduplicate: true })."
5524
+ });
5525
+ }
5526
+ const syncContext = { context: ctx.context };
5527
+ const due = await findDueWebhookEvents(
5528
+ syncContext,
5529
+ /* @__PURE__ */ new Date(),
5530
+ ctx.body?.limit ?? DEFAULT_DUE_WEBHOOK_BATCH
5531
+ );
5532
+ const succeeded = [];
5533
+ const failed = [];
5534
+ for (const row of due) {
5535
+ try {
5536
+ await replay(ctx, row.eventId, { retryUntilExhausted: true });
5537
+ succeeded.push(row.eventId);
5538
+ } catch (err) {
5539
+ if (err instanceof APIError && err.status === "CONFLICT") continue;
5540
+ failed.push({
5541
+ eventId: row.eventId,
5542
+ error: err instanceof Error ? err.message : String(err)
5543
+ });
5544
+ }
5545
+ }
5546
+ if (failed.length > 0) {
5547
+ getLogger(ctx).error(
5548
+ `webhook retry: ${failed.length} of ${due.length} due events failed again`
5549
+ );
5550
+ }
5551
+ return ctx.json({ succeeded, failed });
5552
+ }
5464
5553
  )
5465
5554
  }
5466
5555
  };
@@ -5585,7 +5674,7 @@ var onUserDelete = (options) => async (user, context) => {
5585
5674
 
5586
5675
  // package.json
5587
5676
  var package_default = {
5588
- version: "3.0.2"};
5677
+ version: "3.1.0"};
5589
5678
 
5590
5679
  // src/version.ts
5591
5680
  var version = package_default.version;