ksef-client-ts 0.8.0 → 0.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -401,6 +401,25 @@ var init_ksef_validation_error = __esm({
401
401
  }
402
402
  });
403
403
 
404
+ // src/errors/ksef-metadata-pagination-error.ts
405
+ var KSeFMetadataPaginationError;
406
+ var init_ksef_metadata_pagination_error = __esm({
407
+ "src/errors/ksef-metadata-pagination-error.ts"() {
408
+ "use strict";
409
+ init_cjs_shims();
410
+ init_ksef_error();
411
+ KSeFMetadataPaginationError = class extends KSeFError {
412
+ /** The boundary date value that failed to advance. */
413
+ boundaryValue;
414
+ constructor(message, boundaryValue) {
415
+ super(message);
416
+ this.name = "KSeFMetadataPaginationError";
417
+ this.boundaryValue = boundaryValue;
418
+ }
419
+ };
420
+ }
421
+ });
422
+
404
423
  // src/errors/error-codes.ts
405
424
  function hasErrorCode(body, code) {
406
425
  return !!body?.exception?.exceptionDetailList?.some((d) => d.exceptionCode === code);
@@ -412,7 +431,9 @@ var init_error_codes = __esm({
412
431
  init_cjs_shims();
413
432
  KSeFErrorCode = {
414
433
  BatchTimeout: 21208,
415
- DuplicateInvoice: 440
434
+ DuplicateInvoice: 440,
435
+ /** The supplied public key identifier is unknown or points to a revoked key (KSeF API v2.5.0). */
436
+ UnknownPublicKeyId: 21470
416
437
  };
417
438
  }
418
439
  });
@@ -442,6 +463,38 @@ var init_ksef_batch_timeout_error = __esm({
442
463
  }
443
464
  });
444
465
 
466
+ // src/errors/ksef-unknown-public-key-error.ts
467
+ function messageOf(description) {
468
+ return description?.trim() || "The supplied public key identifier is unknown or revoked (KSeF 21470).";
469
+ }
470
+ var KSeFUnknownPublicKeyError;
471
+ var init_ksef_unknown_public_key_error = __esm({
472
+ "src/errors/ksef-unknown-public-key-error.ts"() {
473
+ "use strict";
474
+ init_cjs_shims();
475
+ init_ksef_api_error();
476
+ init_error_codes();
477
+ KSeFUnknownPublicKeyError = class _KSeFUnknownPublicKeyError extends KSeFApiError {
478
+ statusCode = 400;
479
+ errorCode = KSeFErrorCode.UnknownPublicKeyId;
480
+ constructor(message, errorResponse) {
481
+ super(message, 400, errorResponse);
482
+ this.name = "KSeFUnknownPublicKeyError";
483
+ }
484
+ static fromLegacy(body) {
485
+ const detail = body?.exception?.exceptionDetailList?.find(
486
+ (d) => d.exceptionCode === KSeFErrorCode.UnknownPublicKeyId
487
+ );
488
+ return new _KSeFUnknownPublicKeyError(messageOf(detail?.exceptionDescription), body);
489
+ }
490
+ static fromProblem(problem) {
491
+ const detail = problem.errors?.find((e) => e.code === KSeFErrorCode.UnknownPublicKeyId);
492
+ return new _KSeFUnknownPublicKeyError(messageOf(detail?.description || problem.detail));
493
+ }
494
+ };
495
+ }
496
+ });
497
+
445
498
  // src/errors/ksef-circuit-open-error.ts
446
499
  var KSeFCircuitOpenError;
447
500
  var init_ksef_circuit_open_error = __esm({
@@ -514,7 +567,9 @@ var init_errors = __esm({
514
567
  init_ksef_auth_status_error();
515
568
  init_ksef_session_expired_error();
516
569
  init_ksef_validation_error();
570
+ init_ksef_metadata_pagination_error();
517
571
  init_ksef_batch_timeout_error();
572
+ init_ksef_unknown_public_key_error();
518
573
  init_ksef_circuit_open_error();
519
574
  init_ksef_xsd_validation_error();
520
575
  init_error_codes();
@@ -805,6 +860,7 @@ var init_rest_client = __esm({
805
860
  init_ksef_gone_error();
806
861
  init_ksef_bad_request_error();
807
862
  init_ksef_batch_timeout_error();
863
+ init_ksef_unknown_public_key_error();
808
864
  init_error_codes();
809
865
  init_route_builder();
810
866
  init_transport();
@@ -819,6 +875,7 @@ var init_rest_client = __esm({
819
875
  circuitBreakerPolicy;
820
876
  authManager;
821
877
  presignedUrlPolicy;
878
+ onSystemWarning;
822
879
  constructor(options, config) {
823
880
  this.options = options;
824
881
  this.routeBuilder = new RouteBuilder(options.apiVersion);
@@ -828,23 +885,41 @@ var init_rest_client = __esm({
828
885
  this.circuitBreakerPolicy = config?.circuitBreakerPolicy ?? null;
829
886
  this.authManager = config?.authManager;
830
887
  this.presignedUrlPolicy = config?.presignedUrlPolicy;
888
+ this.onSystemWarning = config?.onSystemWarning;
831
889
  }
832
890
  async execute(request) {
833
891
  const response = await this.sendRequest(request);
834
892
  await this.ensureSuccess(response);
893
+ this.handleSystemWarning(response);
835
894
  const body = await response.json();
836
895
  return { body, headers: response.headers, statusCode: response.status };
837
896
  }
838
897
  async executeVoid(request) {
839
898
  const response = await this.sendRequest(request);
840
899
  await this.ensureSuccess(response);
900
+ this.handleSystemWarning(response);
841
901
  }
842
902
  async executeRaw(request) {
843
903
  const response = await this.sendRequest(request);
844
904
  await this.ensureSuccess(response);
905
+ this.handleSystemWarning(response);
845
906
  const body = await response.arrayBuffer();
846
907
  return { body, headers: response.headers, statusCode: response.status };
847
908
  }
909
+ /** Surface the optional `X-System-Warning` response header (KSeF API v2.6.0). */
910
+ handleSystemWarning(response) {
911
+ const warning = response.headers.get("x-system-warning");
912
+ if (!warning) return;
913
+ if (this.onSystemWarning) {
914
+ try {
915
+ this.onSystemWarning(warning);
916
+ } catch (error) {
917
+ import_consola.consola.warn("onSystemWarning callback threw an exception (ignored):", error);
918
+ }
919
+ } else {
920
+ import_consola.consola.warn(`KSeF system warning: ${warning}`);
921
+ }
922
+ }
848
923
  async sendRequest(request) {
849
924
  const url = this.buildUrl(request);
850
925
  if (request.isPresigned() && this.presignedUrlPolicy) {
@@ -986,9 +1061,15 @@ var init_rest_client = __esm({
986
1061
  if (response.status === 400) {
987
1062
  const problem = tryParseProblem(isBadRequestProblem);
988
1063
  if (problem) {
1064
+ if (problem.errors?.some((e) => e.code === KSeFErrorCode.UnknownPublicKeyId)) {
1065
+ throw KSeFUnknownPublicKeyError.fromProblem(problem);
1066
+ }
989
1067
  throw new KSeFBadRequestError(problem);
990
1068
  }
991
1069
  const legacy = parseJson();
1070
+ if (hasErrorCode(legacy, KSeFErrorCode.UnknownPublicKeyId)) {
1071
+ throw KSeFUnknownPublicKeyError.fromLegacy(legacy);
1072
+ }
992
1073
  if (hasErrorCode(legacy, KSeFErrorCode.BatchTimeout)) {
993
1074
  throw KSeFBatchTimeoutError.fromResponse(400, legacy);
994
1075
  }
@@ -1508,6 +1589,9 @@ function isValidCertificateName(value) {
1508
1589
  function isValidCertificateFingerprint(value) {
1509
1590
  return CertificateFingerprint.test(value);
1510
1591
  }
1592
+ function isValidCertificateSerialNumber(value) {
1593
+ return CertificateSerialNumber.test(value);
1594
+ }
1511
1595
  function isValidBase64(value) {
1512
1596
  return Base64String.test(value);
1513
1597
  }
@@ -1517,7 +1601,7 @@ function isValidIp4Address(value) {
1517
1601
  function isValidSha256Base64(value) {
1518
1602
  return Sha256Base64.test(value);
1519
1603
  }
1520
- var NIP_PATTERN_CORE, VAT_UE_PATTERN_CORE, Nip, VatUe, NipVatUe, InternalId, PeppolId, ReferenceNumber, KsefNumber, KsefNumberV35, KsefNumberV36, CertificateName, Pesel, CertificateFingerprint, Base64String, Ip4Address, Ip4Range, Ip4Mask, Sha256Base64, NIP_WEIGHTS, PESEL_WEIGHTS, CRC8_POLY;
1604
+ var NIP_PATTERN_CORE, VAT_UE_PATTERN_CORE, Nip, VatUe, NipVatUe, InternalId, PeppolId, ReferenceNumber, KsefNumber, KsefNumberV35, KsefNumberV36, CertificateName, Pesel, CertificateFingerprint, CertificateSerialNumber, Base64String, Ip4Address, Ip4Range, Ip4Mask, Sha256Base64, NIP_WEIGHTS, PESEL_WEIGHTS, CRC8_POLY;
1521
1605
  var init_patterns = __esm({
1522
1606
  "src/validation/patterns.ts"() {
1523
1607
  "use strict";
@@ -1536,6 +1620,7 @@ var init_patterns = __esm({
1536
1620
  CertificateName = /^[a-zA-Z0-9_\- ąćęłńóśźżĄĆĘŁŃÓŚŹŻ]+$/;
1537
1621
  Pesel = /^\d{2}(?:0[1-9]|1[0-2]|2[1-9]|3[0-2]|4[1-9]|5[0-2]|6[1-9]|7[0-2]|8[1-9]|9[0-2])\d{7}$/;
1538
1622
  CertificateFingerprint = /^[0-9A-F]{64}$/;
1623
+ CertificateSerialNumber = /^[0-9A-F]{16}$/;
1539
1624
  Base64String = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;
1540
1625
  Ip4Address = /^((25[0-5]|(2[0-4]|1\d|[1-9]|)\d)\.?\b){4}$/;
1541
1626
  Ip4Range = /^((25[0-5]|(2[0-4]|1\d|[1-9]|)\d)\.?\b){4}-((25[0-5]|(2[0-4]|1\d|[1-9]|)\d)\.?\b){4}$/;
@@ -2449,14 +2534,14 @@ var init_fa2 = __esm({
2449
2534
  }
2450
2535
  });
2451
2536
 
2452
- // src/validation/schemas/rr1-v11e.ts
2453
- var rr1_v11e_exports = {};
2454
- __export(rr1_v11e_exports, {
2455
- RR1_V11ESchema: () => RR1_V11ESchema
2537
+ // src/validation/schemas/fa-rr1.ts
2538
+ var fa_rr1_exports = {};
2539
+ __export(fa_rr1_exports, {
2540
+ FA_RR1Schema: () => FA_RR1Schema
2456
2541
  });
2457
- var import_zod3, 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;
2458
- var init_rr1_v11e = __esm({
2459
- "src/validation/schemas/rr1-v11e.ts"() {
2542
+ var import_zod3, 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;
2543
+ var init_fa_rr1 = __esm({
2544
+ "src/validation/schemas/fa-rr1.ts"() {
2460
2545
  "use strict";
2461
2546
  init_cjs_shims();
2462
2547
  import_zod3 = require("zod");
@@ -2526,7 +2611,7 @@ var init_rr1_v11e = __esm({
2526
2611
  TTekstowy3 = import_zod3.z.string().min(1).max(3500);
2527
2612
  TNrKRS3 = import_zod3.z.string().regex(/^\d{10}$/);
2528
2613
  TNrREGON3 = import_zod3.z.union([import_zod3.z.string().regex(/^\d{9}$/), import_zod3.z.string().regex(/^\d{14}$/)]);
2529
- RR1_V11ESchema = import_zod3.z.object({
2614
+ FA_RR1Schema = import_zod3.z.object({
2530
2615
  "Naglowek": TNaglowek3,
2531
2616
  "Podmiot1": import_zod3.z.object({
2532
2617
  "DaneIdentyfikacyjne": TPodmiot13,
@@ -2655,224 +2740,89 @@ var init_rr1_v11e = __esm({
2655
2740
  }
2656
2741
  });
2657
2742
 
2658
- // src/validation/schemas/rr1-v10e.ts
2659
- var rr1_v10e_exports = {};
2660
- __export(rr1_v10e_exports, {
2661
- RR1_V10ESchema: () => RR1_V10ESchema
2743
+ // src/validation/schemas/pef3.ts
2744
+ var pef3_exports = {};
2745
+ __export(pef3_exports, {
2746
+ PEF3Schema: () => PEF3Schema
2662
2747
  });
2663
- var import_zod4, 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;
2664
- var init_rr1_v10e = __esm({
2665
- "src/validation/schemas/rr1-v10e.ts"() {
2748
+ var import_zod4, InvoiceType, PEF3Schema;
2749
+ var init_pef3 = __esm({
2750
+ "src/validation/schemas/pef3.ts"() {
2666
2751
  "use strict";
2667
2752
  init_cjs_shims();
2668
2753
  import_zod4 = require("zod");
2669
- TKodFormularza4 = import_zod4.z.literal("FA_RR");
2670
- TDataCzas4 = import_zod4.z.string();
2671
- TZnakowy5 = import_zod4.z.string().min(1).max(256);
2672
- TNaglowek4 = import_zod4.z.object({
2673
- "KodFormularza": import_zod4.z.object({ "#text": TKodFormularza4, "@kodSystemowy": import_zod4.z.literal("FA_RR(1)"), "@wersjaSchemy": import_zod4.z.literal("1-0E") }).strict(),
2674
- "WariantFormularza": import_zod4.z.literal("1"),
2675
- "DataWytworzeniaFa": import_zod4.z.string(),
2676
- "SystemInfo": TZnakowy5.optional()
2677
- }).strict();
2678
- TNrNIP4 = import_zod4.z.string().regex(/^[1-9]((\d[1-9])|([1-9]\d))\d{7}$/);
2679
- TZnakowy5124 = import_zod4.z.string().min(1).max(512);
2680
- TPodmiot14 = import_zod4.z.object({
2681
- "NIP": TNrNIP4,
2682
- "Nazwa": TZnakowy5124
2683
- }).strict();
2684
- TKodKraju4 = import_zod4.z.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"]);
2685
- TGLN4 = import_zod4.z.string().min(1).max(13);
2686
- TAdres4 = import_zod4.z.object({
2687
- "KodKraju": TKodKraju4,
2688
- "AdresL1": TZnakowy5124,
2689
- "AdresL2": TZnakowy5124.optional(),
2690
- "GLN": TGLN4.optional()
2691
- }).strict();
2692
- TAdresEmail4 = import_zod4.z.string().min(3).max(255).regex(/^(.)+@(.)+$/);
2693
- TNumerTelefonu4 = import_zod4.z.string().min(1).max(16);
2694
- TStatusInfoPodatnika4 = import_zod4.z.enum(["1", "2", "3", "4"]);
2695
- TZnakowy204 = import_zod4.z.string().min(1).max(20);
2696
- TNIPIdWew4 = import_zod4.z.string().min(1).max(20).regex(/^[1-9]((\d[1-9])|([1-9]\d))\d{7}-\d{5}$/);
2697
- TWybor14 = import_zod4.z.literal("1");
2698
- TPodmiot34 = import_zod4.z.object({
2699
- "NIP": TNrNIP4.optional(),
2700
- "IDWew": TNIPIdWew4.optional(),
2701
- "BrakID": TWybor14.optional(),
2702
- "Nazwa": TZnakowy5124
2703
- }).strict();
2704
- TRolaPodmiotu34 = import_zod4.z.enum(["1", "2", "3", "5", "6", "7", "8", "9", "10", "11"]);
2705
- TKodWaluty4 = import_zod4.z.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"]);
2706
- TData4 = import_zod4.z.string();
2707
- TDataT4 = import_zod4.z.string();
2708
- TKwotowy5 = import_zod4.z.string().regex(/^-?([1-9]\d{0,15}|0)(\.\d{1,2})?$/);
2709
- TRodzajFaktury4 = import_zod4.z.enum(["VAT_RR", "KOR_VAT_RR"]);
2710
- TTypKorekty4 = import_zod4.z.enum(["1", "2", "3", "4"]);
2711
- TNumerKSeF4 = import_zod4.z.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})$/);
2712
- TNaturalny4 = import_zod4.z.string();
2713
- TKluczWartosc4 = import_zod4.z.object({
2714
- "NrWiersza": TNaturalny4.optional(),
2715
- "Klucz": TZnakowy5,
2716
- "Wartosc": TZnakowy5
2717
- }).strict();
2718
- TZnakowy504 = import_zod4.z.string().min(1).max(50);
2719
- TIlosci4 = import_zod4.z.string().regex(/^-?([1-9]\d{0,15}|0)(\.\d{1,6})?$/);
2720
- TKwotowy24 = import_zod4.z.string().regex(/^-?([1-9]\d{0,13}|0)(\.\d{1,8})?$/);
2721
- TProcentowy4 = import_zod4.z.coerce.number().min(0).max(100);
2722
- TStawkaPodatku4 = import_zod4.z.enum(["6.5", "7"]);
2723
- TFormaPlatnosci4 = import_zod4.z.literal("1");
2724
- TNrRB4 = import_zod4.z.string().min(10).max(34);
2725
- SWIFT_Type4 = import_zod4.z.string().regex(/^[A-Z]{6}[A-Z0-9]{2}([A-Z0-9]{3}){0,1}$/);
2726
- TRachunekBankowy4 = import_zod4.z.object({
2727
- "NrRB": TNrRB4,
2728
- "SWIFT": SWIFT_Type4.optional(),
2729
- "NazwaBanku": TZnakowy5.optional(),
2730
- "OpisRachunku": TZnakowy5.optional()
2731
- }).strict();
2732
- TTekstowy4 = import_zod4.z.string().min(1).max(3500);
2733
- TNrKRS4 = import_zod4.z.string().regex(/^\d{10}$/);
2734
- TNrREGON4 = import_zod4.z.union([import_zod4.z.string().regex(/^\d{9}$/), import_zod4.z.string().regex(/^\d{14}$/)]);
2735
- RR1_V10ESchema = import_zod4.z.object({
2736
- "Naglowek": TNaglowek4,
2737
- "Podmiot1": import_zod4.z.object({
2738
- "DaneIdentyfikacyjne": TPodmiot14,
2739
- "Adres": TAdres4,
2740
- "AdresKoresp": TAdres4.optional(),
2741
- "DaneKontaktowe": import_zod4.z.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], import_zod4.z.array(import_zod4.z.object({
2742
- "Email": TAdresEmail4.optional(),
2743
- "Telefon": TNumerTelefonu4.optional()
2744
- }).strict()).min(0).max(3)).optional(),
2745
- "NrKontrahenta": TZnakowy5.optional()
2746
- }).strict(),
2747
- "Podmiot2": import_zod4.z.object({
2748
- "DaneIdentyfikacyjne": TPodmiot14,
2749
- "Adres": TAdres4,
2750
- "AdresKoresp": TAdres4.optional(),
2751
- "DaneKontaktowe": import_zod4.z.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], import_zod4.z.array(import_zod4.z.object({
2752
- "Email": TAdresEmail4.optional(),
2753
- "Telefon": TNumerTelefonu4.optional()
2754
- }).strict()).min(0).max(3)).optional(),
2755
- "StatusInfoPodatnika": TStatusInfoPodatnika4.optional()
2756
- }).strict(),
2757
- "Podmiot3": import_zod4.z.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], import_zod4.z.array(import_zod4.z.object({
2758
- "DaneIdentyfikacyjne": TPodmiot34,
2759
- "Adres": TAdres4.optional(),
2760
- "AdresKoresp": TAdres4.optional(),
2761
- "DaneKontaktowe": import_zod4.z.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], import_zod4.z.array(import_zod4.z.object({
2762
- "Email": TAdresEmail4.optional(),
2763
- "Telefon": TNumerTelefonu4.optional()
2764
- }).strict()).min(0).max(3)).optional(),
2765
- "Rola": TRolaPodmiotu34.optional(),
2766
- "RolaInna": TWybor14.optional(),
2767
- "OpisRoli": TZnakowy5.optional()
2768
- }).strict()).min(0).max(100)).optional(),
2769
- "FakturaRR": import_zod4.z.object({
2770
- "KodWaluty": TKodWaluty4,
2771
- "P_1M": TZnakowy5.optional(),
2772
- "P_4A": TDataT4.optional(),
2773
- "P_4B": TDataT4,
2774
- "P_4C": TZnakowy5,
2775
- "P_11_1": TKwotowy5,
2776
- "P_11_1W": TKwotowy5.optional(),
2777
- "P_11_2": TKwotowy5,
2778
- "P_11_2W": TKwotowy5.optional(),
2779
- "P_12_1": TKwotowy5,
2780
- "P_12_1W": TKwotowy5.optional(),
2781
- "P_12_2": TZnakowy5,
2782
- "RodzajFaktury": TRodzajFaktury4,
2783
- "PrzyczynaKorekty": TZnakowy5.optional(),
2784
- "TypKorekty": TTypKorekty4.optional(),
2785
- "DaneFaKorygowanej": import_zod4.z.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], import_zod4.z.array(import_zod4.z.object({
2786
- "DataWystFaKorygowanej": TDataT4,
2787
- "NrFaKorygowanej": TZnakowy5,
2788
- "NrKSeF": TWybor14.optional(),
2789
- "NrKSeFFaKorygowanej": TNumerKSeF4.optional(),
2790
- "NrKSeFN": TWybor14.optional()
2791
- }).strict()).min(1).max(5e4)).optional(),
2792
- "NrFaKorygowany": TZnakowy5.optional(),
2793
- "Podmiot1K": import_zod4.z.object({
2794
- "DaneIdentyfikacyjne": TPodmiot14,
2795
- "Adres": TAdres4
2796
- }).strict().optional(),
2797
- "Podmiot2K": import_zod4.z.object({
2798
- "DaneIdentyfikacyjne": TPodmiot14,
2799
- "Adres": TAdres4
2800
- }).strict().optional(),
2801
- "DokumentZaplaty": import_zod4.z.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], import_zod4.z.array(import_zod4.z.object({
2802
- "NrDokumentu": TZnakowy5,
2803
- "DataDokumentu": TData4.optional()
2804
- }).strict()).min(0).max(50)).optional(),
2805
- "DodatkowyOpis": import_zod4.z.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], import_zod4.z.array(TKluczWartosc4).min(0).max(1e4)).optional(),
2806
- "FakturaRRWiersz": import_zod4.z.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], import_zod4.z.array(import_zod4.z.object({
2807
- "NrWierszaFa": TNaturalny4,
2808
- "UU_ID": TZnakowy504.optional(),
2809
- "P_4AA": TDataT4.optional(),
2810
- "P_5": TZnakowy5,
2811
- "GTIN": TZnakowy204.optional(),
2812
- "PKWiU": TZnakowy504.optional(),
2813
- "CN": TZnakowy504.optional(),
2814
- "P_6A": TZnakowy5,
2815
- "P_6B": TIlosci4,
2816
- "P_6C": TZnakowy5,
2817
- "P_7": TKwotowy24,
2818
- "P_8": TKwotowy5,
2819
- "P_9": TStawkaPodatku4,
2820
- "P_10": TKwotowy5,
2821
- "P_11": TKwotowy5,
2822
- "StanPrzed": TWybor14.optional(),
2823
- "KursWaluty": TIlosci4.optional()
2824
- }).strict()).min(0).max(1e4)).optional(),
2825
- "Rozliczenie": import_zod4.z.object({
2826
- "Obciazenia": import_zod4.z.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], import_zod4.z.array(import_zod4.z.object({
2827
- "Kwota": TKwotowy5,
2828
- "Powod": TZnakowy5
2829
- }).strict()).min(0).max(100)).optional(),
2830
- "SumaObciazen": TKwotowy5.optional(),
2831
- "Odliczenia": import_zod4.z.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], import_zod4.z.array(import_zod4.z.object({
2832
- "Kwota": TKwotowy5,
2833
- "Powod": TZnakowy5
2834
- }).strict()).min(0).max(100)).optional(),
2835
- "SumaOdliczen": TKwotowy5.optional(),
2836
- "DoZaplaty": TKwotowy5.optional(),
2837
- "DoRozliczenia": TKwotowy5.optional()
2838
- }).strict().optional(),
2839
- "Platnosc": import_zod4.z.object({
2840
- "FormaPlatnosci": TFormaPlatnosci4.optional(),
2841
- "PlatnoscInna": TWybor14.optional(),
2842
- "OpisPlatnosci": TZnakowy5.optional(),
2843
- "RachunekBankowy1": import_zod4.z.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], import_zod4.z.array(TRachunekBankowy4).min(0).max(3)).optional(),
2844
- "RachunekBankowy2": import_zod4.z.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], import_zod4.z.array(TRachunekBankowy4).min(0).max(3)).optional(),
2845
- "IPKSeF": import_zod4.z.string().min(1).max(13).regex(/^[0-9]{3}[a-zA-Z0-9]{10}$/).optional(),
2846
- "LinkDoPlatnosci": import_zod4.z.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()
2847
- }).strict().optional()
2848
- }).strict(),
2849
- "Stopka": import_zod4.z.object({
2850
- "Informacje": import_zod4.z.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], import_zod4.z.array(import_zod4.z.object({
2851
- "StopkaFaktury": TTekstowy4.optional()
2852
- }).strict()).min(0).max(3)).optional(),
2853
- "Rejestry": import_zod4.z.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], import_zod4.z.array(import_zod4.z.object({
2854
- "PelnaNazwa": TZnakowy5.optional(),
2855
- "KRS": TNrKRS4.optional(),
2856
- "REGON": TNrREGON4.optional(),
2857
- "BDO": import_zod4.z.string().min(1).max(9).optional()
2858
- }).strict()).min(0).max(100)).optional()
2859
- }).strict().optional()
2754
+ InvoiceType = import_zod4.z.object({
2755
+ "UBLExtensions": import_zod4.z.any().optional(),
2756
+ "UBLVersionID": import_zod4.z.any().optional(),
2757
+ "CustomizationID": import_zod4.z.any().optional(),
2758
+ "ProfileID": import_zod4.z.any().optional(),
2759
+ "ProfileExecutionID": import_zod4.z.any().optional(),
2760
+ "ID": import_zod4.z.any(),
2761
+ "CopyIndicator": import_zod4.z.any().optional(),
2762
+ "UUID": import_zod4.z.any().optional(),
2763
+ "IssueDate": import_zod4.z.any(),
2764
+ "IssueTime": import_zod4.z.any().optional(),
2765
+ "DueDate": import_zod4.z.any().optional(),
2766
+ "InvoiceTypeCode": import_zod4.z.any().optional(),
2767
+ "Note": import_zod4.z.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], import_zod4.z.array(import_zod4.z.any()).min(0)).optional(),
2768
+ "TaxPointDate": import_zod4.z.any().optional(),
2769
+ "DocumentCurrencyCode": import_zod4.z.any().optional(),
2770
+ "TaxCurrencyCode": import_zod4.z.any().optional(),
2771
+ "PricingCurrencyCode": import_zod4.z.any().optional(),
2772
+ "PaymentCurrencyCode": import_zod4.z.any().optional(),
2773
+ "PaymentAlternativeCurrencyCode": import_zod4.z.any().optional(),
2774
+ "AccountingCostCode": import_zod4.z.any().optional(),
2775
+ "AccountingCost": import_zod4.z.any().optional(),
2776
+ "LineCountNumeric": import_zod4.z.any().optional(),
2777
+ "BuyerReference": import_zod4.z.any().optional(),
2778
+ "InvoicePeriod": import_zod4.z.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], import_zod4.z.array(import_zod4.z.any()).min(0)).optional(),
2779
+ "OrderReference": import_zod4.z.any().optional(),
2780
+ "BillingReference": import_zod4.z.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], import_zod4.z.array(import_zod4.z.any()).min(0)).optional(),
2781
+ "DespatchDocumentReference": import_zod4.z.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], import_zod4.z.array(import_zod4.z.any()).min(0)).optional(),
2782
+ "ReceiptDocumentReference": import_zod4.z.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], import_zod4.z.array(import_zod4.z.any()).min(0)).optional(),
2783
+ "StatementDocumentReference": import_zod4.z.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], import_zod4.z.array(import_zod4.z.any()).min(0)).optional(),
2784
+ "OriginatorDocumentReference": import_zod4.z.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], import_zod4.z.array(import_zod4.z.any()).min(0)).optional(),
2785
+ "ContractDocumentReference": import_zod4.z.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], import_zod4.z.array(import_zod4.z.any()).min(0)).optional(),
2786
+ "AdditionalDocumentReference": import_zod4.z.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], import_zod4.z.array(import_zod4.z.any()).min(0)).optional(),
2787
+ "ProjectReference": import_zod4.z.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], import_zod4.z.array(import_zod4.z.any()).min(0)).optional(),
2788
+ "Signature": import_zod4.z.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], import_zod4.z.array(import_zod4.z.any()).min(0)).optional(),
2789
+ "AccountingSupplierParty": import_zod4.z.any(),
2790
+ "AccountingCustomerParty": import_zod4.z.any(),
2791
+ "PayeeParty": import_zod4.z.any().optional(),
2792
+ "BuyerCustomerParty": import_zod4.z.any().optional(),
2793
+ "SellerSupplierParty": import_zod4.z.any().optional(),
2794
+ "TaxRepresentativeParty": import_zod4.z.any().optional(),
2795
+ "Delivery": import_zod4.z.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], import_zod4.z.array(import_zod4.z.any()).min(0)).optional(),
2796
+ "DeliveryTerms": import_zod4.z.any().optional(),
2797
+ "PaymentMeans": import_zod4.z.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], import_zod4.z.array(import_zod4.z.any()).min(0)).optional(),
2798
+ "PaymentTerms": import_zod4.z.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], import_zod4.z.array(import_zod4.z.any()).min(0)).optional(),
2799
+ "PrepaidPayment": import_zod4.z.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], import_zod4.z.array(import_zod4.z.any()).min(0)).optional(),
2800
+ "AllowanceCharge": import_zod4.z.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], import_zod4.z.array(import_zod4.z.any()).min(0)).optional(),
2801
+ "TaxExchangeRate": import_zod4.z.any().optional(),
2802
+ "PricingExchangeRate": import_zod4.z.any().optional(),
2803
+ "PaymentExchangeRate": import_zod4.z.any().optional(),
2804
+ "PaymentAlternativeExchangeRate": import_zod4.z.any().optional(),
2805
+ "TaxTotal": import_zod4.z.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], import_zod4.z.array(import_zod4.z.any()).min(0)).optional(),
2806
+ "WithholdingTaxTotal": import_zod4.z.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], import_zod4.z.array(import_zod4.z.any()).min(0)).optional(),
2807
+ "LegalMonetaryTotal": import_zod4.z.any(),
2808
+ "InvoiceLine": import_zod4.z.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], import_zod4.z.array(import_zod4.z.any()).min(1))
2860
2809
  }).strict();
2810
+ PEF3Schema = InvoiceType;
2861
2811
  }
2862
2812
  });
2863
2813
 
2864
- // src/validation/schemas/pef3.ts
2865
- var pef3_exports = {};
2866
- __export(pef3_exports, {
2867
- PEF3Schema: () => PEF3Schema
2814
+ // src/validation/schemas/pef-kor3.ts
2815
+ var pef_kor3_exports = {};
2816
+ __export(pef_kor3_exports, {
2817
+ PEF_KOR3Schema: () => PEF_KOR3Schema
2868
2818
  });
2869
- var import_zod5, InvoiceType, PEF3Schema;
2870
- var init_pef3 = __esm({
2871
- "src/validation/schemas/pef3.ts"() {
2819
+ var import_zod5, CreditNoteType, PEF_KOR3Schema;
2820
+ var init_pef_kor3 = __esm({
2821
+ "src/validation/schemas/pef-kor3.ts"() {
2872
2822
  "use strict";
2873
2823
  init_cjs_shims();
2874
2824
  import_zod5 = require("zod");
2875
- InvoiceType = import_zod5.z.object({
2825
+ CreditNoteType = import_zod5.z.object({
2876
2826
  "UBLExtensions": import_zod5.z.any().optional(),
2877
2827
  "UBLVersionID": import_zod5.z.any().optional(),
2878
2828
  "CustomizationID": import_zod5.z.any().optional(),
@@ -2883,10 +2833,9 @@ var init_pef3 = __esm({
2883
2833
  "UUID": import_zod5.z.any().optional(),
2884
2834
  "IssueDate": import_zod5.z.any(),
2885
2835
  "IssueTime": import_zod5.z.any().optional(),
2886
- "DueDate": import_zod5.z.any().optional(),
2887
- "InvoiceTypeCode": import_zod5.z.any().optional(),
2888
- "Note": import_zod5.z.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], import_zod5.z.array(import_zod5.z.any()).min(0)).optional(),
2889
2836
  "TaxPointDate": import_zod5.z.any().optional(),
2837
+ "CreditNoteTypeCode": import_zod5.z.any().optional(),
2838
+ "Note": import_zod5.z.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], import_zod5.z.array(import_zod5.z.any()).min(0)).optional(),
2890
2839
  "DocumentCurrencyCode": import_zod5.z.any().optional(),
2891
2840
  "TaxCurrencyCode": import_zod5.z.any().optional(),
2892
2841
  "PricingCurrencyCode": import_zod5.z.any().optional(),
@@ -2897,15 +2846,15 @@ var init_pef3 = __esm({
2897
2846
  "LineCountNumeric": import_zod5.z.any().optional(),
2898
2847
  "BuyerReference": import_zod5.z.any().optional(),
2899
2848
  "InvoicePeriod": import_zod5.z.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], import_zod5.z.array(import_zod5.z.any()).min(0)).optional(),
2849
+ "DiscrepancyResponse": import_zod5.z.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], import_zod5.z.array(import_zod5.z.any()).min(0)).optional(),
2900
2850
  "OrderReference": import_zod5.z.any().optional(),
2901
2851
  "BillingReference": import_zod5.z.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], import_zod5.z.array(import_zod5.z.any()).min(0)).optional(),
2902
2852
  "DespatchDocumentReference": import_zod5.z.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], import_zod5.z.array(import_zod5.z.any()).min(0)).optional(),
2903
2853
  "ReceiptDocumentReference": import_zod5.z.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], import_zod5.z.array(import_zod5.z.any()).min(0)).optional(),
2904
- "StatementDocumentReference": import_zod5.z.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], import_zod5.z.array(import_zod5.z.any()).min(0)).optional(),
2905
- "OriginatorDocumentReference": import_zod5.z.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], import_zod5.z.array(import_zod5.z.any()).min(0)).optional(),
2906
2854
  "ContractDocumentReference": import_zod5.z.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], import_zod5.z.array(import_zod5.z.any()).min(0)).optional(),
2907
2855
  "AdditionalDocumentReference": import_zod5.z.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], import_zod5.z.array(import_zod5.z.any()).min(0)).optional(),
2908
- "ProjectReference": import_zod5.z.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], import_zod5.z.array(import_zod5.z.any()).min(0)).optional(),
2856
+ "StatementDocumentReference": import_zod5.z.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], import_zod5.z.array(import_zod5.z.any()).min(0)).optional(),
2857
+ "OriginatorDocumentReference": import_zod5.z.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], import_zod5.z.array(import_zod5.z.any()).min(0)).optional(),
2909
2858
  "Signature": import_zod5.z.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], import_zod5.z.array(import_zod5.z.any()).min(0)).optional(),
2910
2859
  "AccountingSupplierParty": import_zod5.z.any(),
2911
2860
  "AccountingCustomerParty": import_zod5.z.any(),
@@ -2914,87 +2863,17 @@ var init_pef3 = __esm({
2914
2863
  "SellerSupplierParty": import_zod5.z.any().optional(),
2915
2864
  "TaxRepresentativeParty": import_zod5.z.any().optional(),
2916
2865
  "Delivery": import_zod5.z.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], import_zod5.z.array(import_zod5.z.any()).min(0)).optional(),
2917
- "DeliveryTerms": import_zod5.z.any().optional(),
2866
+ "DeliveryTerms": import_zod5.z.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], import_zod5.z.array(import_zod5.z.any()).min(0)).optional(),
2918
2867
  "PaymentMeans": import_zod5.z.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], import_zod5.z.array(import_zod5.z.any()).min(0)).optional(),
2919
2868
  "PaymentTerms": import_zod5.z.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], import_zod5.z.array(import_zod5.z.any()).min(0)).optional(),
2920
- "PrepaidPayment": import_zod5.z.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], import_zod5.z.array(import_zod5.z.any()).min(0)).optional(),
2921
- "AllowanceCharge": import_zod5.z.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], import_zod5.z.array(import_zod5.z.any()).min(0)).optional(),
2922
2869
  "TaxExchangeRate": import_zod5.z.any().optional(),
2923
2870
  "PricingExchangeRate": import_zod5.z.any().optional(),
2924
2871
  "PaymentExchangeRate": import_zod5.z.any().optional(),
2925
2872
  "PaymentAlternativeExchangeRate": import_zod5.z.any().optional(),
2873
+ "AllowanceCharge": import_zod5.z.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], import_zod5.z.array(import_zod5.z.any()).min(0)).optional(),
2926
2874
  "TaxTotal": import_zod5.z.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], import_zod5.z.array(import_zod5.z.any()).min(0)).optional(),
2927
- "WithholdingTaxTotal": import_zod5.z.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], import_zod5.z.array(import_zod5.z.any()).min(0)).optional(),
2928
2875
  "LegalMonetaryTotal": import_zod5.z.any(),
2929
- "InvoiceLine": import_zod5.z.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], import_zod5.z.array(import_zod5.z.any()).min(1))
2930
- }).strict();
2931
- PEF3Schema = InvoiceType;
2932
- }
2933
- });
2934
-
2935
- // src/validation/schemas/pef-kor3.ts
2936
- var pef_kor3_exports = {};
2937
- __export(pef_kor3_exports, {
2938
- PEF_KOR3Schema: () => PEF_KOR3Schema
2939
- });
2940
- var import_zod6, CreditNoteType, PEF_KOR3Schema;
2941
- var init_pef_kor3 = __esm({
2942
- "src/validation/schemas/pef-kor3.ts"() {
2943
- "use strict";
2944
- init_cjs_shims();
2945
- import_zod6 = require("zod");
2946
- CreditNoteType = import_zod6.z.object({
2947
- "UBLExtensions": import_zod6.z.any().optional(),
2948
- "UBLVersionID": import_zod6.z.any().optional(),
2949
- "CustomizationID": import_zod6.z.any().optional(),
2950
- "ProfileID": import_zod6.z.any().optional(),
2951
- "ProfileExecutionID": import_zod6.z.any().optional(),
2952
- "ID": import_zod6.z.any(),
2953
- "CopyIndicator": import_zod6.z.any().optional(),
2954
- "UUID": import_zod6.z.any().optional(),
2955
- "IssueDate": import_zod6.z.any(),
2956
- "IssueTime": import_zod6.z.any().optional(),
2957
- "TaxPointDate": import_zod6.z.any().optional(),
2958
- "CreditNoteTypeCode": import_zod6.z.any().optional(),
2959
- "Note": import_zod6.z.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], import_zod6.z.array(import_zod6.z.any()).min(0)).optional(),
2960
- "DocumentCurrencyCode": import_zod6.z.any().optional(),
2961
- "TaxCurrencyCode": import_zod6.z.any().optional(),
2962
- "PricingCurrencyCode": import_zod6.z.any().optional(),
2963
- "PaymentCurrencyCode": import_zod6.z.any().optional(),
2964
- "PaymentAlternativeCurrencyCode": import_zod6.z.any().optional(),
2965
- "AccountingCostCode": import_zod6.z.any().optional(),
2966
- "AccountingCost": import_zod6.z.any().optional(),
2967
- "LineCountNumeric": import_zod6.z.any().optional(),
2968
- "BuyerReference": import_zod6.z.any().optional(),
2969
- "InvoicePeriod": import_zod6.z.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], import_zod6.z.array(import_zod6.z.any()).min(0)).optional(),
2970
- "DiscrepancyResponse": import_zod6.z.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], import_zod6.z.array(import_zod6.z.any()).min(0)).optional(),
2971
- "OrderReference": import_zod6.z.any().optional(),
2972
- "BillingReference": import_zod6.z.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], import_zod6.z.array(import_zod6.z.any()).min(0)).optional(),
2973
- "DespatchDocumentReference": import_zod6.z.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], import_zod6.z.array(import_zod6.z.any()).min(0)).optional(),
2974
- "ReceiptDocumentReference": import_zod6.z.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], import_zod6.z.array(import_zod6.z.any()).min(0)).optional(),
2975
- "ContractDocumentReference": import_zod6.z.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], import_zod6.z.array(import_zod6.z.any()).min(0)).optional(),
2976
- "AdditionalDocumentReference": import_zod6.z.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], import_zod6.z.array(import_zod6.z.any()).min(0)).optional(),
2977
- "StatementDocumentReference": import_zod6.z.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], import_zod6.z.array(import_zod6.z.any()).min(0)).optional(),
2978
- "OriginatorDocumentReference": import_zod6.z.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], import_zod6.z.array(import_zod6.z.any()).min(0)).optional(),
2979
- "Signature": import_zod6.z.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], import_zod6.z.array(import_zod6.z.any()).min(0)).optional(),
2980
- "AccountingSupplierParty": import_zod6.z.any(),
2981
- "AccountingCustomerParty": import_zod6.z.any(),
2982
- "PayeeParty": import_zod6.z.any().optional(),
2983
- "BuyerCustomerParty": import_zod6.z.any().optional(),
2984
- "SellerSupplierParty": import_zod6.z.any().optional(),
2985
- "TaxRepresentativeParty": import_zod6.z.any().optional(),
2986
- "Delivery": import_zod6.z.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], import_zod6.z.array(import_zod6.z.any()).min(0)).optional(),
2987
- "DeliveryTerms": import_zod6.z.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], import_zod6.z.array(import_zod6.z.any()).min(0)).optional(),
2988
- "PaymentMeans": import_zod6.z.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], import_zod6.z.array(import_zod6.z.any()).min(0)).optional(),
2989
- "PaymentTerms": import_zod6.z.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], import_zod6.z.array(import_zod6.z.any()).min(0)).optional(),
2990
- "TaxExchangeRate": import_zod6.z.any().optional(),
2991
- "PricingExchangeRate": import_zod6.z.any().optional(),
2992
- "PaymentExchangeRate": import_zod6.z.any().optional(),
2993
- "PaymentAlternativeExchangeRate": import_zod6.z.any().optional(),
2994
- "AllowanceCharge": import_zod6.z.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], import_zod6.z.array(import_zod6.z.any()).min(0)).optional(),
2995
- "TaxTotal": import_zod6.z.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], import_zod6.z.array(import_zod6.z.any()).min(0)).optional(),
2996
- "LegalMonetaryTotal": import_zod6.z.any(),
2997
- "CreditNoteLine": import_zod6.z.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], import_zod6.z.array(import_zod6.z.any()).min(1))
2876
+ "CreditNoteLine": import_zod5.z.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], import_zod5.z.array(import_zod5.z.any()).min(1))
2998
2877
  }).strict();
2999
2878
  PEF_KOR3Schema = CreditNoteType;
3000
2879
  }
@@ -3008,15 +2887,13 @@ var init_schemas = __esm({
3008
2887
  init_cjs_shims();
3009
2888
  init_fa3();
3010
2889
  init_fa2();
3011
- init_rr1_v11e();
3012
- init_rr1_v10e();
2890
+ init_fa_rr1();
3013
2891
  init_pef3();
3014
2892
  init_pef_kor3();
3015
2893
  NAMESPACE_MAP = {
3016
2894
  "http://crd.gov.pl/wzor/2025/06/25/13775/": "FA3",
3017
2895
  "http://crd.gov.pl/wzor/2023/06/29/12648/": "FA2",
3018
- "http://crd.gov.pl/wzor/2026/03/06/14189/": "RR1_V11E",
3019
- "http://crd.gov.pl/wzor/2026/02/17/14164/": "RR1_V10E",
2896
+ "http://crd.gov.pl/wzor/2026/03/06/14189/": "FA_RR1",
3020
2897
  "urn:oasis:names:specification:ubl:schema:xsd:Invoice-2": "PEF3",
3021
2898
  "urn:oasis:names:specification:ubl:schema:xsd:CreditNote-2": "PEF_KOR3"
3022
2899
  };
@@ -3035,11 +2912,8 @@ async function loadSchema(type) {
3035
2912
  case "FA2":
3036
2913
  mod = await Promise.resolve().then(() => (init_fa2(), fa2_exports));
3037
2914
  break;
3038
- case "RR1_V11E":
3039
- mod = await Promise.resolve().then(() => (init_rr1_v11e(), rr1_v11e_exports));
3040
- break;
3041
- case "RR1_V10E":
3042
- mod = await Promise.resolve().then(() => (init_rr1_v10e(), rr1_v10e_exports));
2915
+ case "FA_RR1":
2916
+ mod = await Promise.resolve().then(() => (init_fa_rr1(), fa_rr1_exports));
3043
2917
  break;
3044
2918
  case "PEF3":
3045
2919
  mod = await Promise.resolve().then(() => (init_pef3(), pef3_exports));
@@ -3080,7 +2954,7 @@ var init_schema_registry = __esm({
3080
2954
  * List all available schema types.
3081
2955
  */
3082
2956
  availableSchemas() {
3083
- return ["FA3", "FA2", "RR1_V11E", "RR1_V10E", "PEF3", "PEF_KOR3"];
2957
+ return ["FA3", "FA2", "FA_RR1", "PEF3", "PEF_KOR3"];
3084
2958
  },
3085
2959
  /**
3086
2960
  * Detect schema type from XML namespace URI and/or root element name.
@@ -4203,6 +4077,8 @@ var init_certificates = __esm({
4203
4077
  init_cjs_shims();
4204
4078
  init_rest_request();
4205
4079
  init_routes();
4080
+ init_ksef_validation_error();
4081
+ init_patterns();
4206
4082
  CertificateApiService = class {
4207
4083
  restClient;
4208
4084
  constructor(restClient) {
@@ -4229,6 +4105,14 @@ var init_certificates = __esm({
4229
4105
  return response.body;
4230
4106
  }
4231
4107
  async retrieve(request) {
4108
+ for (const serial of request.certificateSerialNumbers ?? []) {
4109
+ if (!isValidCertificateSerialNumber(serial)) {
4110
+ throw KSeFValidationError.fromField(
4111
+ "certificateSerialNumbers",
4112
+ `Invalid certificate serial number "${serial}": must be exactly 16 uppercase hex characters (^[0-9A-F]{16}$)`
4113
+ );
4114
+ }
4115
+ }
4232
4116
  const req = RestRequest.post(Routes.Certificates.retrieve).body(request);
4233
4117
  const response = await this.restClient.execute(req);
4234
4118
  return response.body;
@@ -4477,8 +4361,8 @@ var init_certificate_fetcher = __esm({
4477
4361
  init_routes();
4478
4362
  CertificateFetcher = class {
4479
4363
  restClient;
4480
- symmetricKeyPem;
4481
- ksefTokenPem;
4364
+ symmetricKey;
4365
+ ksefToken;
4482
4366
  initialized = false;
4483
4367
  constructor(restClient) {
4484
4368
  this.restClient = restClient;
@@ -4491,17 +4375,38 @@ var init_certificate_fetcher = __esm({
4491
4375
  this.initialized = false;
4492
4376
  await this.fetchCertificates();
4493
4377
  }
4378
+ /**
4379
+ * Immutable snapshot ({@link SelectedCertificate}) of the selected
4380
+ * SymmetricKeyEncryption certificate. The stored object is replaced wholesale
4381
+ * by {@link refresh}, never mutated, so holding the returned reference yields a
4382
+ * consistent pem + publicKeyId pair even if a concurrent refresh swaps the cache.
4383
+ */
4384
+ getSymmetricKeyEncryption() {
4385
+ return { ...this.requireSelected(this.symmetricKey) };
4386
+ }
4387
+ /** Immutable snapshot of the selected KsefTokenEncryption certificate. See {@link getSymmetricKeyEncryption}. */
4388
+ getKsefTokenEncryption() {
4389
+ return { ...this.requireSelected(this.ksefToken) };
4390
+ }
4494
4391
  getSymmetricKeyEncryptionPem() {
4495
- if (!this.symmetricKeyPem) {
4496
- throw new Error("CertificateFetcher not initialized. Call init() first.");
4497
- }
4498
- return this.symmetricKeyPem;
4392
+ return this.requireSelected(this.symmetricKey).pem;
4499
4393
  }
4500
4394
  getKsefTokenEncryptionPem() {
4501
- if (!this.ksefTokenPem) {
4395
+ return this.requireSelected(this.ksefToken).pem;
4396
+ }
4397
+ /** Public key identifier of the selected SymmetricKeyEncryption certificate (KSeF API v2.5.0). */
4398
+ getSymmetricKeyPublicKeyId() {
4399
+ return this.requireSelected(this.symmetricKey).publicKeyId;
4400
+ }
4401
+ /** Public key identifier of the selected KsefTokenEncryption certificate (KSeF API v2.5.0). */
4402
+ getKsefTokenPublicKeyId() {
4403
+ return this.requireSelected(this.ksefToken).publicKeyId;
4404
+ }
4405
+ requireSelected(selected) {
4406
+ if (!selected) {
4502
4407
  throw new Error("CertificateFetcher not initialized. Call init() first.");
4503
4408
  }
4504
- return this.ksefTokenPem;
4409
+ return selected;
4505
4410
  }
4506
4411
  async fetchCertificates() {
4507
4412
  const request = RestRequest.get(Routes.Security.publicKeyCertificates);
@@ -4510,19 +4415,27 @@ var init_certificate_fetcher = __esm({
4510
4415
  if (!certs || certs.length === 0) {
4511
4416
  throw new Error("No public key certificates returned from KSeF API.");
4512
4417
  }
4513
- const symmetricCert = certs.find((c) => c.usage.includes("SymmetricKeyEncryption"));
4514
- if (!symmetricCert) {
4515
- throw new Error("No SymmetricKeyEncryption certificate found.");
4516
- }
4517
- this.symmetricKeyPem = this.derBase64ToPem(symmetricCert.certificate);
4518
- const tokenCerts = certs.filter((c) => c.usage.includes("KsefTokenEncryption")).sort((a, b) => a.validFrom.localeCompare(b.validFrom));
4519
- const tokenCert = tokenCerts[0];
4520
- if (!tokenCert) {
4521
- throw new Error("No KsefTokenEncryption certificate found.");
4522
- }
4523
- this.ksefTokenPem = this.derBase64ToPem(tokenCert.certificate);
4418
+ this.symmetricKey = this.select(certs, "SymmetricKeyEncryption");
4419
+ this.ksefToken = this.select(certs, "KsefTokenEncryption");
4524
4420
  this.initialized = true;
4525
4421
  }
4422
+ /**
4423
+ * Select the certificate to use for a given usage under key rotation:
4424
+ * filter to currently-valid certificates (validFrom ≤ now < validTo) and pick
4425
+ * the newest by validFrom. If none are currently valid, fall back to the newest
4426
+ * overall so the server can reject it with a clear error rather than sending nothing.
4427
+ */
4428
+ select(certs, usage) {
4429
+ const candidates = certs.filter((c) => c.usage.includes(usage));
4430
+ if (candidates.length === 0) {
4431
+ throw new Error(`No ${usage} certificate found.`);
4432
+ }
4433
+ const now = Date.now();
4434
+ const byNewestValidFrom = (a, b) => Date.parse(b.validFrom) - Date.parse(a.validFrom);
4435
+ const valid = candidates.filter((c) => Date.parse(c.validFrom) <= now && now < Date.parse(c.validTo)).sort(byNewestValidFrom);
4436
+ const chosen = valid[0] ?? [...candidates].sort(byNewestValidFrom)[0];
4437
+ return { pem: this.derBase64ToPem(chosen.certificate), publicKeyId: chosen.publicKeyId };
4438
+ }
4526
4439
  derBase64ToPem(base64Der) {
4527
4440
  const lines = [];
4528
4441
  for (let i = 0; i < base64Der.length; i += 64) {
@@ -4578,6 +4491,14 @@ var init_cryptography_service = __esm({
4578
4491
  async init() {
4579
4492
  await this.fetcher.init();
4580
4493
  }
4494
+ /** Re-fetch KSeF public certificates, discarding the cached selection (used for key-rotation recovery). */
4495
+ async refresh() {
4496
+ await this.fetcher.refresh();
4497
+ }
4498
+ /** Identifier of the KsefTokenEncryption public key used by {@link encryptKsefToken} (KSeF API v2.5.0). */
4499
+ getKsefTokenPublicKeyId() {
4500
+ return this.fetcher.getKsefTokenPublicKeyId();
4501
+ }
4581
4502
  // ---------------------------------------------------------------------------
4582
4503
  // AES-256-CBC
4583
4504
  // ---------------------------------------------------------------------------
@@ -4623,11 +4544,12 @@ var init_cryptography_service = __esm({
4623
4544
  async getEncryptionData() {
4624
4545
  const key = crypto2.randomBytes(32);
4625
4546
  const iv = crypto2.randomBytes(16);
4626
- const certPem = this.fetcher.getSymmetricKeyEncryptionPem();
4627
- const encryptedKey = await this.rsaOaepEncrypt(certPem, new Uint8Array(key));
4547
+ const cert = this.fetcher.getSymmetricKeyEncryption();
4548
+ const encryptedKey = await this.rsaOaepEncrypt(cert.pem, new Uint8Array(key));
4628
4549
  const encryptionInfo = {
4629
4550
  encryptedSymmetricKey: Buffer.from(encryptedKey).toString("base64"),
4630
- initializationVector: iv.toString("base64")
4551
+ initializationVector: iv.toString("base64"),
4552
+ publicKeyId: cert.publicKeyId
4631
4553
  };
4632
4554
  return {
4633
4555
  cipherKey: new Uint8Array(key),
@@ -4652,9 +4574,29 @@ var init_cryptography_service = __esm({
4652
4574
  * `[ephemeralSPKI | nonce(12) | ciphertext+tag]`.
4653
4575
  */
4654
4576
  async encryptKsefToken(token, challengeTimestamp) {
4577
+ return this.encryptKsefTokenWithCertPem(
4578
+ this.fetcher.getKsefTokenEncryptionPem(),
4579
+ token,
4580
+ challengeTimestamp
4581
+ );
4582
+ }
4583
+ /**
4584
+ * Encrypt a KSeF token and return it together with the public key id of the
4585
+ * exact certificate used.
4586
+ *
4587
+ * Both values come from a single certificate snapshot taken before any
4588
+ * `await`, so a concurrent {@link refresh} cannot tag the ciphertext with a
4589
+ * different key than it was encrypted under (KSeF API v2.5.0). Prefer this over
4590
+ * pairing {@link encryptKsefToken} with a separate {@link getKsefTokenPublicKeyId}.
4591
+ */
4592
+ async encryptKsefTokenWithKeyId(token, challengeTimestamp) {
4593
+ const cert = this.fetcher.getKsefTokenEncryption();
4594
+ const encryptedToken = await this.encryptKsefTokenWithCertPem(cert.pem, token, challengeTimestamp);
4595
+ return { encryptedToken, publicKeyId: cert.publicKeyId };
4596
+ }
4597
+ async encryptKsefTokenWithCertPem(certPem, token, challengeTimestamp) {
4655
4598
  const timestampMs = new Date(challengeTimestamp).getTime();
4656
4599
  const plaintext = Buffer.from(`${token}|${timestampMs}`, "utf-8");
4657
- const certPem = this.fetcher.getKsefTokenEncryptionPem();
4658
4600
  const cert = new crypto2.X509Certificate(certPem);
4659
4601
  const publicKey = cert.publicKey;
4660
4602
  if (publicKey.asymmetricKeyType === "rsa") {
@@ -5173,7 +5115,7 @@ var init_auth_xml_builder = __esm({
5173
5115
  "src/crypto/auth-xml-builder.ts"() {
5174
5116
  "use strict";
5175
5117
  init_cjs_shims();
5176
- AUTH_TOKEN_REQUEST_NS = "http://ksef.mf.gov.pl/auth/token/2.0";
5118
+ AUTH_TOKEN_REQUEST_NS = "http://ksef.mf.gov.pl/auth/token/2.1";
5177
5119
  }
5178
5120
  });
5179
5121
 
@@ -5335,6 +5277,156 @@ var init_zip = __esm({
5335
5277
  }
5336
5278
  });
5337
5279
 
5280
+ // src/utils/targz.ts
5281
+ var targz_exports = {};
5282
+ __export(targz_exports, {
5283
+ createTarGz: () => createTarGz,
5284
+ extractTarGz: () => extractTarGz
5285
+ });
5286
+ async function createTarGz(entries) {
5287
+ const packer = (0, import_tar_stream.pack)();
5288
+ const gzip = packer.pipe((0, import_node_zlib.createGzip)());
5289
+ const chunks = [];
5290
+ return new Promise((resolve, reject) => {
5291
+ let settled = false;
5292
+ const fail = (err) => {
5293
+ if (settled) return;
5294
+ settled = true;
5295
+ reject(err);
5296
+ };
5297
+ packer.on("error", fail);
5298
+ gzip.on("error", fail);
5299
+ gzip.on("data", (chunk) => chunks.push(chunk));
5300
+ gzip.on("end", () => {
5301
+ if (settled) return;
5302
+ settled = true;
5303
+ resolve(Buffer.concat(chunks));
5304
+ });
5305
+ try {
5306
+ for (const entry of entries) {
5307
+ const content = Buffer.from(entry.content);
5308
+ packer.entry({ name: entry.fileName, size: content.length }, content);
5309
+ }
5310
+ packer.finalize();
5311
+ } catch (err) {
5312
+ fail(err instanceof Error ? err : new Error(String(err)));
5313
+ }
5314
+ });
5315
+ }
5316
+ async function extractTarGz(buffer, options = {}) {
5317
+ const limits = { ...DEFAULT_LIMITS, ...options };
5318
+ const ratioCeiling = limits.maxCompressionRatio !== null && limits.maxCompressionRatio !== void 0 && buffer.length > 0 ? buffer.length * limits.maxCompressionRatio : null;
5319
+ return new Promise((resolve, reject) => {
5320
+ const source = import_node_stream.Readable.from(buffer);
5321
+ const gunzip = (0, import_node_zlib.createGunzip)();
5322
+ const extractor = (0, import_tar_stream.extract)();
5323
+ const files = /* @__PURE__ */ new Map();
5324
+ let extractedFileCount = 0;
5325
+ let totalUncompressed = 0;
5326
+ let settled = false;
5327
+ const cleanup = () => {
5328
+ source.destroy();
5329
+ gunzip.destroy();
5330
+ extractor.destroy();
5331
+ };
5332
+ const fail = (err) => {
5333
+ if (settled) return;
5334
+ settled = true;
5335
+ cleanup();
5336
+ reject(err);
5337
+ };
5338
+ const succeed = () => {
5339
+ if (settled) return;
5340
+ settled = true;
5341
+ resolve(files);
5342
+ };
5343
+ gunzip.on("data", (chunk) => {
5344
+ totalUncompressed += chunk.length;
5345
+ if (limits.maxTotalUncompressedSize > 0 && totalUncompressed > limits.maxTotalUncompressedSize) {
5346
+ fail(new Error("tar.gz exceeds max_total_uncompressed_size"));
5347
+ return;
5348
+ }
5349
+ if (ratioCeiling !== null && totalUncompressed > ratioCeiling) {
5350
+ fail(new Error("tar.gz exceeds max_compression_ratio"));
5351
+ }
5352
+ });
5353
+ extractor.on("entry", (header, stream, next) => {
5354
+ if (settled) {
5355
+ stream.resume();
5356
+ return;
5357
+ }
5358
+ if (header.type !== "file") {
5359
+ stream.resume();
5360
+ stream.on("end", next);
5361
+ return;
5362
+ }
5363
+ if (limits.maxFiles > 0 && extractedFileCount >= limits.maxFiles) {
5364
+ fail(new Error("tar.gz contains too many files"));
5365
+ return;
5366
+ }
5367
+ const chunks = [];
5368
+ let entrySize = 0;
5369
+ stream.on("data", (chunk) => {
5370
+ if (settled) return;
5371
+ entrySize += chunk.length;
5372
+ if (limits.maxFileUncompressedSize > 0 && entrySize > limits.maxFileUncompressedSize) {
5373
+ fail(new Error("tar.gz entry exceeds max_file_uncompressed_size"));
5374
+ return;
5375
+ }
5376
+ chunks.push(chunk);
5377
+ });
5378
+ stream.on("error", fail);
5379
+ stream.on("end", () => {
5380
+ if (settled) return;
5381
+ extractedFileCount += 1;
5382
+ files.set(header.name, Buffer.concat(chunks));
5383
+ next();
5384
+ });
5385
+ });
5386
+ extractor.on("finish", succeed);
5387
+ extractor.on("error", fail);
5388
+ gunzip.on("error", fail);
5389
+ source.on("error", fail);
5390
+ source.pipe(gunzip).pipe(extractor);
5391
+ });
5392
+ }
5393
+ var import_node_zlib, import_node_stream, import_tar_stream, DEFAULT_LIMITS;
5394
+ var init_targz = __esm({
5395
+ "src/utils/targz.ts"() {
5396
+ "use strict";
5397
+ init_cjs_shims();
5398
+ import_node_zlib = require("node:zlib");
5399
+ import_node_stream = require("node:stream");
5400
+ import_tar_stream = require("tar-stream");
5401
+ DEFAULT_LIMITS = {
5402
+ maxFiles: 1e4,
5403
+ maxTotalUncompressedSize: 2e9,
5404
+ maxFileUncompressedSize: 5e8,
5405
+ maxCompressionRatio: 200
5406
+ };
5407
+ }
5408
+ });
5409
+
5410
+ // src/crypto/with-key-rotation-retry.ts
5411
+ async function withKeyRotationRetry(crypto8, op) {
5412
+ try {
5413
+ return await op();
5414
+ } catch (err) {
5415
+ if (err instanceof KSeFUnknownPublicKeyError) {
5416
+ await crypto8.refresh();
5417
+ return await op();
5418
+ }
5419
+ throw err;
5420
+ }
5421
+ }
5422
+ var init_with_key_rotation_retry = __esm({
5423
+ "src/crypto/with-key-rotation-retry.ts"() {
5424
+ "use strict";
5425
+ init_cjs_shims();
5426
+ init_ksef_unknown_public_key_error();
5427
+ }
5428
+ });
5429
+
5338
5430
  // src/offline/holidays.ts
5339
5431
  function toDateKey(d) {
5340
5432
  return d.toISOString().slice(0, 10);
@@ -5512,6 +5604,7 @@ var init_offline_invoice_workflow = __esm({
5512
5604
  import_node_crypto3 = __toESM(require("node:crypto"), 1);
5513
5605
  init_ksef_api_error();
5514
5606
  init_deadline();
5607
+ init_with_key_rotation_retry();
5515
5608
  init_document_structures();
5516
5609
  OfflineInvoiceWorkflow = class {
5517
5610
  constructor(qrService) {
@@ -5618,11 +5711,14 @@ var init_offline_invoice_workflow = __esm({
5618
5711
  }
5619
5712
  if (pending.length === 0) return result;
5620
5713
  await client.crypto.init();
5621
- const encData = await client.crypto.getEncryptionData();
5622
5714
  const formCode = options.formCode ?? DEFAULT_FORM_CODE;
5623
- const openResp = await client.onlineSession.openSession(
5624
- { formCode, encryption: encData.encryptionInfo }
5625
- );
5715
+ const { encData, openResp } = await withKeyRotationRetry(client.crypto, async () => {
5716
+ const encData2 = await client.crypto.getEncryptionData();
5717
+ const openResp2 = await client.onlineSession.openSession(
5718
+ { formCode, encryption: encData2.encryptionInfo }
5719
+ );
5720
+ return { encData: encData2, openResp: openResp2 };
5721
+ });
5626
5722
  const sessionRef = openResp.referenceNumber;
5627
5723
  try {
5628
5724
  for (const inv of pending) {
@@ -5707,11 +5803,14 @@ var init_offline_invoice_workflow = __esm({
5707
5803
  }
5708
5804
  const originalHash = import_node_crypto3.default.createHash("sha256").update(original.invoiceXml).digest("base64");
5709
5805
  await client.crypto.init();
5710
- const encData = await client.crypto.getEncryptionData();
5711
5806
  const formCode = options.formCode ?? DEFAULT_FORM_CODE;
5712
- const openResp = await client.onlineSession.openSession(
5713
- { formCode, encryption: encData.encryptionInfo }
5714
- );
5807
+ const { encData, openResp } = await withKeyRotationRetry(client.crypto, async () => {
5808
+ const encData2 = await client.crypto.getEncryptionData();
5809
+ const openResp2 = await client.onlineSession.openSession(
5810
+ { formCode, encryption: encData2.encryptionInfo }
5811
+ );
5812
+ return { encData: encData2, openResp: openResp2 };
5813
+ });
5715
5814
  const sessionRef = openResp.referenceNumber;
5716
5815
  try {
5717
5816
  const data = new TextEncoder().encode(correctedInvoiceXml);
@@ -5833,6 +5932,9 @@ function buildRestClientConfig(options, authManager) {
5833
5932
  allowedHosts: [...base.allowedHosts, ...options.presignedUrlHosts]
5834
5933
  };
5835
5934
  }
5935
+ if (options?.onSystemWarning) {
5936
+ config.onSystemWarning = options.onSystemWarning;
5937
+ }
5836
5938
  return config;
5837
5939
  }
5838
5940
  var KSeFClient;
@@ -5862,6 +5964,7 @@ var init_client = __esm({
5862
5964
  init_test_data();
5863
5965
  init_certificate_fetcher();
5864
5966
  init_cryptography_service();
5967
+ init_with_key_rotation_retry();
5865
5968
  init_verification_link_service();
5866
5969
  init_auth_xml_builder();
5867
5970
  init_offline_invoice_workflow();
@@ -5928,11 +6031,14 @@ var init_client = __esm({
5928
6031
  async loginWithToken(token, nip) {
5929
6032
  const challenge = await this.auth.getChallenge();
5930
6033
  await this.crypto.init();
5931
- const encryptedToken = await this.crypto.encryptKsefToken(token, challenge.timestamp);
5932
- const submitResult = await this.auth.submitKsefTokenAuthRequest({
5933
- challenge: challenge.challenge,
5934
- contextIdentifier: { type: "Nip", value: nip },
5935
- encryptedToken: Buffer.from(encryptedToken).toString("base64")
6034
+ const submitResult = await withKeyRotationRetry(this.crypto, async () => {
6035
+ const { encryptedToken, publicKeyId } = await this.crypto.encryptKsefTokenWithKeyId(token, challenge.timestamp);
6036
+ return this.auth.submitKsefTokenAuthRequest({
6037
+ challenge: challenge.challenge,
6038
+ contextIdentifier: { type: "Nip", value: nip },
6039
+ encryptedToken: Buffer.from(encryptedToken).toString("base64"),
6040
+ publicKeyId
6041
+ });
5936
6042
  });
5937
6043
  const authToken = submitResult.authenticationToken.token;
5938
6044
  await this.awaitAuthReady(submitResult.referenceNumber, authToken);
@@ -5997,6 +6103,7 @@ __export(index_exports, {
5997
6103
  CertificateFetcher: () => CertificateFetcher,
5998
6104
  CertificateFingerprint: () => CertificateFingerprint,
5999
6105
  CertificateName: () => CertificateName,
6106
+ CertificateSerialNumber: () => CertificateSerialNumber,
6000
6107
  CertificateService: () => CertificateService,
6001
6108
  CircuitBreakerPolicy: () => CircuitBreakerPolicy,
6002
6109
  CryptographyService: () => CryptographyService,
@@ -6033,9 +6140,11 @@ __export(index_exports, {
6033
6140
  KSeFErrorCode: () => KSeFErrorCode,
6034
6141
  KSeFForbiddenError: () => KSeFForbiddenError,
6035
6142
  KSeFGoneError: () => KSeFGoneError,
6143
+ KSeFMetadataPaginationError: () => KSeFMetadataPaginationError,
6036
6144
  KSeFRateLimitError: () => KSeFRateLimitError,
6037
6145
  KSeFSessionExpiredError: () => KSeFSessionExpiredError,
6038
6146
  KSeFUnauthorizedError: () => KSeFUnauthorizedError,
6147
+ KSeFUnknownPublicKeyError: () => KSeFUnknownPublicKeyError,
6039
6148
  KSeFValidationError: () => KSeFValidationError,
6040
6149
  KSeFXsdValidationError: () => KSeFXsdValidationError,
6041
6150
  KsefNumber: () => KsefNumber,
@@ -6093,7 +6202,9 @@ __export(index_exports, {
6093
6202
  buildXmlFromObject: () => buildXmlFromObject,
6094
6203
  calculateBackoff: () => calculateBackoff,
6095
6204
  calculateOfflineDeadline: () => calculateOfflineDeadline,
6205
+ collectAllInvoiceMetadata: () => collectAllInvoiceMetadata,
6096
6206
  comparePKey: () => comparePKey,
6207
+ createTarGz: () => createTarGz,
6097
6208
  createZip: () => createZip,
6098
6209
  decodeJwtPayload: () => decodeJwtPayload,
6099
6210
  deduplicateByKsefNumber: () => deduplicateByKsefNumber,
@@ -6106,6 +6217,7 @@ __export(index_exports, {
6106
6217
  exportInvoices: () => exportInvoices,
6107
6218
  extendDeadlineForMaintenance: () => extendDeadlineForMaintenance,
6108
6219
  extractInvoiceFields: () => extractInvoiceFields,
6220
+ extractTarGz: () => extractTarGz,
6109
6221
  getDefaultReason: () => getDefaultReason,
6110
6222
  getEffectiveStartDate: () => getEffectiveStartDate,
6111
6223
  getFormCode: () => getFormCode,
@@ -6123,6 +6235,7 @@ __export(index_exports, {
6123
6235
  isValidBase64: () => isValidBase64,
6124
6236
  isValidCertificateFingerprint: () => isValidCertificateFingerprint,
6125
6237
  isValidCertificateName: () => isValidCertificateName,
6238
+ isValidCertificateSerialNumber: () => isValidCertificateSerialNumber,
6126
6239
  isValidInternalId: () => isValidInternalId,
6127
6240
  isValidIp4Address: () => isValidIp4Address,
6128
6241
  isValidKsefNumber: () => isValidKsefNumber,
@@ -6146,6 +6259,7 @@ __export(index_exports, {
6146
6259
  parseUpoXml: () => parseUpoXml,
6147
6260
  parseXml: () => parseXml,
6148
6261
  pollUntil: () => pollUntil,
6262
+ queryAllInvoiceMetadata: () => queryAllInvoiceMetadata,
6149
6263
  resolveOptions: () => resolveOptions,
6150
6264
  resolveXsdFor: () => resolveXsdFor,
6151
6265
  resumeOnlineSession: () => resumeOnlineSession,
@@ -6506,6 +6620,7 @@ var AuthKsefTokenRequestBuilder = class {
6506
6620
  challenge;
6507
6621
  contextIdentifier;
6508
6622
  encryptedToken;
6623
+ publicKeyId;
6509
6624
  authorizationPolicy;
6510
6625
  withChallenge(challenge) {
6511
6626
  this.challenge = challenge;
@@ -6527,6 +6642,13 @@ var AuthKsefTokenRequestBuilder = class {
6527
6642
  this.encryptedToken = token;
6528
6643
  return this;
6529
6644
  }
6645
+ withPublicKeyId(publicKeyId) {
6646
+ if (!publicKeyId.trim()) {
6647
+ throw KSeFValidationError.fromField("publicKeyId", "Public key id is required");
6648
+ }
6649
+ this.publicKeyId = publicKeyId.trim();
6650
+ return this;
6651
+ }
6530
6652
  withAuthorizationPolicy(policy) {
6531
6653
  this.authorizationPolicy = policy;
6532
6654
  return this;
@@ -6545,6 +6667,7 @@ var AuthKsefTokenRequestBuilder = class {
6545
6667
  challenge: this.challenge,
6546
6668
  contextIdentifier: this.contextIdentifier,
6547
6669
  encryptedToken: this.encryptedToken,
6670
+ ...this.publicKeyId && { publicKeyId: this.publicKeyId },
6548
6671
  ...this.authorizationPolicy && { authorizationPolicy: this.authorizationPolicy }
6549
6672
  };
6550
6673
  }
@@ -6850,6 +6973,7 @@ var BatchFileBuilder = class {
6850
6973
  batchFile: {
6851
6974
  fileSize: zipBytes.length,
6852
6975
  fileHash: zipHash,
6976
+ ...options?.compressionType && { compressionType: options.compressionType },
6853
6977
  fileParts
6854
6978
  },
6855
6979
  encryptedParts
@@ -6952,6 +7076,7 @@ var BatchFileBuilder = class {
6952
7076
  batchFile: {
6953
7077
  fileSize: zipSize,
6954
7078
  fileHash: zipMeta.hashSHA,
7079
+ ...options?.compressionType && { compressionType: options.compressionType },
6955
7080
  fileParts
6956
7081
  },
6957
7082
  streamParts
@@ -7131,6 +7256,7 @@ function escapeXml2(str) {
7131
7256
  // src/utils/index.ts
7132
7257
  init_cjs_shims();
7133
7258
  init_zip();
7259
+ init_targz();
7134
7260
  init_jwt();
7135
7261
 
7136
7262
  // src/utils/hash.ts
@@ -7174,6 +7300,7 @@ init_auth_manager();
7174
7300
  init_online_session();
7175
7301
  init_session_status();
7176
7302
  init_document_structures();
7303
+ init_with_key_rotation_retry();
7177
7304
 
7178
7305
  // src/xml/index.ts
7179
7306
  init_cjs_shims();
@@ -7943,12 +8070,15 @@ function buildSessionHandle(params) {
7943
8070
  }
7944
8071
  async function openOnlineSession(client, options) {
7945
8072
  await client.crypto.init();
7946
- const encData = await client.crypto.getEncryptionData();
7947
8073
  const formCode = options?.formCode ?? DEFAULT_FORM_CODE;
7948
- const openResp = await client.onlineSession.openSession(
7949
- { formCode, encryption: encData.encryptionInfo },
7950
- options?.upoVersion
7951
- );
8074
+ const { encData, openResp } = await withKeyRotationRetry(client.crypto, async () => {
8075
+ const encData2 = await client.crypto.getEncryptionData();
8076
+ const openResp2 = await client.onlineSession.openSession(
8077
+ { formCode, encryption: encData2.encryptionInfo },
8078
+ options?.upoVersion
8079
+ );
8080
+ return { encData: encData2, openResp: openResp2 };
8081
+ });
7952
8082
  return buildSessionHandle({
7953
8083
  deps: {
7954
8084
  crypto: client.crypto,
@@ -8000,17 +8130,17 @@ async function openSendAndClose(client, invoices, options) {
8000
8130
  // src/workflows/batch-session-workflow.ts
8001
8131
  init_cjs_shims();
8002
8132
  init_document_structures();
8133
+ init_with_key_rotation_retry();
8003
8134
  async function uploadBatch(client, zipData, options) {
8004
8135
  if (options?.parallelism !== void 0 && (!Number.isInteger(options.parallelism) || options.parallelism < 1)) {
8005
8136
  throw new Error("parallelism must be a positive integer");
8006
8137
  }
8007
8138
  await client.crypto.init();
8008
8139
  if (options?.validate) {
8009
- const { unzip: unzip2 } = await Promise.resolve().then(() => (init_zip(), zip_exports));
8010
8140
  const { validateBatch: validateBatch2, batchValidationDetails: batchValidationDetails2 } = await Promise.resolve().then(() => (init_invoice_validator(), invoice_validator_exports));
8011
8141
  const { KSeFValidationError: KSeFValidationError2 } = await Promise.resolve().then(() => (init_ksef_validation_error(), ksef_validation_error_exports));
8012
8142
  const zipBuf = Buffer.isBuffer(zipData) ? zipData : Buffer.from(zipData.buffer, zipData.byteOffset, zipData.byteLength);
8013
- const files = await unzip2(zipBuf);
8143
+ 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);
8014
8144
  const invoices = [...files.entries()].filter(([name]) => name.endsWith(".xml")).map(([name, data]) => ({ fileName: name, xml: data.toString("utf-8") }));
8015
8145
  if (invoices.length > 0) {
8016
8146
  const result2 = await validateBatch2(invoices);
@@ -8023,21 +8153,25 @@ async function uploadBatch(client, zipData, options) {
8023
8153
  }
8024
8154
  }
8025
8155
  }
8026
- const encData = await client.crypto.getEncryptionData();
8027
8156
  const formCode = options?.formCode ?? DEFAULT_FORM_CODE;
8028
- const encryptFn = (part) => client.crypto.encryptAES256(part, encData.cipherKey, encData.cipherIv);
8029
- const { batchFile, encryptedParts } = BatchFileBuilder.build(zipData, encryptFn, {
8030
- maxPartSize: options?.maxPartSize
8157
+ const { batchFile, encryptedParts, openResp } = await withKeyRotationRetry(client.crypto, async () => {
8158
+ const encData = await client.crypto.getEncryptionData();
8159
+ const encryptFn = (part) => client.crypto.encryptAES256(part, encData.cipherKey, encData.cipherIv);
8160
+ const { batchFile: batchFile2, encryptedParts: encryptedParts2 } = BatchFileBuilder.build(zipData, encryptFn, {
8161
+ maxPartSize: options?.maxPartSize,
8162
+ compressionType: options?.compressionType
8163
+ });
8164
+ const openResp2 = await client.batchSession.openSession(
8165
+ {
8166
+ formCode,
8167
+ encryption: encData.encryptionInfo,
8168
+ batchFile: batchFile2,
8169
+ offlineMode: options?.offlineMode
8170
+ },
8171
+ options?.upoVersion
8172
+ );
8173
+ return { batchFile: batchFile2, encryptedParts: encryptedParts2, openResp: openResp2 };
8031
8174
  });
8032
- const openResp = await client.batchSession.openSession(
8033
- {
8034
- formCode,
8035
- encryption: encData.encryptionInfo,
8036
- batchFile,
8037
- offlineMode: options?.offlineMode
8038
- },
8039
- options?.upoVersion
8040
- );
8041
8175
  const sendingParts = encryptedParts.map((part, i) => ({
8042
8176
  data: part.buffer.slice(part.byteOffset, part.byteOffset + part.byteLength),
8043
8177
  metadata: {
@@ -8071,26 +8205,29 @@ async function uploadBatchStream(client, zipStreamFactory, zipSize, options) {
8071
8205
  throw new Error("parallelism must be a positive integer");
8072
8206
  }
8073
8207
  await client.crypto.init();
8074
- const encData = await client.crypto.getEncryptionData();
8075
8208
  const formCode = options?.formCode ?? DEFAULT_FORM_CODE;
8076
- const encryptStreamFn = (stream) => client.crypto.encryptAES256Stream(stream, encData.cipherKey, encData.cipherIv);
8077
- const hashStreamFn = (stream) => client.crypto.getFileMetadataFromStream(stream);
8078
- const { batchFile, streamParts } = await BatchFileBuilder.buildFromStream(
8079
- zipStreamFactory,
8080
- zipSize,
8081
- encryptStreamFn,
8082
- hashStreamFn,
8083
- { maxPartSize: options?.maxPartSize }
8084
- );
8085
- const openResp = await client.batchSession.openSession(
8086
- {
8087
- formCode,
8088
- encryption: encData.encryptionInfo,
8089
- batchFile,
8090
- offlineMode: options?.offlineMode
8091
- },
8092
- options?.upoVersion
8093
- );
8209
+ const { streamParts, openResp } = await withKeyRotationRetry(client.crypto, async () => {
8210
+ const encData = await client.crypto.getEncryptionData();
8211
+ const encryptStreamFn = (stream) => client.crypto.encryptAES256Stream(stream, encData.cipherKey, encData.cipherIv);
8212
+ const hashStreamFn = (stream) => client.crypto.getFileMetadataFromStream(stream);
8213
+ const { batchFile, streamParts: streamParts2 } = await BatchFileBuilder.buildFromStream(
8214
+ zipStreamFactory,
8215
+ zipSize,
8216
+ encryptStreamFn,
8217
+ hashStreamFn,
8218
+ { maxPartSize: options?.maxPartSize, compressionType: options?.compressionType }
8219
+ );
8220
+ const openResp2 = await client.batchSession.openSession(
8221
+ {
8222
+ formCode,
8223
+ encryption: encData.encryptionInfo,
8224
+ batchFile,
8225
+ offlineMode: options?.offlineMode
8226
+ },
8227
+ options?.upoVersion
8228
+ );
8229
+ return { streamParts: streamParts2, openResp: openResp2 };
8230
+ });
8094
8231
  await client.batchSession.sendPartsWithStream(openResp, streamParts, options?.parallelism);
8095
8232
  await client.batchSession.closeSession(openResp.referenceNumber);
8096
8233
  const result = await pollUntil(
@@ -8139,13 +8276,19 @@ async function uploadBatchParsed(client, zipData, options) {
8139
8276
  // src/workflows/invoice-export-workflow.ts
8140
8277
  init_cjs_shims();
8141
8278
  init_zip();
8279
+ init_targz();
8280
+ init_with_key_rotation_retry();
8142
8281
  async function doExport(client, filters, options) {
8143
8282
  await client.crypto.init();
8144
- const encData = await client.crypto.getEncryptionData();
8145
- const opResp = await client.invoices.exportInvoices({
8146
- encryption: encData.encryptionInfo,
8147
- filters,
8148
- onlyMetadata: options?.onlyMetadata
8283
+ const { encData, opResp } = await withKeyRotationRetry(client.crypto, async () => {
8284
+ const encData2 = await client.crypto.getEncryptionData();
8285
+ const opResp2 = await client.invoices.exportInvoices({
8286
+ encryption: encData2.encryptionInfo,
8287
+ filters,
8288
+ onlyMetadata: options?.onlyMetadata,
8289
+ ...options?.compressionType && { compressionType: options.compressionType }
8290
+ });
8291
+ return { encData: encData2, opResp: opResp2 };
8149
8292
  });
8150
8293
  const result = await pollUntil(
8151
8294
  () => client.invoices.getInvoiceExportStatus(opResp.referenceNumber),
@@ -8200,8 +8343,8 @@ async function exportAndDownload(client, filters, options) {
8200
8343
  decryptedParts.push(decrypted);
8201
8344
  }
8202
8345
  if (options?.extract) {
8203
- const zipBuffer = Buffer.concat(decryptedParts);
8204
- const files = await unzip(zipBuffer, options.unzipOptions);
8346
+ const archiveBuffer = Buffer.concat(decryptedParts);
8347
+ const files = options.compressionType === "TarGz" ? await extractTarGz(archiveBuffer, options.unzipOptions) : await unzip(archiveBuffer, options.unzipOptions);
8205
8348
  return { ...exportResult, files };
8206
8349
  }
8207
8350
  return {
@@ -8346,22 +8489,24 @@ var FileHwmStore = class {
8346
8489
  // src/workflows/auth-workflow.ts
8347
8490
  init_cjs_shims();
8348
8491
  init_auth_xml_builder();
8349
- async function authenticateWithToken(client, options) {
8350
- const challenge = await client.auth.getChallenge();
8351
- await client.crypto.init();
8352
- const encryptedToken = await client.crypto.encryptKsefToken(options.token, challenge.timestamp);
8353
- const submitResult = await client.auth.submitKsefTokenAuthRequest({
8354
- challenge: challenge.challenge,
8355
- contextIdentifier: { type: "Nip", value: options.nip },
8356
- encryptedToken: Buffer.from(encryptedToken).toString("base64"),
8357
- authorizationPolicy: options.authorizationPolicy
8358
- });
8359
- const authToken = submitResult.authenticationToken.token;
8360
- await pollUntil(
8361
- () => client.auth.getAuthStatus(submitResult.referenceNumber, authToken),
8362
- (s) => s.status.code !== 100,
8363
- { ...options.pollOptions, description: `auth ${submitResult.referenceNumber}` }
8492
+ init_with_key_rotation_retry();
8493
+ init_ksef_auth_status_error();
8494
+ var AUTH_STATUS_SUCCESS = 200;
8495
+ var AUTH_STATUS_IN_PROGRESS = 100;
8496
+ async function awaitAuthentication(client, referenceNumber, authToken, pollOptions) {
8497
+ const final = await pollUntil(
8498
+ () => client.auth.getAuthStatus(referenceNumber, authToken),
8499
+ (s) => s.status.code !== AUTH_STATUS_IN_PROGRESS,
8500
+ { ...pollOptions, description: `auth ${referenceNumber}` }
8364
8501
  );
8502
+ if (final.status.code !== AUTH_STATUS_SUCCESS) {
8503
+ const details = final.status.details?.length ? ` (${final.status.details.join("; ")})` : "";
8504
+ throw new KSeFAuthStatusError(
8505
+ `Authentication failed with status ${final.status.code}: ${final.status.description}${details}`,
8506
+ referenceNumber,
8507
+ final.status.description
8508
+ );
8509
+ }
8365
8510
  const tokens = await client.auth.getAccessToken(authToken);
8366
8511
  client.authManager.setAccessToken(tokens.accessToken.token);
8367
8512
  client.authManager.setRefreshToken(tokens.refreshToken.token);
@@ -8372,6 +8517,22 @@ async function authenticateWithToken(client, options) {
8372
8517
  refreshTokenValidUntil: tokens.refreshToken.validUntil
8373
8518
  };
8374
8519
  }
8520
+ async function authenticateWithToken(client, options) {
8521
+ const challenge = await client.auth.getChallenge();
8522
+ await client.crypto.init();
8523
+ const submitResult = await withKeyRotationRetry(client.crypto, async () => {
8524
+ const { encryptedToken, publicKeyId } = await client.crypto.encryptKsefTokenWithKeyId(options.token, challenge.timestamp);
8525
+ return client.auth.submitKsefTokenAuthRequest({
8526
+ challenge: challenge.challenge,
8527
+ contextIdentifier: { type: "Nip", value: options.nip },
8528
+ encryptedToken: Buffer.from(encryptedToken).toString("base64"),
8529
+ publicKeyId,
8530
+ authorizationPolicy: options.authorizationPolicy
8531
+ });
8532
+ });
8533
+ const authToken = submitResult.authenticationToken.token;
8534
+ return awaitAuthentication(client, submitResult.referenceNumber, authToken, options.pollOptions);
8535
+ }
8375
8536
  async function authenticateWithCertificate(client, options) {
8376
8537
  const challenge = await client.auth.getChallenge();
8377
8538
  const { buildAuthTokenRequestXml: buildAuthTokenRequestXml2 } = await Promise.resolve().then(() => (init_client(), client_exports));
@@ -8384,20 +8545,7 @@ async function authenticateWithCertificate(client, options) {
8384
8545
  options.enforceXadesCompliance ?? false
8385
8546
  );
8386
8547
  const authToken = submitResult.authenticationToken.token;
8387
- await pollUntil(
8388
- () => client.auth.getAuthStatus(submitResult.referenceNumber, authToken),
8389
- (s) => s.status.code !== 100,
8390
- { ...options.pollOptions, description: `auth ${submitResult.referenceNumber}` }
8391
- );
8392
- const tokens = await client.auth.getAccessToken(authToken);
8393
- client.authManager.setAccessToken(tokens.accessToken.token);
8394
- client.authManager.setRefreshToken(tokens.refreshToken.token);
8395
- return {
8396
- accessToken: tokens.accessToken.token,
8397
- accessTokenValidUntil: tokens.accessToken.validUntil,
8398
- refreshToken: tokens.refreshToken.token,
8399
- refreshTokenValidUntil: tokens.refreshToken.validUntil
8400
- };
8548
+ return awaitAuthentication(client, submitResult.referenceNumber, authToken, options.pollOptions);
8401
8549
  }
8402
8550
  async function authenticateWithExternalSignature(client, options) {
8403
8551
  const challenge = await client.auth.getChallenge();
@@ -8412,20 +8560,7 @@ async function authenticateWithExternalSignature(client, options) {
8412
8560
  options.enforceXadesCompliance ?? false
8413
8561
  );
8414
8562
  const authToken = submitResult.authenticationToken.token;
8415
- await pollUntil(
8416
- () => client.auth.getAuthStatus(submitResult.referenceNumber, authToken),
8417
- (s) => s.status.code !== 100,
8418
- { ...options.pollOptions, description: `auth ${submitResult.referenceNumber}` }
8419
- );
8420
- const tokens = await client.auth.getAccessToken(authToken);
8421
- client.authManager.setAccessToken(tokens.accessToken.token);
8422
- client.authManager.setRefreshToken(tokens.refreshToken.token);
8423
- return {
8424
- accessToken: tokens.accessToken.token,
8425
- accessTokenValidUntil: tokens.accessToken.validUntil,
8426
- refreshToken: tokens.refreshToken.token,
8427
- refreshTokenValidUntil: tokens.refreshToken.validUntil
8428
- };
8563
+ return awaitAuthentication(client, submitResult.referenceNumber, authToken, options.pollOptions);
8429
8564
  }
8430
8565
  async function authenticateWithPkcs12(client, options) {
8431
8566
  const { Pkcs12Loader: Pkcs12Loader2 } = await Promise.resolve().then(() => (init_pkcs12_loader(), pkcs12_loader_exports));
@@ -8440,6 +8575,95 @@ async function authenticateWithPkcs12(client, options) {
8440
8575
  });
8441
8576
  }
8442
8577
 
8578
+ // src/workflows/metadata-query-paging.ts
8579
+ init_cjs_shims();
8580
+ init_ksef_metadata_pagination_error();
8581
+ init_ksef_validation_error();
8582
+ var DEFAULT_PAGE_SIZE = 100;
8583
+ var DEFAULT_MAX_BOUNDARY_CROSSINGS = 1e3;
8584
+ function boundaryFieldFor(dateType) {
8585
+ switch (dateType) {
8586
+ case "Issue":
8587
+ return "issueDate";
8588
+ case "Invoicing":
8589
+ return "invoicingDate";
8590
+ case "PermanentStorage":
8591
+ return "permanentStorageDate";
8592
+ }
8593
+ }
8594
+ async function* queryAllInvoiceMetadata(client, filters, options = {}) {
8595
+ const sortOrder = options.sortOrder ?? "Asc";
8596
+ const pageSize = options.pageSize ?? DEFAULT_PAGE_SIZE;
8597
+ const maxBoundaryCrossings = options.maxBoundaryCrossings ?? DEFAULT_MAX_BOUNDARY_CROSSINGS;
8598
+ if (!Number.isInteger(pageSize) || pageSize <= 0) {
8599
+ throw new KSeFValidationError("`pageSize` must be a positive integer.");
8600
+ }
8601
+ if (!Number.isInteger(maxBoundaryCrossings) || maxBoundaryCrossings < 0) {
8602
+ throw new KSeFValidationError("`maxBoundaryCrossings` must be a non-negative integer.");
8603
+ }
8604
+ const boundaryField = boundaryFieldFor(filters.dateRange.dateType);
8605
+ let dateRange = { ...filters.dateRange };
8606
+ let boundaryCrossings = 0;
8607
+ let carryKeys = /* @__PURE__ */ new Set();
8608
+ let carryValue;
8609
+ for (; ; ) {
8610
+ let pageIndex = 0;
8611
+ let lastBoundaryValue;
8612
+ let isTruncated = false;
8613
+ let boundaryKeys = /* @__PURE__ */ new Set();
8614
+ for (; ; ) {
8615
+ const window = { ...filters, dateRange };
8616
+ const response = await client.invoices.queryInvoiceMetadata(
8617
+ window,
8618
+ pageIndex,
8619
+ pageSize,
8620
+ sortOrder
8621
+ );
8622
+ isTruncated = response.isTruncated;
8623
+ for (const invoice of response.invoices) {
8624
+ const boundaryValue = invoice[boundaryField];
8625
+ const key = invoice.ksefNumber.toLowerCase();
8626
+ if (boundaryValue === carryValue && carryKeys.has(key)) continue;
8627
+ if (boundaryValue !== lastBoundaryValue) {
8628
+ lastBoundaryValue = boundaryValue;
8629
+ boundaryKeys = /* @__PURE__ */ new Set();
8630
+ }
8631
+ boundaryKeys.add(key);
8632
+ yield invoice;
8633
+ }
8634
+ if (response.hasMore) {
8635
+ pageIndex += 1;
8636
+ continue;
8637
+ }
8638
+ break;
8639
+ }
8640
+ if (!isTruncated || lastBoundaryValue === void 0) return;
8641
+ const previousBoundary = sortOrder === "Asc" ? dateRange.from : dateRange.to;
8642
+ if (previousBoundary === lastBoundaryValue) {
8643
+ throw new KSeFMetadataPaginationError(
8644
+ `Metadata paging stalled: a truncated window did not advance past ${boundaryField}=${lastBoundaryValue}. The result set likely exceeds the server cap within a single ${boundaryField} value; narrow the query further.`,
8645
+ lastBoundaryValue
8646
+ );
8647
+ }
8648
+ if (++boundaryCrossings > maxBoundaryCrossings) {
8649
+ throw new KSeFMetadataPaginationError(
8650
+ `Metadata paging exceeded ${maxBoundaryCrossings} truncation boundaries; aborting to avoid an unbounded loop.`,
8651
+ lastBoundaryValue
8652
+ );
8653
+ }
8654
+ carryKeys = boundaryKeys;
8655
+ carryValue = lastBoundaryValue;
8656
+ dateRange = sortOrder === "Asc" ? { ...dateRange, from: lastBoundaryValue } : { ...dateRange, to: lastBoundaryValue };
8657
+ }
8658
+ }
8659
+ async function collectAllInvoiceMetadata(client, filters, options = {}) {
8660
+ const all = [];
8661
+ for await (const invoice of queryAllInvoiceMetadata(client, filters, options)) {
8662
+ all.push(invoice);
8663
+ }
8664
+ return all;
8665
+ }
8666
+
8443
8667
  // src/offline/index.ts
8444
8668
  init_cjs_shims();
8445
8669
  init_deadline();
@@ -8598,6 +8822,7 @@ init_client();
8598
8822
  CertificateFetcher,
8599
8823
  CertificateFingerprint,
8600
8824
  CertificateName,
8825
+ CertificateSerialNumber,
8601
8826
  CertificateService,
8602
8827
  CircuitBreakerPolicy,
8603
8828
  CryptographyService,
@@ -8634,9 +8859,11 @@ init_client();
8634
8859
  KSeFErrorCode,
8635
8860
  KSeFForbiddenError,
8636
8861
  KSeFGoneError,
8862
+ KSeFMetadataPaginationError,
8637
8863
  KSeFRateLimitError,
8638
8864
  KSeFSessionExpiredError,
8639
8865
  KSeFUnauthorizedError,
8866
+ KSeFUnknownPublicKeyError,
8640
8867
  KSeFValidationError,
8641
8868
  KSeFXsdValidationError,
8642
8869
  KsefNumber,
@@ -8694,7 +8921,9 @@ init_client();
8694
8921
  buildXmlFromObject,
8695
8922
  calculateBackoff,
8696
8923
  calculateOfflineDeadline,
8924
+ collectAllInvoiceMetadata,
8697
8925
  comparePKey,
8926
+ createTarGz,
8698
8927
  createZip,
8699
8928
  decodeJwtPayload,
8700
8929
  deduplicateByKsefNumber,
@@ -8707,6 +8936,7 @@ init_client();
8707
8936
  exportInvoices,
8708
8937
  extendDeadlineForMaintenance,
8709
8938
  extractInvoiceFields,
8939
+ extractTarGz,
8710
8940
  getDefaultReason,
8711
8941
  getEffectiveStartDate,
8712
8942
  getFormCode,
@@ -8724,6 +8954,7 @@ init_client();
8724
8954
  isValidBase64,
8725
8955
  isValidCertificateFingerprint,
8726
8956
  isValidCertificateName,
8957
+ isValidCertificateSerialNumber,
8727
8958
  isValidInternalId,
8728
8959
  isValidIp4Address,
8729
8960
  isValidKsefNumber,
@@ -8747,6 +8978,7 @@ init_client();
8747
8978
  parseUpoXml,
8748
8979
  parseXml,
8749
8980
  pollUntil,
8981
+ queryAllInvoiceMetadata,
8750
8982
  resolveOptions,
8751
8983
  resolveXsdFor,
8752
8984
  resumeOnlineSession,