ksef-client-ts 0.9.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -8,9 +8,9 @@ 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
11
+ // ../../node_modules/tsup/assets/esm_shims.js
12
12
  var init_esm_shims = __esm({
13
- "node_modules/tsup/assets/esm_shims.js"() {
13
+ "../../node_modules/tsup/assets/esm_shims.js"() {
14
14
  "use strict";
15
15
  }
16
16
  });
@@ -376,6 +376,25 @@ var init_ksef_validation_error = __esm({
376
376
  }
377
377
  });
378
378
 
379
+ // src/errors/ksef-metadata-pagination-error.ts
380
+ var KSeFMetadataPaginationError;
381
+ var init_ksef_metadata_pagination_error = __esm({
382
+ "src/errors/ksef-metadata-pagination-error.ts"() {
383
+ "use strict";
384
+ init_esm_shims();
385
+ init_ksef_error();
386
+ KSeFMetadataPaginationError = class extends KSeFError {
387
+ /** The boundary date value that failed to advance. */
388
+ boundaryValue;
389
+ constructor(message, boundaryValue) {
390
+ super(message);
391
+ this.name = "KSeFMetadataPaginationError";
392
+ this.boundaryValue = boundaryValue;
393
+ }
394
+ };
395
+ }
396
+ });
397
+
379
398
  // src/errors/error-codes.ts
380
399
  function hasErrorCode(body, code) {
381
400
  return !!body?.exception?.exceptionDetailList?.some((d) => d.exceptionCode === code);
@@ -523,6 +542,7 @@ var init_errors = __esm({
523
542
  init_ksef_auth_status_error();
524
543
  init_ksef_session_expired_error();
525
544
  init_ksef_validation_error();
545
+ init_ksef_metadata_pagination_error();
526
546
  init_ksef_batch_timeout_error();
527
547
  init_ksef_unknown_public_key_error();
528
548
  init_ksef_circuit_open_error();
@@ -565,21 +585,21 @@ var init_rest_request = __esm({
565
585
  _query = [];
566
586
  _presigned = false;
567
587
  _skipAuthRetry = false;
568
- constructor(method, path3) {
588
+ constructor(method, path) {
569
589
  this.method = method;
570
- this.path = path3;
590
+ this.path = path;
571
591
  }
572
- static get(path3) {
573
- return new _RestRequest("GET", path3);
592
+ static get(path) {
593
+ return new _RestRequest("GET", path);
574
594
  }
575
- static post(path3) {
576
- return new _RestRequest("POST", path3);
595
+ static post(path) {
596
+ return new _RestRequest("POST", path);
577
597
  }
578
- static put(path3) {
579
- return new _RestRequest("PUT", path3);
598
+ static put(path) {
599
+ return new _RestRequest("PUT", path);
580
600
  }
581
- static delete(path3) {
582
- return new _RestRequest("DELETE", path3);
601
+ static delete(path) {
602
+ return new _RestRequest("DELETE", path);
583
603
  }
584
604
  body(data) {
585
605
  this._body = data;
@@ -943,13 +963,13 @@ var init_rest_client = __esm({
943
963
  }
944
964
  throw lastError;
945
965
  }
946
- recordCircuitOutcome(path3, status) {
966
+ recordCircuitOutcome(path, status) {
947
967
  if (!this.circuitBreakerPolicy) return;
948
968
  if (status >= 500) {
949
- this.circuitBreakerPolicy.recordFailure(path3);
969
+ this.circuitBreakerPolicy.recordFailure(path);
950
970
  return;
951
971
  }
952
- this.circuitBreakerPolicy.recordSuccess(path3);
972
+ this.circuitBreakerPolicy.recordSuccess(path);
953
973
  }
954
974
  async doRequest(request, url, overrideToken) {
955
975
  const headers = {
@@ -986,9 +1006,9 @@ var init_rest_client = __esm({
986
1006
  return response;
987
1007
  }
988
1008
  buildUrl(request) {
989
- const path3 = this.routeBuilder.build(request.path);
1009
+ const path = this.routeBuilder.build(request.path);
990
1010
  const base = this.options.baseUrl;
991
- const url = new URL(`${base}${path3}`);
1011
+ const url = new URL(`${base}${path}`);
992
1012
  const query = request.getQuery();
993
1013
  for (const [key, value] of query) {
994
1014
  url.searchParams.append(key, value);
@@ -1544,6 +1564,9 @@ function isValidCertificateName(value) {
1544
1564
  function isValidCertificateFingerprint(value) {
1545
1565
  return CertificateFingerprint.test(value);
1546
1566
  }
1567
+ function isValidCertificateSerialNumber(value) {
1568
+ return CertificateSerialNumber.test(value);
1569
+ }
1547
1570
  function isValidBase64(value) {
1548
1571
  return Base64String.test(value);
1549
1572
  }
@@ -1553,7 +1576,7 @@ function isValidIp4Address(value) {
1553
1576
  function isValidSha256Base64(value) {
1554
1577
  return Sha256Base64.test(value);
1555
1578
  }
1556
- var NIP_PATTERN_CORE, VAT_UE_PATTERN_CORE, Nip, VatUe, NipVatUe, InternalId, PeppolId, ReferenceNumber, KsefNumber, KsefNumberV35, KsefNumberV36, CertificateName, Pesel, CertificateFingerprint, Base64String, Ip4Address, Ip4Range, Ip4Mask, Sha256Base64, NIP_WEIGHTS, PESEL_WEIGHTS, CRC8_POLY;
1579
+ var NIP_PATTERN_CORE, VAT_UE_PATTERN_CORE, Nip, VatUe, NipVatUe, InternalId, PeppolId, ReferenceNumber, KsefNumber, KsefNumberV35, KsefNumberV36, CertificateName, Pesel, CertificateFingerprint, CertificateSerialNumber, Base64String, Ip4Address, Ip4Range, Ip4Mask, Sha256Base64, NIP_WEIGHTS, PESEL_WEIGHTS, CRC8_POLY;
1557
1580
  var init_patterns = __esm({
1558
1581
  "src/validation/patterns.ts"() {
1559
1582
  "use strict";
@@ -1572,6 +1595,7 @@ var init_patterns = __esm({
1572
1595
  CertificateName = /^[a-zA-Z0-9_\- ąćęłńóśźżĄĆĘŁŃÓŚŹŻ]+$/;
1573
1596
  Pesel = /^\d{2}(?:0[1-9]|1[0-2]|2[1-9]|3[0-2]|4[1-9]|5[0-2]|6[1-9]|7[0-2]|8[1-9]|9[0-2])\d{7}$/;
1574
1597
  CertificateFingerprint = /^[0-9A-F]{64}$/;
1598
+ CertificateSerialNumber = /^[0-9A-F]{16}$/;
1575
1599
  Base64String = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;
1576
1600
  Ip4Address = /^((25[0-5]|(2[0-4]|1\d|[1-9]|)\d)\.?\b){4}$/;
1577
1601
  Ip4Range = /^((25[0-5]|(2[0-4]|1\d|[1-9]|)\d)\.?\b){4}-((25[0-5]|(2[0-4]|1\d|[1-9]|)\d)\.?\b){4}$/;
@@ -2835,11 +2859,6 @@ var init_schemas = __esm({
2835
2859
  "src/validation/schemas/index.ts"() {
2836
2860
  "use strict";
2837
2861
  init_esm_shims();
2838
- init_fa3();
2839
- init_fa2();
2840
- init_fa_rr1();
2841
- init_pef3();
2842
- init_pef_kor3();
2843
2862
  NAMESPACE_MAP = {
2844
2863
  "http://crd.gov.pl/wzor/2025/06/25/13775/": "FA3",
2845
2864
  "http://crd.gov.pl/wzor/2023/06/29/12648/": "FA2",
@@ -3095,11 +3114,11 @@ async function validateSchema(xml, options, _parsed) {
3095
3114
  const prefix = rootElement ? `/${rootElement}/` : "/";
3096
3115
  const validationErrors = result.error.issues.map((issue) => {
3097
3116
  const zodPath = issue.path.join("/");
3098
- const path3 = zodPath ? `${prefix}${zodPath}` : rootElement ? `/${rootElement}` : void 0;
3117
+ const path = zodPath ? `${prefix}${zodPath}` : rootElement ? `/${rootElement}` : void 0;
3099
3118
  return {
3100
3119
  code: mapZodErrorCode(issue),
3101
3120
  message: issue.message,
3102
- path: path3
3121
+ path
3103
3122
  };
3104
3123
  });
3105
3124
  return { valid: false, schemaType, errors: validationErrors };
@@ -3139,9 +3158,9 @@ function validateBusinessRules(xml, _parsed) {
3139
3158
  collectDateErrors(object, rootElement, errors);
3140
3159
  return { valid: errors.length === 0, schemaType, errors };
3141
3160
  }
3142
- function collectNipPeselErrors(obj, path3, errors) {
3161
+ function collectNipPeselErrors(obj, path, errors) {
3143
3162
  for (const [key, value] of Object.entries(obj)) {
3144
- const currentPath = path3 ? `${path3}/${key}` : key;
3163
+ const currentPath = path ? `${path}/${key}` : key;
3145
3164
  if (key === "NIP" && typeof value === "string") {
3146
3165
  if (!isValidNip(value)) {
3147
3166
  errors.push({
@@ -4027,6 +4046,8 @@ var init_certificates = __esm({
4027
4046
  init_esm_shims();
4028
4047
  init_rest_request();
4029
4048
  init_routes();
4049
+ init_ksef_validation_error();
4050
+ init_patterns();
4030
4051
  CertificateApiService = class {
4031
4052
  restClient;
4032
4053
  constructor(restClient) {
@@ -4053,6 +4074,14 @@ var init_certificates = __esm({
4053
4074
  return response.body;
4054
4075
  }
4055
4076
  async retrieve(request) {
4077
+ for (const serial of request.certificateSerialNumbers ?? []) {
4078
+ if (!isValidCertificateSerialNumber(serial)) {
4079
+ throw KSeFValidationError.fromField(
4080
+ "certificateSerialNumbers",
4081
+ `Invalid certificate serial number "${serial}": must be exactly 16 uppercase hex characters (^[0-9A-F]{16}$)`
4082
+ );
4083
+ }
4084
+ }
4056
4085
  const req = RestRequest.post(Routes.Certificates.retrieve).body(request);
4057
4086
  const response = await this.restClient.execute(req);
4058
4087
  return response.body;
@@ -4086,20 +4115,20 @@ var init_lighthouse = __esm({
4086
4115
  this.lighthouseUrl = options.lighthouseUrl;
4087
4116
  this.timeout = options.timeout;
4088
4117
  }
4089
- async fetchJson(path3) {
4118
+ async fetchJson(path) {
4090
4119
  if (!this.lighthouseUrl) {
4091
4120
  throw new KSeFError(
4092
4121
  "Lighthouse API is not available for the DEMO environment. Use TEST or PROD instead."
4093
4122
  );
4094
4123
  }
4095
- const response = await fetch(`${this.lighthouseUrl}${path3}`, {
4124
+ const response = await fetch(`${this.lighthouseUrl}${path}`, {
4096
4125
  headers: { Accept: "application/json" },
4097
4126
  signal: AbortSignal.timeout(this.timeout)
4098
4127
  });
4099
4128
  if (!response.ok) {
4100
4129
  const body = await response.text();
4101
4130
  throw new KSeFError(
4102
- `Lighthouse ${path3} failed: HTTP ${response.status} \u2014 ${body}`
4131
+ `Lighthouse ${path} failed: HTTP ${response.status} \u2014 ${body}`
4103
4132
  );
4104
4133
  }
4105
4134
  return await response.json();
@@ -5070,6 +5099,7 @@ var init_verification_link_service = __esm({
5070
5099
  constructor(baseQrUrl) {
5071
5100
  this.baseQrUrl = baseQrUrl;
5072
5101
  }
5102
+ baseQrUrl;
5073
5103
  /**
5074
5104
  * Build invoice verification URL (Code I).
5075
5105
  * Format: {baseQrUrl}/invoice/{NIP}/{DD-MM-YYYY}/{hash_base64url}
@@ -5550,6 +5580,7 @@ var init_offline_invoice_workflow = __esm({
5550
5580
  constructor(qrService) {
5551
5581
  this.qrService = qrService;
5552
5582
  }
5583
+ qrService;
5553
5584
  async generate(input, options) {
5554
5585
  if (!input.invoiceXml || input.invoiceXml.trim().length === 0) {
5555
5586
  throw new Error("invoiceXml must not be empty");
@@ -6062,219 +6093,6 @@ init_schema_registry();
6062
6093
  init_invoice_validator();
6063
6094
  init_char_validity();
6064
6095
 
6065
- // src/validation/xsd-validator.ts
6066
- init_esm_shims();
6067
- import { createRequire } from "node:module";
6068
- import * as fs from "node:fs";
6069
- import * as path from "node:path";
6070
- import { fileURLToPath, pathToFileURL } from "node:url";
6071
- var cachedPkgRoot = null;
6072
- function locatePackageRoot() {
6073
- if (cachedPkgRoot !== null) return cachedPkgRoot;
6074
- let dir = path.dirname(fileURLToPath(import.meta.url));
6075
- const root = path.parse(dir).root;
6076
- while (dir !== root) {
6077
- const candidate = path.join(dir, "docs", "schemas");
6078
- if (fs.existsSync(candidate)) {
6079
- cachedPkgRoot = dir;
6080
- return dir;
6081
- }
6082
- dir = path.dirname(dir);
6083
- }
6084
- throw new Error("Could not locate ksef-client-ts package root (docs/schemas not found).");
6085
- }
6086
- var XSD_RELATIVE = {
6087
- FA2: ["FA", "schemat_FA(2)_v1-0E.xsd"],
6088
- FA3: ["FA", "schemat_FA(3)_v1-0E.xsd"],
6089
- PEF: ["PEF", "Schemat_PEF(3)_v2-1.xsd"],
6090
- PEF_KOR: ["PEF", "Schemat_PEF_KOR(3)_v2-1.xsd"]
6091
- };
6092
- var FA_XSD_PATHS = {
6093
- get FA2() {
6094
- return resolveXsdFor("FA2");
6095
- },
6096
- get FA3() {
6097
- return resolveXsdFor("FA3");
6098
- }
6099
- };
6100
- var PEF_XSD_PATHS = {
6101
- get PEF() {
6102
- return resolveXsdFor("PEF");
6103
- },
6104
- get PEF_KOR() {
6105
- return resolveXsdFor("PEF_KOR");
6106
- }
6107
- };
6108
- function resolveXsdFor(schema) {
6109
- const rel = XSD_RELATIVE[schema];
6110
- if (!rel) throw new Error(`Unknown invoice schema: ${String(schema)}`);
6111
- return path.join(locatePackageRoot(), "docs", "schemas", ...rel);
6112
- }
6113
- var requireModule = createRequire(import.meta.url);
6114
- var libxmljs = null;
6115
- var libxmljsLoadError = null;
6116
- try {
6117
- libxmljs = requireModule("libxmljs2");
6118
- } catch (err) {
6119
- const code = err?.code;
6120
- if (code === "MODULE_NOT_FOUND" || code === "ERR_MODULE_NOT_FOUND") {
6121
- libxmljs = null;
6122
- } else {
6123
- libxmljs = null;
6124
- libxmljsLoadError = err instanceof Error ? err : new Error(String(err));
6125
- }
6126
- }
6127
- var libxmljsAvailable = libxmljs !== null;
6128
- var MISSING_LIBXMLJS_MESSAGE_PREFIX = "libxmljs2 is not installed";
6129
- function isMissingLibxmljsError(err) {
6130
- return err instanceof Error && err.message.startsWith(MISSING_LIBXMLJS_MESSAGE_PREFIX);
6131
- }
6132
- var EXTERNAL_STRUKTURY_DANYCH_URL = /schemaLocation="http:\/\/crd\.gov\.pl\/xml\/schematy\/dziedzinowe\/mf\/2022\/01\/05\/eD\/DefinicjeTypy\/StrukturyDanych_v10-0E\.xsd"/;
6133
- function rewriteSchemaLocations(xsdContent) {
6134
- if (!EXTERNAL_STRUKTURY_DANYCH_URL.test(xsdContent)) {
6135
- return xsdContent;
6136
- }
6137
- const bazoweStrukturyPath = path.join(
6138
- locatePackageRoot(),
6139
- "docs",
6140
- "schemas",
6141
- "FA",
6142
- "bazowe",
6143
- "StrukturyDanych_v10-0E.xsd"
6144
- );
6145
- const bazoweStrukturyUrl = pathToFileURL(bazoweStrukturyPath).href;
6146
- const rewritten = xsdContent.replace(
6147
- EXTERNAL_STRUKTURY_DANYCH_URL,
6148
- `schemaLocation="${bazoweStrukturyUrl}"`
6149
- );
6150
- if (rewritten === xsdContent) {
6151
- throw new Error(
6152
- "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`."
6153
- );
6154
- }
6155
- return rewritten;
6156
- }
6157
- function validateAgainstXsd(xml, xsdPath) {
6158
- if (!libxmljs) {
6159
- const loadSuffix = libxmljsLoadError ? ` (load failed: ${libxmljsLoadError.message})` : "";
6160
- throw new Error(
6161
- `${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\`).`
6162
- );
6163
- }
6164
- const xsdDir = path.dirname(xsdPath);
6165
- const rawXsd = fs.readFileSync(xsdPath, "utf8");
6166
- const rewrittenXsd = rewriteSchemaLocations(rawXsd);
6167
- const baseUrl = pathToFileURL(xsdDir + path.sep).href;
6168
- let schemaDoc;
6169
- try {
6170
- schemaDoc = libxmljs.parseXml(rewrittenXsd, { baseUrl });
6171
- } catch (err) {
6172
- return { valid: false, errors: [`XSD parse failed: ${err.message}`] };
6173
- }
6174
- let xmlDoc;
6175
- try {
6176
- xmlDoc = libxmljs.parseXml(xml);
6177
- } catch (err) {
6178
- return { valid: false, errors: [`XML parse failed: ${err.message}`] };
6179
- }
6180
- const valid = xmlDoc.validate(schemaDoc);
6181
- const errors = valid ? [] : xmlDoc.validationErrors.map((err) => err.message.trim());
6182
- return { valid, errors };
6183
- }
6184
-
6185
- // src/models/index.ts
6186
- init_esm_shims();
6187
-
6188
- // src/models/common.ts
6189
- init_esm_shims();
6190
-
6191
- // src/models/auth/index.ts
6192
- init_esm_shims();
6193
-
6194
- // src/models/auth/types.ts
6195
- init_esm_shims();
6196
-
6197
- // src/models/auth/active-sessions-types.ts
6198
- init_esm_shims();
6199
-
6200
- // src/models/sessions/index.ts
6201
- init_esm_shims();
6202
-
6203
- // src/models/sessions/online-types.ts
6204
- init_esm_shims();
6205
-
6206
- // src/models/sessions/batch-types.ts
6207
- init_esm_shims();
6208
-
6209
- // src/models/sessions/status-types.ts
6210
- init_esm_shims();
6211
-
6212
- // src/models/sessions/session-state.ts
6213
- init_esm_shims();
6214
-
6215
- // src/models/invoices/index.ts
6216
- init_esm_shims();
6217
-
6218
- // src/models/invoices/types.ts
6219
- init_esm_shims();
6220
-
6221
- // src/models/permissions/index.ts
6222
- init_esm_shims();
6223
-
6224
- // src/models/permissions/types.ts
6225
- init_esm_shims();
6226
-
6227
- // src/models/tokens/index.ts
6228
- init_esm_shims();
6229
-
6230
- // src/models/tokens/types.ts
6231
- init_esm_shims();
6232
-
6233
- // src/models/certificates/index.ts
6234
- init_esm_shims();
6235
-
6236
- // src/models/certificates/types.ts
6237
- init_esm_shims();
6238
-
6239
- // src/models/lighthouse/index.ts
6240
- init_esm_shims();
6241
-
6242
- // src/models/lighthouse/types.ts
6243
- init_esm_shims();
6244
-
6245
- // src/models/limits/index.ts
6246
- init_esm_shims();
6247
-
6248
- // src/models/limits/types.ts
6249
- init_esm_shims();
6250
-
6251
- // src/models/peppol/index.ts
6252
- init_esm_shims();
6253
-
6254
- // src/models/peppol/types.ts
6255
- init_esm_shims();
6256
-
6257
- // src/models/test-data/index.ts
6258
- init_esm_shims();
6259
-
6260
- // src/models/test-data/types.ts
6261
- init_esm_shims();
6262
-
6263
- // src/models/crypto/index.ts
6264
- init_esm_shims();
6265
-
6266
- // src/models/crypto/types.ts
6267
- init_esm_shims();
6268
-
6269
- // src/models/qrcode/index.ts
6270
- init_esm_shims();
6271
-
6272
- // src/models/qrcode/types.ts
6273
- init_esm_shims();
6274
-
6275
- // src/models/index.ts
6276
- init_document_structures();
6277
-
6278
6096
  // src/services/index.ts
6279
6097
  init_esm_shims();
6280
6098
  init_auth();
@@ -8192,7 +8010,6 @@ function buildDefaultFilters(subjectType, from, to) {
8192
8010
 
8193
8011
  // src/workflows/hwm-storage.ts
8194
8012
  init_esm_shims();
8195
- import * as fs2 from "node:fs/promises";
8196
8013
  var InMemoryHwmStore = class {
8197
8014
  points = {};
8198
8015
  async load() {
@@ -8202,30 +8019,38 @@ var InMemoryHwmStore = class {
8202
8019
  this.points = { ...points };
8203
8020
  }
8204
8021
  };
8205
- var FileHwmStore = class {
8206
- constructor(filePath) {
8207
- this.filePath = filePath;
8208
- }
8209
- async load() {
8210
- try {
8211
- const data = await fs2.readFile(this.filePath, "utf-8");
8212
- return JSON.parse(data);
8213
- } catch (err) {
8214
- if (err.code === "ENOENT") {
8215
- return {};
8216
- }
8217
- throw err;
8218
- }
8219
- }
8220
- async save(points) {
8221
- await fs2.writeFile(this.filePath, JSON.stringify(points, null, 2), "utf-8");
8222
- }
8223
- };
8224
8022
 
8225
8023
  // src/workflows/auth-workflow.ts
8226
8024
  init_esm_shims();
8227
8025
  init_auth_xml_builder();
8228
8026
  init_with_key_rotation_retry();
8027
+ init_ksef_auth_status_error();
8028
+ var AUTH_STATUS_SUCCESS = 200;
8029
+ var AUTH_STATUS_IN_PROGRESS = 100;
8030
+ async function awaitAuthentication(client, referenceNumber, authToken, pollOptions) {
8031
+ const final = await pollUntil(
8032
+ () => client.auth.getAuthStatus(referenceNumber, authToken),
8033
+ (s) => s.status.code !== AUTH_STATUS_IN_PROGRESS,
8034
+ { ...pollOptions, description: `auth ${referenceNumber}` }
8035
+ );
8036
+ if (final.status.code !== AUTH_STATUS_SUCCESS) {
8037
+ const details = final.status.details?.length ? ` (${final.status.details.join("; ")})` : "";
8038
+ throw new KSeFAuthStatusError(
8039
+ `Authentication failed with status ${final.status.code}: ${final.status.description}${details}`,
8040
+ referenceNumber,
8041
+ final.status.description
8042
+ );
8043
+ }
8044
+ const tokens = await client.auth.getAccessToken(authToken);
8045
+ client.authManager.setAccessToken(tokens.accessToken.token);
8046
+ client.authManager.setRefreshToken(tokens.refreshToken.token);
8047
+ return {
8048
+ accessToken: tokens.accessToken.token,
8049
+ accessTokenValidUntil: tokens.accessToken.validUntil,
8050
+ refreshToken: tokens.refreshToken.token,
8051
+ refreshTokenValidUntil: tokens.refreshToken.validUntil
8052
+ };
8053
+ }
8229
8054
  async function authenticateWithToken(client, options) {
8230
8055
  const challenge = await client.auth.getChallenge();
8231
8056
  await client.crypto.init();
@@ -8240,20 +8065,7 @@ async function authenticateWithToken(client, options) {
8240
8065
  });
8241
8066
  });
8242
8067
  const authToken = submitResult.authenticationToken.token;
8243
- await pollUntil(
8244
- () => client.auth.getAuthStatus(submitResult.referenceNumber, authToken),
8245
- (s) => s.status.code !== 100,
8246
- { ...options.pollOptions, description: `auth ${submitResult.referenceNumber}` }
8247
- );
8248
- const tokens = await client.auth.getAccessToken(authToken);
8249
- client.authManager.setAccessToken(tokens.accessToken.token);
8250
- client.authManager.setRefreshToken(tokens.refreshToken.token);
8251
- return {
8252
- accessToken: tokens.accessToken.token,
8253
- accessTokenValidUntil: tokens.accessToken.validUntil,
8254
- refreshToken: tokens.refreshToken.token,
8255
- refreshTokenValidUntil: tokens.refreshToken.validUntil
8256
- };
8068
+ return awaitAuthentication(client, submitResult.referenceNumber, authToken, options.pollOptions);
8257
8069
  }
8258
8070
  async function authenticateWithCertificate(client, options) {
8259
8071
  const challenge = await client.auth.getChallenge();
@@ -8267,20 +8079,7 @@ async function authenticateWithCertificate(client, options) {
8267
8079
  options.enforceXadesCompliance ?? false
8268
8080
  );
8269
8081
  const authToken = submitResult.authenticationToken.token;
8270
- await pollUntil(
8271
- () => client.auth.getAuthStatus(submitResult.referenceNumber, authToken),
8272
- (s) => s.status.code !== 100,
8273
- { ...options.pollOptions, description: `auth ${submitResult.referenceNumber}` }
8274
- );
8275
- const tokens = await client.auth.getAccessToken(authToken);
8276
- client.authManager.setAccessToken(tokens.accessToken.token);
8277
- client.authManager.setRefreshToken(tokens.refreshToken.token);
8278
- return {
8279
- accessToken: tokens.accessToken.token,
8280
- accessTokenValidUntil: tokens.accessToken.validUntil,
8281
- refreshToken: tokens.refreshToken.token,
8282
- refreshTokenValidUntil: tokens.refreshToken.validUntil
8283
- };
8082
+ return awaitAuthentication(client, submitResult.referenceNumber, authToken, options.pollOptions);
8284
8083
  }
8285
8084
  async function authenticateWithExternalSignature(client, options) {
8286
8085
  const challenge = await client.auth.getChallenge();
@@ -8295,20 +8094,7 @@ async function authenticateWithExternalSignature(client, options) {
8295
8094
  options.enforceXadesCompliance ?? false
8296
8095
  );
8297
8096
  const authToken = submitResult.authenticationToken.token;
8298
- await pollUntil(
8299
- () => client.auth.getAuthStatus(submitResult.referenceNumber, authToken),
8300
- (s) => s.status.code !== 100,
8301
- { ...options.pollOptions, description: `auth ${submitResult.referenceNumber}` }
8302
- );
8303
- const tokens = await client.auth.getAccessToken(authToken);
8304
- client.authManager.setAccessToken(tokens.accessToken.token);
8305
- client.authManager.setRefreshToken(tokens.refreshToken.token);
8306
- return {
8307
- accessToken: tokens.accessToken.token,
8308
- accessTokenValidUntil: tokens.accessToken.validUntil,
8309
- refreshToken: tokens.refreshToken.token,
8310
- refreshTokenValidUntil: tokens.refreshToken.validUntil
8311
- };
8097
+ return awaitAuthentication(client, submitResult.referenceNumber, authToken, options.pollOptions);
8312
8098
  }
8313
8099
  async function authenticateWithPkcs12(client, options) {
8314
8100
  const { Pkcs12Loader: Pkcs12Loader2 } = await Promise.resolve().then(() => (init_pkcs12_loader(), pkcs12_loader_exports));
@@ -8323,6 +8109,95 @@ async function authenticateWithPkcs12(client, options) {
8323
8109
  });
8324
8110
  }
8325
8111
 
8112
+ // src/workflows/metadata-query-paging.ts
8113
+ init_esm_shims();
8114
+ init_ksef_metadata_pagination_error();
8115
+ init_ksef_validation_error();
8116
+ var DEFAULT_PAGE_SIZE = 100;
8117
+ var DEFAULT_MAX_BOUNDARY_CROSSINGS = 1e3;
8118
+ function boundaryFieldFor(dateType) {
8119
+ switch (dateType) {
8120
+ case "Issue":
8121
+ return "issueDate";
8122
+ case "Invoicing":
8123
+ return "invoicingDate";
8124
+ case "PermanentStorage":
8125
+ return "permanentStorageDate";
8126
+ }
8127
+ }
8128
+ async function* queryAllInvoiceMetadata(client, filters, options = {}) {
8129
+ const sortOrder = options.sortOrder ?? "Asc";
8130
+ const pageSize = options.pageSize ?? DEFAULT_PAGE_SIZE;
8131
+ const maxBoundaryCrossings = options.maxBoundaryCrossings ?? DEFAULT_MAX_BOUNDARY_CROSSINGS;
8132
+ if (!Number.isInteger(pageSize) || pageSize <= 0) {
8133
+ throw new KSeFValidationError("`pageSize` must be a positive integer.");
8134
+ }
8135
+ if (!Number.isInteger(maxBoundaryCrossings) || maxBoundaryCrossings < 0) {
8136
+ throw new KSeFValidationError("`maxBoundaryCrossings` must be a non-negative integer.");
8137
+ }
8138
+ const boundaryField = boundaryFieldFor(filters.dateRange.dateType);
8139
+ let dateRange = { ...filters.dateRange };
8140
+ let boundaryCrossings = 0;
8141
+ let carryKeys = /* @__PURE__ */ new Set();
8142
+ let carryValue;
8143
+ for (; ; ) {
8144
+ let pageIndex = 0;
8145
+ let lastBoundaryValue;
8146
+ let isTruncated = false;
8147
+ let boundaryKeys = /* @__PURE__ */ new Set();
8148
+ for (; ; ) {
8149
+ const window = { ...filters, dateRange };
8150
+ const response = await client.invoices.queryInvoiceMetadata(
8151
+ window,
8152
+ pageIndex,
8153
+ pageSize,
8154
+ sortOrder
8155
+ );
8156
+ isTruncated = response.isTruncated;
8157
+ for (const invoice of response.invoices) {
8158
+ const boundaryValue = invoice[boundaryField];
8159
+ const key = invoice.ksefNumber.toLowerCase();
8160
+ if (boundaryValue === carryValue && carryKeys.has(key)) continue;
8161
+ if (boundaryValue !== lastBoundaryValue) {
8162
+ lastBoundaryValue = boundaryValue;
8163
+ boundaryKeys = /* @__PURE__ */ new Set();
8164
+ }
8165
+ boundaryKeys.add(key);
8166
+ yield invoice;
8167
+ }
8168
+ if (response.hasMore) {
8169
+ pageIndex += 1;
8170
+ continue;
8171
+ }
8172
+ break;
8173
+ }
8174
+ if (!isTruncated || lastBoundaryValue === void 0) return;
8175
+ const previousBoundary = sortOrder === "Asc" ? dateRange.from : dateRange.to;
8176
+ if (previousBoundary === lastBoundaryValue) {
8177
+ throw new KSeFMetadataPaginationError(
8178
+ `Metadata paging stalled: a truncated window did not advance past ${boundaryField}=${lastBoundaryValue}. The result set likely exceeds the server cap within a single ${boundaryField} value; narrow the query further.`,
8179
+ lastBoundaryValue
8180
+ );
8181
+ }
8182
+ if (++boundaryCrossings > maxBoundaryCrossings) {
8183
+ throw new KSeFMetadataPaginationError(
8184
+ `Metadata paging exceeded ${maxBoundaryCrossings} truncation boundaries; aborting to avoid an unbounded loop.`,
8185
+ lastBoundaryValue
8186
+ );
8187
+ }
8188
+ carryKeys = boundaryKeys;
8189
+ carryValue = lastBoundaryValue;
8190
+ dateRange = sortOrder === "Asc" ? { ...dateRange, from: lastBoundaryValue } : { ...dateRange, to: lastBoundaryValue };
8191
+ }
8192
+ }
8193
+ async function collectAllInvoiceMetadata(client, filters, options = {}) {
8194
+ const all = [];
8195
+ for await (const invoice of queryAllInvoiceMetadata(client, filters, options)) {
8196
+ all.push(invoice);
8197
+ }
8198
+ return all;
8199
+ }
8200
+
8326
8201
  // src/offline/index.ts
8327
8202
  init_esm_shims();
8328
8203
  init_deadline();
@@ -8367,98 +8242,6 @@ var InMemoryOfflineInvoiceStorage = class {
8367
8242
  }
8368
8243
  };
8369
8244
 
8370
- // src/offline/file-storage.ts
8371
- init_esm_shims();
8372
- import * as fs3 from "node:fs/promises";
8373
- import * as path2 from "node:path";
8374
- import * as os from "node:os";
8375
- function resolveDir(dir) {
8376
- if (dir === "~" || dir.startsWith("~/")) {
8377
- return path2.join(os.homedir(), dir.slice(1));
8378
- }
8379
- return dir;
8380
- }
8381
- var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
8382
- function validateId(id) {
8383
- if (!UUID_RE.test(id)) {
8384
- throw new Error(`Invalid invoice ID: ${id}`);
8385
- }
8386
- }
8387
- var FileOfflineInvoiceStorage = class {
8388
- dir;
8389
- constructor(directory) {
8390
- this.dir = resolveDir(directory ?? "~/.ksef/offline");
8391
- }
8392
- async ensureDir() {
8393
- await fs3.mkdir(this.dir, { recursive: true });
8394
- }
8395
- filePath(id) {
8396
- validateId(id);
8397
- return path2.join(this.dir, `${id}.json`);
8398
- }
8399
- async save(invoice) {
8400
- await this.ensureDir();
8401
- const file = this.filePath(invoice.id);
8402
- const tmp = `${file}.tmp`;
8403
- await fs3.writeFile(tmp, JSON.stringify(invoice, null, 2));
8404
- await fs3.rename(tmp, file);
8405
- }
8406
- async get(id) {
8407
- const file = this.filePath(id);
8408
- try {
8409
- return JSON.parse(await fs3.readFile(file, "utf-8"));
8410
- } catch (err) {
8411
- if (err instanceof Error && "code" in err && err.code === "ENOENT") {
8412
- return null;
8413
- }
8414
- console.warn(`Warning: Failed to read offline invoice ${id}: ${err instanceof Error ? err.message : String(err)}`);
8415
- return null;
8416
- }
8417
- }
8418
- async list(filter) {
8419
- let files;
8420
- try {
8421
- files = (await fs3.readdir(this.dir)).filter((f) => f.endsWith(".json"));
8422
- } catch {
8423
- return [];
8424
- }
8425
- const results = [];
8426
- for (const file of files) {
8427
- try {
8428
- const data = JSON.parse(
8429
- await fs3.readFile(path2.join(this.dir, file), "utf-8")
8430
- );
8431
- if (!filter || matchesFilter(data, filter)) {
8432
- results.push(data);
8433
- }
8434
- } catch (err) {
8435
- console.warn(`Warning: Skipping corrupt offline invoice file ${file}: ${err instanceof Error ? err.message : String(err)}`);
8436
- }
8437
- }
8438
- return results;
8439
- }
8440
- /**
8441
- * Update invoice metadata (read-modify-write).
8442
- *
8443
- * Note: No file locking — concurrent updates to the same ID may cause
8444
- * lost writes. Acceptable for CLI (single process). Library consumers
8445
- * running parallel operations should use external locking.
8446
- */
8447
- async update(id, updates) {
8448
- const existing = await this.get(id);
8449
- if (!existing) throw new Error(`Offline invoice not found: ${id}`);
8450
- await this.save({ ...existing, ...updates });
8451
- }
8452
- async delete(id) {
8453
- const file = this.filePath(id);
8454
- try {
8455
- await fs3.unlink(file);
8456
- } catch (e) {
8457
- if (e instanceof Error && "code" in e && e.code !== "ENOENT") throw e;
8458
- }
8459
- }
8460
- };
8461
-
8462
8245
  // src/index.ts
8463
8246
  init_offline_invoice_workflow();
8464
8247
  init_client();
@@ -8480,6 +8263,7 @@ export {
8480
8263
  CertificateFetcher,
8481
8264
  CertificateFingerprint,
8482
8265
  CertificateName,
8266
+ CertificateSerialNumber,
8483
8267
  CertificateService,
8484
8268
  CircuitBreakerPolicy,
8485
8269
  CryptographyService,
@@ -8491,11 +8275,8 @@ export {
8491
8275
  EntityPermissionGrantBuilder,
8492
8276
  Environment,
8493
8277
  FAKTURA_NAMESPACE,
8494
- FA_XSD_PATHS,
8495
8278
  FORM_CODES,
8496
8279
  FORM_CODE_KEYS,
8497
- FileHwmStore,
8498
- FileOfflineInvoiceStorage,
8499
8280
  INVOICE_TYPES_BY_SYSTEM_CODE,
8500
8281
  InMemoryHwmStore,
8501
8282
  InMemoryOfflineInvoiceStorage,
@@ -8516,6 +8297,7 @@ export {
8516
8297
  KSeFErrorCode,
8517
8298
  KSeFForbiddenError,
8518
8299
  KSeFGoneError,
8300
+ KSeFMetadataPaginationError,
8519
8301
  KSeFRateLimitError,
8520
8302
  KSeFSessionExpiredError,
8521
8303
  KSeFUnauthorizedError,
@@ -8533,7 +8315,6 @@ export {
8533
8315
  OfflineInvoiceWorkflow,
8534
8316
  OnlineSessionService,
8535
8317
  PEF_NAMESPACE,
8536
- PEF_XSD_PATHS,
8537
8318
  PERMISSION_DESCRIPTION_MAX_LENGTH,
8538
8319
  PERMISSION_DESCRIPTION_MIN_LENGTH,
8539
8320
  PeppolId,
@@ -8577,6 +8358,7 @@ export {
8577
8358
  buildXmlFromObject,
8578
8359
  calculateBackoff,
8579
8360
  calculateOfflineDeadline,
8361
+ collectAllInvoiceMetadata,
8580
8362
  comparePKey,
8581
8363
  createTarGz,
8582
8364
  createZip,
@@ -8601,7 +8383,6 @@ export {
8601
8383
  isExpired,
8602
8384
  isFakturaInput,
8603
8385
  isFormCodeShape,
8604
- isMissingLibxmljsError,
8605
8386
  isPefUblDocumentInput,
8606
8387
  isPolishHoliday,
8607
8388
  isRetryableError,
@@ -8609,6 +8390,7 @@ export {
8609
8390
  isValidBase64,
8610
8391
  isValidCertificateFingerprint,
8611
8392
  isValidCertificateName,
8393
+ isValidCertificateSerialNumber,
8612
8394
  isValidInternalId,
8613
8395
  isValidIp4Address,
8614
8396
  isValidKsefNumber,
@@ -8621,7 +8403,6 @@ export {
8621
8403
  isValidReferenceNumber,
8622
8404
  isValidSha256Base64,
8623
8405
  isValidVatUe,
8624
- libxmljsAvailable,
8625
8406
  nextBusinessDay,
8626
8407
  openOnlineSession,
8627
8408
  openSendAndClose,
@@ -8632,8 +8413,8 @@ export {
8632
8413
  parseUpoXml,
8633
8414
  parseXml,
8634
8415
  pollUntil,
8416
+ queryAllInvoiceMetadata,
8635
8417
  resolveOptions,
8636
- resolveXsdFor,
8637
8418
  resumeOnlineSession,
8638
8419
  runWithConcurrency,
8639
8420
  serializeInvoiceXml,
@@ -8648,7 +8429,6 @@ export {
8648
8429
  uploadBatchStream,
8649
8430
  uploadBatchStreamParsed,
8650
8431
  validate,
8651
- validateAgainstXsd,
8652
8432
  validateBatch,
8653
8433
  validateBusinessRules,
8654
8434
  validateCharValidity,