ksef-client-ts 0.6.2 → 0.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/README.md +3 -1
  2. package/dist/cli.js +2630 -634
  3. package/dist/cli.js.map +1 -1
  4. package/dist/index.cjs +1689 -138
  5. package/dist/index.cjs.map +1 -1
  6. package/dist/index.d.cts +361 -17
  7. package/dist/index.d.ts +361 -17
  8. package/dist/index.js +1657 -138
  9. package/dist/index.js.map +1 -1
  10. package/docs/schemas/FA/bazowe/ElementarneTypyDanych_v10-0E.xsd +1 -0
  11. package/docs/schemas/FA/bazowe/KodyKrajow_v10-0E.xsd +1283 -0
  12. package/docs/schemas/FA/bazowe/StrukturyDanych_v10-0E.xsd +1 -0
  13. package/docs/schemas/FA/schemat_FA(2)_v1-0E.xsd +3661 -0
  14. package/docs/schemas/FA/schemat_FA(3)_v1-0E.xsd +3950 -0
  15. package/docs/schemas/PEF/Schemat_PEF(3)_v2-1.xsd +977 -0
  16. package/docs/schemas/PEF/Schemat_PEF_KOR(3)_v2-1.xsd +926 -0
  17. package/docs/schemas/PEF/bazowe/20241206_PEFPL-CommonAggregateComponents-2.1-v1.4.34.xsd +428 -0
  18. package/docs/schemas/PEF/bazowe/20241206_PEFPL-CommonBasicComponents-2.1-v1.4.34.xsd +65 -0
  19. package/docs/schemas/PEF/bazowe/CCTS_CCT_SchemaModule-2.1.xsd +731 -0
  20. package/docs/schemas/PEF/bazowe/UBL-CommonAggregateComponents-2.1.xsd +39799 -0
  21. package/docs/schemas/PEF/bazowe/UBL-CommonBasicComponents-2.1.xsd +5389 -0
  22. package/docs/schemas/PEF/bazowe/UBL-CommonExtensionComponents-2.1.xsd +223 -0
  23. package/docs/schemas/PEF/bazowe/UBL-CommonSignatureComponents-2.1.xsd +101 -0
  24. package/docs/schemas/PEF/bazowe/UBL-ExtensionContentDataType-2.1.xsd +89 -0
  25. package/docs/schemas/PEF/bazowe/UBL-QualifiedDataTypes-2.1.xsd +69 -0
  26. package/docs/schemas/PEF/bazowe/UBL-SignatureAggregateComponents-2.1.xsd +138 -0
  27. package/docs/schemas/PEF/bazowe/UBL-SignatureBasicComponents-2.1.xsd +78 -0
  28. package/docs/schemas/PEF/bazowe/UBL-UnqualifiedDataTypes-2.1.xsd +553 -0
  29. package/docs/schemas/PEF/bazowe/UBL-XAdESv132-2.1.xsd +476 -0
  30. package/docs/schemas/PEF/bazowe/UBL-XAdESv141-2.1.xsd +25 -0
  31. package/docs/schemas/PEF/bazowe/UBL-xmldsig-core-schema-2.1.xsd +323 -0
  32. package/docs/schemas/PEF/bazowe/commontypes.xsd +735 -0
  33. package/docs/schemas/PEF/bazowe/isotypes.xsd +3158 -0
  34. package/docs/schemas/RR/schemat_FA_RR(1)_v1-1E.xsd +2188 -0
  35. package/docs/schemas/RR/schemat_RR(1)_v1-0E.xsd +2188 -0
  36. package/docs/schemas/RR/schemat_RR(1)_v1-1E.xsd +2188 -0
  37. package/package.json +14 -2
package/dist/index.js CHANGED
@@ -8,11 +8,21 @@ var __export = (target, all) => {
8
8
  __defProp(target, name, { get: all[name], enumerable: true });
9
9
  };
10
10
 
11
+ // node_modules/tsup/assets/esm_shims.js
12
+ import path from "path";
13
+ import { fileURLToPath } from "url";
14
+ var init_esm_shims = __esm({
15
+ "node_modules/tsup/assets/esm_shims.js"() {
16
+ "use strict";
17
+ }
18
+ });
19
+
11
20
  // src/config/environments.ts
12
21
  var Environment;
13
22
  var init_environments = __esm({
14
23
  "src/config/environments.ts"() {
15
24
  "use strict";
25
+ init_esm_shims();
16
26
  Environment = {
17
27
  TEST: {
18
28
  apiUrl: "https://api-test.ksef.mf.gov.pl",
@@ -43,13 +53,15 @@ function resolveOptions(options = {}) {
43
53
  apiVersion: options.apiVersion ?? DEFAULT_API_VERSION,
44
54
  timeout: options.timeout ?? DEFAULT_TIMEOUT,
45
55
  customHeaders: options.customHeaders ?? {},
46
- environmentName: options.environment ?? (options.baseUrl ? void 0 : "TEST")
56
+ environmentName: options.environment ?? (options.baseUrl ? void 0 : "TEST"),
57
+ errorFormat: options.errorFormat ?? "problem-details"
47
58
  };
48
59
  }
49
60
  var DEFAULT_API_VERSION, DEFAULT_TIMEOUT;
50
61
  var init_options = __esm({
51
62
  "src/config/options.ts"() {
52
63
  "use strict";
64
+ init_esm_shims();
53
65
  init_environments();
54
66
  DEFAULT_API_VERSION = "v2";
55
67
  DEFAULT_TIMEOUT = 3e4;
@@ -60,6 +72,7 @@ var init_options = __esm({
60
72
  var init_config = __esm({
61
73
  "src/config/index.ts"() {
62
74
  "use strict";
75
+ init_esm_shims();
63
76
  init_environments();
64
77
  init_options();
65
78
  }
@@ -70,6 +83,7 @@ var KSeFError;
70
83
  var init_ksef_error = __esm({
71
84
  "src/errors/ksef-error.ts"() {
72
85
  "use strict";
86
+ init_esm_shims();
73
87
  KSeFError = class extends Error {
74
88
  constructor(message) {
75
89
  super(message);
@@ -84,6 +98,7 @@ var KSeFApiError;
84
98
  var init_ksef_api_error = __esm({
85
99
  "src/errors/ksef-api-error.ts"() {
86
100
  "use strict";
101
+ init_esm_shims();
87
102
  init_ksef_error();
88
103
  KSeFApiError = class _KSeFApiError extends KSeFError {
89
104
  statusCode;
@@ -99,6 +114,9 @@ var init_ksef_api_error = __esm({
99
114
  const message = details?.length ? details.map((d) => d.exceptionDescription ?? "").filter(Boolean).join("; ") || `KSeF API error: HTTP ${statusCode}` : `KSeF API error: HTTP ${statusCode}`;
100
115
  return new _KSeFApiError(message, statusCode, body);
101
116
  }
117
+ toProblemFields() {
118
+ return { detail: this.message };
119
+ }
102
120
  };
103
121
  }
104
122
  });
@@ -108,19 +126,23 @@ var KSeFRateLimitError;
108
126
  var init_ksef_rate_limit_error = __esm({
109
127
  "src/errors/ksef-rate-limit-error.ts"() {
110
128
  "use strict";
129
+ init_esm_shims();
111
130
  init_ksef_api_error();
112
131
  KSeFRateLimitError = class _KSeFRateLimitError extends KSeFApiError {
132
+ statusCode = 429;
113
133
  retryAfterSeconds;
114
134
  retryAfterDate;
115
135
  recommendedDelay;
116
- constructor(message, statusCode, errorResponse, retryAfterSeconds, retryAfterDate) {
136
+ problem;
137
+ constructor(message, statusCode, errorResponse, retryAfterSeconds, retryAfterDate, problem) {
117
138
  super(message, statusCode, errorResponse);
118
139
  this.name = "KSeFRateLimitError";
119
140
  this.retryAfterSeconds = retryAfterSeconds;
120
141
  this.retryAfterDate = retryAfterDate;
121
142
  this.recommendedDelay = retryAfterSeconds ?? 60;
143
+ this.problem = problem;
122
144
  }
123
- static fromRetryAfterHeader(statusCode, retryAfterHeader, body) {
145
+ static fromRetryAfterHeader(statusCode, retryAfterHeader, body, problem) {
124
146
  let retryAfterSeconds;
125
147
  let retryAfterDate;
126
148
  if (retryAfterHeader) {
@@ -135,8 +157,16 @@ var init_ksef_rate_limit_error = __esm({
135
157
  }
136
158
  }
137
159
  }
138
- const message = retryAfterSeconds != null ? `Rate limited. Retry after ${retryAfterSeconds}s` : "Rate limited by KSeF API";
139
- return new _KSeFRateLimitError(message, statusCode, body, retryAfterSeconds, retryAfterDate);
160
+ const message = retryAfterSeconds != null ? `Rate limited. Retry after ${retryAfterSeconds}s` : problem?.detail ?? "Rate limited by KSeF API";
161
+ return new _KSeFRateLimitError(message, statusCode, body, retryAfterSeconds, retryAfterDate, problem);
162
+ }
163
+ toProblemFields() {
164
+ return {
165
+ detail: this.problem?.detail,
166
+ traceId: this.problem?.traceId,
167
+ instance: this.problem?.instance,
168
+ timestamp: this.problem?.timestamp
169
+ };
140
170
  }
141
171
  };
142
172
  }
@@ -147,21 +177,30 @@ var KSeFUnauthorizedError;
147
177
  var init_ksef_unauthorized_error = __esm({
148
178
  "src/errors/ksef-unauthorized-error.ts"() {
149
179
  "use strict";
150
- init_ksef_error();
151
- KSeFUnauthorizedError = class extends KSeFError {
180
+ init_esm_shims();
181
+ init_ksef_api_error();
182
+ KSeFUnauthorizedError = class extends KSeFApiError {
152
183
  statusCode = 401;
153
184
  detail;
154
185
  traceId;
155
186
  instance;
156
187
  timestamp;
157
188
  constructor(problemDetails) {
158
- super(problemDetails.detail || "Unauthorized");
189
+ super(problemDetails.detail || "Unauthorized", 401);
159
190
  this.name = "KSeFUnauthorizedError";
160
191
  this.detail = problemDetails.detail;
161
192
  this.traceId = problemDetails.traceId;
162
193
  this.instance = problemDetails.instance;
163
194
  this.timestamp = problemDetails.timestamp;
164
195
  }
196
+ toProblemFields() {
197
+ return {
198
+ detail: this.detail,
199
+ traceId: this.traceId,
200
+ instance: this.instance,
201
+ timestamp: this.timestamp
202
+ };
203
+ }
165
204
  };
166
205
  }
167
206
  });
@@ -171,8 +210,9 @@ var KSeFForbiddenError;
171
210
  var init_ksef_forbidden_error = __esm({
172
211
  "src/errors/ksef-forbidden-error.ts"() {
173
212
  "use strict";
174
- init_ksef_error();
175
- KSeFForbiddenError = class extends KSeFError {
213
+ init_esm_shims();
214
+ init_ksef_api_error();
215
+ KSeFForbiddenError = class extends KSeFApiError {
176
216
  statusCode = 403;
177
217
  detail;
178
218
  reasonCode;
@@ -181,7 +221,7 @@ var init_ksef_forbidden_error = __esm({
181
221
  traceId;
182
222
  timestamp;
183
223
  constructor(problemDetails) {
184
- super(problemDetails.detail || "Forbidden");
224
+ super(problemDetails.detail || "Forbidden", 403);
185
225
  this.name = "KSeFForbiddenError";
186
226
  this.detail = problemDetails.detail;
187
227
  this.reasonCode = problemDetails.reasonCode;
@@ -190,6 +230,16 @@ var init_ksef_forbidden_error = __esm({
190
230
  this.traceId = problemDetails.traceId;
191
231
  this.timestamp = problemDetails.timestamp;
192
232
  }
233
+ toProblemFields() {
234
+ return {
235
+ detail: this.detail,
236
+ reasonCode: this.reasonCode,
237
+ security: this.security,
238
+ traceId: this.traceId,
239
+ instance: this.instance,
240
+ timestamp: this.timestamp
241
+ };
242
+ }
193
243
  };
194
244
  }
195
245
  });
@@ -199,21 +249,66 @@ var KSeFGoneError;
199
249
  var init_ksef_gone_error = __esm({
200
250
  "src/errors/ksef-gone-error.ts"() {
201
251
  "use strict";
202
- init_ksef_error();
203
- KSeFGoneError = class extends KSeFError {
252
+ init_esm_shims();
253
+ init_ksef_api_error();
254
+ KSeFGoneError = class extends KSeFApiError {
204
255
  statusCode = 410;
205
256
  detail;
206
257
  instance;
207
258
  traceId;
208
259
  timestamp;
209
260
  constructor(problemDetails) {
210
- super(problemDetails.detail || "Operation status no longer available (retention expired)");
261
+ super(problemDetails.detail || "Operation status no longer available (retention expired)", 410);
211
262
  this.name = "KSeFGoneError";
212
263
  this.detail = problemDetails.detail;
213
264
  this.instance = problemDetails.instance;
214
265
  this.traceId = problemDetails.traceId;
215
266
  this.timestamp = problemDetails.timestamp;
216
267
  }
268
+ toProblemFields() {
269
+ return {
270
+ detail: this.detail,
271
+ traceId: this.traceId,
272
+ instance: this.instance,
273
+ timestamp: this.timestamp
274
+ };
275
+ }
276
+ };
277
+ }
278
+ });
279
+
280
+ // src/errors/ksef-bad-request-error.ts
281
+ var KSeFBadRequestError;
282
+ var init_ksef_bad_request_error = __esm({
283
+ "src/errors/ksef-bad-request-error.ts"() {
284
+ "use strict";
285
+ init_esm_shims();
286
+ init_ksef_api_error();
287
+ KSeFBadRequestError = class extends KSeFApiError {
288
+ statusCode = 400;
289
+ detail;
290
+ instance;
291
+ errors;
292
+ traceId;
293
+ timestamp;
294
+ constructor(problemDetails) {
295
+ super(problemDetails.detail || problemDetails.title || "Bad Request", 400);
296
+ this.name = "KSeFBadRequestError";
297
+ this.detail = problemDetails.detail;
298
+ this.instance = problemDetails.instance;
299
+ this.errors = problemDetails.errors ?? [];
300
+ this.traceId = problemDetails.traceId;
301
+ this.timestamp = problemDetails.timestamp;
302
+ }
303
+ toProblemFields() {
304
+ return {
305
+ detail: this.detail,
306
+ errors: this.errors.length ? this.errors : void 0,
307
+ traceId: this.traceId,
308
+ instance: this.instance,
309
+ timestamp: this.timestamp
310
+ };
311
+ }
217
312
  };
218
313
  }
219
314
  });
@@ -223,6 +318,7 @@ var KSeFAuthStatusError;
223
318
  var init_ksef_auth_status_error = __esm({
224
319
  "src/errors/ksef-auth-status-error.ts"() {
225
320
  "use strict";
321
+ init_esm_shims();
226
322
  init_ksef_error();
227
323
  KSeFAuthStatusError = class extends KSeFError {
228
324
  referenceNumber;
@@ -242,6 +338,7 @@ var KSeFSessionExpiredError;
242
338
  var init_ksef_session_expired_error = __esm({
243
339
  "src/errors/ksef-session-expired-error.ts"() {
244
340
  "use strict";
341
+ init_esm_shims();
245
342
  init_ksef_error();
246
343
  KSeFSessionExpiredError = class extends KSeFError {
247
344
  constructor(message = "KSeF session has expired") {
@@ -261,6 +358,7 @@ var KSeFValidationError;
261
358
  var init_ksef_validation_error = __esm({
262
359
  "src/errors/ksef-validation-error.ts"() {
263
360
  "use strict";
361
+ init_esm_shims();
264
362
  init_ksef_error();
265
363
  KSeFValidationError = class _KSeFValidationError extends KSeFError {
266
364
  details;
@@ -288,6 +386,7 @@ var KSeFErrorCode;
288
386
  var init_error_codes = __esm({
289
387
  "src/errors/error-codes.ts"() {
290
388
  "use strict";
389
+ init_esm_shims();
291
390
  KSeFErrorCode = {
292
391
  BatchTimeout: 21208,
293
392
  DuplicateInvoice: 440
@@ -300,6 +399,7 @@ var KSeFBatchTimeoutError;
300
399
  var init_ksef_batch_timeout_error = __esm({
301
400
  "src/errors/ksef-batch-timeout-error.ts"() {
302
401
  "use strict";
402
+ init_esm_shims();
303
403
  init_ksef_api_error();
304
404
  init_error_codes();
305
405
  KSeFBatchTimeoutError = class _KSeFBatchTimeoutError extends KSeFApiError {
@@ -319,21 +419,83 @@ var init_ksef_batch_timeout_error = __esm({
319
419
  }
320
420
  });
321
421
 
422
+ // src/errors/ksef-circuit-open-error.ts
423
+ var KSeFCircuitOpenError;
424
+ var init_ksef_circuit_open_error = __esm({
425
+ "src/errors/ksef-circuit-open-error.ts"() {
426
+ "use strict";
427
+ init_esm_shims();
428
+ init_ksef_error();
429
+ KSeFCircuitOpenError = class extends KSeFError {
430
+ endpoint;
431
+ openedAt;
432
+ retryAfterMs;
433
+ constructor(endpoint, openedAt, retryAfterMs) {
434
+ super(
435
+ `Circuit breaker is open for '${endpoint}'. Retry after ${Math.round(retryAfterMs)}ms.`
436
+ );
437
+ this.name = "KSeFCircuitOpenError";
438
+ this.endpoint = endpoint;
439
+ this.openedAt = openedAt;
440
+ this.retryAfterMs = retryAfterMs;
441
+ }
442
+ };
443
+ }
444
+ });
445
+
446
+ // src/errors/ksef-xsd-validation-error.ts
447
+ var KSeFXsdValidationError;
448
+ var init_ksef_xsd_validation_error = __esm({
449
+ "src/errors/ksef-xsd-validation-error.ts"() {
450
+ "use strict";
451
+ init_esm_shims();
452
+ init_ksef_error();
453
+ KSeFXsdValidationError = class extends KSeFError {
454
+ schemaFile;
455
+ errors;
456
+ constructor(schemaFile, errors) {
457
+ const preview = errors.slice(0, 3).join("; ");
458
+ const extra = errors.length > 3 ? ` (+${errors.length - 3} more)` : "";
459
+ super(`XSD validation failed against ${schemaFile}: ${preview}${extra}`);
460
+ this.name = "KSeFXsdValidationError";
461
+ this.schemaFile = schemaFile;
462
+ this.errors = errors;
463
+ }
464
+ };
465
+ }
466
+ });
467
+
468
+ // src/errors/assert-never.ts
469
+ function assertNever(value) {
470
+ throw new Error(`Unexpected value: ${String(value)}`);
471
+ }
472
+ var init_assert_never = __esm({
473
+ "src/errors/assert-never.ts"() {
474
+ "use strict";
475
+ init_esm_shims();
476
+ }
477
+ });
478
+
322
479
  // src/errors/index.ts
323
480
  var init_errors = __esm({
324
481
  "src/errors/index.ts"() {
325
482
  "use strict";
483
+ init_esm_shims();
326
484
  init_ksef_error();
327
485
  init_ksef_api_error();
328
486
  init_ksef_rate_limit_error();
329
487
  init_ksef_unauthorized_error();
330
488
  init_ksef_forbidden_error();
331
489
  init_ksef_gone_error();
490
+ init_ksef_bad_request_error();
332
491
  init_ksef_auth_status_error();
333
492
  init_ksef_session_expired_error();
334
493
  init_ksef_validation_error();
335
494
  init_ksef_batch_timeout_error();
495
+ init_ksef_circuit_open_error();
496
+ init_ksef_xsd_validation_error();
336
497
  init_error_codes();
498
+ init_assert_never();
337
499
  }
338
500
  });
339
501
 
@@ -342,6 +504,7 @@ var RouteBuilder;
342
504
  var init_route_builder = __esm({
343
505
  "src/http/route-builder.ts"() {
344
506
  "use strict";
507
+ init_esm_shims();
345
508
  RouteBuilder = class {
346
509
  apiVersion;
347
510
  constructor(apiVersion) {
@@ -360,6 +523,7 @@ var RestRequest;
360
523
  var init_rest_request = __esm({
361
524
  "src/http/rest-request.ts"() {
362
525
  "use strict";
526
+ init_esm_shims();
363
527
  RestRequest = class _RestRequest {
364
528
  method;
365
529
  path;
@@ -368,21 +532,21 @@ var init_rest_request = __esm({
368
532
  _query = [];
369
533
  _presigned = false;
370
534
  _skipAuthRetry = false;
371
- constructor(method, path2) {
535
+ constructor(method, path4) {
372
536
  this.method = method;
373
- this.path = path2;
537
+ this.path = path4;
374
538
  }
375
- static get(path2) {
376
- return new _RestRequest("GET", path2);
539
+ static get(path4) {
540
+ return new _RestRequest("GET", path4);
377
541
  }
378
- static post(path2) {
379
- return new _RestRequest("POST", path2);
542
+ static post(path4) {
543
+ return new _RestRequest("POST", path4);
380
544
  }
381
- static put(path2) {
382
- return new _RestRequest("PUT", path2);
545
+ static put(path4) {
546
+ return new _RestRequest("PUT", path4);
383
547
  }
384
- static delete(path2) {
385
- return new _RestRequest("DELETE", path2);
548
+ static delete(path4) {
549
+ return new _RestRequest("DELETE", path4);
386
550
  }
387
551
  body(data) {
388
552
  this._body = data;
@@ -436,6 +600,7 @@ var defaultTransport;
436
600
  var init_transport = __esm({
437
601
  "src/http/transport.ts"() {
438
602
  "use strict";
603
+ init_esm_shims();
439
604
  defaultTransport = (url, init) => fetch(url, init);
440
605
  }
441
606
  });
@@ -485,6 +650,7 @@ var RETRYABLE_ERROR_CODES;
485
650
  var init_retry_policy = __esm({
486
651
  "src/http/retry-policy.ts"() {
487
652
  "use strict";
653
+ init_esm_shims();
488
654
  RETRYABLE_ERROR_CODES = /* @__PURE__ */ new Set([
489
655
  "ECONNRESET",
490
656
  "ECONNREFUSED",
@@ -575,6 +741,7 @@ var BLOCKED_PARAMS;
575
741
  var init_presigned_url_policy = __esm({
576
742
  "src/http/presigned-url-policy.ts"() {
577
743
  "use strict";
744
+ init_esm_shims();
578
745
  init_ksef_validation_error();
579
746
  BLOCKED_PARAMS = ["redirect", "callback", "return_url", "next"];
580
747
  }
@@ -582,15 +749,38 @@ var init_presigned_url_policy = __esm({
582
749
 
583
750
  // src/http/rest-client.ts
584
751
  import { consola } from "consola";
752
+ function isBadRequestProblem(value) {
753
+ if (typeof value !== "object" || value === null) return false;
754
+ const v = value;
755
+ if (typeof v.title !== "string") return false;
756
+ if (v.status !== void 0 && typeof v.status !== "number") return false;
757
+ if (v.errors !== void 0) {
758
+ if (!Array.isArray(v.errors)) return false;
759
+ for (const item of v.errors) {
760
+ if (typeof item !== "object" || item === null) return false;
761
+ const detail = item;
762
+ if (typeof detail.code !== "number") return false;
763
+ if (typeof detail.description !== "string") return false;
764
+ }
765
+ }
766
+ return true;
767
+ }
768
+ function isTooManyRequestsProblem(value) {
769
+ if (typeof value !== "object" || value === null) return false;
770
+ const v = value;
771
+ return typeof v.title === "string" && (v.status === void 0 || typeof v.status === "number") && (v.detail === void 0 || typeof v.detail === "string") && (v.instance === void 0 || typeof v.instance === "string") && (v.traceId === void 0 || typeof v.traceId === "string") && (v.timestamp === void 0 || typeof v.timestamp === "string");
772
+ }
585
773
  var RestClient;
586
774
  var init_rest_client = __esm({
587
775
  "src/http/rest-client.ts"() {
588
776
  "use strict";
777
+ init_esm_shims();
589
778
  init_ksef_api_error();
590
779
  init_ksef_rate_limit_error();
591
780
  init_ksef_unauthorized_error();
592
781
  init_ksef_forbidden_error();
593
782
  init_ksef_gone_error();
783
+ init_ksef_bad_request_error();
594
784
  init_ksef_batch_timeout_error();
595
785
  init_error_codes();
596
786
  init_route_builder();
@@ -603,6 +793,7 @@ var init_rest_client = __esm({
603
793
  transport;
604
794
  retryPolicy;
605
795
  rateLimitPolicy;
796
+ circuitBreakerPolicy;
606
797
  authManager;
607
798
  presignedUrlPolicy;
608
799
  constructor(options, config) {
@@ -611,6 +802,7 @@ var init_rest_client = __esm({
611
802
  this.transport = config?.transport ?? defaultTransport;
612
803
  this.retryPolicy = config?.retryPolicy ?? defaultRetryPolicy();
613
804
  this.rateLimitPolicy = config?.rateLimitPolicy ?? null;
805
+ this.circuitBreakerPolicy = config?.circuitBreakerPolicy ?? null;
614
806
  this.authManager = config?.authManager;
615
807
  this.presignedUrlPolicy = config?.presignedUrlPolicy;
616
808
  }
@@ -635,18 +827,32 @@ var init_rest_client = __esm({
635
827
  if (request.isPresigned() && this.presignedUrlPolicy) {
636
828
  validatePresignedUrl(url, this.presignedUrlPolicy);
637
829
  }
830
+ let ownsProbeSlot = false;
831
+ if (this.circuitBreakerPolicy) {
832
+ const claimed = this.circuitBreakerPolicy.ensureClosed(request.path);
833
+ if (claimed) ownsProbeSlot = true;
834
+ }
638
835
  if (this.rateLimitPolicy) {
639
- await this.rateLimitPolicy.acquire(request.path);
836
+ try {
837
+ await this.rateLimitPolicy.acquire(request.path);
838
+ } catch (error) {
839
+ if (ownsProbeSlot) this.circuitBreakerPolicy?.releaseProbe(request.path);
840
+ throw error;
841
+ }
640
842
  }
641
843
  let lastError;
642
844
  for (let attempt = 0; attempt <= this.retryPolicy.maxRetries; attempt++) {
845
+ if (this.circuitBreakerPolicy) {
846
+ const claimed = this.circuitBreakerPolicy.ensureClosed(request.path, ownsProbeSlot);
847
+ if (claimed) ownsProbeSlot = true;
848
+ }
643
849
  try {
644
- const response = await this.doRequest(request, url);
850
+ let response = await this.doRequest(request, url);
645
851
  if (response.status === 401 && this.authManager && attempt === 0 && !request.isSkipAuthRetry()) {
646
852
  const newToken = await this.authManager.onUnauthorized();
647
853
  if (newToken) {
648
854
  consola.debug("Auth token refreshed, retrying request");
649
- return this.doRequest(request, url, newToken);
855
+ response = await this.doRequest(request, url, newToken);
650
856
  }
651
857
  }
652
858
  if (isRetryableStatus(response.status, this.retryPolicy) && attempt < this.retryPolicy.maxRetries) {
@@ -656,10 +862,17 @@ var init_rest_client = __esm({
656
862
  consola.debug(`Retryable ${response.status}, attempt ${attempt + 1}/${this.retryPolicy.maxRetries}, waiting ${Math.round(delayMs)}ms`);
657
863
  await sleep(delayMs);
658
864
  if (is429 && this.rateLimitPolicy) {
659
- await this.rateLimitPolicy.acquire(request.path);
865
+ try {
866
+ await this.rateLimitPolicy.acquire(request.path);
867
+ } catch (error) {
868
+ this.recordCircuitOutcome(request.path, 429);
869
+ ownsProbeSlot = false;
870
+ throw error;
871
+ }
660
872
  }
661
873
  continue;
662
874
  }
875
+ this.recordCircuitOutcome(request.path, response.status);
663
876
  return response;
664
877
  } catch (error) {
665
878
  lastError = error;
@@ -669,16 +882,31 @@ var init_rest_client = __esm({
669
882
  await sleep(delayMs);
670
883
  continue;
671
884
  }
885
+ if (isRetryableError(error, this.retryPolicy) || ownsProbeSlot) {
886
+ this.circuitBreakerPolicy?.recordFailure(request.path);
887
+ }
672
888
  throw error;
673
889
  }
674
890
  }
675
891
  throw lastError;
676
892
  }
893
+ recordCircuitOutcome(path4, status) {
894
+ if (!this.circuitBreakerPolicy) return;
895
+ if (status >= 500) {
896
+ this.circuitBreakerPolicy.recordFailure(path4);
897
+ return;
898
+ }
899
+ this.circuitBreakerPolicy.recordSuccess(path4);
900
+ }
677
901
  async doRequest(request, url, overrideToken) {
678
902
  const headers = {
679
903
  ...this.options.customHeaders,
680
904
  ...request.getHeaders()
681
905
  };
906
+ const hasHeader = (name) => Object.keys(headers).some((header) => header.toLowerCase() === name.toLowerCase());
907
+ if (this.options.errorFormat !== "legacy" && !hasHeader("x-error-format")) {
908
+ headers["X-Error-Format"] = "problem-details";
909
+ }
682
910
  if (!headers["Authorization"] && this.authManager) {
683
911
  const token = overrideToken ?? this.authManager.getAccessToken();
684
912
  if (token) {
@@ -705,9 +933,9 @@ var init_rest_client = __esm({
705
933
  return response;
706
934
  }
707
935
  buildUrl(request) {
708
- const path2 = this.routeBuilder.build(request.path);
936
+ const path4 = this.routeBuilder.build(request.path);
709
937
  const base = this.options.baseUrl;
710
- const url = new URL(`${base}${path2}`);
938
+ const url = new URL(`${base}${path4}`);
711
939
  const query = request.getQuery();
712
940
  for (const [key, value] of query) {
713
941
  url.searchParams.append(key, value);
@@ -717,19 +945,40 @@ var init_rest_client = __esm({
717
945
  async ensureSuccess(response) {
718
946
  if (response.ok) return;
719
947
  const text = await response.text().catch(() => "");
948
+ let jsonCache = null;
720
949
  const parseJson = () => {
721
- try {
722
- return JSON.parse(text);
723
- } catch {
724
- return void 0;
950
+ if (jsonCache === null) {
951
+ try {
952
+ jsonCache = { value: JSON.parse(text) };
953
+ } catch {
954
+ jsonCache = { value: void 0 };
955
+ }
725
956
  }
957
+ return jsonCache.value;
726
958
  };
727
- if (response.status === 429) {
959
+ const tryParseProblem = (guard) => {
728
960
  const parsed = parseJson();
961
+ return parsed !== void 0 && guard(parsed) ? parsed : void 0;
962
+ };
963
+ if (response.status === 400) {
964
+ const problem = tryParseProblem(isBadRequestProblem);
965
+ if (problem) {
966
+ throw new KSeFBadRequestError(problem);
967
+ }
968
+ const legacy = parseJson();
969
+ if (hasErrorCode(legacy, KSeFErrorCode.BatchTimeout)) {
970
+ throw KSeFBatchTimeoutError.fromResponse(400, legacy);
971
+ }
972
+ throw KSeFApiError.fromResponse(400, legacy);
973
+ }
974
+ if (response.status === 429) {
975
+ const problem = tryParseProblem(isTooManyRequestsProblem);
976
+ const legacy = problem ? void 0 : parseJson();
729
977
  throw KSeFRateLimitError.fromRetryAfterHeader(
730
978
  response.status,
731
979
  response.headers.get("Retry-After"),
732
- parsed
980
+ legacy,
981
+ problem
733
982
  );
734
983
  }
735
984
  if (response.status === 401) {
@@ -770,6 +1019,7 @@ var Routes;
770
1019
  var init_routes = __esm({
771
1020
  "src/http/routes.ts"() {
772
1021
  "use strict";
1022
+ init_esm_shims();
773
1023
  Routes = {
774
1024
  TestData: {
775
1025
  createSubject: "testdata/subject",
@@ -902,6 +1152,7 @@ var TokenBucket, RateLimitPolicy;
902
1152
  var init_rate_limit_policy = __esm({
903
1153
  "src/http/rate-limit-policy.ts"() {
904
1154
  "use strict";
1155
+ init_esm_shims();
905
1156
  TokenBucket = class {
906
1157
  tokens;
907
1158
  maxTokens;
@@ -962,11 +1213,151 @@ var init_rate_limit_policy = __esm({
962
1213
  }
963
1214
  });
964
1215
 
1216
+ // src/http/circuit-breaker-policy.ts
1217
+ import { consola as consola2 } from "consola";
1218
+ function defaultCircuitBreakerPolicy() {
1219
+ return new CircuitBreakerPolicy();
1220
+ }
1221
+ var GLOBAL_KEY, CircuitBreakerPolicy;
1222
+ var init_circuit_breaker_policy = __esm({
1223
+ "src/http/circuit-breaker-policy.ts"() {
1224
+ "use strict";
1225
+ init_esm_shims();
1226
+ init_ksef_circuit_open_error();
1227
+ GLOBAL_KEY = "__global__";
1228
+ CircuitBreakerPolicy = class _CircuitBreakerPolicy {
1229
+ failureThreshold;
1230
+ openMs;
1231
+ scope;
1232
+ states = /* @__PURE__ */ new Map();
1233
+ constructor(config = {}) {
1234
+ const failureThreshold = config.failureThreshold ?? 5;
1235
+ const openMs = config.openMs ?? 3e4;
1236
+ if (!Number.isInteger(failureThreshold) || failureThreshold <= 0) {
1237
+ throw new RangeError("CircuitBreakerPolicy: failureThreshold must be a positive integer");
1238
+ }
1239
+ if (!Number.isFinite(openMs) || openMs <= 0) {
1240
+ throw new RangeError("CircuitBreakerPolicy: openMs must be > 0");
1241
+ }
1242
+ const scope = config.scope ?? "global";
1243
+ if (scope !== "global" && scope !== "endpoint") {
1244
+ throw new RangeError(
1245
+ "CircuitBreakerPolicy: scope must be 'global' or 'endpoint'"
1246
+ );
1247
+ }
1248
+ this.failureThreshold = failureThreshold;
1249
+ this.openMs = openMs;
1250
+ this.scope = scope;
1251
+ }
1252
+ // Returns true iff this call just claimed the single probe slot for the
1253
+ // caller. The caller MUST pass `alreadyOwnsProbe=true` on subsequent
1254
+ // re-checks for the same logical request (e.g. a retry loop) so the probe
1255
+ // owner cannot deadlock itself on its own in-flight slot.
1256
+ ensureClosed(endpoint, alreadyOwnsProbe = false) {
1257
+ const key = this.keyFor(endpoint);
1258
+ const state = this.states.get(key);
1259
+ if (!state || state.openedAt === null) return false;
1260
+ const now = performance.now();
1261
+ const elapsed = now - state.openedAt;
1262
+ if (elapsed >= this.openMs) {
1263
+ if (alreadyOwnsProbe) return false;
1264
+ if (state.probeInFlight) {
1265
+ throw new KSeFCircuitOpenError(endpoint, state.openedAt, 0);
1266
+ }
1267
+ state.probeInFlight = true;
1268
+ consola2.debug(`Circuit breaker: probe after cooldown for '${key}'`);
1269
+ return true;
1270
+ }
1271
+ const retryAfterMs = Math.max(0, this.openMs - elapsed);
1272
+ throw new KSeFCircuitOpenError(endpoint, state.openedAt, retryAfterMs);
1273
+ }
1274
+ recordSuccess(endpoint) {
1275
+ const key = this.keyFor(endpoint);
1276
+ const state = this.states.get(key);
1277
+ if (!state) return;
1278
+ if (state.openedAt !== null || state.failures > 0) {
1279
+ consola2.debug(`Circuit breaker: reset for '${key}'`);
1280
+ }
1281
+ this.states.delete(key);
1282
+ }
1283
+ // Release a claimed probe slot WITHOUT observing an outcome. Use this when
1284
+ // the probe attempt was aborted before reaching upstream (e.g. rate-limit
1285
+ // acquire rejected, client cancellation). We have no new information about
1286
+ // upstream health, so the breaker must stay OPEN — but we do restart the
1287
+ // cooldown clock so the next probe attempt waits a fresh `openMs`,
1288
+ // preventing a tight loop of aborted probes from spamming the limiter.
1289
+ releaseProbe(endpoint) {
1290
+ const key = this.keyFor(endpoint);
1291
+ const state = this.states.get(key);
1292
+ if (!state || !state.probeInFlight) return;
1293
+ state.probeInFlight = false;
1294
+ if (state.openedAt !== null) {
1295
+ state.openedAt = performance.now();
1296
+ }
1297
+ consola2.debug(`Circuit breaker: probe aborted (not observed) for '${key}', cooldown restarted`);
1298
+ }
1299
+ recordFailure(endpoint) {
1300
+ const key = this.keyFor(endpoint);
1301
+ const now = performance.now();
1302
+ let state = this.states.get(key);
1303
+ if (!state) {
1304
+ state = { failures: 0, openedAt: null, lastFailureAt: null, probeInFlight: false };
1305
+ this.states.set(key, state);
1306
+ }
1307
+ if (state.openedAt !== null && state.probeInFlight) {
1308
+ state.openedAt = now;
1309
+ state.failures = this.failureThreshold;
1310
+ state.lastFailureAt = now;
1311
+ state.probeInFlight = false;
1312
+ consola2.debug(`Circuit breaker: probe failed, re-opened for '${key}'`);
1313
+ this.maybeSweepStaleClosed(now, key);
1314
+ return;
1315
+ }
1316
+ const slidingStale = state.lastFailureAt !== null && now - state.lastFailureAt > this.openMs;
1317
+ state.failures = slidingStale ? 1 : state.failures + 1;
1318
+ state.lastFailureAt = now;
1319
+ if (state.openedAt === null && state.failures >= this.failureThreshold) {
1320
+ state.openedAt = now;
1321
+ consola2.debug(
1322
+ `Circuit breaker: opened for '${key}' after ${state.failures} failures (cooldown ${this.openMs}ms)`
1323
+ );
1324
+ }
1325
+ this.maybeSweepStaleClosed(now, key);
1326
+ }
1327
+ keyFor(endpoint) {
1328
+ return this.scope === "global" ? GLOBAL_KEY : endpoint;
1329
+ }
1330
+ // Prevent unbounded map growth under `scope: 'endpoint'` when callers hit
1331
+ // many distinct parameterized paths (e.g. `auth/sessions/{ref}`) that each
1332
+ // fail once and are never revisited. Global scope is always a single entry.
1333
+ //
1334
+ // Runs amortized O(n) — gated on a size threshold so small workloads pay
1335
+ // nothing. Only evicts states that are genuinely settled: closed, no probe
1336
+ // in flight, and with the last failure older than two cooldowns.
1337
+ maybeSweepStaleClosed(now, keepKey) {
1338
+ if (this.scope !== "endpoint") return;
1339
+ if (this.states.size <= _CircuitBreakerPolicy.sweepThreshold) return;
1340
+ const staleBefore = now - 2 * this.openMs;
1341
+ for (const [key, state] of this.states) {
1342
+ if (key === keepKey) continue;
1343
+ if (state.openedAt !== null) continue;
1344
+ if (state.probeInFlight) continue;
1345
+ if (state.lastFailureAt !== null && state.lastFailureAt < staleBefore) {
1346
+ this.states.delete(key);
1347
+ }
1348
+ }
1349
+ }
1350
+ static sweepThreshold = 64;
1351
+ };
1352
+ }
1353
+ });
1354
+
965
1355
  // src/http/auth-manager.ts
966
1356
  var DefaultAuthManager;
967
1357
  var init_auth_manager = __esm({
968
1358
  "src/http/auth-manager.ts"() {
969
1359
  "use strict";
1360
+ init_esm_shims();
970
1361
  DefaultAuthManager = class {
971
1362
  token;
972
1363
  refreshToken;
@@ -1007,6 +1398,7 @@ var KSEF_FEATURE_HEADER, UpoVersion, ENFORCE_XADES_COMPLIANCE;
1007
1398
  var init_ksef_feature = __esm({
1008
1399
  "src/http/ksef-feature.ts"() {
1009
1400
  "use strict";
1401
+ init_esm_shims();
1010
1402
  KSEF_FEATURE_HEADER = "X-KSeF-Feature";
1011
1403
  UpoVersion = {
1012
1404
  /** UPO v4-2 format (default before 2026-01-05). */
@@ -1106,6 +1498,7 @@ var NIP_PATTERN_CORE, VAT_UE_PATTERN_CORE, Nip, VatUe, NipVatUe, InternalId, Pep
1106
1498
  var init_patterns = __esm({
1107
1499
  "src/validation/patterns.ts"() {
1108
1500
  "use strict";
1501
+ init_esm_shims();
1109
1502
  NIP_PATTERN_CORE = "[1-9]((\\d[1-9])|([1-9]\\d))\\d{7}";
1110
1503
  VAT_UE_PATTERN_CORE = "(ATU\\d{8}|BE[01]{1}\\d{9}|BG\\d{9,10}|CY\\d{8}[A-Z]|CZ\\d{8,10}|DE\\d{9}|DK\\d{8}|EE\\d{9}|EL\\d{9}|ES([A-Z]\\d{8}|\\d{8}[A-Z]|[A-Z]\\d{7}[A-Z])|FI\\d{8}|FR[A-Z0-9]{2}\\d{9}|HR\\d{11}|HU\\d{8}|IE(\\d{7}[A-Z]{2}|\\d[A-Z0-9+*]\\d{5}[A-Z])|IT\\d{11}|LT(\\d{9}|\\d{12})|LU\\d{8}|LV\\d{11}|MT\\d{8}|NL[A-Z0-9+*]{12}|PT\\d{9}|RO\\d{2,10}|SE\\d{12}|SI\\d{8}|SK\\d{10}|XI((\\d{9}|\\d{12})|(GD|HA)\\d{3}))";
1111
1504
  Nip = new RegExp(`^${NIP_PATTERN_CORE}$`);
@@ -1222,6 +1615,7 @@ function getTextContent(el) {
1222
1615
  var init_xml_to_object = __esm({
1223
1616
  "src/validation/xml-to-object.ts"() {
1224
1617
  "use strict";
1618
+ init_esm_shims();
1225
1619
  }
1226
1620
  });
1227
1621
 
@@ -1235,6 +1629,7 @@ var TKodFormularza, TDataCzas, TZnakowy, TNaglowek, TKodyKrajowUE, TNrNIP, TZnak
1235
1629
  var init_fa3 = __esm({
1236
1630
  "src/validation/schemas/fa3.ts"() {
1237
1631
  "use strict";
1632
+ init_esm_shims();
1238
1633
  TKodFormularza = z.literal("FA");
1239
1634
  TDataCzas = z.string();
1240
1635
  TZnakowy = z.string().min(1).max(256);
@@ -1645,6 +2040,7 @@ var TKodFormularza2, TDataCzas2, TZnakowy3, TNaglowek2, TKodyKrajowUE2, TNrNIP2,
1645
2040
  var init_fa2 = __esm({
1646
2041
  "src/validation/schemas/fa2.ts"() {
1647
2042
  "use strict";
2043
+ init_esm_shims();
1648
2044
  TKodFormularza2 = z2.literal("FA");
1649
2045
  TDataCzas2 = z2.string();
1650
2046
  TZnakowy3 = z2.string().min(1).max(256);
@@ -2039,6 +2435,7 @@ var TKodFormularza3, TDataCzas3, TZnakowy4, TNaglowek3, TNrNIP3, TZnakowy5123, T
2039
2435
  var init_rr1_v11e = __esm({
2040
2436
  "src/validation/schemas/rr1-v11e.ts"() {
2041
2437
  "use strict";
2438
+ init_esm_shims();
2042
2439
  TKodFormularza3 = z3.literal("FA_RR");
2043
2440
  TDataCzas3 = z3.string();
2044
2441
  TZnakowy4 = z3.string().min(1).max(256);
@@ -2244,6 +2641,7 @@ var TKodFormularza4, TDataCzas4, TZnakowy5, TNaglowek4, TNrNIP4, TZnakowy5124, T
2244
2641
  var init_rr1_v10e = __esm({
2245
2642
  "src/validation/schemas/rr1-v10e.ts"() {
2246
2643
  "use strict";
2644
+ init_esm_shims();
2247
2645
  TKodFormularza4 = z4.literal("FA_RR");
2248
2646
  TDataCzas4 = z4.string();
2249
2647
  TZnakowy5 = z4.string().min(1).max(256);
@@ -2449,6 +2847,7 @@ var InvoiceType, PEF3Schema;
2449
2847
  var init_pef3 = __esm({
2450
2848
  "src/validation/schemas/pef3.ts"() {
2451
2849
  "use strict";
2850
+ init_esm_shims();
2452
2851
  InvoiceType = z5.object({
2453
2852
  "UBLExtensions": z5.any().optional(),
2454
2853
  "UBLVersionID": z5.any().optional(),
@@ -2519,6 +2918,7 @@ var CreditNoteType, PEF_KOR3Schema;
2519
2918
  var init_pef_kor3 = __esm({
2520
2919
  "src/validation/schemas/pef-kor3.ts"() {
2521
2920
  "use strict";
2921
+ init_esm_shims();
2522
2922
  CreditNoteType = z6.object({
2523
2923
  "UBLExtensions": z6.any().optional(),
2524
2924
  "UBLVersionID": z6.any().optional(),
@@ -2581,6 +2981,7 @@ var NAMESPACE_MAP;
2581
2981
  var init_schemas = __esm({
2582
2982
  "src/validation/schemas/index.ts"() {
2583
2983
  "use strict";
2984
+ init_esm_shims();
2584
2985
  init_fa3();
2585
2986
  init_fa2();
2586
2987
  init_rr1_v11e();
@@ -2637,6 +3038,7 @@ var ROOT_ELEMENT_MAP, schemaCache, SchemaRegistry;
2637
3038
  var init_schema_registry = __esm({
2638
3039
  "src/validation/schema-registry.ts"() {
2639
3040
  "use strict";
3041
+ init_esm_shims();
2640
3042
  init_schemas();
2641
3043
  ROOT_ELEMENT_MAP = {
2642
3044
  Invoice: "PEF3",
@@ -2678,6 +3080,116 @@ var init_schema_registry = __esm({
2678
3080
  }
2679
3081
  });
2680
3082
 
3083
+ // src/validation/char-validity.ts
3084
+ function validateCharValidity(xml) {
3085
+ return [...findProcessingInstructions(xml), ...findDiscouragedUnicode(xml)];
3086
+ }
3087
+ function findProcessingInstructionTokens(xml) {
3088
+ const tokens = [];
3089
+ for (let i = 0; i < xml.length; ) {
3090
+ if (xml.startsWith("<!--", i)) {
3091
+ const end = xml.indexOf("-->", i + 4);
3092
+ i = end === -1 ? xml.length : end + 3;
3093
+ continue;
3094
+ }
3095
+ if (xml.startsWith("<![CDATA[", i)) {
3096
+ const end = xml.indexOf("]]>", i + 9);
3097
+ i = end === -1 ? xml.length : end + 3;
3098
+ continue;
3099
+ }
3100
+ if (xml.startsWith("<?", i)) {
3101
+ const end = xml.indexOf("?>", i + 2);
3102
+ if (end === -1) break;
3103
+ tokens.push({ token: xml.slice(i, end + 2), index: i });
3104
+ i = end + 2;
3105
+ continue;
3106
+ }
3107
+ i += 1;
3108
+ }
3109
+ return tokens;
3110
+ }
3111
+ function findProcessingInstructions(xml) {
3112
+ const errors = [];
3113
+ const matches = findProcessingInstructionTokens(xml);
3114
+ if (matches.length === 0) return errors;
3115
+ const firstMatch = matches[0];
3116
+ const firstTarget = firstMatch.token.match(PI_TARGET_RE)?.[1];
3117
+ const hasBom = xml.charCodeAt(0) === 65279;
3118
+ const prologPosition = hasBom ? 1 : 0;
3119
+ const firstIsProlog = firstMatch.index === prologPosition && firstTarget === "xml";
3120
+ for (let i = 0; i < matches.length; i++) {
3121
+ if (i === 0 && firstIsProlog) continue;
3122
+ const m = matches[i];
3123
+ const target = m.token.match(PI_TARGET_RE)?.[1] ?? "?";
3124
+ errors.push({
3125
+ code: "XML_PROCESSING_INSTRUCTION",
3126
+ message: `Processing instruction <?${target}?> at offset ${m.index} is not allowed (only <?xml ... ?> prolog is permitted)`,
3127
+ path: `offset:${m.index}`
3128
+ });
3129
+ }
3130
+ return errors;
3131
+ }
3132
+ function findDiscouragedUnicode(xml) {
3133
+ const errors = [];
3134
+ const seenRanges = /* @__PURE__ */ new Set();
3135
+ let utf16Offset = 0;
3136
+ for (const ch of xml) {
3137
+ const cp = ch.codePointAt(0);
3138
+ const idx = rangeIndex(cp);
3139
+ if (idx >= 0 && !seenRanges.has(idx)) {
3140
+ seenRanges.add(idx);
3141
+ errors.push({
3142
+ code: "XML_DISCOURAGED_UNICODE",
3143
+ message: `Discouraged Unicode character U+${cp.toString(16).toUpperCase().padStart(4, "0")} found at offset ${utf16Offset} (W3C XML 1.0 \xA72.2 rejects this range)`,
3144
+ path: `offset:${utf16Offset}`
3145
+ });
3146
+ }
3147
+ utf16Offset += ch.length;
3148
+ }
3149
+ return errors;
3150
+ }
3151
+ function rangeIndex(cp) {
3152
+ let lo = 0;
3153
+ let hi = DISCOURAGED_UNICODE_RANGES.length - 1;
3154
+ while (lo <= hi) {
3155
+ const mid = lo + hi >> 1;
3156
+ const [start, end] = DISCOURAGED_UNICODE_RANGES[mid];
3157
+ if (cp < start) hi = mid - 1;
3158
+ else if (cp > end) lo = mid + 1;
3159
+ else return mid;
3160
+ }
3161
+ return -1;
3162
+ }
3163
+ var DISCOURAGED_UNICODE_RANGES, PI_TARGET_RE;
3164
+ var init_char_validity = __esm({
3165
+ "src/validation/char-validity.ts"() {
3166
+ "use strict";
3167
+ init_esm_shims();
3168
+ DISCOURAGED_UNICODE_RANGES = [
3169
+ [127, 132],
3170
+ [134, 159],
3171
+ [64976, 65007],
3172
+ [131070, 131071],
3173
+ [196606, 196607],
3174
+ [262142, 262143],
3175
+ [327678, 327679],
3176
+ [393214, 393215],
3177
+ [458750, 458751],
3178
+ [524286, 524287],
3179
+ [589822, 589823],
3180
+ [655358, 655359],
3181
+ [720894, 720895],
3182
+ [786430, 786431],
3183
+ [851966, 851967],
3184
+ [917502, 917503],
3185
+ [983038, 983039],
3186
+ [1048574, 1048575],
3187
+ [1114110, 1114111]
3188
+ ];
3189
+ PI_TARGET_RE = /^<\?(\S+)/;
3190
+ }
3191
+ });
3192
+
2681
3193
  // src/validation/invoice-validator.ts
2682
3194
  var invoice_validator_exports = {};
2683
3195
  __export(invoice_validator_exports, {
@@ -2735,11 +3247,11 @@ async function validateSchema(xml, options, _parsed) {
2735
3247
  const prefix = rootElement ? `/${rootElement}/` : "/";
2736
3248
  const validationErrors = result.error.issues.map((issue) => {
2737
3249
  const zodPath = issue.path.join("/");
2738
- const path2 = zodPath ? `${prefix}${zodPath}` : rootElement ? `/${rootElement}` : void 0;
3250
+ const path4 = zodPath ? `${prefix}${zodPath}` : rootElement ? `/${rootElement}` : void 0;
2739
3251
  return {
2740
3252
  code: mapZodErrorCode(issue),
2741
3253
  message: issue.message,
2742
- path: path2
3254
+ path: path4
2743
3255
  };
2744
3256
  });
2745
3257
  return { valid: false, schemaType, errors: validationErrors };
@@ -2779,9 +3291,9 @@ function validateBusinessRules(xml, _parsed) {
2779
3291
  collectDateErrors(object, rootElement, errors);
2780
3292
  return { valid: errors.length === 0, schemaType, errors };
2781
3293
  }
2782
- function collectNipPeselErrors(obj, path2, errors) {
3294
+ function collectNipPeselErrors(obj, path4, errors) {
2783
3295
  for (const [key, value] of Object.entries(obj)) {
2784
- const currentPath = path2 ? `${path2}/${key}` : key;
3296
+ const currentPath = path4 ? `${path4}/${key}` : key;
2785
3297
  if (key === "NIP" && typeof value === "string") {
2786
3298
  if (!isValidNip(value)) {
2787
3299
  errors.push({
@@ -2830,6 +3342,12 @@ function collectDateErrors(obj, rootElement, errors) {
2830
3342
  }
2831
3343
  }
2832
3344
  async function validate(xml, options) {
3345
+ if (!options?.skipCharValidity) {
3346
+ const l1aErrors = validateCharValidity(xml);
3347
+ if (l1aErrors.length > 0) {
3348
+ return { valid: false, schemaType: null, errors: l1aErrors };
3349
+ }
3350
+ }
2833
3351
  const parsed = xml && xml.trim() ? xmlToObject(xml) : void 0;
2834
3352
  const l1 = validateWellFormedness(xml, parsed);
2835
3353
  if (!l1.valid) return l1;
@@ -2854,8 +3372,10 @@ function batchValidationDetails(batch) {
2854
3372
  var init_invoice_validator = __esm({
2855
3373
  "src/validation/invoice-validator.ts"() {
2856
3374
  "use strict";
3375
+ init_esm_shims();
2857
3376
  init_xml_to_object();
2858
3377
  init_schema_registry();
3378
+ init_char_validity();
2859
3379
  init_patterns();
2860
3380
  }
2861
3381
  });
@@ -2865,6 +3385,7 @@ var SystemCode, FORM_CODES, DEFAULT_FORM_CODE, INVOICE_TYPES_BY_SYSTEM_CODE, FOR
2865
3385
  var init_types = __esm({
2866
3386
  "src/models/document-structures/types.ts"() {
2867
3387
  "use strict";
3388
+ init_esm_shims();
2868
3389
  SystemCode = {
2869
3390
  FA_2: "FA (2)",
2870
3391
  FA_3: "FA (3)",
@@ -2917,6 +3438,7 @@ var SYSTEM_CODE_TO_FORM_CODE, ALL_FORM_CODES, BATCH_DISALLOWED_SYSTEM_CODES;
2917
3438
  var init_helpers = __esm({
2918
3439
  "src/models/document-structures/helpers.ts"() {
2919
3440
  "use strict";
3441
+ init_esm_shims();
2920
3442
  init_types();
2921
3443
  SYSTEM_CODE_TO_FORM_CODE = {
2922
3444
  [SystemCode.FA_2]: FORM_CODES.FA_2,
@@ -2937,6 +3459,7 @@ var init_helpers = __esm({
2937
3459
  var init_document_structures = __esm({
2938
3460
  "src/models/document-structures/index.ts"() {
2939
3461
  "use strict";
3462
+ init_esm_shims();
2940
3463
  init_types();
2941
3464
  init_helpers();
2942
3465
  }
@@ -2947,6 +3470,7 @@ var AuthService;
2947
3470
  var init_auth = __esm({
2948
3471
  "src/services/auth.ts"() {
2949
3472
  "use strict";
3473
+ init_esm_shims();
2950
3474
  init_ksef_feature();
2951
3475
  init_rest_request();
2952
3476
  init_routes();
@@ -2997,6 +3521,7 @@ var ActiveSessionsService;
2997
3521
  var init_active_sessions = __esm({
2998
3522
  "src/services/active-sessions.ts"() {
2999
3523
  "use strict";
3524
+ init_esm_shims();
3000
3525
  init_rest_request();
3001
3526
  init_routes();
3002
3527
  ActiveSessionsService = class {
@@ -3028,6 +3553,7 @@ var OnlineSessionService;
3028
3553
  var init_online_session = __esm({
3029
3554
  "src/services/online-session.ts"() {
3030
3555
  "use strict";
3556
+ init_esm_shims();
3031
3557
  init_ksef_feature();
3032
3558
  init_rest_request();
3033
3559
  init_routes();
@@ -3080,6 +3606,7 @@ async function runWithConcurrency(tasks, parallelism) {
3080
3606
  var init_concurrency = __esm({
3081
3607
  "src/utils/concurrency.ts"() {
3082
3608
  "use strict";
3609
+ init_esm_shims();
3083
3610
  }
3084
3611
  });
3085
3612
 
@@ -3088,6 +3615,7 @@ var BatchSessionService;
3088
3615
  var init_batch_session = __esm({
3089
3616
  "src/services/batch-session.ts"() {
3090
3617
  "use strict";
3618
+ init_esm_shims();
3091
3619
  init_ksef_feature();
3092
3620
  init_rest_request();
3093
3621
  init_routes();
@@ -3192,6 +3720,7 @@ var SessionStatusService;
3192
3720
  var init_session_status = __esm({
3193
3721
  "src/services/session-status.ts"() {
3194
3722
  "use strict";
3723
+ init_esm_shims();
3195
3724
  init_rest_request();
3196
3725
  init_routes();
3197
3726
  SessionStatusService = class {
@@ -3278,6 +3807,7 @@ var InvoiceDownloadService;
3278
3807
  var init_invoice_download = __esm({
3279
3808
  "src/services/invoice-download.ts"() {
3280
3809
  "use strict";
3810
+ init_esm_shims();
3281
3811
  init_rest_request();
3282
3812
  init_routes();
3283
3813
  InvoiceDownloadService = class {
@@ -3320,9 +3850,11 @@ var PermissionsService;
3320
3850
  var init_permissions = __esm({
3321
3851
  "src/services/permissions.ts"() {
3322
3852
  "use strict";
3853
+ init_esm_shims();
3854
+ init_ksef_validation_error();
3323
3855
  init_rest_request();
3324
3856
  init_routes();
3325
- PermissionsService = class {
3857
+ PermissionsService = class _PermissionsService {
3326
3858
  restClient;
3327
3859
  constructor(restClient) {
3328
3860
  this.restClient = restClient;
@@ -3380,6 +3912,7 @@ var init_permissions = __esm({
3380
3912
  }
3381
3913
  // Search methods
3382
3914
  async queryPersonalGrants(options, pageOffset, pageSize) {
3915
+ _PermissionsService.validateContextIdentifier(options?.contextIdentifier);
3383
3916
  const req = RestRequest.post(Routes.Permissions.Query.personalGrants).body(options ?? {});
3384
3917
  if (pageOffset !== void 0) req.query("pageOffset", String(pageOffset));
3385
3918
  if (pageSize !== void 0) req.query("pageSize", String(pageSize));
@@ -3408,6 +3941,7 @@ var init_permissions = __esm({
3408
3941
  return response.body;
3409
3942
  }
3410
3943
  async queryEntitiesGrants(options, pageOffset, pageSize) {
3944
+ _PermissionsService.validateContextIdentifier(options?.contextIdentifier);
3411
3945
  const req = RestRequest.post(Routes.Permissions.Query.entitiesGrants).body(options ?? {});
3412
3946
  if (pageOffset !== void 0) req.query("pageOffset", String(pageOffset));
3413
3947
  if (pageSize !== void 0) req.query("pageSize", String(pageSize));
@@ -3446,17 +3980,92 @@ var init_permissions = __esm({
3446
3980
  const response = await this.restClient.execute(req);
3447
3981
  return response.body;
3448
3982
  }
3983
+ static validateContextIdentifier(ctx) {
3984
+ if (!ctx) return;
3985
+ if (ctx.type === "InternalId") {
3986
+ const len = ctx.value.length;
3987
+ if (len < 10 || len > 16) {
3988
+ throw KSeFValidationError.fromField(
3989
+ "contextIdentifier.value",
3990
+ `InternalId must be 10-16 characters, got ${len}`
3991
+ );
3992
+ }
3993
+ }
3994
+ }
3449
3995
  };
3450
3996
  }
3451
3997
  });
3452
3998
 
3999
+ // src/utils/jwt.ts
4000
+ function decodeJwtPayload(token) {
4001
+ const parts = token.split(".");
4002
+ if (parts.length !== 3) return null;
4003
+ try {
4004
+ const payload = parts[1];
4005
+ const json = Buffer.from(payload, "base64url").toString("utf-8");
4006
+ return JSON.parse(json);
4007
+ } catch {
4008
+ return null;
4009
+ }
4010
+ }
4011
+ function tryParseJson(value) {
4012
+ if (typeof value !== "string") return void 0;
4013
+ try {
4014
+ return JSON.parse(value);
4015
+ } catch {
4016
+ return void 0;
4017
+ }
4018
+ }
4019
+ function tryParseJsonArray(value) {
4020
+ if (typeof value !== "string") return void 0;
4021
+ try {
4022
+ const parsed = JSON.parse(value);
4023
+ return Array.isArray(parsed) && parsed.every((item) => typeof item === "string") ? parsed : void 0;
4024
+ } catch {
4025
+ return void 0;
4026
+ }
4027
+ }
4028
+ function parseKSeFTokenContext(token) {
4029
+ const raw = decodeJwtPayload(token);
4030
+ if (!raw) return null;
4031
+ return {
4032
+ type: typeof raw["typ"] === "string" ? raw["typ"] : void 0,
4033
+ contextIdentifierType: typeof raw["cit"] === "string" ? raw["cit"] : void 0,
4034
+ contextIdentifierValue: typeof raw["civ"] === "string" ? raw["civ"] : void 0,
4035
+ authMethod: typeof raw["aum"] === "string" ? raw["aum"] : void 0,
4036
+ permissions: tryParseJsonArray(raw["per"]),
4037
+ subjectDetails: tryParseJson(raw["sud"]),
4038
+ authorSubjectIdentifier: tryParseJson(raw["asi"]),
4039
+ issuedAt: typeof raw["iat"] === "number" ? raw["iat"] : void 0,
4040
+ expiresAt: typeof raw["exp"] === "number" ? raw["exp"] : void 0
4041
+ };
4042
+ }
4043
+ var init_jwt = __esm({
4044
+ "src/utils/jwt.ts"() {
4045
+ "use strict";
4046
+ init_esm_shims();
4047
+ }
4048
+ });
4049
+
3453
4050
  // src/services/tokens.ts
3454
- var TokenService;
4051
+ function toTokenAuthorIdentifierType(value) {
4052
+ return TOKEN_AUTHOR_IDENTIFIER_TYPES.has(value) ? value : void 0;
4053
+ }
4054
+ var TOKEN_AUTHOR_IDENTIFIER_TYPES, TokenService;
3455
4055
  var init_tokens = __esm({
3456
4056
  "src/services/tokens.ts"() {
3457
4057
  "use strict";
4058
+ init_esm_shims();
3458
4059
  init_rest_request();
3459
4060
  init_routes();
4061
+ init_jwt();
4062
+ init_ksef_api_error();
4063
+ init_ksef_error();
4064
+ TOKEN_AUTHOR_IDENTIFIER_TYPES = /* @__PURE__ */ new Set([
4065
+ "Nip",
4066
+ "Pesel",
4067
+ "Fingerprint"
4068
+ ]);
3460
4069
  TokenService = class {
3461
4070
  restClient;
3462
4071
  constructor(restClient) {
@@ -3491,6 +4100,73 @@ var init_tokens = __esm({
3491
4100
  const req = RestRequest.delete(Routes.Tokens.byReference(ref));
3492
4101
  await this.restClient.executeVoid(req);
3493
4102
  }
4103
+ /**
4104
+ * Resolves the reference number of the token currently in use for authentication.
4105
+ * The only JWT payload field treated as authoritative is the KSeF-specific `trn`
4106
+ * (token reference number). Standard RFC 7519 claims such as `jti` are NOT a safe
4107
+ * fallback — a `jti` that differs from the KSeF reference would cause a DELETE to
4108
+ * hit a non-existent path, which `revokeSelf` treats as already-revoked, falsely
4109
+ * reporting success while leaving the token active on the server. When `trn` is
4110
+ * absent, we fall back to `GET /tokens` filtered by author and context; requires
4111
+ * exactly one active match and returns undefined when ambiguous.
4112
+ */
4113
+ async findSelfReferenceNumber(accessToken) {
4114
+ if (!accessToken) return void 0;
4115
+ const payload = decodeJwtPayload(accessToken);
4116
+ if (payload && typeof payload["trn"] === "string" && payload["trn"].length > 0) {
4117
+ return payload["trn"];
4118
+ }
4119
+ const ctx = parseKSeFTokenContext(accessToken);
4120
+ const author = ctx?.authorSubjectIdentifier;
4121
+ if (!author?.type || !author.value) return void 0;
4122
+ if (!ctx?.contextIdentifierType || !ctx?.contextIdentifierValue) return void 0;
4123
+ const authorType = toTokenAuthorIdentifierType(author.type);
4124
+ if (!authorType) return void 0;
4125
+ let continuationToken;
4126
+ let match;
4127
+ do {
4128
+ const list = await this.queryTokens({
4129
+ status: ["Active"],
4130
+ authorIdentifier: author.value,
4131
+ authorIdentifierType: authorType,
4132
+ pageSize: 50,
4133
+ continuationToken
4134
+ });
4135
+ for (const t of list.tokens) {
4136
+ if (t.status === "Active" && t.contextIdentifier?.value === ctx.contextIdentifierValue && t.contextIdentifier?.type === ctx.contextIdentifierType) {
4137
+ if (match) return void 0;
4138
+ match = t.referenceNumber;
4139
+ }
4140
+ }
4141
+ continuationToken = list.continuationToken ?? void 0;
4142
+ } while (continuationToken);
4143
+ return match;
4144
+ }
4145
+ /**
4146
+ * Revokes the token currently used for authentication.
4147
+ * Treats 404/409/410 on DELETE as "already revoked" and returns successfully with
4148
+ * `alreadyRevoked: true` so callers can still clear local state.
4149
+ */
4150
+ async revokeSelf(opts = {}) {
4151
+ let ref = opts.referenceNumber;
4152
+ if (!ref && opts.accessToken) {
4153
+ ref = await this.findSelfReferenceNumber(opts.accessToken);
4154
+ }
4155
+ if (!ref) {
4156
+ throw new KSeFError(
4157
+ "Could not determine the current token reference number: no cache, JWT lacks the field, and the active-token list had 0 or 2+ matches in the current context."
4158
+ );
4159
+ }
4160
+ try {
4161
+ await this.revokeToken(ref);
4162
+ return { referenceNumber: ref, alreadyRevoked: false };
4163
+ } catch (err) {
4164
+ if (err instanceof KSeFApiError && (err.statusCode === 404 || err.statusCode === 409 || err.statusCode === 410)) {
4165
+ return { referenceNumber: ref, alreadyRevoked: true };
4166
+ }
4167
+ throw err;
4168
+ }
4169
+ }
3494
4170
  };
3495
4171
  }
3496
4172
  });
@@ -3500,6 +4176,7 @@ var CertificateApiService;
3500
4176
  var init_certificates = __esm({
3501
4177
  "src/services/certificates.ts"() {
3502
4178
  "use strict";
4179
+ init_esm_shims();
3503
4180
  init_rest_request();
3504
4181
  init_routes();
3505
4182
  CertificateApiService = class {
@@ -3552,6 +4229,7 @@ var LighthouseService;
3552
4229
  var init_lighthouse = __esm({
3553
4230
  "src/services/lighthouse.ts"() {
3554
4231
  "use strict";
4232
+ init_esm_shims();
3555
4233
  init_errors();
3556
4234
  LighthouseService = class {
3557
4235
  lighthouseUrl;
@@ -3560,20 +4238,20 @@ var init_lighthouse = __esm({
3560
4238
  this.lighthouseUrl = options.lighthouseUrl;
3561
4239
  this.timeout = options.timeout;
3562
4240
  }
3563
- async fetchJson(path2) {
4241
+ async fetchJson(path4) {
3564
4242
  if (!this.lighthouseUrl) {
3565
4243
  throw new KSeFError(
3566
4244
  "Lighthouse API is not available for the DEMO environment. Use TEST or PROD instead."
3567
4245
  );
3568
4246
  }
3569
- const response = await fetch(`${this.lighthouseUrl}${path2}`, {
4247
+ const response = await fetch(`${this.lighthouseUrl}${path4}`, {
3570
4248
  headers: { Accept: "application/json" },
3571
4249
  signal: AbortSignal.timeout(this.timeout)
3572
4250
  });
3573
4251
  if (!response.ok) {
3574
4252
  const body = await response.text();
3575
4253
  throw new KSeFError(
3576
- `Lighthouse ${path2} failed: HTTP ${response.status} \u2014 ${body}`
4254
+ `Lighthouse ${path4} failed: HTTP ${response.status} \u2014 ${body}`
3577
4255
  );
3578
4256
  }
3579
4257
  return await response.json();
@@ -3594,6 +4272,7 @@ var LimitsService;
3594
4272
  var init_limits = __esm({
3595
4273
  "src/services/limits.ts"() {
3596
4274
  "use strict";
4275
+ init_esm_shims();
3597
4276
  init_rest_request();
3598
4277
  init_routes();
3599
4278
  LimitsService = class {
@@ -3625,6 +4304,7 @@ var PeppolService;
3625
4304
  var init_peppol = __esm({
3626
4305
  "src/services/peppol.ts"() {
3627
4306
  "use strict";
4307
+ init_esm_shims();
3628
4308
  init_rest_request();
3629
4309
  init_routes();
3630
4310
  PeppolService = class {
@@ -3648,6 +4328,7 @@ var TestDataService;
3648
4328
  var init_test_data = __esm({
3649
4329
  "src/services/test-data.ts"() {
3650
4330
  "use strict";
4331
+ init_esm_shims();
3651
4332
  init_rest_request();
3652
4333
  init_routes();
3653
4334
  init_ksef_error();
@@ -3767,6 +4448,7 @@ var CertificateFetcher;
3767
4448
  var init_certificate_fetcher = __esm({
3768
4449
  "src/crypto/certificate-fetcher.ts"() {
3769
4450
  "use strict";
4451
+ init_esm_shims();
3770
4452
  init_rest_request();
3771
4453
  init_routes();
3772
4454
  CertificateFetcher = class {
@@ -3862,6 +4544,7 @@ var CryptographyService;
3862
4544
  var init_cryptography_service = __esm({
3863
4545
  "src/crypto/cryptography-service.ts"() {
3864
4546
  "use strict";
4547
+ init_esm_shims();
3865
4548
  CryptographyService = class {
3866
4549
  fetcher;
3867
4550
  constructor(fetcher) {
@@ -4099,6 +4782,40 @@ __export(signature_service_exports, {
4099
4782
  import * as crypto3 from "crypto";
4100
4783
  import { ExclusiveCanonicalization } from "xml-crypto";
4101
4784
  import { DOMParser as DOMParser2, XMLSerializer } from "@xmldom/xmldom";
4785
+ function pickRsaAlgo() {
4786
+ return {
4787
+ nodeHashName: "sha256",
4788
+ signatureUri: RSA_SHA256_SIGNATURE_URI,
4789
+ digestUri: DIGEST_URI.sha256
4790
+ };
4791
+ }
4792
+ function pickEcdsaAlgo(privateKey) {
4793
+ const curve = privateKey.asymmetricKeyDetails?.namedCurve;
4794
+ switch (curve) {
4795
+ case "prime256v1":
4796
+ return {
4797
+ nodeHashName: "sha256",
4798
+ signatureUri: ECDSA_SIGNATURE_URI.sha256,
4799
+ digestUri: DIGEST_URI.sha256
4800
+ };
4801
+ case "secp384r1":
4802
+ return {
4803
+ nodeHashName: "sha384",
4804
+ signatureUri: ECDSA_SIGNATURE_URI.sha384,
4805
+ digestUri: DIGEST_URI.sha384
4806
+ };
4807
+ case "secp521r1":
4808
+ return {
4809
+ nodeHashName: "sha512",
4810
+ signatureUri: ECDSA_SIGNATURE_URI.sha512,
4811
+ digestUri: DIGEST_URI.sha512
4812
+ };
4813
+ default:
4814
+ throw new KSeFError(
4815
+ `Unsupported ECDSA curve: ${curve ?? "unknown"}. Supported: P-256 (prime256v1), P-384 (secp384r1), P-521 (secp521r1).`
4816
+ );
4817
+ }
4818
+ }
4102
4819
  function extractDerFromPem(pem) {
4103
4820
  const base64 = pem.replace(/-----BEGIN [A-Z\s]+-----/g, "").replace(/-----END [A-Z\s]+-----/g, "").replace(/\s+/g, "");
4104
4821
  return Buffer.from(base64, "base64");
@@ -4113,22 +4830,22 @@ function canonicalize(elem) {
4113
4830
  const c14n = new ExclusiveCanonicalization();
4114
4831
  return c14n.process(elem, {});
4115
4832
  }
4116
- function computeRootDigest(doc) {
4833
+ function computeRootDigest(doc, hashName) {
4117
4834
  const root = doc.documentElement;
4118
4835
  const canonical = canonicalize(root);
4119
- return crypto3.createHash("sha256").update(canonical, "utf-8").digest("base64");
4836
+ return crypto3.createHash(hashName).update(canonical, "utf-8").digest("base64");
4120
4837
  }
4121
- function computeSignedPropertiesDigest(qualifyingPropertiesXml) {
4122
- const parser = new DOMParser2();
4123
- const qpDoc = parser.parseFromString(qualifyingPropertiesXml, "text/xml");
4838
+ function computeSignedPropertiesDigest(qualifyingPropertiesXml, hashName) {
4839
+ const parser2 = new DOMParser2();
4840
+ const qpDoc = parser2.parseFromString(qualifyingPropertiesXml, "text/xml");
4124
4841
  const signedProps = findElementByLocalName(qpDoc.documentElement, "SignedProperties");
4125
4842
  if (!signedProps) {
4126
4843
  throw new Error("SignedProperties element not found in QualifyingProperties");
4127
4844
  }
4128
4845
  const canonical = canonicalize(signedProps);
4129
- return crypto3.createHash("sha256").update(canonical, "utf-8").digest("base64");
4846
+ return crypto3.createHash(hashName).update(canonical, "utf-8").digest("base64");
4130
4847
  }
4131
- function buildSignedInfo(signatureAlgorithm, rootDigest, signedPropertiesDigest) {
4848
+ function buildSignedInfo(signatureAlgorithm, digestAlgorithm, rootDigest, signedPropertiesDigest) {
4132
4849
  return [
4133
4850
  `<ds:SignedInfo xmlns:ds="${DS_NS}">`,
4134
4851
  `<ds:CanonicalizationMethod Algorithm="${EXC_C14N_ALGORITHM}"/>`,
@@ -4139,7 +4856,7 @@ function buildSignedInfo(signatureAlgorithm, rootDigest, signedPropertiesDigest)
4139
4856
  `<ds:Transform Algorithm="${ENVELOPED_SIGNATURE_TRANSFORM}"/>`,
4140
4857
  `<ds:Transform Algorithm="${EXC_C14N_ALGORITHM}"/>`,
4141
4858
  `</ds:Transforms>`,
4142
- `<ds:DigestMethod Algorithm="${SHA256_DIGEST_METHOD}"/>`,
4859
+ `<ds:DigestMethod Algorithm="${digestAlgorithm}"/>`,
4143
4860
  `<ds:DigestValue>${rootDigest}</ds:DigestValue>`,
4144
4861
  `</ds:Reference>`,
4145
4862
  // Reference 2: SignedProperties
@@ -4147,22 +4864,22 @@ function buildSignedInfo(signatureAlgorithm, rootDigest, signedPropertiesDigest)
4147
4864
  `<ds:Transforms>`,
4148
4865
  `<ds:Transform Algorithm="${EXC_C14N_ALGORITHM}"/>`,
4149
4866
  `</ds:Transforms>`,
4150
- `<ds:DigestMethod Algorithm="${SHA256_DIGEST_METHOD}"/>`,
4867
+ `<ds:DigestMethod Algorithm="${digestAlgorithm}"/>`,
4151
4868
  `<ds:DigestValue>${signedPropertiesDigest}</ds:DigestValue>`,
4152
4869
  `</ds:Reference>`,
4153
4870
  `</ds:SignedInfo>`
4154
4871
  ].join("");
4155
4872
  }
4156
- function computeSignatureValue(canonicalSignedInfo, privateKey, isEc) {
4873
+ function computeSignatureValue(canonicalSignedInfo, privateKey, isEc, hashName) {
4157
4874
  const data = Buffer.from(canonicalSignedInfo, "utf-8");
4158
4875
  let signature;
4159
4876
  if (isEc) {
4160
- signature = crypto3.sign("sha256", data, {
4877
+ signature = crypto3.sign(hashName, data, {
4161
4878
  key: privateKey,
4162
4879
  dsaEncoding: "ieee-p1363"
4163
4880
  });
4164
4881
  } else {
4165
- signature = crypto3.sign("sha256", data, privateKey);
4882
+ signature = crypto3.sign(hashName, data, privateKey);
4166
4883
  }
4167
4884
  return signature.toString("base64");
4168
4885
  }
@@ -4183,7 +4900,7 @@ function buildSignatureElement(signedInfoXml, signatureValue, certBase64, qualif
4183
4900
  `</ds:Signature>`
4184
4901
  ].join("");
4185
4902
  }
4186
- function buildQualifyingProperties(signatureId, signedPropertiesId, certDigest, issuerName, serialNumber, signingTime) {
4903
+ function buildQualifyingProperties(signatureId, signedPropertiesId, certDigest, issuerName, serialNumber, signingTime, digestAlgorithm) {
4187
4904
  return [
4188
4905
  `<xades:QualifyingProperties`,
4189
4906
  ` Target="#${signatureId}"`,
@@ -4195,7 +4912,7 @@ function buildQualifyingProperties(signatureId, signedPropertiesId, certDigest,
4195
4912
  `<xades:SigningCertificate>`,
4196
4913
  `<xades:Cert>`,
4197
4914
  `<xades:CertDigest>`,
4198
- `<DigestMethod Algorithm="${SHA256_DIGEST_METHOD}"/>`,
4915
+ `<DigestMethod Algorithm="${digestAlgorithm}"/>`,
4199
4916
  `<DigestValue>${certDigest}</DigestValue>`,
4200
4917
  `</xades:CertDigest>`,
4201
4918
  `<xades:IssuerSerial>`,
@@ -4231,18 +4948,28 @@ function wrapBase64(base64) {
4231
4948
  }
4232
4949
  return lines.join("\n");
4233
4950
  }
4234
- var XADES_NS, DS_NS, SIGNED_PROPERTIES_TYPE, SHA256_DIGEST_METHOD, EXC_C14N_ALGORITHM, ENVELOPED_SIGNATURE_TRANSFORM, RSA_SHA256_SIGNATURE, ECDSA_SHA256_SIGNATURE, CLOCK_SKEW_BUFFER_MS, SIGNATURE_ID, SIGNED_PROPERTIES_ID, SignatureService;
4951
+ var XADES_NS, DS_NS, SIGNED_PROPERTIES_TYPE, EXC_C14N_ALGORITHM, ENVELOPED_SIGNATURE_TRANSFORM, DIGEST_URI, ECDSA_SIGNATURE_URI, RSA_SHA256_SIGNATURE_URI, CLOCK_SKEW_BUFFER_MS, SIGNATURE_ID, SIGNED_PROPERTIES_ID, SignatureService;
4235
4952
  var init_signature_service = __esm({
4236
4953
  "src/crypto/signature-service.ts"() {
4237
4954
  "use strict";
4955
+ init_esm_shims();
4956
+ init_ksef_error();
4238
4957
  XADES_NS = "http://uri.etsi.org/01903/v1.3.2#";
4239
4958
  DS_NS = "http://www.w3.org/2000/09/xmldsig#";
4240
4959
  SIGNED_PROPERTIES_TYPE = "http://uri.etsi.org/01903#SignedProperties";
4241
- SHA256_DIGEST_METHOD = "http://www.w3.org/2001/04/xmlenc#sha256";
4242
4960
  EXC_C14N_ALGORITHM = "http://www.w3.org/2001/10/xml-exc-c14n#";
4243
4961
  ENVELOPED_SIGNATURE_TRANSFORM = "http://www.w3.org/2000/09/xmldsig#enveloped-signature";
4244
- RSA_SHA256_SIGNATURE = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256";
4245
- ECDSA_SHA256_SIGNATURE = "http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha256";
4962
+ DIGEST_URI = {
4963
+ sha256: "http://www.w3.org/2001/04/xmlenc#sha256",
4964
+ sha384: "http://www.w3.org/2001/04/xmldsig-more#sha384",
4965
+ sha512: "http://www.w3.org/2001/04/xmlenc#sha512"
4966
+ };
4967
+ ECDSA_SIGNATURE_URI = {
4968
+ sha256: "http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha256",
4969
+ sha384: "http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha384",
4970
+ sha512: "http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha512"
4971
+ };
4972
+ RSA_SHA256_SIGNATURE_URI = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256";
4246
4973
  CLOCK_SKEW_BUFFER_MS = -6e4;
4247
4974
  SIGNATURE_ID = "Signature";
4248
4975
  SIGNED_PROPERTIES_ID = "SignedProperties";
@@ -4262,18 +4989,24 @@ var init_signature_service = __esm({
4262
4989
  }
4263
4990
  const certDer = extractDerFromPem(certPem);
4264
4991
  const certBase64 = certDer.toString("base64");
4265
- const certDigest = crypto3.createHash("sha256").update(certDer).digest("base64");
4266
4992
  const x5093 = new crypto3.X509Certificate(certPem);
4267
4993
  const issuerName = normalizeIssuerDn(x5093.issuer);
4268
4994
  const serialNumber = hexSerialToDecimal(x5093.serialNumber);
4269
4995
  const privateKey = crypto3.createPrivateKey(
4270
4996
  passphrase ? { key: privateKeyPem, format: "pem", passphrase } : privateKeyPem
4271
4997
  );
4272
- const isEc = privateKey.asymmetricKeyType === "ec";
4273
- const signatureAlgorithm = isEc ? ECDSA_SHA256_SIGNATURE : RSA_SHA256_SIGNATURE;
4998
+ const keyType = privateKey.asymmetricKeyType;
4999
+ if (keyType !== "ec" && keyType !== "rsa") {
5000
+ throw new KSeFError(
5001
+ `Unsupported private key type: ${keyType ?? "unknown"}. Supported: RSA and ECDSA.`
5002
+ );
5003
+ }
5004
+ const isEc = keyType === "ec";
5005
+ const algo = isEc ? pickEcdsaAlgo(privateKey) : pickRsaAlgo();
5006
+ const certDigest = crypto3.createHash(algo.nodeHashName).update(certDer).digest("base64");
4274
5007
  const signingTime = new Date(Date.now() + CLOCK_SKEW_BUFFER_MS).toISOString();
4275
- const parser = new DOMParser2();
4276
- const doc = parser.parseFromString(xml, "text/xml");
5008
+ const parser2 = new DOMParser2();
5009
+ const doc = parser2.parseFromString(xml, "text/xml");
4277
5010
  const root = doc.documentElement;
4278
5011
  if (!root) {
4279
5012
  throw new Error("XML document has no root element");
@@ -4284,21 +5017,27 @@ var init_signature_service = __esm({
4284
5017
  certDigest,
4285
5018
  issuerName,
4286
5019
  serialNumber,
4287
- signingTime
5020
+ signingTime,
5021
+ algo.digestUri
5022
+ );
5023
+ const rootDigest = computeRootDigest(doc, algo.nodeHashName);
5024
+ const signedPropertiesDigest = computeSignedPropertiesDigest(
5025
+ qualifyingPropertiesXml,
5026
+ algo.nodeHashName
4288
5027
  );
4289
- const rootDigest = computeRootDigest(doc);
4290
- const signedPropertiesDigest = computeSignedPropertiesDigest(qualifyingPropertiesXml);
4291
5028
  const signedInfoXml = buildSignedInfo(
4292
- signatureAlgorithm,
5029
+ algo.signatureUri,
5030
+ algo.digestUri,
4293
5031
  rootDigest,
4294
5032
  signedPropertiesDigest
4295
5033
  );
4296
- const signedInfoDoc = parser.parseFromString(signedInfoXml, "text/xml");
5034
+ const signedInfoDoc = parser2.parseFromString(signedInfoXml, "text/xml");
4297
5035
  const canonicalSignedInfo = canonicalize(signedInfoDoc.documentElement);
4298
5036
  const signatureValue = computeSignatureValue(
4299
5037
  canonicalSignedInfo,
4300
5038
  privateKey,
4301
- isEc
5039
+ isEc,
5040
+ algo.nodeHashName
4302
5041
  );
4303
5042
  const signatureXml = buildSignatureElement(
4304
5043
  signedInfoXml,
@@ -4306,7 +5045,7 @@ var init_signature_service = __esm({
4306
5045
  certBase64,
4307
5046
  qualifyingPropertiesXml
4308
5047
  );
4309
- const signatureDoc = parser.parseFromString(signatureXml, "text/xml");
5048
+ const signatureDoc = parser2.parseFromString(signatureXml, "text/xml");
4310
5049
  const importedNode = doc.importNode(signatureDoc.documentElement, true);
4311
5050
  root.appendChild(importedNode);
4312
5051
  return new XMLSerializer().serializeToString(doc);
@@ -4325,6 +5064,7 @@ var Pkcs12Loader;
4325
5064
  var init_pkcs12_loader = __esm({
4326
5065
  "src/crypto/pkcs12-loader.ts"() {
4327
5066
  "use strict";
5067
+ init_esm_shims();
4328
5068
  Pkcs12Loader = class {
4329
5069
  static load(p12, password) {
4330
5070
  const { pki, pkcs12, asn1 } = forge;
@@ -4393,6 +5133,7 @@ var AUTH_TOKEN_REQUEST_NS;
4393
5133
  var init_auth_xml_builder = __esm({
4394
5134
  "src/crypto/auth-xml-builder.ts"() {
4395
5135
  "use strict";
5136
+ init_esm_shims();
4396
5137
  AUTH_TOKEN_REQUEST_NS = "http://ksef.mf.gov.pl/auth/token/2.0";
4397
5138
  }
4398
5139
  });
@@ -4403,6 +5144,7 @@ var VerificationLinkService;
4403
5144
  var init_verification_link_service = __esm({
4404
5145
  "src/qr/verification-link-service.ts"() {
4405
5146
  "use strict";
5147
+ init_esm_shims();
4406
5148
  VerificationLinkService = class {
4407
5149
  constructor(baseQrUrl) {
4408
5150
  this.baseQrUrl = baseQrUrl;
@@ -4424,11 +5166,11 @@ var init_verification_link_service = __esm({
4424
5166
  * Build certificate verification URL (Code II).
4425
5167
  * Format: {baseQrUrl}/certificate/{contextType}/{contextId}/{sellerNip}/{certSerial}/{hash_base64url}/{signature_base64url}
4426
5168
  */
4427
- buildCertificateVerificationUrl(contextType, contextId, sellerNip, certSerial, invoiceHashBase64, privateKeyPem) {
5169
+ buildCertificateVerificationUrl(contextType, contextId, sellerNip, certSerial, invoiceHashBase64, privateKeyPem, privateKeyPassword) {
4428
5170
  const hashBase64Url = this.base64ToBase64Url(invoiceHashBase64);
4429
5171
  const pathWithoutSignature = `${this.baseQrUrl}/certificate/${contextType}/${contextId}/${sellerNip}/${certSerial}/${hashBase64Url}`;
4430
5172
  const dataToSign = pathWithoutSignature.replace(/^https?:\/\//, "");
4431
- const key = crypto5.createPrivateKey(privateKeyPem);
5173
+ const key = privateKeyPassword !== void 0 ? crypto5.createPrivateKey({ key: privateKeyPem, format: "pem", passphrase: privateKeyPassword }) : crypto5.createPrivateKey(privateKeyPem);
4432
5174
  let signature;
4433
5175
  if (key.asymmetricKeyType === "rsa") {
4434
5176
  signature = crypto5.sign("sha256", Buffer.from(dataToSign), {
@@ -4544,6 +5286,7 @@ var DEFAULT_UNZIP_OPTIONS;
4544
5286
  var init_zip = __esm({
4545
5287
  "src/utils/zip.ts"() {
4546
5288
  "use strict";
5289
+ init_esm_shims();
4547
5290
  DEFAULT_UNZIP_OPTIONS = {
4548
5291
  maxFiles: 1e4,
4549
5292
  maxTotalUncompressedSize: 2e9,
@@ -4615,6 +5358,7 @@ var holidayCache;
4615
5358
  var init_holidays = __esm({
4616
5359
  "src/offline/holidays.ts"() {
4617
5360
  "use strict";
5361
+ init_esm_shims();
4618
5362
  holidayCache = /* @__PURE__ */ new Map();
4619
5363
  }
4620
5364
  });
@@ -4714,6 +5458,7 @@ var FAR_FUTURE;
4714
5458
  var init_deadline = __esm({
4715
5459
  "src/offline/deadline.ts"() {
4716
5460
  "use strict";
5461
+ init_esm_shims();
4717
5462
  init_holidays();
4718
5463
  FAR_FUTURE = /* @__PURE__ */ new Date("9999-12-31T23:59:59Z");
4719
5464
  }
@@ -4725,6 +5470,7 @@ var OfflineInvoiceWorkflow;
4725
5470
  var init_offline_invoice_workflow = __esm({
4726
5471
  "src/workflows/offline-invoice-workflow.ts"() {
4727
5472
  "use strict";
5473
+ init_esm_shims();
4728
5474
  init_ksef_api_error();
4729
5475
  init_deadline();
4730
5476
  init_document_structures();
@@ -4758,7 +5504,8 @@ var init_offline_invoice_workflow = __esm({
4758
5504
  input.sellerNip,
4759
5505
  options.certificate.certificateSerial,
4760
5506
  invoiceHashBase64,
4761
- options.certificate.privateKeyPem
5507
+ options.certificate.privateKeyPem,
5508
+ options.certificate.password
4762
5509
  );
4763
5510
  }
4764
5511
  const submitBy = options?.customDeadline ? typeof options.customDeadline === "string" ? options.customDeadline : options.customDeadline.toISOString() : calculateOfflineDeadline(mode, input.invoiceDate, options?.maintenanceWindow).toISOString();
@@ -4948,7 +5695,8 @@ var init_offline_invoice_workflow = __esm({
4948
5695
  original.sellerNip,
4949
5696
  options.certificate.certificateSerial,
4950
5697
  correctedHashBase64,
4951
- options.certificate.privateKeyPem
5698
+ options.certificate.privateKeyPem,
5699
+ options.certificate.password
4952
5700
  );
4953
5701
  }
4954
5702
  const correctionMetadata = {
@@ -5034,6 +5782,11 @@ function buildRestClientConfig(options, authManager) {
5034
5782
  endpointLimits: options.rateLimit.endpointLimits
5035
5783
  });
5036
5784
  }
5785
+ if (options?.circuitBreaker === null) {
5786
+ config.circuitBreakerPolicy = null;
5787
+ } else if (options?.circuitBreaker) {
5788
+ config.circuitBreakerPolicy = new CircuitBreakerPolicy(options.circuitBreaker);
5789
+ }
5037
5790
  if (options?.presignedUrlHosts) {
5038
5791
  const base = defaultPresignedUrlPolicy();
5039
5792
  config.presignedUrlPolicy = {
@@ -5047,10 +5800,12 @@ var KSeFClient;
5047
5800
  var init_client = __esm({
5048
5801
  "src/client.ts"() {
5049
5802
  "use strict";
5803
+ init_esm_shims();
5050
5804
  init_config();
5051
5805
  init_rest_client();
5052
5806
  init_retry_policy();
5053
5807
  init_rate_limit_policy();
5808
+ init_circuit_breaker_policy();
5054
5809
  init_presigned_url_policy();
5055
5810
  init_auth_manager();
5056
5811
  init_auth();
@@ -5184,10 +5939,12 @@ var init_client = __esm({
5184
5939
  });
5185
5940
 
5186
5941
  // src/index.ts
5942
+ init_esm_shims();
5187
5943
  init_config();
5188
5944
  init_errors();
5189
5945
 
5190
5946
  // src/http/index.ts
5947
+ init_esm_shims();
5191
5948
  init_route_builder();
5192
5949
  init_rest_request();
5193
5950
  init_rest_client();
@@ -5195,14 +5952,17 @@ init_routes();
5195
5952
  init_transport();
5196
5953
  init_retry_policy();
5197
5954
  init_rate_limit_policy();
5955
+ init_circuit_breaker_policy();
5198
5956
  init_auth_manager();
5199
5957
  init_presigned_url_policy();
5200
5958
  init_ksef_feature();
5201
5959
 
5202
5960
  // src/validation/index.ts
5961
+ init_esm_shims();
5203
5962
  init_patterns();
5204
5963
 
5205
5964
  // src/validation/constraints.ts
5965
+ init_esm_shims();
5206
5966
  var REQUIRED_CHALLENGE_LENGTH = 36;
5207
5967
  var CERTIFICATE_NAME_MIN_LENGTH = 5;
5208
5968
  var CERTIFICATE_NAME_MAX_LENGTH = 100;
@@ -5215,11 +5975,220 @@ var PERMISSION_DESCRIPTION_MAX_LENGTH = 256;
5215
5975
  init_xml_to_object();
5216
5976
  init_schema_registry();
5217
5977
  init_invoice_validator();
5978
+ init_char_validity();
5979
+
5980
+ // src/validation/xsd-validator.ts
5981
+ init_esm_shims();
5982
+ import { createRequire } from "module";
5983
+ import * as fs from "fs";
5984
+ import * as path2 from "path";
5985
+ import { fileURLToPath as fileURLToPath2, pathToFileURL } from "url";
5986
+ var cachedPkgRoot = null;
5987
+ function locatePackageRoot() {
5988
+ if (cachedPkgRoot !== null) return cachedPkgRoot;
5989
+ let dir = path2.dirname(fileURLToPath2(import.meta.url));
5990
+ const root = path2.parse(dir).root;
5991
+ while (dir !== root) {
5992
+ const candidate = path2.join(dir, "docs", "schemas");
5993
+ if (fs.existsSync(candidate)) {
5994
+ cachedPkgRoot = dir;
5995
+ return dir;
5996
+ }
5997
+ dir = path2.dirname(dir);
5998
+ }
5999
+ throw new Error("Could not locate ksef-client-ts package root (docs/schemas not found).");
6000
+ }
6001
+ var XSD_RELATIVE = {
6002
+ FA2: ["FA", "schemat_FA(2)_v1-0E.xsd"],
6003
+ FA3: ["FA", "schemat_FA(3)_v1-0E.xsd"],
6004
+ PEF: ["PEF", "Schemat_PEF(3)_v2-1.xsd"],
6005
+ PEF_KOR: ["PEF", "Schemat_PEF_KOR(3)_v2-1.xsd"]
6006
+ };
6007
+ var FA_XSD_PATHS = {
6008
+ get FA2() {
6009
+ return resolveXsdFor("FA2");
6010
+ },
6011
+ get FA3() {
6012
+ return resolveXsdFor("FA3");
6013
+ }
6014
+ };
6015
+ var PEF_XSD_PATHS = {
6016
+ get PEF() {
6017
+ return resolveXsdFor("PEF");
6018
+ },
6019
+ get PEF_KOR() {
6020
+ return resolveXsdFor("PEF_KOR");
6021
+ }
6022
+ };
6023
+ function resolveXsdFor(schema) {
6024
+ const rel = XSD_RELATIVE[schema];
6025
+ if (!rel) throw new Error(`Unknown invoice schema: ${String(schema)}`);
6026
+ return path2.join(locatePackageRoot(), "docs", "schemas", ...rel);
6027
+ }
6028
+ var requireModule = createRequire(import.meta.url);
6029
+ var libxmljs = null;
6030
+ var libxmljsLoadError = null;
6031
+ try {
6032
+ libxmljs = requireModule("libxmljs2");
6033
+ } catch (err) {
6034
+ const code = err?.code;
6035
+ if (code === "MODULE_NOT_FOUND" || code === "ERR_MODULE_NOT_FOUND") {
6036
+ libxmljs = null;
6037
+ } else {
6038
+ libxmljs = null;
6039
+ libxmljsLoadError = err instanceof Error ? err : new Error(String(err));
6040
+ }
6041
+ }
6042
+ var libxmljsAvailable = libxmljs !== null;
6043
+ var MISSING_LIBXMLJS_MESSAGE_PREFIX = "libxmljs2 is not installed";
6044
+ var EXTERNAL_STRUKTURY_DANYCH_URL = /schemaLocation="http:\/\/crd\.gov\.pl\/xml\/schematy\/dziedzinowe\/mf\/2022\/01\/05\/eD\/DefinicjeTypy\/StrukturyDanych_v10-0E\.xsd"/;
6045
+ function rewriteSchemaLocations(xsdContent) {
6046
+ if (!EXTERNAL_STRUKTURY_DANYCH_URL.test(xsdContent)) {
6047
+ return xsdContent;
6048
+ }
6049
+ const bazoweStrukturyPath = path2.join(
6050
+ locatePackageRoot(),
6051
+ "docs",
6052
+ "schemas",
6053
+ "FA",
6054
+ "bazowe",
6055
+ "StrukturyDanych_v10-0E.xsd"
6056
+ );
6057
+ const bazoweStrukturyUrl = pathToFileURL(bazoweStrukturyPath).href;
6058
+ const rewritten = xsdContent.replace(
6059
+ EXTERNAL_STRUKTURY_DANYCH_URL,
6060
+ `schemaLocation="${bazoweStrukturyUrl}"`
6061
+ );
6062
+ if (rewritten === xsdContent) {
6063
+ throw new Error(
6064
+ "FA XSD schemaLocation rewrite produced no replacement despite URL being present; regex likely out of sync with docs/schemas/FA/. Re-check after `yarn sync-schemas`."
6065
+ );
6066
+ }
6067
+ return rewritten;
6068
+ }
6069
+ function validateAgainstXsd(xml, xsdPath) {
6070
+ if (!libxmljs) {
6071
+ const loadSuffix = libxmljsLoadError ? ` (load failed: ${libxmljsLoadError.message})` : "";
6072
+ throw new Error(
6073
+ `${MISSING_LIBXMLJS_MESSAGE_PREFIX}${loadSuffix}; cannot run XSD validation. Install it as an optional peer dependency (e.g. \`yarn add -O libxmljs2\` or \`npm i -O libxmljs2\`).`
6074
+ );
6075
+ }
6076
+ const xsdDir = path2.dirname(xsdPath);
6077
+ const rawXsd = fs.readFileSync(xsdPath, "utf8");
6078
+ const rewrittenXsd = rewriteSchemaLocations(rawXsd);
6079
+ const baseUrl = pathToFileURL(xsdDir + path2.sep).href;
6080
+ let schemaDoc;
6081
+ try {
6082
+ schemaDoc = libxmljs.parseXml(rewrittenXsd, { baseUrl });
6083
+ } catch (err) {
6084
+ return { valid: false, errors: [`XSD parse failed: ${err.message}`] };
6085
+ }
6086
+ let xmlDoc;
6087
+ try {
6088
+ xmlDoc = libxmljs.parseXml(xml);
6089
+ } catch (err) {
6090
+ return { valid: false, errors: [`XML parse failed: ${err.message}`] };
6091
+ }
6092
+ const valid = xmlDoc.validate(schemaDoc);
6093
+ const errors = valid ? [] : xmlDoc.validationErrors.map((err) => err.message.trim());
6094
+ return { valid, errors };
6095
+ }
6096
+
6097
+ // src/models/index.ts
6098
+ init_esm_shims();
6099
+
6100
+ // src/models/common.ts
6101
+ init_esm_shims();
6102
+
6103
+ // src/models/auth/index.ts
6104
+ init_esm_shims();
6105
+
6106
+ // src/models/auth/types.ts
6107
+ init_esm_shims();
6108
+
6109
+ // src/models/auth/active-sessions-types.ts
6110
+ init_esm_shims();
6111
+
6112
+ // src/models/sessions/index.ts
6113
+ init_esm_shims();
6114
+
6115
+ // src/models/sessions/online-types.ts
6116
+ init_esm_shims();
6117
+
6118
+ // src/models/sessions/batch-types.ts
6119
+ init_esm_shims();
6120
+
6121
+ // src/models/sessions/status-types.ts
6122
+ init_esm_shims();
6123
+
6124
+ // src/models/sessions/session-state.ts
6125
+ init_esm_shims();
6126
+
6127
+ // src/models/invoices/index.ts
6128
+ init_esm_shims();
6129
+
6130
+ // src/models/invoices/types.ts
6131
+ init_esm_shims();
6132
+
6133
+ // src/models/permissions/index.ts
6134
+ init_esm_shims();
6135
+
6136
+ // src/models/permissions/types.ts
6137
+ init_esm_shims();
6138
+
6139
+ // src/models/tokens/index.ts
6140
+ init_esm_shims();
6141
+
6142
+ // src/models/tokens/types.ts
6143
+ init_esm_shims();
6144
+
6145
+ // src/models/certificates/index.ts
6146
+ init_esm_shims();
6147
+
6148
+ // src/models/certificates/types.ts
6149
+ init_esm_shims();
6150
+
6151
+ // src/models/lighthouse/index.ts
6152
+ init_esm_shims();
6153
+
6154
+ // src/models/lighthouse/types.ts
6155
+ init_esm_shims();
6156
+
6157
+ // src/models/limits/index.ts
6158
+ init_esm_shims();
6159
+
6160
+ // src/models/limits/types.ts
6161
+ init_esm_shims();
6162
+
6163
+ // src/models/peppol/index.ts
6164
+ init_esm_shims();
6165
+
6166
+ // src/models/peppol/types.ts
6167
+ init_esm_shims();
6168
+
6169
+ // src/models/test-data/index.ts
6170
+ init_esm_shims();
6171
+
6172
+ // src/models/test-data/types.ts
6173
+ init_esm_shims();
6174
+
6175
+ // src/models/crypto/index.ts
6176
+ init_esm_shims();
6177
+
6178
+ // src/models/crypto/types.ts
6179
+ init_esm_shims();
6180
+
6181
+ // src/models/qrcode/index.ts
6182
+ init_esm_shims();
6183
+
6184
+ // src/models/qrcode/types.ts
6185
+ init_esm_shims();
5218
6186
 
5219
6187
  // src/models/index.ts
5220
6188
  init_document_structures();
5221
6189
 
5222
6190
  // src/services/index.ts
6191
+ init_esm_shims();
5223
6192
  init_auth();
5224
6193
  init_active_sessions();
5225
6194
  init_online_session();
@@ -5234,7 +6203,11 @@ init_limits();
5234
6203
  init_peppol();
5235
6204
  init_test_data();
5236
6205
 
6206
+ // src/builders/index.ts
6207
+ init_esm_shims();
6208
+
5237
6209
  // src/builders/auth-token-request.ts
6210
+ init_esm_shims();
5238
6211
  init_ksef_validation_error();
5239
6212
  var AuthTokenRequestBuilder = class {
5240
6213
  challenge;
@@ -5289,6 +6262,7 @@ var AuthTokenRequestBuilder = class {
5289
6262
  };
5290
6263
 
5291
6264
  // src/builders/auth-ksef-token-request.ts
6265
+ init_esm_shims();
5292
6266
  init_ksef_validation_error();
5293
6267
  var AuthKsefTokenRequestBuilder = class {
5294
6268
  challenge;
@@ -5343,6 +6317,7 @@ var AuthKsefTokenRequestBuilder = class {
5343
6317
  };
5344
6318
 
5345
6319
  // src/builders/invoice-query-filter.ts
6320
+ init_esm_shims();
5346
6321
  init_ksef_validation_error();
5347
6322
  var InvoiceQueryFilterBuilder = class {
5348
6323
  subjectType;
@@ -5439,7 +6414,11 @@ var InvoiceQueryFilterBuilder = class {
5439
6414
  }
5440
6415
  };
5441
6416
 
6417
+ // src/builders/permissions/index.ts
6418
+ init_esm_shims();
6419
+
5442
6420
  // src/builders/permissions/person-permission.ts
6421
+ init_esm_shims();
5443
6422
  init_ksef_validation_error();
5444
6423
  var PersonPermissionGrantBuilder = class {
5445
6424
  subjectIdentifier;
@@ -5489,6 +6468,7 @@ var PersonPermissionGrantBuilder = class {
5489
6468
  };
5490
6469
 
5491
6470
  // src/builders/permissions/entity-permission.ts
6471
+ init_esm_shims();
5492
6472
  init_ksef_validation_error();
5493
6473
  var EntityPermissionGrantBuilder = class {
5494
6474
  nip;
@@ -5538,6 +6518,7 @@ var EntityPermissionGrantBuilder = class {
5538
6518
  };
5539
6519
 
5540
6520
  // src/builders/permissions/authorization-permission.ts
6521
+ init_esm_shims();
5541
6522
  init_ksef_validation_error();
5542
6523
  var AuthorizationPermissionGrantBuilder = class {
5543
6524
  _subjectIdentifier;
@@ -5583,6 +6564,7 @@ var AuthorizationPermissionGrantBuilder = class {
5583
6564
  };
5584
6565
 
5585
6566
  // src/builders/batch-file.ts
6567
+ init_esm_shims();
5586
6568
  init_ksef_validation_error();
5587
6569
  import * as crypto from "crypto";
5588
6570
  var BATCH_MAX_PART_SIZE = 1e8;
@@ -5753,11 +6735,13 @@ function sha256Base64(data) {
5753
6735
  }
5754
6736
 
5755
6737
  // src/crypto/index.ts
6738
+ init_esm_shims();
5756
6739
  init_certificate_fetcher();
5757
6740
  init_cryptography_service();
5758
6741
  init_signature_service();
5759
6742
 
5760
6743
  // src/crypto/certificate-service.ts
6744
+ init_esm_shims();
5761
6745
  import * as crypto4 from "crypto";
5762
6746
  import * as x5092 from "@peculiar/x509";
5763
6747
  var CertificateService = class {
@@ -5843,9 +6827,11 @@ init_pkcs12_loader();
5843
6827
  init_auth_xml_builder();
5844
6828
 
5845
6829
  // src/qr/index.ts
6830
+ init_esm_shims();
5846
6831
  init_verification_link_service();
5847
6832
 
5848
6833
  // src/qr/qrcode-service.ts
6834
+ init_esm_shims();
5849
6835
  import * as QRCode from "qrcode";
5850
6836
  var QrCodeService = class _QrCodeService {
5851
6837
  static async generateQrCode(url, options) {
@@ -5905,54 +6891,12 @@ function escapeXml2(str) {
5905
6891
  }
5906
6892
 
5907
6893
  // src/utils/index.ts
6894
+ init_esm_shims();
5908
6895
  init_zip();
5909
-
5910
- // src/utils/jwt.ts
5911
- function decodeJwtPayload(token) {
5912
- const parts = token.split(".");
5913
- if (parts.length !== 3) return null;
5914
- try {
5915
- const payload = parts[1];
5916
- const json = Buffer.from(payload, "base64url").toString("utf-8");
5917
- return JSON.parse(json);
5918
- } catch {
5919
- return null;
5920
- }
5921
- }
5922
- function tryParseJson(value) {
5923
- if (typeof value !== "string") return void 0;
5924
- try {
5925
- return JSON.parse(value);
5926
- } catch {
5927
- return void 0;
5928
- }
5929
- }
5930
- function tryParseJsonArray(value) {
5931
- if (typeof value !== "string") return void 0;
5932
- try {
5933
- const parsed = JSON.parse(value);
5934
- return Array.isArray(parsed) && parsed.every((item) => typeof item === "string") ? parsed : void 0;
5935
- } catch {
5936
- return void 0;
5937
- }
5938
- }
5939
- function parseKSeFTokenContext(token) {
5940
- const raw = decodeJwtPayload(token);
5941
- if (!raw) return null;
5942
- return {
5943
- type: typeof raw["typ"] === "string" ? raw["typ"] : void 0,
5944
- contextIdentifierType: typeof raw["cit"] === "string" ? raw["cit"] : void 0,
5945
- contextIdentifierValue: typeof raw["civ"] === "string" ? raw["civ"] : void 0,
5946
- authMethod: typeof raw["aum"] === "string" ? raw["aum"] : void 0,
5947
- permissions: tryParseJsonArray(raw["per"]),
5948
- subjectDetails: tryParseJson(raw["sud"]),
5949
- authorSubjectIdentifier: tryParseJson(raw["asi"]),
5950
- issuedAt: typeof raw["iat"] === "number" ? raw["iat"] : void 0,
5951
- expiresAt: typeof raw["exp"] === "number" ? raw["exp"] : void 0
5952
- };
5953
- }
6896
+ init_jwt();
5954
6897
 
5955
6898
  // src/utils/hash.ts
6899
+ init_esm_shims();
5956
6900
  import crypto6 from "crypto";
5957
6901
  function sha256Base642(data) {
5958
6902
  return crypto6.createHash("sha256").update(data).digest("base64");
@@ -5964,7 +6908,11 @@ function verifyHash(data, expectedHash) {
5964
6908
  // src/utils/index.ts
5965
6909
  init_concurrency();
5966
6910
 
6911
+ // src/workflows/index.ts
6912
+ init_esm_shims();
6913
+
5967
6914
  // src/workflows/polling.ts
6915
+ init_esm_shims();
5968
6916
  async function pollUntil(action, condition, options) {
5969
6917
  const intervalMs = options?.intervalMs ?? 2e3;
5970
6918
  const maxAttempts = options?.maxAttempts ?? 60;
@@ -5982,13 +6930,18 @@ async function pollUntil(action, condition, options) {
5982
6930
  }
5983
6931
 
5984
6932
  // src/workflows/online-session-workflow.ts
6933
+ init_esm_shims();
5985
6934
  init_ksef_session_expired_error();
5986
6935
  init_auth_manager();
5987
6936
  init_online_session();
5988
6937
  init_session_status();
5989
6938
  init_document_structures();
5990
6939
 
6940
+ // src/xml/index.ts
6941
+ init_esm_shims();
6942
+
5991
6943
  // src/xml/upo-parser.ts
6944
+ init_esm_shims();
5992
6945
  init_ksef_validation_error();
5993
6946
  import { XMLParser } from "fast-xml-parser";
5994
6947
  function isRecord(value) {
@@ -6107,6 +7060,7 @@ function parseUpoXml(xml) {
6107
7060
  }
6108
7061
 
6109
7062
  // src/xml/invoice-field-extractor.ts
7063
+ init_esm_shims();
6110
7064
  import { XMLParser as XMLParser2 } from "fast-xml-parser";
6111
7065
  var invoiceParser = new XMLParser2({
6112
7066
  ignoreAttributes: false,
@@ -6146,6 +7100,529 @@ function nonEmptyString(value) {
6146
7100
  return typeof value === "string" && value.length > 0 ? value : void 0;
6147
7101
  }
6148
7102
 
7103
+ // src/xml/xml-engine.ts
7104
+ init_esm_shims();
7105
+ import { XMLBuilder, XMLParser as XMLParser3 } from "fast-xml-parser";
7106
+ var XML_DECLARATION = '<?xml version="1.0" encoding="UTF-8"?>\n';
7107
+ var parser = new XMLParser3({
7108
+ ignoreAttributes: false,
7109
+ preserveOrder: true,
7110
+ attributeNamePrefix: "@_",
7111
+ textNodeName: "#text",
7112
+ allowBooleanAttributes: true,
7113
+ // Preserve leading zeros and keep everything as strings — KSeF fields like
7114
+ // KRS (`\d{10}`) and NIP (`\d{10}`) would otherwise be lossy through parse.
7115
+ parseTagValue: false,
7116
+ parseAttributeValue: false,
7117
+ trimValues: false
7118
+ });
7119
+ var builder = new XMLBuilder({
7120
+ ignoreAttributes: false,
7121
+ preserveOrder: true,
7122
+ attributeNamePrefix: "@_",
7123
+ textNodeName: "#text",
7124
+ format: false,
7125
+ suppressBooleanAttributes: false,
7126
+ suppressEmptyNode: false,
7127
+ processEntities: true
7128
+ });
7129
+ function createObjectBuilder(pretty = false) {
7130
+ return new XMLBuilder({
7131
+ ignoreAttributes: false,
7132
+ preserveOrder: false,
7133
+ attributeNamePrefix: "@_",
7134
+ textNodeName: "#text",
7135
+ format: pretty,
7136
+ suppressBooleanAttributes: false,
7137
+ suppressEmptyNode: false,
7138
+ processEntities: true
7139
+ });
7140
+ }
7141
+ function prependDeclaration(xml) {
7142
+ return xml.startsWith("<?xml") ? xml : `${XML_DECLARATION}${xml}`;
7143
+ }
7144
+ function parseXml(xml) {
7145
+ return parser.parse(xml);
7146
+ }
7147
+ function buildXml(document) {
7148
+ return prependDeclaration(builder.build(document));
7149
+ }
7150
+ function buildXmlFromObject(document, options) {
7151
+ return prependDeclaration(createObjectBuilder(options?.pretty).build(document));
7152
+ }
7153
+ function stripBom(input) {
7154
+ return input.charCodeAt(0) === 65279 ? input.slice(1) : input;
7155
+ }
7156
+
7157
+ // src/xml/order-map.ts
7158
+ init_esm_shims();
7159
+ var ORDER_MAP = {
7160
+ Faktura: ["Naglowek", "Podmiot1", "Podmiot2", "Podmiot3", "Fa", "Stopka"],
7161
+ Naglowek: ["KodFormularza", "WariantFormularza", "DataWytworzeniaFa", "SystemInfo"],
7162
+ Podmiot1: [
7163
+ "PrefiksPodatnika",
7164
+ "NrEORI",
7165
+ "DaneIdentyfikacyjne",
7166
+ "Adres",
7167
+ "AdresKoresp",
7168
+ "DaneKontaktowe",
7169
+ "StatusInfoPodatnika"
7170
+ ],
7171
+ Podmiot2: [
7172
+ "NrEORI",
7173
+ "DaneIdentyfikacyjne",
7174
+ "Adres",
7175
+ "AdresKoresp",
7176
+ "DaneKontaktowe",
7177
+ "NrKlienta",
7178
+ "IDNabywcy",
7179
+ "JST",
7180
+ "GV"
7181
+ ],
7182
+ Podmiot3: [
7183
+ "IDNabywcy",
7184
+ "NrEORI",
7185
+ "DaneIdentyfikacyjne",
7186
+ "Adres",
7187
+ "AdresKoresp",
7188
+ "DaneKontaktowe",
7189
+ "Rola",
7190
+ "Udzial"
7191
+ ],
7192
+ DaneIdentyfikacyjne: [
7193
+ "NIP",
7194
+ "IDWew",
7195
+ "KodUE",
7196
+ "NrVatUE",
7197
+ "KodKraju",
7198
+ "NrID",
7199
+ "BrakID",
7200
+ "Nazwa",
7201
+ "Identyfikator",
7202
+ "KRS"
7203
+ ],
7204
+ Adres: ["KodKraju", "AdresL1", "AdresL2", "AdresL3"],
7205
+ DaneKontaktowe: ["Email", "Telefon"],
7206
+ Fa: [
7207
+ "KodWaluty",
7208
+ "P_1",
7209
+ "P_1M",
7210
+ "P_2",
7211
+ "WZ",
7212
+ "P_6",
7213
+ "OkresFa",
7214
+ // Multi-rate interleave per VAT group — DO NOT flatten into P_13_* block then P_14_* block.
7215
+ // See smekcio TS d1ec8fe and the "multi-rate interleave" regression test.
7216
+ "P_13_1",
7217
+ "P_14_1",
7218
+ "P_14_1W",
7219
+ "P_13_2",
7220
+ "P_14_2",
7221
+ "P_14_2W",
7222
+ "P_13_3",
7223
+ "P_14_3",
7224
+ "P_14_3W",
7225
+ "P_13_4",
7226
+ "P_14_4",
7227
+ "P_14_4W",
7228
+ "P_13_5",
7229
+ "P_14_5",
7230
+ "P_13_6_1",
7231
+ "P_13_6_2",
7232
+ "P_13_6_3",
7233
+ "P_13_7",
7234
+ "P_13_8",
7235
+ "P_13_9",
7236
+ "P_13_10",
7237
+ "P_13_11",
7238
+ "P_15",
7239
+ "KursWalutyZ",
7240
+ "Adnotacje",
7241
+ "RodzajFaktury",
7242
+ "PrzyczynaKorekty",
7243
+ "TypKorekty",
7244
+ "DaneFaKorygowanej",
7245
+ "OkresFaKorygowanej",
7246
+ "NrFaKorygowany",
7247
+ "Podmiot1K",
7248
+ "Podmiot2K",
7249
+ "Podmiot3K",
7250
+ "ZaliczkaCzesciowa",
7251
+ "FP",
7252
+ "TP",
7253
+ "DodatkowyOpis",
7254
+ "FakturaZaliczkowa",
7255
+ "ZwrotAkcyzy",
7256
+ "FaWiersz",
7257
+ "FaWiersze",
7258
+ "Rozliczenie",
7259
+ "Platnosc"
7260
+ ],
7261
+ Adnotacje: ["P_16", "P_17", "P_18", "P_18A", "Zwolnienie", "NoweSrodkiTransportu", "P_23", "PMarzy"],
7262
+ OkresFa: ["P_6_Od", "P_6_Do"],
7263
+ FaWiersz: [
7264
+ "NrWierszaFa",
7265
+ "UU_ID",
7266
+ "P_6A",
7267
+ "P_7",
7268
+ "Indeks",
7269
+ "GTIN",
7270
+ "PKWiU",
7271
+ "CN",
7272
+ "PKOB",
7273
+ "P_8A",
7274
+ "P_8B",
7275
+ "P_9A",
7276
+ "P_9B",
7277
+ "P_10",
7278
+ "P_11",
7279
+ "P_11A",
7280
+ "P_11Vat",
7281
+ "P_12",
7282
+ "P_12_XII",
7283
+ "P_12_Zal_15",
7284
+ "KwotaAkcyzy",
7285
+ "GTU",
7286
+ "Procedura",
7287
+ "KursWaluty",
7288
+ "StanPrzed"
7289
+ ]
7290
+ };
7291
+ function comparePKey(a, b) {
7292
+ const normalize = (value) => value.replace(/^P_/, "").split("_").map((part) => Number.isNaN(Number(part)) ? part : Number(part));
7293
+ const aParts = normalize(a);
7294
+ const bParts = normalize(b);
7295
+ const max = Math.max(aParts.length, bParts.length);
7296
+ for (let i = 0; i < max; i += 1) {
7297
+ const left = aParts[i];
7298
+ const right = bParts[i];
7299
+ if (left === void 0) return -1;
7300
+ if (right === void 0) return 1;
7301
+ if (typeof left === "number" && typeof right === "number") {
7302
+ if (left !== right) return left - right;
7303
+ continue;
7304
+ }
7305
+ const leftStr = String(left);
7306
+ const rightStr = String(right);
7307
+ if (leftStr !== rightStr) return leftStr < rightStr ? -1 : 1;
7308
+ }
7309
+ return 0;
7310
+ }
7311
+ function isObject(value) {
7312
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
7313
+ }
7314
+ function normalizeValueForKey(key, value) {
7315
+ if (Array.isArray(value)) {
7316
+ return value.map(
7317
+ (item) => isObject(item) ? orderXmlObject(item, key) : normalizeValue(item)
7318
+ );
7319
+ }
7320
+ if (isObject(value)) return orderXmlObject(value, key);
7321
+ return value;
7322
+ }
7323
+ function normalizeValue(value) {
7324
+ if (Array.isArray(value)) return value.map((item) => normalizeValue(item));
7325
+ if (isObject(value)) return orderXmlObject(value);
7326
+ return value;
7327
+ }
7328
+ function orderXmlObject(value, contextKey) {
7329
+ const order = contextKey ? ORDER_MAP[contextKey] : void 0;
7330
+ const keys = Object.keys(value);
7331
+ const used = /* @__PURE__ */ new Set();
7332
+ const ordered = {};
7333
+ if (order) {
7334
+ for (const key of order) {
7335
+ if (Object.prototype.hasOwnProperty.call(value, key)) {
7336
+ const item = value[key];
7337
+ if (item !== void 0) ordered[key] = normalizeValueForKey(key, item);
7338
+ used.add(key);
7339
+ }
7340
+ }
7341
+ }
7342
+ const pKeys = keys.filter((key) => !used.has(key) && key.startsWith("P_")).sort(comparePKey);
7343
+ for (const key of pKeys) {
7344
+ const item = value[key];
7345
+ if (item !== void 0) ordered[key] = normalizeValueForKey(key, item);
7346
+ used.add(key);
7347
+ }
7348
+ for (const key of keys) {
7349
+ if (used.has(key)) continue;
7350
+ const item = value[key];
7351
+ if (item !== void 0) ordered[key] = normalizeValueForKey(key, item);
7352
+ }
7353
+ return ordered;
7354
+ }
7355
+
7356
+ // src/xml/faktura-builder.ts
7357
+ init_esm_shims();
7358
+ var FAKTURA_NAMESPACE = {
7359
+ FA2: "http://crd.gov.pl/wzor/2023/06/29/12648/",
7360
+ FA3: "http://crd.gov.pl/wzor/2025/06/25/13775/"
7361
+ };
7362
+ var ETD_NAMESPACE = {
7363
+ FA2: "http://crd.gov.pl/xml/schematy/2020/10/08/eDokumenty",
7364
+ FA3: "http://crd.gov.pl/xml/schematy/dziedzinowe/mf/2022/01/05/eD/DefinicjeTypy/"
7365
+ };
7366
+ function toKodFormularza(formCode) {
7367
+ return {
7368
+ "@_kodSystemowy": formCode.systemCode,
7369
+ "@_wersjaSchemy": formCode.schemaVersion,
7370
+ "#text": formCode.value
7371
+ };
7372
+ }
7373
+ function isFormCodeShape(value) {
7374
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
7375
+ const candidate = value;
7376
+ return typeof candidate.systemCode === "string" && typeof candidate.schemaVersion === "string" && typeof candidate.value === "string";
7377
+ }
7378
+ function isObject2(value) {
7379
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
7380
+ }
7381
+ function normalizeTopLevelChild(key, value) {
7382
+ if (key === "Naglowek" && isObject2(value)) {
7383
+ return normalizeNaglowek(value);
7384
+ }
7385
+ if (Array.isArray(value)) {
7386
+ return value.map((item) => isObject2(item) ? orderXmlObject(item, key) : item);
7387
+ }
7388
+ if (isObject2(value)) return orderXmlObject(value, key);
7389
+ return value;
7390
+ }
7391
+ function normalizeNaglowek(value) {
7392
+ const result = {};
7393
+ for (const [key, item] of Object.entries(value)) {
7394
+ if (item === void 0) continue;
7395
+ if (key === "KodFormularza" && isFormCodeShape(item)) {
7396
+ result[key] = toKodFormularza(item);
7397
+ continue;
7398
+ }
7399
+ if (Array.isArray(item)) {
7400
+ result[key] = item.map(
7401
+ (entry) => isObject2(entry) ? orderXmlObject(entry, key) : entry
7402
+ );
7403
+ continue;
7404
+ }
7405
+ if (isObject2(item)) {
7406
+ result[key] = orderXmlObject(item, key);
7407
+ continue;
7408
+ }
7409
+ result[key] = item;
7410
+ }
7411
+ return result;
7412
+ }
7413
+ function normalizeTopLevel(input) {
7414
+ const result = {};
7415
+ for (const [key, value] of Object.entries(input)) {
7416
+ if (value === void 0) continue;
7417
+ result[key] = normalizeTopLevelChild(key, value);
7418
+ }
7419
+ return result;
7420
+ }
7421
+ function buildFakturaXml(faktura, options = {}) {
7422
+ const schema = options.schema ?? "FA3";
7423
+ const fakturaNamespace = options.fakturaNamespace ?? FAKTURA_NAMESPACE[schema];
7424
+ const etdNamespace = options.etdNamespace ?? ETD_NAMESPACE[schema];
7425
+ const normalized = normalizeTopLevel(faktura);
7426
+ const ordered = orderXmlObject(normalized, "Faktura");
7427
+ const document = {
7428
+ Faktura: {
7429
+ ...ordered,
7430
+ "@_xmlns": fakturaNamespace,
7431
+ "@_xmlns:etd": etdNamespace
7432
+ }
7433
+ };
7434
+ return buildXmlFromObject(document, { pretty: options.pretty });
7435
+ }
7436
+ function isFakturaInput(input) {
7437
+ if (!isObject2(input)) return false;
7438
+ const candidate = input;
7439
+ if (!Object.prototype.hasOwnProperty.call(candidate, "Naglowek")) return false;
7440
+ if (!Object.prototype.hasOwnProperty.call(candidate, "Fa")) return false;
7441
+ return isObject2(candidate.Naglowek) && isObject2(candidate.Fa);
7442
+ }
7443
+
7444
+ // src/xml/pef-builder.ts
7445
+ init_esm_shims();
7446
+ init_ksef_validation_error();
7447
+ var PEF_NAMESPACE = {
7448
+ PEF: "urn:oasis:names:specification:ubl:schema:xsd:Invoice-2",
7449
+ PEF_KOR: "urn:oasis:names:specification:ubl:schema:xsd:CreditNote-2"
7450
+ };
7451
+ var UBL_EXT_NS = "urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2";
7452
+ var UBL_CBC_NS = "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2";
7453
+ var UBL_CAC_NS = "urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2";
7454
+ var UBL_CBC_PL_NS = "urn:pl:extended:CommonBasicComponents-2";
7455
+ var UBL_CAC_PL_NS = "urn:pl:extended:CommonAggregateComponents-2";
7456
+ function isPefUblDocumentInput(input) {
7457
+ if (typeof input !== "object" || input === null || Array.isArray(input)) return false;
7458
+ const obj = input;
7459
+ const invoice = obj.Invoice;
7460
+ const creditNote = obj.CreditNote;
7461
+ const hasInvoice = typeof invoice === "object" && invoice !== null && !Array.isArray(invoice);
7462
+ const hasCreditNote = typeof creditNote === "object" && creditNote !== null && !Array.isArray(creditNote);
7463
+ return hasInvoice !== hasCreditNote;
7464
+ }
7465
+ function inferSchema(input) {
7466
+ return "Invoice" in input ? "PEF" : "PEF_KOR";
7467
+ }
7468
+ function isNonArrayObject(value) {
7469
+ return typeof value === "object" && value !== null && !Array.isArray(value);
7470
+ }
7471
+ function assertPefShape(input) {
7472
+ if (!isNonArrayObject(input)) {
7473
+ throw new KSeFValidationError("PEF input must be a non-array object.");
7474
+ }
7475
+ const hasInvoiceKey = "Invoice" in input;
7476
+ const hasCreditNoteKey = "CreditNote" in input;
7477
+ if (hasInvoiceKey && hasCreditNoteKey) {
7478
+ throw new KSeFValidationError(
7479
+ "PEF input must contain exactly one of `Invoice` or `CreditNote`, not both."
7480
+ );
7481
+ }
7482
+ if (!hasInvoiceKey && !hasCreditNoteKey) {
7483
+ throw new KSeFValidationError(
7484
+ "PEF input must contain either an `Invoice` or a `CreditNote` root element."
7485
+ );
7486
+ }
7487
+ const rootKey = hasInvoiceKey ? "Invoice" : "CreditNote";
7488
+ if (!isNonArrayObject(input[rootKey])) {
7489
+ throw new KSeFValidationError(
7490
+ `PEF \`${rootKey}\` value must be a non-array object.`
7491
+ );
7492
+ }
7493
+ }
7494
+ function buildPefXml(input, options = {}) {
7495
+ assertPefShape(input);
7496
+ const inferred = inferSchema(input);
7497
+ const schema = options.schema ?? input.schema ?? inferred;
7498
+ if (schema !== inferred) {
7499
+ throw new KSeFValidationError(
7500
+ `PEF schema mismatch: expected ${inferred} based on root element, got ${schema}.`
7501
+ );
7502
+ }
7503
+ const commonNamespaces = {
7504
+ "@_xmlns:ext": UBL_EXT_NS,
7505
+ "@_xmlns:cbc": UBL_CBC_NS,
7506
+ "@_xmlns:cac": UBL_CAC_NS,
7507
+ "@_xmlns:cbc-pl": UBL_CBC_PL_NS,
7508
+ "@_xmlns:cac-pl": UBL_CAC_PL_NS
7509
+ };
7510
+ const document = "Invoice" in input ? {
7511
+ Invoice: {
7512
+ ...input.Invoice,
7513
+ "@_xmlns": PEF_NAMESPACE.PEF,
7514
+ ...commonNamespaces
7515
+ }
7516
+ } : {
7517
+ CreditNote: {
7518
+ ...input.CreditNote,
7519
+ "@_xmlns": PEF_NAMESPACE.PEF_KOR,
7520
+ ...commonNamespaces
7521
+ }
7522
+ };
7523
+ return buildXmlFromObject(document, { pretty: options.pretty });
7524
+ }
7525
+
7526
+ // src/xml/invoice-serializer.ts
7527
+ init_esm_shims();
7528
+ init_ksef_validation_error();
7529
+ var FAKTURA_SCHEMAS = /* @__PURE__ */ new Set(["FA2", "FA3"]);
7530
+ var PEF_SCHEMAS = /* @__PURE__ */ new Set(["PEF", "PEF_KOR"]);
7531
+ function isNonArrayObject2(value) {
7532
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
7533
+ }
7534
+ function classifyUnknownObject(input) {
7535
+ const looksLikeFaktura = "Naglowek" in input || "Fa" in input || "Podmiot1" in input || "Podmiot2" in input;
7536
+ const hasInvoice = "Invoice" in input;
7537
+ const hasCreditNote = "CreditNote" in input;
7538
+ if (hasInvoice && hasCreditNote) {
7539
+ return new KSeFValidationError(
7540
+ "Input must contain exactly one of `Invoice` or `CreditNote`, not both."
7541
+ );
7542
+ }
7543
+ if (hasInvoice !== hasCreditNote) {
7544
+ const rootKey = hasInvoice ? "Invoice" : "CreditNote";
7545
+ if (!isNonArrayObject2(input[rootKey])) {
7546
+ return KSeFValidationError.fromField(
7547
+ rootKey,
7548
+ `PEF \`${rootKey}\` value must be a non-array object.`
7549
+ );
7550
+ }
7551
+ }
7552
+ if (looksLikeFaktura) {
7553
+ const missing = [];
7554
+ if (!("Naglowek" in input)) missing.push("Naglowek");
7555
+ if (!("Fa" in input)) missing.push("Fa");
7556
+ if (missing.length > 0) {
7557
+ return KSeFValidationError.fromField(
7558
+ missing[0],
7559
+ `Faktura input is missing required top-level key(s): ${missing.join(", ")}.`
7560
+ );
7561
+ }
7562
+ for (const key of ["Naglowek", "Fa"]) {
7563
+ if (!isNonArrayObject2(input[key])) {
7564
+ return KSeFValidationError.fromField(
7565
+ key,
7566
+ `Faktura \`${key}\` value must be a non-null, non-array object.`
7567
+ );
7568
+ }
7569
+ }
7570
+ return new KSeFValidationError(
7571
+ "Faktura-like input failed shape validation: `Naglowek` and `Fa` must be own enumerable properties on the input object."
7572
+ );
7573
+ }
7574
+ return new KSeFValidationError(
7575
+ "Unsupported invoice input shape: expected `FakturaInput` (with `Naglowek` + `Fa`) or `PefUblDocumentInput` (with `Invoice` or `CreditNote`)."
7576
+ );
7577
+ }
7578
+ function serializeInvoiceXml(input, options) {
7579
+ if (Buffer.isBuffer(input)) return input;
7580
+ if (typeof input === "string") {
7581
+ return Buffer.from(stripBom(input), "utf8");
7582
+ }
7583
+ if (Array.isArray(input)) {
7584
+ return Buffer.from(stripBom(buildXml(input)), "utf8");
7585
+ }
7586
+ if (input && typeof input === "object") {
7587
+ const schema = options?.schema;
7588
+ if (isPefUblDocumentInput(input)) {
7589
+ if (schema && !PEF_SCHEMAS.has(schema)) {
7590
+ throw new KSeFValidationError(
7591
+ `schema option ${schema} is not compatible with a PEF / PEF_KOR input.`
7592
+ );
7593
+ }
7594
+ const pefSchema = schema === "PEF" || schema === "PEF_KOR" ? schema : void 0;
7595
+ const xml = buildPefXml(input, {
7596
+ schema: pefSchema,
7597
+ pretty: options?.pretty
7598
+ });
7599
+ return Buffer.from(stripBom(xml), "utf8");
7600
+ }
7601
+ if (isFakturaInput(input)) {
7602
+ if (schema && !FAKTURA_SCHEMAS.has(schema)) {
7603
+ throw new KSeFValidationError(
7604
+ `schema option ${schema} is not compatible with a Faktura input.`
7605
+ );
7606
+ }
7607
+ const fakturaSchema = schema === "FA2" || schema === "FA3" ? schema : void 0;
7608
+ const xml = buildFakturaXml(input, {
7609
+ schema: fakturaSchema,
7610
+ fakturaNamespace: options?.fakturaNamespace,
7611
+ etdNamespace: options?.etdNamespace,
7612
+ pretty: options?.pretty
7613
+ });
7614
+ return Buffer.from(stripBom(xml), "utf8");
7615
+ }
7616
+ throw classifyUnknownObject(input);
7617
+ }
7618
+ throw new KSeFValidationError(
7619
+ "Unsupported invoice input type: expected Buffer, string, XmlDocument, FakturaInput, or PefUblDocumentInput."
7620
+ );
7621
+ }
7622
+ function buildRawXmlString(document, options) {
7623
+ return buildXmlFromObject(document, options);
7624
+ }
7625
+
6149
7626
  // src/workflows/online-session-workflow.ts
6150
7627
  init_invoice_validator();
6151
7628
  init_ksef_validation_error();
@@ -6283,6 +7760,7 @@ async function openSendAndClose(client, invoices, options) {
6283
7760
  }
6284
7761
 
6285
7762
  // src/workflows/batch-session-workflow.ts
7763
+ init_esm_shims();
6286
7764
  init_document_structures();
6287
7765
  async function uploadBatch(client, zipData, options) {
6288
7766
  if (options?.parallelism !== void 0 && (!Number.isInteger(options.parallelism) || options.parallelism < 1)) {
@@ -6421,6 +7899,7 @@ async function uploadBatchParsed(client, zipData, options) {
6421
7899
  }
6422
7900
 
6423
7901
  // src/workflows/invoice-export-workflow.ts
7902
+ init_esm_shims();
6424
7903
  init_zip();
6425
7904
  async function doExport(client, filters, options) {
6426
7905
  await client.crypto.init();
@@ -6493,7 +7972,11 @@ async function exportAndDownload(client, filters, options) {
6493
7972
  };
6494
7973
  }
6495
7974
 
7975
+ // src/workflows/incremental-export-workflow.ts
7976
+ init_esm_shims();
7977
+
6496
7978
  // src/workflows/hwm-coordinator.ts
7979
+ init_esm_shims();
6497
7980
  function updateContinuationPoint(points, subjectType, pkg) {
6498
7981
  if (pkg.isTruncated && pkg.lastPermanentStorageDate) {
6499
7982
  points[subjectType] = pkg.lastPermanentStorageDate;
@@ -6591,7 +8074,8 @@ function buildDefaultFilters(subjectType, from, to) {
6591
8074
  }
6592
8075
 
6593
8076
  // src/workflows/hwm-storage.ts
6594
- import * as fs from "fs/promises";
8077
+ init_esm_shims();
8078
+ import * as fs2 from "fs/promises";
6595
8079
  var InMemoryHwmStore = class {
6596
8080
  points = {};
6597
8081
  async load() {
@@ -6607,7 +8091,7 @@ var FileHwmStore = class {
6607
8091
  }
6608
8092
  async load() {
6609
8093
  try {
6610
- const data = await fs.readFile(this.filePath, "utf-8");
8094
+ const data = await fs2.readFile(this.filePath, "utf-8");
6611
8095
  return JSON.parse(data);
6612
8096
  } catch (err) {
6613
8097
  if (err.code === "ENOENT") {
@@ -6617,11 +8101,12 @@ var FileHwmStore = class {
6617
8101
  }
6618
8102
  }
6619
8103
  async save(points) {
6620
- await fs.writeFile(this.filePath, JSON.stringify(points, null, 2), "utf-8");
8104
+ await fs2.writeFile(this.filePath, JSON.stringify(points, null, 2), "utf-8");
6621
8105
  }
6622
8106
  };
6623
8107
 
6624
8108
  // src/workflows/auth-workflow.ts
8109
+ init_esm_shims();
6625
8110
  init_auth_xml_builder();
6626
8111
  async function authenticateWithToken(client, options) {
6627
8112
  const challenge = await client.auth.getChallenge();
@@ -6718,10 +8203,12 @@ async function authenticateWithPkcs12(client, options) {
6718
8203
  }
6719
8204
 
6720
8205
  // src/offline/index.ts
8206
+ init_esm_shims();
6721
8207
  init_deadline();
6722
8208
  init_holidays();
6723
8209
 
6724
8210
  // src/offline/storage.ts
8211
+ init_esm_shims();
6725
8212
  function matchesFilter(invoice, filter) {
6726
8213
  if (filter.status !== void 0) {
6727
8214
  const statuses = Array.isArray(filter.status) ? filter.status : [filter.status];
@@ -6760,12 +8247,13 @@ var InMemoryOfflineInvoiceStorage = class {
6760
8247
  };
6761
8248
 
6762
8249
  // src/offline/file-storage.ts
6763
- import * as fs2 from "fs/promises";
6764
- import * as path from "path";
8250
+ init_esm_shims();
8251
+ import * as fs3 from "fs/promises";
8252
+ import * as path3 from "path";
6765
8253
  import * as os from "os";
6766
8254
  function resolveDir(dir) {
6767
8255
  if (dir === "~" || dir.startsWith("~/")) {
6768
- return path.join(os.homedir(), dir.slice(1));
8256
+ return path3.join(os.homedir(), dir.slice(1));
6769
8257
  }
6770
8258
  return dir;
6771
8259
  }
@@ -6781,23 +8269,23 @@ var FileOfflineInvoiceStorage = class {
6781
8269
  this.dir = resolveDir(directory ?? "~/.ksef/offline");
6782
8270
  }
6783
8271
  async ensureDir() {
6784
- await fs2.mkdir(this.dir, { recursive: true });
8272
+ await fs3.mkdir(this.dir, { recursive: true });
6785
8273
  }
6786
8274
  filePath(id) {
6787
8275
  validateId(id);
6788
- return path.join(this.dir, `${id}.json`);
8276
+ return path3.join(this.dir, `${id}.json`);
6789
8277
  }
6790
8278
  async save(invoice) {
6791
8279
  await this.ensureDir();
6792
8280
  const file = this.filePath(invoice.id);
6793
8281
  const tmp = `${file}.tmp`;
6794
- await fs2.writeFile(tmp, JSON.stringify(invoice, null, 2));
6795
- await fs2.rename(tmp, file);
8282
+ await fs3.writeFile(tmp, JSON.stringify(invoice, null, 2));
8283
+ await fs3.rename(tmp, file);
6796
8284
  }
6797
8285
  async get(id) {
6798
8286
  const file = this.filePath(id);
6799
8287
  try {
6800
- return JSON.parse(await fs2.readFile(file, "utf-8"));
8288
+ return JSON.parse(await fs3.readFile(file, "utf-8"));
6801
8289
  } catch (err) {
6802
8290
  if (err instanceof Error && "code" in err && err.code === "ENOENT") {
6803
8291
  return null;
@@ -6809,7 +8297,7 @@ var FileOfflineInvoiceStorage = class {
6809
8297
  async list(filter) {
6810
8298
  let files;
6811
8299
  try {
6812
- files = (await fs2.readdir(this.dir)).filter((f) => f.endsWith(".json"));
8300
+ files = (await fs3.readdir(this.dir)).filter((f) => f.endsWith(".json"));
6813
8301
  } catch {
6814
8302
  return [];
6815
8303
  }
@@ -6817,7 +8305,7 @@ var FileOfflineInvoiceStorage = class {
6817
8305
  for (const file of files) {
6818
8306
  try {
6819
8307
  const data = JSON.parse(
6820
- await fs2.readFile(path.join(this.dir, file), "utf-8")
8308
+ await fs3.readFile(path3.join(this.dir, file), "utf-8")
6821
8309
  );
6822
8310
  if (!filter || matchesFilter(data, filter)) {
6823
8311
  results.push(data);
@@ -6843,7 +8331,7 @@ var FileOfflineInvoiceStorage = class {
6843
8331
  async delete(id) {
6844
8332
  const file = this.filePath(id);
6845
8333
  try {
6846
- await fs2.unlink(file);
8334
+ await fs3.unlink(file);
6847
8335
  } catch (e) {
6848
8336
  if (e instanceof Error && "code" in e && e.code !== "ENOENT") throw e;
6849
8337
  }
@@ -6872,12 +8360,17 @@ export {
6872
8360
  CertificateFingerprint,
6873
8361
  CertificateName,
6874
8362
  CertificateService,
8363
+ CircuitBreakerPolicy,
6875
8364
  CryptographyService,
6876
8365
  DEFAULT_FORM_CODE,
8366
+ DISCOURAGED_UNICODE_RANGES,
6877
8367
  DefaultAuthManager,
6878
8368
  ENFORCE_XADES_COMPLIANCE,
8369
+ ETD_NAMESPACE,
6879
8370
  EntityPermissionGrantBuilder,
6880
8371
  Environment,
8372
+ FAKTURA_NAMESPACE,
8373
+ FA_XSD_PATHS,
6881
8374
  FORM_CODES,
6882
8375
  FORM_CODE_KEYS,
6883
8376
  FileHwmStore,
@@ -6894,7 +8387,9 @@ export {
6894
8387
  KSEF_FEATURE_HEADER,
6895
8388
  KSeFApiError,
6896
8389
  KSeFAuthStatusError,
8390
+ KSeFBadRequestError,
6897
8391
  KSeFBatchTimeoutError,
8392
+ KSeFCircuitOpenError,
6898
8393
  KSeFClient,
6899
8394
  KSeFError,
6900
8395
  KSeFErrorCode,
@@ -6904,6 +8399,7 @@ export {
6904
8399
  KSeFSessionExpiredError,
6905
8400
  KSeFUnauthorizedError,
6906
8401
  KSeFValidationError,
8402
+ KSeFXsdValidationError,
6907
8403
  KsefNumber,
6908
8404
  KsefNumberV35,
6909
8405
  KsefNumberV36,
@@ -6911,8 +8407,11 @@ export {
6911
8407
  LimitsService,
6912
8408
  Nip,
6913
8409
  NipVatUe,
8410
+ ORDER_MAP,
6914
8411
  OfflineInvoiceWorkflow,
6915
8412
  OnlineSessionService,
8413
+ PEF_NAMESPACE,
8414
+ PEF_XSD_PATHS,
6916
8415
  PERMISSION_DESCRIPTION_MAX_LENGTH,
6917
8416
  PERMISSION_DESCRIPTION_MIN_LENGTH,
6918
8417
  PeppolId,
@@ -6942,17 +8441,25 @@ export {
6942
8441
  VatUe,
6943
8442
  VerificationLinkService,
6944
8443
  addBusinessDays,
8444
+ assertNever,
6945
8445
  authenticateWithCertificate,
6946
8446
  authenticateWithExternalSignature,
6947
8447
  authenticateWithPkcs12,
6948
8448
  authenticateWithToken,
6949
8449
  batchValidationDetails,
8450
+ buildFakturaXml,
8451
+ buildPefXml,
8452
+ buildRawXmlString,
6950
8453
  buildUnsignedAuthTokenRequestXml,
8454
+ buildXml,
8455
+ buildXmlFromObject,
6951
8456
  calculateBackoff,
6952
8457
  calculateOfflineDeadline,
8458
+ comparePKey,
6953
8459
  createZip,
6954
8460
  decodeJwtPayload,
6955
8461
  deduplicateByKsefNumber,
8462
+ defaultCircuitBreakerPolicy,
6956
8463
  defaultPresignedUrlPolicy,
6957
8464
  defaultRateLimitPolicy,
6958
8465
  defaultRetryPolicy,
@@ -6968,6 +8475,9 @@ export {
6968
8475
  getTimeUntilDeadline,
6969
8476
  incrementalExportAndDownload,
6970
8477
  isExpired,
8478
+ isFakturaInput,
8479
+ isFormCodeShape,
8480
+ isPefUblDocumentInput,
6971
8481
  isPolishHoliday,
6972
8482
  isRetryableError,
6973
8483
  isRetryableStatus,
@@ -6986,19 +8496,26 @@ export {
6986
8496
  isValidReferenceNumber,
6987
8497
  isValidSha256Base64,
6988
8498
  isValidVatUe,
8499
+ libxmljsAvailable,
6989
8500
  nextBusinessDay,
6990
8501
  openOnlineSession,
6991
8502
  openSendAndClose,
8503
+ orderXmlObject,
6992
8504
  parseFormCode,
6993
8505
  parseKSeFTokenContext,
6994
8506
  parseRetryAfter,
6995
8507
  parseUpoXml,
8508
+ parseXml,
6996
8509
  pollUntil,
6997
8510
  resolveOptions,
8511
+ resolveXsdFor,
6998
8512
  resumeOnlineSession,
6999
8513
  runWithConcurrency,
8514
+ serializeInvoiceXml,
7000
8515
  sha256Base642 as sha256Base64,
7001
8516
  sleep,
8517
+ stripBom,
8518
+ toKodFormularza,
7002
8519
  unzip,
7003
8520
  updateContinuationPoint,
7004
8521
  uploadBatch,
@@ -7006,8 +8523,10 @@ export {
7006
8523
  uploadBatchStream,
7007
8524
  uploadBatchStreamParsed,
7008
8525
  validate,
8526
+ validateAgainstXsd,
7009
8527
  validateBatch,
7010
8528
  validateBusinessRules,
8529
+ validateCharValidity,
7011
8530
  validateFormCodeForSession,
7012
8531
  validatePresignedUrl,
7013
8532
  validateSchema,