@fantastic.dev/better-stripe 0.35.0 → 0.37.1

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 (94) hide show
  1. package/CHANGELOG.md +98 -0
  2. package/README.md +1 -1
  3. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts +178 -0
  4. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts.map +1 -1
  5. package/dist/client/connect/payoutExecutionTestHelpers.d.ts +89 -0
  6. package/dist/client/connect/payoutExecutionTestHelpers.d.ts.map +1 -1
  7. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts +178 -0
  8. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts.map +1 -1
  9. package/dist/client/connect/payoutSyncTestHelpers.d.ts +89 -0
  10. package/dist/client/connect/payoutSyncTestHelpers.d.ts.map +1 -1
  11. package/dist/client/operationEvidence.d.ts +37 -0
  12. package/dist/client/operationEvidence.d.ts.map +1 -0
  13. package/dist/client/operationEvidence.js +44 -0
  14. package/dist/client/operationEvidence.js.map +1 -0
  15. package/dist/client/publicTypes.d.ts +1 -0
  16. package/dist/client/publicTypes.d.ts.map +1 -1
  17. package/dist/client/readContracts.d.ts +2 -0
  18. package/dist/client/readContracts.d.ts.map +1 -1
  19. package/dist/client/readContracts.js +4 -0
  20. package/dist/client/readContracts.js.map +1 -1
  21. package/dist/component/_generated/component.d.ts +181 -0
  22. package/dist/component/_generated/component.d.ts.map +1 -1
  23. package/dist/component/earnings/pairedAdjustment.d.ts +12 -0
  24. package/dist/component/earnings/pairedAdjustment.d.ts.map +1 -0
  25. package/dist/component/earnings/pairedAdjustment.js +46 -0
  26. package/dist/component/earnings/pairedAdjustment.js.map +1 -0
  27. package/dist/component/earnings/triggers.d.ts +120 -0
  28. package/dist/component/earnings/triggers.d.ts.map +1 -1
  29. package/dist/component/earnings/triggers.js +10 -2
  30. package/dist/component/earnings/triggers.js.map +1 -1
  31. package/dist/component/operationEvidence/canonical.d.ts +4 -0
  32. package/dist/component/operationEvidence/canonical.d.ts.map +1 -0
  33. package/dist/component/operationEvidence/canonical.js +8 -0
  34. package/dist/component/operationEvidence/canonical.js.map +1 -0
  35. package/dist/component/operationEvidence/helpers.d.ts +87 -0
  36. package/dist/component/operationEvidence/helpers.d.ts.map +1 -0
  37. package/dist/component/operationEvidence/helpers.js +49 -0
  38. package/dist/component/operationEvidence/helpers.js.map +1 -0
  39. package/dist/component/operationEvidence/maintenance.d.ts +88 -0
  40. package/dist/component/operationEvidence/maintenance.d.ts.map +1 -0
  41. package/dist/component/operationEvidence/maintenance.js +59 -0
  42. package/dist/component/operationEvidence/maintenance.js.map +1 -0
  43. package/dist/component/operationEvidence/mutations.d.ts +97 -0
  44. package/dist/component/operationEvidence/mutations.d.ts.map +1 -0
  45. package/dist/component/operationEvidence/mutations.js +14 -0
  46. package/dist/component/operationEvidence/mutations.js.map +1 -0
  47. package/dist/component/operationEvidence/queries.d.ts +205 -0
  48. package/dist/component/operationEvidence/queries.d.ts.map +1 -0
  49. package/dist/component/operationEvidence/queries.js +75 -0
  50. package/dist/component/operationEvidence/queries.js.map +1 -0
  51. package/dist/component/operationEvidence/schema.d.ts +536 -0
  52. package/dist/component/operationEvidence/schema.d.ts.map +1 -0
  53. package/dist/component/operationEvidence/schema.js +53 -0
  54. package/dist/component/operationEvidence/schema.js.map +1 -0
  55. package/dist/component/payoutRelease/queries.d.ts +2 -2
  56. package/dist/component/payoutRelease/queries.d.ts.map +1 -1
  57. package/dist/component/refundHistory/commandEvidence.d.ts +1 -1
  58. package/dist/component/refundHistory/commandEvidence.d.ts.map +1 -1
  59. package/dist/component/refundHistory/commandEvidence.js +6 -2
  60. package/dist/component/refundHistory/commandEvidence.js.map +1 -1
  61. package/dist/component/refundHistory/originalSeller.d.ts +5 -0
  62. package/dist/component/refundHistory/originalSeller.d.ts.map +1 -0
  63. package/dist/component/refundHistory/originalSeller.js +35 -0
  64. package/dist/component/refundHistory/originalSeller.js.map +1 -0
  65. package/dist/component/refundHistory/queries.d.ts +1 -1
  66. package/dist/component/schema.d.ts +89 -0
  67. package/dist/component/schema.js +3 -0
  68. package/dist/component/schema.js.map +1 -1
  69. package/docs/financial-observations.md +85 -0
  70. package/docs/refund-command-evidence.md +6 -0
  71. package/package.json +1 -1
  72. package/src/client/operationEvidence.test.ts +110 -0
  73. package/src/client/operationEvidence.ts +92 -0
  74. package/src/client/publicTypes.ts +8 -0
  75. package/src/client/readContracts.ts +4 -0
  76. package/src/component/_generated/api.ts +10 -0
  77. package/src/component/_generated/component.ts +207 -0
  78. package/src/component/earnings/paired-adjustment.test.ts +258 -0
  79. package/src/component/earnings/pairedAdjustment.ts +77 -0
  80. package/src/component/earnings/triggers.ts +14 -10
  81. package/src/component/operationEvidence/canonical.ts +10 -0
  82. package/src/component/operationEvidence/helpers.ts +65 -0
  83. package/src/component/operationEvidence/integrity.test.ts +257 -0
  84. package/src/component/operationEvidence/maintenance.test.ts +152 -0
  85. package/src/component/operationEvidence/maintenance.ts +89 -0
  86. package/src/component/operationEvidence/mutations.ts +14 -0
  87. package/src/component/operationEvidence/queries.ts +108 -0
  88. package/src/component/operationEvidence/reads.test.ts +140 -0
  89. package/src/component/operationEvidence/schema.ts +62 -0
  90. package/src/component/refundHistory/commandEvidence.ts +7 -2
  91. package/src/component/refundHistory/original-seller-boundaries.test.ts +138 -0
  92. package/src/component/refundHistory/original-seller.test.ts +175 -0
  93. package/src/component/refundHistory/originalSeller.ts +48 -0
  94. package/src/component/schema.ts +6 -0
@@ -0,0 +1,257 @@
1
+ import { convexTest } from "convex-test";
2
+ import { makeFunctionReference } from "convex/server";
3
+ import { expect, it } from "vitest";
4
+ import { modules, schema } from "../../test.js";
5
+ import { canonicalFingerprint } from "./canonical.js";
6
+ import { captureSource } from "./maintenance.js";
7
+ import { operationEvidenceScope } from "./helpers.js";
8
+
9
+ const capture = makeFunctionReference<"mutation">(
10
+ "operationEvidence/mutations:capture",
11
+ );
12
+ const original = makeFunctionReference<"query">(
13
+ "operationEvidence/queries:original",
14
+ );
15
+ const latest = makeFunctionReference<"query">(
16
+ "operationEvidence/queries:latest",
17
+ );
18
+ const resolve = makeFunctionReference<"query">(
19
+ "operationEvidence/queries:resolve",
20
+ );
21
+
22
+ it("preserves special numeric representations, optional presence and array ordering", async () => {
23
+ const t = convexTest(schema, modules);
24
+ const fingerprints = new Set<string>();
25
+ for (const principal of [-0, 0, NaN, Infinity, -Infinity]) {
26
+ const sourceId = await t.run((ctx) =>
27
+ ctx.db.insert("transferReversalOps", {
28
+ operationId: "same",
29
+ sourceChargeId: "same",
30
+ slices: [],
31
+ commissionExposure: {
32
+ kind: "refund",
33
+ chargeAmount: 1,
34
+ principal,
35
+ finalized: false,
36
+ },
37
+ }),
38
+ );
39
+ const result = await t.mutation(capture, { sourceId });
40
+ fingerprints.add(result.header.originalFingerprint);
41
+ const saved = await t.query(original, { headerId: result.header._id });
42
+ expect(
43
+ Object.is(saved.payload.commissionExposure.principal, principal),
44
+ ).toBe(true);
45
+ }
46
+ expect(fingerprints.size).toBe(5);
47
+ expect(await canonicalFingerprint({ nested: { a: -0, b: [1, 2] } })).toBe(
48
+ await canonicalFingerprint({ nested: { b: [1, 2], a: -0 } }),
49
+ );
50
+ expect(await canonicalFingerprint({ a: [1, 2] })).not.toBe(
51
+ await canonicalFingerprint({ a: [2, 1] }),
52
+ );
53
+ expect(await canonicalFingerprint({ a: {} })).not.toBe(
54
+ await canonicalFingerprint({ a: { optional: null } }),
55
+ );
56
+ });
57
+
58
+ it("holds original identity and bytes while retaining actual contradictory latest data", async () => {
59
+ const t = convexTest(schema, modules);
60
+ const slices = [
61
+ { stripeTransferId: "first", from: 0, to: 1 },
62
+ { stripeTransferId: "second", from: 2, to: 3 },
63
+ ];
64
+ const sourceId = await t.run((ctx) =>
65
+ ctx.db.insert("transferReversalOps", {
66
+ operationId: "original",
67
+ sourceChargeId: "charge",
68
+ slices,
69
+ }),
70
+ );
71
+ const first = await t.mutation(capture, { sourceId });
72
+ await t.run((ctx) =>
73
+ ctx.db.patch("transferReversalOps", sourceId, {
74
+ operationId: "replacement",
75
+ slices: [...slices].reverse(),
76
+ }),
77
+ );
78
+ const next = await t.mutation(capture, { sourceId });
79
+ expect(next).toMatchObject({
80
+ status: "updated",
81
+ evidenceGeneration: 2,
82
+ header: {
83
+ isContradictory: true,
84
+ originalPayloadId: first.header.originalPayloadId,
85
+ operationDigest: first.header.operationDigest,
86
+ },
87
+ });
88
+ expect(
89
+ (await t.query(original, { headerId: first.header._id })).payload,
90
+ ).toMatchObject({ operationId: "original", slices });
91
+ expect(
92
+ (await t.query(latest, { headerId: first.header._id })).payload,
93
+ ).toMatchObject({
94
+ operationId: "replacement",
95
+ slices: [...slices].reverse(),
96
+ });
97
+ expect(
98
+ (await t.query(resolve, { selector: "operationId", value: "original" }))
99
+ .header,
100
+ ).toBeNull();
101
+ await t.run((ctx) =>
102
+ ctx.db.patch("transferReversalOps", sourceId, {
103
+ operationId: "original",
104
+ slices,
105
+ }),
106
+ );
107
+ expect((await t.mutation(capture, { sourceId })).header.isContradictory).toBe(
108
+ true,
109
+ );
110
+ });
111
+
112
+ it("rolls back every evidence write when the transaction aborts after capture", async () => {
113
+ const t = convexTest(schema, modules);
114
+ const sourceId = await t.run((ctx) =>
115
+ ctx.db.insert("transferReversalOps", {
116
+ operationId: "source",
117
+ sourceChargeId: "charge",
118
+ slices: [],
119
+ }),
120
+ );
121
+ const before = await t.run((ctx) =>
122
+ ctx.db.get("transferReversalOps", sourceId),
123
+ );
124
+ await expect(
125
+ t.run(async (ctx) => {
126
+ await captureSource(ctx, sourceId);
127
+ throw new Error("test-only transaction abort");
128
+ }),
129
+ ).rejects.toThrow("test-only transaction abort");
130
+ expect(
131
+ await t.run((ctx) => ctx.db.query("operationEvidenceHeaders").take(2)),
132
+ ).toEqual([]);
133
+ expect(
134
+ await t.run((ctx) => ctx.db.query("operationEvidencePayloads").take(3)),
135
+ ).toEqual([]);
136
+ expect(
137
+ await t.run((ctx) =>
138
+ ctx.db
139
+ .query("financialObservationGenerations")
140
+ .withIndex("by_scope_key", (q) =>
141
+ q.eq("scopeKey", operationEvidenceScope),
142
+ )
143
+ .take(2),
144
+ ),
145
+ ).toEqual([]);
146
+ expect(
147
+ await t.run((ctx) => ctx.db.get("transferReversalOps", sourceId)),
148
+ ).toEqual(before);
149
+ });
150
+
151
+ it("does not repair missing latest data or overwrite original data after an abort", async () => {
152
+ const t = convexTest(schema, modules);
153
+ const sourceId = await t.run((ctx) =>
154
+ ctx.db.insert("transferReversalOps", {
155
+ operationId: "source",
156
+ sourceChargeId: "charge",
157
+ slices: [],
158
+ }),
159
+ );
160
+ const saved = await t.mutation(capture, { sourceId });
161
+ await t.run(async (ctx) => {
162
+ await ctx.db.delete(
163
+ "operationEvidencePayloads",
164
+ saved.header.latestPayloadId,
165
+ );
166
+ await ctx.db.patch("transferReversalOps", sourceId, {
167
+ commissionExposure: {
168
+ kind: "refund",
169
+ chargeAmount: 1,
170
+ principal: 1,
171
+ finalized: true,
172
+ },
173
+ });
174
+ });
175
+ const before = await t.run((ctx) =>
176
+ ctx.db.get("transferReversalOps", sourceId),
177
+ );
178
+ await expect(t.mutation(capture, { sourceId })).rejects.toThrow();
179
+ expect(
180
+ await t.run((ctx) => ctx.db.get("transferReversalOps", sourceId)),
181
+ ).toEqual(before);
182
+ const result = await t.query(original, { headerId: saved.header._id });
183
+ expect(result).toMatchObject({
184
+ evidenceGeneration: 1,
185
+ header: { generation: 1 },
186
+ payload: { operationId: "source" },
187
+ });
188
+ expect(result.payload).not.toHaveProperty("commissionExposure");
189
+ });
190
+
191
+ it("serializes concurrent matching maintenance without duplicating source evidence", async () => {
192
+ const t = convexTest(schema, modules);
193
+ const sourceId = await t.run((ctx) =>
194
+ ctx.db.insert("transferReversalOps", {
195
+ operationId: "source",
196
+ sourceChargeId: "charge",
197
+ slices: [],
198
+ }),
199
+ );
200
+ const results = await Promise.all(
201
+ Array.from({ length: 3 }, () => t.mutation(capture, { sourceId })),
202
+ );
203
+ expect(new Set(results.map((result) => result.header._id)).size).toBe(1);
204
+ expect(results.filter((result) => result.status === "captured")).toHaveLength(
205
+ 1,
206
+ );
207
+ expect(
208
+ await t.run((ctx) => ctx.db.query("operationEvidencePayloads").take(4)),
209
+ ).toHaveLength(2);
210
+ expect(results.every((result) => result.evidenceGeneration === 1)).toBe(true);
211
+ });
212
+
213
+ it("rejects ambiguous headers and unavailable generations before any maintenance writes", async () => {
214
+ const t = convexTest(schema, modules);
215
+ const sourceId = await t.run((ctx) =>
216
+ ctx.db.insert("transferReversalOps", {
217
+ operationId: "source",
218
+ sourceChargeId: "charge",
219
+ slices: [],
220
+ }),
221
+ );
222
+ const first = await t.mutation(capture, { sourceId });
223
+ await t.run(async (ctx) => {
224
+ const { _id, _creationTime, ...fields } = first.header;
225
+ void _id;
226
+ void _creationTime;
227
+ await ctx.db.insert("operationEvidenceHeaders", fields);
228
+ });
229
+ expect(await t.mutation(capture, { sourceId })).toMatchObject({
230
+ status: "unavailable",
231
+ header: null,
232
+ });
233
+ const other = await t.run((ctx) =>
234
+ ctx.db.insert("transferReversalOps", {
235
+ operationId: "other",
236
+ sourceChargeId: "other",
237
+ slices: [],
238
+ }),
239
+ );
240
+ await t.run(async (ctx) => {
241
+ const counter = await ctx.db
242
+ .query("financialObservationGenerations")
243
+ .withIndex("by_scope_key", (q) =>
244
+ q.eq("scopeKey", operationEvidenceScope),
245
+ )
246
+ .take(2);
247
+ await ctx.db.patch("financialObservationGenerations", counter[0]!._id, {
248
+ generation: Number.MAX_SAFE_INTEGER,
249
+ });
250
+ });
251
+ await expect(t.mutation(capture, { sourceId: other })).rejects.toThrow(
252
+ "Operation evidence generation unavailable",
253
+ );
254
+ expect(
255
+ await t.run((ctx) => ctx.db.query("operationEvidencePayloads").take(3)),
256
+ ).toHaveLength(2);
257
+ });
@@ -0,0 +1,152 @@
1
+ import { convexTest } from "convex-test";
2
+ import { makeFunctionReference } from "convex/server";
3
+ import { expect, it } from "vitest";
4
+ import { modules, schema } from "../../test.js";
5
+
6
+ const capture = makeFunctionReference<"mutation">(
7
+ "operationEvidence/mutations:capture",
8
+ );
9
+ const original = makeFunctionReference<"query">(
10
+ "operationEvidence/queries:original",
11
+ );
12
+ const latest = makeFunctionReference<"query">(
13
+ "operationEvidence/queries:latest",
14
+ );
15
+ const claim = makeFunctionReference<"mutation">(
16
+ "connect/mutations:claimReversalSlices",
17
+ );
18
+ const release = makeFunctionReference<"mutation">(
19
+ "connect/mutations:releaseReversalClaim",
20
+ );
21
+
22
+ it("captures actual source bytes, stable replay and changed exposure without financial writes", async () => {
23
+ const t = convexTest(schema, modules);
24
+ const exposure = {
25
+ kind: "refund" as const,
26
+ chargeAmount: 100,
27
+ principal: 1,
28
+ finalized: false,
29
+ refundedPrincipal: 1,
30
+ refundId: "opaque_refund",
31
+ };
32
+ const args = {
33
+ operationId: "operation",
34
+ sourceChargeId: "charge",
35
+ mode: { kind: "full" as const },
36
+ commissionExposure: exposure,
37
+ };
38
+ await t.mutation(claim, args);
39
+ const source = await t.run((ctx) =>
40
+ ctx.db
41
+ .query("transferReversalOps")
42
+ .take(2)
43
+ .then((rows) => rows[0]!),
44
+ );
45
+ const first = await t.mutation(capture, { sourceId: source._id });
46
+ expect(first).toMatchObject({
47
+ coverage: "unknown",
48
+ status: "captured",
49
+ evidenceGeneration: 1,
50
+ header: {
51
+ generation: 1,
52
+ sourceId: source._id,
53
+ producer: "trusted_host_maintenance",
54
+ producerVersion: 1,
55
+ },
56
+ });
57
+ const unchanged = await t.mutation(capture, { sourceId: source._id });
58
+ expect(unchanged).toEqual({ ...first, status: "unchanged" });
59
+ const firstOriginal = await t.query(original, { headerId: first.header._id });
60
+ expect(firstOriginal.payload.commissionExposure).toEqual(exposure);
61
+ expect(firstOriginal.payload.slices).toEqual([]);
62
+ expect(Object.keys(firstOriginal.payload).sort()).toEqual(
63
+ [
64
+ "_creationTime",
65
+ "_id",
66
+ "operationId",
67
+ "sourceChargeId",
68
+ "slices",
69
+ "commissionExposure",
70
+ ].sort(),
71
+ );
72
+ expect(
73
+ await t.run((ctx) => ctx.db.get("transferReversalOps", source._id)),
74
+ ).toEqual(source);
75
+ await t.mutation(claim, {
76
+ ...args,
77
+ commissionExposure: { ...exposure, finalized: true, refundedPrincipal: 2 },
78
+ });
79
+ const changedSource = await t.run((ctx) =>
80
+ ctx.db.get("transferReversalOps", source._id),
81
+ );
82
+ // Raw financial writers are deliberately not evidence producers in this slice.
83
+ expect(await t.query(latest, { headerId: first.header._id })).toMatchObject({
84
+ evidenceGeneration: 1,
85
+ payload: { commissionExposure: { finalized: false, refundedPrincipal: 1 } },
86
+ });
87
+ const changed = await t.mutation(capture, { sourceId: source._id });
88
+ expect(changed).toMatchObject({
89
+ coverage: "unknown",
90
+ status: "updated",
91
+ evidenceGeneration: 2,
92
+ header: {
93
+ generation: 2,
94
+ originalPayloadId: first.header.originalPayloadId,
95
+ latestPayloadId: first.header.latestPayloadId,
96
+ firstObservedAt: first.header.firstObservedAt,
97
+ },
98
+ });
99
+ expect(
100
+ (await t.query(original, { headerId: first.header._id })).payload,
101
+ ).toEqual(firstOriginal.payload);
102
+ expect(
103
+ (await t.query(latest, { headerId: first.header._id })).payload
104
+ .commissionExposure,
105
+ ).toMatchObject({
106
+ finalized: true,
107
+ refundedPrincipal: 2,
108
+ refundId: "opaque_refund",
109
+ });
110
+ expect(
111
+ await t.run((ctx) => ctx.db.get("transferReversalOps", source._id)),
112
+ ).toEqual(changedSource);
113
+ await t.mutation(release, { operationId: "operation", verified: [] });
114
+ expect(
115
+ await t.run((ctx) => ctx.db.get("transferReversalOps", source._id)),
116
+ ).toBeNull();
117
+ expect(
118
+ (await t.query(latest, { headerId: first.header._id })).evidenceGeneration,
119
+ ).toBe(2);
120
+ expect(
121
+ (await t.query(original, { headerId: first.header._id })).payload
122
+ .commissionExposure,
123
+ ).toEqual(exposure);
124
+ expect(
125
+ (await t.query(latest, { headerId: first.header._id })).payload
126
+ .commissionExposure.finalized,
127
+ ).toBe(true);
128
+ expect(await t.mutation(capture, { sourceId: source._id })).toMatchObject({
129
+ status: "source_unavailable",
130
+ evidenceGeneration: 2,
131
+ header: changed.header,
132
+ });
133
+ });
134
+
135
+ it("keeps a source deleted before first observation unknown without inventing evidence", async () => {
136
+ const t = convexTest(schema, modules);
137
+ const sourceId = await t.run(async (ctx) => {
138
+ const id = await ctx.db.insert("transferReversalOps", {
139
+ operationId: "gone",
140
+ sourceChargeId: "charge",
141
+ slices: [],
142
+ });
143
+ await ctx.db.delete("transferReversalOps", id);
144
+ return id;
145
+ });
146
+ expect(await t.mutation(capture, { sourceId })).toMatchObject({
147
+ coverage: "unknown",
148
+ status: "source_unavailable",
149
+ evidenceGeneration: 0,
150
+ header: null,
151
+ });
152
+ });
@@ -0,0 +1,89 @@
1
+ import type { Id } from "../_generated/dataModel.js";
2
+ import type { MutationCtx } from "../_generated/server.js";
3
+ import {
4
+ advanceObservationGeneration,
5
+ observationGeneration,
6
+ } from "../financialObservations/generations.js";
7
+ import {
8
+ bodyOf,
9
+ identityFingerprint,
10
+ operationEvidenceScope,
11
+ selectorDigest,
12
+ sourceFingerprint,
13
+ uniqueSourceHeader,
14
+ } from "./helpers.js";
15
+
16
+ /** Explicit evidence maintenance only. Never called from a financial writer here. */
17
+ export async function captureSource(
18
+ ctx: MutationCtx,
19
+ sourceId: Id<"transferReversalOps">,
20
+ ) {
21
+ const { headers, header } = await uniqueSourceHeader(ctx, sourceId);
22
+ if (headers.length > 1 || (headers.length === 1 && !header))
23
+ return { status: "unavailable" as const, header: null };
24
+ const source = await ctx.db.get("transferReversalOps", sourceId);
25
+ if (!source) return { status: "source_unavailable" as const, header };
26
+ const body = bodyOf(source);
27
+ const fingerprint = await sourceFingerprint(body);
28
+ if (header?.latestFingerprint === fingerprint)
29
+ return { status: "unchanged" as const, header };
30
+ const generation = await observationGeneration(ctx, operationEvidenceScope);
31
+ if (
32
+ generation === null ||
33
+ generation >= Number.MAX_SAFE_INTEGER ||
34
+ (header && header.generation >= Number.MAX_SAFE_INTEGER)
35
+ )
36
+ throw new Error("Operation evidence generation unavailable");
37
+ const identity = await identityFingerprint(body);
38
+ if (header) {
39
+ await ctx.db.replace(
40
+ "operationEvidencePayloads",
41
+ header.latestPayloadId,
42
+ body,
43
+ );
44
+ await ctx.db.patch("operationEvidenceHeaders", header._id, {
45
+ latestFingerprint: fingerprint,
46
+ generation: header.generation + 1,
47
+ isContradictory:
48
+ header.isContradictory ||
49
+ header.originalIdentityFingerprint !== identity,
50
+ });
51
+ await advanceObservationGeneration(ctx, operationEvidenceScope);
52
+ return {
53
+ status: "updated" as const,
54
+ header: (await ctx.db.get("operationEvidenceHeaders", header._id))!,
55
+ };
56
+ }
57
+ const originalPayloadId = await ctx.db.insert(
58
+ "operationEvidencePayloads",
59
+ body,
60
+ );
61
+ const latestPayloadId = await ctx.db.insert(
62
+ "operationEvidencePayloads",
63
+ body,
64
+ );
65
+ const id = await ctx.db.insert("operationEvidenceHeaders", {
66
+ sourceId,
67
+ originalPayloadId,
68
+ latestPayloadId,
69
+ producer: "trusted_host_maintenance",
70
+ producerVersion: 1,
71
+ firstObservedAt: Date.now(),
72
+ sourceCreatedAt: source._creationTime,
73
+ originalFingerprint: fingerprint,
74
+ latestFingerprint: fingerprint,
75
+ originalIdentityFingerprint: identity,
76
+ operationDigest: await selectorDigest("operationId", body.operationId),
77
+ sourceChargeDigest: await selectorDigest(
78
+ "sourceChargeId",
79
+ body.sourceChargeId,
80
+ ),
81
+ generation: 1,
82
+ isContradictory: false,
83
+ });
84
+ await advanceObservationGeneration(ctx, operationEvidenceScope);
85
+ return {
86
+ status: "captured" as const,
87
+ header: (await ctx.db.get("operationEvidenceHeaders", id))!,
88
+ };
89
+ }
@@ -0,0 +1,14 @@
1
+ import { v } from "convex/values";
2
+ import { mutation } from "../_generated/server.js";
3
+ import { readState } from "./helpers.js";
4
+ import { captureSource } from "./maintenance.js";
5
+ import { captureResult } from "./schema.js";
6
+
7
+ export const capture = mutation({
8
+ args: { sourceId: v.id("transferReversalOps") },
9
+ returns: captureResult,
10
+ handler: async (ctx, args) => ({
11
+ ...(await captureSource(ctx, args.sourceId)),
12
+ ...(await readState(ctx)),
13
+ }),
14
+ });
@@ -0,0 +1,108 @@
1
+ import {
2
+ paginationOptsValidator,
3
+ paginationResultValidator,
4
+ } from "convex/server";
5
+ import { v } from "convex/values";
6
+ import { paginator } from "convex-helpers/server/pagination";
7
+ import schema from "../schema.js";
8
+ import { query, type QueryCtx } from "../_generated/server.js";
9
+ import type { Id } from "../_generated/dataModel.js";
10
+ import {
11
+ bodyOf,
12
+ isValidHeader,
13
+ readState,
14
+ selectorDigest,
15
+ sourceFingerprint,
16
+ } from "./helpers.js";
17
+ import {
18
+ headerDoc,
19
+ headerResult,
20
+ payloadResult,
21
+ readFields,
22
+ selectorValidator,
23
+ } from "./schema.js";
24
+
25
+ async function hydrate(
26
+ ctx: QueryCtx,
27
+ headerId: Id<"operationEvidenceHeaders">,
28
+ kind: "original" | "latest",
29
+ ) {
30
+ const header = await ctx.db.get("operationEvidenceHeaders", headerId);
31
+ if (!header || !isValidHeader(header))
32
+ return { header: null, payload: null, ...(await readState(ctx)) };
33
+ const id =
34
+ kind === "original" ? header.originalPayloadId : header.latestPayloadId;
35
+ const expected =
36
+ kind === "original" ? header.originalFingerprint : header.latestFingerprint;
37
+ const payload = await ctx.db.get("operationEvidencePayloads", id);
38
+ if (!payload || (await sourceFingerprint(bodyOf(payload))) !== expected)
39
+ return { header, payload: null, ...(await readState(ctx)) };
40
+ return { header, payload, ...(await readState(ctx)) };
41
+ }
42
+ export const original = query({
43
+ args: { headerId: v.id("operationEvidenceHeaders") },
44
+ returns: payloadResult,
45
+ handler: (ctx, args) => hydrate(ctx, args.headerId, "original"),
46
+ });
47
+ export const latest = query({
48
+ args: { headerId: v.id("operationEvidenceHeaders") },
49
+ returns: payloadResult,
50
+ handler: (ctx, args) => hydrate(ctx, args.headerId, "latest"),
51
+ });
52
+
53
+ export const headers = query({
54
+ args: { paginationOpts: paginationOptsValidator },
55
+ returns: v.object({
56
+ ...paginationResultValidator(headerDoc).fields,
57
+ ...readFields,
58
+ }),
59
+ handler: async (ctx, args) => {
60
+ const count = args.paginationOpts.numItems;
61
+ if (!Number.isInteger(count) || count < 1 || count > 100)
62
+ throw new Error("Invalid operation evidence page size");
63
+ const page = await paginator(ctx.db, schema)
64
+ .query("operationEvidenceHeaders")
65
+ .order("desc")
66
+ .paginate({
67
+ ...args.paginationOpts,
68
+ maximumRowsRead: 200,
69
+ maximumBytesRead: 262144,
70
+ });
71
+ return { ...page, ...(await readState(ctx)) };
72
+ },
73
+ });
74
+
75
+ export const resolve = query({
76
+ args: { selector: selectorValidator, value: v.string() },
77
+ returns: headerResult,
78
+ handler: async (ctx, args) => {
79
+ const digest = await selectorDigest(args.selector, args.value);
80
+ const rows =
81
+ args.selector === "operationId"
82
+ ? await ctx.db
83
+ .query("operationEvidenceHeaders")
84
+ .withIndex("by_operation_digest", (q) =>
85
+ q.eq("operationDigest", digest),
86
+ )
87
+ .take(2)
88
+ : await ctx.db
89
+ .query("operationEvidenceHeaders")
90
+ .withIndex("by_source_charge_digest", (q) =>
91
+ q.eq("sourceChargeDigest", digest),
92
+ )
93
+ .take(2);
94
+ const candidate = rows.length === 1 ? rows[0]! : null;
95
+ if (!candidate || !isValidHeader(candidate) || candidate.isContradictory)
96
+ return { header: null, ...(await readState(ctx)) };
97
+ const original = await ctx.db.get(
98
+ "operationEvidencePayloads",
99
+ candidate.originalPayloadId,
100
+ );
101
+ const matches =
102
+ original &&
103
+ original[args.selector] === args.value &&
104
+ (await sourceFingerprint(bodyOf(original))) ===
105
+ candidate.originalFingerprint;
106
+ return { header: matches ? candidate : null, ...(await readState(ctx)) };
107
+ },
108
+ });