ksef-client-ts 0.6.2 → 0.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/README.md +3 -1
  2. package/dist/cli.js +2630 -634
  3. package/dist/cli.js.map +1 -1
  4. package/dist/index.cjs +1689 -138
  5. package/dist/index.cjs.map +1 -1
  6. package/dist/index.d.cts +361 -17
  7. package/dist/index.d.ts +361 -17
  8. package/dist/index.js +1657 -138
  9. package/dist/index.js.map +1 -1
  10. package/docs/schemas/FA/bazowe/ElementarneTypyDanych_v10-0E.xsd +1 -0
  11. package/docs/schemas/FA/bazowe/KodyKrajow_v10-0E.xsd +1283 -0
  12. package/docs/schemas/FA/bazowe/StrukturyDanych_v10-0E.xsd +1 -0
  13. package/docs/schemas/FA/schemat_FA(2)_v1-0E.xsd +3661 -0
  14. package/docs/schemas/FA/schemat_FA(3)_v1-0E.xsd +3950 -0
  15. package/docs/schemas/PEF/Schemat_PEF(3)_v2-1.xsd +977 -0
  16. package/docs/schemas/PEF/Schemat_PEF_KOR(3)_v2-1.xsd +926 -0
  17. package/docs/schemas/PEF/bazowe/20241206_PEFPL-CommonAggregateComponents-2.1-v1.4.34.xsd +428 -0
  18. package/docs/schemas/PEF/bazowe/20241206_PEFPL-CommonBasicComponents-2.1-v1.4.34.xsd +65 -0
  19. package/docs/schemas/PEF/bazowe/CCTS_CCT_SchemaModule-2.1.xsd +731 -0
  20. package/docs/schemas/PEF/bazowe/UBL-CommonAggregateComponents-2.1.xsd +39799 -0
  21. package/docs/schemas/PEF/bazowe/UBL-CommonBasicComponents-2.1.xsd +5389 -0
  22. package/docs/schemas/PEF/bazowe/UBL-CommonExtensionComponents-2.1.xsd +223 -0
  23. package/docs/schemas/PEF/bazowe/UBL-CommonSignatureComponents-2.1.xsd +101 -0
  24. package/docs/schemas/PEF/bazowe/UBL-ExtensionContentDataType-2.1.xsd +89 -0
  25. package/docs/schemas/PEF/bazowe/UBL-QualifiedDataTypes-2.1.xsd +69 -0
  26. package/docs/schemas/PEF/bazowe/UBL-SignatureAggregateComponents-2.1.xsd +138 -0
  27. package/docs/schemas/PEF/bazowe/UBL-SignatureBasicComponents-2.1.xsd +78 -0
  28. package/docs/schemas/PEF/bazowe/UBL-UnqualifiedDataTypes-2.1.xsd +553 -0
  29. package/docs/schemas/PEF/bazowe/UBL-XAdESv132-2.1.xsd +476 -0
  30. package/docs/schemas/PEF/bazowe/UBL-XAdESv141-2.1.xsd +25 -0
  31. package/docs/schemas/PEF/bazowe/UBL-xmldsig-core-schema-2.1.xsd +323 -0
  32. package/docs/schemas/PEF/bazowe/commontypes.xsd +735 -0
  33. package/docs/schemas/PEF/bazowe/isotypes.xsd +3158 -0
  34. package/docs/schemas/RR/schemat_FA_RR(1)_v1-1E.xsd +2188 -0
  35. package/docs/schemas/RR/schemat_RR(1)_v1-0E.xsd +2188 -0
  36. package/docs/schemas/RR/schemat_RR(1)_v1-1E.xsd +2188 -0
  37. package/package.json +14 -2
package/dist/index.cjs CHANGED
@@ -30,11 +30,22 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
30
30
  ));
31
31
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
32
32
 
33
+ // node_modules/tsup/assets/cjs_shims.js
34
+ var getImportMetaUrl, importMetaUrl;
35
+ var init_cjs_shims = __esm({
36
+ "node_modules/tsup/assets/cjs_shims.js"() {
37
+ "use strict";
38
+ getImportMetaUrl = () => typeof document === "undefined" ? new URL(`file:${__filename}`).href : document.currentScript && document.currentScript.tagName.toUpperCase() === "SCRIPT" ? document.currentScript.src : new URL("main.js", document.baseURI).href;
39
+ importMetaUrl = /* @__PURE__ */ getImportMetaUrl();
40
+ }
41
+ });
42
+
33
43
  // src/config/environments.ts
34
44
  var Environment;
35
45
  var init_environments = __esm({
36
46
  "src/config/environments.ts"() {
37
47
  "use strict";
48
+ init_cjs_shims();
38
49
  Environment = {
39
50
  TEST: {
40
51
  apiUrl: "https://api-test.ksef.mf.gov.pl",
@@ -65,13 +76,15 @@ function resolveOptions(options = {}) {
65
76
  apiVersion: options.apiVersion ?? DEFAULT_API_VERSION,
66
77
  timeout: options.timeout ?? DEFAULT_TIMEOUT,
67
78
  customHeaders: options.customHeaders ?? {},
68
- environmentName: options.environment ?? (options.baseUrl ? void 0 : "TEST")
79
+ environmentName: options.environment ?? (options.baseUrl ? void 0 : "TEST"),
80
+ errorFormat: options.errorFormat ?? "problem-details"
69
81
  };
70
82
  }
71
83
  var DEFAULT_API_VERSION, DEFAULT_TIMEOUT;
72
84
  var init_options = __esm({
73
85
  "src/config/options.ts"() {
74
86
  "use strict";
87
+ init_cjs_shims();
75
88
  init_environments();
76
89
  DEFAULT_API_VERSION = "v2";
77
90
  DEFAULT_TIMEOUT = 3e4;
@@ -82,6 +95,7 @@ var init_options = __esm({
82
95
  var init_config = __esm({
83
96
  "src/config/index.ts"() {
84
97
  "use strict";
98
+ init_cjs_shims();
85
99
  init_environments();
86
100
  init_options();
87
101
  }
@@ -92,6 +106,7 @@ var KSeFError;
92
106
  var init_ksef_error = __esm({
93
107
  "src/errors/ksef-error.ts"() {
94
108
  "use strict";
109
+ init_cjs_shims();
95
110
  KSeFError = class extends Error {
96
111
  constructor(message) {
97
112
  super(message);
@@ -106,6 +121,7 @@ var KSeFApiError;
106
121
  var init_ksef_api_error = __esm({
107
122
  "src/errors/ksef-api-error.ts"() {
108
123
  "use strict";
124
+ init_cjs_shims();
109
125
  init_ksef_error();
110
126
  KSeFApiError = class _KSeFApiError extends KSeFError {
111
127
  statusCode;
@@ -121,6 +137,9 @@ var init_ksef_api_error = __esm({
121
137
  const message = details?.length ? details.map((d) => d.exceptionDescription ?? "").filter(Boolean).join("; ") || `KSeF API error: HTTP ${statusCode}` : `KSeF API error: HTTP ${statusCode}`;
122
138
  return new _KSeFApiError(message, statusCode, body);
123
139
  }
140
+ toProblemFields() {
141
+ return { detail: this.message };
142
+ }
124
143
  };
125
144
  }
126
145
  });
@@ -130,19 +149,23 @@ var KSeFRateLimitError;
130
149
  var init_ksef_rate_limit_error = __esm({
131
150
  "src/errors/ksef-rate-limit-error.ts"() {
132
151
  "use strict";
152
+ init_cjs_shims();
133
153
  init_ksef_api_error();
134
154
  KSeFRateLimitError = class _KSeFRateLimitError extends KSeFApiError {
155
+ statusCode = 429;
135
156
  retryAfterSeconds;
136
157
  retryAfterDate;
137
158
  recommendedDelay;
138
- constructor(message, statusCode, errorResponse, retryAfterSeconds, retryAfterDate) {
159
+ problem;
160
+ constructor(message, statusCode, errorResponse, retryAfterSeconds, retryAfterDate, problem) {
139
161
  super(message, statusCode, errorResponse);
140
162
  this.name = "KSeFRateLimitError";
141
163
  this.retryAfterSeconds = retryAfterSeconds;
142
164
  this.retryAfterDate = retryAfterDate;
143
165
  this.recommendedDelay = retryAfterSeconds ?? 60;
166
+ this.problem = problem;
144
167
  }
145
- static fromRetryAfterHeader(statusCode, retryAfterHeader, body) {
168
+ static fromRetryAfterHeader(statusCode, retryAfterHeader, body, problem) {
146
169
  let retryAfterSeconds;
147
170
  let retryAfterDate;
148
171
  if (retryAfterHeader) {
@@ -157,8 +180,16 @@ var init_ksef_rate_limit_error = __esm({
157
180
  }
158
181
  }
159
182
  }
160
- const message = retryAfterSeconds != null ? `Rate limited. Retry after ${retryAfterSeconds}s` : "Rate limited by KSeF API";
161
- return new _KSeFRateLimitError(message, statusCode, body, retryAfterSeconds, retryAfterDate);
183
+ const message = retryAfterSeconds != null ? `Rate limited. Retry after ${retryAfterSeconds}s` : problem?.detail ?? "Rate limited by KSeF API";
184
+ return new _KSeFRateLimitError(message, statusCode, body, retryAfterSeconds, retryAfterDate, problem);
185
+ }
186
+ toProblemFields() {
187
+ return {
188
+ detail: this.problem?.detail,
189
+ traceId: this.problem?.traceId,
190
+ instance: this.problem?.instance,
191
+ timestamp: this.problem?.timestamp
192
+ };
162
193
  }
163
194
  };
164
195
  }
@@ -169,21 +200,30 @@ var KSeFUnauthorizedError;
169
200
  var init_ksef_unauthorized_error = __esm({
170
201
  "src/errors/ksef-unauthorized-error.ts"() {
171
202
  "use strict";
172
- init_ksef_error();
173
- KSeFUnauthorizedError = class extends KSeFError {
203
+ init_cjs_shims();
204
+ init_ksef_api_error();
205
+ KSeFUnauthorizedError = class extends KSeFApiError {
174
206
  statusCode = 401;
175
207
  detail;
176
208
  traceId;
177
209
  instance;
178
210
  timestamp;
179
211
  constructor(problemDetails) {
180
- super(problemDetails.detail || "Unauthorized");
212
+ super(problemDetails.detail || "Unauthorized", 401);
181
213
  this.name = "KSeFUnauthorizedError";
182
214
  this.detail = problemDetails.detail;
183
215
  this.traceId = problemDetails.traceId;
184
216
  this.instance = problemDetails.instance;
185
217
  this.timestamp = problemDetails.timestamp;
186
218
  }
219
+ toProblemFields() {
220
+ return {
221
+ detail: this.detail,
222
+ traceId: this.traceId,
223
+ instance: this.instance,
224
+ timestamp: this.timestamp
225
+ };
226
+ }
187
227
  };
188
228
  }
189
229
  });
@@ -193,8 +233,9 @@ var KSeFForbiddenError;
193
233
  var init_ksef_forbidden_error = __esm({
194
234
  "src/errors/ksef-forbidden-error.ts"() {
195
235
  "use strict";
196
- init_ksef_error();
197
- KSeFForbiddenError = class extends KSeFError {
236
+ init_cjs_shims();
237
+ init_ksef_api_error();
238
+ KSeFForbiddenError = class extends KSeFApiError {
198
239
  statusCode = 403;
199
240
  detail;
200
241
  reasonCode;
@@ -203,7 +244,7 @@ var init_ksef_forbidden_error = __esm({
203
244
  traceId;
204
245
  timestamp;
205
246
  constructor(problemDetails) {
206
- super(problemDetails.detail || "Forbidden");
247
+ super(problemDetails.detail || "Forbidden", 403);
207
248
  this.name = "KSeFForbiddenError";
208
249
  this.detail = problemDetails.detail;
209
250
  this.reasonCode = problemDetails.reasonCode;
@@ -212,6 +253,16 @@ var init_ksef_forbidden_error = __esm({
212
253
  this.traceId = problemDetails.traceId;
213
254
  this.timestamp = problemDetails.timestamp;
214
255
  }
256
+ toProblemFields() {
257
+ return {
258
+ detail: this.detail,
259
+ reasonCode: this.reasonCode,
260
+ security: this.security,
261
+ traceId: this.traceId,
262
+ instance: this.instance,
263
+ timestamp: this.timestamp
264
+ };
265
+ }
215
266
  };
216
267
  }
217
268
  });
@@ -221,21 +272,66 @@ var KSeFGoneError;
221
272
  var init_ksef_gone_error = __esm({
222
273
  "src/errors/ksef-gone-error.ts"() {
223
274
  "use strict";
224
- init_ksef_error();
225
- KSeFGoneError = class extends KSeFError {
275
+ init_cjs_shims();
276
+ init_ksef_api_error();
277
+ KSeFGoneError = class extends KSeFApiError {
226
278
  statusCode = 410;
227
279
  detail;
228
280
  instance;
229
281
  traceId;
230
282
  timestamp;
231
283
  constructor(problemDetails) {
232
- super(problemDetails.detail || "Operation status no longer available (retention expired)");
284
+ super(problemDetails.detail || "Operation status no longer available (retention expired)", 410);
233
285
  this.name = "KSeFGoneError";
234
286
  this.detail = problemDetails.detail;
235
287
  this.instance = problemDetails.instance;
236
288
  this.traceId = problemDetails.traceId;
237
289
  this.timestamp = problemDetails.timestamp;
238
290
  }
291
+ toProblemFields() {
292
+ return {
293
+ detail: this.detail,
294
+ traceId: this.traceId,
295
+ instance: this.instance,
296
+ timestamp: this.timestamp
297
+ };
298
+ }
299
+ };
300
+ }
301
+ });
302
+
303
+ // src/errors/ksef-bad-request-error.ts
304
+ var KSeFBadRequestError;
305
+ var init_ksef_bad_request_error = __esm({
306
+ "src/errors/ksef-bad-request-error.ts"() {
307
+ "use strict";
308
+ init_cjs_shims();
309
+ init_ksef_api_error();
310
+ KSeFBadRequestError = class extends KSeFApiError {
311
+ statusCode = 400;
312
+ detail;
313
+ instance;
314
+ errors;
315
+ traceId;
316
+ timestamp;
317
+ constructor(problemDetails) {
318
+ super(problemDetails.detail || problemDetails.title || "Bad Request", 400);
319
+ this.name = "KSeFBadRequestError";
320
+ this.detail = problemDetails.detail;
321
+ this.instance = problemDetails.instance;
322
+ this.errors = problemDetails.errors ?? [];
323
+ this.traceId = problemDetails.traceId;
324
+ this.timestamp = problemDetails.timestamp;
325
+ }
326
+ toProblemFields() {
327
+ return {
328
+ detail: this.detail,
329
+ errors: this.errors.length ? this.errors : void 0,
330
+ traceId: this.traceId,
331
+ instance: this.instance,
332
+ timestamp: this.timestamp
333
+ };
334
+ }
239
335
  };
240
336
  }
241
337
  });
@@ -245,6 +341,7 @@ var KSeFAuthStatusError;
245
341
  var init_ksef_auth_status_error = __esm({
246
342
  "src/errors/ksef-auth-status-error.ts"() {
247
343
  "use strict";
344
+ init_cjs_shims();
248
345
  init_ksef_error();
249
346
  KSeFAuthStatusError = class extends KSeFError {
250
347
  referenceNumber;
@@ -264,6 +361,7 @@ var KSeFSessionExpiredError;
264
361
  var init_ksef_session_expired_error = __esm({
265
362
  "src/errors/ksef-session-expired-error.ts"() {
266
363
  "use strict";
364
+ init_cjs_shims();
267
365
  init_ksef_error();
268
366
  KSeFSessionExpiredError = class extends KSeFError {
269
367
  constructor(message = "KSeF session has expired") {
@@ -283,6 +381,7 @@ var KSeFValidationError;
283
381
  var init_ksef_validation_error = __esm({
284
382
  "src/errors/ksef-validation-error.ts"() {
285
383
  "use strict";
384
+ init_cjs_shims();
286
385
  init_ksef_error();
287
386
  KSeFValidationError = class _KSeFValidationError extends KSeFError {
288
387
  details;
@@ -310,6 +409,7 @@ var KSeFErrorCode;
310
409
  var init_error_codes = __esm({
311
410
  "src/errors/error-codes.ts"() {
312
411
  "use strict";
412
+ init_cjs_shims();
313
413
  KSeFErrorCode = {
314
414
  BatchTimeout: 21208,
315
415
  DuplicateInvoice: 440
@@ -322,6 +422,7 @@ var KSeFBatchTimeoutError;
322
422
  var init_ksef_batch_timeout_error = __esm({
323
423
  "src/errors/ksef-batch-timeout-error.ts"() {
324
424
  "use strict";
425
+ init_cjs_shims();
325
426
  init_ksef_api_error();
326
427
  init_error_codes();
327
428
  KSeFBatchTimeoutError = class _KSeFBatchTimeoutError extends KSeFApiError {
@@ -341,21 +442,83 @@ var init_ksef_batch_timeout_error = __esm({
341
442
  }
342
443
  });
343
444
 
445
+ // src/errors/ksef-circuit-open-error.ts
446
+ var KSeFCircuitOpenError;
447
+ var init_ksef_circuit_open_error = __esm({
448
+ "src/errors/ksef-circuit-open-error.ts"() {
449
+ "use strict";
450
+ init_cjs_shims();
451
+ init_ksef_error();
452
+ KSeFCircuitOpenError = class extends KSeFError {
453
+ endpoint;
454
+ openedAt;
455
+ retryAfterMs;
456
+ constructor(endpoint, openedAt, retryAfterMs) {
457
+ super(
458
+ `Circuit breaker is open for '${endpoint}'. Retry after ${Math.round(retryAfterMs)}ms.`
459
+ );
460
+ this.name = "KSeFCircuitOpenError";
461
+ this.endpoint = endpoint;
462
+ this.openedAt = openedAt;
463
+ this.retryAfterMs = retryAfterMs;
464
+ }
465
+ };
466
+ }
467
+ });
468
+
469
+ // src/errors/ksef-xsd-validation-error.ts
470
+ var KSeFXsdValidationError;
471
+ var init_ksef_xsd_validation_error = __esm({
472
+ "src/errors/ksef-xsd-validation-error.ts"() {
473
+ "use strict";
474
+ init_cjs_shims();
475
+ init_ksef_error();
476
+ KSeFXsdValidationError = class extends KSeFError {
477
+ schemaFile;
478
+ errors;
479
+ constructor(schemaFile, errors) {
480
+ const preview = errors.slice(0, 3).join("; ");
481
+ const extra = errors.length > 3 ? ` (+${errors.length - 3} more)` : "";
482
+ super(`XSD validation failed against ${schemaFile}: ${preview}${extra}`);
483
+ this.name = "KSeFXsdValidationError";
484
+ this.schemaFile = schemaFile;
485
+ this.errors = errors;
486
+ }
487
+ };
488
+ }
489
+ });
490
+
491
+ // src/errors/assert-never.ts
492
+ function assertNever(value) {
493
+ throw new Error(`Unexpected value: ${String(value)}`);
494
+ }
495
+ var init_assert_never = __esm({
496
+ "src/errors/assert-never.ts"() {
497
+ "use strict";
498
+ init_cjs_shims();
499
+ }
500
+ });
501
+
344
502
  // src/errors/index.ts
345
503
  var init_errors = __esm({
346
504
  "src/errors/index.ts"() {
347
505
  "use strict";
506
+ init_cjs_shims();
348
507
  init_ksef_error();
349
508
  init_ksef_api_error();
350
509
  init_ksef_rate_limit_error();
351
510
  init_ksef_unauthorized_error();
352
511
  init_ksef_forbidden_error();
353
512
  init_ksef_gone_error();
513
+ init_ksef_bad_request_error();
354
514
  init_ksef_auth_status_error();
355
515
  init_ksef_session_expired_error();
356
516
  init_ksef_validation_error();
357
517
  init_ksef_batch_timeout_error();
518
+ init_ksef_circuit_open_error();
519
+ init_ksef_xsd_validation_error();
358
520
  init_error_codes();
521
+ init_assert_never();
359
522
  }
360
523
  });
361
524
 
@@ -364,6 +527,7 @@ var RouteBuilder;
364
527
  var init_route_builder = __esm({
365
528
  "src/http/route-builder.ts"() {
366
529
  "use strict";
530
+ init_cjs_shims();
367
531
  RouteBuilder = class {
368
532
  apiVersion;
369
533
  constructor(apiVersion) {
@@ -382,6 +546,7 @@ var RestRequest;
382
546
  var init_rest_request = __esm({
383
547
  "src/http/rest-request.ts"() {
384
548
  "use strict";
549
+ init_cjs_shims();
385
550
  RestRequest = class _RestRequest {
386
551
  method;
387
552
  path;
@@ -390,21 +555,21 @@ var init_rest_request = __esm({
390
555
  _query = [];
391
556
  _presigned = false;
392
557
  _skipAuthRetry = false;
393
- constructor(method, path2) {
558
+ constructor(method, path3) {
394
559
  this.method = method;
395
- this.path = path2;
560
+ this.path = path3;
396
561
  }
397
- static get(path2) {
398
- return new _RestRequest("GET", path2);
562
+ static get(path3) {
563
+ return new _RestRequest("GET", path3);
399
564
  }
400
- static post(path2) {
401
- return new _RestRequest("POST", path2);
565
+ static post(path3) {
566
+ return new _RestRequest("POST", path3);
402
567
  }
403
- static put(path2) {
404
- return new _RestRequest("PUT", path2);
568
+ static put(path3) {
569
+ return new _RestRequest("PUT", path3);
405
570
  }
406
- static delete(path2) {
407
- return new _RestRequest("DELETE", path2);
571
+ static delete(path3) {
572
+ return new _RestRequest("DELETE", path3);
408
573
  }
409
574
  body(data) {
410
575
  this._body = data;
@@ -458,6 +623,7 @@ var defaultTransport;
458
623
  var init_transport = __esm({
459
624
  "src/http/transport.ts"() {
460
625
  "use strict";
626
+ init_cjs_shims();
461
627
  defaultTransport = (url, init) => fetch(url, init);
462
628
  }
463
629
  });
@@ -507,6 +673,7 @@ var RETRYABLE_ERROR_CODES;
507
673
  var init_retry_policy = __esm({
508
674
  "src/http/retry-policy.ts"() {
509
675
  "use strict";
676
+ init_cjs_shims();
510
677
  RETRYABLE_ERROR_CODES = /* @__PURE__ */ new Set([
511
678
  "ECONNRESET",
512
679
  "ECONNREFUSED",
@@ -597,22 +764,46 @@ var BLOCKED_PARAMS;
597
764
  var init_presigned_url_policy = __esm({
598
765
  "src/http/presigned-url-policy.ts"() {
599
766
  "use strict";
767
+ init_cjs_shims();
600
768
  init_ksef_validation_error();
601
769
  BLOCKED_PARAMS = ["redirect", "callback", "return_url", "next"];
602
770
  }
603
771
  });
604
772
 
605
773
  // src/http/rest-client.ts
774
+ function isBadRequestProblem(value) {
775
+ if (typeof value !== "object" || value === null) return false;
776
+ const v = value;
777
+ if (typeof v.title !== "string") return false;
778
+ if (v.status !== void 0 && typeof v.status !== "number") return false;
779
+ if (v.errors !== void 0) {
780
+ if (!Array.isArray(v.errors)) return false;
781
+ for (const item of v.errors) {
782
+ if (typeof item !== "object" || item === null) return false;
783
+ const detail = item;
784
+ if (typeof detail.code !== "number") return false;
785
+ if (typeof detail.description !== "string") return false;
786
+ }
787
+ }
788
+ return true;
789
+ }
790
+ function isTooManyRequestsProblem(value) {
791
+ if (typeof value !== "object" || value === null) return false;
792
+ const v = value;
793
+ return typeof v.title === "string" && (v.status === void 0 || typeof v.status === "number") && (v.detail === void 0 || typeof v.detail === "string") && (v.instance === void 0 || typeof v.instance === "string") && (v.traceId === void 0 || typeof v.traceId === "string") && (v.timestamp === void 0 || typeof v.timestamp === "string");
794
+ }
606
795
  var import_consola, RestClient;
607
796
  var init_rest_client = __esm({
608
797
  "src/http/rest-client.ts"() {
609
798
  "use strict";
799
+ init_cjs_shims();
610
800
  import_consola = require("consola");
611
801
  init_ksef_api_error();
612
802
  init_ksef_rate_limit_error();
613
803
  init_ksef_unauthorized_error();
614
804
  init_ksef_forbidden_error();
615
805
  init_ksef_gone_error();
806
+ init_ksef_bad_request_error();
616
807
  init_ksef_batch_timeout_error();
617
808
  init_error_codes();
618
809
  init_route_builder();
@@ -625,6 +816,7 @@ var init_rest_client = __esm({
625
816
  transport;
626
817
  retryPolicy;
627
818
  rateLimitPolicy;
819
+ circuitBreakerPolicy;
628
820
  authManager;
629
821
  presignedUrlPolicy;
630
822
  constructor(options, config) {
@@ -633,6 +825,7 @@ var init_rest_client = __esm({
633
825
  this.transport = config?.transport ?? defaultTransport;
634
826
  this.retryPolicy = config?.retryPolicy ?? defaultRetryPolicy();
635
827
  this.rateLimitPolicy = config?.rateLimitPolicy ?? null;
828
+ this.circuitBreakerPolicy = config?.circuitBreakerPolicy ?? null;
636
829
  this.authManager = config?.authManager;
637
830
  this.presignedUrlPolicy = config?.presignedUrlPolicy;
638
831
  }
@@ -657,18 +850,32 @@ var init_rest_client = __esm({
657
850
  if (request.isPresigned() && this.presignedUrlPolicy) {
658
851
  validatePresignedUrl(url, this.presignedUrlPolicy);
659
852
  }
853
+ let ownsProbeSlot = false;
854
+ if (this.circuitBreakerPolicy) {
855
+ const claimed = this.circuitBreakerPolicy.ensureClosed(request.path);
856
+ if (claimed) ownsProbeSlot = true;
857
+ }
660
858
  if (this.rateLimitPolicy) {
661
- await this.rateLimitPolicy.acquire(request.path);
859
+ try {
860
+ await this.rateLimitPolicy.acquire(request.path);
861
+ } catch (error) {
862
+ if (ownsProbeSlot) this.circuitBreakerPolicy?.releaseProbe(request.path);
863
+ throw error;
864
+ }
662
865
  }
663
866
  let lastError;
664
867
  for (let attempt = 0; attempt <= this.retryPolicy.maxRetries; attempt++) {
868
+ if (this.circuitBreakerPolicy) {
869
+ const claimed = this.circuitBreakerPolicy.ensureClosed(request.path, ownsProbeSlot);
870
+ if (claimed) ownsProbeSlot = true;
871
+ }
665
872
  try {
666
- const response = await this.doRequest(request, url);
873
+ let response = await this.doRequest(request, url);
667
874
  if (response.status === 401 && this.authManager && attempt === 0 && !request.isSkipAuthRetry()) {
668
875
  const newToken = await this.authManager.onUnauthorized();
669
876
  if (newToken) {
670
877
  import_consola.consola.debug("Auth token refreshed, retrying request");
671
- return this.doRequest(request, url, newToken);
878
+ response = await this.doRequest(request, url, newToken);
672
879
  }
673
880
  }
674
881
  if (isRetryableStatus(response.status, this.retryPolicy) && attempt < this.retryPolicy.maxRetries) {
@@ -678,10 +885,17 @@ var init_rest_client = __esm({
678
885
  import_consola.consola.debug(`Retryable ${response.status}, attempt ${attempt + 1}/${this.retryPolicy.maxRetries}, waiting ${Math.round(delayMs)}ms`);
679
886
  await sleep(delayMs);
680
887
  if (is429 && this.rateLimitPolicy) {
681
- await this.rateLimitPolicy.acquire(request.path);
888
+ try {
889
+ await this.rateLimitPolicy.acquire(request.path);
890
+ } catch (error) {
891
+ this.recordCircuitOutcome(request.path, 429);
892
+ ownsProbeSlot = false;
893
+ throw error;
894
+ }
682
895
  }
683
896
  continue;
684
897
  }
898
+ this.recordCircuitOutcome(request.path, response.status);
685
899
  return response;
686
900
  } catch (error) {
687
901
  lastError = error;
@@ -691,16 +905,31 @@ var init_rest_client = __esm({
691
905
  await sleep(delayMs);
692
906
  continue;
693
907
  }
908
+ if (isRetryableError(error, this.retryPolicy) || ownsProbeSlot) {
909
+ this.circuitBreakerPolicy?.recordFailure(request.path);
910
+ }
694
911
  throw error;
695
912
  }
696
913
  }
697
914
  throw lastError;
698
915
  }
916
+ recordCircuitOutcome(path3, status) {
917
+ if (!this.circuitBreakerPolicy) return;
918
+ if (status >= 500) {
919
+ this.circuitBreakerPolicy.recordFailure(path3);
920
+ return;
921
+ }
922
+ this.circuitBreakerPolicy.recordSuccess(path3);
923
+ }
699
924
  async doRequest(request, url, overrideToken) {
700
925
  const headers = {
701
926
  ...this.options.customHeaders,
702
927
  ...request.getHeaders()
703
928
  };
929
+ const hasHeader = (name) => Object.keys(headers).some((header) => header.toLowerCase() === name.toLowerCase());
930
+ if (this.options.errorFormat !== "legacy" && !hasHeader("x-error-format")) {
931
+ headers["X-Error-Format"] = "problem-details";
932
+ }
704
933
  if (!headers["Authorization"] && this.authManager) {
705
934
  const token = overrideToken ?? this.authManager.getAccessToken();
706
935
  if (token) {
@@ -727,9 +956,9 @@ var init_rest_client = __esm({
727
956
  return response;
728
957
  }
729
958
  buildUrl(request) {
730
- const path2 = this.routeBuilder.build(request.path);
959
+ const path3 = this.routeBuilder.build(request.path);
731
960
  const base = this.options.baseUrl;
732
- const url = new URL(`${base}${path2}`);
961
+ const url = new URL(`${base}${path3}`);
733
962
  const query = request.getQuery();
734
963
  for (const [key, value] of query) {
735
964
  url.searchParams.append(key, value);
@@ -739,19 +968,40 @@ var init_rest_client = __esm({
739
968
  async ensureSuccess(response) {
740
969
  if (response.ok) return;
741
970
  const text = await response.text().catch(() => "");
971
+ let jsonCache = null;
742
972
  const parseJson = () => {
743
- try {
744
- return JSON.parse(text);
745
- } catch {
746
- return void 0;
973
+ if (jsonCache === null) {
974
+ try {
975
+ jsonCache = { value: JSON.parse(text) };
976
+ } catch {
977
+ jsonCache = { value: void 0 };
978
+ }
747
979
  }
980
+ return jsonCache.value;
748
981
  };
749
- if (response.status === 429) {
982
+ const tryParseProblem = (guard) => {
750
983
  const parsed = parseJson();
984
+ return parsed !== void 0 && guard(parsed) ? parsed : void 0;
985
+ };
986
+ if (response.status === 400) {
987
+ const problem = tryParseProblem(isBadRequestProblem);
988
+ if (problem) {
989
+ throw new KSeFBadRequestError(problem);
990
+ }
991
+ const legacy = parseJson();
992
+ if (hasErrorCode(legacy, KSeFErrorCode.BatchTimeout)) {
993
+ throw KSeFBatchTimeoutError.fromResponse(400, legacy);
994
+ }
995
+ throw KSeFApiError.fromResponse(400, legacy);
996
+ }
997
+ if (response.status === 429) {
998
+ const problem = tryParseProblem(isTooManyRequestsProblem);
999
+ const legacy = problem ? void 0 : parseJson();
751
1000
  throw KSeFRateLimitError.fromRetryAfterHeader(
752
1001
  response.status,
753
1002
  response.headers.get("Retry-After"),
754
- parsed
1003
+ legacy,
1004
+ problem
755
1005
  );
756
1006
  }
757
1007
  if (response.status === 401) {
@@ -792,6 +1042,7 @@ var Routes;
792
1042
  var init_routes = __esm({
793
1043
  "src/http/routes.ts"() {
794
1044
  "use strict";
1045
+ init_cjs_shims();
795
1046
  Routes = {
796
1047
  TestData: {
797
1048
  createSubject: "testdata/subject",
@@ -924,6 +1175,7 @@ var TokenBucket, RateLimitPolicy;
924
1175
  var init_rate_limit_policy = __esm({
925
1176
  "src/http/rate-limit-policy.ts"() {
926
1177
  "use strict";
1178
+ init_cjs_shims();
927
1179
  TokenBucket = class {
928
1180
  tokens;
929
1181
  maxTokens;
@@ -984,11 +1236,151 @@ var init_rate_limit_policy = __esm({
984
1236
  }
985
1237
  });
986
1238
 
1239
+ // src/http/circuit-breaker-policy.ts
1240
+ function defaultCircuitBreakerPolicy() {
1241
+ return new CircuitBreakerPolicy();
1242
+ }
1243
+ var import_consola2, GLOBAL_KEY, CircuitBreakerPolicy;
1244
+ var init_circuit_breaker_policy = __esm({
1245
+ "src/http/circuit-breaker-policy.ts"() {
1246
+ "use strict";
1247
+ init_cjs_shims();
1248
+ import_consola2 = require("consola");
1249
+ init_ksef_circuit_open_error();
1250
+ GLOBAL_KEY = "__global__";
1251
+ CircuitBreakerPolicy = class _CircuitBreakerPolicy {
1252
+ failureThreshold;
1253
+ openMs;
1254
+ scope;
1255
+ states = /* @__PURE__ */ new Map();
1256
+ constructor(config = {}) {
1257
+ const failureThreshold = config.failureThreshold ?? 5;
1258
+ const openMs = config.openMs ?? 3e4;
1259
+ if (!Number.isInteger(failureThreshold) || failureThreshold <= 0) {
1260
+ throw new RangeError("CircuitBreakerPolicy: failureThreshold must be a positive integer");
1261
+ }
1262
+ if (!Number.isFinite(openMs) || openMs <= 0) {
1263
+ throw new RangeError("CircuitBreakerPolicy: openMs must be > 0");
1264
+ }
1265
+ const scope = config.scope ?? "global";
1266
+ if (scope !== "global" && scope !== "endpoint") {
1267
+ throw new RangeError(
1268
+ "CircuitBreakerPolicy: scope must be 'global' or 'endpoint'"
1269
+ );
1270
+ }
1271
+ this.failureThreshold = failureThreshold;
1272
+ this.openMs = openMs;
1273
+ this.scope = scope;
1274
+ }
1275
+ // Returns true iff this call just claimed the single probe slot for the
1276
+ // caller. The caller MUST pass `alreadyOwnsProbe=true` on subsequent
1277
+ // re-checks for the same logical request (e.g. a retry loop) so the probe
1278
+ // owner cannot deadlock itself on its own in-flight slot.
1279
+ ensureClosed(endpoint, alreadyOwnsProbe = false) {
1280
+ const key = this.keyFor(endpoint);
1281
+ const state = this.states.get(key);
1282
+ if (!state || state.openedAt === null) return false;
1283
+ const now = performance.now();
1284
+ const elapsed = now - state.openedAt;
1285
+ if (elapsed >= this.openMs) {
1286
+ if (alreadyOwnsProbe) return false;
1287
+ if (state.probeInFlight) {
1288
+ throw new KSeFCircuitOpenError(endpoint, state.openedAt, 0);
1289
+ }
1290
+ state.probeInFlight = true;
1291
+ import_consola2.consola.debug(`Circuit breaker: probe after cooldown for '${key}'`);
1292
+ return true;
1293
+ }
1294
+ const retryAfterMs = Math.max(0, this.openMs - elapsed);
1295
+ throw new KSeFCircuitOpenError(endpoint, state.openedAt, retryAfterMs);
1296
+ }
1297
+ recordSuccess(endpoint) {
1298
+ const key = this.keyFor(endpoint);
1299
+ const state = this.states.get(key);
1300
+ if (!state) return;
1301
+ if (state.openedAt !== null || state.failures > 0) {
1302
+ import_consola2.consola.debug(`Circuit breaker: reset for '${key}'`);
1303
+ }
1304
+ this.states.delete(key);
1305
+ }
1306
+ // Release a claimed probe slot WITHOUT observing an outcome. Use this when
1307
+ // the probe attempt was aborted before reaching upstream (e.g. rate-limit
1308
+ // acquire rejected, client cancellation). We have no new information about
1309
+ // upstream health, so the breaker must stay OPEN — but we do restart the
1310
+ // cooldown clock so the next probe attempt waits a fresh `openMs`,
1311
+ // preventing a tight loop of aborted probes from spamming the limiter.
1312
+ releaseProbe(endpoint) {
1313
+ const key = this.keyFor(endpoint);
1314
+ const state = this.states.get(key);
1315
+ if (!state || !state.probeInFlight) return;
1316
+ state.probeInFlight = false;
1317
+ if (state.openedAt !== null) {
1318
+ state.openedAt = performance.now();
1319
+ }
1320
+ import_consola2.consola.debug(`Circuit breaker: probe aborted (not observed) for '${key}', cooldown restarted`);
1321
+ }
1322
+ recordFailure(endpoint) {
1323
+ const key = this.keyFor(endpoint);
1324
+ const now = performance.now();
1325
+ let state = this.states.get(key);
1326
+ if (!state) {
1327
+ state = { failures: 0, openedAt: null, lastFailureAt: null, probeInFlight: false };
1328
+ this.states.set(key, state);
1329
+ }
1330
+ if (state.openedAt !== null && state.probeInFlight) {
1331
+ state.openedAt = now;
1332
+ state.failures = this.failureThreshold;
1333
+ state.lastFailureAt = now;
1334
+ state.probeInFlight = false;
1335
+ import_consola2.consola.debug(`Circuit breaker: probe failed, re-opened for '${key}'`);
1336
+ this.maybeSweepStaleClosed(now, key);
1337
+ return;
1338
+ }
1339
+ const slidingStale = state.lastFailureAt !== null && now - state.lastFailureAt > this.openMs;
1340
+ state.failures = slidingStale ? 1 : state.failures + 1;
1341
+ state.lastFailureAt = now;
1342
+ if (state.openedAt === null && state.failures >= this.failureThreshold) {
1343
+ state.openedAt = now;
1344
+ import_consola2.consola.debug(
1345
+ `Circuit breaker: opened for '${key}' after ${state.failures} failures (cooldown ${this.openMs}ms)`
1346
+ );
1347
+ }
1348
+ this.maybeSweepStaleClosed(now, key);
1349
+ }
1350
+ keyFor(endpoint) {
1351
+ return this.scope === "global" ? GLOBAL_KEY : endpoint;
1352
+ }
1353
+ // Prevent unbounded map growth under `scope: 'endpoint'` when callers hit
1354
+ // many distinct parameterized paths (e.g. `auth/sessions/{ref}`) that each
1355
+ // fail once and are never revisited. Global scope is always a single entry.
1356
+ //
1357
+ // Runs amortized O(n) — gated on a size threshold so small workloads pay
1358
+ // nothing. Only evicts states that are genuinely settled: closed, no probe
1359
+ // in flight, and with the last failure older than two cooldowns.
1360
+ maybeSweepStaleClosed(now, keepKey) {
1361
+ if (this.scope !== "endpoint") return;
1362
+ if (this.states.size <= _CircuitBreakerPolicy.sweepThreshold) return;
1363
+ const staleBefore = now - 2 * this.openMs;
1364
+ for (const [key, state] of this.states) {
1365
+ if (key === keepKey) continue;
1366
+ if (state.openedAt !== null) continue;
1367
+ if (state.probeInFlight) continue;
1368
+ if (state.lastFailureAt !== null && state.lastFailureAt < staleBefore) {
1369
+ this.states.delete(key);
1370
+ }
1371
+ }
1372
+ }
1373
+ static sweepThreshold = 64;
1374
+ };
1375
+ }
1376
+ });
1377
+
987
1378
  // src/http/auth-manager.ts
988
1379
  var DefaultAuthManager;
989
1380
  var init_auth_manager = __esm({
990
1381
  "src/http/auth-manager.ts"() {
991
1382
  "use strict";
1383
+ init_cjs_shims();
992
1384
  DefaultAuthManager = class {
993
1385
  token;
994
1386
  refreshToken;
@@ -1029,6 +1421,7 @@ var KSEF_FEATURE_HEADER, UpoVersion, ENFORCE_XADES_COMPLIANCE;
1029
1421
  var init_ksef_feature = __esm({
1030
1422
  "src/http/ksef-feature.ts"() {
1031
1423
  "use strict";
1424
+ init_cjs_shims();
1032
1425
  KSEF_FEATURE_HEADER = "X-KSeF-Feature";
1033
1426
  UpoVersion = {
1034
1427
  /** UPO v4-2 format (default before 2026-01-05). */
@@ -1128,6 +1521,7 @@ var NIP_PATTERN_CORE, VAT_UE_PATTERN_CORE, Nip, VatUe, NipVatUe, InternalId, Pep
1128
1521
  var init_patterns = __esm({
1129
1522
  "src/validation/patterns.ts"() {
1130
1523
  "use strict";
1524
+ init_cjs_shims();
1131
1525
  NIP_PATTERN_CORE = "[1-9]((\\d[1-9])|([1-9]\\d))\\d{7}";
1132
1526
  VAT_UE_PATTERN_CORE = "(ATU\\d{8}|BE[01]{1}\\d{9}|BG\\d{9,10}|CY\\d{8}[A-Z]|CZ\\d{8,10}|DE\\d{9}|DK\\d{8}|EE\\d{9}|EL\\d{9}|ES([A-Z]\\d{8}|\\d{8}[A-Z]|[A-Z]\\d{7}[A-Z])|FI\\d{8}|FR[A-Z0-9]{2}\\d{9}|HR\\d{11}|HU\\d{8}|IE(\\d{7}[A-Z]{2}|\\d[A-Z0-9+*]\\d{5}[A-Z])|IT\\d{11}|LT(\\d{9}|\\d{12})|LU\\d{8}|LV\\d{11}|MT\\d{8}|NL[A-Z0-9+*]{12}|PT\\d{9}|RO\\d{2,10}|SE\\d{12}|SI\\d{8}|SK\\d{10}|XI((\\d{9}|\\d{12})|(GD|HA)\\d{3}))";
1133
1527
  Nip = new RegExp(`^${NIP_PATTERN_CORE}$`);
@@ -1244,6 +1638,7 @@ var import_xmldom;
1244
1638
  var init_xml_to_object = __esm({
1245
1639
  "src/validation/xml-to-object.ts"() {
1246
1640
  "use strict";
1641
+ init_cjs_shims();
1247
1642
  import_xmldom = require("@xmldom/xmldom");
1248
1643
  }
1249
1644
  });
@@ -1257,6 +1652,7 @@ var import_zod, TKodFormularza, TDataCzas, TZnakowy, TNaglowek, TKodyKrajowUE, T
1257
1652
  var init_fa3 = __esm({
1258
1653
  "src/validation/schemas/fa3.ts"() {
1259
1654
  "use strict";
1655
+ init_cjs_shims();
1260
1656
  import_zod = require("zod");
1261
1657
  TKodFormularza = import_zod.z.literal("FA");
1262
1658
  TDataCzas = import_zod.z.string();
@@ -1667,6 +2063,7 @@ var import_zod2, TKodFormularza2, TDataCzas2, TZnakowy3, TNaglowek2, TKodyKrajow
1667
2063
  var init_fa2 = __esm({
1668
2064
  "src/validation/schemas/fa2.ts"() {
1669
2065
  "use strict";
2066
+ init_cjs_shims();
1670
2067
  import_zod2 = require("zod");
1671
2068
  TKodFormularza2 = import_zod2.z.literal("FA");
1672
2069
  TDataCzas2 = import_zod2.z.string();
@@ -2061,6 +2458,7 @@ var import_zod3, TKodFormularza3, TDataCzas3, TZnakowy4, TNaglowek3, TNrNIP3, TZ
2061
2458
  var init_rr1_v11e = __esm({
2062
2459
  "src/validation/schemas/rr1-v11e.ts"() {
2063
2460
  "use strict";
2461
+ init_cjs_shims();
2064
2462
  import_zod3 = require("zod");
2065
2463
  TKodFormularza3 = import_zod3.z.literal("FA_RR");
2066
2464
  TDataCzas3 = import_zod3.z.string();
@@ -2266,6 +2664,7 @@ var import_zod4, TKodFormularza4, TDataCzas4, TZnakowy5, TNaglowek4, TNrNIP4, TZ
2266
2664
  var init_rr1_v10e = __esm({
2267
2665
  "src/validation/schemas/rr1-v10e.ts"() {
2268
2666
  "use strict";
2667
+ init_cjs_shims();
2269
2668
  import_zod4 = require("zod");
2270
2669
  TKodFormularza4 = import_zod4.z.literal("FA_RR");
2271
2670
  TDataCzas4 = import_zod4.z.string();
@@ -2471,6 +2870,7 @@ var import_zod5, InvoiceType, PEF3Schema;
2471
2870
  var init_pef3 = __esm({
2472
2871
  "src/validation/schemas/pef3.ts"() {
2473
2872
  "use strict";
2873
+ init_cjs_shims();
2474
2874
  import_zod5 = require("zod");
2475
2875
  InvoiceType = import_zod5.z.object({
2476
2876
  "UBLExtensions": import_zod5.z.any().optional(),
@@ -2541,6 +2941,7 @@ var import_zod6, CreditNoteType, PEF_KOR3Schema;
2541
2941
  var init_pef_kor3 = __esm({
2542
2942
  "src/validation/schemas/pef-kor3.ts"() {
2543
2943
  "use strict";
2944
+ init_cjs_shims();
2544
2945
  import_zod6 = require("zod");
2545
2946
  CreditNoteType = import_zod6.z.object({
2546
2947
  "UBLExtensions": import_zod6.z.any().optional(),
@@ -2604,6 +3005,7 @@ var NAMESPACE_MAP;
2604
3005
  var init_schemas = __esm({
2605
3006
  "src/validation/schemas/index.ts"() {
2606
3007
  "use strict";
3008
+ init_cjs_shims();
2607
3009
  init_fa3();
2608
3010
  init_fa2();
2609
3011
  init_rr1_v11e();
@@ -2660,6 +3062,7 @@ var ROOT_ELEMENT_MAP, schemaCache, SchemaRegistry;
2660
3062
  var init_schema_registry = __esm({
2661
3063
  "src/validation/schema-registry.ts"() {
2662
3064
  "use strict";
3065
+ init_cjs_shims();
2663
3066
  init_schemas();
2664
3067
  ROOT_ELEMENT_MAP = {
2665
3068
  Invoice: "PEF3",
@@ -2701,6 +3104,116 @@ var init_schema_registry = __esm({
2701
3104
  }
2702
3105
  });
2703
3106
 
3107
+ // src/validation/char-validity.ts
3108
+ function validateCharValidity(xml) {
3109
+ return [...findProcessingInstructions(xml), ...findDiscouragedUnicode(xml)];
3110
+ }
3111
+ function findProcessingInstructionTokens(xml) {
3112
+ const tokens = [];
3113
+ for (let i = 0; i < xml.length; ) {
3114
+ if (xml.startsWith("<!--", i)) {
3115
+ const end = xml.indexOf("-->", i + 4);
3116
+ i = end === -1 ? xml.length : end + 3;
3117
+ continue;
3118
+ }
3119
+ if (xml.startsWith("<![CDATA[", i)) {
3120
+ const end = xml.indexOf("]]>", i + 9);
3121
+ i = end === -1 ? xml.length : end + 3;
3122
+ continue;
3123
+ }
3124
+ if (xml.startsWith("<?", i)) {
3125
+ const end = xml.indexOf("?>", i + 2);
3126
+ if (end === -1) break;
3127
+ tokens.push({ token: xml.slice(i, end + 2), index: i });
3128
+ i = end + 2;
3129
+ continue;
3130
+ }
3131
+ i += 1;
3132
+ }
3133
+ return tokens;
3134
+ }
3135
+ function findProcessingInstructions(xml) {
3136
+ const errors = [];
3137
+ const matches = findProcessingInstructionTokens(xml);
3138
+ if (matches.length === 0) return errors;
3139
+ const firstMatch = matches[0];
3140
+ const firstTarget = firstMatch.token.match(PI_TARGET_RE)?.[1];
3141
+ const hasBom = xml.charCodeAt(0) === 65279;
3142
+ const prologPosition = hasBom ? 1 : 0;
3143
+ const firstIsProlog = firstMatch.index === prologPosition && firstTarget === "xml";
3144
+ for (let i = 0; i < matches.length; i++) {
3145
+ if (i === 0 && firstIsProlog) continue;
3146
+ const m = matches[i];
3147
+ const target = m.token.match(PI_TARGET_RE)?.[1] ?? "?";
3148
+ errors.push({
3149
+ code: "XML_PROCESSING_INSTRUCTION",
3150
+ message: `Processing instruction <?${target}?> at offset ${m.index} is not allowed (only <?xml ... ?> prolog is permitted)`,
3151
+ path: `offset:${m.index}`
3152
+ });
3153
+ }
3154
+ return errors;
3155
+ }
3156
+ function findDiscouragedUnicode(xml) {
3157
+ const errors = [];
3158
+ const seenRanges = /* @__PURE__ */ new Set();
3159
+ let utf16Offset = 0;
3160
+ for (const ch of xml) {
3161
+ const cp = ch.codePointAt(0);
3162
+ const idx = rangeIndex(cp);
3163
+ if (idx >= 0 && !seenRanges.has(idx)) {
3164
+ seenRanges.add(idx);
3165
+ errors.push({
3166
+ code: "XML_DISCOURAGED_UNICODE",
3167
+ message: `Discouraged Unicode character U+${cp.toString(16).toUpperCase().padStart(4, "0")} found at offset ${utf16Offset} (W3C XML 1.0 \xA72.2 rejects this range)`,
3168
+ path: `offset:${utf16Offset}`
3169
+ });
3170
+ }
3171
+ utf16Offset += ch.length;
3172
+ }
3173
+ return errors;
3174
+ }
3175
+ function rangeIndex(cp) {
3176
+ let lo = 0;
3177
+ let hi = DISCOURAGED_UNICODE_RANGES.length - 1;
3178
+ while (lo <= hi) {
3179
+ const mid = lo + hi >> 1;
3180
+ const [start, end] = DISCOURAGED_UNICODE_RANGES[mid];
3181
+ if (cp < start) hi = mid - 1;
3182
+ else if (cp > end) lo = mid + 1;
3183
+ else return mid;
3184
+ }
3185
+ return -1;
3186
+ }
3187
+ var DISCOURAGED_UNICODE_RANGES, PI_TARGET_RE;
3188
+ var init_char_validity = __esm({
3189
+ "src/validation/char-validity.ts"() {
3190
+ "use strict";
3191
+ init_cjs_shims();
3192
+ DISCOURAGED_UNICODE_RANGES = [
3193
+ [127, 132],
3194
+ [134, 159],
3195
+ [64976, 65007],
3196
+ [131070, 131071],
3197
+ [196606, 196607],
3198
+ [262142, 262143],
3199
+ [327678, 327679],
3200
+ [393214, 393215],
3201
+ [458750, 458751],
3202
+ [524286, 524287],
3203
+ [589822, 589823],
3204
+ [655358, 655359],
3205
+ [720894, 720895],
3206
+ [786430, 786431],
3207
+ [851966, 851967],
3208
+ [917502, 917503],
3209
+ [983038, 983039],
3210
+ [1048574, 1048575],
3211
+ [1114110, 1114111]
3212
+ ];
3213
+ PI_TARGET_RE = /^<\?(\S+)/;
3214
+ }
3215
+ });
3216
+
2704
3217
  // src/validation/invoice-validator.ts
2705
3218
  var invoice_validator_exports = {};
2706
3219
  __export(invoice_validator_exports, {
@@ -2758,11 +3271,11 @@ async function validateSchema(xml, options, _parsed) {
2758
3271
  const prefix = rootElement ? `/${rootElement}/` : "/";
2759
3272
  const validationErrors = result.error.issues.map((issue) => {
2760
3273
  const zodPath = issue.path.join("/");
2761
- const path2 = zodPath ? `${prefix}${zodPath}` : rootElement ? `/${rootElement}` : void 0;
3274
+ const path3 = zodPath ? `${prefix}${zodPath}` : rootElement ? `/${rootElement}` : void 0;
2762
3275
  return {
2763
3276
  code: mapZodErrorCode(issue),
2764
3277
  message: issue.message,
2765
- path: path2
3278
+ path: path3
2766
3279
  };
2767
3280
  });
2768
3281
  return { valid: false, schemaType, errors: validationErrors };
@@ -2802,9 +3315,9 @@ function validateBusinessRules(xml, _parsed) {
2802
3315
  collectDateErrors(object, rootElement, errors);
2803
3316
  return { valid: errors.length === 0, schemaType, errors };
2804
3317
  }
2805
- function collectNipPeselErrors(obj, path2, errors) {
3318
+ function collectNipPeselErrors(obj, path3, errors) {
2806
3319
  for (const [key, value] of Object.entries(obj)) {
2807
- const currentPath = path2 ? `${path2}/${key}` : key;
3320
+ const currentPath = path3 ? `${path3}/${key}` : key;
2808
3321
  if (key === "NIP" && typeof value === "string") {
2809
3322
  if (!isValidNip(value)) {
2810
3323
  errors.push({
@@ -2853,6 +3366,12 @@ function collectDateErrors(obj, rootElement, errors) {
2853
3366
  }
2854
3367
  }
2855
3368
  async function validate(xml, options) {
3369
+ if (!options?.skipCharValidity) {
3370
+ const l1aErrors = validateCharValidity(xml);
3371
+ if (l1aErrors.length > 0) {
3372
+ return { valid: false, schemaType: null, errors: l1aErrors };
3373
+ }
3374
+ }
2856
3375
  const parsed = xml && xml.trim() ? xmlToObject(xml) : void 0;
2857
3376
  const l1 = validateWellFormedness(xml, parsed);
2858
3377
  if (!l1.valid) return l1;
@@ -2877,8 +3396,10 @@ function batchValidationDetails(batch) {
2877
3396
  var init_invoice_validator = __esm({
2878
3397
  "src/validation/invoice-validator.ts"() {
2879
3398
  "use strict";
3399
+ init_cjs_shims();
2880
3400
  init_xml_to_object();
2881
3401
  init_schema_registry();
3402
+ init_char_validity();
2882
3403
  init_patterns();
2883
3404
  }
2884
3405
  });
@@ -2888,6 +3409,7 @@ var SystemCode, FORM_CODES, DEFAULT_FORM_CODE, INVOICE_TYPES_BY_SYSTEM_CODE, FOR
2888
3409
  var init_types = __esm({
2889
3410
  "src/models/document-structures/types.ts"() {
2890
3411
  "use strict";
3412
+ init_cjs_shims();
2891
3413
  SystemCode = {
2892
3414
  FA_2: "FA (2)",
2893
3415
  FA_3: "FA (3)",
@@ -2940,6 +3462,7 @@ var SYSTEM_CODE_TO_FORM_CODE, ALL_FORM_CODES, BATCH_DISALLOWED_SYSTEM_CODES;
2940
3462
  var init_helpers = __esm({
2941
3463
  "src/models/document-structures/helpers.ts"() {
2942
3464
  "use strict";
3465
+ init_cjs_shims();
2943
3466
  init_types();
2944
3467
  SYSTEM_CODE_TO_FORM_CODE = {
2945
3468
  [SystemCode.FA_2]: FORM_CODES.FA_2,
@@ -2960,6 +3483,7 @@ var init_helpers = __esm({
2960
3483
  var init_document_structures = __esm({
2961
3484
  "src/models/document-structures/index.ts"() {
2962
3485
  "use strict";
3486
+ init_cjs_shims();
2963
3487
  init_types();
2964
3488
  init_helpers();
2965
3489
  }
@@ -2970,6 +3494,7 @@ var AuthService;
2970
3494
  var init_auth = __esm({
2971
3495
  "src/services/auth.ts"() {
2972
3496
  "use strict";
3497
+ init_cjs_shims();
2973
3498
  init_ksef_feature();
2974
3499
  init_rest_request();
2975
3500
  init_routes();
@@ -3020,6 +3545,7 @@ var ActiveSessionsService;
3020
3545
  var init_active_sessions = __esm({
3021
3546
  "src/services/active-sessions.ts"() {
3022
3547
  "use strict";
3548
+ init_cjs_shims();
3023
3549
  init_rest_request();
3024
3550
  init_routes();
3025
3551
  ActiveSessionsService = class {
@@ -3051,6 +3577,7 @@ var OnlineSessionService;
3051
3577
  var init_online_session = __esm({
3052
3578
  "src/services/online-session.ts"() {
3053
3579
  "use strict";
3580
+ init_cjs_shims();
3054
3581
  init_ksef_feature();
3055
3582
  init_rest_request();
3056
3583
  init_routes();
@@ -3103,6 +3630,7 @@ async function runWithConcurrency(tasks, parallelism) {
3103
3630
  var init_concurrency = __esm({
3104
3631
  "src/utils/concurrency.ts"() {
3105
3632
  "use strict";
3633
+ init_cjs_shims();
3106
3634
  }
3107
3635
  });
3108
3636
 
@@ -3111,6 +3639,7 @@ var BatchSessionService;
3111
3639
  var init_batch_session = __esm({
3112
3640
  "src/services/batch-session.ts"() {
3113
3641
  "use strict";
3642
+ init_cjs_shims();
3114
3643
  init_ksef_feature();
3115
3644
  init_rest_request();
3116
3645
  init_routes();
@@ -3215,6 +3744,7 @@ var SessionStatusService;
3215
3744
  var init_session_status = __esm({
3216
3745
  "src/services/session-status.ts"() {
3217
3746
  "use strict";
3747
+ init_cjs_shims();
3218
3748
  init_rest_request();
3219
3749
  init_routes();
3220
3750
  SessionStatusService = class {
@@ -3301,6 +3831,7 @@ var InvoiceDownloadService;
3301
3831
  var init_invoice_download = __esm({
3302
3832
  "src/services/invoice-download.ts"() {
3303
3833
  "use strict";
3834
+ init_cjs_shims();
3304
3835
  init_rest_request();
3305
3836
  init_routes();
3306
3837
  InvoiceDownloadService = class {
@@ -3343,9 +3874,11 @@ var PermissionsService;
3343
3874
  var init_permissions = __esm({
3344
3875
  "src/services/permissions.ts"() {
3345
3876
  "use strict";
3877
+ init_cjs_shims();
3878
+ init_ksef_validation_error();
3346
3879
  init_rest_request();
3347
3880
  init_routes();
3348
- PermissionsService = class {
3881
+ PermissionsService = class _PermissionsService {
3349
3882
  restClient;
3350
3883
  constructor(restClient) {
3351
3884
  this.restClient = restClient;
@@ -3403,6 +3936,7 @@ var init_permissions = __esm({
3403
3936
  }
3404
3937
  // Search methods
3405
3938
  async queryPersonalGrants(options, pageOffset, pageSize) {
3939
+ _PermissionsService.validateContextIdentifier(options?.contextIdentifier);
3406
3940
  const req = RestRequest.post(Routes.Permissions.Query.personalGrants).body(options ?? {});
3407
3941
  if (pageOffset !== void 0) req.query("pageOffset", String(pageOffset));
3408
3942
  if (pageSize !== void 0) req.query("pageSize", String(pageSize));
@@ -3431,6 +3965,7 @@ var init_permissions = __esm({
3431
3965
  return response.body;
3432
3966
  }
3433
3967
  async queryEntitiesGrants(options, pageOffset, pageSize) {
3968
+ _PermissionsService.validateContextIdentifier(options?.contextIdentifier);
3434
3969
  const req = RestRequest.post(Routes.Permissions.Query.entitiesGrants).body(options ?? {});
3435
3970
  if (pageOffset !== void 0) req.query("pageOffset", String(pageOffset));
3436
3971
  if (pageSize !== void 0) req.query("pageSize", String(pageSize));
@@ -3469,17 +4004,92 @@ var init_permissions = __esm({
3469
4004
  const response = await this.restClient.execute(req);
3470
4005
  return response.body;
3471
4006
  }
4007
+ static validateContextIdentifier(ctx) {
4008
+ if (!ctx) return;
4009
+ if (ctx.type === "InternalId") {
4010
+ const len = ctx.value.length;
4011
+ if (len < 10 || len > 16) {
4012
+ throw KSeFValidationError.fromField(
4013
+ "contextIdentifier.value",
4014
+ `InternalId must be 10-16 characters, got ${len}`
4015
+ );
4016
+ }
4017
+ }
4018
+ }
3472
4019
  };
3473
4020
  }
3474
4021
  });
3475
4022
 
4023
+ // src/utils/jwt.ts
4024
+ function decodeJwtPayload(token) {
4025
+ const parts = token.split(".");
4026
+ if (parts.length !== 3) return null;
4027
+ try {
4028
+ const payload = parts[1];
4029
+ const json = Buffer.from(payload, "base64url").toString("utf-8");
4030
+ return JSON.parse(json);
4031
+ } catch {
4032
+ return null;
4033
+ }
4034
+ }
4035
+ function tryParseJson(value) {
4036
+ if (typeof value !== "string") return void 0;
4037
+ try {
4038
+ return JSON.parse(value);
4039
+ } catch {
4040
+ return void 0;
4041
+ }
4042
+ }
4043
+ function tryParseJsonArray(value) {
4044
+ if (typeof value !== "string") return void 0;
4045
+ try {
4046
+ const parsed = JSON.parse(value);
4047
+ return Array.isArray(parsed) && parsed.every((item) => typeof item === "string") ? parsed : void 0;
4048
+ } catch {
4049
+ return void 0;
4050
+ }
4051
+ }
4052
+ function parseKSeFTokenContext(token) {
4053
+ const raw = decodeJwtPayload(token);
4054
+ if (!raw) return null;
4055
+ return {
4056
+ type: typeof raw["typ"] === "string" ? raw["typ"] : void 0,
4057
+ contextIdentifierType: typeof raw["cit"] === "string" ? raw["cit"] : void 0,
4058
+ contextIdentifierValue: typeof raw["civ"] === "string" ? raw["civ"] : void 0,
4059
+ authMethod: typeof raw["aum"] === "string" ? raw["aum"] : void 0,
4060
+ permissions: tryParseJsonArray(raw["per"]),
4061
+ subjectDetails: tryParseJson(raw["sud"]),
4062
+ authorSubjectIdentifier: tryParseJson(raw["asi"]),
4063
+ issuedAt: typeof raw["iat"] === "number" ? raw["iat"] : void 0,
4064
+ expiresAt: typeof raw["exp"] === "number" ? raw["exp"] : void 0
4065
+ };
4066
+ }
4067
+ var init_jwt = __esm({
4068
+ "src/utils/jwt.ts"() {
4069
+ "use strict";
4070
+ init_cjs_shims();
4071
+ }
4072
+ });
4073
+
3476
4074
  // src/services/tokens.ts
3477
- var TokenService;
4075
+ function toTokenAuthorIdentifierType(value) {
4076
+ return TOKEN_AUTHOR_IDENTIFIER_TYPES.has(value) ? value : void 0;
4077
+ }
4078
+ var TOKEN_AUTHOR_IDENTIFIER_TYPES, TokenService;
3478
4079
  var init_tokens = __esm({
3479
4080
  "src/services/tokens.ts"() {
3480
4081
  "use strict";
4082
+ init_cjs_shims();
3481
4083
  init_rest_request();
3482
4084
  init_routes();
4085
+ init_jwt();
4086
+ init_ksef_api_error();
4087
+ init_ksef_error();
4088
+ TOKEN_AUTHOR_IDENTIFIER_TYPES = /* @__PURE__ */ new Set([
4089
+ "Nip",
4090
+ "Pesel",
4091
+ "Fingerprint"
4092
+ ]);
3483
4093
  TokenService = class {
3484
4094
  restClient;
3485
4095
  constructor(restClient) {
@@ -3514,6 +4124,73 @@ var init_tokens = __esm({
3514
4124
  const req = RestRequest.delete(Routes.Tokens.byReference(ref));
3515
4125
  await this.restClient.executeVoid(req);
3516
4126
  }
4127
+ /**
4128
+ * Resolves the reference number of the token currently in use for authentication.
4129
+ * The only JWT payload field treated as authoritative is the KSeF-specific `trn`
4130
+ * (token reference number). Standard RFC 7519 claims such as `jti` are NOT a safe
4131
+ * fallback — a `jti` that differs from the KSeF reference would cause a DELETE to
4132
+ * hit a non-existent path, which `revokeSelf` treats as already-revoked, falsely
4133
+ * reporting success while leaving the token active on the server. When `trn` is
4134
+ * absent, we fall back to `GET /tokens` filtered by author and context; requires
4135
+ * exactly one active match and returns undefined when ambiguous.
4136
+ */
4137
+ async findSelfReferenceNumber(accessToken) {
4138
+ if (!accessToken) return void 0;
4139
+ const payload = decodeJwtPayload(accessToken);
4140
+ if (payload && typeof payload["trn"] === "string" && payload["trn"].length > 0) {
4141
+ return payload["trn"];
4142
+ }
4143
+ const ctx = parseKSeFTokenContext(accessToken);
4144
+ const author = ctx?.authorSubjectIdentifier;
4145
+ if (!author?.type || !author.value) return void 0;
4146
+ if (!ctx?.contextIdentifierType || !ctx?.contextIdentifierValue) return void 0;
4147
+ const authorType = toTokenAuthorIdentifierType(author.type);
4148
+ if (!authorType) return void 0;
4149
+ let continuationToken;
4150
+ let match;
4151
+ do {
4152
+ const list = await this.queryTokens({
4153
+ status: ["Active"],
4154
+ authorIdentifier: author.value,
4155
+ authorIdentifierType: authorType,
4156
+ pageSize: 50,
4157
+ continuationToken
4158
+ });
4159
+ for (const t of list.tokens) {
4160
+ if (t.status === "Active" && t.contextIdentifier?.value === ctx.contextIdentifierValue && t.contextIdentifier?.type === ctx.contextIdentifierType) {
4161
+ if (match) return void 0;
4162
+ match = t.referenceNumber;
4163
+ }
4164
+ }
4165
+ continuationToken = list.continuationToken ?? void 0;
4166
+ } while (continuationToken);
4167
+ return match;
4168
+ }
4169
+ /**
4170
+ * Revokes the token currently used for authentication.
4171
+ * Treats 404/409/410 on DELETE as "already revoked" and returns successfully with
4172
+ * `alreadyRevoked: true` so callers can still clear local state.
4173
+ */
4174
+ async revokeSelf(opts = {}) {
4175
+ let ref = opts.referenceNumber;
4176
+ if (!ref && opts.accessToken) {
4177
+ ref = await this.findSelfReferenceNumber(opts.accessToken);
4178
+ }
4179
+ if (!ref) {
4180
+ throw new KSeFError(
4181
+ "Could not determine the current token reference number: no cache, JWT lacks the field, and the active-token list had 0 or 2+ matches in the current context."
4182
+ );
4183
+ }
4184
+ try {
4185
+ await this.revokeToken(ref);
4186
+ return { referenceNumber: ref, alreadyRevoked: false };
4187
+ } catch (err) {
4188
+ if (err instanceof KSeFApiError && (err.statusCode === 404 || err.statusCode === 409 || err.statusCode === 410)) {
4189
+ return { referenceNumber: ref, alreadyRevoked: true };
4190
+ }
4191
+ throw err;
4192
+ }
4193
+ }
3517
4194
  };
3518
4195
  }
3519
4196
  });
@@ -3523,6 +4200,7 @@ var CertificateApiService;
3523
4200
  var init_certificates = __esm({
3524
4201
  "src/services/certificates.ts"() {
3525
4202
  "use strict";
4203
+ init_cjs_shims();
3526
4204
  init_rest_request();
3527
4205
  init_routes();
3528
4206
  CertificateApiService = class {
@@ -3575,6 +4253,7 @@ var LighthouseService;
3575
4253
  var init_lighthouse = __esm({
3576
4254
  "src/services/lighthouse.ts"() {
3577
4255
  "use strict";
4256
+ init_cjs_shims();
3578
4257
  init_errors();
3579
4258
  LighthouseService = class {
3580
4259
  lighthouseUrl;
@@ -3583,20 +4262,20 @@ var init_lighthouse = __esm({
3583
4262
  this.lighthouseUrl = options.lighthouseUrl;
3584
4263
  this.timeout = options.timeout;
3585
4264
  }
3586
- async fetchJson(path2) {
4265
+ async fetchJson(path3) {
3587
4266
  if (!this.lighthouseUrl) {
3588
4267
  throw new KSeFError(
3589
4268
  "Lighthouse API is not available for the DEMO environment. Use TEST or PROD instead."
3590
4269
  );
3591
4270
  }
3592
- const response = await fetch(`${this.lighthouseUrl}${path2}`, {
4271
+ const response = await fetch(`${this.lighthouseUrl}${path3}`, {
3593
4272
  headers: { Accept: "application/json" },
3594
4273
  signal: AbortSignal.timeout(this.timeout)
3595
4274
  });
3596
4275
  if (!response.ok) {
3597
4276
  const body = await response.text();
3598
4277
  throw new KSeFError(
3599
- `Lighthouse ${path2} failed: HTTP ${response.status} \u2014 ${body}`
4278
+ `Lighthouse ${path3} failed: HTTP ${response.status} \u2014 ${body}`
3600
4279
  );
3601
4280
  }
3602
4281
  return await response.json();
@@ -3617,6 +4296,7 @@ var LimitsService;
3617
4296
  var init_limits = __esm({
3618
4297
  "src/services/limits.ts"() {
3619
4298
  "use strict";
4299
+ init_cjs_shims();
3620
4300
  init_rest_request();
3621
4301
  init_routes();
3622
4302
  LimitsService = class {
@@ -3648,6 +4328,7 @@ var PeppolService;
3648
4328
  var init_peppol = __esm({
3649
4329
  "src/services/peppol.ts"() {
3650
4330
  "use strict";
4331
+ init_cjs_shims();
3651
4332
  init_rest_request();
3652
4333
  init_routes();
3653
4334
  PeppolService = class {
@@ -3671,6 +4352,7 @@ var TestDataService;
3671
4352
  var init_test_data = __esm({
3672
4353
  "src/services/test-data.ts"() {
3673
4354
  "use strict";
4355
+ init_cjs_shims();
3674
4356
  init_rest_request();
3675
4357
  init_routes();
3676
4358
  init_ksef_error();
@@ -3790,6 +4472,7 @@ var CertificateFetcher;
3790
4472
  var init_certificate_fetcher = __esm({
3791
4473
  "src/crypto/certificate-fetcher.ts"() {
3792
4474
  "use strict";
4475
+ init_cjs_shims();
3793
4476
  init_rest_request();
3794
4477
  init_routes();
3795
4478
  CertificateFetcher = class {
@@ -3883,6 +4566,7 @@ var crypto2, x509, CryptographyService;
3883
4566
  var init_cryptography_service = __esm({
3884
4567
  "src/crypto/cryptography-service.ts"() {
3885
4568
  "use strict";
4569
+ init_cjs_shims();
3886
4570
  crypto2 = __toESM(require("crypto"), 1);
3887
4571
  x509 = __toESM(require("@peculiar/x509"), 1);
3888
4572
  CryptographyService = class {
@@ -4119,6 +4803,40 @@ var signature_service_exports = {};
4119
4803
  __export(signature_service_exports, {
4120
4804
  SignatureService: () => SignatureService
4121
4805
  });
4806
+ function pickRsaAlgo() {
4807
+ return {
4808
+ nodeHashName: "sha256",
4809
+ signatureUri: RSA_SHA256_SIGNATURE_URI,
4810
+ digestUri: DIGEST_URI.sha256
4811
+ };
4812
+ }
4813
+ function pickEcdsaAlgo(privateKey) {
4814
+ const curve = privateKey.asymmetricKeyDetails?.namedCurve;
4815
+ switch (curve) {
4816
+ case "prime256v1":
4817
+ return {
4818
+ nodeHashName: "sha256",
4819
+ signatureUri: ECDSA_SIGNATURE_URI.sha256,
4820
+ digestUri: DIGEST_URI.sha256
4821
+ };
4822
+ case "secp384r1":
4823
+ return {
4824
+ nodeHashName: "sha384",
4825
+ signatureUri: ECDSA_SIGNATURE_URI.sha384,
4826
+ digestUri: DIGEST_URI.sha384
4827
+ };
4828
+ case "secp521r1":
4829
+ return {
4830
+ nodeHashName: "sha512",
4831
+ signatureUri: ECDSA_SIGNATURE_URI.sha512,
4832
+ digestUri: DIGEST_URI.sha512
4833
+ };
4834
+ default:
4835
+ throw new KSeFError(
4836
+ `Unsupported ECDSA curve: ${curve ?? "unknown"}. Supported: P-256 (prime256v1), P-384 (secp384r1), P-521 (secp521r1).`
4837
+ );
4838
+ }
4839
+ }
4122
4840
  function extractDerFromPem(pem) {
4123
4841
  const base64 = pem.replace(/-----BEGIN [A-Z\s]+-----/g, "").replace(/-----END [A-Z\s]+-----/g, "").replace(/\s+/g, "");
4124
4842
  return Buffer.from(base64, "base64");
@@ -4133,22 +4851,22 @@ function canonicalize(elem) {
4133
4851
  const c14n = new import_xml_crypto.ExclusiveCanonicalization();
4134
4852
  return c14n.process(elem, {});
4135
4853
  }
4136
- function computeRootDigest(doc) {
4854
+ function computeRootDigest(doc, hashName) {
4137
4855
  const root = doc.documentElement;
4138
4856
  const canonical = canonicalize(root);
4139
- return crypto3.createHash("sha256").update(canonical, "utf-8").digest("base64");
4857
+ return crypto3.createHash(hashName).update(canonical, "utf-8").digest("base64");
4140
4858
  }
4141
- function computeSignedPropertiesDigest(qualifyingPropertiesXml) {
4142
- const parser = new import_xmldom2.DOMParser();
4143
- const qpDoc = parser.parseFromString(qualifyingPropertiesXml, "text/xml");
4859
+ function computeSignedPropertiesDigest(qualifyingPropertiesXml, hashName) {
4860
+ const parser2 = new import_xmldom2.DOMParser();
4861
+ const qpDoc = parser2.parseFromString(qualifyingPropertiesXml, "text/xml");
4144
4862
  const signedProps = findElementByLocalName(qpDoc.documentElement, "SignedProperties");
4145
4863
  if (!signedProps) {
4146
4864
  throw new Error("SignedProperties element not found in QualifyingProperties");
4147
4865
  }
4148
4866
  const canonical = canonicalize(signedProps);
4149
- return crypto3.createHash("sha256").update(canonical, "utf-8").digest("base64");
4867
+ return crypto3.createHash(hashName).update(canonical, "utf-8").digest("base64");
4150
4868
  }
4151
- function buildSignedInfo(signatureAlgorithm, rootDigest, signedPropertiesDigest) {
4869
+ function buildSignedInfo(signatureAlgorithm, digestAlgorithm, rootDigest, signedPropertiesDigest) {
4152
4870
  return [
4153
4871
  `<ds:SignedInfo xmlns:ds="${DS_NS}">`,
4154
4872
  `<ds:CanonicalizationMethod Algorithm="${EXC_C14N_ALGORITHM}"/>`,
@@ -4159,7 +4877,7 @@ function buildSignedInfo(signatureAlgorithm, rootDigest, signedPropertiesDigest)
4159
4877
  `<ds:Transform Algorithm="${ENVELOPED_SIGNATURE_TRANSFORM}"/>`,
4160
4878
  `<ds:Transform Algorithm="${EXC_C14N_ALGORITHM}"/>`,
4161
4879
  `</ds:Transforms>`,
4162
- `<ds:DigestMethod Algorithm="${SHA256_DIGEST_METHOD}"/>`,
4880
+ `<ds:DigestMethod Algorithm="${digestAlgorithm}"/>`,
4163
4881
  `<ds:DigestValue>${rootDigest}</ds:DigestValue>`,
4164
4882
  `</ds:Reference>`,
4165
4883
  // Reference 2: SignedProperties
@@ -4167,22 +4885,22 @@ function buildSignedInfo(signatureAlgorithm, rootDigest, signedPropertiesDigest)
4167
4885
  `<ds:Transforms>`,
4168
4886
  `<ds:Transform Algorithm="${EXC_C14N_ALGORITHM}"/>`,
4169
4887
  `</ds:Transforms>`,
4170
- `<ds:DigestMethod Algorithm="${SHA256_DIGEST_METHOD}"/>`,
4888
+ `<ds:DigestMethod Algorithm="${digestAlgorithm}"/>`,
4171
4889
  `<ds:DigestValue>${signedPropertiesDigest}</ds:DigestValue>`,
4172
4890
  `</ds:Reference>`,
4173
4891
  `</ds:SignedInfo>`
4174
4892
  ].join("");
4175
4893
  }
4176
- function computeSignatureValue(canonicalSignedInfo, privateKey, isEc) {
4894
+ function computeSignatureValue(canonicalSignedInfo, privateKey, isEc, hashName) {
4177
4895
  const data = Buffer.from(canonicalSignedInfo, "utf-8");
4178
4896
  let signature;
4179
4897
  if (isEc) {
4180
- signature = crypto3.sign("sha256", data, {
4898
+ signature = crypto3.sign(hashName, data, {
4181
4899
  key: privateKey,
4182
4900
  dsaEncoding: "ieee-p1363"
4183
4901
  });
4184
4902
  } else {
4185
- signature = crypto3.sign("sha256", data, privateKey);
4903
+ signature = crypto3.sign(hashName, data, privateKey);
4186
4904
  }
4187
4905
  return signature.toString("base64");
4188
4906
  }
@@ -4203,7 +4921,7 @@ function buildSignatureElement(signedInfoXml, signatureValue, certBase64, qualif
4203
4921
  `</ds:Signature>`
4204
4922
  ].join("");
4205
4923
  }
4206
- function buildQualifyingProperties(signatureId, signedPropertiesId, certDigest, issuerName, serialNumber, signingTime) {
4924
+ function buildQualifyingProperties(signatureId, signedPropertiesId, certDigest, issuerName, serialNumber, signingTime, digestAlgorithm) {
4207
4925
  return [
4208
4926
  `<xades:QualifyingProperties`,
4209
4927
  ` Target="#${signatureId}"`,
@@ -4215,7 +4933,7 @@ function buildQualifyingProperties(signatureId, signedPropertiesId, certDigest,
4215
4933
  `<xades:SigningCertificate>`,
4216
4934
  `<xades:Cert>`,
4217
4935
  `<xades:CertDigest>`,
4218
- `<DigestMethod Algorithm="${SHA256_DIGEST_METHOD}"/>`,
4936
+ `<DigestMethod Algorithm="${digestAlgorithm}"/>`,
4219
4937
  `<DigestValue>${certDigest}</DigestValue>`,
4220
4938
  `</xades:CertDigest>`,
4221
4939
  `<xades:IssuerSerial>`,
@@ -4251,21 +4969,31 @@ function wrapBase64(base64) {
4251
4969
  }
4252
4970
  return lines.join("\n");
4253
4971
  }
4254
- var crypto3, import_xml_crypto, import_xmldom2, XADES_NS, DS_NS, SIGNED_PROPERTIES_TYPE, SHA256_DIGEST_METHOD, EXC_C14N_ALGORITHM, ENVELOPED_SIGNATURE_TRANSFORM, RSA_SHA256_SIGNATURE, ECDSA_SHA256_SIGNATURE, CLOCK_SKEW_BUFFER_MS, SIGNATURE_ID, SIGNED_PROPERTIES_ID, SignatureService;
4972
+ var crypto3, import_xml_crypto, import_xmldom2, XADES_NS, DS_NS, SIGNED_PROPERTIES_TYPE, EXC_C14N_ALGORITHM, ENVELOPED_SIGNATURE_TRANSFORM, DIGEST_URI, ECDSA_SIGNATURE_URI, RSA_SHA256_SIGNATURE_URI, CLOCK_SKEW_BUFFER_MS, SIGNATURE_ID, SIGNED_PROPERTIES_ID, SignatureService;
4255
4973
  var init_signature_service = __esm({
4256
4974
  "src/crypto/signature-service.ts"() {
4257
4975
  "use strict";
4976
+ init_cjs_shims();
4258
4977
  crypto3 = __toESM(require("crypto"), 1);
4259
4978
  import_xml_crypto = require("xml-crypto");
4260
4979
  import_xmldom2 = require("@xmldom/xmldom");
4980
+ init_ksef_error();
4261
4981
  XADES_NS = "http://uri.etsi.org/01903/v1.3.2#";
4262
4982
  DS_NS = "http://www.w3.org/2000/09/xmldsig#";
4263
4983
  SIGNED_PROPERTIES_TYPE = "http://uri.etsi.org/01903#SignedProperties";
4264
- SHA256_DIGEST_METHOD = "http://www.w3.org/2001/04/xmlenc#sha256";
4265
4984
  EXC_C14N_ALGORITHM = "http://www.w3.org/2001/10/xml-exc-c14n#";
4266
4985
  ENVELOPED_SIGNATURE_TRANSFORM = "http://www.w3.org/2000/09/xmldsig#enveloped-signature";
4267
- RSA_SHA256_SIGNATURE = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256";
4268
- ECDSA_SHA256_SIGNATURE = "http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha256";
4986
+ DIGEST_URI = {
4987
+ sha256: "http://www.w3.org/2001/04/xmlenc#sha256",
4988
+ sha384: "http://www.w3.org/2001/04/xmldsig-more#sha384",
4989
+ sha512: "http://www.w3.org/2001/04/xmlenc#sha512"
4990
+ };
4991
+ ECDSA_SIGNATURE_URI = {
4992
+ sha256: "http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha256",
4993
+ sha384: "http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha384",
4994
+ sha512: "http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha512"
4995
+ };
4996
+ RSA_SHA256_SIGNATURE_URI = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256";
4269
4997
  CLOCK_SKEW_BUFFER_MS = -6e4;
4270
4998
  SIGNATURE_ID = "Signature";
4271
4999
  SIGNED_PROPERTIES_ID = "SignedProperties";
@@ -4285,18 +5013,24 @@ var init_signature_service = __esm({
4285
5013
  }
4286
5014
  const certDer = extractDerFromPem(certPem);
4287
5015
  const certBase64 = certDer.toString("base64");
4288
- const certDigest = crypto3.createHash("sha256").update(certDer).digest("base64");
4289
5016
  const x5093 = new crypto3.X509Certificate(certPem);
4290
5017
  const issuerName = normalizeIssuerDn(x5093.issuer);
4291
5018
  const serialNumber = hexSerialToDecimal(x5093.serialNumber);
4292
5019
  const privateKey = crypto3.createPrivateKey(
4293
5020
  passphrase ? { key: privateKeyPem, format: "pem", passphrase } : privateKeyPem
4294
5021
  );
4295
- const isEc = privateKey.asymmetricKeyType === "ec";
4296
- const signatureAlgorithm = isEc ? ECDSA_SHA256_SIGNATURE : RSA_SHA256_SIGNATURE;
5022
+ const keyType = privateKey.asymmetricKeyType;
5023
+ if (keyType !== "ec" && keyType !== "rsa") {
5024
+ throw new KSeFError(
5025
+ `Unsupported private key type: ${keyType ?? "unknown"}. Supported: RSA and ECDSA.`
5026
+ );
5027
+ }
5028
+ const isEc = keyType === "ec";
5029
+ const algo = isEc ? pickEcdsaAlgo(privateKey) : pickRsaAlgo();
5030
+ const certDigest = crypto3.createHash(algo.nodeHashName).update(certDer).digest("base64");
4297
5031
  const signingTime = new Date(Date.now() + CLOCK_SKEW_BUFFER_MS).toISOString();
4298
- const parser = new import_xmldom2.DOMParser();
4299
- const doc = parser.parseFromString(xml, "text/xml");
5032
+ const parser2 = new import_xmldom2.DOMParser();
5033
+ const doc = parser2.parseFromString(xml, "text/xml");
4300
5034
  const root = doc.documentElement;
4301
5035
  if (!root) {
4302
5036
  throw new Error("XML document has no root element");
@@ -4307,21 +5041,27 @@ var init_signature_service = __esm({
4307
5041
  certDigest,
4308
5042
  issuerName,
4309
5043
  serialNumber,
4310
- signingTime
5044
+ signingTime,
5045
+ algo.digestUri
5046
+ );
5047
+ const rootDigest = computeRootDigest(doc, algo.nodeHashName);
5048
+ const signedPropertiesDigest = computeSignedPropertiesDigest(
5049
+ qualifyingPropertiesXml,
5050
+ algo.nodeHashName
4311
5051
  );
4312
- const rootDigest = computeRootDigest(doc);
4313
- const signedPropertiesDigest = computeSignedPropertiesDigest(qualifyingPropertiesXml);
4314
5052
  const signedInfoXml = buildSignedInfo(
4315
- signatureAlgorithm,
5053
+ algo.signatureUri,
5054
+ algo.digestUri,
4316
5055
  rootDigest,
4317
5056
  signedPropertiesDigest
4318
5057
  );
4319
- const signedInfoDoc = parser.parseFromString(signedInfoXml, "text/xml");
5058
+ const signedInfoDoc = parser2.parseFromString(signedInfoXml, "text/xml");
4320
5059
  const canonicalSignedInfo = canonicalize(signedInfoDoc.documentElement);
4321
5060
  const signatureValue = computeSignatureValue(
4322
5061
  canonicalSignedInfo,
4323
5062
  privateKey,
4324
- isEc
5063
+ isEc,
5064
+ algo.nodeHashName
4325
5065
  );
4326
5066
  const signatureXml = buildSignatureElement(
4327
5067
  signedInfoXml,
@@ -4329,7 +5069,7 @@ var init_signature_service = __esm({
4329
5069
  certBase64,
4330
5070
  qualifyingPropertiesXml
4331
5071
  );
4332
- const signatureDoc = parser.parseFromString(signatureXml, "text/xml");
5072
+ const signatureDoc = parser2.parseFromString(signatureXml, "text/xml");
4333
5073
  const importedNode = doc.importNode(signatureDoc.documentElement, true);
4334
5074
  root.appendChild(importedNode);
4335
5075
  return new import_xmldom2.XMLSerializer().serializeToString(doc);
@@ -4347,6 +5087,7 @@ var import_node_forge, Pkcs12Loader;
4347
5087
  var init_pkcs12_loader = __esm({
4348
5088
  "src/crypto/pkcs12-loader.ts"() {
4349
5089
  "use strict";
5090
+ init_cjs_shims();
4350
5091
  import_node_forge = __toESM(require("node-forge"), 1);
4351
5092
  Pkcs12Loader = class {
4352
5093
  static load(p12, password) {
@@ -4416,6 +5157,7 @@ var AUTH_TOKEN_REQUEST_NS;
4416
5157
  var init_auth_xml_builder = __esm({
4417
5158
  "src/crypto/auth-xml-builder.ts"() {
4418
5159
  "use strict";
5160
+ init_cjs_shims();
4419
5161
  AUTH_TOKEN_REQUEST_NS = "http://ksef.mf.gov.pl/auth/token/2.0";
4420
5162
  }
4421
5163
  });
@@ -4425,6 +5167,7 @@ var import_node_crypto, VerificationLinkService;
4425
5167
  var init_verification_link_service = __esm({
4426
5168
  "src/qr/verification-link-service.ts"() {
4427
5169
  "use strict";
5170
+ init_cjs_shims();
4428
5171
  import_node_crypto = __toESM(require("crypto"), 1);
4429
5172
  VerificationLinkService = class {
4430
5173
  constructor(baseQrUrl) {
@@ -4447,11 +5190,11 @@ var init_verification_link_service = __esm({
4447
5190
  * Build certificate verification URL (Code II).
4448
5191
  * Format: {baseQrUrl}/certificate/{contextType}/{contextId}/{sellerNip}/{certSerial}/{hash_base64url}/{signature_base64url}
4449
5192
  */
4450
- buildCertificateVerificationUrl(contextType, contextId, sellerNip, certSerial, invoiceHashBase64, privateKeyPem) {
5193
+ buildCertificateVerificationUrl(contextType, contextId, sellerNip, certSerial, invoiceHashBase64, privateKeyPem, privateKeyPassword) {
4451
5194
  const hashBase64Url = this.base64ToBase64Url(invoiceHashBase64);
4452
5195
  const pathWithoutSignature = `${this.baseQrUrl}/certificate/${contextType}/${contextId}/${sellerNip}/${certSerial}/${hashBase64Url}`;
4453
5196
  const dataToSign = pathWithoutSignature.replace(/^https?:\/\//, "");
4454
- const key = import_node_crypto.default.createPrivateKey(privateKeyPem);
5197
+ const key = privateKeyPassword !== void 0 ? import_node_crypto.default.createPrivateKey({ key: privateKeyPem, format: "pem", passphrase: privateKeyPassword }) : import_node_crypto.default.createPrivateKey(privateKeyPem);
4455
5198
  let signature;
4456
5199
  if (key.asymmetricKeyType === "rsa") {
4457
5200
  signature = import_node_crypto.default.sign("sha256", Buffer.from(dataToSign), {
@@ -4565,6 +5308,7 @@ var import_yazl, import_yauzl, DEFAULT_UNZIP_OPTIONS;
4565
5308
  var init_zip = __esm({
4566
5309
  "src/utils/zip.ts"() {
4567
5310
  "use strict";
5311
+ init_cjs_shims();
4568
5312
  import_yazl = require("yazl");
4569
5313
  import_yauzl = require("yauzl");
4570
5314
  DEFAULT_UNZIP_OPTIONS = {
@@ -4638,6 +5382,7 @@ var holidayCache;
4638
5382
  var init_holidays = __esm({
4639
5383
  "src/offline/holidays.ts"() {
4640
5384
  "use strict";
5385
+ init_cjs_shims();
4641
5386
  holidayCache = /* @__PURE__ */ new Map();
4642
5387
  }
4643
5388
  });
@@ -4737,6 +5482,7 @@ var FAR_FUTURE;
4737
5482
  var init_deadline = __esm({
4738
5483
  "src/offline/deadline.ts"() {
4739
5484
  "use strict";
5485
+ init_cjs_shims();
4740
5486
  init_holidays();
4741
5487
  FAR_FUTURE = /* @__PURE__ */ new Date("9999-12-31T23:59:59Z");
4742
5488
  }
@@ -4747,6 +5493,7 @@ var import_node_crypto3, OfflineInvoiceWorkflow;
4747
5493
  var init_offline_invoice_workflow = __esm({
4748
5494
  "src/workflows/offline-invoice-workflow.ts"() {
4749
5495
  "use strict";
5496
+ init_cjs_shims();
4750
5497
  import_node_crypto3 = __toESM(require("crypto"), 1);
4751
5498
  init_ksef_api_error();
4752
5499
  init_deadline();
@@ -4781,7 +5528,8 @@ var init_offline_invoice_workflow = __esm({
4781
5528
  input.sellerNip,
4782
5529
  options.certificate.certificateSerial,
4783
5530
  invoiceHashBase64,
4784
- options.certificate.privateKeyPem
5531
+ options.certificate.privateKeyPem,
5532
+ options.certificate.password
4785
5533
  );
4786
5534
  }
4787
5535
  const submitBy = options?.customDeadline ? typeof options.customDeadline === "string" ? options.customDeadline : options.customDeadline.toISOString() : calculateOfflineDeadline(mode, input.invoiceDate, options?.maintenanceWindow).toISOString();
@@ -4971,7 +5719,8 @@ var init_offline_invoice_workflow = __esm({
4971
5719
  original.sellerNip,
4972
5720
  options.certificate.certificateSerial,
4973
5721
  correctedHashBase64,
4974
- options.certificate.privateKeyPem
5722
+ options.certificate.privateKeyPem,
5723
+ options.certificate.password
4975
5724
  );
4976
5725
  }
4977
5726
  const correctionMetadata = {
@@ -5057,6 +5806,11 @@ function buildRestClientConfig(options, authManager) {
5057
5806
  endpointLimits: options.rateLimit.endpointLimits
5058
5807
  });
5059
5808
  }
5809
+ if (options?.circuitBreaker === null) {
5810
+ config.circuitBreakerPolicy = null;
5811
+ } else if (options?.circuitBreaker) {
5812
+ config.circuitBreakerPolicy = new CircuitBreakerPolicy(options.circuitBreaker);
5813
+ }
5060
5814
  if (options?.presignedUrlHosts) {
5061
5815
  const base = defaultPresignedUrlPolicy();
5062
5816
  config.presignedUrlPolicy = {
@@ -5070,10 +5824,12 @@ var KSeFClient;
5070
5824
  var init_client = __esm({
5071
5825
  "src/client.ts"() {
5072
5826
  "use strict";
5827
+ init_cjs_shims();
5073
5828
  init_config();
5074
5829
  init_rest_client();
5075
5830
  init_retry_policy();
5076
5831
  init_rate_limit_policy();
5832
+ init_circuit_breaker_policy();
5077
5833
  init_presigned_url_policy();
5078
5834
  init_auth_manager();
5079
5835
  init_auth();
@@ -5227,12 +5983,17 @@ __export(index_exports, {
5227
5983
  CertificateFingerprint: () => CertificateFingerprint,
5228
5984
  CertificateName: () => CertificateName,
5229
5985
  CertificateService: () => CertificateService,
5986
+ CircuitBreakerPolicy: () => CircuitBreakerPolicy,
5230
5987
  CryptographyService: () => CryptographyService,
5231
5988
  DEFAULT_FORM_CODE: () => DEFAULT_FORM_CODE,
5989
+ DISCOURAGED_UNICODE_RANGES: () => DISCOURAGED_UNICODE_RANGES,
5232
5990
  DefaultAuthManager: () => DefaultAuthManager,
5233
5991
  ENFORCE_XADES_COMPLIANCE: () => ENFORCE_XADES_COMPLIANCE,
5992
+ ETD_NAMESPACE: () => ETD_NAMESPACE,
5234
5993
  EntityPermissionGrantBuilder: () => EntityPermissionGrantBuilder,
5235
5994
  Environment: () => Environment,
5995
+ FAKTURA_NAMESPACE: () => FAKTURA_NAMESPACE,
5996
+ FA_XSD_PATHS: () => FA_XSD_PATHS,
5236
5997
  FORM_CODES: () => FORM_CODES,
5237
5998
  FORM_CODE_KEYS: () => FORM_CODE_KEYS,
5238
5999
  FileHwmStore: () => FileHwmStore,
@@ -5249,7 +6010,9 @@ __export(index_exports, {
5249
6010
  KSEF_FEATURE_HEADER: () => KSEF_FEATURE_HEADER,
5250
6011
  KSeFApiError: () => KSeFApiError,
5251
6012
  KSeFAuthStatusError: () => KSeFAuthStatusError,
6013
+ KSeFBadRequestError: () => KSeFBadRequestError,
5252
6014
  KSeFBatchTimeoutError: () => KSeFBatchTimeoutError,
6015
+ KSeFCircuitOpenError: () => KSeFCircuitOpenError,
5253
6016
  KSeFClient: () => KSeFClient,
5254
6017
  KSeFError: () => KSeFError,
5255
6018
  KSeFErrorCode: () => KSeFErrorCode,
@@ -5259,6 +6022,7 @@ __export(index_exports, {
5259
6022
  KSeFSessionExpiredError: () => KSeFSessionExpiredError,
5260
6023
  KSeFUnauthorizedError: () => KSeFUnauthorizedError,
5261
6024
  KSeFValidationError: () => KSeFValidationError,
6025
+ KSeFXsdValidationError: () => KSeFXsdValidationError,
5262
6026
  KsefNumber: () => KsefNumber,
5263
6027
  KsefNumberV35: () => KsefNumberV35,
5264
6028
  KsefNumberV36: () => KsefNumberV36,
@@ -5266,8 +6030,11 @@ __export(index_exports, {
5266
6030
  LimitsService: () => LimitsService,
5267
6031
  Nip: () => Nip,
5268
6032
  NipVatUe: () => NipVatUe,
6033
+ ORDER_MAP: () => ORDER_MAP,
5269
6034
  OfflineInvoiceWorkflow: () => OfflineInvoiceWorkflow,
5270
6035
  OnlineSessionService: () => OnlineSessionService,
6036
+ PEF_NAMESPACE: () => PEF_NAMESPACE,
6037
+ PEF_XSD_PATHS: () => PEF_XSD_PATHS,
5271
6038
  PERMISSION_DESCRIPTION_MAX_LENGTH: () => PERMISSION_DESCRIPTION_MAX_LENGTH,
5272
6039
  PERMISSION_DESCRIPTION_MIN_LENGTH: () => PERMISSION_DESCRIPTION_MIN_LENGTH,
5273
6040
  PeppolId: () => PeppolId,
@@ -5297,17 +6064,25 @@ __export(index_exports, {
5297
6064
  VatUe: () => VatUe,
5298
6065
  VerificationLinkService: () => VerificationLinkService,
5299
6066
  addBusinessDays: () => addBusinessDays,
6067
+ assertNever: () => assertNever,
5300
6068
  authenticateWithCertificate: () => authenticateWithCertificate,
5301
6069
  authenticateWithExternalSignature: () => authenticateWithExternalSignature,
5302
6070
  authenticateWithPkcs12: () => authenticateWithPkcs12,
5303
6071
  authenticateWithToken: () => authenticateWithToken,
5304
6072
  batchValidationDetails: () => batchValidationDetails,
6073
+ buildFakturaXml: () => buildFakturaXml,
6074
+ buildPefXml: () => buildPefXml,
6075
+ buildRawXmlString: () => buildRawXmlString,
5305
6076
  buildUnsignedAuthTokenRequestXml: () => buildUnsignedAuthTokenRequestXml,
6077
+ buildXml: () => buildXml,
6078
+ buildXmlFromObject: () => buildXmlFromObject,
5306
6079
  calculateBackoff: () => calculateBackoff,
5307
6080
  calculateOfflineDeadline: () => calculateOfflineDeadline,
6081
+ comparePKey: () => comparePKey,
5308
6082
  createZip: () => createZip,
5309
6083
  decodeJwtPayload: () => decodeJwtPayload,
5310
6084
  deduplicateByKsefNumber: () => deduplicateByKsefNumber,
6085
+ defaultCircuitBreakerPolicy: () => defaultCircuitBreakerPolicy,
5311
6086
  defaultPresignedUrlPolicy: () => defaultPresignedUrlPolicy,
5312
6087
  defaultRateLimitPolicy: () => defaultRateLimitPolicy,
5313
6088
  defaultRetryPolicy: () => defaultRetryPolicy,
@@ -5323,6 +6098,9 @@ __export(index_exports, {
5323
6098
  getTimeUntilDeadline: () => getTimeUntilDeadline,
5324
6099
  incrementalExportAndDownload: () => incrementalExportAndDownload,
5325
6100
  isExpired: () => isExpired,
6101
+ isFakturaInput: () => isFakturaInput,
6102
+ isFormCodeShape: () => isFormCodeShape,
6103
+ isPefUblDocumentInput: () => isPefUblDocumentInput,
5326
6104
  isPolishHoliday: () => isPolishHoliday,
5327
6105
  isRetryableError: () => isRetryableError,
5328
6106
  isRetryableStatus: () => isRetryableStatus,
@@ -5341,19 +6119,26 @@ __export(index_exports, {
5341
6119
  isValidReferenceNumber: () => isValidReferenceNumber,
5342
6120
  isValidSha256Base64: () => isValidSha256Base64,
5343
6121
  isValidVatUe: () => isValidVatUe,
6122
+ libxmljsAvailable: () => libxmljsAvailable,
5344
6123
  nextBusinessDay: () => nextBusinessDay,
5345
6124
  openOnlineSession: () => openOnlineSession,
5346
6125
  openSendAndClose: () => openSendAndClose,
6126
+ orderXmlObject: () => orderXmlObject,
5347
6127
  parseFormCode: () => parseFormCode,
5348
6128
  parseKSeFTokenContext: () => parseKSeFTokenContext,
5349
6129
  parseRetryAfter: () => parseRetryAfter,
5350
6130
  parseUpoXml: () => parseUpoXml,
6131
+ parseXml: () => parseXml,
5351
6132
  pollUntil: () => pollUntil,
5352
6133
  resolveOptions: () => resolveOptions,
6134
+ resolveXsdFor: () => resolveXsdFor,
5353
6135
  resumeOnlineSession: () => resumeOnlineSession,
5354
6136
  runWithConcurrency: () => runWithConcurrency,
6137
+ serializeInvoiceXml: () => serializeInvoiceXml,
5355
6138
  sha256Base64: () => sha256Base642,
5356
6139
  sleep: () => sleep,
6140
+ stripBom: () => stripBom,
6141
+ toKodFormularza: () => toKodFormularza,
5357
6142
  unzip: () => unzip,
5358
6143
  updateContinuationPoint: () => updateContinuationPoint,
5359
6144
  uploadBatch: () => uploadBatch,
@@ -5361,8 +6146,10 @@ __export(index_exports, {
5361
6146
  uploadBatchStream: () => uploadBatchStream,
5362
6147
  uploadBatchStreamParsed: () => uploadBatchStreamParsed,
5363
6148
  validate: () => validate,
6149
+ validateAgainstXsd: () => validateAgainstXsd,
5364
6150
  validateBatch: () => validateBatch,
5365
6151
  validateBusinessRules: () => validateBusinessRules,
6152
+ validateCharValidity: () => validateCharValidity,
5366
6153
  validateFormCodeForSession: () => validateFormCodeForSession,
5367
6154
  validatePresignedUrl: () => validatePresignedUrl,
5368
6155
  validateSchema: () => validateSchema,
@@ -5371,10 +6158,12 @@ __export(index_exports, {
5371
6158
  xmlToObject: () => xmlToObject
5372
6159
  });
5373
6160
  module.exports = __toCommonJS(index_exports);
6161
+ init_cjs_shims();
5374
6162
  init_config();
5375
6163
  init_errors();
5376
6164
 
5377
6165
  // src/http/index.ts
6166
+ init_cjs_shims();
5378
6167
  init_route_builder();
5379
6168
  init_rest_request();
5380
6169
  init_rest_client();
@@ -5382,14 +6171,17 @@ init_routes();
5382
6171
  init_transport();
5383
6172
  init_retry_policy();
5384
6173
  init_rate_limit_policy();
6174
+ init_circuit_breaker_policy();
5385
6175
  init_auth_manager();
5386
6176
  init_presigned_url_policy();
5387
6177
  init_ksef_feature();
5388
6178
 
5389
6179
  // src/validation/index.ts
6180
+ init_cjs_shims();
5390
6181
  init_patterns();
5391
6182
 
5392
6183
  // src/validation/constraints.ts
6184
+ init_cjs_shims();
5393
6185
  var REQUIRED_CHALLENGE_LENGTH = 36;
5394
6186
  var CERTIFICATE_NAME_MIN_LENGTH = 5;
5395
6187
  var CERTIFICATE_NAME_MAX_LENGTH = 100;
@@ -5402,11 +6194,220 @@ var PERMISSION_DESCRIPTION_MAX_LENGTH = 256;
5402
6194
  init_xml_to_object();
5403
6195
  init_schema_registry();
5404
6196
  init_invoice_validator();
6197
+ init_char_validity();
6198
+
6199
+ // src/validation/xsd-validator.ts
6200
+ init_cjs_shims();
6201
+ var import_node_module = require("module");
6202
+ var fs = __toESM(require("fs"), 1);
6203
+ var path = __toESM(require("path"), 1);
6204
+ var import_node_url = require("url");
6205
+ var cachedPkgRoot = null;
6206
+ function locatePackageRoot() {
6207
+ if (cachedPkgRoot !== null) return cachedPkgRoot;
6208
+ let dir = path.dirname((0, import_node_url.fileURLToPath)(importMetaUrl));
6209
+ const root = path.parse(dir).root;
6210
+ while (dir !== root) {
6211
+ const candidate = path.join(dir, "docs", "schemas");
6212
+ if (fs.existsSync(candidate)) {
6213
+ cachedPkgRoot = dir;
6214
+ return dir;
6215
+ }
6216
+ dir = path.dirname(dir);
6217
+ }
6218
+ throw new Error("Could not locate ksef-client-ts package root (docs/schemas not found).");
6219
+ }
6220
+ var XSD_RELATIVE = {
6221
+ FA2: ["FA", "schemat_FA(2)_v1-0E.xsd"],
6222
+ FA3: ["FA", "schemat_FA(3)_v1-0E.xsd"],
6223
+ PEF: ["PEF", "Schemat_PEF(3)_v2-1.xsd"],
6224
+ PEF_KOR: ["PEF", "Schemat_PEF_KOR(3)_v2-1.xsd"]
6225
+ };
6226
+ var FA_XSD_PATHS = {
6227
+ get FA2() {
6228
+ return resolveXsdFor("FA2");
6229
+ },
6230
+ get FA3() {
6231
+ return resolveXsdFor("FA3");
6232
+ }
6233
+ };
6234
+ var PEF_XSD_PATHS = {
6235
+ get PEF() {
6236
+ return resolveXsdFor("PEF");
6237
+ },
6238
+ get PEF_KOR() {
6239
+ return resolveXsdFor("PEF_KOR");
6240
+ }
6241
+ };
6242
+ function resolveXsdFor(schema) {
6243
+ const rel = XSD_RELATIVE[schema];
6244
+ if (!rel) throw new Error(`Unknown invoice schema: ${String(schema)}`);
6245
+ return path.join(locatePackageRoot(), "docs", "schemas", ...rel);
6246
+ }
6247
+ var requireModule = (0, import_node_module.createRequire)(importMetaUrl);
6248
+ var libxmljs = null;
6249
+ var libxmljsLoadError = null;
6250
+ try {
6251
+ libxmljs = requireModule("libxmljs2");
6252
+ } catch (err) {
6253
+ const code = err?.code;
6254
+ if (code === "MODULE_NOT_FOUND" || code === "ERR_MODULE_NOT_FOUND") {
6255
+ libxmljs = null;
6256
+ } else {
6257
+ libxmljs = null;
6258
+ libxmljsLoadError = err instanceof Error ? err : new Error(String(err));
6259
+ }
6260
+ }
6261
+ var libxmljsAvailable = libxmljs !== null;
6262
+ var MISSING_LIBXMLJS_MESSAGE_PREFIX = "libxmljs2 is not installed";
6263
+ var EXTERNAL_STRUKTURY_DANYCH_URL = /schemaLocation="http:\/\/crd\.gov\.pl\/xml\/schematy\/dziedzinowe\/mf\/2022\/01\/05\/eD\/DefinicjeTypy\/StrukturyDanych_v10-0E\.xsd"/;
6264
+ function rewriteSchemaLocations(xsdContent) {
6265
+ if (!EXTERNAL_STRUKTURY_DANYCH_URL.test(xsdContent)) {
6266
+ return xsdContent;
6267
+ }
6268
+ const bazoweStrukturyPath = path.join(
6269
+ locatePackageRoot(),
6270
+ "docs",
6271
+ "schemas",
6272
+ "FA",
6273
+ "bazowe",
6274
+ "StrukturyDanych_v10-0E.xsd"
6275
+ );
6276
+ const bazoweStrukturyUrl = (0, import_node_url.pathToFileURL)(bazoweStrukturyPath).href;
6277
+ const rewritten = xsdContent.replace(
6278
+ EXTERNAL_STRUKTURY_DANYCH_URL,
6279
+ `schemaLocation="${bazoweStrukturyUrl}"`
6280
+ );
6281
+ if (rewritten === xsdContent) {
6282
+ throw new Error(
6283
+ "FA XSD schemaLocation rewrite produced no replacement despite URL being present; regex likely out of sync with docs/schemas/FA/. Re-check after `yarn sync-schemas`."
6284
+ );
6285
+ }
6286
+ return rewritten;
6287
+ }
6288
+ function validateAgainstXsd(xml, xsdPath) {
6289
+ if (!libxmljs) {
6290
+ const loadSuffix = libxmljsLoadError ? ` (load failed: ${libxmljsLoadError.message})` : "";
6291
+ throw new Error(
6292
+ `${MISSING_LIBXMLJS_MESSAGE_PREFIX}${loadSuffix}; cannot run XSD validation. Install it as an optional peer dependency (e.g. \`yarn add -O libxmljs2\` or \`npm i -O libxmljs2\`).`
6293
+ );
6294
+ }
6295
+ const xsdDir = path.dirname(xsdPath);
6296
+ const rawXsd = fs.readFileSync(xsdPath, "utf8");
6297
+ const rewrittenXsd = rewriteSchemaLocations(rawXsd);
6298
+ const baseUrl = (0, import_node_url.pathToFileURL)(xsdDir + path.sep).href;
6299
+ let schemaDoc;
6300
+ try {
6301
+ schemaDoc = libxmljs.parseXml(rewrittenXsd, { baseUrl });
6302
+ } catch (err) {
6303
+ return { valid: false, errors: [`XSD parse failed: ${err.message}`] };
6304
+ }
6305
+ let xmlDoc;
6306
+ try {
6307
+ xmlDoc = libxmljs.parseXml(xml);
6308
+ } catch (err) {
6309
+ return { valid: false, errors: [`XML parse failed: ${err.message}`] };
6310
+ }
6311
+ const valid = xmlDoc.validate(schemaDoc);
6312
+ const errors = valid ? [] : xmlDoc.validationErrors.map((err) => err.message.trim());
6313
+ return { valid, errors };
6314
+ }
6315
+
6316
+ // src/models/index.ts
6317
+ init_cjs_shims();
6318
+
6319
+ // src/models/common.ts
6320
+ init_cjs_shims();
6321
+
6322
+ // src/models/auth/index.ts
6323
+ init_cjs_shims();
6324
+
6325
+ // src/models/auth/types.ts
6326
+ init_cjs_shims();
6327
+
6328
+ // src/models/auth/active-sessions-types.ts
6329
+ init_cjs_shims();
6330
+
6331
+ // src/models/sessions/index.ts
6332
+ init_cjs_shims();
6333
+
6334
+ // src/models/sessions/online-types.ts
6335
+ init_cjs_shims();
6336
+
6337
+ // src/models/sessions/batch-types.ts
6338
+ init_cjs_shims();
6339
+
6340
+ // src/models/sessions/status-types.ts
6341
+ init_cjs_shims();
6342
+
6343
+ // src/models/sessions/session-state.ts
6344
+ init_cjs_shims();
6345
+
6346
+ // src/models/invoices/index.ts
6347
+ init_cjs_shims();
6348
+
6349
+ // src/models/invoices/types.ts
6350
+ init_cjs_shims();
6351
+
6352
+ // src/models/permissions/index.ts
6353
+ init_cjs_shims();
6354
+
6355
+ // src/models/permissions/types.ts
6356
+ init_cjs_shims();
6357
+
6358
+ // src/models/tokens/index.ts
6359
+ init_cjs_shims();
6360
+
6361
+ // src/models/tokens/types.ts
6362
+ init_cjs_shims();
6363
+
6364
+ // src/models/certificates/index.ts
6365
+ init_cjs_shims();
6366
+
6367
+ // src/models/certificates/types.ts
6368
+ init_cjs_shims();
6369
+
6370
+ // src/models/lighthouse/index.ts
6371
+ init_cjs_shims();
6372
+
6373
+ // src/models/lighthouse/types.ts
6374
+ init_cjs_shims();
6375
+
6376
+ // src/models/limits/index.ts
6377
+ init_cjs_shims();
6378
+
6379
+ // src/models/limits/types.ts
6380
+ init_cjs_shims();
6381
+
6382
+ // src/models/peppol/index.ts
6383
+ init_cjs_shims();
6384
+
6385
+ // src/models/peppol/types.ts
6386
+ init_cjs_shims();
6387
+
6388
+ // src/models/test-data/index.ts
6389
+ init_cjs_shims();
6390
+
6391
+ // src/models/test-data/types.ts
6392
+ init_cjs_shims();
6393
+
6394
+ // src/models/crypto/index.ts
6395
+ init_cjs_shims();
6396
+
6397
+ // src/models/crypto/types.ts
6398
+ init_cjs_shims();
6399
+
6400
+ // src/models/qrcode/index.ts
6401
+ init_cjs_shims();
6402
+
6403
+ // src/models/qrcode/types.ts
6404
+ init_cjs_shims();
5405
6405
 
5406
6406
  // src/models/index.ts
5407
6407
  init_document_structures();
5408
6408
 
5409
6409
  // src/services/index.ts
6410
+ init_cjs_shims();
5410
6411
  init_auth();
5411
6412
  init_active_sessions();
5412
6413
  init_online_session();
@@ -5421,7 +6422,11 @@ init_limits();
5421
6422
  init_peppol();
5422
6423
  init_test_data();
5423
6424
 
6425
+ // src/builders/index.ts
6426
+ init_cjs_shims();
6427
+
5424
6428
  // src/builders/auth-token-request.ts
6429
+ init_cjs_shims();
5425
6430
  init_ksef_validation_error();
5426
6431
  var AuthTokenRequestBuilder = class {
5427
6432
  challenge;
@@ -5476,6 +6481,7 @@ var AuthTokenRequestBuilder = class {
5476
6481
  };
5477
6482
 
5478
6483
  // src/builders/auth-ksef-token-request.ts
6484
+ init_cjs_shims();
5479
6485
  init_ksef_validation_error();
5480
6486
  var AuthKsefTokenRequestBuilder = class {
5481
6487
  challenge;
@@ -5530,6 +6536,7 @@ var AuthKsefTokenRequestBuilder = class {
5530
6536
  };
5531
6537
 
5532
6538
  // src/builders/invoice-query-filter.ts
6539
+ init_cjs_shims();
5533
6540
  init_ksef_validation_error();
5534
6541
  var InvoiceQueryFilterBuilder = class {
5535
6542
  subjectType;
@@ -5626,7 +6633,11 @@ var InvoiceQueryFilterBuilder = class {
5626
6633
  }
5627
6634
  };
5628
6635
 
6636
+ // src/builders/permissions/index.ts
6637
+ init_cjs_shims();
6638
+
5629
6639
  // src/builders/permissions/person-permission.ts
6640
+ init_cjs_shims();
5630
6641
  init_ksef_validation_error();
5631
6642
  var PersonPermissionGrantBuilder = class {
5632
6643
  subjectIdentifier;
@@ -5676,6 +6687,7 @@ var PersonPermissionGrantBuilder = class {
5676
6687
  };
5677
6688
 
5678
6689
  // src/builders/permissions/entity-permission.ts
6690
+ init_cjs_shims();
5679
6691
  init_ksef_validation_error();
5680
6692
  var EntityPermissionGrantBuilder = class {
5681
6693
  nip;
@@ -5725,6 +6737,7 @@ var EntityPermissionGrantBuilder = class {
5725
6737
  };
5726
6738
 
5727
6739
  // src/builders/permissions/authorization-permission.ts
6740
+ init_cjs_shims();
5728
6741
  init_ksef_validation_error();
5729
6742
  var AuthorizationPermissionGrantBuilder = class {
5730
6743
  _subjectIdentifier;
@@ -5770,6 +6783,7 @@ var AuthorizationPermissionGrantBuilder = class {
5770
6783
  };
5771
6784
 
5772
6785
  // src/builders/batch-file.ts
6786
+ init_cjs_shims();
5773
6787
  var crypto = __toESM(require("crypto"), 1);
5774
6788
  init_ksef_validation_error();
5775
6789
  var BATCH_MAX_PART_SIZE = 1e8;
@@ -5940,11 +6954,13 @@ function sha256Base64(data) {
5940
6954
  }
5941
6955
 
5942
6956
  // src/crypto/index.ts
6957
+ init_cjs_shims();
5943
6958
  init_certificate_fetcher();
5944
6959
  init_cryptography_service();
5945
6960
  init_signature_service();
5946
6961
 
5947
6962
  // src/crypto/certificate-service.ts
6963
+ init_cjs_shims();
5948
6964
  var crypto4 = __toESM(require("crypto"), 1);
5949
6965
  var x5092 = __toESM(require("@peculiar/x509"), 1);
5950
6966
  var CertificateService = class {
@@ -6030,9 +7046,11 @@ init_pkcs12_loader();
6030
7046
  init_auth_xml_builder();
6031
7047
 
6032
7048
  // src/qr/index.ts
7049
+ init_cjs_shims();
6033
7050
  init_verification_link_service();
6034
7051
 
6035
7052
  // src/qr/qrcode-service.ts
7053
+ init_cjs_shims();
6036
7054
  var QRCode = __toESM(require("qrcode"), 1);
6037
7055
  var QrCodeService = class _QrCodeService {
6038
7056
  static async generateQrCode(url, options) {
@@ -6092,54 +7110,12 @@ function escapeXml2(str) {
6092
7110
  }
6093
7111
 
6094
7112
  // src/utils/index.ts
7113
+ init_cjs_shims();
6095
7114
  init_zip();
6096
-
6097
- // src/utils/jwt.ts
6098
- function decodeJwtPayload(token) {
6099
- const parts = token.split(".");
6100
- if (parts.length !== 3) return null;
6101
- try {
6102
- const payload = parts[1];
6103
- const json = Buffer.from(payload, "base64url").toString("utf-8");
6104
- return JSON.parse(json);
6105
- } catch {
6106
- return null;
6107
- }
6108
- }
6109
- function tryParseJson(value) {
6110
- if (typeof value !== "string") return void 0;
6111
- try {
6112
- return JSON.parse(value);
6113
- } catch {
6114
- return void 0;
6115
- }
6116
- }
6117
- function tryParseJsonArray(value) {
6118
- if (typeof value !== "string") return void 0;
6119
- try {
6120
- const parsed = JSON.parse(value);
6121
- return Array.isArray(parsed) && parsed.every((item) => typeof item === "string") ? parsed : void 0;
6122
- } catch {
6123
- return void 0;
6124
- }
6125
- }
6126
- function parseKSeFTokenContext(token) {
6127
- const raw = decodeJwtPayload(token);
6128
- if (!raw) return null;
6129
- return {
6130
- type: typeof raw["typ"] === "string" ? raw["typ"] : void 0,
6131
- contextIdentifierType: typeof raw["cit"] === "string" ? raw["cit"] : void 0,
6132
- contextIdentifierValue: typeof raw["civ"] === "string" ? raw["civ"] : void 0,
6133
- authMethod: typeof raw["aum"] === "string" ? raw["aum"] : void 0,
6134
- permissions: tryParseJsonArray(raw["per"]),
6135
- subjectDetails: tryParseJson(raw["sud"]),
6136
- authorSubjectIdentifier: tryParseJson(raw["asi"]),
6137
- issuedAt: typeof raw["iat"] === "number" ? raw["iat"] : void 0,
6138
- expiresAt: typeof raw["exp"] === "number" ? raw["exp"] : void 0
6139
- };
6140
- }
7115
+ init_jwt();
6141
7116
 
6142
7117
  // src/utils/hash.ts
7118
+ init_cjs_shims();
6143
7119
  var import_node_crypto2 = __toESM(require("crypto"), 1);
6144
7120
  function sha256Base642(data) {
6145
7121
  return import_node_crypto2.default.createHash("sha256").update(data).digest("base64");
@@ -6151,7 +7127,11 @@ function verifyHash(data, expectedHash) {
6151
7127
  // src/utils/index.ts
6152
7128
  init_concurrency();
6153
7129
 
7130
+ // src/workflows/index.ts
7131
+ init_cjs_shims();
7132
+
6154
7133
  // src/workflows/polling.ts
7134
+ init_cjs_shims();
6155
7135
  async function pollUntil(action, condition, options) {
6156
7136
  const intervalMs = options?.intervalMs ?? 2e3;
6157
7137
  const maxAttempts = options?.maxAttempts ?? 60;
@@ -6169,13 +7149,18 @@ async function pollUntil(action, condition, options) {
6169
7149
  }
6170
7150
 
6171
7151
  // src/workflows/online-session-workflow.ts
7152
+ init_cjs_shims();
6172
7153
  init_ksef_session_expired_error();
6173
7154
  init_auth_manager();
6174
7155
  init_online_session();
6175
7156
  init_session_status();
6176
7157
  init_document_structures();
6177
7158
 
7159
+ // src/xml/index.ts
7160
+ init_cjs_shims();
7161
+
6178
7162
  // src/xml/upo-parser.ts
7163
+ init_cjs_shims();
6179
7164
  var import_fast_xml_parser = require("fast-xml-parser");
6180
7165
  init_ksef_validation_error();
6181
7166
  function isRecord(value) {
@@ -6294,6 +7279,7 @@ function parseUpoXml(xml) {
6294
7279
  }
6295
7280
 
6296
7281
  // src/xml/invoice-field-extractor.ts
7282
+ init_cjs_shims();
6297
7283
  var import_fast_xml_parser2 = require("fast-xml-parser");
6298
7284
  var invoiceParser = new import_fast_xml_parser2.XMLParser({
6299
7285
  ignoreAttributes: false,
@@ -6333,6 +7319,529 @@ function nonEmptyString(value) {
6333
7319
  return typeof value === "string" && value.length > 0 ? value : void 0;
6334
7320
  }
6335
7321
 
7322
+ // src/xml/xml-engine.ts
7323
+ init_cjs_shims();
7324
+ var import_fast_xml_parser3 = require("fast-xml-parser");
7325
+ var XML_DECLARATION = '<?xml version="1.0" encoding="UTF-8"?>\n';
7326
+ var parser = new import_fast_xml_parser3.XMLParser({
7327
+ ignoreAttributes: false,
7328
+ preserveOrder: true,
7329
+ attributeNamePrefix: "@_",
7330
+ textNodeName: "#text",
7331
+ allowBooleanAttributes: true,
7332
+ // Preserve leading zeros and keep everything as strings — KSeF fields like
7333
+ // KRS (`\d{10}`) and NIP (`\d{10}`) would otherwise be lossy through parse.
7334
+ parseTagValue: false,
7335
+ parseAttributeValue: false,
7336
+ trimValues: false
7337
+ });
7338
+ var builder = new import_fast_xml_parser3.XMLBuilder({
7339
+ ignoreAttributes: false,
7340
+ preserveOrder: true,
7341
+ attributeNamePrefix: "@_",
7342
+ textNodeName: "#text",
7343
+ format: false,
7344
+ suppressBooleanAttributes: false,
7345
+ suppressEmptyNode: false,
7346
+ processEntities: true
7347
+ });
7348
+ function createObjectBuilder(pretty = false) {
7349
+ return new import_fast_xml_parser3.XMLBuilder({
7350
+ ignoreAttributes: false,
7351
+ preserveOrder: false,
7352
+ attributeNamePrefix: "@_",
7353
+ textNodeName: "#text",
7354
+ format: pretty,
7355
+ suppressBooleanAttributes: false,
7356
+ suppressEmptyNode: false,
7357
+ processEntities: true
7358
+ });
7359
+ }
7360
+ function prependDeclaration(xml) {
7361
+ return xml.startsWith("<?xml") ? xml : `${XML_DECLARATION}${xml}`;
7362
+ }
7363
+ function parseXml(xml) {
7364
+ return parser.parse(xml);
7365
+ }
7366
+ function buildXml(document2) {
7367
+ return prependDeclaration(builder.build(document2));
7368
+ }
7369
+ function buildXmlFromObject(document2, options) {
7370
+ return prependDeclaration(createObjectBuilder(options?.pretty).build(document2));
7371
+ }
7372
+ function stripBom(input) {
7373
+ return input.charCodeAt(0) === 65279 ? input.slice(1) : input;
7374
+ }
7375
+
7376
+ // src/xml/order-map.ts
7377
+ init_cjs_shims();
7378
+ var ORDER_MAP = {
7379
+ Faktura: ["Naglowek", "Podmiot1", "Podmiot2", "Podmiot3", "Fa", "Stopka"],
7380
+ Naglowek: ["KodFormularza", "WariantFormularza", "DataWytworzeniaFa", "SystemInfo"],
7381
+ Podmiot1: [
7382
+ "PrefiksPodatnika",
7383
+ "NrEORI",
7384
+ "DaneIdentyfikacyjne",
7385
+ "Adres",
7386
+ "AdresKoresp",
7387
+ "DaneKontaktowe",
7388
+ "StatusInfoPodatnika"
7389
+ ],
7390
+ Podmiot2: [
7391
+ "NrEORI",
7392
+ "DaneIdentyfikacyjne",
7393
+ "Adres",
7394
+ "AdresKoresp",
7395
+ "DaneKontaktowe",
7396
+ "NrKlienta",
7397
+ "IDNabywcy",
7398
+ "JST",
7399
+ "GV"
7400
+ ],
7401
+ Podmiot3: [
7402
+ "IDNabywcy",
7403
+ "NrEORI",
7404
+ "DaneIdentyfikacyjne",
7405
+ "Adres",
7406
+ "AdresKoresp",
7407
+ "DaneKontaktowe",
7408
+ "Rola",
7409
+ "Udzial"
7410
+ ],
7411
+ DaneIdentyfikacyjne: [
7412
+ "NIP",
7413
+ "IDWew",
7414
+ "KodUE",
7415
+ "NrVatUE",
7416
+ "KodKraju",
7417
+ "NrID",
7418
+ "BrakID",
7419
+ "Nazwa",
7420
+ "Identyfikator",
7421
+ "KRS"
7422
+ ],
7423
+ Adres: ["KodKraju", "AdresL1", "AdresL2", "AdresL3"],
7424
+ DaneKontaktowe: ["Email", "Telefon"],
7425
+ Fa: [
7426
+ "KodWaluty",
7427
+ "P_1",
7428
+ "P_1M",
7429
+ "P_2",
7430
+ "WZ",
7431
+ "P_6",
7432
+ "OkresFa",
7433
+ // Multi-rate interleave per VAT group — DO NOT flatten into P_13_* block then P_14_* block.
7434
+ // See smekcio TS d1ec8fe and the "multi-rate interleave" regression test.
7435
+ "P_13_1",
7436
+ "P_14_1",
7437
+ "P_14_1W",
7438
+ "P_13_2",
7439
+ "P_14_2",
7440
+ "P_14_2W",
7441
+ "P_13_3",
7442
+ "P_14_3",
7443
+ "P_14_3W",
7444
+ "P_13_4",
7445
+ "P_14_4",
7446
+ "P_14_4W",
7447
+ "P_13_5",
7448
+ "P_14_5",
7449
+ "P_13_6_1",
7450
+ "P_13_6_2",
7451
+ "P_13_6_3",
7452
+ "P_13_7",
7453
+ "P_13_8",
7454
+ "P_13_9",
7455
+ "P_13_10",
7456
+ "P_13_11",
7457
+ "P_15",
7458
+ "KursWalutyZ",
7459
+ "Adnotacje",
7460
+ "RodzajFaktury",
7461
+ "PrzyczynaKorekty",
7462
+ "TypKorekty",
7463
+ "DaneFaKorygowanej",
7464
+ "OkresFaKorygowanej",
7465
+ "NrFaKorygowany",
7466
+ "Podmiot1K",
7467
+ "Podmiot2K",
7468
+ "Podmiot3K",
7469
+ "ZaliczkaCzesciowa",
7470
+ "FP",
7471
+ "TP",
7472
+ "DodatkowyOpis",
7473
+ "FakturaZaliczkowa",
7474
+ "ZwrotAkcyzy",
7475
+ "FaWiersz",
7476
+ "FaWiersze",
7477
+ "Rozliczenie",
7478
+ "Platnosc"
7479
+ ],
7480
+ Adnotacje: ["P_16", "P_17", "P_18", "P_18A", "Zwolnienie", "NoweSrodkiTransportu", "P_23", "PMarzy"],
7481
+ OkresFa: ["P_6_Od", "P_6_Do"],
7482
+ FaWiersz: [
7483
+ "NrWierszaFa",
7484
+ "UU_ID",
7485
+ "P_6A",
7486
+ "P_7",
7487
+ "Indeks",
7488
+ "GTIN",
7489
+ "PKWiU",
7490
+ "CN",
7491
+ "PKOB",
7492
+ "P_8A",
7493
+ "P_8B",
7494
+ "P_9A",
7495
+ "P_9B",
7496
+ "P_10",
7497
+ "P_11",
7498
+ "P_11A",
7499
+ "P_11Vat",
7500
+ "P_12",
7501
+ "P_12_XII",
7502
+ "P_12_Zal_15",
7503
+ "KwotaAkcyzy",
7504
+ "GTU",
7505
+ "Procedura",
7506
+ "KursWaluty",
7507
+ "StanPrzed"
7508
+ ]
7509
+ };
7510
+ function comparePKey(a, b) {
7511
+ const normalize = (value) => value.replace(/^P_/, "").split("_").map((part) => Number.isNaN(Number(part)) ? part : Number(part));
7512
+ const aParts = normalize(a);
7513
+ const bParts = normalize(b);
7514
+ const max = Math.max(aParts.length, bParts.length);
7515
+ for (let i = 0; i < max; i += 1) {
7516
+ const left = aParts[i];
7517
+ const right = bParts[i];
7518
+ if (left === void 0) return -1;
7519
+ if (right === void 0) return 1;
7520
+ if (typeof left === "number" && typeof right === "number") {
7521
+ if (left !== right) return left - right;
7522
+ continue;
7523
+ }
7524
+ const leftStr = String(left);
7525
+ const rightStr = String(right);
7526
+ if (leftStr !== rightStr) return leftStr < rightStr ? -1 : 1;
7527
+ }
7528
+ return 0;
7529
+ }
7530
+ function isObject(value) {
7531
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
7532
+ }
7533
+ function normalizeValueForKey(key, value) {
7534
+ if (Array.isArray(value)) {
7535
+ return value.map(
7536
+ (item) => isObject(item) ? orderXmlObject(item, key) : normalizeValue(item)
7537
+ );
7538
+ }
7539
+ if (isObject(value)) return orderXmlObject(value, key);
7540
+ return value;
7541
+ }
7542
+ function normalizeValue(value) {
7543
+ if (Array.isArray(value)) return value.map((item) => normalizeValue(item));
7544
+ if (isObject(value)) return orderXmlObject(value);
7545
+ return value;
7546
+ }
7547
+ function orderXmlObject(value, contextKey) {
7548
+ const order = contextKey ? ORDER_MAP[contextKey] : void 0;
7549
+ const keys = Object.keys(value);
7550
+ const used = /* @__PURE__ */ new Set();
7551
+ const ordered = {};
7552
+ if (order) {
7553
+ for (const key of order) {
7554
+ if (Object.prototype.hasOwnProperty.call(value, key)) {
7555
+ const item = value[key];
7556
+ if (item !== void 0) ordered[key] = normalizeValueForKey(key, item);
7557
+ used.add(key);
7558
+ }
7559
+ }
7560
+ }
7561
+ const pKeys = keys.filter((key) => !used.has(key) && key.startsWith("P_")).sort(comparePKey);
7562
+ for (const key of pKeys) {
7563
+ const item = value[key];
7564
+ if (item !== void 0) ordered[key] = normalizeValueForKey(key, item);
7565
+ used.add(key);
7566
+ }
7567
+ for (const key of keys) {
7568
+ if (used.has(key)) continue;
7569
+ const item = value[key];
7570
+ if (item !== void 0) ordered[key] = normalizeValueForKey(key, item);
7571
+ }
7572
+ return ordered;
7573
+ }
7574
+
7575
+ // src/xml/faktura-builder.ts
7576
+ init_cjs_shims();
7577
+ var FAKTURA_NAMESPACE = {
7578
+ FA2: "http://crd.gov.pl/wzor/2023/06/29/12648/",
7579
+ FA3: "http://crd.gov.pl/wzor/2025/06/25/13775/"
7580
+ };
7581
+ var ETD_NAMESPACE = {
7582
+ FA2: "http://crd.gov.pl/xml/schematy/2020/10/08/eDokumenty",
7583
+ FA3: "http://crd.gov.pl/xml/schematy/dziedzinowe/mf/2022/01/05/eD/DefinicjeTypy/"
7584
+ };
7585
+ function toKodFormularza(formCode) {
7586
+ return {
7587
+ "@_kodSystemowy": formCode.systemCode,
7588
+ "@_wersjaSchemy": formCode.schemaVersion,
7589
+ "#text": formCode.value
7590
+ };
7591
+ }
7592
+ function isFormCodeShape(value) {
7593
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
7594
+ const candidate = value;
7595
+ return typeof candidate.systemCode === "string" && typeof candidate.schemaVersion === "string" && typeof candidate.value === "string";
7596
+ }
7597
+ function isObject2(value) {
7598
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
7599
+ }
7600
+ function normalizeTopLevelChild(key, value) {
7601
+ if (key === "Naglowek" && isObject2(value)) {
7602
+ return normalizeNaglowek(value);
7603
+ }
7604
+ if (Array.isArray(value)) {
7605
+ return value.map((item) => isObject2(item) ? orderXmlObject(item, key) : item);
7606
+ }
7607
+ if (isObject2(value)) return orderXmlObject(value, key);
7608
+ return value;
7609
+ }
7610
+ function normalizeNaglowek(value) {
7611
+ const result = {};
7612
+ for (const [key, item] of Object.entries(value)) {
7613
+ if (item === void 0) continue;
7614
+ if (key === "KodFormularza" && isFormCodeShape(item)) {
7615
+ result[key] = toKodFormularza(item);
7616
+ continue;
7617
+ }
7618
+ if (Array.isArray(item)) {
7619
+ result[key] = item.map(
7620
+ (entry) => isObject2(entry) ? orderXmlObject(entry, key) : entry
7621
+ );
7622
+ continue;
7623
+ }
7624
+ if (isObject2(item)) {
7625
+ result[key] = orderXmlObject(item, key);
7626
+ continue;
7627
+ }
7628
+ result[key] = item;
7629
+ }
7630
+ return result;
7631
+ }
7632
+ function normalizeTopLevel(input) {
7633
+ const result = {};
7634
+ for (const [key, value] of Object.entries(input)) {
7635
+ if (value === void 0) continue;
7636
+ result[key] = normalizeTopLevelChild(key, value);
7637
+ }
7638
+ return result;
7639
+ }
7640
+ function buildFakturaXml(faktura, options = {}) {
7641
+ const schema = options.schema ?? "FA3";
7642
+ const fakturaNamespace = options.fakturaNamespace ?? FAKTURA_NAMESPACE[schema];
7643
+ const etdNamespace = options.etdNamespace ?? ETD_NAMESPACE[schema];
7644
+ const normalized = normalizeTopLevel(faktura);
7645
+ const ordered = orderXmlObject(normalized, "Faktura");
7646
+ const document2 = {
7647
+ Faktura: {
7648
+ ...ordered,
7649
+ "@_xmlns": fakturaNamespace,
7650
+ "@_xmlns:etd": etdNamespace
7651
+ }
7652
+ };
7653
+ return buildXmlFromObject(document2, { pretty: options.pretty });
7654
+ }
7655
+ function isFakturaInput(input) {
7656
+ if (!isObject2(input)) return false;
7657
+ const candidate = input;
7658
+ if (!Object.prototype.hasOwnProperty.call(candidate, "Naglowek")) return false;
7659
+ if (!Object.prototype.hasOwnProperty.call(candidate, "Fa")) return false;
7660
+ return isObject2(candidate.Naglowek) && isObject2(candidate.Fa);
7661
+ }
7662
+
7663
+ // src/xml/pef-builder.ts
7664
+ init_cjs_shims();
7665
+ init_ksef_validation_error();
7666
+ var PEF_NAMESPACE = {
7667
+ PEF: "urn:oasis:names:specification:ubl:schema:xsd:Invoice-2",
7668
+ PEF_KOR: "urn:oasis:names:specification:ubl:schema:xsd:CreditNote-2"
7669
+ };
7670
+ var UBL_EXT_NS = "urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2";
7671
+ var UBL_CBC_NS = "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2";
7672
+ var UBL_CAC_NS = "urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2";
7673
+ var UBL_CBC_PL_NS = "urn:pl:extended:CommonBasicComponents-2";
7674
+ var UBL_CAC_PL_NS = "urn:pl:extended:CommonAggregateComponents-2";
7675
+ function isPefUblDocumentInput(input) {
7676
+ if (typeof input !== "object" || input === null || Array.isArray(input)) return false;
7677
+ const obj = input;
7678
+ const invoice = obj.Invoice;
7679
+ const creditNote = obj.CreditNote;
7680
+ const hasInvoice = typeof invoice === "object" && invoice !== null && !Array.isArray(invoice);
7681
+ const hasCreditNote = typeof creditNote === "object" && creditNote !== null && !Array.isArray(creditNote);
7682
+ return hasInvoice !== hasCreditNote;
7683
+ }
7684
+ function inferSchema(input) {
7685
+ return "Invoice" in input ? "PEF" : "PEF_KOR";
7686
+ }
7687
+ function isNonArrayObject(value) {
7688
+ return typeof value === "object" && value !== null && !Array.isArray(value);
7689
+ }
7690
+ function assertPefShape(input) {
7691
+ if (!isNonArrayObject(input)) {
7692
+ throw new KSeFValidationError("PEF input must be a non-array object.");
7693
+ }
7694
+ const hasInvoiceKey = "Invoice" in input;
7695
+ const hasCreditNoteKey = "CreditNote" in input;
7696
+ if (hasInvoiceKey && hasCreditNoteKey) {
7697
+ throw new KSeFValidationError(
7698
+ "PEF input must contain exactly one of `Invoice` or `CreditNote`, not both."
7699
+ );
7700
+ }
7701
+ if (!hasInvoiceKey && !hasCreditNoteKey) {
7702
+ throw new KSeFValidationError(
7703
+ "PEF input must contain either an `Invoice` or a `CreditNote` root element."
7704
+ );
7705
+ }
7706
+ const rootKey = hasInvoiceKey ? "Invoice" : "CreditNote";
7707
+ if (!isNonArrayObject(input[rootKey])) {
7708
+ throw new KSeFValidationError(
7709
+ `PEF \`${rootKey}\` value must be a non-array object.`
7710
+ );
7711
+ }
7712
+ }
7713
+ function buildPefXml(input, options = {}) {
7714
+ assertPefShape(input);
7715
+ const inferred = inferSchema(input);
7716
+ const schema = options.schema ?? input.schema ?? inferred;
7717
+ if (schema !== inferred) {
7718
+ throw new KSeFValidationError(
7719
+ `PEF schema mismatch: expected ${inferred} based on root element, got ${schema}.`
7720
+ );
7721
+ }
7722
+ const commonNamespaces = {
7723
+ "@_xmlns:ext": UBL_EXT_NS,
7724
+ "@_xmlns:cbc": UBL_CBC_NS,
7725
+ "@_xmlns:cac": UBL_CAC_NS,
7726
+ "@_xmlns:cbc-pl": UBL_CBC_PL_NS,
7727
+ "@_xmlns:cac-pl": UBL_CAC_PL_NS
7728
+ };
7729
+ const document2 = "Invoice" in input ? {
7730
+ Invoice: {
7731
+ ...input.Invoice,
7732
+ "@_xmlns": PEF_NAMESPACE.PEF,
7733
+ ...commonNamespaces
7734
+ }
7735
+ } : {
7736
+ CreditNote: {
7737
+ ...input.CreditNote,
7738
+ "@_xmlns": PEF_NAMESPACE.PEF_KOR,
7739
+ ...commonNamespaces
7740
+ }
7741
+ };
7742
+ return buildXmlFromObject(document2, { pretty: options.pretty });
7743
+ }
7744
+
7745
+ // src/xml/invoice-serializer.ts
7746
+ init_cjs_shims();
7747
+ init_ksef_validation_error();
7748
+ var FAKTURA_SCHEMAS = /* @__PURE__ */ new Set(["FA2", "FA3"]);
7749
+ var PEF_SCHEMAS = /* @__PURE__ */ new Set(["PEF", "PEF_KOR"]);
7750
+ function isNonArrayObject2(value) {
7751
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
7752
+ }
7753
+ function classifyUnknownObject(input) {
7754
+ const looksLikeFaktura = "Naglowek" in input || "Fa" in input || "Podmiot1" in input || "Podmiot2" in input;
7755
+ const hasInvoice = "Invoice" in input;
7756
+ const hasCreditNote = "CreditNote" in input;
7757
+ if (hasInvoice && hasCreditNote) {
7758
+ return new KSeFValidationError(
7759
+ "Input must contain exactly one of `Invoice` or `CreditNote`, not both."
7760
+ );
7761
+ }
7762
+ if (hasInvoice !== hasCreditNote) {
7763
+ const rootKey = hasInvoice ? "Invoice" : "CreditNote";
7764
+ if (!isNonArrayObject2(input[rootKey])) {
7765
+ return KSeFValidationError.fromField(
7766
+ rootKey,
7767
+ `PEF \`${rootKey}\` value must be a non-array object.`
7768
+ );
7769
+ }
7770
+ }
7771
+ if (looksLikeFaktura) {
7772
+ const missing = [];
7773
+ if (!("Naglowek" in input)) missing.push("Naglowek");
7774
+ if (!("Fa" in input)) missing.push("Fa");
7775
+ if (missing.length > 0) {
7776
+ return KSeFValidationError.fromField(
7777
+ missing[0],
7778
+ `Faktura input is missing required top-level key(s): ${missing.join(", ")}.`
7779
+ );
7780
+ }
7781
+ for (const key of ["Naglowek", "Fa"]) {
7782
+ if (!isNonArrayObject2(input[key])) {
7783
+ return KSeFValidationError.fromField(
7784
+ key,
7785
+ `Faktura \`${key}\` value must be a non-null, non-array object.`
7786
+ );
7787
+ }
7788
+ }
7789
+ return new KSeFValidationError(
7790
+ "Faktura-like input failed shape validation: `Naglowek` and `Fa` must be own enumerable properties on the input object."
7791
+ );
7792
+ }
7793
+ return new KSeFValidationError(
7794
+ "Unsupported invoice input shape: expected `FakturaInput` (with `Naglowek` + `Fa`) or `PefUblDocumentInput` (with `Invoice` or `CreditNote`)."
7795
+ );
7796
+ }
7797
+ function serializeInvoiceXml(input, options) {
7798
+ if (Buffer.isBuffer(input)) return input;
7799
+ if (typeof input === "string") {
7800
+ return Buffer.from(stripBom(input), "utf8");
7801
+ }
7802
+ if (Array.isArray(input)) {
7803
+ return Buffer.from(stripBom(buildXml(input)), "utf8");
7804
+ }
7805
+ if (input && typeof input === "object") {
7806
+ const schema = options?.schema;
7807
+ if (isPefUblDocumentInput(input)) {
7808
+ if (schema && !PEF_SCHEMAS.has(schema)) {
7809
+ throw new KSeFValidationError(
7810
+ `schema option ${schema} is not compatible with a PEF / PEF_KOR input.`
7811
+ );
7812
+ }
7813
+ const pefSchema = schema === "PEF" || schema === "PEF_KOR" ? schema : void 0;
7814
+ const xml = buildPefXml(input, {
7815
+ schema: pefSchema,
7816
+ pretty: options?.pretty
7817
+ });
7818
+ return Buffer.from(stripBom(xml), "utf8");
7819
+ }
7820
+ if (isFakturaInput(input)) {
7821
+ if (schema && !FAKTURA_SCHEMAS.has(schema)) {
7822
+ throw new KSeFValidationError(
7823
+ `schema option ${schema} is not compatible with a Faktura input.`
7824
+ );
7825
+ }
7826
+ const fakturaSchema = schema === "FA2" || schema === "FA3" ? schema : void 0;
7827
+ const xml = buildFakturaXml(input, {
7828
+ schema: fakturaSchema,
7829
+ fakturaNamespace: options?.fakturaNamespace,
7830
+ etdNamespace: options?.etdNamespace,
7831
+ pretty: options?.pretty
7832
+ });
7833
+ return Buffer.from(stripBom(xml), "utf8");
7834
+ }
7835
+ throw classifyUnknownObject(input);
7836
+ }
7837
+ throw new KSeFValidationError(
7838
+ "Unsupported invoice input type: expected Buffer, string, XmlDocument, FakturaInput, or PefUblDocumentInput."
7839
+ );
7840
+ }
7841
+ function buildRawXmlString(document2, options) {
7842
+ return buildXmlFromObject(document2, options);
7843
+ }
7844
+
6336
7845
  // src/workflows/online-session-workflow.ts
6337
7846
  init_invoice_validator();
6338
7847
  init_ksef_validation_error();
@@ -6470,6 +7979,7 @@ async function openSendAndClose(client, invoices, options) {
6470
7979
  }
6471
7980
 
6472
7981
  // src/workflows/batch-session-workflow.ts
7982
+ init_cjs_shims();
6473
7983
  init_document_structures();
6474
7984
  async function uploadBatch(client, zipData, options) {
6475
7985
  if (options?.parallelism !== void 0 && (!Number.isInteger(options.parallelism) || options.parallelism < 1)) {
@@ -6608,6 +8118,7 @@ async function uploadBatchParsed(client, zipData, options) {
6608
8118
  }
6609
8119
 
6610
8120
  // src/workflows/invoice-export-workflow.ts
8121
+ init_cjs_shims();
6611
8122
  init_zip();
6612
8123
  async function doExport(client, filters, options) {
6613
8124
  await client.crypto.init();
@@ -6680,7 +8191,11 @@ async function exportAndDownload(client, filters, options) {
6680
8191
  };
6681
8192
  }
6682
8193
 
8194
+ // src/workflows/incremental-export-workflow.ts
8195
+ init_cjs_shims();
8196
+
6683
8197
  // src/workflows/hwm-coordinator.ts
8198
+ init_cjs_shims();
6684
8199
  function updateContinuationPoint(points, subjectType, pkg) {
6685
8200
  if (pkg.isTruncated && pkg.lastPermanentStorageDate) {
6686
8201
  points[subjectType] = pkg.lastPermanentStorageDate;
@@ -6778,7 +8293,8 @@ function buildDefaultFilters(subjectType, from, to) {
6778
8293
  }
6779
8294
 
6780
8295
  // src/workflows/hwm-storage.ts
6781
- var fs = __toESM(require("fs/promises"), 1);
8296
+ init_cjs_shims();
8297
+ var fs2 = __toESM(require("fs/promises"), 1);
6782
8298
  var InMemoryHwmStore = class {
6783
8299
  points = {};
6784
8300
  async load() {
@@ -6794,7 +8310,7 @@ var FileHwmStore = class {
6794
8310
  }
6795
8311
  async load() {
6796
8312
  try {
6797
- const data = await fs.readFile(this.filePath, "utf-8");
8313
+ const data = await fs2.readFile(this.filePath, "utf-8");
6798
8314
  return JSON.parse(data);
6799
8315
  } catch (err) {
6800
8316
  if (err.code === "ENOENT") {
@@ -6804,11 +8320,12 @@ var FileHwmStore = class {
6804
8320
  }
6805
8321
  }
6806
8322
  async save(points) {
6807
- await fs.writeFile(this.filePath, JSON.stringify(points, null, 2), "utf-8");
8323
+ await fs2.writeFile(this.filePath, JSON.stringify(points, null, 2), "utf-8");
6808
8324
  }
6809
8325
  };
6810
8326
 
6811
8327
  // src/workflows/auth-workflow.ts
8328
+ init_cjs_shims();
6812
8329
  init_auth_xml_builder();
6813
8330
  async function authenticateWithToken(client, options) {
6814
8331
  const challenge = await client.auth.getChallenge();
@@ -6905,10 +8422,12 @@ async function authenticateWithPkcs12(client, options) {
6905
8422
  }
6906
8423
 
6907
8424
  // src/offline/index.ts
8425
+ init_cjs_shims();
6908
8426
  init_deadline();
6909
8427
  init_holidays();
6910
8428
 
6911
8429
  // src/offline/storage.ts
8430
+ init_cjs_shims();
6912
8431
  function matchesFilter(invoice, filter) {
6913
8432
  if (filter.status !== void 0) {
6914
8433
  const statuses = Array.isArray(filter.status) ? filter.status : [filter.status];
@@ -6947,12 +8466,13 @@ var InMemoryOfflineInvoiceStorage = class {
6947
8466
  };
6948
8467
 
6949
8468
  // src/offline/file-storage.ts
6950
- var fs2 = __toESM(require("fs/promises"), 1);
6951
- var path = __toESM(require("path"), 1);
8469
+ init_cjs_shims();
8470
+ var fs3 = __toESM(require("fs/promises"), 1);
8471
+ var path2 = __toESM(require("path"), 1);
6952
8472
  var os = __toESM(require("os"), 1);
6953
8473
  function resolveDir(dir) {
6954
8474
  if (dir === "~" || dir.startsWith("~/")) {
6955
- return path.join(os.homedir(), dir.slice(1));
8475
+ return path2.join(os.homedir(), dir.slice(1));
6956
8476
  }
6957
8477
  return dir;
6958
8478
  }
@@ -6968,23 +8488,23 @@ var FileOfflineInvoiceStorage = class {
6968
8488
  this.dir = resolveDir(directory ?? "~/.ksef/offline");
6969
8489
  }
6970
8490
  async ensureDir() {
6971
- await fs2.mkdir(this.dir, { recursive: true });
8491
+ await fs3.mkdir(this.dir, { recursive: true });
6972
8492
  }
6973
8493
  filePath(id) {
6974
8494
  validateId(id);
6975
- return path.join(this.dir, `${id}.json`);
8495
+ return path2.join(this.dir, `${id}.json`);
6976
8496
  }
6977
8497
  async save(invoice) {
6978
8498
  await this.ensureDir();
6979
8499
  const file = this.filePath(invoice.id);
6980
8500
  const tmp = `${file}.tmp`;
6981
- await fs2.writeFile(tmp, JSON.stringify(invoice, null, 2));
6982
- await fs2.rename(tmp, file);
8501
+ await fs3.writeFile(tmp, JSON.stringify(invoice, null, 2));
8502
+ await fs3.rename(tmp, file);
6983
8503
  }
6984
8504
  async get(id) {
6985
8505
  const file = this.filePath(id);
6986
8506
  try {
6987
- return JSON.parse(await fs2.readFile(file, "utf-8"));
8507
+ return JSON.parse(await fs3.readFile(file, "utf-8"));
6988
8508
  } catch (err) {
6989
8509
  if (err instanceof Error && "code" in err && err.code === "ENOENT") {
6990
8510
  return null;
@@ -6996,7 +8516,7 @@ var FileOfflineInvoiceStorage = class {
6996
8516
  async list(filter) {
6997
8517
  let files;
6998
8518
  try {
6999
- files = (await fs2.readdir(this.dir)).filter((f) => f.endsWith(".json"));
8519
+ files = (await fs3.readdir(this.dir)).filter((f) => f.endsWith(".json"));
7000
8520
  } catch {
7001
8521
  return [];
7002
8522
  }
@@ -7004,7 +8524,7 @@ var FileOfflineInvoiceStorage = class {
7004
8524
  for (const file of files) {
7005
8525
  try {
7006
8526
  const data = JSON.parse(
7007
- await fs2.readFile(path.join(this.dir, file), "utf-8")
8527
+ await fs3.readFile(path2.join(this.dir, file), "utf-8")
7008
8528
  );
7009
8529
  if (!filter || matchesFilter(data, filter)) {
7010
8530
  results.push(data);
@@ -7030,7 +8550,7 @@ var FileOfflineInvoiceStorage = class {
7030
8550
  async delete(id) {
7031
8551
  const file = this.filePath(id);
7032
8552
  try {
7033
- await fs2.unlink(file);
8553
+ await fs3.unlink(file);
7034
8554
  } catch (e) {
7035
8555
  if (e instanceof Error && "code" in e && e.code !== "ENOENT") throw e;
7036
8556
  }
@@ -7060,12 +8580,17 @@ init_client();
7060
8580
  CertificateFingerprint,
7061
8581
  CertificateName,
7062
8582
  CertificateService,
8583
+ CircuitBreakerPolicy,
7063
8584
  CryptographyService,
7064
8585
  DEFAULT_FORM_CODE,
8586
+ DISCOURAGED_UNICODE_RANGES,
7065
8587
  DefaultAuthManager,
7066
8588
  ENFORCE_XADES_COMPLIANCE,
8589
+ ETD_NAMESPACE,
7067
8590
  EntityPermissionGrantBuilder,
7068
8591
  Environment,
8592
+ FAKTURA_NAMESPACE,
8593
+ FA_XSD_PATHS,
7069
8594
  FORM_CODES,
7070
8595
  FORM_CODE_KEYS,
7071
8596
  FileHwmStore,
@@ -7082,7 +8607,9 @@ init_client();
7082
8607
  KSEF_FEATURE_HEADER,
7083
8608
  KSeFApiError,
7084
8609
  KSeFAuthStatusError,
8610
+ KSeFBadRequestError,
7085
8611
  KSeFBatchTimeoutError,
8612
+ KSeFCircuitOpenError,
7086
8613
  KSeFClient,
7087
8614
  KSeFError,
7088
8615
  KSeFErrorCode,
@@ -7092,6 +8619,7 @@ init_client();
7092
8619
  KSeFSessionExpiredError,
7093
8620
  KSeFUnauthorizedError,
7094
8621
  KSeFValidationError,
8622
+ KSeFXsdValidationError,
7095
8623
  KsefNumber,
7096
8624
  KsefNumberV35,
7097
8625
  KsefNumberV36,
@@ -7099,8 +8627,11 @@ init_client();
7099
8627
  LimitsService,
7100
8628
  Nip,
7101
8629
  NipVatUe,
8630
+ ORDER_MAP,
7102
8631
  OfflineInvoiceWorkflow,
7103
8632
  OnlineSessionService,
8633
+ PEF_NAMESPACE,
8634
+ PEF_XSD_PATHS,
7104
8635
  PERMISSION_DESCRIPTION_MAX_LENGTH,
7105
8636
  PERMISSION_DESCRIPTION_MIN_LENGTH,
7106
8637
  PeppolId,
@@ -7130,17 +8661,25 @@ init_client();
7130
8661
  VatUe,
7131
8662
  VerificationLinkService,
7132
8663
  addBusinessDays,
8664
+ assertNever,
7133
8665
  authenticateWithCertificate,
7134
8666
  authenticateWithExternalSignature,
7135
8667
  authenticateWithPkcs12,
7136
8668
  authenticateWithToken,
7137
8669
  batchValidationDetails,
8670
+ buildFakturaXml,
8671
+ buildPefXml,
8672
+ buildRawXmlString,
7138
8673
  buildUnsignedAuthTokenRequestXml,
8674
+ buildXml,
8675
+ buildXmlFromObject,
7139
8676
  calculateBackoff,
7140
8677
  calculateOfflineDeadline,
8678
+ comparePKey,
7141
8679
  createZip,
7142
8680
  decodeJwtPayload,
7143
8681
  deduplicateByKsefNumber,
8682
+ defaultCircuitBreakerPolicy,
7144
8683
  defaultPresignedUrlPolicy,
7145
8684
  defaultRateLimitPolicy,
7146
8685
  defaultRetryPolicy,
@@ -7156,6 +8695,9 @@ init_client();
7156
8695
  getTimeUntilDeadline,
7157
8696
  incrementalExportAndDownload,
7158
8697
  isExpired,
8698
+ isFakturaInput,
8699
+ isFormCodeShape,
8700
+ isPefUblDocumentInput,
7159
8701
  isPolishHoliday,
7160
8702
  isRetryableError,
7161
8703
  isRetryableStatus,
@@ -7174,19 +8716,26 @@ init_client();
7174
8716
  isValidReferenceNumber,
7175
8717
  isValidSha256Base64,
7176
8718
  isValidVatUe,
8719
+ libxmljsAvailable,
7177
8720
  nextBusinessDay,
7178
8721
  openOnlineSession,
7179
8722
  openSendAndClose,
8723
+ orderXmlObject,
7180
8724
  parseFormCode,
7181
8725
  parseKSeFTokenContext,
7182
8726
  parseRetryAfter,
7183
8727
  parseUpoXml,
8728
+ parseXml,
7184
8729
  pollUntil,
7185
8730
  resolveOptions,
8731
+ resolveXsdFor,
7186
8732
  resumeOnlineSession,
7187
8733
  runWithConcurrency,
8734
+ serializeInvoiceXml,
7188
8735
  sha256Base64,
7189
8736
  sleep,
8737
+ stripBom,
8738
+ toKodFormularza,
7190
8739
  unzip,
7191
8740
  updateContinuationPoint,
7192
8741
  uploadBatch,
@@ -7194,8 +8743,10 @@ init_client();
7194
8743
  uploadBatchStream,
7195
8744
  uploadBatchStreamParsed,
7196
8745
  validate,
8746
+ validateAgainstXsd,
7197
8747
  validateBatch,
7198
8748
  validateBusinessRules,
8749
+ validateCharValidity,
7199
8750
  validateFormCodeForSession,
7200
8751
  validatePresignedUrl,
7201
8752
  validateSchema,