ksef-client-ts 0.7.0 → 0.7.2-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/README.md +2 -1
  2. package/dist/cli.js +1717 -333
  3. package/dist/cli.js.map +1 -1
  4. package/dist/index.cjs +733 -85
  5. package/dist/index.cjs.map +1 -1
  6. package/dist/index.d.cts +77 -2
  7. package/dist/index.d.ts +77 -2
  8. package/dist/index.js +711 -75
  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/cli.js CHANGED
@@ -320,6 +320,50 @@ var init_ksef_batch_timeout_error = __esm({
320
320
  }
321
321
  });
322
322
 
323
+ // src/errors/ksef-circuit-open-error.ts
324
+ var KSeFCircuitOpenError;
325
+ var init_ksef_circuit_open_error = __esm({
326
+ "src/errors/ksef-circuit-open-error.ts"() {
327
+ "use strict";
328
+ init_ksef_error();
329
+ KSeFCircuitOpenError = class extends KSeFError {
330
+ endpoint;
331
+ openedAt;
332
+ retryAfterMs;
333
+ constructor(endpoint, openedAt, retryAfterMs) {
334
+ super(
335
+ `Circuit breaker is open for '${endpoint}'. Retry after ${Math.round(retryAfterMs)}ms.`
336
+ );
337
+ this.name = "KSeFCircuitOpenError";
338
+ this.endpoint = endpoint;
339
+ this.openedAt = openedAt;
340
+ this.retryAfterMs = retryAfterMs;
341
+ }
342
+ };
343
+ }
344
+ });
345
+
346
+ // src/errors/ksef-xsd-validation-error.ts
347
+ var KSeFXsdValidationError;
348
+ var init_ksef_xsd_validation_error = __esm({
349
+ "src/errors/ksef-xsd-validation-error.ts"() {
350
+ "use strict";
351
+ init_ksef_error();
352
+ KSeFXsdValidationError = class extends KSeFError {
353
+ schemaFile;
354
+ errors;
355
+ constructor(schemaFile, errors) {
356
+ const preview = errors.slice(0, 3).join("; ");
357
+ const extra = errors.length > 3 ? ` (+${errors.length - 3} more)` : "";
358
+ super(`XSD validation failed against ${schemaFile}: ${preview}${extra}`);
359
+ this.name = "KSeFXsdValidationError";
360
+ this.schemaFile = schemaFile;
361
+ this.errors = errors;
362
+ }
363
+ };
364
+ }
365
+ });
366
+
323
367
  // src/errors/assert-never.ts
324
368
  var init_assert_never = __esm({
325
369
  "src/errors/assert-never.ts"() {
@@ -342,6 +386,8 @@ var init_errors = __esm({
342
386
  init_ksef_session_expired_error();
343
387
  init_ksef_validation_error();
344
388
  init_ksef_batch_timeout_error();
389
+ init_ksef_circuit_open_error();
390
+ init_ksef_xsd_validation_error();
345
391
  init_error_codes();
346
392
  init_assert_never();
347
393
  }
@@ -617,6 +663,7 @@ var init_rest_client = __esm({
617
663
  transport;
618
664
  retryPolicy;
619
665
  rateLimitPolicy;
666
+ circuitBreakerPolicy;
620
667
  authManager;
621
668
  presignedUrlPolicy;
622
669
  constructor(options, config) {
@@ -625,6 +672,7 @@ var init_rest_client = __esm({
625
672
  this.transport = config?.transport ?? defaultTransport;
626
673
  this.retryPolicy = config?.retryPolicy ?? defaultRetryPolicy();
627
674
  this.rateLimitPolicy = config?.rateLimitPolicy ?? null;
675
+ this.circuitBreakerPolicy = config?.circuitBreakerPolicy ?? null;
628
676
  this.authManager = config?.authManager;
629
677
  this.presignedUrlPolicy = config?.presignedUrlPolicy;
630
678
  }
@@ -649,18 +697,32 @@ var init_rest_client = __esm({
649
697
  if (request.isPresigned() && this.presignedUrlPolicy) {
650
698
  validatePresignedUrl(url2, this.presignedUrlPolicy);
651
699
  }
700
+ let ownsProbeSlot = false;
701
+ if (this.circuitBreakerPolicy) {
702
+ const claimed = this.circuitBreakerPolicy.ensureClosed(request.path);
703
+ if (claimed) ownsProbeSlot = true;
704
+ }
652
705
  if (this.rateLimitPolicy) {
653
- await this.rateLimitPolicy.acquire(request.path);
706
+ try {
707
+ await this.rateLimitPolicy.acquire(request.path);
708
+ } catch (error) {
709
+ if (ownsProbeSlot) this.circuitBreakerPolicy?.releaseProbe(request.path);
710
+ throw error;
711
+ }
654
712
  }
655
713
  let lastError;
656
714
  for (let attempt = 0; attempt <= this.retryPolicy.maxRetries; attempt++) {
715
+ if (this.circuitBreakerPolicy) {
716
+ const claimed = this.circuitBreakerPolicy.ensureClosed(request.path, ownsProbeSlot);
717
+ if (claimed) ownsProbeSlot = true;
718
+ }
657
719
  try {
658
- const response = await this.doRequest(request, url2);
720
+ let response = await this.doRequest(request, url2);
659
721
  if (response.status === 401 && this.authManager && attempt === 0 && !request.isSkipAuthRetry()) {
660
722
  const newToken = await this.authManager.onUnauthorized();
661
723
  if (newToken) {
662
724
  consola3.debug("Auth token refreshed, retrying request");
663
- return this.doRequest(request, url2, newToken);
725
+ response = await this.doRequest(request, url2, newToken);
664
726
  }
665
727
  }
666
728
  if (isRetryableStatus(response.status, this.retryPolicy) && attempt < this.retryPolicy.maxRetries) {
@@ -670,10 +732,17 @@ var init_rest_client = __esm({
670
732
  consola3.debug(`Retryable ${response.status}, attempt ${attempt + 1}/${this.retryPolicy.maxRetries}, waiting ${Math.round(delayMs)}ms`);
671
733
  await sleep(delayMs);
672
734
  if (is429 && this.rateLimitPolicy) {
673
- await this.rateLimitPolicy.acquire(request.path);
735
+ try {
736
+ await this.rateLimitPolicy.acquire(request.path);
737
+ } catch (error) {
738
+ this.recordCircuitOutcome(request.path, 429);
739
+ ownsProbeSlot = false;
740
+ throw error;
741
+ }
674
742
  }
675
743
  continue;
676
744
  }
745
+ this.recordCircuitOutcome(request.path, response.status);
677
746
  return response;
678
747
  } catch (error) {
679
748
  lastError = error;
@@ -683,11 +752,22 @@ var init_rest_client = __esm({
683
752
  await sleep(delayMs);
684
753
  continue;
685
754
  }
755
+ if (isRetryableError(error, this.retryPolicy) || ownsProbeSlot) {
756
+ this.circuitBreakerPolicy?.recordFailure(request.path);
757
+ }
686
758
  throw error;
687
759
  }
688
760
  }
689
761
  throw lastError;
690
762
  }
763
+ recordCircuitOutcome(path12, status7) {
764
+ if (!this.circuitBreakerPolicy) return;
765
+ if (status7 >= 500) {
766
+ this.circuitBreakerPolicy.recordFailure(path12);
767
+ return;
768
+ }
769
+ this.circuitBreakerPolicy.recordSuccess(path12);
770
+ }
691
771
  async doRequest(request, url2, overrideToken) {
692
772
  const headers = {
693
773
  ...this.options.customHeaders,
@@ -723,9 +803,9 @@ var init_rest_client = __esm({
723
803
  return response;
724
804
  }
725
805
  buildUrl(request) {
726
- const path10 = this.routeBuilder.build(request.path);
806
+ const path12 = this.routeBuilder.build(request.path);
727
807
  const base = this.options.baseUrl;
728
- const url2 = new URL(`${base}${path10}`);
808
+ const url2 = new URL(`${base}${path12}`);
729
809
  const query2 = request.getQuery();
730
810
  for (const [key, value] of query2) {
731
811
  url2.searchParams.append(key, value);
@@ -869,6 +949,141 @@ var init_rate_limit_policy = __esm({
869
949
  }
870
950
  });
871
951
 
952
+ // src/http/circuit-breaker-policy.ts
953
+ import { consola as consola4 } from "consola";
954
+ var GLOBAL_KEY, CircuitBreakerPolicy;
955
+ var init_circuit_breaker_policy = __esm({
956
+ "src/http/circuit-breaker-policy.ts"() {
957
+ "use strict";
958
+ init_ksef_circuit_open_error();
959
+ GLOBAL_KEY = "__global__";
960
+ CircuitBreakerPolicy = class _CircuitBreakerPolicy {
961
+ failureThreshold;
962
+ openMs;
963
+ scope;
964
+ states = /* @__PURE__ */ new Map();
965
+ constructor(config = {}) {
966
+ const failureThreshold = config.failureThreshold ?? 5;
967
+ const openMs = config.openMs ?? 3e4;
968
+ if (!Number.isInteger(failureThreshold) || failureThreshold <= 0) {
969
+ throw new RangeError("CircuitBreakerPolicy: failureThreshold must be a positive integer");
970
+ }
971
+ if (!Number.isFinite(openMs) || openMs <= 0) {
972
+ throw new RangeError("CircuitBreakerPolicy: openMs must be > 0");
973
+ }
974
+ const scope = config.scope ?? "global";
975
+ if (scope !== "global" && scope !== "endpoint") {
976
+ throw new RangeError(
977
+ "CircuitBreakerPolicy: scope must be 'global' or 'endpoint'"
978
+ );
979
+ }
980
+ this.failureThreshold = failureThreshold;
981
+ this.openMs = openMs;
982
+ this.scope = scope;
983
+ }
984
+ // Returns true iff this call just claimed the single probe slot for the
985
+ // caller. The caller MUST pass `alreadyOwnsProbe=true` on subsequent
986
+ // re-checks for the same logical request (e.g. a retry loop) so the probe
987
+ // owner cannot deadlock itself on its own in-flight slot.
988
+ ensureClosed(endpoint, alreadyOwnsProbe = false) {
989
+ const key = this.keyFor(endpoint);
990
+ const state = this.states.get(key);
991
+ if (!state || state.openedAt === null) return false;
992
+ const now = performance.now();
993
+ const elapsed = now - state.openedAt;
994
+ if (elapsed >= this.openMs) {
995
+ if (alreadyOwnsProbe) return false;
996
+ if (state.probeInFlight) {
997
+ throw new KSeFCircuitOpenError(endpoint, state.openedAt, 0);
998
+ }
999
+ state.probeInFlight = true;
1000
+ consola4.debug(`Circuit breaker: probe after cooldown for '${key}'`);
1001
+ return true;
1002
+ }
1003
+ const retryAfterMs = Math.max(0, this.openMs - elapsed);
1004
+ throw new KSeFCircuitOpenError(endpoint, state.openedAt, retryAfterMs);
1005
+ }
1006
+ recordSuccess(endpoint) {
1007
+ const key = this.keyFor(endpoint);
1008
+ const state = this.states.get(key);
1009
+ if (!state) return;
1010
+ if (state.openedAt !== null || state.failures > 0) {
1011
+ consola4.debug(`Circuit breaker: reset for '${key}'`);
1012
+ }
1013
+ this.states.delete(key);
1014
+ }
1015
+ // Release a claimed probe slot WITHOUT observing an outcome. Use this when
1016
+ // the probe attempt was aborted before reaching upstream (e.g. rate-limit
1017
+ // acquire rejected, client cancellation). We have no new information about
1018
+ // upstream health, so the breaker must stay OPEN — but we do restart the
1019
+ // cooldown clock so the next probe attempt waits a fresh `openMs`,
1020
+ // preventing a tight loop of aborted probes from spamming the limiter.
1021
+ releaseProbe(endpoint) {
1022
+ const key = this.keyFor(endpoint);
1023
+ const state = this.states.get(key);
1024
+ if (!state || !state.probeInFlight) return;
1025
+ state.probeInFlight = false;
1026
+ if (state.openedAt !== null) {
1027
+ state.openedAt = performance.now();
1028
+ }
1029
+ consola4.debug(`Circuit breaker: probe aborted (not observed) for '${key}', cooldown restarted`);
1030
+ }
1031
+ recordFailure(endpoint) {
1032
+ const key = this.keyFor(endpoint);
1033
+ const now = performance.now();
1034
+ let state = this.states.get(key);
1035
+ if (!state) {
1036
+ state = { failures: 0, openedAt: null, lastFailureAt: null, probeInFlight: false };
1037
+ this.states.set(key, state);
1038
+ }
1039
+ if (state.openedAt !== null && state.probeInFlight) {
1040
+ state.openedAt = now;
1041
+ state.failures = this.failureThreshold;
1042
+ state.lastFailureAt = now;
1043
+ state.probeInFlight = false;
1044
+ consola4.debug(`Circuit breaker: probe failed, re-opened for '${key}'`);
1045
+ this.maybeSweepStaleClosed(now, key);
1046
+ return;
1047
+ }
1048
+ const slidingStale = state.lastFailureAt !== null && now - state.lastFailureAt > this.openMs;
1049
+ state.failures = slidingStale ? 1 : state.failures + 1;
1050
+ state.lastFailureAt = now;
1051
+ if (state.openedAt === null && state.failures >= this.failureThreshold) {
1052
+ state.openedAt = now;
1053
+ consola4.debug(
1054
+ `Circuit breaker: opened for '${key}' after ${state.failures} failures (cooldown ${this.openMs}ms)`
1055
+ );
1056
+ }
1057
+ this.maybeSweepStaleClosed(now, key);
1058
+ }
1059
+ keyFor(endpoint) {
1060
+ return this.scope === "global" ? GLOBAL_KEY : endpoint;
1061
+ }
1062
+ // Prevent unbounded map growth under `scope: 'endpoint'` when callers hit
1063
+ // many distinct parameterized paths (e.g. `auth/sessions/{ref}`) that each
1064
+ // fail once and are never revisited. Global scope is always a single entry.
1065
+ //
1066
+ // Runs amortized O(n) — gated on a size threshold so small workloads pay
1067
+ // nothing. Only evicts states that are genuinely settled: closed, no probe
1068
+ // in flight, and with the last failure older than two cooldowns.
1069
+ maybeSweepStaleClosed(now, keepKey) {
1070
+ if (this.scope !== "endpoint") return;
1071
+ if (this.states.size <= _CircuitBreakerPolicy.sweepThreshold) return;
1072
+ const staleBefore = now - 2 * this.openMs;
1073
+ for (const [key, state] of this.states) {
1074
+ if (key === keepKey) continue;
1075
+ if (state.openedAt !== null) continue;
1076
+ if (state.probeInFlight) continue;
1077
+ if (state.lastFailureAt !== null && state.lastFailureAt < staleBefore) {
1078
+ this.states.delete(key);
1079
+ }
1080
+ }
1081
+ }
1082
+ static sweepThreshold = 64;
1083
+ };
1084
+ }
1085
+ });
1086
+
872
1087
  // src/http/auth-manager.ts
873
1088
  var DefaultAuthManager;
874
1089
  var init_auth_manager = __esm({
@@ -932,21 +1147,21 @@ var init_rest_request = __esm({
932
1147
  _query = [];
933
1148
  _presigned = false;
934
1149
  _skipAuthRetry = false;
935
- constructor(method, path10) {
1150
+ constructor(method, path12) {
936
1151
  this.method = method;
937
- this.path = path10;
1152
+ this.path = path12;
938
1153
  }
939
- static get(path10) {
940
- return new _RestRequest("GET", path10);
1154
+ static get(path12) {
1155
+ return new _RestRequest("GET", path12);
941
1156
  }
942
- static post(path10) {
943
- return new _RestRequest("POST", path10);
1157
+ static post(path12) {
1158
+ return new _RestRequest("POST", path12);
944
1159
  }
945
- static put(path10) {
946
- return new _RestRequest("PUT", path10);
1160
+ static put(path12) {
1161
+ return new _RestRequest("PUT", path12);
947
1162
  }
948
- static delete(path10) {
949
- return new _RestRequest("DELETE", path10);
1163
+ static delete(path12) {
1164
+ return new _RestRequest("DELETE", path12);
950
1165
  }
951
1166
  body(data) {
952
1167
  this._body = data;
@@ -1885,20 +2100,20 @@ var init_lighthouse = __esm({
1885
2100
  this.lighthouseUrl = options.lighthouseUrl;
1886
2101
  this.timeout = options.timeout;
1887
2102
  }
1888
- async fetchJson(path10) {
2103
+ async fetchJson(path12) {
1889
2104
  if (!this.lighthouseUrl) {
1890
2105
  throw new KSeFError(
1891
2106
  "Lighthouse API is not available for the DEMO environment. Use TEST or PROD instead."
1892
2107
  );
1893
2108
  }
1894
- const response = await fetch(`${this.lighthouseUrl}${path10}`, {
2109
+ const response = await fetch(`${this.lighthouseUrl}${path12}`, {
1895
2110
  headers: { Accept: "application/json" },
1896
2111
  signal: AbortSignal.timeout(this.timeout)
1897
2112
  });
1898
2113
  if (!response.ok) {
1899
2114
  const body = await response.text();
1900
2115
  throw new KSeFError(
1901
- `Lighthouse ${path10} failed: HTTP ${response.status} \u2014 ${body}`
2116
+ `Lighthouse ${path12} failed: HTTP ${response.status} \u2014 ${body}`
1902
2117
  );
1903
2118
  }
1904
2119
  return await response.json();
@@ -2156,7 +2371,7 @@ ${lines.join("\n")}
2156
2371
  });
2157
2372
 
2158
2373
  // src/crypto/cryptography-service.ts
2159
- import * as crypto from "crypto";
2374
+ import * as crypto from "node:crypto";
2160
2375
  import * as x509 from "@peculiar/x509";
2161
2376
  function setCryptoProvider() {
2162
2377
  x509.cryptoProvider.set(crypto.webcrypto);
@@ -2244,7 +2459,7 @@ var init_cryptography_service = __esm({
2244
2459
  const certPem = this.fetcher.getSymmetricKeyEncryptionPem();
2245
2460
  const encryptedKey = crypto.publicEncrypt(
2246
2461
  {
2247
- key: certPem,
2462
+ key: this.extractSpkiPem(certPem),
2248
2463
  oaepHash: "sha256",
2249
2464
  padding: crypto.constants.RSA_PKCS1_OAEP_PADDING
2250
2465
  },
@@ -2374,12 +2589,22 @@ var init_cryptography_service = __esm({
2374
2589
  // ---------------------------------------------------------------------------
2375
2590
  // Private helpers
2376
2591
  // ---------------------------------------------------------------------------
2592
+ /**
2593
+ * Extract a public-key SPKI PEM (`-----BEGIN PUBLIC KEY-----`) from a full
2594
+ * CERTIFICATE PEM. Node's `publicEncrypt` accepts either form, but Deno's
2595
+ * Node compatibility layer only accepts SPKI PEM, so we normalize upfront
2596
+ * to keep the library portable across runtimes.
2597
+ */
2598
+ extractSpkiPem(certPem) {
2599
+ const publicKey = new crypto.X509Certificate(certPem).publicKey;
2600
+ return publicKey.export({ type: "spki", format: "pem" });
2601
+ }
2377
2602
  /** RSA-OAEP SHA-256 encryption. */
2378
2603
  encryptRsaOaep(certPem, plaintext) {
2379
2604
  return new Uint8Array(
2380
2605
  crypto.publicEncrypt(
2381
2606
  {
2382
- key: certPem,
2607
+ key: this.extractSpkiPem(certPem),
2383
2608
  oaepHash: "sha256",
2384
2609
  padding: crypto.constants.RSA_PKCS1_OAEP_PADDING
2385
2610
  },
@@ -2417,7 +2642,7 @@ var init_cryptography_service = __esm({
2417
2642
  });
2418
2643
 
2419
2644
  // src/qr/verification-link-service.ts
2420
- import crypto2 from "crypto";
2645
+ import crypto2 from "node:crypto";
2421
2646
  var VerificationLinkService;
2422
2647
  var init_verification_link_service = __esm({
2423
2648
  "src/qr/verification-link-service.ts"() {
@@ -2443,11 +2668,11 @@ var init_verification_link_service = __esm({
2443
2668
  * Build certificate verification URL (Code II).
2444
2669
  * Format: {baseQrUrl}/certificate/{contextType}/{contextId}/{sellerNip}/{certSerial}/{hash_base64url}/{signature_base64url}
2445
2670
  */
2446
- buildCertificateVerificationUrl(contextType, contextId, sellerNip, certSerial, invoiceHashBase64, privateKeyPem) {
2671
+ buildCertificateVerificationUrl(contextType, contextId, sellerNip, certSerial, invoiceHashBase64, privateKeyPem, privateKeyPassword) {
2447
2672
  const hashBase64Url = this.base64ToBase64Url(invoiceHashBase64);
2448
2673
  const pathWithoutSignature = `${this.baseQrUrl}/certificate/${contextType}/${contextId}/${sellerNip}/${certSerial}/${hashBase64Url}`;
2449
2674
  const dataToSign = pathWithoutSignature.replace(/^https?:\/\//, "");
2450
- const key = crypto2.createPrivateKey(privateKeyPem);
2675
+ const key = privateKeyPassword !== void 0 ? crypto2.createPrivateKey({ key: privateKeyPem, format: "pem", passphrase: privateKeyPassword }) : crypto2.createPrivateKey(privateKeyPem);
2451
2676
  let signature;
2452
2677
  if (key.asymmetricKeyType === "rsa") {
2453
2678
  signature = crypto2.sign("sha256", Buffer.from(dataToSign), {
@@ -2723,7 +2948,7 @@ var init_document_structures = __esm({
2723
2948
  });
2724
2949
 
2725
2950
  // src/workflows/offline-invoice-workflow.ts
2726
- import crypto3 from "crypto";
2951
+ import crypto3 from "node:crypto";
2727
2952
  var OfflineInvoiceWorkflow;
2728
2953
  var init_offline_invoice_workflow = __esm({
2729
2954
  "src/workflows/offline-invoice-workflow.ts"() {
@@ -2761,7 +2986,8 @@ var init_offline_invoice_workflow = __esm({
2761
2986
  input.sellerNip,
2762
2987
  options.certificate.certificateSerial,
2763
2988
  invoiceHashBase64,
2764
- options.certificate.privateKeyPem
2989
+ options.certificate.privateKeyPem,
2990
+ options.certificate.password
2765
2991
  );
2766
2992
  }
2767
2993
  const submitBy = options?.customDeadline ? typeof options.customDeadline === "string" ? options.customDeadline : options.customDeadline.toISOString() : calculateOfflineDeadline(mode, input.invoiceDate, options?.maintenanceWindow).toISOString();
@@ -2951,7 +3177,8 @@ var init_offline_invoice_workflow = __esm({
2951
3177
  original.sellerNip,
2952
3178
  options.certificate.certificateSerial,
2953
3179
  correctedHashBase64,
2954
- options.certificate.privateKeyPem
3180
+ options.certificate.privateKeyPem,
3181
+ options.certificate.password
2955
3182
  );
2956
3183
  }
2957
3184
  const correctionMetadata = {
@@ -3013,9 +3240,43 @@ var signature_service_exports = {};
3013
3240
  __export(signature_service_exports, {
3014
3241
  SignatureService: () => SignatureService
3015
3242
  });
3016
- import * as crypto4 from "crypto";
3243
+ import * as crypto4 from "node:crypto";
3017
3244
  import { ExclusiveCanonicalization } from "xml-crypto";
3018
3245
  import { DOMParser, XMLSerializer } from "@xmldom/xmldom";
3246
+ function pickRsaAlgo() {
3247
+ return {
3248
+ nodeHashName: "sha256",
3249
+ signatureUri: RSA_SHA256_SIGNATURE_URI,
3250
+ digestUri: DIGEST_URI.sha256
3251
+ };
3252
+ }
3253
+ function pickEcdsaAlgo(privateKey) {
3254
+ const curve = privateKey.asymmetricKeyDetails?.namedCurve;
3255
+ switch (curve) {
3256
+ case "prime256v1":
3257
+ return {
3258
+ nodeHashName: "sha256",
3259
+ signatureUri: ECDSA_SIGNATURE_URI.sha256,
3260
+ digestUri: DIGEST_URI.sha256
3261
+ };
3262
+ case "secp384r1":
3263
+ return {
3264
+ nodeHashName: "sha384",
3265
+ signatureUri: ECDSA_SIGNATURE_URI.sha384,
3266
+ digestUri: DIGEST_URI.sha384
3267
+ };
3268
+ case "secp521r1":
3269
+ return {
3270
+ nodeHashName: "sha512",
3271
+ signatureUri: ECDSA_SIGNATURE_URI.sha512,
3272
+ digestUri: DIGEST_URI.sha512
3273
+ };
3274
+ default:
3275
+ throw new KSeFError(
3276
+ `Unsupported ECDSA curve: ${curve ?? "unknown"}. Supported: P-256 (prime256v1), P-384 (secp384r1), P-521 (secp521r1).`
3277
+ );
3278
+ }
3279
+ }
3019
3280
  function extractDerFromPem(pem) {
3020
3281
  const base64 = pem.replace(/-----BEGIN [A-Z\s]+-----/g, "").replace(/-----END [A-Z\s]+-----/g, "").replace(/\s+/g, "");
3021
3282
  return Buffer.from(base64, "base64");
@@ -3030,12 +3291,12 @@ function canonicalize(elem) {
3030
3291
  const c14n = new ExclusiveCanonicalization();
3031
3292
  return c14n.process(elem, {});
3032
3293
  }
3033
- function computeRootDigest(doc) {
3294
+ function computeRootDigest(doc, hashName) {
3034
3295
  const root = doc.documentElement;
3035
3296
  const canonical = canonicalize(root);
3036
- return crypto4.createHash("sha256").update(canonical, "utf-8").digest("base64");
3297
+ return crypto4.createHash(hashName).update(canonical, "utf-8").digest("base64");
3037
3298
  }
3038
- function computeSignedPropertiesDigest(qualifyingPropertiesXml) {
3299
+ function computeSignedPropertiesDigest(qualifyingPropertiesXml, hashName) {
3039
3300
  const parser2 = new DOMParser();
3040
3301
  const qpDoc = parser2.parseFromString(qualifyingPropertiesXml, "text/xml");
3041
3302
  const signedProps = findElementByLocalName(qpDoc.documentElement, "SignedProperties");
@@ -3043,9 +3304,9 @@ function computeSignedPropertiesDigest(qualifyingPropertiesXml) {
3043
3304
  throw new Error("SignedProperties element not found in QualifyingProperties");
3044
3305
  }
3045
3306
  const canonical = canonicalize(signedProps);
3046
- return crypto4.createHash("sha256").update(canonical, "utf-8").digest("base64");
3307
+ return crypto4.createHash(hashName).update(canonical, "utf-8").digest("base64");
3047
3308
  }
3048
- function buildSignedInfo(signatureAlgorithm, rootDigest, signedPropertiesDigest) {
3309
+ function buildSignedInfo(signatureAlgorithm, digestAlgorithm, rootDigest, signedPropertiesDigest) {
3049
3310
  return [
3050
3311
  `<ds:SignedInfo xmlns:ds="${DS_NS}">`,
3051
3312
  `<ds:CanonicalizationMethod Algorithm="${EXC_C14N_ALGORITHM}"/>`,
@@ -3056,7 +3317,7 @@ function buildSignedInfo(signatureAlgorithm, rootDigest, signedPropertiesDigest)
3056
3317
  `<ds:Transform Algorithm="${ENVELOPED_SIGNATURE_TRANSFORM}"/>`,
3057
3318
  `<ds:Transform Algorithm="${EXC_C14N_ALGORITHM}"/>`,
3058
3319
  `</ds:Transforms>`,
3059
- `<ds:DigestMethod Algorithm="${SHA256_DIGEST_METHOD}"/>`,
3320
+ `<ds:DigestMethod Algorithm="${digestAlgorithm}"/>`,
3060
3321
  `<ds:DigestValue>${rootDigest}</ds:DigestValue>`,
3061
3322
  `</ds:Reference>`,
3062
3323
  // Reference 2: SignedProperties
@@ -3064,22 +3325,22 @@ function buildSignedInfo(signatureAlgorithm, rootDigest, signedPropertiesDigest)
3064
3325
  `<ds:Transforms>`,
3065
3326
  `<ds:Transform Algorithm="${EXC_C14N_ALGORITHM}"/>`,
3066
3327
  `</ds:Transforms>`,
3067
- `<ds:DigestMethod Algorithm="${SHA256_DIGEST_METHOD}"/>`,
3328
+ `<ds:DigestMethod Algorithm="${digestAlgorithm}"/>`,
3068
3329
  `<ds:DigestValue>${signedPropertiesDigest}</ds:DigestValue>`,
3069
3330
  `</ds:Reference>`,
3070
3331
  `</ds:SignedInfo>`
3071
3332
  ].join("");
3072
3333
  }
3073
- function computeSignatureValue(canonicalSignedInfo, privateKey, isEc) {
3334
+ function computeSignatureValue(canonicalSignedInfo, privateKey, isEc, hashName) {
3074
3335
  const data = Buffer.from(canonicalSignedInfo, "utf-8");
3075
3336
  let signature;
3076
3337
  if (isEc) {
3077
- signature = crypto4.sign("sha256", data, {
3338
+ signature = crypto4.sign(hashName, data, {
3078
3339
  key: privateKey,
3079
3340
  dsaEncoding: "ieee-p1363"
3080
3341
  });
3081
3342
  } else {
3082
- signature = crypto4.sign("sha256", data, privateKey);
3343
+ signature = crypto4.sign(hashName, data, privateKey);
3083
3344
  }
3084
3345
  return signature.toString("base64");
3085
3346
  }
@@ -3100,7 +3361,7 @@ function buildSignatureElement(signedInfoXml, signatureValue, certBase64, qualif
3100
3361
  `</ds:Signature>`
3101
3362
  ].join("");
3102
3363
  }
3103
- function buildQualifyingProperties(signatureId, signedPropertiesId, certDigest, issuerName, serialNumber, signingTime) {
3364
+ function buildQualifyingProperties(signatureId, signedPropertiesId, certDigest, issuerName, serialNumber, signingTime, digestAlgorithm) {
3104
3365
  return [
3105
3366
  `<xades:QualifyingProperties`,
3106
3367
  ` Target="#${signatureId}"`,
@@ -3112,7 +3373,7 @@ function buildQualifyingProperties(signatureId, signedPropertiesId, certDigest,
3112
3373
  `<xades:SigningCertificate>`,
3113
3374
  `<xades:Cert>`,
3114
3375
  `<xades:CertDigest>`,
3115
- `<DigestMethod Algorithm="${SHA256_DIGEST_METHOD}"/>`,
3376
+ `<DigestMethod Algorithm="${digestAlgorithm}"/>`,
3116
3377
  `<DigestValue>${certDigest}</DigestValue>`,
3117
3378
  `</xades:CertDigest>`,
3118
3379
  `<xades:IssuerSerial>`,
@@ -3148,18 +3409,27 @@ function wrapBase64(base64) {
3148
3409
  }
3149
3410
  return lines.join("\n");
3150
3411
  }
3151
- 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;
3412
+ 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;
3152
3413
  var init_signature_service = __esm({
3153
3414
  "src/crypto/signature-service.ts"() {
3154
3415
  "use strict";
3416
+ init_ksef_error();
3155
3417
  XADES_NS = "http://uri.etsi.org/01903/v1.3.2#";
3156
3418
  DS_NS = "http://www.w3.org/2000/09/xmldsig#";
3157
3419
  SIGNED_PROPERTIES_TYPE = "http://uri.etsi.org/01903#SignedProperties";
3158
- SHA256_DIGEST_METHOD = "http://www.w3.org/2001/04/xmlenc#sha256";
3159
3420
  EXC_C14N_ALGORITHM = "http://www.w3.org/2001/10/xml-exc-c14n#";
3160
3421
  ENVELOPED_SIGNATURE_TRANSFORM = "http://www.w3.org/2000/09/xmldsig#enveloped-signature";
3161
- RSA_SHA256_SIGNATURE = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256";
3162
- ECDSA_SHA256_SIGNATURE = "http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha256";
3422
+ DIGEST_URI = {
3423
+ sha256: "http://www.w3.org/2001/04/xmlenc#sha256",
3424
+ sha384: "http://www.w3.org/2001/04/xmldsig-more#sha384",
3425
+ sha512: "http://www.w3.org/2001/04/xmlenc#sha512"
3426
+ };
3427
+ ECDSA_SIGNATURE_URI = {
3428
+ sha256: "http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha256",
3429
+ sha384: "http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha384",
3430
+ sha512: "http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha512"
3431
+ };
3432
+ RSA_SHA256_SIGNATURE_URI = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256";
3163
3433
  CLOCK_SKEW_BUFFER_MS = -6e4;
3164
3434
  SIGNATURE_ID = "Signature";
3165
3435
  SIGNED_PROPERTIES_ID = "SignedProperties";
@@ -3179,15 +3449,21 @@ var init_signature_service = __esm({
3179
3449
  }
3180
3450
  const certDer = extractDerFromPem(certPem);
3181
3451
  const certBase64 = certDer.toString("base64");
3182
- const certDigest = crypto4.createHash("sha256").update(certDer).digest("base64");
3183
3452
  const x5093 = new crypto4.X509Certificate(certPem);
3184
3453
  const issuerName = normalizeIssuerDn(x5093.issuer);
3185
3454
  const serialNumber = hexSerialToDecimal(x5093.serialNumber);
3186
3455
  const privateKey = crypto4.createPrivateKey(
3187
3456
  passphrase ? { key: privateKeyPem, format: "pem", passphrase } : privateKeyPem
3188
3457
  );
3189
- const isEc = privateKey.asymmetricKeyType === "ec";
3190
- const signatureAlgorithm = isEc ? ECDSA_SHA256_SIGNATURE : RSA_SHA256_SIGNATURE;
3458
+ const keyType = privateKey.asymmetricKeyType;
3459
+ if (keyType !== "ec" && keyType !== "rsa") {
3460
+ throw new KSeFError(
3461
+ `Unsupported private key type: ${keyType ?? "unknown"}. Supported: RSA and ECDSA.`
3462
+ );
3463
+ }
3464
+ const isEc = keyType === "ec";
3465
+ const algo = isEc ? pickEcdsaAlgo(privateKey) : pickRsaAlgo();
3466
+ const certDigest = crypto4.createHash(algo.nodeHashName).update(certDer).digest("base64");
3191
3467
  const signingTime = new Date(Date.now() + CLOCK_SKEW_BUFFER_MS).toISOString();
3192
3468
  const parser2 = new DOMParser();
3193
3469
  const doc = parser2.parseFromString(xml, "text/xml");
@@ -3201,12 +3477,17 @@ var init_signature_service = __esm({
3201
3477
  certDigest,
3202
3478
  issuerName,
3203
3479
  serialNumber,
3204
- signingTime
3480
+ signingTime,
3481
+ algo.digestUri
3482
+ );
3483
+ const rootDigest = computeRootDigest(doc, algo.nodeHashName);
3484
+ const signedPropertiesDigest = computeSignedPropertiesDigest(
3485
+ qualifyingPropertiesXml,
3486
+ algo.nodeHashName
3205
3487
  );
3206
- const rootDigest = computeRootDigest(doc);
3207
- const signedPropertiesDigest = computeSignedPropertiesDigest(qualifyingPropertiesXml);
3208
3488
  const signedInfoXml = buildSignedInfo(
3209
- signatureAlgorithm,
3489
+ algo.signatureUri,
3490
+ algo.digestUri,
3210
3491
  rootDigest,
3211
3492
  signedPropertiesDigest
3212
3493
  );
@@ -3215,7 +3496,8 @@ var init_signature_service = __esm({
3215
3496
  const signatureValue = computeSignatureValue(
3216
3497
  canonicalSignedInfo,
3217
3498
  privateKey,
3218
- isEc
3499
+ isEc,
3500
+ algo.nodeHashName
3219
3501
  );
3220
3502
  const signatureXml = buildSignatureElement(
3221
3503
  signedInfoXml,
@@ -3312,6 +3594,11 @@ function buildRestClientConfig(options, authManager) {
3312
3594
  endpointLimits: options.rateLimit.endpointLimits
3313
3595
  });
3314
3596
  }
3597
+ if (options?.circuitBreaker === null) {
3598
+ config.circuitBreakerPolicy = null;
3599
+ } else if (options?.circuitBreaker) {
3600
+ config.circuitBreakerPolicy = new CircuitBreakerPolicy(options.circuitBreaker);
3601
+ }
3315
3602
  if (options?.presignedUrlHosts) {
3316
3603
  const base = defaultPresignedUrlPolicy();
3317
3604
  config.presignedUrlPolicy = {
@@ -3329,6 +3616,7 @@ var init_client = __esm({
3329
3616
  init_rest_client();
3330
3617
  init_retry_policy();
3331
3618
  init_rate_limit_policy();
3619
+ init_circuit_breaker_policy();
3332
3620
  init_presigned_url_policy();
3333
3621
  init_auth_manager();
3334
3622
  init_auth();
@@ -3655,10 +3943,35 @@ var init_invoice_field_extractor = __esm({
3655
3943
 
3656
3944
  // src/xml/xml-engine.ts
3657
3945
  import { XMLBuilder, XMLParser as XMLParser3 } from "fast-xml-parser";
3658
- var parser, builder;
3946
+ function createObjectBuilder(pretty = false) {
3947
+ return new XMLBuilder({
3948
+ ignoreAttributes: false,
3949
+ preserveOrder: false,
3950
+ attributeNamePrefix: "@_",
3951
+ textNodeName: "#text",
3952
+ format: pretty,
3953
+ suppressBooleanAttributes: false,
3954
+ suppressEmptyNode: false,
3955
+ processEntities: true
3956
+ });
3957
+ }
3958
+ function prependDeclaration(xml) {
3959
+ return xml.startsWith("<?xml") ? xml : `${XML_DECLARATION}${xml}`;
3960
+ }
3961
+ function buildXml(document) {
3962
+ return prependDeclaration(builder.build(document));
3963
+ }
3964
+ function buildXmlFromObject(document, options) {
3965
+ return prependDeclaration(createObjectBuilder(options?.pretty).build(document));
3966
+ }
3967
+ function stripBom(input) {
3968
+ return input.charCodeAt(0) === 65279 ? input.slice(1) : input;
3969
+ }
3970
+ var XML_DECLARATION, parser, builder;
3659
3971
  var init_xml_engine = __esm({
3660
3972
  "src/xml/xml-engine.ts"() {
3661
3973
  "use strict";
3974
+ XML_DECLARATION = '<?xml version="1.0" encoding="UTF-8"?>\n';
3662
3975
  parser = new XMLParser3({
3663
3976
  ignoreAttributes: false,
3664
3977
  preserveOrder: true,
@@ -3685,31 +3998,485 @@ var init_xml_engine = __esm({
3685
3998
  });
3686
3999
 
3687
4000
  // src/xml/order-map.ts
4001
+ function comparePKey(a, b) {
4002
+ const normalize = (value) => value.replace(/^P_/, "").split("_").map((part) => Number.isNaN(Number(part)) ? part : Number(part));
4003
+ const aParts = normalize(a);
4004
+ const bParts = normalize(b);
4005
+ const max = Math.max(aParts.length, bParts.length);
4006
+ for (let i = 0; i < max; i += 1) {
4007
+ const left = aParts[i];
4008
+ const right = bParts[i];
4009
+ if (left === void 0) return -1;
4010
+ if (right === void 0) return 1;
4011
+ if (typeof left === "number" && typeof right === "number") {
4012
+ if (left !== right) return left - right;
4013
+ continue;
4014
+ }
4015
+ const leftStr = String(left);
4016
+ const rightStr = String(right);
4017
+ if (leftStr !== rightStr) return leftStr < rightStr ? -1 : 1;
4018
+ }
4019
+ return 0;
4020
+ }
4021
+ function isObject(value) {
4022
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
4023
+ }
4024
+ function normalizeValueForKey(key, value) {
4025
+ if (Array.isArray(value)) {
4026
+ return value.map(
4027
+ (item) => isObject(item) ? orderXmlObject(item, key) : normalizeValue(item)
4028
+ );
4029
+ }
4030
+ if (isObject(value)) return orderXmlObject(value, key);
4031
+ return value;
4032
+ }
4033
+ function normalizeValue(value) {
4034
+ if (Array.isArray(value)) return value.map((item) => normalizeValue(item));
4035
+ if (isObject(value)) return orderXmlObject(value);
4036
+ return value;
4037
+ }
4038
+ function orderXmlObject(value, contextKey) {
4039
+ const order = contextKey ? ORDER_MAP[contextKey] : void 0;
4040
+ const keys = Object.keys(value);
4041
+ const used = /* @__PURE__ */ new Set();
4042
+ const ordered = {};
4043
+ if (order) {
4044
+ for (const key of order) {
4045
+ if (Object.prototype.hasOwnProperty.call(value, key)) {
4046
+ const item = value[key];
4047
+ if (item !== void 0) ordered[key] = normalizeValueForKey(key, item);
4048
+ used.add(key);
4049
+ }
4050
+ }
4051
+ }
4052
+ const pKeys = keys.filter((key) => !used.has(key) && key.startsWith("P_")).sort(comparePKey);
4053
+ for (const key of pKeys) {
4054
+ const item = value[key];
4055
+ if (item !== void 0) ordered[key] = normalizeValueForKey(key, item);
4056
+ used.add(key);
4057
+ }
4058
+ for (const key of keys) {
4059
+ if (used.has(key)) continue;
4060
+ const item = value[key];
4061
+ if (item !== void 0) ordered[key] = normalizeValueForKey(key, item);
4062
+ }
4063
+ return ordered;
4064
+ }
4065
+ var ORDER_MAP;
3688
4066
  var init_order_map = __esm({
3689
4067
  "src/xml/order-map.ts"() {
3690
4068
  "use strict";
4069
+ ORDER_MAP = {
4070
+ Faktura: ["Naglowek", "Podmiot1", "Podmiot2", "Podmiot3", "Fa", "Stopka"],
4071
+ Naglowek: ["KodFormularza", "WariantFormularza", "DataWytworzeniaFa", "SystemInfo"],
4072
+ Podmiot1: [
4073
+ "PrefiksPodatnika",
4074
+ "NrEORI",
4075
+ "DaneIdentyfikacyjne",
4076
+ "Adres",
4077
+ "AdresKoresp",
4078
+ "DaneKontaktowe",
4079
+ "StatusInfoPodatnika"
4080
+ ],
4081
+ Podmiot2: [
4082
+ "NrEORI",
4083
+ "DaneIdentyfikacyjne",
4084
+ "Adres",
4085
+ "AdresKoresp",
4086
+ "DaneKontaktowe",
4087
+ "NrKlienta",
4088
+ "IDNabywcy",
4089
+ "JST",
4090
+ "GV"
4091
+ ],
4092
+ Podmiot3: [
4093
+ "IDNabywcy",
4094
+ "NrEORI",
4095
+ "DaneIdentyfikacyjne",
4096
+ "Adres",
4097
+ "AdresKoresp",
4098
+ "DaneKontaktowe",
4099
+ "Rola",
4100
+ "Udzial"
4101
+ ],
4102
+ DaneIdentyfikacyjne: [
4103
+ "NIP",
4104
+ "IDWew",
4105
+ "KodUE",
4106
+ "NrVatUE",
4107
+ "KodKraju",
4108
+ "NrID",
4109
+ "BrakID",
4110
+ "Nazwa",
4111
+ "Identyfikator",
4112
+ "KRS"
4113
+ ],
4114
+ Adres: ["KodKraju", "AdresL1", "AdresL2", "AdresL3"],
4115
+ DaneKontaktowe: ["Email", "Telefon"],
4116
+ Fa: [
4117
+ "KodWaluty",
4118
+ "P_1",
4119
+ "P_1M",
4120
+ "P_2",
4121
+ "WZ",
4122
+ "P_6",
4123
+ "OkresFa",
4124
+ // Multi-rate interleave per VAT group — DO NOT flatten into P_13_* block then P_14_* block.
4125
+ // See smekcio TS d1ec8fe and the "multi-rate interleave" regression test.
4126
+ "P_13_1",
4127
+ "P_14_1",
4128
+ "P_14_1W",
4129
+ "P_13_2",
4130
+ "P_14_2",
4131
+ "P_14_2W",
4132
+ "P_13_3",
4133
+ "P_14_3",
4134
+ "P_14_3W",
4135
+ "P_13_4",
4136
+ "P_14_4",
4137
+ "P_14_4W",
4138
+ "P_13_5",
4139
+ "P_14_5",
4140
+ "P_13_6_1",
4141
+ "P_13_6_2",
4142
+ "P_13_6_3",
4143
+ "P_13_7",
4144
+ "P_13_8",
4145
+ "P_13_9",
4146
+ "P_13_10",
4147
+ "P_13_11",
4148
+ "P_15",
4149
+ "KursWalutyZ",
4150
+ "Adnotacje",
4151
+ "RodzajFaktury",
4152
+ "PrzyczynaKorekty",
4153
+ "TypKorekty",
4154
+ "DaneFaKorygowanej",
4155
+ "OkresFaKorygowanej",
4156
+ "NrFaKorygowany",
4157
+ "Podmiot1K",
4158
+ "Podmiot2K",
4159
+ "Podmiot3K",
4160
+ "ZaliczkaCzesciowa",
4161
+ "FP",
4162
+ "TP",
4163
+ "DodatkowyOpis",
4164
+ "FakturaZaliczkowa",
4165
+ "ZwrotAkcyzy",
4166
+ "FaWiersz",
4167
+ "FaWiersze",
4168
+ "Rozliczenie",
4169
+ "Platnosc"
4170
+ ],
4171
+ Adnotacje: ["P_16", "P_17", "P_18", "P_18A", "Zwolnienie", "NoweSrodkiTransportu", "P_23", "PMarzy"],
4172
+ OkresFa: ["P_6_Od", "P_6_Do"],
4173
+ FaWiersz: [
4174
+ "NrWierszaFa",
4175
+ "UU_ID",
4176
+ "P_6A",
4177
+ "P_7",
4178
+ "Indeks",
4179
+ "GTIN",
4180
+ "PKWiU",
4181
+ "CN",
4182
+ "PKOB",
4183
+ "P_8A",
4184
+ "P_8B",
4185
+ "P_9A",
4186
+ "P_9B",
4187
+ "P_10",
4188
+ "P_11",
4189
+ "P_11A",
4190
+ "P_11Vat",
4191
+ "P_12",
4192
+ "P_12_XII",
4193
+ "P_12_Zal_15",
4194
+ "KwotaAkcyzy",
4195
+ "GTU",
4196
+ "Procedura",
4197
+ "KursWaluty",
4198
+ "StanPrzed"
4199
+ ]
4200
+ };
3691
4201
  }
3692
4202
  });
3693
4203
 
3694
4204
  // src/xml/faktura-builder.ts
4205
+ function toKodFormularza(formCode) {
4206
+ return {
4207
+ "@_kodSystemowy": formCode.systemCode,
4208
+ "@_wersjaSchemy": formCode.schemaVersion,
4209
+ "#text": formCode.value
4210
+ };
4211
+ }
4212
+ function isFormCodeShape(value) {
4213
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
4214
+ const candidate = value;
4215
+ return typeof candidate.systemCode === "string" && typeof candidate.schemaVersion === "string" && typeof candidate.value === "string";
4216
+ }
4217
+ function isObject2(value) {
4218
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
4219
+ }
4220
+ function normalizeTopLevelChild(key, value) {
4221
+ if (key === "Naglowek" && isObject2(value)) {
4222
+ return normalizeNaglowek(value);
4223
+ }
4224
+ if (Array.isArray(value)) {
4225
+ return value.map((item) => isObject2(item) ? orderXmlObject(item, key) : item);
4226
+ }
4227
+ if (isObject2(value)) return orderXmlObject(value, key);
4228
+ return value;
4229
+ }
4230
+ function normalizeNaglowek(value) {
4231
+ const result = {};
4232
+ for (const [key, item] of Object.entries(value)) {
4233
+ if (item === void 0) continue;
4234
+ if (key === "KodFormularza" && isFormCodeShape(item)) {
4235
+ result[key] = toKodFormularza(item);
4236
+ continue;
4237
+ }
4238
+ if (Array.isArray(item)) {
4239
+ result[key] = item.map(
4240
+ (entry) => isObject2(entry) ? orderXmlObject(entry, key) : entry
4241
+ );
4242
+ continue;
4243
+ }
4244
+ if (isObject2(item)) {
4245
+ result[key] = orderXmlObject(item, key);
4246
+ continue;
4247
+ }
4248
+ result[key] = item;
4249
+ }
4250
+ return result;
4251
+ }
4252
+ function normalizeTopLevel(input) {
4253
+ const result = {};
4254
+ for (const [key, value] of Object.entries(input)) {
4255
+ if (value === void 0) continue;
4256
+ result[key] = normalizeTopLevelChild(key, value);
4257
+ }
4258
+ return result;
4259
+ }
4260
+ function buildFakturaXml(faktura, options = {}) {
4261
+ const schema = options.schema ?? "FA3";
4262
+ const fakturaNamespace = options.fakturaNamespace ?? FAKTURA_NAMESPACE[schema];
4263
+ const etdNamespace = options.etdNamespace ?? ETD_NAMESPACE[schema];
4264
+ const normalized = normalizeTopLevel(faktura);
4265
+ const ordered = orderXmlObject(normalized, "Faktura");
4266
+ const document = {
4267
+ Faktura: {
4268
+ ...ordered,
4269
+ "@_xmlns": fakturaNamespace,
4270
+ "@_xmlns:etd": etdNamespace
4271
+ }
4272
+ };
4273
+ return buildXmlFromObject(document, { pretty: options.pretty });
4274
+ }
4275
+ function isFakturaInput(input) {
4276
+ if (!isObject2(input)) return false;
4277
+ const candidate = input;
4278
+ if (!Object.prototype.hasOwnProperty.call(candidate, "Naglowek")) return false;
4279
+ if (!Object.prototype.hasOwnProperty.call(candidate, "Fa")) return false;
4280
+ return isObject2(candidate.Naglowek) && isObject2(candidate.Fa);
4281
+ }
4282
+ var FAKTURA_NAMESPACE, ETD_NAMESPACE;
3695
4283
  var init_faktura_builder = __esm({
3696
4284
  "src/xml/faktura-builder.ts"() {
3697
4285
  "use strict";
3698
4286
  init_xml_engine();
3699
4287
  init_order_map();
4288
+ FAKTURA_NAMESPACE = {
4289
+ FA2: "http://crd.gov.pl/wzor/2023/06/29/12648/",
4290
+ FA3: "http://crd.gov.pl/wzor/2025/06/25/13775/"
4291
+ };
4292
+ ETD_NAMESPACE = {
4293
+ FA2: "http://crd.gov.pl/xml/schematy/2020/10/08/eDokumenty",
4294
+ FA3: "http://crd.gov.pl/xml/schematy/dziedzinowe/mf/2022/01/05/eD/DefinicjeTypy/"
4295
+ };
3700
4296
  }
3701
4297
  });
3702
4298
 
3703
4299
  // src/xml/pef-builder.ts
4300
+ function isPefUblDocumentInput(input) {
4301
+ if (typeof input !== "object" || input === null || Array.isArray(input)) return false;
4302
+ const obj = input;
4303
+ const invoice3 = obj.Invoice;
4304
+ const creditNote = obj.CreditNote;
4305
+ const hasInvoice = typeof invoice3 === "object" && invoice3 !== null && !Array.isArray(invoice3);
4306
+ const hasCreditNote = typeof creditNote === "object" && creditNote !== null && !Array.isArray(creditNote);
4307
+ return hasInvoice !== hasCreditNote;
4308
+ }
4309
+ function inferSchema(input) {
4310
+ return "Invoice" in input ? "PEF" : "PEF_KOR";
4311
+ }
4312
+ function isNonArrayObject(value) {
4313
+ return typeof value === "object" && value !== null && !Array.isArray(value);
4314
+ }
4315
+ function assertPefShape(input) {
4316
+ if (!isNonArrayObject(input)) {
4317
+ throw new KSeFValidationError("PEF input must be a non-array object.");
4318
+ }
4319
+ const hasInvoiceKey = "Invoice" in input;
4320
+ const hasCreditNoteKey = "CreditNote" in input;
4321
+ if (hasInvoiceKey && hasCreditNoteKey) {
4322
+ throw new KSeFValidationError(
4323
+ "PEF input must contain exactly one of `Invoice` or `CreditNote`, not both."
4324
+ );
4325
+ }
4326
+ if (!hasInvoiceKey && !hasCreditNoteKey) {
4327
+ throw new KSeFValidationError(
4328
+ "PEF input must contain either an `Invoice` or a `CreditNote` root element."
4329
+ );
4330
+ }
4331
+ const rootKey = hasInvoiceKey ? "Invoice" : "CreditNote";
4332
+ if (!isNonArrayObject(input[rootKey])) {
4333
+ throw new KSeFValidationError(
4334
+ `PEF \`${rootKey}\` value must be a non-array object.`
4335
+ );
4336
+ }
4337
+ }
4338
+ function buildPefXml(input, options = {}) {
4339
+ assertPefShape(input);
4340
+ const inferred = inferSchema(input);
4341
+ const schema = options.schema ?? input.schema ?? inferred;
4342
+ if (schema !== inferred) {
4343
+ throw new KSeFValidationError(
4344
+ `PEF schema mismatch: expected ${inferred} based on root element, got ${schema}.`
4345
+ );
4346
+ }
4347
+ const commonNamespaces = {
4348
+ "@_xmlns:ext": UBL_EXT_NS,
4349
+ "@_xmlns:cbc": UBL_CBC_NS,
4350
+ "@_xmlns:cac": UBL_CAC_NS,
4351
+ "@_xmlns:cbc-pl": UBL_CBC_PL_NS,
4352
+ "@_xmlns:cac-pl": UBL_CAC_PL_NS
4353
+ };
4354
+ const document = "Invoice" in input ? {
4355
+ Invoice: {
4356
+ ...input.Invoice,
4357
+ "@_xmlns": PEF_NAMESPACE.PEF,
4358
+ ...commonNamespaces
4359
+ }
4360
+ } : {
4361
+ CreditNote: {
4362
+ ...input.CreditNote,
4363
+ "@_xmlns": PEF_NAMESPACE.PEF_KOR,
4364
+ ...commonNamespaces
4365
+ }
4366
+ };
4367
+ return buildXmlFromObject(document, { pretty: options.pretty });
4368
+ }
4369
+ var PEF_NAMESPACE, UBL_EXT_NS, UBL_CBC_NS, UBL_CAC_NS, UBL_CBC_PL_NS, UBL_CAC_PL_NS;
3704
4370
  var init_pef_builder = __esm({
3705
4371
  "src/xml/pef-builder.ts"() {
3706
4372
  "use strict";
3707
4373
  init_ksef_validation_error();
3708
4374
  init_xml_engine();
4375
+ PEF_NAMESPACE = {
4376
+ PEF: "urn:oasis:names:specification:ubl:schema:xsd:Invoice-2",
4377
+ PEF_KOR: "urn:oasis:names:specification:ubl:schema:xsd:CreditNote-2"
4378
+ };
4379
+ UBL_EXT_NS = "urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2";
4380
+ UBL_CBC_NS = "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2";
4381
+ UBL_CAC_NS = "urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2";
4382
+ UBL_CBC_PL_NS = "urn:pl:extended:CommonBasicComponents-2";
4383
+ UBL_CAC_PL_NS = "urn:pl:extended:CommonAggregateComponents-2";
3709
4384
  }
3710
4385
  });
3711
4386
 
3712
4387
  // src/xml/invoice-serializer.ts
4388
+ function isNonArrayObject2(value) {
4389
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
4390
+ }
4391
+ function classifyUnknownObject(input) {
4392
+ const looksLikeFaktura = "Naglowek" in input || "Fa" in input || "Podmiot1" in input || "Podmiot2" in input;
4393
+ const hasInvoice = "Invoice" in input;
4394
+ const hasCreditNote = "CreditNote" in input;
4395
+ if (hasInvoice && hasCreditNote) {
4396
+ return new KSeFValidationError(
4397
+ "Input must contain exactly one of `Invoice` or `CreditNote`, not both."
4398
+ );
4399
+ }
4400
+ if (hasInvoice !== hasCreditNote) {
4401
+ const rootKey = hasInvoice ? "Invoice" : "CreditNote";
4402
+ if (!isNonArrayObject2(input[rootKey])) {
4403
+ return KSeFValidationError.fromField(
4404
+ rootKey,
4405
+ `PEF \`${rootKey}\` value must be a non-array object.`
4406
+ );
4407
+ }
4408
+ }
4409
+ if (looksLikeFaktura) {
4410
+ const missing = [];
4411
+ if (!("Naglowek" in input)) missing.push("Naglowek");
4412
+ if (!("Fa" in input)) missing.push("Fa");
4413
+ if (missing.length > 0) {
4414
+ return KSeFValidationError.fromField(
4415
+ missing[0],
4416
+ `Faktura input is missing required top-level key(s): ${missing.join(", ")}.`
4417
+ );
4418
+ }
4419
+ for (const key of ["Naglowek", "Fa"]) {
4420
+ if (!isNonArrayObject2(input[key])) {
4421
+ return KSeFValidationError.fromField(
4422
+ key,
4423
+ `Faktura \`${key}\` value must be a non-null, non-array object.`
4424
+ );
4425
+ }
4426
+ }
4427
+ return new KSeFValidationError(
4428
+ "Faktura-like input failed shape validation: `Naglowek` and `Fa` must be own enumerable properties on the input object."
4429
+ );
4430
+ }
4431
+ return new KSeFValidationError(
4432
+ "Unsupported invoice input shape: expected `FakturaInput` (with `Naglowek` + `Fa`) or `PefUblDocumentInput` (with `Invoice` or `CreditNote`)."
4433
+ );
4434
+ }
4435
+ function serializeInvoiceXml(input, options) {
4436
+ if (Buffer.isBuffer(input)) return input;
4437
+ if (typeof input === "string") {
4438
+ return Buffer.from(stripBom(input), "utf8");
4439
+ }
4440
+ if (Array.isArray(input)) {
4441
+ return Buffer.from(stripBom(buildXml(input)), "utf8");
4442
+ }
4443
+ if (input && typeof input === "object") {
4444
+ const schema = options?.schema;
4445
+ if (isPefUblDocumentInput(input)) {
4446
+ if (schema && !PEF_SCHEMAS.has(schema)) {
4447
+ throw new KSeFValidationError(
4448
+ `schema option ${schema} is not compatible with a PEF / PEF_KOR input.`
4449
+ );
4450
+ }
4451
+ const pefSchema = schema === "PEF" || schema === "PEF_KOR" ? schema : void 0;
4452
+ const xml = buildPefXml(input, {
4453
+ schema: pefSchema,
4454
+ pretty: options?.pretty
4455
+ });
4456
+ return Buffer.from(stripBom(xml), "utf8");
4457
+ }
4458
+ if (isFakturaInput(input)) {
4459
+ if (schema && !FAKTURA_SCHEMAS.has(schema)) {
4460
+ throw new KSeFValidationError(
4461
+ `schema option ${schema} is not compatible with a Faktura input.`
4462
+ );
4463
+ }
4464
+ const fakturaSchema = schema === "FA2" || schema === "FA3" ? schema : void 0;
4465
+ const xml = buildFakturaXml(input, {
4466
+ schema: fakturaSchema,
4467
+ fakturaNamespace: options?.fakturaNamespace,
4468
+ etdNamespace: options?.etdNamespace,
4469
+ pretty: options?.pretty
4470
+ });
4471
+ return Buffer.from(stripBom(xml), "utf8");
4472
+ }
4473
+ throw classifyUnknownObject(input);
4474
+ }
4475
+ throw new KSeFValidationError(
4476
+ "Unsupported invoice input type: expected Buffer, string, XmlDocument, FakturaInput, or PefUblDocumentInput."
4477
+ );
4478
+ }
4479
+ var FAKTURA_SCHEMAS, PEF_SCHEMAS;
3713
4480
  var init_invoice_serializer = __esm({
3714
4481
  "src/xml/invoice-serializer.ts"() {
3715
4482
  "use strict";
@@ -3717,6 +4484,8 @@ var init_invoice_serializer = __esm({
3717
4484
  init_faktura_builder();
3718
4485
  init_pef_builder();
3719
4486
  init_xml_engine();
4487
+ FAKTURA_SCHEMAS = /* @__PURE__ */ new Set(["FA2", "FA3"]);
4488
+ PEF_SCHEMAS = /* @__PURE__ */ new Set(["PEF", "PEF_KOR"]);
3720
4489
  }
3721
4490
  });
3722
4491
 
@@ -5581,11 +6350,11 @@ async function validateSchema(xml, options, _parsed) {
5581
6350
  const prefix = rootElement ? `/${rootElement}/` : "/";
5582
6351
  const validationErrors = result.error.issues.map((issue) => {
5583
6352
  const zodPath = issue.path.join("/");
5584
- const path10 = zodPath ? `${prefix}${zodPath}` : rootElement ? `/${rootElement}` : void 0;
6353
+ const path12 = zodPath ? `${prefix}${zodPath}` : rootElement ? `/${rootElement}` : void 0;
5585
6354
  return {
5586
6355
  code: mapZodErrorCode(issue),
5587
6356
  message: issue.message,
5588
- path: path10
6357
+ path: path12
5589
6358
  };
5590
6359
  });
5591
6360
  return { valid: false, schemaType, errors: validationErrors };
@@ -5625,9 +6394,9 @@ function validateBusinessRules(xml, _parsed) {
5625
6394
  collectDateErrors(object, rootElement, errors);
5626
6395
  return { valid: errors.length === 0, schemaType, errors };
5627
6396
  }
5628
- function collectNipPeselErrors(obj, path10, errors) {
6397
+ function collectNipPeselErrors(obj, path12, errors) {
5629
6398
  for (const [key, value] of Object.entries(obj)) {
5630
- const currentPath = path10 ? `${path10}/${key}` : key;
6399
+ const currentPath = path12 ? `${path12}/${key}` : key;
5631
6400
  if (key === "NIP" && typeof value === "string") {
5632
6401
  if (!isValidNip(value)) {
5633
6402
  errors.push({
@@ -5714,7 +6483,7 @@ var init_invoice_validator = __esm({
5714
6483
  });
5715
6484
 
5716
6485
  // src/builders/batch-file.ts
5717
- import * as crypto6 from "crypto";
6486
+ import * as crypto6 from "node:crypto";
5718
6487
  function splitBuffer(data, maxPartSize) {
5719
6488
  if (data.length <= maxPartSize) {
5720
6489
  return [data];
@@ -6043,18 +6812,18 @@ var init_batch_session_workflow = __esm({
6043
6812
  });
6044
6813
 
6045
6814
  // src/cli/index.ts
6046
- import { readFileSync as readFileSync9 } from "fs";
6047
- import { fileURLToPath } from "url";
6048
- import { dirname as dirname2, resolve } from "path";
6049
- import { defineCommand as defineCommand18, runMain } from "citty";
6815
+ import { readFileSync as readFileSync11 } from "node:fs";
6816
+ import { fileURLToPath as fileURLToPath2 } from "node:url";
6817
+ import { dirname as dirname3, resolve } from "node:path";
6818
+ import { defineCommand as defineCommand19, runMain } from "citty";
6050
6819
 
6051
6820
  // src/cli/commands/config.ts
6052
6821
  import { defineCommand } from "citty";
6053
6822
 
6054
6823
  // src/cli/config-store.ts
6055
- import * as fs from "fs";
6056
- import * as path from "path";
6057
- import * as os from "os";
6824
+ import * as fs from "node:fs";
6825
+ import * as path from "node:path";
6826
+ import * as os from "node:os";
6058
6827
 
6059
6828
  // src/cli/types.ts
6060
6829
  var ENV_MAP = {
@@ -6133,9 +6902,9 @@ function outputWarning(msg) {
6133
6902
  }
6134
6903
 
6135
6904
  // src/cli/session-store.ts
6136
- import * as fs2 from "fs";
6137
- import * as path2 from "path";
6138
- import * as os2 from "os";
6905
+ import * as fs2 from "node:fs";
6906
+ import * as path2 from "node:path";
6907
+ import * as os2 from "node:os";
6139
6908
  var SESSION_DIR = path2.join(os2.homedir(), ".ksef");
6140
6909
  var SESSION_FILE = path2.join(SESSION_DIR, "session.json");
6141
6910
  function loadSession() {
@@ -6306,7 +7075,13 @@ async function withErrorHandler(fn, opts) {
6306
7075
  await fn();
6307
7076
  } catch (error) {
6308
7077
  renderCliError(error, opts);
6309
- process.exit(1);
7078
+ let code = 1;
7079
+ try {
7080
+ code = opts?.exitCode?.(error) ?? 1;
7081
+ } catch {
7082
+ code = 1;
7083
+ }
7084
+ process.exit(code);
6310
7085
  }
6311
7086
  }
6312
7087
 
@@ -6384,21 +7159,21 @@ var configCommand = defineCommand({
6384
7159
  });
6385
7160
 
6386
7161
  // src/cli/commands/auth.ts
6387
- import * as fs5 from "fs";
7162
+ import * as fs5 from "node:fs";
6388
7163
  import { defineCommand as defineCommand2 } from "citty";
6389
- import { consola as consola6 } from "consola";
7164
+ import { consola as consola7 } from "consola";
6390
7165
 
6391
7166
  // src/cli/client-factory.ts
6392
7167
  init_client();
6393
- import { consola as consola5 } from "consola";
7168
+ import { consola as consola6 } from "consola";
6394
7169
 
6395
7170
  // src/cli/session-recovery.ts
6396
- import { consola as consola4 } from "consola";
7171
+ import { consola as consola5 } from "consola";
6397
7172
 
6398
7173
  // src/cli/credentials-store.ts
6399
- import * as fs3 from "fs";
6400
- import * as path3 from "path";
6401
- import * as os3 from "os";
7174
+ import * as fs3 from "node:fs";
7175
+ import * as path3 from "node:path";
7176
+ import * as os3 from "node:os";
6402
7177
  var CREDENTIALS_DIR = path3.join(os3.homedir(), ".ksef");
6403
7178
  var CREDENTIALS_FILE = path3.join(CREDENTIALS_DIR, "credentials.json");
6404
7179
  function loadCredentials() {
@@ -6460,7 +7235,7 @@ async function recoverSession(globalOpts) {
6460
7235
  const session = loadSession();
6461
7236
  if (session && isSessionExpired(session) && session.refreshToken) {
6462
7237
  try {
6463
- consola4.info("Session expired, refreshing token...");
7238
+ consola5.info("Session expired, refreshing token...");
6464
7239
  const opts = globalOpts.env ? globalOpts : { ...globalOpts, env: session.environment };
6465
7240
  const client = createClient(opts);
6466
7241
  client.authManager.setAccessToken(session.accessToken);
@@ -6477,7 +7252,7 @@ async function recoverSession(globalOpts) {
6477
7252
  const credentials = loadCredentials();
6478
7253
  const config = loadConfig();
6479
7254
  if (credentials?.token && config.nip) {
6480
- consola4.info("Logging in with stored credentials...");
7255
+ consola5.info("Logging in with stored credentials...");
6481
7256
  const env = globalOpts.env ?? session?.environment ?? config.environment;
6482
7257
  const opts = { ...globalOpts, env };
6483
7258
  const client = createClient(opts);
@@ -6509,7 +7284,7 @@ async function recoverSession(globalOpts) {
6509
7284
  // src/cli/client-factory.ts
6510
7285
  function createClient(globalOpts) {
6511
7286
  if (globalOpts.verbose) {
6512
- consola5.level = 4;
7287
+ consola6.level = 4;
6513
7288
  }
6514
7289
  const config = loadConfig();
6515
7290
  const env = globalOpts.env ?? config.environment;
@@ -6522,7 +7297,7 @@ function createClient(globalOpts) {
6522
7297
  }
6523
7298
  async function requireSession(globalOpts) {
6524
7299
  if (globalOpts.verbose) {
6525
- consola5.level = 4;
7300
+ consola6.level = 4;
6526
7301
  }
6527
7302
  const session = loadSession();
6528
7303
  if (session && !isSessionExpired(session)) {
@@ -6538,9 +7313,9 @@ async function requireSession(globalOpts) {
6538
7313
  }
6539
7314
 
6540
7315
  // src/cli/pending-challenge-store.ts
6541
- import * as fs4 from "fs";
6542
- import * as path4 from "path";
6543
- import * as os4 from "os";
7316
+ import * as fs4 from "node:fs";
7317
+ import * as path4 from "node:path";
7318
+ import * as os4 from "node:os";
6544
7319
  var PENDING_CHALLENGE_FILE = path4.join(os4.homedir(), ".ksef", "pending-challenge.json");
6545
7320
  function savePendingChallenge(data) {
6546
7321
  const dir = path4.dirname(PENDING_CHALLENGE_FILE);
@@ -6613,7 +7388,7 @@ var login = defineCommand2({
6613
7388
  const globalOpts = getGlobalOpts(args);
6614
7389
  const config = loadConfig();
6615
7390
  if (!args.env) {
6616
- consola6.info(`Using default environment: ${config.environment}`);
7391
+ consola7.info(`Using default environment: ${config.environment}`);
6617
7392
  }
6618
7393
  const client = createClient(globalOpts);
6619
7394
  const nip = args.nip ?? config.nip;
@@ -6625,13 +7400,13 @@ var login = defineCommand2({
6625
7400
  if (token) {
6626
7401
  loginResult = await client.loginWithToken(token, nip);
6627
7402
  } else if (args.p12) {
6628
- const fs15 = await import("fs");
6629
- const p12Buffer = fs15.readFileSync(args.p12);
7403
+ const fs17 = await import("node:fs");
7404
+ const p12Buffer = fs17.readFileSync(args.p12);
6630
7405
  loginResult = await client.loginWithPkcs12(p12Buffer, args["p12-password"] ?? "", nip);
6631
7406
  } else if (args.cert && args.key) {
6632
- const fs15 = await import("fs");
6633
- const certPem = fs15.readFileSync(args.cert, "utf-8");
6634
- const keyPem = fs15.readFileSync(args.key, "utf-8");
7407
+ const fs17 = await import("node:fs");
7408
+ const certPem = fs17.readFileSync(args.cert, "utf-8");
7409
+ const keyPem = fs17.readFileSync(args.key, "utf-8");
6635
7410
  loginResult = await client.loginWithCertificate(certPem, keyPem, nip, args["key-password"]);
6636
7411
  } else {
6637
7412
  throw new Error("Provide --token, --p12, or both --cert and --key for authentication.");
@@ -6664,7 +7439,7 @@ var login = defineCommand2({
6664
7439
  if (args.json) {
6665
7440
  console.log(JSON.stringify({ status: "ok", clientIp: loginResult.clientIp }, null, 2));
6666
7441
  } else {
6667
- consola6.info(`Seen client IP: ${loginResult.clientIp}`);
7442
+ consola7.info(`Seen client IP: ${loginResult.clientIp}`);
6668
7443
  outputSuccess("Logged in successfully.");
6669
7444
  }
6670
7445
  }, { json: Boolean(args.json) });
@@ -6850,7 +7625,7 @@ var whoami = defineCommand2({
6850
7625
  }
6851
7626
  }
6852
7627
  if (restored) {
6853
- consola6.info("Session restored from stored credentials.");
7628
+ consola7.info("Session restored from stored credentials.");
6854
7629
  }
6855
7630
  const context2 = parseKSeFTokenContext(session.accessToken);
6856
7631
  const info = {
@@ -6980,9 +7755,9 @@ var authCommand = defineCommand2({
6980
7755
  });
6981
7756
 
6982
7757
  // src/cli/commands/session.ts
6983
- import * as fs6 from "fs";
7758
+ import * as fs6 from "node:fs";
6984
7759
  import { defineCommand as defineCommand3 } from "citty";
6985
- import { consola as consola7 } from "consola";
7760
+ import { consola as consola8 } from "consola";
6986
7761
  init_document_structures();
6987
7762
  init_xml();
6988
7763
  function getGlobalOpts2(args) {
@@ -7028,7 +7803,7 @@ var open = defineCommand3({
7028
7803
  if (args.batch) {
7029
7804
  throw new Error("Batch session open is used internally by `ksef invoice send <dir>`. Use `ksef session open` for online sessions.");
7030
7805
  }
7031
- if (!args.json) consola7.start("Opening online session...");
7806
+ if (!args.json) consola8.start("Opening online session...");
7032
7807
  const result = await client.onlineSession.openSession(
7033
7808
  { formCode, encryption: encryptionData.encryptionInfo }
7034
7809
  );
@@ -7065,7 +7840,7 @@ var close = defineCommand3({
7065
7840
  if (!ref) {
7066
7841
  throw new Error("No session reference. Provide a ref or run `ksef session open` first.");
7067
7842
  }
7068
- if (!args.json) consola7.start("Closing session...");
7843
+ if (!args.json) consola8.start("Closing session...");
7069
7844
  await client.onlineSession.closeSession(ref);
7070
7845
  clearOnlineSessionRef();
7071
7846
  outputSuccess(`Session ${ref} closed.`);
@@ -7153,7 +7928,7 @@ var list = defineCommand3({
7153
7928
  { json: false }
7154
7929
  );
7155
7930
  if (result.continuationToken) {
7156
- consola7.info(`More results available. Continuation token: ${result.continuationToken}`);
7931
+ consola8.info(`More results available. Continuation token: ${result.continuationToken}`);
7157
7932
  }
7158
7933
  }, { json: Boolean(args.json) });
7159
7934
  }
@@ -7204,7 +7979,7 @@ var invoices = defineCommand3({
7204
7979
  { json: false }
7205
7980
  );
7206
7981
  if (result.continuationToken) {
7207
- consola7.info(`More results available. Continuation token: ${result.continuationToken}`);
7982
+ consola8.info(`More results available. Continuation token: ${result.continuationToken}`);
7208
7983
  }
7209
7984
  }, { json: Boolean(args.json) });
7210
7985
  }
@@ -7255,7 +8030,7 @@ var failed = defineCommand3({
7255
8030
  { json: false }
7256
8031
  );
7257
8032
  if (result.continuationToken) {
7258
- consola7.info(`More results available. Continuation token: ${result.continuationToken}`);
8033
+ consola8.info(`More results available. Continuation token: ${result.continuationToken}`);
7259
8034
  }
7260
8035
  }, { json: Boolean(args.json) });
7261
8036
  }
@@ -7354,7 +8129,7 @@ var active = defineCommand3({
7354
8129
  { json: false }
7355
8130
  );
7356
8131
  if (result.continuationToken) {
7357
- consola7.info(`More results available. Continuation token: ${result.continuationToken}`);
8132
+ consola8.info(`More results available. Continuation token: ${result.continuationToken}`);
7358
8133
  }
7359
8134
  }, { json: Boolean(args.json) });
7360
8135
  }
@@ -7435,21 +8210,21 @@ var sessionCommand = defineCommand3({
7435
8210
  });
7436
8211
 
7437
8212
  // src/cli/commands/invoice.ts
7438
- import * as fs9 from "fs";
7439
- import * as path6 from "path";
7440
- import { Readable } from "stream";
7441
- import { defineCommand as defineCommand5 } from "citty";
7442
- import { consola as consola9 } from "consola";
8213
+ import * as fs11 from "node:fs";
8214
+ import * as path8 from "node:path";
8215
+ import { Readable } from "node:stream";
8216
+ import { defineCommand as defineCommand6 } from "citty";
8217
+ import { consola as consola11 } from "consola";
7443
8218
  init_document_structures();
7444
8219
 
7445
8220
  // src/cli/commands/export-incremental.ts
7446
- import * as fs8 from "fs";
7447
- import * as path5 from "path";
8221
+ import * as fs8 from "node:fs";
8222
+ import * as path5 from "node:path";
7448
8223
  import { defineCommand as defineCommand4 } from "citty";
7449
- import { consola as consola8 } from "consola";
8224
+ import { consola as consola9 } from "consola";
7450
8225
 
7451
8226
  // src/workflows/hwm-storage.ts
7452
- import * as fs7 from "fs/promises";
8227
+ import * as fs7 from "node:fs/promises";
7453
8228
  var FileHwmStore = class {
7454
8229
  constructor(filePath) {
7455
8230
  this.filePath = filePath;
@@ -7475,7 +8250,7 @@ init_zip();
7475
8250
  init_polling();
7476
8251
 
7477
8252
  // src/utils/hash.ts
7478
- import crypto5 from "crypto";
8253
+ import crypto5 from "node:crypto";
7479
8254
  function sha256Base64(data) {
7480
8255
  return crypto5.createHash("sha256").update(data).digest("base64");
7481
8256
  }
@@ -7666,9 +8441,9 @@ var exportIncremental = defineCommand4({
7666
8441
  fs8.mkdirSync(outputDir, { recursive: true });
7667
8442
  }
7668
8443
  if (!isJson) {
7669
- consola8.start(`Incremental export: ${from} \u2192 ${to}, subject: ${subjectType}`);
7670
- consola8.info(`State file: ${stateFile}`);
7671
- consola8.info(`Output dir: ${outputDir}`);
8444
+ consola9.start(`Incremental export: ${from} \u2192 ${to}, subject: ${subjectType}`);
8445
+ consola9.info(`State file: ${stateFile}`);
8446
+ consola9.info(`Output dir: ${outputDir}`);
7672
8447
  }
7673
8448
  const iterationParts = [];
7674
8449
  const result = await incrementalExportAndDownload(client, {
@@ -7684,7 +8459,7 @@ var exportIncremental = defineCommand4({
7684
8459
  iterationParts.push({ iteration, partCount: iterResult.parts.length });
7685
8460
  if (!isJson) {
7686
8461
  const hwmDate = continuationPoints[subjectType] ?? "complete";
7687
- consola8.info(
8462
+ consola9.info(
7688
8463
  `Iteration ${iteration + 1}: ${iterResult.invoiceCount} invoices, truncated: ${iterResult.isTruncated}, HWM: ${hwmDate}`
7689
8464
  );
7690
8465
  }
@@ -7713,13 +8488,619 @@ var exportIncremental = defineCommand4({
7713
8488
  outputSuccess(
7714
8489
  `Export complete: ${result.iterationCount} iterations, ${result.decryptedParts.length} parts downloaded`
7715
8490
  );
7716
- consola8.info(`Final HWM: ${continuationPoints[subjectType] ?? "complete"}`);
7717
- consola8.info(`Output: ${outputDir}`);
8491
+ consola9.info(`Final HWM: ${continuationPoints[subjectType] ?? "complete"}`);
8492
+ consola9.info(`Output: ${outputDir}`);
7718
8493
  }
7719
8494
  }, { json: Boolean(args.json) });
7720
8495
  }
7721
8496
  });
7722
8497
 
8498
+ // src/cli/commands/invoice-build.ts
8499
+ import { defineCommand as defineCommand5 } from "citty";
8500
+ import { consola as consola10 } from "consola";
8501
+ init_xml();
8502
+ init_invoice_validator();
8503
+
8504
+ // src/validation/xsd-validator.ts
8505
+ import { createRequire } from "node:module";
8506
+ import * as fs9 from "node:fs";
8507
+ import * as path6 from "node:path";
8508
+ import { fileURLToPath, pathToFileURL } from "node:url";
8509
+ var cachedPkgRoot = null;
8510
+ function locatePackageRoot() {
8511
+ if (cachedPkgRoot !== null) return cachedPkgRoot;
8512
+ let dir = path6.dirname(fileURLToPath(import.meta.url));
8513
+ const root = path6.parse(dir).root;
8514
+ while (dir !== root) {
8515
+ const candidate = path6.join(dir, "docs", "schemas");
8516
+ if (fs9.existsSync(candidate)) {
8517
+ cachedPkgRoot = dir;
8518
+ return dir;
8519
+ }
8520
+ dir = path6.dirname(dir);
8521
+ }
8522
+ throw new Error("Could not locate ksef-client-ts package root (docs/schemas not found).");
8523
+ }
8524
+ var XSD_RELATIVE = {
8525
+ FA2: ["FA", "schemat_FA(2)_v1-0E.xsd"],
8526
+ FA3: ["FA", "schemat_FA(3)_v1-0E.xsd"],
8527
+ PEF: ["PEF", "Schemat_PEF(3)_v2-1.xsd"],
8528
+ PEF_KOR: ["PEF", "Schemat_PEF_KOR(3)_v2-1.xsd"]
8529
+ };
8530
+ function resolveXsdFor(schema) {
8531
+ const rel = XSD_RELATIVE[schema];
8532
+ if (!rel) throw new Error(`Unknown invoice schema: ${String(schema)}`);
8533
+ return path6.join(locatePackageRoot(), "docs", "schemas", ...rel);
8534
+ }
8535
+ var requireModule = createRequire(import.meta.url);
8536
+ var libxmljs = null;
8537
+ var libxmljsLoadError = null;
8538
+ try {
8539
+ libxmljs = requireModule("libxmljs2");
8540
+ } catch (err) {
8541
+ const code = err?.code;
8542
+ if (code === "MODULE_NOT_FOUND" || code === "ERR_MODULE_NOT_FOUND") {
8543
+ libxmljs = null;
8544
+ } else {
8545
+ libxmljs = null;
8546
+ libxmljsLoadError = err instanceof Error ? err : new Error(String(err));
8547
+ }
8548
+ }
8549
+ var MISSING_LIBXMLJS_MESSAGE_PREFIX = "libxmljs2 is not installed";
8550
+ function isMissingLibxmljsError(err) {
8551
+ return err instanceof Error && err.message.startsWith(MISSING_LIBXMLJS_MESSAGE_PREFIX);
8552
+ }
8553
+ var EXTERNAL_STRUKTURY_DANYCH_URL = /schemaLocation="http:\/\/crd\.gov\.pl\/xml\/schematy\/dziedzinowe\/mf\/2022\/01\/05\/eD\/DefinicjeTypy\/StrukturyDanych_v10-0E\.xsd"/;
8554
+ function rewriteSchemaLocations(xsdContent) {
8555
+ if (!EXTERNAL_STRUKTURY_DANYCH_URL.test(xsdContent)) {
8556
+ return xsdContent;
8557
+ }
8558
+ const bazoweStrukturyPath = path6.join(
8559
+ locatePackageRoot(),
8560
+ "docs",
8561
+ "schemas",
8562
+ "FA",
8563
+ "bazowe",
8564
+ "StrukturyDanych_v10-0E.xsd"
8565
+ );
8566
+ const bazoweStrukturyUrl = pathToFileURL(bazoweStrukturyPath).href;
8567
+ const rewritten = xsdContent.replace(
8568
+ EXTERNAL_STRUKTURY_DANYCH_URL,
8569
+ `schemaLocation="${bazoweStrukturyUrl}"`
8570
+ );
8571
+ if (rewritten === xsdContent) {
8572
+ throw new Error(
8573
+ "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`."
8574
+ );
8575
+ }
8576
+ return rewritten;
8577
+ }
8578
+ function validateAgainstXsd(xml, xsdPath) {
8579
+ if (!libxmljs) {
8580
+ const loadSuffix = libxmljsLoadError ? ` (load failed: ${libxmljsLoadError.message})` : "";
8581
+ throw new Error(
8582
+ `${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\`).`
8583
+ );
8584
+ }
8585
+ const xsdDir = path6.dirname(xsdPath);
8586
+ const rawXsd = fs9.readFileSync(xsdPath, "utf8");
8587
+ const rewrittenXsd = rewriteSchemaLocations(rawXsd);
8588
+ const baseUrl = pathToFileURL(xsdDir + path6.sep).href;
8589
+ let schemaDoc;
8590
+ try {
8591
+ schemaDoc = libxmljs.parseXml(rewrittenXsd, { baseUrl });
8592
+ } catch (err) {
8593
+ return { valid: false, errors: [`XSD parse failed: ${err.message}`] };
8594
+ }
8595
+ let xmlDoc;
8596
+ try {
8597
+ xmlDoc = libxmljs.parseXml(xml);
8598
+ } catch (err) {
8599
+ return { valid: false, errors: [`XML parse failed: ${err.message}`] };
8600
+ }
8601
+ const valid = xmlDoc.validate(schemaDoc);
8602
+ const errors = valid ? [] : xmlDoc.validationErrors.map((err) => err.message.trim());
8603
+ return { valid, errors };
8604
+ }
8605
+
8606
+ // src/cli/commands/invoice-build.ts
8607
+ init_ksef_validation_error();
8608
+ init_ksef_xsd_validation_error();
8609
+
8610
+ // src/cli/commands/invoice-build-helpers.ts
8611
+ init_ksef_validation_error();
8612
+ init_ksef_xsd_validation_error();
8613
+ import * as fs10 from "node:fs";
8614
+ import * as path7 from "node:path";
8615
+ import { parse as parseYaml, YAMLParseError } from "yaml";
8616
+
8617
+ // src/cli/commands/invoice-build-templates/fa2.json
8618
+ var fa2_default = {
8619
+ Naglowek: {
8620
+ KodFormularza: { systemCode: "FA (2)", schemaVersion: "1-0E", value: "FA" },
8621
+ WariantFormularza: 2,
8622
+ DataWytworzeniaFa: "2026-04-18T00:00:00Z",
8623
+ SystemInfo: "ksef-client-ts"
8624
+ },
8625
+ Podmiot1: {
8626
+ DaneIdentyfikacyjne: { NIP: "1111111111", Nazwa: "Sample Seller" },
8627
+ Adres: { KodKraju: "PL", AdresL1: "ul. Przykladowa 1", AdresL2: "00-001 Warszawa" }
8628
+ },
8629
+ Podmiot2: {
8630
+ DaneIdentyfikacyjne: { NIP: "2222222222", Nazwa: "Sample Buyer" },
8631
+ Adres: { KodKraju: "PL", AdresL1: "ul. Klientowska 2", AdresL2: "00-002 Warszawa" },
8632
+ DaneKontaktowe: { Email: "buyer@example.com" }
8633
+ },
8634
+ Fa: {
8635
+ KodWaluty: "PLN",
8636
+ P_1: "2026-04-18",
8637
+ P_2: "FA/2026/0001",
8638
+ P_13_1: "100.00",
8639
+ P_14_1: "23.00",
8640
+ P_15: "123.00",
8641
+ Adnotacje: {
8642
+ P_16: "2",
8643
+ P_17: "2",
8644
+ P_18: "2",
8645
+ P_18A: "2",
8646
+ Zwolnienie: { P_19N: "1" },
8647
+ NoweSrodkiTransportu: { P_22N: "1" },
8648
+ P_23: "2",
8649
+ PMarzy: { P_PMarzyN: "1" }
8650
+ },
8651
+ RodzajFaktury: "VAT",
8652
+ FaWiersz: [
8653
+ {
8654
+ NrWierszaFa: 1,
8655
+ P_7: "Sample product",
8656
+ P_8A: "szt.",
8657
+ P_8B: "1.00",
8658
+ P_9A: "100.00",
8659
+ P_11: "100.00",
8660
+ P_12: "23"
8661
+ }
8662
+ ]
8663
+ }
8664
+ };
8665
+
8666
+ // src/cli/commands/invoice-build-templates/fa3.json
8667
+ var fa3_default = {
8668
+ Naglowek: {
8669
+ KodFormularza: { systemCode: "FA (3)", schemaVersion: "1-0E", value: "FA" },
8670
+ WariantFormularza: 3,
8671
+ DataWytworzeniaFa: "2026-04-18T00:00:00Z",
8672
+ SystemInfo: "ksef-client-ts"
8673
+ },
8674
+ Podmiot1: {
8675
+ DaneIdentyfikacyjne: { NIP: "1111111111", Nazwa: "Sample Seller" },
8676
+ Adres: { KodKraju: "PL", AdresL1: "ul. Przykladowa 1", AdresL2: "00-001 Warszawa" },
8677
+ DaneKontaktowe: { Email: "seller@example.com" }
8678
+ },
8679
+ Podmiot2: {
8680
+ DaneIdentyfikacyjne: { NIP: "2222222222", Nazwa: "Sample Buyer" },
8681
+ Adres: { KodKraju: "PL", AdresL1: "ul. Klientowska 2", AdresL2: "00-002 Warszawa" },
8682
+ DaneKontaktowe: { Email: "buyer@example.com" },
8683
+ JST: "2",
8684
+ GV: "2"
8685
+ },
8686
+ Fa: {
8687
+ KodWaluty: "PLN",
8688
+ P_1: "2026-04-18",
8689
+ P_2: "FA/2026/0001",
8690
+ P_13_1: "100.00",
8691
+ P_14_1: "23.00",
8692
+ P_15: "123.00",
8693
+ Adnotacje: {
8694
+ P_16: "2",
8695
+ P_17: "2",
8696
+ P_18: "2",
8697
+ P_18A: "2",
8698
+ Zwolnienie: { P_19N: "1" },
8699
+ NoweSrodkiTransportu: { P_22N: "1" },
8700
+ P_23: "2",
8701
+ PMarzy: { P_PMarzyN: "1" }
8702
+ },
8703
+ RodzajFaktury: "VAT",
8704
+ FaWiersz: [
8705
+ {
8706
+ NrWierszaFa: 1,
8707
+ P_7: "Sample product",
8708
+ P_8A: "szt.",
8709
+ P_8B: "1.00",
8710
+ P_9A: "100.00",
8711
+ P_11: "100.00",
8712
+ P_12: "23"
8713
+ }
8714
+ ]
8715
+ }
8716
+ };
8717
+
8718
+ // src/cli/commands/invoice-build-templates/pef.json
8719
+ var pef_default = {
8720
+ Invoice: {
8721
+ "cbc:CustomizationID": "urn:cen.eu:en16931:2017#compliant#urn:fdc:peppol.eu:2017:poacc:billing:3.0",
8722
+ "cbc:ProfileID": "urn:fdc:peppol.eu:2017:poacc:billing:01:1.0",
8723
+ "cbc:ID": "INV/2026/0001",
8724
+ "cbc:IssueDate": "2026-04-18",
8725
+ "cbc:DueDate": "2026-05-18",
8726
+ "cbc:InvoiceTypeCode": "380",
8727
+ "cbc:DocumentCurrencyCode": "PLN",
8728
+ "cac:AccountingSupplierParty": {
8729
+ "cac:Party": {
8730
+ "cac:PartyName": { "cbc:Name": "Sample Seller" },
8731
+ "cac:PostalAddress": {
8732
+ "cbc:StreetName": "ul. Przykladowa 1",
8733
+ "cbc:CityName": "Warszawa",
8734
+ "cbc:PostalZone": "00-001",
8735
+ "cac:Country": { "cbc:IdentificationCode": "PL" }
8736
+ },
8737
+ "cac:PartyTaxScheme": {
8738
+ "cbc:CompanyID": "PL1111111111",
8739
+ "cac:TaxScheme": { "cbc:ID": "VAT" }
8740
+ },
8741
+ "cac:PartyLegalEntity": {
8742
+ "cbc:RegistrationName": "Sample Seller",
8743
+ "cbc:CompanyID": "1111111111"
8744
+ }
8745
+ }
8746
+ },
8747
+ "cac:AccountingCustomerParty": {
8748
+ "cac:Party": {
8749
+ "cac:PartyName": { "cbc:Name": "Sample Buyer" },
8750
+ "cac:PostalAddress": {
8751
+ "cbc:StreetName": "ul. Klientowska 2",
8752
+ "cbc:CityName": "Warszawa",
8753
+ "cbc:PostalZone": "00-002",
8754
+ "cac:Country": { "cbc:IdentificationCode": "PL" }
8755
+ },
8756
+ "cac:PartyLegalEntity": {
8757
+ "cbc:RegistrationName": "Sample Buyer",
8758
+ "cbc:CompanyID": "2222222222"
8759
+ }
8760
+ }
8761
+ },
8762
+ "cac:TaxTotal": [
8763
+ { "cbc:TaxAmount": { "@_currencyID": "PLN", "#text": "23.00" } }
8764
+ ],
8765
+ "cac:LegalMonetaryTotal": {
8766
+ "cbc:LineExtensionAmount": { "@_currencyID": "PLN", "#text": "100.00" },
8767
+ "cbc:TaxExclusiveAmount": { "@_currencyID": "PLN", "#text": "100.00" },
8768
+ "cbc:TaxInclusiveAmount": { "@_currencyID": "PLN", "#text": "123.00" },
8769
+ "cbc:PayableAmount": { "@_currencyID": "PLN", "#text": "123.00" }
8770
+ },
8771
+ "cac:InvoiceLine": [
8772
+ {
8773
+ "cbc:ID": "1",
8774
+ "cbc:InvoicedQuantity": { "@_unitCode": "C62", "#text": "1" },
8775
+ "cbc:LineExtensionAmount": { "@_currencyID": "PLN", "#text": "100.00" },
8776
+ "cac:Item": { "cbc:Name": "Sample product" },
8777
+ "cac:Price": {
8778
+ "cbc:PriceAmount": { "@_currencyID": "PLN", "#text": "100.00" }
8779
+ }
8780
+ }
8781
+ ]
8782
+ }
8783
+ };
8784
+
8785
+ // src/cli/commands/invoice-build-templates/pef-kor.json
8786
+ var pef_kor_default = {
8787
+ CreditNote: {
8788
+ "cbc:CustomizationID": "urn:cen.eu:en16931:2017#compliant#urn:fdc:peppol.eu:2017:poacc:billing:3.0",
8789
+ "cbc:ProfileID": "urn:fdc:peppol.eu:2017:poacc:billing:01:1.0",
8790
+ "cbc:ID": "COR/2026/0001",
8791
+ "cbc:IssueDate": "2026-04-18",
8792
+ "cbc:CreditNoteTypeCode": "381",
8793
+ "cbc:DocumentCurrencyCode": "PLN",
8794
+ "cac:BillingReference": {
8795
+ "cac:InvoiceDocumentReference": {
8796
+ "cbc:ID": "INV/2026/0001",
8797
+ "cbc:IssueDate": "2026-03-01"
8798
+ }
8799
+ },
8800
+ "cac:AccountingSupplierParty": {
8801
+ "cac:Party": {
8802
+ "cac:PartyName": { "cbc:Name": "Sample Seller" },
8803
+ "cac:PostalAddress": {
8804
+ "cbc:StreetName": "ul. Przykladowa 1",
8805
+ "cbc:CityName": "Warszawa",
8806
+ "cbc:PostalZone": "00-001",
8807
+ "cac:Country": { "cbc:IdentificationCode": "PL" }
8808
+ },
8809
+ "cac:PartyTaxScheme": {
8810
+ "cbc:CompanyID": "PL1111111111",
8811
+ "cac:TaxScheme": { "cbc:ID": "VAT" }
8812
+ },
8813
+ "cac:PartyLegalEntity": {
8814
+ "cbc:RegistrationName": "Sample Seller",
8815
+ "cbc:CompanyID": "1111111111"
8816
+ }
8817
+ }
8818
+ },
8819
+ "cac:AccountingCustomerParty": {
8820
+ "cac:Party": {
8821
+ "cac:PartyName": { "cbc:Name": "Sample Buyer" },
8822
+ "cac:PostalAddress": {
8823
+ "cbc:StreetName": "ul. Klientowska 2",
8824
+ "cbc:CityName": "Warszawa",
8825
+ "cbc:PostalZone": "00-002",
8826
+ "cac:Country": { "cbc:IdentificationCode": "PL" }
8827
+ },
8828
+ "cac:PartyLegalEntity": {
8829
+ "cbc:RegistrationName": "Sample Buyer",
8830
+ "cbc:CompanyID": "2222222222"
8831
+ }
8832
+ }
8833
+ },
8834
+ "cac:TaxTotal": [
8835
+ { "cbc:TaxAmount": { "@_currencyID": "PLN", "#text": "-23.00" } }
8836
+ ],
8837
+ "cac:LegalMonetaryTotal": {
8838
+ "cbc:LineExtensionAmount": { "@_currencyID": "PLN", "#text": "-100.00" },
8839
+ "cbc:TaxExclusiveAmount": { "@_currencyID": "PLN", "#text": "-100.00" },
8840
+ "cbc:TaxInclusiveAmount": { "@_currencyID": "PLN", "#text": "-123.00" },
8841
+ "cbc:PayableAmount": { "@_currencyID": "PLN", "#text": "-123.00" }
8842
+ },
8843
+ "cac:CreditNoteLine": [
8844
+ {
8845
+ "cbc:ID": "1",
8846
+ "cbc:CreditedQuantity": { "@_unitCode": "C62", "#text": "1" },
8847
+ "cbc:LineExtensionAmount": { "@_currencyID": "PLN", "#text": "-100.00" },
8848
+ "cac:Item": { "cbc:Name": "Sample product (corrected)" },
8849
+ "cac:Price": {
8850
+ "cbc:PriceAmount": { "@_currencyID": "PLN", "#text": "100.00" }
8851
+ }
8852
+ }
8853
+ ]
8854
+ }
8855
+ };
8856
+
8857
+ // src/cli/commands/invoice-build-helpers.ts
8858
+ var VALID_SCHEMAS = ["FA2", "FA3", "PEF", "PEF_KOR"];
8859
+ var VALID_FORMATS = ["auto", "json", "yaml"];
8860
+ var TEMPLATES = {
8861
+ FA2: fa2_default,
8862
+ FA3: fa3_default,
8863
+ PEF: pef_default,
8864
+ PEF_KOR: pef_kor_default
8865
+ };
8866
+ async function readInput(input, format) {
8867
+ const raw = input === "-" ? await readStdin2() : fs10.readFileSync(input, "utf-8");
8868
+ const resolvedFormat = format === "auto" ? inferFormatFromPath(input) : format;
8869
+ return { raw, format: resolvedFormat };
8870
+ }
8871
+ async function readStdin2() {
8872
+ const chunks = [];
8873
+ for await (const chunk of process.stdin) chunks.push(chunk);
8874
+ return Buffer.concat(chunks).toString("utf-8");
8875
+ }
8876
+ function inferFormatFromPath(input) {
8877
+ if (input === "-") return "json";
8878
+ const ext = path7.extname(input).toLowerCase();
8879
+ if (ext === ".yml" || ext === ".yaml") return "yaml";
8880
+ return "json";
8881
+ }
8882
+ function parseInput(raw, format) {
8883
+ if (format === "yaml") return parseYaml(raw);
8884
+ return JSON.parse(raw);
8885
+ }
8886
+ function inferSchema2(parsed) {
8887
+ if (typeof parsed !== "object" || parsed === null) return "FA3";
8888
+ const obj = parsed;
8889
+ if ("Invoice" in obj) return "PEF";
8890
+ if ("CreditNote" in obj) return "PEF_KOR";
8891
+ const naglowek = obj.Naglowek;
8892
+ if (typeof naglowek === "object" && naglowek !== null) {
8893
+ const formCode = naglowek.KodFormularza;
8894
+ if (typeof formCode === "object" && formCode !== null) {
8895
+ const systemCode = formCode.systemCode;
8896
+ if (systemCode === "FA (2)") return "FA2";
8897
+ }
8898
+ }
8899
+ return "FA3";
8900
+ }
8901
+ function writeOutput(xml, output) {
8902
+ if (!output || output === "-") {
8903
+ process.stdout.write(xml);
8904
+ return;
8905
+ }
8906
+ fs10.writeFileSync(output, xml);
8907
+ }
8908
+ function emitTemplate(schema) {
8909
+ const id = schema.toUpperCase();
8910
+ const template = TEMPLATES[id];
8911
+ if (!template) {
8912
+ throw KSeFValidationError.fromField(
8913
+ "template",
8914
+ `Template must be one of: ${VALID_SCHEMAS.join(", ")}.`
8915
+ );
8916
+ }
8917
+ process.stdout.write(JSON.stringify(template, null, 2) + "\n");
8918
+ }
8919
+ function buildDrySummary(parsed, schema) {
8920
+ if (typeof parsed !== "object" || parsed === null) {
8921
+ return { schema, sections: [] };
8922
+ }
8923
+ const obj = parsed;
8924
+ const sections = Object.keys(obj);
8925
+ const summary = { schema, sections };
8926
+ if (schema === "FA2" || schema === "FA3") {
8927
+ const fa = obj.Fa;
8928
+ if (typeof fa === "object" && fa !== null) {
8929
+ const p2 = fa.P_2;
8930
+ if (typeof p2 === "string" || typeof p2 === "number") {
8931
+ summary.invoiceNumber = String(p2);
8932
+ }
8933
+ const wiersz = fa.FaWiersz;
8934
+ if (Array.isArray(wiersz)) summary.lineCount = wiersz.length;
8935
+ else if (typeof wiersz === "object" && wiersz !== null) summary.lineCount = 1;
8936
+ }
8937
+ } else {
8938
+ const root = schema === "PEF" ? obj.Invoice : obj.CreditNote;
8939
+ if (root) {
8940
+ const id = root["cbc:ID"];
8941
+ if (typeof id === "string" || typeof id === "number") {
8942
+ summary.invoiceNumber = String(id);
8943
+ }
8944
+ const lines = schema === "PEF" ? root["cac:InvoiceLine"] : root["cac:CreditNoteLine"];
8945
+ if (Array.isArray(lines)) summary.lineCount = lines.length;
8946
+ else if (typeof lines === "object" && lines !== null) summary.lineCount = 1;
8947
+ }
8948
+ }
8949
+ return summary;
8950
+ }
8951
+ function mapBuildExitCode(error) {
8952
+ if (error instanceof SyntaxError) return 2;
8953
+ if (error instanceof YAMLParseError) return 2;
8954
+ if (error instanceof KSeFXsdValidationError) return 4;
8955
+ if (isMissingLibxmljsError(error)) return 4;
8956
+ if (error instanceof KSeFValidationError) return 3;
8957
+ if (typeof error === "object" && error !== null && "code" in error) {
8958
+ const code = error.code;
8959
+ if (typeof code === "string" && IO_ERRNO_CODES.has(code)) {
8960
+ return 5;
8961
+ }
8962
+ }
8963
+ return void 0;
8964
+ }
8965
+ var IO_ERRNO_CODES = /* @__PURE__ */ new Set([
8966
+ "ENOENT",
8967
+ "EACCES",
8968
+ "EPERM",
8969
+ "EISDIR",
8970
+ "ENOTDIR",
8971
+ "ENOSPC",
8972
+ "EROFS",
8973
+ "EMFILE",
8974
+ "ENFILE",
8975
+ "EIO",
8976
+ "EDQUOT",
8977
+ "EBADF",
8978
+ "EEXIST",
8979
+ "ENAMETOOLONG",
8980
+ "ELOOP",
8981
+ "ETXTBSY"
8982
+ ]);
8983
+
8984
+ // src/cli/commands/invoice-build.ts
8985
+ var invoiceBuild = defineCommand5({
8986
+ meta: {
8987
+ name: "build",
8988
+ description: "Build invoice XML from structured JSON/YAML input"
8989
+ },
8990
+ args: {
8991
+ input: {
8992
+ type: "positional",
8993
+ required: false,
8994
+ description: 'Input file path, or "-" to read from stdin'
8995
+ },
8996
+ schema: {
8997
+ type: "string",
8998
+ description: "Explicit schema: FA2|FA3|PEF|PEF_KOR (default: inferred from input)"
8999
+ },
9000
+ output: {
9001
+ type: "string",
9002
+ alias: "o",
9003
+ description: 'Output file path; omit or "-" for stdout'
9004
+ },
9005
+ pretty: {
9006
+ type: "boolean",
9007
+ description: "Pretty-print XML with 2-space indentation"
9008
+ },
9009
+ validate: {
9010
+ type: "boolean",
9011
+ description: "Run schema validation on the serialized XML"
9012
+ },
9013
+ "validate-xsd": {
9014
+ type: "boolean",
9015
+ description: "Run XSD validation on the serialized XML (requires libxmljs2)"
9016
+ },
9017
+ "dry-run": {
9018
+ type: "boolean",
9019
+ description: "Parse and summarise input; do not emit XML"
9020
+ },
9021
+ format: {
9022
+ type: "string",
9023
+ description: "Input format: json|yaml (default: infer from file extension)"
9024
+ },
9025
+ template: {
9026
+ type: "string",
9027
+ description: "Print a skeleton JSON for FA2|FA3|PEF|PEF_KOR and exit"
9028
+ },
9029
+ json: {
9030
+ type: "boolean",
9031
+ description: "Machine-readable output (for --dry-run / error messages)"
9032
+ }
9033
+ },
9034
+ async run({ args }) {
9035
+ await withErrorHandler(
9036
+ async () => {
9037
+ if (args.template) {
9038
+ emitTemplate(args.template);
9039
+ return;
9040
+ }
9041
+ if (!args.input) {
9042
+ throw new Error(
9043
+ 'Input file required. Provide a path or use "-" to read from stdin.'
9044
+ );
9045
+ }
9046
+ const formatRaw = args.format;
9047
+ if (formatRaw && !VALID_FORMATS.includes(formatRaw)) {
9048
+ throw KSeFValidationError.fromField(
9049
+ "format",
9050
+ `Format must be one of: ${VALID_FORMATS.join(", ")}.`
9051
+ );
9052
+ }
9053
+ const formatOption = formatRaw ?? "auto";
9054
+ const { raw, format } = await readInput(args.input, formatOption);
9055
+ const parsed = parseInput(raw, format);
9056
+ const explicitSchemaRaw = args.schema;
9057
+ if (explicitSchemaRaw && !VALID_SCHEMAS.includes(explicitSchemaRaw)) {
9058
+ throw KSeFValidationError.fromField(
9059
+ "schema",
9060
+ `Schema must be one of: ${VALID_SCHEMAS.join(", ")}.`
9061
+ );
9062
+ }
9063
+ const explicitSchema = explicitSchemaRaw;
9064
+ const schema = explicitSchema ?? inferSchema2(parsed);
9065
+ if (args["dry-run"]) {
9066
+ const summary = buildDrySummary(parsed, schema);
9067
+ if (args.json) {
9068
+ outputResult(summary, { json: true });
9069
+ } else {
9070
+ consola10.info(`Schema: ${summary.schema}${explicitSchema ? "" : " (inferred)"}`);
9071
+ consola10.info(`Invoice #: ${summary.invoiceNumber ?? "(not set)"}`);
9072
+ consola10.info(`Sections: ${summary.sections.join(", ")}`);
9073
+ if (summary.lineCount !== void 0) {
9074
+ consola10.info(`Line count: ${summary.lineCount}`);
9075
+ }
9076
+ }
9077
+ return;
9078
+ }
9079
+ const xml = serializeInvoiceXml(parsed, {
9080
+ schema,
9081
+ pretty: Boolean(args.pretty)
9082
+ });
9083
+ const xmlStr = args.validate || args["validate-xsd"] ? xml.toString("utf-8") : "";
9084
+ if (args.validate) {
9085
+ const result = await validate(xmlStr);
9086
+ if (!result.valid) {
9087
+ throw KSeFValidationError.fromMessages(result.errors.map((e) => e.message));
9088
+ }
9089
+ }
9090
+ if (args["validate-xsd"]) {
9091
+ const xsdPath = resolveXsdFor(schema);
9092
+ const xsdResult = validateAgainstXsd(xmlStr, xsdPath);
9093
+ if (!xsdResult.valid) {
9094
+ throw new KSeFXsdValidationError(xsdPath, xsdResult.errors);
9095
+ }
9096
+ }
9097
+ writeOutput(xml, args.output);
9098
+ },
9099
+ { json: Boolean(args.json), exitCode: mapBuildExitCode }
9100
+ );
9101
+ }
9102
+ });
9103
+
7723
9104
  // src/cli/commands/invoice.ts
7724
9105
  init_invoice_validator();
7725
9106
  init_ksef_validation_error();
@@ -7777,7 +9158,7 @@ var QUERY_FILTER_ARGS = {
7777
9158
  amountType: { type: "string", description: "Amount type: Brutto|Netto|Vat (default: Brutto)" },
7778
9159
  currency: { type: "string", description: "Currency code (e.g. PLN, EUR)" }
7779
9160
  };
7780
- var send = defineCommand5({
9161
+ var send = defineCommand6({
7781
9162
  meta: { name: "send", description: "Send invoice(s) \u2014 single XML file or directory for batch" },
7782
9163
  args: {
7783
9164
  path: { type: "positional", description: "Path to XML file, directory of XMLs, or ZIP for batch", required: true },
@@ -7812,13 +9193,13 @@ var send = defineCommand5({
7812
9193
  }
7813
9194
  formCode = resolved;
7814
9195
  }
7815
- if (!fs9.existsSync(filePath)) {
9196
+ if (!fs11.existsSync(filePath)) {
7816
9197
  throw new Error(`Path not found: ${filePath}`);
7817
9198
  }
7818
- const stat = fs9.statSync(filePath);
9199
+ const stat = fs11.statSync(filePath);
7819
9200
  if (args.stream) {
7820
9201
  if (args.validate) {
7821
- consola9.warn("--validate is not supported in stream mode. Run `ksef invoice validate <path>` before sending, or remove --stream.");
9202
+ consola11.warn("--validate is not supported in stream mode. Run `ksef invoice validate <path>` before sending, or remove --stream.");
7822
9203
  }
7823
9204
  if (!filePath.endsWith(".zip") || stat.isDirectory()) {
7824
9205
  throw new Error("--stream requires a .zip file path.");
@@ -7831,8 +9212,8 @@ var send = defineCommand5({
7831
9212
  }
7832
9213
  const { uploadBatchStream: uploadBatchStream2 } = await Promise.resolve().then(() => (init_batch_session_workflow(), batch_session_workflow_exports));
7833
9214
  const zipSize = stat.size;
7834
- const zipStreamFactory = () => Readable.toWeb(fs9.createReadStream(filePath));
7835
- if (!args.json) consola9.start(`Sending batch via stream (${(zipSize / 1e6).toFixed(1)} MB)...`);
9215
+ const zipStreamFactory = () => Readable.toWeb(fs11.createReadStream(filePath));
9216
+ if (!args.json) consola11.start(`Sending batch via stream (${(zipSize / 1e6).toFixed(1)} MB)...`);
7836
9217
  const result = await uploadBatchStream2(client, zipStreamFactory, zipSize, {
7837
9218
  formCode,
7838
9219
  pollOptions: { intervalMs: 3e3 },
@@ -7846,7 +9227,7 @@ var send = defineCommand5({
7846
9227
  return;
7847
9228
  }
7848
9229
  if (stat.isDirectory()) {
7849
- const xmlFiles = fs9.readdirSync(filePath).filter((f) => f.endsWith(".xml")).map((f) => path6.join(filePath, f));
9230
+ const xmlFiles = fs11.readdirSync(filePath).filter((f) => f.endsWith(".xml")).map((f) => path8.join(filePath, f));
7850
9231
  if (xmlFiles.length === 0) {
7851
9232
  throw new Error(`No XML files found in ${filePath}`);
7852
9233
  }
@@ -7856,14 +9237,14 @@ var send = defineCommand5({
7856
9237
  if (!validateFormCodeForSession(formCode, "batch")) {
7857
9238
  throw new Error(`Document type "${formCode.systemCode}" is not supported in batch sessions. PEF/PEF_KOR require online sessions.`);
7858
9239
  }
7859
- const fileBuffers = xmlFiles.map((file) => ({ file, content: fs9.readFileSync(file) }));
9240
+ const fileBuffers = xmlFiles.map((file) => ({ file, content: fs11.readFileSync(file) }));
7860
9241
  if (args.validate) {
7861
9242
  const { validateBatch: validateBatch2, batchValidationDetails: batchValidationDetails2 } = await Promise.resolve().then(() => (init_invoice_validator(), invoice_validator_exports));
7862
9243
  const invoicesToValidate = fileBuffers.map(({ file, content }) => ({
7863
- fileName: path6.basename(file),
9244
+ fileName: path8.basename(file),
7864
9245
  xml: content.toString("utf-8")
7865
9246
  }));
7866
- if (!args.json) consola9.start(`Validating ${invoicesToValidate.length} invoices...`);
9247
+ if (!args.json) consola11.start(`Validating ${invoicesToValidate.length} invoices...`);
7867
9248
  const batchResult = await validateBatch2(invoicesToValidate);
7868
9249
  if (!batchResult.valid) {
7869
9250
  const invalidCount = batchResult.results.filter((r) => !r.result.valid).length;
@@ -7872,9 +9253,9 @@ var send = defineCommand5({
7872
9253
  batchValidationDetails2(batchResult)
7873
9254
  );
7874
9255
  }
7875
- if (!args.json) consola9.success(`All ${xmlFiles.length} invoices valid.`);
9256
+ if (!args.json) consola11.success(`All ${xmlFiles.length} invoices valid.`);
7876
9257
  }
7877
- if (!args.json) consola9.start(`Sending ${xmlFiles.length} invoices via batch session...`);
9258
+ if (!args.json) consola11.start(`Sending ${xmlFiles.length} invoices via batch session...`);
7878
9259
  await client.crypto.init();
7879
9260
  const encryptionData = client.crypto.getEncryptionData();
7880
9261
  const parts = fileBuffers.map(({ content }, i) => {
@@ -7913,7 +9294,7 @@ var send = defineCommand5({
7913
9294
  if (!ref) {
7914
9295
  throw new Error("No active online session. Run `ksef session open` or provide --session-ref.");
7915
9296
  }
7916
- const xmlContent = fs9.readFileSync(filePath);
9297
+ const xmlContent = fs11.readFileSync(filePath);
7917
9298
  if (args.validate) {
7918
9299
  const xmlStr = xmlContent.toString("utf-8");
7919
9300
  const validationResult = await validate(xmlStr);
@@ -7923,9 +9304,9 @@ var send = defineCommand5({
7923
9304
  validationResult.errors.map((e) => ({ field: e.path, message: e.message }))
7924
9305
  );
7925
9306
  }
7926
- if (!args.json) consola9.success("Validation passed.");
9307
+ if (!args.json) consola11.success("Validation passed.");
7927
9308
  }
7928
- if (!args.json) consola9.start("Sending invoice...");
9309
+ if (!args.json) consola11.start("Sending invoice...");
7929
9310
  await client.crypto.init();
7930
9311
  const storedEnc = loadEncryptionData();
7931
9312
  if (!storedEnc) {
@@ -7951,7 +9332,7 @@ var send = defineCommand5({
7951
9332
  }, { json: Boolean(args.json) });
7952
9333
  }
7953
9334
  });
7954
- var get = defineCommand5({
9335
+ var get = defineCommand6({
7955
9336
  meta: { name: "get", description: "Download invoice by KSeF number" },
7956
9337
  args: {
7957
9338
  ksefNumber: { type: "positional", description: "KSeF invoice number", required: true },
@@ -7971,7 +9352,7 @@ var get = defineCommand5({
7971
9352
  return;
7972
9353
  }
7973
9354
  if (args.o) {
7974
- fs9.writeFileSync(args.o, xml, "utf-8");
9355
+ fs11.writeFileSync(args.o, xml, "utf-8");
7975
9356
  outputSuccess(`Invoice saved to ${args.o}`);
7976
9357
  } else {
7977
9358
  console.log(xml);
@@ -7979,7 +9360,7 @@ var get = defineCommand5({
7979
9360
  }, { json: Boolean(args.json) });
7980
9361
  }
7981
9362
  });
7982
- var query = defineCommand5({
9363
+ var query = defineCommand6({
7983
9364
  meta: { name: "query", description: "Query invoice metadata" },
7984
9365
  args: {
7985
9366
  ...QUERY_FILTER_ARGS,
@@ -8008,7 +9389,7 @@ var query = defineCommand5({
8008
9389
  return;
8009
9390
  }
8010
9391
  if (result.invoices.length === 0) {
8011
- consola9.info("No invoices found matching the criteria.");
9392
+ consola11.info("No invoices found matching the criteria.");
8012
9393
  return;
8013
9394
  }
8014
9395
  outputTable(
@@ -8031,12 +9412,12 @@ var query = defineCommand5({
8031
9412
  { json: false }
8032
9413
  );
8033
9414
  if (result.hasMore) {
8034
- consola9.info("More results available. Use --page to fetch the next page.");
9415
+ consola11.info("More results available. Use --page to fetch the next page.");
8035
9416
  }
8036
9417
  }, { json: Boolean(args.json) });
8037
9418
  }
8038
9419
  });
8039
- var exportCmd = defineCommand5({
9420
+ var exportCmd = defineCommand6({
8040
9421
  meta: { name: "export", description: "Start invoice export" },
8041
9422
  args: {
8042
9423
  ...QUERY_FILTER_ARGS,
@@ -8051,7 +9432,7 @@ var exportCmd = defineCommand5({
8051
9432
  return withErrorHandler(async () => {
8052
9433
  const globalOpts = getGlobalOpts4(args);
8053
9434
  const { client } = await requireSession(globalOpts);
8054
- if (!args.json) consola9.start("Starting invoice export...");
9435
+ if (!args.json) consola11.start("Starting invoice export...");
8055
9436
  await client.crypto.init();
8056
9437
  const encryptionData = client.crypto.getEncryptionData();
8057
9438
  const filters = buildQueryFilters(args);
@@ -8062,12 +9443,12 @@ var exportCmd = defineCommand5({
8062
9443
  outputResult(result, { json: true });
8063
9444
  } else {
8064
9445
  outputSuccess(`Export started. Ref: ${result.referenceNumber}`);
8065
- consola9.info("Check status with: ksef invoice export-status " + result.referenceNumber);
9446
+ consola11.info("Check status with: ksef invoice export-status " + result.referenceNumber);
8066
9447
  }
8067
9448
  }, { json: Boolean(args.json) });
8068
9449
  }
8069
9450
  });
8070
- var exportStatus = defineCommand5({
9451
+ var exportStatus = defineCommand6({
8071
9452
  meta: { name: "export-status", description: "Check invoice export status" },
8072
9453
  args: {
8073
9454
  ref: { type: "positional", description: "Export reference number", required: true },
@@ -8085,15 +9466,15 @@ var exportStatus = defineCommand5({
8085
9466
  outputResult(result, { json: true });
8086
9467
  return;
8087
9468
  }
8088
- consola9.info(`Status: ${result.status.code} \u2014 ${result.status.description}`);
9469
+ consola11.info(`Status: ${result.status.code} \u2014 ${result.status.description}`);
8089
9470
  if (result.completedDate) {
8090
- consola9.info(`Completed: ${result.completedDate}`);
9471
+ consola11.info(`Completed: ${result.completedDate}`);
8091
9472
  }
8092
9473
  if (result.packageExpirationDate) {
8093
- consola9.info(`Package expires: ${result.packageExpirationDate}`);
9474
+ consola11.info(`Package expires: ${result.packageExpirationDate}`);
8094
9475
  }
8095
9476
  if (result.package) {
8096
- consola9.info(`Invoices: ${result.package.invoiceCount}, Size: ${result.package.size} bytes`);
9477
+ consola11.info(`Invoices: ${result.package.invoiceCount}, Size: ${result.package.size} bytes`);
8097
9478
  if (result.package.parts.length > 0) {
8098
9479
  outputTable(
8099
9480
  result.package.parts.map((p) => ({
@@ -8118,7 +9499,7 @@ var exportStatus = defineCommand5({
8118
9499
  }
8119
9500
  });
8120
9501
  var VALID_SCHEMA_TYPES = SCHEMA_TYPES;
8121
- var validateCmd = defineCommand5({
9502
+ var validateCmd = defineCommand6({
8122
9503
  meta: { name: "validate", description: "Validate invoice XML against KSeF schema" },
8123
9504
  args: {
8124
9505
  files: { type: "positional", description: "XML file(s) or directory to validate", required: true },
@@ -8133,13 +9514,13 @@ var validateCmd = defineCommand5({
8133
9514
  }
8134
9515
  const inputPath = args.files;
8135
9516
  const filePaths = [];
8136
- if (fs9.existsSync(inputPath) && fs9.statSync(inputPath).isDirectory()) {
8137
- const xmlFiles = fs9.readdirSync(inputPath).filter((f) => f.endsWith(".xml")).sort().map((f) => path6.join(inputPath, f));
9517
+ if (fs11.existsSync(inputPath) && fs11.statSync(inputPath).isDirectory()) {
9518
+ const xmlFiles = fs11.readdirSync(inputPath).filter((f) => f.endsWith(".xml")).sort().map((f) => path8.join(inputPath, f));
8138
9519
  if (xmlFiles.length === 0) {
8139
9520
  throw new Error(`No XML files found in ${inputPath}`);
8140
9521
  }
8141
9522
  filePaths.push(...xmlFiles);
8142
- } else if (fs9.existsSync(inputPath)) {
9523
+ } else if (fs11.existsSync(inputPath)) {
8143
9524
  filePaths.push(inputPath);
8144
9525
  } else {
8145
9526
  throw new Error(`File not found: ${inputPath}`);
@@ -8148,28 +9529,28 @@ var validateCmd = defineCommand5({
8148
9529
  let invalidCount = 0;
8149
9530
  const allResults = [];
8150
9531
  for (const file of filePaths) {
8151
- const xml = fs9.readFileSync(file, "utf-8");
9532
+ const xml = fs11.readFileSync(file, "utf-8");
8152
9533
  const result = await validate(xml, schemaOverride ? { schema: schemaOverride } : void 0);
8153
9534
  if (result.valid) {
8154
9535
  validCount++;
8155
9536
  if (!args.json) {
8156
- consola9.success(`${path6.basename(file)}: valid (${result.schemaType})`);
9537
+ consola11.success(`${path8.basename(file)}: valid (${result.schemaType})`);
8157
9538
  if (result.schemaType === "PEF3" || result.schemaType === "PEF_KOR3") {
8158
- consola9.warn("PEF validation covers wrapper structure only \u2014 UBL content is not validated.");
9539
+ consola11.warn("PEF validation covers wrapper structure only \u2014 UBL content is not validated.");
8159
9540
  }
8160
9541
  }
8161
9542
  } else {
8162
9543
  invalidCount++;
8163
9544
  if (!args.json) {
8164
- consola9.error(`${path6.basename(file)}: INVALID (${result.schemaType ?? "unknown schema"})`);
9545
+ consola11.error(`${path8.basename(file)}: INVALID (${result.schemaType ?? "unknown schema"})`);
8165
9546
  for (const err of result.errors) {
8166
9547
  const loc = err.path ? ` at ${err.path}` : "";
8167
- consola9.log(` [${err.code}]${loc}: ${err.message}`);
9548
+ consola11.log(` [${err.code}]${loc}: ${err.message}`);
8168
9549
  }
8169
9550
  }
8170
9551
  }
8171
9552
  allResults.push({
8172
- file: path6.basename(file),
9553
+ file: path8.basename(file),
8173
9554
  valid: result.valid,
8174
9555
  schemaType: result.schemaType,
8175
9556
  errors: result.errors
@@ -8178,8 +9559,8 @@ var validateCmd = defineCommand5({
8178
9559
  if (args.json) {
8179
9560
  outputResult({ files: allResults, summary: { total: filePaths.length, valid: validCount, invalid: invalidCount } }, { json: true });
8180
9561
  } else if (filePaths.length > 1) {
8181
- consola9.log("");
8182
- consola9.info(`Summary: ${validCount} valid, ${invalidCount} invalid, ${filePaths.length} total`);
9562
+ consola11.log("");
9563
+ consola11.info(`Summary: ${validCount} valid, ${invalidCount} invalid, ${filePaths.length} total`);
8183
9564
  }
8184
9565
  if (invalidCount > 0) {
8185
9566
  process.exitCode = 1;
@@ -8187,13 +9568,13 @@ var validateCmd = defineCommand5({
8187
9568
  }, { json: Boolean(args.json) });
8188
9569
  }
8189
9570
  });
8190
- var invoiceCommand = defineCommand5({
9571
+ var invoiceCommand = defineCommand6({
8191
9572
  meta: { name: "invoice", description: "Invoice commands" },
8192
- subCommands: { send, get, query, validate: validateCmd, export: exportCmd, "export-status": exportStatus, "export-incremental": exportIncremental }
9573
+ subCommands: { send, build: invoiceBuild, get, query, validate: validateCmd, export: exportCmd, "export-status": exportStatus, "export-incremental": exportIncremental }
8193
9574
  });
8194
9575
 
8195
9576
  // src/cli/commands/permission.ts
8196
- import { defineCommand as defineCommand6 } from "citty";
9577
+ import { defineCommand as defineCommand7 } from "citty";
8197
9578
  init_ksef_validation_error();
8198
9579
  function getGlobalOpts5(args) {
8199
9580
  return {
@@ -8204,7 +9585,7 @@ function getGlobalOpts5(args) {
8204
9585
  nip: args.nip
8205
9586
  };
8206
9587
  }
8207
- var grant = defineCommand6({
9588
+ var grant = defineCommand7({
8208
9589
  meta: { name: "grant", description: "Grant permissions to a subject" },
8209
9590
  args: {
8210
9591
  type: { type: "string", description: "Grant type: person, entity, authorization, indirect, subunit, eu-entity-admin, eu-entity-representative", required: true },
@@ -8386,7 +9767,7 @@ var grant = defineCommand6({
8386
9767
  }, { json: Boolean(args.json) });
8387
9768
  }
8388
9769
  });
8389
- var revoke2 = defineCommand6({
9770
+ var revoke2 = defineCommand7({
8390
9771
  meta: { name: "revoke", description: "Revoke a permission grant" },
8391
9772
  args: {
8392
9773
  grantId: { type: "positional", description: "Grant ID to revoke", required: true },
@@ -8415,7 +9796,7 @@ var revoke2 = defineCommand6({
8415
9796
  }, { json: Boolean(args.json) });
8416
9797
  }
8417
9798
  });
8418
- var search = defineCommand6({
9799
+ var search = defineCommand7({
8419
9800
  meta: { name: "search", description: "Search permissions" },
8420
9801
  args: {
8421
9802
  type: { type: "string", description: "Search type: personal, persons, subunits, entities, entities-grants, subordinate-entities, authorizations, eu-entities", required: true },
@@ -8681,7 +10062,7 @@ var search = defineCommand6({
8681
10062
  }, { json: Boolean(args.json) });
8682
10063
  }
8683
10064
  });
8684
- var status3 = defineCommand6({
10065
+ var status3 = defineCommand7({
8685
10066
  meta: { name: "status", description: "Check permission operation status" },
8686
10067
  args: {
8687
10068
  ref: { type: "positional", description: "Operation reference number", required: true },
@@ -8707,7 +10088,7 @@ var status3 = defineCommand6({
8707
10088
  }, { json: Boolean(args.json) });
8708
10089
  }
8709
10090
  });
8710
- var attachmentStatus = defineCommand6({
10091
+ var attachmentStatus = defineCommand7({
8711
10092
  meta: { name: "attachment-status", description: "Check if attachment permissions are allowed" },
8712
10093
  args: {
8713
10094
  env: { type: "string", description: "Environment (test/demo/prod)" },
@@ -8731,14 +10112,14 @@ var attachmentStatus = defineCommand6({
8731
10112
  }, { json: Boolean(args.json) });
8732
10113
  }
8733
10114
  });
8734
- var permissionCommand = defineCommand6({
10115
+ var permissionCommand = defineCommand7({
8735
10116
  meta: { name: "permission", description: "Permission management commands" },
8736
10117
  subCommands: { grant, revoke: revoke2, search, status: status3, "attachment-status": attachmentStatus }
8737
10118
  });
8738
10119
 
8739
10120
  // src/cli/commands/token.ts
8740
- import { defineCommand as defineCommand7 } from "citty";
8741
- import { consola as consola10 } from "consola";
10121
+ import { defineCommand as defineCommand8 } from "citty";
10122
+ import { consola as consola12 } from "consola";
8742
10123
  function getGlobalOpts6(args) {
8743
10124
  return {
8744
10125
  env: args.env,
@@ -8748,7 +10129,7 @@ function getGlobalOpts6(args) {
8748
10129
  nip: args.nip
8749
10130
  };
8750
10131
  }
8751
- var generate = defineCommand7({
10132
+ var generate = defineCommand8({
8752
10133
  meta: { name: "generate", description: "Generate a new KSeF token" },
8753
10134
  args: {
8754
10135
  permissions: { type: "string", description: "Comma-separated permissions (e.g. InvoiceRead,InvoiceWrite)", required: true },
@@ -8784,7 +10165,7 @@ var generate = defineCommand7({
8784
10165
  }, { json: Boolean(args.json) });
8785
10166
  }
8786
10167
  });
8787
- var list2 = defineCommand7({
10168
+ var list2 = defineCommand8({
8788
10169
  meta: { name: "list", description: "List KSeF tokens" },
8789
10170
  args: {
8790
10171
  status: { type: "string", description: "Comma-separated statuses (e.g. Active,Pending)" },
@@ -8838,12 +10219,12 @@ var list2 = defineCommand7({
8838
10219
  { json: false }
8839
10220
  );
8840
10221
  if (result.continuationToken) {
8841
- consola10.info(`More results available. Continuation token: ${result.continuationToken}`);
10222
+ consola12.info(`More results available. Continuation token: ${result.continuationToken}`);
8842
10223
  }
8843
10224
  }, { json: Boolean(args.json) });
8844
10225
  }
8845
10226
  });
8846
- var get2 = defineCommand7({
10227
+ var get2 = defineCommand8({
8847
10228
  meta: { name: "get", description: "Get token details" },
8848
10229
  args: {
8849
10230
  ref: { type: "positional", description: "Token reference number", required: true },
@@ -8876,7 +10257,7 @@ var get2 = defineCommand7({
8876
10257
  }, { json: Boolean(args.json) });
8877
10258
  }
8878
10259
  });
8879
- var revoke3 = defineCommand7({
10260
+ var revoke3 = defineCommand8({
8880
10261
  meta: { name: "revoke", description: "Revoke a KSeF token" },
8881
10262
  args: {
8882
10263
  ref: { type: "positional", description: "Token reference number", required: true },
@@ -8900,19 +10281,19 @@ var revoke3 = defineCommand7({
8900
10281
  }, { json: Boolean(args.json) });
8901
10282
  }
8902
10283
  });
8903
- var tokenCommand = defineCommand7({
10284
+ var tokenCommand = defineCommand8({
8904
10285
  meta: { name: "token", description: "Token management commands" },
8905
10286
  subCommands: { generate, list: list2, get: get2, revoke: revoke3 }
8906
10287
  });
8907
10288
 
8908
10289
  // src/cli/commands/cert.ts
8909
- import { defineCommand as defineCommand8 } from "citty";
8910
- import { consola as consola11 } from "consola";
8911
- import fs10 from "fs";
8912
- import path7 from "path";
10290
+ import { defineCommand as defineCommand9 } from "citty";
10291
+ import { consola as consola13 } from "consola";
10292
+ import fs12 from "node:fs";
10293
+ import path9 from "node:path";
8913
10294
 
8914
10295
  // src/crypto/certificate-service.ts
8915
- import * as crypto7 from "crypto";
10296
+ import * as crypto7 from "node:crypto";
8916
10297
  import * as x5092 from "@peculiar/x509";
8917
10298
  var CertificateService = class {
8918
10299
  static getSha256Fingerprint(certPem) {
@@ -9002,7 +10383,7 @@ function getGlobalOpts7(args) {
9002
10383
  nip: args.nip
9003
10384
  };
9004
10385
  }
9005
- var generate2 = defineCommand8({
10386
+ var generate2 = defineCommand9({
9006
10387
  meta: { name: "generate", description: "Generate a self-signed certificate locally" },
9007
10388
  args: {
9008
10389
  type: { type: "string", description: "Certificate type: personal or company-seal", required: true },
@@ -9027,21 +10408,21 @@ var generate2 = defineCommand8({
9027
10408
  const certType = args.type;
9028
10409
  const cn = args.cn;
9029
10410
  const method = args.method || "RSA";
9030
- const outDir = path7.resolve(args.out || ".");
10411
+ const outDir = path9.resolve(args.out || ".");
9031
10412
  if (certType !== "personal" && certType !== "company-seal") {
9032
10413
  throw new Error('--type must be "personal" or "company-seal".');
9033
10414
  }
9034
10415
  if (method !== "RSA" && method !== "ECDSA") {
9035
10416
  throw new Error('--method must be "RSA" or "ECDSA".');
9036
10417
  }
9037
- fs10.mkdirSync(outDir, { recursive: true });
9038
- const certPath = path7.join(outDir, "cert.pem");
9039
- const keyPath = path7.join(outDir, "key.pem");
10418
+ fs12.mkdirSync(outDir, { recursive: true });
10419
+ const certPath = path9.join(outDir, "cert.pem");
10420
+ const keyPath = path9.join(outDir, "key.pem");
9040
10421
  if (!args.force) {
9041
- if (fs10.existsSync(certPath)) {
10422
+ if (fs12.existsSync(certPath)) {
9042
10423
  throw new Error(`File already exists: ${certPath}. Use --force to overwrite.`);
9043
10424
  }
9044
- if (fs10.existsSync(keyPath)) {
10425
+ if (fs12.existsSync(keyPath)) {
9045
10426
  throw new Error(`File already exists: ${keyPath}. Use --force to overwrite.`);
9046
10427
  }
9047
10428
  }
@@ -9068,8 +10449,8 @@ var generate2 = defineCommand8({
9068
10449
  method
9069
10450
  );
9070
10451
  }
9071
- fs10.writeFileSync(certPath, result.certificatePem, "utf-8");
9072
- fs10.writeFileSync(keyPath, result.privateKeyPem, "utf-8");
10452
+ fs12.writeFileSync(certPath, result.certificatePem, "utf-8");
10453
+ fs12.writeFileSync(keyPath, result.privateKeyPem, "utf-8");
9073
10454
  if (args.json) {
9074
10455
  outputResult({ certPath, keyPath, fingerprint: result.fingerprint }, { json: true });
9075
10456
  } else {
@@ -9083,7 +10464,7 @@ var generate2 = defineCommand8({
9083
10464
  }, { json: Boolean(args.json) });
9084
10465
  }
9085
10466
  });
9086
- var enroll = defineCommand8({
10467
+ var enroll = defineCommand9({
9087
10468
  meta: { name: "enroll", description: "Submit certificate enrollment" },
9088
10469
  args: {
9089
10470
  cert: { type: "string", description: "Path to certificate PEM file", required: true },
@@ -9100,7 +10481,7 @@ var enroll = defineCommand8({
9100
10481
  return withErrorHandler(async () => {
9101
10482
  const globalOpts = getGlobalOpts7(args);
9102
10483
  const { client } = await requireSession(globalOpts);
9103
- const certPem = fs10.readFileSync(args.cert, "utf-8");
10484
+ const certPem = fs12.readFileSync(args.cert, "utf-8");
9104
10485
  await client.crypto.init();
9105
10486
  const request = {
9106
10487
  certificateName: args.name,
@@ -9121,7 +10502,7 @@ var enroll = defineCommand8({
9121
10502
  }, { json: Boolean(args.json) });
9122
10503
  }
9123
10504
  });
9124
- var status4 = defineCommand8({
10505
+ var status4 = defineCommand9({
9125
10506
  meta: { name: "status", description: "Check certificate enrollment status" },
9126
10507
  args: {
9127
10508
  ref: { type: "positional", description: "Enrollment reference number", required: true },
@@ -9153,7 +10534,7 @@ var status4 = defineCommand8({
9153
10534
  }, { json: Boolean(args.json) });
9154
10535
  }
9155
10536
  });
9156
- var list3 = defineCommand8({
10537
+ var list3 = defineCommand9({
9157
10538
  meta: { name: "list", description: "Query certificates" },
9158
10539
  args: {
9159
10540
  serial: { type: "string", description: "Filter by serial number" },
@@ -9211,12 +10592,12 @@ var list3 = defineCommand8({
9211
10592
  { json: false }
9212
10593
  );
9213
10594
  if (result.hasMore) {
9214
- consola11.info("More results available. Use --page to paginate.");
10595
+ consola13.info("More results available. Use --page to paginate.");
9215
10596
  }
9216
10597
  }, { json: Boolean(args.json) });
9217
10598
  }
9218
10599
  });
9219
- var revoke4 = defineCommand8({
10600
+ var revoke4 = defineCommand9({
9220
10601
  meta: { name: "revoke", description: "Revoke a certificate" },
9221
10602
  args: {
9222
10603
  serial: { type: "positional", description: "Certificate serial number", required: true },
@@ -9243,7 +10624,7 @@ var revoke4 = defineCommand8({
9243
10624
  }, { json: Boolean(args.json) });
9244
10625
  }
9245
10626
  });
9246
- var limits = defineCommand8({
10627
+ var limits = defineCommand9({
9247
10628
  meta: { name: "limits", description: "View certificate limits" },
9248
10629
  args: {
9249
10630
  env: { type: "string", description: "Environment (test/demo/prod)" },
@@ -9271,7 +10652,7 @@ var limits = defineCommand8({
9271
10652
  }, { json: Boolean(args.json) });
9272
10653
  }
9273
10654
  });
9274
- var enrollmentData = defineCommand8({
10655
+ var enrollmentData = defineCommand9({
9275
10656
  meta: { name: "enrollment-data", description: "Get enrollment data template from KSeF" },
9276
10657
  args: {
9277
10658
  env: { type: "string", description: "Environment (test/demo/prod)" },
@@ -9302,7 +10683,7 @@ var enrollmentData = defineCommand8({
9302
10683
  }, { json: Boolean(args.json) });
9303
10684
  }
9304
10685
  });
9305
- var retrieve = defineCommand8({
10686
+ var retrieve = defineCommand9({
9306
10687
  meta: { name: "retrieve", description: "Retrieve certificates by serial numbers" },
9307
10688
  args: {
9308
10689
  serial: { type: "string", description: "Comma-separated certificate serial numbers", required: true },
@@ -9345,14 +10726,14 @@ var retrieve = defineCommand8({
9345
10726
  }, { json: Boolean(args.json) });
9346
10727
  }
9347
10728
  });
9348
- var certCommand = defineCommand8({
10729
+ var certCommand = defineCommand9({
9349
10730
  meta: { name: "cert", description: "Certificate management commands" },
9350
10731
  subCommands: { generate: generate2, enroll, status: status4, list: list3, revoke: revoke4, limits, "enrollment-data": enrollmentData, retrieve }
9351
10732
  });
9352
10733
 
9353
10734
  // src/cli/commands/qr.ts
9354
- import * as fs11 from "fs";
9355
- import { defineCommand as defineCommand9 } from "citty";
10735
+ import * as fs13 from "node:fs";
10736
+ import { defineCommand as defineCommand10 } from "citty";
9356
10737
 
9357
10738
  // src/qr/qrcode-service.ts
9358
10739
  import * as QRCode from "qrcode";
@@ -9423,7 +10804,7 @@ function getGlobalOpts8(args) {
9423
10804
  nip: args.nip
9424
10805
  };
9425
10806
  }
9426
- var invoice2 = defineCommand9({
10807
+ var invoice2 = defineCommand10({
9427
10808
  meta: { name: "invoice", description: "Generate invoice QR code" },
9428
10809
  args: {
9429
10810
  nip: { type: "string", description: "NIP number", required: true },
@@ -9455,7 +10836,7 @@ var invoice2 = defineCommand9({
9455
10836
  const effectiveLabel = args.offline ? "OFFLINE" : args.label;
9456
10837
  const svg = effectiveLabel ? await QrCodeService.generateQrCodeSvgWithLabel(url2, effectiveLabel, { width: size }) : await QrCodeService.generateQrCodeSvg(url2, { width: size });
9457
10838
  if (args.o) {
9458
- fs11.writeFileSync(args.o, svg);
10839
+ fs13.writeFileSync(args.o, svg);
9459
10840
  outputSuccess(`QR code saved to ${args.o}
9460
10841
  URL: ${url2}`);
9461
10842
  } else {
@@ -9464,7 +10845,7 @@ URL: ${url2}`);
9464
10845
  } else {
9465
10846
  const buffer = await QrCodeService.generateQrCode(url2, { width: size });
9466
10847
  if (args.o) {
9467
- fs11.writeFileSync(args.o, buffer);
10848
+ fs13.writeFileSync(args.o, buffer);
9468
10849
  outputSuccess(`QR code saved to ${args.o}
9469
10850
  URL: ${url2}`);
9470
10851
  } else {
@@ -9474,7 +10855,7 @@ URL: ${url2}`);
9474
10855
  }, { json: Boolean(args.json) });
9475
10856
  }
9476
10857
  });
9477
- var certificate = defineCommand9({
10858
+ var certificate = defineCommand10({
9478
10859
  meta: { name: "certificate", description: "Generate certificate QR code" },
9479
10860
  args: {
9480
10861
  "context-type": { type: "string", description: "Context identifier type", required: true },
@@ -9483,6 +10864,7 @@ var certificate = defineCommand9({
9483
10864
  "cert-serial": { type: "string", description: "Certificate serial number", required: true },
9484
10865
  hash: { type: "string", description: "Certificate hash (base64)", required: true },
9485
10866
  key: { type: "string", description: "Path to PEM private key file", required: true },
10867
+ "key-password": { type: "string", description: "Password for encrypted PEM private key" },
9486
10868
  format: { type: "string", description: "Output format: png or svg (default: png)" },
9487
10869
  size: { type: "string", description: "QR code size in pixels (default: 300)" },
9488
10870
  label: { type: "string", description: "Label text (SVG only)" },
@@ -9499,14 +10881,16 @@ var certificate = defineCommand9({
9499
10881
  const client = createClient(globalOpts);
9500
10882
  const size = args.size ? parseInt(args.size, 10) : 300;
9501
10883
  const format = args.format ?? "png";
9502
- const privateKeyPem = fs11.readFileSync(args.key, "utf-8");
10884
+ const privateKeyPem = fs13.readFileSync(args.key, "utf-8");
10885
+ const keyPassword = args["key-password"];
9503
10886
  const url2 = client.qr.buildCertificateVerificationUrl(
9504
10887
  args["context-type"],
9505
10888
  args["context-id"],
9506
10889
  args["seller-nip"],
9507
10890
  args["cert-serial"],
9508
10891
  args.hash,
9509
- privateKeyPem
10892
+ privateKeyPem,
10893
+ keyPassword
9510
10894
  );
9511
10895
  if (args.json) {
9512
10896
  const result = await QrCodeService.generateResult(url2, { width: size });
@@ -9516,7 +10900,7 @@ var certificate = defineCommand9({
9516
10900
  if (format === "svg") {
9517
10901
  const svg = args.label ? await QrCodeService.generateQrCodeSvgWithLabel(url2, args.label, { width: size }) : await QrCodeService.generateQrCodeSvg(url2, { width: size });
9518
10902
  if (args.o) {
9519
- fs11.writeFileSync(args.o, svg);
10903
+ fs13.writeFileSync(args.o, svg);
9520
10904
  outputSuccess(`QR code saved to ${args.o}
9521
10905
  URL: ${url2}`);
9522
10906
  } else {
@@ -9525,7 +10909,7 @@ URL: ${url2}`);
9525
10909
  } else {
9526
10910
  const buffer = await QrCodeService.generateQrCode(url2, { width: size });
9527
10911
  if (args.o) {
9528
- fs11.writeFileSync(args.o, buffer);
10912
+ fs13.writeFileSync(args.o, buffer);
9529
10913
  outputSuccess(`QR code saved to ${args.o}
9530
10914
  URL: ${url2}`);
9531
10915
  } else {
@@ -9535,7 +10919,7 @@ URL: ${url2}`);
9535
10919
  }, { json: Boolean(args.json) });
9536
10920
  }
9537
10921
  });
9538
- var url = defineCommand9({
10922
+ var url = defineCommand10({
9539
10923
  meta: { name: "url", description: "Print invoice verification URL (no QR image)" },
9540
10924
  args: {
9541
10925
  nip: { type: "string", description: "NIP number", required: true },
@@ -9559,13 +10943,13 @@ var url = defineCommand9({
9559
10943
  }, { json: Boolean(args.json) });
9560
10944
  }
9561
10945
  });
9562
- var qrCommand = defineCommand9({
10946
+ var qrCommand = defineCommand10({
9563
10947
  meta: { name: "qr", description: "QR code generation commands" },
9564
10948
  subCommands: { invoice: invoice2, certificate, url }
9565
10949
  });
9566
10950
 
9567
10951
  // src/cli/commands/lighthouse.ts
9568
- import { defineCommand as defineCommand10 } from "citty";
10952
+ import { defineCommand as defineCommand11 } from "citty";
9569
10953
  function getGlobalOpts9(args) {
9570
10954
  return {
9571
10955
  env: args.env ?? "prod",
@@ -9575,7 +10959,7 @@ function getGlobalOpts9(args) {
9575
10959
  nip: args.nip
9576
10960
  };
9577
10961
  }
9578
- var status5 = defineCommand10({
10962
+ var status5 = defineCommand11({
9579
10963
  meta: { name: "status", description: "Check KSeF system status" },
9580
10964
  args: {
9581
10965
  env: { type: "string", description: "Environment (test/prod, default: prod)" },
@@ -9603,7 +10987,7 @@ var status5 = defineCommand10({
9603
10987
  }, { json: Boolean(args.json) });
9604
10988
  }
9605
10989
  });
9606
- var messages = defineCommand10({
10990
+ var messages = defineCommand11({
9607
10991
  meta: { name: "messages", description: "View KSeF system messages" },
9608
10992
  args: {
9609
10993
  env: { type: "string", description: "Environment (test/prod, default: prod)" },
@@ -9645,13 +11029,13 @@ var messages = defineCommand10({
9645
11029
  }, { json: Boolean(args.json) });
9646
11030
  }
9647
11031
  });
9648
- var lighthouseCommand = defineCommand10({
11032
+ var lighthouseCommand = defineCommand11({
9649
11033
  meta: { name: "lighthouse", description: "KSeF system status commands" },
9650
11034
  subCommands: { status: status5, messages }
9651
11035
  });
9652
11036
 
9653
11037
  // src/cli/commands/test-data.ts
9654
- import { defineCommand as defineCommand11 } from "citty";
11038
+ import { defineCommand as defineCommand12 } from "citty";
9655
11039
  function getGlobalOpts10(args) {
9656
11040
  return {
9657
11041
  env: args.env,
@@ -9674,7 +11058,7 @@ function outputDone(json) {
9674
11058
  outputSuccess("Done.");
9675
11059
  }
9676
11060
  }
9677
- var createSubject = defineCommand11({
11061
+ var createSubject = defineCommand12({
9678
11062
  meta: { name: "create-subject", description: "Create a test subject" },
9679
11063
  args: {
9680
11064
  nip: { type: "string", description: "Subject NIP", required: true },
@@ -9701,7 +11085,7 @@ var createSubject = defineCommand11({
9701
11085
  }, { json: Boolean(args.json) });
9702
11086
  }
9703
11087
  });
9704
- var removeSubject = defineCommand11({
11088
+ var removeSubject = defineCommand12({
9705
11089
  meta: { name: "remove-subject", description: "Remove a test subject" },
9706
11090
  args: {
9707
11091
  nip: { type: "string", description: "Subject NIP", required: true },
@@ -9720,7 +11104,7 @@ var removeSubject = defineCommand11({
9720
11104
  }, { json: Boolean(args.json) });
9721
11105
  }
9722
11106
  });
9723
- var createPerson = defineCommand11({
11107
+ var createPerson = defineCommand12({
9724
11108
  meta: { name: "create-person", description: "Create a test person" },
9725
11109
  args: {
9726
11110
  nip: { type: "string", description: "Person NIP", required: true },
@@ -9751,7 +11135,7 @@ var createPerson = defineCommand11({
9751
11135
  }, { json: Boolean(args.json) });
9752
11136
  }
9753
11137
  });
9754
- var removePerson = defineCommand11({
11138
+ var removePerson = defineCommand12({
9755
11139
  meta: { name: "remove-person", description: "Remove a test person" },
9756
11140
  args: {
9757
11141
  nip: { type: "string", description: "Person NIP", required: true },
@@ -9770,7 +11154,7 @@ var removePerson = defineCommand11({
9770
11154
  }, { json: Boolean(args.json) });
9771
11155
  }
9772
11156
  });
9773
- var grantPermissions = defineCommand11({
11157
+ var grantPermissions = defineCommand12({
9774
11158
  meta: { name: "grant-permissions", description: "Grant test data permissions" },
9775
11159
  args: {
9776
11160
  "context-nip": { type: "string", description: "Context NIP", required: true },
@@ -9801,7 +11185,7 @@ var grantPermissions = defineCommand11({
9801
11185
  }, { json: Boolean(args.json) });
9802
11186
  }
9803
11187
  });
9804
- var revokePermissions = defineCommand11({
11188
+ var revokePermissions = defineCommand12({
9805
11189
  meta: { name: "revoke-permissions", description: "Revoke test data permissions" },
9806
11190
  args: {
9807
11191
  "context-nip": { type: "string", description: "Context NIP", required: true },
@@ -9829,7 +11213,7 @@ var revokePermissions = defineCommand11({
9829
11213
  }, { json: Boolean(args.json) });
9830
11214
  }
9831
11215
  });
9832
- var enableAttachment = defineCommand11({
11216
+ var enableAttachment = defineCommand12({
9833
11217
  meta: { name: "enable-attachment", description: "Enable attachment permission for a subject" },
9834
11218
  args: {
9835
11219
  nip: { type: "string", description: "Subject NIP", required: true },
@@ -9848,7 +11232,7 @@ var enableAttachment = defineCommand11({
9848
11232
  }, { json: Boolean(args.json) });
9849
11233
  }
9850
11234
  });
9851
- var disableAttachment = defineCommand11({
11235
+ var disableAttachment = defineCommand12({
9852
11236
  meta: { name: "disable-attachment", description: "Disable attachment permission for a subject" },
9853
11237
  args: {
9854
11238
  nip: { type: "string", description: "Subject NIP", required: true },
@@ -9871,7 +11255,7 @@ var disableAttachment = defineCommand11({
9871
11255
  }, { json: Boolean(args.json) });
9872
11256
  }
9873
11257
  });
9874
- var changeSessionLimits = defineCommand11({
11258
+ var changeSessionLimits = defineCommand12({
9875
11259
  meta: { name: "change-session-limits", description: "Change session limits in current context" },
9876
11260
  args: {
9877
11261
  "online-max-size": { type: "string", description: "Online session: max invoice size in MB (0-5)", required: true },
@@ -9908,7 +11292,7 @@ var changeSessionLimits = defineCommand11({
9908
11292
  }, { json: Boolean(args.json) });
9909
11293
  }
9910
11294
  });
9911
- var restoreSessionLimits = defineCommand11({
11295
+ var restoreSessionLimits = defineCommand12({
9912
11296
  meta: { name: "restore-session-limits", description: "Restore default session limits" },
9913
11297
  args: {
9914
11298
  env: { type: "string", description: "Environment (test/demo/prod)" },
@@ -9927,7 +11311,7 @@ var restoreSessionLimits = defineCommand11({
9927
11311
  }, { json: Boolean(args.json) });
9928
11312
  }
9929
11313
  });
9930
- var changeCertLimits = defineCommand11({
11314
+ var changeCertLimits = defineCommand12({
9931
11315
  meta: { name: "change-cert-limits", description: "Change subject limits (enrollment/certificate) in current subject" },
9932
11316
  args: {
9933
11317
  "identifier-type": { type: "string", description: "Subject identifier type (Nip/Pesel/Fingerprint)" },
@@ -9954,7 +11338,7 @@ var changeCertLimits = defineCommand11({
9954
11338
  }, { json: Boolean(args.json) });
9955
11339
  }
9956
11340
  });
9957
- var restoreCertLimits = defineCommand11({
11341
+ var restoreCertLimits = defineCommand12({
9958
11342
  meta: { name: "restore-cert-limits", description: "Restore default certificates limit" },
9959
11343
  args: {
9960
11344
  env: { type: "string", description: "Environment (test/demo/prod)" },
@@ -9973,7 +11357,7 @@ var restoreCertLimits = defineCommand11({
9973
11357
  }, { json: Boolean(args.json) });
9974
11358
  }
9975
11359
  });
9976
- var setRateLimits = defineCommand11({
11360
+ var setRateLimits = defineCommand12({
9977
11361
  meta: { name: "set-rate-limits", description: "Set effective API rate limits" },
9978
11362
  args: {
9979
11363
  limits: { type: "string", description: "Rate limits as JSON string (ApiRateLimitsOverride)", required: true },
@@ -9996,7 +11380,7 @@ var setRateLimits = defineCommand11({
9996
11380
  }, { json: Boolean(args.json) });
9997
11381
  }
9998
11382
  });
9999
- var restoreRateLimits = defineCommand11({
11383
+ var restoreRateLimits = defineCommand12({
10000
11384
  meta: { name: "restore-rate-limits", description: "Restore default API rate limits" },
10001
11385
  args: {
10002
11386
  env: { type: "string", description: "Environment (test/demo/prod)" },
@@ -10015,7 +11399,7 @@ var restoreRateLimits = defineCommand11({
10015
11399
  }, { json: Boolean(args.json) });
10016
11400
  }
10017
11401
  });
10018
- var setProductionRateLimits = defineCommand11({
11402
+ var setProductionRateLimits = defineCommand12({
10019
11403
  meta: { name: "set-production-rate-limits", description: "Set production API rate limits" },
10020
11404
  args: {
10021
11405
  env: { type: "string", description: "Environment (test/demo/prod)" },
@@ -10034,7 +11418,7 @@ var setProductionRateLimits = defineCommand11({
10034
11418
  }, { json: Boolean(args.json) });
10035
11419
  }
10036
11420
  });
10037
- var blockContext = defineCommand11({
11421
+ var blockContext = defineCommand12({
10038
11422
  meta: { name: "block-context", description: "Block a context" },
10039
11423
  args: {
10040
11424
  "context-value": { type: "string", description: "Context identifier value", required: true },
@@ -10061,7 +11445,7 @@ var blockContext = defineCommand11({
10061
11445
  }, { json: Boolean(args.json) });
10062
11446
  }
10063
11447
  });
10064
- var unblockContext = defineCommand11({
11448
+ var unblockContext = defineCommand12({
10065
11449
  meta: { name: "unblock-context", description: "Unblock a context" },
10066
11450
  args: {
10067
11451
  "context-value": { type: "string", description: "Context identifier value", required: true },
@@ -10088,7 +11472,7 @@ var unblockContext = defineCommand11({
10088
11472
  }, { json: Boolean(args.json) });
10089
11473
  }
10090
11474
  });
10091
- var testDataCommand = defineCommand11({
11475
+ var testDataCommand = defineCommand12({
10092
11476
  meta: { name: "test-data", description: "Test environment data management (test/demo only)" },
10093
11477
  subCommands: {
10094
11478
  "create-subject": createSubject,
@@ -10112,7 +11496,7 @@ var testDataCommand = defineCommand11({
10112
11496
  });
10113
11497
 
10114
11498
  // src/cli/commands/limits.ts
10115
- import { defineCommand as defineCommand12 } from "citty";
11499
+ import { defineCommand as defineCommand13 } from "citty";
10116
11500
  function getGlobalOpts11(args) {
10117
11501
  return {
10118
11502
  env: args.env,
@@ -10122,7 +11506,7 @@ function getGlobalOpts11(args) {
10122
11506
  nip: args.nip
10123
11507
  };
10124
11508
  }
10125
- var context = defineCommand12({
11509
+ var context = defineCommand13({
10126
11510
  meta: { name: "context", description: "View effective context limits" },
10127
11511
  args: {
10128
11512
  env: { type: "string", description: "Environment (test/demo/prod)" },
@@ -10150,7 +11534,7 @@ var context = defineCommand12({
10150
11534
  }, { json: Boolean(args.json) });
10151
11535
  }
10152
11536
  });
10153
- var subject = defineCommand12({
11537
+ var subject = defineCommand13({
10154
11538
  meta: { name: "subject", description: "View effective subject limits" },
10155
11539
  args: {
10156
11540
  env: { type: "string", description: "Environment (test/demo/prod)" },
@@ -10174,7 +11558,7 @@ var subject = defineCommand12({
10174
11558
  }, { json: Boolean(args.json) });
10175
11559
  }
10176
11560
  });
10177
- var rate = defineCommand12({
11561
+ var rate = defineCommand13({
10178
11562
  meta: { name: "rate", description: "View effective API rate limits" },
10179
11563
  args: {
10180
11564
  env: { type: "string", description: "Environment (test/demo/prod)" },
@@ -10210,14 +11594,14 @@ var rate = defineCommand12({
10210
11594
  }, { json: Boolean(args.json) });
10211
11595
  }
10212
11596
  });
10213
- var limitsCommand = defineCommand12({
11597
+ var limitsCommand = defineCommand13({
10214
11598
  meta: { name: "limits", description: "View KSeF API limits" },
10215
11599
  subCommands: { context, subject, rate }
10216
11600
  });
10217
11601
 
10218
11602
  // src/cli/commands/peppol.ts
10219
- import { defineCommand as defineCommand13 } from "citty";
10220
- import { consola as consola12 } from "consola";
11603
+ import { defineCommand as defineCommand14 } from "citty";
11604
+ import { consola as consola14 } from "consola";
10221
11605
  function getGlobalOpts12(args) {
10222
11606
  return {
10223
11607
  env: args.env,
@@ -10227,7 +11611,7 @@ function getGlobalOpts12(args) {
10227
11611
  nip: args.nip
10228
11612
  };
10229
11613
  }
10230
- var providers = defineCommand13({
11614
+ var providers = defineCommand14({
10231
11615
  meta: { name: "providers", description: "Query Peppol providers" },
10232
11616
  args: {
10233
11617
  page: { type: "string", description: "Page offset" },
@@ -10266,19 +11650,19 @@ var providers = defineCommand13({
10266
11650
  { json: false }
10267
11651
  );
10268
11652
  if (result.hasMore) {
10269
- consola12.info("More results available. Use --page to paginate.");
11653
+ consola14.info("More results available. Use --page to paginate.");
10270
11654
  }
10271
11655
  }, { json: Boolean(args.json) });
10272
11656
  }
10273
11657
  });
10274
- var peppolCommand = defineCommand13({
11658
+ var peppolCommand = defineCommand14({
10275
11659
  meta: { name: "peppol", description: "Peppol integration commands" },
10276
11660
  subCommands: { providers }
10277
11661
  });
10278
11662
 
10279
11663
  // src/cli/commands/doctor.ts
10280
- import { defineCommand as defineCommand14 } from "citty";
10281
- import { consola as consola13 } from "consola";
11664
+ import { defineCommand as defineCommand15 } from "citty";
11665
+ import { consola as consola15 } from "consola";
10282
11666
  function getGlobalOpts13(args) {
10283
11667
  return {
10284
11668
  env: args.env,
@@ -10288,7 +11672,7 @@ function getGlobalOpts13(args) {
10288
11672
  verbose: args.verbose
10289
11673
  };
10290
11674
  }
10291
- var doctorCommand = defineCommand14({
11675
+ var doctorCommand = defineCommand15({
10292
11676
  meta: { name: "doctor", description: "Check CLI configuration and connectivity" },
10293
11677
  args: {
10294
11678
  env: { type: "string", description: "Environment (test/demo/prod)" },
@@ -10369,14 +11753,14 @@ var doctorCommand = defineCommand14({
10369
11753
  }
10370
11754
  for (const check of checks) {
10371
11755
  const icon = check.status === "pass" ? "\u2713" : check.status === "warn" ? "\u26A0" : "\u2717";
10372
- const log = check.status === "pass" ? consola13.success : check.status === "warn" ? consola13.warn : consola13.error;
11756
+ const log = check.status === "pass" ? consola15.success : check.status === "warn" ? consola15.warn : consola15.error;
10373
11757
  log(`${icon} ${check.message}`);
10374
11758
  }
10375
11759
  if (passed === total) {
10376
- consola13.success(`
11760
+ consola15.success(`
10377
11761
  ${passed}/${total} checks passed.`);
10378
11762
  } else {
10379
- consola13.warn(`
11763
+ consola15.warn(`
10380
11764
  ${passed}/${total} checks passed.`);
10381
11765
  }
10382
11766
  }, { json: Boolean(args.json) });
@@ -10384,7 +11768,7 @@ ${passed}/${total} checks passed.`);
10384
11768
  });
10385
11769
 
10386
11770
  // src/cli/commands/completion.ts
10387
- import { defineCommand as defineCommand15 } from "citty";
11771
+ import { defineCommand as defineCommand16 } from "citty";
10388
11772
  var COMMAND_TREE = {
10389
11773
  config: ["set", "show", "reset"],
10390
11774
  auth: ["challenge", "login", "status", "logout", "refresh", "whoami"],
@@ -10476,41 +11860,41 @@ function generateFish() {
10476
11860
  }
10477
11861
  return lines.join("\n") + "\n";
10478
11862
  }
10479
- var bash = defineCommand15({
11863
+ var bash = defineCommand16({
10480
11864
  meta: { name: "bash", description: "Generate bash completion script" },
10481
11865
  run() {
10482
11866
  console.log(generateBash());
10483
11867
  }
10484
11868
  });
10485
- var zsh = defineCommand15({
11869
+ var zsh = defineCommand16({
10486
11870
  meta: { name: "zsh", description: "Generate zsh completion script" },
10487
11871
  run() {
10488
11872
  console.log(generateZsh());
10489
11873
  }
10490
11874
  });
10491
- var fish = defineCommand15({
11875
+ var fish = defineCommand16({
10492
11876
  meta: { name: "fish", description: "Generate fish completion script" },
10493
11877
  run() {
10494
11878
  console.log(generateFish());
10495
11879
  }
10496
11880
  });
10497
- var completionCommand = defineCommand15({
11881
+ var completionCommand = defineCommand16({
10498
11882
  meta: { name: "completion", description: "Generate shell completion scripts" },
10499
11883
  subCommands: { bash, zsh, fish }
10500
11884
  });
10501
11885
 
10502
11886
  // src/cli/commands/setup.ts
10503
- import * as fs12 from "fs";
10504
- import * as path8 from "path";
10505
- import * as os5 from "os";
10506
- import { defineCommand as defineCommand16 } from "citty";
10507
- import { consola as consola14 } from "consola";
11887
+ import * as fs14 from "node:fs";
11888
+ import * as path10 from "node:path";
11889
+ import * as os5 from "node:os";
11890
+ import { defineCommand as defineCommand17 } from "citty";
11891
+ import { consola as consola16 } from "consola";
10508
11892
  init_patterns();
10509
11893
  init_auth_xml_builder();
10510
11894
  init_polling();
10511
11895
 
10512
11896
  // src/cli/utils/open-folder.ts
10513
- import { execFile } from "child_process";
11897
+ import { execFile } from "node:child_process";
10514
11898
  function openFolder(folderPath) {
10515
11899
  return new Promise((resolve2) => {
10516
11900
  const platform = process.platform;
@@ -10533,8 +11917,8 @@ function openFolder(folderPath) {
10533
11917
  }
10534
11918
 
10535
11919
  // src/cli/commands/setup.ts
10536
- var KSEF_DIR = path8.join(os5.homedir(), ".ksef");
10537
- var AUTH_XML_FILE = path8.join(KSEF_DIR, "auth.xml");
11920
+ var KSEF_DIR = path10.join(os5.homedir(), ".ksef");
11921
+ var AUTH_XML_FILE = path10.join(KSEF_DIR, "auth.xml");
10538
11922
  var SIGNING_URL = "https://podpis.gov.pl/podpisz-dokument-elektronicznie/";
10539
11923
  var ALL_PERMISSIONS = [
10540
11924
  { value: "InvoiceRead", label: "InvoiceRead \u2014 Read invoices" },
@@ -10547,36 +11931,36 @@ var ALL_PERMISSIONS = [
10547
11931
  ];
10548
11932
  function expandTilde(p) {
10549
11933
  if (p.startsWith("~")) {
10550
- return path8.join(os5.homedir(), p.slice(1));
11934
+ return path10.join(os5.homedir(), p.slice(1));
10551
11935
  }
10552
11936
  return p;
10553
11937
  }
10554
11938
  async function promptNip() {
10555
11939
  while (true) {
10556
- const nip = await consola14.prompt("Enter your NIP (10 digits):", {
11940
+ const nip = await consola16.prompt("Enter your NIP (10 digits):", {
10557
11941
  type: "text",
10558
11942
  cancel: "reject"
10559
11943
  });
10560
11944
  if (isValidNip(nip.trim())) {
10561
11945
  return nip.trim();
10562
11946
  }
10563
- consola14.warn("Invalid NIP. Must be a valid 10-digit Polish tax identification number.");
11947
+ consola16.warn("Invalid NIP. Must be a valid 10-digit Polish tax identification number.");
10564
11948
  }
10565
11949
  }
10566
11950
  async function promptSignedXmlPath() {
10567
11951
  while (true) {
10568
- const raw = await consola14.prompt("Path to signed XML file:", {
11952
+ const raw = await consola16.prompt("Path to signed XML file:", {
10569
11953
  type: "text",
10570
11954
  cancel: "reject"
10571
11955
  });
10572
11956
  const resolved = expandTilde(raw.trim());
10573
- if (fs12.existsSync(resolved)) {
11957
+ if (fs14.existsSync(resolved)) {
10574
11958
  return resolved;
10575
11959
  }
10576
- consola14.warn(`File not found: ${resolved}`);
11960
+ consola16.warn(`File not found: ${resolved}`);
10577
11961
  }
10578
11962
  }
10579
- var setupCommand = defineCommand16({
11963
+ var setupCommand = defineCommand17({
10580
11964
  meta: { name: "setup", description: "Interactive setup wizard for KSeF CLI" },
10581
11965
  args: {
10582
11966
  env: { type: "string", description: "Environment (test/demo/prod)" }
@@ -10588,17 +11972,17 @@ var setupCommand = defineCommand16({
10588
11972
  "Interactive terminal required. Use `ksef auth login-external` and `ksef token generate` for non-interactive setup."
10589
11973
  );
10590
11974
  }
10591
- consola14.box("KSeF CLI Setup Wizard");
11975
+ consola16.box("KSeF CLI Setup Wizard");
10592
11976
  const existingSession = loadSession();
10593
11977
  const existingCredentials = loadCredentials();
10594
11978
  if (existingSession || existingCredentials?.token) {
10595
- const overwrite = await consola14.prompt("An existing session or token was found. Overwrite?", {
11979
+ const overwrite = await consola16.prompt("An existing session or token was found. Overwrite?", {
10596
11980
  type: "confirm",
10597
11981
  initial: false,
10598
11982
  cancel: "reject"
10599
11983
  });
10600
11984
  if (!overwrite) {
10601
- consola14.info("Setup cancelled.");
11985
+ consola16.info("Setup cancelled.");
10602
11986
  return;
10603
11987
  }
10604
11988
  }
@@ -10606,25 +11990,25 @@ var setupCommand = defineCommand16({
10606
11990
  const env = args.env ?? config.environment;
10607
11991
  const nip = await promptNip();
10608
11992
  saveConfig({ ...config, nip, environment: env });
10609
- consola14.info(`Config saved: NIP=${nip}, env=${env}`);
11993
+ consola16.info(`Config saved: NIP=${nip}, env=${env}`);
10610
11994
  const client = createClient({ env });
10611
11995
  let useSelfSigned = false;
10612
11996
  if (env === "test") {
10613
- useSelfSigned = await consola14.prompt("Test environment detected. Use self-signed certificate for quick auth?", {
11997
+ useSelfSigned = await consola16.prompt("Test environment detected. Use self-signed certificate for quick auth?", {
10614
11998
  type: "confirm",
10615
11999
  initial: true,
10616
12000
  cancel: "reject"
10617
12001
  });
10618
12002
  }
10619
12003
  if (useSelfSigned) {
10620
- consola14.info("Generating self-signed certificate...");
12004
+ consola16.info("Generating self-signed certificate...");
10621
12005
  const cert = await CertificateService.generateCompanySeal(
10622
12006
  "CLI Setup",
10623
12007
  `VATPL-${nip}`,
10624
12008
  `CLI Setup ${nip}`,
10625
12009
  "RSA"
10626
12010
  );
10627
- consola14.info("Authenticating with self-signed certificate...");
12011
+ consola16.info("Authenticating with self-signed certificate...");
10628
12012
  await client.loginWithCertificate(cert.certificatePem, cert.privateKeyPem, nip);
10629
12013
  const session = {
10630
12014
  accessToken: client.authManager.getAccessToken(),
@@ -10636,15 +12020,15 @@ var setupCommand = defineCommand16({
10636
12020
  } else {
10637
12021
  let authenticated = false;
10638
12022
  while (!authenticated) {
10639
- consola14.info("Requesting authorization challenge from KSeF...");
12023
+ consola16.info("Requesting authorization challenge from KSeF...");
10640
12024
  const challengeResult = await client.auth.getChallenge();
10641
12025
  const unsignedXml = buildUnsignedAuthTokenRequestXml({
10642
12026
  challenge: challengeResult.challenge,
10643
12027
  contextIdentifier: { type: "Nip", value: nip }
10644
12028
  });
10645
- fs12.mkdirSync(KSEF_DIR, { recursive: true });
10646
- fs12.writeFileSync(AUTH_XML_FILE, unsignedXml, "utf-8");
10647
- consola14.info(`Unsigned XML saved to ${AUTH_XML_FILE}`);
12029
+ fs14.mkdirSync(KSEF_DIR, { recursive: true });
12030
+ fs14.writeFileSync(AUTH_XML_FILE, unsignedXml, "utf-8");
12031
+ consola16.info(`Unsigned XML saved to ${AUTH_XML_FILE}`);
10648
12032
  savePendingChallenge({
10649
12033
  challenge: challengeResult.challenge,
10650
12034
  timestamp: challengeResult.timestamp,
@@ -10653,9 +12037,9 @@ var setupCommand = defineCommand16({
10653
12037
  });
10654
12038
  const opened = await openFolder(KSEF_DIR);
10655
12039
  if (!opened) {
10656
- consola14.info(`Open the folder manually: ${KSEF_DIR}`);
12040
+ consola16.info(`Open the folder manually: ${KSEF_DIR}`);
10657
12041
  }
10658
- consola14.box([
12042
+ consola16.box([
10659
12043
  "Sign the XML file using a qualified signature:",
10660
12044
  "",
10661
12045
  ` 1. Open: ${SIGNING_URL}`,
@@ -10664,12 +12048,12 @@ var setupCommand = defineCommand16({
10664
12048
  " 4. Download the signed XML file"
10665
12049
  ].join("\n"));
10666
12050
  const signedXmlPath = await promptSignedXmlPath();
10667
- const signedXml = fs12.readFileSync(signedXmlPath, "utf-8");
12051
+ const signedXml = fs14.readFileSync(signedXmlPath, "utf-8");
10668
12052
  try {
10669
- consola14.info("Submitting signed XML to KSeF...");
12053
+ consola16.info("Submitting signed XML to KSeF...");
10670
12054
  const submitResult = await client.auth.submitXadesAuthRequest(signedXml);
10671
12055
  const authToken = submitResult.authenticationToken.token;
10672
- consola14.info("Waiting for authorization...");
12056
+ consola16.info("Waiting for authorization...");
10673
12057
  await pollUntil(
10674
12058
  () => client.auth.getAuthStatus(submitResult.referenceNumber, authToken),
10675
12059
  (s) => s.status.code !== 100,
@@ -10688,36 +12072,36 @@ var setupCommand = defineCommand16({
10688
12072
  outputSuccess("Authenticated successfully via external signature.");
10689
12073
  } catch (error) {
10690
12074
  const msg = error instanceof Error ? error.message : String(error);
10691
- consola14.error(`Authentication failed: ${msg}`);
10692
- const retry = await consola14.prompt("Get a new challenge and try again?", {
12075
+ consola16.error(`Authentication failed: ${msg}`);
12076
+ const retry = await consola16.prompt("Get a new challenge and try again?", {
10693
12077
  type: "confirm",
10694
12078
  initial: true,
10695
12079
  cancel: "reject"
10696
12080
  });
10697
12081
  if (!retry) {
10698
- consola14.info("Setup incomplete. Your NIP and environment are saved. Run `ksef auth login-external` to authenticate later.");
12082
+ consola16.info("Setup incomplete. Your NIP and environment are saved. Run `ksef auth login-external` to authenticate later.");
10699
12083
  return;
10700
12084
  }
10701
12085
  }
10702
12086
  }
10703
12087
  }
10704
- const generateToken = await consola14.prompt("Generate a long-lived API token?", {
12088
+ const generateToken = await consola16.prompt("Generate a long-lived API token?", {
10705
12089
  type: "confirm",
10706
12090
  initial: true,
10707
12091
  cancel: "reject"
10708
12092
  });
10709
12093
  if (generateToken) {
10710
12094
  try {
10711
- const selectedPermissions = await consola14.prompt("Select token permissions:", {
12095
+ const selectedPermissions = await consola16.prompt("Select token permissions:", {
10712
12096
  type: "multiselect",
10713
12097
  options: ALL_PERMISSIONS,
10714
12098
  cancel: "reject"
10715
12099
  });
10716
12100
  if (selectedPermissions.length === 0) {
10717
- consola14.warn("No permissions selected. Skipping token generation.");
12101
+ consola16.warn("No permissions selected. Skipping token generation.");
10718
12102
  } else {
10719
12103
  const defaultDescription = `KSeF CLI API Token ${(/* @__PURE__ */ new Date()).toISOString().slice(0, 10)}`;
10720
- const description = await consola14.prompt(`Token description (${defaultDescription}):`, {
12104
+ const description = await consola16.prompt(`Token description (${defaultDescription}):`, {
10721
12105
  type: "text",
10722
12106
  default: defaultDescription,
10723
12107
  cancel: "reject"
@@ -10739,19 +12123,19 @@ var setupCommand = defineCommand16({
10739
12123
  environment: env
10740
12124
  };
10741
12125
  saveSession(newSession);
10742
- consola14.info("Re-authenticated with generated token.");
12126
+ consola16.info("Re-authenticated with generated token.");
10743
12127
  } catch {
10744
- consola14.warn("Token saved but re-login failed. Run `ksef auth login` to authenticate with the stored token.");
12128
+ consola16.warn("Token saved but re-login failed. Run `ksef auth login` to authenticate with the stored token.");
10745
12129
  }
10746
12130
  }
10747
12131
  } catch (error) {
10748
12132
  const msg = error instanceof Error ? error.message : String(error);
10749
- consola14.error(`Token generation failed: ${msg}`);
10750
- consola14.info("Your session is still active. Run `ksef token generate` to create a token later.");
12133
+ consola16.error(`Token generation failed: ${msg}`);
12134
+ consola16.info("Your session is still active. Run `ksef token generate` to create a token later.");
10751
12135
  }
10752
12136
  }
10753
12137
  const finalCredentials = loadCredentials();
10754
- consola14.box([
12138
+ consola16.box([
10755
12139
  "Setup complete!",
10756
12140
  "",
10757
12141
  ` Environment: ${env}`,
@@ -10769,14 +12153,14 @@ var setupCommand = defineCommand16({
10769
12153
  });
10770
12154
 
10771
12155
  // src/cli/commands/offline.ts
10772
- import * as fs14 from "fs";
10773
- import { defineCommand as defineCommand17 } from "citty";
10774
- import { consola as consola15 } from "consola";
12156
+ import * as fs16 from "node:fs";
12157
+ import { defineCommand as defineCommand18 } from "citty";
12158
+ import { consola as consola17 } from "consola";
10775
12159
 
10776
12160
  // src/offline/file-storage.ts
10777
- import * as fs13 from "fs/promises";
10778
- import * as path9 from "path";
10779
- import * as os6 from "os";
12161
+ import * as fs15 from "node:fs/promises";
12162
+ import * as path11 from "node:path";
12163
+ import * as os6 from "node:os";
10780
12164
 
10781
12165
  // src/offline/storage.ts
10782
12166
  function matchesFilter(invoice3, filter) {
@@ -10796,7 +12180,7 @@ function matchesFilter(invoice3, filter) {
10796
12180
  // src/offline/file-storage.ts
10797
12181
  function resolveDir(dir) {
10798
12182
  if (dir === "~" || dir.startsWith("~/")) {
10799
- return path9.join(os6.homedir(), dir.slice(1));
12183
+ return path11.join(os6.homedir(), dir.slice(1));
10800
12184
  }
10801
12185
  return dir;
10802
12186
  }
@@ -10812,23 +12196,23 @@ var FileOfflineInvoiceStorage = class {
10812
12196
  this.dir = resolveDir(directory ?? "~/.ksef/offline");
10813
12197
  }
10814
12198
  async ensureDir() {
10815
- await fs13.mkdir(this.dir, { recursive: true });
12199
+ await fs15.mkdir(this.dir, { recursive: true });
10816
12200
  }
10817
12201
  filePath(id) {
10818
12202
  validateId(id);
10819
- return path9.join(this.dir, `${id}.json`);
12203
+ return path11.join(this.dir, `${id}.json`);
10820
12204
  }
10821
12205
  async save(invoice3) {
10822
12206
  await this.ensureDir();
10823
12207
  const file = this.filePath(invoice3.id);
10824
12208
  const tmp = `${file}.tmp`;
10825
- await fs13.writeFile(tmp, JSON.stringify(invoice3, null, 2));
10826
- await fs13.rename(tmp, file);
12209
+ await fs15.writeFile(tmp, JSON.stringify(invoice3, null, 2));
12210
+ await fs15.rename(tmp, file);
10827
12211
  }
10828
12212
  async get(id) {
10829
12213
  const file = this.filePath(id);
10830
12214
  try {
10831
- return JSON.parse(await fs13.readFile(file, "utf-8"));
12215
+ return JSON.parse(await fs15.readFile(file, "utf-8"));
10832
12216
  } catch (err) {
10833
12217
  if (err instanceof Error && "code" in err && err.code === "ENOENT") {
10834
12218
  return null;
@@ -10840,7 +12224,7 @@ var FileOfflineInvoiceStorage = class {
10840
12224
  async list(filter) {
10841
12225
  let files;
10842
12226
  try {
10843
- files = (await fs13.readdir(this.dir)).filter((f) => f.endsWith(".json"));
12227
+ files = (await fs15.readdir(this.dir)).filter((f) => f.endsWith(".json"));
10844
12228
  } catch {
10845
12229
  return [];
10846
12230
  }
@@ -10848,7 +12232,7 @@ var FileOfflineInvoiceStorage = class {
10848
12232
  for (const file of files) {
10849
12233
  try {
10850
12234
  const data = JSON.parse(
10851
- await fs13.readFile(path9.join(this.dir, file), "utf-8")
12235
+ await fs15.readFile(path11.join(this.dir, file), "utf-8")
10852
12236
  );
10853
12237
  if (!filter || matchesFilter(data, filter)) {
10854
12238
  results.push(data);
@@ -10874,7 +12258,7 @@ var FileOfflineInvoiceStorage = class {
10874
12258
  async delete(id) {
10875
12259
  const file = this.filePath(id);
10876
12260
  try {
10877
- await fs13.unlink(file);
12261
+ await fs15.unlink(file);
10878
12262
  } catch (e) {
10879
12263
  if (e instanceof Error && "code" in e && e.code !== "ENOENT") throw e;
10880
12264
  }
@@ -10903,7 +12287,7 @@ var globalArgs = {
10903
12287
  nip: { type: "string", description: "NIP number" },
10904
12288
  "store-dir": { type: "string", description: "Offline invoice store directory" }
10905
12289
  };
10906
- var generate3 = defineCommand17({
12290
+ var generate3 = defineCommand18({
10907
12291
  meta: { name: "generate", description: "Generate offline invoice metadata with QR codes" },
10908
12292
  args: {
10909
12293
  ...globalArgs,
@@ -10922,10 +12306,10 @@ var generate3 = defineCommand17({
10922
12306
  const globalOpts = getGlobalOpts14(args);
10923
12307
  const config = loadConfig();
10924
12308
  const xmlPath = args.xml;
10925
- if (!fs14.existsSync(xmlPath)) {
12309
+ if (!fs16.existsSync(xmlPath)) {
10926
12310
  throw new Error(`File not found: ${xmlPath}`);
10927
12311
  }
10928
- const invoiceXml = fs14.readFileSync(xmlPath, "utf-8");
12312
+ const invoiceXml = fs16.readFileSync(xmlPath, "utf-8");
10929
12313
  const sellerNip = args.nip ?? config.nip;
10930
12314
  if (!sellerNip) {
10931
12315
  throw new Error("NIP is required. Use --nip or set via `ksef config set --nip`");
@@ -10938,7 +12322,7 @@ var generate3 = defineCommand17({
10938
12322
  throw new Error("--cert-serial is required when using --key");
10939
12323
  }
10940
12324
  const certificate2 = args.key ? {
10941
- privateKeyPem: fs14.readFileSync(args.key, "utf-8"),
12325
+ privateKeyPem: fs16.readFileSync(args.key, "utf-8"),
10942
12326
  certificateSerial: args["cert-serial"]
10943
12327
  } : void 0;
10944
12328
  const validModes = ["offline24", "offline", "awaryjny", "awaria_calkowita"];
@@ -10964,7 +12348,7 @@ var generate3 = defineCommand17({
10964
12348
  );
10965
12349
  if (args["qr-out"]) {
10966
12350
  const outDir = args["qr-out"];
10967
- fs14.mkdirSync(outDir, { recursive: true });
12351
+ fs16.mkdirSync(outDir, { recursive: true });
10968
12352
  const format = args["qr-format"] ?? "png";
10969
12353
  if (format !== "png" && format !== "svg") {
10970
12354
  throw new Error(`Invalid --qr-format "${format}". Must be one of: png, svg`);
@@ -10972,17 +12356,17 @@ var generate3 = defineCommand17({
10972
12356
  const shortId = metadata.id.slice(0, 8);
10973
12357
  if (format === "svg") {
10974
12358
  const svg1 = await QrCodeService.generateQrCodeSvgWithLabel(metadata.kod1Url, "OFFLINE");
10975
- fs14.writeFileSync(`${outDir}/${shortId}-kod1.svg`, svg1);
12359
+ fs16.writeFileSync(`${outDir}/${shortId}-kod1.svg`, svg1);
10976
12360
  if (metadata.kod2Url) {
10977
12361
  const svg2 = await QrCodeService.generateQrCodeSvgWithLabel(metadata.kod2Url, "CERTYFIKAT");
10978
- fs14.writeFileSync(`${outDir}/${shortId}-kod2.svg`, svg2);
12362
+ fs16.writeFileSync(`${outDir}/${shortId}-kod2.svg`, svg2);
10979
12363
  }
10980
12364
  } else {
10981
12365
  const png1 = await QrCodeService.generateQrCode(metadata.kod1Url);
10982
- fs14.writeFileSync(`${outDir}/${shortId}-kod1.png`, png1);
12366
+ fs16.writeFileSync(`${outDir}/${shortId}-kod1.png`, png1);
10983
12367
  if (metadata.kod2Url) {
10984
12368
  const png2 = await QrCodeService.generateQrCode(metadata.kod2Url);
10985
- fs14.writeFileSync(`${outDir}/${shortId}-kod2.png`, png2);
12369
+ fs16.writeFileSync(`${outDir}/${shortId}-kod2.png`, png2);
10986
12370
  }
10987
12371
  }
10988
12372
  outputSuccess(`QR codes saved to ${outDir}/`);
@@ -11005,7 +12389,7 @@ var generate3 = defineCommand17({
11005
12389
  }, { json: Boolean(args.json) });
11006
12390
  }
11007
12391
  });
11008
- var list4 = defineCommand17({
12392
+ var list4 = defineCommand18({
11009
12393
  meta: { name: "list", description: "List stored offline invoices" },
11010
12394
  args: {
11011
12395
  ...globalArgs,
@@ -11054,7 +12438,7 @@ var list4 = defineCommand17({
11054
12438
  }, { json: Boolean(args.json) });
11055
12439
  }
11056
12440
  });
11057
- var status6 = defineCommand17({
12441
+ var status6 = defineCommand18({
11058
12442
  meta: { name: "status", description: "Show offline invoice details" },
11059
12443
  args: {
11060
12444
  ...globalArgs,
@@ -11090,7 +12474,7 @@ var status6 = defineCommand17({
11090
12474
  }, { json: Boolean(args.json) });
11091
12475
  }
11092
12476
  });
11093
- var submit = defineCommand17({
12477
+ var submit = defineCommand18({
11094
12478
  meta: { name: "submit", description: "Submit offline invoices to KSeF" },
11095
12479
  args: {
11096
12480
  ...globalArgs,
@@ -11146,7 +12530,7 @@ var submit = defineCommand17({
11146
12530
  }, { json: Boolean(args.json) });
11147
12531
  }
11148
12532
  });
11149
- var correct = defineCommand17({
12533
+ var correct = defineCommand18({
11150
12534
  meta: { name: "correct", description: "Technical correction for rejected offline invoice" },
11151
12535
  args: {
11152
12536
  ...globalArgs,
@@ -11159,10 +12543,10 @@ var correct = defineCommand17({
11159
12543
  const { client } = await requireSession(globalOpts);
11160
12544
  const storage = getStorage(args);
11161
12545
  const xmlPath = args.xml;
11162
- if (!fs14.existsSync(xmlPath)) {
12546
+ if (!fs16.existsSync(xmlPath)) {
11163
12547
  throw new Error(`File not found: ${xmlPath}`);
11164
12548
  }
11165
- const correctedXml = fs14.readFileSync(xmlPath, "utf-8");
12549
+ const correctedXml = fs16.readFileSync(xmlPath, "utf-8");
11166
12550
  const result = await client.offline.correct(client, {
11167
12551
  rejectedInvoiceId: args.id,
11168
12552
  correctedInvoiceXml: correctedXml,
@@ -11176,7 +12560,7 @@ var correct = defineCommand17({
11176
12560
  }, { json: Boolean(args.json) });
11177
12561
  }
11178
12562
  });
11179
- var del = defineCommand17({
12563
+ var del = defineCommand18({
11180
12564
  meta: { name: "delete", description: "Delete offline invoice from local store" },
11181
12565
  args: {
11182
12566
  ...globalArgs,
@@ -11199,12 +12583,12 @@ var del = defineCommand17({
11199
12583
  `${expired.length} expired invoice(s) would be deleted. Use --force to confirm in non-interactive mode.`
11200
12584
  );
11201
12585
  }
11202
- const confirmed = await consola15.prompt(
12586
+ const confirmed = await consola17.prompt(
11203
12587
  `Delete ${expired.length} expired invoice(s)?`,
11204
12588
  { type: "confirm", initial: false }
11205
12589
  );
11206
12590
  if (!confirmed) {
11207
- consola15.info("Cancelled.");
12591
+ consola17.info("Cancelled.");
11208
12592
  return;
11209
12593
  }
11210
12594
  }
@@ -11226,16 +12610,16 @@ var del = defineCommand17({
11226
12610
  }, { json: Boolean(args.json) });
11227
12611
  }
11228
12612
  });
11229
- var offlineCommand = defineCommand17({
12613
+ var offlineCommand = defineCommand18({
11230
12614
  meta: { name: "offline", description: "Offline invoice management" },
11231
12615
  subCommands: { generate: generate3, list: list4, status: status6, submit, correct, delete: del }
11232
12616
  });
11233
12617
 
11234
12618
  // src/cli/index.ts
11235
- var __dirname = dirname2(fileURLToPath(import.meta.url));
11236
- var pkg = JSON.parse(readFileSync9(resolve(__dirname, "..", "package.json"), "utf-8"));
12619
+ var __dirname = dirname3(fileURLToPath2(import.meta.url));
12620
+ var pkg = JSON.parse(readFileSync11(resolve(__dirname, "..", "package.json"), "utf-8"));
11237
12621
  var version = pkg.version;
11238
- var main = defineCommand18({
12622
+ var main = defineCommand19({
11239
12623
  meta: {
11240
12624
  name: "ksef",
11241
12625
  version,