@fantastic.dev/better-stripe 0.53.0 → 0.55.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 (184) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/README.md +1 -1
  3. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts +226 -34
  4. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts.map +1 -1
  5. package/dist/client/connect/payoutExecutionTestHelpers.d.ts +97 -1
  6. package/dist/client/connect/payoutExecutionTestHelpers.d.ts.map +1 -1
  7. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts +226 -34
  8. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts.map +1 -1
  9. package/dist/client/connect/payoutSyncTestHelpers.d.ts +97 -1
  10. package/dist/client/connect/payoutSyncTestHelpers.d.ts.map +1 -1
  11. package/dist/client/index.d.ts +8 -0
  12. package/dist/client/index.d.ts.map +1 -1
  13. package/dist/client/index.js +1 -0
  14. package/dist/client/index.js.map +1 -1
  15. package/dist/client/usage/client.d.ts +2 -2
  16. package/dist/client/usage/client.d.ts.map +1 -1
  17. package/dist/client/usage/client.js +3 -3
  18. package/dist/client/usage/client.js.map +1 -1
  19. package/dist/client/usage/deliveryClient.d.ts +64 -0
  20. package/dist/client/usage/deliveryClient.d.ts.map +1 -0
  21. package/dist/client/usage/deliveryClient.js +60 -0
  22. package/dist/client/usage/deliveryClient.js.map +1 -0
  23. package/dist/client/usage/deliveryProtocol.d.ts +130 -0
  24. package/dist/client/usage/deliveryProtocol.d.ts.map +1 -0
  25. package/dist/client/usage/deliveryProtocol.js +21 -0
  26. package/dist/client/usage/deliveryProtocol.js.map +1 -0
  27. package/dist/client/usage/deliveryProvider.d.ts +32 -0
  28. package/dist/client/usage/deliveryProvider.d.ts.map +1 -0
  29. package/dist/client/usage/deliveryProvider.js +127 -0
  30. package/dist/client/usage/deliveryProvider.js.map +1 -0
  31. package/dist/client/usage/index.d.ts +8 -0
  32. package/dist/client/usage/index.d.ts.map +1 -1
  33. package/dist/client/usage/index.js +1 -0
  34. package/dist/client/usage/index.js.map +1 -1
  35. package/dist/client/usage/invoiceObservation.d.ts +38 -0
  36. package/dist/client/usage/invoiceObservation.d.ts.map +1 -0
  37. package/dist/client/usage/invoiceObservation.js +157 -0
  38. package/dist/client/usage/invoiceObservation.js.map +1 -0
  39. package/dist/client/usage/observationClient.d.ts +83 -0
  40. package/dist/client/usage/observationClient.d.ts.map +1 -0
  41. package/dist/client/usage/observationClient.js +157 -0
  42. package/dist/client/usage/observationClient.js.map +1 -0
  43. package/dist/client/usage/observationTypes.d.ts +63 -0
  44. package/dist/client/usage/observationTypes.d.ts.map +1 -0
  45. package/dist/client/usage/observationTypes.js +59 -0
  46. package/dist/client/usage/observationTypes.js.map +1 -0
  47. package/dist/client/usage/providerObservation.d.ts +4 -0
  48. package/dist/client/usage/providerObservation.d.ts.map +1 -0
  49. package/dist/client/usage/providerObservation.js +96 -0
  50. package/dist/client/usage/providerObservation.js.map +1 -0
  51. package/dist/client/usage/reconciliation.d.ts +12 -0
  52. package/dist/client/usage/reconciliation.d.ts.map +1 -0
  53. package/dist/client/usage/reconciliation.js +48 -0
  54. package/dist/client/usage/reconciliation.js.map +1 -0
  55. package/dist/client/usage/summary.d.ts +50 -0
  56. package/dist/client/usage/summary.d.ts.map +1 -0
  57. package/dist/client/usage/summary.js +110 -0
  58. package/dist/client/usage/summary.js.map +1 -0
  59. package/dist/client/webhooks/handler.d.ts.map +1 -1
  60. package/dist/client/webhooks/handler.js +2 -1
  61. package/dist/client/webhooks/handler.js.map +1 -1
  62. package/dist/client/webhooks/meterErrors.d.ts +5 -0
  63. package/dist/client/webhooks/meterErrors.d.ts.map +1 -0
  64. package/dist/client/webhooks/meterErrors.js +98 -0
  65. package/dist/client/webhooks/meterErrors.js.map +1 -0
  66. package/dist/client/webhooks/v2.d.ts.map +1 -1
  67. package/dist/client/webhooks/v2.js +5 -0
  68. package/dist/client/webhooks/v2.js.map +1 -1
  69. package/dist/component/_generated/api.d.ts +22 -0
  70. package/dist/component/_generated/api.d.ts.map +1 -1
  71. package/dist/component/_generated/api.js.map +1 -1
  72. package/dist/component/_generated/component.d.ts +265 -0
  73. package/dist/component/_generated/component.d.ts.map +1 -1
  74. package/dist/component/balanceFunding/internal/actions.d.ts +11 -11
  75. package/dist/component/balanceFunding/mutations.d.ts +27 -27
  76. package/dist/component/balanceFunding/stateHandlers.d.ts +8 -8
  77. package/dist/component/earnings/triggers.d.ts +206 -18
  78. package/dist/component/earnings/triggers.d.ts.map +1 -1
  79. package/dist/component/schema.d.ts +97 -1
  80. package/dist/component/schema.js +6 -0
  81. package/dist/component/schema.js.map +1 -1
  82. package/dist/component/usage/schema.d.ts +101 -1
  83. package/dist/component/usage/schema.d.ts.map +1 -1
  84. package/dist/component/usage/schema.js +11 -2
  85. package/dist/component/usage/schema.js.map +1 -1
  86. package/dist/component/usageDelivery/bridge.d.ts +25 -0
  87. package/dist/component/usageDelivery/bridge.d.ts.map +1 -0
  88. package/dist/component/usageDelivery/bridge.js +45 -0
  89. package/dist/component/usageDelivery/bridge.js.map +1 -0
  90. package/dist/component/usageDelivery/fields.d.ts +79 -0
  91. package/dist/component/usageDelivery/fields.d.ts.map +1 -0
  92. package/dist/component/usageDelivery/fields.js +39 -0
  93. package/dist/component/usageDelivery/fields.js.map +1 -0
  94. package/dist/component/usageDelivery/helpers.d.ts +84 -0
  95. package/dist/component/usageDelivery/helpers.d.ts.map +1 -0
  96. package/dist/component/usageDelivery/helpers.js +63 -0
  97. package/dist/component/usageDelivery/helpers.js.map +1 -0
  98. package/dist/component/usageDelivery/mutations.d.ts +97 -0
  99. package/dist/component/usageDelivery/mutations.d.ts.map +1 -0
  100. package/dist/component/usageDelivery/mutations.js +160 -0
  101. package/dist/component/usageDelivery/mutations.js.map +1 -0
  102. package/dist/component/usageDelivery/queries.d.ts +115 -0
  103. package/dist/component/usageDelivery/queries.d.ts.map +1 -0
  104. package/dist/component/usageDelivery/queries.js +22 -0
  105. package/dist/component/usageDelivery/queries.js.map +1 -0
  106. package/dist/component/usageDelivery/schema.d.ts +79 -0
  107. package/dist/component/usageDelivery/schema.d.ts.map +1 -0
  108. package/dist/component/usageDelivery/schema.js +30 -0
  109. package/dist/component/usageDelivery/schema.js.map +1 -0
  110. package/dist/component/usageDelivery/steps.d.ts +85 -0
  111. package/dist/component/usageDelivery/steps.d.ts.map +1 -0
  112. package/dist/component/usageDelivery/steps.js +161 -0
  113. package/dist/component/usageDelivery/steps.js.map +1 -0
  114. package/dist/component/usageDelivery/workflow.d.ts +15 -0
  115. package/dist/component/usageDelivery/workflow.d.ts.map +1 -0
  116. package/dist/component/usageDelivery/workflow.js +28 -0
  117. package/dist/component/usageDelivery/workflow.js.map +1 -0
  118. package/dist/component/usageObservations/helpers.d.ts +38 -0
  119. package/dist/component/usageObservations/helpers.d.ts.map +1 -0
  120. package/dist/component/usageObservations/helpers.js +80 -0
  121. package/dist/component/usageObservations/helpers.js.map +1 -0
  122. package/dist/component/usageObservations/history.d.ts +6 -0
  123. package/dist/component/usageObservations/history.d.ts.map +1 -0
  124. package/dist/component/usageObservations/history.js +29 -0
  125. package/dist/component/usageObservations/history.js.map +1 -0
  126. package/dist/component/usageObservations/mutations.d.ts +6 -0
  127. package/dist/component/usageObservations/mutations.d.ts.map +1 -0
  128. package/dist/component/usageObservations/mutations.js +39 -0
  129. package/dist/component/usageObservations/mutations.js.map +1 -0
  130. package/dist/component/usageObservations/queries.d.ts +78 -0
  131. package/dist/component/usageObservations/queries.d.ts.map +1 -0
  132. package/dist/component/usageObservations/queries.js +131 -0
  133. package/dist/component/usageObservations/queries.js.map +1 -0
  134. package/dist/component/usageObservations/schema.d.ts +72 -0
  135. package/dist/component/usageObservations/schema.d.ts.map +1 -0
  136. package/dist/component/usageObservations/schema.js +29 -0
  137. package/dist/component/usageObservations/schema.js.map +1 -0
  138. package/docs/README.md +5 -1
  139. package/docs/metering-setup.md +3 -1
  140. package/docs/usage-delivery.md +143 -0
  141. package/docs/usage-observations.md +152 -0
  142. package/package.json +4 -2
  143. package/src/client/index.ts +34 -0
  144. package/src/client/usage/client.ts +5 -2
  145. package/src/client/usage/deliveryClient.ts +130 -0
  146. package/src/client/usage/deliveryProtocol.ts +26 -0
  147. package/src/client/usage/deliveryProvider.test.ts +207 -0
  148. package/src/client/usage/deliveryProvider.ts +155 -0
  149. package/src/client/usage/index.ts +31 -0
  150. package/src/client/usage/invoiceObservation.test.ts +195 -0
  151. package/src/client/usage/invoiceObservation.ts +203 -0
  152. package/src/client/usage/observationClient.ts +233 -0
  153. package/src/client/usage/observationTypes.ts +101 -0
  154. package/src/client/usage/providerObservation.test.ts +207 -0
  155. package/src/client/usage/providerObservation.ts +124 -0
  156. package/src/client/usage/reconciliation.test.ts +117 -0
  157. package/src/client/usage/reconciliation.ts +86 -0
  158. package/src/client/usage/summary.test.ts +222 -0
  159. package/src/client/usage/summary.ts +188 -0
  160. package/src/client/webhooks/handler.ts +2 -1
  161. package/src/client/webhooks/meterErrors.test.ts +164 -0
  162. package/src/client/webhooks/meterErrors.ts +118 -0
  163. package/src/client/webhooks/v2.ts +5 -0
  164. package/src/component/_generated/api.ts +22 -0
  165. package/src/component/_generated/component.ts +437 -0
  166. package/src/component/schema.ts +12 -0
  167. package/src/component/usage/schema.ts +11 -2
  168. package/src/component/usageDelivery/bridge.ts +56 -0
  169. package/src/component/usageDelivery/concurrency.test.ts +62 -0
  170. package/src/component/usageDelivery/fields.ts +60 -0
  171. package/src/component/usageDelivery/helpers.ts +77 -0
  172. package/src/component/usageDelivery/mutations.ts +210 -0
  173. package/src/component/usageDelivery/queries.ts +25 -0
  174. package/src/component/usageDelivery/schema.ts +33 -0
  175. package/src/component/usageDelivery/steps.ts +209 -0
  176. package/src/component/usageDelivery/workflow.test.ts +402 -0
  177. package/src/component/usageDelivery/workflow.ts +36 -0
  178. package/src/component/usageObservations/helpers.ts +95 -0
  179. package/src/component/usageObservations/history.test.ts +87 -0
  180. package/src/component/usageObservations/history.ts +39 -0
  181. package/src/component/usageObservations/mutations.ts +39 -0
  182. package/src/component/usageObservations/queries.test.ts +162 -0
  183. package/src/component/usageObservations/queries.ts +145 -0
  184. package/src/component/usageObservations/schema.ts +40 -0
@@ -0,0 +1,131 @@
1
+ import { paginationOptsValidator, paginationResultValidator, } from "convex/server";
2
+ import { paginator } from "convex-helpers/server/pagination";
3
+ import schema from "../schema.js";
4
+ import { refFields } from "../usageDelivery/schema.js";
5
+ import { read } from "../usageDelivery/helpers.js";
6
+ import { historyDoc } from "./schema.js";
7
+ import { errorDoc } from "../usageDelivery/fields.js";
8
+ import { source } from "./helpers.js";
9
+ import { query } from "../_generated/server.js";
10
+ import { v } from "convex/values";
11
+ import { scopeValidator } from "../usage/schema.js";
12
+ import { scopeKey, subscriptionSnapshot } from "../usage/helpers.js";
13
+ import { validateUsagePageRequest } from "../../client/usage/boundaries.js";
14
+ import { summarizeUsageRecords } from "../../client/usage/summary.js";
15
+ export const summary = query({
16
+ args: {
17
+ scope: scopeValidator,
18
+ period: v.object({ start: v.number(), end: v.number() }),
19
+ maxRecords: v.number(),
20
+ },
21
+ returns: v.string(),
22
+ handler: async (ctx, args) => {
23
+ const key = scopeKey(args.scope);
24
+ validateUsagePageRequest({ period: args.period, limit: 1, cursor: null });
25
+ if (!Number.isInteger(args.maxRecords) ||
26
+ args.maxRecords < 1 ||
27
+ args.maxRecords > 500)
28
+ throw new Error("Usage summary read budget must be 1–500");
29
+ const rows = await ctx.db
30
+ .query("usageEvents")
31
+ .withIndex("by_scope_time", (q) => q
32
+ .eq("scopeKey", key)
33
+ .gte("occurredAt", args.period.start)
34
+ .lt("occurredAt", args.period.end))
35
+ .take(args.maxRecords + 1);
36
+ const views = await Promise.all(rows.slice(0, args.maxRecords).map(async (event) => {
37
+ const [outbox, error] = await Promise.all([
38
+ ctx.db
39
+ .query("usageOutbox")
40
+ .withIndex("by_event", (q) => q.eq("eventId", event._id))
41
+ .unique(),
42
+ ctx.db
43
+ .query("usageDeliveryErrors")
44
+ .withIndex("by_event", (q) => q.eq("eventId", event._id))
45
+ .first(),
46
+ ]);
47
+ if (!outbox)
48
+ throw new Error("Usage outbox invariant violated");
49
+ return {
50
+ record: JSON.parse(event.recordJson),
51
+ subscription: subscriptionSnapshot(event.subscriptionJson),
52
+ delivery: outbox.state,
53
+ hasValidationError: error !== null,
54
+ };
55
+ }));
56
+ return JSON.stringify(summarizeUsageRecords(views, {
57
+ period: args.period,
58
+ observedAt: Math.floor(Date.now() / 1000),
59
+ complete: rows.length <= args.maxRecords,
60
+ }));
61
+ },
62
+ });
63
+ export const cached = query({
64
+ args: { sourceJson: v.string() },
65
+ returns: v.union(v.string(), v.null()),
66
+ handler: async (ctx, args) => {
67
+ const binding = await source(args.sourceJson);
68
+ const row = await ctx.db
69
+ .query("usageProviderObservations")
70
+ .withIndex("by_key", (q) => q.eq("key", binding.key))
71
+ .unique();
72
+ return row &&
73
+ row.scopeKey === binding.scopeKey &&
74
+ row.sourceJson === binding.sourceJson
75
+ ? row.observationJson
76
+ : null;
77
+ },
78
+ });
79
+ function validate(numItems, cursor) {
80
+ validateUsagePageRequest({
81
+ period: { start: 0, end: 1 },
82
+ limit: numItems,
83
+ cursor,
84
+ });
85
+ }
86
+ const paginated = paginationResultValidator(historyDoc);
87
+ export const deliveryHistory = query({
88
+ args: { ...refFields, paginationOpts: paginationOptsValidator },
89
+ returns: v.object({ ...paginated.fields, legacyHistoryMissing: v.boolean() }),
90
+ handler: async (ctx, args) => {
91
+ const { outbox } = await read(ctx, args);
92
+ validate(args.paginationOpts.numItems, args.paginationOpts.cursor);
93
+ const [page, first] = await Promise.all([
94
+ paginator(ctx.db, schema)
95
+ .query("usageDeliveryHistory")
96
+ .withIndex("by_event_sequence", (q) => q.eq("eventId", args.eventId))
97
+ .order("asc")
98
+ .paginate({
99
+ ...args.paginationOpts,
100
+ maximumRowsRead: 200,
101
+ maximumBytesRead: 1000000,
102
+ }),
103
+ ctx.db
104
+ .query("usageDeliveryHistory")
105
+ .withIndex("by_event_identity", (q) => q.eq("eventId", args.eventId).eq("identity", "started:1"))
106
+ .unique(),
107
+ ]);
108
+ return {
109
+ ...page,
110
+ legacyHistoryMissing: outbox.attempts > 0 && first === null,
111
+ };
112
+ },
113
+ });
114
+ export const validationHistory = query({
115
+ args: { ...refFields, paginationOpts: paginationOptsValidator },
116
+ returns: paginationResultValidator(errorDoc),
117
+ handler: async (ctx, args) => {
118
+ await read(ctx, args);
119
+ validate(args.paginationOpts.numItems, args.paginationOpts.cursor);
120
+ return paginator(ctx.db, schema)
121
+ .query("usageDeliveryErrors")
122
+ .withIndex("by_event", (q) => q.eq("eventId", args.eventId))
123
+ .order("desc")
124
+ .paginate({
125
+ ...args.paginationOpts,
126
+ maximumRowsRead: 200,
127
+ maximumBytesRead: 1000000,
128
+ });
129
+ },
130
+ });
131
+ //# sourceMappingURL=queries.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"queries.js","sourceRoot":"","sources":["../../../src/component/usageObservations/queries.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EACvB,yBAAyB,GAC1B,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,SAAS,EAAE,MAAM,kCAAkC,CAAC;AAC7D,OAAO,MAAM,MAAM,cAAc,CAAC;AAClC,OAAO,EAAE,SAAS,EAAE,MAAM,4BAA4B,CAAC;AACvD,OAAO,EAAE,IAAI,EAAE,MAAM,6BAA6B,CAAC;AACnD,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,QAAQ,EAAE,MAAM,4BAA4B,CAAC;AACtD,OAAO,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AACtC,OAAO,EAAE,KAAK,EAAE,MAAM,yBAAyB,CAAC;AAChD,OAAO,EAAE,CAAC,EAAE,MAAM,eAAe,CAAC;AAClC,OAAO,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAC;AACpD,OAAO,EAAE,QA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C,IAAI,KAAK,KAAK,IAAI;SAC5D,CAAC;IACJ,CAAC;CACF,CAAC,CAAC;AACH,MAAM,CAAC,MAAM,iBAAiB,GAAG,KAAK,CAAC;IACrC,IAAI,EAAE,EAAE,GAAG,SAAS,EAAE,cAAc,EAAE,uBAAuB,EAAE;IAC/D,OAAO,EAAE,yBAAyB,CAAC,QAAQ,CAAC;IAC5C,OAAO,EAAE,KAAK,EAAE,GAAG,EAAE,IAAI,EAAE,EAAE;QAC3B,MAAM,IAAI,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC;QACtB,QAAQ,CAAC,IAAI,CAAC,cAAc,CAAC,QAAQ,EAAE,IAAI,CAAC,cAAc,CAAC,MAAM,CAAC,CAAC;QACnE,OAAO,SAAS,CAAC,GAAG,CAAC,EAAE,EAAE,MAAM,CAAC;aAC7B,KAAK,CAAC,qBAAqB,CAAC;aAC5B,SAAS,CAAC,UAAU,EAAE,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,SAAS,EAAE,IAAI,CAAC,OAAO,CAAC,CAAC;aAC3D,KAAK,CAAC,MAAM,CAAC;aACb,QAAQ,CAAC;YACR,GAAG,IAAI,CAAC,cAAc;YACtB,eAAe,EAAE,GAAG;YACpB,gBAAgB,EAAE,OAAO;SAC1B,CAAC,CAAC;IACP,CAAC;CACF,CAAC,CAAC"}
@@ -0,0 +1,72 @@
1
+ export declare const observationsTable: import("convex/server").TableDefinition<import("convex/values").VObject<{
2
+ key: string;
3
+ observationJson: string;
4
+ scopeKey: string;
5
+ sourceJson: string;
6
+ startedAt: number;
7
+ }, {
8
+ key: import("convex/values").VString<string, "required">;
9
+ scopeKey: import("convex/values").VString<string, "required">;
10
+ sourceJson: import("convex/values").VString<string, "required">;
11
+ observationJson: import("convex/values").VString<string, "required">;
12
+ startedAt: import("convex/values").VFloat64<number, "required">;
13
+ }, "required", "key" | "observationJson" | "scopeKey" | "sourceJson" | "startedAt">, {
14
+ by_key: ["key", "_creationTime"];
15
+ }, {}, {}>;
16
+ export declare const historyPhase: import("convex/values").VUnion<"accepted" | "held" | "rate_limited" | "rejected" | "resumed" | "retry_exhausted" | "started" | "unavailable" | "unknown" | "window_expired", [import("convex/values").VLiteral<"started", "required">, import("convex/values").VLiteral<"accepted", "required">, import("convex/values").VLiteral<"rate_limited", "required">, import("convex/values").VLiteral<"unavailable", "required">, import("convex/values").VLiteral<"unknown", "required">, import("convex/values").VLiteral<"rejected", "required">, import("convex/values").VLiteral<"held", "required">, import("convex/values").VLiteral<"resumed", "required">, import("convex/values").VLiteral<"window_expired", "required">, import("convex/values").VLiteral<"retry_exhausted", "required">], "required", never>;
17
+ export declare const historyFields: {
18
+ scopeKey: import("convex/values").VString<string, "required">;
19
+ eventId: import("convex/values").VId<import("convex/values").GenericId<"usageEvents">, "required">;
20
+ sequence: import("convex/values").VFloat64<number, "required">;
21
+ attempt: import("convex/values").VFloat64<number, "required">;
22
+ phase: import("convex/values").VUnion<"accepted" | "held" | "rate_limited" | "rejected" | "resumed" | "retry_exhausted" | "started" | "unavailable" | "unknown" | "window_expired", [import("convex/values").VLiteral<"started", "required">, import("convex/values").VLiteral<"accepted", "required">, import("convex/values").VLiteral<"rate_limited", "required">, import("convex/values").VLiteral<"unavailable", "required">, import("convex/values").VLiteral<"unknown", "required">, import("convex/values").VLiteral<"rejected", "required">, import("convex/values").VLiteral<"held", "required">, import("convex/values").VLiteral<"resumed", "required">, import("convex/values").VLiteral<"window_expired", "required">, import("convex/values").VLiteral<"retry_exhausted", "required">], "required", never>;
23
+ identity: import("convex/values").VString<string, "required">;
24
+ recordedAt: import("convex/values").VFloat64<number, "required">;
25
+ created: import("convex/values").VFloat64<number | undefined, "optional">;
26
+ };
27
+ export declare const historyDoc: import("convex/values").VObject<{
28
+ _creationTime: number;
29
+ _id: import("convex/values").GenericId<"usageDeliveryHistory">;
30
+ attempt: number;
31
+ created?: number | undefined;
32
+ eventId: import("convex/values").GenericId<"usageEvents">;
33
+ identity: string;
34
+ phase: "accepted" | "held" | "rate_limited" | "rejected" | "resumed" | "retry_exhausted" | "started" | "unavailable" | "unknown" | "window_expired";
35
+ recordedAt: number;
36
+ scopeKey: string;
37
+ sequence: number;
38
+ }, {
39
+ scopeKey: import("convex/values").VString<string, "required">;
40
+ eventId: import("convex/values").VId<import("convex/values").GenericId<"usageEvents">, "required">;
41
+ sequence: import("convex/values").VFloat64<number, "required">;
42
+ attempt: import("convex/values").VFloat64<number, "required">;
43
+ phase: import("convex/values").VUnion<"accepted" | "held" | "rate_limited" | "rejected" | "resumed" | "retry_exhausted" | "started" | "unavailable" | "unknown" | "window_expired", [import("convex/values").VLiteral<"started", "required">, import("convex/values").VLiteral<"accepted", "required">, import("convex/values").VLiteral<"rate_limited", "required">, import("convex/values").VLiteral<"unavailable", "required">, import("convex/values").VLiteral<"unknown", "required">, import("convex/values").VLiteral<"rejected", "required">, import("convex/values").VLiteral<"held", "required">, import("convex/values").VLiteral<"resumed", "required">, import("convex/values").VLiteral<"window_expired", "required">, import("convex/values").VLiteral<"retry_exhausted", "required">], "required", never>;
44
+ identity: import("convex/values").VString<string, "required">;
45
+ recordedAt: import("convex/values").VFloat64<number, "required">;
46
+ created: import("convex/values").VFloat64<number | undefined, "optional">;
47
+ _id: import("convex/values").VId<import("convex/values").GenericId<"usageDeliveryHistory">, "required">;
48
+ _creationTime: import("convex/values").VFloat64<number, "required">;
49
+ }, "required", "_creationTime" | "_id" | "attempt" | "created" | "eventId" | "identity" | "phase" | "recordedAt" | "scopeKey" | "sequence">;
50
+ export declare const historyTable: import("convex/server").TableDefinition<import("convex/values").VObject<{
51
+ attempt: number;
52
+ created?: number | undefined;
53
+ eventId: import("convex/values").GenericId<"usageEvents">;
54
+ identity: string;
55
+ phase: "accepted" | "held" | "rate_limited" | "rejected" | "resumed" | "retry_exhausted" | "started" | "unavailable" | "unknown" | "window_expired";
56
+ recordedAt: number;
57
+ scopeKey: string;
58
+ sequence: number;
59
+ }, {
60
+ scopeKey: import("convex/values").VString<string, "required">;
61
+ eventId: import("convex/values").VId<import("convex/values").GenericId<"usageEvents">, "required">;
62
+ sequence: import("convex/values").VFloat64<number, "required">;
63
+ attempt: import("convex/values").VFloat64<number, "required">;
64
+ phase: import("convex/values").VUnion<"accepted" | "held" | "rate_limited" | "rejected" | "resumed" | "retry_exhausted" | "started" | "unavailable" | "unknown" | "window_expired", [import("convex/values").VLiteral<"started", "required">, import("convex/values").VLiteral<"accepted", "required">, import("convex/values").VLiteral<"rate_limited", "required">, import("convex/values").VLiteral<"unavailable", "required">, import("convex/values").VLiteral<"unknown", "required">, import("convex/values").VLiteral<"rejected", "required">, import("convex/values").VLiteral<"held", "required">, import("convex/values").VLiteral<"resumed", "required">, import("convex/values").VLiteral<"window_expired", "required">, import("convex/values").VLiteral<"retry_exhausted", "required">], "required", never>;
65
+ identity: import("convex/values").VString<string, "required">;
66
+ recordedAt: import("convex/values").VFloat64<number, "required">;
67
+ created: import("convex/values").VFloat64<number | undefined, "optional">;
68
+ }, "required", "attempt" | "created" | "eventId" | "identity" | "phase" | "recordedAt" | "scopeKey" | "sequence">, {
69
+ by_event_identity: ["eventId", "identity", "_creationTime"];
70
+ by_event_sequence: ["eventId", "sequence", "_creationTime"];
71
+ }, {}, {}>;
72
+ //# sourceMappingURL=schema.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"schema.d.ts","sourceRoot":"","sources":["../../../src/component/usageObservations/schema.ts"],"names":[],"mappings":"AAEA,eAAO,MAAM,iBAAiB;;;;;;;;;;;;;;UAMH,CAAC;AAE5B,eAAO,MAAM,YAAY,oxBAWxB,CAAC;AACF,eAAO,MAAM,aAAa;IACxB,QAAQ;IACR,OAAO;IACP,QAAQ;IACR,OAAO;IACP,KAAK;IACL,QAAQ;IACR,UAAU;IACV,OAAO;CACR,CAAC;AACF,eAAO,MAAM,UAAU;;;;;;;;;;;;;;;;;;;;;;2IAIrB,CAAC;AACH,eAAO,MAAM,YAAY;;;;;;;;;;;;;;;;;;;;;UAE6B,CAAC"}
@@ -0,0 +1,29 @@
1
+ import { defineTable } from "convex/server";
2
+ import { v } from "convex/values";
3
+ export const observationsTable = defineTable({
4
+ key: v.string(),
5
+ scopeKey: v.string(),
6
+ sourceJson: v.string(),
7
+ observationJson: v.string(),
8
+ startedAt: v.number(),
9
+ }).index("by_key", ["key"]);
10
+ export const historyPhase = v.union(v.literal("started"), v.literal("accepted"), v.literal("rate_limited"), v.literal("unavailable"), v.literal("unknown"), v.literal("rejected"), v.literal("held"), v.literal("resumed"), v.literal("window_expired"), v.literal("retry_exhausted"));
11
+ export const historyFields = {
12
+ scopeKey: v.string(),
13
+ eventId: v.id("usageEvents"),
14
+ sequence: v.number(),
15
+ attempt: v.number(),
16
+ phase: historyPhase,
17
+ identity: v.string(),
18
+ recordedAt: v.number(),
19
+ created: v.optional(v.number()),
20
+ };
21
+ export const historyDoc = v.object({
22
+ _id: v.id("usageDeliveryHistory"),
23
+ _creationTime: v.number(),
24
+ ...historyFields,
25
+ });
26
+ export const historyTable = defineTable(historyFields)
27
+ .index("by_event_sequence", ["eventId", "sequence"])
28
+ .index("by_event_identity", ["eventId", "identity"]);
29
+ //# sourceMappingURL=schema.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"schema.js","sourceRoot":"","sources":["../../../src/component/usageObservations/schema.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAC5C,OAAO,EAAE,CAAC,EAAE,MAAM,eAAe,CAAC;AAClC,MAAM,CAAC,MAAM,iBAAiB,GAAG,WAAW,CAAC;IAC3C,GAAG,EAAE,CAAC,CAAC,MAAM,EAAE;IACf,QAAQ,EAAE,CAAC,CAAC,MAAM,EAAE;IACpB,UAAU,EAAE,CAAC,CAAC,MAAM,EAAE;IACtB,eAAe,EAAE,CAAC,CAAC,MAAM,EAAE;IAC3B,SAAS,EAAE,CAAC,CAAC,MAAM,EAAE;CACtB,CAAC,CAAC,KAAK,CAAC,QAAQ,EAAE,C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AAS,EAAE,UAAU,CAAC,CAAC;KACnD,KAAK,CAAC,mBAAmB,EAAE,CAAC,SAAS,EAAE,UAAU,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. Shared contracts, catalog provisioning and local usage acceptance are available; delivery and credit accounting are in progress.
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
 
@@ -60,3 +60,7 @@ Start with the [native Stripe setup guide](metering-setup.md), then read the
60
60
  [Atomic usage ledger and scoped history](usage-ledger.md) describes acceptance and retention.
61
61
 
62
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.
65
+
66
+ [Usage observations and reconciliation](usage-observations.md) covers exact summaries, paginated audit history, native freshness and invoice observations.
@@ -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, allowance/credit
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).
@@ -184,3 +184,5 @@ Primary references:
184
184
  - [Metronome quickstart](https://docs.metronome.com/guides/get-started/api-quickstart)
185
185
 
186
186
  Use the [native catalog guide](usage-catalog.md) to provision versioned meters and prices through BetterStripe.
187
+
188
+ Use the [usage observation guide](usage-observations.md) for bounded local reads, native aggregate refreshes and honest invoice/credit availability.
@@ -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).
@@ -0,0 +1,152 @@
1
+ # Read and reconcile usage
2
+
3
+ BetterStripe keeps local acceptance, transport acceptance, native aggregates,
4
+ estimates and invoices separate. Start with [setup](metering-setup.md), the
5
+ [catalog](usage-catalog.md), [ledger](usage-ledger.md) and
6
+ [delivery](usage-delivery.md). Authenticate and authorize the exact Stripe realm,
7
+ payer and meter before every read, page or reconciliation call. Resolve the
8
+ original binding and subscription snapshot on the server.
9
+
10
+ ## Local summaries and history
11
+
12
+ ```ts
13
+ const local = await stripe.usage.getSummary(ctx, {
14
+ scope: verifiedScope,
15
+ period: { start, end }, // Unix seconds, half-open.
16
+ maxRecords: 100,
17
+ });
18
+ ```
19
+
20
+ The indexed summary reads at most `maxRecords + 1` immutable records, with a
21
+ budget of 1–500 and a default of 100. `complete: false` means the result is only a
22
+ bounded prefix. It never presents that prefix as a complete bill or silently
23
+ assumes missing history is zero. Use the ledger's paginated `read` to export a
24
+ larger period. An empty complete local result means no local events were found;
25
+ it says nothing about native Stripe usage.
26
+
27
+ Groups retain the original plan, version, unit, currency, customer, price and
28
+ subscription item/period. Quantities and decimal minor currency amounts are
29
+ strings. There is no combined money total across currencies or plan versions.
30
+ Each group distinguishes locally accepted quantities, transport-accepted
31
+ quantities and quantities by current delivery state. Validation-error counts
32
+ count events with observed errors, not a complete inventory of provider errors.
33
+
34
+ Pay-as-you-go estimates apply the original exact rate. Included-unit projections
35
+ require a complete original billing period and apply that period's allowance
36
+ before the overage rate. Partial periods, overlapping native subscription
37
+ items and multiple original bindings within an overlapping period return
38
+ unavailable estimates. A plan or price change on the same item does not reset
39
+ the local allowance. Estimates exclude taxes, discounts, fixed
40
+ fees, rounding and other invoice lines. They are not finalized amounts or limits
41
+ that authorize work. Strict allowance reservations are implemented separately.
42
+ Prepaid balance/estimate fields remain explicitly unavailable until the prepaid
43
+ accounting APIs are configured. They never infer available credits from usage.
44
+
45
+ `read(ctx, {scope, page: {period, limit, cursor}})` returns immutable event history
46
+ with current delivery state. For an event's delivery audit:
47
+
48
+ ```ts
49
+ const attempts = await stripe.usage.readDeliveryHistory(ctx, {
50
+ scope: verifiedScope,
51
+ eventId,
52
+ limit: 20,
53
+ cursor: null,
54
+ });
55
+ const errors = await stripe.usage.readValidationHistory(ctx, {
56
+ scope: verifiedScope,
57
+ eventId,
58
+ limit: 20,
59
+ cursor: null,
60
+ });
61
+ ```
62
+
63
+ Both return `records`, `cursor` and `isDone`. Page sizes are 1–100; continue until
64
+ `isDone`, including an empty final page when required. Delivery history appends
65
+ started attempts, outcomes and operational holds/resumes independently of the
66
+ Workflow journal. Idempotent receipt projection does not duplicate audit entries.
67
+ `legacyHistoryMissing` identifies events whose earlier attempts predate this
68
+ history implementation. History is not reconstructed from guesses. Validation
69
+ history contains only provider samples that were actually observed. Correction
70
+ history is a typed unsupported state until the correction workflow is installed.
71
+
72
+ ## Native aggregates and cached freshness
73
+
74
+ Construct one server-owned observation request using the original binding and
75
+ subscription snapshot:
76
+
77
+ ```ts
78
+ const request = {
79
+ scope: verifiedScope,
80
+ binding: originalBinding,
81
+ subscription: originalSubscription,
82
+ period: { start, end },
83
+ limit: 100,
84
+ cursor: null,
85
+ };
86
+
87
+ // In an authorized action, with the secret resolved at execution time.
88
+ const result = await stripe.usage.reconcile(ctx, request, {
89
+ stripeSecretKey: process.env.STRIPE_SECRET_KEY,
90
+ });
91
+
92
+ // In an authorized reactive query, without a Stripe key or network call.
93
+ const cached = await stripe.usage.getReconciliation(ctx, {
94
+ ...request,
95
+ maxAgeSeconds: 60,
96
+ maxRecords: 100,
97
+ });
98
+ ```
99
+
100
+ `observeProviderUsage` refreshes only the native observation.
101
+ `getProviderUsage` reads only its scoped cache. One refresh makes a bounded native
102
+ page request, with a maximum page size of 100 and zero SDK retries. There is no
103
+ automatic polling loop. Use explicit, bounded refreshes, normally at least a
104
+ minute apart, and keep transient failures visible. Cache identity includes the
105
+ original scope, binding, subscription, exact period and page request. Older
106
+ in-flight refreshes cannot replace a newer projection.
107
+
108
+ Stripe requires minute-aligned aggregate start/end times. The adapter returns
109
+ `unsupported` for unaligned periods and never rounds a billing period to hide
110
+ that difference. An empty native response is `aggregation_pending`, not zero.
111
+ An explicit native zero remains a zero observation with aggregation lag possible.
112
+ Missing pages, overlapping buckets or incomplete period coverage cannot establish
113
+ a complete total. Unsafe integer or fractional provider values are reported as
114
+ unsupported precision because this adapter submits scaled integer units. It never
115
+ rounds a provider number to fit the local quantity contract.
116
+
117
+ Cached available data carries `observedAt` and `stale`. The default freshness
118
+ limit is 60 seconds; hosts may choose 1–86,400 seconds. Fresh transport responses
119
+ can still contain lagging Stripe aggregates. `aggregationLagPossible` stays true.
120
+ Native customer/meter reads require the key's own verified account and mode and
121
+ the original Accounts v2 payer/subscription mapping. Foreign key/context modes
122
+ return typed unsupported or unavailable results.
123
+
124
+ Reconciliation returns independent `local`, `aggregate`, `comparison` and invoice/
125
+ correction availability. `observed_match` means only that complete, fresh observed
126
+ transport quantities equal the observed aggregate for that exact period. It does
127
+ not prove invoice inclusion or payment. Incomplete local history, stale/incomplete
128
+ provider data, unresolved sends and ambiguous terms prevent comparison. A
129
+ mismatch can reflect aggregation lag, external usage or validation errors.
130
+ Reconciliation never resends, cancels, reroutes or reprices billable usage.
131
+
132
+ ## Invoice observations
133
+
134
+ From an authorized action, use `readInvoiceUsage(ctx, request, providerOptions)`
135
+ for a native preview. Add `invoiceId` to request a specific existing invoice.
136
+ This verifies its realm/mode, Accounts v2 payer, native customer and subscription.
137
+ The result distinguishes whole-invoice amounts from matching metered lines,
138
+ preserves full decimal quantities and nullable tiered unit amounts, and reports
139
+ whether the native line page is complete. Missing or ambiguous lines do not become
140
+ a zero meter amount. Native line periods are preserved with Stripe's semantics.
141
+
142
+ Previews remain previews. Only an existing invoice with native finalization
143
+ evidence is marked finalized. `paymentEvidence: "not_resolved"` applies even to a
144
+ paid invoice: credits or out-of-band marking can pay an invoice without new cash.
145
+ Use the separate payment-provenance and settlement APIs before distributing money.
146
+ These readers never finalize, charge, refund or settle an invoice. The generic
147
+ reconciliation result leaves invoices unavailable until explicitly observed.
148
+
149
+ Authoritative references: [native aggregate period and pagination rules](https://docs.stripe.com/api/billing/meter-event-summary/list),
150
+ [asynchronous aggregation and invoice cutoffs](https://docs.stripe.com/billing/subscriptions/usage-based/recording-usage-api),
151
+ [invoice previews](https://docs.stripe.com/api/invoices/create_preview), and
152
+ [full-precision invoice line quantities](https://docs.stripe.com/api/invoice-line-item/object).
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fantastic.dev/better-stripe",
3
- "version": "0.53.0",
3
+ "version": "0.55.0",
4
4
  "description": "A Convex component for Stripe V2 Accounts API integration.",
5
5
  "keywords": [
6
6
  "stripe",
@@ -102,7 +102,9 @@
102
102
  "docs/architecture.md",
103
103
  "docs/development.md",
104
104
  "docs/usage-ledger.md",
105
- "docs/usage-catalog.md"
105
+ "docs/usage-catalog.md",
106
+ "docs/usage-delivery.md",
107
+ "docs/usage-observations.md"
106
108
  ],
107
109
  "scripts": {
108
110
  "build": "tsc --project ./tsconfig.build.json && node scripts/check-public-exports.mjs",
@@ -1827,3 +1827,37 @@ export type {
1827
1827
  SubscriptionPaymentMethodOptions,
1828
1828
  SubscriptionPaymentMethodResult,
1829
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";
1846
+
1847
+ export type {
1848
+ UsageObservationOptions,
1849
+ UsageAggregateValue,
1850
+ UsageAggregateObservation,
1851
+ } from "./usage/observationTypes.js";
1852
+ export type {
1853
+ UsageLocalSummary,
1854
+ UsageLocalGroup,
1855
+ UsageCreditSummary,
1856
+ } from "./usage/summary.js";
1857
+ export type { UsageComparison } from "./usage/reconciliation.js";
1858
+ export type { UsageReconciliationOptions } from "./usage/observationClient.js";
1859
+
1860
+ export type {
1861
+ UsageInvoiceObservation,
1862
+ UsageInvoiceLine,
1863
+ } from "./usage/invoiceObservation.js";