@onesim.global/sdk 0.0.0-stage → 0.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.
@@ -0,0 +1,314 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.BalanceResource = exports.Esims = exports.Orders = exports.Packages = exports.OnesimClient = void 0;
4
+ const errors_js_1 = require("./errors.js");
5
+ const http_js_1 = require("./http.js");
6
+ const API_KEY_ENV = 'ONESIM_API_KEY';
7
+ const DEFAULT_BASE_URL = 'https://api.onesim.global';
8
+ const DEFAULT_TIMEOUT = 60_000;
9
+ const DEFAULT_MAX_RETRIES = 2;
10
+ const DEFAULT_POLL_TIMEOUT = 660_000;
11
+ const DEFAULT_POLL_INTERVAL = 3_000;
12
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
13
+ const id = (value) => encodeURIComponent(value);
14
+ /**
15
+ * The onesim partner API.
16
+ *
17
+ * ```ts
18
+ * import OnesimClient from '@onesim.global/sdk';
19
+ *
20
+ * const onesim = new OnesimClient(); // reads ONESIM_API_KEY
21
+ * const catalogue = await onesim.packages.list();
22
+ * ```
23
+ */
24
+ class OnesimClient {
25
+ /** Your catalogue: what you can buy and what it costs you. */
26
+ packages;
27
+ /** Buying blank eSIMs, packages and bundles. */
28
+ orders;
29
+ /** The eSIMs you own, with their packages and usage. */
30
+ esims;
31
+ /** Your partner balance. */
32
+ balance;
33
+ constructor(options = {}) {
34
+ const apiKey = options.apiKey ?? readEnv(API_KEY_ENV);
35
+ if (typeof apiKey !== 'string' || apiKey === '') {
36
+ throw new TypeError(`OnesimClient: no API key. Pass apiKey, or set the ${API_KEY_ENV} environment variable.`);
37
+ }
38
+ const timeout = options.timeout ?? DEFAULT_TIMEOUT;
39
+ if (!(timeout > 0))
40
+ throw new TypeError('OnesimClient: timeout must be a positive number.');
41
+ const maxRetries = options.maxRetries ?? DEFAULT_MAX_RETRIES;
42
+ if (!Number.isInteger(maxRetries) || maxRetries < 0) {
43
+ throw new TypeError('OnesimClient: maxRetries must be a whole number, 0 or more.');
44
+ }
45
+ let fetch = options.fetch;
46
+ if (!fetch) {
47
+ if (typeof globalThis.fetch !== 'function') {
48
+ throw new TypeError('OnesimClient: this runtime has no global fetch; pass one as `fetch`.');
49
+ }
50
+ // Looked up on each call, so a fetch replaced later (e.g. by a test) is used.
51
+ fetch = (url, init) => globalThis.fetch(url, init);
52
+ }
53
+ const http = new http_js_1.Http({
54
+ apiKey,
55
+ baseURL: (options.baseURL ?? DEFAULT_BASE_URL).replace(/\/+$/, ''),
56
+ timeout,
57
+ maxRetries,
58
+ fetch
59
+ });
60
+ this.packages = new Packages(http);
61
+ this.orders = new Orders(http);
62
+ this.esims = new Esims(http);
63
+ this.balance = new BalanceResource(http);
64
+ }
65
+ }
66
+ exports.OnesimClient = OnesimClient;
67
+ // process.env where there is one (Node.js, Bun, Deno); never throws where
68
+ // there is not (Workers, browsers) or where reading it is not allowed.
69
+ function readEnv(name) {
70
+ try {
71
+ const env = globalThis.process?.env;
72
+ return env?.[name]?.trim() || undefined;
73
+ }
74
+ catch {
75
+ return undefined;
76
+ }
77
+ }
78
+ class Packages {
79
+ #http;
80
+ constructor(http) {
81
+ this.#http = http;
82
+ }
83
+ /** `GET /v1/packages`: your packages and the price of a blank eSIM. A `null` price means "not offered that way". */
84
+ list(options = {}) {
85
+ return this.#http.request({
86
+ method: 'GET',
87
+ path: '/v1/packages',
88
+ signal: options.signal
89
+ });
90
+ }
91
+ /** `GET /v1/packages/{id}`. */
92
+ retrieve(packageId, options = {}) {
93
+ return this.#http.request({
94
+ method: 'GET',
95
+ path: `/v1/packages/${id(packageId)}`,
96
+ signal: options.signal
97
+ });
98
+ }
99
+ }
100
+ exports.Packages = Packages;
101
+ class Orders {
102
+ #http;
103
+ constructor(http) {
104
+ this.#http = http;
105
+ }
106
+ /**
107
+ * `POST /v1/orders`: buy a blank eSIM (`type: 'esim'`), a package on an eSIM
108
+ * you own (`type: 'package'`) or a new eSIM with a package (`type: 'bundle'`).
109
+ * Resolves with the order as the API answers it: `completed`, or `pending`
110
+ * (follow it with `orders.poll`, or use `orders.createAndPoll`).
111
+ *
112
+ * Every attempt of this call sends the same Idempotency-Key, so a retry
113
+ * never buys twice. Pass your own `idempotencyKey`, stored with your
114
+ * booking, to make retries across restarts safe too. Any `OnesimError`
115
+ * thrown carries the key it used as `error.idempotencyKey`.
116
+ */
117
+ async create(body, options = {}) {
118
+ const idempotencyKey = idempotencyKeyOf(options);
119
+ try {
120
+ return await this.#create(body, idempotencyKey, options.signal);
121
+ }
122
+ catch (error) {
123
+ if (error instanceof errors_js_1.OnesimError)
124
+ error.idempotencyKey = idempotencyKey;
125
+ throw error;
126
+ }
127
+ }
128
+ /**
129
+ * `orders.create`, then `orders.poll` while the order is pending. Resolves
130
+ * with the final order whatever its status (`completed`, `failed` or
131
+ * `refunded`): a `502 provisioning_failed` is not thrown but resolves with
132
+ * its failed order, so check `order.status`. Other errors are thrown, with
133
+ * the Idempotency-Key as `error.idempotencyKey`; `PollTimeoutError` when
134
+ * `timeout` runs out first.
135
+ */
136
+ async createAndPoll(body, options = {}) {
137
+ const { signal } = options;
138
+ // Checked before buying, not after.
139
+ const settings = pollSettings(options);
140
+ const idempotencyKey = idempotencyKeyOf(options);
141
+ try {
142
+ let order;
143
+ try {
144
+ order = await this.#create(body, idempotencyKey, signal);
145
+ }
146
+ catch (error) {
147
+ // A failed order is an answer like any other here.
148
+ if (error instanceof errors_js_1.APIError &&
149
+ error.code === 'provisioning_failed' &&
150
+ error.order) {
151
+ return error.order;
152
+ }
153
+ throw error;
154
+ }
155
+ if (order.status !== 'pending')
156
+ return order;
157
+ return await this.#poll(order.id, order, settings, signal);
158
+ }
159
+ catch (error) {
160
+ if (error instanceof errors_js_1.OnesimError)
161
+ error.idempotencyKey = idempotencyKey;
162
+ throw error;
163
+ }
164
+ }
165
+ /** `GET /v1/orders/{id}`. Reading a pending order also moves it forward. */
166
+ retrieve(orderId, options = {}) {
167
+ return this.#http.request({
168
+ method: 'GET',
169
+ path: `/v1/orders/${id(orderId)}`,
170
+ signal: options.signal
171
+ });
172
+ }
173
+ /** `GET /v1/orders`: one page of your orders, newest first. */
174
+ list(params = {}, options = {}) {
175
+ return this.#http.request({
176
+ method: 'GET',
177
+ path: '/v1/orders',
178
+ query: { ...params },
179
+ signal: options.signal
180
+ });
181
+ }
182
+ /** Every order matching `params`, newest first, following `next_cursor` page after page. */
183
+ async *listAll(params = {}, options = {}) {
184
+ let cursor = params.cursor;
185
+ do {
186
+ const page = await this.list({ ...params, cursor }, options);
187
+ yield* page.data;
188
+ cursor = page.next_cursor ?? undefined;
189
+ } while (cursor);
190
+ }
191
+ /**
192
+ * Reads the order until it is no longer `pending`, and resolves with it:
193
+ * `completed`, `failed` or `refunded`. A pending order completes or fails
194
+ * within about ten minutes. `timeout` bounds the whole poll, reads and
195
+ * their retries included: when it runs out, throws `PollTimeoutError` with
196
+ * the order as last read.
197
+ */
198
+ async poll(orderId, options = {}) {
199
+ return this.#poll(orderId, undefined, pollSettings(options), options.signal);
200
+ }
201
+ #create(body, idempotencyKey, signal) {
202
+ return this.#http.request({
203
+ method: 'POST',
204
+ path: '/v1/orders',
205
+ body,
206
+ idempotencyKey,
207
+ signal
208
+ });
209
+ }
210
+ // Reads and their retries share the timeout: the deadline aborts a read in
211
+ // flight, and no read starts once it has passed.
212
+ async #poll(orderId, current, { timeout, pollInterval }, signal) {
213
+ (0, http_js_1.throwIfAborted)(signal);
214
+ const deadline = Date.now() + timeout;
215
+ const budget = new AbortController();
216
+ const timer = setTimeout(() => budget.abort(), timeout);
217
+ const onAbort = () => budget.abort();
218
+ signal?.addEventListener('abort', onAbort, { once: true });
219
+ let order = current;
220
+ try {
221
+ for (;;) {
222
+ if (order) {
223
+ if (order.status !== 'pending')
224
+ return order;
225
+ const remaining = deadline - Date.now();
226
+ if (remaining <= 0)
227
+ break;
228
+ await (0, http_js_1.sleep)(Math.min(pollInterval, remaining), budget.signal);
229
+ }
230
+ if (deadline - Date.now() <= 0)
231
+ break;
232
+ order = await this.retrieve(orderId, { signal: budget.signal });
233
+ }
234
+ }
235
+ catch (error) {
236
+ // The caller's own abort ends the poll with its reason.
237
+ (0, http_js_1.throwIfAborted)(signal);
238
+ if (!budget.signal.aborted)
239
+ throw error;
240
+ }
241
+ finally {
242
+ clearTimeout(timer);
243
+ signal?.removeEventListener('abort', onAbort);
244
+ }
245
+ throw new errors_js_1.PollTimeoutError(orderId, order, timeout);
246
+ }
247
+ }
248
+ exports.Orders = Orders;
249
+ function idempotencyKeyOf(options) {
250
+ if (options.idempotencyKey !== undefined &&
251
+ !UUID.test(options.idempotencyKey)) {
252
+ throw new TypeError('OnesimClient: idempotencyKey must be a UUID.');
253
+ }
254
+ return options.idempotencyKey ?? crypto.randomUUID();
255
+ }
256
+ function pollSettings(options) {
257
+ const { timeout = DEFAULT_POLL_TIMEOUT, pollInterval = DEFAULT_POLL_INTERVAL } = options;
258
+ if (!(timeout >= 0) || !(pollInterval >= 0)) {
259
+ throw new TypeError('Poll: timeout and pollInterval must be 0 or more.');
260
+ }
261
+ return { timeout, pollInterval };
262
+ }
263
+ class Esims {
264
+ #http;
265
+ constructor(http) {
266
+ this.#http = http;
267
+ }
268
+ /**
269
+ * `GET /v1/esims/{id}`: the eSIM with its packages and usage, read live from
270
+ * the network. When the network does not answer, the last known values with
271
+ * `refreshed_at: null`.
272
+ */
273
+ retrieve(esimId, options = {}) {
274
+ return this.#http.request({
275
+ method: 'GET',
276
+ path: `/v1/esims/${id(esimId)}`,
277
+ signal: options.signal
278
+ });
279
+ }
280
+ /** `GET /v1/esims`: one page of your eSIMs, newest first. */
281
+ list(params = {}, options = {}) {
282
+ return this.#http.request({
283
+ method: 'GET',
284
+ path: '/v1/esims',
285
+ query: { ...params },
286
+ signal: options.signal
287
+ });
288
+ }
289
+ /** Every eSIM matching `params`, newest first, following `next_cursor` page after page. */
290
+ async *listAll(params = {}, options = {}) {
291
+ let cursor = params.cursor;
292
+ do {
293
+ const page = await this.list({ ...params, cursor }, options);
294
+ yield* page.data;
295
+ cursor = page.next_cursor ?? undefined;
296
+ } while (cursor);
297
+ }
298
+ }
299
+ exports.Esims = Esims;
300
+ class BalanceResource {
301
+ #http;
302
+ constructor(http) {
303
+ this.#http = http;
304
+ }
305
+ /** `GET /v1/balance`: your balance, overdraft and what you can spend now, in cents. */
306
+ retrieve(options = {}) {
307
+ return this.#http.request({
308
+ method: 'GET',
309
+ path: '/v1/balance',
310
+ signal: options.signal
311
+ });
312
+ }
313
+ }
314
+ exports.BalanceResource = BalanceResource;
@@ -0,0 +1,126 @@
1
+ import type { ErrorCode, Order } from './types.js';
2
+ /** The base class of every error the SDK throws for the API. */
3
+ export declare class OnesimError extends Error {
4
+ /**
5
+ * On an error from `orders.create` or `orders.createAndPoll`: the
6
+ * Idempotency-Key it sent. Retry the purchase with this key and it is never
7
+ * bought twice.
8
+ */
9
+ idempotencyKey?: string;
10
+ constructor(message: string, options?: {
11
+ cause?: unknown;
12
+ });
13
+ }
14
+ export interface APIErrorInit {
15
+ status: number;
16
+ code: ErrorCode | (string & {}) | null;
17
+ message: string;
18
+ requestId: string | null;
19
+ amount?: number;
20
+ limit?: 'blank' | 'daily' | (string & {});
21
+ order?: Order;
22
+ retryAfter?: number;
23
+ idempotencyKey?: string;
24
+ body: unknown;
25
+ }
26
+ /**
27
+ * The API answered with a status other than 2xx. Act on `code`. A subclass
28
+ * names the common statuses: `BadRequestError` (400), `AuthenticationError`
29
+ * (401), `PermissionDeniedError` (403), `NotFoundError` (404), `ConflictError`
30
+ * (409), `RateLimitError` (429) and `InternalServerError` (5xx); any other
31
+ * status (e.g. 402 `insufficient_balance`) is an `APIError` itself.
32
+ */
33
+ export declare class APIError extends OnesimError {
34
+ /** The HTTP status. */
35
+ readonly status: number;
36
+ /**
37
+ * The error code, e.g. `insufficient_balance`. New codes may be added: handle
38
+ * one you do not know by `status`. `null` when the body is not the API's
39
+ * error shape (e.g. an HTML page from a proxy).
40
+ */
41
+ readonly code: ErrorCode | (string & {}) | null;
42
+ /** Quote it when you contact onesim. */
43
+ readonly requestId: string | null;
44
+ /** `price_changed`: the current amount, in cents. */
45
+ readonly amount?: number;
46
+ /** `esim_limit_reached`: `blank` or `daily`. */
47
+ readonly limit?: 'blank' | 'daily' | (string & {});
48
+ /** `provisioning_failed`: the failed order. Its amount is back on your balance. */
49
+ readonly order?: Order;
50
+ /** The `Retry-After` header, in seconds. */
51
+ readonly retryAfter?: number;
52
+ /** The response body: the parsed JSON, or the text when it is not JSON. */
53
+ readonly body: unknown;
54
+ constructor(init: APIErrorInit);
55
+ }
56
+ /** 400: `invalid_request` or `idempotency_key_required`. */
57
+ export declare class BadRequestError extends APIError {
58
+ constructor(init: APIErrorInit);
59
+ }
60
+ /** 401 `unauthorized`: a missing, unknown or revoked key. */
61
+ export declare class AuthenticationError extends APIError {
62
+ constructor(init: APIErrorInit);
63
+ }
64
+ /** 403 `not_offered`: your agreement does not include this way of buying. */
65
+ export declare class PermissionDeniedError extends APIError {
66
+ constructor(init: APIErrorInit);
67
+ }
68
+ /** 404 `not_found`. */
69
+ export declare class NotFoundError extends APIError {
70
+ constructor(init: APIErrorInit);
71
+ }
72
+ /**
73
+ * 409: `idempotency_conflict`, `esim_busy`, `price_changed`,
74
+ * `esim_limit_reached` or `esim_unusable`.
75
+ */
76
+ export declare class ConflictError extends APIError {
77
+ constructor(init: APIErrorInit);
78
+ }
79
+ /** 429 `rate_limited`: `retryAfter` says how many seconds to wait. */
80
+ export declare class RateLimitError extends APIError {
81
+ constructor(init: APIErrorInit);
82
+ }
83
+ /**
84
+ * 5xx: `internal_error`, `provisioning_failed` (final; the failed order is in
85
+ * `order`), `esims_unavailable`, or an error page from the network on the way.
86
+ */
87
+ export declare class InternalServerError extends APIError {
88
+ constructor(init: APIErrorInit);
89
+ }
90
+ /** The `APIError` subclass for an answer's status. */
91
+ export declare function makeAPIError(init: APIErrorInit): APIError;
92
+ /**
93
+ * No answer from the API after every retry: the network failed or the last
94
+ * attempt timed out. A purchase may or may not have happened: retry it with
95
+ * `idempotencyKey`.
96
+ */
97
+ export declare class APIConnectionError extends OnesimError {
98
+ constructor(message: string, options: {
99
+ cause: unknown;
100
+ idempotencyKey?: string;
101
+ });
102
+ }
103
+ /** An `APIConnectionError` whose last attempt ran out of the client's `timeout`. */
104
+ export declare class APIConnectionTimeoutError extends APIConnectionError {
105
+ constructor(message: string, options: {
106
+ cause: unknown;
107
+ idempotencyKey?: string;
108
+ });
109
+ }
110
+ /** Polling an order ran out of time while it was still pending. */
111
+ export declare class PollTimeoutError extends OnesimError {
112
+ /** The order polled. */
113
+ readonly orderId: string;
114
+ /**
115
+ * The order as last read: still `pending`. Absent only when the time ran
116
+ * out before the first read answered.
117
+ */
118
+ readonly order?: Order;
119
+ constructor(orderId: string, order: Order | undefined, timeout: number);
120
+ }
121
+ export type WebhookErrorReason = 'missing_signature' | 'malformed_signature' | 'timestamp_out_of_tolerance' | 'invalid_signature' | 'invalid_payload';
122
+ /** A webhook delivery failed verification. Answer it with a 400 and do not act on it. */
123
+ export declare class WebhookVerificationError extends OnesimError {
124
+ readonly reason: WebhookErrorReason;
125
+ constructor(reason: WebhookErrorReason, message: string);
126
+ }
@@ -0,0 +1,199 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.WebhookVerificationError = exports.PollTimeoutError = exports.APIConnectionTimeoutError = exports.APIConnectionError = exports.InternalServerError = exports.RateLimitError = exports.ConflictError = exports.NotFoundError = exports.PermissionDeniedError = exports.AuthenticationError = exports.BadRequestError = exports.APIError = exports.OnesimError = void 0;
4
+ exports.makeAPIError = makeAPIError;
5
+ /** The base class of every error the SDK throws for the API. */
6
+ class OnesimError extends Error {
7
+ /**
8
+ * On an error from `orders.create` or `orders.createAndPoll`: the
9
+ * Idempotency-Key it sent. Retry the purchase with this key and it is never
10
+ * bought twice.
11
+ */
12
+ idempotencyKey;
13
+ constructor(message, options) {
14
+ super(message, options);
15
+ this.name = 'OnesimError';
16
+ }
17
+ }
18
+ exports.OnesimError = OnesimError;
19
+ /**
20
+ * The API answered with a status other than 2xx. Act on `code`. A subclass
21
+ * names the common statuses: `BadRequestError` (400), `AuthenticationError`
22
+ * (401), `PermissionDeniedError` (403), `NotFoundError` (404), `ConflictError`
23
+ * (409), `RateLimitError` (429) and `InternalServerError` (5xx); any other
24
+ * status (e.g. 402 `insufficient_balance`) is an `APIError` itself.
25
+ */
26
+ class APIError extends OnesimError {
27
+ /** The HTTP status. */
28
+ status;
29
+ /**
30
+ * The error code, e.g. `insufficient_balance`. New codes may be added: handle
31
+ * one you do not know by `status`. `null` when the body is not the API's
32
+ * error shape (e.g. an HTML page from a proxy).
33
+ */
34
+ code;
35
+ /** Quote it when you contact onesim. */
36
+ requestId;
37
+ /** `price_changed`: the current amount, in cents. */
38
+ amount;
39
+ /** `esim_limit_reached`: `blank` or `daily`. */
40
+ limit;
41
+ /** `provisioning_failed`: the failed order. Its amount is back on your balance. */
42
+ order;
43
+ /** The `Retry-After` header, in seconds. */
44
+ retryAfter;
45
+ /** The response body: the parsed JSON, or the text when it is not JSON. */
46
+ body;
47
+ constructor(init) {
48
+ super(init.message);
49
+ this.name = 'APIError';
50
+ this.status = init.status;
51
+ this.code = init.code;
52
+ this.requestId = init.requestId;
53
+ if (init.amount !== undefined)
54
+ this.amount = init.amount;
55
+ if (init.limit !== undefined)
56
+ this.limit = init.limit;
57
+ if (init.order !== undefined)
58
+ this.order = init.order;
59
+ if (init.retryAfter !== undefined)
60
+ this.retryAfter = init.retryAfter;
61
+ if (init.idempotencyKey !== undefined)
62
+ this.idempotencyKey = init.idempotencyKey;
63
+ this.body = init.body;
64
+ }
65
+ }
66
+ exports.APIError = APIError;
67
+ /** 400: `invalid_request` or `idempotency_key_required`. */
68
+ class BadRequestError extends APIError {
69
+ constructor(init) {
70
+ super(init);
71
+ this.name = 'BadRequestError';
72
+ }
73
+ }
74
+ exports.BadRequestError = BadRequestError;
75
+ /** 401 `unauthorized`: a missing, unknown or revoked key. */
76
+ class AuthenticationError extends APIError {
77
+ constructor(init) {
78
+ super(init);
79
+ this.name = 'AuthenticationError';
80
+ }
81
+ }
82
+ exports.AuthenticationError = AuthenticationError;
83
+ /** 403 `not_offered`: your agreement does not include this way of buying. */
84
+ class PermissionDeniedError extends APIError {
85
+ constructor(init) {
86
+ super(init);
87
+ this.name = 'PermissionDeniedError';
88
+ }
89
+ }
90
+ exports.PermissionDeniedError = PermissionDeniedError;
91
+ /** 404 `not_found`. */
92
+ class NotFoundError extends APIError {
93
+ constructor(init) {
94
+ super(init);
95
+ this.name = 'NotFoundError';
96
+ }
97
+ }
98
+ exports.NotFoundError = NotFoundError;
99
+ /**
100
+ * 409: `idempotency_conflict`, `esim_busy`, `price_changed`,
101
+ * `esim_limit_reached` or `esim_unusable`.
102
+ */
103
+ class ConflictError extends APIError {
104
+ constructor(init) {
105
+ super(init);
106
+ this.name = 'ConflictError';
107
+ }
108
+ }
109
+ exports.ConflictError = ConflictError;
110
+ /** 429 `rate_limited`: `retryAfter` says how many seconds to wait. */
111
+ class RateLimitError extends APIError {
112
+ constructor(init) {
113
+ super(init);
114
+ this.name = 'RateLimitError';
115
+ }
116
+ }
117
+ exports.RateLimitError = RateLimitError;
118
+ /**
119
+ * 5xx: `internal_error`, `provisioning_failed` (final; the failed order is in
120
+ * `order`), `esims_unavailable`, or an error page from the network on the way.
121
+ */
122
+ class InternalServerError extends APIError {
123
+ constructor(init) {
124
+ super(init);
125
+ this.name = 'InternalServerError';
126
+ }
127
+ }
128
+ exports.InternalServerError = InternalServerError;
129
+ /** The `APIError` subclass for an answer's status. */
130
+ function makeAPIError(init) {
131
+ switch (init.status) {
132
+ case 400:
133
+ return new BadRequestError(init);
134
+ case 401:
135
+ return new AuthenticationError(init);
136
+ case 403:
137
+ return new PermissionDeniedError(init);
138
+ case 404:
139
+ return new NotFoundError(init);
140
+ case 409:
141
+ return new ConflictError(init);
142
+ case 429:
143
+ return new RateLimitError(init);
144
+ default:
145
+ return init.status >= 500
146
+ ? new InternalServerError(init)
147
+ : new APIError(init);
148
+ }
149
+ }
150
+ /**
151
+ * No answer from the API after every retry: the network failed or the last
152
+ * attempt timed out. A purchase may or may not have happened: retry it with
153
+ * `idempotencyKey`.
154
+ */
155
+ class APIConnectionError extends OnesimError {
156
+ constructor(message, options) {
157
+ super(message, { cause: options.cause });
158
+ this.name = 'APIConnectionError';
159
+ if (options.idempotencyKey !== undefined)
160
+ this.idempotencyKey = options.idempotencyKey;
161
+ }
162
+ }
163
+ exports.APIConnectionError = APIConnectionError;
164
+ /** An `APIConnectionError` whose last attempt ran out of the client's `timeout`. */
165
+ class APIConnectionTimeoutError extends APIConnectionError {
166
+ constructor(message, options) {
167
+ super(message, options);
168
+ this.name = 'APIConnectionTimeoutError';
169
+ }
170
+ }
171
+ exports.APIConnectionTimeoutError = APIConnectionTimeoutError;
172
+ /** Polling an order ran out of time while it was still pending. */
173
+ class PollTimeoutError extends OnesimError {
174
+ /** The order polled. */
175
+ orderId;
176
+ /**
177
+ * The order as last read: still `pending`. Absent only when the time ran
178
+ * out before the first read answered.
179
+ */
180
+ order;
181
+ constructor(orderId, order, timeout) {
182
+ super(`Order ${orderId} was still pending after ${timeout} ms.`);
183
+ this.name = 'PollTimeoutError';
184
+ this.orderId = orderId;
185
+ if (order !== undefined)
186
+ this.order = order;
187
+ }
188
+ }
189
+ exports.PollTimeoutError = PollTimeoutError;
190
+ /** A webhook delivery failed verification. Answer it with a 400 and do not act on it. */
191
+ class WebhookVerificationError extends OnesimError {
192
+ reason;
193
+ constructor(reason, message) {
194
+ super(message);
195
+ this.name = 'WebhookVerificationError';
196
+ this.reason = reason;
197
+ }
198
+ }
199
+ exports.WebhookVerificationError = WebhookVerificationError;