@fantastic.dev/better-stripe 0.52.0 → 0.54.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/CHANGELOG.md +12 -0
- package/README.md +1 -1
- package/dist/client/connect/payoutAdoptionTestHelpers.d.ts +160 -2
- package/dist/client/connect/payoutAdoptionTestHelpers.d.ts.map +1 -1
- package/dist/client/connect/payoutExecutionTestHelpers.d.ts +80 -1
- package/dist/client/connect/payoutExecutionTestHelpers.d.ts.map +1 -1
- package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts +160 -2
- package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts.map +1 -1
- package/dist/client/connect/payoutSyncTestHelpers.d.ts +80 -1
- package/dist/client/connect/payoutSyncTestHelpers.d.ts.map +1 -1
- package/dist/client/index.d.ts +6 -0
- package/dist/client/index.d.ts.map +1 -1
- package/dist/client/index.js +2 -0
- package/dist/client/index.js.map +1 -1
- package/dist/client/products/catalogClient.d.ts +23 -0
- package/dist/client/products/catalogClient.d.ts.map +1 -1
- package/dist/client/products/catalogClient.js +32 -0
- package/dist/client/products/catalogClient.js.map +1 -1
- package/dist/client/products/fixedPrice.d.ts +4 -0
- package/dist/client/products/fixedPrice.d.ts.map +1 -0
- package/dist/client/products/fixedPrice.js +10 -0
- package/dist/client/products/fixedPrice.js.map +1 -0
- package/dist/client/products/products.d.ts.map +1 -1
- package/dist/client/products/products.js +3 -0
- package/dist/client/products/products.js.map +1 -1
- package/dist/client/usage/catalog.d.ts +7 -0
- package/dist/client/usage/catalog.d.ts.map +1 -0
- package/dist/client/usage/catalog.js +55 -0
- package/dist/client/usage/catalog.js.map +1 -0
- package/dist/client/usage/catalogLifecycle.d.ts +25 -0
- package/dist/client/usage/catalogLifecycle.d.ts.map +1 -0
- package/dist/client/usage/catalogLifecycle.js +64 -0
- package/dist/client/usage/catalogLifecycle.js.map +1 -0
- package/dist/client/usage/catalogMath.d.ts +3 -0
- package/dist/client/usage/catalogMath.d.ts.map +1 -0
- package/dist/client/usage/catalogMath.js +21 -0
- package/dist/client/usage/catalogMath.js.map +1 -0
- package/dist/client/usage/catalogPrices.d.ts +5 -0
- package/dist/client/usage/catalogPrices.d.ts.map +1 -0
- package/dist/client/usage/catalogPrices.js +178 -0
- package/dist/client/usage/catalogPrices.js.map +1 -0
- package/dist/client/usage/catalogRead.d.ts +25 -0
- package/dist/client/usage/catalogRead.d.ts.map +1 -0
- package/dist/client/usage/catalogRead.js +71 -0
- package/dist/client/usage/catalogRead.js.map +1 -0
- package/dist/client/usage/catalogTypes.d.ts +97 -0
- package/dist/client/usage/catalogTypes.d.ts.map +1 -0
- package/dist/client/usage/catalogTypes.js +106 -0
- package/dist/client/usage/catalogTypes.js.map +1 -0
- package/dist/client/usage/client.d.ts +2 -2
- package/dist/client/usage/client.d.ts.map +1 -1
- package/dist/client/usage/client.js +3 -3
- package/dist/client/usage/client.js.map +1 -1
- package/dist/client/usage/deliveryClient.d.ts +64 -0
- package/dist/client/usage/deliveryClient.d.ts.map +1 -0
- package/dist/client/usage/deliveryClient.js +60 -0
- package/dist/client/usage/deliveryClient.js.map +1 -0
- package/dist/client/usage/deliveryProtocol.d.ts +130 -0
- package/dist/client/usage/deliveryProtocol.d.ts.map +1 -0
- package/dist/client/usage/deliveryProtocol.js +21 -0
- package/dist/client/usage/deliveryProtocol.js.map +1 -0
- package/dist/client/usage/deliveryProvider.d.ts +32 -0
- package/dist/client/usage/deliveryProvider.d.ts.map +1 -0
- package/dist/client/usage/deliveryProvider.js +127 -0
- package/dist/client/usage/deliveryProvider.js.map +1 -0
- package/dist/client/usage/index.d.ts +3 -0
- package/dist/client/usage/index.d.ts.map +1 -1
- package/dist/client/usage/index.js +1 -0
- package/dist/client/usage/index.js.map +1 -1
- package/dist/client/webhooks/handler.d.ts.map +1 -1
- package/dist/client/webhooks/handler.js +2 -1
- package/dist/client/webhooks/handler.js.map +1 -1
- package/dist/client/webhooks/meterErrors.d.ts +5 -0
- package/dist/client/webhooks/meterErrors.d.ts.map +1 -0
- package/dist/client/webhooks/meterErrors.js +98 -0
- package/dist/client/webhooks/meterErrors.js.map +1 -0
- package/dist/client/webhooks/processors.d.ts.map +1 -1
- package/dist/client/webhooks/processors.js +3 -0
- package/dist/client/webhooks/processors.js.map +1 -1
- package/dist/client/webhooks/v2.d.ts.map +1 -1
- package/dist/client/webhooks/v2.js +5 -0
- package/dist/client/webhooks/v2.js.map +1 -1
- package/dist/component/_generated/api.d.ts +18 -0
- package/dist/component/_generated/api.d.ts.map +1 -1
- package/dist/component/_generated/api.js.map +1 -1
- package/dist/component/_generated/component.d.ts +232 -0
- package/dist/component/_generated/component.d.ts.map +1 -1
- package/dist/component/earnings/triggers.d.ts +150 -2
- package/dist/component/earnings/triggers.d.ts.map +1 -1
- package/dist/component/payoutRelease/queries.d.ts +2 -2
- package/dist/component/payoutRelease/queries.d.ts.map +1 -1
- package/dist/component/refundHistory/queries.d.ts +1 -1
- package/dist/component/schema.d.ts +80 -1
- package/dist/component/schema.js +5 -0
- package/dist/component/schema.js.map +1 -1
- package/dist/component/usage/schema.d.ts +96 -1
- package/dist/component/usage/schema.d.ts.map +1 -1
- package/dist/component/usage/schema.js +11 -2
- package/dist/component/usage/schema.js.map +1 -1
- package/dist/component/usageCatalog/mutations.d.ts +25 -0
- package/dist/component/usageCatalog/mutations.d.ts.map +1 -0
- package/dist/component/usageCatalog/mutations.js +75 -0
- package/dist/component/usageCatalog/mutations.js.map +1 -0
- package/dist/component/usageCatalog/queries.d.ts +33 -0
- package/dist/component/usageCatalog/queries.d.ts.map +1 -0
- package/dist/component/usageCatalog/queries.js +26 -0
- package/dist/component/usageCatalog/queries.js.map +1 -0
- package/dist/component/usageCatalog/schema.d.ts +57 -0
- package/dist/component/usageCatalog/schema.d.ts.map +1 -0
- package/dist/component/usageCatalog/schema.js +22 -0
- package/dist/component/usageCatalog/schema.js.map +1 -0
- package/dist/component/usageDelivery/bridge.d.ts +25 -0
- package/dist/component/usageDelivery/bridge.d.ts.map +1 -0
- package/dist/component/usageDelivery/bridge.js +45 -0
- package/dist/component/usageDelivery/bridge.js.map +1 -0
- package/dist/component/usageDelivery/fields.d.ts +78 -0
- package/dist/component/usageDelivery/fields.d.ts.map +1 -0
- package/dist/component/usageDelivery/fields.js +38 -0
- package/dist/component/usageDelivery/fields.js.map +1 -0
- package/dist/component/usageDelivery/helpers.d.ts +83 -0
- package/dist/component/usageDelivery/helpers.d.ts.map +1 -0
- package/dist/component/usageDelivery/helpers.js +63 -0
- package/dist/component/usageDelivery/helpers.js.map +1 -0
- package/dist/component/usageDelivery/mutations.d.ts +97 -0
- package/dist/component/usageDelivery/mutations.d.ts.map +1 -0
- package/dist/component/usageDelivery/mutations.js +153 -0
- package/dist/component/usageDelivery/mutations.js.map +1 -0
- package/dist/component/usageDelivery/queries.d.ts +113 -0
- package/dist/component/usageDelivery/queries.d.ts.map +1 -0
- package/dist/component/usageDelivery/queries.js +22 -0
- package/dist/component/usageDelivery/queries.js.map +1 -0
- package/dist/component/usageDelivery/schema.d.ts +79 -0
- package/dist/component/usageDelivery/schema.d.ts.map +1 -0
- package/dist/component/usageDelivery/schema.js +30 -0
- package/dist/component/usageDelivery/schema.js.map +1 -0
- package/dist/component/usageDelivery/steps.d.ts +85 -0
- package/dist/component/usageDelivery/steps.d.ts.map +1 -0
- package/dist/component/usageDelivery/steps.js +154 -0
- package/dist/component/usageDelivery/steps.js.map +1 -0
- package/dist/component/usageDelivery/workflow.d.ts +15 -0
- package/dist/component/usageDelivery/workflow.d.ts.map +1 -0
- package/dist/component/usageDelivery/workflow.js +28 -0
- package/dist/component/usageDelivery/workflow.js.map +1 -0
- package/docs/README.md +5 -1
- package/docs/metering-setup.md +3 -1
- package/docs/usage-catalog.md +106 -0
- package/docs/usage-delivery.md +143 -0
- package/package.json +4 -2
- package/src/client/index.ts +23 -0
- package/src/client/products/catalogClient.ts +77 -0
- package/src/client/products/fixedPrice.test.ts +57 -0
- package/src/client/products/fixedPrice.ts +13 -0
- package/src/client/products/products.ts +2 -0
- package/src/client/usage/catalog.test.ts +464 -0
- package/src/client/usage/catalog.ts +117 -0
- package/src/client/usage/catalogLifecycle.ts +128 -0
- package/src/client/usage/catalogMath.test.ts +13 -0
- package/src/client/usage/catalogMath.ts +22 -0
- package/src/client/usage/catalogPrices.ts +251 -0
- package/src/client/usage/catalogRead.ts +98 -0
- package/src/client/usage/catalogTypes.ts +170 -0
- package/src/client/usage/client.ts +5 -2
- package/src/client/usage/deliveryClient.ts +130 -0
- package/src/client/usage/deliveryProtocol.ts +26 -0
- package/src/client/usage/deliveryProvider.test.ts +207 -0
- package/src/client/usage/deliveryProvider.ts +155 -0
- package/src/client/usage/index.ts +13 -0
- package/src/client/webhooks/handler.ts +2 -1
- package/src/client/webhooks/meterErrors.test.ts +164 -0
- package/src/client/webhooks/meterErrors.ts +118 -0
- package/src/client/webhooks/processors.ts +2 -0
- package/src/client/webhooks/v2.ts +5 -0
- package/src/component/_generated/api.ts +18 -0
- package/src/component/_generated/component.ts +380 -0
- package/src/component/schema.ts +8 -0
- package/src/component/usage/schema.ts +11 -2
- package/src/component/usageCatalog/mutations.ts +79 -0
- package/src/component/usageCatalog/queries.ts +32 -0
- package/src/component/usageCatalog/schema.ts +21 -0
- package/src/component/usageDelivery/bridge.ts +56 -0
- package/src/component/usageDelivery/concurrency.test.ts +62 -0
- package/src/component/usageDelivery/fields.ts +59 -0
- package/src/component/usageDelivery/helpers.ts +77 -0
- package/src/component/usageDelivery/mutations.ts +185 -0
- package/src/component/usageDelivery/queries.ts +25 -0
- package/src/component/usageDelivery/schema.ts +33 -0
- package/src/component/usageDelivery/steps.ts +171 -0
- package/src/component/usageDelivery/workflow.test.ts +402 -0
- package/src/component/usageDelivery/workflow.ts +36 -0
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
import { internalMutation } from "../_generated/server.js";
|
|
2
|
+
import { v } from "convex/values";
|
|
3
|
+
import { refFields, request, status } from "./schema.js";
|
|
4
|
+
import { outcome } from "./fields.js";
|
|
5
|
+
import { read, statusOf, lockKeys } from "./helpers.js";
|
|
6
|
+
export const claim = internalMutation({
|
|
7
|
+
args: refFields,
|
|
8
|
+
returns: v.union(v.object({ kind: v.literal("ready"), request: v.object(request) }), v.object({ kind: v.literal("wait"), delayMs: v.number() }), v.object({ kind: v.literal("done") })),
|
|
9
|
+
handler: async (ctx, args) => {
|
|
10
|
+
const { outbox, record } = await read(ctx, args), now = Math.floor(Date.now() / 1000);
|
|
11
|
+
if (outbox.held ||
|
|
12
|
+
["provider_accepted", "rejected", "unknown", "held"].includes(outbox.state))
|
|
13
|
+
return { kind: "done" };
|
|
14
|
+
if (record.occurredAt < now - 35 * 86400 ||
|
|
15
|
+
record.occurredAt > now + 300 ||
|
|
16
|
+
(outbox.firstSendAt !== undefined &&
|
|
17
|
+
now - outbox.firstSendAt >= 23 * 3600)) {
|
|
18
|
+
await ctx.db.patch("usageOutbox", outbox._id, {
|
|
19
|
+
state: outbox.firstSendAt === undefined ? "held" : "unknown",
|
|
20
|
+
reason: "delivery_window_expired",
|
|
21
|
+
});
|
|
22
|
+
return { kind: "done" };
|
|
23
|
+
}
|
|
24
|
+
if (outbox.state === "sending") {
|
|
25
|
+
if ((outbox.leaseUntil ?? 0) > now)
|
|
26
|
+
return {
|
|
27
|
+
kind: "wait",
|
|
28
|
+
delayMs: Math.min(60000, Math.max(1000, ((outbox.leaseUntil ?? now) - now) * 1000)),
|
|
29
|
+
};
|
|
30
|
+
await ctx.db.patch("usageOutbox", outbox._id, {
|
|
31
|
+
state: "unknown",
|
|
32
|
+
reason: "provider_outcome_unknown",
|
|
33
|
+
});
|
|
34
|
+
return { kind: "done" };
|
|
35
|
+
}
|
|
36
|
+
const keys = lockKeys(record);
|
|
37
|
+
const realm = await ctx.db
|
|
38
|
+
.query("usageDeliveryLocks")
|
|
39
|
+
.withIndex("by_key", (q) => q.eq("key", keys.realm))
|
|
40
|
+
.unique();
|
|
41
|
+
const customer = await ctx.db
|
|
42
|
+
.query("usageDeliveryLocks")
|
|
43
|
+
.withIndex("by_key", (q) => q.eq("key", keys.customer))
|
|
44
|
+
.unique();
|
|
45
|
+
const waitUntil = Math.max(outbox.nextAttemptAt, realm?.nextAttemptAt ?? 0, customer?.leaseUntil ?? 0);
|
|
46
|
+
if (waitUntil > now)
|
|
47
|
+
return {
|
|
48
|
+
kind: "wait",
|
|
49
|
+
delayMs: Math.min(60000, (waitUntil - now) * 1000),
|
|
50
|
+
};
|
|
51
|
+
const slot = { key: keys.realm, leaseUntil: 0, nextAttemptAt: now + 1 };
|
|
52
|
+
if (realm)
|
|
53
|
+
await ctx.db.patch("usageDeliveryLocks", realm._id, slot);
|
|
54
|
+
else
|
|
55
|
+
await ctx.db.insert("usageDeliveryLocks", slot);
|
|
56
|
+
const lock = {
|
|
57
|
+
key: keys.customer,
|
|
58
|
+
eventId: args.eventId,
|
|
59
|
+
leaseUntil: now + 900,
|
|
60
|
+
nextAttemptAt: 0,
|
|
61
|
+
};
|
|
62
|
+
if (customer)
|
|
63
|
+
await ctx.db.patch("usageDeliveryLocks", customer._id, lock);
|
|
64
|
+
else
|
|
65
|
+
await ctx.db.insert("usageDeliveryLocks", lock);
|
|
66
|
+
const attempt = outbox.attempts + 1;
|
|
67
|
+
await ctx.db.patch("usageOutbox", outbox._id, {
|
|
68
|
+
state: "sending",
|
|
69
|
+
attempts: attempt,
|
|
70
|
+
firstSendAt: outbox.firstSendAt ?? now,
|
|
71
|
+
leaseUntil: now + 900,
|
|
72
|
+
reason: undefined,
|
|
73
|
+
});
|
|
74
|
+
return {
|
|
75
|
+
kind: "ready",
|
|
76
|
+
request: {
|
|
77
|
+
...args,
|
|
78
|
+
attempt,
|
|
79
|
+
definitionVersion: 1,
|
|
80
|
+
apiVersion: record.binding.apiVersion,
|
|
81
|
+
identifier: outbox.providerIdentifier,
|
|
82
|
+
},
|
|
83
|
+
};
|
|
84
|
+
},
|
|
85
|
+
});
|
|
86
|
+
export const save = internalMutation({
|
|
87
|
+
args: { ...request, outcome },
|
|
88
|
+
returns: status,
|
|
89
|
+
handler: async (ctx, args) => {
|
|
90
|
+
const { outbox, record } = await read(ctx, args);
|
|
91
|
+
if (outbox.attempts !== args.attempt ||
|
|
92
|
+
outbox.providerIdentifier !== args.identifier ||
|
|
93
|
+
record.binding.apiVersion !== args.apiVersion ||
|
|
94
|
+
outbox.definitionVersion !== args.definitionVersion)
|
|
95
|
+
throw new Error("Stale usage delivery receipt");
|
|
96
|
+
if (outbox.receipt || outbox.state === "rejected")
|
|
97
|
+
return statusOf(outbox);
|
|
98
|
+
const result = args.outcome, now = Math.floor(Date.now() / 1000);
|
|
99
|
+
const update = result.status === "accepted"
|
|
100
|
+
? {
|
|
101
|
+
state: "provider_accepted",
|
|
102
|
+
receipt: { identifier: args.identifier, created: result.created },
|
|
103
|
+
reason: undefined,
|
|
104
|
+
}
|
|
105
|
+
: result.status === "unknown"
|
|
106
|
+
? {
|
|
107
|
+
state: "unknown",
|
|
108
|
+
reason: "provider_outcome_unknown",
|
|
109
|
+
}
|
|
110
|
+
: result.status === "rejected"
|
|
111
|
+
? {
|
|
112
|
+
state: "rejected",
|
|
113
|
+
reason: "provider_rejected",
|
|
114
|
+
}
|
|
115
|
+
: result.status === "unavailable"
|
|
116
|
+
? {
|
|
117
|
+
state: "held",
|
|
118
|
+
reason: "provider_unavailable",
|
|
119
|
+
}
|
|
120
|
+
: {
|
|
121
|
+
state: outbox.held ? "held" : "queued",
|
|
122
|
+
reason: "rate_limited",
|
|
123
|
+
nextAttemptAt: now + Math.min(60, 2 ** Math.min(outbox.attempts, 6)),
|
|
124
|
+
};
|
|
125
|
+
await ctx.db.patch("usageOutbox", outbox._id, update);
|
|
126
|
+
if (result.status !== "unknown") {
|
|
127
|
+
const key = lockKeys(record).customer;
|
|
128
|
+
const lock = await ctx.db
|
|
129
|
+
.query("usageDeliveryLocks")
|
|
130
|
+
.withIndex("by_key", (q) => q.eq("key", key))
|
|
131
|
+
.unique();
|
|
132
|
+
if (lock?.eventId === args.eventId)
|
|
133
|
+
await ctx.db.patch("usageDeliveryLocks", lock._id, {
|
|
134
|
+
leaseUntil: 0,
|
|
135
|
+
eventId: undefined,
|
|
136
|
+
});
|
|
137
|
+
}
|
|
138
|
+
return statusOf((await read(ctx, args)).outbox);
|
|
139
|
+
},
|
|
140
|
+
});
|
|
141
|
+
export const exhaust = internalMutation({
|
|
142
|
+
args: refFields,
|
|
143
|
+
returns: v.null(),
|
|
144
|
+
handler: async (ctx, args) => {
|
|
145
|
+
const { outbox } = await read(ctx, args);
|
|
146
|
+
if (outbox.state === "queued")
|
|
147
|
+
await ctx.db.patch("usageOutbox", outbox._id, {
|
|
148
|
+
state: "held",
|
|
149
|
+
reason: "retry_exhausted",
|
|
150
|
+
});
|
|
151
|
+
return null;
|
|
152
|
+
},
|
|
153
|
+
});
|
|
154
|
+
//# sourceMappingURL=steps.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"steps.js","sourceRoot":"","sources":["../../../src/component/usageDelivery/steps.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,MAAM,yBAAyB,CAAC;AAC3D,OAAO,EAAE,CAAC,EAAE,MAAM,eAAe,CAAC;AAClC,OAAO,EAAE,SAAS,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AACzD,OAAO,EAAE,OAAO,EAAE,MAAM,aAAa,CAAC;AACtC,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAC;AACxD,MAAM,CAAC,MAAM,KAAK,GAAG,gBAAgB,CAAC;IACpC,IAAI,EAAE,SAAS;IACf,OAAO,EAAE,CAAC,CAAC,KAAK,CACd,CAAC,CAAC,MAAM,CAAC,EAAE,IAAI,EAAE,CAAC,CAAC,OAAO,CAAC,OAAO,CAAC,EAAE,OAAO,EAAE,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,EAAE,CAAC,EAClE,CAAC,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CAAC,GAAG,EAAE;oBACjD,UAAU,EAAE,CAAC;oBACb,OAAO,EAAE,SAAS;iBACnB,CAAC,CAAC;QACP,CAAC;QACD,OAAO,QAAQ,CAAC,CAAC,MAAM,IAAI,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC;IAClD,CAAC;CACF,CAAC,CAAC;AACH,MAAM,CAAC,MAAM,OAAO,GAAG,gBAAgB,CAAC;IACtC,IAAI,EAAE,SAAS;IACf,OAAO,EAAE,CAAC,CAAC,IAAI,EAAE;IACjB,OAAO,EAAE,KAAK,EAAE,GAAG,EAAE,IAAI,EAAE,EAAE;QAC3B,MAAM,EAAE,MAAM,EAAE,GAAG,MAAM,IAAI,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC;QACzC,IAAI,MAAM,CAAC,KAAK,KAAK,QAAQ;YAC3B,MAAM,GAAG,CAAC,EAAE,CAAC,KAAK,CAAC,aAAa,EAAE,MAAM,CAAC,GAAG,EAAE;gBAC5C,KAAK,EAAE,MAAM;gBACb,MAAM,EAAE,iBAAiB;aAC1B,CAAC,CAAC;QACL,OAAO,IAAI,CAAC;IACd,CAAC;CACF,CAAC,CAAC"}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
export declare const run: import("convex/server").RegisteredMutation<"internal", import("@convex-dev/workflow").WorkflowArgs<{
|
|
2
|
+
scope: import("convex/values").VObject<{
|
|
3
|
+
customerAccount: string;
|
|
4
|
+
livemode: boolean;
|
|
5
|
+
meterId: string;
|
|
6
|
+
stripeAccountId: string;
|
|
7
|
+
}, {
|
|
8
|
+
stripeAccountId: import("convex/values").VString<string, "required">;
|
|
9
|
+
customerAccount: import("convex/values").VString<string, "required">;
|
|
10
|
+
meterId: import("convex/values").VString<string, "required">;
|
|
11
|
+
livemode: import("convex/values").VBoolean<boolean, "required">;
|
|
12
|
+
}, "required", "customerAccount" | "livemode" | "meterId" | "stripeAccountId">;
|
|
13
|
+
eventId: import("convex/values").VId<import("convex/values").GenericId<"usageEvents">, "required">;
|
|
14
|
+
}>, import("@convex-dev/workflow").WorkflowMutationResult<null>>;
|
|
15
|
+
//# sourceMappingURL=workflow.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"workflow.d.ts","sourceRoot":"","sources":["../../../src/component/usageDelivery/workflow.ts"],"names":[],"mappings":"AAIA,eAAO,MAAM,GAAG;;;;;;;;;;;;;gEA+BZ,CAAC"}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { anyApi } from "convex/server";
|
|
2
|
+
import { executionWorkflow } from "../durableExecution/runtime.js";
|
|
3
|
+
import { refFields } from "./schema.js";
|
|
4
|
+
import { v } from "convex/values";
|
|
5
|
+
export const run = executionWorkflow
|
|
6
|
+
.define({ args: refFields, returns: v.null() })
|
|
7
|
+
.handler(async (step, args) => {
|
|
8
|
+
let sends = 0;
|
|
9
|
+
for (let turn = 0; turn < 40; turn++) {
|
|
10
|
+
const claimed = await step.runMutation(anyApi.usageDelivery.steps.claim, args, { name: `claim-${turn}` });
|
|
11
|
+
if (claimed.kind === "done")
|
|
12
|
+
return null;
|
|
13
|
+
if (claimed.kind === "wait") {
|
|
14
|
+
await step.sleep(claimed.delayMs);
|
|
15
|
+
continue;
|
|
16
|
+
}
|
|
17
|
+
const outcome = await step.runAction(anyApi.usageDelivery.bridge.invoke, claimed.request, { name: `provider-${turn}`, retry: false });
|
|
18
|
+
const saved = await step.runMutation(anyApi.usageDelivery.steps.save, { ...claimed.request, outcome }, { name: "save-receipt" });
|
|
19
|
+
sends++;
|
|
20
|
+
if (saved.state !== "queued")
|
|
21
|
+
return null;
|
|
22
|
+
if (sends >= 3)
|
|
23
|
+
break;
|
|
24
|
+
}
|
|
25
|
+
await step.runMutation(anyApi.usageDelivery.steps.exhaust, args);
|
|
26
|
+
return null;
|
|
27
|
+
});
|
|
28
|
+
//# sourceMappingURL=workflow.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"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M,CAAC,aAAa,CAAC,KAAK,CAAC,IAAI,EAC/B,EAAE,GAAG,OAAO,CAAC,OAAO,EAAE,OAAO,EAAE,EAC/B,EAAE,IAAI,EAAE,cAAc,EAAE,CACzB,CAAC;QACF,KAAK,EAAE,CAAC;QACR,IAAI,KAAK,CAAC,KAAK,KAAK,QAAQ;YAAE,OAAO,IAAI,CAAC;QAC1C,IAAI,KAAK,IAAI,CAAC;YAAE,MAAM;IACxB,CAAC;IACD,MAAM,IAAI,CAAC,WAAW,CAAC,MAAM,CAAC,aAAa,CAAC,KAAK,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC;IACjE,OAAO,IAAI,CAAC;AACd,CAAC,CAAC,CAAC"}
|
package/docs/README.md
CHANGED
|
@@ -24,7 +24,7 @@ guide for your integration.
|
|
|
24
24
|
- [SetupIntent recovery](setup-intent-recovery.md).
|
|
25
25
|
- [Balance funding state](balance-funding-state.md) and [workflow](balance-funding-workflow.md).
|
|
26
26
|
- [Example balance funding cutover](example-balance-funding-cutover.md).
|
|
27
|
-
- [Metered usage investigation](metered-usage.md), provider comparison and acceptance requirements.
|
|
27
|
+
- [Metered usage investigation](metered-usage.md), provider comparison and acceptance requirements. Shared contracts, catalog provisioning and local usage acceptance are available; credit accounting is in progress.
|
|
28
28
|
|
|
29
29
|
## Marketplace, settlement, and recovery
|
|
30
30
|
|
|
@@ -58,3 +58,7 @@ Start with the [native Stripe setup guide](metering-setup.md), then read the
|
|
|
58
58
|
[shared contracts and sandbox evidence](metered-usage.md).
|
|
59
59
|
|
|
60
60
|
[Atomic usage ledger and scoped history](usage-ledger.md) describes acceptance and retention.
|
|
61
|
+
|
|
62
|
+
[Native usage catalog](usage-catalog.md) covers provisioning, immutable versions and typed price observations.
|
|
63
|
+
|
|
64
|
+
[Durable native delivery](usage-delivery.md) explains host actions, bounded retries, operational holds and asynchronous errors.
|
package/docs/metering-setup.md
CHANGED
|
@@ -7,7 +7,7 @@ native Stripe integration into the existing BetterStripe Convex component.
|
|
|
7
7
|
|
|
8
8
|
Current status: shared configuration/quantity helpers and repository sandbox probes
|
|
9
9
|
are implemented. Atomic recording and bounded local history are available through the
|
|
10
|
-
[usage ledger](usage-ledger.md). Durable provider delivery
|
|
10
|
+
[usage ledger](usage-ledger.md). [Durable provider delivery](usage-delivery.md) is available. Allowance/credit
|
|
11
11
|
accounting and the three example UI flows are still under development. The probes
|
|
12
12
|
below verify provider behavior directly; they are not public BetterStripe billing
|
|
13
13
|
workflows. See [metered usage contracts and evidence](metered-usage.md).
|
|
@@ -182,3 +182,5 @@ Primary references:
|
|
|
182
182
|
- [Stripe meter event API](https://docs.stripe.com/api/billing/meter-event/create)
|
|
183
183
|
- [Stripe billing credits](https://docs.stripe.com/billing/subscriptions/usage-based/billing-credits)
|
|
184
184
|
- [Metronome quickstart](https://docs.metronome.com/guides/get-started/api-quickstart)
|
|
185
|
+
|
|
186
|
+
Use the [native catalog guide](usage-catalog.md) to provision versioned meters and prices through BetterStripe.
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
# Provision the native usage catalog
|
|
2
|
+
|
|
3
|
+
BetterStripe uses Stripe Billing Meters and recurring metered Prices. No
|
|
4
|
+
Metronome account is required. Follow [sandbox setup](metering-setup.md) first.
|
|
5
|
+
These methods run in authenticated host actions. Resolve the account, test/live
|
|
6
|
+
mode, plan and product on the server, and authorize the caller before provisioning.
|
|
7
|
+
|
|
8
|
+
```ts
|
|
9
|
+
import { defineUsagePlan } from "@fantastic.dev/better-stripe/usage";
|
|
10
|
+
|
|
11
|
+
const plan = defineUsagePlan({
|
|
12
|
+
key: "api-calls",
|
|
13
|
+
version: "v1",
|
|
14
|
+
model: "pay_as_you_go",
|
|
15
|
+
unit: { name: "call", precision: 0 },
|
|
16
|
+
rate: { currency: "usd", unitAmountDecimal: "2" },
|
|
17
|
+
});
|
|
18
|
+
const scope = { stripeAccountId: verifiedPlatformAccountId, livemode: false };
|
|
19
|
+
const meter = await stripe.ensureUsageMeter(ctx, {
|
|
20
|
+
scope,
|
|
21
|
+
plan,
|
|
22
|
+
eventName: "api_calls_v1",
|
|
23
|
+
displayName: "API calls v1",
|
|
24
|
+
});
|
|
25
|
+
const price = await stripe.ensureUsagePrice(ctx, {
|
|
26
|
+
scope,
|
|
27
|
+
plan,
|
|
28
|
+
meterId: meter.id,
|
|
29
|
+
stripeProductId: verifiedProductId,
|
|
30
|
+
lookupKey: "api_calls_v1_usd",
|
|
31
|
+
});
|
|
32
|
+
// price is a Convex-safe UsagePriceBinding with exact string amounts.
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
Use `model: "included_overage"`, `includedQuantity: "1000"` and
|
|
36
|
+
`reset: "billing_period"` for monthly included units with overages. Stripe receives
|
|
37
|
+
a graduated free first tier and an infinite paid tier. Use `model: "prepaid"` and
|
|
38
|
+
`insufficientBalance: "reject"` for the prepaid catalog. Its recurring price charges
|
|
39
|
+
the configured rate, and payment-backed Billing Credit Grants offset eligible
|
|
40
|
+
charges. Provisioning this price does not fund credits or enforce a balance.
|
|
41
|
+
See the [implementation status](metered-usage.md) before enabling consumption.
|
|
42
|
+
|
|
43
|
+
Rates are decimal minor currency units per whole billable unit. With precision 2,
|
|
44
|
+
a rate of `"2"` becomes `"0.02"` per scaled provider unit. The adapter rejects more
|
|
45
|
+
than 12 provider decimal places rather than rounding. Included tier boundaries
|
|
46
|
+
must be exact positive safe integers after scaling. Monthly intervals, sum
|
|
47
|
+
aggregation, `stripe_customer_id` and `value` mappings are supported. Other
|
|
48
|
+
intervals, transformations and provider terms require an explicit adapter change.
|
|
49
|
+
|
|
50
|
+
The configured Stripe key must own `scope.stripeAccountId`. The adapter verifies
|
|
51
|
+
that account and the key's mode before writes. Connected-account headers are not
|
|
52
|
+
supported by these APIs. Restricted keys that cannot perform this verification
|
|
53
|
+
return `provider_unavailable`. A mismatch returns `unsupported_scope`.
|
|
54
|
+
|
|
55
|
+
## Immutable identities and recovery
|
|
56
|
+
|
|
57
|
+
A meter identity is scoped by account, mode, plan key and version. A price identity
|
|
58
|
+
uses the same account/mode plus its lookup key. Plan terms, event name, mappings,
|
|
59
|
+
product, price currency and rates cannot change under those identities. Use a new
|
|
60
|
+
version, event name and lookup key for changed terms. A provider resource cannot
|
|
61
|
+
be adopted into a second managed identity.
|
|
62
|
+
|
|
63
|
+
The component persists a creation intent before calling Stripe and uses a stable
|
|
64
|
+
idempotency key. Retries verify provider terms and repair a failed mirror write.
|
|
65
|
+
Pinned resources are retrieved by ID and never recreated when retrieval fails.
|
|
66
|
+
Unpinned meter discovery is bounded to 1,000 resources. Incomplete discovery,
|
|
67
|
+
ambiguous matches and conflicting terms stop provisioning.
|
|
68
|
+
|
|
69
|
+
Automatic creation stops 23 hours after the first intent. Stripe's idempotency
|
|
70
|
+
retention is finite. An absent result after that point returns
|
|
71
|
+
`unknown_create_outcome`; investigate the provider account and adopt the verified
|
|
72
|
+
existing meter rather than generating another event identity. Found matching
|
|
73
|
+
resources can still repair a mirror after this window. Do not delete intent rows
|
|
74
|
+
or change keys to retry an uncertain write.
|
|
75
|
+
|
|
76
|
+
## Lifecycle and reads
|
|
77
|
+
|
|
78
|
+
`adoptUsageMeter` accepts an exact provider meter ID plus the same configuration
|
|
79
|
+
as `ensureUsageMeter`. `getUsageMeterFromStripe` retrieves one ID.
|
|
80
|
+
`listStripeUsageMeters` accepts a page limit of 1–100 and optional cursor, and
|
|
81
|
+
returns `data`, `hasMore` and `cursor`. These provider methods require the same
|
|
82
|
+
verified scope. `deactivateUsageMeter` and `reactivateUsageMeter` operate only on
|
|
83
|
+
managed IDs and refresh their local observation.
|
|
84
|
+
|
|
85
|
+
Deactivation stops new usage ingestion for that meter. It does not migrate or
|
|
86
|
+
cancel existing subscriptions, settle prior usage or change immutable prices.
|
|
87
|
+
Review active subscriptions and queued delivery before deactivation. Explicitly
|
|
88
|
+
create and bind a new version when changing billing terms.
|
|
89
|
+
|
|
90
|
+
`getUsagePrice(ctx, { scope, lookupKey })` is a local query-compatible reader.
|
|
91
|
+
Its `available` result contains `observedAt` and a discriminated
|
|
92
|
+
`pricingMode: "metered"` binding, exact string amounts and explicit tiers. Missing,
|
|
93
|
+
pending and invalid observations return typed `unavailable` states. Reauthorize
|
|
94
|
+
every read. Cached observations do not prove fresh provider state or invoicing.
|
|
95
|
+
|
|
96
|
+
The legacy fixed-price mirror and its readers only represent fixed integer prices.
|
|
97
|
+
Webhook and bulk sync omit metered, tiered, transformed and decimal-only prices
|
|
98
|
+
instead of converting a null amount into zero. Use the scoped usage reader for
|
|
99
|
+
managed metered prices. Historical mirrors written by earlier package versions
|
|
100
|
+
are not automatically migrated; audit those records before relying on old data.
|
|
101
|
+
Existing fixed-price creation, adoption and readers retain their contracts.
|
|
102
|
+
|
|
103
|
+
Authoritative references: [Stripe meters](https://docs.stripe.com/api/billing/meter),
|
|
104
|
+
[usage-based prices](https://docs.stripe.com/billing/subscriptions/usage-based/implementation-guide),
|
|
105
|
+
[idempotency retention](https://docs.stripe.com/api/idempotent_requests), and
|
|
106
|
+
[Billing Credit Grant eligibility](https://docs.stripe.com/billing/subscriptions/usage-based/billing-credits).
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
# Deliver accepted usage to native Stripe
|
|
2
|
+
|
|
3
|
+
Start with the [catalog](usage-catalog.md) and [atomic ledger](usage-ledger.md).
|
|
4
|
+
This layer sends the same immutable usage records for all three billing models.
|
|
5
|
+
It does not purchase prepaid credits, collect payment, finalize invoices or settle
|
|
6
|
+
seller proceeds. Native Stripe Billing Meters need no Metronome token.
|
|
7
|
+
|
|
8
|
+
## Register a host internal provider action
|
|
9
|
+
|
|
10
|
+
The component owns the outbox, Workflow journal, rate limits and receipts. The
|
|
11
|
+
host owns credentials and authorization. Register this action in your Convex app:
|
|
12
|
+
|
|
13
|
+
```ts
|
|
14
|
+
import { internalAction } from "./_generated/server";
|
|
15
|
+
import {
|
|
16
|
+
usageDeliveryArgs,
|
|
17
|
+
usageDeliveryResult,
|
|
18
|
+
} from "@fantastic.dev/better-stripe/usage";
|
|
19
|
+
import { stripe } from "./stripe"; // Your configured BetterStripe instance.
|
|
20
|
+
|
|
21
|
+
export const sendUsage = internalAction({
|
|
22
|
+
args: usageDeliveryArgs,
|
|
23
|
+
returns: usageDeliveryResult,
|
|
24
|
+
handler: (ctx, request) =>
|
|
25
|
+
stripe.usage.deliver(ctx, request, {
|
|
26
|
+
stripeSecretKey: process.env.STRIPE_SECRET_KEY,
|
|
27
|
+
}),
|
|
28
|
+
});
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
Then record and dispatch from an authorized host mutation. Authenticate the actor,
|
|
32
|
+
authorize the exact realm/payer/meter, apply your billable-activity policy and
|
|
33
|
+
resolve the subscription binding from verified server state before this code:
|
|
34
|
+
|
|
35
|
+
```ts
|
|
36
|
+
const receipt = await stripe.usage.record(ctx, {
|
|
37
|
+
event: serverEvent,
|
|
38
|
+
subscription: verifiedSubscription,
|
|
39
|
+
});
|
|
40
|
+
await stripe.usage.startDelivery(ctx, {
|
|
41
|
+
scope: serverEvent.scope,
|
|
42
|
+
eventId: receipt.eventId,
|
|
43
|
+
provider: internal.billing.sendUsage,
|
|
44
|
+
});
|
|
45
|
+
return receipt;
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
Both calls participate in the host mutation transaction. A failed dispatch rolls
|
|
49
|
+
back acceptance too. Alternatively, accept without dispatch and start delivery
|
|
50
|
+
later from an internal worker. Never accept a provider function reference,
|
|
51
|
+
credential, price or unverified scope from a browser. Reauthorize every status,
|
|
52
|
+
hold and resume request. The internal provider action must use the package's
|
|
53
|
+
`deliver` helper and must not implement its own retry loop.
|
|
54
|
+
|
|
55
|
+
`startDeliveryBatch` accepts one scope, the same internal provider reference and
|
|
56
|
+
1–10 event IDs. Each event has its own durable progress. If a host action fails
|
|
57
|
+
partway through dispatching a batch, replay its original IDs; completed dispatches
|
|
58
|
+
are idempotent. Delivery is individually submitted, with no unbounded native
|
|
59
|
+
batch or account-wide scan.
|
|
60
|
+
|
|
61
|
+
## Execution and retries
|
|
62
|
+
|
|
63
|
+
The existing nested Workflow runtime runs at most two steps concurrently and
|
|
64
|
+
never retries provider actions automatically. Delivery additionally reserves a
|
|
65
|
+
single slot per native customer/meter across Accounts v2 payer aliases, and a
|
|
66
|
+
conservative account/mode rate of one send per second. Claims use Convex
|
|
67
|
+
transactions. A send lease lasts 15 minutes, beyond the host action execution
|
|
68
|
+
limit. The native helper rechecks its attempt and lease immediately before the
|
|
69
|
+
write. Native requests use a 15-second timeout and zero SDK network retries.
|
|
70
|
+
|
|
71
|
+
The immutable event pins its Stripe API version and routing/pricing snapshot.
|
|
72
|
+
Delivery definition version 1 and the internal provider handle are retained.
|
|
73
|
+
The outbox's `bs_usage_…` identifier is also the native idempotency key. Neither
|
|
74
|
+
identity changes on resume. Credentials are supplied at execution time and never
|
|
75
|
+
stored in outbox rows or Workflow arguments/results.
|
|
76
|
+
|
|
77
|
+
Known HTTP 429 responses back off exponentially, with at most three sends per
|
|
78
|
+
Workflow run and a 60-second delay ceiling. Other queued events retain their
|
|
79
|
+
progress. Missing credentials and preflight failures stop as `provider_unavailable`
|
|
80
|
+
until an administrator fixes the configuration and resumes. Explicit validation
|
|
81
|
+
rejections stop as `rejected`. Ambiguous responses, duplicate-identifier errors,
|
|
82
|
+
network loss and provider 5xx responses become `unknown` and retain the possible
|
|
83
|
+
effect. Raw SDK errors and response payloads do not enter the journal.
|
|
84
|
+
|
|
85
|
+
A failed receipt mutation can resume from that failed step using the already
|
|
86
|
+
journaled provider result. Do not restart from step zero, delete the outbox or
|
|
87
|
+
change the source identifier. A worker crash before the provider result is
|
|
88
|
+
journaled becomes unknown when its send lease expires.
|
|
89
|
+
|
|
90
|
+
New delivery must still fall within Stripe's 35-day past/5-minute future event
|
|
91
|
+
window. Automatic sends also stop 23 hours after the first send attempt. Stripe
|
|
92
|
+
retains deduplication for at least 24 hours, not forever. A historical acceptance
|
|
93
|
+
receipt remains valid after these windows expire, but does not authorize replay.
|
|
94
|
+
The adapter never changes the original occurrence time to make an event eligible.
|
|
95
|
+
|
|
96
|
+
## Status and operational controls
|
|
97
|
+
|
|
98
|
+
Use `getDelivery(ctx, {scope, eventId})` for current delivery state, attempt count,
|
|
99
|
+
provider identifier, optional acceptance receipt and observed validation errors.
|
|
100
|
+
`provider_accepted` means transport acceptance. It does not prove successful
|
|
101
|
+
aggregation, invoice inclusion, finalization or payment. Keep the original ledger
|
|
102
|
+
receipt and later observations separate.
|
|
103
|
+
|
|
104
|
+
`holdDelivery` prevents future sends. It cannot abort an in-flight native request;
|
|
105
|
+
a later accepted receipt remains visible even while the administrative hold flag
|
|
106
|
+
is set. `resumeDelivery` clears a hold and starts or resumes compatible work after
|
|
107
|
+
known retryable failures. It never blindly replays unknown effects or expired
|
|
108
|
+
windows. Native Stripe has no per-event retrieve API that proves the fate of an
|
|
109
|
+
unknown submission. An aggregate total cannot prove an individual event's fate.
|
|
110
|
+
Investigate provider logs and reconciliation before any financial correction.
|
|
111
|
+
|
|
112
|
+
`cancelDelivery` returns a typed unsupported result. Holding work is not native
|
|
113
|
+
cancellation, an adjustment or a refund. Use the separately implemented correction
|
|
114
|
+
workflow when available and preserve the original event and payment provenance.
|
|
115
|
+
No deletion or financial-history cleanup API is provided here.
|
|
116
|
+
|
|
117
|
+
## Receive asynchronous native validation errors
|
|
118
|
+
|
|
119
|
+
Configure a Stripe **thin** event destination for:
|
|
120
|
+
|
|
121
|
+
- `v1.billing.meter.error_report_triggered`
|
|
122
|
+
- `v1.billing.meter.no_meter_found`
|
|
123
|
+
|
|
124
|
+
Use the BetterStripe webhook route and configure its thin destination secret as
|
|
125
|
+
`webhookSecretV2`. The `v1.` names still carry thin payloads. The package selects
|
|
126
|
+
the thin signature verifier, retrieves the full event from Stripe, verifies its
|
|
127
|
+
account/mode and maps allowlisted sample identifiers to their original outbox
|
|
128
|
+
records. Destination/account context must match the configured key's own realm.
|
|
129
|
+
Organization or foreign account contexts are not silently substituted.
|
|
130
|
+
|
|
131
|
+
Observed errors are append-only and deduplicated by native report/event/code.
|
|
132
|
+
They do not overwrite transport acceptance or invoice history. Reads include at
|
|
133
|
+
most 20 errors plus `validationHistoryComplete` for this bounded local history.
|
|
134
|
+
This flag does not claim complete provider validation. Stripe reports samples;
|
|
135
|
+
unmatched identifiers, unsupported codes and truncated reports cannot prove that
|
|
136
|
+
all affected events were observed. The adapter bounds a report to 100 matched
|
|
137
|
+
samples, reports truncation and discards raw error messages and metadata.
|
|
138
|
+
|
|
139
|
+
Test locally with Stripe's thin-event forwarding and meter-error triggers before
|
|
140
|
+
production. Use the sandbox and verify webhook signatures. See Stripe's
|
|
141
|
+
[recording and error guide](https://docs.stripe.com/billing/subscriptions/usage-based/recording-usage-api),
|
|
142
|
+
[event creation contract](https://docs.stripe.com/api/billing/meter-event/create)
|
|
143
|
+
and [finite idempotency retention](https://docs.stripe.com/api/idempotent_requests).
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@fantastic.dev/better-stripe",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.54.0",
|
|
4
4
|
"description": "A Convex component for Stripe V2 Accounts API integration.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"stripe",
|
|
@@ -101,7 +101,9 @@
|
|
|
101
101
|
"docs/configuration.md",
|
|
102
102
|
"docs/architecture.md",
|
|
103
103
|
"docs/development.md",
|
|
104
|
-
"docs/usage-ledger.md"
|
|
104
|
+
"docs/usage-ledger.md",
|
|
105
|
+
"docs/usage-catalog.md",
|
|
106
|
+
"docs/usage-delivery.md"
|
|
105
107
|
],
|
|
106
108
|
"scripts": {
|
|
107
109
|
"build": "tsc --project ./tsconfig.build.json && node scripts/check-public-exports.mjs",
|
package/src/client/index.ts
CHANGED
|
@@ -1,3 +1,10 @@
|
|
|
1
|
+
export { UsageCatalogError } from "./usage/catalogTypes.js";
|
|
2
|
+
export type {
|
|
3
|
+
UsageCatalogScope,
|
|
4
|
+
UsageMeterOptions,
|
|
5
|
+
UsagePriceOptions,
|
|
6
|
+
} from "./usage/catalogTypes.js";
|
|
7
|
+
export type { UsagePriceBinding } from "./usage/catalogRead.js";
|
|
1
8
|
import * as setupIntentRead from "./billing/setup-intent-read.js";
|
|
2
9
|
import { UsageLedgerClient } from "./usage/client.js";
|
|
3
10
|
export type { RecordUsageOptions } from "./usage/client.js";
|
|
@@ -1820,3 +1827,19 @@ export type {
|
|
|
1820
1827
|
SubscriptionPaymentMethodOptions,
|
|
1821
1828
|
SubscriptionPaymentMethodResult,
|
|
1822
1829
|
} from "./billing/subscription-payment-method.js";
|
|
1830
|
+
|
|
1831
|
+
export type {
|
|
1832
|
+
UsageDeliveryRequest,
|
|
1833
|
+
UsageDeliveryOutcome,
|
|
1834
|
+
UsageDeliveryProviderOptions,
|
|
1835
|
+
} from "./usage/deliveryProvider.js";
|
|
1836
|
+
export type {
|
|
1837
|
+
UsageDeliveryRef,
|
|
1838
|
+
UsageDeliveryStatus,
|
|
1839
|
+
UsageDeliveryStartOptions,
|
|
1840
|
+
} from "./usage/deliveryClient.js";
|
|
1841
|
+
|
|
1842
|
+
export {
|
|
1843
|
+
usageDeliveryArgs,
|
|
1844
|
+
usageDeliveryResult,
|
|
1845
|
+
} from "./usage/deliveryProtocol.js";
|
|
@@ -1,3 +1,7 @@
|
|
|
1
|
+
import { UsageCatalogError } from "../usage/catalogTypes.js";
|
|
2
|
+
import * as usageCatalog from "../usage/catalog.js";
|
|
3
|
+
import * as usageLifecycle from "../usage/catalogLifecycle.js";
|
|
4
|
+
import { getUsagePriceBinding } from "../usage/catalogRead.js";
|
|
1
5
|
import type Stripe from "stripe";
|
|
2
6
|
import { BillingPortalClient } from "../core/billingPortalClient.js";
|
|
3
7
|
import type { RunCtx } from "../helpers.js";
|
|
@@ -9,6 +13,79 @@ import * as catalog from "./catalog.js";
|
|
|
9
13
|
/** Catalog APIs inherited by BetterStripe. Host authorization remains required. */
|
|
10
14
|
export abstract class CatalogClient extends BillingPortalClient {
|
|
11
15
|
abstract get statementDescriptorSuffix(): string | undefined;
|
|
16
|
+
ensureUsageMeter(ctx: RunCtx, opts: usageCatalog.UsageMeterOptions) {
|
|
17
|
+
return usageCatalog.ensureUsageMeter(
|
|
18
|
+
this.stripe(),
|
|
19
|
+
this.component,
|
|
20
|
+
ctx,
|
|
21
|
+
opts,
|
|
22
|
+
);
|
|
23
|
+
}
|
|
24
|
+
async ensureUsagePrice(ctx: RunCtx, opts: usageCatalog.UsagePriceOptions) {
|
|
25
|
+
await usageCatalog.ensureUsagePrice(
|
|
26
|
+
this.stripe(),
|
|
27
|
+
this.component,
|
|
28
|
+
ctx,
|
|
29
|
+
opts,
|
|
30
|
+
);
|
|
31
|
+
const binding = await getUsagePriceBinding(this.component, ctx, opts);
|
|
32
|
+
if (binding.status !== "available")
|
|
33
|
+
throw new UsageCatalogError(
|
|
34
|
+
"provider_unavailable",
|
|
35
|
+
"Native usage price mirror is unavailable",
|
|
36
|
+
);
|
|
37
|
+
return binding.value;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
adoptUsageMeter(
|
|
41
|
+
ctx: RunCtx,
|
|
42
|
+
opts: usageCatalog.UsageMeterOptions & { meterId: string },
|
|
43
|
+
) {
|
|
44
|
+
return usageLifecycle.adoptUsageMeter(
|
|
45
|
+
this.stripe(),
|
|
46
|
+
this.component,
|
|
47
|
+
ctx,
|
|
48
|
+
opts,
|
|
49
|
+
);
|
|
50
|
+
}
|
|
51
|
+
getUsageMeterFromStripe(
|
|
52
|
+
_ctx: RunCtx,
|
|
53
|
+
opts: Parameters<typeof usageLifecycle.getUsageMeterFromStripe>[1],
|
|
54
|
+
) {
|
|
55
|
+
return usageLifecycle.getUsageMeterFromStripe(this.stripe(), opts);
|
|
56
|
+
}
|
|
57
|
+
listStripeUsageMeters(
|
|
58
|
+
_ctx: RunCtx,
|
|
59
|
+
opts: Parameters<typeof usageLifecycle.listStripeUsageMeters>[1],
|
|
60
|
+
) {
|
|
61
|
+
return usageLifecycle.listStripeUsageMeters(this.stripe(), opts);
|
|
62
|
+
}
|
|
63
|
+
deactivateUsageMeter(
|
|
64
|
+
ctx: RunCtx,
|
|
65
|
+
opts: { scope: usageCatalog.UsageCatalogScope; meterId: string },
|
|
66
|
+
) {
|
|
67
|
+
return usageLifecycle.setUsageMeterActive(
|
|
68
|
+
this.stripe(),
|
|
69
|
+
this.component,
|
|
70
|
+
ctx,
|
|
71
|
+
{ ...opts, active: false },
|
|
72
|
+
);
|
|
73
|
+
}
|
|
74
|
+
reactivateUsageMeter(
|
|
75
|
+
ctx: RunCtx,
|
|
76
|
+
opts: { scope: usageCatalog.UsageCatalogScope; meterId: string },
|
|
77
|
+
) {
|
|
78
|
+
return usageLifecycle.setUsageMeterActive(
|
|
79
|
+
this.stripe(),
|
|
80
|
+
this.component,
|
|
81
|
+
ctx,
|
|
82
|
+
{ ...opts, active: true },
|
|
83
|
+
);
|
|
84
|
+
}
|
|
85
|
+
getUsagePrice(ctx: RunCtx, opts: Parameters<typeof getUsagePriceBinding>[2]) {
|
|
86
|
+
return getUsagePriceBinding(this.component, ctx, opts);
|
|
87
|
+
}
|
|
88
|
+
|
|
12
89
|
async getStripePriceByLookupKey(
|
|
13
90
|
_ctx: RunCtx,
|
|
14
91
|
opts: { lookupKey: string },
|