@bachsproof/cli 0.0.0-stage → 2.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +27 -2
- package/dist/cli.d.ts +3 -0
- package/dist/cli.js +370 -0
- package/dist/cli.js.map +1 -0
- package/dist/index.d.ts +54 -0
- package/dist/index.js +227 -0
- package/dist/index.js.map +1 -0
- package/package.json +56 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 BachsProof contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,28 @@
|
|
|
1
|
-
#
|
|
1
|
+
# `@bachsproof/cli`
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The CLI is the supported BachsProof v2 entry point.
|
|
4
|
+
|
|
5
|
+
```bash
|
|
6
|
+
pnpm add -D @bachsproof/cli
|
|
7
|
+
pnpm exec bachsproof init
|
|
8
|
+
pnpm exec bachsproof test
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
`init` creates one `bachsproof.config.mjs` file. The file contains the complete
|
|
12
|
+
webhook URL, test signing secret, amount, currency, `createPayment()`, and
|
|
13
|
+
`verify()` callbacks. The CLI configures the Bachs adapter, webhook signing,
|
|
14
|
+
the eleven scenarios, ordinary concurrent delivery, and mandatory financial
|
|
15
|
+
verification automatically.
|
|
16
|
+
|
|
17
|
+
The same config object works in Vitest, Jest, or a custom script:
|
|
18
|
+
|
|
19
|
+
```js
|
|
20
|
+
import { loadConfig, runConfig, summarizeRuns } from "@bachsproof/cli";
|
|
21
|
+
|
|
22
|
+
const config = await loadConfig("bachsproof.config.mjs");
|
|
23
|
+
const results = await runConfig(config);
|
|
24
|
+
console.log(summarizeRuns(results));
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
Financial verification is required. Configure a test-only application and
|
|
28
|
+
database; BachsProof never calls Bachs or moves real money.
|
package/dist/cli.d.ts
ADDED
package/dist/cli.js
ADDED
|
@@ -0,0 +1,370 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { writeFile, access } from 'fs/promises';
|
|
3
|
+
import { constants } from 'fs';
|
|
4
|
+
import { join, resolve } from 'path';
|
|
5
|
+
import { createJiti } from 'jiti';
|
|
6
|
+
import { BachsProof, SUPPORTED_SCENARIOS } from '@bachsproof/core';
|
|
7
|
+
import { bachsAdapter, signBachsWebhook } from '@bachsproof/bachs';
|
|
8
|
+
|
|
9
|
+
var configTemplate = `/**
|
|
10
|
+
* BachsProof v2 configuration.
|
|
11
|
+
*
|
|
12
|
+
* Use only an isolated application, test database, queue, and webhook secret.
|
|
13
|
+
* BachsProof creates local simulated events. It never calls Bachs or moves money.
|
|
14
|
+
*/
|
|
15
|
+
import { defineConfig } from "@bachsproof/cli";
|
|
16
|
+
|
|
17
|
+
export default defineConfig({
|
|
18
|
+
// The complete URL of your isolated application's Bachs webhook route.
|
|
19
|
+
webhookUrl: process.env.BACHSPROOF_WEBHOOK_URL ?? "http://127.0.0.1:3000/webhooks/bachs",
|
|
20
|
+
|
|
21
|
+
// Use a secret that belongs only to your test application.
|
|
22
|
+
secret: process.env.BACHS_WEBHOOK_SECRET ?? "",
|
|
23
|
+
|
|
24
|
+
// 500,000 NGN minor units means NGN 5,000.00.
|
|
25
|
+
amountMinor: 500_000,
|
|
26
|
+
currency: "NGN",
|
|
27
|
+
|
|
28
|
+
// Before BachsProof sends a webhook, create a fresh payment record and
|
|
29
|
+
// return its reference. Replace the example error with your test helper.
|
|
30
|
+
async createPayment({ scenario, amountMinor, currency, paymentIndex, paymentCount }) {
|
|
31
|
+
throw new Error(
|
|
32
|
+
"Implement createPayment in bachsproof.config.mjs. " +
|
|
33
|
+
"Create an isolated test payment and return its non-empty reference for " +
|
|
34
|
+
scenario + " (" + (paymentIndex + 1) + " of " + paymentCount + ")."
|
|
35
|
+
);
|
|
36
|
+
// Example:
|
|
37
|
+
// const payment = await testApplication.createPayment({ amountMinor, currency });
|
|
38
|
+
// return payment.reference;
|
|
39
|
+
},
|
|
40
|
+
|
|
41
|
+
// Read the application's committed payment and ledger records. Do not return
|
|
42
|
+
// the expected values from this file; return what the database contains.
|
|
43
|
+
async verify(reference) {
|
|
44
|
+
throw new Error(
|
|
45
|
+
"Implement verify in bachsproof.config.mjs by reading committed " +
|
|
46
|
+
"financial records for " + reference + "."
|
|
47
|
+
);
|
|
48
|
+
// Example result:
|
|
49
|
+
// return {
|
|
50
|
+
// reference,
|
|
51
|
+
// creditCount: credits.length,
|
|
52
|
+
// creditedAmountMinor: credits.reduce((sum, credit) => sum + credit.amountMinor, 0),
|
|
53
|
+
// currency: payment.currency,
|
|
54
|
+
// status: payment.status,
|
|
55
|
+
// pending: false,
|
|
56
|
+
// ledgerEntries: credits.map((credit) => ({
|
|
57
|
+
// id: String(credit.id),
|
|
58
|
+
// type: String(credit.type),
|
|
59
|
+
// amountMinor: credit.amountMinor,
|
|
60
|
+
// currency: credit.currency
|
|
61
|
+
// }))
|
|
62
|
+
// };
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
// Optional: run only selected scenario identifiers. Omit to run all eleven.
|
|
66
|
+
// scenarios: ["sequential-duplicate-webhook"],
|
|
67
|
+
|
|
68
|
+
// Optional: increase this only when your isolated application processes
|
|
69
|
+
// webhooks asynchronously. The default is 10 seconds.
|
|
70
|
+
// verificationTimeoutMs: 10_000
|
|
71
|
+
});
|
|
72
|
+
`;
|
|
73
|
+
async function exists(path) {
|
|
74
|
+
try {
|
|
75
|
+
await access(path, constants.F_OK);
|
|
76
|
+
return true;
|
|
77
|
+
} catch {
|
|
78
|
+
return false;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
async function initProject(directory = process.cwd(), force = false) {
|
|
82
|
+
const configPath = join(resolve(directory), "bachsproof.config.mjs");
|
|
83
|
+
if (!force && await exists(configPath)) {
|
|
84
|
+
throw new Error(`Refusing to overwrite existing BachsProof file: ${configPath}. Use --force only when replacement is intentional.`);
|
|
85
|
+
}
|
|
86
|
+
await writeFile(configPath, configTemplate, "utf8");
|
|
87
|
+
return [configPath];
|
|
88
|
+
}
|
|
89
|
+
var SCENARIO_LABELS = {
|
|
90
|
+
"sequential-duplicate-webhook": "Sequential duplicate webhook",
|
|
91
|
+
"concurrent-duplicate-credit": "Concurrent duplicate credit",
|
|
92
|
+
"concurrent-unique-payments": "Concurrent unique payments",
|
|
93
|
+
"cross-event-duplicate-payment": "Cross-event duplicate payment",
|
|
94
|
+
"out-of-order-events": "Out-of-order events",
|
|
95
|
+
"incomplete-checkout": "Incomplete checkout",
|
|
96
|
+
"expired-checkout": "Expired checkout",
|
|
97
|
+
"incorrect-payment-amount": "Incorrect payment amount",
|
|
98
|
+
"incorrect-payment-currency": "Incorrect payment currency",
|
|
99
|
+
"underpaid-payment": "Underpaid payment",
|
|
100
|
+
"failed-payment": "Failed payment"
|
|
101
|
+
};
|
|
102
|
+
function scenarioLabel(scenario) {
|
|
103
|
+
return SCENARIO_LABELS[scenario];
|
|
104
|
+
}
|
|
105
|
+
function assertConfig(value) {
|
|
106
|
+
if (!value || typeof value !== "object") throw new Error("BachsProof config must export a default object");
|
|
107
|
+
const config = value;
|
|
108
|
+
if (typeof config.webhookUrl !== "string" || config.webhookUrl.trim().length === 0) {
|
|
109
|
+
throw new Error("BachsProof config requires a complete webhookUrl");
|
|
110
|
+
}
|
|
111
|
+
try {
|
|
112
|
+
const url = new URL(config.webhookUrl);
|
|
113
|
+
if (url.protocol !== "http:" && url.protocol !== "https:") throw new Error("webhookUrl must use http or https");
|
|
114
|
+
} catch (error) {
|
|
115
|
+
throw new Error(`BachsProof config webhookUrl is invalid: ${error instanceof Error ? error.message : String(error)}`);
|
|
116
|
+
}
|
|
117
|
+
if (typeof config.secret !== "string" || config.secret.trim().length === 0) {
|
|
118
|
+
throw new Error("BachsProof config requires a non-empty test webhook secret");
|
|
119
|
+
}
|
|
120
|
+
if (!Number.isSafeInteger(config.amountMinor) || config.amountMinor < 0) {
|
|
121
|
+
throw new Error("BachsProof config amountMinor must be a non-negative safe integer");
|
|
122
|
+
}
|
|
123
|
+
if (typeof config.currency !== "string" || !/^[A-Z]{3}$/.test(config.currency)) {
|
|
124
|
+
throw new Error("BachsProof config currency must be a three-letter ISO currency code");
|
|
125
|
+
}
|
|
126
|
+
if (typeof config.createPayment !== "function") throw new Error("BachsProof config requires a createPayment callback");
|
|
127
|
+
if (typeof config.verify !== "function") throw new Error("BachsProof config requires a verify callback");
|
|
128
|
+
if (config.verificationTimeoutMs !== void 0 && (!Number.isSafeInteger(config.verificationTimeoutMs) || config.verificationTimeoutMs < 1)) {
|
|
129
|
+
throw new Error("BachsProof config verificationTimeoutMs must be a positive safe integer");
|
|
130
|
+
}
|
|
131
|
+
if (config.scenarios !== void 0) {
|
|
132
|
+
if (!Array.isArray(config.scenarios) || config.scenarios.length === 0) throw new Error("BachsProof config scenarios must contain at least one scenario");
|
|
133
|
+
for (const scenario of config.scenarios) {
|
|
134
|
+
if (!SUPPORTED_SCENARIOS.includes(scenario)) {
|
|
135
|
+
throw new Error(`Unknown BachsProof scenario: ${String(scenario)}`);
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
async function loadConfig(configPath = "bachsproof.config.mjs") {
|
|
141
|
+
const absolutePath = resolve(process.cwd(), configPath);
|
|
142
|
+
const jiti = createJiti(absolutePath, { interopDefault: true });
|
|
143
|
+
const loaded = await jiti.import(absolutePath, { default: true });
|
|
144
|
+
assertConfig(loaded);
|
|
145
|
+
return loaded;
|
|
146
|
+
}
|
|
147
|
+
function withBachsSigning(provider, secret) {
|
|
148
|
+
return {
|
|
149
|
+
...provider,
|
|
150
|
+
headers(event) {
|
|
151
|
+
const body = provider.serialize(event);
|
|
152
|
+
return {
|
|
153
|
+
...provider.headers?.(event) ?? {},
|
|
154
|
+
...signBachsWebhook(body, secret)
|
|
155
|
+
};
|
|
156
|
+
},
|
|
157
|
+
headersForBody(event, body) {
|
|
158
|
+
return {
|
|
159
|
+
...provider.headersForBody?.(event, body) ?? provider.headers?.(event) ?? {},
|
|
160
|
+
...signBachsWebhook(body, secret)
|
|
161
|
+
};
|
|
162
|
+
}
|
|
163
|
+
};
|
|
164
|
+
}
|
|
165
|
+
function selectedScenarios(config, testName) {
|
|
166
|
+
const scenarios = config.scenarios ?? [...SUPPORTED_SCENARIOS];
|
|
167
|
+
if (!testName) return scenarios;
|
|
168
|
+
const selected = scenarios.find((scenario) => scenarioLabel(scenario) === testName || scenario === testName);
|
|
169
|
+
if (!selected) throw new Error(`Unknown BachsProof scenario or test name "${testName}". Use one of: ${scenarios.map(scenarioLabel).join(", ")}`);
|
|
170
|
+
return [selected];
|
|
171
|
+
}
|
|
172
|
+
async function runConfig(config, options = {}) {
|
|
173
|
+
assertConfig(config);
|
|
174
|
+
const scenarios = selectedScenarios(config, options.testName);
|
|
175
|
+
const provider = withBachsSigning(bachsAdapter({ mode: "mock" }), config.secret);
|
|
176
|
+
const usedReferences = /* @__PURE__ */ new Set();
|
|
177
|
+
const createPayment = async (context) => {
|
|
178
|
+
const reference = await config.createPayment(context);
|
|
179
|
+
if (typeof reference !== "string" || reference.trim().length === 0) return reference;
|
|
180
|
+
const normalized = reference.trim();
|
|
181
|
+
if (usedReferences.has(normalized)) {
|
|
182
|
+
throw new Error(`createPayment returned reference ${normalized}, which was already used by another selected scenario`);
|
|
183
|
+
}
|
|
184
|
+
usedReferences.add(normalized);
|
|
185
|
+
return normalized;
|
|
186
|
+
};
|
|
187
|
+
const runner = new BachsProof({
|
|
188
|
+
provider,
|
|
189
|
+
webhookUrl: config.webhookUrl,
|
|
190
|
+
createPayment,
|
|
191
|
+
verify: config.verify,
|
|
192
|
+
financialVerification: config.verificationTimeoutMs === void 0 ? void 0 : { completionDeadlineMs: config.verificationTimeoutMs }
|
|
193
|
+
});
|
|
194
|
+
const results = [];
|
|
195
|
+
for (const scenario of scenarios) {
|
|
196
|
+
const result = await runner.run({
|
|
197
|
+
scenario,
|
|
198
|
+
amountMinor: config.amountMinor,
|
|
199
|
+
currency: config.currency
|
|
200
|
+
});
|
|
201
|
+
results.push({ name: scenarioLabel(scenario), scenario, result });
|
|
202
|
+
}
|
|
203
|
+
return results;
|
|
204
|
+
}
|
|
205
|
+
function summarizeRuns(results) {
|
|
206
|
+
const durationMs = results.reduce((total, { result }) => {
|
|
207
|
+
if (!result.report.completedAt) return total;
|
|
208
|
+
return total + Math.max(0, Date.parse(result.report.completedAt) - Date.parse(result.report.startedAt));
|
|
209
|
+
}, 0);
|
|
210
|
+
return {
|
|
211
|
+
total: results.length,
|
|
212
|
+
passed: results.filter(({ result }) => result.passed).length,
|
|
213
|
+
failed: results.filter(({ result }) => !result.passed).length,
|
|
214
|
+
financiallyVerified: results.filter(({ result }) => result.report.financiallyVerified).length,
|
|
215
|
+
financiallyUnverified: results.filter(({ result }) => !result.report.financiallyVerified).length,
|
|
216
|
+
financialViolations: results.reduce((total, { result }) => total + (result.report.verification?.violations.length ?? 0), 0),
|
|
217
|
+
durationMs
|
|
218
|
+
};
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
// src/cli.ts
|
|
222
|
+
function usage() {
|
|
223
|
+
return `BachsProof
|
|
224
|
+
Beyond webhook delivery. Verify financial correctness.
|
|
225
|
+
|
|
226
|
+
Usage:
|
|
227
|
+
bachsproof init [directory] [--force]
|
|
228
|
+
bachsproof test [--config <path>] [--name <scenario-name>] [--json]
|
|
229
|
+
|
|
230
|
+
init creates one bachsproof.config.mjs file.
|
|
231
|
+
test runs all eleven financial correctness scenarios unless --name or
|
|
232
|
+
scenarios in the config selects a subset.
|
|
233
|
+
`;
|
|
234
|
+
}
|
|
235
|
+
function explainError(error) {
|
|
236
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
237
|
+
if (message.includes("Refusing to overwrite existing BachsProof file")) {
|
|
238
|
+
return `${message}
|
|
239
|
+
Open the existing file if you want to keep it. Use --force only when replacement is intentional.`;
|
|
240
|
+
}
|
|
241
|
+
if (message.includes("Implement createPayment")) {
|
|
242
|
+
return `${message}
|
|
243
|
+
The callback must create a fresh record in your isolated test application and return its reference.`;
|
|
244
|
+
}
|
|
245
|
+
if (message.includes("Implement verify")) {
|
|
246
|
+
return `${message}
|
|
247
|
+
The callback must read committed payment and ledger records. HTTP success alone is not financial proof.`;
|
|
248
|
+
}
|
|
249
|
+
if (message.includes("already used") || message.includes("duplicate payment references")) {
|
|
250
|
+
return `${message}
|
|
251
|
+
Every selected scenario needs a fresh isolated payment record.`;
|
|
252
|
+
}
|
|
253
|
+
if (message.includes("Unknown BachsProof scenario")) {
|
|
254
|
+
return `${message}
|
|
255
|
+
Use the exact scenario identifier from the generated configuration comments.`;
|
|
256
|
+
}
|
|
257
|
+
if (message.includes("Webhook delivery")) {
|
|
258
|
+
return `${message}
|
|
259
|
+
Check the isolated webhook URL and application logs. BachsProof still verifies financial state when it is safe to do so.`;
|
|
260
|
+
}
|
|
261
|
+
if (message.includes("Financial verification")) {
|
|
262
|
+
return `${message}
|
|
263
|
+
Check that verify() reads the requested reference and reports actual committed financial state.`;
|
|
264
|
+
}
|
|
265
|
+
return message;
|
|
266
|
+
}
|
|
267
|
+
function printInitializationGuide() {
|
|
268
|
+
console.log(`
|
|
269
|
+
BachsProof initialized successfully.
|
|
270
|
+
|
|
271
|
+
Open bachsproof.config.mjs and implement two callbacks:
|
|
272
|
+
|
|
273
|
+
1. createPayment() creates a fresh payment in your isolated test application.
|
|
274
|
+
2. verify() reads the committed payment and ledger records.
|
|
275
|
+
|
|
276
|
+
Then run:
|
|
277
|
+
pnpm exec bachsproof test --name "sequential duplicate webhook"
|
|
278
|
+
pnpm exec bachsproof test
|
|
279
|
+
|
|
280
|
+
Use a test-only application, database, queue, and webhook secret.
|
|
281
|
+
`);
|
|
282
|
+
}
|
|
283
|
+
function valueAfter(args, flag) {
|
|
284
|
+
const index = args.indexOf(flag);
|
|
285
|
+
if (index >= 0) return args[index + 1];
|
|
286
|
+
const inline = args.find((arg) => arg.startsWith(`${flag}=`));
|
|
287
|
+
return inline?.slice(flag.length + 1).replace(/^("|')(.*)\1$/, "$2");
|
|
288
|
+
}
|
|
289
|
+
function has(args, flag) {
|
|
290
|
+
return args.includes(flag);
|
|
291
|
+
}
|
|
292
|
+
function redact(value, secret) {
|
|
293
|
+
return secret ? value.replaceAll(secret, "[redacted]") : value;
|
|
294
|
+
}
|
|
295
|
+
function reasonFor(report) {
|
|
296
|
+
const violation = report.verification?.violations[0];
|
|
297
|
+
if (violation) {
|
|
298
|
+
switch (violation.id) {
|
|
299
|
+
case "INV-001":
|
|
300
|
+
return "The same payment was credited more than once.";
|
|
301
|
+
case "INV-002":
|
|
302
|
+
case "INV-005":
|
|
303
|
+
return "The credited amount or currency does not match the payment.";
|
|
304
|
+
case "INV-003":
|
|
305
|
+
return "The successful payment did not produce the required credit.";
|
|
306
|
+
case "INV-004":
|
|
307
|
+
return "An ineligible payment created a credit.";
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
return report.errors[0];
|
|
311
|
+
}
|
|
312
|
+
function formatState(state) {
|
|
313
|
+
return state ? `${state.creditCount} credit(s) totalling ${state.creditedAmountMinor} ${state.currency} minor units` : "not available";
|
|
314
|
+
}
|
|
315
|
+
async function main(args = process.argv.slice(2)) {
|
|
316
|
+
const command = args[0];
|
|
317
|
+
if (!command || command === "--help" || command === "-h") {
|
|
318
|
+
console.log(usage());
|
|
319
|
+
return 0;
|
|
320
|
+
}
|
|
321
|
+
if (command === "init") {
|
|
322
|
+
const directory = args.find((arg, index) => index > 0 && !arg.startsWith("-")) ?? process.cwd();
|
|
323
|
+
const paths = await initProject(directory, has(args, "--force"));
|
|
324
|
+
for (const path of paths) console.log(`created ${path}`);
|
|
325
|
+
printInitializationGuide();
|
|
326
|
+
return 0;
|
|
327
|
+
}
|
|
328
|
+
if (command !== "test") throw new Error(`Unknown command ${command}
|
|
329
|
+
|
|
330
|
+
${usage()}`);
|
|
331
|
+
const configPath = valueAfter(args, "--config") ?? "bachsproof.config.mjs";
|
|
332
|
+
const testName = valueAfter(args, "--name");
|
|
333
|
+
const config = await loadConfig(configPath);
|
|
334
|
+
const results = await runConfig(config, { testName });
|
|
335
|
+
const summary = summarizeRuns(results);
|
|
336
|
+
const failed = results.some(({ result }) => !result.passed);
|
|
337
|
+
if (has(args, "--json")) {
|
|
338
|
+
console.log(redact(JSON.stringify(results, null, 2), config.secret));
|
|
339
|
+
} else {
|
|
340
|
+
console.log("BachsProof\n");
|
|
341
|
+
for (const { name, result } of results) {
|
|
342
|
+
const duration = result.report.completedAt ? Math.max(0, Date.parse(result.report.completedAt) - Date.parse(result.report.startedAt)) : 0;
|
|
343
|
+
console.log(`${result.passed ? "PASS" : "FAIL"} ${name}`);
|
|
344
|
+
if (!result.passed) {
|
|
345
|
+
console.log(` Payment reference: ${result.report.paymentReference}`);
|
|
346
|
+
console.log(` Expected: one credit of ${result.report.expected.amountMinor} ${result.report.expected.currency} minor units when eligible`);
|
|
347
|
+
console.log(` Observed: ${formatState(result.report.observed)}`);
|
|
348
|
+
const reason = reasonFor(result.report);
|
|
349
|
+
if (reason) console.log(` Reason: ${redact(reason, config.secret)}`);
|
|
350
|
+
}
|
|
351
|
+
console.log(` ${result.report.financiallyVerified ? "Financial verification completed" : "Financial verification did not complete"} (${duration}ms)
|
|
352
|
+
`);
|
|
353
|
+
}
|
|
354
|
+
console.log("Summary");
|
|
355
|
+
console.log(`${summary.total} scenarios`);
|
|
356
|
+
console.log(`${summary.passed} passed`);
|
|
357
|
+
console.log(`${summary.failed} failed`);
|
|
358
|
+
}
|
|
359
|
+
return failed ? 1 : 0;
|
|
360
|
+
}
|
|
361
|
+
main().then((code) => {
|
|
362
|
+
process.exitCode = code;
|
|
363
|
+
}).catch((error) => {
|
|
364
|
+
console.error(explainError(error));
|
|
365
|
+
process.exitCode = 1;
|
|
366
|
+
});
|
|
367
|
+
|
|
368
|
+
export { main };
|
|
369
|
+
//# sourceMappingURL=cli.js.map
|
|
370
|
+
//# sourceMappingURL=cli.js.map
|
package/dist/cli.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/init.ts","../src/runner.ts","../src/cli.ts"],"names":["resolve"],"mappings":";;;;;;;;AAIA,IAAM,cAAA,GAAiB,CAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;A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AAM,YAAA,CAAa,KAAK,CAAC,CAAA;AACjC,EAAA,OAAA,CAAQ,QAAA,GAAW,CAAA;AACrB,CAAC,CAAA","file":"cli.js","sourcesContent":["import { access, writeFile } from \"node:fs/promises\";\nimport { constants } from \"node:fs\";\nimport { join, resolve } from \"node:path\";\n\nconst configTemplate = `/**\n * BachsProof v2 configuration.\n *\n * Use only an isolated application, test database, queue, and webhook secret.\n * BachsProof creates local simulated events. It never calls Bachs or moves money.\n */\nimport { defineConfig } from \"@bachsproof/cli\";\n\nexport default defineConfig({\n // The complete URL of your isolated application's Bachs webhook route.\n webhookUrl: process.env.BACHSPROOF_WEBHOOK_URL ?? \"http://127.0.0.1:3000/webhooks/bachs\",\n\n // Use a secret that belongs only to your test application.\n secret: process.env.BACHS_WEBHOOK_SECRET ?? \"\",\n\n // 500,000 NGN minor units means NGN 5,000.00.\n amountMinor: 500_000,\n currency: \"NGN\",\n\n // Before BachsProof sends a webhook, create a fresh payment record and\n // return its reference. Replace the example error with your test helper.\n async createPayment({ scenario, amountMinor, currency, paymentIndex, paymentCount }) {\n throw new Error(\n \"Implement createPayment in bachsproof.config.mjs. \" +\n \"Create an isolated test payment and return its non-empty reference for \" +\n scenario + \" (\" + (paymentIndex + 1) + \" of \" + paymentCount + \").\"\n );\n // Example:\n // const payment = await testApplication.createPayment({ amountMinor, currency });\n // return payment.reference;\n },\n\n // Read the application's committed payment and ledger records. Do not return\n // the expected values from this file; return what the database contains.\n async verify(reference) {\n throw new Error(\n \"Implement verify in bachsproof.config.mjs by reading committed \" +\n \"financial records for \" + reference + \".\"\n );\n // Example result:\n // return {\n // reference,\n // creditCount: credits.length,\n // creditedAmountMinor: credits.reduce((sum, credit) => sum + credit.amountMinor, 0),\n // currency: payment.currency,\n // status: payment.status,\n // pending: false,\n // ledgerEntries: credits.map((credit) => ({\n // id: String(credit.id),\n // type: String(credit.type),\n // amountMinor: credit.amountMinor,\n // currency: credit.currency\n // }))\n // };\n }\n\n // Optional: run only selected scenario identifiers. Omit to run all eleven.\n // scenarios: [\"sequential-duplicate-webhook\"],\n\n // Optional: increase this only when your isolated application processes\n // webhooks asynchronously. The default is 10 seconds.\n // verificationTimeoutMs: 10_000\n});\n`;\n\nasync function exists(path: string): Promise<boolean> {\n try {\n await access(path, constants.F_OK);\n return true;\n } catch {\n return false;\n }\n}\n\n/** Create exactly one config file and never overwrite it accidentally. */\nexport async function initProject(directory = process.cwd(), force = false): Promise<string[]> {\n const configPath = join(resolve(directory), \"bachsproof.config.mjs\");\n if (!force && await exists(configPath)) {\n throw new Error(`Refusing to overwrite existing BachsProof file: ${configPath}. Use --force only when replacement is intentional.`);\n }\n await writeFile(configPath, configTemplate, \"utf8\");\n return [configPath];\n}\n","import { createJiti } from \"jiti\";\nimport { resolve } from \"node:path\";\nimport { BachsProof, SUPPORTED_SCENARIOS, type PaymentEvent, type PaymentReferenceCreator, type ProviderAdapter, type ScenarioName } from \"@bachsproof/core\";\nimport { bachsAdapter, signBachsWebhook } from \"@bachsproof/bachs\";\nimport type { BachsProofCliRun, BachsProofConfig, BachsProofSummary, RunConfigOptions } from \"./types.js\";\n\nconst SCENARIO_LABELS: Record<ScenarioName, string> = {\n \"sequential-duplicate-webhook\": \"Sequential duplicate webhook\",\n \"concurrent-duplicate-credit\": \"Concurrent duplicate credit\",\n \"concurrent-unique-payments\": \"Concurrent unique payments\",\n \"cross-event-duplicate-payment\": \"Cross-event duplicate payment\",\n \"out-of-order-events\": \"Out-of-order events\",\n \"incomplete-checkout\": \"Incomplete checkout\",\n \"expired-checkout\": \"Expired checkout\",\n \"incorrect-payment-amount\": \"Incorrect payment amount\",\n \"incorrect-payment-currency\": \"Incorrect payment currency\",\n \"underpaid-payment\": \"Underpaid payment\",\n \"failed-payment\": \"Failed payment\"\n};\n\nexport function scenarioLabel(scenario: ScenarioName): string {\n return SCENARIO_LABELS[scenario];\n}\n\nfunction assertConfig(value: unknown): asserts value is BachsProofConfig {\n if (!value || typeof value !== \"object\") throw new Error(\"BachsProof config must export a default object\");\n const config = value as Partial<BachsProofConfig>;\n if (typeof config.webhookUrl !== \"string\" || config.webhookUrl.trim().length === 0) {\n throw new Error(\"BachsProof config requires a complete webhookUrl\");\n }\n try {\n const url = new URL(config.webhookUrl);\n if (url.protocol !== \"http:\" && url.protocol !== \"https:\") throw new Error(\"webhookUrl must use http or https\");\n } catch (error) {\n throw new Error(`BachsProof config webhookUrl is invalid: ${error instanceof Error ? error.message : String(error)}`);\n }\n if (typeof config.secret !== \"string\" || config.secret.trim().length === 0) {\n throw new Error(\"BachsProof config requires a non-empty test webhook secret\");\n }\n if (!Number.isSafeInteger(config.amountMinor) || (config.amountMinor as number) < 0) {\n throw new Error(\"BachsProof config amountMinor must be a non-negative safe integer\");\n }\n if (typeof config.currency !== \"string\" || !/^[A-Z]{3}$/.test(config.currency)) {\n throw new Error(\"BachsProof config currency must be a three-letter ISO currency code\");\n }\n if (typeof config.createPayment !== \"function\") throw new Error(\"BachsProof config requires a createPayment callback\");\n if (typeof config.verify !== \"function\") throw new Error(\"BachsProof config requires a verify callback\");\n if (config.verificationTimeoutMs !== undefined && (!Number.isSafeInteger(config.verificationTimeoutMs) || config.verificationTimeoutMs < 1)) {\n throw new Error(\"BachsProof config verificationTimeoutMs must be a positive safe integer\");\n }\n if (config.scenarios !== undefined) {\n if (!Array.isArray(config.scenarios) || config.scenarios.length === 0) throw new Error(\"BachsProof config scenarios must contain at least one scenario\");\n for (const scenario of config.scenarios) {\n if (!(SUPPORTED_SCENARIOS as readonly string[]).includes(scenario)) {\n throw new Error(`Unknown BachsProof scenario: ${String(scenario)}`);\n }\n }\n }\n}\n\n/** Load a JavaScript, MJS, CJS, or TypeScript config file. */\nexport async function loadConfig(configPath = \"bachsproof.config.mjs\"): Promise<BachsProofConfig> {\n const absolutePath = resolve(process.cwd(), configPath);\n const jiti = createJiti(absolutePath, { interopDefault: true });\n const loaded = await jiti.import(absolutePath, { default: true }) as unknown;\n assertConfig(loaded);\n return loaded;\n}\n\nfunction withBachsSigning(provider: ProviderAdapter, secret: string): ProviderAdapter {\n return {\n ...provider,\n headers(event) {\n const body = provider.serialize(event);\n return {\n ...(provider.headers?.(event) ?? {}),\n ...signBachsWebhook(body, secret)\n };\n },\n headersForBody(event, body) {\n return {\n ...(provider.headersForBody?.(event, body) ?? provider.headers?.(event) ?? {}),\n ...signBachsWebhook(body, secret)\n };\n }\n };\n}\n\nfunction selectedScenarios(config: BachsProofConfig, testName?: string): ScenarioName[] {\n const scenarios = config.scenarios ?? [...SUPPORTED_SCENARIOS];\n if (!testName) return scenarios;\n const selected = scenarios.find((scenario) => scenarioLabel(scenario) === testName || scenario === testName);\n if (!selected) throw new Error(`Unknown BachsProof scenario or test name \"${testName}\". Use one of: ${scenarios.map(scenarioLabel).join(\", \")}`);\n return [selected];\n}\n\nexport async function runConfig(config: BachsProofConfig, options: RunConfigOptions = {}): Promise<BachsProofCliRun[]> {\n assertConfig(config);\n const scenarios = selectedScenarios(config, options.testName);\n const provider = withBachsSigning(bachsAdapter({ mode: \"mock\" }), config.secret);\n const usedReferences = new Set<string>();\n const createPayment: PaymentReferenceCreator = async (context) => {\n const reference = await config.createPayment(context);\n if (typeof reference !== \"string\" || reference.trim().length === 0) return reference as string;\n const normalized = reference.trim();\n if (usedReferences.has(normalized)) {\n throw new Error(`createPayment returned reference ${normalized}, which was already used by another selected scenario`);\n }\n usedReferences.add(normalized);\n return normalized;\n };\n const runner = new BachsProof({\n provider,\n webhookUrl: config.webhookUrl,\n createPayment,\n verify: config.verify,\n financialVerification: config.verificationTimeoutMs === undefined ? undefined : { completionDeadlineMs: config.verificationTimeoutMs }\n });\n const results: BachsProofCliRun[] = [];\n for (const scenario of scenarios) {\n const result = await runner.run({\n scenario,\n amountMinor: config.amountMinor,\n currency: config.currency\n });\n results.push({ name: scenarioLabel(scenario), scenario, result });\n }\n return results;\n}\n\nexport function summarizeRuns(results: BachsProofCliRun[]): BachsProofSummary {\n const durationMs = results.reduce((total, { result }) => {\n if (!result.report.completedAt) return total;\n return total + Math.max(0, Date.parse(result.report.completedAt) - Date.parse(result.report.startedAt));\n }, 0);\n return {\n total: results.length,\n passed: results.filter(({ result }) => result.passed).length,\n failed: results.filter(({ result }) => !result.passed).length,\n financiallyVerified: results.filter(({ result }) => result.report.financiallyVerified).length,\n financiallyUnverified: results.filter(({ result }) => !result.report.financiallyVerified).length,\n financialViolations: results.reduce((total, { result }) => total + (result.report.verification?.violations.length ?? 0), 0),\n durationMs\n };\n}\n\nexport { bachsAdapter, signBachsWebhook } from \"@bachsproof/bachs\";\n","import { resolve } from \"node:path\";\nimport { initProject } from \"./init.js\";\nimport { loadConfig, runConfig, scenarioLabel, summarizeRuns } from \"./runner.js\";\n\nfunction usage(): string {\n return `BachsProof\nBeyond webhook delivery. Verify financial correctness.\n\nUsage:\n bachsproof init [directory] [--force]\n bachsproof test [--config <path>] [--name <scenario-name>] [--json]\n\ninit creates one bachsproof.config.mjs file.\ntest runs all eleven financial correctness scenarios unless --name or\nscenarios in the config selects a subset.\n`;\n}\n\nfunction explainError(error: unknown): string {\n const message = error instanceof Error ? error.message : String(error);\n if (message.includes(\"Refusing to overwrite existing BachsProof file\")) {\n return `${message}\\nOpen the existing file if you want to keep it. Use --force only when replacement is intentional.`;\n }\n if (message.includes(\"Implement createPayment\")) {\n return `${message}\\nThe callback must create a fresh record in your isolated test application and return its reference.`;\n }\n if (message.includes(\"Implement verify\")) {\n return `${message}\\nThe callback must read committed payment and ledger records. HTTP success alone is not financial proof.`;\n }\n if (message.includes(\"already used\") || message.includes(\"duplicate payment references\")) {\n return `${message}\\nEvery selected scenario needs a fresh isolated payment record.`;\n }\n if (message.includes(\"Unknown BachsProof scenario\")) {\n return `${message}\\nUse the exact scenario identifier from the generated configuration comments.`;\n }\n if (message.includes(\"Webhook delivery\")) {\n return `${message}\\nCheck the isolated webhook URL and application logs. BachsProof still verifies financial state when it is safe to do so.`;\n }\n if (message.includes(\"Financial verification\")) {\n return `${message}\\nCheck that verify() reads the requested reference and reports actual committed financial state.`;\n }\n return message;\n}\n\nfunction printInitializationGuide(): void {\n console.log(`\nBachsProof initialized successfully.\n\nOpen bachsproof.config.mjs and implement two callbacks:\n\n1. createPayment() creates a fresh payment in your isolated test application.\n2. verify() reads the committed payment and ledger records.\n\nThen run:\n pnpm exec bachsproof test --name \"sequential duplicate webhook\"\n pnpm exec bachsproof test\n\nUse a test-only application, database, queue, and webhook secret.\n`);\n}\n\nfunction valueAfter(args: string[], flag: string): string | undefined {\n const index = args.indexOf(flag);\n if (index >= 0) return args[index + 1];\n const inline = args.find((arg) => arg.startsWith(`${flag}=`));\n return inline?.slice(flag.length + 1).replace(/^(\"|')(.*)\\1$/, \"$2\");\n}\n\nfunction has(args: string[], flag: string): boolean {\n return args.includes(flag);\n}\n\nfunction redact(value: string, secret: string): string {\n return secret ? value.replaceAll(secret, \"[redacted]\") : value;\n}\n\nfunction reasonFor(report: import(\"@bachsproof/core\").BachsProofReport): string | undefined {\n const violation = report.verification?.violations[0];\n if (violation) {\n switch (violation.id) {\n case \"INV-001\": return \"The same payment was credited more than once.\";\n case \"INV-002\":\n case \"INV-005\": return \"The credited amount or currency does not match the payment.\";\n case \"INV-003\": return \"The successful payment did not produce the required credit.\";\n case \"INV-004\": return \"An ineligible payment created a credit.\";\n }\n }\n return report.errors[0];\n}\n\nfunction formatState(state: import(\"@bachsproof/core\").ObservedPaymentState | undefined): string {\n return state ? `${state.creditCount} credit(s) totalling ${state.creditedAmountMinor} ${state.currency} minor units` : \"not available\";\n}\n\nexport async function main(args = process.argv.slice(2)): Promise<number> {\n const command = args[0];\n if (!command || command === \"--help\" || command === \"-h\") {\n console.log(usage());\n return 0;\n }\n if (command === \"init\") {\n const directory = args.find((arg, index) => index > 0 && !arg.startsWith(\"-\")) ?? process.cwd();\n const paths = await initProject(directory, has(args, \"--force\"));\n for (const path of paths) console.log(`created ${path}`);\n printInitializationGuide();\n return 0;\n }\n if (command !== \"test\") throw new Error(`Unknown command ${command}\\n\\n${usage()}`);\n\n const configPath = valueAfter(args, \"--config\") ?? \"bachsproof.config.mjs\";\n const testName = valueAfter(args, \"--name\");\n const config = await loadConfig(configPath);\n const results = await runConfig(config, { testName });\n const summary = summarizeRuns(results);\n const failed = results.some(({ result }) => !result.passed);\n if (has(args, \"--json\")) {\n console.log(redact(JSON.stringify(results, null, 2), config.secret));\n } else {\n console.log(\"BachsProof\\n\");\n for (const { name, result } of results) {\n const duration = result.report.completedAt ? Math.max(0, Date.parse(result.report.completedAt) - Date.parse(result.report.startedAt)) : 0;\n console.log(`${result.passed ? \"PASS\" : \"FAIL\"} ${name}`);\n if (!result.passed) {\n console.log(` Payment reference: ${result.report.paymentReference}`);\n console.log(` Expected: one credit of ${result.report.expected.amountMinor} ${result.report.expected.currency} minor units when eligible`);\n console.log(` Observed: ${formatState(result.report.observed)}`);\n const reason = reasonFor(result.report);\n if (reason) console.log(` Reason: ${redact(reason, config.secret)}`);\n }\n console.log(` ${result.report.financiallyVerified ? \"Financial verification completed\" : \"Financial verification did not complete\"} (${duration}ms)\\n`);\n }\n console.log(\"Summary\");\n console.log(`${summary.total} scenarios`);\n console.log(`${summary.passed} passed`);\n console.log(`${summary.failed} failed`);\n }\n return failed ? 1 : 0;\n}\n\nmain().then((code) => {\n process.exitCode = code;\n}).catch((error: unknown) => {\n console.error(explainError(error));\n process.exitCode = 1;\n});\n"]}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import * as _bachsproof_core from '@bachsproof/core';
|
|
2
|
+
import { ScenarioName, PaymentEvent, PaymentReferenceCreator, FinancialVerifier } from '@bachsproof/core';
|
|
3
|
+
export { FinancialVerificationContext, FinancialVerificationInput, FinancialVerifier, PaymentPreparationContext, PaymentReferenceCreator, ScenarioName } from '@bachsproof/core';
|
|
4
|
+
|
|
5
|
+
/** The only developer-facing configuration supported by BachsProof v2. */
|
|
6
|
+
interface BachsProofConfig<TEvent extends PaymentEvent = PaymentEvent> {
|
|
7
|
+
/** Complete URL of the isolated application's Bachs webhook route. */
|
|
8
|
+
webhookUrl: string;
|
|
9
|
+
/** Test-only secret used to sign every generated webhook automatically. */
|
|
10
|
+
secret: string;
|
|
11
|
+
/** Default integer amount in minor units. */
|
|
12
|
+
amountMinor: number;
|
|
13
|
+
/** Default three-letter ISO currency code. */
|
|
14
|
+
currency: string;
|
|
15
|
+
/** Creates a fresh application payment and returns its reference. */
|
|
16
|
+
createPayment: PaymentReferenceCreator;
|
|
17
|
+
/** Reads the committed payment and ledger state for a prepared reference. */
|
|
18
|
+
verify: FinancialVerifier;
|
|
19
|
+
/** Run a subset; omitted means all eleven scenarios. */
|
|
20
|
+
scenarios?: ScenarioName[];
|
|
21
|
+
/** Increase the default asynchronous financial observation deadline if needed. */
|
|
22
|
+
verificationTimeoutMs?: number;
|
|
23
|
+
}
|
|
24
|
+
interface BachsProofCliRun {
|
|
25
|
+
name: string;
|
|
26
|
+
scenario: ScenarioName;
|
|
27
|
+
result: _bachsproof_core.BachsProofResult;
|
|
28
|
+
}
|
|
29
|
+
interface BachsProofSummary {
|
|
30
|
+
total: number;
|
|
31
|
+
passed: number;
|
|
32
|
+
failed: number;
|
|
33
|
+
financiallyVerified: number;
|
|
34
|
+
financiallyUnverified: number;
|
|
35
|
+
financialViolations: number;
|
|
36
|
+
durationMs: number;
|
|
37
|
+
}
|
|
38
|
+
interface RunConfigOptions {
|
|
39
|
+
testName?: string;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** Type helper for bachsproof.config.mjs and bachsproof.config.ts files. */
|
|
43
|
+
declare function defineConfig<TEvent extends PaymentEvent = PaymentEvent>(config: BachsProofConfig<TEvent>): BachsProofConfig<TEvent>;
|
|
44
|
+
|
|
45
|
+
/** Create exactly one config file and never overwrite it accidentally. */
|
|
46
|
+
declare function initProject(directory?: string, force?: boolean): Promise<string[]>;
|
|
47
|
+
|
|
48
|
+
declare function scenarioLabel(scenario: ScenarioName): string;
|
|
49
|
+
/** Load a JavaScript, MJS, CJS, or TypeScript config file. */
|
|
50
|
+
declare function loadConfig(configPath?: string): Promise<BachsProofConfig>;
|
|
51
|
+
declare function runConfig(config: BachsProofConfig, options?: RunConfigOptions): Promise<BachsProofCliRun[]>;
|
|
52
|
+
declare function summarizeRuns(results: BachsProofCliRun[]): BachsProofSummary;
|
|
53
|
+
|
|
54
|
+
export { type BachsProofCliRun, type BachsProofConfig, type BachsProofSummary, type RunConfigOptions, defineConfig, initProject, loadConfig, runConfig, scenarioLabel, summarizeRuns };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,227 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { writeFile, access } from 'fs/promises';
|
|
3
|
+
import { constants } from 'fs';
|
|
4
|
+
import { join, resolve } from 'path';
|
|
5
|
+
import { createJiti } from 'jiti';
|
|
6
|
+
import { BachsProof, SUPPORTED_SCENARIOS } from '@bachsproof/core';
|
|
7
|
+
import { bachsAdapter, signBachsWebhook } from '@bachsproof/bachs';
|
|
8
|
+
|
|
9
|
+
// src/config.ts
|
|
10
|
+
function defineConfig(config) {
|
|
11
|
+
return config;
|
|
12
|
+
}
|
|
13
|
+
var configTemplate = `/**
|
|
14
|
+
* BachsProof v2 configuration.
|
|
15
|
+
*
|
|
16
|
+
* Use only an isolated application, test database, queue, and webhook secret.
|
|
17
|
+
* BachsProof creates local simulated events. It never calls Bachs or moves money.
|
|
18
|
+
*/
|
|
19
|
+
import { defineConfig } from "@bachsproof/cli";
|
|
20
|
+
|
|
21
|
+
export default defineConfig({
|
|
22
|
+
// The complete URL of your isolated application's Bachs webhook route.
|
|
23
|
+
webhookUrl: process.env.BACHSPROOF_WEBHOOK_URL ?? "http://127.0.0.1:3000/webhooks/bachs",
|
|
24
|
+
|
|
25
|
+
// Use a secret that belongs only to your test application.
|
|
26
|
+
secret: process.env.BACHS_WEBHOOK_SECRET ?? "",
|
|
27
|
+
|
|
28
|
+
// 500,000 NGN minor units means NGN 5,000.00.
|
|
29
|
+
amountMinor: 500_000,
|
|
30
|
+
currency: "NGN",
|
|
31
|
+
|
|
32
|
+
// Before BachsProof sends a webhook, create a fresh payment record and
|
|
33
|
+
// return its reference. Replace the example error with your test helper.
|
|
34
|
+
async createPayment({ scenario, amountMinor, currency, paymentIndex, paymentCount }) {
|
|
35
|
+
throw new Error(
|
|
36
|
+
"Implement createPayment in bachsproof.config.mjs. " +
|
|
37
|
+
"Create an isolated test payment and return its non-empty reference for " +
|
|
38
|
+
scenario + " (" + (paymentIndex + 1) + " of " + paymentCount + ")."
|
|
39
|
+
);
|
|
40
|
+
// Example:
|
|
41
|
+
// const payment = await testApplication.createPayment({ amountMinor, currency });
|
|
42
|
+
// return payment.reference;
|
|
43
|
+
},
|
|
44
|
+
|
|
45
|
+
// Read the application's committed payment and ledger records. Do not return
|
|
46
|
+
// the expected values from this file; return what the database contains.
|
|
47
|
+
async verify(reference) {
|
|
48
|
+
throw new Error(
|
|
49
|
+
"Implement verify in bachsproof.config.mjs by reading committed " +
|
|
50
|
+
"financial records for " + reference + "."
|
|
51
|
+
);
|
|
52
|
+
// Example result:
|
|
53
|
+
// return {
|
|
54
|
+
// reference,
|
|
55
|
+
// creditCount: credits.length,
|
|
56
|
+
// creditedAmountMinor: credits.reduce((sum, credit) => sum + credit.amountMinor, 0),
|
|
57
|
+
// currency: payment.currency,
|
|
58
|
+
// status: payment.status,
|
|
59
|
+
// pending: false,
|
|
60
|
+
// ledgerEntries: credits.map((credit) => ({
|
|
61
|
+
// id: String(credit.id),
|
|
62
|
+
// type: String(credit.type),
|
|
63
|
+
// amountMinor: credit.amountMinor,
|
|
64
|
+
// currency: credit.currency
|
|
65
|
+
// }))
|
|
66
|
+
// };
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
// Optional: run only selected scenario identifiers. Omit to run all eleven.
|
|
70
|
+
// scenarios: ["sequential-duplicate-webhook"],
|
|
71
|
+
|
|
72
|
+
// Optional: increase this only when your isolated application processes
|
|
73
|
+
// webhooks asynchronously. The default is 10 seconds.
|
|
74
|
+
// verificationTimeoutMs: 10_000
|
|
75
|
+
});
|
|
76
|
+
`;
|
|
77
|
+
async function exists(path) {
|
|
78
|
+
try {
|
|
79
|
+
await access(path, constants.F_OK);
|
|
80
|
+
return true;
|
|
81
|
+
} catch {
|
|
82
|
+
return false;
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
async function initProject(directory = process.cwd(), force = false) {
|
|
86
|
+
const configPath = join(resolve(directory), "bachsproof.config.mjs");
|
|
87
|
+
if (!force && await exists(configPath)) {
|
|
88
|
+
throw new Error(`Refusing to overwrite existing BachsProof file: ${configPath}. Use --force only when replacement is intentional.`);
|
|
89
|
+
}
|
|
90
|
+
await writeFile(configPath, configTemplate, "utf8");
|
|
91
|
+
return [configPath];
|
|
92
|
+
}
|
|
93
|
+
var SCENARIO_LABELS = {
|
|
94
|
+
"sequential-duplicate-webhook": "Sequential duplicate webhook",
|
|
95
|
+
"concurrent-duplicate-credit": "Concurrent duplicate credit",
|
|
96
|
+
"concurrent-unique-payments": "Concurrent unique payments",
|
|
97
|
+
"cross-event-duplicate-payment": "Cross-event duplicate payment",
|
|
98
|
+
"out-of-order-events": "Out-of-order events",
|
|
99
|
+
"incomplete-checkout": "Incomplete checkout",
|
|
100
|
+
"expired-checkout": "Expired checkout",
|
|
101
|
+
"incorrect-payment-amount": "Incorrect payment amount",
|
|
102
|
+
"incorrect-payment-currency": "Incorrect payment currency",
|
|
103
|
+
"underpaid-payment": "Underpaid payment",
|
|
104
|
+
"failed-payment": "Failed payment"
|
|
105
|
+
};
|
|
106
|
+
function scenarioLabel(scenario) {
|
|
107
|
+
return SCENARIO_LABELS[scenario];
|
|
108
|
+
}
|
|
109
|
+
function assertConfig(value) {
|
|
110
|
+
if (!value || typeof value !== "object") throw new Error("BachsProof config must export a default object");
|
|
111
|
+
const config = value;
|
|
112
|
+
if (typeof config.webhookUrl !== "string" || config.webhookUrl.trim().length === 0) {
|
|
113
|
+
throw new Error("BachsProof config requires a complete webhookUrl");
|
|
114
|
+
}
|
|
115
|
+
try {
|
|
116
|
+
const url = new URL(config.webhookUrl);
|
|
117
|
+
if (url.protocol !== "http:" && url.protocol !== "https:") throw new Error("webhookUrl must use http or https");
|
|
118
|
+
} catch (error) {
|
|
119
|
+
throw new Error(`BachsProof config webhookUrl is invalid: ${error instanceof Error ? error.message : String(error)}`);
|
|
120
|
+
}
|
|
121
|
+
if (typeof config.secret !== "string" || config.secret.trim().length === 0) {
|
|
122
|
+
throw new Error("BachsProof config requires a non-empty test webhook secret");
|
|
123
|
+
}
|
|
124
|
+
if (!Number.isSafeInteger(config.amountMinor) || config.amountMinor < 0) {
|
|
125
|
+
throw new Error("BachsProof config amountMinor must be a non-negative safe integer");
|
|
126
|
+
}
|
|
127
|
+
if (typeof config.currency !== "string" || !/^[A-Z]{3}$/.test(config.currency)) {
|
|
128
|
+
throw new Error("BachsProof config currency must be a three-letter ISO currency code");
|
|
129
|
+
}
|
|
130
|
+
if (typeof config.createPayment !== "function") throw new Error("BachsProof config requires a createPayment callback");
|
|
131
|
+
if (typeof config.verify !== "function") throw new Error("BachsProof config requires a verify callback");
|
|
132
|
+
if (config.verificationTimeoutMs !== void 0 && (!Number.isSafeInteger(config.verificationTimeoutMs) || config.verificationTimeoutMs < 1)) {
|
|
133
|
+
throw new Error("BachsProof config verificationTimeoutMs must be a positive safe integer");
|
|
134
|
+
}
|
|
135
|
+
if (config.scenarios !== void 0) {
|
|
136
|
+
if (!Array.isArray(config.scenarios) || config.scenarios.length === 0) throw new Error("BachsProof config scenarios must contain at least one scenario");
|
|
137
|
+
for (const scenario of config.scenarios) {
|
|
138
|
+
if (!SUPPORTED_SCENARIOS.includes(scenario)) {
|
|
139
|
+
throw new Error(`Unknown BachsProof scenario: ${String(scenario)}`);
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
async function loadConfig(configPath = "bachsproof.config.mjs") {
|
|
145
|
+
const absolutePath = resolve(process.cwd(), configPath);
|
|
146
|
+
const jiti = createJiti(absolutePath, { interopDefault: true });
|
|
147
|
+
const loaded = await jiti.import(absolutePath, { default: true });
|
|
148
|
+
assertConfig(loaded);
|
|
149
|
+
return loaded;
|
|
150
|
+
}
|
|
151
|
+
function withBachsSigning(provider, secret) {
|
|
152
|
+
return {
|
|
153
|
+
...provider,
|
|
154
|
+
headers(event) {
|
|
155
|
+
const body = provider.serialize(event);
|
|
156
|
+
return {
|
|
157
|
+
...provider.headers?.(event) ?? {},
|
|
158
|
+
...signBachsWebhook(body, secret)
|
|
159
|
+
};
|
|
160
|
+
},
|
|
161
|
+
headersForBody(event, body) {
|
|
162
|
+
return {
|
|
163
|
+
...provider.headersForBody?.(event, body) ?? provider.headers?.(event) ?? {},
|
|
164
|
+
...signBachsWebhook(body, secret)
|
|
165
|
+
};
|
|
166
|
+
}
|
|
167
|
+
};
|
|
168
|
+
}
|
|
169
|
+
function selectedScenarios(config, testName) {
|
|
170
|
+
const scenarios = config.scenarios ?? [...SUPPORTED_SCENARIOS];
|
|
171
|
+
if (!testName) return scenarios;
|
|
172
|
+
const selected = scenarios.find((scenario) => scenarioLabel(scenario) === testName || scenario === testName);
|
|
173
|
+
if (!selected) throw new Error(`Unknown BachsProof scenario or test name "${testName}". Use one of: ${scenarios.map(scenarioLabel).join(", ")}`);
|
|
174
|
+
return [selected];
|
|
175
|
+
}
|
|
176
|
+
async function runConfig(config, options = {}) {
|
|
177
|
+
assertConfig(config);
|
|
178
|
+
const scenarios = selectedScenarios(config, options.testName);
|
|
179
|
+
const provider = withBachsSigning(bachsAdapter({ mode: "mock" }), config.secret);
|
|
180
|
+
const usedReferences = /* @__PURE__ */ new Set();
|
|
181
|
+
const createPayment = async (context) => {
|
|
182
|
+
const reference = await config.createPayment(context);
|
|
183
|
+
if (typeof reference !== "string" || reference.trim().length === 0) return reference;
|
|
184
|
+
const normalized = reference.trim();
|
|
185
|
+
if (usedReferences.has(normalized)) {
|
|
186
|
+
throw new Error(`createPayment returned reference ${normalized}, which was already used by another selected scenario`);
|
|
187
|
+
}
|
|
188
|
+
usedReferences.add(normalized);
|
|
189
|
+
return normalized;
|
|
190
|
+
};
|
|
191
|
+
const runner = new BachsProof({
|
|
192
|
+
provider,
|
|
193
|
+
webhookUrl: config.webhookUrl,
|
|
194
|
+
createPayment,
|
|
195
|
+
verify: config.verify,
|
|
196
|
+
financialVerification: config.verificationTimeoutMs === void 0 ? void 0 : { completionDeadlineMs: config.verificationTimeoutMs }
|
|
197
|
+
});
|
|
198
|
+
const results = [];
|
|
199
|
+
for (const scenario of scenarios) {
|
|
200
|
+
const result = await runner.run({
|
|
201
|
+
scenario,
|
|
202
|
+
amountMinor: config.amountMinor,
|
|
203
|
+
currency: config.currency
|
|
204
|
+
});
|
|
205
|
+
results.push({ name: scenarioLabel(scenario), scenario, result });
|
|
206
|
+
}
|
|
207
|
+
return results;
|
|
208
|
+
}
|
|
209
|
+
function summarizeRuns(results) {
|
|
210
|
+
const durationMs = results.reduce((total, { result }) => {
|
|
211
|
+
if (!result.report.completedAt) return total;
|
|
212
|
+
return total + Math.max(0, Date.parse(result.report.completedAt) - Date.parse(result.report.startedAt));
|
|
213
|
+
}, 0);
|
|
214
|
+
return {
|
|
215
|
+
total: results.length,
|
|
216
|
+
passed: results.filter(({ result }) => result.passed).length,
|
|
217
|
+
failed: results.filter(({ result }) => !result.passed).length,
|
|
218
|
+
financiallyVerified: results.filter(({ result }) => result.report.financiallyVerified).length,
|
|
219
|
+
financiallyUnverified: results.filter(({ result }) => !result.report.financiallyVerified).length,
|
|
220
|
+
financialViolations: results.reduce((total, { result }) => total + (result.report.verification?.violations.length ?? 0), 0),
|
|
221
|
+
durationMs
|
|
222
|
+
};
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
export { defineConfig, initProject, loadConfig, runConfig, scenarioLabel, summarizeRuns };
|
|
226
|
+
//# sourceMappingURL=index.js.map
|
|
227
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
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AO,KAAM,CAAC,MAAA,CAAO,MAAM,CAAA,CAAE,MAAA;AAAA,IACvD,mBAAA,EAAqB,OAAA,CAAQ,MAAA,CAAO,CAAC,EAAE,QAAO,KAAM,MAAA,CAAO,MAAA,CAAO,mBAAmB,CAAA,CAAE,MAAA;AAAA,IACvF,qBAAA,EAAuB,OAAA,CAAQ,MAAA,CAAO,CAAC,EAAE,MAAA,EAAO,KAAM,CAAC,MAAA,CAAO,MAAA,CAAO,mBAAmB,CAAA,CAAE,MAAA;AAAA,IAC1F,mBAAA,EAAqB,OAAA,CAAQ,MAAA,CAAO,CAAC,OAAO,EAAE,MAAA,EAAO,KAAM,KAAA,IAAS,OAAO,MAAA,CAAO,YAAA,EAAc,UAAA,CAAW,MAAA,IAAU,IAAI,CAAC,CAAA;AAAA,IAC1H;AAAA,GACF;AACF","file":"index.js","sourcesContent":["import type { PaymentEvent } from \"@bachsproof/core\";\nimport type { BachsProofConfig } from \"./types.js\";\n\n/** Type helper for bachsproof.config.mjs and bachsproof.config.ts files. */\nexport function defineConfig<TEvent extends PaymentEvent = PaymentEvent>(config: BachsProofConfig<TEvent>): BachsProofConfig<TEvent> {\n return config;\n}\n","import { access, writeFile } from \"node:fs/promises\";\nimport { constants } from \"node:fs\";\nimport { join, resolve } from \"node:path\";\n\nconst configTemplate = `/**\n * BachsProof v2 configuration.\n *\n * Use only an isolated application, test database, queue, and webhook secret.\n * BachsProof creates local simulated events. It never calls Bachs or moves money.\n */\nimport { defineConfig } from \"@bachsproof/cli\";\n\nexport default defineConfig({\n // The complete URL of your isolated application's Bachs webhook route.\n webhookUrl: process.env.BACHSPROOF_WEBHOOK_URL ?? \"http://127.0.0.1:3000/webhooks/bachs\",\n\n // Use a secret that belongs only to your test application.\n secret: process.env.BACHS_WEBHOOK_SECRET ?? \"\",\n\n // 500,000 NGN minor units means NGN 5,000.00.\n amountMinor: 500_000,\n currency: \"NGN\",\n\n // Before BachsProof sends a webhook, create a fresh payment record and\n // return its reference. Replace the example error with your test helper.\n async createPayment({ scenario, amountMinor, currency, paymentIndex, paymentCount }) {\n throw new Error(\n \"Implement createPayment in bachsproof.config.mjs. \" +\n \"Create an isolated test payment and return its non-empty reference for \" +\n scenario + \" (\" + (paymentIndex + 1) + \" of \" + paymentCount + \").\"\n );\n // Example:\n // const payment = await testApplication.createPayment({ amountMinor, currency });\n // return payment.reference;\n },\n\n // Read the application's committed payment and ledger records. Do not return\n // the expected values from this file; return what the database contains.\n async verify(reference) {\n throw new Error(\n \"Implement verify in bachsproof.config.mjs by reading committed \" +\n \"financial records for \" + reference + \".\"\n );\n // Example result:\n // return {\n // reference,\n // creditCount: credits.length,\n // creditedAmountMinor: credits.reduce((sum, credit) => sum + credit.amountMinor, 0),\n // currency: payment.currency,\n // status: payment.status,\n // pending: false,\n // ledgerEntries: credits.map((credit) => ({\n // id: String(credit.id),\n // type: String(credit.type),\n // amountMinor: credit.amountMinor,\n // currency: credit.currency\n // }))\n // };\n }\n\n // Optional: run only selected scenario identifiers. Omit to run all eleven.\n // scenarios: [\"sequential-duplicate-webhook\"],\n\n // Optional: increase this only when your isolated application processes\n // webhooks asynchronously. The default is 10 seconds.\n // verificationTimeoutMs: 10_000\n});\n`;\n\nasync function exists(path: string): Promise<boolean> {\n try {\n await access(path, constants.F_OK);\n return true;\n } catch {\n return false;\n }\n}\n\n/** Create exactly one config file and never overwrite it accidentally. */\nexport async function initProject(directory = process.cwd(), force = false): Promise<string[]> {\n const configPath = join(resolve(directory), \"bachsproof.config.mjs\");\n if (!force && await exists(configPath)) {\n throw new Error(`Refusing to overwrite existing BachsProof file: ${configPath}. Use --force only when replacement is intentional.`);\n }\n await writeFile(configPath, configTemplate, \"utf8\");\n return [configPath];\n}\n","import { createJiti } from \"jiti\";\nimport { resolve } from \"node:path\";\nimport { BachsProof, SUPPORTED_SCENARIOS, type PaymentEvent, type PaymentReferenceCreator, type ProviderAdapter, type ScenarioName } from \"@bachsproof/core\";\nimport { bachsAdapter, signBachsWebhook } from \"@bachsproof/bachs\";\nimport type { BachsProofCliRun, BachsProofConfig, BachsProofSummary, RunConfigOptions } from \"./types.js\";\n\nconst SCENARIO_LABELS: Record<ScenarioName, string> = {\n \"sequential-duplicate-webhook\": \"Sequential duplicate webhook\",\n \"concurrent-duplicate-credit\": \"Concurrent duplicate credit\",\n \"concurrent-unique-payments\": \"Concurrent unique payments\",\n \"cross-event-duplicate-payment\": \"Cross-event duplicate payment\",\n \"out-of-order-events\": \"Out-of-order events\",\n \"incomplete-checkout\": \"Incomplete checkout\",\n \"expired-checkout\": \"Expired checkout\",\n \"incorrect-payment-amount\": \"Incorrect payment amount\",\n \"incorrect-payment-currency\": \"Incorrect payment currency\",\n \"underpaid-payment\": \"Underpaid payment\",\n \"failed-payment\": \"Failed payment\"\n};\n\nexport function scenarioLabel(scenario: ScenarioName): string {\n return SCENARIO_LABELS[scenario];\n}\n\nfunction assertConfig(value: unknown): asserts value is BachsProofConfig {\n if (!value || typeof value !== \"object\") throw new Error(\"BachsProof config must export a default object\");\n const config = value as Partial<BachsProofConfig>;\n if (typeof config.webhookUrl !== \"string\" || config.webhookUrl.trim().length === 0) {\n throw new Error(\"BachsProof config requires a complete webhookUrl\");\n }\n try {\n const url = new URL(config.webhookUrl);\n if (url.protocol !== \"http:\" && url.protocol !== \"https:\") throw new Error(\"webhookUrl must use http or https\");\n } catch (error) {\n throw new Error(`BachsProof config webhookUrl is invalid: ${error instanceof Error ? error.message : String(error)}`);\n }\n if (typeof config.secret !== \"string\" || config.secret.trim().length === 0) {\n throw new Error(\"BachsProof config requires a non-empty test webhook secret\");\n }\n if (!Number.isSafeInteger(config.amountMinor) || (config.amountMinor as number) < 0) {\n throw new Error(\"BachsProof config amountMinor must be a non-negative safe integer\");\n }\n if (typeof config.currency !== \"string\" || !/^[A-Z]{3}$/.test(config.currency)) {\n throw new Error(\"BachsProof config currency must be a three-letter ISO currency code\");\n }\n if (typeof config.createPayment !== \"function\") throw new Error(\"BachsProof config requires a createPayment callback\");\n if (typeof config.verify !== \"function\") throw new Error(\"BachsProof config requires a verify callback\");\n if (config.verificationTimeoutMs !== undefined && (!Number.isSafeInteger(config.verificationTimeoutMs) || config.verificationTimeoutMs < 1)) {\n throw new Error(\"BachsProof config verificationTimeoutMs must be a positive safe integer\");\n }\n if (config.scenarios !== undefined) {\n if (!Array.isArray(config.scenarios) || config.scenarios.length === 0) throw new Error(\"BachsProof config scenarios must contain at least one scenario\");\n for (const scenario of config.scenarios) {\n if (!(SUPPORTED_SCENARIOS as readonly string[]).includes(scenario)) {\n throw new Error(`Unknown BachsProof scenario: ${String(scenario)}`);\n }\n }\n }\n}\n\n/** Load a JavaScript, MJS, CJS, or TypeScript config file. */\nexport async function loadConfig(configPath = \"bachsproof.config.mjs\"): Promise<BachsProofConfig> {\n const absolutePath = resolve(process.cwd(), configPath);\n const jiti = createJiti(absolutePath, { interopDefault: true });\n const loaded = await jiti.import(absolutePath, { default: true }) as unknown;\n assertConfig(loaded);\n return loaded;\n}\n\nfunction withBachsSigning(provider: ProviderAdapter, secret: string): ProviderAdapter {\n return {\n ...provider,\n headers(event) {\n const body = provider.serialize(event);\n return {\n ...(provider.headers?.(event) ?? {}),\n ...signBachsWebhook(body, secret)\n };\n },\n headersForBody(event, body) {\n return {\n ...(provider.headersForBody?.(event, body) ?? provider.headers?.(event) ?? {}),\n ...signBachsWebhook(body, secret)\n };\n }\n };\n}\n\nfunction selectedScenarios(config: BachsProofConfig, testName?: string): ScenarioName[] {\n const scenarios = config.scenarios ?? [...SUPPORTED_SCENARIOS];\n if (!testName) return scenarios;\n const selected = scenarios.find((scenario) => scenarioLabel(scenario) === testName || scenario === testName);\n if (!selected) throw new Error(`Unknown BachsProof scenario or test name \"${testName}\". Use one of: ${scenarios.map(scenarioLabel).join(\", \")}`);\n return [selected];\n}\n\nexport async function runConfig(config: BachsProofConfig, options: RunConfigOptions = {}): Promise<BachsProofCliRun[]> {\n assertConfig(config);\n const scenarios = selectedScenarios(config, options.testName);\n const provider = withBachsSigning(bachsAdapter({ mode: \"mock\" }), config.secret);\n const usedReferences = new Set<string>();\n const createPayment: PaymentReferenceCreator = async (context) => {\n const reference = await config.createPayment(context);\n if (typeof reference !== \"string\" || reference.trim().length === 0) return reference as string;\n const normalized = reference.trim();\n if (usedReferences.has(normalized)) {\n throw new Error(`createPayment returned reference ${normalized}, which was already used by another selected scenario`);\n }\n usedReferences.add(normalized);\n return normalized;\n };\n const runner = new BachsProof({\n provider,\n webhookUrl: config.webhookUrl,\n createPayment,\n verify: config.verify,\n financialVerification: config.verificationTimeoutMs === undefined ? undefined : { completionDeadlineMs: config.verificationTimeoutMs }\n });\n const results: BachsProofCliRun[] = [];\n for (const scenario of scenarios) {\n const result = await runner.run({\n scenario,\n amountMinor: config.amountMinor,\n currency: config.currency\n });\n results.push({ name: scenarioLabel(scenario), scenario, result });\n }\n return results;\n}\n\nexport function summarizeRuns(results: BachsProofCliRun[]): BachsProofSummary {\n const durationMs = results.reduce((total, { result }) => {\n if (!result.report.completedAt) return total;\n return total + Math.max(0, Date.parse(result.report.completedAt) - Date.parse(result.report.startedAt));\n }, 0);\n return {\n total: results.length,\n passed: results.filter(({ result }) => result.passed).length,\n failed: results.filter(({ result }) => !result.passed).length,\n financiallyVerified: results.filter(({ result }) => result.report.financiallyVerified).length,\n financiallyUnverified: results.filter(({ result }) => !result.report.financiallyVerified).length,\n financialViolations: results.reduce((total, { result }) => total + (result.report.verification?.violations.length ?? 0), 0),\n durationMs\n };\n}\n\nexport { bachsAdapter, signBachsWebhook } from \"@bachsproof/bachs\";\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,59 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@bachsproof/cli",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "2.0.0",
|
|
4
|
+
"description": "CLI for BachsProof financial correctness testing",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"payments",
|
|
7
|
+
"payment-testing",
|
|
8
|
+
"webhooks",
|
|
9
|
+
"concurrency",
|
|
10
|
+
"cli",
|
|
11
|
+
"typescript"
|
|
12
|
+
],
|
|
13
|
+
"license": "MIT",
|
|
14
|
+
"repository": {
|
|
15
|
+
"type": "git",
|
|
16
|
+
"url": "git+https://github.com/therealEmma/BachsProof.git",
|
|
17
|
+
"directory": "packages/cli"
|
|
18
|
+
},
|
|
19
|
+
"homepage": "https://github.com/therealEmma/BachsProof#readme",
|
|
20
|
+
"bugs": {
|
|
21
|
+
"url": "https://github.com/therealEmma/BachsProof/issues"
|
|
22
|
+
},
|
|
23
|
+
"publishConfig": {
|
|
24
|
+
"access": "public"
|
|
25
|
+
},
|
|
26
|
+
"type": "module",
|
|
27
|
+
"bin": {
|
|
28
|
+
"bachsproof": "./dist/cli.js"
|
|
29
|
+
},
|
|
30
|
+
"exports": {
|
|
31
|
+
".": {
|
|
32
|
+
"types": "./dist/index.d.ts",
|
|
33
|
+
"import": "./dist/index.js"
|
|
34
|
+
}
|
|
35
|
+
},
|
|
36
|
+
"main": "./dist/index.js",
|
|
37
|
+
"types": "./dist/index.d.ts",
|
|
38
|
+
"files": [
|
|
39
|
+
"dist",
|
|
40
|
+
"README.md",
|
|
41
|
+
"LICENSE"
|
|
42
|
+
],
|
|
43
|
+
"engines": {
|
|
44
|
+
"node": ">=22"
|
|
45
|
+
},
|
|
46
|
+
"dependencies": {
|
|
47
|
+
"jiti": "^2.7.0",
|
|
48
|
+
"@bachsproof/core": "2.0.0",
|
|
49
|
+
"@bachsproof/bachs": "2.0.0"
|
|
50
|
+
},
|
|
51
|
+
"devDependencies": {
|
|
52
|
+
"@types/node": "^22.10.0",
|
|
53
|
+
"tsup": "^8.3.5",
|
|
54
|
+
"typescript": "^5.7.2"
|
|
55
|
+
},
|
|
56
|
+
"scripts": {
|
|
57
|
+
"build": "tsup"
|
|
58
|
+
}
|
|
6
59
|
}
|