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/index.js CHANGED
@@ -387,7 +387,9 @@ var init_error_codes = __esm({
387
387
  init_esm_shims();
388
388
  KSeFErrorCode = {
389
389
  BatchTimeout: 21208,
390
- DuplicateInvoice: 440
390
+ DuplicateInvoice: 440,
391
+ /** The supplied public key identifier is unknown or points to a revoked key (KSeF API v2.5.0). */
392
+ UnknownPublicKeyId: 21470
391
393
  };
392
394
  }
393
395
  });
@@ -417,6 +419,38 @@ var init_ksef_batch_timeout_error = __esm({
417
419
  }
418
420
  });
419
421
 
422
+ // src/errors/ksef-unknown-public-key-error.ts
423
+ function messageOf(description) {
424
+ return description?.trim() || "The supplied public key identifier is unknown or revoked (KSeF 21470).";
425
+ }
426
+ var KSeFUnknownPublicKeyError;
427
+ var init_ksef_unknown_public_key_error = __esm({
428
+ "src/errors/ksef-unknown-public-key-error.ts"() {
429
+ "use strict";
430
+ init_esm_shims();
431
+ init_ksef_api_error();
432
+ init_error_codes();
433
+ KSeFUnknownPublicKeyError = class _KSeFUnknownPublicKeyError extends KSeFApiError {
434
+ statusCode = 400;
435
+ errorCode = KSeFErrorCode.UnknownPublicKeyId;
436
+ constructor(message, errorResponse) {
437
+ super(message, 400, errorResponse);
438
+ this.name = "KSeFUnknownPublicKeyError";
439
+ }
440
+ static fromLegacy(body) {
441
+ const detail = body?.exception?.exceptionDetailList?.find(
442
+ (d) => d.exceptionCode === KSeFErrorCode.UnknownPublicKeyId
443
+ );
444
+ return new _KSeFUnknownPublicKeyError(messageOf(detail?.exceptionDescription), body);
445
+ }
446
+ static fromProblem(problem) {
447
+ const detail = problem.errors?.find((e) => e.code === KSeFErrorCode.UnknownPublicKeyId);
448
+ return new _KSeFUnknownPublicKeyError(messageOf(detail?.description || problem.detail));
449
+ }
450
+ };
451
+ }
452
+ });
453
+
420
454
  // src/errors/ksef-circuit-open-error.ts
421
455
  var KSeFCircuitOpenError;
422
456
  var init_ksef_circuit_open_error = __esm({
@@ -490,6 +524,7 @@ var init_errors = __esm({
490
524
  init_ksef_session_expired_error();
491
525
  init_ksef_validation_error();
492
526
  init_ksef_batch_timeout_error();
527
+ init_ksef_unknown_public_key_error();
493
528
  init_ksef_circuit_open_error();
494
529
  init_ksef_xsd_validation_error();
495
530
  init_error_codes();
@@ -780,6 +815,7 @@ var init_rest_client = __esm({
780
815
  init_ksef_gone_error();
781
816
  init_ksef_bad_request_error();
782
817
  init_ksef_batch_timeout_error();
818
+ init_ksef_unknown_public_key_error();
783
819
  init_error_codes();
784
820
  init_route_builder();
785
821
  init_transport();
@@ -794,6 +830,7 @@ var init_rest_client = __esm({
794
830
  circuitBreakerPolicy;
795
831
  authManager;
796
832
  presignedUrlPolicy;
833
+ onSystemWarning;
797
834
  constructor(options, config) {
798
835
  this.options = options;
799
836
  this.routeBuilder = new RouteBuilder(options.apiVersion);
@@ -803,23 +840,41 @@ var init_rest_client = __esm({
803
840
  this.circuitBreakerPolicy = config?.circuitBreakerPolicy ?? null;
804
841
  this.authManager = config?.authManager;
805
842
  this.presignedUrlPolicy = config?.presignedUrlPolicy;
843
+ this.onSystemWarning = config?.onSystemWarning;
806
844
  }
807
845
  async execute(request) {
808
846
  const response = await this.sendRequest(request);
809
847
  await this.ensureSuccess(response);
848
+ this.handleSystemWarning(response);
810
849
  const body = await response.json();
811
850
  return { body, headers: response.headers, statusCode: response.status };
812
851
  }
813
852
  async executeVoid(request) {
814
853
  const response = await this.sendRequest(request);
815
854
  await this.ensureSuccess(response);
855
+ this.handleSystemWarning(response);
816
856
  }
817
857
  async executeRaw(request) {
818
858
  const response = await this.sendRequest(request);
819
859
  await this.ensureSuccess(response);
860
+ this.handleSystemWarning(response);
820
861
  const body = await response.arrayBuffer();
821
862
  return { body, headers: response.headers, statusCode: response.status };
822
863
  }
864
+ /** Surface the optional `X-System-Warning` response header (KSeF API v2.6.0). */
865
+ handleSystemWarning(response) {
866
+ const warning = response.headers.get("x-system-warning");
867
+ if (!warning) return;
868
+ if (this.onSystemWarning) {
869
+ try {
870
+ this.onSystemWarning(warning);
871
+ } catch (error) {
872
+ consola.warn("onSystemWarning callback threw an exception (ignored):", error);
873
+ }
874
+ } else {
875
+ consola.warn(`KSeF system warning: ${warning}`);
876
+ }
877
+ }
823
878
  async sendRequest(request) {
824
879
  const url = this.buildUrl(request);
825
880
  if (request.isPresigned() && this.presignedUrlPolicy) {
@@ -961,9 +1016,15 @@ var init_rest_client = __esm({
961
1016
  if (response.status === 400) {
962
1017
  const problem = tryParseProblem(isBadRequestProblem);
963
1018
  if (problem) {
1019
+ if (problem.errors?.some((e) => e.code === KSeFErrorCode.UnknownPublicKeyId)) {
1020
+ throw KSeFUnknownPublicKeyError.fromProblem(problem);
1021
+ }
964
1022
  throw new KSeFBadRequestError(problem);
965
1023
  }
966
1024
  const legacy = parseJson();
1025
+ if (hasErrorCode(legacy, KSeFErrorCode.UnknownPublicKeyId)) {
1026
+ throw KSeFUnknownPublicKeyError.fromLegacy(legacy);
1027
+ }
967
1028
  if (hasErrorCode(legacy, KSeFErrorCode.BatchTimeout)) {
968
1029
  throw KSeFBatchTimeoutError.fromResponse(400, legacy);
969
1030
  }
@@ -2423,15 +2484,15 @@ var init_fa2 = __esm({
2423
2484
  }
2424
2485
  });
2425
2486
 
2426
- // src/validation/schemas/rr1-v11e.ts
2427
- var rr1_v11e_exports = {};
2428
- __export(rr1_v11e_exports, {
2429
- RR1_V11ESchema: () => RR1_V11ESchema
2487
+ // src/validation/schemas/fa-rr1.ts
2488
+ var fa_rr1_exports = {};
2489
+ __export(fa_rr1_exports, {
2490
+ FA_RR1Schema: () => FA_RR1Schema
2430
2491
  });
2431
2492
  import { z as z3 } from "zod";
2432
- 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;
2433
- var init_rr1_v11e = __esm({
2434
- "src/validation/schemas/rr1-v11e.ts"() {
2493
+ 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;
2494
+ var init_fa_rr1 = __esm({
2495
+ "src/validation/schemas/fa-rr1.ts"() {
2435
2496
  "use strict";
2436
2497
  init_esm_shims();
2437
2498
  TKodFormularza3 = z3.literal("FA_RR");
@@ -2500,7 +2561,7 @@ var init_rr1_v11e = __esm({
2500
2561
  TTekstowy3 = z3.string().min(1).max(3500);
2501
2562
  TNrKRS3 = z3.string().regex(/^\d{10}$/);
2502
2563
  TNrREGON3 = z3.union([z3.string().regex(/^\d{9}$/), z3.string().regex(/^\d{14}$/)]);
2503
- RR1_V11ESchema = z3.object({
2564
+ FA_RR1Schema = z3.object({
2504
2565
  "Naglowek": TNaglowek3,
2505
2566
  "Podmiot1": z3.object({
2506
2567
  "DaneIdentyfikacyjne": TPodmiot13,
@@ -2629,224 +2690,89 @@ var init_rr1_v11e = __esm({
2629
2690
  }
2630
2691
  });
2631
2692
 
2632
- // src/validation/schemas/rr1-v10e.ts
2633
- var rr1_v10e_exports = {};
2634
- __export(rr1_v10e_exports, {
2635
- RR1_V10ESchema: () => RR1_V10ESchema
2693
+ // src/validation/schemas/pef3.ts
2694
+ var pef3_exports = {};
2695
+ __export(pef3_exports, {
2696
+ PEF3Schema: () => PEF3Schema
2636
2697
  });
2637
2698
  import { z as z4 } from "zod";
2638
- 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;
2639
- var init_rr1_v10e = __esm({
2640
- "src/validation/schemas/rr1-v10e.ts"() {
2699
+ var InvoiceType, PEF3Schema;
2700
+ var init_pef3 = __esm({
2701
+ "src/validation/schemas/pef3.ts"() {
2641
2702
  "use strict";
2642
2703
  init_esm_shims();
2643
- TKodFormularza4 = z4.literal("FA_RR");
2644
- TDataCzas4 = z4.string();
2645
- TZnakowy5 = z4.string().min(1).max(256);
2646
- TNaglowek4 = z4.object({
2647
- "KodFormularza": z4.object({ "#text": TKodFormularza4, "@kodSystemowy": z4.literal("FA_RR(1)"), "@wersjaSchemy": z4.literal("1-0E") }).strict(),
2648
- "WariantFormularza": z4.literal("1"),
2649
- "DataWytworzeniaFa": z4.string(),
2650
- "SystemInfo": TZnakowy5.optional()
2651
- }).strict();
2652
- TNrNIP4 = z4.string().regex(/^[1-9]((\d[1-9])|([1-9]\d))\d{7}$/);
2653
- TZnakowy5124 = z4.string().min(1).max(512);
2654
- TPodmiot14 = z4.object({
2655
- "NIP": TNrNIP4,
2656
- "Nazwa": TZnakowy5124
2657
- }).strict();
2658
- 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"]);
2659
- TGLN4 = z4.string().min(1).max(13);
2660
- TAdres4 = z4.object({
2661
- "KodKraju": TKodKraju4,
2662
- "AdresL1": TZnakowy5124,
2663
- "AdresL2": TZnakowy5124.optional(),
2664
- "GLN": TGLN4.optional()
2665
- }).strict();
2666
- TAdresEmail4 = z4.string().min(3).max(255).regex(/^(.)+@(.)+$/);
2667
- TNumerTelefonu4 = z4.string().min(1).max(16);
2668
- TStatusInfoPodatnika4 = z4.enum(["1", "2", "3", "4"]);
2669
- TZnakowy204 = z4.string().min(1).max(20);
2670
- TNIPIdWew4 = z4.string().min(1).max(20).regex(/^[1-9]((\d[1-9])|([1-9]\d))\d{7}-\d{5}$/);
2671
- TWybor14 = z4.literal("1");
2672
- TPodmiot34 = z4.object({
2673
- "NIP": TNrNIP4.optional(),
2674
- "IDWew": TNIPIdWew4.optional(),
2675
- "BrakID": TWybor14.optional(),
2676
- "Nazwa": TZnakowy5124
2677
- }).strict();
2678
- TRolaPodmiotu34 = z4.enum(["1", "2", "3", "5", "6", "7", "8", "9", "10", "11"]);
2679
- 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"]);
2680
- TData4 = z4.string();
2681
- TDataT4 = z4.string();
2682
- TKwotowy5 = z4.string().regex(/^-?([1-9]\d{0,15}|0)(\.\d{1,2})?$/);
2683
- TRodzajFaktury4 = z4.enum(["VAT_RR", "KOR_VAT_RR"]);
2684
- TTypKorekty4 = z4.enum(["1", "2", "3", "4"]);
2685
- 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})$/);
2686
- TNaturalny4 = z4.string();
2687
- TKluczWartosc4 = z4.object({
2688
- "NrWiersza": TNaturalny4.optional(),
2689
- "Klucz": TZnakowy5,
2690
- "Wartosc": TZnakowy5
2691
- }).strict();
2692
- TZnakowy504 = z4.string().min(1).max(50);
2693
- TIlosci4 = z4.string().regex(/^-?([1-9]\d{0,15}|0)(\.\d{1,6})?$/);
2694
- TKwotowy24 = z4.string().regex(/^-?([1-9]\d{0,13}|0)(\.\d{1,8})?$/);
2695
- TProcentowy4 = z4.coerce.number().min(0).max(100);
2696
- TStawkaPodatku4 = z4.enum(["6.5", "7"]);
2697
- TFormaPlatnosci4 = z4.literal("1");
2698
- TNrRB4 = z4.string().min(10).max(34);
2699
- SWIFT_Type4 = z4.string().regex(/^[A-Z]{6}[A-Z0-9]{2}([A-Z0-9]{3}){0,1}$/);
2700
- TRachunekBankowy4 = z4.object({
2701
- "NrRB": TNrRB4,
2702
- "SWIFT": SWIFT_Type4.optional(),
2703
- "NazwaBanku": TZnakowy5.optional(),
2704
- "OpisRachunku": TZnakowy5.optional()
2705
- }).strict();
2706
- TTekstowy4 = z4.string().min(1).max(3500);
2707
- TNrKRS4 = z4.string().regex(/^\d{10}$/);
2708
- TNrREGON4 = z4.union([z4.string().regex(/^\d{9}$/), z4.string().regex(/^\d{14}$/)]);
2709
- RR1_V10ESchema = z4.object({
2710
- "Naglowek": TNaglowek4,
2711
- "Podmiot1": z4.object({
2712
- "DaneIdentyfikacyjne": TPodmiot14,
2713
- "Adres": TAdres4,
2714
- "AdresKoresp": TAdres4.optional(),
2715
- "DaneKontaktowe": z4.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z4.array(z4.object({
2716
- "Email": TAdresEmail4.optional(),
2717
- "Telefon": TNumerTelefonu4.optional()
2718
- }).strict()).min(0).max(3)).optional(),
2719
- "NrKontrahenta": TZnakowy5.optional()
2720
- }).strict(),
2721
- "Podmiot2": z4.object({
2722
- "DaneIdentyfikacyjne": TPodmiot14,
2723
- "Adres": TAdres4,
2724
- "AdresKoresp": TAdres4.optional(),
2725
- "DaneKontaktowe": z4.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z4.array(z4.object({
2726
- "Email": TAdresEmail4.optional(),
2727
- "Telefon": TNumerTelefonu4.optional()
2728
- }).strict()).min(0).max(3)).optional(),
2729
- "StatusInfoPodatnika": TStatusInfoPodatnika4.optional()
2730
- }).strict(),
2731
- "Podmiot3": z4.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z4.array(z4.object({
2732
- "DaneIdentyfikacyjne": TPodmiot34,
2733
- "Adres": TAdres4.optional(),
2734
- "AdresKoresp": TAdres4.optional(),
2735
- "DaneKontaktowe": z4.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z4.array(z4.object({
2736
- "Email": TAdresEmail4.optional(),
2737
- "Telefon": TNumerTelefonu4.optional()
2738
- }).strict()).min(0).max(3)).optional(),
2739
- "Rola": TRolaPodmiotu34.optional(),
2740
- "RolaInna": TWybor14.optional(),
2741
- "OpisRoli": TZnakowy5.optional()
2742
- }).strict()).min(0).max(100)).optional(),
2743
- "FakturaRR": z4.object({
2744
- "KodWaluty": TKodWaluty4,
2745
- "P_1M": TZnakowy5.optional(),
2746
- "P_4A": TDataT4.optional(),
2747
- "P_4B": TDataT4,
2748
- "P_4C": TZnakowy5,
2749
- "P_11_1": TKwotowy5,
2750
- "P_11_1W": TKwotowy5.optional(),
2751
- "P_11_2": TKwotowy5,
2752
- "P_11_2W": TKwotowy5.optional(),
2753
- "P_12_1": TKwotowy5,
2754
- "P_12_1W": TKwotowy5.optional(),
2755
- "P_12_2": TZnakowy5,
2756
- "RodzajFaktury": TRodzajFaktury4,
2757
- "PrzyczynaKorekty": TZnakowy5.optional(),
2758
- "TypKorekty": TTypKorekty4.optional(),
2759
- "DaneFaKorygowanej": z4.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z4.array(z4.object({
2760
- "DataWystFaKorygowanej": TDataT4,
2761
- "NrFaKorygowanej": TZnakowy5,
2762
- "NrKSeF": TWybor14.optional(),
2763
- "NrKSeFFaKorygowanej": TNumerKSeF4.optional(),
2764
- "NrKSeFN": TWybor14.optional()
2765
- }).strict()).min(1).max(5e4)).optional(),
2766
- "NrFaKorygowany": TZnakowy5.optional(),
2767
- "Podmiot1K": z4.object({
2768
- "DaneIdentyfikacyjne": TPodmiot14,
2769
- "Adres": TAdres4
2770
- }).strict().optional(),
2771
- "Podmiot2K": z4.object({
2772
- "DaneIdentyfikacyjne": TPodmiot14,
2773
- "Adres": TAdres4
2774
- }).strict().optional(),
2775
- "DokumentZaplaty": z4.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z4.array(z4.object({
2776
- "NrDokumentu": TZnakowy5,
2777
- "DataDokumentu": TData4.optional()
2778
- }).strict()).min(0).max(50)).optional(),
2779
- "DodatkowyOpis": z4.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z4.array(TKluczWartosc4).min(0).max(1e4)).optional(),
2780
- "FakturaRRWiersz": z4.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z4.array(z4.object({
2781
- "NrWierszaFa": TNaturalny4,
2782
- "UU_ID": TZnakowy504.optional(),
2783
- "P_4AA": TDataT4.optional(),
2784
- "P_5": TZnakowy5,
2785
- "GTIN": TZnakowy204.optional(),
2786
- "PKWiU": TZnakowy504.optional(),
2787
- "CN": TZnakowy504.optional(),
2788
- "P_6A": TZnakowy5,
2789
- "P_6B": TIlosci4,
2790
- "P_6C": TZnakowy5,
2791
- "P_7": TKwotowy24,
2792
- "P_8": TKwotowy5,
2793
- "P_9": TStawkaPodatku4,
2794
- "P_10": TKwotowy5,
2795
- "P_11": TKwotowy5,
2796
- "StanPrzed": TWybor14.optional(),
2797
- "KursWaluty": TIlosci4.optional()
2798
- }).strict()).min(0).max(1e4)).optional(),
2799
- "Rozliczenie": z4.object({
2800
- "Obciazenia": z4.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z4.array(z4.object({
2801
- "Kwota": TKwotowy5,
2802
- "Powod": TZnakowy5
2803
- }).strict()).min(0).max(100)).optional(),
2804
- "SumaObciazen": TKwotowy5.optional(),
2805
- "Odliczenia": z4.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z4.array(z4.object({
2806
- "Kwota": TKwotowy5,
2807
- "Powod": TZnakowy5
2808
- }).strict()).min(0).max(100)).optional(),
2809
- "SumaOdliczen": TKwotowy5.optional(),
2810
- "DoZaplaty": TKwotowy5.optional(),
2811
- "DoRozliczenia": TKwotowy5.optional()
2812
- }).strict().optional(),
2813
- "Platnosc": z4.object({
2814
- "FormaPlatnosci": TFormaPlatnosci4.optional(),
2815
- "PlatnoscInna": TWybor14.optional(),
2816
- "OpisPlatnosci": TZnakowy5.optional(),
2817
- "RachunekBankowy1": z4.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z4.array(TRachunekBankowy4).min(0).max(3)).optional(),
2818
- "RachunekBankowy2": z4.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z4.array(TRachunekBankowy4).min(0).max(3)).optional(),
2819
- "IPKSeF": z4.string().min(1).max(13).regex(/^[0-9]{3}[a-zA-Z0-9]{10}$/).optional(),
2820
- "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()
2821
- }).strict().optional()
2822
- }).strict(),
2823
- "Stopka": z4.object({
2824
- "Informacje": z4.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z4.array(z4.object({
2825
- "StopkaFaktury": TTekstowy4.optional()
2826
- }).strict()).min(0).max(3)).optional(),
2827
- "Rejestry": z4.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z4.array(z4.object({
2828
- "PelnaNazwa": TZnakowy5.optional(),
2829
- "KRS": TNrKRS4.optional(),
2830
- "REGON": TNrREGON4.optional(),
2831
- "BDO": z4.string().min(1).max(9).optional()
2832
- }).strict()).min(0).max(100)).optional()
2833
- }).strict().optional()
2704
+ InvoiceType = z4.object({
2705
+ "UBLExtensions": z4.any().optional(),
2706
+ "UBLVersionID": z4.any().optional(),
2707
+ "CustomizationID": z4.any().optional(),
2708
+ "ProfileID": z4.any().optional(),
2709
+ "ProfileExecutionID": z4.any().optional(),
2710
+ "ID": z4.any(),
2711
+ "CopyIndicator": z4.any().optional(),
2712
+ "UUID": z4.any().optional(),
2713
+ "IssueDate": z4.any(),
2714
+ "IssueTime": z4.any().optional(),
2715
+ "DueDate": z4.any().optional(),
2716
+ "InvoiceTypeCode": z4.any().optional(),
2717
+ "Note": z4.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z4.array(z4.any()).min(0)).optional(),
2718
+ "TaxPointDate": z4.any().optional(),
2719
+ "DocumentCurrencyCode": z4.any().optional(),
2720
+ "TaxCurrencyCode": z4.any().optional(),
2721
+ "PricingCurrencyCode": z4.any().optional(),
2722
+ "PaymentCurrencyCode": z4.any().optional(),
2723
+ "PaymentAlternativeCurrencyCode": z4.any().optional(),
2724
+ "AccountingCostCode": z4.any().optional(),
2725
+ "AccountingCost": z4.any().optional(),
2726
+ "LineCountNumeric": z4.any().optional(),
2727
+ "BuyerReference": z4.any().optional(),
2728
+ "InvoicePeriod": z4.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z4.array(z4.any()).min(0)).optional(),
2729
+ "OrderReference": z4.any().optional(),
2730
+ "BillingReference": z4.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z4.array(z4.any()).min(0)).optional(),
2731
+ "DespatchDocumentReference": z4.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z4.array(z4.any()).min(0)).optional(),
2732
+ "ReceiptDocumentReference": z4.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z4.array(z4.any()).min(0)).optional(),
2733
+ "StatementDocumentReference": z4.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z4.array(z4.any()).min(0)).optional(),
2734
+ "OriginatorDocumentReference": z4.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z4.array(z4.any()).min(0)).optional(),
2735
+ "ContractDocumentReference": z4.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z4.array(z4.any()).min(0)).optional(),
2736
+ "AdditionalDocumentReference": z4.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z4.array(z4.any()).min(0)).optional(),
2737
+ "ProjectReference": z4.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z4.array(z4.any()).min(0)).optional(),
2738
+ "Signature": z4.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z4.array(z4.any()).min(0)).optional(),
2739
+ "AccountingSupplierParty": z4.any(),
2740
+ "AccountingCustomerParty": z4.any(),
2741
+ "PayeeParty": z4.any().optional(),
2742
+ "BuyerCustomerParty": z4.any().optional(),
2743
+ "SellerSupplierParty": z4.any().optional(),
2744
+ "TaxRepresentativeParty": z4.any().optional(),
2745
+ "Delivery": z4.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z4.array(z4.any()).min(0)).optional(),
2746
+ "DeliveryTerms": z4.any().optional(),
2747
+ "PaymentMeans": z4.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z4.array(z4.any()).min(0)).optional(),
2748
+ "PaymentTerms": z4.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z4.array(z4.any()).min(0)).optional(),
2749
+ "PrepaidPayment": z4.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z4.array(z4.any()).min(0)).optional(),
2750
+ "AllowanceCharge": z4.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z4.array(z4.any()).min(0)).optional(),
2751
+ "TaxExchangeRate": z4.any().optional(),
2752
+ "PricingExchangeRate": z4.any().optional(),
2753
+ "PaymentExchangeRate": z4.any().optional(),
2754
+ "PaymentAlternativeExchangeRate": z4.any().optional(),
2755
+ "TaxTotal": z4.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z4.array(z4.any()).min(0)).optional(),
2756
+ "WithholdingTaxTotal": z4.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z4.array(z4.any()).min(0)).optional(),
2757
+ "LegalMonetaryTotal": z4.any(),
2758
+ "InvoiceLine": z4.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z4.array(z4.any()).min(1))
2834
2759
  }).strict();
2760
+ PEF3Schema = InvoiceType;
2835
2761
  }
2836
2762
  });
2837
2763
 
2838
- // src/validation/schemas/pef3.ts
2839
- var pef3_exports = {};
2840
- __export(pef3_exports, {
2841
- PEF3Schema: () => PEF3Schema
2764
+ // src/validation/schemas/pef-kor3.ts
2765
+ var pef_kor3_exports = {};
2766
+ __export(pef_kor3_exports, {
2767
+ PEF_KOR3Schema: () => PEF_KOR3Schema
2842
2768
  });
2843
2769
  import { z as z5 } from "zod";
2844
- var InvoiceType, PEF3Schema;
2845
- var init_pef3 = __esm({
2846
- "src/validation/schemas/pef3.ts"() {
2770
+ var CreditNoteType, PEF_KOR3Schema;
2771
+ var init_pef_kor3 = __esm({
2772
+ "src/validation/schemas/pef-kor3.ts"() {
2847
2773
  "use strict";
2848
2774
  init_esm_shims();
2849
- InvoiceType = z5.object({
2775
+ CreditNoteType = z5.object({
2850
2776
  "UBLExtensions": z5.any().optional(),
2851
2777
  "UBLVersionID": z5.any().optional(),
2852
2778
  "CustomizationID": z5.any().optional(),
@@ -2857,10 +2783,9 @@ var init_pef3 = __esm({
2857
2783
  "UUID": z5.any().optional(),
2858
2784
  "IssueDate": z5.any(),
2859
2785
  "IssueTime": z5.any().optional(),
2860
- "DueDate": z5.any().optional(),
2861
- "InvoiceTypeCode": z5.any().optional(),
2862
- "Note": z5.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z5.array(z5.any()).min(0)).optional(),
2863
2786
  "TaxPointDate": z5.any().optional(),
2787
+ "CreditNoteTypeCode": z5.any().optional(),
2788
+ "Note": z5.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z5.array(z5.any()).min(0)).optional(),
2864
2789
  "DocumentCurrencyCode": z5.any().optional(),
2865
2790
  "TaxCurrencyCode": z5.any().optional(),
2866
2791
  "PricingCurrencyCode": z5.any().optional(),
@@ -2871,15 +2796,15 @@ var init_pef3 = __esm({
2871
2796
  "LineCountNumeric": z5.any().optional(),
2872
2797
  "BuyerReference": z5.any().optional(),
2873
2798
  "InvoicePeriod": z5.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z5.array(z5.any()).min(0)).optional(),
2799
+ "DiscrepancyResponse": z5.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z5.array(z5.any()).min(0)).optional(),
2874
2800
  "OrderReference": z5.any().optional(),
2875
2801
  "BillingReference": z5.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z5.array(z5.any()).min(0)).optional(),
2876
2802
  "DespatchDocumentReference": z5.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z5.array(z5.any()).min(0)).optional(),
2877
2803
  "ReceiptDocumentReference": z5.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z5.array(z5.any()).min(0)).optional(),
2878
- "StatementDocumentReference": z5.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z5.array(z5.any()).min(0)).optional(),
2879
- "OriginatorDocumentReference": z5.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z5.array(z5.any()).min(0)).optional(),
2880
2804
  "ContractDocumentReference": z5.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z5.array(z5.any()).min(0)).optional(),
2881
2805
  "AdditionalDocumentReference": z5.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z5.array(z5.any()).min(0)).optional(),
2882
- "ProjectReference": z5.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z5.array(z5.any()).min(0)).optional(),
2806
+ "StatementDocumentReference": z5.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z5.array(z5.any()).min(0)).optional(),
2807
+ "OriginatorDocumentReference": z5.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z5.array(z5.any()).min(0)).optional(),
2883
2808
  "Signature": z5.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z5.array(z5.any()).min(0)).optional(),
2884
2809
  "AccountingSupplierParty": z5.any(),
2885
2810
  "AccountingCustomerParty": z5.any(),
@@ -2888,87 +2813,17 @@ var init_pef3 = __esm({
2888
2813
  "SellerSupplierParty": z5.any().optional(),
2889
2814
  "TaxRepresentativeParty": z5.any().optional(),
2890
2815
  "Delivery": z5.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z5.array(z5.any()).min(0)).optional(),
2891
- "DeliveryTerms": z5.any().optional(),
2816
+ "DeliveryTerms": z5.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z5.array(z5.any()).min(0)).optional(),
2892
2817
  "PaymentMeans": z5.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z5.array(z5.any()).min(0)).optional(),
2893
2818
  "PaymentTerms": z5.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z5.array(z5.any()).min(0)).optional(),
2894
- "PrepaidPayment": z5.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z5.array(z5.any()).min(0)).optional(),
2895
- "AllowanceCharge": z5.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z5.array(z5.any()).min(0)).optional(),
2896
2819
  "TaxExchangeRate": z5.any().optional(),
2897
2820
  "PricingExchangeRate": z5.any().optional(),
2898
2821
  "PaymentExchangeRate": z5.any().optional(),
2899
2822
  "PaymentAlternativeExchangeRate": z5.any().optional(),
2823
+ "AllowanceCharge": z5.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z5.array(z5.any()).min(0)).optional(),
2900
2824
  "TaxTotal": z5.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z5.array(z5.any()).min(0)).optional(),
2901
- "WithholdingTaxTotal": z5.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z5.array(z5.any()).min(0)).optional(),
2902
2825
  "LegalMonetaryTotal": z5.any(),
2903
- "InvoiceLine": z5.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z5.array(z5.any()).min(1))
2904
- }).strict();
2905
- PEF3Schema = InvoiceType;
2906
- }
2907
- });
2908
-
2909
- // src/validation/schemas/pef-kor3.ts
2910
- var pef_kor3_exports = {};
2911
- __export(pef_kor3_exports, {
2912
- PEF_KOR3Schema: () => PEF_KOR3Schema
2913
- });
2914
- import { z as z6 } from "zod";
2915
- var CreditNoteType, PEF_KOR3Schema;
2916
- var init_pef_kor3 = __esm({
2917
- "src/validation/schemas/pef-kor3.ts"() {
2918
- "use strict";
2919
- init_esm_shims();
2920
- CreditNoteType = z6.object({
2921
- "UBLExtensions": z6.any().optional(),
2922
- "UBLVersionID": z6.any().optional(),
2923
- "CustomizationID": z6.any().optional(),
2924
- "ProfileID": z6.any().optional(),
2925
- "ProfileExecutionID": z6.any().optional(),
2926
- "ID": z6.any(),
2927
- "CopyIndicator": z6.any().optional(),
2928
- "UUID": z6.any().optional(),
2929
- "IssueDate": z6.any(),
2930
- "IssueTime": z6.any().optional(),
2931
- "TaxPointDate": z6.any().optional(),
2932
- "CreditNoteTypeCode": z6.any().optional(),
2933
- "Note": z6.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z6.array(z6.any()).min(0)).optional(),
2934
- "DocumentCurrencyCode": z6.any().optional(),
2935
- "TaxCurrencyCode": z6.any().optional(),
2936
- "PricingCurrencyCode": z6.any().optional(),
2937
- "PaymentCurrencyCode": z6.any().optional(),
2938
- "PaymentAlternativeCurrencyCode": z6.any().optional(),
2939
- "AccountingCostCode": z6.any().optional(),
2940
- "AccountingCost": z6.any().optional(),
2941
- "LineCountNumeric": z6.any().optional(),
2942
- "BuyerReference": z6.any().optional(),
2943
- "InvoicePeriod": z6.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z6.array(z6.any()).min(0)).optional(),
2944
- "DiscrepancyResponse": z6.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z6.array(z6.any()).min(0)).optional(),
2945
- "OrderReference": z6.any().optional(),
2946
- "BillingReference": z6.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z6.array(z6.any()).min(0)).optional(),
2947
- "DespatchDocumentReference": z6.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z6.array(z6.any()).min(0)).optional(),
2948
- "ReceiptDocumentReference": z6.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z6.array(z6.any()).min(0)).optional(),
2949
- "ContractDocumentReference": z6.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z6.array(z6.any()).min(0)).optional(),
2950
- "AdditionalDocumentReference": z6.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z6.array(z6.any()).min(0)).optional(),
2951
- "StatementDocumentReference": z6.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z6.array(z6.any()).min(0)).optional(),
2952
- "OriginatorDocumentReference": z6.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z6.array(z6.any()).min(0)).optional(),
2953
- "Signature": z6.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z6.array(z6.any()).min(0)).optional(),
2954
- "AccountingSupplierParty": z6.any(),
2955
- "AccountingCustomerParty": z6.any(),
2956
- "PayeeParty": z6.any().optional(),
2957
- "BuyerCustomerParty": z6.any().optional(),
2958
- "SellerSupplierParty": z6.any().optional(),
2959
- "TaxRepresentativeParty": z6.any().optional(),
2960
- "Delivery": z6.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z6.array(z6.any()).min(0)).optional(),
2961
- "DeliveryTerms": z6.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z6.array(z6.any()).min(0)).optional(),
2962
- "PaymentMeans": z6.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z6.array(z6.any()).min(0)).optional(),
2963
- "PaymentTerms": z6.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z6.array(z6.any()).min(0)).optional(),
2964
- "TaxExchangeRate": z6.any().optional(),
2965
- "PricingExchangeRate": z6.any().optional(),
2966
- "PaymentExchangeRate": z6.any().optional(),
2967
- "PaymentAlternativeExchangeRate": z6.any().optional(),
2968
- "AllowanceCharge": z6.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z6.array(z6.any()).min(0)).optional(),
2969
- "TaxTotal": z6.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z6.array(z6.any()).min(0)).optional(),
2970
- "LegalMonetaryTotal": z6.any(),
2971
- "CreditNoteLine": z6.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z6.array(z6.any()).min(1))
2826
+ "CreditNoteLine": z5.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z5.array(z5.any()).min(1))
2972
2827
  }).strict();
2973
2828
  PEF_KOR3Schema = CreditNoteType;
2974
2829
  }
@@ -2982,15 +2837,13 @@ var init_schemas = __esm({
2982
2837
  init_esm_shims();
2983
2838
  init_fa3();
2984
2839
  init_fa2();
2985
- init_rr1_v11e();
2986
- init_rr1_v10e();
2840
+ init_fa_rr1();
2987
2841
  init_pef3();
2988
2842
  init_pef_kor3();
2989
2843
  NAMESPACE_MAP = {
2990
2844
  "http://crd.gov.pl/wzor/2025/06/25/13775/": "FA3",
2991
2845
  "http://crd.gov.pl/wzor/2023/06/29/12648/": "FA2",
2992
- "http://crd.gov.pl/wzor/2026/03/06/14189/": "RR1_V11E",
2993
- "http://crd.gov.pl/wzor/2026/02/17/14164/": "RR1_V10E",
2846
+ "http://crd.gov.pl/wzor/2026/03/06/14189/": "FA_RR1",
2994
2847
  "urn:oasis:names:specification:ubl:schema:xsd:Invoice-2": "PEF3",
2995
2848
  "urn:oasis:names:specification:ubl:schema:xsd:CreditNote-2": "PEF_KOR3"
2996
2849
  };
@@ -3009,11 +2862,8 @@ async function loadSchema(type) {
3009
2862
  case "FA2":
3010
2863
  mod = await Promise.resolve().then(() => (init_fa2(), fa2_exports));
3011
2864
  break;
3012
- case "RR1_V11E":
3013
- mod = await Promise.resolve().then(() => (init_rr1_v11e(), rr1_v11e_exports));
3014
- break;
3015
- case "RR1_V10E":
3016
- mod = await Promise.resolve().then(() => (init_rr1_v10e(), rr1_v10e_exports));
2865
+ case "FA_RR1":
2866
+ mod = await Promise.resolve().then(() => (init_fa_rr1(), fa_rr1_exports));
3017
2867
  break;
3018
2868
  case "PEF3":
3019
2869
  mod = await Promise.resolve().then(() => (init_pef3(), pef3_exports));
@@ -3054,7 +2904,7 @@ var init_schema_registry = __esm({
3054
2904
  * List all available schema types.
3055
2905
  */
3056
2906
  availableSchemas() {
3057
- return ["FA3", "FA2", "RR1_V11E", "RR1_V10E", "PEF3", "PEF_KOR3"];
2907
+ return ["FA3", "FA2", "FA_RR1", "PEF3", "PEF_KOR3"];
3058
2908
  },
3059
2909
  /**
3060
2910
  * Detect schema type from XML namespace URI and/or root element name.
@@ -4451,8 +4301,8 @@ var init_certificate_fetcher = __esm({
4451
4301
  init_routes();
4452
4302
  CertificateFetcher = class {
4453
4303
  restClient;
4454
- symmetricKeyPem;
4455
- ksefTokenPem;
4304
+ symmetricKey;
4305
+ ksefToken;
4456
4306
  initialized = false;
4457
4307
  constructor(restClient) {
4458
4308
  this.restClient = restClient;
@@ -4465,17 +4315,38 @@ var init_certificate_fetcher = __esm({
4465
4315
  this.initialized = false;
4466
4316
  await this.fetchCertificates();
4467
4317
  }
4318
+ /**
4319
+ * Immutable snapshot ({@link SelectedCertificate}) of the selected
4320
+ * SymmetricKeyEncryption certificate. The stored object is replaced wholesale
4321
+ * by {@link refresh}, never mutated, so holding the returned reference yields a
4322
+ * consistent pem + publicKeyId pair even if a concurrent refresh swaps the cache.
4323
+ */
4324
+ getSymmetricKeyEncryption() {
4325
+ return { ...this.requireSelected(this.symmetricKey) };
4326
+ }
4327
+ /** Immutable snapshot of the selected KsefTokenEncryption certificate. See {@link getSymmetricKeyEncryption}. */
4328
+ getKsefTokenEncryption() {
4329
+ return { ...this.requireSelected(this.ksefToken) };
4330
+ }
4468
4331
  getSymmetricKeyEncryptionPem() {
4469
- if (!this.symmetricKeyPem) {
4470
- throw new Error("CertificateFetcher not initialized. Call init() first.");
4471
- }
4472
- return this.symmetricKeyPem;
4332
+ return this.requireSelected(this.symmetricKey).pem;
4473
4333
  }
4474
4334
  getKsefTokenEncryptionPem() {
4475
- if (!this.ksefTokenPem) {
4335
+ return this.requireSelected(this.ksefToken).pem;
4336
+ }
4337
+ /** Public key identifier of the selected SymmetricKeyEncryption certificate (KSeF API v2.5.0). */
4338
+ getSymmetricKeyPublicKeyId() {
4339
+ return this.requireSelected(this.symmetricKey).publicKeyId;
4340
+ }
4341
+ /** Public key identifier of the selected KsefTokenEncryption certificate (KSeF API v2.5.0). */
4342
+ getKsefTokenPublicKeyId() {
4343
+ return this.requireSelected(this.ksefToken).publicKeyId;
4344
+ }
4345
+ requireSelected(selected) {
4346
+ if (!selected) {
4476
4347
  throw new Error("CertificateFetcher not initialized. Call init() first.");
4477
4348
  }
4478
- return this.ksefTokenPem;
4349
+ return selected;
4479
4350
  }
4480
4351
  async fetchCertificates() {
4481
4352
  const request = RestRequest.get(Routes.Security.publicKeyCertificates);
@@ -4484,19 +4355,27 @@ var init_certificate_fetcher = __esm({
4484
4355
  if (!certs || certs.length === 0) {
4485
4356
  throw new Error("No public key certificates returned from KSeF API.");
4486
4357
  }
4487
- const symmetricCert = certs.find((c) => c.usage.includes("SymmetricKeyEncryption"));
4488
- if (!symmetricCert) {
4489
- throw new Error("No SymmetricKeyEncryption certificate found.");
4490
- }
4491
- this.symmetricKeyPem = this.derBase64ToPem(symmetricCert.certificate);
4492
- const tokenCerts = certs.filter((c) => c.usage.includes("KsefTokenEncryption")).sort((a, b) => a.validFrom.localeCompare(b.validFrom));
4493
- const tokenCert = tokenCerts[0];
4494
- if (!tokenCert) {
4495
- throw new Error("No KsefTokenEncryption certificate found.");
4496
- }
4497
- this.ksefTokenPem = this.derBase64ToPem(tokenCert.certificate);
4358
+ this.symmetricKey = this.select(certs, "SymmetricKeyEncryption");
4359
+ this.ksefToken = this.select(certs, "KsefTokenEncryption");
4498
4360
  this.initialized = true;
4499
4361
  }
4362
+ /**
4363
+ * Select the certificate to use for a given usage under key rotation:
4364
+ * filter to currently-valid certificates (validFrom ≤ now < validTo) and pick
4365
+ * the newest by validFrom. If none are currently valid, fall back to the newest
4366
+ * overall so the server can reject it with a clear error rather than sending nothing.
4367
+ */
4368
+ select(certs, usage) {
4369
+ const candidates = certs.filter((c) => c.usage.includes(usage));
4370
+ if (candidates.length === 0) {
4371
+ throw new Error(`No ${usage} certificate found.`);
4372
+ }
4373
+ const now = Date.now();
4374
+ const byNewestValidFrom = (a, b) => Date.parse(b.validFrom) - Date.parse(a.validFrom);
4375
+ const valid = candidates.filter((c) => Date.parse(c.validFrom) <= now && now < Date.parse(c.validTo)).sort(byNewestValidFrom);
4376
+ const chosen = valid[0] ?? [...candidates].sort(byNewestValidFrom)[0];
4377
+ return { pem: this.derBase64ToPem(chosen.certificate), publicKeyId: chosen.publicKeyId };
4378
+ }
4500
4379
  derBase64ToPem(base64Der) {
4501
4380
  const lines = [];
4502
4381
  for (let i = 0; i < base64Der.length; i += 64) {
@@ -4552,6 +4431,14 @@ var init_cryptography_service = __esm({
4552
4431
  async init() {
4553
4432
  await this.fetcher.init();
4554
4433
  }
4434
+ /** Re-fetch KSeF public certificates, discarding the cached selection (used for key-rotation recovery). */
4435
+ async refresh() {
4436
+ await this.fetcher.refresh();
4437
+ }
4438
+ /** Identifier of the KsefTokenEncryption public key used by {@link encryptKsefToken} (KSeF API v2.5.0). */
4439
+ getKsefTokenPublicKeyId() {
4440
+ return this.fetcher.getKsefTokenPublicKeyId();
4441
+ }
4555
4442
  // ---------------------------------------------------------------------------
4556
4443
  // AES-256-CBC
4557
4444
  // ---------------------------------------------------------------------------
@@ -4597,11 +4484,12 @@ var init_cryptography_service = __esm({
4597
4484
  async getEncryptionData() {
4598
4485
  const key = crypto2.randomBytes(32);
4599
4486
  const iv = crypto2.randomBytes(16);
4600
- const certPem = this.fetcher.getSymmetricKeyEncryptionPem();
4601
- const encryptedKey = await this.rsaOaepEncrypt(certPem, new Uint8Array(key));
4487
+ const cert = this.fetcher.getSymmetricKeyEncryption();
4488
+ const encryptedKey = await this.rsaOaepEncrypt(cert.pem, new Uint8Array(key));
4602
4489
  const encryptionInfo = {
4603
4490
  encryptedSymmetricKey: Buffer.from(encryptedKey).toString("base64"),
4604
- initializationVector: iv.toString("base64")
4491
+ initializationVector: iv.toString("base64"),
4492
+ publicKeyId: cert.publicKeyId
4605
4493
  };
4606
4494
  return {
4607
4495
  cipherKey: new Uint8Array(key),
@@ -4626,9 +4514,29 @@ var init_cryptography_service = __esm({
4626
4514
  * `[ephemeralSPKI | nonce(12) | ciphertext+tag]`.
4627
4515
  */
4628
4516
  async encryptKsefToken(token, challengeTimestamp) {
4517
+ return this.encryptKsefTokenWithCertPem(
4518
+ this.fetcher.getKsefTokenEncryptionPem(),
4519
+ token,
4520
+ challengeTimestamp
4521
+ );
4522
+ }
4523
+ /**
4524
+ * Encrypt a KSeF token and return it together with the public key id of the
4525
+ * exact certificate used.
4526
+ *
4527
+ * Both values come from a single certificate snapshot taken before any
4528
+ * `await`, so a concurrent {@link refresh} cannot tag the ciphertext with a
4529
+ * different key than it was encrypted under (KSeF API v2.5.0). Prefer this over
4530
+ * pairing {@link encryptKsefToken} with a separate {@link getKsefTokenPublicKeyId}.
4531
+ */
4532
+ async encryptKsefTokenWithKeyId(token, challengeTimestamp) {
4533
+ const cert = this.fetcher.getKsefTokenEncryption();
4534
+ const encryptedToken = await this.encryptKsefTokenWithCertPem(cert.pem, token, challengeTimestamp);
4535
+ return { encryptedToken, publicKeyId: cert.publicKeyId };
4536
+ }
4537
+ async encryptKsefTokenWithCertPem(certPem, token, challengeTimestamp) {
4629
4538
  const timestampMs = new Date(challengeTimestamp).getTime();
4630
4539
  const plaintext = Buffer.from(`${token}|${timestampMs}`, "utf-8");
4631
- const certPem = this.fetcher.getKsefTokenEncryptionPem();
4632
4540
  const cert = new crypto2.X509Certificate(certPem);
4633
4541
  const publicKey = cert.publicKey;
4634
4542
  if (publicKey.asymmetricKeyType === "rsa") {
@@ -5147,7 +5055,7 @@ var init_auth_xml_builder = __esm({
5147
5055
  "src/crypto/auth-xml-builder.ts"() {
5148
5056
  "use strict";
5149
5057
  init_esm_shims();
5150
- AUTH_TOKEN_REQUEST_NS = "http://ksef.mf.gov.pl/auth/token/2.0";
5058
+ AUTH_TOKEN_REQUEST_NS = "http://ksef.mf.gov.pl/auth/token/2.1";
5151
5059
  }
5152
5060
  });
5153
5061
 
@@ -5309,6 +5217,156 @@ var init_zip = __esm({
5309
5217
  }
5310
5218
  });
5311
5219
 
5220
+ // src/utils/targz.ts
5221
+ var targz_exports = {};
5222
+ __export(targz_exports, {
5223
+ createTarGz: () => createTarGz,
5224
+ extractTarGz: () => extractTarGz
5225
+ });
5226
+ import { createGzip, createGunzip } from "node:zlib";
5227
+ import { Readable } from "node:stream";
5228
+ import { extract, pack } from "tar-stream";
5229
+ async function createTarGz(entries) {
5230
+ const packer = pack();
5231
+ const gzip = packer.pipe(createGzip());
5232
+ const chunks = [];
5233
+ return new Promise((resolve, reject) => {
5234
+ let settled = false;
5235
+ const fail = (err) => {
5236
+ if (settled) return;
5237
+ settled = true;
5238
+ reject(err);
5239
+ };
5240
+ packer.on("error", fail);
5241
+ gzip.on("error", fail);
5242
+ gzip.on("data", (chunk) => chunks.push(chunk));
5243
+ gzip.on("end", () => {
5244
+ if (settled) return;
5245
+ settled = true;
5246
+ resolve(Buffer.concat(chunks));
5247
+ });
5248
+ try {
5249
+ for (const entry of entries) {
5250
+ const content = Buffer.from(entry.content);
5251
+ packer.entry({ name: entry.fileName, size: content.length }, content);
5252
+ }
5253
+ packer.finalize();
5254
+ } catch (err) {
5255
+ fail(err instanceof Error ? err : new Error(String(err)));
5256
+ }
5257
+ });
5258
+ }
5259
+ async function extractTarGz(buffer, options = {}) {
5260
+ const limits = { ...DEFAULT_LIMITS, ...options };
5261
+ const ratioCeiling = limits.maxCompressionRatio !== null && limits.maxCompressionRatio !== void 0 && buffer.length > 0 ? buffer.length * limits.maxCompressionRatio : null;
5262
+ return new Promise((resolve, reject) => {
5263
+ const source = Readable.from(buffer);
5264
+ const gunzip = createGunzip();
5265
+ const extractor = extract();
5266
+ const files = /* @__PURE__ */ new Map();
5267
+ let extractedFileCount = 0;
5268
+ let totalUncompressed = 0;
5269
+ let settled = false;
5270
+ const cleanup = () => {
5271
+ source.destroy();
5272
+ gunzip.destroy();
5273
+ extractor.destroy();
5274
+ };
5275
+ const fail = (err) => {
5276
+ if (settled) return;
5277
+ settled = true;
5278
+ cleanup();
5279
+ reject(err);
5280
+ };
5281
+ const succeed = () => {
5282
+ if (settled) return;
5283
+ settled = true;
5284
+ resolve(files);
5285
+ };
5286
+ gunzip.on("data", (chunk) => {
5287
+ totalUncompressed += chunk.length;
5288
+ if (limits.maxTotalUncompressedSize > 0 && totalUncompressed > limits.maxTotalUncompressedSize) {
5289
+ fail(new Error("tar.gz exceeds max_total_uncompressed_size"));
5290
+ return;
5291
+ }
5292
+ if (ratioCeiling !== null && totalUncompressed > ratioCeiling) {
5293
+ fail(new Error("tar.gz exceeds max_compression_ratio"));
5294
+ }
5295
+ });
5296
+ extractor.on("entry", (header, stream, next) => {
5297
+ if (settled) {
5298
+ stream.resume();
5299
+ return;
5300
+ }
5301
+ if (header.type !== "file") {
5302
+ stream.resume();
5303
+ stream.on("end", next);
5304
+ return;
5305
+ }
5306
+ if (limits.maxFiles > 0 && extractedFileCount >= limits.maxFiles) {
5307
+ fail(new Error("tar.gz contains too many files"));
5308
+ return;
5309
+ }
5310
+ const chunks = [];
5311
+ let entrySize = 0;
5312
+ stream.on("data", (chunk) => {
5313
+ if (settled) return;
5314
+ entrySize += chunk.length;
5315
+ if (limits.maxFileUncompressedSize > 0 && entrySize > limits.maxFileUncompressedSize) {
5316
+ fail(new Error("tar.gz entry exceeds max_file_uncompressed_size"));
5317
+ return;
5318
+ }
5319
+ chunks.push(chunk);
5320
+ });
5321
+ stream.on("error", fail);
5322
+ stream.on("end", () => {
5323
+ if (settled) return;
5324
+ extractedFileCount += 1;
5325
+ files.set(header.name, Buffer.concat(chunks));
5326
+ next();
5327
+ });
5328
+ });
5329
+ extractor.on("finish", succeed);
5330
+ extractor.on("error", fail);
5331
+ gunzip.on("error", fail);
5332
+ source.on("error", fail);
5333
+ source.pipe(gunzip).pipe(extractor);
5334
+ });
5335
+ }
5336
+ var DEFAULT_LIMITS;
5337
+ var init_targz = __esm({
5338
+ "src/utils/targz.ts"() {
5339
+ "use strict";
5340
+ init_esm_shims();
5341
+ DEFAULT_LIMITS = {
5342
+ maxFiles: 1e4,
5343
+ maxTotalUncompressedSize: 2e9,
5344
+ maxFileUncompressedSize: 5e8,
5345
+ maxCompressionRatio: 200
5346
+ };
5347
+ }
5348
+ });
5349
+
5350
+ // src/crypto/with-key-rotation-retry.ts
5351
+ async function withKeyRotationRetry(crypto8, op) {
5352
+ try {
5353
+ return await op();
5354
+ } catch (err) {
5355
+ if (err instanceof KSeFUnknownPublicKeyError) {
5356
+ await crypto8.refresh();
5357
+ return await op();
5358
+ }
5359
+ throw err;
5360
+ }
5361
+ }
5362
+ var init_with_key_rotation_retry = __esm({
5363
+ "src/crypto/with-key-rotation-retry.ts"() {
5364
+ "use strict";
5365
+ init_esm_shims();
5366
+ init_ksef_unknown_public_key_error();
5367
+ }
5368
+ });
5369
+
5312
5370
  // src/offline/holidays.ts
5313
5371
  function toDateKey(d) {
5314
5372
  return d.toISOString().slice(0, 10);
@@ -5486,6 +5544,7 @@ var init_offline_invoice_workflow = __esm({
5486
5544
  init_esm_shims();
5487
5545
  init_ksef_api_error();
5488
5546
  init_deadline();
5547
+ init_with_key_rotation_retry();
5489
5548
  init_document_structures();
5490
5549
  OfflineInvoiceWorkflow = class {
5491
5550
  constructor(qrService) {
@@ -5592,11 +5651,14 @@ var init_offline_invoice_workflow = __esm({
5592
5651
  }
5593
5652
  if (pending.length === 0) return result;
5594
5653
  await client.crypto.init();
5595
- const encData = await client.crypto.getEncryptionData();
5596
5654
  const formCode = options.formCode ?? DEFAULT_FORM_CODE;
5597
- const openResp = await client.onlineSession.openSession(
5598
- { formCode, encryption: encData.encryptionInfo }
5599
- );
5655
+ const { encData, openResp } = await withKeyRotationRetry(client.crypto, async () => {
5656
+ const encData2 = await client.crypto.getEncryptionData();
5657
+ const openResp2 = await client.onlineSession.openSession(
5658
+ { formCode, encryption: encData2.encryptionInfo }
5659
+ );
5660
+ return { encData: encData2, openResp: openResp2 };
5661
+ });
5600
5662
  const sessionRef = openResp.referenceNumber;
5601
5663
  try {
5602
5664
  for (const inv of pending) {
@@ -5681,11 +5743,14 @@ var init_offline_invoice_workflow = __esm({
5681
5743
  }
5682
5744
  const originalHash = crypto7.createHash("sha256").update(original.invoiceXml).digest("base64");
5683
5745
  await client.crypto.init();
5684
- const encData = await client.crypto.getEncryptionData();
5685
5746
  const formCode = options.formCode ?? DEFAULT_FORM_CODE;
5686
- const openResp = await client.onlineSession.openSession(
5687
- { formCode, encryption: encData.encryptionInfo }
5688
- );
5747
+ const { encData, openResp } = await withKeyRotationRetry(client.crypto, async () => {
5748
+ const encData2 = await client.crypto.getEncryptionData();
5749
+ const openResp2 = await client.onlineSession.openSession(
5750
+ { formCode, encryption: encData2.encryptionInfo }
5751
+ );
5752
+ return { encData: encData2, openResp: openResp2 };
5753
+ });
5689
5754
  const sessionRef = openResp.referenceNumber;
5690
5755
  try {
5691
5756
  const data = new TextEncoder().encode(correctedInvoiceXml);
@@ -5807,6 +5872,9 @@ function buildRestClientConfig(options, authManager) {
5807
5872
  allowedHosts: [...base.allowedHosts, ...options.presignedUrlHosts]
5808
5873
  };
5809
5874
  }
5875
+ if (options?.onSystemWarning) {
5876
+ config.onSystemWarning = options.onSystemWarning;
5877
+ }
5810
5878
  return config;
5811
5879
  }
5812
5880
  var KSeFClient;
@@ -5836,6 +5904,7 @@ var init_client = __esm({
5836
5904
  init_test_data();
5837
5905
  init_certificate_fetcher();
5838
5906
  init_cryptography_service();
5907
+ init_with_key_rotation_retry();
5839
5908
  init_verification_link_service();
5840
5909
  init_auth_xml_builder();
5841
5910
  init_offline_invoice_workflow();
@@ -5902,11 +5971,14 @@ var init_client = __esm({
5902
5971
  async loginWithToken(token, nip) {
5903
5972
  const challenge = await this.auth.getChallenge();
5904
5973
  await this.crypto.init();
5905
- const encryptedToken = await this.crypto.encryptKsefToken(token, challenge.timestamp);
5906
- const submitResult = await this.auth.submitKsefTokenAuthRequest({
5907
- challenge: challenge.challenge,
5908
- contextIdentifier: { type: "Nip", value: nip },
5909
- encryptedToken: Buffer.from(encryptedToken).toString("base64")
5974
+ const submitResult = await withKeyRotationRetry(this.crypto, async () => {
5975
+ const { encryptedToken, publicKeyId } = await this.crypto.encryptKsefTokenWithKeyId(token, challenge.timestamp);
5976
+ return this.auth.submitKsefTokenAuthRequest({
5977
+ challenge: challenge.challenge,
5978
+ contextIdentifier: { type: "Nip", value: nip },
5979
+ encryptedToken: Buffer.from(encryptedToken).toString("base64"),
5980
+ publicKeyId
5981
+ });
5910
5982
  });
5911
5983
  const authToken = submitResult.authenticationToken.token;
5912
5984
  await this.awaitAuthReady(submitResult.referenceNumber, authToken);
@@ -6284,6 +6356,7 @@ var AuthKsefTokenRequestBuilder = class {
6284
6356
  challenge;
6285
6357
  contextIdentifier;
6286
6358
  encryptedToken;
6359
+ publicKeyId;
6287
6360
  authorizationPolicy;
6288
6361
  withChallenge(challenge) {
6289
6362
  this.challenge = challenge;
@@ -6305,6 +6378,13 @@ var AuthKsefTokenRequestBuilder = class {
6305
6378
  this.encryptedToken = token;
6306
6379
  return this;
6307
6380
  }
6381
+ withPublicKeyId(publicKeyId) {
6382
+ if (!publicKeyId.trim()) {
6383
+ throw KSeFValidationError.fromField("publicKeyId", "Public key id is required");
6384
+ }
6385
+ this.publicKeyId = publicKeyId.trim();
6386
+ return this;
6387
+ }
6308
6388
  withAuthorizationPolicy(policy) {
6309
6389
  this.authorizationPolicy = policy;
6310
6390
  return this;
@@ -6323,6 +6403,7 @@ var AuthKsefTokenRequestBuilder = class {
6323
6403
  challenge: this.challenge,
6324
6404
  contextIdentifier: this.contextIdentifier,
6325
6405
  encryptedToken: this.encryptedToken,
6406
+ ...this.publicKeyId && { publicKeyId: this.publicKeyId },
6326
6407
  ...this.authorizationPolicy && { authorizationPolicy: this.authorizationPolicy }
6327
6408
  };
6328
6409
  }
@@ -6628,6 +6709,7 @@ var BatchFileBuilder = class {
6628
6709
  batchFile: {
6629
6710
  fileSize: zipBytes.length,
6630
6711
  fileHash: zipHash,
6712
+ ...options?.compressionType && { compressionType: options.compressionType },
6631
6713
  fileParts
6632
6714
  },
6633
6715
  encryptedParts
@@ -6730,6 +6812,7 @@ var BatchFileBuilder = class {
6730
6812
  batchFile: {
6731
6813
  fileSize: zipSize,
6732
6814
  fileHash: zipMeta.hashSHA,
6815
+ ...options?.compressionType && { compressionType: options.compressionType },
6733
6816
  fileParts
6734
6817
  },
6735
6818
  streamParts
@@ -6909,6 +6992,7 @@ function escapeXml2(str) {
6909
6992
  // src/utils/index.ts
6910
6993
  init_esm_shims();
6911
6994
  init_zip();
6995
+ init_targz();
6912
6996
  init_jwt();
6913
6997
 
6914
6998
  // src/utils/hash.ts
@@ -6952,6 +7036,7 @@ init_auth_manager();
6952
7036
  init_online_session();
6953
7037
  init_session_status();
6954
7038
  init_document_structures();
7039
+ init_with_key_rotation_retry();
6955
7040
 
6956
7041
  // src/xml/index.ts
6957
7042
  init_esm_shims();
@@ -7721,12 +7806,15 @@ function buildSessionHandle(params) {
7721
7806
  }
7722
7807
  async function openOnlineSession(client, options) {
7723
7808
  await client.crypto.init();
7724
- const encData = await client.crypto.getEncryptionData();
7725
7809
  const formCode = options?.formCode ?? DEFAULT_FORM_CODE;
7726
- const openResp = await client.onlineSession.openSession(
7727
- { formCode, encryption: encData.encryptionInfo },
7728
- options?.upoVersion
7729
- );
7810
+ const { encData, openResp } = await withKeyRotationRetry(client.crypto, async () => {
7811
+ const encData2 = await client.crypto.getEncryptionData();
7812
+ const openResp2 = await client.onlineSession.openSession(
7813
+ { formCode, encryption: encData2.encryptionInfo },
7814
+ options?.upoVersion
7815
+ );
7816
+ return { encData: encData2, openResp: openResp2 };
7817
+ });
7730
7818
  return buildSessionHandle({
7731
7819
  deps: {
7732
7820
  crypto: client.crypto,
@@ -7778,17 +7866,17 @@ async function openSendAndClose(client, invoices, options) {
7778
7866
  // src/workflows/batch-session-workflow.ts
7779
7867
  init_esm_shims();
7780
7868
  init_document_structures();
7869
+ init_with_key_rotation_retry();
7781
7870
  async function uploadBatch(client, zipData, options) {
7782
7871
  if (options?.parallelism !== void 0 && (!Number.isInteger(options.parallelism) || options.parallelism < 1)) {
7783
7872
  throw new Error("parallelism must be a positive integer");
7784
7873
  }
7785
7874
  await client.crypto.init();
7786
7875
  if (options?.validate) {
7787
- const { unzip: unzip2 } = await Promise.resolve().then(() => (init_zip(), zip_exports));
7788
7876
  const { validateBatch: validateBatch2, batchValidationDetails: batchValidationDetails2 } = await Promise.resolve().then(() => (init_invoice_validator(), invoice_validator_exports));
7789
7877
  const { KSeFValidationError: KSeFValidationError2 } = await Promise.resolve().then(() => (init_ksef_validation_error(), ksef_validation_error_exports));
7790
7878
  const zipBuf = Buffer.isBuffer(zipData) ? zipData : Buffer.from(zipData.buffer, zipData.byteOffset, zipData.byteLength);
7791
- const files = await unzip2(zipBuf);
7879
+ 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);
7792
7880
  const invoices = [...files.entries()].filter(([name]) => name.endsWith(".xml")).map(([name, data]) => ({ fileName: name, xml: data.toString("utf-8") }));
7793
7881
  if (invoices.length > 0) {
7794
7882
  const result2 = await validateBatch2(invoices);
@@ -7801,21 +7889,25 @@ async function uploadBatch(client, zipData, options) {
7801
7889
  }
7802
7890
  }
7803
7891
  }
7804
- const encData = await client.crypto.getEncryptionData();
7805
7892
  const formCode = options?.formCode ?? DEFAULT_FORM_CODE;
7806
- const encryptFn = (part) => client.crypto.encryptAES256(part, encData.cipherKey, encData.cipherIv);
7807
- const { batchFile, encryptedParts } = BatchFileBuilder.build(zipData, encryptFn, {
7808
- maxPartSize: options?.maxPartSize
7893
+ const { batchFile, encryptedParts, openResp } = await withKeyRotationRetry(client.crypto, async () => {
7894
+ const encData = await client.crypto.getEncryptionData();
7895
+ const encryptFn = (part) => client.crypto.encryptAES256(part, encData.cipherKey, encData.cipherIv);
7896
+ const { batchFile: batchFile2, encryptedParts: encryptedParts2 } = BatchFileBuilder.build(zipData, encryptFn, {
7897
+ maxPartSize: options?.maxPartSize,
7898
+ compressionType: options?.compressionType
7899
+ });
7900
+ const openResp2 = await client.batchSession.openSession(
7901
+ {
7902
+ formCode,
7903
+ encryption: encData.encryptionInfo,
7904
+ batchFile: batchFile2,
7905
+ offlineMode: options?.offlineMode
7906
+ },
7907
+ options?.upoVersion
7908
+ );
7909
+ return { batchFile: batchFile2, encryptedParts: encryptedParts2, openResp: openResp2 };
7809
7910
  });
7810
- const openResp = await client.batchSession.openSession(
7811
- {
7812
- formCode,
7813
- encryption: encData.encryptionInfo,
7814
- batchFile,
7815
- offlineMode: options?.offlineMode
7816
- },
7817
- options?.upoVersion
7818
- );
7819
7911
  const sendingParts = encryptedParts.map((part, i) => ({
7820
7912
  data: part.buffer.slice(part.byteOffset, part.byteOffset + part.byteLength),
7821
7913
  metadata: {
@@ -7849,26 +7941,29 @@ async function uploadBatchStream(client, zipStreamFactory, zipSize, options) {
7849
7941
  throw new Error("parallelism must be a positive integer");
7850
7942
  }
7851
7943
  await client.crypto.init();
7852
- const encData = await client.crypto.getEncryptionData();
7853
7944
  const formCode = options?.formCode ?? DEFAULT_FORM_CODE;
7854
- const encryptStreamFn = (stream) => client.crypto.encryptAES256Stream(stream, encData.cipherKey, encData.cipherIv);
7855
- const hashStreamFn = (stream) => client.crypto.getFileMetadataFromStream(stream);
7856
- const { batchFile, streamParts } = await BatchFileBuilder.buildFromStream(
7857
- zipStreamFactory,
7858
- zipSize,
7859
- encryptStreamFn,
7860
- hashStreamFn,
7861
- { maxPartSize: options?.maxPartSize }
7862
- );
7863
- const openResp = await client.batchSession.openSession(
7864
- {
7865
- formCode,
7866
- encryption: encData.encryptionInfo,
7867
- batchFile,
7868
- offlineMode: options?.offlineMode
7869
- },
7870
- options?.upoVersion
7871
- );
7945
+ const { streamParts, openResp } = await withKeyRotationRetry(client.crypto, async () => {
7946
+ const encData = await client.crypto.getEncryptionData();
7947
+ const encryptStreamFn = (stream) => client.crypto.encryptAES256Stream(stream, encData.cipherKey, encData.cipherIv);
7948
+ const hashStreamFn = (stream) => client.crypto.getFileMetadataFromStream(stream);
7949
+ const { batchFile, streamParts: streamParts2 } = await BatchFileBuilder.buildFromStream(
7950
+ zipStreamFactory,
7951
+ zipSize,
7952
+ encryptStreamFn,
7953
+ hashStreamFn,
7954
+ { maxPartSize: options?.maxPartSize, compressionType: options?.compressionType }
7955
+ );
7956
+ const openResp2 = await client.batchSession.openSession(
7957
+ {
7958
+ formCode,
7959
+ encryption: encData.encryptionInfo,
7960
+ batchFile,
7961
+ offlineMode: options?.offlineMode
7962
+ },
7963
+ options?.upoVersion
7964
+ );
7965
+ return { streamParts: streamParts2, openResp: openResp2 };
7966
+ });
7872
7967
  await client.batchSession.sendPartsWithStream(openResp, streamParts, options?.parallelism);
7873
7968
  await client.batchSession.closeSession(openResp.referenceNumber);
7874
7969
  const result = await pollUntil(
@@ -7917,13 +8012,19 @@ async function uploadBatchParsed(client, zipData, options) {
7917
8012
  // src/workflows/invoice-export-workflow.ts
7918
8013
  init_esm_shims();
7919
8014
  init_zip();
8015
+ init_targz();
8016
+ init_with_key_rotation_retry();
7920
8017
  async function doExport(client, filters, options) {
7921
8018
  await client.crypto.init();
7922
- const encData = await client.crypto.getEncryptionData();
7923
- const opResp = await client.invoices.exportInvoices({
7924
- encryption: encData.encryptionInfo,
7925
- filters,
7926
- onlyMetadata: options?.onlyMetadata
8019
+ const { encData, opResp } = await withKeyRotationRetry(client.crypto, async () => {
8020
+ const encData2 = await client.crypto.getEncryptionData();
8021
+ const opResp2 = await client.invoices.exportInvoices({
8022
+ encryption: encData2.encryptionInfo,
8023
+ filters,
8024
+ onlyMetadata: options?.onlyMetadata,
8025
+ ...options?.compressionType && { compressionType: options.compressionType }
8026
+ });
8027
+ return { encData: encData2, opResp: opResp2 };
7927
8028
  });
7928
8029
  const result = await pollUntil(
7929
8030
  () => client.invoices.getInvoiceExportStatus(opResp.referenceNumber),
@@ -7978,8 +8079,8 @@ async function exportAndDownload(client, filters, options) {
7978
8079
  decryptedParts.push(decrypted);
7979
8080
  }
7980
8081
  if (options?.extract) {
7981
- const zipBuffer = Buffer.concat(decryptedParts);
7982
- const files = await unzip(zipBuffer, options.unzipOptions);
8082
+ const archiveBuffer = Buffer.concat(decryptedParts);
8083
+ const files = options.compressionType === "TarGz" ? await extractTarGz(archiveBuffer, options.unzipOptions) : await unzip(archiveBuffer, options.unzipOptions);
7983
8084
  return { ...exportResult, files };
7984
8085
  }
7985
8086
  return {
@@ -8124,15 +8225,19 @@ var FileHwmStore = class {
8124
8225
  // src/workflows/auth-workflow.ts
8125
8226
  init_esm_shims();
8126
8227
  init_auth_xml_builder();
8228
+ init_with_key_rotation_retry();
8127
8229
  async function authenticateWithToken(client, options) {
8128
8230
  const challenge = await client.auth.getChallenge();
8129
8231
  await client.crypto.init();
8130
- const encryptedToken = await client.crypto.encryptKsefToken(options.token, challenge.timestamp);
8131
- const submitResult = await client.auth.submitKsefTokenAuthRequest({
8132
- challenge: challenge.challenge,
8133
- contextIdentifier: { type: "Nip", value: options.nip },
8134
- encryptedToken: Buffer.from(encryptedToken).toString("base64"),
8135
- authorizationPolicy: options.authorizationPolicy
8232
+ const submitResult = await withKeyRotationRetry(client.crypto, async () => {
8233
+ const { encryptedToken, publicKeyId } = await client.crypto.encryptKsefTokenWithKeyId(options.token, challenge.timestamp);
8234
+ return client.auth.submitKsefTokenAuthRequest({
8235
+ challenge: challenge.challenge,
8236
+ contextIdentifier: { type: "Nip", value: options.nip },
8237
+ encryptedToken: Buffer.from(encryptedToken).toString("base64"),
8238
+ publicKeyId,
8239
+ authorizationPolicy: options.authorizationPolicy
8240
+ });
8136
8241
  });
8137
8242
  const authToken = submitResult.authenticationToken.token;
8138
8243
  await pollUntil(
@@ -8414,6 +8519,7 @@ export {
8414
8519
  KSeFRateLimitError,
8415
8520
  KSeFSessionExpiredError,
8416
8521
  KSeFUnauthorizedError,
8522
+ KSeFUnknownPublicKeyError,
8417
8523
  KSeFValidationError,
8418
8524
  KSeFXsdValidationError,
8419
8525
  KsefNumber,
@@ -8472,6 +8578,7 @@ export {
8472
8578
  calculateBackoff,
8473
8579
  calculateOfflineDeadline,
8474
8580
  comparePKey,
8581
+ createTarGz,
8475
8582
  createZip,
8476
8583
  decodeJwtPayload,
8477
8584
  deduplicateByKsefNumber,
@@ -8484,6 +8591,7 @@ export {
8484
8591
  exportInvoices,
8485
8592
  extendDeadlineForMaintenance,
8486
8593
  extractInvoiceFields,
8594
+ extractTarGz,
8487
8595
  getDefaultReason,
8488
8596
  getEffectiveStartDate,
8489
8597
  getFormCode,