ksef-client-ts 0.7.0 → 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 +2 -1
  2. package/dist/cli.js +1677 -303
  3. package/dist/cli.js.map +1 -1
  4. package/dist/index.cjs +713 -75
  5. package/dist/index.cjs.map +1 -1
  6. package/dist/index.d.cts +70 -2
  7. package/dist/index.d.ts +70 -2
  8. package/dist/index.js +693 -65
  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 +12 -2
package/dist/index.js CHANGED
@@ -8,11 +8,21 @@ var __export = (target, all) => {
8
8
  __defProp(target, name, { get: all[name], enumerable: true });
9
9
  };
10
10
 
11
+ // node_modules/tsup/assets/esm_shims.js
12
+ import path from "path";
13
+ import { fileURLToPath } from "url";
14
+ var init_esm_shims = __esm({
15
+ "node_modules/tsup/assets/esm_shims.js"() {
16
+ "use strict";
17
+ }
18
+ });
19
+
11
20
  // src/config/environments.ts
12
21
  var Environment;
13
22
  var init_environments = __esm({
14
23
  "src/config/environments.ts"() {
15
24
  "use strict";
25
+ init_esm_shims();
16
26
  Environment = {
17
27
  TEST: {
18
28
  apiUrl: "https://api-test.ksef.mf.gov.pl",
@@ -51,6 +61,7 @@ var DEFAULT_API_VERSION, DEFAULT_TIMEOUT;
51
61
  var init_options = __esm({
52
62
  "src/config/options.ts"() {
53
63
  "use strict";
64
+ init_esm_shims();
54
65
  init_environments();
55
66
  DEFAULT_API_VERSION = "v2";
56
67
  DEFAULT_TIMEOUT = 3e4;
@@ -61,6 +72,7 @@ var init_options = __esm({
61
72
  var init_config = __esm({
62
73
  "src/config/index.ts"() {
63
74
  "use strict";
75
+ init_esm_shims();
64
76
  init_environments();
65
77
  init_options();
66
78
  }
@@ -71,6 +83,7 @@ var KSeFError;
71
83
  var init_ksef_error = __esm({
72
84
  "src/errors/ksef-error.ts"() {
73
85
  "use strict";
86
+ init_esm_shims();
74
87
  KSeFError = class extends Error {
75
88
  constructor(message) {
76
89
  super(message);
@@ -85,6 +98,7 @@ var KSeFApiError;
85
98
  var init_ksef_api_error = __esm({
86
99
  "src/errors/ksef-api-error.ts"() {
87
100
  "use strict";
101
+ init_esm_shims();
88
102
  init_ksef_error();
89
103
  KSeFApiError = class _KSeFApiError extends KSeFError {
90
104
  statusCode;
@@ -112,6 +126,7 @@ var KSeFRateLimitError;
112
126
  var init_ksef_rate_limit_error = __esm({
113
127
  "src/errors/ksef-rate-limit-error.ts"() {
114
128
  "use strict";
129
+ init_esm_shims();
115
130
  init_ksef_api_error();
116
131
  KSeFRateLimitError = class _KSeFRateLimitError extends KSeFApiError {
117
132
  statusCode = 429;
@@ -162,6 +177,7 @@ var KSeFUnauthorizedError;
162
177
  var init_ksef_unauthorized_error = __esm({
163
178
  "src/errors/ksef-unauthorized-error.ts"() {
164
179
  "use strict";
180
+ init_esm_shims();
165
181
  init_ksef_api_error();
166
182
  KSeFUnauthorizedError = class extends KSeFApiError {
167
183
  statusCode = 401;
@@ -194,6 +210,7 @@ var KSeFForbiddenError;
194
210
  var init_ksef_forbidden_error = __esm({
195
211
  "src/errors/ksef-forbidden-error.ts"() {
196
212
  "use strict";
213
+ init_esm_shims();
197
214
  init_ksef_api_error();
198
215
  KSeFForbiddenError = class extends KSeFApiError {
199
216
  statusCode = 403;
@@ -232,6 +249,7 @@ var KSeFGoneError;
232
249
  var init_ksef_gone_error = __esm({
233
250
  "src/errors/ksef-gone-error.ts"() {
234
251
  "use strict";
252
+ init_esm_shims();
235
253
  init_ksef_api_error();
236
254
  KSeFGoneError = class extends KSeFApiError {
237
255
  statusCode = 410;
@@ -264,6 +282,7 @@ var KSeFBadRequestError;
264
282
  var init_ksef_bad_request_error = __esm({
265
283
  "src/errors/ksef-bad-request-error.ts"() {
266
284
  "use strict";
285
+ init_esm_shims();
267
286
  init_ksef_api_error();
268
287
  KSeFBadRequestError = class extends KSeFApiError {
269
288
  statusCode = 400;
@@ -299,6 +318,7 @@ var KSeFAuthStatusError;
299
318
  var init_ksef_auth_status_error = __esm({
300
319
  "src/errors/ksef-auth-status-error.ts"() {
301
320
  "use strict";
321
+ init_esm_shims();
302
322
  init_ksef_error();
303
323
  KSeFAuthStatusError = class extends KSeFError {
304
324
  referenceNumber;
@@ -318,6 +338,7 @@ var KSeFSessionExpiredError;
318
338
  var init_ksef_session_expired_error = __esm({
319
339
  "src/errors/ksef-session-expired-error.ts"() {
320
340
  "use strict";
341
+ init_esm_shims();
321
342
  init_ksef_error();
322
343
  KSeFSessionExpiredError = class extends KSeFError {
323
344
  constructor(message = "KSeF session has expired") {
@@ -337,6 +358,7 @@ var KSeFValidationError;
337
358
  var init_ksef_validation_error = __esm({
338
359
  "src/errors/ksef-validation-error.ts"() {
339
360
  "use strict";
361
+ init_esm_shims();
340
362
  init_ksef_error();
341
363
  KSeFValidationError = class _KSeFValidationError extends KSeFError {
342
364
  details;
@@ -364,6 +386,7 @@ var KSeFErrorCode;
364
386
  var init_error_codes = __esm({
365
387
  "src/errors/error-codes.ts"() {
366
388
  "use strict";
389
+ init_esm_shims();
367
390
  KSeFErrorCode = {
368
391
  BatchTimeout: 21208,
369
392
  DuplicateInvoice: 440
@@ -376,6 +399,7 @@ var KSeFBatchTimeoutError;
376
399
  var init_ksef_batch_timeout_error = __esm({
377
400
  "src/errors/ksef-batch-timeout-error.ts"() {
378
401
  "use strict";
402
+ init_esm_shims();
379
403
  init_ksef_api_error();
380
404
  init_error_codes();
381
405
  KSeFBatchTimeoutError = class _KSeFBatchTimeoutError extends KSeFApiError {
@@ -395,6 +419,52 @@ var init_ksef_batch_timeout_error = __esm({
395
419
  }
396
420
  });
397
421
 
422
+ // src/errors/ksef-circuit-open-error.ts
423
+ var KSeFCircuitOpenError;
424
+ var init_ksef_circuit_open_error = __esm({
425
+ "src/errors/ksef-circuit-open-error.ts"() {
426
+ "use strict";
427
+ init_esm_shims();
428
+ init_ksef_error();
429
+ KSeFCircuitOpenError = class extends KSeFError {
430
+ endpoint;
431
+ openedAt;
432
+ retryAfterMs;
433
+ constructor(endpoint, openedAt, retryAfterMs) {
434
+ super(
435
+ `Circuit breaker is open for '${endpoint}'. Retry after ${Math.round(retryAfterMs)}ms.`
436
+ );
437
+ this.name = "KSeFCircuitOpenError";
438
+ this.endpoint = endpoint;
439
+ this.openedAt = openedAt;
440
+ this.retryAfterMs = retryAfterMs;
441
+ }
442
+ };
443
+ }
444
+ });
445
+
446
+ // src/errors/ksef-xsd-validation-error.ts
447
+ var KSeFXsdValidationError;
448
+ var init_ksef_xsd_validation_error = __esm({
449
+ "src/errors/ksef-xsd-validation-error.ts"() {
450
+ "use strict";
451
+ init_esm_shims();
452
+ init_ksef_error();
453
+ KSeFXsdValidationError = class extends KSeFError {
454
+ schemaFile;
455
+ errors;
456
+ constructor(schemaFile, errors) {
457
+ const preview = errors.slice(0, 3).join("; ");
458
+ const extra = errors.length > 3 ? ` (+${errors.length - 3} more)` : "";
459
+ super(`XSD validation failed against ${schemaFile}: ${preview}${extra}`);
460
+ this.name = "KSeFXsdValidationError";
461
+ this.schemaFile = schemaFile;
462
+ this.errors = errors;
463
+ }
464
+ };
465
+ }
466
+ });
467
+
398
468
  // src/errors/assert-never.ts
399
469
  function assertNever(value) {
400
470
  throw new Error(`Unexpected value: ${String(value)}`);
@@ -402,6 +472,7 @@ function assertNever(value) {
402
472
  var init_assert_never = __esm({
403
473
  "src/errors/assert-never.ts"() {
404
474
  "use strict";
475
+ init_esm_shims();
405
476
  }
406
477
  });
407
478
 
@@ -409,6 +480,7 @@ var init_assert_never = __esm({
409
480
  var init_errors = __esm({
410
481
  "src/errors/index.ts"() {
411
482
  "use strict";
483
+ init_esm_shims();
412
484
  init_ksef_error();
413
485
  init_ksef_api_error();
414
486
  init_ksef_rate_limit_error();
@@ -420,6 +492,8 @@ var init_errors = __esm({
420
492
  init_ksef_session_expired_error();
421
493
  init_ksef_validation_error();
422
494
  init_ksef_batch_timeout_error();
495
+ init_ksef_circuit_open_error();
496
+ init_ksef_xsd_validation_error();
423
497
  init_error_codes();
424
498
  init_assert_never();
425
499
  }
@@ -430,6 +504,7 @@ var RouteBuilder;
430
504
  var init_route_builder = __esm({
431
505
  "src/http/route-builder.ts"() {
432
506
  "use strict";
507
+ init_esm_shims();
433
508
  RouteBuilder = class {
434
509
  apiVersion;
435
510
  constructor(apiVersion) {
@@ -448,6 +523,7 @@ var RestRequest;
448
523
  var init_rest_request = __esm({
449
524
  "src/http/rest-request.ts"() {
450
525
  "use strict";
526
+ init_esm_shims();
451
527
  RestRequest = class _RestRequest {
452
528
  method;
453
529
  path;
@@ -456,21 +532,21 @@ var init_rest_request = __esm({
456
532
  _query = [];
457
533
  _presigned = false;
458
534
  _skipAuthRetry = false;
459
- constructor(method, path2) {
535
+ constructor(method, path4) {
460
536
  this.method = method;
461
- this.path = path2;
537
+ this.path = path4;
462
538
  }
463
- static get(path2) {
464
- return new _RestRequest("GET", path2);
539
+ static get(path4) {
540
+ return new _RestRequest("GET", path4);
465
541
  }
466
- static post(path2) {
467
- return new _RestRequest("POST", path2);
542
+ static post(path4) {
543
+ return new _RestRequest("POST", path4);
468
544
  }
469
- static put(path2) {
470
- return new _RestRequest("PUT", path2);
545
+ static put(path4) {
546
+ return new _RestRequest("PUT", path4);
471
547
  }
472
- static delete(path2) {
473
- return new _RestRequest("DELETE", path2);
548
+ static delete(path4) {
549
+ return new _RestRequest("DELETE", path4);
474
550
  }
475
551
  body(data) {
476
552
  this._body = data;
@@ -524,6 +600,7 @@ var defaultTransport;
524
600
  var init_transport = __esm({
525
601
  "src/http/transport.ts"() {
526
602
  "use strict";
603
+ init_esm_shims();
527
604
  defaultTransport = (url, init) => fetch(url, init);
528
605
  }
529
606
  });
@@ -573,6 +650,7 @@ var RETRYABLE_ERROR_CODES;
573
650
  var init_retry_policy = __esm({
574
651
  "src/http/retry-policy.ts"() {
575
652
  "use strict";
653
+ init_esm_shims();
576
654
  RETRYABLE_ERROR_CODES = /* @__PURE__ */ new Set([
577
655
  "ECONNRESET",
578
656
  "ECONNREFUSED",
@@ -663,6 +741,7 @@ var BLOCKED_PARAMS;
663
741
  var init_presigned_url_policy = __esm({
664
742
  "src/http/presigned-url-policy.ts"() {
665
743
  "use strict";
744
+ init_esm_shims();
666
745
  init_ksef_validation_error();
667
746
  BLOCKED_PARAMS = ["redirect", "callback", "return_url", "next"];
668
747
  }
@@ -695,6 +774,7 @@ var RestClient;
695
774
  var init_rest_client = __esm({
696
775
  "src/http/rest-client.ts"() {
697
776
  "use strict";
777
+ init_esm_shims();
698
778
  init_ksef_api_error();
699
779
  init_ksef_rate_limit_error();
700
780
  init_ksef_unauthorized_error();
@@ -713,6 +793,7 @@ var init_rest_client = __esm({
713
793
  transport;
714
794
  retryPolicy;
715
795
  rateLimitPolicy;
796
+ circuitBreakerPolicy;
716
797
  authManager;
717
798
  presignedUrlPolicy;
718
799
  constructor(options, config) {
@@ -721,6 +802,7 @@ var init_rest_client = __esm({
721
802
  this.transport = config?.transport ?? defaultTransport;
722
803
  this.retryPolicy = config?.retryPolicy ?? defaultRetryPolicy();
723
804
  this.rateLimitPolicy = config?.rateLimitPolicy ?? null;
805
+ this.circuitBreakerPolicy = config?.circuitBreakerPolicy ?? null;
724
806
  this.authManager = config?.authManager;
725
807
  this.presignedUrlPolicy = config?.presignedUrlPolicy;
726
808
  }
@@ -745,18 +827,32 @@ var init_rest_client = __esm({
745
827
  if (request.isPresigned() && this.presignedUrlPolicy) {
746
828
  validatePresignedUrl(url, this.presignedUrlPolicy);
747
829
  }
830
+ let ownsProbeSlot = false;
831
+ if (this.circuitBreakerPolicy) {
832
+ const claimed = this.circuitBreakerPolicy.ensureClosed(request.path);
833
+ if (claimed) ownsProbeSlot = true;
834
+ }
748
835
  if (this.rateLimitPolicy) {
749
- await this.rateLimitPolicy.acquire(request.path);
836
+ try {
837
+ await this.rateLimitPolicy.acquire(request.path);
838
+ } catch (error) {
839
+ if (ownsProbeSlot) this.circuitBreakerPolicy?.releaseProbe(request.path);
840
+ throw error;
841
+ }
750
842
  }
751
843
  let lastError;
752
844
  for (let attempt = 0; attempt <= this.retryPolicy.maxRetries; attempt++) {
845
+ if (this.circuitBreakerPolicy) {
846
+ const claimed = this.circuitBreakerPolicy.ensureClosed(request.path, ownsProbeSlot);
847
+ if (claimed) ownsProbeSlot = true;
848
+ }
753
849
  try {
754
- const response = await this.doRequest(request, url);
850
+ let response = await this.doRequest(request, url);
755
851
  if (response.status === 401 && this.authManager && attempt === 0 && !request.isSkipAuthRetry()) {
756
852
  const newToken = await this.authManager.onUnauthorized();
757
853
  if (newToken) {
758
854
  consola.debug("Auth token refreshed, retrying request");
759
- return this.doRequest(request, url, newToken);
855
+ response = await this.doRequest(request, url, newToken);
760
856
  }
761
857
  }
762
858
  if (isRetryableStatus(response.status, this.retryPolicy) && attempt < this.retryPolicy.maxRetries) {
@@ -766,10 +862,17 @@ var init_rest_client = __esm({
766
862
  consola.debug(`Retryable ${response.status}, attempt ${attempt + 1}/${this.retryPolicy.maxRetries}, waiting ${Math.round(delayMs)}ms`);
767
863
  await sleep(delayMs);
768
864
  if (is429 && this.rateLimitPolicy) {
769
- await this.rateLimitPolicy.acquire(request.path);
865
+ try {
866
+ await this.rateLimitPolicy.acquire(request.path);
867
+ } catch (error) {
868
+ this.recordCircuitOutcome(request.path, 429);
869
+ ownsProbeSlot = false;
870
+ throw error;
871
+ }
770
872
  }
771
873
  continue;
772
874
  }
875
+ this.recordCircuitOutcome(request.path, response.status);
773
876
  return response;
774
877
  } catch (error) {
775
878
  lastError = error;
@@ -779,11 +882,22 @@ var init_rest_client = __esm({
779
882
  await sleep(delayMs);
780
883
  continue;
781
884
  }
885
+ if (isRetryableError(error, this.retryPolicy) || ownsProbeSlot) {
886
+ this.circuitBreakerPolicy?.recordFailure(request.path);
887
+ }
782
888
  throw error;
783
889
  }
784
890
  }
785
891
  throw lastError;
786
892
  }
893
+ recordCircuitOutcome(path4, status) {
894
+ if (!this.circuitBreakerPolicy) return;
895
+ if (status >= 500) {
896
+ this.circuitBreakerPolicy.recordFailure(path4);
897
+ return;
898
+ }
899
+ this.circuitBreakerPolicy.recordSuccess(path4);
900
+ }
787
901
  async doRequest(request, url, overrideToken) {
788
902
  const headers = {
789
903
  ...this.options.customHeaders,
@@ -819,9 +933,9 @@ var init_rest_client = __esm({
819
933
  return response;
820
934
  }
821
935
  buildUrl(request) {
822
- const path2 = this.routeBuilder.build(request.path);
936
+ const path4 = this.routeBuilder.build(request.path);
823
937
  const base = this.options.baseUrl;
824
- const url = new URL(`${base}${path2}`);
938
+ const url = new URL(`${base}${path4}`);
825
939
  const query = request.getQuery();
826
940
  for (const [key, value] of query) {
827
941
  url.searchParams.append(key, value);
@@ -905,6 +1019,7 @@ var Routes;
905
1019
  var init_routes = __esm({
906
1020
  "src/http/routes.ts"() {
907
1021
  "use strict";
1022
+ init_esm_shims();
908
1023
  Routes = {
909
1024
  TestData: {
910
1025
  createSubject: "testdata/subject",
@@ -1037,6 +1152,7 @@ var TokenBucket, RateLimitPolicy;
1037
1152
  var init_rate_limit_policy = __esm({
1038
1153
  "src/http/rate-limit-policy.ts"() {
1039
1154
  "use strict";
1155
+ init_esm_shims();
1040
1156
  TokenBucket = class {
1041
1157
  tokens;
1042
1158
  maxTokens;
@@ -1097,11 +1213,151 @@ var init_rate_limit_policy = __esm({
1097
1213
  }
1098
1214
  });
1099
1215
 
1216
+ // src/http/circuit-breaker-policy.ts
1217
+ import { consola as consola2 } from "consola";
1218
+ function defaultCircuitBreakerPolicy() {
1219
+ return new CircuitBreakerPolicy();
1220
+ }
1221
+ var GLOBAL_KEY, CircuitBreakerPolicy;
1222
+ var init_circuit_breaker_policy = __esm({
1223
+ "src/http/circuit-breaker-policy.ts"() {
1224
+ "use strict";
1225
+ init_esm_shims();
1226
+ init_ksef_circuit_open_error();
1227
+ GLOBAL_KEY = "__global__";
1228
+ CircuitBreakerPolicy = class _CircuitBreakerPolicy {
1229
+ failureThreshold;
1230
+ openMs;
1231
+ scope;
1232
+ states = /* @__PURE__ */ new Map();
1233
+ constructor(config = {}) {
1234
+ const failureThreshold = config.failureThreshold ?? 5;
1235
+ const openMs = config.openMs ?? 3e4;
1236
+ if (!Number.isInteger(failureThreshold) || failureThreshold <= 0) {
1237
+ throw new RangeError("CircuitBreakerPolicy: failureThreshold must be a positive integer");
1238
+ }
1239
+ if (!Number.isFinite(openMs) || openMs <= 0) {
1240
+ throw new RangeError("CircuitBreakerPolicy: openMs must be > 0");
1241
+ }
1242
+ const scope = config.scope ?? "global";
1243
+ if (scope !== "global" && scope !== "endpoint") {
1244
+ throw new RangeError(
1245
+ "CircuitBreakerPolicy: scope must be 'global' or 'endpoint'"
1246
+ );
1247
+ }
1248
+ this.failureThreshold = failureThreshold;
1249
+ this.openMs = openMs;
1250
+ this.scope = scope;
1251
+ }
1252
+ // Returns true iff this call just claimed the single probe slot for the
1253
+ // caller. The caller MUST pass `alreadyOwnsProbe=true` on subsequent
1254
+ // re-checks for the same logical request (e.g. a retry loop) so the probe
1255
+ // owner cannot deadlock itself on its own in-flight slot.
1256
+ ensureClosed(endpoint, alreadyOwnsProbe = false) {
1257
+ const key = this.keyFor(endpoint);
1258
+ const state = this.states.get(key);
1259
+ if (!state || state.openedAt === null) return false;
1260
+ const now = performance.now();
1261
+ const elapsed = now - state.openedAt;
1262
+ if (elapsed >= this.openMs) {
1263
+ if (alreadyOwnsProbe) return false;
1264
+ if (state.probeInFlight) {
1265
+ throw new KSeFCircuitOpenError(endpoint, state.openedAt, 0);
1266
+ }
1267
+ state.probeInFlight = true;
1268
+ consola2.debug(`Circuit breaker: probe after cooldown for '${key}'`);
1269
+ return true;
1270
+ }
1271
+ const retryAfterMs = Math.max(0, this.openMs - elapsed);
1272
+ throw new KSeFCircuitOpenError(endpoint, state.openedAt, retryAfterMs);
1273
+ }
1274
+ recordSuccess(endpoint) {
1275
+ const key = this.keyFor(endpoint);
1276
+ const state = this.states.get(key);
1277
+ if (!state) return;
1278
+ if (state.openedAt !== null || state.failures > 0) {
1279
+ consola2.debug(`Circuit breaker: reset for '${key}'`);
1280
+ }
1281
+ this.states.delete(key);
1282
+ }
1283
+ // Release a claimed probe slot WITHOUT observing an outcome. Use this when
1284
+ // the probe attempt was aborted before reaching upstream (e.g. rate-limit
1285
+ // acquire rejected, client cancellation). We have no new information about
1286
+ // upstream health, so the breaker must stay OPEN — but we do restart the
1287
+ // cooldown clock so the next probe attempt waits a fresh `openMs`,
1288
+ // preventing a tight loop of aborted probes from spamming the limiter.
1289
+ releaseProbe(endpoint) {
1290
+ const key = this.keyFor(endpoint);
1291
+ const state = this.states.get(key);
1292
+ if (!state || !state.probeInFlight) return;
1293
+ state.probeInFlight = false;
1294
+ if (state.openedAt !== null) {
1295
+ state.openedAt = performance.now();
1296
+ }
1297
+ consola2.debug(`Circuit breaker: probe aborted (not observed) for '${key}', cooldown restarted`);
1298
+ }
1299
+ recordFailure(endpoint) {
1300
+ const key = this.keyFor(endpoint);
1301
+ const now = performance.now();
1302
+ let state = this.states.get(key);
1303
+ if (!state) {
1304
+ state = { failures: 0, openedAt: null, lastFailureAt: null, probeInFlight: false };
1305
+ this.states.set(key, state);
1306
+ }
1307
+ if (state.openedAt !== null && state.probeInFlight) {
1308
+ state.openedAt = now;
1309
+ state.failures = this.failureThreshold;
1310
+ state.lastFailureAt = now;
1311
+ state.probeInFlight = false;
1312
+ consola2.debug(`Circuit breaker: probe failed, re-opened for '${key}'`);
1313
+ this.maybeSweepStaleClosed(now, key);
1314
+ return;
1315
+ }
1316
+ const slidingStale = state.lastFailureAt !== null && now - state.lastFailureAt > this.openMs;
1317
+ state.failures = slidingStale ? 1 : state.failures + 1;
1318
+ state.lastFailureAt = now;
1319
+ if (state.openedAt === null && state.failures >= this.failureThreshold) {
1320
+ state.openedAt = now;
1321
+ consola2.debug(
1322
+ `Circuit breaker: opened for '${key}' after ${state.failures} failures (cooldown ${this.openMs}ms)`
1323
+ );
1324
+ }
1325
+ this.maybeSweepStaleClosed(now, key);
1326
+ }
1327
+ keyFor(endpoint) {
1328
+ return this.scope === "global" ? GLOBAL_KEY : endpoint;
1329
+ }
1330
+ // Prevent unbounded map growth under `scope: 'endpoint'` when callers hit
1331
+ // many distinct parameterized paths (e.g. `auth/sessions/{ref}`) that each
1332
+ // fail once and are never revisited. Global scope is always a single entry.
1333
+ //
1334
+ // Runs amortized O(n) — gated on a size threshold so small workloads pay
1335
+ // nothing. Only evicts states that are genuinely settled: closed, no probe
1336
+ // in flight, and with the last failure older than two cooldowns.
1337
+ maybeSweepStaleClosed(now, keepKey) {
1338
+ if (this.scope !== "endpoint") return;
1339
+ if (this.states.size <= _CircuitBreakerPolicy.sweepThreshold) return;
1340
+ const staleBefore = now - 2 * this.openMs;
1341
+ for (const [key, state] of this.states) {
1342
+ if (key === keepKey) continue;
1343
+ if (state.openedAt !== null) continue;
1344
+ if (state.probeInFlight) continue;
1345
+ if (state.lastFailureAt !== null && state.lastFailureAt < staleBefore) {
1346
+ this.states.delete(key);
1347
+ }
1348
+ }
1349
+ }
1350
+ static sweepThreshold = 64;
1351
+ };
1352
+ }
1353
+ });
1354
+
1100
1355
  // src/http/auth-manager.ts
1101
1356
  var DefaultAuthManager;
1102
1357
  var init_auth_manager = __esm({
1103
1358
  "src/http/auth-manager.ts"() {
1104
1359
  "use strict";
1360
+ init_esm_shims();
1105
1361
  DefaultAuthManager = class {
1106
1362
  token;
1107
1363
  refreshToken;
@@ -1142,6 +1398,7 @@ var KSEF_FEATURE_HEADER, UpoVersion, ENFORCE_XADES_COMPLIANCE;
1142
1398
  var init_ksef_feature = __esm({
1143
1399
  "src/http/ksef-feature.ts"() {
1144
1400
  "use strict";
1401
+ init_esm_shims();
1145
1402
  KSEF_FEATURE_HEADER = "X-KSeF-Feature";
1146
1403
  UpoVersion = {
1147
1404
  /** UPO v4-2 format (default before 2026-01-05). */
@@ -1241,6 +1498,7 @@ var NIP_PATTERN_CORE, VAT_UE_PATTERN_CORE, Nip, VatUe, NipVatUe, InternalId, Pep
1241
1498
  var init_patterns = __esm({
1242
1499
  "src/validation/patterns.ts"() {
1243
1500
  "use strict";
1501
+ init_esm_shims();
1244
1502
  NIP_PATTERN_CORE = "[1-9]((\\d[1-9])|([1-9]\\d))\\d{7}";
1245
1503
  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}))";
1246
1504
  Nip = new RegExp(`^${NIP_PATTERN_CORE}$`);
@@ -1357,6 +1615,7 @@ function getTextContent(el) {
1357
1615
  var init_xml_to_object = __esm({
1358
1616
  "src/validation/xml-to-object.ts"() {
1359
1617
  "use strict";
1618
+ init_esm_shims();
1360
1619
  }
1361
1620
  });
1362
1621
 
@@ -1370,6 +1629,7 @@ var TKodFormularza, TDataCzas, TZnakowy, TNaglowek, TKodyKrajowUE, TNrNIP, TZnak
1370
1629
  var init_fa3 = __esm({
1371
1630
  "src/validation/schemas/fa3.ts"() {
1372
1631
  "use strict";
1632
+ init_esm_shims();
1373
1633
  TKodFormularza = z.literal("FA");
1374
1634
  TDataCzas = z.string();
1375
1635
  TZnakowy = z.string().min(1).max(256);
@@ -1780,6 +2040,7 @@ var TKodFormularza2, TDataCzas2, TZnakowy3, TNaglowek2, TKodyKrajowUE2, TNrNIP2,
1780
2040
  var init_fa2 = __esm({
1781
2041
  "src/validation/schemas/fa2.ts"() {
1782
2042
  "use strict";
2043
+ init_esm_shims();
1783
2044
  TKodFormularza2 = z2.literal("FA");
1784
2045
  TDataCzas2 = z2.string();
1785
2046
  TZnakowy3 = z2.string().min(1).max(256);
@@ -2174,6 +2435,7 @@ var TKodFormularza3, TDataCzas3, TZnakowy4, TNaglowek3, TNrNIP3, TZnakowy5123, T
2174
2435
  var init_rr1_v11e = __esm({
2175
2436
  "src/validation/schemas/rr1-v11e.ts"() {
2176
2437
  "use strict";
2438
+ init_esm_shims();
2177
2439
  TKodFormularza3 = z3.literal("FA_RR");
2178
2440
  TDataCzas3 = z3.string();
2179
2441
  TZnakowy4 = z3.string().min(1).max(256);
@@ -2379,6 +2641,7 @@ var TKodFormularza4, TDataCzas4, TZnakowy5, TNaglowek4, TNrNIP4, TZnakowy5124, T
2379
2641
  var init_rr1_v10e = __esm({
2380
2642
  "src/validation/schemas/rr1-v10e.ts"() {
2381
2643
  "use strict";
2644
+ init_esm_shims();
2382
2645
  TKodFormularza4 = z4.literal("FA_RR");
2383
2646
  TDataCzas4 = z4.string();
2384
2647
  TZnakowy5 = z4.string().min(1).max(256);
@@ -2584,6 +2847,7 @@ var InvoiceType, PEF3Schema;
2584
2847
  var init_pef3 = __esm({
2585
2848
  "src/validation/schemas/pef3.ts"() {
2586
2849
  "use strict";
2850
+ init_esm_shims();
2587
2851
  InvoiceType = z5.object({
2588
2852
  "UBLExtensions": z5.any().optional(),
2589
2853
  "UBLVersionID": z5.any().optional(),
@@ -2654,6 +2918,7 @@ var CreditNoteType, PEF_KOR3Schema;
2654
2918
  var init_pef_kor3 = __esm({
2655
2919
  "src/validation/schemas/pef-kor3.ts"() {
2656
2920
  "use strict";
2921
+ init_esm_shims();
2657
2922
  CreditNoteType = z6.object({
2658
2923
  "UBLExtensions": z6.any().optional(),
2659
2924
  "UBLVersionID": z6.any().optional(),
@@ -2716,6 +2981,7 @@ var NAMESPACE_MAP;
2716
2981
  var init_schemas = __esm({
2717
2982
  "src/validation/schemas/index.ts"() {
2718
2983
  "use strict";
2984
+ init_esm_shims();
2719
2985
  init_fa3();
2720
2986
  init_fa2();
2721
2987
  init_rr1_v11e();
@@ -2772,6 +3038,7 @@ var ROOT_ELEMENT_MAP, schemaCache, SchemaRegistry;
2772
3038
  var init_schema_registry = __esm({
2773
3039
  "src/validation/schema-registry.ts"() {
2774
3040
  "use strict";
3041
+ init_esm_shims();
2775
3042
  init_schemas();
2776
3043
  ROOT_ELEMENT_MAP = {
2777
3044
  Invoice: "PEF3",
@@ -2897,6 +3164,7 @@ var DISCOURAGED_UNICODE_RANGES, PI_TARGET_RE;
2897
3164
  var init_char_validity = __esm({
2898
3165
  "src/validation/char-validity.ts"() {
2899
3166
  "use strict";
3167
+ init_esm_shims();
2900
3168
  DISCOURAGED_UNICODE_RANGES = [
2901
3169
  [127, 132],
2902
3170
  [134, 159],
@@ -2979,11 +3247,11 @@ async function validateSchema(xml, options, _parsed) {
2979
3247
  const prefix = rootElement ? `/${rootElement}/` : "/";
2980
3248
  const validationErrors = result.error.issues.map((issue) => {
2981
3249
  const zodPath = issue.path.join("/");
2982
- const path2 = zodPath ? `${prefix}${zodPath}` : rootElement ? `/${rootElement}` : void 0;
3250
+ const path4 = zodPath ? `${prefix}${zodPath}` : rootElement ? `/${rootElement}` : void 0;
2983
3251
  return {
2984
3252
  code: mapZodErrorCode(issue),
2985
3253
  message: issue.message,
2986
- path: path2
3254
+ path: path4
2987
3255
  };
2988
3256
  });
2989
3257
  return { valid: false, schemaType, errors: validationErrors };
@@ -3023,9 +3291,9 @@ function validateBusinessRules(xml, _parsed) {
3023
3291
  collectDateErrors(object, rootElement, errors);
3024
3292
  return { valid: errors.length === 0, schemaType, errors };
3025
3293
  }
3026
- function collectNipPeselErrors(obj, path2, errors) {
3294
+ function collectNipPeselErrors(obj, path4, errors) {
3027
3295
  for (const [key, value] of Object.entries(obj)) {
3028
- const currentPath = path2 ? `${path2}/${key}` : key;
3296
+ const currentPath = path4 ? `${path4}/${key}` : key;
3029
3297
  if (key === "NIP" && typeof value === "string") {
3030
3298
  if (!isValidNip(value)) {
3031
3299
  errors.push({
@@ -3104,6 +3372,7 @@ function batchValidationDetails(batch) {
3104
3372
  var init_invoice_validator = __esm({
3105
3373
  "src/validation/invoice-validator.ts"() {
3106
3374
  "use strict";
3375
+ init_esm_shims();
3107
3376
  init_xml_to_object();
3108
3377
  init_schema_registry();
3109
3378
  init_char_validity();
@@ -3116,6 +3385,7 @@ var SystemCode, FORM_CODES, DEFAULT_FORM_CODE, INVOICE_TYPES_BY_SYSTEM_CODE, FOR
3116
3385
  var init_types = __esm({
3117
3386
  "src/models/document-structures/types.ts"() {
3118
3387
  "use strict";
3388
+ init_esm_shims();
3119
3389
  SystemCode = {
3120
3390
  FA_2: "FA (2)",
3121
3391
  FA_3: "FA (3)",
@@ -3168,6 +3438,7 @@ var SYSTEM_CODE_TO_FORM_CODE, ALL_FORM_CODES, BATCH_DISALLOWED_SYSTEM_CODES;
3168
3438
  var init_helpers = __esm({
3169
3439
  "src/models/document-structures/helpers.ts"() {
3170
3440
  "use strict";
3441
+ init_esm_shims();
3171
3442
  init_types();
3172
3443
  SYSTEM_CODE_TO_FORM_CODE = {
3173
3444
  [SystemCode.FA_2]: FORM_CODES.FA_2,
@@ -3188,6 +3459,7 @@ var init_helpers = __esm({
3188
3459
  var init_document_structures = __esm({
3189
3460
  "src/models/document-structures/index.ts"() {
3190
3461
  "use strict";
3462
+ init_esm_shims();
3191
3463
  init_types();
3192
3464
  init_helpers();
3193
3465
  }
@@ -3198,6 +3470,7 @@ var AuthService;
3198
3470
  var init_auth = __esm({
3199
3471
  "src/services/auth.ts"() {
3200
3472
  "use strict";
3473
+ init_esm_shims();
3201
3474
  init_ksef_feature();
3202
3475
  init_rest_request();
3203
3476
  init_routes();
@@ -3248,6 +3521,7 @@ var ActiveSessionsService;
3248
3521
  var init_active_sessions = __esm({
3249
3522
  "src/services/active-sessions.ts"() {
3250
3523
  "use strict";
3524
+ init_esm_shims();
3251
3525
  init_rest_request();
3252
3526
  init_routes();
3253
3527
  ActiveSessionsService = class {
@@ -3279,6 +3553,7 @@ var OnlineSessionService;
3279
3553
  var init_online_session = __esm({
3280
3554
  "src/services/online-session.ts"() {
3281
3555
  "use strict";
3556
+ init_esm_shims();
3282
3557
  init_ksef_feature();
3283
3558
  init_rest_request();
3284
3559
  init_routes();
@@ -3331,6 +3606,7 @@ async function runWithConcurrency(tasks, parallelism) {
3331
3606
  var init_concurrency = __esm({
3332
3607
  "src/utils/concurrency.ts"() {
3333
3608
  "use strict";
3609
+ init_esm_shims();
3334
3610
  }
3335
3611
  });
3336
3612
 
@@ -3339,6 +3615,7 @@ var BatchSessionService;
3339
3615
  var init_batch_session = __esm({
3340
3616
  "src/services/batch-session.ts"() {
3341
3617
  "use strict";
3618
+ init_esm_shims();
3342
3619
  init_ksef_feature();
3343
3620
  init_rest_request();
3344
3621
  init_routes();
@@ -3443,6 +3720,7 @@ var SessionStatusService;
3443
3720
  var init_session_status = __esm({
3444
3721
  "src/services/session-status.ts"() {
3445
3722
  "use strict";
3723
+ init_esm_shims();
3446
3724
  init_rest_request();
3447
3725
  init_routes();
3448
3726
  SessionStatusService = class {
@@ -3529,6 +3807,7 @@ var InvoiceDownloadService;
3529
3807
  var init_invoice_download = __esm({
3530
3808
  "src/services/invoice-download.ts"() {
3531
3809
  "use strict";
3810
+ init_esm_shims();
3532
3811
  init_rest_request();
3533
3812
  init_routes();
3534
3813
  InvoiceDownloadService = class {
@@ -3571,6 +3850,7 @@ var PermissionsService;
3571
3850
  var init_permissions = __esm({
3572
3851
  "src/services/permissions.ts"() {
3573
3852
  "use strict";
3853
+ init_esm_shims();
3574
3854
  init_ksef_validation_error();
3575
3855
  init_rest_request();
3576
3856
  init_routes();
@@ -3763,6 +4043,7 @@ function parseKSeFTokenContext(token) {
3763
4043
  var init_jwt = __esm({
3764
4044
  "src/utils/jwt.ts"() {
3765
4045
  "use strict";
4046
+ init_esm_shims();
3766
4047
  }
3767
4048
  });
3768
4049
 
@@ -3774,6 +4055,7 @@ var TOKEN_AUTHOR_IDENTIFIER_TYPES, TokenService;
3774
4055
  var init_tokens = __esm({
3775
4056
  "src/services/tokens.ts"() {
3776
4057
  "use strict";
4058
+ init_esm_shims();
3777
4059
  init_rest_request();
3778
4060
  init_routes();
3779
4061
  init_jwt();
@@ -3894,6 +4176,7 @@ var CertificateApiService;
3894
4176
  var init_certificates = __esm({
3895
4177
  "src/services/certificates.ts"() {
3896
4178
  "use strict";
4179
+ init_esm_shims();
3897
4180
  init_rest_request();
3898
4181
  init_routes();
3899
4182
  CertificateApiService = class {
@@ -3946,6 +4229,7 @@ var LighthouseService;
3946
4229
  var init_lighthouse = __esm({
3947
4230
  "src/services/lighthouse.ts"() {
3948
4231
  "use strict";
4232
+ init_esm_shims();
3949
4233
  init_errors();
3950
4234
  LighthouseService = class {
3951
4235
  lighthouseUrl;
@@ -3954,20 +4238,20 @@ var init_lighthouse = __esm({
3954
4238
  this.lighthouseUrl = options.lighthouseUrl;
3955
4239
  this.timeout = options.timeout;
3956
4240
  }
3957
- async fetchJson(path2) {
4241
+ async fetchJson(path4) {
3958
4242
  if (!this.lighthouseUrl) {
3959
4243
  throw new KSeFError(
3960
4244
  "Lighthouse API is not available for the DEMO environment. Use TEST or PROD instead."
3961
4245
  );
3962
4246
  }
3963
- const response = await fetch(`${this.lighthouseUrl}${path2}`, {
4247
+ const response = await fetch(`${this.lighthouseUrl}${path4}`, {
3964
4248
  headers: { Accept: "application/json" },
3965
4249
  signal: AbortSignal.timeout(this.timeout)
3966
4250
  });
3967
4251
  if (!response.ok) {
3968
4252
  const body = await response.text();
3969
4253
  throw new KSeFError(
3970
- `Lighthouse ${path2} failed: HTTP ${response.status} \u2014 ${body}`
4254
+ `Lighthouse ${path4} failed: HTTP ${response.status} \u2014 ${body}`
3971
4255
  );
3972
4256
  }
3973
4257
  return await response.json();
@@ -3988,6 +4272,7 @@ var LimitsService;
3988
4272
  var init_limits = __esm({
3989
4273
  "src/services/limits.ts"() {
3990
4274
  "use strict";
4275
+ init_esm_shims();
3991
4276
  init_rest_request();
3992
4277
  init_routes();
3993
4278
  LimitsService = class {
@@ -4019,6 +4304,7 @@ var PeppolService;
4019
4304
  var init_peppol = __esm({
4020
4305
  "src/services/peppol.ts"() {
4021
4306
  "use strict";
4307
+ init_esm_shims();
4022
4308
  init_rest_request();
4023
4309
  init_routes();
4024
4310
  PeppolService = class {
@@ -4042,6 +4328,7 @@ var TestDataService;
4042
4328
  var init_test_data = __esm({
4043
4329
  "src/services/test-data.ts"() {
4044
4330
  "use strict";
4331
+ init_esm_shims();
4045
4332
  init_rest_request();
4046
4333
  init_routes();
4047
4334
  init_ksef_error();
@@ -4161,6 +4448,7 @@ var CertificateFetcher;
4161
4448
  var init_certificate_fetcher = __esm({
4162
4449
  "src/crypto/certificate-fetcher.ts"() {
4163
4450
  "use strict";
4451
+ init_esm_shims();
4164
4452
  init_rest_request();
4165
4453
  init_routes();
4166
4454
  CertificateFetcher = class {
@@ -4256,6 +4544,7 @@ var CryptographyService;
4256
4544
  var init_cryptography_service = __esm({
4257
4545
  "src/crypto/cryptography-service.ts"() {
4258
4546
  "use strict";
4547
+ init_esm_shims();
4259
4548
  CryptographyService = class {
4260
4549
  fetcher;
4261
4550
  constructor(fetcher) {
@@ -4493,6 +4782,40 @@ __export(signature_service_exports, {
4493
4782
  import * as crypto3 from "crypto";
4494
4783
  import { ExclusiveCanonicalization } from "xml-crypto";
4495
4784
  import { DOMParser as DOMParser2, XMLSerializer } from "@xmldom/xmldom";
4785
+ function pickRsaAlgo() {
4786
+ return {
4787
+ nodeHashName: "sha256",
4788
+ signatureUri: RSA_SHA256_SIGNATURE_URI,
4789
+ digestUri: DIGEST_URI.sha256
4790
+ };
4791
+ }
4792
+ function pickEcdsaAlgo(privateKey) {
4793
+ const curve = privateKey.asymmetricKeyDetails?.namedCurve;
4794
+ switch (curve) {
4795
+ case "prime256v1":
4796
+ return {
4797
+ nodeHashName: "sha256",
4798
+ signatureUri: ECDSA_SIGNATURE_URI.sha256,
4799
+ digestUri: DIGEST_URI.sha256
4800
+ };
4801
+ case "secp384r1":
4802
+ return {
4803
+ nodeHashName: "sha384",
4804
+ signatureUri: ECDSA_SIGNATURE_URI.sha384,
4805
+ digestUri: DIGEST_URI.sha384
4806
+ };
4807
+ case "secp521r1":
4808
+ return {
4809
+ nodeHashName: "sha512",
4810
+ signatureUri: ECDSA_SIGNATURE_URI.sha512,
4811
+ digestUri: DIGEST_URI.sha512
4812
+ };
4813
+ default:
4814
+ throw new KSeFError(
4815
+ `Unsupported ECDSA curve: ${curve ?? "unknown"}. Supported: P-256 (prime256v1), P-384 (secp384r1), P-521 (secp521r1).`
4816
+ );
4817
+ }
4818
+ }
4496
4819
  function extractDerFromPem(pem) {
4497
4820
  const base64 = pem.replace(/-----BEGIN [A-Z\s]+-----/g, "").replace(/-----END [A-Z\s]+-----/g, "").replace(/\s+/g, "");
4498
4821
  return Buffer.from(base64, "base64");
@@ -4507,12 +4830,12 @@ function canonicalize(elem) {
4507
4830
  const c14n = new ExclusiveCanonicalization();
4508
4831
  return c14n.process(elem, {});
4509
4832
  }
4510
- function computeRootDigest(doc) {
4833
+ function computeRootDigest(doc, hashName) {
4511
4834
  const root = doc.documentElement;
4512
4835
  const canonical = canonicalize(root);
4513
- return crypto3.createHash("sha256").update(canonical, "utf-8").digest("base64");
4836
+ return crypto3.createHash(hashName).update(canonical, "utf-8").digest("base64");
4514
4837
  }
4515
- function computeSignedPropertiesDigest(qualifyingPropertiesXml) {
4838
+ function computeSignedPropertiesDigest(qualifyingPropertiesXml, hashName) {
4516
4839
  const parser2 = new DOMParser2();
4517
4840
  const qpDoc = parser2.parseFromString(qualifyingPropertiesXml, "text/xml");
4518
4841
  const signedProps = findElementByLocalName(qpDoc.documentElement, "SignedProperties");
@@ -4520,9 +4843,9 @@ function computeSignedPropertiesDigest(qualifyingPropertiesXml) {
4520
4843
  throw new Error("SignedProperties element not found in QualifyingProperties");
4521
4844
  }
4522
4845
  const canonical = canonicalize(signedProps);
4523
- return crypto3.createHash("sha256").update(canonical, "utf-8").digest("base64");
4846
+ return crypto3.createHash(hashName).update(canonical, "utf-8").digest("base64");
4524
4847
  }
4525
- function buildSignedInfo(signatureAlgorithm, rootDigest, signedPropertiesDigest) {
4848
+ function buildSignedInfo(signatureAlgorithm, digestAlgorithm, rootDigest, signedPropertiesDigest) {
4526
4849
  return [
4527
4850
  `<ds:SignedInfo xmlns:ds="${DS_NS}">`,
4528
4851
  `<ds:CanonicalizationMethod Algorithm="${EXC_C14N_ALGORITHM}"/>`,
@@ -4533,7 +4856,7 @@ function buildSignedInfo(signatureAlgorithm, rootDigest, signedPropertiesDigest)
4533
4856
  `<ds:Transform Algorithm="${ENVELOPED_SIGNATURE_TRANSFORM}"/>`,
4534
4857
  `<ds:Transform Algorithm="${EXC_C14N_ALGORITHM}"/>`,
4535
4858
  `</ds:Transforms>`,
4536
- `<ds:DigestMethod Algorithm="${SHA256_DIGEST_METHOD}"/>`,
4859
+ `<ds:DigestMethod Algorithm="${digestAlgorithm}"/>`,
4537
4860
  `<ds:DigestValue>${rootDigest}</ds:DigestValue>`,
4538
4861
  `</ds:Reference>`,
4539
4862
  // Reference 2: SignedProperties
@@ -4541,22 +4864,22 @@ function buildSignedInfo(signatureAlgorithm, rootDigest, signedPropertiesDigest)
4541
4864
  `<ds:Transforms>`,
4542
4865
  `<ds:Transform Algorithm="${EXC_C14N_ALGORITHM}"/>`,
4543
4866
  `</ds:Transforms>`,
4544
- `<ds:DigestMethod Algorithm="${SHA256_DIGEST_METHOD}"/>`,
4867
+ `<ds:DigestMethod Algorithm="${digestAlgorithm}"/>`,
4545
4868
  `<ds:DigestValue>${signedPropertiesDigest}</ds:DigestValue>`,
4546
4869
  `</ds:Reference>`,
4547
4870
  `</ds:SignedInfo>`
4548
4871
  ].join("");
4549
4872
  }
4550
- function computeSignatureValue(canonicalSignedInfo, privateKey, isEc) {
4873
+ function computeSignatureValue(canonicalSignedInfo, privateKey, isEc, hashName) {
4551
4874
  const data = Buffer.from(canonicalSignedInfo, "utf-8");
4552
4875
  let signature;
4553
4876
  if (isEc) {
4554
- signature = crypto3.sign("sha256", data, {
4877
+ signature = crypto3.sign(hashName, data, {
4555
4878
  key: privateKey,
4556
4879
  dsaEncoding: "ieee-p1363"
4557
4880
  });
4558
4881
  } else {
4559
- signature = crypto3.sign("sha256", data, privateKey);
4882
+ signature = crypto3.sign(hashName, data, privateKey);
4560
4883
  }
4561
4884
  return signature.toString("base64");
4562
4885
  }
@@ -4577,7 +4900,7 @@ function buildSignatureElement(signedInfoXml, signatureValue, certBase64, qualif
4577
4900
  `</ds:Signature>`
4578
4901
  ].join("");
4579
4902
  }
4580
- function buildQualifyingProperties(signatureId, signedPropertiesId, certDigest, issuerName, serialNumber, signingTime) {
4903
+ function buildQualifyingProperties(signatureId, signedPropertiesId, certDigest, issuerName, serialNumber, signingTime, digestAlgorithm) {
4581
4904
  return [
4582
4905
  `<xades:QualifyingProperties`,
4583
4906
  ` Target="#${signatureId}"`,
@@ -4589,7 +4912,7 @@ function buildQualifyingProperties(signatureId, signedPropertiesId, certDigest,
4589
4912
  `<xades:SigningCertificate>`,
4590
4913
  `<xades:Cert>`,
4591
4914
  `<xades:CertDigest>`,
4592
- `<DigestMethod Algorithm="${SHA256_DIGEST_METHOD}"/>`,
4915
+ `<DigestMethod Algorithm="${digestAlgorithm}"/>`,
4593
4916
  `<DigestValue>${certDigest}</DigestValue>`,
4594
4917
  `</xades:CertDigest>`,
4595
4918
  `<xades:IssuerSerial>`,
@@ -4625,18 +4948,28 @@ function wrapBase64(base64) {
4625
4948
  }
4626
4949
  return lines.join("\n");
4627
4950
  }
4628
- var 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;
4951
+ var 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;
4629
4952
  var init_signature_service = __esm({
4630
4953
  "src/crypto/signature-service.ts"() {
4631
4954
  "use strict";
4955
+ init_esm_shims();
4956
+ init_ksef_error();
4632
4957
  XADES_NS = "http://uri.etsi.org/01903/v1.3.2#";
4633
4958
  DS_NS = "http://www.w3.org/2000/09/xmldsig#";
4634
4959
  SIGNED_PROPERTIES_TYPE = "http://uri.etsi.org/01903#SignedProperties";
4635
- SHA256_DIGEST_METHOD = "http://www.w3.org/2001/04/xmlenc#sha256";
4636
4960
  EXC_C14N_ALGORITHM = "http://www.w3.org/2001/10/xml-exc-c14n#";
4637
4961
  ENVELOPED_SIGNATURE_TRANSFORM = "http://www.w3.org/2000/09/xmldsig#enveloped-signature";
4638
- RSA_SHA256_SIGNATURE = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256";
4639
- ECDSA_SHA256_SIGNATURE = "http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha256";
4962
+ DIGEST_URI = {
4963
+ sha256: "http://www.w3.org/2001/04/xmlenc#sha256",
4964
+ sha384: "http://www.w3.org/2001/04/xmldsig-more#sha384",
4965
+ sha512: "http://www.w3.org/2001/04/xmlenc#sha512"
4966
+ };
4967
+ ECDSA_SIGNATURE_URI = {
4968
+ sha256: "http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha256",
4969
+ sha384: "http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha384",
4970
+ sha512: "http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha512"
4971
+ };
4972
+ RSA_SHA256_SIGNATURE_URI = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256";
4640
4973
  CLOCK_SKEW_BUFFER_MS = -6e4;
4641
4974
  SIGNATURE_ID = "Signature";
4642
4975
  SIGNED_PROPERTIES_ID = "SignedProperties";
@@ -4656,15 +4989,21 @@ var init_signature_service = __esm({
4656
4989
  }
4657
4990
  const certDer = extractDerFromPem(certPem);
4658
4991
  const certBase64 = certDer.toString("base64");
4659
- const certDigest = crypto3.createHash("sha256").update(certDer).digest("base64");
4660
4992
  const x5093 = new crypto3.X509Certificate(certPem);
4661
4993
  const issuerName = normalizeIssuerDn(x5093.issuer);
4662
4994
  const serialNumber = hexSerialToDecimal(x5093.serialNumber);
4663
4995
  const privateKey = crypto3.createPrivateKey(
4664
4996
  passphrase ? { key: privateKeyPem, format: "pem", passphrase } : privateKeyPem
4665
4997
  );
4666
- const isEc = privateKey.asymmetricKeyType === "ec";
4667
- const signatureAlgorithm = isEc ? ECDSA_SHA256_SIGNATURE : RSA_SHA256_SIGNATURE;
4998
+ const keyType = privateKey.asymmetricKeyType;
4999
+ if (keyType !== "ec" && keyType !== "rsa") {
5000
+ throw new KSeFError(
5001
+ `Unsupported private key type: ${keyType ?? "unknown"}. Supported: RSA and ECDSA.`
5002
+ );
5003
+ }
5004
+ const isEc = keyType === "ec";
5005
+ const algo = isEc ? pickEcdsaAlgo(privateKey) : pickRsaAlgo();
5006
+ const certDigest = crypto3.createHash(algo.nodeHashName).update(certDer).digest("base64");
4668
5007
  const signingTime = new Date(Date.now() + CLOCK_SKEW_BUFFER_MS).toISOString();
4669
5008
  const parser2 = new DOMParser2();
4670
5009
  const doc = parser2.parseFromString(xml, "text/xml");
@@ -4678,12 +5017,17 @@ var init_signature_service = __esm({
4678
5017
  certDigest,
4679
5018
  issuerName,
4680
5019
  serialNumber,
4681
- signingTime
5020
+ signingTime,
5021
+ algo.digestUri
5022
+ );
5023
+ const rootDigest = computeRootDigest(doc, algo.nodeHashName);
5024
+ const signedPropertiesDigest = computeSignedPropertiesDigest(
5025
+ qualifyingPropertiesXml,
5026
+ algo.nodeHashName
4682
5027
  );
4683
- const rootDigest = computeRootDigest(doc);
4684
- const signedPropertiesDigest = computeSignedPropertiesDigest(qualifyingPropertiesXml);
4685
5028
  const signedInfoXml = buildSignedInfo(
4686
- signatureAlgorithm,
5029
+ algo.signatureUri,
5030
+ algo.digestUri,
4687
5031
  rootDigest,
4688
5032
  signedPropertiesDigest
4689
5033
  );
@@ -4692,7 +5036,8 @@ var init_signature_service = __esm({
4692
5036
  const signatureValue = computeSignatureValue(
4693
5037
  canonicalSignedInfo,
4694
5038
  privateKey,
4695
- isEc
5039
+ isEc,
5040
+ algo.nodeHashName
4696
5041
  );
4697
5042
  const signatureXml = buildSignatureElement(
4698
5043
  signedInfoXml,
@@ -4719,6 +5064,7 @@ var Pkcs12Loader;
4719
5064
  var init_pkcs12_loader = __esm({
4720
5065
  "src/crypto/pkcs12-loader.ts"() {
4721
5066
  "use strict";
5067
+ init_esm_shims();
4722
5068
  Pkcs12Loader = class {
4723
5069
  static load(p12, password) {
4724
5070
  const { pki, pkcs12, asn1 } = forge;
@@ -4787,6 +5133,7 @@ var AUTH_TOKEN_REQUEST_NS;
4787
5133
  var init_auth_xml_builder = __esm({
4788
5134
  "src/crypto/auth-xml-builder.ts"() {
4789
5135
  "use strict";
5136
+ init_esm_shims();
4790
5137
  AUTH_TOKEN_REQUEST_NS = "http://ksef.mf.gov.pl/auth/token/2.0";
4791
5138
  }
4792
5139
  });
@@ -4797,6 +5144,7 @@ var VerificationLinkService;
4797
5144
  var init_verification_link_service = __esm({
4798
5145
  "src/qr/verification-link-service.ts"() {
4799
5146
  "use strict";
5147
+ init_esm_shims();
4800
5148
  VerificationLinkService = class {
4801
5149
  constructor(baseQrUrl) {
4802
5150
  this.baseQrUrl = baseQrUrl;
@@ -4818,11 +5166,11 @@ var init_verification_link_service = __esm({
4818
5166
  * Build certificate verification URL (Code II).
4819
5167
  * Format: {baseQrUrl}/certificate/{contextType}/{contextId}/{sellerNip}/{certSerial}/{hash_base64url}/{signature_base64url}
4820
5168
  */
4821
- buildCertificateVerificationUrl(contextType, contextId, sellerNip, certSerial, invoiceHashBase64, privateKeyPem) {
5169
+ buildCertificateVerificationUrl(contextType, contextId, sellerNip, certSerial, invoiceHashBase64, privateKeyPem, privateKeyPassword) {
4822
5170
  const hashBase64Url = this.base64ToBase64Url(invoiceHashBase64);
4823
5171
  const pathWithoutSignature = `${this.baseQrUrl}/certificate/${contextType}/${contextId}/${sellerNip}/${certSerial}/${hashBase64Url}`;
4824
5172
  const dataToSign = pathWithoutSignature.replace(/^https?:\/\//, "");
4825
- const key = crypto5.createPrivateKey(privateKeyPem);
5173
+ const key = privateKeyPassword !== void 0 ? crypto5.createPrivateKey({ key: privateKeyPem, format: "pem", passphrase: privateKeyPassword }) : crypto5.createPrivateKey(privateKeyPem);
4826
5174
  let signature;
4827
5175
  if (key.asymmetricKeyType === "rsa") {
4828
5176
  signature = crypto5.sign("sha256", Buffer.from(dataToSign), {
@@ -4938,6 +5286,7 @@ var DEFAULT_UNZIP_OPTIONS;
4938
5286
  var init_zip = __esm({
4939
5287
  "src/utils/zip.ts"() {
4940
5288
  "use strict";
5289
+ init_esm_shims();
4941
5290
  DEFAULT_UNZIP_OPTIONS = {
4942
5291
  maxFiles: 1e4,
4943
5292
  maxTotalUncompressedSize: 2e9,
@@ -5009,6 +5358,7 @@ var holidayCache;
5009
5358
  var init_holidays = __esm({
5010
5359
  "src/offline/holidays.ts"() {
5011
5360
  "use strict";
5361
+ init_esm_shims();
5012
5362
  holidayCache = /* @__PURE__ */ new Map();
5013
5363
  }
5014
5364
  });
@@ -5108,6 +5458,7 @@ var FAR_FUTURE;
5108
5458
  var init_deadline = __esm({
5109
5459
  "src/offline/deadline.ts"() {
5110
5460
  "use strict";
5461
+ init_esm_shims();
5111
5462
  init_holidays();
5112
5463
  FAR_FUTURE = /* @__PURE__ */ new Date("9999-12-31T23:59:59Z");
5113
5464
  }
@@ -5119,6 +5470,7 @@ var OfflineInvoiceWorkflow;
5119
5470
  var init_offline_invoice_workflow = __esm({
5120
5471
  "src/workflows/offline-invoice-workflow.ts"() {
5121
5472
  "use strict";
5473
+ init_esm_shims();
5122
5474
  init_ksef_api_error();
5123
5475
  init_deadline();
5124
5476
  init_document_structures();
@@ -5152,7 +5504,8 @@ var init_offline_invoice_workflow = __esm({
5152
5504
  input.sellerNip,
5153
5505
  options.certificate.certificateSerial,
5154
5506
  invoiceHashBase64,
5155
- options.certificate.privateKeyPem
5507
+ options.certificate.privateKeyPem,
5508
+ options.certificate.password
5156
5509
  );
5157
5510
  }
5158
5511
  const submitBy = options?.customDeadline ? typeof options.customDeadline === "string" ? options.customDeadline : options.customDeadline.toISOString() : calculateOfflineDeadline(mode, input.invoiceDate, options?.maintenanceWindow).toISOString();
@@ -5342,7 +5695,8 @@ var init_offline_invoice_workflow = __esm({
5342
5695
  original.sellerNip,
5343
5696
  options.certificate.certificateSerial,
5344
5697
  correctedHashBase64,
5345
- options.certificate.privateKeyPem
5698
+ options.certificate.privateKeyPem,
5699
+ options.certificate.password
5346
5700
  );
5347
5701
  }
5348
5702
  const correctionMetadata = {
@@ -5428,6 +5782,11 @@ function buildRestClientConfig(options, authManager) {
5428
5782
  endpointLimits: options.rateLimit.endpointLimits
5429
5783
  });
5430
5784
  }
5785
+ if (options?.circuitBreaker === null) {
5786
+ config.circuitBreakerPolicy = null;
5787
+ } else if (options?.circuitBreaker) {
5788
+ config.circuitBreakerPolicy = new CircuitBreakerPolicy(options.circuitBreaker);
5789
+ }
5431
5790
  if (options?.presignedUrlHosts) {
5432
5791
  const base = defaultPresignedUrlPolicy();
5433
5792
  config.presignedUrlPolicy = {
@@ -5441,10 +5800,12 @@ var KSeFClient;
5441
5800
  var init_client = __esm({
5442
5801
  "src/client.ts"() {
5443
5802
  "use strict";
5803
+ init_esm_shims();
5444
5804
  init_config();
5445
5805
  init_rest_client();
5446
5806
  init_retry_policy();
5447
5807
  init_rate_limit_policy();
5808
+ init_circuit_breaker_policy();
5448
5809
  init_presigned_url_policy();
5449
5810
  init_auth_manager();
5450
5811
  init_auth();
@@ -5578,10 +5939,12 @@ var init_client = __esm({
5578
5939
  });
5579
5940
 
5580
5941
  // src/index.ts
5942
+ init_esm_shims();
5581
5943
  init_config();
5582
5944
  init_errors();
5583
5945
 
5584
5946
  // src/http/index.ts
5947
+ init_esm_shims();
5585
5948
  init_route_builder();
5586
5949
  init_rest_request();
5587
5950
  init_rest_client();
@@ -5589,14 +5952,17 @@ init_routes();
5589
5952
  init_transport();
5590
5953
  init_retry_policy();
5591
5954
  init_rate_limit_policy();
5955
+ init_circuit_breaker_policy();
5592
5956
  init_auth_manager();
5593
5957
  init_presigned_url_policy();
5594
5958
  init_ksef_feature();
5595
5959
 
5596
5960
  // src/validation/index.ts
5961
+ init_esm_shims();
5597
5962
  init_patterns();
5598
5963
 
5599
5964
  // src/validation/constraints.ts
5965
+ init_esm_shims();
5600
5966
  var REQUIRED_CHALLENGE_LENGTH = 36;
5601
5967
  var CERTIFICATE_NAME_MIN_LENGTH = 5;
5602
5968
  var CERTIFICATE_NAME_MAX_LENGTH = 100;
@@ -5611,10 +5977,218 @@ init_schema_registry();
5611
5977
  init_invoice_validator();
5612
5978
  init_char_validity();
5613
5979
 
5980
+ // src/validation/xsd-validator.ts
5981
+ init_esm_shims();
5982
+ import { createRequire } from "module";
5983
+ import * as fs from "fs";
5984
+ import * as path2 from "path";
5985
+ import { fileURLToPath as fileURLToPath2, pathToFileURL } from "url";
5986
+ var cachedPkgRoot = null;
5987
+ function locatePackageRoot() {
5988
+ if (cachedPkgRoot !== null) return cachedPkgRoot;
5989
+ let dir = path2.dirname(fileURLToPath2(import.meta.url));
5990
+ const root = path2.parse(dir).root;
5991
+ while (dir !== root) {
5992
+ const candidate = path2.join(dir, "docs", "schemas");
5993
+ if (fs.existsSync(candidate)) {
5994
+ cachedPkgRoot = dir;
5995
+ return dir;
5996
+ }
5997
+ dir = path2.dirname(dir);
5998
+ }
5999
+ throw new Error("Could not locate ksef-client-ts package root (docs/schemas not found).");
6000
+ }
6001
+ var XSD_RELATIVE = {
6002
+ FA2: ["FA", "schemat_FA(2)_v1-0E.xsd"],
6003
+ FA3: ["FA", "schemat_FA(3)_v1-0E.xsd"],
6004
+ PEF: ["PEF", "Schemat_PEF(3)_v2-1.xsd"],
6005
+ PEF_KOR: ["PEF", "Schemat_PEF_KOR(3)_v2-1.xsd"]
6006
+ };
6007
+ var FA_XSD_PATHS = {
6008
+ get FA2() {
6009
+ return resolveXsdFor("FA2");
6010
+ },
6011
+ get FA3() {
6012
+ return resolveXsdFor("FA3");
6013
+ }
6014
+ };
6015
+ var PEF_XSD_PATHS = {
6016
+ get PEF() {
6017
+ return resolveXsdFor("PEF");
6018
+ },
6019
+ get PEF_KOR() {
6020
+ return resolveXsdFor("PEF_KOR");
6021
+ }
6022
+ };
6023
+ function resolveXsdFor(schema) {
6024
+ const rel = XSD_RELATIVE[schema];
6025
+ if (!rel) throw new Error(`Unknown invoice schema: ${String(schema)}`);
6026
+ return path2.join(locatePackageRoot(), "docs", "schemas", ...rel);
6027
+ }
6028
+ var requireModule = createRequire(import.meta.url);
6029
+ var libxmljs = null;
6030
+ var libxmljsLoadError = null;
6031
+ try {
6032
+ libxmljs = requireModule("libxmljs2");
6033
+ } catch (err) {
6034
+ const code = err?.code;
6035
+ if (code === "MODULE_NOT_FOUND" || code === "ERR_MODULE_NOT_FOUND") {
6036
+ libxmljs = null;
6037
+ } else {
6038
+ libxmljs = null;
6039
+ libxmljsLoadError = err instanceof Error ? err : new Error(String(err));
6040
+ }
6041
+ }
6042
+ var libxmljsAvailable = libxmljs !== null;
6043
+ var MISSING_LIBXMLJS_MESSAGE_PREFIX = "libxmljs2 is not installed";
6044
+ var EXTERNAL_STRUKTURY_DANYCH_URL = /schemaLocation="http:\/\/crd\.gov\.pl\/xml\/schematy\/dziedzinowe\/mf\/2022\/01\/05\/eD\/DefinicjeTypy\/StrukturyDanych_v10-0E\.xsd"/;
6045
+ function rewriteSchemaLocations(xsdContent) {
6046
+ if (!EXTERNAL_STRUKTURY_DANYCH_URL.test(xsdContent)) {
6047
+ return xsdContent;
6048
+ }
6049
+ const bazoweStrukturyPath = path2.join(
6050
+ locatePackageRoot(),
6051
+ "docs",
6052
+ "schemas",
6053
+ "FA",
6054
+ "bazowe",
6055
+ "StrukturyDanych_v10-0E.xsd"
6056
+ );
6057
+ const bazoweStrukturyUrl = pathToFileURL(bazoweStrukturyPath).href;
6058
+ const rewritten = xsdContent.replace(
6059
+ EXTERNAL_STRUKTURY_DANYCH_URL,
6060
+ `schemaLocation="${bazoweStrukturyUrl}"`
6061
+ );
6062
+ if (rewritten === xsdContent) {
6063
+ throw new Error(
6064
+ "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`."
6065
+ );
6066
+ }
6067
+ return rewritten;
6068
+ }
6069
+ function validateAgainstXsd(xml, xsdPath) {
6070
+ if (!libxmljs) {
6071
+ const loadSuffix = libxmljsLoadError ? ` (load failed: ${libxmljsLoadError.message})` : "";
6072
+ throw new Error(
6073
+ `${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\`).`
6074
+ );
6075
+ }
6076
+ const xsdDir = path2.dirname(xsdPath);
6077
+ const rawXsd = fs.readFileSync(xsdPath, "utf8");
6078
+ const rewrittenXsd = rewriteSchemaLocations(rawXsd);
6079
+ const baseUrl = pathToFileURL(xsdDir + path2.sep).href;
6080
+ let schemaDoc;
6081
+ try {
6082
+ schemaDoc = libxmljs.parseXml(rewrittenXsd, { baseUrl });
6083
+ } catch (err) {
6084
+ return { valid: false, errors: [`XSD parse failed: ${err.message}`] };
6085
+ }
6086
+ let xmlDoc;
6087
+ try {
6088
+ xmlDoc = libxmljs.parseXml(xml);
6089
+ } catch (err) {
6090
+ return { valid: false, errors: [`XML parse failed: ${err.message}`] };
6091
+ }
6092
+ const valid = xmlDoc.validate(schemaDoc);
6093
+ const errors = valid ? [] : xmlDoc.validationErrors.map((err) => err.message.trim());
6094
+ return { valid, errors };
6095
+ }
6096
+
6097
+ // src/models/index.ts
6098
+ init_esm_shims();
6099
+
6100
+ // src/models/common.ts
6101
+ init_esm_shims();
6102
+
6103
+ // src/models/auth/index.ts
6104
+ init_esm_shims();
6105
+
6106
+ // src/models/auth/types.ts
6107
+ init_esm_shims();
6108
+
6109
+ // src/models/auth/active-sessions-types.ts
6110
+ init_esm_shims();
6111
+
6112
+ // src/models/sessions/index.ts
6113
+ init_esm_shims();
6114
+
6115
+ // src/models/sessions/online-types.ts
6116
+ init_esm_shims();
6117
+
6118
+ // src/models/sessions/batch-types.ts
6119
+ init_esm_shims();
6120
+
6121
+ // src/models/sessions/status-types.ts
6122
+ init_esm_shims();
6123
+
6124
+ // src/models/sessions/session-state.ts
6125
+ init_esm_shims();
6126
+
6127
+ // src/models/invoices/index.ts
6128
+ init_esm_shims();
6129
+
6130
+ // src/models/invoices/types.ts
6131
+ init_esm_shims();
6132
+
6133
+ // src/models/permissions/index.ts
6134
+ init_esm_shims();
6135
+
6136
+ // src/models/permissions/types.ts
6137
+ init_esm_shims();
6138
+
6139
+ // src/models/tokens/index.ts
6140
+ init_esm_shims();
6141
+
6142
+ // src/models/tokens/types.ts
6143
+ init_esm_shims();
6144
+
6145
+ // src/models/certificates/index.ts
6146
+ init_esm_shims();
6147
+
6148
+ // src/models/certificates/types.ts
6149
+ init_esm_shims();
6150
+
6151
+ // src/models/lighthouse/index.ts
6152
+ init_esm_shims();
6153
+
6154
+ // src/models/lighthouse/types.ts
6155
+ init_esm_shims();
6156
+
6157
+ // src/models/limits/index.ts
6158
+ init_esm_shims();
6159
+
6160
+ // src/models/limits/types.ts
6161
+ init_esm_shims();
6162
+
6163
+ // src/models/peppol/index.ts
6164
+ init_esm_shims();
6165
+
6166
+ // src/models/peppol/types.ts
6167
+ init_esm_shims();
6168
+
6169
+ // src/models/test-data/index.ts
6170
+ init_esm_shims();
6171
+
6172
+ // src/models/test-data/types.ts
6173
+ init_esm_shims();
6174
+
6175
+ // src/models/crypto/index.ts
6176
+ init_esm_shims();
6177
+
6178
+ // src/models/crypto/types.ts
6179
+ init_esm_shims();
6180
+
6181
+ // src/models/qrcode/index.ts
6182
+ init_esm_shims();
6183
+
6184
+ // src/models/qrcode/types.ts
6185
+ init_esm_shims();
6186
+
5614
6187
  // src/models/index.ts
5615
6188
  init_document_structures();
5616
6189
 
5617
6190
  // src/services/index.ts
6191
+ init_esm_shims();
5618
6192
  init_auth();
5619
6193
  init_active_sessions();
5620
6194
  init_online_session();
@@ -5629,7 +6203,11 @@ init_limits();
5629
6203
  init_peppol();
5630
6204
  init_test_data();
5631
6205
 
6206
+ // src/builders/index.ts
6207
+ init_esm_shims();
6208
+
5632
6209
  // src/builders/auth-token-request.ts
6210
+ init_esm_shims();
5633
6211
  init_ksef_validation_error();
5634
6212
  var AuthTokenRequestBuilder = class {
5635
6213
  challenge;
@@ -5684,6 +6262,7 @@ var AuthTokenRequestBuilder = class {
5684
6262
  };
5685
6263
 
5686
6264
  // src/builders/auth-ksef-token-request.ts
6265
+ init_esm_shims();
5687
6266
  init_ksef_validation_error();
5688
6267
  var AuthKsefTokenRequestBuilder = class {
5689
6268
  challenge;
@@ -5738,6 +6317,7 @@ var AuthKsefTokenRequestBuilder = class {
5738
6317
  };
5739
6318
 
5740
6319
  // src/builders/invoice-query-filter.ts
6320
+ init_esm_shims();
5741
6321
  init_ksef_validation_error();
5742
6322
  var InvoiceQueryFilterBuilder = class {
5743
6323
  subjectType;
@@ -5834,7 +6414,11 @@ var InvoiceQueryFilterBuilder = class {
5834
6414
  }
5835
6415
  };
5836
6416
 
6417
+ // src/builders/permissions/index.ts
6418
+ init_esm_shims();
6419
+
5837
6420
  // src/builders/permissions/person-permission.ts
6421
+ init_esm_shims();
5838
6422
  init_ksef_validation_error();
5839
6423
  var PersonPermissionGrantBuilder = class {
5840
6424
  subjectIdentifier;
@@ -5884,6 +6468,7 @@ var PersonPermissionGrantBuilder = class {
5884
6468
  };
5885
6469
 
5886
6470
  // src/builders/permissions/entity-permission.ts
6471
+ init_esm_shims();
5887
6472
  init_ksef_validation_error();
5888
6473
  var EntityPermissionGrantBuilder = class {
5889
6474
  nip;
@@ -5933,6 +6518,7 @@ var EntityPermissionGrantBuilder = class {
5933
6518
  };
5934
6519
 
5935
6520
  // src/builders/permissions/authorization-permission.ts
6521
+ init_esm_shims();
5936
6522
  init_ksef_validation_error();
5937
6523
  var AuthorizationPermissionGrantBuilder = class {
5938
6524
  _subjectIdentifier;
@@ -5978,6 +6564,7 @@ var AuthorizationPermissionGrantBuilder = class {
5978
6564
  };
5979
6565
 
5980
6566
  // src/builders/batch-file.ts
6567
+ init_esm_shims();
5981
6568
  init_ksef_validation_error();
5982
6569
  import * as crypto from "crypto";
5983
6570
  var BATCH_MAX_PART_SIZE = 1e8;
@@ -6148,11 +6735,13 @@ function sha256Base64(data) {
6148
6735
  }
6149
6736
 
6150
6737
  // src/crypto/index.ts
6738
+ init_esm_shims();
6151
6739
  init_certificate_fetcher();
6152
6740
  init_cryptography_service();
6153
6741
  init_signature_service();
6154
6742
 
6155
6743
  // src/crypto/certificate-service.ts
6744
+ init_esm_shims();
6156
6745
  import * as crypto4 from "crypto";
6157
6746
  import * as x5092 from "@peculiar/x509";
6158
6747
  var CertificateService = class {
@@ -6238,9 +6827,11 @@ init_pkcs12_loader();
6238
6827
  init_auth_xml_builder();
6239
6828
 
6240
6829
  // src/qr/index.ts
6830
+ init_esm_shims();
6241
6831
  init_verification_link_service();
6242
6832
 
6243
6833
  // src/qr/qrcode-service.ts
6834
+ init_esm_shims();
6244
6835
  import * as QRCode from "qrcode";
6245
6836
  var QrCodeService = class _QrCodeService {
6246
6837
  static async generateQrCode(url, options) {
@@ -6300,10 +6891,12 @@ function escapeXml2(str) {
6300
6891
  }
6301
6892
 
6302
6893
  // src/utils/index.ts
6894
+ init_esm_shims();
6303
6895
  init_zip();
6304
6896
  init_jwt();
6305
6897
 
6306
6898
  // src/utils/hash.ts
6899
+ init_esm_shims();
6307
6900
  import crypto6 from "crypto";
6308
6901
  function sha256Base642(data) {
6309
6902
  return crypto6.createHash("sha256").update(data).digest("base64");
@@ -6315,7 +6908,11 @@ function verifyHash(data, expectedHash) {
6315
6908
  // src/utils/index.ts
6316
6909
  init_concurrency();
6317
6910
 
6911
+ // src/workflows/index.ts
6912
+ init_esm_shims();
6913
+
6318
6914
  // src/workflows/polling.ts
6915
+ init_esm_shims();
6319
6916
  async function pollUntil(action, condition, options) {
6320
6917
  const intervalMs = options?.intervalMs ?? 2e3;
6321
6918
  const maxAttempts = options?.maxAttempts ?? 60;
@@ -6333,13 +6930,18 @@ async function pollUntil(action, condition, options) {
6333
6930
  }
6334
6931
 
6335
6932
  // src/workflows/online-session-workflow.ts
6933
+ init_esm_shims();
6336
6934
  init_ksef_session_expired_error();
6337
6935
  init_auth_manager();
6338
6936
  init_online_session();
6339
6937
  init_session_status();
6340
6938
  init_document_structures();
6341
6939
 
6940
+ // src/xml/index.ts
6941
+ init_esm_shims();
6942
+
6342
6943
  // src/xml/upo-parser.ts
6944
+ init_esm_shims();
6343
6945
  init_ksef_validation_error();
6344
6946
  import { XMLParser } from "fast-xml-parser";
6345
6947
  function isRecord(value) {
@@ -6458,6 +7060,7 @@ function parseUpoXml(xml) {
6458
7060
  }
6459
7061
 
6460
7062
  // src/xml/invoice-field-extractor.ts
7063
+ init_esm_shims();
6461
7064
  import { XMLParser as XMLParser2 } from "fast-xml-parser";
6462
7065
  var invoiceParser = new XMLParser2({
6463
7066
  ignoreAttributes: false,
@@ -6498,6 +7101,7 @@ function nonEmptyString(value) {
6498
7101
  }
6499
7102
 
6500
7103
  // src/xml/xml-engine.ts
7104
+ init_esm_shims();
6501
7105
  import { XMLBuilder, XMLParser as XMLParser3 } from "fast-xml-parser";
6502
7106
  var XML_DECLARATION = '<?xml version="1.0" encoding="UTF-8"?>\n';
6503
7107
  var parser = new XMLParser3({
@@ -6551,6 +7155,7 @@ function stripBom(input) {
6551
7155
  }
6552
7156
 
6553
7157
  // src/xml/order-map.ts
7158
+ init_esm_shims();
6554
7159
  var ORDER_MAP = {
6555
7160
  Faktura: ["Naglowek", "Podmiot1", "Podmiot2", "Podmiot3", "Fa", "Stopka"],
6556
7161
  Naglowek: ["KodFormularza", "WariantFormularza", "DataWytworzeniaFa", "SystemInfo"],
@@ -6749,6 +7354,7 @@ function orderXmlObject(value, contextKey) {
6749
7354
  }
6750
7355
 
6751
7356
  // src/xml/faktura-builder.ts
7357
+ init_esm_shims();
6752
7358
  var FAKTURA_NAMESPACE = {
6753
7359
  FA2: "http://crd.gov.pl/wzor/2023/06/29/12648/",
6754
7360
  FA3: "http://crd.gov.pl/wzor/2025/06/25/13775/"
@@ -6836,6 +7442,7 @@ function isFakturaInput(input) {
6836
7442
  }
6837
7443
 
6838
7444
  // src/xml/pef-builder.ts
7445
+ init_esm_shims();
6839
7446
  init_ksef_validation_error();
6840
7447
  var PEF_NAMESPACE = {
6841
7448
  PEF: "urn:oasis:names:specification:ubl:schema:xsd:Invoice-2",
@@ -6917,6 +7524,7 @@ function buildPefXml(input, options = {}) {
6917
7524
  }
6918
7525
 
6919
7526
  // src/xml/invoice-serializer.ts
7527
+ init_esm_shims();
6920
7528
  init_ksef_validation_error();
6921
7529
  var FAKTURA_SCHEMAS = /* @__PURE__ */ new Set(["FA2", "FA3"]);
6922
7530
  var PEF_SCHEMAS = /* @__PURE__ */ new Set(["PEF", "PEF_KOR"]);
@@ -7152,6 +7760,7 @@ async function openSendAndClose(client, invoices, options) {
7152
7760
  }
7153
7761
 
7154
7762
  // src/workflows/batch-session-workflow.ts
7763
+ init_esm_shims();
7155
7764
  init_document_structures();
7156
7765
  async function uploadBatch(client, zipData, options) {
7157
7766
  if (options?.parallelism !== void 0 && (!Number.isInteger(options.parallelism) || options.parallelism < 1)) {
@@ -7290,6 +7899,7 @@ async function uploadBatchParsed(client, zipData, options) {
7290
7899
  }
7291
7900
 
7292
7901
  // src/workflows/invoice-export-workflow.ts
7902
+ init_esm_shims();
7293
7903
  init_zip();
7294
7904
  async function doExport(client, filters, options) {
7295
7905
  await client.crypto.init();
@@ -7362,7 +7972,11 @@ async function exportAndDownload(client, filters, options) {
7362
7972
  };
7363
7973
  }
7364
7974
 
7975
+ // src/workflows/incremental-export-workflow.ts
7976
+ init_esm_shims();
7977
+
7365
7978
  // src/workflows/hwm-coordinator.ts
7979
+ init_esm_shims();
7366
7980
  function updateContinuationPoint(points, subjectType, pkg) {
7367
7981
  if (pkg.isTruncated && pkg.lastPermanentStorageDate) {
7368
7982
  points[subjectType] = pkg.lastPermanentStorageDate;
@@ -7460,7 +8074,8 @@ function buildDefaultFilters(subjectType, from, to) {
7460
8074
  }
7461
8075
 
7462
8076
  // src/workflows/hwm-storage.ts
7463
- import * as fs from "fs/promises";
8077
+ init_esm_shims();
8078
+ import * as fs2 from "fs/promises";
7464
8079
  var InMemoryHwmStore = class {
7465
8080
  points = {};
7466
8081
  async load() {
@@ -7476,7 +8091,7 @@ var FileHwmStore = class {
7476
8091
  }
7477
8092
  async load() {
7478
8093
  try {
7479
- const data = await fs.readFile(this.filePath, "utf-8");
8094
+ const data = await fs2.readFile(this.filePath, "utf-8");
7480
8095
  return JSON.parse(data);
7481
8096
  } catch (err) {
7482
8097
  if (err.code === "ENOENT") {
@@ -7486,11 +8101,12 @@ var FileHwmStore = class {
7486
8101
  }
7487
8102
  }
7488
8103
  async save(points) {
7489
- await fs.writeFile(this.filePath, JSON.stringify(points, null, 2), "utf-8");
8104
+ await fs2.writeFile(this.filePath, JSON.stringify(points, null, 2), "utf-8");
7490
8105
  }
7491
8106
  };
7492
8107
 
7493
8108
  // src/workflows/auth-workflow.ts
8109
+ init_esm_shims();
7494
8110
  init_auth_xml_builder();
7495
8111
  async function authenticateWithToken(client, options) {
7496
8112
  const challenge = await client.auth.getChallenge();
@@ -7587,10 +8203,12 @@ async function authenticateWithPkcs12(client, options) {
7587
8203
  }
7588
8204
 
7589
8205
  // src/offline/index.ts
8206
+ init_esm_shims();
7590
8207
  init_deadline();
7591
8208
  init_holidays();
7592
8209
 
7593
8210
  // src/offline/storage.ts
8211
+ init_esm_shims();
7594
8212
  function matchesFilter(invoice, filter) {
7595
8213
  if (filter.status !== void 0) {
7596
8214
  const statuses = Array.isArray(filter.status) ? filter.status : [filter.status];
@@ -7629,12 +8247,13 @@ var InMemoryOfflineInvoiceStorage = class {
7629
8247
  };
7630
8248
 
7631
8249
  // src/offline/file-storage.ts
7632
- import * as fs2 from "fs/promises";
7633
- import * as path from "path";
8250
+ init_esm_shims();
8251
+ import * as fs3 from "fs/promises";
8252
+ import * as path3 from "path";
7634
8253
  import * as os from "os";
7635
8254
  function resolveDir(dir) {
7636
8255
  if (dir === "~" || dir.startsWith("~/")) {
7637
- return path.join(os.homedir(), dir.slice(1));
8256
+ return path3.join(os.homedir(), dir.slice(1));
7638
8257
  }
7639
8258
  return dir;
7640
8259
  }
@@ -7650,23 +8269,23 @@ var FileOfflineInvoiceStorage = class {
7650
8269
  this.dir = resolveDir(directory ?? "~/.ksef/offline");
7651
8270
  }
7652
8271
  async ensureDir() {
7653
- await fs2.mkdir(this.dir, { recursive: true });
8272
+ await fs3.mkdir(this.dir, { recursive: true });
7654
8273
  }
7655
8274
  filePath(id) {
7656
8275
  validateId(id);
7657
- return path.join(this.dir, `${id}.json`);
8276
+ return path3.join(this.dir, `${id}.json`);
7658
8277
  }
7659
8278
  async save(invoice) {
7660
8279
  await this.ensureDir();
7661
8280
  const file = this.filePath(invoice.id);
7662
8281
  const tmp = `${file}.tmp`;
7663
- await fs2.writeFile(tmp, JSON.stringify(invoice, null, 2));
7664
- await fs2.rename(tmp, file);
8282
+ await fs3.writeFile(tmp, JSON.stringify(invoice, null, 2));
8283
+ await fs3.rename(tmp, file);
7665
8284
  }
7666
8285
  async get(id) {
7667
8286
  const file = this.filePath(id);
7668
8287
  try {
7669
- return JSON.parse(await fs2.readFile(file, "utf-8"));
8288
+ return JSON.parse(await fs3.readFile(file, "utf-8"));
7670
8289
  } catch (err) {
7671
8290
  if (err instanceof Error && "code" in err && err.code === "ENOENT") {
7672
8291
  return null;
@@ -7678,7 +8297,7 @@ var FileOfflineInvoiceStorage = class {
7678
8297
  async list(filter) {
7679
8298
  let files;
7680
8299
  try {
7681
- files = (await fs2.readdir(this.dir)).filter((f) => f.endsWith(".json"));
8300
+ files = (await fs3.readdir(this.dir)).filter((f) => f.endsWith(".json"));
7682
8301
  } catch {
7683
8302
  return [];
7684
8303
  }
@@ -7686,7 +8305,7 @@ var FileOfflineInvoiceStorage = class {
7686
8305
  for (const file of files) {
7687
8306
  try {
7688
8307
  const data = JSON.parse(
7689
- await fs2.readFile(path.join(this.dir, file), "utf-8")
8308
+ await fs3.readFile(path3.join(this.dir, file), "utf-8")
7690
8309
  );
7691
8310
  if (!filter || matchesFilter(data, filter)) {
7692
8311
  results.push(data);
@@ -7712,7 +8331,7 @@ var FileOfflineInvoiceStorage = class {
7712
8331
  async delete(id) {
7713
8332
  const file = this.filePath(id);
7714
8333
  try {
7715
- await fs2.unlink(file);
8334
+ await fs3.unlink(file);
7716
8335
  } catch (e) {
7717
8336
  if (e instanceof Error && "code" in e && e.code !== "ENOENT") throw e;
7718
8337
  }
@@ -7741,6 +8360,7 @@ export {
7741
8360
  CertificateFingerprint,
7742
8361
  CertificateName,
7743
8362
  CertificateService,
8363
+ CircuitBreakerPolicy,
7744
8364
  CryptographyService,
7745
8365
  DEFAULT_FORM_CODE,
7746
8366
  DISCOURAGED_UNICODE_RANGES,
@@ -7750,6 +8370,7 @@ export {
7750
8370
  EntityPermissionGrantBuilder,
7751
8371
  Environment,
7752
8372
  FAKTURA_NAMESPACE,
8373
+ FA_XSD_PATHS,
7753
8374
  FORM_CODES,
7754
8375
  FORM_CODE_KEYS,
7755
8376
  FileHwmStore,
@@ -7768,6 +8389,7 @@ export {
7768
8389
  KSeFAuthStatusError,
7769
8390
  KSeFBadRequestError,
7770
8391
  KSeFBatchTimeoutError,
8392
+ KSeFCircuitOpenError,
7771
8393
  KSeFClient,
7772
8394
  KSeFError,
7773
8395
  KSeFErrorCode,
@@ -7777,6 +8399,7 @@ export {
7777
8399
  KSeFSessionExpiredError,
7778
8400
  KSeFUnauthorizedError,
7779
8401
  KSeFValidationError,
8402
+ KSeFXsdValidationError,
7780
8403
  KsefNumber,
7781
8404
  KsefNumberV35,
7782
8405
  KsefNumberV36,
@@ -7788,6 +8411,7 @@ export {
7788
8411
  OfflineInvoiceWorkflow,
7789
8412
  OnlineSessionService,
7790
8413
  PEF_NAMESPACE,
8414
+ PEF_XSD_PATHS,
7791
8415
  PERMISSION_DESCRIPTION_MAX_LENGTH,
7792
8416
  PERMISSION_DESCRIPTION_MIN_LENGTH,
7793
8417
  PeppolId,
@@ -7835,6 +8459,7 @@ export {
7835
8459
  createZip,
7836
8460
  decodeJwtPayload,
7837
8461
  deduplicateByKsefNumber,
8462
+ defaultCircuitBreakerPolicy,
7838
8463
  defaultPresignedUrlPolicy,
7839
8464
  defaultRateLimitPolicy,
7840
8465
  defaultRetryPolicy,
@@ -7871,6 +8496,7 @@ export {
7871
8496
  isValidReferenceNumber,
7872
8497
  isValidSha256Base64,
7873
8498
  isValidVatUe,
8499
+ libxmljsAvailable,
7874
8500
  nextBusinessDay,
7875
8501
  openOnlineSession,
7876
8502
  openSendAndClose,
@@ -7882,6 +8508,7 @@ export {
7882
8508
  parseXml,
7883
8509
  pollUntil,
7884
8510
  resolveOptions,
8511
+ resolveXsdFor,
7885
8512
  resumeOnlineSession,
7886
8513
  runWithConcurrency,
7887
8514
  serializeInvoiceXml,
@@ -7896,6 +8523,7 @@ export {
7896
8523
  uploadBatchStream,
7897
8524
  uploadBatchStreamParsed,
7898
8525
  validate,
8526
+ validateAgainstXsd,
7899
8527
  validateBatch,
7900
8528
  validateBusinessRules,
7901
8529
  validateCharValidity,