better-auth-streampay 3.0.2 → 3.2.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/client.d.cts +2 -2
- package/dist/client.d.ts +2 -2
- package/dist/index.cjs +330 -135
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +330 -135
- package/dist/index.js.map +1 -1
- package/dist/{streampay-uhs67tYl.d.cts → streampay-B7cFK2CP.d.cts} +54 -17
- package/dist/{streampay-uhs67tYl.d.ts → streampay-B7cFK2CP.d.ts} +54 -17
- package/docs/integration.md +19 -2
- package/docs/staging-validation.md +1 -0
- package/docs/state-machines.md +323 -0
- package/docs/subscriptions.md +5 -2
- package/package.json +1 -1
package/dist/index.d.cts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { a as StreamPayClient } from './streampay-
|
|
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-
|
|
1
|
+
import { a as StreamPayClient } from './streampay-B7cFK2CP.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-B7cFK2CP.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-
|
|
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-
|
|
1
|
+
import { a as StreamPayClient } from './streampay-B7cFK2CP.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-B7cFK2CP.js';
|
|
3
3
|
import { InvoiceDetailed, PaymentResponse, ConsumerResponse } from '@streamsdk/typescript';
|
|
4
4
|
import 'better-auth';
|
|
5
5
|
import 'zod';
|
package/dist/index.js
CHANGED
|
@@ -877,6 +877,120 @@ function projectPlanFields(sub, plans) {
|
|
|
877
877
|
pendingSeatsEffectiveAt: pendingSeats === null ? null : pendingEffectiveAt
|
|
878
878
|
};
|
|
879
879
|
}
|
|
880
|
+
|
|
881
|
+
// src/plugins/subscriptions/lifecycle.ts
|
|
882
|
+
function isAlreadyCanceledFreezeError(err) {
|
|
883
|
+
const sdkError = readSdkErrorFields(err);
|
|
884
|
+
const envelope = readEnvelope(sdkError.body);
|
|
885
|
+
return sdkError.status === 403 && envelope?.code === "STREAM_ERROR" && envelope.additionalInfo === "Cannot delete non-latest freeze entry.";
|
|
886
|
+
}
|
|
887
|
+
async function deactivatePaymentLink(client, paymentLinkId, log) {
|
|
888
|
+
if (!client.updatePaymentLinkStatus) {
|
|
889
|
+
log.warn(
|
|
890
|
+
`payment link=${paymentLinkId} stays payable: client does not implement updatePaymentLinkStatus.`
|
|
891
|
+
);
|
|
892
|
+
return;
|
|
893
|
+
}
|
|
894
|
+
try {
|
|
895
|
+
await client.updatePaymentLinkStatus(paymentLinkId, { status: "INACTIVE" });
|
|
896
|
+
} catch (err) {
|
|
897
|
+
if (readSdkErrorFields(err).status !== 404) throw err;
|
|
898
|
+
}
|
|
899
|
+
}
|
|
900
|
+
function subscriptionCouponIds(stream) {
|
|
901
|
+
return couponIdsFromMetadata(stream.coupon_calculation_metadata);
|
|
902
|
+
}
|
|
903
|
+
function couponIdsFromMetadata(metadata) {
|
|
904
|
+
const coupons = [];
|
|
905
|
+
for (const coupon of metadata?.coupons ?? []) {
|
|
906
|
+
if (coupon.coupon_id) coupons.push(coupon.coupon_id);
|
|
907
|
+
}
|
|
908
|
+
return coupons;
|
|
909
|
+
}
|
|
910
|
+
function subscriptionItemsForUpdate(stream, currentProductId, targetProductId, targetSeats) {
|
|
911
|
+
if (!stream.items?.length) {
|
|
912
|
+
throw invalidProviderItems("StreamPay returned a subscription without any items.");
|
|
913
|
+
}
|
|
914
|
+
const subscriptionCoupons = new Set(subscriptionCouponIds(stream));
|
|
915
|
+
let matches = 0;
|
|
916
|
+
const items = stream.items.map((item) => {
|
|
917
|
+
const productId = subscriptionItemProductId(item);
|
|
918
|
+
const quantity = item.quantity ?? 1;
|
|
919
|
+
if (!productId || !Number.isSafeInteger(quantity) || quantity < 1) {
|
|
920
|
+
throw invalidProviderItems("StreamPay returned an invalid subscription item.");
|
|
921
|
+
}
|
|
922
|
+
const isPlanItem = productId === currentProductId;
|
|
923
|
+
if (isPlanItem) matches += 1;
|
|
924
|
+
const itemCoupons = couponIdsFromMetadata(item.coupon_calculation_metadata).filter(
|
|
925
|
+
(couponId) => !subscriptionCoupons.has(couponId)
|
|
926
|
+
);
|
|
927
|
+
return {
|
|
928
|
+
product_id: isPlanItem ? targetProductId : productId,
|
|
929
|
+
quantity: isPlanItem ? targetSeats : quantity,
|
|
930
|
+
...itemCoupons.length > 0 ? { coupons: itemCoupons } : {}
|
|
931
|
+
};
|
|
932
|
+
});
|
|
933
|
+
if (matches !== 1) {
|
|
934
|
+
throw invalidProviderItems(
|
|
935
|
+
`Expected exactly one plan item for product "${currentProductId}", received ${matches}.`
|
|
936
|
+
);
|
|
937
|
+
}
|
|
938
|
+
return items;
|
|
939
|
+
}
|
|
940
|
+
function invalidProviderItems(message) {
|
|
941
|
+
return new APIError("INTERNAL_SERVER_ERROR", {
|
|
942
|
+
code: $ERROR_CODES.SUBSCRIPTION_INVALID_STATE.code,
|
|
943
|
+
message
|
|
944
|
+
});
|
|
945
|
+
}
|
|
946
|
+
function configuredPlanForSubscription(subscription, plans) {
|
|
947
|
+
const matches = plans.list.filter(
|
|
948
|
+
(plan) => subscription.items?.some((item) => subscriptionItemProductId(item) === plan.productId)
|
|
949
|
+
);
|
|
950
|
+
if (matches.length > 1) {
|
|
951
|
+
throw invalidProviderItems(
|
|
952
|
+
"StreamPay returned a subscription containing multiple configured plan products."
|
|
953
|
+
);
|
|
954
|
+
}
|
|
955
|
+
return matches[0];
|
|
956
|
+
}
|
|
957
|
+
async function findSubscriptionFreeze(client, options, subscriptionId, matches) {
|
|
958
|
+
const listPage = options.listSubscriptionFreezes;
|
|
959
|
+
if (!listPage) {
|
|
960
|
+
const response = await client.listSubscriptionFreezes(subscriptionId);
|
|
961
|
+
return {
|
|
962
|
+
freeze: response.data?.find(matches),
|
|
963
|
+
hasMore: response.pagination?.has_next_page ?? false
|
|
964
|
+
};
|
|
965
|
+
}
|
|
966
|
+
const seenIds = /* @__PURE__ */ new Set();
|
|
967
|
+
for (let page = 1; page <= 100; page++) {
|
|
968
|
+
const response = await listPage(subscriptionId, { page, limit: 100 });
|
|
969
|
+
const pagination = response.pagination;
|
|
970
|
+
if (!Array.isArray(response.data) || !pagination || pagination.current_page !== page || typeof pagination.has_next_page !== "boolean") {
|
|
971
|
+
throw freezePaginationConflict("StreamPay returned invalid freeze pagination.");
|
|
972
|
+
}
|
|
973
|
+
let advanced = false;
|
|
974
|
+
for (const freeze2 of response.data) {
|
|
975
|
+
if (freeze2.id && !seenIds.has(freeze2.id)) {
|
|
976
|
+
seenIds.add(freeze2.id);
|
|
977
|
+
advanced = true;
|
|
978
|
+
}
|
|
979
|
+
}
|
|
980
|
+
if (!advanced && (pagination.has_next_page || response.data.length > 0)) {
|
|
981
|
+
throw freezePaginationConflict("StreamPay freeze pagination returned no new entries.");
|
|
982
|
+
}
|
|
983
|
+
const freeze = response.data.find(matches);
|
|
984
|
+
if (freeze || !pagination.has_next_page) return { freeze, hasMore: false };
|
|
985
|
+
}
|
|
986
|
+
throw freezePaginationConflict("StreamPay freeze pagination exceeded 100 pages.");
|
|
987
|
+
}
|
|
988
|
+
function freezePaginationConflict(message) {
|
|
989
|
+
return new APIError("CONFLICT", {
|
|
990
|
+
code: $ERROR_CODES.SUBSCRIPTION_INVALID_STATE.code,
|
|
991
|
+
message
|
|
992
|
+
});
|
|
993
|
+
}
|
|
880
994
|
function subscriptionSlotKey(referenceType, referenceId, group) {
|
|
881
995
|
const tuple = JSON.stringify([referenceType, referenceId, group ?? null]);
|
|
882
996
|
return `sp_slot_v1_${createHash("sha256").update(tuple).digest("hex")}`;
|
|
@@ -913,6 +1027,40 @@ function isUniqueConstraintError(err) {
|
|
|
913
1027
|
}
|
|
914
1028
|
var WEBHOOK_PROCESSING_LEASE_MS = 2 * 60 * 1e3;
|
|
915
1029
|
var WEBHOOK_RETRY_DELAYS_MS = [5, 30, 120, 360, 720].map((minutes) => minutes * 60 * 1e3);
|
|
1030
|
+
var WebhookEventInProgressError = class extends Error {
|
|
1031
|
+
constructor(eventType) {
|
|
1032
|
+
super(`Webhook ${eventType} is already being processed; retry later.`);
|
|
1033
|
+
this.name = "WebhookEventInProgressError";
|
|
1034
|
+
}
|
|
1035
|
+
};
|
|
1036
|
+
async function findDueWebhookEvents(ctx, now, limit) {
|
|
1037
|
+
const [retryDue, abandoned] = await Promise.all([
|
|
1038
|
+
ctx.context.adapter.findMany({
|
|
1039
|
+
model: WEBHOOK_EVENT_MODEL,
|
|
1040
|
+
where: [
|
|
1041
|
+
{ field: "status", value: "pending" },
|
|
1042
|
+
{ field: "nextAttemptAt", operator: "lte", value: now }
|
|
1043
|
+
],
|
|
1044
|
+
limit,
|
|
1045
|
+
sortBy: { field: "nextAttemptAt", direction: "asc" }
|
|
1046
|
+
}),
|
|
1047
|
+
ctx.context.adapter.findMany({
|
|
1048
|
+
model: WEBHOOK_EVENT_MODEL,
|
|
1049
|
+
where: [
|
|
1050
|
+
{ field: "status", value: "pending" },
|
|
1051
|
+
{
|
|
1052
|
+
field: "lockedAt",
|
|
1053
|
+
operator: "lt",
|
|
1054
|
+
value: new Date(now.getTime() - WEBHOOK_PROCESSING_LEASE_MS)
|
|
1055
|
+
}
|
|
1056
|
+
],
|
|
1057
|
+
limit,
|
|
1058
|
+
sortBy: { field: "lockedAt", direction: "asc" }
|
|
1059
|
+
})
|
|
1060
|
+
]);
|
|
1061
|
+
const byId = new Map([...retryDue, ...abandoned].map((row) => [row.id, row]));
|
|
1062
|
+
return [...byId.values()].slice(0, limit);
|
|
1063
|
+
}
|
|
916
1064
|
async function claimOrAdvanceWebhookEvent(ctx, payload, rawBody, signatureHeader, maxAttempts, scope) {
|
|
917
1065
|
const sourceEventId = extractEventId(payload);
|
|
918
1066
|
const eventId = sourceEventId && (scope ? `${scope}:${sourceEventId}` : sourceEventId);
|
|
@@ -1171,12 +1319,77 @@ var SubscriptionCorrelationError = class extends Error {
|
|
|
1171
1319
|
this.name = "SubscriptionCorrelationError";
|
|
1172
1320
|
}
|
|
1173
1321
|
};
|
|
1174
|
-
async function
|
|
1322
|
+
async function takeSlotFromReservation(ctx, client, slotKey, ownerRowId, streampaySubscriptionId) {
|
|
1323
|
+
const holder = await ctx.context.adapter.findOne({
|
|
1324
|
+
model: SUBSCRIPTION_MODEL2,
|
|
1325
|
+
where: [{ field: "activeSlotKey", value: slotKey }]
|
|
1326
|
+
});
|
|
1327
|
+
if (!holder || holder.id === ownerRowId) return;
|
|
1328
|
+
if (holder.status !== "incomplete" || holder.streampaySubscriptionId) {
|
|
1329
|
+
throw new SubscriptionCorrelationError(
|
|
1330
|
+
`StreamPay sub=${streampaySubscriptionId} needs the billing slot held by live row=${holder.id} (${holder.status}). Resolve the duplicate subscription, then replay.`
|
|
1331
|
+
);
|
|
1332
|
+
}
|
|
1333
|
+
if (holder.streampayPaymentLinkId) {
|
|
1334
|
+
try {
|
|
1335
|
+
await deactivatePaymentLink(client, holder.streampayPaymentLinkId, logger(ctx));
|
|
1336
|
+
} catch (err) {
|
|
1337
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
1338
|
+
logger(ctx).error(
|
|
1339
|
+
`payment link=${holder.streampayPaymentLinkId} of released row=${holder.id} could not be deactivated and may still be paid; deactivate it manually: ${message}`
|
|
1340
|
+
);
|
|
1341
|
+
}
|
|
1342
|
+
}
|
|
1343
|
+
const released = await ctx.context.adapter.update({
|
|
1344
|
+
model: SUBSCRIPTION_MODEL2,
|
|
1345
|
+
update: { status: "incomplete_expired", activeSlotKey: null, updatedAt: /* @__PURE__ */ new Date() },
|
|
1346
|
+
where: [
|
|
1347
|
+
{ field: "id", value: holder.id },
|
|
1348
|
+
{ field: "status", value: "incomplete" },
|
|
1349
|
+
{ field: "activeSlotKey", value: slotKey },
|
|
1350
|
+
{ field: "streampayPaymentLinkId", value: holder.streampayPaymentLinkId ?? null }
|
|
1351
|
+
]
|
|
1352
|
+
});
|
|
1353
|
+
if (!released) {
|
|
1354
|
+
throw new Error(`Checkout reservation row=${holder.id} changed while releasing its slot.`);
|
|
1355
|
+
}
|
|
1356
|
+
logger(ctx).warn(
|
|
1357
|
+
`released checkout reservation row=${holder.id} for paid StreamPay sub=${streampaySubscriptionId}.`
|
|
1358
|
+
);
|
|
1359
|
+
}
|
|
1360
|
+
async function linkReservedRow(ctx, client, row, projected, metadataReferenceType, streampaySubscriptionId) {
|
|
1361
|
+
const activeSlotKey = projected.activeSlotKey === null ? null : row.activeSlotKey ?? subscriptionSlotKey(
|
|
1362
|
+
row.referenceType ?? metadataReferenceType ?? "user",
|
|
1363
|
+
row.referenceId,
|
|
1364
|
+
projected.group === void 0 ? row.group : projected.group
|
|
1365
|
+
);
|
|
1366
|
+
return updateReconciledSubscription(
|
|
1367
|
+
ctx,
|
|
1368
|
+
client,
|
|
1369
|
+
row,
|
|
1370
|
+
{
|
|
1371
|
+
...projected,
|
|
1372
|
+
billingStatus: row.billingStatus ?? "current",
|
|
1373
|
+
...activeSlotKey === null ? {} : { activeSlotKey }
|
|
1374
|
+
},
|
|
1375
|
+
streampaySubscriptionId
|
|
1376
|
+
);
|
|
1377
|
+
}
|
|
1378
|
+
async function updateReconciledSubscription(ctx, client, existing, projected, streampaySubscriptionId) {
|
|
1175
1379
|
if (existing.providerUpdatedAt instanceof Date && projected.providerUpdatedAt instanceof Date && projected.providerUpdatedAt.getTime() < existing.providerUpdatedAt.getTime()) {
|
|
1176
1380
|
throw new Error(
|
|
1177
1381
|
`StreamPay returned stale subscription state for sub=${streampaySubscriptionId}. Retry reconciliation.`
|
|
1178
1382
|
);
|
|
1179
1383
|
}
|
|
1384
|
+
if (projected.activeSlotKey && projected.activeSlotKey !== existing.activeSlotKey) {
|
|
1385
|
+
await takeSlotFromReservation(
|
|
1386
|
+
ctx,
|
|
1387
|
+
client,
|
|
1388
|
+
projected.activeSlotKey,
|
|
1389
|
+
existing.id,
|
|
1390
|
+
streampaySubscriptionId
|
|
1391
|
+
);
|
|
1392
|
+
}
|
|
1180
1393
|
const updated = await ctx.context.adapter.update({
|
|
1181
1394
|
model: SUBSCRIPTION_MODEL2,
|
|
1182
1395
|
update: projected,
|
|
@@ -1252,6 +1465,7 @@ async function reconcileFromStreamPay(ctx, payload, client, plans) {
|
|
|
1252
1465
|
}
|
|
1253
1466
|
const updated = await updateReconciledSubscription(
|
|
1254
1467
|
ctx,
|
|
1468
|
+
client,
|
|
1255
1469
|
existing,
|
|
1256
1470
|
projected,
|
|
1257
1471
|
streampaySubscriptionId
|
|
@@ -1285,21 +1499,12 @@ async function reconcileFromStreamPay(ctx, payload, client, plans) {
|
|
|
1285
1499
|
`webhook ${payload.event_type}: referenced subscription row=${localRowId} is missing; rebuilding from signed metadata.`
|
|
1286
1500
|
);
|
|
1287
1501
|
} else if (metadataRow.referenceId === referenceId && (!metadataReferenceType || (metadataRow.referenceType ?? "user") === metadataReferenceType) && metadataRow.plan === planName && (!metadataRow.streampayConsumerId || !stream.organization_consumer_id || metadataRow.streampayConsumerId === stream.organization_consumer_id) && (!metadataRow.streampaySubscriptionId || metadataRow.streampaySubscriptionId === streampaySubscriptionId) && (!metadataRow.streampayPaymentLinkId || !paymentLinkId || metadataRow.streampayPaymentLinkId === paymentLinkId)) {
|
|
1288
|
-
const
|
|
1289
|
-
...projected,
|
|
1290
|
-
billingStatus: metadataRow.billingStatus ?? "current",
|
|
1291
|
-
...projected.activeSlotKey === null ? {} : {
|
|
1292
|
-
activeSlotKey: metadataRow.activeSlotKey ?? subscriptionSlotKey(
|
|
1293
|
-
metadataRow.referenceType ?? metadataReferenceType ?? "user",
|
|
1294
|
-
metadataRow.referenceId,
|
|
1295
|
-
projected.group === void 0 ? metadataRow.group : projected.group
|
|
1296
|
-
)
|
|
1297
|
-
}
|
|
1298
|
-
};
|
|
1299
|
-
const updated = await updateReconciledSubscription(
|
|
1502
|
+
const updated = await linkReservedRow(
|
|
1300
1503
|
ctx,
|
|
1504
|
+
client,
|
|
1301
1505
|
metadataRow,
|
|
1302
|
-
|
|
1506
|
+
projected,
|
|
1507
|
+
metadataReferenceType,
|
|
1303
1508
|
streampaySubscriptionId
|
|
1304
1509
|
);
|
|
1305
1510
|
return { row: updated, stream };
|
|
@@ -1322,30 +1527,22 @@ async function reconcileFromStreamPay(ctx, payload, client, plans) {
|
|
|
1322
1527
|
stream.organization_consumer_id ?? null
|
|
1323
1528
|
);
|
|
1324
1529
|
if (incomplete) {
|
|
1325
|
-
const
|
|
1326
|
-
...projected,
|
|
1327
|
-
billingStatus: incomplete.billingStatus ?? "current",
|
|
1328
|
-
...projected.activeSlotKey === null ? {} : {
|
|
1329
|
-
activeSlotKey: incomplete.activeSlotKey ?? subscriptionSlotKey(
|
|
1330
|
-
incomplete.referenceType ?? metadataReferenceType ?? "user",
|
|
1331
|
-
incomplete.referenceId,
|
|
1332
|
-
projected.group === void 0 ? incomplete.group : projected.group
|
|
1333
|
-
)
|
|
1334
|
-
}
|
|
1335
|
-
};
|
|
1336
|
-
const updated = await updateReconciledSubscription(
|
|
1530
|
+
const updated = await linkReservedRow(
|
|
1337
1531
|
ctx,
|
|
1532
|
+
client,
|
|
1338
1533
|
incomplete,
|
|
1339
|
-
|
|
1534
|
+
projected,
|
|
1535
|
+
metadataReferenceType,
|
|
1340
1536
|
streampaySubscriptionId
|
|
1341
1537
|
);
|
|
1342
|
-
return {
|
|
1343
|
-
row: updated,
|
|
1344
|
-
stream
|
|
1345
|
-
};
|
|
1538
|
+
return { row: updated, stream };
|
|
1346
1539
|
}
|
|
1347
1540
|
const plan = plans.byName.get(planName);
|
|
1348
1541
|
const referenceType = metadataReferenceType ?? "custom";
|
|
1542
|
+
const activeSlotKey = isTerminalSubscriptionStatus(projected.status) ? null : subscriptionSlotKey(referenceType, referenceId, plan?.group);
|
|
1543
|
+
if (activeSlotKey) {
|
|
1544
|
+
await takeSlotFromReservation(ctx, client, activeSlotKey, null, streampaySubscriptionId);
|
|
1545
|
+
}
|
|
1349
1546
|
const row = await ctx.context.adapter.create({
|
|
1350
1547
|
model: SUBSCRIPTION_MODEL2,
|
|
1351
1548
|
data: {
|
|
@@ -1354,7 +1551,7 @@ async function reconcileFromStreamPay(ctx, payload, client, plans) {
|
|
|
1354
1551
|
...projected,
|
|
1355
1552
|
referenceId,
|
|
1356
1553
|
referenceType,
|
|
1357
|
-
activeSlotKey
|
|
1554
|
+
activeSlotKey,
|
|
1358
1555
|
streampayPaymentLinkId: paymentLinkId,
|
|
1359
1556
|
plan: planName,
|
|
1360
1557
|
planVersion: plan?.version ?? null,
|
|
@@ -1378,6 +1575,9 @@ async function syncWebhookPayload(ctx, payload, client, plans, callbacks, option
|
|
|
1378
1575
|
let claim = { action: "process", row: null };
|
|
1379
1576
|
if (dedupe) {
|
|
1380
1577
|
claim = await claimOrAdvanceWebhookEvent(ctx, payload, rawBody, signatureHeader, maxAttempts);
|
|
1578
|
+
if (claim.action === "skip" && claim.reason === "in_progress") {
|
|
1579
|
+
throw new WebhookEventInProgressError(payload.event_type);
|
|
1580
|
+
}
|
|
1381
1581
|
if (claim.action === "skip") return;
|
|
1382
1582
|
if (claim.action === "dead_letter") {
|
|
1383
1583
|
logger(ctx).warn(
|
|
@@ -3221,6 +3421,12 @@ function checkoutInProgressError() {
|
|
|
3221
3421
|
message: "A subscription checkout is already being created for this plan group."
|
|
3222
3422
|
});
|
|
3223
3423
|
}
|
|
3424
|
+
function subscriptionAlreadyActiveError() {
|
|
3425
|
+
return new APIError("CONFLICT", {
|
|
3426
|
+
code: $ERROR_CODES.SUBSCRIPTION_ALREADY_ACTIVE.code,
|
|
3427
|
+
message: "An active subscription already exists for this plan group."
|
|
3428
|
+
});
|
|
3429
|
+
}
|
|
3224
3430
|
async function resumeOrReserveCheckoutSlot(args) {
|
|
3225
3431
|
const { client, adapter, candidates, activeSlotKey, planName, seats, now, log } = args;
|
|
3226
3432
|
const matchesCheckout = (row2) => row2.plan === planName && (row2.seats ?? 1) === seats;
|
|
@@ -3267,7 +3473,8 @@ async function resumeOrReserveCheckoutSlot(args) {
|
|
|
3267
3473
|
model: SUBSCRIPTION_MODEL4,
|
|
3268
3474
|
where: [{ field: "activeSlotKey", value: activeSlotKey }]
|
|
3269
3475
|
});
|
|
3270
|
-
if (reserved
|
|
3476
|
+
if (!reserved) throw err;
|
|
3477
|
+
if (reserved.status !== "incomplete") throw subscriptionAlreadyActiveError();
|
|
3271
3478
|
if (matchesCheckout(reserved)) {
|
|
3272
3479
|
let recovery;
|
|
3273
3480
|
try {
|
|
@@ -3288,6 +3495,20 @@ async function resumeOrReserveCheckoutSlot(args) {
|
|
|
3288
3495
|
}
|
|
3289
3496
|
const reservationIsStale = !(reserved.createdAt instanceof Date) || now - reserved.createdAt.getTime() >= UPGRADE_IDEMPOTENCY_WINDOW_MS;
|
|
3290
3497
|
if (!reservationIsStale) throw checkoutInProgressError();
|
|
3498
|
+
if (reserved.streampayPaymentLinkId) {
|
|
3499
|
+
try {
|
|
3500
|
+
await deactivatePaymentLink(client, reserved.streampayPaymentLinkId, log);
|
|
3501
|
+
} catch (deactivationError) {
|
|
3502
|
+
toAPIError(
|
|
3503
|
+
{
|
|
3504
|
+
logPrefix: `deactivate stale checkout link=${reserved.streampayPaymentLinkId} failed for row=${reserved.id}:`,
|
|
3505
|
+
userMessage: "Unable to replace the previous subscription checkout."
|
|
3506
|
+
},
|
|
3507
|
+
deactivationError,
|
|
3508
|
+
log
|
|
3509
|
+
);
|
|
3510
|
+
}
|
|
3511
|
+
}
|
|
3291
3512
|
const released = await adapter.update({
|
|
3292
3513
|
model: SUBSCRIPTION_MODEL4,
|
|
3293
3514
|
update: { status: "incomplete_expired", activeSlotKey: null, updatedAt: /* @__PURE__ */ new Date() },
|
|
@@ -3311,105 +3532,6 @@ async function resumeOrReserveCheckoutSlot(args) {
|
|
|
3311
3532
|
}
|
|
3312
3533
|
return { kind: "reserved", row, consumerId };
|
|
3313
3534
|
}
|
|
3314
|
-
function isAlreadyCanceledFreezeError(err) {
|
|
3315
|
-
const sdkError = readSdkErrorFields(err);
|
|
3316
|
-
const envelope = readEnvelope(sdkError.body);
|
|
3317
|
-
return sdkError.status === 403 && envelope?.code === "STREAM_ERROR" && envelope.additionalInfo === "Cannot delete non-latest freeze entry.";
|
|
3318
|
-
}
|
|
3319
|
-
function subscriptionCouponIds(stream) {
|
|
3320
|
-
return couponIdsFromMetadata(stream.coupon_calculation_metadata);
|
|
3321
|
-
}
|
|
3322
|
-
function couponIdsFromMetadata(metadata) {
|
|
3323
|
-
const coupons = [];
|
|
3324
|
-
for (const coupon of metadata?.coupons ?? []) {
|
|
3325
|
-
if (coupon.coupon_id) coupons.push(coupon.coupon_id);
|
|
3326
|
-
}
|
|
3327
|
-
return coupons;
|
|
3328
|
-
}
|
|
3329
|
-
function subscriptionItemsForUpdate(stream, currentProductId, targetProductId, targetSeats) {
|
|
3330
|
-
if (!stream.items?.length) {
|
|
3331
|
-
throw invalidProviderItems("StreamPay returned a subscription without any items.");
|
|
3332
|
-
}
|
|
3333
|
-
const subscriptionCoupons = new Set(subscriptionCouponIds(stream));
|
|
3334
|
-
let matches = 0;
|
|
3335
|
-
const items = stream.items.map((item) => {
|
|
3336
|
-
const productId = subscriptionItemProductId(item);
|
|
3337
|
-
const quantity = item.quantity ?? 1;
|
|
3338
|
-
if (!productId || !Number.isSafeInteger(quantity) || quantity < 1) {
|
|
3339
|
-
throw invalidProviderItems("StreamPay returned an invalid subscription item.");
|
|
3340
|
-
}
|
|
3341
|
-
const isPlanItem = productId === currentProductId;
|
|
3342
|
-
if (isPlanItem) matches += 1;
|
|
3343
|
-
const itemCoupons = couponIdsFromMetadata(item.coupon_calculation_metadata).filter(
|
|
3344
|
-
(couponId) => !subscriptionCoupons.has(couponId)
|
|
3345
|
-
);
|
|
3346
|
-
return {
|
|
3347
|
-
product_id: isPlanItem ? targetProductId : productId,
|
|
3348
|
-
quantity: isPlanItem ? targetSeats : quantity,
|
|
3349
|
-
...itemCoupons.length > 0 ? { coupons: itemCoupons } : {}
|
|
3350
|
-
};
|
|
3351
|
-
});
|
|
3352
|
-
if (matches !== 1) {
|
|
3353
|
-
throw invalidProviderItems(
|
|
3354
|
-
`Expected exactly one plan item for product "${currentProductId}", received ${matches}.`
|
|
3355
|
-
);
|
|
3356
|
-
}
|
|
3357
|
-
return items;
|
|
3358
|
-
}
|
|
3359
|
-
function invalidProviderItems(message) {
|
|
3360
|
-
return new APIError("INTERNAL_SERVER_ERROR", {
|
|
3361
|
-
code: $ERROR_CODES.SUBSCRIPTION_INVALID_STATE.code,
|
|
3362
|
-
message
|
|
3363
|
-
});
|
|
3364
|
-
}
|
|
3365
|
-
function configuredPlanForSubscription(subscription, plans) {
|
|
3366
|
-
const matches = plans.list.filter(
|
|
3367
|
-
(plan) => subscription.items?.some((item) => subscriptionItemProductId(item) === plan.productId)
|
|
3368
|
-
);
|
|
3369
|
-
if (matches.length > 1) {
|
|
3370
|
-
throw invalidProviderItems(
|
|
3371
|
-
"StreamPay returned a subscription containing multiple configured plan products."
|
|
3372
|
-
);
|
|
3373
|
-
}
|
|
3374
|
-
return matches[0];
|
|
3375
|
-
}
|
|
3376
|
-
async function findSubscriptionFreeze(client, options, subscriptionId, matches) {
|
|
3377
|
-
const listPage = options.listSubscriptionFreezes;
|
|
3378
|
-
if (!listPage) {
|
|
3379
|
-
const response = await client.listSubscriptionFreezes(subscriptionId);
|
|
3380
|
-
return {
|
|
3381
|
-
freeze: response.data?.find(matches),
|
|
3382
|
-
hasMore: response.pagination?.has_next_page ?? false
|
|
3383
|
-
};
|
|
3384
|
-
}
|
|
3385
|
-
const seenIds = /* @__PURE__ */ new Set();
|
|
3386
|
-
for (let page = 1; page <= 100; page++) {
|
|
3387
|
-
const response = await listPage(subscriptionId, { page, limit: 100 });
|
|
3388
|
-
const pagination = response.pagination;
|
|
3389
|
-
if (!Array.isArray(response.data) || !pagination || pagination.current_page !== page || typeof pagination.has_next_page !== "boolean") {
|
|
3390
|
-
throw freezePaginationConflict("StreamPay returned invalid freeze pagination.");
|
|
3391
|
-
}
|
|
3392
|
-
let advanced = false;
|
|
3393
|
-
for (const freeze2 of response.data) {
|
|
3394
|
-
if (freeze2.id && !seenIds.has(freeze2.id)) {
|
|
3395
|
-
seenIds.add(freeze2.id);
|
|
3396
|
-
advanced = true;
|
|
3397
|
-
}
|
|
3398
|
-
}
|
|
3399
|
-
if (!advanced && (pagination.has_next_page || response.data.length > 0)) {
|
|
3400
|
-
throw freezePaginationConflict("StreamPay freeze pagination returned no new entries.");
|
|
3401
|
-
}
|
|
3402
|
-
const freeze = response.data.find(matches);
|
|
3403
|
-
if (freeze || !pagination.has_next_page) return { freeze, hasMore: false };
|
|
3404
|
-
}
|
|
3405
|
-
throw freezePaginationConflict("StreamPay freeze pagination exceeded 100 pages.");
|
|
3406
|
-
}
|
|
3407
|
-
function freezePaginationConflict(message) {
|
|
3408
|
-
return new APIError("CONFLICT", {
|
|
3409
|
-
code: $ERROR_CODES.SUBSCRIPTION_INVALID_STATE.code,
|
|
3410
|
-
message
|
|
3411
|
-
});
|
|
3412
|
-
}
|
|
3413
3535
|
var SUBSCRIPTION_INTERVALS = ["WEEK", "MONTH", "QUARTER", "YEAR"];
|
|
3414
3536
|
var PlanSchema = z.object({
|
|
3415
3537
|
name: z.string().min(1, "every plan must have a non-empty `name`."),
|
|
@@ -4074,6 +4196,24 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
|
|
|
4074
4196
|
`failed to persist payment link=${paymentLinkId} for row=${row.id}: ${message}. Protected checkout metadata will reconcile the row from the webhook.`
|
|
4075
4197
|
);
|
|
4076
4198
|
}
|
|
4199
|
+
if (updatedRow?.status === "incomplete_expired") {
|
|
4200
|
+
getLogger(ctx).warn(
|
|
4201
|
+
`checkout reservation row=${row.id} was released while payment link=${paymentLinkId} was created; deactivating the link.`
|
|
4202
|
+
);
|
|
4203
|
+
try {
|
|
4204
|
+
await deactivatePaymentLink(client, paymentLinkId, getLogger(ctx));
|
|
4205
|
+
} catch (deactivationError) {
|
|
4206
|
+
toAPIError(
|
|
4207
|
+
{
|
|
4208
|
+
logPrefix: `deactivate orphaned checkout link=${paymentLinkId} failed for row=${row.id}:`,
|
|
4209
|
+
userMessage: "Failed to start subscription checkout."
|
|
4210
|
+
},
|
|
4211
|
+
deactivationError,
|
|
4212
|
+
getLogger(ctx)
|
|
4213
|
+
);
|
|
4214
|
+
}
|
|
4215
|
+
throw checkoutInProgressError();
|
|
4216
|
+
}
|
|
4077
4217
|
return ctx.json({
|
|
4078
4218
|
subscriptionId: updatedRow?.id ?? row.id,
|
|
4079
4219
|
url,
|
|
@@ -5103,6 +5243,7 @@ function subscriptions(subsOptions) {
|
|
|
5103
5243
|
}
|
|
5104
5244
|
const payload = parsedPayload;
|
|
5105
5245
|
const plans = await plansRef();
|
|
5246
|
+
const previousStatus = row.status;
|
|
5106
5247
|
const claimed = await claimWebhookEventForReplay(syncCtx, row);
|
|
5107
5248
|
if (!claimed?.lockedBy) {
|
|
5108
5249
|
throw new APIError("CONFLICT", {
|
|
@@ -5113,6 +5254,7 @@ function subscriptions(subsOptions) {
|
|
|
5113
5254
|
try {
|
|
5114
5255
|
await syncWebhookPayload(syncCtx, payload, options.client, plans, subsOptions, {
|
|
5115
5256
|
dedupe: false,
|
|
5257
|
+
retryOnCallbackError: subsOptions.retryOnCallbackError !== false,
|
|
5116
5258
|
retryingRenewalCallback: claimed.lastError?.startsWith(
|
|
5117
5259
|
"Subscription callback onSubscriptionRenewed failed:"
|
|
5118
5260
|
) === true
|
|
@@ -5120,6 +5262,7 @@ function subscriptions(subsOptions) {
|
|
|
5120
5262
|
await markWebhookEventCompleted(syncCtx, claimed.id, claimed.lockedBy);
|
|
5121
5263
|
return { replayed: true, eventId };
|
|
5122
5264
|
} catch (err) {
|
|
5265
|
+
const maxAttempts = subsOptions.maxWebhookAttempts ?? DEFAULT_MAX_WEBHOOK_ATTEMPTS;
|
|
5123
5266
|
await recordWebhookEventFailure(
|
|
5124
5267
|
syncCtx,
|
|
5125
5268
|
claimed.id,
|
|
@@ -5127,7 +5270,7 @@ function subscriptions(subsOptions) {
|
|
|
5127
5270
|
null,
|
|
5128
5271
|
err,
|
|
5129
5272
|
claimed.lockedBy,
|
|
5130
|
-
|
|
5273
|
+
previousStatus === "dead_letter" || classifyWebhookFailure(err) === "PERMANENT" || claimed.attemptCount >= maxAttempts
|
|
5131
5274
|
);
|
|
5132
5275
|
throw err;
|
|
5133
5276
|
}
|
|
@@ -5306,6 +5449,13 @@ function verifyWebhookOrThrow(input) {
|
|
|
5306
5449
|
}
|
|
5307
5450
|
|
|
5308
5451
|
// src/plugins/webhooks.ts
|
|
5452
|
+
var DEFAULT_DUE_WEBHOOK_BATCH = 25;
|
|
5453
|
+
var ProcessDueWebhookEventsBody = z.object({ limit: z.number().int().min(1).max(100).optional() }).optional();
|
|
5454
|
+
function inProgressError() {
|
|
5455
|
+
return new APIError("SERVICE_UNAVAILABLE", {
|
|
5456
|
+
message: "Webhook event is already being processed. Retry later."
|
|
5457
|
+
});
|
|
5458
|
+
}
|
|
5309
5459
|
function toErrorCode(reason) {
|
|
5310
5460
|
return reason === "MISSING_HEADER" || reason === "INVALID_SIGNATURE" || reason === "EXPIRED" ? "UNAUTHORIZED" : "BAD_REQUEST";
|
|
5311
5461
|
}
|
|
@@ -5342,6 +5492,7 @@ var webhooks = (webhooksOptions) => {
|
|
|
5342
5492
|
throw new APIError("BAD_REQUEST", {
|
|
5343
5493
|
message: "Stored webhook payload is not a valid event envelope."
|
|
5344
5494
|
});
|
|
5495
|
+
const previousStatus = row.status;
|
|
5345
5496
|
const claimed = await claimWebhookEventForReplay(syncContext, row);
|
|
5346
5497
|
if (!claimed?.lockedBy)
|
|
5347
5498
|
throw new APIError("CONFLICT", {
|
|
@@ -5358,7 +5509,7 @@ var webhooks = (webhooksOptions) => {
|
|
|
5358
5509
|
row.signatureHeader,
|
|
5359
5510
|
err,
|
|
5360
5511
|
claimed.lockedBy,
|
|
5361
|
-
|
|
5512
|
+
previousStatus === "dead_letter" || claimed.attemptCount >= DEFAULT_MAX_WEBHOOK_ATTEMPTS
|
|
5362
5513
|
);
|
|
5363
5514
|
throw err;
|
|
5364
5515
|
}
|
|
@@ -5420,6 +5571,7 @@ var webhooks = (webhooksOptions) => {
|
|
|
5420
5571
|
signatureHeader
|
|
5421
5572
|
});
|
|
5422
5573
|
} catch (err) {
|
|
5574
|
+
if (err instanceof WebhookEventInProgressError) throw inProgressError();
|
|
5423
5575
|
const message = err instanceof Error ? err.message : String(err);
|
|
5424
5576
|
logger2.error(`subscription sync failed: ${message}`);
|
|
5425
5577
|
throw new APIError("INTERNAL_SERVER_ERROR", {
|
|
@@ -5436,6 +5588,7 @@ var webhooks = (webhooksOptions) => {
|
|
|
5436
5588
|
DEFAULT_MAX_WEBHOOK_ATTEMPTS,
|
|
5437
5589
|
"handlers"
|
|
5438
5590
|
) : null;
|
|
5591
|
+
if (claim?.action === "skip" && claim.reason === "in_progress") throw inProgressError();
|
|
5439
5592
|
if (claim && claim.action !== "process") return ctx.json({ received: true });
|
|
5440
5593
|
const row = claim?.action === "process" ? claim.row : null;
|
|
5441
5594
|
try {
|
|
@@ -5461,6 +5614,48 @@ var webhooks = (webhooksOptions) => {
|
|
|
5461
5614
|
}
|
|
5462
5615
|
return ctx.json({ received: true });
|
|
5463
5616
|
}
|
|
5617
|
+
),
|
|
5618
|
+
processDueStreampayWebhookEvents: createAuthEndpoint(
|
|
5619
|
+
"/streampay/webhooks/process-due",
|
|
5620
|
+
{
|
|
5621
|
+
method: "POST",
|
|
5622
|
+
body: ProcessDueWebhookEventsBody,
|
|
5623
|
+
metadata: { SERVER_ONLY: true }
|
|
5624
|
+
},
|
|
5625
|
+
async (ctx) => {
|
|
5626
|
+
const replay = registry?.replayWebhookEvent;
|
|
5627
|
+
if (!replay) {
|
|
5628
|
+
throw new APIError("BAD_REQUEST", {
|
|
5629
|
+
message: "Retry processing requires the webhook inbox: enable subscriptions or webhooks({ deduplicate: true })."
|
|
5630
|
+
});
|
|
5631
|
+
}
|
|
5632
|
+
const syncContext = { context: ctx.context };
|
|
5633
|
+
const due = await findDueWebhookEvents(
|
|
5634
|
+
syncContext,
|
|
5635
|
+
/* @__PURE__ */ new Date(),
|
|
5636
|
+
ctx.body?.limit ?? DEFAULT_DUE_WEBHOOK_BATCH
|
|
5637
|
+
);
|
|
5638
|
+
const succeeded = [];
|
|
5639
|
+
const failed = [];
|
|
5640
|
+
for (const row of due) {
|
|
5641
|
+
try {
|
|
5642
|
+
await replay(ctx, row.eventId);
|
|
5643
|
+
succeeded.push(row.eventId);
|
|
5644
|
+
} catch (err) {
|
|
5645
|
+
if (err instanceof APIError && err.status === "CONFLICT") continue;
|
|
5646
|
+
failed.push({
|
|
5647
|
+
eventId: row.eventId,
|
|
5648
|
+
error: err instanceof Error ? err.message : String(err)
|
|
5649
|
+
});
|
|
5650
|
+
}
|
|
5651
|
+
}
|
|
5652
|
+
if (failed.length > 0) {
|
|
5653
|
+
getLogger(ctx).error(
|
|
5654
|
+
`webhook retry: ${failed.length} of ${due.length} due events failed again`
|
|
5655
|
+
);
|
|
5656
|
+
}
|
|
5657
|
+
return ctx.json({ succeeded, failed });
|
|
5658
|
+
}
|
|
5464
5659
|
)
|
|
5465
5660
|
}
|
|
5466
5661
|
};
|
|
@@ -5585,7 +5780,7 @@ var onUserDelete = (options) => async (user, context) => {
|
|
|
5585
5780
|
|
|
5586
5781
|
// package.json
|
|
5587
5782
|
var package_default = {
|
|
5588
|
-
version: "3.0
|
|
5783
|
+
version: "3.2.0"};
|
|
5589
5784
|
|
|
5590
5785
|
// src/version.ts
|
|
5591
5786
|
var version = package_default.version;
|