ksef-client-ts 0.8.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -291,7 +291,9 @@ var init_error_codes = __esm({
291
291
  "use strict";
292
292
  KSeFErrorCode = {
293
293
  BatchTimeout: 21208,
294
- DuplicateInvoice: 440
294
+ DuplicateInvoice: 440,
295
+ /** The supplied public key identifier is unknown or points to a revoked key (KSeF API v2.5.0). */
296
+ UnknownPublicKeyId: 21470
295
297
  };
296
298
  }
297
299
  });
@@ -320,6 +322,37 @@ var init_ksef_batch_timeout_error = __esm({
320
322
  }
321
323
  });
322
324
 
325
+ // src/errors/ksef-unknown-public-key-error.ts
326
+ function messageOf(description) {
327
+ return description?.trim() || "The supplied public key identifier is unknown or revoked (KSeF 21470).";
328
+ }
329
+ var KSeFUnknownPublicKeyError;
330
+ var init_ksef_unknown_public_key_error = __esm({
331
+ "src/errors/ksef-unknown-public-key-error.ts"() {
332
+ "use strict";
333
+ init_ksef_api_error();
334
+ init_error_codes();
335
+ KSeFUnknownPublicKeyError = class _KSeFUnknownPublicKeyError extends KSeFApiError {
336
+ statusCode = 400;
337
+ errorCode = KSeFErrorCode.UnknownPublicKeyId;
338
+ constructor(message, errorResponse) {
339
+ super(message, 400, errorResponse);
340
+ this.name = "KSeFUnknownPublicKeyError";
341
+ }
342
+ static fromLegacy(body) {
343
+ const detail = body?.exception?.exceptionDetailList?.find(
344
+ (d) => d.exceptionCode === KSeFErrorCode.UnknownPublicKeyId
345
+ );
346
+ return new _KSeFUnknownPublicKeyError(messageOf(detail?.exceptionDescription), body);
347
+ }
348
+ static fromProblem(problem) {
349
+ const detail = problem.errors?.find((e) => e.code === KSeFErrorCode.UnknownPublicKeyId);
350
+ return new _KSeFUnknownPublicKeyError(messageOf(detail?.description || problem.detail));
351
+ }
352
+ };
353
+ }
354
+ });
355
+
323
356
  // src/errors/ksef-circuit-open-error.ts
324
357
  var KSeFCircuitOpenError;
325
358
  var init_ksef_circuit_open_error = __esm({
@@ -386,6 +419,7 @@ var init_errors = __esm({
386
419
  init_ksef_session_expired_error();
387
420
  init_ksef_validation_error();
388
421
  init_ksef_batch_timeout_error();
422
+ init_ksef_unknown_public_key_error();
389
423
  init_ksef_circuit_open_error();
390
424
  init_ksef_xsd_validation_error();
391
425
  init_error_codes();
@@ -652,6 +686,7 @@ var init_rest_client = __esm({
652
686
  init_ksef_gone_error();
653
687
  init_ksef_bad_request_error();
654
688
  init_ksef_batch_timeout_error();
689
+ init_ksef_unknown_public_key_error();
655
690
  init_error_codes();
656
691
  init_route_builder();
657
692
  init_transport();
@@ -666,6 +701,7 @@ var init_rest_client = __esm({
666
701
  circuitBreakerPolicy;
667
702
  authManager;
668
703
  presignedUrlPolicy;
704
+ onSystemWarning;
669
705
  constructor(options, config) {
670
706
  this.options = options;
671
707
  this.routeBuilder = new RouteBuilder(options.apiVersion);
@@ -675,23 +711,41 @@ var init_rest_client = __esm({
675
711
  this.circuitBreakerPolicy = config?.circuitBreakerPolicy ?? null;
676
712
  this.authManager = config?.authManager;
677
713
  this.presignedUrlPolicy = config?.presignedUrlPolicy;
714
+ this.onSystemWarning = config?.onSystemWarning;
678
715
  }
679
716
  async execute(request) {
680
717
  const response = await this.sendRequest(request);
681
718
  await this.ensureSuccess(response);
719
+ this.handleSystemWarning(response);
682
720
  const body = await response.json();
683
721
  return { body, headers: response.headers, statusCode: response.status };
684
722
  }
685
723
  async executeVoid(request) {
686
724
  const response = await this.sendRequest(request);
687
725
  await this.ensureSuccess(response);
726
+ this.handleSystemWarning(response);
688
727
  }
689
728
  async executeRaw(request) {
690
729
  const response = await this.sendRequest(request);
691
730
  await this.ensureSuccess(response);
731
+ this.handleSystemWarning(response);
692
732
  const body = await response.arrayBuffer();
693
733
  return { body, headers: response.headers, statusCode: response.status };
694
734
  }
735
+ /** Surface the optional `X-System-Warning` response header (KSeF API v2.6.0). */
736
+ handleSystemWarning(response) {
737
+ const warning = response.headers.get("x-system-warning");
738
+ if (!warning) return;
739
+ if (this.onSystemWarning) {
740
+ try {
741
+ this.onSystemWarning(warning);
742
+ } catch (error) {
743
+ consola3.warn("onSystemWarning callback threw an exception (ignored):", error);
744
+ }
745
+ } else {
746
+ consola3.warn(`KSeF system warning: ${warning}`);
747
+ }
748
+ }
695
749
  async sendRequest(request) {
696
750
  const url2 = this.buildUrl(request);
697
751
  if (request.isPresigned() && this.presignedUrlPolicy) {
@@ -833,9 +887,15 @@ var init_rest_client = __esm({
833
887
  if (response.status === 400) {
834
888
  const problem = tryParseProblem(isBadRequestProblem);
835
889
  if (problem) {
890
+ if (problem.errors?.some((e) => e.code === KSeFErrorCode.UnknownPublicKeyId)) {
891
+ throw KSeFUnknownPublicKeyError.fromProblem(problem);
892
+ }
836
893
  throw new KSeFBadRequestError(problem);
837
894
  }
838
895
  const legacy = parseJson();
896
+ if (hasErrorCode(legacy, KSeFErrorCode.UnknownPublicKeyId)) {
897
+ throw KSeFUnknownPublicKeyError.fromLegacy(legacy);
898
+ }
839
899
  if (hasErrorCode(legacy, KSeFErrorCode.BatchTimeout)) {
840
900
  throw KSeFBatchTimeoutError.fromResponse(400, legacy);
841
901
  }
@@ -2311,8 +2371,8 @@ var init_certificate_fetcher = __esm({
2311
2371
  init_routes();
2312
2372
  CertificateFetcher = class {
2313
2373
  restClient;
2314
- symmetricKeyPem;
2315
- ksefTokenPem;
2374
+ symmetricKey;
2375
+ ksefToken;
2316
2376
  initialized = false;
2317
2377
  constructor(restClient) {
2318
2378
  this.restClient = restClient;
@@ -2325,17 +2385,38 @@ var init_certificate_fetcher = __esm({
2325
2385
  this.initialized = false;
2326
2386
  await this.fetchCertificates();
2327
2387
  }
2388
+ /**
2389
+ * Immutable snapshot ({@link SelectedCertificate}) of the selected
2390
+ * SymmetricKeyEncryption certificate. The stored object is replaced wholesale
2391
+ * by {@link refresh}, never mutated, so holding the returned reference yields a
2392
+ * consistent pem + publicKeyId pair even if a concurrent refresh swaps the cache.
2393
+ */
2394
+ getSymmetricKeyEncryption() {
2395
+ return { ...this.requireSelected(this.symmetricKey) };
2396
+ }
2397
+ /** Immutable snapshot of the selected KsefTokenEncryption certificate. See {@link getSymmetricKeyEncryption}. */
2398
+ getKsefTokenEncryption() {
2399
+ return { ...this.requireSelected(this.ksefToken) };
2400
+ }
2328
2401
  getSymmetricKeyEncryptionPem() {
2329
- if (!this.symmetricKeyPem) {
2330
- throw new Error("CertificateFetcher not initialized. Call init() first.");
2331
- }
2332
- return this.symmetricKeyPem;
2402
+ return this.requireSelected(this.symmetricKey).pem;
2333
2403
  }
2334
2404
  getKsefTokenEncryptionPem() {
2335
- if (!this.ksefTokenPem) {
2405
+ return this.requireSelected(this.ksefToken).pem;
2406
+ }
2407
+ /** Public key identifier of the selected SymmetricKeyEncryption certificate (KSeF API v2.5.0). */
2408
+ getSymmetricKeyPublicKeyId() {
2409
+ return this.requireSelected(this.symmetricKey).publicKeyId;
2410
+ }
2411
+ /** Public key identifier of the selected KsefTokenEncryption certificate (KSeF API v2.5.0). */
2412
+ getKsefTokenPublicKeyId() {
2413
+ return this.requireSelected(this.ksefToken).publicKeyId;
2414
+ }
2415
+ requireSelected(selected) {
2416
+ if (!selected) {
2336
2417
  throw new Error("CertificateFetcher not initialized. Call init() first.");
2337
2418
  }
2338
- return this.ksefTokenPem;
2419
+ return selected;
2339
2420
  }
2340
2421
  async fetchCertificates() {
2341
2422
  const request = RestRequest.get(Routes.Security.publicKeyCertificates);
@@ -2344,19 +2425,27 @@ var init_certificate_fetcher = __esm({
2344
2425
  if (!certs || certs.length === 0) {
2345
2426
  throw new Error("No public key certificates returned from KSeF API.");
2346
2427
  }
2347
- const symmetricCert = certs.find((c) => c.usage.includes("SymmetricKeyEncryption"));
2348
- if (!symmetricCert) {
2349
- throw new Error("No SymmetricKeyEncryption certificate found.");
2350
- }
2351
- this.symmetricKeyPem = this.derBase64ToPem(symmetricCert.certificate);
2352
- const tokenCerts = certs.filter((c) => c.usage.includes("KsefTokenEncryption")).sort((a, b) => a.validFrom.localeCompare(b.validFrom));
2353
- const tokenCert = tokenCerts[0];
2354
- if (!tokenCert) {
2355
- throw new Error("No KsefTokenEncryption certificate found.");
2356
- }
2357
- this.ksefTokenPem = this.derBase64ToPem(tokenCert.certificate);
2428
+ this.symmetricKey = this.select(certs, "SymmetricKeyEncryption");
2429
+ this.ksefToken = this.select(certs, "KsefTokenEncryption");
2358
2430
  this.initialized = true;
2359
2431
  }
2432
+ /**
2433
+ * Select the certificate to use for a given usage under key rotation:
2434
+ * filter to currently-valid certificates (validFrom ≤ now < validTo) and pick
2435
+ * the newest by validFrom. If none are currently valid, fall back to the newest
2436
+ * overall so the server can reject it with a clear error rather than sending nothing.
2437
+ */
2438
+ select(certs, usage) {
2439
+ const candidates = certs.filter((c) => c.usage.includes(usage));
2440
+ if (candidates.length === 0) {
2441
+ throw new Error(`No ${usage} certificate found.`);
2442
+ }
2443
+ const now = Date.now();
2444
+ const byNewestValidFrom = (a, b) => Date.parse(b.validFrom) - Date.parse(a.validFrom);
2445
+ const valid = candidates.filter((c) => Date.parse(c.validFrom) <= now && now < Date.parse(c.validTo)).sort(byNewestValidFrom);
2446
+ const chosen = valid[0] ?? [...candidates].sort(byNewestValidFrom)[0];
2447
+ return { pem: this.derBase64ToPem(chosen.certificate), publicKeyId: chosen.publicKeyId };
2448
+ }
2360
2449
  derBase64ToPem(base64Der) {
2361
2450
  const lines = [];
2362
2451
  for (let i = 0; i < base64Der.length; i += 64) {
@@ -2411,6 +2500,14 @@ var init_cryptography_service = __esm({
2411
2500
  async init() {
2412
2501
  await this.fetcher.init();
2413
2502
  }
2503
+ /** Re-fetch KSeF public certificates, discarding the cached selection (used for key-rotation recovery). */
2504
+ async refresh() {
2505
+ await this.fetcher.refresh();
2506
+ }
2507
+ /** Identifier of the KsefTokenEncryption public key used by {@link encryptKsefToken} (KSeF API v2.5.0). */
2508
+ getKsefTokenPublicKeyId() {
2509
+ return this.fetcher.getKsefTokenPublicKeyId();
2510
+ }
2414
2511
  // ---------------------------------------------------------------------------
2415
2512
  // AES-256-CBC
2416
2513
  // ---------------------------------------------------------------------------
@@ -2456,11 +2553,12 @@ var init_cryptography_service = __esm({
2456
2553
  async getEncryptionData() {
2457
2554
  const key = crypto.randomBytes(32);
2458
2555
  const iv = crypto.randomBytes(16);
2459
- const certPem = this.fetcher.getSymmetricKeyEncryptionPem();
2460
- const encryptedKey = await this.rsaOaepEncrypt(certPem, new Uint8Array(key));
2556
+ const cert = this.fetcher.getSymmetricKeyEncryption();
2557
+ const encryptedKey = await this.rsaOaepEncrypt(cert.pem, new Uint8Array(key));
2461
2558
  const encryptionInfo = {
2462
2559
  encryptedSymmetricKey: Buffer.from(encryptedKey).toString("base64"),
2463
- initializationVector: iv.toString("base64")
2560
+ initializationVector: iv.toString("base64"),
2561
+ publicKeyId: cert.publicKeyId
2464
2562
  };
2465
2563
  return {
2466
2564
  cipherKey: new Uint8Array(key),
@@ -2485,9 +2583,29 @@ var init_cryptography_service = __esm({
2485
2583
  * `[ephemeralSPKI | nonce(12) | ciphertext+tag]`.
2486
2584
  */
2487
2585
  async encryptKsefToken(token, challengeTimestamp) {
2586
+ return this.encryptKsefTokenWithCertPem(
2587
+ this.fetcher.getKsefTokenEncryptionPem(),
2588
+ token,
2589
+ challengeTimestamp
2590
+ );
2591
+ }
2592
+ /**
2593
+ * Encrypt a KSeF token and return it together with the public key id of the
2594
+ * exact certificate used.
2595
+ *
2596
+ * Both values come from a single certificate snapshot taken before any
2597
+ * `await`, so a concurrent {@link refresh} cannot tag the ciphertext with a
2598
+ * different key than it was encrypted under (KSeF API v2.5.0). Prefer this over
2599
+ * pairing {@link encryptKsefToken} with a separate {@link getKsefTokenPublicKeyId}.
2600
+ */
2601
+ async encryptKsefTokenWithKeyId(token, challengeTimestamp) {
2602
+ const cert = this.fetcher.getKsefTokenEncryption();
2603
+ const encryptedToken = await this.encryptKsefTokenWithCertPem(cert.pem, token, challengeTimestamp);
2604
+ return { encryptedToken, publicKeyId: cert.publicKeyId };
2605
+ }
2606
+ async encryptKsefTokenWithCertPem(certPem, token, challengeTimestamp) {
2488
2607
  const timestampMs = new Date(challengeTimestamp).getTime();
2489
2608
  const plaintext = Buffer.from(`${token}|${timestampMs}`, "utf-8");
2490
- const certPem = this.fetcher.getKsefTokenEncryptionPem();
2491
2609
  const cert = new crypto.X509Certificate(certPem);
2492
2610
  const publicKey = cert.publicKey;
2493
2611
  if (publicKey.asymmetricKeyType === "rsa") {
@@ -2646,6 +2764,25 @@ var init_cryptography_service = __esm({
2646
2764
  }
2647
2765
  });
2648
2766
 
2767
+ // src/crypto/with-key-rotation-retry.ts
2768
+ async function withKeyRotationRetry(crypto8, op) {
2769
+ try {
2770
+ return await op();
2771
+ } catch (err) {
2772
+ if (err instanceof KSeFUnknownPublicKeyError) {
2773
+ await crypto8.refresh();
2774
+ return await op();
2775
+ }
2776
+ throw err;
2777
+ }
2778
+ }
2779
+ var init_with_key_rotation_retry = __esm({
2780
+ "src/crypto/with-key-rotation-retry.ts"() {
2781
+ "use strict";
2782
+ init_ksef_unknown_public_key_error();
2783
+ }
2784
+ });
2785
+
2649
2786
  // src/qr/verification-link-service.ts
2650
2787
  import crypto2 from "node:crypto";
2651
2788
  var VerificationLinkService;
@@ -2729,7 +2866,7 @@ var AUTH_TOKEN_REQUEST_NS;
2729
2866
  var init_auth_xml_builder = __esm({
2730
2867
  "src/crypto/auth-xml-builder.ts"() {
2731
2868
  "use strict";
2732
- AUTH_TOKEN_REQUEST_NS = "http://ksef.mf.gov.pl/auth/token/2.0";
2869
+ AUTH_TOKEN_REQUEST_NS = "http://ksef.mf.gov.pl/auth/token/2.1";
2733
2870
  }
2734
2871
  });
2735
2872
 
@@ -2960,6 +3097,7 @@ var init_offline_invoice_workflow = __esm({
2960
3097
  "use strict";
2961
3098
  init_ksef_api_error();
2962
3099
  init_deadline();
3100
+ init_with_key_rotation_retry();
2963
3101
  init_document_structures();
2964
3102
  OfflineInvoiceWorkflow = class {
2965
3103
  constructor(qrService) {
@@ -3066,11 +3204,14 @@ var init_offline_invoice_workflow = __esm({
3066
3204
  }
3067
3205
  if (pending.length === 0) return result;
3068
3206
  await client.crypto.init();
3069
- const encData = await client.crypto.getEncryptionData();
3070
3207
  const formCode = options.formCode ?? DEFAULT_FORM_CODE;
3071
- const openResp = await client.onlineSession.openSession(
3072
- { formCode, encryption: encData.encryptionInfo }
3073
- );
3208
+ const { encData, openResp } = await withKeyRotationRetry(client.crypto, async () => {
3209
+ const encData2 = await client.crypto.getEncryptionData();
3210
+ const openResp2 = await client.onlineSession.openSession(
3211
+ { formCode, encryption: encData2.encryptionInfo }
3212
+ );
3213
+ return { encData: encData2, openResp: openResp2 };
3214
+ });
3074
3215
  const sessionRef = openResp.referenceNumber;
3075
3216
  try {
3076
3217
  for (const inv of pending) {
@@ -3155,11 +3296,14 @@ var init_offline_invoice_workflow = __esm({
3155
3296
  }
3156
3297
  const originalHash = crypto3.createHash("sha256").update(original.invoiceXml).digest("base64");
3157
3298
  await client.crypto.init();
3158
- const encData = await client.crypto.getEncryptionData();
3159
3299
  const formCode = options.formCode ?? DEFAULT_FORM_CODE;
3160
- const openResp = await client.onlineSession.openSession(
3161
- { formCode, encryption: encData.encryptionInfo }
3162
- );
3300
+ const { encData, openResp } = await withKeyRotationRetry(client.crypto, async () => {
3301
+ const encData2 = await client.crypto.getEncryptionData();
3302
+ const openResp2 = await client.onlineSession.openSession(
3303
+ { formCode, encryption: encData2.encryptionInfo }
3304
+ );
3305
+ return { encData: encData2, openResp: openResp2 };
3306
+ });
3163
3307
  const sessionRef = openResp.referenceNumber;
3164
3308
  try {
3165
3309
  const data = new TextEncoder().encode(correctedInvoiceXml);
@@ -3611,6 +3755,9 @@ function buildRestClientConfig(options, authManager) {
3611
3755
  allowedHosts: [...base.allowedHosts, ...options.presignedUrlHosts]
3612
3756
  };
3613
3757
  }
3758
+ if (options?.onSystemWarning) {
3759
+ config.onSystemWarning = options.onSystemWarning;
3760
+ }
3614
3761
  return config;
3615
3762
  }
3616
3763
  var KSeFClient;
@@ -3639,6 +3786,7 @@ var init_client = __esm({
3639
3786
  init_test_data();
3640
3787
  init_certificate_fetcher();
3641
3788
  init_cryptography_service();
3789
+ init_with_key_rotation_retry();
3642
3790
  init_verification_link_service();
3643
3791
  init_auth_xml_builder();
3644
3792
  init_offline_invoice_workflow();
@@ -3705,11 +3853,14 @@ var init_client = __esm({
3705
3853
  async loginWithToken(token, nip) {
3706
3854
  const challenge2 = await this.auth.getChallenge();
3707
3855
  await this.crypto.init();
3708
- const encryptedToken = await this.crypto.encryptKsefToken(token, challenge2.timestamp);
3709
- const submitResult = await this.auth.submitKsefTokenAuthRequest({
3710
- challenge: challenge2.challenge,
3711
- contextIdentifier: { type: "Nip", value: nip },
3712
- encryptedToken: Buffer.from(encryptedToken).toString("base64")
3856
+ const submitResult = await withKeyRotationRetry(this.crypto, async () => {
3857
+ const { encryptedToken, publicKeyId } = await this.crypto.encryptKsefTokenWithKeyId(token, challenge2.timestamp);
3858
+ return this.auth.submitKsefTokenAuthRequest({
3859
+ challenge: challenge2.challenge,
3860
+ contextIdentifier: { type: "Nip", value: nip },
3861
+ encryptedToken: Buffer.from(encryptedToken).toString("base64"),
3862
+ publicKeyId
3863
+ });
3713
3864
  });
3714
3865
  const authToken = submitResult.authenticationToken.token;
3715
3866
  await this.awaitAuthReady(submitResult.referenceNumber, authToken);
@@ -4607,6 +4758,135 @@ var init_zip = __esm({
4607
4758
  }
4608
4759
  });
4609
4760
 
4761
+ // src/utils/targz.ts
4762
+ var targz_exports = {};
4763
+ __export(targz_exports, {
4764
+ createTarGz: () => createTarGz,
4765
+ extractTarGz: () => extractTarGz
4766
+ });
4767
+ import { createGzip, createGunzip } from "node:zlib";
4768
+ import { Readable } from "node:stream";
4769
+ import { extract, pack } from "tar-stream";
4770
+ async function createTarGz(entries) {
4771
+ const packer = pack();
4772
+ const gzip = packer.pipe(createGzip());
4773
+ const chunks = [];
4774
+ return new Promise((resolve2, reject) => {
4775
+ let settled = false;
4776
+ const fail = (err) => {
4777
+ if (settled) return;
4778
+ settled = true;
4779
+ reject(err);
4780
+ };
4781
+ packer.on("error", fail);
4782
+ gzip.on("error", fail);
4783
+ gzip.on("data", (chunk) => chunks.push(chunk));
4784
+ gzip.on("end", () => {
4785
+ if (settled) return;
4786
+ settled = true;
4787
+ resolve2(Buffer.concat(chunks));
4788
+ });
4789
+ try {
4790
+ for (const entry of entries) {
4791
+ const content = Buffer.from(entry.content);
4792
+ packer.entry({ name: entry.fileName, size: content.length }, content);
4793
+ }
4794
+ packer.finalize();
4795
+ } catch (err) {
4796
+ fail(err instanceof Error ? err : new Error(String(err)));
4797
+ }
4798
+ });
4799
+ }
4800
+ async function extractTarGz(buffer, options = {}) {
4801
+ const limits2 = { ...DEFAULT_LIMITS, ...options };
4802
+ const ratioCeiling = limits2.maxCompressionRatio !== null && limits2.maxCompressionRatio !== void 0 && buffer.length > 0 ? buffer.length * limits2.maxCompressionRatio : null;
4803
+ return new Promise((resolve2, reject) => {
4804
+ const source = Readable.from(buffer);
4805
+ const gunzip = createGunzip();
4806
+ const extractor = extract();
4807
+ const files = /* @__PURE__ */ new Map();
4808
+ let extractedFileCount = 0;
4809
+ let totalUncompressed = 0;
4810
+ let settled = false;
4811
+ const cleanup = () => {
4812
+ source.destroy();
4813
+ gunzip.destroy();
4814
+ extractor.destroy();
4815
+ };
4816
+ const fail = (err) => {
4817
+ if (settled) return;
4818
+ settled = true;
4819
+ cleanup();
4820
+ reject(err);
4821
+ };
4822
+ const succeed = () => {
4823
+ if (settled) return;
4824
+ settled = true;
4825
+ resolve2(files);
4826
+ };
4827
+ gunzip.on("data", (chunk) => {
4828
+ totalUncompressed += chunk.length;
4829
+ if (limits2.maxTotalUncompressedSize > 0 && totalUncompressed > limits2.maxTotalUncompressedSize) {
4830
+ fail(new Error("tar.gz exceeds max_total_uncompressed_size"));
4831
+ return;
4832
+ }
4833
+ if (ratioCeiling !== null && totalUncompressed > ratioCeiling) {
4834
+ fail(new Error("tar.gz exceeds max_compression_ratio"));
4835
+ }
4836
+ });
4837
+ extractor.on("entry", (header, stream, next) => {
4838
+ if (settled) {
4839
+ stream.resume();
4840
+ return;
4841
+ }
4842
+ if (header.type !== "file") {
4843
+ stream.resume();
4844
+ stream.on("end", next);
4845
+ return;
4846
+ }
4847
+ if (limits2.maxFiles > 0 && extractedFileCount >= limits2.maxFiles) {
4848
+ fail(new Error("tar.gz contains too many files"));
4849
+ return;
4850
+ }
4851
+ const chunks = [];
4852
+ let entrySize = 0;
4853
+ stream.on("data", (chunk) => {
4854
+ if (settled) return;
4855
+ entrySize += chunk.length;
4856
+ if (limits2.maxFileUncompressedSize > 0 && entrySize > limits2.maxFileUncompressedSize) {
4857
+ fail(new Error("tar.gz entry exceeds max_file_uncompressed_size"));
4858
+ return;
4859
+ }
4860
+ chunks.push(chunk);
4861
+ });
4862
+ stream.on("error", fail);
4863
+ stream.on("end", () => {
4864
+ if (settled) return;
4865
+ extractedFileCount += 1;
4866
+ files.set(header.name, Buffer.concat(chunks));
4867
+ next();
4868
+ });
4869
+ });
4870
+ extractor.on("finish", succeed);
4871
+ extractor.on("error", fail);
4872
+ gunzip.on("error", fail);
4873
+ source.on("error", fail);
4874
+ source.pipe(gunzip).pipe(extractor);
4875
+ });
4876
+ }
4877
+ var DEFAULT_LIMITS;
4878
+ var init_targz = __esm({
4879
+ "src/utils/targz.ts"() {
4880
+ "use strict";
4881
+ DEFAULT_LIMITS = {
4882
+ maxFiles: 1e4,
4883
+ maxTotalUncompressedSize: 2e9,
4884
+ maxFileUncompressedSize: 5e8,
4885
+ maxCompressionRatio: 200
4886
+ };
4887
+ }
4888
+ });
4889
+
4610
4890
  // src/validation/xml-to-object.ts
4611
4891
  import { DOMParser as DOMParser2 } from "@xmldom/xmldom";
4612
4892
  function xmlToObject(xml) {
@@ -5505,15 +5785,15 @@ var init_fa2 = __esm({
5505
5785
  }
5506
5786
  });
5507
5787
 
5508
- // src/validation/schemas/rr1-v11e.ts
5509
- var rr1_v11e_exports = {};
5510
- __export(rr1_v11e_exports, {
5511
- RR1_V11ESchema: () => RR1_V11ESchema
5788
+ // src/validation/schemas/fa-rr1.ts
5789
+ var fa_rr1_exports = {};
5790
+ __export(fa_rr1_exports, {
5791
+ FA_RR1Schema: () => FA_RR1Schema
5512
5792
  });
5513
5793
  import { z as z3 } from "zod";
5514
- var TKodFormularza3, TDataCzas3, TZnakowy4, TNaglowek3, TNrNIP3, TZnakowy5123, TPodmiot13, TKodKraju3, TGLN3, TAdres3, TAdresEmail3, TNumerTelefonu3, TStatusInfoPodatnika3, TZnakowy203, TNIPIdWew3, TWybor13, TPodmiot33, TRolaPodmiotu33, TKodWaluty3, TData3, TDataT3, TKwotowy4, TRodzajFaktury3, TTypKorekty3, TNumerKSeF3, TNaturalny3, TKluczWartosc3, TZnakowy503, TIlosci3, TKwotowy23, TProcentowy3, TStawkaPodatku3, TFormaPlatnosci3, TNrRB3, SWIFT_Type3, TRachunekBankowy3, TTekstowy3, TNrKRS3, TNrREGON3, RR1_V11ESchema;
5515
- var init_rr1_v11e = __esm({
5516
- "src/validation/schemas/rr1-v11e.ts"() {
5794
+ var TKodFormularza3, TDataCzas3, TZnakowy4, TNaglowek3, TNrNIP3, TZnakowy5123, TPodmiot13, TKodKraju3, TGLN3, TAdres3, TAdresEmail3, TNumerTelefonu3, TStatusInfoPodatnika3, TZnakowy203, TNIPIdWew3, TWybor13, TPodmiot33, TRolaPodmiotu33, TKodWaluty3, TData3, TDataT3, TKwotowy4, TRodzajFaktury3, TTypKorekty3, TNumerKSeF3, TNaturalny3, TKluczWartosc3, TZnakowy503, TIlosci3, TKwotowy23, TProcentowy3, TStawkaPodatku3, TFormaPlatnosci3, TNrRB3, SWIFT_Type3, TRachunekBankowy3, TTekstowy3, TNrKRS3, TNrREGON3, FA_RR1Schema;
5795
+ var init_fa_rr1 = __esm({
5796
+ "src/validation/schemas/fa-rr1.ts"() {
5517
5797
  "use strict";
5518
5798
  TKodFormularza3 = z3.literal("FA_RR");
5519
5799
  TDataCzas3 = z3.string();
@@ -5581,7 +5861,7 @@ var init_rr1_v11e = __esm({
5581
5861
  TTekstowy3 = z3.string().min(1).max(3500);
5582
5862
  TNrKRS3 = z3.string().regex(/^\d{10}$/);
5583
5863
  TNrREGON3 = z3.union([z3.string().regex(/^\d{9}$/), z3.string().regex(/^\d{14}$/)]);
5584
- RR1_V11ESchema = z3.object({
5864
+ FA_RR1Schema = z3.object({
5585
5865
  "Naglowek": TNaglowek3,
5586
5866
  "Podmiot1": z3.object({
5587
5867
  "DaneIdentyfikacyjne": TPodmiot13,
@@ -5710,222 +5990,87 @@ var init_rr1_v11e = __esm({
5710
5990
  }
5711
5991
  });
5712
5992
 
5713
- // src/validation/schemas/rr1-v10e.ts
5714
- var rr1_v10e_exports = {};
5715
- __export(rr1_v10e_exports, {
5716
- RR1_V10ESchema: () => RR1_V10ESchema
5993
+ // src/validation/schemas/pef3.ts
5994
+ var pef3_exports = {};
5995
+ __export(pef3_exports, {
5996
+ PEF3Schema: () => PEF3Schema
5717
5997
  });
5718
5998
  import { z as z4 } from "zod";
5719
- var TKodFormularza4, TDataCzas4, TZnakowy5, TNaglowek4, TNrNIP4, TZnakowy5124, TPodmiot14, TKodKraju4, TGLN4, TAdres4, TAdresEmail4, TNumerTelefonu4, TStatusInfoPodatnika4, TZnakowy204, TNIPIdWew4, TWybor14, TPodmiot34, TRolaPodmiotu34, TKodWaluty4, TData4, TDataT4, TKwotowy5, TRodzajFaktury4, TTypKorekty4, TNumerKSeF4, TNaturalny4, TKluczWartosc4, TZnakowy504, TIlosci4, TKwotowy24, TProcentowy4, TStawkaPodatku4, TFormaPlatnosci4, TNrRB4, SWIFT_Type4, TRachunekBankowy4, TTekstowy4, TNrKRS4, TNrREGON4, RR1_V10ESchema;
5720
- var init_rr1_v10e = __esm({
5721
- "src/validation/schemas/rr1-v10e.ts"() {
5999
+ var InvoiceType, PEF3Schema;
6000
+ var init_pef3 = __esm({
6001
+ "src/validation/schemas/pef3.ts"() {
5722
6002
  "use strict";
5723
- TKodFormularza4 = z4.literal("FA_RR");
5724
- TDataCzas4 = z4.string();
5725
- TZnakowy5 = z4.string().min(1).max(256);
5726
- TNaglowek4 = z4.object({
5727
- "KodFormularza": z4.object({ "#text": TKodFormularza4, "@kodSystemowy": z4.literal("FA_RR(1)"), "@wersjaSchemy": z4.literal("1-0E") }).strict(),
5728
- "WariantFormularza": z4.literal("1"),
5729
- "DataWytworzeniaFa": z4.string(),
5730
- "SystemInfo": TZnakowy5.optional()
5731
- }).strict();
5732
- TNrNIP4 = z4.string().regex(/^[1-9]((\d[1-9])|([1-9]\d))\d{7}$/);
5733
- TZnakowy5124 = z4.string().min(1).max(512);
5734
- TPodmiot14 = z4.object({
5735
- "NIP": TNrNIP4,
5736
- "Nazwa": TZnakowy5124
5737
- }).strict();
5738
- TKodKraju4 = z4.enum(["AF", "AX", "AL", "DZ", "AD", "AO", "AI", "AQ", "AG", "AN", "SA", "AR", "AM", "AW", "AU", "AT", "AZ", "BS", "BH", "BD", "BB", "BE", "BZ", "BJ", "BM", "BT", "BY", "BO", "BQ", "BA", "BW", "BR", "BN", "IO", "BG", "BF", "BI", "XC", "CL", "CN", "HR", "CW", "CY", "TD", "ME", "DK", "DM", "DO", "DJ", "EG", "EC", "ER", "EE", "ET", "FK", "FJ", "PH", "FI", "FR", "TF", "GA", "GM", "GH", "GI", "GR", "GD", "GL", "GE", "GU", "GG", "GY", "GF", "GP", "GT", "GN", "GQ", "GW", "HT", "ES", "HN", "HK", "IN", "ID", "IQ", "IR", "IE", "IS", "IL", "JM", "JP", "YE", "JE", "JO", "KY", "KH", "CM", "CA", "QA", "KZ", "KE", "KG", "KI", "CO", "KM", "CG", "CD", "KP", "XK", "CR", "CU", "KW", "LA", "LS", "LB", "LR", "LY", "LI", "LT", "LV", "LU", "MK", "MG", "YT", "MO", "MW", "MV", "MY", "ML", "MT", "MP", "MA", "MQ", "MR", "MU", "MX", "XL", "FM", "UM", "MD", "MC", "MN", "MS", "MZ", "MM", "NA", "NR", "NP", "NL", "DE", "NE", "NG", "NI", "NU", "NF", "NO", "NC", "NZ", "PS", "OM", "PK", "PW", "PA", "PG", "PY", "PE", "PN", "PF", "PL", "GS", "PT", "PR", "CF", "CZ", "KR", "ZA", "RE", "RU", "RO", "RW", "EH", "BL", "KN", "LC", "MF", "VC", "SV", "WS", "AS", "SM", "SN", "RS", "SC", "SL", "SG", "SK", "SI", "SO", "LK", "PM", "US", "SZ", "SD", "SS", "SR", "SJ", "SH", "SY", "CH", "SE", "TJ", "TH", "TW", "TZ", "TG", "TK", "TO", "TT", "TN", "TR", "TM", "TV", "UG", "UA", "UY", "UZ", "VU", "WF", "VA", "HU", "VE", "GB", "VN", "IT", "TL", "CI", "BV", "CX", "IM", "SX", "CK", "VI", "VG", "HM", "CC", "MH", "FO", "SB", "ST", "TC", "ZM", "CV", "ZW", "AE", "XI"]);
5739
- TGLN4 = z4.string().min(1).max(13);
5740
- TAdres4 = z4.object({
5741
- "KodKraju": TKodKraju4,
5742
- "AdresL1": TZnakowy5124,
5743
- "AdresL2": TZnakowy5124.optional(),
5744
- "GLN": TGLN4.optional()
5745
- }).strict();
5746
- TAdresEmail4 = z4.string().min(3).max(255).regex(/^(.)+@(.)+$/);
5747
- TNumerTelefonu4 = z4.string().min(1).max(16);
5748
- TStatusInfoPodatnika4 = z4.enum(["1", "2", "3", "4"]);
5749
- TZnakowy204 = z4.string().min(1).max(20);
5750
- TNIPIdWew4 = z4.string().min(1).max(20).regex(/^[1-9]((\d[1-9])|([1-9]\d))\d{7}-\d{5}$/);
5751
- TWybor14 = z4.literal("1");
5752
- TPodmiot34 = z4.object({
5753
- "NIP": TNrNIP4.optional(),
5754
- "IDWew": TNIPIdWew4.optional(),
5755
- "BrakID": TWybor14.optional(),
5756
- "Nazwa": TZnakowy5124
5757
- }).strict();
5758
- TRolaPodmiotu34 = z4.enum(["1", "2", "3", "5", "6", "7", "8", "9", "10", "11"]);
5759
- TKodWaluty4 = z4.enum(["AED", "AFN", "ALL", "AMD", "ANG", "AOA", "ARS", "AUD", "AWG", "AZN", "BAM", "BBD", "BDT", "BGN", "BHD", "BIF", "BMD", "BND", "BOB", "BOV", "BRL", "BSD", "BTN", "BWP", "BYN", "BZD", "CAD", "CDF", "CHE", "CHF", "CHW", "CLF", "CLP", "CNY", "COP", "COU", "CRC", "CUC", "CUP", "CVE", "CZK", "DJF", "DKK", "DOP", "DZD", "EGP", "ERN", "ETB", "EUR", "FJD", "FKP", "GBP", "GEL", "GGP", "GHS", "GIP", "GMD", "GNF", "GTQ", "GYD", "HKD", "HNL", "HRK", "HTG", "HUF", "IDR", "ILS", "IMP", "INR", "IQD", "IRR", "ISK", "JEP", "JMD", "JOD", "JPY", "KES", "KGS", "KHR", "KMF", "KPW", "KRW", "KWD", "KYD", "KZT", "LAK", "LBP", "LKR", "LRD", "LSL", "LYD", "MAD", "MDL", "MGA", "MKD", "MMK", "MNT", "MOP", "MRU", "MUR", "MVR", "MWK", "MXN", "MXV", "MYR", "MZN", "NAD", "NGN", "NIO", "NOK", "NPR", "NZD", "OMR", "PAB", "PEN", "PGK", "PHP", "PKR", "PLN", "PYG", "QAR", "RON", "RSD", "RUB", "RWF", "SAR", "SBD", "SCR", "SDG", "SEK", "SGD", "SHP", "SLL", "SOS", "SRD", "SSP", "STN", "SVC", "SYP", "SZL", "THB", "TJS", "TMT", "TND", "TOP", "TRY", "TTD", "TWD", "TZS", "UAH", "UGX", "USD", "USN", "UYI", "UYU", "UYW", "UZS", "VES", "VND", "VUV", "WST", "XAF", "XAG", "XAU", "XBA", "XBB", "XBC", "XBD", "XCD", "XCG", "XDR", "XOF", "XPD", "XPF", "XPT", "XSU", "XUA", "XXX", "YER", "ZAR", "ZMW", "ZWL"]);
5760
- TData4 = z4.string();
5761
- TDataT4 = z4.string();
5762
- TKwotowy5 = z4.string().regex(/^-?([1-9]\d{0,15}|0)(\.\d{1,2})?$/);
5763
- TRodzajFaktury4 = z4.enum(["VAT_RR", "KOR_VAT_RR"]);
5764
- TTypKorekty4 = z4.enum(["1", "2", "3", "4"]);
5765
- TNumerKSeF4 = z4.string().regex(/^([1-9]((\d[1-9])|([1-9]\d))\d{7}|M\d{9}|[A-Z]{3}\d{7})-(20[2-9][0-9]|2[1-9][0-9]{2}|[3-9][0-9]{3})(0[1-9]|1[0-2])(0[1-9]|[1-2][0-9]|3[0-1])-([0-9A-F]{6})-?([0-9A-F]{6})-([0-9A-F]{2})$/);
5766
- TNaturalny4 = z4.string();
5767
- TKluczWartosc4 = z4.object({
5768
- "NrWiersza": TNaturalny4.optional(),
5769
- "Klucz": TZnakowy5,
5770
- "Wartosc": TZnakowy5
5771
- }).strict();
5772
- TZnakowy504 = z4.string().min(1).max(50);
5773
- TIlosci4 = z4.string().regex(/^-?([1-9]\d{0,15}|0)(\.\d{1,6})?$/);
5774
- TKwotowy24 = z4.string().regex(/^-?([1-9]\d{0,13}|0)(\.\d{1,8})?$/);
5775
- TProcentowy4 = z4.coerce.number().min(0).max(100);
5776
- TStawkaPodatku4 = z4.enum(["6.5", "7"]);
5777
- TFormaPlatnosci4 = z4.literal("1");
5778
- TNrRB4 = z4.string().min(10).max(34);
5779
- SWIFT_Type4 = z4.string().regex(/^[A-Z]{6}[A-Z0-9]{2}([A-Z0-9]{3}){0,1}$/);
5780
- TRachunekBankowy4 = z4.object({
5781
- "NrRB": TNrRB4,
5782
- "SWIFT": SWIFT_Type4.optional(),
5783
- "NazwaBanku": TZnakowy5.optional(),
5784
- "OpisRachunku": TZnakowy5.optional()
5785
- }).strict();
5786
- TTekstowy4 = z4.string().min(1).max(3500);
5787
- TNrKRS4 = z4.string().regex(/^\d{10}$/);
5788
- TNrREGON4 = z4.union([z4.string().regex(/^\d{9}$/), z4.string().regex(/^\d{14}$/)]);
5789
- RR1_V10ESchema = z4.object({
5790
- "Naglowek": TNaglowek4,
5791
- "Podmiot1": z4.object({
5792
- "DaneIdentyfikacyjne": TPodmiot14,
5793
- "Adres": TAdres4,
5794
- "AdresKoresp": TAdres4.optional(),
5795
- "DaneKontaktowe": z4.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z4.array(z4.object({
5796
- "Email": TAdresEmail4.optional(),
5797
- "Telefon": TNumerTelefonu4.optional()
5798
- }).strict()).min(0).max(3)).optional(),
5799
- "NrKontrahenta": TZnakowy5.optional()
5800
- }).strict(),
5801
- "Podmiot2": z4.object({
5802
- "DaneIdentyfikacyjne": TPodmiot14,
5803
- "Adres": TAdres4,
5804
- "AdresKoresp": TAdres4.optional(),
5805
- "DaneKontaktowe": z4.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z4.array(z4.object({
5806
- "Email": TAdresEmail4.optional(),
5807
- "Telefon": TNumerTelefonu4.optional()
5808
- }).strict()).min(0).max(3)).optional(),
5809
- "StatusInfoPodatnika": TStatusInfoPodatnika4.optional()
5810
- }).strict(),
5811
- "Podmiot3": z4.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z4.array(z4.object({
5812
- "DaneIdentyfikacyjne": TPodmiot34,
5813
- "Adres": TAdres4.optional(),
5814
- "AdresKoresp": TAdres4.optional(),
5815
- "DaneKontaktowe": z4.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z4.array(z4.object({
5816
- "Email": TAdresEmail4.optional(),
5817
- "Telefon": TNumerTelefonu4.optional()
5818
- }).strict()).min(0).max(3)).optional(),
5819
- "Rola": TRolaPodmiotu34.optional(),
5820
- "RolaInna": TWybor14.optional(),
5821
- "OpisRoli": TZnakowy5.optional()
5822
- }).strict()).min(0).max(100)).optional(),
5823
- "FakturaRR": z4.object({
5824
- "KodWaluty": TKodWaluty4,
5825
- "P_1M": TZnakowy5.optional(),
5826
- "P_4A": TDataT4.optional(),
5827
- "P_4B": TDataT4,
5828
- "P_4C": TZnakowy5,
5829
- "P_11_1": TKwotowy5,
5830
- "P_11_1W": TKwotowy5.optional(),
5831
- "P_11_2": TKwotowy5,
5832
- "P_11_2W": TKwotowy5.optional(),
5833
- "P_12_1": TKwotowy5,
5834
- "P_12_1W": TKwotowy5.optional(),
5835
- "P_12_2": TZnakowy5,
5836
- "RodzajFaktury": TRodzajFaktury4,
5837
- "PrzyczynaKorekty": TZnakowy5.optional(),
5838
- "TypKorekty": TTypKorekty4.optional(),
5839
- "DaneFaKorygowanej": z4.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z4.array(z4.object({
5840
- "DataWystFaKorygowanej": TDataT4,
5841
- "NrFaKorygowanej": TZnakowy5,
5842
- "NrKSeF": TWybor14.optional(),
5843
- "NrKSeFFaKorygowanej": TNumerKSeF4.optional(),
5844
- "NrKSeFN": TWybor14.optional()
5845
- }).strict()).min(1).max(5e4)).optional(),
5846
- "NrFaKorygowany": TZnakowy5.optional(),
5847
- "Podmiot1K": z4.object({
5848
- "DaneIdentyfikacyjne": TPodmiot14,
5849
- "Adres": TAdres4
5850
- }).strict().optional(),
5851
- "Podmiot2K": z4.object({
5852
- "DaneIdentyfikacyjne": TPodmiot14,
5853
- "Adres": TAdres4
5854
- }).strict().optional(),
5855
- "DokumentZaplaty": z4.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z4.array(z4.object({
5856
- "NrDokumentu": TZnakowy5,
5857
- "DataDokumentu": TData4.optional()
5858
- }).strict()).min(0).max(50)).optional(),
5859
- "DodatkowyOpis": z4.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z4.array(TKluczWartosc4).min(0).max(1e4)).optional(),
5860
- "FakturaRRWiersz": z4.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z4.array(z4.object({
5861
- "NrWierszaFa": TNaturalny4,
5862
- "UU_ID": TZnakowy504.optional(),
5863
- "P_4AA": TDataT4.optional(),
5864
- "P_5": TZnakowy5,
5865
- "GTIN": TZnakowy204.optional(),
5866
- "PKWiU": TZnakowy504.optional(),
5867
- "CN": TZnakowy504.optional(),
5868
- "P_6A": TZnakowy5,
5869
- "P_6B": TIlosci4,
5870
- "P_6C": TZnakowy5,
5871
- "P_7": TKwotowy24,
5872
- "P_8": TKwotowy5,
5873
- "P_9": TStawkaPodatku4,
5874
- "P_10": TKwotowy5,
5875
- "P_11": TKwotowy5,
5876
- "StanPrzed": TWybor14.optional(),
5877
- "KursWaluty": TIlosci4.optional()
5878
- }).strict()).min(0).max(1e4)).optional(),
5879
- "Rozliczenie": z4.object({
5880
- "Obciazenia": z4.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z4.array(z4.object({
5881
- "Kwota": TKwotowy5,
5882
- "Powod": TZnakowy5
5883
- }).strict()).min(0).max(100)).optional(),
5884
- "SumaObciazen": TKwotowy5.optional(),
5885
- "Odliczenia": z4.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z4.array(z4.object({
5886
- "Kwota": TKwotowy5,
5887
- "Powod": TZnakowy5
5888
- }).strict()).min(0).max(100)).optional(),
5889
- "SumaOdliczen": TKwotowy5.optional(),
5890
- "DoZaplaty": TKwotowy5.optional(),
5891
- "DoRozliczenia": TKwotowy5.optional()
5892
- }).strict().optional(),
5893
- "Platnosc": z4.object({
5894
- "FormaPlatnosci": TFormaPlatnosci4.optional(),
5895
- "PlatnoscInna": TWybor14.optional(),
5896
- "OpisPlatnosci": TZnakowy5.optional(),
5897
- "RachunekBankowy1": z4.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z4.array(TRachunekBankowy4).min(0).max(3)).optional(),
5898
- "RachunekBankowy2": z4.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z4.array(TRachunekBankowy4).min(0).max(3)).optional(),
5899
- "IPKSeF": z4.string().min(1).max(13).regex(/^[0-9]{3}[a-zA-Z0-9]{10}$/).optional(),
5900
- "LinkDoPlatnosci": z4.string().min(1).max(512).regex(/^(https?):\/\/([a-zA-Z0-9][a-zA-Z0-9-]*\.)+[a-zA-Z]{2,}(:[0-9]{1,5})?(\/[^\s?#]*)?\?([^#\s]*&)?IPKSeF=[0-9]{3}[a-zA-Z0-9]{10}(&[^#\s]*)?(#.*)?$/).optional()
5901
- }).strict().optional()
5902
- }).strict(),
5903
- "Stopka": z4.object({
5904
- "Informacje": z4.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z4.array(z4.object({
5905
- "StopkaFaktury": TTekstowy4.optional()
5906
- }).strict()).min(0).max(3)).optional(),
5907
- "Rejestry": z4.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z4.array(z4.object({
5908
- "PelnaNazwa": TZnakowy5.optional(),
5909
- "KRS": TNrKRS4.optional(),
5910
- "REGON": TNrREGON4.optional(),
5911
- "BDO": z4.string().min(1).max(9).optional()
5912
- }).strict()).min(0).max(100)).optional()
5913
- }).strict().optional()
6003
+ InvoiceType = z4.object({
6004
+ "UBLExtensions": z4.any().optional(),
6005
+ "UBLVersionID": z4.any().optional(),
6006
+ "CustomizationID": z4.any().optional(),
6007
+ "ProfileID": z4.any().optional(),
6008
+ "ProfileExecutionID": z4.any().optional(),
6009
+ "ID": z4.any(),
6010
+ "CopyIndicator": z4.any().optional(),
6011
+ "UUID": z4.any().optional(),
6012
+ "IssueDate": z4.any(),
6013
+ "IssueTime": z4.any().optional(),
6014
+ "DueDate": z4.any().optional(),
6015
+ "InvoiceTypeCode": z4.any().optional(),
6016
+ "Note": z4.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z4.array(z4.any()).min(0)).optional(),
6017
+ "TaxPointDate": z4.any().optional(),
6018
+ "DocumentCurrencyCode": z4.any().optional(),
6019
+ "TaxCurrencyCode": z4.any().optional(),
6020
+ "PricingCurrencyCode": z4.any().optional(),
6021
+ "PaymentCurrencyCode": z4.any().optional(),
6022
+ "PaymentAlternativeCurrencyCode": z4.any().optional(),
6023
+ "AccountingCostCode": z4.any().optional(),
6024
+ "AccountingCost": z4.any().optional(),
6025
+ "LineCountNumeric": z4.any().optional(),
6026
+ "BuyerReference": z4.any().optional(),
6027
+ "InvoicePeriod": z4.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z4.array(z4.any()).min(0)).optional(),
6028
+ "OrderReference": z4.any().optional(),
6029
+ "BillingReference": z4.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z4.array(z4.any()).min(0)).optional(),
6030
+ "DespatchDocumentReference": z4.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z4.array(z4.any()).min(0)).optional(),
6031
+ "ReceiptDocumentReference": z4.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z4.array(z4.any()).min(0)).optional(),
6032
+ "StatementDocumentReference": z4.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z4.array(z4.any()).min(0)).optional(),
6033
+ "OriginatorDocumentReference": z4.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z4.array(z4.any()).min(0)).optional(),
6034
+ "ContractDocumentReference": z4.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z4.array(z4.any()).min(0)).optional(),
6035
+ "AdditionalDocumentReference": z4.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z4.array(z4.any()).min(0)).optional(),
6036
+ "ProjectReference": z4.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z4.array(z4.any()).min(0)).optional(),
6037
+ "Signature": z4.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z4.array(z4.any()).min(0)).optional(),
6038
+ "AccountingSupplierParty": z4.any(),
6039
+ "AccountingCustomerParty": z4.any(),
6040
+ "PayeeParty": z4.any().optional(),
6041
+ "BuyerCustomerParty": z4.any().optional(),
6042
+ "SellerSupplierParty": z4.any().optional(),
6043
+ "TaxRepresentativeParty": z4.any().optional(),
6044
+ "Delivery": z4.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z4.array(z4.any()).min(0)).optional(),
6045
+ "DeliveryTerms": z4.any().optional(),
6046
+ "PaymentMeans": z4.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z4.array(z4.any()).min(0)).optional(),
6047
+ "PaymentTerms": z4.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z4.array(z4.any()).min(0)).optional(),
6048
+ "PrepaidPayment": z4.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z4.array(z4.any()).min(0)).optional(),
6049
+ "AllowanceCharge": z4.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z4.array(z4.any()).min(0)).optional(),
6050
+ "TaxExchangeRate": z4.any().optional(),
6051
+ "PricingExchangeRate": z4.any().optional(),
6052
+ "PaymentExchangeRate": z4.any().optional(),
6053
+ "PaymentAlternativeExchangeRate": z4.any().optional(),
6054
+ "TaxTotal": z4.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z4.array(z4.any()).min(0)).optional(),
6055
+ "WithholdingTaxTotal": z4.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z4.array(z4.any()).min(0)).optional(),
6056
+ "LegalMonetaryTotal": z4.any(),
6057
+ "InvoiceLine": z4.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z4.array(z4.any()).min(1))
5914
6058
  }).strict();
6059
+ PEF3Schema = InvoiceType;
5915
6060
  }
5916
6061
  });
5917
6062
 
5918
- // src/validation/schemas/pef3.ts
5919
- var pef3_exports = {};
5920
- __export(pef3_exports, {
5921
- PEF3Schema: () => PEF3Schema
6063
+ // src/validation/schemas/pef-kor3.ts
6064
+ var pef_kor3_exports = {};
6065
+ __export(pef_kor3_exports, {
6066
+ PEF_KOR3Schema: () => PEF_KOR3Schema
5922
6067
  });
5923
6068
  import { z as z5 } from "zod";
5924
- var InvoiceType, PEF3Schema;
5925
- var init_pef3 = __esm({
5926
- "src/validation/schemas/pef3.ts"() {
6069
+ var CreditNoteType, PEF_KOR3Schema;
6070
+ var init_pef_kor3 = __esm({
6071
+ "src/validation/schemas/pef-kor3.ts"() {
5927
6072
  "use strict";
5928
- InvoiceType = z5.object({
6073
+ CreditNoteType = z5.object({
5929
6074
  "UBLExtensions": z5.any().optional(),
5930
6075
  "UBLVersionID": z5.any().optional(),
5931
6076
  "CustomizationID": z5.any().optional(),
@@ -5936,10 +6081,9 @@ var init_pef3 = __esm({
5936
6081
  "UUID": z5.any().optional(),
5937
6082
  "IssueDate": z5.any(),
5938
6083
  "IssueTime": z5.any().optional(),
5939
- "DueDate": z5.any().optional(),
5940
- "InvoiceTypeCode": z5.any().optional(),
5941
- "Note": z5.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z5.array(z5.any()).min(0)).optional(),
5942
6084
  "TaxPointDate": z5.any().optional(),
6085
+ "CreditNoteTypeCode": z5.any().optional(),
6086
+ "Note": z5.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z5.array(z5.any()).min(0)).optional(),
5943
6087
  "DocumentCurrencyCode": z5.any().optional(),
5944
6088
  "TaxCurrencyCode": z5.any().optional(),
5945
6089
  "PricingCurrencyCode": z5.any().optional(),
@@ -5950,15 +6094,15 @@ var init_pef3 = __esm({
5950
6094
  "LineCountNumeric": z5.any().optional(),
5951
6095
  "BuyerReference": z5.any().optional(),
5952
6096
  "InvoicePeriod": z5.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z5.array(z5.any()).min(0)).optional(),
6097
+ "DiscrepancyResponse": z5.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z5.array(z5.any()).min(0)).optional(),
5953
6098
  "OrderReference": z5.any().optional(),
5954
6099
  "BillingReference": z5.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z5.array(z5.any()).min(0)).optional(),
5955
6100
  "DespatchDocumentReference": z5.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z5.array(z5.any()).min(0)).optional(),
5956
6101
  "ReceiptDocumentReference": z5.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z5.array(z5.any()).min(0)).optional(),
5957
- "StatementDocumentReference": z5.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z5.array(z5.any()).min(0)).optional(),
5958
- "OriginatorDocumentReference": z5.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z5.array(z5.any()).min(0)).optional(),
5959
6102
  "ContractDocumentReference": z5.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z5.array(z5.any()).min(0)).optional(),
5960
6103
  "AdditionalDocumentReference": z5.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z5.array(z5.any()).min(0)).optional(),
5961
- "ProjectReference": z5.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z5.array(z5.any()).min(0)).optional(),
6104
+ "StatementDocumentReference": z5.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z5.array(z5.any()).min(0)).optional(),
6105
+ "OriginatorDocumentReference": z5.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z5.array(z5.any()).min(0)).optional(),
5962
6106
  "Signature": z5.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z5.array(z5.any()).min(0)).optional(),
5963
6107
  "AccountingSupplierParty": z5.any(),
5964
6108
  "AccountingCustomerParty": z5.any(),
@@ -5967,86 +6111,17 @@ var init_pef3 = __esm({
5967
6111
  "SellerSupplierParty": z5.any().optional(),
5968
6112
  "TaxRepresentativeParty": z5.any().optional(),
5969
6113
  "Delivery": z5.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z5.array(z5.any()).min(0)).optional(),
5970
- "DeliveryTerms": z5.any().optional(),
6114
+ "DeliveryTerms": z5.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z5.array(z5.any()).min(0)).optional(),
5971
6115
  "PaymentMeans": z5.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z5.array(z5.any()).min(0)).optional(),
5972
6116
  "PaymentTerms": z5.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z5.array(z5.any()).min(0)).optional(),
5973
- "PrepaidPayment": z5.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z5.array(z5.any()).min(0)).optional(),
5974
- "AllowanceCharge": z5.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z5.array(z5.any()).min(0)).optional(),
5975
6117
  "TaxExchangeRate": z5.any().optional(),
5976
6118
  "PricingExchangeRate": z5.any().optional(),
5977
6119
  "PaymentExchangeRate": z5.any().optional(),
5978
6120
  "PaymentAlternativeExchangeRate": z5.any().optional(),
6121
+ "AllowanceCharge": z5.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z5.array(z5.any()).min(0)).optional(),
5979
6122
  "TaxTotal": z5.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z5.array(z5.any()).min(0)).optional(),
5980
- "WithholdingTaxTotal": z5.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z5.array(z5.any()).min(0)).optional(),
5981
6123
  "LegalMonetaryTotal": z5.any(),
5982
- "InvoiceLine": z5.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z5.array(z5.any()).min(1))
5983
- }).strict();
5984
- PEF3Schema = InvoiceType;
5985
- }
5986
- });
5987
-
5988
- // src/validation/schemas/pef-kor3.ts
5989
- var pef_kor3_exports = {};
5990
- __export(pef_kor3_exports, {
5991
- PEF_KOR3Schema: () => PEF_KOR3Schema
5992
- });
5993
- import { z as z6 } from "zod";
5994
- var CreditNoteType, PEF_KOR3Schema;
5995
- var init_pef_kor3 = __esm({
5996
- "src/validation/schemas/pef-kor3.ts"() {
5997
- "use strict";
5998
- CreditNoteType = z6.object({
5999
- "UBLExtensions": z6.any().optional(),
6000
- "UBLVersionID": z6.any().optional(),
6001
- "CustomizationID": z6.any().optional(),
6002
- "ProfileID": z6.any().optional(),
6003
- "ProfileExecutionID": z6.any().optional(),
6004
- "ID": z6.any(),
6005
- "CopyIndicator": z6.any().optional(),
6006
- "UUID": z6.any().optional(),
6007
- "IssueDate": z6.any(),
6008
- "IssueTime": z6.any().optional(),
6009
- "TaxPointDate": z6.any().optional(),
6010
- "CreditNoteTypeCode": z6.any().optional(),
6011
- "Note": z6.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z6.array(z6.any()).min(0)).optional(),
6012
- "DocumentCurrencyCode": z6.any().optional(),
6013
- "TaxCurrencyCode": z6.any().optional(),
6014
- "PricingCurrencyCode": z6.any().optional(),
6015
- "PaymentCurrencyCode": z6.any().optional(),
6016
- "PaymentAlternativeCurrencyCode": z6.any().optional(),
6017
- "AccountingCostCode": z6.any().optional(),
6018
- "AccountingCost": z6.any().optional(),
6019
- "LineCountNumeric": z6.any().optional(),
6020
- "BuyerReference": z6.any().optional(),
6021
- "InvoicePeriod": z6.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z6.array(z6.any()).min(0)).optional(),
6022
- "DiscrepancyResponse": z6.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z6.array(z6.any()).min(0)).optional(),
6023
- "OrderReference": z6.any().optional(),
6024
- "BillingReference": z6.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z6.array(z6.any()).min(0)).optional(),
6025
- "DespatchDocumentReference": z6.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z6.array(z6.any()).min(0)).optional(),
6026
- "ReceiptDocumentReference": z6.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z6.array(z6.any()).min(0)).optional(),
6027
- "ContractDocumentReference": z6.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z6.array(z6.any()).min(0)).optional(),
6028
- "AdditionalDocumentReference": z6.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z6.array(z6.any()).min(0)).optional(),
6029
- "StatementDocumentReference": z6.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z6.array(z6.any()).min(0)).optional(),
6030
- "OriginatorDocumentReference": z6.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z6.array(z6.any()).min(0)).optional(),
6031
- "Signature": z6.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z6.array(z6.any()).min(0)).optional(),
6032
- "AccountingSupplierParty": z6.any(),
6033
- "AccountingCustomerParty": z6.any(),
6034
- "PayeeParty": z6.any().optional(),
6035
- "BuyerCustomerParty": z6.any().optional(),
6036
- "SellerSupplierParty": z6.any().optional(),
6037
- "TaxRepresentativeParty": z6.any().optional(),
6038
- "Delivery": z6.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z6.array(z6.any()).min(0)).optional(),
6039
- "DeliveryTerms": z6.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z6.array(z6.any()).min(0)).optional(),
6040
- "PaymentMeans": z6.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z6.array(z6.any()).min(0)).optional(),
6041
- "PaymentTerms": z6.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z6.array(z6.any()).min(0)).optional(),
6042
- "TaxExchangeRate": z6.any().optional(),
6043
- "PricingExchangeRate": z6.any().optional(),
6044
- "PaymentExchangeRate": z6.any().optional(),
6045
- "PaymentAlternativeExchangeRate": z6.any().optional(),
6046
- "AllowanceCharge": z6.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z6.array(z6.any()).min(0)).optional(),
6047
- "TaxTotal": z6.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z6.array(z6.any()).min(0)).optional(),
6048
- "LegalMonetaryTotal": z6.any(),
6049
- "CreditNoteLine": z6.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z6.array(z6.any()).min(1))
6124
+ "CreditNoteLine": z5.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z5.array(z5.any()).min(1))
6050
6125
  }).strict();
6051
6126
  PEF_KOR3Schema = CreditNoteType;
6052
6127
  }
@@ -6059,16 +6134,14 @@ var init_schemas = __esm({
6059
6134
  "use strict";
6060
6135
  init_fa3();
6061
6136
  init_fa2();
6062
- init_rr1_v11e();
6063
- init_rr1_v10e();
6137
+ init_fa_rr1();
6064
6138
  init_pef3();
6065
6139
  init_pef_kor3();
6066
- SCHEMA_TYPES = ["FA3", "FA2", "RR1_V11E", "RR1_V10E", "PEF3", "PEF_KOR3"];
6140
+ SCHEMA_TYPES = ["FA3", "FA2", "FA_RR1", "PEF3", "PEF_KOR3"];
6067
6141
  NAMESPACE_MAP = {
6068
6142
  "http://crd.gov.pl/wzor/2025/06/25/13775/": "FA3",
6069
6143
  "http://crd.gov.pl/wzor/2023/06/29/12648/": "FA2",
6070
- "http://crd.gov.pl/wzor/2026/03/06/14189/": "RR1_V11E",
6071
- "http://crd.gov.pl/wzor/2026/02/17/14164/": "RR1_V10E",
6144
+ "http://crd.gov.pl/wzor/2026/03/06/14189/": "FA_RR1",
6072
6145
  "urn:oasis:names:specification:ubl:schema:xsd:Invoice-2": "PEF3",
6073
6146
  "urn:oasis:names:specification:ubl:schema:xsd:CreditNote-2": "PEF_KOR3"
6074
6147
  };
@@ -6087,11 +6160,8 @@ async function loadSchema(type) {
6087
6160
  case "FA2":
6088
6161
  mod = await Promise.resolve().then(() => (init_fa2(), fa2_exports));
6089
6162
  break;
6090
- case "RR1_V11E":
6091
- mod = await Promise.resolve().then(() => (init_rr1_v11e(), rr1_v11e_exports));
6092
- break;
6093
- case "RR1_V10E":
6094
- mod = await Promise.resolve().then(() => (init_rr1_v10e(), rr1_v10e_exports));
6163
+ case "FA_RR1":
6164
+ mod = await Promise.resolve().then(() => (init_fa_rr1(), fa_rr1_exports));
6095
6165
  break;
6096
6166
  case "PEF3":
6097
6167
  mod = await Promise.resolve().then(() => (init_pef3(), pef3_exports));
@@ -6131,7 +6201,7 @@ var init_schema_registry = __esm({
6131
6201
  * List all available schema types.
6132
6202
  */
6133
6203
  availableSchemas() {
6134
- return ["FA3", "FA2", "RR1_V11E", "RR1_V10E", "PEF3", "PEF_KOR3"];
6204
+ return ["FA3", "FA2", "FA_RR1", "PEF3", "PEF_KOR3"];
6135
6205
  },
6136
6206
  /**
6137
6207
  * Detect schema type from XML namespace URI and/or root element name.
@@ -6552,6 +6622,7 @@ var init_batch_file = __esm({
6552
6622
  batchFile: {
6553
6623
  fileSize: zipBytes.length,
6554
6624
  fileHash: zipHash,
6625
+ ...options?.compressionType && { compressionType: options.compressionType },
6555
6626
  fileParts
6556
6627
  },
6557
6628
  encryptedParts
@@ -6654,6 +6725,7 @@ var init_batch_file = __esm({
6654
6725
  batchFile: {
6655
6726
  fileSize: zipSize,
6656
6727
  fileHash: zipMeta.hashSHA,
6728
+ ...options?.compressionType && { compressionType: options.compressionType },
6657
6729
  fileParts
6658
6730
  },
6659
6731
  streamParts
@@ -6677,11 +6749,10 @@ async function uploadBatch(client, zipData, options) {
6677
6749
  }
6678
6750
  await client.crypto.init();
6679
6751
  if (options?.validate) {
6680
- const { unzip: unzip2 } = await Promise.resolve().then(() => (init_zip(), zip_exports));
6681
6752
  const { validateBatch: validateBatch2, batchValidationDetails: batchValidationDetails2 } = await Promise.resolve().then(() => (init_invoice_validator(), invoice_validator_exports));
6682
6753
  const { KSeFValidationError: KSeFValidationError2 } = await Promise.resolve().then(() => (init_ksef_validation_error(), ksef_validation_error_exports));
6683
6754
  const zipBuf = Buffer.isBuffer(zipData) ? zipData : Buffer.from(zipData.buffer, zipData.byteOffset, zipData.byteLength);
6684
- const files = await unzip2(zipBuf);
6755
+ const files = options?.compressionType === "TarGz" ? await (await Promise.resolve().then(() => (init_targz(), targz_exports))).extractTarGz(zipBuf) : await (await Promise.resolve().then(() => (init_zip(), zip_exports))).unzip(zipBuf);
6685
6756
  const invoices2 = [...files.entries()].filter(([name]) => name.endsWith(".xml")).map(([name, data]) => ({ fileName: name, xml: data.toString("utf-8") }));
6686
6757
  if (invoices2.length > 0) {
6687
6758
  const result2 = await validateBatch2(invoices2);
@@ -6694,21 +6765,25 @@ async function uploadBatch(client, zipData, options) {
6694
6765
  }
6695
6766
  }
6696
6767
  }
6697
- const encData = await client.crypto.getEncryptionData();
6698
6768
  const formCode = options?.formCode ?? DEFAULT_FORM_CODE;
6699
- const encryptFn = (part) => client.crypto.encryptAES256(part, encData.cipherKey, encData.cipherIv);
6700
- const { batchFile, encryptedParts } = BatchFileBuilder.build(zipData, encryptFn, {
6701
- maxPartSize: options?.maxPartSize
6769
+ const { batchFile, encryptedParts, openResp } = await withKeyRotationRetry(client.crypto, async () => {
6770
+ const encData = await client.crypto.getEncryptionData();
6771
+ const encryptFn = (part) => client.crypto.encryptAES256(part, encData.cipherKey, encData.cipherIv);
6772
+ const { batchFile: batchFile2, encryptedParts: encryptedParts2 } = BatchFileBuilder.build(zipData, encryptFn, {
6773
+ maxPartSize: options?.maxPartSize,
6774
+ compressionType: options?.compressionType
6775
+ });
6776
+ const openResp2 = await client.batchSession.openSession(
6777
+ {
6778
+ formCode,
6779
+ encryption: encData.encryptionInfo,
6780
+ batchFile: batchFile2,
6781
+ offlineMode: options?.offlineMode
6782
+ },
6783
+ options?.upoVersion
6784
+ );
6785
+ return { batchFile: batchFile2, encryptedParts: encryptedParts2, openResp: openResp2 };
6702
6786
  });
6703
- const openResp = await client.batchSession.openSession(
6704
- {
6705
- formCode,
6706
- encryption: encData.encryptionInfo,
6707
- batchFile,
6708
- offlineMode: options?.offlineMode
6709
- },
6710
- options?.upoVersion
6711
- );
6712
6787
  const sendingParts = encryptedParts.map((part, i) => ({
6713
6788
  data: part.buffer.slice(part.byteOffset, part.byteOffset + part.byteLength),
6714
6789
  metadata: {
@@ -6742,26 +6817,29 @@ async function uploadBatchStream(client, zipStreamFactory, zipSize, options) {
6742
6817
  throw new Error("parallelism must be a positive integer");
6743
6818
  }
6744
6819
  await client.crypto.init();
6745
- const encData = await client.crypto.getEncryptionData();
6746
6820
  const formCode = options?.formCode ?? DEFAULT_FORM_CODE;
6747
- const encryptStreamFn = (stream) => client.crypto.encryptAES256Stream(stream, encData.cipherKey, encData.cipherIv);
6748
- const hashStreamFn = (stream) => client.crypto.getFileMetadataFromStream(stream);
6749
- const { batchFile, streamParts } = await BatchFileBuilder.buildFromStream(
6750
- zipStreamFactory,
6751
- zipSize,
6752
- encryptStreamFn,
6753
- hashStreamFn,
6754
- { maxPartSize: options?.maxPartSize }
6755
- );
6756
- const openResp = await client.batchSession.openSession(
6757
- {
6758
- formCode,
6759
- encryption: encData.encryptionInfo,
6760
- batchFile,
6761
- offlineMode: options?.offlineMode
6762
- },
6763
- options?.upoVersion
6764
- );
6821
+ const { streamParts, openResp } = await withKeyRotationRetry(client.crypto, async () => {
6822
+ const encData = await client.crypto.getEncryptionData();
6823
+ const encryptStreamFn = (stream) => client.crypto.encryptAES256Stream(stream, encData.cipherKey, encData.cipherIv);
6824
+ const hashStreamFn = (stream) => client.crypto.getFileMetadataFromStream(stream);
6825
+ const { batchFile, streamParts: streamParts2 } = await BatchFileBuilder.buildFromStream(
6826
+ zipStreamFactory,
6827
+ zipSize,
6828
+ encryptStreamFn,
6829
+ hashStreamFn,
6830
+ { maxPartSize: options?.maxPartSize, compressionType: options?.compressionType }
6831
+ );
6832
+ const openResp2 = await client.batchSession.openSession(
6833
+ {
6834
+ formCode,
6835
+ encryption: encData.encryptionInfo,
6836
+ batchFile,
6837
+ offlineMode: options?.offlineMode
6838
+ },
6839
+ options?.upoVersion
6840
+ );
6841
+ return { streamParts: streamParts2, openResp: openResp2 };
6842
+ });
6765
6843
  await client.batchSession.sendPartsWithStream(openResp, streamParts, options?.parallelism);
6766
6844
  await client.batchSession.closeSession(openResp.referenceNumber);
6767
6845
  const result = await pollUntil(
@@ -6812,6 +6890,7 @@ var init_batch_session_workflow = __esm({
6812
6890
  init_document_structures();
6813
6891
  init_batch_file();
6814
6892
  init_polling();
6893
+ init_with_key_rotation_retry();
6815
6894
  init_xml();
6816
6895
  }
6817
6896
  });
@@ -7208,15 +7287,19 @@ function clearCredentials() {
7208
7287
  // src/workflows/auth-workflow.ts
7209
7288
  init_polling();
7210
7289
  init_auth_xml_builder();
7290
+ init_with_key_rotation_retry();
7211
7291
  async function authenticateWithToken(client, options) {
7212
7292
  const challenge2 = await client.auth.getChallenge();
7213
7293
  await client.crypto.init();
7214
- const encryptedToken = await client.crypto.encryptKsefToken(options.token, challenge2.timestamp);
7215
- const submitResult = await client.auth.submitKsefTokenAuthRequest({
7216
- challenge: challenge2.challenge,
7217
- contextIdentifier: { type: "Nip", value: options.nip },
7218
- encryptedToken: Buffer.from(encryptedToken).toString("base64"),
7219
- authorizationPolicy: options.authorizationPolicy
7294
+ const submitResult = await withKeyRotationRetry(client.crypto, async () => {
7295
+ const { encryptedToken, publicKeyId } = await client.crypto.encryptKsefTokenWithKeyId(options.token, challenge2.timestamp);
7296
+ return client.auth.submitKsefTokenAuthRequest({
7297
+ challenge: challenge2.challenge,
7298
+ contextIdentifier: { type: "Nip", value: options.nip },
7299
+ encryptedToken: Buffer.from(encryptedToken).toString("base64"),
7300
+ publicKeyId,
7301
+ authorizationPolicy: options.authorizationPolicy
7302
+ });
7220
7303
  });
7221
7304
  const authToken = submitResult.authenticationToken.token;
7222
7305
  await pollUntil(
@@ -7765,6 +7848,7 @@ import { defineCommand as defineCommand3 } from "citty";
7765
7848
  import { consola as consola8 } from "consola";
7766
7849
  init_document_structures();
7767
7850
  init_xml();
7851
+ init_with_key_rotation_retry();
7768
7852
  function getGlobalOpts2(args) {
7769
7853
  return {
7770
7854
  env: args.env,
@@ -7795,7 +7879,6 @@ var open = defineCommand3({
7795
7879
  throw new Error("NIP is required. Provide --nip or set it via `ksef config set --nip <nip>`.");
7796
7880
  }
7797
7881
  await client.crypto.init();
7798
- const encryptionData = await client.crypto.getEncryptionData();
7799
7882
  const formCodeKey = args.formCode;
7800
7883
  let formCode = DEFAULT_FORM_CODE;
7801
7884
  if (formCodeKey) {
@@ -7809,9 +7892,13 @@ var open = defineCommand3({
7809
7892
  throw new Error("Batch session open is used internally by `ksef invoice send <dir>`. Use `ksef session open` for online sessions.");
7810
7893
  }
7811
7894
  if (!args.json) consola8.start("Opening online session...");
7812
- const result = await client.onlineSession.openSession(
7813
- { formCode, encryption: encryptionData.encryptionInfo }
7814
- );
7895
+ const { encryptionData, result } = await withKeyRotationRetry(client.crypto, async () => {
7896
+ const encryptionData2 = await client.crypto.getEncryptionData();
7897
+ const result2 = await client.onlineSession.openSession(
7898
+ { formCode, encryption: encryptionData2.encryptionInfo }
7899
+ );
7900
+ return { encryptionData: encryptionData2, result: result2 };
7901
+ });
7815
7902
  saveOnlineSessionRef(result.referenceNumber, {
7816
7903
  cipherKey: Buffer.from(encryptionData.cipherKey).toString("base64"),
7817
7904
  cipherIv: Buffer.from(encryptionData.cipherIv).toString("base64")
@@ -8217,7 +8304,7 @@ var sessionCommand = defineCommand3({
8217
8304
  // src/cli/commands/invoice.ts
8218
8305
  import * as fs11 from "node:fs";
8219
8306
  import * as path8 from "node:path";
8220
- import { Readable } from "node:stream";
8307
+ import { Readable as Readable2 } from "node:stream";
8221
8308
  import { defineCommand as defineCommand6 } from "citty";
8222
8309
  import { consola as consola11 } from "consola";
8223
8310
  init_document_structures();
@@ -8252,7 +8339,9 @@ var FileHwmStore = class {
8252
8339
 
8253
8340
  // src/workflows/invoice-export-workflow.ts
8254
8341
  init_zip();
8342
+ init_targz();
8255
8343
  init_polling();
8344
+ init_with_key_rotation_retry();
8256
8345
 
8257
8346
  // src/utils/hash.ts
8258
8347
  import crypto5 from "node:crypto";
@@ -8266,11 +8355,15 @@ function verifyHash(data, expectedHash) {
8266
8355
  // src/workflows/invoice-export-workflow.ts
8267
8356
  async function doExport(client, filters, options) {
8268
8357
  await client.crypto.init();
8269
- const encData = await client.crypto.getEncryptionData();
8270
- const opResp = await client.invoices.exportInvoices({
8271
- encryption: encData.encryptionInfo,
8272
- filters,
8273
- onlyMetadata: options?.onlyMetadata
8358
+ const { encData, opResp } = await withKeyRotationRetry(client.crypto, async () => {
8359
+ const encData2 = await client.crypto.getEncryptionData();
8360
+ const opResp2 = await client.invoices.exportInvoices({
8361
+ encryption: encData2.encryptionInfo,
8362
+ filters,
8363
+ onlyMetadata: options?.onlyMetadata,
8364
+ ...options?.compressionType && { compressionType: options.compressionType }
8365
+ });
8366
+ return { encData: encData2, opResp: opResp2 };
8274
8367
  });
8275
8368
  const result = await pollUntil(
8276
8369
  () => client.invoices.getInvoiceExportStatus(opResp.referenceNumber),
@@ -9110,6 +9203,7 @@ var invoiceBuild = defineCommand5({
9110
9203
  init_invoice_validator();
9111
9204
  init_ksef_validation_error();
9112
9205
  init_schemas();
9206
+ init_with_key_rotation_retry();
9113
9207
  function getGlobalOpts4(args) {
9114
9208
  return {
9115
9209
  env: args.env,
@@ -9217,7 +9311,7 @@ var send = defineCommand6({
9217
9311
  }
9218
9312
  const { uploadBatchStream: uploadBatchStream2 } = await Promise.resolve().then(() => (init_batch_session_workflow(), batch_session_workflow_exports));
9219
9313
  const zipSize = stat.size;
9220
- const zipStreamFactory = () => Readable.toWeb(fs11.createReadStream(filePath));
9314
+ const zipStreamFactory = () => Readable2.toWeb(fs11.createReadStream(filePath));
9221
9315
  if (!args.json) consola11.start(`Sending batch via stream (${(zipSize / 1e6).toFixed(1)} MB)...`);
9222
9316
  const result = await uploadBatchStream2(client, zipStreamFactory, zipSize, {
9223
9317
  formCode,
@@ -9262,7 +9356,6 @@ var send = defineCommand6({
9262
9356
  }
9263
9357
  if (!args.json) consola11.start(`Sending ${xmlFiles.length} invoices via batch session...`);
9264
9358
  await client.crypto.init();
9265
- const encryptionData = await client.crypto.getEncryptionData();
9266
9359
  const parts = fileBuffers.map(({ content }, i) => {
9267
9360
  const metadata = client.crypto.getFileMetadata(new Uint8Array(content));
9268
9361
  return {
@@ -9282,9 +9375,12 @@ var send = defineCommand6({
9282
9375
  fileHash: p.metadata.hashSHA
9283
9376
  }))
9284
9377
  };
9285
- const openResult = await client.batchSession.openSession(
9286
- { formCode, batchFile: batchFileInfo, encryption: encryptionData.encryptionInfo }
9287
- );
9378
+ const openResult = await withKeyRotationRetry(client.crypto, async () => {
9379
+ const encryptionData = await client.crypto.getEncryptionData();
9380
+ return client.batchSession.openSession(
9381
+ { formCode, batchFile: batchFileInfo, encryption: encryptionData.encryptionInfo }
9382
+ );
9383
+ });
9288
9384
  saveOnlineSessionRef(openResult.referenceNumber);
9289
9385
  await client.batchSession.sendParts(openResult, parts, parallelism);
9290
9386
  await client.batchSession.closeSession(openResult.referenceNumber);
@@ -9439,11 +9535,13 @@ var exportCmd = defineCommand6({
9439
9535
  const { client } = await requireSession(globalOpts);
9440
9536
  if (!args.json) consola11.start("Starting invoice export...");
9441
9537
  await client.crypto.init();
9442
- const encryptionData = await client.crypto.getEncryptionData();
9443
9538
  const filters = buildQueryFilters(args);
9444
- const result = await client.invoices.exportInvoices(
9445
- { encryption: encryptionData.encryptionInfo, filters, onlyMetadata: args.onlyMetadata }
9446
- );
9539
+ const result = await withKeyRotationRetry(client.crypto, async () => {
9540
+ const encryptionData = await client.crypto.getEncryptionData();
9541
+ return client.invoices.exportInvoices(
9542
+ { encryption: encryptionData.encryptionInfo, filters, onlyMetadata: args.onlyMetadata }
9543
+ );
9544
+ });
9447
9545
  if (args.json) {
9448
9546
  outputResult(result, { json: true });
9449
9547
  } else {