@baseworks/invoice 0.1.1 → 1.1.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/README.md +81 -14
- package/dist/chunk-335MPCTE.js +133 -0
- package/dist/cli.js +58 -42
- package/dist/client.d.ts +216 -29
- package/dist/client.js +99 -23
- package/dist/events.d.ts +180 -69
- package/dist/events.js +5 -1
- package/dist/graphql.d.ts +22 -0
- package/dist/graphql.js +17 -2
- package/dist/mcp.d.ts +13 -0
- package/dist/mcp.js +146 -0
- package/dist/projections.js +55 -20
- package/package.json +14 -3
- package/src/__tests__/cli.test.ts +43 -25
- package/src/__tests__/client.test.ts +147 -0
- package/src/__tests__/dts-exports.test.ts +75 -0
- package/src/__tests__/mcp.test.ts +163 -0
- package/src/cli.ts +85 -60
- package/src/client.ts +78 -26
- package/src/compat.ts +61 -0
- package/src/events.ts +72 -22
- package/src/graphql.ts +17 -2
- package/src/mcp.ts +191 -0
- package/src/projections.ts +54 -19
- package/src/types.ts +208 -22
- package/dist/chunk-7P7ARN3X.js +0 -78
package/dist/projections.js
CHANGED
|
@@ -1,61 +1,96 @@
|
|
|
1
1
|
import {
|
|
2
2
|
InvoiceEvents,
|
|
3
3
|
TransactionEvents
|
|
4
|
-
} from "./chunk-
|
|
4
|
+
} from "./chunk-335MPCTE.js";
|
|
5
5
|
|
|
6
6
|
// src/projections.ts
|
|
7
7
|
import { defineProjection } from "@baseworks/foldbase";
|
|
8
8
|
var readInvoices = defineProjection("invoices", InvoiceEvents, (on) => ({
|
|
9
9
|
InvoiceDrafted: on.InvoiceDrafted.upsert((e) => ({
|
|
10
|
-
customer_id: e.
|
|
11
|
-
customer_name: e.
|
|
10
|
+
customer_id: e.customer_id,
|
|
11
|
+
customer_name: e.customer_name,
|
|
12
12
|
currency: e.currency,
|
|
13
13
|
lines: e.lines,
|
|
14
14
|
number: 0,
|
|
15
15
|
status: "draft",
|
|
16
|
-
subtotal_cents: e.
|
|
17
|
-
total_cents: e.
|
|
16
|
+
subtotal_cents: e.subtotal_cents,
|
|
17
|
+
total_cents: e.total_cents,
|
|
18
18
|
amount_paid_cents: 0,
|
|
19
19
|
issued_at: 0,
|
|
20
20
|
due_at: 0,
|
|
21
|
-
short_id: e.
|
|
21
|
+
short_id: e.short_id,
|
|
22
|
+
source: e.source ?? null,
|
|
23
|
+
metadata: e.metadata ?? null,
|
|
22
24
|
created_at: e.at
|
|
23
25
|
})),
|
|
24
26
|
InvoiceUpdated: on.InvoiceUpdated.upsert((e) => ({
|
|
25
|
-
customer_id: e.
|
|
26
|
-
customer_name: e.
|
|
27
|
+
customer_id: e.customer_id,
|
|
28
|
+
customer_name: e.customer_name,
|
|
27
29
|
lines: e.lines,
|
|
28
|
-
subtotal_cents: e.
|
|
29
|
-
total_cents: e.
|
|
30
|
+
subtotal_cents: e.subtotal_cents,
|
|
31
|
+
total_cents: e.total_cents,
|
|
32
|
+
metadata: e.metadata ?? null
|
|
30
33
|
})),
|
|
31
34
|
InvoiceFinalized: on.InvoiceFinalized.upsert((e) => ({
|
|
32
35
|
number: e.number,
|
|
33
36
|
status: "finalized",
|
|
34
37
|
lines: e.lines,
|
|
35
|
-
subtotal_cents: e.
|
|
36
|
-
total_cents: e.
|
|
37
|
-
issued_at: e.
|
|
38
|
-
due_at: e.
|
|
38
|
+
subtotal_cents: e.subtotal_cents,
|
|
39
|
+
total_cents: e.total_cents,
|
|
40
|
+
issued_at: e.issued_at,
|
|
41
|
+
due_at: e.due_at
|
|
39
42
|
})),
|
|
40
43
|
PaymentRecorded: on.PaymentRecorded.upsert((e) => ({
|
|
41
|
-
amount_paid_cents: e.
|
|
44
|
+
amount_paid_cents: e.amount_paid_cents,
|
|
42
45
|
status: e.status
|
|
43
46
|
})),
|
|
44
47
|
InvoiceVoided: on.InvoiceVoided.upsert(() => ({
|
|
45
48
|
status: "void"
|
|
49
|
+
})),
|
|
50
|
+
// The provider's whole document. `number` is 0 and stays 0: a mirror has no number of the organization's own.
|
|
51
|
+
InvoiceMirrored: on.InvoiceMirrored.upsert((e) => ({
|
|
52
|
+
source: e.source,
|
|
53
|
+
mirror_key: e.mirror_key,
|
|
54
|
+
external_refs: e.external_refs,
|
|
55
|
+
customer_id: e.customer_id,
|
|
56
|
+
customer_name: e.customer_name,
|
|
57
|
+
currency: e.currency,
|
|
58
|
+
lines: e.lines,
|
|
59
|
+
number: 0,
|
|
60
|
+
status: e.status,
|
|
61
|
+
subtotal_cents: e.subtotal_cents,
|
|
62
|
+
tax_cents: e.tax_cents,
|
|
63
|
+
total_cents: e.total_cents,
|
|
64
|
+
amount_paid_cents: e.amount_paid_cents,
|
|
65
|
+
issued_at: e.issued_at,
|
|
66
|
+
due_at: e.due_at,
|
|
67
|
+
paid_at: e.paid_at,
|
|
68
|
+
voided_at: e.voided_at,
|
|
69
|
+
provider_updated_at: e.provider_updated_at,
|
|
70
|
+
metadata: e.metadata,
|
|
71
|
+
short_id: e.short_id,
|
|
72
|
+
created_at: e.created_at
|
|
73
|
+
})),
|
|
74
|
+
InvoiceFiscalChanged: on.InvoiceFiscalChanged.upsert((e) => ({
|
|
75
|
+
fiscal_status: e.status,
|
|
76
|
+
fiscal_system: e.system,
|
|
77
|
+
fiscal_external_id: e.external_id,
|
|
78
|
+
fiscal_message: e.message,
|
|
79
|
+
fiscal_updated_at: e.at
|
|
46
80
|
}))
|
|
47
81
|
}));
|
|
48
82
|
var readTransactions = defineProjection("transactions", TransactionEvents, (on) => ({
|
|
49
83
|
TransactionRecorded: on.TransactionRecorded.upsert((e) => ({
|
|
50
|
-
invoice_id: e.
|
|
51
|
-
invoice_number: e.
|
|
52
|
-
customer_id: e.
|
|
53
|
-
customer_name: e.
|
|
84
|
+
invoice_id: e.invoice_id,
|
|
85
|
+
invoice_number: e.invoice_number,
|
|
86
|
+
customer_id: e.customer_id,
|
|
87
|
+
customer_name: e.customer_name,
|
|
54
88
|
kind: e.kind,
|
|
55
|
-
amount_cents: e.
|
|
89
|
+
amount_cents: e.amount_cents,
|
|
56
90
|
currency: e.currency,
|
|
57
91
|
method: e.method,
|
|
58
92
|
reference: e.reference,
|
|
93
|
+
payment_id: e.payment_id ?? null,
|
|
59
94
|
created_at: e.at
|
|
60
95
|
}))
|
|
61
96
|
}));
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@baseworks/invoice",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "1.1.0",
|
|
4
4
|
"description": "Invoice capability: typed HTTP client, event catalog, projections, and CLI plugin for invoice-service (AR ledger). Contract-first, versioned with the service.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"publishConfig": {
|
|
@@ -11,7 +11,8 @@
|
|
|
11
11
|
"./events": "./dist/events.js",
|
|
12
12
|
"./projections": "./dist/projections.js",
|
|
13
13
|
"./cli": "./dist/cli.js",
|
|
14
|
-
"./graphql": "./dist/graphql.js"
|
|
14
|
+
"./graphql": "./dist/graphql.js",
|
|
15
|
+
"./mcp": "./dist/mcp.js"
|
|
15
16
|
},
|
|
16
17
|
"files": [
|
|
17
18
|
"dist",
|
|
@@ -21,7 +22,8 @@
|
|
|
21
22
|
"@baseworks/cli": "^0.2.0",
|
|
22
23
|
"commander": "^15.0.0",
|
|
23
24
|
"zod": "^3.25.76",
|
|
24
|
-
"@baseworks/
|
|
25
|
+
"@baseworks/mcp": "^0.1.2",
|
|
26
|
+
"@baseworks/foldbase": "0.2.0"
|
|
25
27
|
},
|
|
26
28
|
"devDependencies": {
|
|
27
29
|
"@types/node": "^22.20.0",
|
|
@@ -29,8 +31,17 @@
|
|
|
29
31
|
"tsup": "^8.5.1",
|
|
30
32
|
"typescript": "^5.9.3",
|
|
31
33
|
"vitest": "^4.1.9",
|
|
34
|
+
"@modelcontextprotocol/sdk": "^1.32.2",
|
|
32
35
|
"@baseworks/tsconfig": "0.1.0"
|
|
33
36
|
},
|
|
37
|
+
"peerDependencies": {
|
|
38
|
+
"@modelcontextprotocol/sdk": "^1.32.0"
|
|
39
|
+
},
|
|
40
|
+
"peerDependenciesMeta": {
|
|
41
|
+
"@modelcontextprotocol/sdk": {
|
|
42
|
+
"optional": true
|
|
43
|
+
}
|
|
44
|
+
},
|
|
34
45
|
"scripts": {
|
|
35
46
|
"build": "tsup",
|
|
36
47
|
"typecheck": "tsc --noEmit",
|
|
@@ -10,28 +10,46 @@ afterAll(() => server.close())
|
|
|
10
10
|
|
|
11
11
|
const DRAFT = {
|
|
12
12
|
id: '019f6a3e-1111-7c71-beff-496d1be3fd1f',
|
|
13
|
-
|
|
13
|
+
short_id: 'inv9x2',
|
|
14
14
|
number: null,
|
|
15
15
|
status: 'draft',
|
|
16
|
-
|
|
17
|
-
|
|
16
|
+
customer_id: 'cst1',
|
|
17
|
+
customer_name: 'Acme Co',
|
|
18
18
|
currency: 'USD',
|
|
19
|
-
lines: [{ description: 'Consulting', quantity: 10,
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
19
|
+
lines: [{ description: 'Consulting', quantity: 10, unit_price_cents: 15000, amount_cents: 150000, product_id: null }],
|
|
20
|
+
subtotal_cents: 150000,
|
|
21
|
+
total_cents: 150000,
|
|
22
|
+
amount_paid_cents: 0,
|
|
23
|
+
balance_cents: 150000,
|
|
24
|
+
issued_at: null,
|
|
25
|
+
due_at: null,
|
|
26
|
+
created_at: 1784200000000,
|
|
27
27
|
updatedAt: 1784200000000,
|
|
28
28
|
}
|
|
29
|
-
const FINAL = { ...DRAFT, number: 1, status: 'finalized',
|
|
30
|
-
const PAID = { ...FINAL, status: 'paid',
|
|
29
|
+
const FINAL = { ...DRAFT, number: 1, status: 'finalized', issued_at: 1784200000000 }
|
|
30
|
+
const PAID = { ...FINAL, status: 'paid', amount_paid_cents: 150000, balance_cents: 0 }
|
|
31
|
+
|
|
32
|
+
describe('dtab invoices (list filters)', () => {
|
|
33
|
+
it('sends every filter, on the bare command and on ls, and shows the payment column', async () => {
|
|
34
|
+
let seen = ''
|
|
35
|
+
server.use(http.get(`${TEST_BASE}/invoices`, ({ request }) => {
|
|
36
|
+
seen = new URL(request.url).search
|
|
37
|
+
return HttpResponse.json({ invoices: [{ ...DRAFT, status: 'finalized', payment_status: 'unpaid' }] })
|
|
38
|
+
}))
|
|
39
|
+
const r = await run(['invoices', '--payment-status', 'unpaid,partially_paid', '--overdue', '--source', 'stripe', '--fiscal-status', 'queued', '--customer-id', 'cst1', '--status', 'finalized'])
|
|
40
|
+
expect(r.exitCode).toBe(0)
|
|
41
|
+
const q = Object.fromEntries(new URLSearchParams(seen))
|
|
42
|
+
expect(q).toEqual({ status: 'finalized', payment_status: 'unpaid,partially_paid', overdue: 'true', source: 'stripe', fiscal_status: 'queued', customer_id: 'cst1' })
|
|
43
|
+
expect(r.stdout).toContain('PAYMENT')
|
|
44
|
+
expect(r.stdout).toContain('unpaid')
|
|
45
|
+
await run(['invoices', 'ls', '--overdue', '--payment-status', 'paid'])
|
|
46
|
+
expect(Object.fromEntries(new URLSearchParams(seen))).toEqual({ payment_status: 'paid', overdue: 'true' })
|
|
47
|
+
})
|
|
48
|
+
})
|
|
31
49
|
|
|
32
50
|
describe('dtab invoices (list)', () => {
|
|
33
51
|
it('columns incl. NO/STATUS/TOTAL/BALANCE, draft NO shows —', async () => {
|
|
34
|
-
mocks.mockGet('/
|
|
52
|
+
mocks.mockGet('/invoices', { invoices: [DRAFT, FINAL] })
|
|
35
53
|
const r = await run(['invoices'])
|
|
36
54
|
expect(r.exitCode).toBe(0)
|
|
37
55
|
expect(r.stdout).toContain('inv9x2')
|
|
@@ -42,15 +60,15 @@ describe('dtab invoices (list)', () => {
|
|
|
42
60
|
})
|
|
43
61
|
|
|
44
62
|
it('inv + invoice aliases list', async () => {
|
|
45
|
-
mocks.mockGet('/
|
|
63
|
+
mocks.mockGet('/invoices', { invoices: [DRAFT] })
|
|
46
64
|
expect((await run(['inv'])).stdout).toContain('inv9x2')
|
|
47
|
-
mocks.mockGet('/
|
|
65
|
+
mocks.mockGet('/invoices', { invoices: [DRAFT] })
|
|
48
66
|
expect((await run(['invoice'])).stdout).toContain('inv9x2')
|
|
49
67
|
})
|
|
50
68
|
|
|
51
69
|
it('--status filter passes through', async () => {
|
|
52
70
|
let seen = ''
|
|
53
|
-
server.use(http.get(`${TEST_BASE}/
|
|
71
|
+
server.use(http.get(`${TEST_BASE}/invoices`, ({ request }) => {
|
|
54
72
|
seen = new URL(request.url).search
|
|
55
73
|
return HttpResponse.json({ invoices: [] })
|
|
56
74
|
}))
|
|
@@ -61,13 +79,13 @@ describe('dtab invoices (list)', () => {
|
|
|
61
79
|
|
|
62
80
|
describe('dtab invoices create', () => {
|
|
63
81
|
it('parses --line "desc|qty|price" → cents, sends customer + currency', async () => {
|
|
64
|
-
const cap = mocks.mockPostCapture('/
|
|
82
|
+
const cap = mocks.mockPostCapture('/invoices', { invoice: DRAFT })
|
|
65
83
|
const r = await run(['invoices', 'create', '--customer', 'cst1', '--currency', 'USD', '--line', 'Consulting|10|150.00'])
|
|
66
84
|
expect(r.exitCode).toBe(0)
|
|
67
85
|
const body = cap.body as Record<string, unknown>
|
|
68
|
-
expect(body.
|
|
86
|
+
expect(body.customer_id).toBe('cst1')
|
|
69
87
|
expect(body.currency).toBe('USD')
|
|
70
|
-
expect(body.lines).toEqual([{ description: 'Consulting', quantity: 10,
|
|
88
|
+
expect(body.lines).toEqual([{ description: 'Consulting', quantity: 10, unit_price_cents: 15000 }])
|
|
71
89
|
})
|
|
72
90
|
|
|
73
91
|
it('rejects malformed --line', async () => {
|
|
@@ -85,7 +103,7 @@ describe('dtab invoices create', () => {
|
|
|
85
103
|
|
|
86
104
|
describe('dtab invoices get / finalize / pay / void', () => {
|
|
87
105
|
it('get shows lines table + totals + balance', async () => {
|
|
88
|
-
mocks.mockGet('/
|
|
106
|
+
mocks.mockGet('/invoices/inv9x2', { invoice: FINAL })
|
|
89
107
|
const r = await run(['invoices', 'get', 'inv9x2'])
|
|
90
108
|
expect(r.stdout).toContain('Consulting')
|
|
91
109
|
expect(r.stdout).toContain('1500.00 USD')
|
|
@@ -93,23 +111,23 @@ describe('dtab invoices get / finalize / pay / void', () => {
|
|
|
93
111
|
})
|
|
94
112
|
|
|
95
113
|
it('finalize posts to /finalize, shows number', async () => {
|
|
96
|
-
mocks.mockPost('/
|
|
114
|
+
mocks.mockPost('/invoices/inv9x2/finalize', { invoice: FINAL })
|
|
97
115
|
const r = await run(['invoices', 'finalize', 'inv9x2'])
|
|
98
116
|
expect(r.stdout).toContain('#1')
|
|
99
117
|
})
|
|
100
118
|
|
|
101
119
|
it('pay converts --amount to cents, posts payment', async () => {
|
|
102
|
-
const cap = mocks.mockPostCapture('/
|
|
120
|
+
const cap = mocks.mockPostCapture('/invoices/inv9x2/payments', { invoice: PAID })
|
|
103
121
|
const r = await run(['invoices', 'pay', 'inv9x2', '--amount', '1500.00', '--method', 'bank'])
|
|
104
122
|
expect(r.exitCode).toBe(0)
|
|
105
123
|
const body = cap.body as Record<string, unknown>
|
|
106
|
-
expect(body.
|
|
124
|
+
expect(body.amount_cents).toBe(150000)
|
|
107
125
|
expect(body.method).toBe('bank')
|
|
108
126
|
expect(r.stdout).toContain('paid')
|
|
109
127
|
})
|
|
110
128
|
|
|
111
129
|
it('void posts to /void', async () => {
|
|
112
|
-
mocks.mockPost('/
|
|
130
|
+
mocks.mockPost('/invoices/inv9x2/void', { invoice: { ...FINAL, status: 'void' } })
|
|
113
131
|
const r = await run(['invoices', 'void', 'inv9x2', '--reason', 'mistake'])
|
|
114
132
|
expect(r.exitCode).toBe(0)
|
|
115
133
|
expect(r.stdout).toContain('inv9x2')
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @baseworks/invoice 0.3.0: the wire is snake_case. Options are `base_url` and `org_id` (`baseUrl`, `orgId`
|
|
3
|
+
* still read, deprecated). A caller that still speaks camelCase (billing, stripe) is sent as snake_case, and
|
|
4
|
+
* reads the old names on what comes back, without the old names appearing in the data.
|
|
5
|
+
*/
|
|
6
|
+
import { describe, expect, it } from 'vitest'
|
|
7
|
+
import { InvoiceClient, createInvoiceClient } from '../client.js'
|
|
8
|
+
|
|
9
|
+
const seen: Array<{ method: string; url: string; org: string | null; auth: string | null; body: unknown }> = []
|
|
10
|
+
const INVOICE = {
|
|
11
|
+
id: 'i1', short_id: 'sh1', number: 7, status: 'finalized', customer_id: 'c1', customer_name: 'Acme', currency: 'EUR',
|
|
12
|
+
lines: [{ description: 'x', quantity: 2, unit_price_cents: 500, amount_cents: 1000, product_id: null }],
|
|
13
|
+
subtotal_cents: 1000, total_cents: 1000, amount_paid_cents: 250, balance_cents: 750, issued_at: 5, due_at: null, created_at: 1, updated_at: 2,
|
|
14
|
+
}
|
|
15
|
+
const TXN = { id: 't1', invoice_id: 'i1', invoice_number: 7, customer_id: 'c1', customer_name: 'Acme', kind: 'payment', amount_cents: 250, currency: 'EUR', method: null, reference: 'R', created_at: 3 }
|
|
16
|
+
const f = (async (url: string, init?: RequestInit) => {
|
|
17
|
+
const h = new Headers(init?.headers)
|
|
18
|
+
seen.push({ method: init?.method ?? 'GET', url: String(url), org: h.get('x-org-id'), auth: h.get('authorization'), body: init?.body ? JSON.parse(String(init.body)) : undefined })
|
|
19
|
+
const path = new URL(String(url)).pathname
|
|
20
|
+
if (path.endsWith('/payments') && init?.method === 'GET') return new Response(JSON.stringify({ transactions: [TXN] }))
|
|
21
|
+
if (path.endsWith('/transactions')) return new Response(JSON.stringify({ transactions: [TXN] }))
|
|
22
|
+
if (path.endsWith('/invoices') && init?.method === 'GET') return new Response(JSON.stringify({ invoices: [INVOICE] }))
|
|
23
|
+
return new Response(JSON.stringify({ invoice: INVOICE }), { status: init?.method === 'POST' && path.endsWith('/invoices') ? 201 : 200 })
|
|
24
|
+
}) as unknown as typeof fetch
|
|
25
|
+
|
|
26
|
+
describe('options', () => {
|
|
27
|
+
it.each([
|
|
28
|
+
['snake_case', { base_url: 'http://i.test/api/', org_id: 'org-1' }],
|
|
29
|
+
['deprecated camelCase', { baseUrl: 'http://i.test/api/', orgId: 'org-1' }],
|
|
30
|
+
])('%s: the base, the org header and the token are the same', async (_n, o) => {
|
|
31
|
+
seen.length = 0
|
|
32
|
+
await createInvoiceClient({ ...o, token: 't', fetch: f }).list()
|
|
33
|
+
expect(seen).toEqual([{ method: 'GET', url: 'http://i.test/api/invoices', org: 'org-1', auth: 'Bearer t', body: undefined }])
|
|
34
|
+
})
|
|
35
|
+
it('withOrg moves to another org, whichever spelling the client was built with', async () => {
|
|
36
|
+
for (const o of [{ base_url: 'http://i.test' }, { baseUrl: 'http://i.test' }]) {
|
|
37
|
+
seen.length = 0
|
|
38
|
+
await new InvoiceClient({ ...o, org_id: 'org-1', fetch: f }).withOrg('org-2').list()
|
|
39
|
+
expect(seen[0]!.org).toBe('org-2')
|
|
40
|
+
}
|
|
41
|
+
})
|
|
42
|
+
it('needs a base', () => { expect(() => new InvoiceClient({})).toThrow(/base_url/) })
|
|
43
|
+
})
|
|
44
|
+
|
|
45
|
+
describe('what comes back', () => {
|
|
46
|
+
it('is the service\'s snake_case, and the old names read the same values', async () => {
|
|
47
|
+
const c = new InvoiceClient({ base_url: 'http://i.test', fetch: f })
|
|
48
|
+
const inv = await c.get('i1')
|
|
49
|
+
expect(inv.total_cents).toBe(1000)
|
|
50
|
+
expect(inv.totalCents).toBe(1000) // deprecated
|
|
51
|
+
expect(inv.shortId).toBe('sh1')
|
|
52
|
+
expect(inv.customerName).toBe('Acme')
|
|
53
|
+
expect(inv.balanceCents).toBe(750)
|
|
54
|
+
expect(inv.dueAt).toBeNull()
|
|
55
|
+
expect(inv.lines[0]!.unitPriceCents).toBe(500)
|
|
56
|
+
expect(inv.lines[0]!.unit_price_cents).toBe(500)
|
|
57
|
+
expect((await c.list())[0]!.createdAt).toBe(1)
|
|
58
|
+
const [t] = await c.invoiceTransactions('i1')
|
|
59
|
+
expect([t!.amountCents, t!.invoiceNumber, t!.customerId, t!.createdAt]).toEqual([250, 7, 'c1', 3])
|
|
60
|
+
expect((await c.transactions())[0]!.amount_cents).toBe(250)
|
|
61
|
+
})
|
|
62
|
+
it('the old names are not data: JSON and equality see the snake_case object only', async () => {
|
|
63
|
+
const inv = await new InvoiceClient({ base_url: 'http://i.test', fetch: f }).get('i1')
|
|
64
|
+
expect(JSON.parse(JSON.stringify(inv))).toEqual(INVOICE)
|
|
65
|
+
expect(inv).toEqual(INVOICE)
|
|
66
|
+
expect(Object.keys(inv).some((k) => /[A-Z]/.test(k))).toBe(false)
|
|
67
|
+
})
|
|
68
|
+
})
|
|
69
|
+
|
|
70
|
+
describe('what goes out', () => {
|
|
71
|
+
const c = () => new InvoiceClient({ base_url: 'http://i.test', fetch: f })
|
|
72
|
+
it('camelCase input is sent as snake_case', async () => {
|
|
73
|
+
seen.length = 0
|
|
74
|
+
await c().create({ customerId: 'c1', currency: 'EUR', lines: [{ description: 'x', quantity: 2, unitPriceCents: 500, productId: 'p' }] })
|
|
75
|
+
await c().update('i1', { customerId: 'c2', lines: [{ description: 'y', quantity: 1, unitPriceCents: 1 }] })
|
|
76
|
+
await c().finalize('i1', { issuedAt: 5, dueAt: 9 })
|
|
77
|
+
await c().recordPayment('i1', { amountCents: 100, method: 'bank' })
|
|
78
|
+
expect(seen.map((s) => s.body)).toEqual([
|
|
79
|
+
{ customer_id: 'c1', currency: 'EUR', lines: [{ description: 'x', quantity: 2, unit_price_cents: 500, product_id: 'p' }] },
|
|
80
|
+
{ customer_id: 'c2', lines: [{ description: 'y', quantity: 1, unit_price_cents: 1 }] },
|
|
81
|
+
{ issued_at: 5, due_at: 9 },
|
|
82
|
+
{ amount_cents: 100, method: 'bank' },
|
|
83
|
+
])
|
|
84
|
+
})
|
|
85
|
+
it('snake_case input is sent as it is, and the new name wins when both are given', async () => {
|
|
86
|
+
seen.length = 0
|
|
87
|
+
await c().create({ customer_id: 'c1', customerId: 'old', currency: 'EUR', lines: [{ description: 'x', quantity: 1, unit_price_cents: 5, unitPriceCents: 9 }] })
|
|
88
|
+
await c().recordPayment('i1', { amount_cents: 7, amountCents: 8 })
|
|
89
|
+
expect(seen.map((s) => s.body)).toEqual([
|
|
90
|
+
{ customer_id: 'c1', currency: 'EUR', lines: [{ description: 'x', quantity: 1, unit_price_cents: 5 }] },
|
|
91
|
+
{ amount_cents: 7 },
|
|
92
|
+
])
|
|
93
|
+
})
|
|
94
|
+
})
|
|
95
|
+
|
|
96
|
+
describe('1.1.0: the list filters, the mirror, the fiscal state', () => {
|
|
97
|
+
const sent: Array<{ method: string; url: string; body: unknown }> = []
|
|
98
|
+
const g = (async (url: string, init?: RequestInit) => {
|
|
99
|
+
sent.push({ method: init?.method ?? 'GET', url: String(url), body: init?.body ? JSON.parse(String(init.body)) : undefined })
|
|
100
|
+
if (String(url).includes('/mirror')) return new Response(JSON.stringify({ invoice: INVOICE, created: true }))
|
|
101
|
+
if (init?.method === 'POST') return new Response(JSON.stringify({ invoice: INVOICE }))
|
|
102
|
+
if (String(url).includes('/fiscal')) return new Response(JSON.stringify({ invoice: { ...INVOICE, fiscal: { status: 'queued' } } }))
|
|
103
|
+
return new Response(JSON.stringify({ invoices: [INVOICE] }))
|
|
104
|
+
}) as unknown as typeof fetch
|
|
105
|
+
const c = () => new InvoiceClient({ base_url: 'http://i.test/api', fetch: g })
|
|
106
|
+
|
|
107
|
+
it('list sends every filter, several payment statuses comma-separated', async () => {
|
|
108
|
+
sent.length = 0
|
|
109
|
+
await c().list({ status: 'finalized', payment_status: ['unpaid', 'partially_paid'], overdue: true, source: 'stripe', fiscal_status: 'queued', customer_id: 'c1', limit: 5 })
|
|
110
|
+
const q = new URL(sent[0]!.url).searchParams
|
|
111
|
+
expect(Object.fromEntries(q)).toEqual({ limit: '5', status: 'finalized', payment_status: 'unpaid,partially_paid', overdue: 'true', source: 'stripe', fiscal_status: 'queued', customer_id: 'c1' })
|
|
112
|
+
sent.length = 0
|
|
113
|
+
await c().list({ payment_status: 'paid', overdue: false })
|
|
114
|
+
expect(Object.fromEntries(new URL(sent[0]!.url).searchParams)).toEqual({ payment_status: 'paid', overdue: 'false' })
|
|
115
|
+
})
|
|
116
|
+
it('mirror PUTs the whole document; setFiscal PUTs the state; both read the old names too', async () => {
|
|
117
|
+
sent.length = 0
|
|
118
|
+
const doc = { source: 'stripe' as const, external_ref: { system: 'stripe', id: 'in_1' }, customer_id: 'c1', currency: 'USD', lines: [], subtotal_cents: 0, tax_cents: 0, total_cents: 0, status: 'finalized' as const, issued_at: 1, provider_updated_at: 2 }
|
|
119
|
+
const r = await c().mirror(doc)
|
|
120
|
+
expect(sent[0]).toEqual({ method: 'PUT', url: 'http://i.test/api/invoices/mirror', body: doc })
|
|
121
|
+
expect(r.created).toBe(true)
|
|
122
|
+
expect(r.invoice.totalCents).toBe(1000)
|
|
123
|
+
const inv = await c().setFiscal('i1', { status: 'queued', system: 'gib' })
|
|
124
|
+
expect(sent[1]).toEqual({ method: 'PUT', url: 'http://i.test/api/invoices/i1/fiscal', body: { status: 'queued', system: 'gib' } })
|
|
125
|
+
expect(inv.fiscal?.status).toBe('queued')
|
|
126
|
+
})
|
|
127
|
+
it('recordPayment sends payment_id', async () => {
|
|
128
|
+
sent.length = 0
|
|
129
|
+
await c().recordPayment('i1', { amount_cents: 5, payment_id: 'pay_1' })
|
|
130
|
+
expect(sent[0]!.body).toEqual({ amount_cents: 5, payment_id: 'pay_1' })
|
|
131
|
+
})
|
|
132
|
+
})
|
|
133
|
+
|
|
134
|
+
describe('the source is snake_case', () => {
|
|
135
|
+
it('compat.ts is the only place the old names live', async () => {
|
|
136
|
+
const { readdirSync, readFileSync } = await import('node:fs')
|
|
137
|
+
const { resolve, join, dirname } = await import('node:path')
|
|
138
|
+
const { fileURLToPath } = await import('node:url')
|
|
139
|
+
const src = resolve(dirname(fileURLToPath(import.meta.url)), '..')
|
|
140
|
+
const OLD = /\.(customerId|customerName|shortId|subtotalCents|totalCents|amountPaidCents|balanceCents|issuedAt|dueAt|createdAt|updatedAt|unitPriceCents|amountCents|productId|invoiceId|invoiceNumber|userId|orgId|baseUrl)\b/
|
|
141
|
+
// cli.ts is left out: `opts.customerId` is the name commander gives `--customer-id`
|
|
142
|
+
for (const f of readdirSync(src).filter((x) => x.endsWith('.ts') && !['compat.ts', 'graphql.ts', 'cli.ts'].includes(x))) {
|
|
143
|
+
const hits = readFileSync(join(src, f), 'utf8').split('\n').map((l, i) => [i + 1, l] as const).filter(([, l]) => OLD.test(l) && !/deprecated|Deprecated/i.test(l))
|
|
144
|
+
expect(hits, f).toEqual([])
|
|
145
|
+
}
|
|
146
|
+
})
|
|
147
|
+
})
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import { execSync } from 'node:child_process'
|
|
2
|
+
import { existsSync, readdirSync, readFileSync } from 'node:fs'
|
|
3
|
+
import { dirname, join, resolve } from 'node:path'
|
|
4
|
+
import { fileURLToPath } from 'node:url'
|
|
5
|
+
import { beforeAll, describe, expect, it } from 'vitest'
|
|
6
|
+
import ts from 'typescript'
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* A consumer sees the .d.ts, not the sources. A type named in an exported signature that the package does not export
|
|
10
|
+
* cannot be named by the consumer (it had to be re-declared, as `AddressPatch` was). For every entry's declaration
|
|
11
|
+
* file: whatever the exported declarations reference, in the same file, must itself be exported.
|
|
12
|
+
*/
|
|
13
|
+
const root = resolve(dirname(fileURLToPath(import.meta.url)), '../..')
|
|
14
|
+
const dist = join(root, 'dist')
|
|
15
|
+
|
|
16
|
+
beforeAll(() => { execSync('npx tsup', { cwd: root, stdio: 'ignore' }) }, 180_000)
|
|
17
|
+
|
|
18
|
+
function unexportedButReferenced(file: string): string[] {
|
|
19
|
+
const sf = ts.createSourceFile(file, readFileSync(file, 'utf8'), ts.ScriptTarget.ES2022, true)
|
|
20
|
+
const declared = new Map<string, ts.Node>()
|
|
21
|
+
const exported = new Set<string>()
|
|
22
|
+
const hasExport = (n: ts.Node) => !!(ts.canHaveModifiers(n) && ts.getModifiers(n)?.some((m) => m.kind === ts.SyntaxKind.ExportKeyword))
|
|
23
|
+
for (const st of sf.statements) {
|
|
24
|
+
if (ts.isExportDeclaration(st) && st.exportClause && ts.isNamedExports(st.exportClause)) {
|
|
25
|
+
if (!st.moduleSpecifier) for (const e of st.exportClause.elements) exported.add((e.propertyName ?? e.name).text)
|
|
26
|
+
} else if (ts.isInterfaceDeclaration(st) || ts.isTypeAliasDeclaration(st) || ts.isClassDeclaration(st) || ts.isFunctionDeclaration(st) || ts.isEnumDeclaration(st)) {
|
|
27
|
+
if (st.name) { declared.set(st.name.text, st); if (hasExport(st)) exported.add(st.name.text) }
|
|
28
|
+
} else if (ts.isVariableStatement(st)) {
|
|
29
|
+
for (const d of st.declarationList.declarations) if (ts.isIdentifier(d.name)) { declared.set(d.name.text, st); if (hasExport(st)) exported.add(d.name.text) }
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
// names used by a declaration (types and `typeof x`), ignoring its own type parameters
|
|
33
|
+
const refs = (node: ts.Node): string[] => {
|
|
34
|
+
const out: string[] = []
|
|
35
|
+
const visit = (n: ts.Node) => {
|
|
36
|
+
if (ts.isTypeReferenceNode(n) && ts.isIdentifier(n.typeName)) out.push(n.typeName.text)
|
|
37
|
+
if (ts.isExpressionWithTypeArguments(n) && ts.isIdentifier(n.expression)) out.push(n.expression.text)
|
|
38
|
+
if (ts.isTypeQueryNode(n) && ts.isIdentifier(n.exprName)) out.push(n.exprName.text)
|
|
39
|
+
ts.forEachChild(n, visit)
|
|
40
|
+
}
|
|
41
|
+
visit(node)
|
|
42
|
+
return out
|
|
43
|
+
}
|
|
44
|
+
const bad = new Set<string>()
|
|
45
|
+
const seen = new Set<string>()
|
|
46
|
+
const queue = [...exported]
|
|
47
|
+
while (queue.length) {
|
|
48
|
+
const name = queue.pop()!
|
|
49
|
+
if (seen.has(name)) continue
|
|
50
|
+
seen.add(name)
|
|
51
|
+
const node = declared.get(name)
|
|
52
|
+
if (!node) continue
|
|
53
|
+
for (const r of refs(node)) {
|
|
54
|
+
if (!declared.has(r)) continue // a global, a type parameter, or imported from another package
|
|
55
|
+
if (!exported.has(r)) bad.add(r)
|
|
56
|
+
queue.push(r)
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
return [...bad].sort()
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
describe('the declaration files', () => {
|
|
63
|
+
it('every entry exports every type its exported signatures name', () => {
|
|
64
|
+
const files = readdirSync(dist).filter((f) => f.endsWith('.d.ts'))
|
|
65
|
+
expect(files.length).toBeGreaterThan(3)
|
|
66
|
+
const report: Record<string, string[]> = {}
|
|
67
|
+
for (const f of files) { const bad = unexportedButReferenced(join(dist, f)); if (bad.length) report[f] = bad }
|
|
68
|
+
expect(report).toEqual({})
|
|
69
|
+
})
|
|
70
|
+
|
|
71
|
+
it('the deprecated aliases are types a caller can name', () => {
|
|
72
|
+
const d = readFileSync(join(dist, 'client.d.ts'), 'utf8')
|
|
73
|
+
for (const n of ['InvoiceDeprecated', 'InvoiceLineDeprecated', 'TransactionDeprecated']) expect(d).toMatch(new RegExp(`export \\{[^}]*\\b${n}\\b`))
|
|
74
|
+
})
|
|
75
|
+
})
|