ksef-client-ts 0.9.1 → 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
  });
@@ -585,21 +585,21 @@ var init_rest_request = __esm({
585
585
  _query = [];
586
586
  _presigned = false;
587
587
  _skipAuthRetry = false;
588
- constructor(method, path3) {
588
+ constructor(method, path) {
589
589
  this.method = method;
590
- this.path = path3;
590
+ this.path = path;
591
591
  }
592
- static get(path3) {
593
- return new _RestRequest("GET", path3);
592
+ static get(path) {
593
+ return new _RestRequest("GET", path);
594
594
  }
595
- static post(path3) {
596
- return new _RestRequest("POST", path3);
595
+ static post(path) {
596
+ return new _RestRequest("POST", path);
597
597
  }
598
- static put(path3) {
599
- return new _RestRequest("PUT", path3);
598
+ static put(path) {
599
+ return new _RestRequest("PUT", path);
600
600
  }
601
- static delete(path3) {
602
- return new _RestRequest("DELETE", path3);
601
+ static delete(path) {
602
+ return new _RestRequest("DELETE", path);
603
603
  }
604
604
  body(data) {
605
605
  this._body = data;
@@ -963,13 +963,13 @@ var init_rest_client = __esm({
963
963
  }
964
964
  throw lastError;
965
965
  }
966
- recordCircuitOutcome(path3, status) {
966
+ recordCircuitOutcome(path, status) {
967
967
  if (!this.circuitBreakerPolicy) return;
968
968
  if (status >= 500) {
969
- this.circuitBreakerPolicy.recordFailure(path3);
969
+ this.circuitBreakerPolicy.recordFailure(path);
970
970
  return;
971
971
  }
972
- this.circuitBreakerPolicy.recordSuccess(path3);
972
+ this.circuitBreakerPolicy.recordSuccess(path);
973
973
  }
974
974
  async doRequest(request, url, overrideToken) {
975
975
  const headers = {
@@ -1006,9 +1006,9 @@ var init_rest_client = __esm({
1006
1006
  return response;
1007
1007
  }
1008
1008
  buildUrl(request) {
1009
- const path3 = this.routeBuilder.build(request.path);
1009
+ const path = this.routeBuilder.build(request.path);
1010
1010
  const base = this.options.baseUrl;
1011
- const url = new URL(`${base}${path3}`);
1011
+ const url = new URL(`${base}${path}`);
1012
1012
  const query = request.getQuery();
1013
1013
  for (const [key, value] of query) {
1014
1014
  url.searchParams.append(key, value);
@@ -2859,11 +2859,6 @@ var init_schemas = __esm({
2859
2859
  "src/validation/schemas/index.ts"() {
2860
2860
  "use strict";
2861
2861
  init_esm_shims();
2862
- init_fa3();
2863
- init_fa2();
2864
- init_fa_rr1();
2865
- init_pef3();
2866
- init_pef_kor3();
2867
2862
  NAMESPACE_MAP = {
2868
2863
  "http://crd.gov.pl/wzor/2025/06/25/13775/": "FA3",
2869
2864
  "http://crd.gov.pl/wzor/2023/06/29/12648/": "FA2",
@@ -3119,11 +3114,11 @@ async function validateSchema(xml, options, _parsed) {
3119
3114
  const prefix = rootElement ? `/${rootElement}/` : "/";
3120
3115
  const validationErrors = result.error.issues.map((issue) => {
3121
3116
  const zodPath = issue.path.join("/");
3122
- const path3 = zodPath ? `${prefix}${zodPath}` : rootElement ? `/${rootElement}` : void 0;
3117
+ const path = zodPath ? `${prefix}${zodPath}` : rootElement ? `/${rootElement}` : void 0;
3123
3118
  return {
3124
3119
  code: mapZodErrorCode(issue),
3125
3120
  message: issue.message,
3126
- path: path3
3121
+ path
3127
3122
  };
3128
3123
  });
3129
3124
  return { valid: false, schemaType, errors: validationErrors };
@@ -3163,9 +3158,9 @@ function validateBusinessRules(xml, _parsed) {
3163
3158
  collectDateErrors(object, rootElement, errors);
3164
3159
  return { valid: errors.length === 0, schemaType, errors };
3165
3160
  }
3166
- function collectNipPeselErrors(obj, path3, errors) {
3161
+ function collectNipPeselErrors(obj, path, errors) {
3167
3162
  for (const [key, value] of Object.entries(obj)) {
3168
- const currentPath = path3 ? `${path3}/${key}` : key;
3163
+ const currentPath = path ? `${path}/${key}` : key;
3169
3164
  if (key === "NIP" && typeof value === "string") {
3170
3165
  if (!isValidNip(value)) {
3171
3166
  errors.push({
@@ -4120,20 +4115,20 @@ var init_lighthouse = __esm({
4120
4115
  this.lighthouseUrl = options.lighthouseUrl;
4121
4116
  this.timeout = options.timeout;
4122
4117
  }
4123
- async fetchJson(path3) {
4118
+ async fetchJson(path) {
4124
4119
  if (!this.lighthouseUrl) {
4125
4120
  throw new KSeFError(
4126
4121
  "Lighthouse API is not available for the DEMO environment. Use TEST or PROD instead."
4127
4122
  );
4128
4123
  }
4129
- const response = await fetch(`${this.lighthouseUrl}${path3}`, {
4124
+ const response = await fetch(`${this.lighthouseUrl}${path}`, {
4130
4125
  headers: { Accept: "application/json" },
4131
4126
  signal: AbortSignal.timeout(this.timeout)
4132
4127
  });
4133
4128
  if (!response.ok) {
4134
4129
  const body = await response.text();
4135
4130
  throw new KSeFError(
4136
- `Lighthouse ${path3} failed: HTTP ${response.status} \u2014 ${body}`
4131
+ `Lighthouse ${path} failed: HTTP ${response.status} \u2014 ${body}`
4137
4132
  );
4138
4133
  }
4139
4134
  return await response.json();
@@ -5104,6 +5099,7 @@ var init_verification_link_service = __esm({
5104
5099
  constructor(baseQrUrl) {
5105
5100
  this.baseQrUrl = baseQrUrl;
5106
5101
  }
5102
+ baseQrUrl;
5107
5103
  /**
5108
5104
  * Build invoice verification URL (Code I).
5109
5105
  * Format: {baseQrUrl}/invoice/{NIP}/{DD-MM-YYYY}/{hash_base64url}
@@ -5584,6 +5580,7 @@ var init_offline_invoice_workflow = __esm({
5584
5580
  constructor(qrService) {
5585
5581
  this.qrService = qrService;
5586
5582
  }
5583
+ qrService;
5587
5584
  async generate(input, options) {
5588
5585
  if (!input.invoiceXml || input.invoiceXml.trim().length === 0) {
5589
5586
  throw new Error("invoiceXml must not be empty");
@@ -6096,219 +6093,6 @@ init_schema_registry();
6096
6093
  init_invoice_validator();
6097
6094
  init_char_validity();
6098
6095
 
6099
- // src/validation/xsd-validator.ts
6100
- init_esm_shims();
6101
- import { createRequire } from "node:module";
6102
- import * as fs from "node:fs";
6103
- import * as path from "node:path";
6104
- import { fileURLToPath, pathToFileURL } from "node:url";
6105
- var cachedPkgRoot = null;
6106
- function locatePackageRoot() {
6107
- if (cachedPkgRoot !== null) return cachedPkgRoot;
6108
- let dir = path.dirname(fileURLToPath(import.meta.url));
6109
- const root = path.parse(dir).root;
6110
- while (dir !== root) {
6111
- const candidate = path.join(dir, "docs", "schemas");
6112
- if (fs.existsSync(candidate)) {
6113
- cachedPkgRoot = dir;
6114
- return dir;
6115
- }
6116
- dir = path.dirname(dir);
6117
- }
6118
- throw new Error("Could not locate ksef-client-ts package root (docs/schemas not found).");
6119
- }
6120
- var XSD_RELATIVE = {
6121
- FA2: ["FA", "schemat_FA(2)_v1-0E.xsd"],
6122
- FA3: ["FA", "schemat_FA(3)_v1-0E.xsd"],
6123
- PEF: ["PEF", "Schemat_PEF(3)_v2-1.xsd"],
6124
- PEF_KOR: ["PEF", "Schemat_PEF_KOR(3)_v2-1.xsd"]
6125
- };
6126
- var FA_XSD_PATHS = {
6127
- get FA2() {
6128
- return resolveXsdFor("FA2");
6129
- },
6130
- get FA3() {
6131
- return resolveXsdFor("FA3");
6132
- }
6133
- };
6134
- var PEF_XSD_PATHS = {
6135
- get PEF() {
6136
- return resolveXsdFor("PEF");
6137
- },
6138
- get PEF_KOR() {
6139
- return resolveXsdFor("PEF_KOR");
6140
- }
6141
- };
6142
- function resolveXsdFor(schema) {
6143
- const rel = XSD_RELATIVE[schema];
6144
- if (!rel) throw new Error(`Unknown invoice schema: ${String(schema)}`);
6145
- return path.join(locatePackageRoot(), "docs", "schemas", ...rel);
6146
- }
6147
- var requireModule = createRequire(import.meta.url);
6148
- var libxmljs = null;
6149
- var libxmljsLoadError = null;
6150
- try {
6151
- libxmljs = requireModule("libxmljs2");
6152
- } catch (err) {
6153
- const code = err?.code;
6154
- if (code === "MODULE_NOT_FOUND" || code === "ERR_MODULE_NOT_FOUND") {
6155
- libxmljs = null;
6156
- } else {
6157
- libxmljs = null;
6158
- libxmljsLoadError = err instanceof Error ? err : new Error(String(err));
6159
- }
6160
- }
6161
- var libxmljsAvailable = libxmljs !== null;
6162
- var MISSING_LIBXMLJS_MESSAGE_PREFIX = "libxmljs2 is not installed";
6163
- function isMissingLibxmljsError(err) {
6164
- return err instanceof Error && err.message.startsWith(MISSING_LIBXMLJS_MESSAGE_PREFIX);
6165
- }
6166
- var EXTERNAL_STRUKTURY_DANYCH_URL = /schemaLocation="http:\/\/crd\.gov\.pl\/xml\/schematy\/dziedzinowe\/mf\/2022\/01\/05\/eD\/DefinicjeTypy\/StrukturyDanych_v10-0E\.xsd"/;
6167
- function rewriteSchemaLocations(xsdContent) {
6168
- if (!EXTERNAL_STRUKTURY_DANYCH_URL.test(xsdContent)) {
6169
- return xsdContent;
6170
- }
6171
- const bazoweStrukturyPath = path.join(
6172
- locatePackageRoot(),
6173
- "docs",
6174
- "schemas",
6175
- "FA",
6176
- "bazowe",
6177
- "StrukturyDanych_v10-0E.xsd"
6178
- );
6179
- const bazoweStrukturyUrl = pathToFileURL(bazoweStrukturyPath).href;
6180
- const rewritten = xsdContent.replace(
6181
- EXTERNAL_STRUKTURY_DANYCH_URL,
6182
- `schemaLocation="${bazoweStrukturyUrl}"`
6183
- );
6184
- if (rewritten === xsdContent) {
6185
- throw new Error(
6186
- "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`."
6187
- );
6188
- }
6189
- return rewritten;
6190
- }
6191
- function validateAgainstXsd(xml, xsdPath) {
6192
- if (!libxmljs) {
6193
- const loadSuffix = libxmljsLoadError ? ` (load failed: ${libxmljsLoadError.message})` : "";
6194
- throw new Error(
6195
- `${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\`).`
6196
- );
6197
- }
6198
- const xsdDir = path.dirname(xsdPath);
6199
- const rawXsd = fs.readFileSync(xsdPath, "utf8");
6200
- const rewrittenXsd = rewriteSchemaLocations(rawXsd);
6201
- const baseUrl = pathToFileURL(xsdDir + path.sep).href;
6202
- let schemaDoc;
6203
- try {
6204
- schemaDoc = libxmljs.parseXml(rewrittenXsd, { baseUrl });
6205
- } catch (err) {
6206
- return { valid: false, errors: [`XSD parse failed: ${err.message}`] };
6207
- }
6208
- let xmlDoc;
6209
- try {
6210
- xmlDoc = libxmljs.parseXml(xml);
6211
- } catch (err) {
6212
- return { valid: false, errors: [`XML parse failed: ${err.message}`] };
6213
- }
6214
- const valid = xmlDoc.validate(schemaDoc);
6215
- const errors = valid ? [] : xmlDoc.validationErrors.map((err) => err.message.trim());
6216
- return { valid, errors };
6217
- }
6218
-
6219
- // src/models/index.ts
6220
- init_esm_shims();
6221
-
6222
- // src/models/common.ts
6223
- init_esm_shims();
6224
-
6225
- // src/models/auth/index.ts
6226
- init_esm_shims();
6227
-
6228
- // src/models/auth/types.ts
6229
- init_esm_shims();
6230
-
6231
- // src/models/auth/active-sessions-types.ts
6232
- init_esm_shims();
6233
-
6234
- // src/models/sessions/index.ts
6235
- init_esm_shims();
6236
-
6237
- // src/models/sessions/online-types.ts
6238
- init_esm_shims();
6239
-
6240
- // src/models/sessions/batch-types.ts
6241
- init_esm_shims();
6242
-
6243
- // src/models/sessions/status-types.ts
6244
- init_esm_shims();
6245
-
6246
- // src/models/sessions/session-state.ts
6247
- init_esm_shims();
6248
-
6249
- // src/models/invoices/index.ts
6250
- init_esm_shims();
6251
-
6252
- // src/models/invoices/types.ts
6253
- init_esm_shims();
6254
-
6255
- // src/models/permissions/index.ts
6256
- init_esm_shims();
6257
-
6258
- // src/models/permissions/types.ts
6259
- init_esm_shims();
6260
-
6261
- // src/models/tokens/index.ts
6262
- init_esm_shims();
6263
-
6264
- // src/models/tokens/types.ts
6265
- init_esm_shims();
6266
-
6267
- // src/models/certificates/index.ts
6268
- init_esm_shims();
6269
-
6270
- // src/models/certificates/types.ts
6271
- init_esm_shims();
6272
-
6273
- // src/models/lighthouse/index.ts
6274
- init_esm_shims();
6275
-
6276
- // src/models/lighthouse/types.ts
6277
- init_esm_shims();
6278
-
6279
- // src/models/limits/index.ts
6280
- init_esm_shims();
6281
-
6282
- // src/models/limits/types.ts
6283
- init_esm_shims();
6284
-
6285
- // src/models/peppol/index.ts
6286
- init_esm_shims();
6287
-
6288
- // src/models/peppol/types.ts
6289
- init_esm_shims();
6290
-
6291
- // src/models/test-data/index.ts
6292
- init_esm_shims();
6293
-
6294
- // src/models/test-data/types.ts
6295
- init_esm_shims();
6296
-
6297
- // src/models/crypto/index.ts
6298
- init_esm_shims();
6299
-
6300
- // src/models/crypto/types.ts
6301
- init_esm_shims();
6302
-
6303
- // src/models/qrcode/index.ts
6304
- init_esm_shims();
6305
-
6306
- // src/models/qrcode/types.ts
6307
- init_esm_shims();
6308
-
6309
- // src/models/index.ts
6310
- init_document_structures();
6311
-
6312
6096
  // src/services/index.ts
6313
6097
  init_esm_shims();
6314
6098
  init_auth();
@@ -8226,7 +8010,6 @@ function buildDefaultFilters(subjectType, from, to) {
8226
8010
 
8227
8011
  // src/workflows/hwm-storage.ts
8228
8012
  init_esm_shims();
8229
- import * as fs2 from "node:fs/promises";
8230
8013
  var InMemoryHwmStore = class {
8231
8014
  points = {};
8232
8015
  async load() {
@@ -8236,25 +8019,6 @@ var InMemoryHwmStore = class {
8236
8019
  this.points = { ...points };
8237
8020
  }
8238
8021
  };
8239
- var FileHwmStore = class {
8240
- constructor(filePath) {
8241
- this.filePath = filePath;
8242
- }
8243
- async load() {
8244
- try {
8245
- const data = await fs2.readFile(this.filePath, "utf-8");
8246
- return JSON.parse(data);
8247
- } catch (err) {
8248
- if (err.code === "ENOENT") {
8249
- return {};
8250
- }
8251
- throw err;
8252
- }
8253
- }
8254
- async save(points) {
8255
- await fs2.writeFile(this.filePath, JSON.stringify(points, null, 2), "utf-8");
8256
- }
8257
- };
8258
8022
 
8259
8023
  // src/workflows/auth-workflow.ts
8260
8024
  init_esm_shims();
@@ -8478,98 +8242,6 @@ var InMemoryOfflineInvoiceStorage = class {
8478
8242
  }
8479
8243
  };
8480
8244
 
8481
- // src/offline/file-storage.ts
8482
- init_esm_shims();
8483
- import * as fs3 from "node:fs/promises";
8484
- import * as path2 from "node:path";
8485
- import * as os from "node:os";
8486
- function resolveDir(dir) {
8487
- if (dir === "~" || dir.startsWith("~/")) {
8488
- return path2.join(os.homedir(), dir.slice(1));
8489
- }
8490
- return dir;
8491
- }
8492
- var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
8493
- function validateId(id) {
8494
- if (!UUID_RE.test(id)) {
8495
- throw new Error(`Invalid invoice ID: ${id}`);
8496
- }
8497
- }
8498
- var FileOfflineInvoiceStorage = class {
8499
- dir;
8500
- constructor(directory) {
8501
- this.dir = resolveDir(directory ?? "~/.ksef/offline");
8502
- }
8503
- async ensureDir() {
8504
- await fs3.mkdir(this.dir, { recursive: true });
8505
- }
8506
- filePath(id) {
8507
- validateId(id);
8508
- return path2.join(this.dir, `${id}.json`);
8509
- }
8510
- async save(invoice) {
8511
- await this.ensureDir();
8512
- const file = this.filePath(invoice.id);
8513
- const tmp = `${file}.tmp`;
8514
- await fs3.writeFile(tmp, JSON.stringify(invoice, null, 2));
8515
- await fs3.rename(tmp, file);
8516
- }
8517
- async get(id) {
8518
- const file = this.filePath(id);
8519
- try {
8520
- return JSON.parse(await fs3.readFile(file, "utf-8"));
8521
- } catch (err) {
8522
- if (err instanceof Error && "code" in err && err.code === "ENOENT") {
8523
- return null;
8524
- }
8525
- console.warn(`Warning: Failed to read offline invoice ${id}: ${err instanceof Error ? err.message : String(err)}`);
8526
- return null;
8527
- }
8528
- }
8529
- async list(filter) {
8530
- let files;
8531
- try {
8532
- files = (await fs3.readdir(this.dir)).filter((f) => f.endsWith(".json"));
8533
- } catch {
8534
- return [];
8535
- }
8536
- const results = [];
8537
- for (const file of files) {
8538
- try {
8539
- const data = JSON.parse(
8540
- await fs3.readFile(path2.join(this.dir, file), "utf-8")
8541
- );
8542
- if (!filter || matchesFilter(data, filter)) {
8543
- results.push(data);
8544
- }
8545
- } catch (err) {
8546
- console.warn(`Warning: Skipping corrupt offline invoice file ${file}: ${err instanceof Error ? err.message : String(err)}`);
8547
- }
8548
- }
8549
- return results;
8550
- }
8551
- /**
8552
- * Update invoice metadata (read-modify-write).
8553
- *
8554
- * Note: No file locking — concurrent updates to the same ID may cause
8555
- * lost writes. Acceptable for CLI (single process). Library consumers
8556
- * running parallel operations should use external locking.
8557
- */
8558
- async update(id, updates) {
8559
- const existing = await this.get(id);
8560
- if (!existing) throw new Error(`Offline invoice not found: ${id}`);
8561
- await this.save({ ...existing, ...updates });
8562
- }
8563
- async delete(id) {
8564
- const file = this.filePath(id);
8565
- try {
8566
- await fs3.unlink(file);
8567
- } catch (e) {
8568
- if (e instanceof Error && "code" in e && e.code !== "ENOENT") throw e;
8569
- }
8570
- }
8571
- };
8572
-
8573
8245
  // src/index.ts
8574
8246
  init_offline_invoice_workflow();
8575
8247
  init_client();
@@ -8603,11 +8275,8 @@ export {
8603
8275
  EntityPermissionGrantBuilder,
8604
8276
  Environment,
8605
8277
  FAKTURA_NAMESPACE,
8606
- FA_XSD_PATHS,
8607
8278
  FORM_CODES,
8608
8279
  FORM_CODE_KEYS,
8609
- FileHwmStore,
8610
- FileOfflineInvoiceStorage,
8611
8280
  INVOICE_TYPES_BY_SYSTEM_CODE,
8612
8281
  InMemoryHwmStore,
8613
8282
  InMemoryOfflineInvoiceStorage,
@@ -8646,7 +8315,6 @@ export {
8646
8315
  OfflineInvoiceWorkflow,
8647
8316
  OnlineSessionService,
8648
8317
  PEF_NAMESPACE,
8649
- PEF_XSD_PATHS,
8650
8318
  PERMISSION_DESCRIPTION_MAX_LENGTH,
8651
8319
  PERMISSION_DESCRIPTION_MIN_LENGTH,
8652
8320
  PeppolId,
@@ -8715,7 +8383,6 @@ export {
8715
8383
  isExpired,
8716
8384
  isFakturaInput,
8717
8385
  isFormCodeShape,
8718
- isMissingLibxmljsError,
8719
8386
  isPefUblDocumentInput,
8720
8387
  isPolishHoliday,
8721
8388
  isRetryableError,
@@ -8736,7 +8403,6 @@ export {
8736
8403
  isValidReferenceNumber,
8737
8404
  isValidSha256Base64,
8738
8405
  isValidVatUe,
8739
- libxmljsAvailable,
8740
8406
  nextBusinessDay,
8741
8407
  openOnlineSession,
8742
8408
  openSendAndClose,
@@ -8749,7 +8415,6 @@ export {
8749
8415
  pollUntil,
8750
8416
  queryAllInvoiceMetadata,
8751
8417
  resolveOptions,
8752
- resolveXsdFor,
8753
8418
  resumeOnlineSession,
8754
8419
  runWithConcurrency,
8755
8420
  serializeInvoiceXml,
@@ -8764,7 +8429,6 @@ export {
8764
8429
  uploadBatchStream,
8765
8430
  uploadBatchStreamParsed,
8766
8431
  validate,
8767
- validateAgainstXsd,
8768
8432
  validateBatch,
8769
8433
  validateBusinessRules,
8770
8434
  validateCharValidity,