@beliq/sdk 0.7.2 → 0.7.4

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/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
- import { A as AccountInfo, S as Standard, I as Invoice, n as GenerateProfile, F as FacturxProfile, V as ValidationResult, R as RulesetArtifact, a as DocumentInput, o as ValidateFormat, q as RulesetChannel, r as ParseFormat, u as ParseResult, C as ConvertTargetFormat, v as ConvertSourceFormat, w as ApiErrorCode } from './types-B-aV1djO.js';
1
+ import { A as AccountInfo, S as Standard, I as Invoice, n as GenerateProfile, F as FacturxProfile, V as ValidationResult, R as RulesetArtifact, a as DocumentInput, o as ValidateFormat, q as RulesetChannel, r as ParseFormat, u as ParseResult, C as ConvertTargetFormat, v as ConvertSourceFormat, w as ApiErrorCode } from './types-u5eeJLoG.js';
2
2
  import { PlainObject } from './helpers.js';
3
- export { x as ApiError, D as DEFAULT_BASE_URL, y as DEFAULT_MAX_RETRIES, z as DEFAULT_RETRY_BUDGET_MS, B as DEFAULT_TIMEOUT_MS, E as GenerateBody, G as GeneratePreset, H as GenerateResponse, L as LIVE_CONVERT_SOURCE_FORMATS, b as LIVE_CONVERT_TARGET_FORMATS, c as LIVE_GENERATE_PRESETS, d as LIVE_GENERATE_STANDARDS, e as LIVE_PARSE_FORMATS, f as LIVE_PROFILES, g as LIVE_PROFILES_BY_STANDARD, h as LIVE_VALIDATE_FORMATS, J as ParseWarning, K as ParseWarningCode, M as Severity, N as ValidationFormat, O as ValidationIssue, l as isProfileAllowedForStandard, p as profilesForStandard } from './types-B-aV1djO.js';
3
+ export { x as ApiError, D as DEFAULT_BASE_URL, y as DEFAULT_MAX_RETRIES, z as DEFAULT_RETRY_BUDGET_MS, B as DEFAULT_TIMEOUT_MS, E as GenerateBody, G as GeneratePreset, H as GenerateResponse, L as LIVE_CONVERT_SOURCE_FORMATS, b as LIVE_CONVERT_TARGET_FORMATS, c as LIVE_GENERATE_PRESETS, d as LIVE_GENERATE_STANDARDS, e as LIVE_PARSE_FORMATS, f as LIVE_PROFILES, g as LIVE_PROFILES_BY_STANDARD, h as LIVE_VALIDATE_FORMATS, J as ParseWarning, K as ParseWarningCode, M as Severity, N as ValidationFormat, O as ValidationIssue, l as isProfileAllowedForStandard, p as profilesForStandard } from './types-u5eeJLoG.js';
4
4
 
5
5
  interface BeliqOptions {
6
6
  /** API key from the beliq dashboard (API Keys). */
@@ -22,10 +22,11 @@ interface BeliqOptions {
22
22
  timeoutMs?: number;
23
23
  /**
24
24
  * Extra attempts after the first for the failures retried by count (default
25
- * 3): a 429 other than `QUOTA_EXCEEDED`, a 502 or 503 carrying any beliq error
26
- * code but a 503 `DATABASE_UNAVAILABLE`, and any thrown error but a connection
27
- * that could not be opened, such as a connection lost after the request was
28
- * sent. When you set it, it bounds every retry, so 0 disables retrying.
25
+ * 3): a 429 other than `QUOTA_EXCEEDED` and `DOCUMENT_CEILING_REACHED`, a
26
+ * 502 or 503 carrying any beliq error code but a 503 `DATABASE_UNAVAILABLE`,
27
+ * and any thrown error but a connection that could not be opened, such as a
28
+ * connection lost after the request was sent. When you set it, it bounds
29
+ * every retry, so 0 disables retrying.
29
30
  */
30
31
  maxRetries?: number;
31
32
  /**
@@ -60,7 +61,17 @@ interface GenerateInput {
60
61
  /** Raw JSON deep-merged into the request body. */
61
62
  advanced?: PlainObject;
62
63
  }
63
- interface DocumentOptions {
64
+ /** Options every method takes. */
65
+ interface RequestOptions {
66
+ /**
67
+ * Ends the call at once with the signal's reason, during an attempt or a
68
+ * wait between retries, so a worker that stops does not sit in a
69
+ * `Retry-After` wait. Nothing is sent when it is aborted already. An attempt
70
+ * already sent may still have run on beliq's side.
71
+ */
72
+ signal?: AbortSignal;
73
+ }
74
+ interface DocumentOptions extends RequestOptions {
64
75
  /** Override the sniffed request content type (application/xml | application/pdf). */
65
76
  contentType?: string;
66
77
  /**
@@ -169,9 +180,9 @@ declare class Beliq {
169
180
  readonly livemode: boolean;
170
181
  constructor(options: BeliqOptions);
171
182
  /** Account, plan, and quota context for the key. Does not consume quota. */
172
- me(): Promise<AccountInfo>;
183
+ me(options?: RequestOptions): Promise<AccountInfo>;
173
184
  /** Generate an e-invoice from an EN 16931 object. */
174
- generate(input: GenerateInput): Promise<GenerateResult>;
185
+ generate(input: GenerateInput, options?: RequestOptions): Promise<GenerateResult>;
175
186
  /** Validate a document. The result names the rules that ran and, in `verificationBadgeLabel` when the API states one, the check depth. */
176
187
  validate(document: DocumentInput, options?: ValidateOptions): Promise<ValidationResult>;
177
188
  /** Parse a document into a structured EN 16931 invoice. */
@@ -189,12 +200,56 @@ declare class BeliqApiError extends Error {
189
200
  readonly code?: ApiErrorCode | string;
190
201
  readonly status: number;
191
202
  readonly details?: Record<string, unknown>;
203
+ /**
204
+ * The response's `Retry-After` in seconds, when it gave one as whole seconds
205
+ * (RFC 9110 delay-seconds); `undefined` otherwise, an HTTP date included. The retry loop reads
206
+ * the header the same way, so this is the wait it would have taken.
207
+ */
208
+ readonly retryAfterSeconds?: number;
192
209
  constructor(message: string, opts: {
193
210
  code?: ApiErrorCode | string;
194
211
  status: number;
195
212
  details?: Record<string, unknown>;
213
+ retryAfterSeconds?: number;
196
214
  });
197
215
  }
198
216
 
199
- export { AccountInfo, ApiErrorCode, Beliq, BeliqApiError, ConvertSourceFormat, ConvertTargetFormat, DocumentInput, FacturxProfile, GenerateProfile, Invoice, ParseFormat, ParseResult, RulesetArtifact, RulesetChannel, Standard, ValidateFormat, ValidationResult };
200
- export type { BeliqOptions, ConvertMeta, ConvertOptions, ConvertResult, DocumentOptions, GenerateInput, GenerateMeta, GenerateResult, LostElement, LostElementsTruncated, ParseOptions, ValidateOptions };
217
+ /**
218
+ * How a failure is retried.
219
+ *
220
+ * `budget`: an outage a wait can outlast, retried until the time budget is spent.
221
+ * A 503 `DATABASE_UNAVAILABLE`, a 502 or 503 with no beliq error code (the edge
222
+ * answered, or the pod that held the connection is gone), and a connection that
223
+ * could not be opened.
224
+ *
225
+ * `count`: retried up to `maxRetries` times. A 429 other than `QUOTA_EXCEEDED`
226
+ * and `DOCUMENT_CEILING_REACHED`, since each one counts toward the account's
227
+ * throttle; a 502 or 503 with any other beliq code, `ENGINE_UNAVAILABLE`
228
+ * included, since an engine timeout answers that code too and a budget would run
229
+ * the same slow document dozens of times; and a thrown error that may have come
230
+ * after the request was sent. beliq may have run and charged that request, but
231
+ * it does not charge a repeat of a charged request within 15 minutes, up to 10
232
+ * repeats (beliq's own values, which no standard sets), and every attempt sends
233
+ * the same bytes.
234
+ *
235
+ * `none`: not retried. A 504 and this client's own timeout mean the work may
236
+ * still be running on beliq's side, and a repeat runs the same document again
237
+ * from the start, likely into the same deadline. A certificate failure and
238
+ * every other status are final too.
239
+ */
240
+ type RetryClass = 'budget' | 'count' | 'none';
241
+ /**
242
+ * How the client's retry loop treats a failure that a `Beliq` method threw, so
243
+ * a caller that turns the client's retry off can hand the failure to a retry
244
+ * of its own. The loop uses this same function, so its answer is the one the
245
+ * loop acted on: `budget` was retried until `retryBudgetMs` was spent, `count`
246
+ * up to `maxRetries` times, `none` not at all. It reads a `BeliqApiError` by its
247
+ * status and code, `TIMEOUT` (this client's own deadline) as `none`, and any
248
+ * other error by its `cause.code`, as `fetch` throws it. An abort by the
249
+ * caller's own `signal` throws the signal's reason, which the loop never
250
+ * classifies: check the signal's `aborted` before asking this.
251
+ */
252
+ declare function retryClass(error: unknown): RetryClass;
253
+
254
+ export { AccountInfo, ApiErrorCode, Beliq, BeliqApiError, ConvertSourceFormat, ConvertTargetFormat, DocumentInput, FacturxProfile, GenerateProfile, Invoice, ParseFormat, ParseResult, RulesetArtifact, RulesetChannel, Standard, ValidateFormat, ValidationResult, retryClass };
255
+ export type { BeliqOptions, ConvertMeta, ConvertOptions, ConvertResult, DocumentOptions, GenerateInput, GenerateMeta, GenerateResult, LostElement, LostElementsTruncated, ParseOptions, RequestOptions, RetryClass, ValidateOptions };
package/dist/index.js CHANGED
@@ -141,14 +141,26 @@ var BeliqApiError = class extends Error {
141
141
  code;
142
142
  status;
143
143
  details;
144
+ /**
145
+ * The response's `Retry-After` in seconds, when it gave one as whole seconds
146
+ * (RFC 9110 delay-seconds); `undefined` otherwise, an HTTP date included. The retry loop reads
147
+ * the header the same way, so this is the wait it would have taken.
148
+ */
149
+ retryAfterSeconds;
144
150
  constructor(message, opts) {
145
151
  super(message);
146
152
  this.name = "BeliqApiError";
147
153
  this.code = opts.code;
148
154
  this.status = opts.status;
149
155
  this.details = opts.details;
156
+ this.retryAfterSeconds = opts.retryAfterSeconds;
150
157
  }
151
158
  };
159
+ var DELAY_SECONDS = /^\d+$/;
160
+ function parseRetryAfterSeconds(headers) {
161
+ const header = headers?.get("retry-after");
162
+ return header !== null && header !== void 0 && DELAY_SECONDS.test(header) ? Number(header) : void 0;
163
+ }
152
164
  function parseEnvelope(bytes) {
153
165
  let text;
154
166
  try {
@@ -164,11 +176,16 @@ function parseEnvelope(bytes) {
164
176
  return null;
165
177
  }
166
178
  }
167
- function errorFromResponse(status, bytes) {
179
+ function errorFromResponse(status, bytes, headers) {
168
180
  const envelope = parseEnvelope(bytes);
169
181
  const err = envelope?.error;
170
182
  const message = err?.message ?? envelope?.message ?? `beliq request failed with status ${status}`;
171
- return new BeliqApiError(message, { code: err?.code, status, details: err?.details });
183
+ return new BeliqApiError(message, {
184
+ code: err?.code,
185
+ status,
186
+ details: err?.details,
187
+ retryAfterSeconds: parseRetryAfterSeconds(headers)
188
+ });
172
189
  }
173
190
 
174
191
  // src/constants.ts
@@ -240,7 +257,10 @@ var LIVE_CONVERT_TARGET_FORMATS = [
240
257
  ];
241
258
 
242
259
  // src/transport.ts
243
- var QUOTA_EXHAUSTED_CODE = "QUOTA_EXCEEDED";
260
+ var QUOTA_EXHAUSTED_CODES = /* @__PURE__ */ new Set([
261
+ "QUOTA_EXCEEDED",
262
+ "DOCUMENT_CEILING_REACHED"
263
+ ]);
244
264
  var DATABASE_UNAVAILABLE_CODE = "DATABASE_UNAVAILABLE";
245
265
  var BEFORE_SEND_CODES = /* @__PURE__ */ new Set([
246
266
  "ECONNREFUSED",
@@ -250,15 +270,57 @@ var BEFORE_SEND_CODES = /* @__PURE__ */ new Set([
250
270
  "EHOSTUNREACH",
251
271
  "UND_ERR_CONNECT_TIMEOUT"
252
272
  ]);
273
+ var CERTIFICATE_ERROR_CODES = /* @__PURE__ */ new Set([
274
+ "UNABLE_TO_GET_ISSUER_CERT",
275
+ "UNABLE_TO_GET_CRL",
276
+ "UNABLE_TO_DECRYPT_CERT_SIGNATURE",
277
+ "UNABLE_TO_DECRYPT_CRL_SIGNATURE",
278
+ "UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY",
279
+ "CERT_SIGNATURE_FAILURE",
280
+ "CRL_SIGNATURE_FAILURE",
281
+ "CERT_NOT_YET_VALID",
282
+ "CERT_HAS_EXPIRED",
283
+ "CRL_NOT_YET_VALID",
284
+ "CRL_HAS_EXPIRED",
285
+ "ERROR_IN_CERT_NOT_BEFORE_FIELD",
286
+ "ERROR_IN_CERT_NOT_AFTER_FIELD",
287
+ "ERROR_IN_CRL_LAST_UPDATE_FIELD",
288
+ "ERROR_IN_CRL_NEXT_UPDATE_FIELD",
289
+ "OUT_OF_MEM",
290
+ "DEPTH_ZERO_SELF_SIGNED_CERT",
291
+ "SELF_SIGNED_CERT_IN_CHAIN",
292
+ "UNABLE_TO_GET_ISSUER_CERT_LOCALLY",
293
+ "UNABLE_TO_VERIFY_LEAF_SIGNATURE",
294
+ "CERT_CHAIN_TOO_LONG",
295
+ "CERT_REVOKED",
296
+ "INVALID_CA",
297
+ "PATH_LENGTH_EXCEEDED",
298
+ "INVALID_PURPOSE",
299
+ "CERT_UNTRUSTED",
300
+ "CERT_REJECTED",
301
+ "HOSTNAME_MISMATCH"
302
+ ]);
303
+ function isCertificateFailure(code) {
304
+ return CERTIFICATE_ERROR_CODES.has(code) || code === "ERR_TLS_CERT_ALTNAME_INVALID";
305
+ }
253
306
  function classifyStatus(status, code) {
254
- if (status === 429) return code === QUOTA_EXHAUSTED_CODE ? void 0 : "count";
255
- if (status !== 502 && status !== 503) return void 0;
307
+ if (status === 429) return code !== void 0 && QUOTA_EXHAUSTED_CODES.has(code) ? "none" : "count";
308
+ if (status !== 502 && status !== 503) return "none";
256
309
  if (!code) return "budget";
257
310
  return status === 503 && code === DATABASE_UNAVAILABLE_CODE ? "budget" : "count";
258
311
  }
259
312
  function classifyThrown(err) {
260
313
  const code = err?.cause?.code;
261
- return typeof code === "string" && BEFORE_SEND_CODES.has(code) ? "budget" : "count";
314
+ if (typeof code !== "string") return "count";
315
+ if (isCertificateFailure(code)) return "none";
316
+ return BEFORE_SEND_CODES.has(code) ? "budget" : "count";
317
+ }
318
+ function retryClass(error) {
319
+ if (error instanceof BeliqApiError || error?.name === "BeliqApiError" && typeof error.status === "number") {
320
+ const apiError = error;
321
+ return classifyStatus(apiError.status, apiError.code);
322
+ }
323
+ return classifyThrown(error);
262
324
  }
263
325
  var BACKOFF_BASE_MS = 500;
264
326
  var BACKOFF_CEILING_MS = 3e4;
@@ -277,20 +339,28 @@ function buildUrl(baseUrl, path, query) {
277
339
  return qs ? `${baseUrl}${path}?${qs}` : `${baseUrl}${path}`;
278
340
  }
279
341
  function retryDelayMs(res, attempt, config) {
280
- const header = res?.headers.get("retry-after");
281
- if (header) {
282
- const seconds = Number(header);
283
- if (Number.isFinite(seconds) && seconds >= 0) {
284
- return seconds * 1e3 + Math.random() * RETRY_AFTER_JITTER_MS;
285
- }
286
- }
342
+ const seconds = parseRetryAfterSeconds(res?.headers);
343
+ if (seconds !== void 0) return seconds * 1e3 + Math.random() * RETRY_AFTER_JITTER_MS;
287
344
  const base = config.backoffBaseMs ?? BACKOFF_BASE_MS;
288
345
  const ceiling = config.backoffCeilingMs ?? BACKOFF_CEILING_MS;
289
346
  const backoff = Math.min(base * 2 ** attempt, ceiling / 2);
290
347
  return backoff + Math.random() * backoff;
291
348
  }
292
- var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
293
- async function send(config, req) {
349
+ function sleep(ms, signal) {
350
+ return new Promise((resolve, reject) => {
351
+ signal?.throwIfAborted();
352
+ const onAbort = () => {
353
+ clearTimeout(timer);
354
+ reject(signal?.reason);
355
+ };
356
+ const timer = setTimeout(() => {
357
+ signal?.removeEventListener("abort", onAbort);
358
+ resolve();
359
+ }, ms);
360
+ signal?.addEventListener("abort", onAbort, { once: true });
361
+ });
362
+ }
363
+ async function send(config, req, signal) {
294
364
  const headers = { ...req.headers, ...authHeaders(config) };
295
365
  if (req.contentType) headers["Content-Type"] = req.contentType;
296
366
  if (req.accept) headers["Accept"] = req.accept;
@@ -299,11 +369,14 @@ async function send(config, req) {
299
369
  const started = performance.now();
300
370
  let countedRetries = 0;
301
371
  for (let attempt = 0; ; attempt++) {
372
+ signal?.throwIfAborted();
302
373
  const controller = new AbortController();
374
+ const onCallerAbort = () => controller.abort();
375
+ signal?.addEventListener("abort", onCallerAbort, { once: true });
303
376
  const timer = config.timeoutMs > 0 ? setTimeout(() => controller.abort(), config.timeoutMs) : void 0;
304
377
  let res;
305
378
  let failure;
306
- let retryClass;
379
+ let kind;
307
380
  try {
308
381
  res = await config.fetchImpl(url, {
309
382
  method: req.method,
@@ -313,10 +386,10 @@ async function send(config, req) {
313
386
  });
314
387
  const bytes = new Uint8Array(await res.arrayBuffer());
315
388
  if (res.ok) return { status: res.status, headers: res.headers, bytes };
316
- const apiError = errorFromResponse(res.status, bytes);
317
- failure = apiError;
318
- retryClass = classifyStatus(apiError.status, apiError.code);
389
+ failure = errorFromResponse(res.status, bytes, res.headers);
390
+ kind = retryClass(failure);
319
391
  } catch (err) {
392
+ signal?.throwIfAborted();
320
393
  if (controller.signal.aborted) {
321
394
  throw new BeliqApiError(
322
395
  `beliq: request to ${req.path} exceeded ${config.timeoutMs}ms`,
@@ -324,20 +397,21 @@ async function send(config, req) {
324
397
  );
325
398
  }
326
399
  failure = err;
327
- retryClass = classifyThrown(err);
400
+ kind = retryClass(err);
328
401
  } finally {
329
402
  if (timer) clearTimeout(timer);
403
+ signal?.removeEventListener("abort", onCallerAbort);
330
404
  }
331
- if (retryClass === void 0) throw failure;
405
+ if (kind === "none") throw failure;
332
406
  if (config.maxRetries !== void 0) {
333
407
  if (attempt >= config.maxRetries) throw failure;
334
- } else if (retryClass === "count" && countedRetries >= DEFAULT_MAX_RETRIES) {
408
+ } else if (kind === "count" && countedRetries >= DEFAULT_MAX_RETRIES) {
335
409
  throw failure;
336
410
  }
337
411
  const delay = retryDelayMs(res, attempt, config);
338
412
  if (performance.now() - started + delay > config.retryBudgetMs) throw failure;
339
- if (retryClass === "count") countedRetries++;
340
- await sleep(delay);
413
+ if (kind === "count") countedRetries++;
414
+ await sleep(delay, signal);
341
415
  }
342
416
  }
343
417
 
@@ -422,19 +496,20 @@ var Beliq = class {
422
496
  };
423
497
  }
424
498
  /** Account, plan, and quota context for the key. Does not consume quota. */
425
- async me() {
426
- return this.#json({ operation: "me" });
499
+ async me(options = {}) {
500
+ return this.#json({ operation: "me" }, options.signal);
427
501
  }
428
502
  /** Generate an e-invoice from an EN 16931 object. */
429
- async generate(input) {
503
+ async generate(input, options = {}) {
430
504
  const res = await send(
431
505
  this.#config,
432
- buildRequest({ operation: "generate", ...input, sealed: input.seal })
506
+ buildRequest({ operation: "generate", ...input, sealed: input.seal }),
507
+ options.signal
433
508
  );
434
509
  const meta = generateMeta(res.headers);
435
510
  if (input.seal) {
436
511
  const envelope = parseEnvelope(res.bytes);
437
- if (envelope?.success === false) throw errorFromResponse(res.status, res.bytes);
512
+ if (envelope?.success === false) throw errorFromResponse(res.status, res.bytes, res.headers);
438
513
  const data = envelope?.data;
439
514
  if (!data || data.output === void 0) {
440
515
  throw new BeliqApiError("beliq: seal response was not a JSON envelope", {
@@ -468,7 +543,7 @@ var Beliq = class {
468
543
  validateFormat: options.format,
469
544
  franceCtc: options.franceCtc,
470
545
  ruleset: options.ruleset
471
- });
546
+ }, options.signal);
472
547
  }
473
548
  /** Parse a document into a structured EN 16931 invoice. */
474
549
  async parse(document, options = {}) {
@@ -476,7 +551,7 @@ var Beliq = class {
476
551
  operation: "parse",
477
552
  ...this.#rawParams(document, options),
478
553
  parseFormat: options.format
479
- });
554
+ }, options.signal);
480
555
  }
481
556
  /** Convert a document between EN 16931 formats. */
482
557
  async convert(document, options) {
@@ -489,7 +564,8 @@ var Beliq = class {
489
564
  targetFormat: options.targetFormat,
490
565
  targetProfile: options.targetProfile,
491
566
  dropFranceCtcOverlay: options.dropFranceCtcOverlay
492
- })
567
+ }),
568
+ options.signal
493
569
  );
494
570
  return {
495
571
  contentType: res.headers.get("content-type") ?? "application/octet-stream",
@@ -505,10 +581,10 @@ var Beliq = class {
505
581
  advanced: options.advanced
506
582
  };
507
583
  }
508
- async #json(params) {
509
- const res = await send(this.#config, buildRequest(params));
584
+ async #json(params, signal) {
585
+ const res = await send(this.#config, buildRequest(params), signal);
510
586
  const envelope = parseEnvelope(res.bytes);
511
- if (envelope?.success === false) throw errorFromResponse(res.status, res.bytes);
587
+ if (envelope?.success === false) throw errorFromResponse(res.status, res.bytes, res.headers);
512
588
  if (!envelope || envelope.data === void 0) {
513
589
  throw new BeliqApiError("beliq: response was not a JSON envelope", { status: res.status });
514
590
  }
@@ -531,5 +607,6 @@ export {
531
607
  LIVE_PROFILES_BY_STANDARD,
532
608
  LIVE_VALIDATE_FORMATS,
533
609
  isProfileAllowedForStandard,
534
- profilesForStandard
610
+ profilesForStandard,
611
+ retryClass
535
612
  };