better-auth-streampay 3.1.0 → 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 +245 -139
- 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 +245 -139
- package/dist/index.js.map +1 -1
- package/dist/{streampay-Bij1FvXa.d.cts → streampay-B7cFK2CP.d.cts} +4 -2
- package/dist/{streampay-Bij1FvXa.d.ts → streampay-B7cFK2CP.d.ts} +4 -2
- package/docs/integration.md +4 -2
- package/docs/staging-validation.md +1 -0
- package/docs/state-machines.md +323 -0
- package/docs/subscriptions.md +4 -1
- package/package.json +1 -1
package/dist/client.d.cts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { s as streampay, E as ErrorCodeEntry } from './streampay-
|
|
2
|
-
export { $ as $ERROR_CODES, S as StreamPayErrorCode } from './streampay-
|
|
1
|
+
import { s as streampay, E as ErrorCodeEntry } from './streampay-B7cFK2CP.cjs';
|
|
2
|
+
export { $ as $ERROR_CODES, S as StreamPayErrorCode } from './streampay-B7cFK2CP.cjs';
|
|
3
3
|
import 'better-auth';
|
|
4
4
|
import '@streamsdk/typescript';
|
|
5
5
|
import 'zod';
|
package/dist/client.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { s as streampay, E as ErrorCodeEntry } from './streampay-
|
|
2
|
-
export { $ as $ERROR_CODES, S as StreamPayErrorCode } from './streampay-
|
|
1
|
+
import { s as streampay, E as ErrorCodeEntry } from './streampay-B7cFK2CP.js';
|
|
2
|
+
export { $ as $ERROR_CODES, S as StreamPayErrorCode } from './streampay-B7cFK2CP.js';
|
|
3
3
|
import 'better-auth';
|
|
4
4
|
import '@streamsdk/typescript';
|
|
5
5
|
import 'zod';
|
package/dist/index.cjs
CHANGED
|
@@ -879,6 +879,120 @@ function projectPlanFields(sub, plans) {
|
|
|
879
879
|
pendingSeatsEffectiveAt: pendingSeats === null ? null : pendingEffectiveAt
|
|
880
880
|
};
|
|
881
881
|
}
|
|
882
|
+
|
|
883
|
+
// src/plugins/subscriptions/lifecycle.ts
|
|
884
|
+
function isAlreadyCanceledFreezeError(err) {
|
|
885
|
+
const sdkError = readSdkErrorFields(err);
|
|
886
|
+
const envelope = readEnvelope(sdkError.body);
|
|
887
|
+
return sdkError.status === 403 && envelope?.code === "STREAM_ERROR" && envelope.additionalInfo === "Cannot delete non-latest freeze entry.";
|
|
888
|
+
}
|
|
889
|
+
async function deactivatePaymentLink(client, paymentLinkId, log) {
|
|
890
|
+
if (!client.updatePaymentLinkStatus) {
|
|
891
|
+
log.warn(
|
|
892
|
+
`payment link=${paymentLinkId} stays payable: client does not implement updatePaymentLinkStatus.`
|
|
893
|
+
);
|
|
894
|
+
return;
|
|
895
|
+
}
|
|
896
|
+
try {
|
|
897
|
+
await client.updatePaymentLinkStatus(paymentLinkId, { status: "INACTIVE" });
|
|
898
|
+
} catch (err) {
|
|
899
|
+
if (readSdkErrorFields(err).status !== 404) throw err;
|
|
900
|
+
}
|
|
901
|
+
}
|
|
902
|
+
function subscriptionCouponIds(stream) {
|
|
903
|
+
return couponIdsFromMetadata(stream.coupon_calculation_metadata);
|
|
904
|
+
}
|
|
905
|
+
function couponIdsFromMetadata(metadata) {
|
|
906
|
+
const coupons = [];
|
|
907
|
+
for (const coupon of metadata?.coupons ?? []) {
|
|
908
|
+
if (coupon.coupon_id) coupons.push(coupon.coupon_id);
|
|
909
|
+
}
|
|
910
|
+
return coupons;
|
|
911
|
+
}
|
|
912
|
+
function subscriptionItemsForUpdate(stream, currentProductId, targetProductId, targetSeats) {
|
|
913
|
+
if (!stream.items?.length) {
|
|
914
|
+
throw invalidProviderItems("StreamPay returned a subscription without any items.");
|
|
915
|
+
}
|
|
916
|
+
const subscriptionCoupons = new Set(subscriptionCouponIds(stream));
|
|
917
|
+
let matches = 0;
|
|
918
|
+
const items = stream.items.map((item) => {
|
|
919
|
+
const productId = subscriptionItemProductId(item);
|
|
920
|
+
const quantity = item.quantity ?? 1;
|
|
921
|
+
if (!productId || !Number.isSafeInteger(quantity) || quantity < 1) {
|
|
922
|
+
throw invalidProviderItems("StreamPay returned an invalid subscription item.");
|
|
923
|
+
}
|
|
924
|
+
const isPlanItem = productId === currentProductId;
|
|
925
|
+
if (isPlanItem) matches += 1;
|
|
926
|
+
const itemCoupons = couponIdsFromMetadata(item.coupon_calculation_metadata).filter(
|
|
927
|
+
(couponId) => !subscriptionCoupons.has(couponId)
|
|
928
|
+
);
|
|
929
|
+
return {
|
|
930
|
+
product_id: isPlanItem ? targetProductId : productId,
|
|
931
|
+
quantity: isPlanItem ? targetSeats : quantity,
|
|
932
|
+
...itemCoupons.length > 0 ? { coupons: itemCoupons } : {}
|
|
933
|
+
};
|
|
934
|
+
});
|
|
935
|
+
if (matches !== 1) {
|
|
936
|
+
throw invalidProviderItems(
|
|
937
|
+
`Expected exactly one plan item for product "${currentProductId}", received ${matches}.`
|
|
938
|
+
);
|
|
939
|
+
}
|
|
940
|
+
return items;
|
|
941
|
+
}
|
|
942
|
+
function invalidProviderItems(message) {
|
|
943
|
+
return new api.APIError("INTERNAL_SERVER_ERROR", {
|
|
944
|
+
code: $ERROR_CODES.SUBSCRIPTION_INVALID_STATE.code,
|
|
945
|
+
message
|
|
946
|
+
});
|
|
947
|
+
}
|
|
948
|
+
function configuredPlanForSubscription(subscription, plans) {
|
|
949
|
+
const matches = plans.list.filter(
|
|
950
|
+
(plan) => subscription.items?.some((item) => subscriptionItemProductId(item) === plan.productId)
|
|
951
|
+
);
|
|
952
|
+
if (matches.length > 1) {
|
|
953
|
+
throw invalidProviderItems(
|
|
954
|
+
"StreamPay returned a subscription containing multiple configured plan products."
|
|
955
|
+
);
|
|
956
|
+
}
|
|
957
|
+
return matches[0];
|
|
958
|
+
}
|
|
959
|
+
async function findSubscriptionFreeze(client, options, subscriptionId, matches) {
|
|
960
|
+
const listPage = options.listSubscriptionFreezes;
|
|
961
|
+
if (!listPage) {
|
|
962
|
+
const response = await client.listSubscriptionFreezes(subscriptionId);
|
|
963
|
+
return {
|
|
964
|
+
freeze: response.data?.find(matches),
|
|
965
|
+
hasMore: response.pagination?.has_next_page ?? false
|
|
966
|
+
};
|
|
967
|
+
}
|
|
968
|
+
const seenIds = /* @__PURE__ */ new Set();
|
|
969
|
+
for (let page = 1; page <= 100; page++) {
|
|
970
|
+
const response = await listPage(subscriptionId, { page, limit: 100 });
|
|
971
|
+
const pagination = response.pagination;
|
|
972
|
+
if (!Array.isArray(response.data) || !pagination || pagination.current_page !== page || typeof pagination.has_next_page !== "boolean") {
|
|
973
|
+
throw freezePaginationConflict("StreamPay returned invalid freeze pagination.");
|
|
974
|
+
}
|
|
975
|
+
let advanced = false;
|
|
976
|
+
for (const freeze2 of response.data) {
|
|
977
|
+
if (freeze2.id && !seenIds.has(freeze2.id)) {
|
|
978
|
+
seenIds.add(freeze2.id);
|
|
979
|
+
advanced = true;
|
|
980
|
+
}
|
|
981
|
+
}
|
|
982
|
+
if (!advanced && (pagination.has_next_page || response.data.length > 0)) {
|
|
983
|
+
throw freezePaginationConflict("StreamPay freeze pagination returned no new entries.");
|
|
984
|
+
}
|
|
985
|
+
const freeze = response.data.find(matches);
|
|
986
|
+
if (freeze || !pagination.has_next_page) return { freeze, hasMore: false };
|
|
987
|
+
}
|
|
988
|
+
throw freezePaginationConflict("StreamPay freeze pagination exceeded 100 pages.");
|
|
989
|
+
}
|
|
990
|
+
function freezePaginationConflict(message) {
|
|
991
|
+
return new api.APIError("CONFLICT", {
|
|
992
|
+
code: $ERROR_CODES.SUBSCRIPTION_INVALID_STATE.code,
|
|
993
|
+
message
|
|
994
|
+
});
|
|
995
|
+
}
|
|
882
996
|
function subscriptionSlotKey(referenceType, referenceId, group) {
|
|
883
997
|
const tuple = JSON.stringify([referenceType, referenceId, group ?? null]);
|
|
884
998
|
return `sp_slot_v1_${crypto.createHash("sha256").update(tuple).digest("hex")}`;
|
|
@@ -1207,12 +1321,77 @@ var SubscriptionCorrelationError = class extends Error {
|
|
|
1207
1321
|
this.name = "SubscriptionCorrelationError";
|
|
1208
1322
|
}
|
|
1209
1323
|
};
|
|
1210
|
-
async function
|
|
1324
|
+
async function takeSlotFromReservation(ctx, client, slotKey, ownerRowId, streampaySubscriptionId) {
|
|
1325
|
+
const holder = await ctx.context.adapter.findOne({
|
|
1326
|
+
model: SUBSCRIPTION_MODEL2,
|
|
1327
|
+
where: [{ field: "activeSlotKey", value: slotKey }]
|
|
1328
|
+
});
|
|
1329
|
+
if (!holder || holder.id === ownerRowId) return;
|
|
1330
|
+
if (holder.status !== "incomplete" || holder.streampaySubscriptionId) {
|
|
1331
|
+
throw new SubscriptionCorrelationError(
|
|
1332
|
+
`StreamPay sub=${streampaySubscriptionId} needs the billing slot held by live row=${holder.id} (${holder.status}). Resolve the duplicate subscription, then replay.`
|
|
1333
|
+
);
|
|
1334
|
+
}
|
|
1335
|
+
if (holder.streampayPaymentLinkId) {
|
|
1336
|
+
try {
|
|
1337
|
+
await deactivatePaymentLink(client, holder.streampayPaymentLinkId, logger(ctx));
|
|
1338
|
+
} catch (err) {
|
|
1339
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
1340
|
+
logger(ctx).error(
|
|
1341
|
+
`payment link=${holder.streampayPaymentLinkId} of released row=${holder.id} could not be deactivated and may still be paid; deactivate it manually: ${message}`
|
|
1342
|
+
);
|
|
1343
|
+
}
|
|
1344
|
+
}
|
|
1345
|
+
const released = await ctx.context.adapter.update({
|
|
1346
|
+
model: SUBSCRIPTION_MODEL2,
|
|
1347
|
+
update: { status: "incomplete_expired", activeSlotKey: null, updatedAt: /* @__PURE__ */ new Date() },
|
|
1348
|
+
where: [
|
|
1349
|
+
{ field: "id", value: holder.id },
|
|
1350
|
+
{ field: "status", value: "incomplete" },
|
|
1351
|
+
{ field: "activeSlotKey", value: slotKey },
|
|
1352
|
+
{ field: "streampayPaymentLinkId", value: holder.streampayPaymentLinkId ?? null }
|
|
1353
|
+
]
|
|
1354
|
+
});
|
|
1355
|
+
if (!released) {
|
|
1356
|
+
throw new Error(`Checkout reservation row=${holder.id} changed while releasing its slot.`);
|
|
1357
|
+
}
|
|
1358
|
+
logger(ctx).warn(
|
|
1359
|
+
`released checkout reservation row=${holder.id} for paid StreamPay sub=${streampaySubscriptionId}.`
|
|
1360
|
+
);
|
|
1361
|
+
}
|
|
1362
|
+
async function linkReservedRow(ctx, client, row, projected, metadataReferenceType, streampaySubscriptionId) {
|
|
1363
|
+
const activeSlotKey = projected.activeSlotKey === null ? null : row.activeSlotKey ?? subscriptionSlotKey(
|
|
1364
|
+
row.referenceType ?? metadataReferenceType ?? "user",
|
|
1365
|
+
row.referenceId,
|
|
1366
|
+
projected.group === void 0 ? row.group : projected.group
|
|
1367
|
+
);
|
|
1368
|
+
return updateReconciledSubscription(
|
|
1369
|
+
ctx,
|
|
1370
|
+
client,
|
|
1371
|
+
row,
|
|
1372
|
+
{
|
|
1373
|
+
...projected,
|
|
1374
|
+
billingStatus: row.billingStatus ?? "current",
|
|
1375
|
+
...activeSlotKey === null ? {} : { activeSlotKey }
|
|
1376
|
+
},
|
|
1377
|
+
streampaySubscriptionId
|
|
1378
|
+
);
|
|
1379
|
+
}
|
|
1380
|
+
async function updateReconciledSubscription(ctx, client, existing, projected, streampaySubscriptionId) {
|
|
1211
1381
|
if (existing.providerUpdatedAt instanceof Date && projected.providerUpdatedAt instanceof Date && projected.providerUpdatedAt.getTime() < existing.providerUpdatedAt.getTime()) {
|
|
1212
1382
|
throw new Error(
|
|
1213
1383
|
`StreamPay returned stale subscription state for sub=${streampaySubscriptionId}. Retry reconciliation.`
|
|
1214
1384
|
);
|
|
1215
1385
|
}
|
|
1386
|
+
if (projected.activeSlotKey && projected.activeSlotKey !== existing.activeSlotKey) {
|
|
1387
|
+
await takeSlotFromReservation(
|
|
1388
|
+
ctx,
|
|
1389
|
+
client,
|
|
1390
|
+
projected.activeSlotKey,
|
|
1391
|
+
existing.id,
|
|
1392
|
+
streampaySubscriptionId
|
|
1393
|
+
);
|
|
1394
|
+
}
|
|
1216
1395
|
const updated = await ctx.context.adapter.update({
|
|
1217
1396
|
model: SUBSCRIPTION_MODEL2,
|
|
1218
1397
|
update: projected,
|
|
@@ -1288,6 +1467,7 @@ async function reconcileFromStreamPay(ctx, payload, client, plans) {
|
|
|
1288
1467
|
}
|
|
1289
1468
|
const updated = await updateReconciledSubscription(
|
|
1290
1469
|
ctx,
|
|
1470
|
+
client,
|
|
1291
1471
|
existing,
|
|
1292
1472
|
projected,
|
|
1293
1473
|
streampaySubscriptionId
|
|
@@ -1321,21 +1501,12 @@ async function reconcileFromStreamPay(ctx, payload, client, plans) {
|
|
|
1321
1501
|
`webhook ${payload.event_type}: referenced subscription row=${localRowId} is missing; rebuilding from signed metadata.`
|
|
1322
1502
|
);
|
|
1323
1503
|
} 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)) {
|
|
1324
|
-
const
|
|
1325
|
-
...projected,
|
|
1326
|
-
billingStatus: metadataRow.billingStatus ?? "current",
|
|
1327
|
-
...projected.activeSlotKey === null ? {} : {
|
|
1328
|
-
activeSlotKey: metadataRow.activeSlotKey ?? subscriptionSlotKey(
|
|
1329
|
-
metadataRow.referenceType ?? metadataReferenceType ?? "user",
|
|
1330
|
-
metadataRow.referenceId,
|
|
1331
|
-
projected.group === void 0 ? metadataRow.group : projected.group
|
|
1332
|
-
)
|
|
1333
|
-
}
|
|
1334
|
-
};
|
|
1335
|
-
const updated = await updateReconciledSubscription(
|
|
1504
|
+
const updated = await linkReservedRow(
|
|
1336
1505
|
ctx,
|
|
1506
|
+
client,
|
|
1337
1507
|
metadataRow,
|
|
1338
|
-
|
|
1508
|
+
projected,
|
|
1509
|
+
metadataReferenceType,
|
|
1339
1510
|
streampaySubscriptionId
|
|
1340
1511
|
);
|
|
1341
1512
|
return { row: updated, stream };
|
|
@@ -1358,30 +1529,22 @@ async function reconcileFromStreamPay(ctx, payload, client, plans) {
|
|
|
1358
1529
|
stream.organization_consumer_id ?? null
|
|
1359
1530
|
);
|
|
1360
1531
|
if (incomplete) {
|
|
1361
|
-
const
|
|
1362
|
-
...projected,
|
|
1363
|
-
billingStatus: incomplete.billingStatus ?? "current",
|
|
1364
|
-
...projected.activeSlotKey === null ? {} : {
|
|
1365
|
-
activeSlotKey: incomplete.activeSlotKey ?? subscriptionSlotKey(
|
|
1366
|
-
incomplete.referenceType ?? metadataReferenceType ?? "user",
|
|
1367
|
-
incomplete.referenceId,
|
|
1368
|
-
projected.group === void 0 ? incomplete.group : projected.group
|
|
1369
|
-
)
|
|
1370
|
-
}
|
|
1371
|
-
};
|
|
1372
|
-
const updated = await updateReconciledSubscription(
|
|
1532
|
+
const updated = await linkReservedRow(
|
|
1373
1533
|
ctx,
|
|
1534
|
+
client,
|
|
1374
1535
|
incomplete,
|
|
1375
|
-
|
|
1536
|
+
projected,
|
|
1537
|
+
metadataReferenceType,
|
|
1376
1538
|
streampaySubscriptionId
|
|
1377
1539
|
);
|
|
1378
|
-
return {
|
|
1379
|
-
row: updated,
|
|
1380
|
-
stream
|
|
1381
|
-
};
|
|
1540
|
+
return { row: updated, stream };
|
|
1382
1541
|
}
|
|
1383
1542
|
const plan = plans.byName.get(planName);
|
|
1384
1543
|
const referenceType = metadataReferenceType ?? "custom";
|
|
1544
|
+
const activeSlotKey = isTerminalSubscriptionStatus(projected.status) ? null : subscriptionSlotKey(referenceType, referenceId, plan?.group);
|
|
1545
|
+
if (activeSlotKey) {
|
|
1546
|
+
await takeSlotFromReservation(ctx, client, activeSlotKey, null, streampaySubscriptionId);
|
|
1547
|
+
}
|
|
1385
1548
|
const row = await ctx.context.adapter.create({
|
|
1386
1549
|
model: SUBSCRIPTION_MODEL2,
|
|
1387
1550
|
data: {
|
|
@@ -1390,7 +1553,7 @@ async function reconcileFromStreamPay(ctx, payload, client, plans) {
|
|
|
1390
1553
|
...projected,
|
|
1391
1554
|
referenceId,
|
|
1392
1555
|
referenceType,
|
|
1393
|
-
activeSlotKey
|
|
1556
|
+
activeSlotKey,
|
|
1394
1557
|
streampayPaymentLinkId: paymentLinkId,
|
|
1395
1558
|
plan: planName,
|
|
1396
1559
|
planVersion: plan?.version ?? null,
|
|
@@ -3260,6 +3423,12 @@ function checkoutInProgressError() {
|
|
|
3260
3423
|
message: "A subscription checkout is already being created for this plan group."
|
|
3261
3424
|
});
|
|
3262
3425
|
}
|
|
3426
|
+
function subscriptionAlreadyActiveError() {
|
|
3427
|
+
return new api.APIError("CONFLICT", {
|
|
3428
|
+
code: $ERROR_CODES.SUBSCRIPTION_ALREADY_ACTIVE.code,
|
|
3429
|
+
message: "An active subscription already exists for this plan group."
|
|
3430
|
+
});
|
|
3431
|
+
}
|
|
3263
3432
|
async function resumeOrReserveCheckoutSlot(args) {
|
|
3264
3433
|
const { client, adapter, candidates, activeSlotKey, planName, seats, now, log } = args;
|
|
3265
3434
|
const matchesCheckout = (row2) => row2.plan === planName && (row2.seats ?? 1) === seats;
|
|
@@ -3306,7 +3475,8 @@ async function resumeOrReserveCheckoutSlot(args) {
|
|
|
3306
3475
|
model: SUBSCRIPTION_MODEL4,
|
|
3307
3476
|
where: [{ field: "activeSlotKey", value: activeSlotKey }]
|
|
3308
3477
|
});
|
|
3309
|
-
if (reserved
|
|
3478
|
+
if (!reserved) throw err;
|
|
3479
|
+
if (reserved.status !== "incomplete") throw subscriptionAlreadyActiveError();
|
|
3310
3480
|
if (matchesCheckout(reserved)) {
|
|
3311
3481
|
let recovery;
|
|
3312
3482
|
try {
|
|
@@ -3327,6 +3497,20 @@ async function resumeOrReserveCheckoutSlot(args) {
|
|
|
3327
3497
|
}
|
|
3328
3498
|
const reservationIsStale = !(reserved.createdAt instanceof Date) || now - reserved.createdAt.getTime() >= UPGRADE_IDEMPOTENCY_WINDOW_MS;
|
|
3329
3499
|
if (!reservationIsStale) throw checkoutInProgressError();
|
|
3500
|
+
if (reserved.streampayPaymentLinkId) {
|
|
3501
|
+
try {
|
|
3502
|
+
await deactivatePaymentLink(client, reserved.streampayPaymentLinkId, log);
|
|
3503
|
+
} catch (deactivationError) {
|
|
3504
|
+
toAPIError(
|
|
3505
|
+
{
|
|
3506
|
+
logPrefix: `deactivate stale checkout link=${reserved.streampayPaymentLinkId} failed for row=${reserved.id}:`,
|
|
3507
|
+
userMessage: "Unable to replace the previous subscription checkout."
|
|
3508
|
+
},
|
|
3509
|
+
deactivationError,
|
|
3510
|
+
log
|
|
3511
|
+
);
|
|
3512
|
+
}
|
|
3513
|
+
}
|
|
3330
3514
|
const released = await adapter.update({
|
|
3331
3515
|
model: SUBSCRIPTION_MODEL4,
|
|
3332
3516
|
update: { status: "incomplete_expired", activeSlotKey: null, updatedAt: /* @__PURE__ */ new Date() },
|
|
@@ -3350,105 +3534,6 @@ async function resumeOrReserveCheckoutSlot(args) {
|
|
|
3350
3534
|
}
|
|
3351
3535
|
return { kind: "reserved", row, consumerId };
|
|
3352
3536
|
}
|
|
3353
|
-
function isAlreadyCanceledFreezeError(err) {
|
|
3354
|
-
const sdkError = readSdkErrorFields(err);
|
|
3355
|
-
const envelope = readEnvelope(sdkError.body);
|
|
3356
|
-
return sdkError.status === 403 && envelope?.code === "STREAM_ERROR" && envelope.additionalInfo === "Cannot delete non-latest freeze entry.";
|
|
3357
|
-
}
|
|
3358
|
-
function subscriptionCouponIds(stream) {
|
|
3359
|
-
return couponIdsFromMetadata(stream.coupon_calculation_metadata);
|
|
3360
|
-
}
|
|
3361
|
-
function couponIdsFromMetadata(metadata) {
|
|
3362
|
-
const coupons = [];
|
|
3363
|
-
for (const coupon of metadata?.coupons ?? []) {
|
|
3364
|
-
if (coupon.coupon_id) coupons.push(coupon.coupon_id);
|
|
3365
|
-
}
|
|
3366
|
-
return coupons;
|
|
3367
|
-
}
|
|
3368
|
-
function subscriptionItemsForUpdate(stream, currentProductId, targetProductId, targetSeats) {
|
|
3369
|
-
if (!stream.items?.length) {
|
|
3370
|
-
throw invalidProviderItems("StreamPay returned a subscription without any items.");
|
|
3371
|
-
}
|
|
3372
|
-
const subscriptionCoupons = new Set(subscriptionCouponIds(stream));
|
|
3373
|
-
let matches = 0;
|
|
3374
|
-
const items = stream.items.map((item) => {
|
|
3375
|
-
const productId = subscriptionItemProductId(item);
|
|
3376
|
-
const quantity = item.quantity ?? 1;
|
|
3377
|
-
if (!productId || !Number.isSafeInteger(quantity) || quantity < 1) {
|
|
3378
|
-
throw invalidProviderItems("StreamPay returned an invalid subscription item.");
|
|
3379
|
-
}
|
|
3380
|
-
const isPlanItem = productId === currentProductId;
|
|
3381
|
-
if (isPlanItem) matches += 1;
|
|
3382
|
-
const itemCoupons = couponIdsFromMetadata(item.coupon_calculation_metadata).filter(
|
|
3383
|
-
(couponId) => !subscriptionCoupons.has(couponId)
|
|
3384
|
-
);
|
|
3385
|
-
return {
|
|
3386
|
-
product_id: isPlanItem ? targetProductId : productId,
|
|
3387
|
-
quantity: isPlanItem ? targetSeats : quantity,
|
|
3388
|
-
...itemCoupons.length > 0 ? { coupons: itemCoupons } : {}
|
|
3389
|
-
};
|
|
3390
|
-
});
|
|
3391
|
-
if (matches !== 1) {
|
|
3392
|
-
throw invalidProviderItems(
|
|
3393
|
-
`Expected exactly one plan item for product "${currentProductId}", received ${matches}.`
|
|
3394
|
-
);
|
|
3395
|
-
}
|
|
3396
|
-
return items;
|
|
3397
|
-
}
|
|
3398
|
-
function invalidProviderItems(message) {
|
|
3399
|
-
return new api.APIError("INTERNAL_SERVER_ERROR", {
|
|
3400
|
-
code: $ERROR_CODES.SUBSCRIPTION_INVALID_STATE.code,
|
|
3401
|
-
message
|
|
3402
|
-
});
|
|
3403
|
-
}
|
|
3404
|
-
function configuredPlanForSubscription(subscription, plans) {
|
|
3405
|
-
const matches = plans.list.filter(
|
|
3406
|
-
(plan) => subscription.items?.some((item) => subscriptionItemProductId(item) === plan.productId)
|
|
3407
|
-
);
|
|
3408
|
-
if (matches.length > 1) {
|
|
3409
|
-
throw invalidProviderItems(
|
|
3410
|
-
"StreamPay returned a subscription containing multiple configured plan products."
|
|
3411
|
-
);
|
|
3412
|
-
}
|
|
3413
|
-
return matches[0];
|
|
3414
|
-
}
|
|
3415
|
-
async function findSubscriptionFreeze(client, options, subscriptionId, matches) {
|
|
3416
|
-
const listPage = options.listSubscriptionFreezes;
|
|
3417
|
-
if (!listPage) {
|
|
3418
|
-
const response = await client.listSubscriptionFreezes(subscriptionId);
|
|
3419
|
-
return {
|
|
3420
|
-
freeze: response.data?.find(matches),
|
|
3421
|
-
hasMore: response.pagination?.has_next_page ?? false
|
|
3422
|
-
};
|
|
3423
|
-
}
|
|
3424
|
-
const seenIds = /* @__PURE__ */ new Set();
|
|
3425
|
-
for (let page = 1; page <= 100; page++) {
|
|
3426
|
-
const response = await listPage(subscriptionId, { page, limit: 100 });
|
|
3427
|
-
const pagination = response.pagination;
|
|
3428
|
-
if (!Array.isArray(response.data) || !pagination || pagination.current_page !== page || typeof pagination.has_next_page !== "boolean") {
|
|
3429
|
-
throw freezePaginationConflict("StreamPay returned invalid freeze pagination.");
|
|
3430
|
-
}
|
|
3431
|
-
let advanced = false;
|
|
3432
|
-
for (const freeze2 of response.data) {
|
|
3433
|
-
if (freeze2.id && !seenIds.has(freeze2.id)) {
|
|
3434
|
-
seenIds.add(freeze2.id);
|
|
3435
|
-
advanced = true;
|
|
3436
|
-
}
|
|
3437
|
-
}
|
|
3438
|
-
if (!advanced && (pagination.has_next_page || response.data.length > 0)) {
|
|
3439
|
-
throw freezePaginationConflict("StreamPay freeze pagination returned no new entries.");
|
|
3440
|
-
}
|
|
3441
|
-
const freeze = response.data.find(matches);
|
|
3442
|
-
if (freeze || !pagination.has_next_page) return { freeze, hasMore: false };
|
|
3443
|
-
}
|
|
3444
|
-
throw freezePaginationConflict("StreamPay freeze pagination exceeded 100 pages.");
|
|
3445
|
-
}
|
|
3446
|
-
function freezePaginationConflict(message) {
|
|
3447
|
-
return new api.APIError("CONFLICT", {
|
|
3448
|
-
code: $ERROR_CODES.SUBSCRIPTION_INVALID_STATE.code,
|
|
3449
|
-
message
|
|
3450
|
-
});
|
|
3451
|
-
}
|
|
3452
3537
|
var SUBSCRIPTION_INTERVALS = ["WEEK", "MONTH", "QUARTER", "YEAR"];
|
|
3453
3538
|
var PlanSchema = zod.z.object({
|
|
3454
3539
|
name: zod.z.string().min(1, "every plan must have a non-empty `name`."),
|
|
@@ -4113,6 +4198,24 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
|
|
|
4113
4198
|
`failed to persist payment link=${paymentLinkId} for row=${row.id}: ${message}. Protected checkout metadata will reconcile the row from the webhook.`
|
|
4114
4199
|
);
|
|
4115
4200
|
}
|
|
4201
|
+
if (updatedRow?.status === "incomplete_expired") {
|
|
4202
|
+
getLogger(ctx).warn(
|
|
4203
|
+
`checkout reservation row=${row.id} was released while payment link=${paymentLinkId} was created; deactivating the link.`
|
|
4204
|
+
);
|
|
4205
|
+
try {
|
|
4206
|
+
await deactivatePaymentLink(client, paymentLinkId, getLogger(ctx));
|
|
4207
|
+
} catch (deactivationError) {
|
|
4208
|
+
toAPIError(
|
|
4209
|
+
{
|
|
4210
|
+
logPrefix: `deactivate orphaned checkout link=${paymentLinkId} failed for row=${row.id}:`,
|
|
4211
|
+
userMessage: "Failed to start subscription checkout."
|
|
4212
|
+
},
|
|
4213
|
+
deactivationError,
|
|
4214
|
+
getLogger(ctx)
|
|
4215
|
+
);
|
|
4216
|
+
}
|
|
4217
|
+
throw checkoutInProgressError();
|
|
4218
|
+
}
|
|
4116
4219
|
return ctx.json({
|
|
4117
4220
|
subscriptionId: updatedRow?.id ?? row.id,
|
|
4118
4221
|
url,
|
|
@@ -5105,9 +5208,9 @@ function subscriptions(subsOptions) {
|
|
|
5105
5208
|
}
|
|
5106
5209
|
};
|
|
5107
5210
|
if (dedupeEnabled) {
|
|
5108
|
-
registry.replayWebhookEvent = async (ctx, eventId
|
|
5211
|
+
registry.replayWebhookEvent = async (ctx, eventId) => {
|
|
5109
5212
|
if (eventId.startsWith("handlers:") && registry.replayWebhookHandler) {
|
|
5110
|
-
return registry.replayWebhookHandler(ctx, eventId
|
|
5213
|
+
return registry.replayWebhookHandler(ctx, eventId);
|
|
5111
5214
|
}
|
|
5112
5215
|
const syncCtx = {
|
|
5113
5216
|
context: ctx.context
|
|
@@ -5142,6 +5245,7 @@ function subscriptions(subsOptions) {
|
|
|
5142
5245
|
}
|
|
5143
5246
|
const payload = parsedPayload;
|
|
5144
5247
|
const plans = await plansRef();
|
|
5248
|
+
const previousStatus = row.status;
|
|
5145
5249
|
const claimed = await claimWebhookEventForReplay(syncCtx, row);
|
|
5146
5250
|
if (!claimed?.lockedBy) {
|
|
5147
5251
|
throw new api.APIError("CONFLICT", {
|
|
@@ -5152,6 +5256,7 @@ function subscriptions(subsOptions) {
|
|
|
5152
5256
|
try {
|
|
5153
5257
|
await syncWebhookPayload(syncCtx, payload, options.client, plans, subsOptions, {
|
|
5154
5258
|
dedupe: false,
|
|
5259
|
+
retryOnCallbackError: subsOptions.retryOnCallbackError !== false,
|
|
5155
5260
|
retryingRenewalCallback: claimed.lastError?.startsWith(
|
|
5156
5261
|
"Subscription callback onSubscriptionRenewed failed:"
|
|
5157
5262
|
) === true
|
|
@@ -5167,7 +5272,7 @@ function subscriptions(subsOptions) {
|
|
|
5167
5272
|
null,
|
|
5168
5273
|
err,
|
|
5169
5274
|
claimed.lockedBy,
|
|
5170
|
-
|
|
5275
|
+
previousStatus === "dead_letter" || classifyWebhookFailure(err) === "PERMANENT" || claimed.attemptCount >= maxAttempts
|
|
5171
5276
|
);
|
|
5172
5277
|
throw err;
|
|
5173
5278
|
}
|
|
@@ -5367,7 +5472,7 @@ var webhooks = (webhooksOptions) => {
|
|
|
5367
5472
|
return (_options, registry) => {
|
|
5368
5473
|
const { secret, toleranceSeconds, deduplicate = false, ...handlers } = webhooksOptions;
|
|
5369
5474
|
if (deduplicate && registry) {
|
|
5370
|
-
registry.replayWebhookHandler = async (ctx, eventId
|
|
5475
|
+
registry.replayWebhookHandler = async (ctx, eventId) => {
|
|
5371
5476
|
const syncContext = { context: ctx.context };
|
|
5372
5477
|
const row = await syncContext.context.adapter.findOne({
|
|
5373
5478
|
model: WEBHOOK_EVENT_MODEL,
|
|
@@ -5389,6 +5494,7 @@ var webhooks = (webhooksOptions) => {
|
|
|
5389
5494
|
throw new api.APIError("BAD_REQUEST", {
|
|
5390
5495
|
message: "Stored webhook payload is not a valid event envelope."
|
|
5391
5496
|
});
|
|
5497
|
+
const previousStatus = row.status;
|
|
5392
5498
|
const claimed = await claimWebhookEventForReplay(syncContext, row);
|
|
5393
5499
|
if (!claimed?.lockedBy)
|
|
5394
5500
|
throw new api.APIError("CONFLICT", {
|
|
@@ -5405,7 +5511,7 @@ var webhooks = (webhooksOptions) => {
|
|
|
5405
5511
|
row.signatureHeader,
|
|
5406
5512
|
err,
|
|
5407
5513
|
claimed.lockedBy,
|
|
5408
|
-
|
|
5514
|
+
previousStatus === "dead_letter" || claimed.attemptCount >= DEFAULT_MAX_WEBHOOK_ATTEMPTS
|
|
5409
5515
|
);
|
|
5410
5516
|
throw err;
|
|
5411
5517
|
}
|
|
@@ -5535,7 +5641,7 @@ var webhooks = (webhooksOptions) => {
|
|
|
5535
5641
|
const failed = [];
|
|
5536
5642
|
for (const row of due) {
|
|
5537
5643
|
try {
|
|
5538
|
-
await replay(ctx, row.eventId
|
|
5644
|
+
await replay(ctx, row.eventId);
|
|
5539
5645
|
succeeded.push(row.eventId);
|
|
5540
5646
|
} catch (err) {
|
|
5541
5647
|
if (err instanceof api.APIError && err.status === "CONFLICT") continue;
|
|
@@ -5676,7 +5782,7 @@ var onUserDelete = (options) => async (user, context) => {
|
|
|
5676
5782
|
|
|
5677
5783
|
// package.json
|
|
5678
5784
|
var package_default = {
|
|
5679
|
-
version: "3.
|
|
5785
|
+
version: "3.2.0"};
|
|
5680
5786
|
|
|
5681
5787
|
// src/version.ts
|
|
5682
5788
|
var version = package_default.version;
|