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.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",
@@ -73,6 +84,7 @@ var DEFAULT_API_VERSION, DEFAULT_TIMEOUT;
73
84
  var init_options = __esm({
74
85
  "src/config/options.ts"() {
75
86
  "use strict";
87
+ init_cjs_shims();
76
88
  init_environments();
77
89
  DEFAULT_API_VERSION = "v2";
78
90
  DEFAULT_TIMEOUT = 3e4;
@@ -83,6 +95,7 @@ var init_options = __esm({
83
95
  var init_config = __esm({
84
96
  "src/config/index.ts"() {
85
97
  "use strict";
98
+ init_cjs_shims();
86
99
  init_environments();
87
100
  init_options();
88
101
  }
@@ -93,6 +106,7 @@ var KSeFError;
93
106
  var init_ksef_error = __esm({
94
107
  "src/errors/ksef-error.ts"() {
95
108
  "use strict";
109
+ init_cjs_shims();
96
110
  KSeFError = class extends Error {
97
111
  constructor(message) {
98
112
  super(message);
@@ -107,6 +121,7 @@ var KSeFApiError;
107
121
  var init_ksef_api_error = __esm({
108
122
  "src/errors/ksef-api-error.ts"() {
109
123
  "use strict";
124
+ init_cjs_shims();
110
125
  init_ksef_error();
111
126
  KSeFApiError = class _KSeFApiError extends KSeFError {
112
127
  statusCode;
@@ -134,6 +149,7 @@ var KSeFRateLimitError;
134
149
  var init_ksef_rate_limit_error = __esm({
135
150
  "src/errors/ksef-rate-limit-error.ts"() {
136
151
  "use strict";
152
+ init_cjs_shims();
137
153
  init_ksef_api_error();
138
154
  KSeFRateLimitError = class _KSeFRateLimitError extends KSeFApiError {
139
155
  statusCode = 429;
@@ -184,6 +200,7 @@ var KSeFUnauthorizedError;
184
200
  var init_ksef_unauthorized_error = __esm({
185
201
  "src/errors/ksef-unauthorized-error.ts"() {
186
202
  "use strict";
203
+ init_cjs_shims();
187
204
  init_ksef_api_error();
188
205
  KSeFUnauthorizedError = class extends KSeFApiError {
189
206
  statusCode = 401;
@@ -216,6 +233,7 @@ var KSeFForbiddenError;
216
233
  var init_ksef_forbidden_error = __esm({
217
234
  "src/errors/ksef-forbidden-error.ts"() {
218
235
  "use strict";
236
+ init_cjs_shims();
219
237
  init_ksef_api_error();
220
238
  KSeFForbiddenError = class extends KSeFApiError {
221
239
  statusCode = 403;
@@ -254,6 +272,7 @@ var KSeFGoneError;
254
272
  var init_ksef_gone_error = __esm({
255
273
  "src/errors/ksef-gone-error.ts"() {
256
274
  "use strict";
275
+ init_cjs_shims();
257
276
  init_ksef_api_error();
258
277
  KSeFGoneError = class extends KSeFApiError {
259
278
  statusCode = 410;
@@ -286,6 +305,7 @@ var KSeFBadRequestError;
286
305
  var init_ksef_bad_request_error = __esm({
287
306
  "src/errors/ksef-bad-request-error.ts"() {
288
307
  "use strict";
308
+ init_cjs_shims();
289
309
  init_ksef_api_error();
290
310
  KSeFBadRequestError = class extends KSeFApiError {
291
311
  statusCode = 400;
@@ -321,6 +341,7 @@ var KSeFAuthStatusError;
321
341
  var init_ksef_auth_status_error = __esm({
322
342
  "src/errors/ksef-auth-status-error.ts"() {
323
343
  "use strict";
344
+ init_cjs_shims();
324
345
  init_ksef_error();
325
346
  KSeFAuthStatusError = class extends KSeFError {
326
347
  referenceNumber;
@@ -340,6 +361,7 @@ var KSeFSessionExpiredError;
340
361
  var init_ksef_session_expired_error = __esm({
341
362
  "src/errors/ksef-session-expired-error.ts"() {
342
363
  "use strict";
364
+ init_cjs_shims();
343
365
  init_ksef_error();
344
366
  KSeFSessionExpiredError = class extends KSeFError {
345
367
  constructor(message = "KSeF session has expired") {
@@ -359,6 +381,7 @@ var KSeFValidationError;
359
381
  var init_ksef_validation_error = __esm({
360
382
  "src/errors/ksef-validation-error.ts"() {
361
383
  "use strict";
384
+ init_cjs_shims();
362
385
  init_ksef_error();
363
386
  KSeFValidationError = class _KSeFValidationError extends KSeFError {
364
387
  details;
@@ -386,6 +409,7 @@ var KSeFErrorCode;
386
409
  var init_error_codes = __esm({
387
410
  "src/errors/error-codes.ts"() {
388
411
  "use strict";
412
+ init_cjs_shims();
389
413
  KSeFErrorCode = {
390
414
  BatchTimeout: 21208,
391
415
  DuplicateInvoice: 440
@@ -398,6 +422,7 @@ var KSeFBatchTimeoutError;
398
422
  var init_ksef_batch_timeout_error = __esm({
399
423
  "src/errors/ksef-batch-timeout-error.ts"() {
400
424
  "use strict";
425
+ init_cjs_shims();
401
426
  init_ksef_api_error();
402
427
  init_error_codes();
403
428
  KSeFBatchTimeoutError = class _KSeFBatchTimeoutError extends KSeFApiError {
@@ -417,6 +442,52 @@ var init_ksef_batch_timeout_error = __esm({
417
442
  }
418
443
  });
419
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
+
420
491
  // src/errors/assert-never.ts
421
492
  function assertNever(value) {
422
493
  throw new Error(`Unexpected value: ${String(value)}`);
@@ -424,6 +495,7 @@ function assertNever(value) {
424
495
  var init_assert_never = __esm({
425
496
  "src/errors/assert-never.ts"() {
426
497
  "use strict";
498
+ init_cjs_shims();
427
499
  }
428
500
  });
429
501
 
@@ -431,6 +503,7 @@ var init_assert_never = __esm({
431
503
  var init_errors = __esm({
432
504
  "src/errors/index.ts"() {
433
505
  "use strict";
506
+ init_cjs_shims();
434
507
  init_ksef_error();
435
508
  init_ksef_api_error();
436
509
  init_ksef_rate_limit_error();
@@ -442,6 +515,8 @@ var init_errors = __esm({
442
515
  init_ksef_session_expired_error();
443
516
  init_ksef_validation_error();
444
517
  init_ksef_batch_timeout_error();
518
+ init_ksef_circuit_open_error();
519
+ init_ksef_xsd_validation_error();
445
520
  init_error_codes();
446
521
  init_assert_never();
447
522
  }
@@ -452,6 +527,7 @@ var RouteBuilder;
452
527
  var init_route_builder = __esm({
453
528
  "src/http/route-builder.ts"() {
454
529
  "use strict";
530
+ init_cjs_shims();
455
531
  RouteBuilder = class {
456
532
  apiVersion;
457
533
  constructor(apiVersion) {
@@ -470,6 +546,7 @@ var RestRequest;
470
546
  var init_rest_request = __esm({
471
547
  "src/http/rest-request.ts"() {
472
548
  "use strict";
549
+ init_cjs_shims();
473
550
  RestRequest = class _RestRequest {
474
551
  method;
475
552
  path;
@@ -478,21 +555,21 @@ var init_rest_request = __esm({
478
555
  _query = [];
479
556
  _presigned = false;
480
557
  _skipAuthRetry = false;
481
- constructor(method, path2) {
558
+ constructor(method, path3) {
482
559
  this.method = method;
483
- this.path = path2;
560
+ this.path = path3;
484
561
  }
485
- static get(path2) {
486
- return new _RestRequest("GET", path2);
562
+ static get(path3) {
563
+ return new _RestRequest("GET", path3);
487
564
  }
488
- static post(path2) {
489
- return new _RestRequest("POST", path2);
565
+ static post(path3) {
566
+ return new _RestRequest("POST", path3);
490
567
  }
491
- static put(path2) {
492
- return new _RestRequest("PUT", path2);
568
+ static put(path3) {
569
+ return new _RestRequest("PUT", path3);
493
570
  }
494
- static delete(path2) {
495
- return new _RestRequest("DELETE", path2);
571
+ static delete(path3) {
572
+ return new _RestRequest("DELETE", path3);
496
573
  }
497
574
  body(data) {
498
575
  this._body = data;
@@ -546,6 +623,7 @@ var defaultTransport;
546
623
  var init_transport = __esm({
547
624
  "src/http/transport.ts"() {
548
625
  "use strict";
626
+ init_cjs_shims();
549
627
  defaultTransport = (url, init) => fetch(url, init);
550
628
  }
551
629
  });
@@ -595,6 +673,7 @@ var RETRYABLE_ERROR_CODES;
595
673
  var init_retry_policy = __esm({
596
674
  "src/http/retry-policy.ts"() {
597
675
  "use strict";
676
+ init_cjs_shims();
598
677
  RETRYABLE_ERROR_CODES = /* @__PURE__ */ new Set([
599
678
  "ECONNRESET",
600
679
  "ECONNREFUSED",
@@ -685,6 +764,7 @@ var BLOCKED_PARAMS;
685
764
  var init_presigned_url_policy = __esm({
686
765
  "src/http/presigned-url-policy.ts"() {
687
766
  "use strict";
767
+ init_cjs_shims();
688
768
  init_ksef_validation_error();
689
769
  BLOCKED_PARAMS = ["redirect", "callback", "return_url", "next"];
690
770
  }
@@ -716,6 +796,7 @@ var import_consola, RestClient;
716
796
  var init_rest_client = __esm({
717
797
  "src/http/rest-client.ts"() {
718
798
  "use strict";
799
+ init_cjs_shims();
719
800
  import_consola = require("consola");
720
801
  init_ksef_api_error();
721
802
  init_ksef_rate_limit_error();
@@ -735,6 +816,7 @@ var init_rest_client = __esm({
735
816
  transport;
736
817
  retryPolicy;
737
818
  rateLimitPolicy;
819
+ circuitBreakerPolicy;
738
820
  authManager;
739
821
  presignedUrlPolicy;
740
822
  constructor(options, config) {
@@ -743,6 +825,7 @@ var init_rest_client = __esm({
743
825
  this.transport = config?.transport ?? defaultTransport;
744
826
  this.retryPolicy = config?.retryPolicy ?? defaultRetryPolicy();
745
827
  this.rateLimitPolicy = config?.rateLimitPolicy ?? null;
828
+ this.circuitBreakerPolicy = config?.circuitBreakerPolicy ?? null;
746
829
  this.authManager = config?.authManager;
747
830
  this.presignedUrlPolicy = config?.presignedUrlPolicy;
748
831
  }
@@ -767,18 +850,32 @@ var init_rest_client = __esm({
767
850
  if (request.isPresigned() && this.presignedUrlPolicy) {
768
851
  validatePresignedUrl(url, this.presignedUrlPolicy);
769
852
  }
853
+ let ownsProbeSlot = false;
854
+ if (this.circuitBreakerPolicy) {
855
+ const claimed = this.circuitBreakerPolicy.ensureClosed(request.path);
856
+ if (claimed) ownsProbeSlot = true;
857
+ }
770
858
  if (this.rateLimitPolicy) {
771
- 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
+ }
772
865
  }
773
866
  let lastError;
774
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
+ }
775
872
  try {
776
- const response = await this.doRequest(request, url);
873
+ let response = await this.doRequest(request, url);
777
874
  if (response.status === 401 && this.authManager && attempt === 0 && !request.isSkipAuthRetry()) {
778
875
  const newToken = await this.authManager.onUnauthorized();
779
876
  if (newToken) {
780
877
  import_consola.consola.debug("Auth token refreshed, retrying request");
781
- return this.doRequest(request, url, newToken);
878
+ response = await this.doRequest(request, url, newToken);
782
879
  }
783
880
  }
784
881
  if (isRetryableStatus(response.status, this.retryPolicy) && attempt < this.retryPolicy.maxRetries) {
@@ -788,10 +885,17 @@ var init_rest_client = __esm({
788
885
  import_consola.consola.debug(`Retryable ${response.status}, attempt ${attempt + 1}/${this.retryPolicy.maxRetries}, waiting ${Math.round(delayMs)}ms`);
789
886
  await sleep(delayMs);
790
887
  if (is429 && this.rateLimitPolicy) {
791
- 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
+ }
792
895
  }
793
896
  continue;
794
897
  }
898
+ this.recordCircuitOutcome(request.path, response.status);
795
899
  return response;
796
900
  } catch (error) {
797
901
  lastError = error;
@@ -801,11 +905,22 @@ var init_rest_client = __esm({
801
905
  await sleep(delayMs);
802
906
  continue;
803
907
  }
908
+ if (isRetryableError(error, this.retryPolicy) || ownsProbeSlot) {
909
+ this.circuitBreakerPolicy?.recordFailure(request.path);
910
+ }
804
911
  throw error;
805
912
  }
806
913
  }
807
914
  throw lastError;
808
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
+ }
809
924
  async doRequest(request, url, overrideToken) {
810
925
  const headers = {
811
926
  ...this.options.customHeaders,
@@ -841,9 +956,9 @@ var init_rest_client = __esm({
841
956
  return response;
842
957
  }
843
958
  buildUrl(request) {
844
- const path2 = this.routeBuilder.build(request.path);
959
+ const path3 = this.routeBuilder.build(request.path);
845
960
  const base = this.options.baseUrl;
846
- const url = new URL(`${base}${path2}`);
961
+ const url = new URL(`${base}${path3}`);
847
962
  const query = request.getQuery();
848
963
  for (const [key, value] of query) {
849
964
  url.searchParams.append(key, value);
@@ -927,6 +1042,7 @@ var Routes;
927
1042
  var init_routes = __esm({
928
1043
  "src/http/routes.ts"() {
929
1044
  "use strict";
1045
+ init_cjs_shims();
930
1046
  Routes = {
931
1047
  TestData: {
932
1048
  createSubject: "testdata/subject",
@@ -1059,6 +1175,7 @@ var TokenBucket, RateLimitPolicy;
1059
1175
  var init_rate_limit_policy = __esm({
1060
1176
  "src/http/rate-limit-policy.ts"() {
1061
1177
  "use strict";
1178
+ init_cjs_shims();
1062
1179
  TokenBucket = class {
1063
1180
  tokens;
1064
1181
  maxTokens;
@@ -1119,11 +1236,151 @@ var init_rate_limit_policy = __esm({
1119
1236
  }
1120
1237
  });
1121
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
+
1122
1378
  // src/http/auth-manager.ts
1123
1379
  var DefaultAuthManager;
1124
1380
  var init_auth_manager = __esm({
1125
1381
  "src/http/auth-manager.ts"() {
1126
1382
  "use strict";
1383
+ init_cjs_shims();
1127
1384
  DefaultAuthManager = class {
1128
1385
  token;
1129
1386
  refreshToken;
@@ -1164,6 +1421,7 @@ var KSEF_FEATURE_HEADER, UpoVersion, ENFORCE_XADES_COMPLIANCE;
1164
1421
  var init_ksef_feature = __esm({
1165
1422
  "src/http/ksef-feature.ts"() {
1166
1423
  "use strict";
1424
+ init_cjs_shims();
1167
1425
  KSEF_FEATURE_HEADER = "X-KSeF-Feature";
1168
1426
  UpoVersion = {
1169
1427
  /** UPO v4-2 format (default before 2026-01-05). */
@@ -1263,6 +1521,7 @@ var NIP_PATTERN_CORE, VAT_UE_PATTERN_CORE, Nip, VatUe, NipVatUe, InternalId, Pep
1263
1521
  var init_patterns = __esm({
1264
1522
  "src/validation/patterns.ts"() {
1265
1523
  "use strict";
1524
+ init_cjs_shims();
1266
1525
  NIP_PATTERN_CORE = "[1-9]((\\d[1-9])|([1-9]\\d))\\d{7}";
1267
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}))";
1268
1527
  Nip = new RegExp(`^${NIP_PATTERN_CORE}$`);
@@ -1379,6 +1638,7 @@ var import_xmldom;
1379
1638
  var init_xml_to_object = __esm({
1380
1639
  "src/validation/xml-to-object.ts"() {
1381
1640
  "use strict";
1641
+ init_cjs_shims();
1382
1642
  import_xmldom = require("@xmldom/xmldom");
1383
1643
  }
1384
1644
  });
@@ -1392,6 +1652,7 @@ var import_zod, TKodFormularza, TDataCzas, TZnakowy, TNaglowek, TKodyKrajowUE, T
1392
1652
  var init_fa3 = __esm({
1393
1653
  "src/validation/schemas/fa3.ts"() {
1394
1654
  "use strict";
1655
+ init_cjs_shims();
1395
1656
  import_zod = require("zod");
1396
1657
  TKodFormularza = import_zod.z.literal("FA");
1397
1658
  TDataCzas = import_zod.z.string();
@@ -1802,6 +2063,7 @@ var import_zod2, TKodFormularza2, TDataCzas2, TZnakowy3, TNaglowek2, TKodyKrajow
1802
2063
  var init_fa2 = __esm({
1803
2064
  "src/validation/schemas/fa2.ts"() {
1804
2065
  "use strict";
2066
+ init_cjs_shims();
1805
2067
  import_zod2 = require("zod");
1806
2068
  TKodFormularza2 = import_zod2.z.literal("FA");
1807
2069
  TDataCzas2 = import_zod2.z.string();
@@ -2196,6 +2458,7 @@ var import_zod3, TKodFormularza3, TDataCzas3, TZnakowy4, TNaglowek3, TNrNIP3, TZ
2196
2458
  var init_rr1_v11e = __esm({
2197
2459
  "src/validation/schemas/rr1-v11e.ts"() {
2198
2460
  "use strict";
2461
+ init_cjs_shims();
2199
2462
  import_zod3 = require("zod");
2200
2463
  TKodFormularza3 = import_zod3.z.literal("FA_RR");
2201
2464
  TDataCzas3 = import_zod3.z.string();
@@ -2401,6 +2664,7 @@ var import_zod4, TKodFormularza4, TDataCzas4, TZnakowy5, TNaglowek4, TNrNIP4, TZ
2401
2664
  var init_rr1_v10e = __esm({
2402
2665
  "src/validation/schemas/rr1-v10e.ts"() {
2403
2666
  "use strict";
2667
+ init_cjs_shims();
2404
2668
  import_zod4 = require("zod");
2405
2669
  TKodFormularza4 = import_zod4.z.literal("FA_RR");
2406
2670
  TDataCzas4 = import_zod4.z.string();
@@ -2606,6 +2870,7 @@ var import_zod5, InvoiceType, PEF3Schema;
2606
2870
  var init_pef3 = __esm({
2607
2871
  "src/validation/schemas/pef3.ts"() {
2608
2872
  "use strict";
2873
+ init_cjs_shims();
2609
2874
  import_zod5 = require("zod");
2610
2875
  InvoiceType = import_zod5.z.object({
2611
2876
  "UBLExtensions": import_zod5.z.any().optional(),
@@ -2676,6 +2941,7 @@ var import_zod6, CreditNoteType, PEF_KOR3Schema;
2676
2941
  var init_pef_kor3 = __esm({
2677
2942
  "src/validation/schemas/pef-kor3.ts"() {
2678
2943
  "use strict";
2944
+ init_cjs_shims();
2679
2945
  import_zod6 = require("zod");
2680
2946
  CreditNoteType = import_zod6.z.object({
2681
2947
  "UBLExtensions": import_zod6.z.any().optional(),
@@ -2739,6 +3005,7 @@ var NAMESPACE_MAP;
2739
3005
  var init_schemas = __esm({
2740
3006
  "src/validation/schemas/index.ts"() {
2741
3007
  "use strict";
3008
+ init_cjs_shims();
2742
3009
  init_fa3();
2743
3010
  init_fa2();
2744
3011
  init_rr1_v11e();
@@ -2795,6 +3062,7 @@ var ROOT_ELEMENT_MAP, schemaCache, SchemaRegistry;
2795
3062
  var init_schema_registry = __esm({
2796
3063
  "src/validation/schema-registry.ts"() {
2797
3064
  "use strict";
3065
+ init_cjs_shims();
2798
3066
  init_schemas();
2799
3067
  ROOT_ELEMENT_MAP = {
2800
3068
  Invoice: "PEF3",
@@ -2920,6 +3188,7 @@ var DISCOURAGED_UNICODE_RANGES, PI_TARGET_RE;
2920
3188
  var init_char_validity = __esm({
2921
3189
  "src/validation/char-validity.ts"() {
2922
3190
  "use strict";
3191
+ init_cjs_shims();
2923
3192
  DISCOURAGED_UNICODE_RANGES = [
2924
3193
  [127, 132],
2925
3194
  [134, 159],
@@ -3002,11 +3271,11 @@ async function validateSchema(xml, options, _parsed) {
3002
3271
  const prefix = rootElement ? `/${rootElement}/` : "/";
3003
3272
  const validationErrors = result.error.issues.map((issue) => {
3004
3273
  const zodPath = issue.path.join("/");
3005
- const path2 = zodPath ? `${prefix}${zodPath}` : rootElement ? `/${rootElement}` : void 0;
3274
+ const path3 = zodPath ? `${prefix}${zodPath}` : rootElement ? `/${rootElement}` : void 0;
3006
3275
  return {
3007
3276
  code: mapZodErrorCode(issue),
3008
3277
  message: issue.message,
3009
- path: path2
3278
+ path: path3
3010
3279
  };
3011
3280
  });
3012
3281
  return { valid: false, schemaType, errors: validationErrors };
@@ -3046,9 +3315,9 @@ function validateBusinessRules(xml, _parsed) {
3046
3315
  collectDateErrors(object, rootElement, errors);
3047
3316
  return { valid: errors.length === 0, schemaType, errors };
3048
3317
  }
3049
- function collectNipPeselErrors(obj, path2, errors) {
3318
+ function collectNipPeselErrors(obj, path3, errors) {
3050
3319
  for (const [key, value] of Object.entries(obj)) {
3051
- const currentPath = path2 ? `${path2}/${key}` : key;
3320
+ const currentPath = path3 ? `${path3}/${key}` : key;
3052
3321
  if (key === "NIP" && typeof value === "string") {
3053
3322
  if (!isValidNip(value)) {
3054
3323
  errors.push({
@@ -3127,6 +3396,7 @@ function batchValidationDetails(batch) {
3127
3396
  var init_invoice_validator = __esm({
3128
3397
  "src/validation/invoice-validator.ts"() {
3129
3398
  "use strict";
3399
+ init_cjs_shims();
3130
3400
  init_xml_to_object();
3131
3401
  init_schema_registry();
3132
3402
  init_char_validity();
@@ -3139,6 +3409,7 @@ var SystemCode, FORM_CODES, DEFAULT_FORM_CODE, INVOICE_TYPES_BY_SYSTEM_CODE, FOR
3139
3409
  var init_types = __esm({
3140
3410
  "src/models/document-structures/types.ts"() {
3141
3411
  "use strict";
3412
+ init_cjs_shims();
3142
3413
  SystemCode = {
3143
3414
  FA_2: "FA (2)",
3144
3415
  FA_3: "FA (3)",
@@ -3191,6 +3462,7 @@ var SYSTEM_CODE_TO_FORM_CODE, ALL_FORM_CODES, BATCH_DISALLOWED_SYSTEM_CODES;
3191
3462
  var init_helpers = __esm({
3192
3463
  "src/models/document-structures/helpers.ts"() {
3193
3464
  "use strict";
3465
+ init_cjs_shims();
3194
3466
  init_types();
3195
3467
  SYSTEM_CODE_TO_FORM_CODE = {
3196
3468
  [SystemCode.FA_2]: FORM_CODES.FA_2,
@@ -3211,6 +3483,7 @@ var init_helpers = __esm({
3211
3483
  var init_document_structures = __esm({
3212
3484
  "src/models/document-structures/index.ts"() {
3213
3485
  "use strict";
3486
+ init_cjs_shims();
3214
3487
  init_types();
3215
3488
  init_helpers();
3216
3489
  }
@@ -3221,6 +3494,7 @@ var AuthService;
3221
3494
  var init_auth = __esm({
3222
3495
  "src/services/auth.ts"() {
3223
3496
  "use strict";
3497
+ init_cjs_shims();
3224
3498
  init_ksef_feature();
3225
3499
  init_rest_request();
3226
3500
  init_routes();
@@ -3271,6 +3545,7 @@ var ActiveSessionsService;
3271
3545
  var init_active_sessions = __esm({
3272
3546
  "src/services/active-sessions.ts"() {
3273
3547
  "use strict";
3548
+ init_cjs_shims();
3274
3549
  init_rest_request();
3275
3550
  init_routes();
3276
3551
  ActiveSessionsService = class {
@@ -3302,6 +3577,7 @@ var OnlineSessionService;
3302
3577
  var init_online_session = __esm({
3303
3578
  "src/services/online-session.ts"() {
3304
3579
  "use strict";
3580
+ init_cjs_shims();
3305
3581
  init_ksef_feature();
3306
3582
  init_rest_request();
3307
3583
  init_routes();
@@ -3354,6 +3630,7 @@ async function runWithConcurrency(tasks, parallelism) {
3354
3630
  var init_concurrency = __esm({
3355
3631
  "src/utils/concurrency.ts"() {
3356
3632
  "use strict";
3633
+ init_cjs_shims();
3357
3634
  }
3358
3635
  });
3359
3636
 
@@ -3362,6 +3639,7 @@ var BatchSessionService;
3362
3639
  var init_batch_session = __esm({
3363
3640
  "src/services/batch-session.ts"() {
3364
3641
  "use strict";
3642
+ init_cjs_shims();
3365
3643
  init_ksef_feature();
3366
3644
  init_rest_request();
3367
3645
  init_routes();
@@ -3466,6 +3744,7 @@ var SessionStatusService;
3466
3744
  var init_session_status = __esm({
3467
3745
  "src/services/session-status.ts"() {
3468
3746
  "use strict";
3747
+ init_cjs_shims();
3469
3748
  init_rest_request();
3470
3749
  init_routes();
3471
3750
  SessionStatusService = class {
@@ -3552,6 +3831,7 @@ var InvoiceDownloadService;
3552
3831
  var init_invoice_download = __esm({
3553
3832
  "src/services/invoice-download.ts"() {
3554
3833
  "use strict";
3834
+ init_cjs_shims();
3555
3835
  init_rest_request();
3556
3836
  init_routes();
3557
3837
  InvoiceDownloadService = class {
@@ -3594,6 +3874,7 @@ var PermissionsService;
3594
3874
  var init_permissions = __esm({
3595
3875
  "src/services/permissions.ts"() {
3596
3876
  "use strict";
3877
+ init_cjs_shims();
3597
3878
  init_ksef_validation_error();
3598
3879
  init_rest_request();
3599
3880
  init_routes();
@@ -3786,6 +4067,7 @@ function parseKSeFTokenContext(token) {
3786
4067
  var init_jwt = __esm({
3787
4068
  "src/utils/jwt.ts"() {
3788
4069
  "use strict";
4070
+ init_cjs_shims();
3789
4071
  }
3790
4072
  });
3791
4073
 
@@ -3797,6 +4079,7 @@ var TOKEN_AUTHOR_IDENTIFIER_TYPES, TokenService;
3797
4079
  var init_tokens = __esm({
3798
4080
  "src/services/tokens.ts"() {
3799
4081
  "use strict";
4082
+ init_cjs_shims();
3800
4083
  init_rest_request();
3801
4084
  init_routes();
3802
4085
  init_jwt();
@@ -3917,6 +4200,7 @@ var CertificateApiService;
3917
4200
  var init_certificates = __esm({
3918
4201
  "src/services/certificates.ts"() {
3919
4202
  "use strict";
4203
+ init_cjs_shims();
3920
4204
  init_rest_request();
3921
4205
  init_routes();
3922
4206
  CertificateApiService = class {
@@ -3969,6 +4253,7 @@ var LighthouseService;
3969
4253
  var init_lighthouse = __esm({
3970
4254
  "src/services/lighthouse.ts"() {
3971
4255
  "use strict";
4256
+ init_cjs_shims();
3972
4257
  init_errors();
3973
4258
  LighthouseService = class {
3974
4259
  lighthouseUrl;
@@ -3977,20 +4262,20 @@ var init_lighthouse = __esm({
3977
4262
  this.lighthouseUrl = options.lighthouseUrl;
3978
4263
  this.timeout = options.timeout;
3979
4264
  }
3980
- async fetchJson(path2) {
4265
+ async fetchJson(path3) {
3981
4266
  if (!this.lighthouseUrl) {
3982
4267
  throw new KSeFError(
3983
4268
  "Lighthouse API is not available for the DEMO environment. Use TEST or PROD instead."
3984
4269
  );
3985
4270
  }
3986
- const response = await fetch(`${this.lighthouseUrl}${path2}`, {
4271
+ const response = await fetch(`${this.lighthouseUrl}${path3}`, {
3987
4272
  headers: { Accept: "application/json" },
3988
4273
  signal: AbortSignal.timeout(this.timeout)
3989
4274
  });
3990
4275
  if (!response.ok) {
3991
4276
  const body = await response.text();
3992
4277
  throw new KSeFError(
3993
- `Lighthouse ${path2} failed: HTTP ${response.status} \u2014 ${body}`
4278
+ `Lighthouse ${path3} failed: HTTP ${response.status} \u2014 ${body}`
3994
4279
  );
3995
4280
  }
3996
4281
  return await response.json();
@@ -4011,6 +4296,7 @@ var LimitsService;
4011
4296
  var init_limits = __esm({
4012
4297
  "src/services/limits.ts"() {
4013
4298
  "use strict";
4299
+ init_cjs_shims();
4014
4300
  init_rest_request();
4015
4301
  init_routes();
4016
4302
  LimitsService = class {
@@ -4042,6 +4328,7 @@ var PeppolService;
4042
4328
  var init_peppol = __esm({
4043
4329
  "src/services/peppol.ts"() {
4044
4330
  "use strict";
4331
+ init_cjs_shims();
4045
4332
  init_rest_request();
4046
4333
  init_routes();
4047
4334
  PeppolService = class {
@@ -4065,6 +4352,7 @@ var TestDataService;
4065
4352
  var init_test_data = __esm({
4066
4353
  "src/services/test-data.ts"() {
4067
4354
  "use strict";
4355
+ init_cjs_shims();
4068
4356
  init_rest_request();
4069
4357
  init_routes();
4070
4358
  init_ksef_error();
@@ -4184,6 +4472,7 @@ var CertificateFetcher;
4184
4472
  var init_certificate_fetcher = __esm({
4185
4473
  "src/crypto/certificate-fetcher.ts"() {
4186
4474
  "use strict";
4475
+ init_cjs_shims();
4187
4476
  init_rest_request();
4188
4477
  init_routes();
4189
4478
  CertificateFetcher = class {
@@ -4277,6 +4566,7 @@ var crypto2, x509, CryptographyService;
4277
4566
  var init_cryptography_service = __esm({
4278
4567
  "src/crypto/cryptography-service.ts"() {
4279
4568
  "use strict";
4569
+ init_cjs_shims();
4280
4570
  crypto2 = __toESM(require("crypto"), 1);
4281
4571
  x509 = __toESM(require("@peculiar/x509"), 1);
4282
4572
  CryptographyService = class {
@@ -4513,6 +4803,40 @@ var signature_service_exports = {};
4513
4803
  __export(signature_service_exports, {
4514
4804
  SignatureService: () => SignatureService
4515
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
+ }
4516
4840
  function extractDerFromPem(pem) {
4517
4841
  const base64 = pem.replace(/-----BEGIN [A-Z\s]+-----/g, "").replace(/-----END [A-Z\s]+-----/g, "").replace(/\s+/g, "");
4518
4842
  return Buffer.from(base64, "base64");
@@ -4527,12 +4851,12 @@ function canonicalize(elem) {
4527
4851
  const c14n = new import_xml_crypto.ExclusiveCanonicalization();
4528
4852
  return c14n.process(elem, {});
4529
4853
  }
4530
- function computeRootDigest(doc) {
4854
+ function computeRootDigest(doc, hashName) {
4531
4855
  const root = doc.documentElement;
4532
4856
  const canonical = canonicalize(root);
4533
- return crypto3.createHash("sha256").update(canonical, "utf-8").digest("base64");
4857
+ return crypto3.createHash(hashName).update(canonical, "utf-8").digest("base64");
4534
4858
  }
4535
- function computeSignedPropertiesDigest(qualifyingPropertiesXml) {
4859
+ function computeSignedPropertiesDigest(qualifyingPropertiesXml, hashName) {
4536
4860
  const parser2 = new import_xmldom2.DOMParser();
4537
4861
  const qpDoc = parser2.parseFromString(qualifyingPropertiesXml, "text/xml");
4538
4862
  const signedProps = findElementByLocalName(qpDoc.documentElement, "SignedProperties");
@@ -4540,9 +4864,9 @@ function computeSignedPropertiesDigest(qualifyingPropertiesXml) {
4540
4864
  throw new Error("SignedProperties element not found in QualifyingProperties");
4541
4865
  }
4542
4866
  const canonical = canonicalize(signedProps);
4543
- return crypto3.createHash("sha256").update(canonical, "utf-8").digest("base64");
4867
+ return crypto3.createHash(hashName).update(canonical, "utf-8").digest("base64");
4544
4868
  }
4545
- function buildSignedInfo(signatureAlgorithm, rootDigest, signedPropertiesDigest) {
4869
+ function buildSignedInfo(signatureAlgorithm, digestAlgorithm, rootDigest, signedPropertiesDigest) {
4546
4870
  return [
4547
4871
  `<ds:SignedInfo xmlns:ds="${DS_NS}">`,
4548
4872
  `<ds:CanonicalizationMethod Algorithm="${EXC_C14N_ALGORITHM}"/>`,
@@ -4553,7 +4877,7 @@ function buildSignedInfo(signatureAlgorithm, rootDigest, signedPropertiesDigest)
4553
4877
  `<ds:Transform Algorithm="${ENVELOPED_SIGNATURE_TRANSFORM}"/>`,
4554
4878
  `<ds:Transform Algorithm="${EXC_C14N_ALGORITHM}"/>`,
4555
4879
  `</ds:Transforms>`,
4556
- `<ds:DigestMethod Algorithm="${SHA256_DIGEST_METHOD}"/>`,
4880
+ `<ds:DigestMethod Algorithm="${digestAlgorithm}"/>`,
4557
4881
  `<ds:DigestValue>${rootDigest}</ds:DigestValue>`,
4558
4882
  `</ds:Reference>`,
4559
4883
  // Reference 2: SignedProperties
@@ -4561,22 +4885,22 @@ function buildSignedInfo(signatureAlgorithm, rootDigest, signedPropertiesDigest)
4561
4885
  `<ds:Transforms>`,
4562
4886
  `<ds:Transform Algorithm="${EXC_C14N_ALGORITHM}"/>`,
4563
4887
  `</ds:Transforms>`,
4564
- `<ds:DigestMethod Algorithm="${SHA256_DIGEST_METHOD}"/>`,
4888
+ `<ds:DigestMethod Algorithm="${digestAlgorithm}"/>`,
4565
4889
  `<ds:DigestValue>${signedPropertiesDigest}</ds:DigestValue>`,
4566
4890
  `</ds:Reference>`,
4567
4891
  `</ds:SignedInfo>`
4568
4892
  ].join("");
4569
4893
  }
4570
- function computeSignatureValue(canonicalSignedInfo, privateKey, isEc) {
4894
+ function computeSignatureValue(canonicalSignedInfo, privateKey, isEc, hashName) {
4571
4895
  const data = Buffer.from(canonicalSignedInfo, "utf-8");
4572
4896
  let signature;
4573
4897
  if (isEc) {
4574
- signature = crypto3.sign("sha256", data, {
4898
+ signature = crypto3.sign(hashName, data, {
4575
4899
  key: privateKey,
4576
4900
  dsaEncoding: "ieee-p1363"
4577
4901
  });
4578
4902
  } else {
4579
- signature = crypto3.sign("sha256", data, privateKey);
4903
+ signature = crypto3.sign(hashName, data, privateKey);
4580
4904
  }
4581
4905
  return signature.toString("base64");
4582
4906
  }
@@ -4597,7 +4921,7 @@ function buildSignatureElement(signedInfoXml, signatureValue, certBase64, qualif
4597
4921
  `</ds:Signature>`
4598
4922
  ].join("");
4599
4923
  }
4600
- function buildQualifyingProperties(signatureId, signedPropertiesId, certDigest, issuerName, serialNumber, signingTime) {
4924
+ function buildQualifyingProperties(signatureId, signedPropertiesId, certDigest, issuerName, serialNumber, signingTime, digestAlgorithm) {
4601
4925
  return [
4602
4926
  `<xades:QualifyingProperties`,
4603
4927
  ` Target="#${signatureId}"`,
@@ -4609,7 +4933,7 @@ function buildQualifyingProperties(signatureId, signedPropertiesId, certDigest,
4609
4933
  `<xades:SigningCertificate>`,
4610
4934
  `<xades:Cert>`,
4611
4935
  `<xades:CertDigest>`,
4612
- `<DigestMethod Algorithm="${SHA256_DIGEST_METHOD}"/>`,
4936
+ `<DigestMethod Algorithm="${digestAlgorithm}"/>`,
4613
4937
  `<DigestValue>${certDigest}</DigestValue>`,
4614
4938
  `</xades:CertDigest>`,
4615
4939
  `<xades:IssuerSerial>`,
@@ -4645,21 +4969,31 @@ function wrapBase64(base64) {
4645
4969
  }
4646
4970
  return lines.join("\n");
4647
4971
  }
4648
- 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;
4649
4973
  var init_signature_service = __esm({
4650
4974
  "src/crypto/signature-service.ts"() {
4651
4975
  "use strict";
4976
+ init_cjs_shims();
4652
4977
  crypto3 = __toESM(require("crypto"), 1);
4653
4978
  import_xml_crypto = require("xml-crypto");
4654
4979
  import_xmldom2 = require("@xmldom/xmldom");
4980
+ init_ksef_error();
4655
4981
  XADES_NS = "http://uri.etsi.org/01903/v1.3.2#";
4656
4982
  DS_NS = "http://www.w3.org/2000/09/xmldsig#";
4657
4983
  SIGNED_PROPERTIES_TYPE = "http://uri.etsi.org/01903#SignedProperties";
4658
- SHA256_DIGEST_METHOD = "http://www.w3.org/2001/04/xmlenc#sha256";
4659
4984
  EXC_C14N_ALGORITHM = "http://www.w3.org/2001/10/xml-exc-c14n#";
4660
4985
  ENVELOPED_SIGNATURE_TRANSFORM = "http://www.w3.org/2000/09/xmldsig#enveloped-signature";
4661
- RSA_SHA256_SIGNATURE = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256";
4662
- 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";
4663
4997
  CLOCK_SKEW_BUFFER_MS = -6e4;
4664
4998
  SIGNATURE_ID = "Signature";
4665
4999
  SIGNED_PROPERTIES_ID = "SignedProperties";
@@ -4679,15 +5013,21 @@ var init_signature_service = __esm({
4679
5013
  }
4680
5014
  const certDer = extractDerFromPem(certPem);
4681
5015
  const certBase64 = certDer.toString("base64");
4682
- const certDigest = crypto3.createHash("sha256").update(certDer).digest("base64");
4683
5016
  const x5093 = new crypto3.X509Certificate(certPem);
4684
5017
  const issuerName = normalizeIssuerDn(x5093.issuer);
4685
5018
  const serialNumber = hexSerialToDecimal(x5093.serialNumber);
4686
5019
  const privateKey = crypto3.createPrivateKey(
4687
5020
  passphrase ? { key: privateKeyPem, format: "pem", passphrase } : privateKeyPem
4688
5021
  );
4689
- const isEc = privateKey.asymmetricKeyType === "ec";
4690
- 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");
4691
5031
  const signingTime = new Date(Date.now() + CLOCK_SKEW_BUFFER_MS).toISOString();
4692
5032
  const parser2 = new import_xmldom2.DOMParser();
4693
5033
  const doc = parser2.parseFromString(xml, "text/xml");
@@ -4701,12 +5041,17 @@ var init_signature_service = __esm({
4701
5041
  certDigest,
4702
5042
  issuerName,
4703
5043
  serialNumber,
4704
- signingTime
5044
+ signingTime,
5045
+ algo.digestUri
5046
+ );
5047
+ const rootDigest = computeRootDigest(doc, algo.nodeHashName);
5048
+ const signedPropertiesDigest = computeSignedPropertiesDigest(
5049
+ qualifyingPropertiesXml,
5050
+ algo.nodeHashName
4705
5051
  );
4706
- const rootDigest = computeRootDigest(doc);
4707
- const signedPropertiesDigest = computeSignedPropertiesDigest(qualifyingPropertiesXml);
4708
5052
  const signedInfoXml = buildSignedInfo(
4709
- signatureAlgorithm,
5053
+ algo.signatureUri,
5054
+ algo.digestUri,
4710
5055
  rootDigest,
4711
5056
  signedPropertiesDigest
4712
5057
  );
@@ -4715,7 +5060,8 @@ var init_signature_service = __esm({
4715
5060
  const signatureValue = computeSignatureValue(
4716
5061
  canonicalSignedInfo,
4717
5062
  privateKey,
4718
- isEc
5063
+ isEc,
5064
+ algo.nodeHashName
4719
5065
  );
4720
5066
  const signatureXml = buildSignatureElement(
4721
5067
  signedInfoXml,
@@ -4741,6 +5087,7 @@ var import_node_forge, Pkcs12Loader;
4741
5087
  var init_pkcs12_loader = __esm({
4742
5088
  "src/crypto/pkcs12-loader.ts"() {
4743
5089
  "use strict";
5090
+ init_cjs_shims();
4744
5091
  import_node_forge = __toESM(require("node-forge"), 1);
4745
5092
  Pkcs12Loader = class {
4746
5093
  static load(p12, password) {
@@ -4810,6 +5157,7 @@ var AUTH_TOKEN_REQUEST_NS;
4810
5157
  var init_auth_xml_builder = __esm({
4811
5158
  "src/crypto/auth-xml-builder.ts"() {
4812
5159
  "use strict";
5160
+ init_cjs_shims();
4813
5161
  AUTH_TOKEN_REQUEST_NS = "http://ksef.mf.gov.pl/auth/token/2.0";
4814
5162
  }
4815
5163
  });
@@ -4819,6 +5167,7 @@ var import_node_crypto, VerificationLinkService;
4819
5167
  var init_verification_link_service = __esm({
4820
5168
  "src/qr/verification-link-service.ts"() {
4821
5169
  "use strict";
5170
+ init_cjs_shims();
4822
5171
  import_node_crypto = __toESM(require("crypto"), 1);
4823
5172
  VerificationLinkService = class {
4824
5173
  constructor(baseQrUrl) {
@@ -4841,11 +5190,11 @@ var init_verification_link_service = __esm({
4841
5190
  * Build certificate verification URL (Code II).
4842
5191
  * Format: {baseQrUrl}/certificate/{contextType}/{contextId}/{sellerNip}/{certSerial}/{hash_base64url}/{signature_base64url}
4843
5192
  */
4844
- buildCertificateVerificationUrl(contextType, contextId, sellerNip, certSerial, invoiceHashBase64, privateKeyPem) {
5193
+ buildCertificateVerificationUrl(contextType, contextId, sellerNip, certSerial, invoiceHashBase64, privateKeyPem, privateKeyPassword) {
4845
5194
  const hashBase64Url = this.base64ToBase64Url(invoiceHashBase64);
4846
5195
  const pathWithoutSignature = `${this.baseQrUrl}/certificate/${contextType}/${contextId}/${sellerNip}/${certSerial}/${hashBase64Url}`;
4847
5196
  const dataToSign = pathWithoutSignature.replace(/^https?:\/\//, "");
4848
- 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);
4849
5198
  let signature;
4850
5199
  if (key.asymmetricKeyType === "rsa") {
4851
5200
  signature = import_node_crypto.default.sign("sha256", Buffer.from(dataToSign), {
@@ -4959,6 +5308,7 @@ var import_yazl, import_yauzl, DEFAULT_UNZIP_OPTIONS;
4959
5308
  var init_zip = __esm({
4960
5309
  "src/utils/zip.ts"() {
4961
5310
  "use strict";
5311
+ init_cjs_shims();
4962
5312
  import_yazl = require("yazl");
4963
5313
  import_yauzl = require("yauzl");
4964
5314
  DEFAULT_UNZIP_OPTIONS = {
@@ -5032,6 +5382,7 @@ var holidayCache;
5032
5382
  var init_holidays = __esm({
5033
5383
  "src/offline/holidays.ts"() {
5034
5384
  "use strict";
5385
+ init_cjs_shims();
5035
5386
  holidayCache = /* @__PURE__ */ new Map();
5036
5387
  }
5037
5388
  });
@@ -5131,6 +5482,7 @@ var FAR_FUTURE;
5131
5482
  var init_deadline = __esm({
5132
5483
  "src/offline/deadline.ts"() {
5133
5484
  "use strict";
5485
+ init_cjs_shims();
5134
5486
  init_holidays();
5135
5487
  FAR_FUTURE = /* @__PURE__ */ new Date("9999-12-31T23:59:59Z");
5136
5488
  }
@@ -5141,6 +5493,7 @@ var import_node_crypto3, OfflineInvoiceWorkflow;
5141
5493
  var init_offline_invoice_workflow = __esm({
5142
5494
  "src/workflows/offline-invoice-workflow.ts"() {
5143
5495
  "use strict";
5496
+ init_cjs_shims();
5144
5497
  import_node_crypto3 = __toESM(require("crypto"), 1);
5145
5498
  init_ksef_api_error();
5146
5499
  init_deadline();
@@ -5175,7 +5528,8 @@ var init_offline_invoice_workflow = __esm({
5175
5528
  input.sellerNip,
5176
5529
  options.certificate.certificateSerial,
5177
5530
  invoiceHashBase64,
5178
- options.certificate.privateKeyPem
5531
+ options.certificate.privateKeyPem,
5532
+ options.certificate.password
5179
5533
  );
5180
5534
  }
5181
5535
  const submitBy = options?.customDeadline ? typeof options.customDeadline === "string" ? options.customDeadline : options.customDeadline.toISOString() : calculateOfflineDeadline(mode, input.invoiceDate, options?.maintenanceWindow).toISOString();
@@ -5365,7 +5719,8 @@ var init_offline_invoice_workflow = __esm({
5365
5719
  original.sellerNip,
5366
5720
  options.certificate.certificateSerial,
5367
5721
  correctedHashBase64,
5368
- options.certificate.privateKeyPem
5722
+ options.certificate.privateKeyPem,
5723
+ options.certificate.password
5369
5724
  );
5370
5725
  }
5371
5726
  const correctionMetadata = {
@@ -5451,6 +5806,11 @@ function buildRestClientConfig(options, authManager) {
5451
5806
  endpointLimits: options.rateLimit.endpointLimits
5452
5807
  });
5453
5808
  }
5809
+ if (options?.circuitBreaker === null) {
5810
+ config.circuitBreakerPolicy = null;
5811
+ } else if (options?.circuitBreaker) {
5812
+ config.circuitBreakerPolicy = new CircuitBreakerPolicy(options.circuitBreaker);
5813
+ }
5454
5814
  if (options?.presignedUrlHosts) {
5455
5815
  const base = defaultPresignedUrlPolicy();
5456
5816
  config.presignedUrlPolicy = {
@@ -5464,10 +5824,12 @@ var KSeFClient;
5464
5824
  var init_client = __esm({
5465
5825
  "src/client.ts"() {
5466
5826
  "use strict";
5827
+ init_cjs_shims();
5467
5828
  init_config();
5468
5829
  init_rest_client();
5469
5830
  init_retry_policy();
5470
5831
  init_rate_limit_policy();
5832
+ init_circuit_breaker_policy();
5471
5833
  init_presigned_url_policy();
5472
5834
  init_auth_manager();
5473
5835
  init_auth();
@@ -5621,6 +5983,7 @@ __export(index_exports, {
5621
5983
  CertificateFingerprint: () => CertificateFingerprint,
5622
5984
  CertificateName: () => CertificateName,
5623
5985
  CertificateService: () => CertificateService,
5986
+ CircuitBreakerPolicy: () => CircuitBreakerPolicy,
5624
5987
  CryptographyService: () => CryptographyService,
5625
5988
  DEFAULT_FORM_CODE: () => DEFAULT_FORM_CODE,
5626
5989
  DISCOURAGED_UNICODE_RANGES: () => DISCOURAGED_UNICODE_RANGES,
@@ -5630,6 +5993,7 @@ __export(index_exports, {
5630
5993
  EntityPermissionGrantBuilder: () => EntityPermissionGrantBuilder,
5631
5994
  Environment: () => Environment,
5632
5995
  FAKTURA_NAMESPACE: () => FAKTURA_NAMESPACE,
5996
+ FA_XSD_PATHS: () => FA_XSD_PATHS,
5633
5997
  FORM_CODES: () => FORM_CODES,
5634
5998
  FORM_CODE_KEYS: () => FORM_CODE_KEYS,
5635
5999
  FileHwmStore: () => FileHwmStore,
@@ -5648,6 +6012,7 @@ __export(index_exports, {
5648
6012
  KSeFAuthStatusError: () => KSeFAuthStatusError,
5649
6013
  KSeFBadRequestError: () => KSeFBadRequestError,
5650
6014
  KSeFBatchTimeoutError: () => KSeFBatchTimeoutError,
6015
+ KSeFCircuitOpenError: () => KSeFCircuitOpenError,
5651
6016
  KSeFClient: () => KSeFClient,
5652
6017
  KSeFError: () => KSeFError,
5653
6018
  KSeFErrorCode: () => KSeFErrorCode,
@@ -5657,6 +6022,7 @@ __export(index_exports, {
5657
6022
  KSeFSessionExpiredError: () => KSeFSessionExpiredError,
5658
6023
  KSeFUnauthorizedError: () => KSeFUnauthorizedError,
5659
6024
  KSeFValidationError: () => KSeFValidationError,
6025
+ KSeFXsdValidationError: () => KSeFXsdValidationError,
5660
6026
  KsefNumber: () => KsefNumber,
5661
6027
  KsefNumberV35: () => KsefNumberV35,
5662
6028
  KsefNumberV36: () => KsefNumberV36,
@@ -5668,6 +6034,7 @@ __export(index_exports, {
5668
6034
  OfflineInvoiceWorkflow: () => OfflineInvoiceWorkflow,
5669
6035
  OnlineSessionService: () => OnlineSessionService,
5670
6036
  PEF_NAMESPACE: () => PEF_NAMESPACE,
6037
+ PEF_XSD_PATHS: () => PEF_XSD_PATHS,
5671
6038
  PERMISSION_DESCRIPTION_MAX_LENGTH: () => PERMISSION_DESCRIPTION_MAX_LENGTH,
5672
6039
  PERMISSION_DESCRIPTION_MIN_LENGTH: () => PERMISSION_DESCRIPTION_MIN_LENGTH,
5673
6040
  PeppolId: () => PeppolId,
@@ -5715,6 +6082,7 @@ __export(index_exports, {
5715
6082
  createZip: () => createZip,
5716
6083
  decodeJwtPayload: () => decodeJwtPayload,
5717
6084
  deduplicateByKsefNumber: () => deduplicateByKsefNumber,
6085
+ defaultCircuitBreakerPolicy: () => defaultCircuitBreakerPolicy,
5718
6086
  defaultPresignedUrlPolicy: () => defaultPresignedUrlPolicy,
5719
6087
  defaultRateLimitPolicy: () => defaultRateLimitPolicy,
5720
6088
  defaultRetryPolicy: () => defaultRetryPolicy,
@@ -5751,6 +6119,7 @@ __export(index_exports, {
5751
6119
  isValidReferenceNumber: () => isValidReferenceNumber,
5752
6120
  isValidSha256Base64: () => isValidSha256Base64,
5753
6121
  isValidVatUe: () => isValidVatUe,
6122
+ libxmljsAvailable: () => libxmljsAvailable,
5754
6123
  nextBusinessDay: () => nextBusinessDay,
5755
6124
  openOnlineSession: () => openOnlineSession,
5756
6125
  openSendAndClose: () => openSendAndClose,
@@ -5762,6 +6131,7 @@ __export(index_exports, {
5762
6131
  parseXml: () => parseXml,
5763
6132
  pollUntil: () => pollUntil,
5764
6133
  resolveOptions: () => resolveOptions,
6134
+ resolveXsdFor: () => resolveXsdFor,
5765
6135
  resumeOnlineSession: () => resumeOnlineSession,
5766
6136
  runWithConcurrency: () => runWithConcurrency,
5767
6137
  serializeInvoiceXml: () => serializeInvoiceXml,
@@ -5776,6 +6146,7 @@ __export(index_exports, {
5776
6146
  uploadBatchStream: () => uploadBatchStream,
5777
6147
  uploadBatchStreamParsed: () => uploadBatchStreamParsed,
5778
6148
  validate: () => validate,
6149
+ validateAgainstXsd: () => validateAgainstXsd,
5779
6150
  validateBatch: () => validateBatch,
5780
6151
  validateBusinessRules: () => validateBusinessRules,
5781
6152
  validateCharValidity: () => validateCharValidity,
@@ -5787,10 +6158,12 @@ __export(index_exports, {
5787
6158
  xmlToObject: () => xmlToObject
5788
6159
  });
5789
6160
  module.exports = __toCommonJS(index_exports);
6161
+ init_cjs_shims();
5790
6162
  init_config();
5791
6163
  init_errors();
5792
6164
 
5793
6165
  // src/http/index.ts
6166
+ init_cjs_shims();
5794
6167
  init_route_builder();
5795
6168
  init_rest_request();
5796
6169
  init_rest_client();
@@ -5798,14 +6171,17 @@ init_routes();
5798
6171
  init_transport();
5799
6172
  init_retry_policy();
5800
6173
  init_rate_limit_policy();
6174
+ init_circuit_breaker_policy();
5801
6175
  init_auth_manager();
5802
6176
  init_presigned_url_policy();
5803
6177
  init_ksef_feature();
5804
6178
 
5805
6179
  // src/validation/index.ts
6180
+ init_cjs_shims();
5806
6181
  init_patterns();
5807
6182
 
5808
6183
  // src/validation/constraints.ts
6184
+ init_cjs_shims();
5809
6185
  var REQUIRED_CHALLENGE_LENGTH = 36;
5810
6186
  var CERTIFICATE_NAME_MIN_LENGTH = 5;
5811
6187
  var CERTIFICATE_NAME_MAX_LENGTH = 100;
@@ -5820,10 +6196,218 @@ init_schema_registry();
5820
6196
  init_invoice_validator();
5821
6197
  init_char_validity();
5822
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();
6405
+
5823
6406
  // src/models/index.ts
5824
6407
  init_document_structures();
5825
6408
 
5826
6409
  // src/services/index.ts
6410
+ init_cjs_shims();
5827
6411
  init_auth();
5828
6412
  init_active_sessions();
5829
6413
  init_online_session();
@@ -5838,7 +6422,11 @@ init_limits();
5838
6422
  init_peppol();
5839
6423
  init_test_data();
5840
6424
 
6425
+ // src/builders/index.ts
6426
+ init_cjs_shims();
6427
+
5841
6428
  // src/builders/auth-token-request.ts
6429
+ init_cjs_shims();
5842
6430
  init_ksef_validation_error();
5843
6431
  var AuthTokenRequestBuilder = class {
5844
6432
  challenge;
@@ -5893,6 +6481,7 @@ var AuthTokenRequestBuilder = class {
5893
6481
  };
5894
6482
 
5895
6483
  // src/builders/auth-ksef-token-request.ts
6484
+ init_cjs_shims();
5896
6485
  init_ksef_validation_error();
5897
6486
  var AuthKsefTokenRequestBuilder = class {
5898
6487
  challenge;
@@ -5947,6 +6536,7 @@ var AuthKsefTokenRequestBuilder = class {
5947
6536
  };
5948
6537
 
5949
6538
  // src/builders/invoice-query-filter.ts
6539
+ init_cjs_shims();
5950
6540
  init_ksef_validation_error();
5951
6541
  var InvoiceQueryFilterBuilder = class {
5952
6542
  subjectType;
@@ -6043,7 +6633,11 @@ var InvoiceQueryFilterBuilder = class {
6043
6633
  }
6044
6634
  };
6045
6635
 
6636
+ // src/builders/permissions/index.ts
6637
+ init_cjs_shims();
6638
+
6046
6639
  // src/builders/permissions/person-permission.ts
6640
+ init_cjs_shims();
6047
6641
  init_ksef_validation_error();
6048
6642
  var PersonPermissionGrantBuilder = class {
6049
6643
  subjectIdentifier;
@@ -6093,6 +6687,7 @@ var PersonPermissionGrantBuilder = class {
6093
6687
  };
6094
6688
 
6095
6689
  // src/builders/permissions/entity-permission.ts
6690
+ init_cjs_shims();
6096
6691
  init_ksef_validation_error();
6097
6692
  var EntityPermissionGrantBuilder = class {
6098
6693
  nip;
@@ -6142,6 +6737,7 @@ var EntityPermissionGrantBuilder = class {
6142
6737
  };
6143
6738
 
6144
6739
  // src/builders/permissions/authorization-permission.ts
6740
+ init_cjs_shims();
6145
6741
  init_ksef_validation_error();
6146
6742
  var AuthorizationPermissionGrantBuilder = class {
6147
6743
  _subjectIdentifier;
@@ -6187,6 +6783,7 @@ var AuthorizationPermissionGrantBuilder = class {
6187
6783
  };
6188
6784
 
6189
6785
  // src/builders/batch-file.ts
6786
+ init_cjs_shims();
6190
6787
  var crypto = __toESM(require("crypto"), 1);
6191
6788
  init_ksef_validation_error();
6192
6789
  var BATCH_MAX_PART_SIZE = 1e8;
@@ -6357,11 +6954,13 @@ function sha256Base64(data) {
6357
6954
  }
6358
6955
 
6359
6956
  // src/crypto/index.ts
6957
+ init_cjs_shims();
6360
6958
  init_certificate_fetcher();
6361
6959
  init_cryptography_service();
6362
6960
  init_signature_service();
6363
6961
 
6364
6962
  // src/crypto/certificate-service.ts
6963
+ init_cjs_shims();
6365
6964
  var crypto4 = __toESM(require("crypto"), 1);
6366
6965
  var x5092 = __toESM(require("@peculiar/x509"), 1);
6367
6966
  var CertificateService = class {
@@ -6447,9 +7046,11 @@ init_pkcs12_loader();
6447
7046
  init_auth_xml_builder();
6448
7047
 
6449
7048
  // src/qr/index.ts
7049
+ init_cjs_shims();
6450
7050
  init_verification_link_service();
6451
7051
 
6452
7052
  // src/qr/qrcode-service.ts
7053
+ init_cjs_shims();
6453
7054
  var QRCode = __toESM(require("qrcode"), 1);
6454
7055
  var QrCodeService = class _QrCodeService {
6455
7056
  static async generateQrCode(url, options) {
@@ -6509,10 +7110,12 @@ function escapeXml2(str) {
6509
7110
  }
6510
7111
 
6511
7112
  // src/utils/index.ts
7113
+ init_cjs_shims();
6512
7114
  init_zip();
6513
7115
  init_jwt();
6514
7116
 
6515
7117
  // src/utils/hash.ts
7118
+ init_cjs_shims();
6516
7119
  var import_node_crypto2 = __toESM(require("crypto"), 1);
6517
7120
  function sha256Base642(data) {
6518
7121
  return import_node_crypto2.default.createHash("sha256").update(data).digest("base64");
@@ -6524,7 +7127,11 @@ function verifyHash(data, expectedHash) {
6524
7127
  // src/utils/index.ts
6525
7128
  init_concurrency();
6526
7129
 
7130
+ // src/workflows/index.ts
7131
+ init_cjs_shims();
7132
+
6527
7133
  // src/workflows/polling.ts
7134
+ init_cjs_shims();
6528
7135
  async function pollUntil(action, condition, options) {
6529
7136
  const intervalMs = options?.intervalMs ?? 2e3;
6530
7137
  const maxAttempts = options?.maxAttempts ?? 60;
@@ -6542,13 +7149,18 @@ async function pollUntil(action, condition, options) {
6542
7149
  }
6543
7150
 
6544
7151
  // src/workflows/online-session-workflow.ts
7152
+ init_cjs_shims();
6545
7153
  init_ksef_session_expired_error();
6546
7154
  init_auth_manager();
6547
7155
  init_online_session();
6548
7156
  init_session_status();
6549
7157
  init_document_structures();
6550
7158
 
7159
+ // src/xml/index.ts
7160
+ init_cjs_shims();
7161
+
6551
7162
  // src/xml/upo-parser.ts
7163
+ init_cjs_shims();
6552
7164
  var import_fast_xml_parser = require("fast-xml-parser");
6553
7165
  init_ksef_validation_error();
6554
7166
  function isRecord(value) {
@@ -6667,6 +7279,7 @@ function parseUpoXml(xml) {
6667
7279
  }
6668
7280
 
6669
7281
  // src/xml/invoice-field-extractor.ts
7282
+ init_cjs_shims();
6670
7283
  var import_fast_xml_parser2 = require("fast-xml-parser");
6671
7284
  var invoiceParser = new import_fast_xml_parser2.XMLParser({
6672
7285
  ignoreAttributes: false,
@@ -6707,6 +7320,7 @@ function nonEmptyString(value) {
6707
7320
  }
6708
7321
 
6709
7322
  // src/xml/xml-engine.ts
7323
+ init_cjs_shims();
6710
7324
  var import_fast_xml_parser3 = require("fast-xml-parser");
6711
7325
  var XML_DECLARATION = '<?xml version="1.0" encoding="UTF-8"?>\n';
6712
7326
  var parser = new import_fast_xml_parser3.XMLParser({
@@ -6749,17 +7363,18 @@ function prependDeclaration(xml) {
6749
7363
  function parseXml(xml) {
6750
7364
  return parser.parse(xml);
6751
7365
  }
6752
- function buildXml(document) {
6753
- return prependDeclaration(builder.build(document));
7366
+ function buildXml(document2) {
7367
+ return prependDeclaration(builder.build(document2));
6754
7368
  }
6755
- function buildXmlFromObject(document, options) {
6756
- return prependDeclaration(createObjectBuilder(options?.pretty).build(document));
7369
+ function buildXmlFromObject(document2, options) {
7370
+ return prependDeclaration(createObjectBuilder(options?.pretty).build(document2));
6757
7371
  }
6758
7372
  function stripBom(input) {
6759
7373
  return input.charCodeAt(0) === 65279 ? input.slice(1) : input;
6760
7374
  }
6761
7375
 
6762
7376
  // src/xml/order-map.ts
7377
+ init_cjs_shims();
6763
7378
  var ORDER_MAP = {
6764
7379
  Faktura: ["Naglowek", "Podmiot1", "Podmiot2", "Podmiot3", "Fa", "Stopka"],
6765
7380
  Naglowek: ["KodFormularza", "WariantFormularza", "DataWytworzeniaFa", "SystemInfo"],
@@ -6958,6 +7573,7 @@ function orderXmlObject(value, contextKey) {
6958
7573
  }
6959
7574
 
6960
7575
  // src/xml/faktura-builder.ts
7576
+ init_cjs_shims();
6961
7577
  var FAKTURA_NAMESPACE = {
6962
7578
  FA2: "http://crd.gov.pl/wzor/2023/06/29/12648/",
6963
7579
  FA3: "http://crd.gov.pl/wzor/2025/06/25/13775/"
@@ -7027,14 +7643,14 @@ function buildFakturaXml(faktura, options = {}) {
7027
7643
  const etdNamespace = options.etdNamespace ?? ETD_NAMESPACE[schema];
7028
7644
  const normalized = normalizeTopLevel(faktura);
7029
7645
  const ordered = orderXmlObject(normalized, "Faktura");
7030
- const document = {
7646
+ const document2 = {
7031
7647
  Faktura: {
7032
7648
  ...ordered,
7033
7649
  "@_xmlns": fakturaNamespace,
7034
7650
  "@_xmlns:etd": etdNamespace
7035
7651
  }
7036
7652
  };
7037
- return buildXmlFromObject(document, { pretty: options.pretty });
7653
+ return buildXmlFromObject(document2, { pretty: options.pretty });
7038
7654
  }
7039
7655
  function isFakturaInput(input) {
7040
7656
  if (!isObject2(input)) return false;
@@ -7045,6 +7661,7 @@ function isFakturaInput(input) {
7045
7661
  }
7046
7662
 
7047
7663
  // src/xml/pef-builder.ts
7664
+ init_cjs_shims();
7048
7665
  init_ksef_validation_error();
7049
7666
  var PEF_NAMESPACE = {
7050
7667
  PEF: "urn:oasis:names:specification:ubl:schema:xsd:Invoice-2",
@@ -7109,7 +7726,7 @@ function buildPefXml(input, options = {}) {
7109
7726
  "@_xmlns:cbc-pl": UBL_CBC_PL_NS,
7110
7727
  "@_xmlns:cac-pl": UBL_CAC_PL_NS
7111
7728
  };
7112
- const document = "Invoice" in input ? {
7729
+ const document2 = "Invoice" in input ? {
7113
7730
  Invoice: {
7114
7731
  ...input.Invoice,
7115
7732
  "@_xmlns": PEF_NAMESPACE.PEF,
@@ -7122,10 +7739,11 @@ function buildPefXml(input, options = {}) {
7122
7739
  ...commonNamespaces
7123
7740
  }
7124
7741
  };
7125
- return buildXmlFromObject(document, { pretty: options.pretty });
7742
+ return buildXmlFromObject(document2, { pretty: options.pretty });
7126
7743
  }
7127
7744
 
7128
7745
  // src/xml/invoice-serializer.ts
7746
+ init_cjs_shims();
7129
7747
  init_ksef_validation_error();
7130
7748
  var FAKTURA_SCHEMAS = /* @__PURE__ */ new Set(["FA2", "FA3"]);
7131
7749
  var PEF_SCHEMAS = /* @__PURE__ */ new Set(["PEF", "PEF_KOR"]);
@@ -7220,8 +7838,8 @@ function serializeInvoiceXml(input, options) {
7220
7838
  "Unsupported invoice input type: expected Buffer, string, XmlDocument, FakturaInput, or PefUblDocumentInput."
7221
7839
  );
7222
7840
  }
7223
- function buildRawXmlString(document, options) {
7224
- return buildXmlFromObject(document, options);
7841
+ function buildRawXmlString(document2, options) {
7842
+ return buildXmlFromObject(document2, options);
7225
7843
  }
7226
7844
 
7227
7845
  // src/workflows/online-session-workflow.ts
@@ -7361,6 +7979,7 @@ async function openSendAndClose(client, invoices, options) {
7361
7979
  }
7362
7980
 
7363
7981
  // src/workflows/batch-session-workflow.ts
7982
+ init_cjs_shims();
7364
7983
  init_document_structures();
7365
7984
  async function uploadBatch(client, zipData, options) {
7366
7985
  if (options?.parallelism !== void 0 && (!Number.isInteger(options.parallelism) || options.parallelism < 1)) {
@@ -7499,6 +8118,7 @@ async function uploadBatchParsed(client, zipData, options) {
7499
8118
  }
7500
8119
 
7501
8120
  // src/workflows/invoice-export-workflow.ts
8121
+ init_cjs_shims();
7502
8122
  init_zip();
7503
8123
  async function doExport(client, filters, options) {
7504
8124
  await client.crypto.init();
@@ -7571,7 +8191,11 @@ async function exportAndDownload(client, filters, options) {
7571
8191
  };
7572
8192
  }
7573
8193
 
8194
+ // src/workflows/incremental-export-workflow.ts
8195
+ init_cjs_shims();
8196
+
7574
8197
  // src/workflows/hwm-coordinator.ts
8198
+ init_cjs_shims();
7575
8199
  function updateContinuationPoint(points, subjectType, pkg) {
7576
8200
  if (pkg.isTruncated && pkg.lastPermanentStorageDate) {
7577
8201
  points[subjectType] = pkg.lastPermanentStorageDate;
@@ -7669,7 +8293,8 @@ function buildDefaultFilters(subjectType, from, to) {
7669
8293
  }
7670
8294
 
7671
8295
  // src/workflows/hwm-storage.ts
7672
- var fs = __toESM(require("fs/promises"), 1);
8296
+ init_cjs_shims();
8297
+ var fs2 = __toESM(require("fs/promises"), 1);
7673
8298
  var InMemoryHwmStore = class {
7674
8299
  points = {};
7675
8300
  async load() {
@@ -7685,7 +8310,7 @@ var FileHwmStore = class {
7685
8310
  }
7686
8311
  async load() {
7687
8312
  try {
7688
- const data = await fs.readFile(this.filePath, "utf-8");
8313
+ const data = await fs2.readFile(this.filePath, "utf-8");
7689
8314
  return JSON.parse(data);
7690
8315
  } catch (err) {
7691
8316
  if (err.code === "ENOENT") {
@@ -7695,11 +8320,12 @@ var FileHwmStore = class {
7695
8320
  }
7696
8321
  }
7697
8322
  async save(points) {
7698
- 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");
7699
8324
  }
7700
8325
  };
7701
8326
 
7702
8327
  // src/workflows/auth-workflow.ts
8328
+ init_cjs_shims();
7703
8329
  init_auth_xml_builder();
7704
8330
  async function authenticateWithToken(client, options) {
7705
8331
  const challenge = await client.auth.getChallenge();
@@ -7796,10 +8422,12 @@ async function authenticateWithPkcs12(client, options) {
7796
8422
  }
7797
8423
 
7798
8424
  // src/offline/index.ts
8425
+ init_cjs_shims();
7799
8426
  init_deadline();
7800
8427
  init_holidays();
7801
8428
 
7802
8429
  // src/offline/storage.ts
8430
+ init_cjs_shims();
7803
8431
  function matchesFilter(invoice, filter) {
7804
8432
  if (filter.status !== void 0) {
7805
8433
  const statuses = Array.isArray(filter.status) ? filter.status : [filter.status];
@@ -7838,12 +8466,13 @@ var InMemoryOfflineInvoiceStorage = class {
7838
8466
  };
7839
8467
 
7840
8468
  // src/offline/file-storage.ts
7841
- var fs2 = __toESM(require("fs/promises"), 1);
7842
- 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);
7843
8472
  var os = __toESM(require("os"), 1);
7844
8473
  function resolveDir(dir) {
7845
8474
  if (dir === "~" || dir.startsWith("~/")) {
7846
- return path.join(os.homedir(), dir.slice(1));
8475
+ return path2.join(os.homedir(), dir.slice(1));
7847
8476
  }
7848
8477
  return dir;
7849
8478
  }
@@ -7859,23 +8488,23 @@ var FileOfflineInvoiceStorage = class {
7859
8488
  this.dir = resolveDir(directory ?? "~/.ksef/offline");
7860
8489
  }
7861
8490
  async ensureDir() {
7862
- await fs2.mkdir(this.dir, { recursive: true });
8491
+ await fs3.mkdir(this.dir, { recursive: true });
7863
8492
  }
7864
8493
  filePath(id) {
7865
8494
  validateId(id);
7866
- return path.join(this.dir, `${id}.json`);
8495
+ return path2.join(this.dir, `${id}.json`);
7867
8496
  }
7868
8497
  async save(invoice) {
7869
8498
  await this.ensureDir();
7870
8499
  const file = this.filePath(invoice.id);
7871
8500
  const tmp = `${file}.tmp`;
7872
- await fs2.writeFile(tmp, JSON.stringify(invoice, null, 2));
7873
- await fs2.rename(tmp, file);
8501
+ await fs3.writeFile(tmp, JSON.stringify(invoice, null, 2));
8502
+ await fs3.rename(tmp, file);
7874
8503
  }
7875
8504
  async get(id) {
7876
8505
  const file = this.filePath(id);
7877
8506
  try {
7878
- return JSON.parse(await fs2.readFile(file, "utf-8"));
8507
+ return JSON.parse(await fs3.readFile(file, "utf-8"));
7879
8508
  } catch (err) {
7880
8509
  if (err instanceof Error && "code" in err && err.code === "ENOENT") {
7881
8510
  return null;
@@ -7887,7 +8516,7 @@ var FileOfflineInvoiceStorage = class {
7887
8516
  async list(filter) {
7888
8517
  let files;
7889
8518
  try {
7890
- files = (await fs2.readdir(this.dir)).filter((f) => f.endsWith(".json"));
8519
+ files = (await fs3.readdir(this.dir)).filter((f) => f.endsWith(".json"));
7891
8520
  } catch {
7892
8521
  return [];
7893
8522
  }
@@ -7895,7 +8524,7 @@ var FileOfflineInvoiceStorage = class {
7895
8524
  for (const file of files) {
7896
8525
  try {
7897
8526
  const data = JSON.parse(
7898
- await fs2.readFile(path.join(this.dir, file), "utf-8")
8527
+ await fs3.readFile(path2.join(this.dir, file), "utf-8")
7899
8528
  );
7900
8529
  if (!filter || matchesFilter(data, filter)) {
7901
8530
  results.push(data);
@@ -7921,7 +8550,7 @@ var FileOfflineInvoiceStorage = class {
7921
8550
  async delete(id) {
7922
8551
  const file = this.filePath(id);
7923
8552
  try {
7924
- await fs2.unlink(file);
8553
+ await fs3.unlink(file);
7925
8554
  } catch (e) {
7926
8555
  if (e instanceof Error && "code" in e && e.code !== "ENOENT") throw e;
7927
8556
  }
@@ -7951,6 +8580,7 @@ init_client();
7951
8580
  CertificateFingerprint,
7952
8581
  CertificateName,
7953
8582
  CertificateService,
8583
+ CircuitBreakerPolicy,
7954
8584
  CryptographyService,
7955
8585
  DEFAULT_FORM_CODE,
7956
8586
  DISCOURAGED_UNICODE_RANGES,
@@ -7960,6 +8590,7 @@ init_client();
7960
8590
  EntityPermissionGrantBuilder,
7961
8591
  Environment,
7962
8592
  FAKTURA_NAMESPACE,
8593
+ FA_XSD_PATHS,
7963
8594
  FORM_CODES,
7964
8595
  FORM_CODE_KEYS,
7965
8596
  FileHwmStore,
@@ -7978,6 +8609,7 @@ init_client();
7978
8609
  KSeFAuthStatusError,
7979
8610
  KSeFBadRequestError,
7980
8611
  KSeFBatchTimeoutError,
8612
+ KSeFCircuitOpenError,
7981
8613
  KSeFClient,
7982
8614
  KSeFError,
7983
8615
  KSeFErrorCode,
@@ -7987,6 +8619,7 @@ init_client();
7987
8619
  KSeFSessionExpiredError,
7988
8620
  KSeFUnauthorizedError,
7989
8621
  KSeFValidationError,
8622
+ KSeFXsdValidationError,
7990
8623
  KsefNumber,
7991
8624
  KsefNumberV35,
7992
8625
  KsefNumberV36,
@@ -7998,6 +8631,7 @@ init_client();
7998
8631
  OfflineInvoiceWorkflow,
7999
8632
  OnlineSessionService,
8000
8633
  PEF_NAMESPACE,
8634
+ PEF_XSD_PATHS,
8001
8635
  PERMISSION_DESCRIPTION_MAX_LENGTH,
8002
8636
  PERMISSION_DESCRIPTION_MIN_LENGTH,
8003
8637
  PeppolId,
@@ -8045,6 +8679,7 @@ init_client();
8045
8679
  createZip,
8046
8680
  decodeJwtPayload,
8047
8681
  deduplicateByKsefNumber,
8682
+ defaultCircuitBreakerPolicy,
8048
8683
  defaultPresignedUrlPolicy,
8049
8684
  defaultRateLimitPolicy,
8050
8685
  defaultRetryPolicy,
@@ -8081,6 +8716,7 @@ init_client();
8081
8716
  isValidReferenceNumber,
8082
8717
  isValidSha256Base64,
8083
8718
  isValidVatUe,
8719
+ libxmljsAvailable,
8084
8720
  nextBusinessDay,
8085
8721
  openOnlineSession,
8086
8722
  openSendAndClose,
@@ -8092,6 +8728,7 @@ init_client();
8092
8728
  parseXml,
8093
8729
  pollUntil,
8094
8730
  resolveOptions,
8731
+ resolveXsdFor,
8095
8732
  resumeOnlineSession,
8096
8733
  runWithConcurrency,
8097
8734
  serializeInvoiceXml,
@@ -8106,6 +8743,7 @@ init_client();
8106
8743
  uploadBatchStream,
8107
8744
  uploadBatchStreamParsed,
8108
8745
  validate,
8746
+ validateAgainstXsd,
8109
8747
  validateBatch,
8110
8748
  validateBusinessRules,
8111
8749
  validateCharValidity,