@beliq/sdk 0.5.2 → 0.7.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/CHANGELOG.md CHANGED
@@ -4,6 +4,71 @@
4
4
  resolves 0.4.x and never reaches 0.5.0. Additive spec syncs ship as patches for
5
5
  that reason, and a minor is reserved for a change that needs consumers to opt in.
6
6
 
7
+ ## 0.7.0 - 2026-11-06
8
+
9
+ A minor, because a call that meets an outage can now take up to 15 minutes to
10
+ return, plus the last attempt's deadline, where 0.6 gave up after 3 retries,
11
+ and a `^0.6.0` range does not reach a minor.
12
+
13
+ - The client retries an outage by a time budget, the new option
14
+ `retryBudgetMs`, default `DEFAULT_RETRY_BUDGET_MS` (900000, 15 minutes from
15
+ the start of the first attempt). It covers a `503` `DATABASE_UNAVAILABLE`, a
16
+ `502` or `503` with no beliq error code, and a connection that could not be
17
+ opened (`ECONNREFUSED`, `ENOTFOUND`, `EAI_AGAIN`, `ENETUNREACH`,
18
+ `EHOSTUNREACH`, `UND_ERR_CONNECT_TIMEOUT`).
19
+ 0.6 retried each of them 3 times, about 2 minutes at `Retry-After: 30`. No
20
+ attempt starts after the budget.
21
+ - Every wait follows the server's `Retry-After` in full. 0.6 cut the header to
22
+ 30 s. A `Retry-After` longer than the budget left ends the call at once with
23
+ that error.
24
+ - Without a `Retry-After`, no backoff wait reaches 30 s. Before, the wait
25
+ doubled with every attempt and had no ceiling.
26
+ - `maxRetries` keeps its default of 3 for everything else that is retried: a
27
+ `429` `RATE_LIMITED` or `ACCOUNT_THROTTLED`, a `503` `ENGINE_UNAVAILABLE` and
28
+ any other `502` or `503` with a beliq error code, and any other thrown error.
29
+ When you set `maxRetries`, `DEFAULT_MAX_RETRIES` included, it bounds every
30
+ retry, the budget's included, so `maxRetries: 0` still turns retrying off.
31
+ - The README and the option comments no longer say that a retry never costs a
32
+ second quota unit. A `DATABASE_UNAVAILABLE` after the charge is refunded only
33
+ when the database lets it, a test key's units are never refunded, and a
34
+ connection lost after the request was sent can mean the first request was
35
+ charged. The README's table lists what is retried, which 0.6's README
36
+ understated: it left out the thrown errors.
37
+
38
+ ## 0.6.0 - 2026-11-03
39
+
40
+ A minor, because code can stop compiling in two places, and a `^0.5.0` range
41
+ does not reach a minor.
42
+
43
+ - `ConvertMeta.lostElements` holds the entries of `x-lost-elements` as the API
44
+ sends them. Each is a `LostElement` with `path`, `value`, `reason`, `severity`
45
+ and `acceptableLoss`, as
46
+ https://docs.beliq.eu/api-reference/convert/#lostelement-schema describes.
47
+ Past the API's 6 KB header cap the list holds one `LostElementsTruncated`
48
+ entry, `{ truncated: true, reason? }`, instead, and `lostElementsCount` stays
49
+ the exact count. The field was typed `string[]` and held `"[object Object]"`
50
+ for every entry, so code that reads an entry as a string stops compiling.
51
+ Both types are exported.
52
+ - The vendored `openapi.json` is document `0.23.0` of the API, up from
53
+ `0.16.0`. In the generated types, `generate()`'s `invoice.spain` (Facturae)
54
+ takes only the value the engine builds for each field: `modality` `I`,
55
+ `invoiceIssuerType` `EM`, `invoiceDocumentType` `FC`, `invoiceClass` `OO`
56
+ and `taxTypeCode` `01`. `invoice.poland` (KSeF) takes only `"2"` for
57
+ `adnotacje.P_18`, `adnotacje.P_23`, `jst` and `gv`. Code that passes another
58
+ value stops compiling. The API refuses those values.
59
+ - The error code union gains `DATABASE_UNAVAILABLE`, a 503 on every route,
60
+ which the client retries like any 503. A `switch` over the code that
61
+ TypeScript checks for exhaustiveness needs the new case.
62
+ - `ValidateFormat` and `ParseFormat` take `poland_ksef_fa2`.
63
+ - `LIVE_VALIDATE_FORMATS` gains `fatturapa`, `facturae`, `eslog` and
64
+ `poland_ksef_fa3`, the four national formats `GET /v1/rulesets` lists, each
65
+ Schema-checked. A tool that builds a validate option list from it offers the
66
+ four. `LIVE_PARSE_FORMATS` stays `auto`, `cii` and `ubl`, because
67
+ `POST /v1/parse` reads CII and UBL only.
68
+ - `advanced` on `validate()`, `parse()` and `convert()` is merged into the
69
+ query. The API answers 400 `VALIDATION_ERROR` to a query key the operation
70
+ does not declare, and `err.details.fields` names it.
71
+
7
72
  ## 0.5.2 - 2026-10-24
8
73
 
9
74
  A patch: `@beliq/sdk/helpers` gains the wording for a verdict and a converted
package/README.md CHANGED
@@ -92,21 +92,64 @@ backoff around it.
92
92
  ```ts
93
93
  new Beliq({
94
94
  apiKey: 'blq_live_...',
95
- timeoutMs: 90_000, // per-attempt deadline (default)
96
- maxRetries: 3, // extra attempts after the first (default)
95
+ timeoutMs: 90_000, // per-attempt deadline (default)
96
+ retryBudgetMs: 900_000, // how long to keep retrying an outage: 15 minutes (default)
97
97
  });
98
98
  ```
99
99
 
100
- Both defaults are exported as `DEFAULT_TIMEOUT_MS` and `DEFAULT_MAX_RETRIES`, so
101
- you can derive from them instead of repeating the numbers.
102
-
103
- Only `429`, `502` and `503` are retried, honouring the server's `Retry-After`
104
- with jitter. beliq refunds the document's quota unit on a `503`, so a retry never
105
- costs you a second document.
100
+ Leave `maxRetries` unset unless you want to bound every retry: unset, it allows 3
101
+ retries of the failures retried by count and leaves the budget's failures to the
102
+ budget, while any number you pass, `DEFAULT_MAX_RETRIES` included, bounds them
103
+ all.
104
+
105
+ The defaults are exported as `DEFAULT_TIMEOUT_MS`, `DEFAULT_RETRY_BUDGET_MS` and
106
+ `DEFAULT_MAX_RETRIES`, so you can derive from them instead of repeating the
107
+ numbers.
108
+
109
+ | Failure | Retried |
110
+ |---|---|
111
+ | `503` `DATABASE_UNAVAILABLE` | until the budget is spent |
112
+ | `502` or `503` with no beliq error code, which a proxy in front of the API sends | until the budget is spent |
113
+ | A connection that could not be opened: a `cause.code` of `ECONNREFUSED`, `ENOTFOUND`, `EAI_AGAIN`, `ENETUNREACH`, `EHOSTUNREACH` or `UND_ERR_CONNECT_TIMEOUT` | until the budget is spent |
114
+ | `429` `RATE_LIMITED` or `ACCOUNT_THROTTLED` | up to `maxRetries` times |
115
+ | `503` `ENGINE_UNAVAILABLE`, and any other `502` or `503` with a beliq error code | up to `maxRetries` times |
116
+ | Any other thrown error, such as a connection lost after the request was sent | up to `maxRetries` times |
117
+ | `429` `QUOTA_EXCEEDED`, `504`, this client's own timeout, and every other status | never |
118
+
119
+ Every wait follows the server's `Retry-After` in full, plus up to 250 ms of
120
+ jitter. Without one, the client backs off exponentially from 500 ms with jitter,
121
+ and no wait reaches 30 s. No attempt starts after the budget, so a `Retry-After`
122
+ longer than the time left ends the call at once with that error, and an outage
123
+ longer than the budget ends it with the last error. A call that meets an outage
124
+ can therefore take up to 15 minutes to return, plus the last attempt's own
125
+ deadline of up to `timeoutMs`. A host name that does not resolve counts as an
126
+ outage too, so a misspelt `baseUrl` takes the whole budget to fail. Where your
127
+ code cannot wait that long, such as inside a request with a time limit of its
128
+ own, pass a shorter `retryBudgetMs`. The 15 minutes are beliq's own choice, not
129
+ a standard's: they outlast two of the three database outages beliq has
130
+ measured, of about 9 and 12 minutes. The third lasted 33 minutes, and a call
131
+ that meets one like it ends with the last error.
132
+
133
+ `maxRetries: 0` turns retrying off, and so does `retryBudgetMs: 0`.
134
+
135
+ What a retry costs:
136
+
137
+ - Most `DATABASE_UNAVAILABLE` answers come before any quota unit is spent, and a
138
+ retry of one of those costs nothing. When the request had spent a unit, beliq
139
+ tries to refund it at once and says on the `x-beliq-quota-refunded` header
140
+ whether that worked. While the database is out, the refund usually cannot be
141
+ applied; https://docs.beliq.eu/api-reference/errors/ says how such a unit is
142
+ reconciled.
143
+ - The unit of an `ENGINE_UNAVAILABLE` is refunded, within the cap that page
144
+ names.
145
+ - A test key's sandbox units are never refunded.
146
+ - A connection lost after the request was sent can mean beliq already processed
147
+ it. A retry of `generate`, `validate`, `parse` or `convert` is then a second
148
+ request and spends a second unit.
106
149
 
107
150
  `504` and this client's own timeout are deliberately **not** retried: both mean
108
- the work may still be running on beliq's side, so retrying risks producing a
109
- second document rather than recovering the first.
151
+ the work may still be running on beliq's side, so a retry would run it, and
152
+ charge it, a second time.
110
153
 
111
154
  A `429` carrying `QUOTA_EXCEEDED` is not retried either. `RATE_LIMITED` and
112
155
  `ACCOUNT_THROTTLED` clear on their own, but a spent monthly allowance only returns
@@ -129,7 +172,7 @@ shorter than the server's own turns completed work into an unknown outcome. Set
129
172
  | `parse(document, options?)` | POST /v1/parse | XML or PDF | `ParseResult` |
130
173
  | `convert(document, options)` | POST /v1/convert | XML or PDF | `{ contentType, bytes, meta }` |
131
174
 
132
- `document` accepts a `string`, `Uint8Array`, `Buffer`, `ArrayBuffer`, or typed array. The content type is sniffed from the bytes (PDF vs XML) unless you pass `options.contentType`. `generate` and `convert` return raw document bytes plus the response-header metadata (`schematronVersion`, `pdfKind`, `sourceFormat`/`targetFormat`, `lostElements`, `conversionTools`, `livemode`); for an XML output, `generate` also decodes `xml`.
175
+ `document` accepts a `string`, `Uint8Array`, `Buffer`, `ArrayBuffer`, or typed array. The content type is sniffed from the bytes (PDF vs XML) unless you pass `options.contentType`. `generate` and `convert` return raw document bytes plus the response-header metadata (`schematronVersion`, `pdfKind`, `sourceFormat`/`targetFormat`, `lostElements`, `conversionTools`, `livemode`); for an XML output, `generate` also decodes `xml`. Each entry of `lostElements` is a `LostElement` as https://docs.beliq.eu/api-reference/convert/#lostelement-schema describes it, except past the API's 6 KB header cap, where the list holds one `{ truncated: true, reason }` entry instead and `lostElementsCount` stays the exact count.
133
176
 
134
177
  ### Verify-it-yourself seal
135
178
 
package/dist/helpers.cjs CHANGED
@@ -209,7 +209,15 @@ function isProfileAllowedForStandard(standard, profile) {
209
209
  const allowed = profilesForStandard(standard);
210
210
  return allowed.length === 0 || allowed.includes(profile);
211
211
  }
212
- var LIVE_VALIDATE_FORMATS = ["auto", "cii", "ubl"];
212
+ var LIVE_VALIDATE_FORMATS = [
213
+ "auto",
214
+ "cii",
215
+ "ubl",
216
+ "fatturapa",
217
+ "facturae",
218
+ "eslog",
219
+ "poland_ksef_fa3"
220
+ ];
213
221
  var LIVE_PARSE_FORMATS = ["auto", "cii", "ubl"];
214
222
  var LIVE_CONVERT_SOURCE_FORMATS = [
215
223
  "auto",
@@ -1,5 +1,6 @@
1
- import { P as PlainObject, V as ValidationResult } from './types-BRDATaM6.cjs';
2
- export { D as DEFAULT_BASE_URL, a as DocumentInput, G as GeneratePreset, 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, i as compactQuery, j as decodeUtf8, k as isPlainObject, l as isProfileAllowedForStandard, m as mergeDeep, p as profilesForStandard, s as sniffContentType, t as toBytes } from './types-BRDATaM6.cjs';
1
+ import { P as PlainObject } from './types-BjW5SogX.cjs';
2
+ import { ValidationResult } from './index.cjs';
3
+ export { D as DEFAULT_BASE_URL, a as DocumentInput, G as GeneratePreset, 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, i as compactQuery, j as decodeUtf8, k as isPlainObject, l as isProfileAllowedForStandard, m as mergeDeep, p as profilesForStandard, s as sniffContentType, t as toBytes } from './types-BjW5SogX.cjs';
3
4
 
4
5
  type Operation = 'me' | 'generate' | 'validate' | 'parse' | 'convert';
5
6
  /** 'json' => parse the `{ success, data }` envelope; 'binary' => return raw bytes. */
@@ -82,4 +83,5 @@ declare function pdfInputLine(result: Pick<ValidationResult, 'pdfInput'>): strin
82
83
  /** Which ruleset channel the API says served the request, when the result names one. */
83
84
  declare function rulesetChannelLine(result: Pick<ValidationResult, 'rulesetChannel' | 'rulesetFellBack' | 'rulesetSunsetsOn'>): string | undefined;
84
85
 
85
- export { type BuildParams, type BuiltRequest, CONVERT_PDF_LINE, DEPTH_NOT_STATED, FRANCE_CTC_BLOCKING_FINDING_RULE_ID, type Operation, type OutputKind, PlainObject, type QueryValue, buildRequest, checkDepth, franceBlockLines, franceBlockingRuleIds, pdfInputLine, rulesetChannelLine, verdictWord };
86
+ export { CONVERT_PDF_LINE, DEPTH_NOT_STATED, FRANCE_CTC_BLOCKING_FINDING_RULE_ID, PlainObject, buildRequest, checkDepth, franceBlockLines, franceBlockingRuleIds, pdfInputLine, rulesetChannelLine, verdictWord };
87
+ export type { BuildParams, BuiltRequest, Operation, OutputKind, QueryValue };
package/dist/helpers.d.ts CHANGED
@@ -1,5 +1,6 @@
1
- import { P as PlainObject, V as ValidationResult } from './types-BRDATaM6.js';
2
- export { D as DEFAULT_BASE_URL, a as DocumentInput, G as GeneratePreset, 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, i as compactQuery, j as decodeUtf8, k as isPlainObject, l as isProfileAllowedForStandard, m as mergeDeep, p as profilesForStandard, s as sniffContentType, t as toBytes } from './types-BRDATaM6.js';
1
+ import { P as PlainObject } from './types-BjW5SogX.js';
2
+ import { ValidationResult } from './index.js';
3
+ export { D as DEFAULT_BASE_URL, a as DocumentInput, G as GeneratePreset, 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, i as compactQuery, j as decodeUtf8, k as isPlainObject, l as isProfileAllowedForStandard, m as mergeDeep, p as profilesForStandard, s as sniffContentType, t as toBytes } from './types-BjW5SogX.js';
3
4
 
4
5
  type Operation = 'me' | 'generate' | 'validate' | 'parse' | 'convert';
5
6
  /** 'json' => parse the `{ success, data }` envelope; 'binary' => return raw bytes. */
@@ -82,4 +83,5 @@ declare function pdfInputLine(result: Pick<ValidationResult, 'pdfInput'>): strin
82
83
  /** Which ruleset channel the API says served the request, when the result names one. */
83
84
  declare function rulesetChannelLine(result: Pick<ValidationResult, 'rulesetChannel' | 'rulesetFellBack' | 'rulesetSunsetsOn'>): string | undefined;
84
85
 
85
- export { type BuildParams, type BuiltRequest, CONVERT_PDF_LINE, DEPTH_NOT_STATED, FRANCE_CTC_BLOCKING_FINDING_RULE_ID, type Operation, type OutputKind, PlainObject, type QueryValue, buildRequest, checkDepth, franceBlockLines, franceBlockingRuleIds, pdfInputLine, rulesetChannelLine, verdictWord };
86
+ export { CONVERT_PDF_LINE, DEPTH_NOT_STATED, FRANCE_CTC_BLOCKING_FINDING_RULE_ID, PlainObject, buildRequest, checkDepth, franceBlockLines, franceBlockingRuleIds, pdfInputLine, rulesetChannelLine, verdictWord };
87
+ export type { BuildParams, BuiltRequest, Operation, OutputKind, QueryValue };
package/dist/helpers.js CHANGED
@@ -157,7 +157,15 @@ function isProfileAllowedForStandard(standard, profile) {
157
157
  const allowed = profilesForStandard(standard);
158
158
  return allowed.length === 0 || allowed.includes(profile);
159
159
  }
160
- var LIVE_VALIDATE_FORMATS = ["auto", "cii", "ubl"];
160
+ var LIVE_VALIDATE_FORMATS = [
161
+ "auto",
162
+ "cii",
163
+ "ubl",
164
+ "fatturapa",
165
+ "facturae",
166
+ "eslog",
167
+ "poland_ksef_fa3"
168
+ ];
161
169
  var LIVE_PARSE_FORMATS = ["auto", "cii", "ubl"];
162
170
  var LIVE_CONVERT_SOURCE_FORMATS = [
163
171
  "auto",
package/dist/index.cjs CHANGED
@@ -24,6 +24,7 @@ __export(index_exports, {
24
24
  BeliqApiError: () => BeliqApiError,
25
25
  DEFAULT_BASE_URL: () => DEFAULT_BASE_URL,
26
26
  DEFAULT_MAX_RETRIES: () => DEFAULT_MAX_RETRIES,
27
+ DEFAULT_RETRY_BUDGET_MS: () => DEFAULT_RETRY_BUDGET_MS,
27
28
  DEFAULT_TIMEOUT_MS: () => DEFAULT_TIMEOUT_MS,
28
29
  LIVE_CONVERT_SOURCE_FORMATS: () => LIVE_CONVERT_SOURCE_FORMATS,
29
30
  LIVE_CONVERT_TARGET_FORMATS: () => LIVE_CONVERT_TARGET_FORMATS,
@@ -211,6 +212,7 @@ function errorFromResponse(status, bytes) {
211
212
  var DEFAULT_BASE_URL = "https://api.beliq.eu";
212
213
  var DEFAULT_TIMEOUT_MS = 9e4;
213
214
  var DEFAULT_MAX_RETRIES = 3;
215
+ var DEFAULT_RETRY_BUDGET_MS = 9e5;
214
216
  var LIVE_GENERATE_STANDARDS = [
215
217
  "xrechnung",
216
218
  "zugferd",
@@ -246,7 +248,15 @@ function isProfileAllowedForStandard(standard, profile) {
246
248
  const allowed = profilesForStandard(standard);
247
249
  return allowed.length === 0 || allowed.includes(profile);
248
250
  }
249
- var LIVE_VALIDATE_FORMATS = ["auto", "cii", "ubl"];
251
+ var LIVE_VALIDATE_FORMATS = [
252
+ "auto",
253
+ "cii",
254
+ "ubl",
255
+ "fatturapa",
256
+ "facturae",
257
+ "eslog",
258
+ "poland_ksef_fa3"
259
+ ];
250
260
  var LIVE_PARSE_FORMATS = ["auto", "cii", "ubl"];
251
261
  var LIVE_CONVERT_SOURCE_FORMATS = [
252
262
  "auto",
@@ -267,14 +277,29 @@ var LIVE_CONVERT_TARGET_FORMATS = [
267
277
  ];
268
278
 
269
279
  // src/transport.ts
270
- var RETRYABLE_STATUSES = /* @__PURE__ */ new Set([429, 502, 503]);
271
280
  var QUOTA_EXHAUSTED_CODE = "QUOTA_EXCEEDED";
272
- function isRetryable(status, code) {
273
- if (!RETRYABLE_STATUSES.has(status)) return false;
274
- return !(status === 429 && code === QUOTA_EXHAUSTED_CODE);
281
+ var DATABASE_UNAVAILABLE_CODE = "DATABASE_UNAVAILABLE";
282
+ var BEFORE_SEND_CODES = /* @__PURE__ */ new Set([
283
+ "ECONNREFUSED",
284
+ "ENOTFOUND",
285
+ "EAI_AGAIN",
286
+ "ENETUNREACH",
287
+ "EHOSTUNREACH",
288
+ "UND_ERR_CONNECT_TIMEOUT"
289
+ ]);
290
+ function classifyStatus(status, code) {
291
+ if (status === 429) return code === QUOTA_EXHAUSTED_CODE ? void 0 : "count";
292
+ if (status !== 502 && status !== 503) return void 0;
293
+ if (!code) return "budget";
294
+ return status === 503 && code === DATABASE_UNAVAILABLE_CODE ? "budget" : "count";
295
+ }
296
+ function classifyThrown(err) {
297
+ const code = err?.cause?.code;
298
+ return typeof code === "string" && BEFORE_SEND_CODES.has(code) ? "budget" : "count";
275
299
  }
276
- var MAX_RETRY_AFTER_MS = 3e4;
277
300
  var BACKOFF_BASE_MS = 500;
301
+ var BACKOFF_CEILING_MS = 3e4;
302
+ var RETRY_AFTER_JITTER_MS = 250;
278
303
  function authHeaders(config) {
279
304
  return config.auth === "bearer" ? { Authorization: `Bearer ${config.apiKey}` } : { "X-API-Key": config.apiKey };
280
305
  }
@@ -288,15 +313,17 @@ function buildUrl(baseUrl, path, query) {
288
313
  const qs = params.toString();
289
314
  return qs ? `${baseUrl}${path}?${qs}` : `${baseUrl}${path}`;
290
315
  }
291
- function retryDelayMs(res, attempt) {
316
+ function retryDelayMs(res, attempt, config) {
292
317
  const header = res?.headers.get("retry-after");
293
318
  if (header) {
294
319
  const seconds = Number(header);
295
320
  if (Number.isFinite(seconds) && seconds >= 0) {
296
- return Math.min(seconds * 1e3, MAX_RETRY_AFTER_MS) + Math.random() * 250;
321
+ return seconds * 1e3 + Math.random() * RETRY_AFTER_JITTER_MS;
297
322
  }
298
323
  }
299
- const backoff = BACKOFF_BASE_MS * 2 ** attempt;
324
+ const base = config.backoffBaseMs ?? BACKOFF_BASE_MS;
325
+ const ceiling = config.backoffCeilingMs ?? BACKOFF_CEILING_MS;
326
+ const backoff = Math.min(base * 2 ** attempt, ceiling / 2);
300
327
  return backoff + Math.random() * backoff;
301
328
  }
302
329
  var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
@@ -306,11 +333,14 @@ async function send(config, req) {
306
333
  if (req.accept) headers["Accept"] = req.accept;
307
334
  const body = req.jsonBody !== void 0 ? JSON.stringify(req.jsonBody) : req.rawBody;
308
335
  const url = buildUrl(config.baseUrl, req.path, req.query);
309
- let lastError;
310
- for (let attempt = 0; attempt <= config.maxRetries; attempt++) {
336
+ const started = performance.now();
337
+ let countedRetries = 0;
338
+ for (let attempt = 0; ; attempt++) {
311
339
  const controller = new AbortController();
312
340
  const timer = config.timeoutMs > 0 ? setTimeout(() => controller.abort(), config.timeoutMs) : void 0;
313
341
  let res;
342
+ let failure;
343
+ let retryClass;
314
344
  try {
315
345
  res = await config.fetchImpl(url, {
316
346
  method: req.method,
@@ -321,26 +351,31 @@ async function send(config, req) {
321
351
  const bytes = new Uint8Array(await res.arrayBuffer());
322
352
  if (res.ok) return { status: res.status, headers: res.headers, bytes };
323
353
  const apiError = errorFromResponse(res.status, bytes);
324
- lastError = apiError;
325
- if (!isRetryable(apiError.status, apiError.code) || attempt === config.maxRetries) {
326
- throw apiError;
327
- }
354
+ failure = apiError;
355
+ retryClass = classifyStatus(apiError.status, apiError.code);
328
356
  } catch (err) {
329
- if (err instanceof BeliqApiError && !isRetryable(err.status, err.code)) throw err;
330
357
  if (controller.signal.aborted) {
331
358
  throw new BeliqApiError(
332
359
  `beliq: request to ${req.path} exceeded ${config.timeoutMs}ms`,
333
360
  { status: 0, code: "TIMEOUT" }
334
361
  );
335
362
  }
336
- lastError = err;
337
- if (attempt === config.maxRetries) throw err;
363
+ failure = err;
364
+ retryClass = classifyThrown(err);
338
365
  } finally {
339
366
  if (timer) clearTimeout(timer);
340
367
  }
341
- await sleep(retryDelayMs(res, attempt));
368
+ if (retryClass === void 0) throw failure;
369
+ if (config.maxRetries !== void 0) {
370
+ if (attempt >= config.maxRetries) throw failure;
371
+ } else if (retryClass === "count" && countedRetries >= DEFAULT_MAX_RETRIES) {
372
+ throw failure;
373
+ }
374
+ const delay = retryDelayMs(res, attempt, config);
375
+ if (performance.now() - started + delay > config.retryBudgetMs) throw failure;
376
+ if (retryClass === "count") countedRetries++;
377
+ await sleep(delay);
342
378
  }
343
- throw lastError;
344
379
  }
345
380
 
346
381
  // src/client.ts
@@ -366,6 +401,16 @@ function parseRulesetArtifacts(headers) {
366
401
  return void 0;
367
402
  }
368
403
  }
404
+ function parseLostElements(headers) {
405
+ const raw = headers.get("x-lost-elements");
406
+ if (!raw) return void 0;
407
+ try {
408
+ const parsed = JSON.parse(raw);
409
+ return Array.isArray(parsed) ? parsed : void 0;
410
+ } catch {
411
+ return void 0;
412
+ }
413
+ }
369
414
  function generateMeta(headers) {
370
415
  return {
371
416
  schematronVersion: headers.get("x-schematron-version") ?? void 0,
@@ -377,22 +422,13 @@ function generateMeta(headers) {
377
422
  };
378
423
  }
379
424
  function convertMeta(headers) {
380
- let lostElements;
381
- const lostRaw = headers.get("x-lost-elements");
382
- if (lostRaw) {
383
- try {
384
- const parsed = JSON.parse(lostRaw);
385
- if (Array.isArray(parsed)) lostElements = parsed.map(String);
386
- } catch {
387
- }
388
- }
389
425
  const countRaw = headers.get("x-lost-elements-count");
390
426
  return {
391
427
  sourceFormat: headers.get("x-source-format") ?? void 0,
392
428
  targetFormat: headers.get("x-target-format") ?? void 0,
393
429
  profileDetected: headers.get("x-profile-detected") ?? void 0,
394
430
  lostElementsCount: countRaw != null ? Number(countRaw) : void 0,
395
- lostElements,
431
+ lostElements: parseLostElements(headers),
396
432
  conversionTools: headers.get("x-conversion-tools") ?? void 0,
397
433
  livemode: livemodeHeader(headers)
398
434
  };
@@ -418,7 +454,8 @@ var Beliq = class {
418
454
  auth: options.auth ?? "header",
419
455
  fetchImpl,
420
456
  timeoutMs: options.timeoutMs ?? DEFAULT_TIMEOUT_MS,
421
- maxRetries: options.maxRetries ?? DEFAULT_MAX_RETRIES
457
+ maxRetries: options.maxRetries,
458
+ retryBudgetMs: options.retryBudgetMs ?? DEFAULT_RETRY_BUDGET_MS
422
459
  };
423
460
  }
424
461
  /** Account, plan, and quota context for the key. Does not consume quota. */
@@ -520,6 +557,7 @@ var Beliq = class {
520
557
  BeliqApiError,
521
558
  DEFAULT_BASE_URL,
522
559
  DEFAULT_MAX_RETRIES,
560
+ DEFAULT_RETRY_BUDGET_MS,
523
561
  DEFAULT_TIMEOUT_MS,
524
562
  LIVE_CONVERT_SOURCE_FORMATS,
525
563
  LIVE_CONVERT_TARGET_FORMATS,
package/dist/index.d.cts CHANGED
@@ -1,5 +1,6 @@
1
- import { A as AccountInfo, S as Standard, I as Invoice, n as GenerateProfile, F as FacturxProfile, P as PlainObject, V as ValidationResult, R as RulesetArtifact, a as DocumentInput, o as ValidateFormat, q as ParseFormat, r as ParseResult, C as ConvertTargetFormat, u as ConvertSourceFormat, v as ApiErrorCode } from './types-BRDATaM6.cjs';
2
- export { w as ApiError, D as DEFAULT_BASE_URL, x as DEFAULT_MAX_RETRIES, y as DEFAULT_TIMEOUT_MS, z as GenerateBody, G as GeneratePreset, B 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, E as ParseWarning, H as ParseWarningCode, J as Severity, K as ValidationFormat, M as ValidationIssue, l as isProfileAllowedForStandard, p as profilesForStandard } from './types-BRDATaM6.cjs';
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 ParseFormat, r as ParseResult, C as ConvertTargetFormat, u as ConvertSourceFormat, v as ApiErrorCode } from './types-BjW5SogX.cjs';
2
+ import { PlainObject } from './helpers.cjs';
3
+ export { w as ApiError, D as DEFAULT_BASE_URL, x as DEFAULT_MAX_RETRIES, y as DEFAULT_RETRY_BUDGET_MS, z as DEFAULT_TIMEOUT_MS, B as GenerateBody, G as GeneratePreset, E 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, H as ParseWarning, J as ParseWarningCode, K as Severity, M as ValidationFormat, N as ValidationIssue, l as isProfileAllowedForStandard, p as profilesForStandard } from './types-BjW5SogX.cjs';
3
4
 
4
5
  interface BeliqOptions {
5
6
  /** API key from the beliq dashboard (API Keys). */
@@ -15,16 +16,27 @@ interface BeliqOptions {
15
16
  * the full Schematron rule set over a document, so a generate or validate can
16
17
  * take tens of seconds legitimately. Set well above the latency you expect:
17
18
  * a deadline shorter than the server's own means giving up on work that is
18
- * still running, which is the one case a retry can duplicate a document.
19
- * 0 disables the deadline.
19
+ * still running, and this client does not retry its own timeout, since the
20
+ * work may have finished. 0 disables the deadline.
20
21
  */
21
22
  timeoutMs?: number;
22
23
  /**
23
- * Extra attempts after the first (default 3). Retries only 429, 502 and 503,
24
- * honouring `Retry-After`; beliq refunds the quota unit on a 503, so a retry
25
- * costs nothing. 0 disables retrying.
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.
26
29
  */
27
30
  maxRetries?: number;
31
+ /**
32
+ * How long to keep retrying, in ms from the start of the first attempt
33
+ * (default 900000, 15 minutes). A 503 `DATABASE_UNAVAILABLE`, a 502 or 503 with
34
+ * no beliq error code, and a connection that could not be opened are retried
35
+ * until it is spent. Every wait follows the server's `Retry-After` in full; no
36
+ * attempt starts after the budget, so a `Retry-After` longer than what is left
37
+ * ends the call at once. 0 disables retrying.
38
+ */
39
+ retryBudgetMs?: number;
28
40
  }
29
41
  interface GenerateInput {
30
42
  standard: Standard;
@@ -51,7 +63,11 @@ interface GenerateInput {
51
63
  interface DocumentOptions {
52
64
  /** Override the sniffed request content type (application/xml | application/pdf). */
53
65
  contentType?: string;
54
- /** Raw JSON deep-merged into the query. */
66
+ /**
67
+ * Raw JSON deep-merged into the query; its values win over the named options.
68
+ * The API answers 400 `VALIDATION_ERROR` to a query key the operation does not
69
+ * declare, and `details.fields` names it.
70
+ */
55
71
  advanced?: PlainObject;
56
72
  }
57
73
  interface ValidateOptions extends DocumentOptions {
@@ -91,13 +107,29 @@ interface GenerateResult {
91
107
  validationResult?: ValidationResult;
92
108
  meta: GenerateMeta;
93
109
  }
110
+ /** One loss a conversion recorded: https://docs.beliq.eu/api-reference/convert/#lostelement-schema */
111
+ interface LostElement {
112
+ path: string;
113
+ value: string | null;
114
+ reason: string;
115
+ severity: 'info' | 'warning';
116
+ acceptableLoss: boolean;
117
+ }
118
+ /**
119
+ * The one entry `lostElements` holds in place of the list when the list would pass
120
+ * the API's 6 KB header cap. `lostElementsCount` stays the exact count.
121
+ */
122
+ interface LostElementsTruncated {
123
+ truncated: true;
124
+ reason?: string;
125
+ }
94
126
  /** Header metadata returned alongside a converted document. */
95
127
  interface ConvertMeta {
96
128
  sourceFormat?: string;
97
129
  targetFormat?: string;
98
130
  profileDetected?: string;
99
131
  lostElementsCount?: number;
100
- lostElements?: string[];
132
+ lostElements?: Array<LostElement | LostElementsTruncated>;
101
133
  conversionTools?: string;
102
134
  /** True for a live key, false for a blq_test_ sandbox key. */
103
135
  livemode?: boolean;
@@ -145,4 +177,5 @@ declare class BeliqApiError extends Error {
145
177
  });
146
178
  }
147
179
 
148
- export { AccountInfo, ApiErrorCode, Beliq, BeliqApiError, type BeliqOptions, type ConvertMeta, type ConvertOptions, type ConvertResult, ConvertSourceFormat, ConvertTargetFormat, DocumentInput, type DocumentOptions, FacturxProfile, type GenerateInput, type GenerateMeta, GenerateProfile, type GenerateResult, Invoice, ParseFormat, type ParseOptions, ParseResult, RulesetArtifact, Standard, ValidateFormat, type ValidateOptions, ValidationResult };
180
+ export { AccountInfo, ApiErrorCode, Beliq, BeliqApiError, ConvertSourceFormat, ConvertTargetFormat, DocumentInput, FacturxProfile, GenerateProfile, Invoice, ParseFormat, ParseResult, RulesetArtifact, Standard, ValidateFormat, ValidationResult };
181
+ export type { BeliqOptions, ConvertMeta, ConvertOptions, ConvertResult, DocumentOptions, GenerateInput, GenerateMeta, GenerateResult, LostElement, LostElementsTruncated, ParseOptions, ValidateOptions };
package/dist/index.d.ts CHANGED
@@ -1,5 +1,6 @@
1
- import { A as AccountInfo, S as Standard, I as Invoice, n as GenerateProfile, F as FacturxProfile, P as PlainObject, V as ValidationResult, R as RulesetArtifact, a as DocumentInput, o as ValidateFormat, q as ParseFormat, r as ParseResult, C as ConvertTargetFormat, u as ConvertSourceFormat, v as ApiErrorCode } from './types-BRDATaM6.js';
2
- export { w as ApiError, D as DEFAULT_BASE_URL, x as DEFAULT_MAX_RETRIES, y as DEFAULT_TIMEOUT_MS, z as GenerateBody, G as GeneratePreset, B 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, E as ParseWarning, H as ParseWarningCode, J as Severity, K as ValidationFormat, M as ValidationIssue, l as isProfileAllowedForStandard, p as profilesForStandard } from './types-BRDATaM6.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 ParseFormat, r as ParseResult, C as ConvertTargetFormat, u as ConvertSourceFormat, v as ApiErrorCode } from './types-BjW5SogX.js';
2
+ import { PlainObject } from './helpers.js';
3
+ export { w as ApiError, D as DEFAULT_BASE_URL, x as DEFAULT_MAX_RETRIES, y as DEFAULT_RETRY_BUDGET_MS, z as DEFAULT_TIMEOUT_MS, B as GenerateBody, G as GeneratePreset, E 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, H as ParseWarning, J as ParseWarningCode, K as Severity, M as ValidationFormat, N as ValidationIssue, l as isProfileAllowedForStandard, p as profilesForStandard } from './types-BjW5SogX.js';
3
4
 
4
5
  interface BeliqOptions {
5
6
  /** API key from the beliq dashboard (API Keys). */
@@ -15,16 +16,27 @@ interface BeliqOptions {
15
16
  * the full Schematron rule set over a document, so a generate or validate can
16
17
  * take tens of seconds legitimately. Set well above the latency you expect:
17
18
  * a deadline shorter than the server's own means giving up on work that is
18
- * still running, which is the one case a retry can duplicate a document.
19
- * 0 disables the deadline.
19
+ * still running, and this client does not retry its own timeout, since the
20
+ * work may have finished. 0 disables the deadline.
20
21
  */
21
22
  timeoutMs?: number;
22
23
  /**
23
- * Extra attempts after the first (default 3). Retries only 429, 502 and 503,
24
- * honouring `Retry-After`; beliq refunds the quota unit on a 503, so a retry
25
- * costs nothing. 0 disables retrying.
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.
26
29
  */
27
30
  maxRetries?: number;
31
+ /**
32
+ * How long to keep retrying, in ms from the start of the first attempt
33
+ * (default 900000, 15 minutes). A 503 `DATABASE_UNAVAILABLE`, a 502 or 503 with
34
+ * no beliq error code, and a connection that could not be opened are retried
35
+ * until it is spent. Every wait follows the server's `Retry-After` in full; no
36
+ * attempt starts after the budget, so a `Retry-After` longer than what is left
37
+ * ends the call at once. 0 disables retrying.
38
+ */
39
+ retryBudgetMs?: number;
28
40
  }
29
41
  interface GenerateInput {
30
42
  standard: Standard;
@@ -51,7 +63,11 @@ interface GenerateInput {
51
63
  interface DocumentOptions {
52
64
  /** Override the sniffed request content type (application/xml | application/pdf). */
53
65
  contentType?: string;
54
- /** Raw JSON deep-merged into the query. */
66
+ /**
67
+ * Raw JSON deep-merged into the query; its values win over the named options.
68
+ * The API answers 400 `VALIDATION_ERROR` to a query key the operation does not
69
+ * declare, and `details.fields` names it.
70
+ */
55
71
  advanced?: PlainObject;
56
72
  }
57
73
  interface ValidateOptions extends DocumentOptions {
@@ -91,13 +107,29 @@ interface GenerateResult {
91
107
  validationResult?: ValidationResult;
92
108
  meta: GenerateMeta;
93
109
  }
110
+ /** One loss a conversion recorded: https://docs.beliq.eu/api-reference/convert/#lostelement-schema */
111
+ interface LostElement {
112
+ path: string;
113
+ value: string | null;
114
+ reason: string;
115
+ severity: 'info' | 'warning';
116
+ acceptableLoss: boolean;
117
+ }
118
+ /**
119
+ * The one entry `lostElements` holds in place of the list when the list would pass
120
+ * the API's 6 KB header cap. `lostElementsCount` stays the exact count.
121
+ */
122
+ interface LostElementsTruncated {
123
+ truncated: true;
124
+ reason?: string;
125
+ }
94
126
  /** Header metadata returned alongside a converted document. */
95
127
  interface ConvertMeta {
96
128
  sourceFormat?: string;
97
129
  targetFormat?: string;
98
130
  profileDetected?: string;
99
131
  lostElementsCount?: number;
100
- lostElements?: string[];
132
+ lostElements?: Array<LostElement | LostElementsTruncated>;
101
133
  conversionTools?: string;
102
134
  /** True for a live key, false for a blq_test_ sandbox key. */
103
135
  livemode?: boolean;
@@ -145,4 +177,5 @@ declare class BeliqApiError extends Error {
145
177
  });
146
178
  }
147
179
 
148
- export { AccountInfo, ApiErrorCode, Beliq, BeliqApiError, type BeliqOptions, type ConvertMeta, type ConvertOptions, type ConvertResult, ConvertSourceFormat, ConvertTargetFormat, DocumentInput, type DocumentOptions, FacturxProfile, type GenerateInput, type GenerateMeta, GenerateProfile, type GenerateResult, Invoice, ParseFormat, type ParseOptions, ParseResult, RulesetArtifact, Standard, ValidateFormat, type ValidateOptions, ValidationResult };
180
+ export { AccountInfo, ApiErrorCode, Beliq, BeliqApiError, ConvertSourceFormat, ConvertTargetFormat, DocumentInput, FacturxProfile, GenerateProfile, Invoice, ParseFormat, ParseResult, RulesetArtifact, Standard, ValidateFormat, ValidationResult };
181
+ export type { BeliqOptions, ConvertMeta, ConvertOptions, ConvertResult, DocumentOptions, GenerateInput, GenerateMeta, GenerateResult, LostElement, LostElementsTruncated, ParseOptions, ValidateOptions };