@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/dist/index.js CHANGED
@@ -171,6 +171,7 @@ function errorFromResponse(status, bytes) {
171
171
  var DEFAULT_BASE_URL = "https://api.beliq.eu";
172
172
  var DEFAULT_TIMEOUT_MS = 9e4;
173
173
  var DEFAULT_MAX_RETRIES = 3;
174
+ var DEFAULT_RETRY_BUDGET_MS = 9e5;
174
175
  var LIVE_GENERATE_STANDARDS = [
175
176
  "xrechnung",
176
177
  "zugferd",
@@ -206,7 +207,15 @@ function isProfileAllowedForStandard(standard, profile) {
206
207
  const allowed = profilesForStandard(standard);
207
208
  return allowed.length === 0 || allowed.includes(profile);
208
209
  }
209
- var LIVE_VALIDATE_FORMATS = ["auto", "cii", "ubl"];
210
+ var LIVE_VALIDATE_FORMATS = [
211
+ "auto",
212
+ "cii",
213
+ "ubl",
214
+ "fatturapa",
215
+ "facturae",
216
+ "eslog",
217
+ "poland_ksef_fa3"
218
+ ];
210
219
  var LIVE_PARSE_FORMATS = ["auto", "cii", "ubl"];
211
220
  var LIVE_CONVERT_SOURCE_FORMATS = [
212
221
  "auto",
@@ -227,14 +236,29 @@ var LIVE_CONVERT_TARGET_FORMATS = [
227
236
  ];
228
237
 
229
238
  // src/transport.ts
230
- var RETRYABLE_STATUSES = /* @__PURE__ */ new Set([429, 502, 503]);
231
239
  var QUOTA_EXHAUSTED_CODE = "QUOTA_EXCEEDED";
232
- function isRetryable(status, code) {
233
- if (!RETRYABLE_STATUSES.has(status)) return false;
234
- return !(status === 429 && code === QUOTA_EXHAUSTED_CODE);
240
+ var DATABASE_UNAVAILABLE_CODE = "DATABASE_UNAVAILABLE";
241
+ var BEFORE_SEND_CODES = /* @__PURE__ */ new Set([
242
+ "ECONNREFUSED",
243
+ "ENOTFOUND",
244
+ "EAI_AGAIN",
245
+ "ENETUNREACH",
246
+ "EHOSTUNREACH",
247
+ "UND_ERR_CONNECT_TIMEOUT"
248
+ ]);
249
+ function classifyStatus(status, code) {
250
+ if (status === 429) return code === QUOTA_EXHAUSTED_CODE ? void 0 : "count";
251
+ if (status !== 502 && status !== 503) return void 0;
252
+ if (!code) return "budget";
253
+ return status === 503 && code === DATABASE_UNAVAILABLE_CODE ? "budget" : "count";
254
+ }
255
+ function classifyThrown(err) {
256
+ const code = err?.cause?.code;
257
+ return typeof code === "string" && BEFORE_SEND_CODES.has(code) ? "budget" : "count";
235
258
  }
236
- var MAX_RETRY_AFTER_MS = 3e4;
237
259
  var BACKOFF_BASE_MS = 500;
260
+ var BACKOFF_CEILING_MS = 3e4;
261
+ var RETRY_AFTER_JITTER_MS = 250;
238
262
  function authHeaders(config) {
239
263
  return config.auth === "bearer" ? { Authorization: `Bearer ${config.apiKey}` } : { "X-API-Key": config.apiKey };
240
264
  }
@@ -248,15 +272,17 @@ function buildUrl(baseUrl, path, query) {
248
272
  const qs = params.toString();
249
273
  return qs ? `${baseUrl}${path}?${qs}` : `${baseUrl}${path}`;
250
274
  }
251
- function retryDelayMs(res, attempt) {
275
+ function retryDelayMs(res, attempt, config) {
252
276
  const header = res?.headers.get("retry-after");
253
277
  if (header) {
254
278
  const seconds = Number(header);
255
279
  if (Number.isFinite(seconds) && seconds >= 0) {
256
- return Math.min(seconds * 1e3, MAX_RETRY_AFTER_MS) + Math.random() * 250;
280
+ return seconds * 1e3 + Math.random() * RETRY_AFTER_JITTER_MS;
257
281
  }
258
282
  }
259
- const backoff = BACKOFF_BASE_MS * 2 ** attempt;
283
+ const base = config.backoffBaseMs ?? BACKOFF_BASE_MS;
284
+ const ceiling = config.backoffCeilingMs ?? BACKOFF_CEILING_MS;
285
+ const backoff = Math.min(base * 2 ** attempt, ceiling / 2);
260
286
  return backoff + Math.random() * backoff;
261
287
  }
262
288
  var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
@@ -266,11 +292,14 @@ async function send(config, req) {
266
292
  if (req.accept) headers["Accept"] = req.accept;
267
293
  const body = req.jsonBody !== void 0 ? JSON.stringify(req.jsonBody) : req.rawBody;
268
294
  const url = buildUrl(config.baseUrl, req.path, req.query);
269
- let lastError;
270
- for (let attempt = 0; attempt <= config.maxRetries; attempt++) {
295
+ const started = performance.now();
296
+ let countedRetries = 0;
297
+ for (let attempt = 0; ; attempt++) {
271
298
  const controller = new AbortController();
272
299
  const timer = config.timeoutMs > 0 ? setTimeout(() => controller.abort(), config.timeoutMs) : void 0;
273
300
  let res;
301
+ let failure;
302
+ let retryClass;
274
303
  try {
275
304
  res = await config.fetchImpl(url, {
276
305
  method: req.method,
@@ -281,26 +310,31 @@ async function send(config, req) {
281
310
  const bytes = new Uint8Array(await res.arrayBuffer());
282
311
  if (res.ok) return { status: res.status, headers: res.headers, bytes };
283
312
  const apiError = errorFromResponse(res.status, bytes);
284
- lastError = apiError;
285
- if (!isRetryable(apiError.status, apiError.code) || attempt === config.maxRetries) {
286
- throw apiError;
287
- }
313
+ failure = apiError;
314
+ retryClass = classifyStatus(apiError.status, apiError.code);
288
315
  } catch (err) {
289
- if (err instanceof BeliqApiError && !isRetryable(err.status, err.code)) throw err;
290
316
  if (controller.signal.aborted) {
291
317
  throw new BeliqApiError(
292
318
  `beliq: request to ${req.path} exceeded ${config.timeoutMs}ms`,
293
319
  { status: 0, code: "TIMEOUT" }
294
320
  );
295
321
  }
296
- lastError = err;
297
- if (attempt === config.maxRetries) throw err;
322
+ failure = err;
323
+ retryClass = classifyThrown(err);
298
324
  } finally {
299
325
  if (timer) clearTimeout(timer);
300
326
  }
301
- await sleep(retryDelayMs(res, attempt));
327
+ if (retryClass === void 0) throw failure;
328
+ if (config.maxRetries !== void 0) {
329
+ if (attempt >= config.maxRetries) throw failure;
330
+ } else if (retryClass === "count" && countedRetries >= DEFAULT_MAX_RETRIES) {
331
+ throw failure;
332
+ }
333
+ const delay = retryDelayMs(res, attempt, config);
334
+ if (performance.now() - started + delay > config.retryBudgetMs) throw failure;
335
+ if (retryClass === "count") countedRetries++;
336
+ await sleep(delay);
302
337
  }
303
- throw lastError;
304
338
  }
305
339
 
306
340
  // src/client.ts
@@ -326,6 +360,16 @@ function parseRulesetArtifacts(headers) {
326
360
  return void 0;
327
361
  }
328
362
  }
363
+ function parseLostElements(headers) {
364
+ const raw = headers.get("x-lost-elements");
365
+ if (!raw) return void 0;
366
+ try {
367
+ const parsed = JSON.parse(raw);
368
+ return Array.isArray(parsed) ? parsed : void 0;
369
+ } catch {
370
+ return void 0;
371
+ }
372
+ }
329
373
  function generateMeta(headers) {
330
374
  return {
331
375
  schematronVersion: headers.get("x-schematron-version") ?? void 0,
@@ -337,22 +381,13 @@ function generateMeta(headers) {
337
381
  };
338
382
  }
339
383
  function convertMeta(headers) {
340
- let lostElements;
341
- const lostRaw = headers.get("x-lost-elements");
342
- if (lostRaw) {
343
- try {
344
- const parsed = JSON.parse(lostRaw);
345
- if (Array.isArray(parsed)) lostElements = parsed.map(String);
346
- } catch {
347
- }
348
- }
349
384
  const countRaw = headers.get("x-lost-elements-count");
350
385
  return {
351
386
  sourceFormat: headers.get("x-source-format") ?? void 0,
352
387
  targetFormat: headers.get("x-target-format") ?? void 0,
353
388
  profileDetected: headers.get("x-profile-detected") ?? void 0,
354
389
  lostElementsCount: countRaw != null ? Number(countRaw) : void 0,
355
- lostElements,
390
+ lostElements: parseLostElements(headers),
356
391
  conversionTools: headers.get("x-conversion-tools") ?? void 0,
357
392
  livemode: livemodeHeader(headers)
358
393
  };
@@ -378,7 +413,8 @@ var Beliq = class {
378
413
  auth: options.auth ?? "header",
379
414
  fetchImpl,
380
415
  timeoutMs: options.timeoutMs ?? DEFAULT_TIMEOUT_MS,
381
- maxRetries: options.maxRetries ?? DEFAULT_MAX_RETRIES
416
+ maxRetries: options.maxRetries,
417
+ retryBudgetMs: options.retryBudgetMs ?? DEFAULT_RETRY_BUDGET_MS
382
418
  };
383
419
  }
384
420
  /** Account, plan, and quota context for the key. Does not consume quota. */
@@ -479,6 +515,7 @@ export {
479
515
  BeliqApiError,
480
516
  DEFAULT_BASE_URL,
481
517
  DEFAULT_MAX_RETRIES,
518
+ DEFAULT_RETRY_BUDGET_MS,
482
519
  DEFAULT_TIMEOUT_MS,
483
520
  LIVE_CONVERT_SOURCE_FORMATS,
484
521
  LIVE_CONVERT_TARGET_FORMATS,