kumpara 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +205 -2
- package/dist/cjs/client.d.ts +62 -0
- package/dist/cjs/client.js +148 -0
- package/dist/cjs/errors.d.ts +53 -0
- package/dist/cjs/errors.js +106 -0
- package/dist/cjs/index.d.ts +8 -0
- package/dist/cjs/index.js +32 -0
- package/dist/cjs/package.json +1 -0
- package/dist/cjs/resources.d.ts +72 -0
- package/dist/cjs/resources.js +136 -0
- package/dist/cjs/types.d.ts +132 -0
- package/dist/cjs/types.js +6 -0
- package/dist/cjs/webhook.d.ts +24 -0
- package/dist/cjs/webhook.js +69 -0
- package/dist/esm/client.d.ts +62 -0
- package/dist/esm/client.js +144 -0
- package/dist/esm/errors.d.ts +53 -0
- package/dist/esm/errors.js +90 -0
- package/dist/esm/index.d.ts +8 -0
- package/dist/esm/index.js +5 -0
- package/dist/esm/resources.d.ts +72 -0
- package/dist/esm/resources.js +129 -0
- package/dist/esm/types.d.ts +132 -0
- package/dist/esm/types.js +5 -0
- package/dist/esm/webhook.d.ts +24 -0
- package/dist/esm/webhook.js +64 -0
- package/package.json +49 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Nufel Web Hosting
|
|
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,206 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Kumpara for Node.js
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
[](https://github.com/nufel-web-hosting/kumpara-node/actions/workflows/ci.yml)
|
|
4
|
+
[](https://www.npmjs.com/package/kumpara)
|
|
5
|
+
[](LICENSE)
|
|
6
|
+
|
|
7
|
+
Offisielt Node.js-bibliotek for [Kumpara](https://kumpara.no): lag, send og følg opp norske fakturaer med KID og PDF fra din egen kode.
|
|
8
|
+
|
|
9
|
+
*The official Node.js SDK for Kumpara, the Norwegian invoicing API: create and send invoices with KID, PDF and webhooks from your own code.*
|
|
10
|
+
|
|
11
|
+
- Kunder, varer, fakturaer og kreditnotaer
|
|
12
|
+
- KID med MOD10 eller MOD11, fortløpende fakturanummer uten hull
|
|
13
|
+
- PDF og e-post til kunden
|
|
14
|
+
- Webhooks med signaturkontroll
|
|
15
|
+
- Kontoer for kundene dine (`tenants`)
|
|
16
|
+
- Trygge nye forsøk: `externalRef` gjør at ingenting blir dobbelt
|
|
17
|
+
- TypeScript-typer med, ingen avhengigheter, virker med både `import` og `require`
|
|
18
|
+
|
|
19
|
+
Kumpara flytter aldri penger. «Betalt» er en markering du eller systemet ditt gjør.
|
|
20
|
+
|
|
21
|
+
## Installer
|
|
22
|
+
|
|
23
|
+
```bash
|
|
24
|
+
npm install kumpara
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
Krever Node.js 20 eller nyere.
|
|
28
|
+
|
|
29
|
+
## Kom i gang
|
|
30
|
+
|
|
31
|
+
Lag en nøkkel i Kumpara under **Utviklerverktøy → API**. Start med en **Test**-nøkkel (`kp_test_...`): egen testkonto, «TEST» på PDF-en, og ingen e-post går til kunder.
|
|
32
|
+
|
|
33
|
+
Legg nøkkelen i miljøvariabelen `KUMPARA_API_KEY`. Aldri i koden, og aldri i nettleseren: biblioteket er for serveren din.
|
|
34
|
+
|
|
35
|
+
```js
|
|
36
|
+
import { Kumpara } from 'kumpara';
|
|
37
|
+
|
|
38
|
+
const kumpara = new Kumpara(); // leser KUMPARA_API_KEY
|
|
39
|
+
|
|
40
|
+
const customer = await kumpara.customers.create({
|
|
41
|
+
type: 'company',
|
|
42
|
+
name: 'Fjord Design AS',
|
|
43
|
+
orgNumber: '923609016',
|
|
44
|
+
email: 'post@fjorddesign.no',
|
|
45
|
+
address: 'Strandgata 1',
|
|
46
|
+
postalCode: '5003',
|
|
47
|
+
city: 'Bergen',
|
|
48
|
+
externalRef: 'kunde-42', // din egen id: samme verdi igjen endrer samme kunde
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
const invoice = await kumpara.invoices.create({
|
|
52
|
+
customerId: customer.id,
|
|
53
|
+
lines: [
|
|
54
|
+
{ name: 'Abonnement Pro, desember', quantity: 1, unitPrice: 14900 },
|
|
55
|
+
{ name: 'Oppsett', quantity: 2, unit: 'time', unitPrice: 95000 },
|
|
56
|
+
],
|
|
57
|
+
dueDays: 14,
|
|
58
|
+
externalRef: 'ordre-1001', // samme verdi igjen gir samme faktura tilbake, aldri en ny
|
|
59
|
+
send: true, // e-post med PDF til kunden
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
console.log(invoice.invoiceNumber, invoice.kid);
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
Med CommonJS: `const { Kumpara } = require('kumpara');`
|
|
66
|
+
|
|
67
|
+
**Alle beløp er i øre, som hele tall.** 149 kr = `14900`.
|
|
68
|
+
|
|
69
|
+
Hvert kall gir `data`-delen av svaret fra API-et. Feltene står i [dokumentasjonen](https://kumpara.no/docs).
|
|
70
|
+
|
|
71
|
+
## Kall
|
|
72
|
+
|
|
73
|
+
```js
|
|
74
|
+
await kumpara.me(); // kontoen nøkkelen virker i, og mode: test eller live
|
|
75
|
+
await kumpara.registry('923609016'); // slå opp i Enhetsregisteret (org.nr. eller navn)
|
|
76
|
+
|
|
77
|
+
await kumpara.customers.list({ q: 'fjord', page: 1 });
|
|
78
|
+
await kumpara.customers.get(12);
|
|
79
|
+
await kumpara.customers.update(12, { email: 'faktura@fjorddesign.no' });
|
|
80
|
+
|
|
81
|
+
await kumpara.products.create({ name: 'Timepris design', unit: 'time', unitPrice: 95000 });
|
|
82
|
+
|
|
83
|
+
await kumpara.invoices.list({ filter: 'overdue' }); // open, overdue, paid, credited, credit
|
|
84
|
+
await kumpara.invoices.send(26); // eller send(26, 'regnskap@firma.no')
|
|
85
|
+
await kumpara.invoices.markPaid(26, { paidDate: '2026-11-19' });
|
|
86
|
+
await kumpara.invoices.markUnpaid(26);
|
|
87
|
+
await kumpara.invoices.credit(26, 'Feil antall timer'); // kreditnota for hele fakturaen
|
|
88
|
+
|
|
89
|
+
import { writeFile } from 'node:fs/promises';
|
|
90
|
+
await writeFile('faktura.pdf', await kumpara.invoices.pdfBuffer(26));
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
## Feil
|
|
94
|
+
|
|
95
|
+
Når API-et sier nei, kastes en `ApiError` eller en av underklassene. `message` er API-ets egen tekst (norsk, for mennesker). Bruk `code` og `field` i koden.
|
|
96
|
+
|
|
97
|
+
```js
|
|
98
|
+
import { ConflictError, ValidationError } from 'kumpara';
|
|
99
|
+
|
|
100
|
+
try {
|
|
101
|
+
await kumpara.invoices.create(invoice);
|
|
102
|
+
} catch (e) {
|
|
103
|
+
if (e instanceof ValidationError) {
|
|
104
|
+
// 422: e.field sier hvilket felt, for eksempel "plan" når gratisfakturaene er brukt opp
|
|
105
|
+
} else if (e instanceof ConflictError) {
|
|
106
|
+
// 409: "settings" (avsenderopplysninger mangler) eller "numberStart" (første fakturanummer ikke valgt)
|
|
107
|
+
} else {
|
|
108
|
+
throw e;
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
| Feil | HTTP | Eksempel på `code` |
|
|
114
|
+
|---|---|---|
|
|
115
|
+
| `AuthenticationError` | 401 | `invalid_api_key`, `unauthorized` |
|
|
116
|
+
| `PaymentError` | 402, 502 | `payment_failed`, `payment_provider` |
|
|
117
|
+
| `PermissionError` | 403 | `missing_scope`, `not_allowed_for_api_key`, `account_closed` |
|
|
118
|
+
| `NotFoundError` | 404 | `not_found` |
|
|
119
|
+
| `ConflictError` | 409 | `conflict` |
|
|
120
|
+
| `ValidationError` | 422 | `validation_error` |
|
|
121
|
+
| `RateLimitError` | 429 | `rate_limited`, `too_many_invalid_keys` |
|
|
122
|
+
| `ServerError` | 5xx | `server_error` |
|
|
123
|
+
| `ConnectionError` | | Ikke noe svar (DNS, TLS, tidsavbrudd) |
|
|
124
|
+
|
|
125
|
+
### Nye forsøk
|
|
126
|
+
|
|
127
|
+
Biblioteket prøver igjen av seg selv (to ganger som standard) når det er trygt:
|
|
128
|
+
|
|
129
|
+
- `429 rate_limited`: venter så lenge `Retry-After` sier, opptil 10 sekunder.
|
|
130
|
+
- Nettverksfeil og `5xx`: bare for `GET`, og for `POST` med `externalRef` eller `ref`, fordi Kumpara da gir samme resultat tilbake i stedet for å lage noe nytt.
|
|
131
|
+
|
|
132
|
+
Bruk derfor alltid `externalRef` når du lager fakturaer.
|
|
133
|
+
|
|
134
|
+
```js
|
|
135
|
+
const kumpara = new Kumpara({ maxRetries: 0, timeout: 15_000 });
|
|
136
|
+
```
|
|
137
|
+
|
|
138
|
+
## Webhooks
|
|
139
|
+
|
|
140
|
+
Legg til en https-adresse under **Utviklerverktøy → Webhooks** i Kumpara. Sjekk signaturen mot den **rå** kroppen før du stoler på innholdet:
|
|
141
|
+
|
|
142
|
+
```js
|
|
143
|
+
import express from 'express';
|
|
144
|
+
import { Webhook, SignatureError } from 'kumpara';
|
|
145
|
+
|
|
146
|
+
const app = express();
|
|
147
|
+
|
|
148
|
+
app.post('/kumpara/webhook', express.raw({ type: 'application/json' }), (req, res) => {
|
|
149
|
+
let event;
|
|
150
|
+
try {
|
|
151
|
+
event = Webhook.constructEvent(req.body, req.get('Kumpara-Signature'), process.env.KUMPARA_WEBHOOK_SECRET);
|
|
152
|
+
} catch (e) {
|
|
153
|
+
if (e instanceof SignatureError) return res.sendStatus(400);
|
|
154
|
+
throw e;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
if (event.type === 'invoice.paid') {
|
|
158
|
+
const invoice = event.data.invoice;
|
|
159
|
+
// marker ordren invoice.externalRef som betalt i systemet ditt
|
|
160
|
+
}
|
|
161
|
+
res.sendStatus(200);
|
|
162
|
+
});
|
|
163
|
+
```
|
|
164
|
+
|
|
165
|
+
Svar med `2xx` innen 5 sekunder. Samme hendelse kan i sjeldne tilfeller komme to ganger: bruk `event.id` for å se om du har behandlet den før.
|
|
166
|
+
|
|
167
|
+
## Kontoer for kundene dine
|
|
168
|
+
|
|
169
|
+
Lager du en app der kundene dine fakturerer, kan hver av dem få sin egen Kumpara-konto. Nøkkelen trenger rettigheten `tenants`.
|
|
170
|
+
|
|
171
|
+
```js
|
|
172
|
+
const tenant = await kumpara.tenants.create({
|
|
173
|
+
ref: 'kunde-42', // din egen id: samme ref igjen gir samme konto
|
|
174
|
+
name: 'Rørlegger Hansen AS',
|
|
175
|
+
orgNumber: '923609016',
|
|
176
|
+
email: 'post@hansen.no',
|
|
177
|
+
address: 'Ny vei 9',
|
|
178
|
+
postalCode: '5003',
|
|
179
|
+
city: 'Bergen',
|
|
180
|
+
bankAccount: '86011117947',
|
|
181
|
+
});
|
|
182
|
+
|
|
183
|
+
const hansen = kumpara.withTenant(tenant.id); // en ny klient som jobber i den kontoen
|
|
184
|
+
await hansen.invoices.create({ /* ... */ });
|
|
185
|
+
```
|
|
186
|
+
|
|
187
|
+
Med en live-nøkkel er hver ny konto et eget Pro-abonnement. Les [dokumentasjonen](https://kumpara.no/docs#kontoer-for-kundene-dine) før du bruker det.
|
|
188
|
+
|
|
189
|
+
## Test og live
|
|
190
|
+
|
|
191
|
+
`kumpara.isTestMode` er `true` for en `kp_test_`-nøkkel. Bygg og test med den, og bytt til `kp_live_` når alt virker.
|
|
192
|
+
|
|
193
|
+
## AI-assistenter
|
|
194
|
+
|
|
195
|
+
Kumpara kan også brukes direkte fra Claude og ChatGPT med MCP: `https://mcp.kumpara.no`. Dokumentasjonen for AI-assistenter som skriver kode: [kumpara.no/llms.txt](https://kumpara.no/llms.txt).
|
|
196
|
+
|
|
197
|
+
## Utvikling
|
|
198
|
+
|
|
199
|
+
```bash
|
|
200
|
+
npm install
|
|
201
|
+
npm test
|
|
202
|
+
```
|
|
203
|
+
|
|
204
|
+
## Lisens
|
|
205
|
+
|
|
206
|
+
MIT. Se [LICENSE](LICENSE). Kumpara er laget av Nufel Web Hosting.
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { Customers, Invoices, Products, Tenants } from './resources.js';
|
|
2
|
+
import type { KumparaObject } from './types.js';
|
|
3
|
+
export declare const VERSION = "0.1.1";
|
|
4
|
+
export declare const DEFAULT_BASE_URL = "https://api.kumpara.no/v1";
|
|
5
|
+
/** What the client needs from an HTTP answer: the global fetch's Response has all of it. */
|
|
6
|
+
export interface FetchResponseLike {
|
|
7
|
+
ok: boolean;
|
|
8
|
+
status: number;
|
|
9
|
+
headers: {
|
|
10
|
+
get(name: string): string | null;
|
|
11
|
+
};
|
|
12
|
+
text(): Promise<string>;
|
|
13
|
+
}
|
|
14
|
+
/** A fetch function: the global one, or your own (tests, a proxy). Typed loosely so no DOM or Node types are needed. */
|
|
15
|
+
export type FetchLike = (url: string, init: any) => Promise<FetchResponseLike>;
|
|
16
|
+
export interface KumparaOptions {
|
|
17
|
+
/** kp_test_... or kp_live_...; default: the KUMPARA_API_KEY environment variable. */
|
|
18
|
+
apiKey?: string;
|
|
19
|
+
/** Work in one of your customers' accounts (X-Tenant-Id). */
|
|
20
|
+
tenantId?: number | null;
|
|
21
|
+
baseUrl?: string;
|
|
22
|
+
/** Milliseconds per attempt. Default 30000. */
|
|
23
|
+
timeout?: number;
|
|
24
|
+
/** Extra attempts when it is safe to repeat. Default 2. */
|
|
25
|
+
maxRetries?: number;
|
|
26
|
+
/** Your own fetch (for tests or a proxy). Default: the global fetch. */
|
|
27
|
+
fetch?: FetchLike;
|
|
28
|
+
/** @internal How to wait between attempts (tests). */
|
|
29
|
+
sleep?: (ms: number) => Promise<void>;
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* The Kumpara API client.
|
|
33
|
+
*
|
|
34
|
+
* const kumpara = new Kumpara(); // reads KUMPARA_API_KEY
|
|
35
|
+
* const invoice = await kumpara.invoices.create({ ... });
|
|
36
|
+
*
|
|
37
|
+
* Every call resolves with the `data` part of the API's answer, and rejects with an ApiError (or one of its
|
|
38
|
+
* subclasses) when the API says no. Amounts are in øre (149 kr = 14900).
|
|
39
|
+
*/
|
|
40
|
+
export declare class Kumpara {
|
|
41
|
+
#private;
|
|
42
|
+
readonly customers: Customers;
|
|
43
|
+
readonly products: Products;
|
|
44
|
+
readonly invoices: Invoices;
|
|
45
|
+
readonly tenants: Tenants;
|
|
46
|
+
constructor(options?: KumparaOptions);
|
|
47
|
+
/** A new client working in one of your customers' accounts (X-Tenant-Id). This one is unchanged. */
|
|
48
|
+
withTenant(tenantId: number | null): Kumpara;
|
|
49
|
+
/** True for a kp_test_ key: test account, no e-mail to customers, TEST on the PDF. */
|
|
50
|
+
get isTestMode(): boolean;
|
|
51
|
+
/** The account the key works in, and `mode`: test or live. */
|
|
52
|
+
me(): Promise<KumparaObject>;
|
|
53
|
+
/** Look up a company in Enhetsregisteret by organisation number or name. */
|
|
54
|
+
registry(query: string): Promise<KumparaObject>;
|
|
55
|
+
/**
|
|
56
|
+
* One API call. Retries what is safe to repeat: a 429 (the call was not run), and for GET, or a POST whose body
|
|
57
|
+
* carries externalRef/ref (Kumpara gives the same result back), also network errors and 5xx answers.
|
|
58
|
+
*
|
|
59
|
+
* @internal Used by the resource classes; prefer those.
|
|
60
|
+
*/
|
|
61
|
+
request<T = KumparaObject>(method: 'GET' | 'POST', path: string, query?: Record<string, unknown>, body?: object): Promise<T>;
|
|
62
|
+
}
|
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.Kumpara = exports.DEFAULT_BASE_URL = exports.VERSION = void 0;
|
|
4
|
+
const errors_js_1 = require("./errors.js");
|
|
5
|
+
const resources_js_1 = require("./resources.js");
|
|
6
|
+
exports.VERSION = '0.1.1';
|
|
7
|
+
exports.DEFAULT_BASE_URL = 'https://api.kumpara.no/v1';
|
|
8
|
+
const MAX_RETRY_WAIT = 10; // seconds; a longer Retry-After is thrown to the caller
|
|
9
|
+
/**
|
|
10
|
+
* The Kumpara API client.
|
|
11
|
+
*
|
|
12
|
+
* const kumpara = new Kumpara(); // reads KUMPARA_API_KEY
|
|
13
|
+
* const invoice = await kumpara.invoices.create({ ... });
|
|
14
|
+
*
|
|
15
|
+
* Every call resolves with the `data` part of the API's answer, and rejects with an ApiError (or one of its
|
|
16
|
+
* subclasses) when the API says no. Amounts are in øre (149 kr = 14900).
|
|
17
|
+
*/
|
|
18
|
+
class Kumpara {
|
|
19
|
+
customers;
|
|
20
|
+
products;
|
|
21
|
+
invoices;
|
|
22
|
+
tenants;
|
|
23
|
+
#apiKey;
|
|
24
|
+
#tenantId;
|
|
25
|
+
#baseUrl;
|
|
26
|
+
#timeout;
|
|
27
|
+
#maxRetries;
|
|
28
|
+
#fetch;
|
|
29
|
+
#sleep;
|
|
30
|
+
#options;
|
|
31
|
+
constructor(options = {}) {
|
|
32
|
+
const apiKey = (options.apiKey ?? process.env.KUMPARA_API_KEY ?? '').trim();
|
|
33
|
+
if (apiKey === '') {
|
|
34
|
+
throw new TypeError('No API key. Pass { apiKey }, or set the KUMPARA_API_KEY environment variable.');
|
|
35
|
+
}
|
|
36
|
+
const fetchFn = options.fetch ?? globalThis.fetch;
|
|
37
|
+
if (typeof fetchFn !== 'function') {
|
|
38
|
+
throw new TypeError('No fetch available. Use Node.js 20 or newer, or pass { fetch }.');
|
|
39
|
+
}
|
|
40
|
+
this.#options = options;
|
|
41
|
+
this.#apiKey = apiKey;
|
|
42
|
+
this.#tenantId = options.tenantId ?? null;
|
|
43
|
+
this.#baseUrl = (options.baseUrl ?? exports.DEFAULT_BASE_URL).replace(/\/+$/, '');
|
|
44
|
+
this.#timeout = options.timeout ?? 30_000;
|
|
45
|
+
this.#maxRetries = Math.max(0, options.maxRetries ?? 2);
|
|
46
|
+
this.#fetch = fetchFn;
|
|
47
|
+
this.#sleep = options.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
|
|
48
|
+
this.customers = new resources_js_1.Customers(this);
|
|
49
|
+
this.products = new resources_js_1.Products(this);
|
|
50
|
+
this.invoices = new resources_js_1.Invoices(this);
|
|
51
|
+
this.tenants = new resources_js_1.Tenants(this);
|
|
52
|
+
}
|
|
53
|
+
/** A new client working in one of your customers' accounts (X-Tenant-Id). This one is unchanged. */
|
|
54
|
+
withTenant(tenantId) {
|
|
55
|
+
return new Kumpara({ ...this.#options, apiKey: this.#apiKey, tenantId });
|
|
56
|
+
}
|
|
57
|
+
/** True for a kp_test_ key: test account, no e-mail to customers, TEST on the PDF. */
|
|
58
|
+
get isTestMode() {
|
|
59
|
+
return this.#apiKey.startsWith('kp_test_');
|
|
60
|
+
}
|
|
61
|
+
/** The account the key works in, and `mode`: test or live. */
|
|
62
|
+
me() {
|
|
63
|
+
return this.request('GET', '/me');
|
|
64
|
+
}
|
|
65
|
+
/** Look up a company in Enhetsregisteret by organisation number or name. */
|
|
66
|
+
registry(query) {
|
|
67
|
+
return this.request('GET', '/registry', { q: query });
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* One API call. Retries what is safe to repeat: a 429 (the call was not run), and for GET, or a POST whose body
|
|
71
|
+
* carries externalRef/ref (Kumpara gives the same result back), also network errors and 5xx answers.
|
|
72
|
+
*
|
|
73
|
+
* @internal Used by the resource classes; prefer those.
|
|
74
|
+
*/
|
|
75
|
+
async request(method, path, query = {}, body) {
|
|
76
|
+
const url = new URL(this.#baseUrl + path);
|
|
77
|
+
for (const [key, value] of Object.entries(query)) {
|
|
78
|
+
if (value !== undefined && value !== null && value !== '') {
|
|
79
|
+
url.searchParams.set(key, String(value));
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
const headers = {
|
|
83
|
+
Authorization: `Bearer ${this.#apiKey}`,
|
|
84
|
+
Accept: 'application/json',
|
|
85
|
+
'User-Agent': `kumpara-node/${exports.VERSION} node/${process.versions.node}`,
|
|
86
|
+
};
|
|
87
|
+
if (this.#tenantId !== null) {
|
|
88
|
+
headers['X-Tenant-Id'] = String(this.#tenantId);
|
|
89
|
+
}
|
|
90
|
+
let payload;
|
|
91
|
+
if (body !== undefined) {
|
|
92
|
+
headers['Content-Type'] = 'application/json';
|
|
93
|
+
payload = JSON.stringify(body);
|
|
94
|
+
}
|
|
95
|
+
const sent = (body ?? {});
|
|
96
|
+
const repeatable = method === 'GET' || sent.externalRef !== undefined || sent.ref !== undefined;
|
|
97
|
+
for (let attempt = 0;; attempt++) {
|
|
98
|
+
let response;
|
|
99
|
+
try {
|
|
100
|
+
response = await this.#fetch(url.toString(), {
|
|
101
|
+
method,
|
|
102
|
+
headers,
|
|
103
|
+
body: payload,
|
|
104
|
+
signal: AbortSignal.timeout(this.#timeout),
|
|
105
|
+
});
|
|
106
|
+
}
|
|
107
|
+
catch (cause) {
|
|
108
|
+
if (repeatable && attempt < this.#maxRetries) {
|
|
109
|
+
await this.#sleep(this.#backoff(attempt));
|
|
110
|
+
continue;
|
|
111
|
+
}
|
|
112
|
+
const reason = cause instanceof Error ? cause.message : String(cause);
|
|
113
|
+
throw Object.assign(new errors_js_1.ConnectionError(`Could not reach Kumpara: ${reason}`), { cause });
|
|
114
|
+
}
|
|
115
|
+
const text = await response.text();
|
|
116
|
+
let json = null;
|
|
117
|
+
try {
|
|
118
|
+
json = JSON.parse(text);
|
|
119
|
+
}
|
|
120
|
+
catch {
|
|
121
|
+
// not JSON: handled as an error below
|
|
122
|
+
}
|
|
123
|
+
const answer = (json && typeof json === 'object' ? json : {});
|
|
124
|
+
if (response.ok && answer.success === true) {
|
|
125
|
+
return (answer.data && typeof answer.data === 'object' ? answer.data : {});
|
|
126
|
+
}
|
|
127
|
+
const error = (0, errors_js_1.errorFromResponse)(response.status, json, text, response.headers.get('retry-after'));
|
|
128
|
+
if (attempt < this.#maxRetries) {
|
|
129
|
+
if (response.status === 429 && error.code === 'rate_limited') {
|
|
130
|
+
const wait = error.retryAfter ?? 1;
|
|
131
|
+
if (wait <= MAX_RETRY_WAIT) {
|
|
132
|
+
await this.#sleep(wait * 1000);
|
|
133
|
+
continue;
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
else if (response.status >= 500 && repeatable && error.code !== 'payment_provider') {
|
|
137
|
+
await this.#sleep(this.#backoff(attempt));
|
|
138
|
+
continue;
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
throw error;
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
#backoff(attempt) {
|
|
145
|
+
return Math.min(8000, 500 * 2 ** attempt) + Math.floor(Math.random() * 250);
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
exports.Kumpara = Kumpara;
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
/** Every error this SDK throws extends this one. */
|
|
2
|
+
export declare class KumparaError extends Error {
|
|
3
|
+
constructor(message: string);
|
|
4
|
+
}
|
|
5
|
+
/** No answer from Kumpara (DNS, TLS, timeout). The call may or may not have run: use externalRef to repeat it safely. */
|
|
6
|
+
export declare class ConnectionError extends KumparaError {
|
|
7
|
+
}
|
|
8
|
+
/** A webhook whose Kumpara-Signature does not match, is too old, or whose body is not a Kumpara event. */
|
|
9
|
+
export declare class SignatureError extends KumparaError {
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* The API answered with an error. `message` is the API's own text (Norwegian, for people); use `code` and `field`
|
|
13
|
+
* in code. The subclasses follow the HTTP status.
|
|
14
|
+
*/
|
|
15
|
+
export declare class ApiError extends KumparaError {
|
|
16
|
+
/** HTTP status, for example 422. */
|
|
17
|
+
readonly status: number;
|
|
18
|
+
/** Stable error code, for example validation_error, conflict, rate_limited. */
|
|
19
|
+
readonly code: string;
|
|
20
|
+
/** The field the error is about, when it is about one (for example email, settings, plan). */
|
|
21
|
+
readonly field: string | null;
|
|
22
|
+
/** Seconds to wait (429). */
|
|
23
|
+
readonly retryAfter: number | null;
|
|
24
|
+
/** The raw response body. */
|
|
25
|
+
readonly body: string;
|
|
26
|
+
constructor(message: string, status: number, code: string, field: string | null, retryAfter: number | null, body: string);
|
|
27
|
+
}
|
|
28
|
+
/** 401: no key, or the key does not exist (invalid_api_key, unauthorized). */
|
|
29
|
+
export declare class AuthenticationError extends ApiError {
|
|
30
|
+
}
|
|
31
|
+
/** 402 payment_failed or 502 payment_provider: the card was declined or the payment provider did not answer. Nothing was made. */
|
|
32
|
+
export declare class PaymentError extends ApiError {
|
|
33
|
+
}
|
|
34
|
+
/** 403: missing_scope, not_allowed_for_api_key or account_closed. */
|
|
35
|
+
export declare class PermissionError extends ApiError {
|
|
36
|
+
}
|
|
37
|
+
/** 404 not_found. */
|
|
38
|
+
export declare class NotFoundError extends ApiError {
|
|
39
|
+
}
|
|
40
|
+
/** 409 conflict: cannot be done now. `field` says why, for example settings (sender details missing) or numberStart. */
|
|
41
|
+
export declare class ConflictError extends ApiError {
|
|
42
|
+
}
|
|
43
|
+
/** 422 validation_error. `field` names the field, for example plan when the free invoices are used up. */
|
|
44
|
+
export declare class ValidationError extends ApiError {
|
|
45
|
+
}
|
|
46
|
+
/** 429: rate_limited (see retryAfter) or too_many_invalid_keys. */
|
|
47
|
+
export declare class RateLimitError extends ApiError {
|
|
48
|
+
}
|
|
49
|
+
/** 5xx: an error at Kumpara. Try again later. */
|
|
50
|
+
export declare class ServerError extends ApiError {
|
|
51
|
+
}
|
|
52
|
+
/** @internal */
|
|
53
|
+
export declare function errorFromResponse(status: number, json: unknown, body: string, retryAfterHeader: string | null): ApiError;
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.ServerError = exports.RateLimitError = exports.ValidationError = exports.ConflictError = exports.NotFoundError = exports.PermissionError = exports.PaymentError = exports.AuthenticationError = exports.ApiError = exports.SignatureError = exports.ConnectionError = exports.KumparaError = void 0;
|
|
4
|
+
exports.errorFromResponse = errorFromResponse;
|
|
5
|
+
/** Every error this SDK throws extends this one. */
|
|
6
|
+
class KumparaError extends Error {
|
|
7
|
+
constructor(message) {
|
|
8
|
+
super(message);
|
|
9
|
+
this.name = new.target.name;
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
exports.KumparaError = KumparaError;
|
|
13
|
+
/** No answer from Kumpara (DNS, TLS, timeout). The call may or may not have run: use externalRef to repeat it safely. */
|
|
14
|
+
class ConnectionError extends KumparaError {
|
|
15
|
+
}
|
|
16
|
+
exports.ConnectionError = ConnectionError;
|
|
17
|
+
/** A webhook whose Kumpara-Signature does not match, is too old, or whose body is not a Kumpara event. */
|
|
18
|
+
class SignatureError extends KumparaError {
|
|
19
|
+
}
|
|
20
|
+
exports.SignatureError = SignatureError;
|
|
21
|
+
/**
|
|
22
|
+
* The API answered with an error. `message` is the API's own text (Norwegian, for people); use `code` and `field`
|
|
23
|
+
* in code. The subclasses follow the HTTP status.
|
|
24
|
+
*/
|
|
25
|
+
class ApiError extends KumparaError {
|
|
26
|
+
/** HTTP status, for example 422. */
|
|
27
|
+
status;
|
|
28
|
+
/** Stable error code, for example validation_error, conflict, rate_limited. */
|
|
29
|
+
code;
|
|
30
|
+
/** The field the error is about, when it is about one (for example email, settings, plan). */
|
|
31
|
+
field;
|
|
32
|
+
/** Seconds to wait (429). */
|
|
33
|
+
retryAfter;
|
|
34
|
+
/** The raw response body. */
|
|
35
|
+
body;
|
|
36
|
+
constructor(message, status, code, field, retryAfter, body) {
|
|
37
|
+
super(message);
|
|
38
|
+
this.status = status;
|
|
39
|
+
this.code = code;
|
|
40
|
+
this.field = field;
|
|
41
|
+
this.retryAfter = retryAfter;
|
|
42
|
+
this.body = body;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
exports.ApiError = ApiError;
|
|
46
|
+
/** 401: no key, or the key does not exist (invalid_api_key, unauthorized). */
|
|
47
|
+
class AuthenticationError extends ApiError {
|
|
48
|
+
}
|
|
49
|
+
exports.AuthenticationError = AuthenticationError;
|
|
50
|
+
/** 402 payment_failed or 502 payment_provider: the card was declined or the payment provider did not answer. Nothing was made. */
|
|
51
|
+
class PaymentError extends ApiError {
|
|
52
|
+
}
|
|
53
|
+
exports.PaymentError = PaymentError;
|
|
54
|
+
/** 403: missing_scope, not_allowed_for_api_key or account_closed. */
|
|
55
|
+
class PermissionError extends ApiError {
|
|
56
|
+
}
|
|
57
|
+
exports.PermissionError = PermissionError;
|
|
58
|
+
/** 404 not_found. */
|
|
59
|
+
class NotFoundError extends ApiError {
|
|
60
|
+
}
|
|
61
|
+
exports.NotFoundError = NotFoundError;
|
|
62
|
+
/** 409 conflict: cannot be done now. `field` says why, for example settings (sender details missing) or numberStart. */
|
|
63
|
+
class ConflictError extends ApiError {
|
|
64
|
+
}
|
|
65
|
+
exports.ConflictError = ConflictError;
|
|
66
|
+
/** 422 validation_error. `field` names the field, for example plan when the free invoices are used up. */
|
|
67
|
+
class ValidationError extends ApiError {
|
|
68
|
+
}
|
|
69
|
+
exports.ValidationError = ValidationError;
|
|
70
|
+
/** 429: rate_limited (see retryAfter) or too_many_invalid_keys. */
|
|
71
|
+
class RateLimitError extends ApiError {
|
|
72
|
+
}
|
|
73
|
+
exports.RateLimitError = RateLimitError;
|
|
74
|
+
/** 5xx: an error at Kumpara. Try again later. */
|
|
75
|
+
class ServerError extends ApiError {
|
|
76
|
+
}
|
|
77
|
+
exports.ServerError = ServerError;
|
|
78
|
+
const CODE_FOR_STATUS = {
|
|
79
|
+
400: 'bad_request',
|
|
80
|
+
401: 'unauthorized',
|
|
81
|
+
402: 'payment_failed',
|
|
82
|
+
403: 'forbidden',
|
|
83
|
+
404: 'not_found',
|
|
84
|
+
405: 'method_not_allowed',
|
|
85
|
+
409: 'conflict',
|
|
86
|
+
422: 'validation_error',
|
|
87
|
+
429: 'rate_limited',
|
|
88
|
+
};
|
|
89
|
+
/** @internal */
|
|
90
|
+
function errorFromResponse(status, json, body, retryAfterHeader) {
|
|
91
|
+
const data = (json && typeof json === 'object' ? json : {});
|
|
92
|
+
const code = typeof data.code === 'string' ? data.code : (CODE_FOR_STATUS[status] ?? 'server_error');
|
|
93
|
+
const message = typeof data.message === 'string' && data.message !== '' ? data.message : `Kumpara answered HTTP ${status}`;
|
|
94
|
+
const field = typeof data.field === 'string' ? data.field : null;
|
|
95
|
+
const retryAfter = retryAfterHeader !== null && /^\d+$/.test(retryAfterHeader) ? Number(retryAfterHeader) : null;
|
|
96
|
+
const ErrorClass = status === 401 ? AuthenticationError
|
|
97
|
+
: status === 402 || code === 'payment_provider' ? PaymentError
|
|
98
|
+
: status === 403 ? PermissionError
|
|
99
|
+
: status === 404 ? NotFoundError
|
|
100
|
+
: status === 409 ? ConflictError
|
|
101
|
+
: status === 422 ? ValidationError
|
|
102
|
+
: status === 429 ? RateLimitError
|
|
103
|
+
: status >= 500 ? ServerError
|
|
104
|
+
: ApiError;
|
|
105
|
+
return new ErrorClass(message, status, code, field, retryAfter, body);
|
|
106
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export { Kumpara, VERSION, DEFAULT_BASE_URL } from './client.js';
|
|
2
|
+
export type { KumparaOptions, FetchLike, FetchResponseLike } from './client.js';
|
|
3
|
+
export { Customers, Products, Invoices, Tenants } from './resources.js';
|
|
4
|
+
export { Webhook, constructEvent, verify, DEFAULT_TOLERANCE } from './webhook.js';
|
|
5
|
+
export type { VerifyOptions } from './webhook.js';
|
|
6
|
+
export { KumparaError, ConnectionError, SignatureError, ApiError, AuthenticationError, PaymentError, PermissionError, NotFoundError, ConflictError, ValidationError, RateLimitError, ServerError, } from './errors.js';
|
|
7
|
+
export type * from './types.js';
|
|
8
|
+
export { Kumpara as default } from './client.js';
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.default = exports.ServerError = exports.RateLimitError = exports.ValidationError = exports.ConflictError = exports.NotFoundError = exports.PermissionError = exports.PaymentError = exports.AuthenticationError = exports.ApiError = exports.SignatureError = exports.ConnectionError = exports.KumparaError = exports.DEFAULT_TOLERANCE = exports.verify = exports.constructEvent = exports.Webhook = exports.Tenants = exports.Invoices = exports.Products = exports.Customers = exports.DEFAULT_BASE_URL = exports.VERSION = exports.Kumpara = void 0;
|
|
4
|
+
var client_js_1 = require("./client.js");
|
|
5
|
+
Object.defineProperty(exports, "Kumpara", { enumerable: true, get: function () { return client_js_1.Kumpara; } });
|
|
6
|
+
Object.defineProperty(exports, "VERSION", { enumerable: true, get: function () { return client_js_1.VERSION; } });
|
|
7
|
+
Object.defineProperty(exports, "DEFAULT_BASE_URL", { enumerable: true, get: function () { return client_js_1.DEFAULT_BASE_URL; } });
|
|
8
|
+
var resources_js_1 = require("./resources.js");
|
|
9
|
+
Object.defineProperty(exports, "Customers", { enumerable: true, get: function () { return resources_js_1.Customers; } });
|
|
10
|
+
Object.defineProperty(exports, "Products", { enumerable: true, get: function () { return resources_js_1.Products; } });
|
|
11
|
+
Object.defineProperty(exports, "Invoices", { enumerable: true, get: function () { return resources_js_1.Invoices; } });
|
|
12
|
+
Object.defineProperty(exports, "Tenants", { enumerable: true, get: function () { return resources_js_1.Tenants; } });
|
|
13
|
+
var webhook_js_1 = require("./webhook.js");
|
|
14
|
+
Object.defineProperty(exports, "Webhook", { enumerable: true, get: function () { return webhook_js_1.Webhook; } });
|
|
15
|
+
Object.defineProperty(exports, "constructEvent", { enumerable: true, get: function () { return webhook_js_1.constructEvent; } });
|
|
16
|
+
Object.defineProperty(exports, "verify", { enumerable: true, get: function () { return webhook_js_1.verify; } });
|
|
17
|
+
Object.defineProperty(exports, "DEFAULT_TOLERANCE", { enumerable: true, get: function () { return webhook_js_1.DEFAULT_TOLERANCE; } });
|
|
18
|
+
var errors_js_1 = require("./errors.js");
|
|
19
|
+
Object.defineProperty(exports, "KumparaError", { enumerable: true, get: function () { return errors_js_1.KumparaError; } });
|
|
20
|
+
Object.defineProperty(exports, "ConnectionError", { enumerable: true, get: function () { return errors_js_1.ConnectionError; } });
|
|
21
|
+
Object.defineProperty(exports, "SignatureError", { enumerable: true, get: function () { return errors_js_1.SignatureError; } });
|
|
22
|
+
Object.defineProperty(exports, "ApiError", { enumerable: true, get: function () { return errors_js_1.ApiError; } });
|
|
23
|
+
Object.defineProperty(exports, "AuthenticationError", { enumerable: true, get: function () { return errors_js_1.AuthenticationError; } });
|
|
24
|
+
Object.defineProperty(exports, "PaymentError", { enumerable: true, get: function () { return errors_js_1.PaymentError; } });
|
|
25
|
+
Object.defineProperty(exports, "PermissionError", { enumerable: true, get: function () { return errors_js_1.PermissionError; } });
|
|
26
|
+
Object.defineProperty(exports, "NotFoundError", { enumerable: true, get: function () { return errors_js_1.NotFoundError; } });
|
|
27
|
+
Object.defineProperty(exports, "ConflictError", { enumerable: true, get: function () { return errors_js_1.ConflictError; } });
|
|
28
|
+
Object.defineProperty(exports, "ValidationError", { enumerable: true, get: function () { return errors_js_1.ValidationError; } });
|
|
29
|
+
Object.defineProperty(exports, "RateLimitError", { enumerable: true, get: function () { return errors_js_1.RateLimitError; } });
|
|
30
|
+
Object.defineProperty(exports, "ServerError", { enumerable: true, get: function () { return errors_js_1.ServerError; } });
|
|
31
|
+
var client_js_2 = require("./client.js");
|
|
32
|
+
Object.defineProperty(exports, "default", { enumerable: true, get: function () { return client_js_2.Kumpara; } });
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{ "type": "commonjs" }
|