@fantastic.dev/better-stripe 0.51.0 → 0.52.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.
Files changed (69) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/README.md +1 -1
  3. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts +166 -32
  4. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts.map +1 -1
  5. package/dist/client/connect/payoutExecutionTestHelpers.d.ts +83 -16
  6. package/dist/client/connect/payoutExecutionTestHelpers.d.ts.map +1 -1
  7. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts +134 -0
  8. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts.map +1 -1
  9. package/dist/client/connect/payoutSyncTestHelpers.d.ts +67 -0
  10. package/dist/client/connect/payoutSyncTestHelpers.d.ts.map +1 -1
  11. package/dist/client/index.d.ts +3 -0
  12. package/dist/client/index.d.ts.map +1 -1
  13. package/dist/client/index.js +4 -0
  14. package/dist/client/index.js.map +1 -1
  15. package/dist/client/usage/client.d.ts +37 -0
  16. package/dist/client/usage/client.d.ts.map +1 -0
  17. package/dist/client/usage/client.js +59 -0
  18. package/dist/client/usage/client.js.map +1 -0
  19. package/dist/client/usage/records.d.ts +1 -1
  20. package/dist/client/usage/records.d.ts.map +1 -1
  21. package/dist/client/usage/records.js +1 -1
  22. package/dist/client/usage/records.js.map +1 -1
  23. package/dist/component/_generated/api.d.ts +6 -0
  24. package/dist/component/_generated/api.d.ts.map +1 -1
  25. package/dist/component/_generated/api.js.map +1 -1
  26. package/dist/component/_generated/component.d.ts +79 -0
  27. package/dist/component/_generated/component.d.ts.map +1 -1
  28. package/dist/component/balanceFunding/internal/actions.d.ts +11 -11
  29. package/dist/component/balanceFunding/stateHandlers.d.ts +8 -8
  30. package/dist/component/earnings/triggers.d.ts +178 -16
  31. package/dist/component/earnings/triggers.d.ts.map +1 -1
  32. package/dist/component/payoutRelease/queries.d.ts +2 -2
  33. package/dist/component/payoutRelease/queries.d.ts.map +1 -1
  34. package/dist/component/schema.d.ts +67 -0
  35. package/dist/component/schema.js +5 -0
  36. package/dist/component/schema.js.map +1 -1
  37. package/dist/component/usage/helpers.d.ts +13 -0
  38. package/dist/component/usage/helpers.d.ts.map +1 -0
  39. package/dist/component/usage/helpers.js +34 -0
  40. package/dist/component/usage/helpers.js.map +1 -0
  41. package/dist/component/usage/mutations.d.ts +14 -0
  42. package/dist/component/usage/mutations.d.ts.map +1 -0
  43. package/dist/component/usage/mutations.js +124 -0
  44. package/dist/component/usage/mutations.js.map +1 -0
  45. package/dist/component/usage/queries.d.ts +62 -0
  46. package/dist/component/usage/queries.d.ts.map +1 -0
  47. package/dist/component/usage/queries.js +65 -0
  48. package/dist/component/usage/queries.js.map +1 -0
  49. package/dist/component/usage/schema.d.ts +110 -0
  50. package/dist/component/usage/schema.d.ts.map +1 -0
  51. package/dist/component/usage/schema.js +54 -0
  52. package/dist/component/usage/schema.js.map +1 -0
  53. package/docs/README.md +2 -0
  54. package/docs/metered-usage.md +2 -2
  55. package/docs/metering-setup.md +2 -1
  56. package/docs/usage-ledger.md +62 -0
  57. package/package.json +3 -2
  58. package/src/client/index.ts +5 -0
  59. package/src/client/usage/client.ts +97 -0
  60. package/src/client/usage/ledger-client.test.ts +74 -0
  61. package/src/client/usage/records.ts +1 -1
  62. package/src/component/_generated/api.ts +6 -0
  63. package/src/component/_generated/component.ts +106 -0
  64. package/src/component/schema.ts +10 -0
  65. package/src/component/usage/helpers.ts +33 -0
  66. package/src/component/usage/ledger.test.ts +310 -0
  67. package/src/component/usage/mutations.ts +139 -0
  68. package/src/component/usage/queries.ts +69 -0
  69. package/src/component/usage/schema.ts +65 -0
@@ -0,0 +1,124 @@
1
+ import { v } from "convex/values";
2
+ import { mutation } from "../_generated/server.js";
3
+ import { prepareUsageRecord, } from "../../client/usage/records.js";
4
+ import { defineUsagePlan } from "../../client/usage/contracts.js";
5
+ import { assertUsageReplay } from "../../client/usage/boundaries.js";
6
+ import { scopeKey, subscriptionSnapshot } from "./helpers.js";
7
+ /** Trusted host mutation. Authenticate, authorize scope and verify native binding first. */
8
+ export const record = mutation({
9
+ args: {
10
+ inputJson: v.string(),
11
+ subscriptionJson: v.string(),
12
+ dispatch: v.optional(v.string()),
13
+ reservationId: v.optional(v.id("usageReservations")),
14
+ quota: v.optional(v.number()),
15
+ },
16
+ returns: v.object({
17
+ eventId: v.id("usageEvents"),
18
+ identity: v.string(),
19
+ acceptedAt: v.number(),
20
+ delivery: v.literal("queued"),
21
+ }),
22
+ handler: async (ctx, args) => {
23
+ if (new TextEncoder().encode(args.inputJson).length > 8192)
24
+ throw new Error("Usage payload exceeds size limit");
25
+ const event = prepareUsageRecord(JSON.parse(args.inputJson));
26
+ const key = scopeKey(event.scope);
27
+ const subscription = subscriptionSnapshot(args.subscriptionJson);
28
+ const subscriptionJson = JSON.stringify(subscription);
29
+ const existing = await ctx.db
30
+ .query("usageEvents")
31
+ .withIndex("by_identity", (q) => q.eq("identity", event.identity))
32
+ .unique();
33
+ if (existing) {
34
+ if (args.reservationId !== undefined &&
35
+ args.reservationId !== existing.reservationId)
36
+ throw new Error("Conflicting usage reservation replay");
37
+ assertUsageReplay(JSON.parse(existing.recordJson), event);
38
+ if (existing.subscriptionJson !== subscriptionJson)
39
+ throw new Error("Conflicting usage replay");
40
+ const outbox = await ctx.db
41
+ .query("usageOutbox")
42
+ .withIndex("by_event", (q) => q.eq("eventId", existing._id))
43
+ .unique();
44
+ if (!outbox)
45
+ throw new Error("Usage outbox invariant violated");
46
+ // Acceptance is an immutable receipt; subsequent delivery is read separately.
47
+ return {
48
+ eventId: existing._id,
49
+ identity: existing.identity,
50
+ acceptedAt: existing.acceptedAt,
51
+ delivery: "queued",
52
+ };
53
+ }
54
+ const now = Math.floor(Date.now() / 1000);
55
+ if (event.occurredAt < now - 35 * 86400 || event.occurredAt > now + 300)
56
+ throw new Error("Usage occurrence is outside the native delivery window");
57
+ if (event.binding.stripePriceId !== subscription.stripePriceId ||
58
+ event.occurredAt < subscription.period.start ||
59
+ event.occurredAt >= subscription.period.end)
60
+ throw new Error("Usage does not match its subscription period/price");
61
+ const quota = args.quota ?? 100000;
62
+ if (!Number.isInteger(quota) || quota < 1 || quota > 100000)
63
+ throw new Error("Invalid usage scope quota");
64
+ const counter = await ctx.db
65
+ .query("usageScopeCounters")
66
+ .withIndex("by_scope", (q) => q.eq("scopeKey", key))
67
+ .unique();
68
+ if ((counter?.count ?? 0) >= quota)
69
+ throw new Error("Usage scope quota exhausted");
70
+ const reservation = args.reservationId
71
+ ? await ctx.db.get("usageReservations", args.reservationId)
72
+ : null;
73
+ if (args.reservationId !== undefined && !reservation)
74
+ throw new Error("Usage reservation is unavailable");
75
+ if (event.binding.plan.model === "prepaid" && !reservation)
76
+ throw new Error("A matching usage reservation is required");
77
+ if (reservation &&
78
+ (reservation.scopeKey !== key ||
79
+ reservation.sourceEventId !== event.sourceEventId ||
80
+ JSON.stringify(defineUsagePlan(JSON.parse(reservation.planJson))) !==
81
+ JSON.stringify(event.binding.plan) ||
82
+ reservation.scaledQuantity !== event.scaledQuantity ||
83
+ reservation.state !== "reserved"))
84
+ throw new Error("Usage reservation does not match event");
85
+ const eventId = await ctx.db.insert("usageEvents", {
86
+ reservationId: args.reservationId,
87
+ scopeKey: key,
88
+ identity: event.identity,
89
+ recordJson: JSON.stringify(event),
90
+ subscriptionJson,
91
+ occurredAt: event.occurredAt,
92
+ acceptedAt: now,
93
+ });
94
+ await ctx.db.insert("usageOutbox", {
95
+ eventId,
96
+ scopeKey: key,
97
+ state: "queued",
98
+ attempts: 0,
99
+ nextAttemptAt: now,
100
+ providerIdentifier: `bs_usage_${eventId}`,
101
+ dispatch: args.dispatch,
102
+ });
103
+ if (counter)
104
+ await ctx.db.patch("usageScopeCounters", counter._id, {
105
+ count: counter.count + 1,
106
+ });
107
+ else
108
+ await ctx.db.insert("usageScopeCounters", { scopeKey: key, count: 1 });
109
+ if (reservation)
110
+ await ctx.db.patch("usageReservations", reservation._id, {
111
+ state: "committed",
112
+ eventId,
113
+ });
114
+ if (args.dispatch)
115
+ await ctx.scheduler.runAfter(0, args.dispatch, { eventId });
116
+ return {
117
+ eventId,
118
+ identity: event.identity,
119
+ acceptedAt: now,
120
+ delivery: "queued",
121
+ };
122
+ },
123
+ });
124
+ //# sourceMappingURL=mutations.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mutations.js","sourceRoot":"","sources":["../../../src/component/usage/mutations.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,eAAe,CAAC;AAElC,OAAO,EAAE,QAAQ,EAAE,MAAM,yBAAyB,CAAC;AACnD,OAAO,EACL,kBAAkB,GAEnB,MAAM,+BAA+B,CAAC;AACvC,OAAO,EAAE,eAAe,EAAE,MAAM,iCAAiC,CAAC;AAClE,OAAO,EAAE,iBAAiB,EAAE,MAAM,kCAAkC,CAAC;AACrE,OAAO,EAAE,QAAQ,EAAE,oBAAoB,EAAE,MAAM,cAAc,CAAC;AAE9D,4FAA4F;AAC5F,MAAM,CAAC,MAAM,MAAM,GAAG,QAAQ,CAAC;IAC7B,IAAI,EAAE;QACJ,SAAS,EAAE,CAAC,CAAC,MAAM,EAAE;QACrB,gBAAgB,EAAE,CAAC,CAAC,MAAM,EAAE;QAC5B,QAAQ,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC;QAChC,aAAa,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,EAAE,CAAC,mBAAmB,CAAC,CAAC;QACpD,KAAK,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC;KAC9B;IACD,OAAO,EAAE,CAAC,CAAC,MAAM,CAAC;QAChB,OAAO,EAAE,CAAC,CAAC,EAAE,CAAC,aAAa,CAAC;QAC5B,QAAQ,EAAE,CAAC,CAAC,MAAM,EAAE;QACpB,UAAU,EAAE,CAAC,CAAC,M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;CACF,CAAC,CAAC"}
@@ -0,0 +1,62 @@
1
+ export declare const get: import("convex/server").RegisteredQuery<"public", {
2
+ eventId: import("convex/values").GenericId<"usageEvents">;
3
+ scope: {
4
+ customerAccount: string;
5
+ livemode: boolean;
6
+ meterId: string;
7
+ stripeAccountId: string;
8
+ };
9
+ }, Promise<{
10
+ event: {
11
+ _creationTime: number;
12
+ _id: import("convex/values").GenericId<"usageEvents">;
13
+ acceptedAt: number;
14
+ identity: string;
15
+ occurredAt: number;
16
+ recordJson: string;
17
+ reservationId?: import("convex/values").GenericId<"usageReservations"> | undefined;
18
+ scopeKey: string;
19
+ subscriptionJson: string;
20
+ };
21
+ delivery: "held" | "provider_accepted" | "queued" | "rejected" | "sending" | "unknown";
22
+ } | null>>;
23
+ export declare const read: import("convex/server").RegisteredQuery<"public", {
24
+ paginationOpts: {
25
+ id?: number;
26
+ endCursor?: string | null;
27
+ maximumRowsRead?: number;
28
+ maximumBytesRead?: number;
29
+ numItems: number;
30
+ cursor: string | null;
31
+ };
32
+ period: {
33
+ end: number;
34
+ start: number;
35
+ };
36
+ scope: {
37
+ customerAccount: string;
38
+ livemode: boolean;
39
+ meterId: string;
40
+ stripeAccountId: string;
41
+ };
42
+ }, Promise<{
43
+ isDone: boolean;
44
+ continueCursor: import("convex/server").Cursor;
45
+ splitCursor?: import("convex/server").Cursor | null;
46
+ pageStatus?: "SplitRecommended" | "SplitRequired" | null;
47
+ page: {
48
+ event: {
49
+ _creationTime: number;
50
+ _id: import("convex/values").GenericId<"usageEvents">;
51
+ acceptedAt: number;
52
+ identity: string;
53
+ occurredAt: number;
54
+ recordJson: string;
55
+ reservationId?: import("convex/values").GenericId<"usageReservations"> | undefined;
56
+ scopeKey: string;
57
+ subscriptionJson: string;
58
+ };
59
+ delivery: "held" | "provider_accepted" | "queued" | "rejected" | "sending" | "unknown";
60
+ }[];
61
+ }>>;
62
+ //# sourceMappingURL=queries.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"queries.d.ts","sourceRoot":"","sources":["../../../src/component/usage/queries.ts"],"names":[],"mappings":"AAaA,eAAO,MAAM,GAAG;;;;;;;;;;;;;;;;;;;;;UAcd,CAAC;AACH,eAAO,MAAM,IAAI;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAwCf,CAAC"}
@@ -0,0 +1,65 @@
1
+ import { v } from "convex/values";
2
+ import { paginationOptsValidator, paginationResultValidator, } from "convex/server";
3
+ import { paginator } from "convex-helpers/server/pagination";
4
+ import { query } from "../_generated/server.js";
5
+ import schema from "../schema.js";
6
+ import { eventDoc, scopeValidator, deliveryValidator } from "./schema.js";
7
+ import { scopeKey } from "./helpers.js";
8
+ import { validateUsagePageRequest } from "../../client/usage/boundaries.js";
9
+ const view = v.object({ event: eventDoc, delivery: deliveryValidator });
10
+ export const get = query({
11
+ args: { scope: scopeValidator, eventId: v.id("usageEvents") },
12
+ returns: v.union(view, v.null()),
13
+ handler: async (ctx, args) => {
14
+ const key = scopeKey(args.scope);
15
+ const event = await ctx.db.get("usageEvents", args.eventId);
16
+ if (!event || event.scopeKey !== key)
17
+ return null;
18
+ const outbox = await ctx.db
19
+ .query("usageOutbox")
20
+ .withIndex("by_event", (q) => q.eq("eventId", event._id))
21
+ .unique();
22
+ if (!outbox)
23
+ throw new Error("Usage outbox invariant violated");
24
+ return { event, delivery: outbox.state };
25
+ },
26
+ });
27
+ export const read = query({
28
+ args: {
29
+ scope: scopeValidator,
30
+ period: v.object({ start: v.number(), end: v.number() }),
31
+ paginationOpts: paginationOptsValidator,
32
+ },
33
+ returns: paginationResultValidator(view),
34
+ handler: async (ctx, args) => {
35
+ const key = scopeKey(args.scope);
36
+ const request = validateUsagePageRequest({
37
+ period: args.period,
38
+ limit: args.paginationOpts.numItems,
39
+ cursor: args.paginationOpts.cursor,
40
+ });
41
+ const result = await paginator(ctx.db, schema)
42
+ .query("usageEvents")
43
+ .withIndex("by_scope_time", (q) => q
44
+ .eq("scopeKey", key)
45
+ .gte("occurredAt", request.period.start)
46
+ .lt("occurredAt", request.period.end))
47
+ .order("desc")
48
+ .paginate({
49
+ ...args.paginationOpts,
50
+ maximumRowsRead: 200,
51
+ maximumBytesRead: 1000000,
52
+ });
53
+ const page = await Promise.all(result.page.map(async (event) => {
54
+ const outbox = await ctx.db
55
+ .query("usageOutbox")
56
+ .withIndex("by_event", (q) => q.eq("eventId", event._id))
57
+ .unique();
58
+ if (!outbox)
59
+ throw new Error("Usage outbox invariant violated");
60
+ return { event, delivery: outbox.state };
61
+ }));
62
+ return { ...result, page };
63
+ },
64
+ });
65
+ //# sourceMappingURL=queries.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"queries.js","sourceRoot":"","sources":["../../../src/component/usage/queries.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,eAAe,CAAC;AAClC,OAAO,EACL,uBAAuB,EACvB,yBAAyB,GAC1B,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,SAAS,EAAE,MAAM,kCAAkC,CAAC;AAC7D,OAAO,EAAE,KAAK,EAAE,MAAM,yBAAyB,CAAC;AAChD,OAAO,MAAM,MAAM,cAAc,CAAC;AAClC,OAAO,EAAE,QAAQ,EAAE,cAAc,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAC1E,OAAO,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAC;AACxC,OAAO,EAAE,wBAAwB,EAAE,MAAM,kCAAkC,CAAC;AAE5E,MAAM,IAAI,GAAG,CAAC,CAAC,MAAM,CAAC,EAAE,KAAK,EAAE,QAAQ,EAAE,QAAQ,EAAE,iBAAiB,EAAE,CAAC,CAAC;AACxE,MAAM,CAAC,MAAM,GAAG,GAAG,KAAK,CAAC;IACvB,IAAI,EAAE,EAAE,KAAK,EAAE,cAAc,EAAE,OAAO,EAAE,CAAC,CAAC,EAAE,CAAC,aAAa,CAAC,EAAE;IAC7D,OAAO,EAAE,CAAC,CAAC,KAAK,CAAC,IAAI,EAAE,CA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;IAC7B,CAAC;CACF,CAAC,CAAC"}
@@ -0,0 +1,110 @@
1
+ export declare const scopeValidator: import("convex/values").VObject<{
2
+ customerAccount: string;
3
+ livemode: boolean;
4
+ meterId: string;
5
+ stripeAccountId: string;
6
+ }, {
7
+ stripeAccountId: import("convex/values").VString<string, "required">;
8
+ customerAccount: import("convex/values").VString<string, "required">;
9
+ meterId: import("convex/values").VString<string, "required">;
10
+ livemode: import("convex/values").VBoolean<boolean, "required">;
11
+ }, "required", "customerAccount" | "livemode" | "meterId" | "stripeAccountId">;
12
+ export declare const deliveryValidator: import("convex/values").VUnion<"held" | "provider_accepted" | "queued" | "rejected" | "sending" | "unknown", [import("convex/values").VLiteral<"queued", "required">, import("convex/values").VLiteral<"sending", "required">, import("convex/values").VLiteral<"provider_accepted", "required">, import("convex/values").VLiteral<"rejected", "required">, import("convex/values").VLiteral<"unknown", "required">, import("convex/values").VLiteral<"held", "required">], "required", never>;
13
+ export declare const eventFields: {
14
+ reservationId: import("convex/values").VId<import("convex/values").GenericId<"usageReservations"> | undefined, "optional">;
15
+ scopeKey: import("convex/values").VString<string, "required">;
16
+ identity: import("convex/values").VString<string, "required">;
17
+ recordJson: import("convex/values").VString<string, "required">;
18
+ subscriptionJson: import("convex/values").VString<string, "required">;
19
+ occurredAt: import("convex/values").VFloat64<number, "required">;
20
+ acceptedAt: import("convex/values").VFloat64<number, "required">;
21
+ };
22
+ export declare const eventDoc: import("convex/values").VObject<{
23
+ _creationTime: number;
24
+ _id: import("convex/values").GenericId<"usageEvents">;
25
+ acceptedAt: number;
26
+ identity: string;
27
+ occurredAt: number;
28
+ recordJson: string;
29
+ reservationId?: import("convex/values").GenericId<"usageReservations"> | undefined;
30
+ scopeKey: string;
31
+ subscriptionJson: string;
32
+ }, {
33
+ reservationId: import("convex/values").VId<import("convex/values").GenericId<"usageReservations"> | undefined, "optional">;
34
+ scopeKey: import("convex/values").VString<string, "required">;
35
+ identity: import("convex/values").VString<string, "required">;
36
+ recordJson: import("convex/values").VString<string, "required">;
37
+ subscriptionJson: import("convex/values").VString<string, "required">;
38
+ occurredAt: import("convex/values").VFloat64<number, "required">;
39
+ acceptedAt: import("convex/values").VFloat64<number, "required">;
40
+ _id: import("convex/values").VId<import("convex/values").GenericId<"usageEvents">, "required">;
41
+ _creationTime: import("convex/values").VFloat64<number, "required">;
42
+ }, "required", "_creationTime" | "_id" | "acceptedAt" | "identity" | "occurredAt" | "recordJson" | "reservationId" | "scopeKey" | "subscriptionJson">;
43
+ export declare const usageEventsTable: import("convex/server").TableDefinition<import("convex/values").VObject<{
44
+ acceptedAt: number;
45
+ identity: string;
46
+ occurredAt: number;
47
+ recordJson: string;
48
+ reservationId?: import("convex/values").GenericId<"usageReservations"> | undefined;
49
+ scopeKey: string;
50
+ subscriptionJson: string;
51
+ }, {
52
+ reservationId: import("convex/values").VId<import("convex/values").GenericId<"usageReservations"> | undefined, "optional">;
53
+ scopeKey: import("convex/values").VString<string, "required">;
54
+ identity: import("convex/values").VString<string, "required">;
55
+ recordJson: import("convex/values").VString<string, "required">;
56
+ subscriptionJson: import("convex/values").VString<string, "required">;
57
+ occurredAt: import("convex/values").VFloat64<number, "required">;
58
+ acceptedAt: import("convex/values").VFloat64<number, "required">;
59
+ }, "required", "acceptedAt" | "identity" | "occurredAt" | "recordJson" | "reservationId" | "scopeKey" | "subscriptionJson">, {
60
+ by_identity: ["identity", "_creationTime"];
61
+ by_scope_time: ["scopeKey", "occurredAt", "_creationTime"];
62
+ }, {}, {}>;
63
+ export declare const usageOutboxTable: import("convex/server").TableDefinition<import("convex/values").VObject<{
64
+ attempts: number;
65
+ dispatch?: string | undefined;
66
+ eventId: import("convex/values").GenericId<"usageEvents">;
67
+ nextAttemptAt: number;
68
+ providerIdentifier: string;
69
+ scopeKey: string;
70
+ state: "held" | "provider_accepted" | "queued" | "rejected" | "sending" | "unknown";
71
+ }, {
72
+ eventId: import("convex/values").VId<import("convex/values").GenericId<"usageEvents">, "required">;
73
+ scopeKey: import("convex/values").VString<string, "required">;
74
+ state: import("convex/values").VUnion<"held" | "provider_accepted" | "queued" | "rejected" | "sending" | "unknown", [import("convex/values").VLiteral<"queued", "required">, import("convex/values").VLiteral<"sending", "required">, import("convex/values").VLiteral<"provider_accepted", "required">, import("convex/values").VLiteral<"rejected", "required">, import("convex/values").VLiteral<"unknown", "required">, import("convex/values").VLiteral<"held", "required">], "required", never>;
75
+ attempts: import("convex/values").VFloat64<number, "required">;
76
+ nextAttemptAt: import("convex/values").VFloat64<number, "required">;
77
+ providerIdentifier: import("convex/values").VString<string, "required">;
78
+ dispatch: import("convex/values").VString<string | undefined, "optional">;
79
+ }, "required", "attempts" | "dispatch" | "eventId" | "nextAttemptAt" | "providerIdentifier" | "scopeKey" | "state">, {
80
+ by_event: ["eventId", "_creationTime"];
81
+ by_scope_state: ["scopeKey", "state", "_creationTime"];
82
+ by_state_next: ["state", "nextAttemptAt", "_creationTime"];
83
+ }, {}, {}>;
84
+ export declare const usageScopeCountersTable: import("convex/server").TableDefinition<import("convex/values").VObject<{
85
+ count: number;
86
+ scopeKey: string;
87
+ }, {
88
+ scopeKey: import("convex/values").VString<string, "required">;
89
+ count: import("convex/values").VFloat64<number, "required">;
90
+ }, "required", "count" | "scopeKey">, {
91
+ by_scope: ["scopeKey", "_creationTime"];
92
+ }, {}, {}>;
93
+ export declare const usageReservationsTable: import("convex/server").TableDefinition<import("convex/values").VObject<{
94
+ eventId?: import("convex/values").GenericId<"usageEvents"> | undefined;
95
+ planJson: string;
96
+ scaledQuantity: string;
97
+ scopeKey: string;
98
+ sourceEventId: string;
99
+ state: "committed" | "released" | "reserved";
100
+ }, {
101
+ scopeKey: import("convex/values").VString<string, "required">;
102
+ sourceEventId: import("convex/values").VString<string, "required">;
103
+ planJson: import("convex/values").VString<string, "required">;
104
+ scaledQuantity: import("convex/values").VString<string, "required">;
105
+ state: import("convex/values").VUnion<"committed" | "released" | "reserved", [import("convex/values").VLiteral<"reserved", "required">, import("convex/values").VLiteral<"committed", "required">, import("convex/values").VLiteral<"released", "required">], "required", never>;
106
+ eventId: import("convex/values").VId<import("convex/values").GenericId<"usageEvents"> | undefined, "optional">;
107
+ }, "required", "eventId" | "planJson" | "scaledQuantity" | "scopeKey" | "sourceEventId" | "state">, {
108
+ by_scope_source: ["scopeKey", "sourceEventId", "_creationTime"];
109
+ }, {}, {}>;
110
+ //# sourceMappingURL=schema.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"schema.d.ts","sourceRoot":"","sources":["../../../src/component/usage/schema.ts"],"names":[],"mappings":"AAGA,eAAO,MAAM,cAAc;;;;;;;;;;8EAKzB,CAAC;AACH,eAAO,MAAM,iBAAiB,geAO7B,CAAC;AACF,eAAO,MAAM,WAAW;IACtB,aAAa;IACb,QAAQ;IACR,QAAQ;IACR,UAAU;IACV,gBAAgB;IAChB,UAAU;IACV,UAAU;CACX,CAAC;AACF,eAAO,MAAM,QAAQ;;;;;;;;;;;;;;;;;;;;qJAInB,CAAC;AACH,eAAO,MAAM,gBAAgB;;;;;;;;;;;;;;;;;;;UAEwB,CAAC;AACtD,eAAO,MAAM,gBAAgB;;;;;;;;;;;;;;;;;;;;UAWoB,CAAC;AAClD,eAAO,MAAM,uBAAuB;;;;;;;;UAGF,CAAC;AAInC,eAAO,MAAM,sBAAsB;;;;;;;;;;;;;;;;UAWuB,CAAC"}
@@ -0,0 +1,54 @@
1
+ import { defineTable } from "convex/server";
2
+ import { v } from "convex/values";
3
+ export const scopeValidator = v.object({
4
+ stripeAccountId: v.string(),
5
+ customerAccount: v.string(),
6
+ meterId: v.string(),
7
+ livemode: v.boolean(),
8
+ });
9
+ export const deliveryValidator = v.union(v.literal("queued"), v.literal("sending"), v.literal("provider_accepted"), v.literal("rejected"), v.literal("unknown"), v.literal("held"));
10
+ export const eventFields = {
11
+ reservationId: v.optional(v.id("usageReservations")),
12
+ scopeKey: v.string(),
13
+ identity: v.string(),
14
+ recordJson: v.string(),
15
+ subscriptionJson: v.string(),
16
+ occurredAt: v.number(),
17
+ acceptedAt: v.number(),
18
+ };
19
+ export const eventDoc = v.object({
20
+ _id: v.id("usageEvents"),
21
+ _creationTime: v.number(),
22
+ ...eventFields,
23
+ });
24
+ export const usageEventsTable = defineTable(eventFields)
25
+ .index("by_identity", ["identity"])
26
+ .index("by_scope_time", ["scopeKey", "occurredAt"]);
27
+ export const usageOutboxTable = defineTable({
28
+ eventId: v.id("usageEvents"),
29
+ scopeKey: v.string(),
30
+ state: deliveryValidator,
31
+ attempts: v.number(),
32
+ nextAttemptAt: v.number(),
33
+ providerIdentifier: v.string(),
34
+ dispatch: v.optional(v.string()),
35
+ })
36
+ .index("by_event", ["eventId"])
37
+ .index("by_state_next", ["state", "nextAttemptAt"])
38
+ .index("by_scope_state", ["scopeKey", "state"]);
39
+ export const usageScopeCountersTable = defineTable({
40
+ scopeKey: v.string(),
41
+ count: v.number(),
42
+ }).index("by_scope", ["scopeKey"]);
43
+ // Only accounting APIs may create reservations. There is no public arbitrary
44
+ // reservation/grant insertion API. Acceptance commits a matching reservation
45
+ // in the same transaction as its immutable event and outbox intent.
46
+ export const usageReservationsTable = defineTable({
47
+ scopeKey: v.string(),
48
+ sourceEventId: v.string(),
49
+ planJson: v.string(),
50
+ scaledQuantity: v.string(),
51
+ state: v.union(v.literal("reserved"), v.literal("committed"), v.literal("released")),
52
+ eventId: v.optional(v.id("usageEvents")),
53
+ }).index("by_scope_source", ["scopeKey", "sourceEventId"]);
54
+ //# sourceMappingURL=schema.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"schema.js","sourceRoot":"","sources":["../../../src/component/usage/schema.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAC5C,OAAO,EAAE,CAAC,EAAE,MAAM,eAAe,CAAC;AAElC,MAAM,CAAC,MAAM,cAAc,GAAG,CAAC,CAAC,MAAM,CAAC;IACrC,eAAe,EAAE,CAAC,CAAC,MAAM,EAAE;IAC3B,eAAe,EAAE,CAAC,C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,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,EAAE,CAAC,aAAa,CAAC,CAAC;CACzC,CAAC,CAAC,KAAK,CAAC,iBAAiB,EAAE,CAAC,UAAU,EAAE,eAAe,CAAC,CAAC,CAAC"}
package/docs/README.md CHANGED
@@ -56,3 +56,5 @@ covers sandbox configuration, checkout comparisons, and test flows.
56
56
 
57
57
  Start with the [native Stripe setup guide](metering-setup.md), then read the
58
58
  [shared contracts and sandbox evidence](metered-usage.md).
59
+
60
+ [Atomic usage ledger and scoped history](usage-ledger.md) describes acceptance and retention.
@@ -348,8 +348,8 @@ normalized immutable terms and rejects changed replay on the original identity,
348
348
  including time, currency, mapped customer and version. A transition must never
349
349
  turn a prepaid consumption into a new pay-as-you-go charge.
350
350
 
351
- These are shared contracts and host-boundary helpers. Runtime catalog, acceptance,
352
- delivery, correction and transition adapters are implemented in subsequent tickets.
351
+ These are shared contracts and host-boundary helpers. The [atomic ledger](usage-ledger.md) implements acceptance and local history.
352
+ Catalog, delivery, correction and transition adapters follow in subsequent tickets.
353
353
 
354
354
  `UsageContractPort` defines shared `record`, paginated `read`, `reconcile` and
355
355
  `capabilities` requests/results for host adapters. `record` is an atomic local
@@ -6,7 +6,8 @@ integrations, but Billing Meters APIs remain available. This project is building
6
6
  native Stripe integration into the existing BetterStripe Convex component.
7
7
 
8
8
  Current status: shared configuration/quantity helpers and repository sandbox probes
9
- are implemented. Operational recording, durable delivery, allowance/credit
9
+ are implemented. Atomic recording and bounded local history are available through the
10
+ [usage ledger](usage-ledger.md). Durable provider delivery, allowance/credit
10
11
  accounting and the three example UI flows are still under development. The probes
11
12
  below verify provider behavior directly; they are not public BetterStripe billing
12
13
  workflows. See [metered usage contracts and evidence](metered-usage.md).
@@ -0,0 +1,62 @@
1
+ # Record usage atomically
2
+
3
+ `stripe.usage.record`, `get` and `read` are trusted host APIs. The host must
4
+ authenticate the actor, authorize the exact Stripe realm/payer/meter and resolve
5
+ the native customer, subscription, item and price from verified server state.
6
+ Use `authorizeUsageRecord` to run authorization and billable-activity policy before
7
+ calling the facade. Browser-supplied account IDs and prices are not authorization.
8
+
9
+ ```ts
10
+ import { authorizeUsageRecord } from "@fantastic.dev/better-stripe/usage";
11
+
12
+ // In a host mutation, resolve these from authenticated, persisted activity.
13
+ const receipt = await authorizeUsageRecord(ctx, policy, serverEvent, (event) =>
14
+ stripe.usage.record(ctx, { event, subscription: verifiedSubscription }),
15
+ );
16
+ ```
17
+
18
+ Acceptance writes an immutable event, durable outbox row and retained-scope counter
19
+ in one Convex transaction. An optional `dispatch` handle schedules an internal
20
+ host action in that transaction. Create the handle on the server; never accept it
21
+ from a browser. Scheduling failure rolls back acceptance, counter changes and any
22
+ reservation commit. Without dispatch, the outbox stays queued for later delivery.
23
+ Recording does not contact Stripe or prove billing, aggregation or payment.
24
+
25
+ Use stable source-event IDs. Equal replay returns the original acceptance receipt,
26
+ including after the event's delivery window expires. A changed quantity, occurrence
27
+ time, mapped customer, plan/version, currency, price or subscription snapshot
28
+ conflicts. Realm, payer, meter and test/live mode are independent scopes. A source
29
+ ID reused in a different authorized scope is an independent event, not permission
30
+ to alter the original. Do not move activity between scopes to repair a failure.
31
+
32
+ Quantities use the shared exact decimal contract and integer scaled representation.
33
+ New occurrence times must be within Stripe's 35-day past/5-minute future window
34
+ and the immutable half-open subscription period. The price must match that
35
+ subscription binding. The component assigns acceptance time in Unix seconds.
36
+ Payloads are limited to 8 KiB and subscription snapshots to 2 KiB, measured as UTF-8.
37
+ No arbitrary event metadata, secret or user payload is accepted.
38
+
39
+ The default quota is 100,000 retained events per scope. A host may select a lower
40
+ `quota`, from 1 to 100,000. Exhaustion rejects new work and preserves history.
41
+ Replays do not consume quota. Export and reconcile bounded pages before planning
42
+ future archival; this implementation has no financial-history deletion API.
43
+ Do not clear the tables to reset a quota or repair unresolved usage.
44
+
45
+ Prepaid recording requires a matching component-owned reservation and atomically
46
+ commits it with the event. The scope, source ID, exact quantity and immutable plan
47
+ must match. No arbitrary reservation-creation API exists. Payment-backed grant and
48
+ reservation provisioning is implemented in the credit-accounting ticket; until
49
+ then the facade rejects prepaid events without such a reservation. Included-usage
50
+ snapshots use the same ledger; strict allowance reservations can use the same
51
+ atomic commit seam when allowance accounting is enabled.
52
+
53
+ `get(ctx, {scope, eventId})` returns null for a foreign scope or absent event.
54
+ `read(ctx, {scope, page: {period: {start, end}, limit, cursor}})` returns `events`,
55
+ `cursor` and `isDone`. It uses an indexed range and bounds pages to 1–100 events.
56
+ The acceptance receipt always records initial queued intent; the view's separate
57
+ `delivery` field reports current outbox state. Reauthorize every page. A complete
58
+ local page history does not establish complete provider aggregation or invoices.
59
+
60
+ This layer implements acceptance/history, not provider delivery or credit funding.
61
+ See [native setup](metering-setup.md), [shared contracts](metered-usage.md) and
62
+ [Stripe's native event windows](https://docs.stripe.com/api/billing/meter-event/create).
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fantastic.dev/better-stripe",
3
- "version": "0.51.0",
3
+ "version": "0.52.0",
4
4
  "description": "A Convex component for Stripe V2 Accounts API integration.",
5
5
  "keywords": [
6
6
  "stripe",
@@ -100,7 +100,8 @@
100
100
  "docs/testing.md",
101
101
  "docs/configuration.md",
102
102
  "docs/architecture.md",
103
- "docs/development.md"
103
+ "docs/development.md",
104
+ "docs/usage-ledger.md"
104
105
  ],
105
106
  "scripts": {
106
107
  "build": "tsc --project ./tsconfig.build.json && node scripts/check-public-exports.mjs",
@@ -1,4 +1,6 @@
1
1
  import * as setupIntentRead from "./billing/setup-intent-read.js";
2
+ import { UsageLedgerClient } from "./usage/client.js";
3
+ export type { RecordUsageOptions } from "./usage/client.js";
2
4
  export type {
3
5
  SetupIntentReadOptions,
4
6
  SetupIntentObservation,
@@ -240,6 +242,9 @@ export type BetterStripeComponent = ComponentApi;
240
242
  // BETTER STRIPE CLIENT
241
243
 
242
244
  export class BetterStripe extends PaymentSourceClient {
245
+ get usage() {
246
+ return new UsageLedgerClient(this.component);
247
+ }
243
248
  readonly stripeApiVersion: SupportedStripeApiVersion;
244
249
  private _apiKey?: string;
245
250
  private _triggers?: SyncTriggers;