@billionaire-sh/node-sdk 0.0.0-stage → 1.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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Kolaveri Labs
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,284 @@
1
- # Temporary Holding Version
1
+ # billionaire Node.js SDK
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A TypeScript-first Node.js SDK for integrating with billionaire, the accounting and tax platform. This SDK provides a simple, type-safe interface to the billionaire API: the invoices an entity issues, its bookkeeping, and everything else billionaire keeps for it.
4
+
5
+ ## Overview
6
+
7
+ billionaire keeps the books of an entity — its invoices, bookings, payments and tax returns. Other platforms do not invoice on their own: they hand what they charged to billionaire through this SDK, and the entity that owns the platform issues its invoice, books the revenue and settles the payment, all with billionaire's one invoicing engine. The platforms stay loosely coupled: they know billionaire only through its API and this SDK.
8
+
9
+ ### Key Features
10
+
11
+ - 🔐 **OAuth2 Authentication** - Secure client credentials flow with automatic token management
12
+ - 🏢 **Multi-Tenant Support** - Every call acts for one entity; a robot account is granted the entities it may act for
13
+ - 📝 **TypeScript Support** - Full TypeScript support with auto-generated types from OpenAPI spec
14
+ - 🔄 **Auto Token Refresh** - Automatic token renewal with 5-minute buffer before expiration
15
+ - 🎯 **Type-Safe API** - OpenAPI-generated types ensure type safety across all operations
16
+ - ⚡ **Modern Architecture** - Built with ES modules and CommonJS dual support
17
+
18
+ ## Installation
19
+
20
+ ```bash
21
+ npm install @billionaire-sh/node-sdk
22
+ # or
23
+ yarn add @billionaire-sh/node-sdk
24
+ # or
25
+ pnpm add @billionaire-sh/node-sdk
26
+ ```
27
+
28
+ ## Quick Start
29
+
30
+ ```typescript
31
+ import { BLNRClient } from '@billionaire-sh/node-sdk'
32
+
33
+ // Initialize the client
34
+ const client = new BLNRClient({
35
+ clientId: 'your-client-id',
36
+ clientSecret: 'your-client-secret',
37
+ entityId: 'your-entity-id', // Optional - will use default from token if not provided
38
+ baseUrl: 'https://billionaire.sh/api', // Optional - defaults to production
39
+ })
40
+
41
+ // `platformInvoices` is the platform's own API (`/platform/invoices`): it
42
+ // acts for the entity that owns the platform, so the robot needs its grant
43
+ // there — `entityId` plays no part in it.
44
+
45
+ // Before charging: the invoice the entity would issue, nothing issued
46
+ const preview = await client.platformInvoices.preview({
47
+ currency: 'EUR',
48
+ issuedAt: new Date().toISOString(),
49
+ grossAmount: 11781,
50
+ lines: [/* … each line's net, tax and rate, as it will be charged */],
51
+ // Whom for, described as on `process` — its tax is read by the same rule;
52
+ // null where the customer cannot be described yet
53
+ customer: { /* reference, partyType, name, email, vatId, taxNumber, address */ },
54
+ })
55
+ // preview.invoice?.netAmount, .taxAmount, .grossAmount, .byRate, .lines
56
+
57
+ // The platform charged a customer: the entity issues its invoice for it
58
+ const { outcome, invoiceId } = await client.platformInvoices.process({
59
+ platform: 'order3000',
60
+ stripeInvoiceId: 'in_1QxYz…',
61
+ // … the customer, the lines and the totals the platform charged
62
+ })
63
+
64
+ // Paid, voided and credited invoices follow the same way
65
+ await client.platformInvoices.processPayment('in_1QxYz…', { /* … */ })
66
+ await client.platformInvoices.processVoid('in_1QxYz…', { voidedAt })
67
+ await client.platformInvoices.processCredit('in_1QxYz…', {
68
+ stripeCreditNoteId: 'cn_1QxYz…',
69
+ creditedAt,
70
+ grossAmount: 2380,
71
+ netAmount: 2000,
72
+ // A credit note for part of the invoice corrects it by these lines
73
+ lines: [
74
+ {
75
+ invoiceLineIndex: 1,
76
+ description: 'Module',
77
+ quantity: 1,
78
+ netAmount: 2000,
79
+ taxAmount: 380,
80
+ taxRatePercent: 19,
81
+ isReverseCharge: false,
82
+ taxCountry: null,
83
+ },
84
+ ],
85
+ })
86
+
87
+ // The platform's invoices the entity still shows as unpaid, for a
88
+ // follow-up that asks the payment provider about each
89
+ const open = await client.platformInvoices.listOpen({
90
+ filters: { platform: 'order3000' },
91
+ pagination: { page: 1, pageSize: 100 },
92
+ })
93
+ for (const invoice of open) console.log(invoice.stripeInvoiceId)
94
+
95
+ // A paying customer's details changed: the entity's party for it takes them
96
+ const { partyId } = await client.platformCustomers.process({
97
+ platform: 'order3000',
98
+ customer, // its reference, legal name, email, VAT ID and invoice address
99
+ })
100
+ // … and reads back as the books keep it (HTTP 404 while none is kept)
101
+ const party = await client.platformCustomers.get({
102
+ platform: 'order3000',
103
+ reference: customer.reference,
104
+ })
105
+ ```
106
+
107
+ ## Type naming convention
108
+
109
+ Every exported name in this SDK carries a **`BLNR`** prefix
110
+ (`BLNRClient`, `BLNRProcessPlatformInvoiceRequest`, …). The prefix
111
+ namespaces the SDK surface so consumer code never has to alias imports to
112
+ disambiguate them from local domain types:
113
+
114
+ ```typescript
115
+ // no `as SDKFoo` aliasing needed — the name is already namespaced
116
+ import type { BLNRProcessPlatformInvoiceRequest } from '@billionaire-sh/node-sdk'
117
+ ```
118
+
119
+ ## Architecture
120
+
121
+ ### Authentication Flow
122
+
123
+ The SDK uses OAuth2 client credentials flow for authentication:
124
+
125
+ 1. **Initial Authentication**: On first use, the SDK requests an access token using your client credentials
126
+ 2. **Token Storage**: The access token is stored in memory with its expiration time
127
+ 3. **Automatic Refresh**: Tokens are automatically refreshed 5 minutes before expiration
128
+ 4. **Entity Resolution**: If no entity ID is provided, the SDK extracts the default entity from the JWT token
129
+
130
+ ### Project Structure
131
+
132
+ ```
133
+ billionaire-node-sdk/
134
+ ├── src/
135
+ │ ├── client.ts # Main client class and initialization
136
+ │ ├── token-manager.ts # OAuth2 token management and refresh logic
137
+ │ ├── resources/
138
+ │ │ ├── index.ts # Base resource class for API calls
139
+ │ │ ├── platformCustomers.ts # Platform customers resource implementation
140
+ │ │ └── platformInvoices.ts # Platform invoices resource implementation
141
+ │ └── types/
142
+ │ ├── index.ts # Type exports
143
+ │ └── generated.d.ts # Auto-generated types from OpenAPI spec
144
+ ├── scripts/
145
+ │ ├── dev.sh # Development script with Vault integration
146
+ │ └── vaultcar.sh # HashiCorp Vault integration for secrets
147
+ └── package.json
148
+ ```
149
+
150
+ ## Configuration
151
+
152
+ ### Client Options
153
+
154
+ ```typescript
155
+ interface BLNRClientConfig {
156
+ clientId: string // OAuth2 client ID (required)
157
+ clientSecret: string // OAuth2 client secret (required)
158
+ entityId?: string // Specific entity ID (optional)
159
+ baseUrl?: string // Base URL for API requests (default: https://billionaire.sh/api)
160
+ tokenUrl?: string // OAuth2 token endpoint (default: ${baseUrl}/m2m/token)
161
+ }
162
+ ```
163
+
164
+ ### Environment Variables
165
+
166
+ For development, you can use environment variables:
167
+
168
+ ```bash
169
+ BILLIONAIRE_CLIENT_ID=your-client-id
170
+ BILLIONAIRE_CLIENT_SECRET=your-client-secret
171
+ BILLIONAIRE_BASE_URL=https://billionaire.sh/api
172
+ ```
173
+
174
+ ## API Documentation
175
+
176
+ The OpenAPI document is served by billionaire itself:
177
+
178
+ - **Development**: http://localhost:8000/api/openapi
179
+ - **Staging**: https://staging.billionaire.sh/api/openapi
180
+ - **Production**: https://billionaire.sh/api/openapi
181
+
182
+ ## SDK Development Workflow
183
+
184
+ ### Adding New API Endpoints
185
+
186
+ When new endpoints are added or modified in billionaire, follow this workflow to update the SDK:
187
+
188
+ 1. **Define API Contracts**: Create or update TypeScript contracts that define the API structure
189
+ - Add/modify contracts in `/apps/billionaire/billionaire/src/app/api/openapi/contracts/`
190
+ - Use `@ts-rest/core` to define type-safe contracts
191
+ - Export contracts from `/apps/billionaire/billionaire/src/app/api/openapi/contract.ts`
192
+ - Write the OpenAPI document: `npm run build:openapi-json` in `apps/billionaire/billionaire`
193
+
194
+ 2. **Implement API Endpoints**: Create the actual endpoint logic in billionaire
195
+ - Implement handlers in `/apps/billionaire/billionaire/src/app/api/entities/[entityIdOrAccessor]/` following the contract definitions — or, for the platform's own API, in `/apps/billionaire/billionaire/src/app/api/platform/`, which acts for the entity that owns the platform (its resource overrides `rootPath()`)
196
+ - Each handler is a thin proxy over a server action declaring `permissions: ['iam:robot', …]`
197
+ - Ensure endpoints match the contracts exactly
198
+
199
+ 3. **Update SDK Resources**: Integrate the new endpoints into the SDK
200
+ - Create or update resource classes in `/libs/billionaire/node-sdk/src/resources/`
201
+ - Follow the existing pattern extending from `BaseResource`
202
+ - Export new resources from the main `BLNRClient` class
203
+ - After the OpenAPI document changed, run `npm run generate` (types and zod schemas) and keep the result: the generated files are tracked
204
+ - `npm run build` only bundles — it never rewrites `src`, so a checkout that merely builds the SDK stays clean; publishing (`prepack`) generates first
205
+
206
+ 4. **Create Changeset**: Document the changes
207
+
208
+ ```bash
209
+ pnpm changeset
210
+ ```
211
+
212
+ - Select `billionaire` package
213
+ - Choose version bump type (patch/minor/major)
214
+ - Describe the new endpoints or changes added
215
+
216
+ ### Local Development
217
+
218
+ ```bash
219
+ # Generate types and zod schemas from the OpenAPI spec (tracked files)
220
+ npm run generate
221
+
222
+ # Bundle the package locally (does not regenerate)
223
+ npm run build
224
+
225
+ # Test SDK in development mode
226
+ npm run dev
227
+ ```
228
+
229
+ ### Development with Vault
230
+
231
+ The SDK includes HashiCorp Vault integration for secure credential management:
232
+
233
+ ```bash
234
+ # Run with Vault integration
235
+ npm run dev
236
+ ```
237
+
238
+ Credentials are fetched from:
239
+
240
+ - `secret/order3000/BILLIONAIRE_CLIENT_ID`
241
+ - `secret/order3000/BILLIONAIRE_CLIENT_SECRET`
242
+ - `secret/order3000/BILLIONAIRE_BASE_URL`
243
+
244
+ ## Security Considerations
245
+
246
+ 1. **Never commit credentials** - Always use environment variables or secret management systems
247
+ 2. **Token Security** - Access tokens are stored in memory only, never persisted to disk
248
+ 3. **HTTPS Only** - All API calls are made over HTTPS
249
+ 4. **Automatic Token Rotation** - Tokens are refreshed automatically before expiration
250
+
251
+ ## Error Handling
252
+
253
+ A failed call throws an `Error` whose message starts with the HTTP status and carries the response body:
254
+
255
+ ```typescript
256
+ try {
257
+ await client.platformInvoices.process(request)
258
+ } catch (error) {
259
+ // "HTTP 400: Bad Request — {"error":"…"}"
260
+ console.error(error)
261
+ }
262
+ ```
263
+
264
+ ## Platform Integration
265
+
266
+ ### Multi-Tenant Architecture
267
+
268
+ Every call acts for one entity:
269
+
270
+ - **Automatic Entity Resolution**: If no entity ID is provided, the SDK uses the default entity from the authentication token
271
+ - **Explicit Entity Selection**: You can specify an entity ID in the client configuration
272
+ - **Entity Isolation**: All operations are scoped to the specified entity, and a robot account acts only for the entities it is granted
273
+
274
+ ## Contributing
275
+
276
+ This SDK is part of the Kolaveri monorepo. Development follows the monorepo conventions:
277
+
278
+ 1. Follow TypeScript strict mode
279
+ 2. Run linting before commits: `npx nx lint billionaire-node-sdk`
280
+ 3. Generate types from OpenAPI spec when API changes
281
+
282
+ ## License
283
+
284
+ Part of the Kolaveri platform - see root repository for license information.