facturas 0.13.0 → 0.15.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.
@@ -7,10 +7,10 @@ import {
7
7
  ARCA_RECEIVER_CONDITION_IDS,
8
8
  ARCA_VAT_RATES,
9
9
  ARCA_VOUCHER_TYPES
10
- } from "./chunk-LQMNKQ2V.mjs";
10
+ } from "./chunk-DHN6OQJP.mjs";
11
11
  import {
12
12
  createPadronService
13
- } from "./chunk-WVKVJTFG.mjs";
13
+ } from "./chunk-EXECWJEC.mjs";
14
14
  import {
15
15
  arcaMinorUnitsToNumber,
16
16
  assertArcaMinorUnits,
@@ -21,7 +21,7 @@ import {
21
21
  normalizeWsfeVoucherInput,
22
22
  roundHalfEvenRatio,
23
23
  serializeArcaExchangeRate
24
- } from "./chunk-BPBTQDCO.mjs";
24
+ } from "./chunk-VJ2ICMSA.mjs";
25
25
  import {
26
26
  createWsmtxcaService
27
27
  } from "./chunk-WN62NMUJ.mjs";
@@ -274,6 +274,121 @@ function invalidCredentialFields(normalized) {
274
274
  return invalidFields;
275
275
  }
276
276
 
277
+ // src/internal/dates.ts
278
+ function toIsoDate(value) {
279
+ if (typeof value !== "string" && typeof value !== "number") {
280
+ return void 0;
281
+ }
282
+ const text = String(value).trim();
283
+ if (/^\d{4}-\d{2}-\d{2}$/.test(text)) {
284
+ return text;
285
+ }
286
+ if (/^\d{8}$/.test(text)) {
287
+ return `${text.slice(0, 4)}-${text.slice(4, 6)}-${text.slice(6, 8)}`;
288
+ }
289
+ return void 0;
290
+ }
291
+
292
+ // src/services/qr.ts
293
+ var ARCA_QR_URL = "https://www.arca.gob.ar/fe/qr/";
294
+ function arcaQrUrl(input) {
295
+ const json = JSON.stringify(arcaQrPayload(input));
296
+ return `${ARCA_QR_URL}?p=${Buffer.from(json, "utf8").toString("base64")}`;
297
+ }
298
+ function arcaQrPayload(input) {
299
+ const fecha = isoCalendarDate(input.date);
300
+ const cuit = digits(input.taxId, "taxId", 11, 11);
301
+ for (const [field, max] of [
302
+ ["salesPoint", 99999],
303
+ ["voucherType", 999],
304
+ ["number", 99999999]
305
+ ]) {
306
+ const value = input[field];
307
+ if (!(Number.isSafeInteger(value) && value >= 1 && value <= max)) {
308
+ invalid(field, `an integer from 1 through ${max}`);
309
+ }
310
+ }
311
+ const total = Number(assertArcaMinorUnits(input.total, "total"));
312
+ const currency = (input.currency ?? "PES").trim().toUpperCase();
313
+ if (!/^[A-Z0-9]{3}$/.test(currency)) {
314
+ invalid("currency", "a three-character ARCA currency id");
315
+ }
316
+ const ctz = currency === "PES" ? 1 : exchangeRate(input.exchangeRate);
317
+ const codAut = digits(input.cae, "cae", 14, 14);
318
+ const document = receiverDocument(input.document);
319
+ return {
320
+ ver: 1,
321
+ fecha,
322
+ cuit,
323
+ ptoVta: input.salesPoint,
324
+ tipoCmp: input.voucherType,
325
+ nroCmp: input.number,
326
+ importe: Number((total / 100).toFixed(2)),
327
+ moneda: currency,
328
+ ctz,
329
+ ...document,
330
+ tipoCodAut: input.authorization === "CAEA" ? "A" : "E",
331
+ codAut
332
+ };
333
+ }
334
+ function isoCalendarDate(value) {
335
+ let compact;
336
+ try {
337
+ compact = normalizeWsfeDateInput(value, "date");
338
+ } catch {
339
+ invalid("date", "a YYYY-MM-DD or YYYYMMDD calendar date");
340
+ }
341
+ const iso2 = toIsoDate(compact);
342
+ if (iso2 === void 0) {
343
+ invalid("date", "a YYYY-MM-DD or YYYYMMDD calendar date");
344
+ }
345
+ return iso2;
346
+ }
347
+ function exchangeRate(value) {
348
+ if (value === void 0) {
349
+ invalid("exchangeRate", "a positive exchange rate for a non-peso currency");
350
+ }
351
+ const rate = Number(value);
352
+ if (!(Number.isFinite(rate) && rate > 0)) {
353
+ invalid("exchangeRate", "a positive number");
354
+ }
355
+ return rate;
356
+ }
357
+ function receiverDocument(document) {
358
+ if (document === void 0) {
359
+ return {};
360
+ }
361
+ if (!(Number.isSafeInteger(document.type) && document.type >= 0 && document.type <= 99)) {
362
+ invalid("document.type", "an ARCA document type");
363
+ }
364
+ const number = digits(document.number, "document.number", 0, 20);
365
+ if (document.type === 99 || number === 0) {
366
+ return {};
367
+ }
368
+ return { tipoDocRec: document.type, nroDocRec: number };
369
+ }
370
+ function digits(value, field, min, max) {
371
+ const text = String(value).trim();
372
+ if (!/^\d*$/.test(text) || text.length < min || text.length > max) {
373
+ invalid(field, min === max ? `${min} digits` : `${min} to ${max} digits`);
374
+ }
375
+ if (text === "") {
376
+ return 0;
377
+ }
378
+ const parsed = Number(text);
379
+ if (!Number.isSafeInteger(parsed)) {
380
+ invalid(field, "a safe integer");
381
+ }
382
+ return parsed;
383
+ }
384
+ function invalid(field, expected) {
385
+ throw new ArcaInputError(`qr.${field} must be ${expected}.`, {
386
+ code: "ARCA_INPUT_INVALID_VALUE",
387
+ field,
388
+ expected
389
+ });
390
+ }
391
+
277
392
  // src/store/types.ts
278
393
  import { createHash } from "crypto";
279
394
  function attemptKey(environment, taxId, key) {
@@ -504,35 +619,70 @@ function toVoucherSummary(found) {
504
619
  "receiverVatConditionId",
505
620
  "currencyId",
506
621
  "exchangeRate",
622
+ "result",
623
+ "cae"
624
+ ]) {
625
+ if (found[field] !== void 0) {
626
+ Object.assign(summary, { [field]: found[field] });
627
+ }
628
+ }
629
+ for (const field of [
507
630
  "totalAmount",
508
631
  "netAmount",
509
632
  "vatAmount",
510
633
  "exemptAmount",
511
634
  "nonTaxableAmount",
512
- "taxAmount",
635
+ "taxAmount"
636
+ ]) {
637
+ const minor2 = minorUnits(found[field]);
638
+ if (minor2 !== void 0) {
639
+ summary[field] = minor2;
640
+ }
641
+ }
642
+ for (const field of [
513
643
  "serviceStartDate",
514
644
  "serviceEndDate",
515
645
  "paymentDueDate",
516
- "result",
517
- "cae",
518
646
  "caeExpiry"
519
647
  ]) {
520
- if (found[field] !== void 0) {
521
- Object.assign(summary, { [field]: found[field] });
648
+ const iso2 = toIsoDate(found[field]);
649
+ if (iso2 !== void 0) {
650
+ summary[field] = iso2;
522
651
  }
523
652
  }
524
- if (found.voucherDate !== void 0) {
525
- summary.date = found.voucherDate;
653
+ const date = toIsoDate(found.voucherDate);
654
+ if (date !== void 0) {
655
+ summary.date = date;
526
656
  }
527
- if (found.vatRates !== void 0) {
528
- summary.vatRates = found.vatRates.map(({ id, baseAmount, amount }) => ({
529
- id,
530
- baseAmount,
531
- amount
532
- }));
657
+ const vatRates = found.vatRates?.map(({ id, baseAmount, amount }) => {
658
+ const base = minorUnits(baseAmount);
659
+ const minor2 = minorUnits(amount);
660
+ return base === void 0 || minor2 === void 0 ? void 0 : { id, baseAmount: base, amount: minor2 };
661
+ });
662
+ if (vatRates?.every((rate) => rate !== void 0)) {
663
+ summary.vatRates = vatRates;
533
664
  }
534
665
  return summary;
535
666
  }
667
+ function normalizeLegacySummary(found) {
668
+ const { number, date, ...rest } = found;
669
+ return toVoucherSummary({
670
+ ...rest,
671
+ voucherNumber: number,
672
+ ...date === void 0 ? {} : { voucherDate: date },
673
+ raw: {}
674
+ });
675
+ }
676
+ function minorUnits(value) {
677
+ if (value === void 0) {
678
+ return void 0;
679
+ }
680
+ try {
681
+ return Number(normalizeArcaAmountToMinorUnits(value, "amount"));
682
+ } catch {
683
+ return void 0;
684
+ }
685
+ }
536
686
  function compareAssociations(sent, found) {
537
687
  const expected = sent.associatedVouchers ?? [];
538
688
  const actual = found.associatedVouchers;
@@ -1873,7 +2023,7 @@ function wsmtxcaRequest(data, number) {
1873
2023
  (source) => source !== void 0
1874
2024
  ).length;
1875
2025
  if (!lines?.length || sources !== 1) {
1876
- invalid("items", "WSMTXCA requires items with line detail");
2026
+ invalid2("items", "WSMTXCA requires items with line detail");
1877
2027
  }
1878
2028
  const items = lines.map((line) => ({
1879
2029
  unidadesMtx: line.matrixUnits,
@@ -1900,7 +2050,7 @@ function wsmtxcaRequest(data, number) {
1900
2050
  }
1901
2051
  const tributes = data.taxes?.length ? data.taxes : void 0;
1902
2052
  if (tributes === void 0 && normalizeArcaAmountToMinorUnits(data.taxAmount, "taxes") !== 0n) {
1903
- invalid("taxes", "Tribute amount requires tribute details");
2053
+ invalid2("taxes", "Tribute amount requires tribute details");
1904
2054
  }
1905
2055
  return {
1906
2056
  comprobanteCAERequest: {
@@ -1970,7 +2120,7 @@ function wsmtxcaRequest(data, number) {
1970
2120
  }
1971
2121
  };
1972
2122
  }
1973
- function invalid(field, message) {
2123
+ function invalid2(field, message) {
1974
2124
  throw new ArcaInputError(message, {
1975
2125
  code: "ARCA_INPUT_INVALID_VALUE",
1976
2126
  field
@@ -2597,7 +2747,7 @@ function deriveWsfeInvoice(input, now = /* @__PURE__ */ new Date()) {
2597
2747
  );
2598
2748
  validateIssuanceFields(input);
2599
2749
  if (input.amounts !== void 0 && input.items !== void 0) {
2600
- invalid2("amounts", "used instead of items, never with items");
2750
+ invalid3("amounts", "used instead of items, never with items");
2601
2751
  }
2602
2752
  assertIssuerCondition(input.issuer);
2603
2753
  assertSalesPoint(input.salesPoint);
@@ -2679,7 +2829,7 @@ function reviewedInvoiceAmounts(amounts, taxes) {
2679
2829
  }
2680
2830
  function assertIssuerCondition(issuer) {
2681
2831
  if (typeof issuer !== "string" || !Object.hasOwn(ARCA_ISSUER_CONDITION_IDS, issuer)) {
2682
- invalid2(
2832
+ invalid3(
2683
2833
  "issuer",
2684
2834
  "responsable_inscripto, monotributo, exento, or no_alcanzado"
2685
2835
  );
@@ -2687,7 +2837,7 @@ function assertIssuerCondition(issuer) {
2687
2837
  }
2688
2838
  function assertSalesPoint(salesPoint) {
2689
2839
  if (!Number.isSafeInteger(salesPoint) || salesPoint < 1 || salesPoint > 99999) {
2690
- invalid2("salesPoint", "an integer from 1 through 99999");
2840
+ invalid3("salesPoint", "an integer from 1 through 99999");
2691
2841
  }
2692
2842
  }
2693
2843
  function resolveInvoiceClass(issuer, condition) {
@@ -2705,10 +2855,10 @@ function deriveReceiver(to) {
2705
2855
  );
2706
2856
  }
2707
2857
  if (typeof to.condition !== "string" || !Object.hasOwn(ARCA_RECEIVER_CONDITION_IDS, to.condition)) {
2708
- invalid2("to.condition", "one of the five supported receiver conditions");
2858
+ invalid3("to.condition", "one of the five supported receiver conditions");
2709
2859
  }
2710
2860
  if (to.cuit !== void 0 && to.dni !== void 0) {
2711
- invalid2("to", "either cuit or dni, never both");
2861
+ invalid3("to", "either cuit or dni, never both");
2712
2862
  }
2713
2863
  if (to.condition !== "consumidor_final" && to.cuit === void 0) {
2714
2864
  throw new ArcaInputError(
@@ -2730,11 +2880,11 @@ function deriveReceiver(to) {
2730
2880
  }
2731
2881
  function issueDocumentNumber(value, field, min, max) {
2732
2882
  if (typeof value !== "number" && typeof value !== "string") {
2733
- invalid2(field, `a positive document number with ${min} to ${max} digits`);
2883
+ invalid3(field, `a positive document number with ${min} to ${max} digits`);
2734
2884
  }
2735
2885
  const text = String(value);
2736
2886
  if (!/^\d+$/.test(text) || text.length < min || text.length > max || !Number.isSafeInteger(Number(text)) || Number(text) <= 0) {
2737
- invalid2(field, `a positive document number with ${min} to ${max} digits`);
2887
+ invalid3(field, `a positive document number with ${min} to ${max} digits`);
2738
2888
  }
2739
2889
  return Number(text);
2740
2890
  }
@@ -2743,10 +2893,10 @@ function deriveCurrency(input) {
2743
2893
  if (typeof currency === "object" && currency !== null) {
2744
2894
  assertIssueKeys(currency, ["id"], "currency");
2745
2895
  if (!/^[A-Z0-9]{3}$/.test(currency.id)) {
2746
- invalid2("currency.id", "a three-character ARCA currency code");
2896
+ invalid3("currency.id", "a three-character ARCA currency code");
2747
2897
  }
2748
2898
  if (input.exchangeRate === void 0) {
2749
- invalid2("exchangeRate", "an explicit rate for this currency");
2899
+ invalid3("exchangeRate", "an explicit rate for this currency");
2750
2900
  }
2751
2901
  return {
2752
2902
  currencyId: currency.id,
@@ -2757,10 +2907,10 @@ function deriveCurrency(input) {
2757
2907
  };
2758
2908
  }
2759
2909
  if (currency !== "ARS" && currency !== "USD") {
2760
- invalid2("currency", "ARS or USD");
2910
+ invalid3("currency", "ARS or USD");
2761
2911
  }
2762
2912
  if (input.exchangeRate !== void 0 && typeof input.exchangeRate !== "string") {
2763
- invalid2("exchangeRate", "a decimal string");
2913
+ invalid3("exchangeRate", "a decimal string");
2764
2914
  }
2765
2915
  if (currency === "USD" && input.exchangeRate === void 0) {
2766
2916
  throw new ArcaInputError("exchangeRate is required for USD.", {
@@ -2769,18 +2919,18 @@ function deriveCurrency(input) {
2769
2919
  expected: "a positive decimal string"
2770
2920
  });
2771
2921
  }
2772
- const exchangeRate = serializeArcaExchangeRate(
2922
+ const exchangeRate2 = serializeArcaExchangeRate(
2773
2923
  input.exchangeRate ?? "1",
2774
2924
  "exchangeRate"
2775
2925
  );
2776
- if (currency === "ARS" && exchangeRate !== "1") {
2926
+ if (currency === "ARS" && exchangeRate2 !== "1") {
2777
2927
  throw new ArcaInputError("exchangeRate must be 1 for ARS.", {
2778
2928
  code: "ARCA_INPUT_INVALID_EXCHANGE_RATE",
2779
2929
  field: "exchangeRate",
2780
2930
  expected: "1 for ARS"
2781
2931
  });
2782
2932
  }
2783
- return { currencyId: ARCA_CURRENCY_IDS[currency], exchangeRate };
2933
+ return { currencyId: ARCA_CURRENCY_IDS[currency], exchangeRate: exchangeRate2 };
2784
2934
  }
2785
2935
  function deriveService(service, date) {
2786
2936
  if (service === void 0) {
@@ -2810,10 +2960,10 @@ function deriveService(service, date) {
2810
2960
  "service.dueDate"
2811
2961
  );
2812
2962
  if (serviceEndDate < serviceStartDate) {
2813
- invalid2("service.to", "a date on or after service.from");
2963
+ invalid3("service.to", "a date on or after service.from");
2814
2964
  }
2815
2965
  if (paymentDueDate < date) {
2816
- invalid2("service.dueDate", "a date on or after date");
2966
+ invalid3("service.dueDate", "a date on or after date");
2817
2967
  }
2818
2968
  return { concept: 2, serviceStartDate, serviceEndDate, paymentDueDate };
2819
2969
  }
@@ -2828,7 +2978,7 @@ function buenosAiresDate(now) {
2828
2978
  }
2829
2979
  function assertIssueObject(value, field) {
2830
2980
  if (value === null || typeof value !== "object" || Array.isArray(value)) {
2831
- invalid2(field, "an object");
2981
+ invalid3(field, "an object");
2832
2982
  }
2833
2983
  }
2834
2984
  function assertIssueKeys(value, keys, prefix, method = "issue()") {
@@ -2843,28 +2993,41 @@ function assertIssueKeys(value, keys, prefix, method = "issue()") {
2843
2993
  }
2844
2994
  }
2845
2995
  }
2846
- function invalid2(field, expected) {
2996
+ function invalid3(field, expected) {
2847
2997
  throw new ArcaInputError(`${field} must be ${expected}.`, {
2848
2998
  code: "ARCA_INPUT_INVALID_VALUE",
2849
2999
  field,
2850
3000
  expected
2851
3001
  });
2852
3002
  }
3003
+ var NUMERIC_RECEIVER_CONDITIONS = [1, 4, 5, 6, 7, 8, 9, 10, 13, 15, 16];
3004
+ function receiverConditionId(condition, path) {
3005
+ if (typeof condition === "number") {
3006
+ if (!NUMERIC_RECEIVER_CONDITIONS.includes(condition)) {
3007
+ invalid3(path, "an ARCA receiver condition");
3008
+ }
3009
+ return condition;
3010
+ }
3011
+ if (typeof condition !== "string" || !Object.hasOwn(ARCA_RECEIVER_CONDITION_IDS, condition)) {
3012
+ invalid3(path, "one of the five supported receiver conditions");
3013
+ }
3014
+ return ARCA_RECEIVER_CONDITION_IDS[condition];
3015
+ }
2853
3016
  function deriveNumericReceiver(to) {
2854
- if (![1, 4, 5, 6, 7, 8, 9, 10, 13, 15, 16].includes(to.condition)) {
2855
- invalid2("to.condition", "an ARCA receiver condition");
3017
+ if (!NUMERIC_RECEIVER_CONDITIONS.includes(to.condition)) {
3018
+ invalid3("to.condition", "an ARCA receiver condition");
2856
3019
  }
2857
3020
  const document = "document" in to ? to.document : void 0;
2858
3021
  if (document) {
2859
3022
  assertIssueKeys(document, ["type", "number"], "to.document");
2860
3023
  if (to.cuit !== void 0 || to.dni !== void 0) {
2861
- invalid2("to", "one document identity");
3024
+ invalid3("to", "one document identity");
2862
3025
  }
2863
3026
  if (!Number.isInteger(document.type) || document.type < 0 || document.type > 99 || !/^\d{1,11}$/.test(String(document.number)) || !Number.isSafeInteger(Number(document.number))) {
2864
- invalid2("to.document", "a valid document type and number");
3027
+ invalid3("to.document", "a valid document type and number");
2865
3028
  }
2866
3029
  if (document.type === 80 && String(document.number).length !== 11) {
2867
- invalid2("to.document.number", "an 11-digit CUIT");
3030
+ invalid3("to.document.number", "an 11-digit CUIT");
2868
3031
  }
2869
3032
  return {
2870
3033
  documentType: document.type,
@@ -2873,10 +3036,10 @@ function deriveNumericReceiver(to) {
2873
3036
  };
2874
3037
  }
2875
3038
  if (to.cuit === void 0 && to.dni === void 0) {
2876
- invalid2("to", "an explicit document");
3039
+ invalid3("to", "an explicit document");
2877
3040
  }
2878
3041
  if (to.cuit !== void 0 && to.dni !== void 0) {
2879
- invalid2("to", "one document identity");
3042
+ invalid3("to", "one document identity");
2880
3043
  }
2881
3044
  return {
2882
3045
  documentType: to.cuit === void 0 ? 96 : 80,
@@ -2891,14 +3054,14 @@ function deriveNumericReceiver(to) {
2891
3054
  }
2892
3055
 
2893
3056
  // src/services/wsfe-credit-note.ts
2894
- function invalid3(reason) {
3057
+ function invalid4(reason) {
2895
3058
  throw new ArcaInputError(`issueCreditNote cannot proceed: ${reason}.`, {
2896
3059
  code: "ARCA_INPUT_INVALID_VALUE"
2897
3060
  });
2898
3061
  }
2899
3062
  function required(value, field) {
2900
3063
  if (value === void 0 || value === null) {
2901
- invalid3(`original is missing ${field}`);
3064
+ invalid4(`original is missing ${field}`);
2902
3065
  }
2903
3066
  return value;
2904
3067
  }
@@ -2927,7 +3090,7 @@ function deriveWsfeFullCreditNote(original, input, now = /* @__PURE__ */ new Dat
2927
3090
  }
2928
3091
  function deriveWsfePartialCreditNote(originals, input, now = /* @__PURE__ */ new Date(), kind = "creditNote") {
2929
3092
  if (input.items === void 0 && input.amounts === void 0) {
2930
- invalid3("items is required to credit chosen lines");
3093
+ invalid4("items is required to credit chosen lines");
2931
3094
  }
2932
3095
  const requestedTotal = input.total === void 0 ? void 0 : assertArcaMinorUnits(input.total, "total");
2933
3096
  const { note, header } = prepareCreditNote(originals, input, now, kind);
@@ -2949,7 +3112,7 @@ function deriveWsfePartialCreditNote(originals, input, now = /* @__PURE__ */ new
2949
3112
  );
2950
3113
  const ceiling = originals.length === 1 ? "the original" : "the sum of the originals";
2951
3114
  if (kind === "creditNote" && (requestedTotal ?? BigInt(amounts.sentTotal)) > originalTotal) {
2952
- invalid3(
3115
+ invalid4(
2953
3116
  `the note total is greater than ${ceiling}; the SDK does not track earlier notes against an original`
2954
3117
  );
2955
3118
  }
@@ -2973,7 +3136,7 @@ function deriveWsfePartialCreditNote(originals, input, now = /* @__PURE__ */ new
2973
3136
  );
2974
3137
  const sentTotal = input.amounts && requestedTotal !== void 0 ? Number(requestedTotal) : total;
2975
3138
  if (kind === "creditNote" && BigInt(sentTotal) > originalTotal) {
2976
- invalid3(`the note total is greater than ${ceiling}`);
3139
+ invalid4(`the note total is greater than ${ceiling}`);
2977
3140
  }
2978
3141
  data.totalAmount = minor(sentTotal, "total");
2979
3142
  amounts.computedTotal += total - amounts.sentTotal;
@@ -2992,7 +3155,7 @@ function prepareCreditNote(originals, input, now, kind) {
2992
3155
  );
2993
3156
  const [first, ...rest] = derived;
2994
3157
  if (first === void 0) {
2995
- invalid3("for must name at least one original");
3158
+ invalid4("for must name at least one original");
2996
3159
  }
2997
3160
  for (const other of rest) {
2998
3161
  assertInheritedHeader(first.header, other.header);
@@ -3015,24 +3178,42 @@ function assertInheritedHeader(first, other) {
3015
3178
  const left = first[field];
3016
3179
  const right = other[field];
3017
3180
  if (JSON.stringify(left) !== JSON.stringify(right)) {
3018
- invalid3(
3181
+ invalid4(
3019
3182
  `the originals disagree on ${field}, which the note inherits from them`
3020
3183
  );
3021
3184
  }
3022
3185
  }
3023
3186
  }
3187
+ function resolveReceiverCondition(original, input) {
3188
+ const supplied = input.to === void 0 ? void 0 : receiverConditionId(input.to.condition, "to.condition");
3189
+ const reported = original.receiverVatConditionId;
3190
+ if (reported === void 0) {
3191
+ if (supplied === void 0) {
3192
+ invalid4(
3193
+ "original is missing receiverVatConditionId; pass to.condition with the receiver's condition"
3194
+ );
3195
+ }
3196
+ return supplied;
3197
+ }
3198
+ if (supplied !== void 0 && supplied !== reported) {
3199
+ invalid4(
3200
+ `to.condition (${supplied}) does not match the original's receiver condition (${reported})`
3201
+ );
3202
+ }
3203
+ return reported;
3204
+ }
3024
3205
  function prepareOneCreditNote(original, input, now, kind) {
3025
3206
  assertOriginalExtensions(original);
3026
3207
  const family = voucherFamily(original.voucherType ?? 0);
3027
3208
  if (family.types[2] === original.voucherType) {
3028
- invalid3("original must be an invoice or debit note");
3209
+ invalid4("original must be an invoice or debit note");
3029
3210
  }
3030
3211
  const note = {
3031
3212
  voucherClass: family.voucherClass,
3032
3213
  voucherType: family.types[kind === "creditNote" ? 2 : 1]
3033
3214
  };
3034
3215
  if (!(["A", "O"].includes(original.result ?? "") && original.cae?.trim() && original.caeExpiry?.trim())) {
3035
- invalid3("original is not authorized");
3216
+ invalid4("original is not authorized");
3036
3217
  }
3037
3218
  const voucherDate = normalizeWsfeDateInput(
3038
3219
  input.date ?? buenosAiresDate(now),
@@ -3043,7 +3224,7 @@ function prepareOneCreditNote(original, input, now, kind) {
3043
3224
  "original.voucherDate"
3044
3225
  );
3045
3226
  if (originalDate > voucherDate && originalDate.slice(0, 6) !== voucherDate.slice(0, 6)) {
3046
- invalid3(
3227
+ invalid4(
3047
3228
  "original date is later than the note and outside its month (10210)"
3048
3229
  );
3049
3230
  }
@@ -3053,10 +3234,7 @@ function prepareOneCreditNote(original, input, now, kind) {
3053
3234
  concept: required(original.concept, "concept"),
3054
3235
  documentType: required(original.documentType, "documentType"),
3055
3236
  documentNumber: Number(required(original.documentNumber, "documentNumber")),
3056
- receiverVatConditionId: required(
3057
- original.receiverVatConditionId,
3058
- "receiverVatConditionId"
3059
- ),
3237
+ receiverVatConditionId: resolveReceiverCondition(original, input),
3060
3238
  currencyId: required(original.currencyId, "currencyId"),
3061
3239
  ...original.sameCurrencyForeignCancellation === void 0 ? {} : {
3062
3240
  sameCurrencyForeignCancellation: original.sameCurrencyForeignCancellation
@@ -3101,6 +3279,7 @@ var CREDIT_NOTE_KEYS = [
3101
3279
  "for",
3102
3280
  "salesPoint",
3103
3281
  "date",
3282
+ "to",
3104
3283
  "items",
3105
3284
  "total",
3106
3285
  "all",
@@ -3114,6 +3293,18 @@ var TARGET_BOUNDS = [
3114
3293
  ["voucherType", 999],
3115
3294
  ["number", 99999999]
3116
3295
  ];
3296
+ function assertNoteReceiver(to) {
3297
+ if (to === void 0) {
3298
+ return;
3299
+ }
3300
+ assertIssueObject(to, "to");
3301
+ assertIssueKeys(to, ["condition"], "to", "issueCreditNote()");
3302
+ try {
3303
+ receiverConditionId(to.condition, "to.condition");
3304
+ } catch {
3305
+ invalid4("to.condition must be a supported receiver condition");
3306
+ }
3307
+ }
3117
3308
  function assertCreditNoteInput(input) {
3118
3309
  assertIssueObject(input, "input");
3119
3310
  validateIssuanceFields(input);
@@ -3133,16 +3324,18 @@ function assertCreditNoteInput(input) {
3133
3324
  assertCreditNoteBound(input.salesPoint, 99999, "salesPoint");
3134
3325
  }
3135
3326
  const date = input.date === void 0 ? void 0 : normalizeWsfeDateInput(input.date, "date");
3327
+ assertNoteReceiver(input.to);
3136
3328
  const common = {
3137
3329
  ...input.fce === void 0 ? {} : { fce: structuredClone(input.fce) },
3138
3330
  ...input.taxes === void 0 ? {} : { taxes: structuredClone(input.taxes) },
3139
3331
  ...input.optionalFields === void 0 ? {} : { optionalFields: structuredClone(input.optionalFields) },
3140
3332
  for: target,
3141
3333
  ...input.salesPoint === void 0 ? {} : { salesPoint: input.salesPoint },
3142
- ...date === void 0 ? {} : { date }
3334
+ ...date === void 0 ? {} : { date },
3335
+ ...input.to === void 0 ? {} : { to: { condition: input.to.condition } }
3143
3336
  };
3144
3337
  if (input.items !== void 0 && input.amounts !== void 0) {
3145
- invalid3("use items or amounts, never both");
3338
+ invalid4("use items or amounts, never both");
3146
3339
  }
3147
3340
  if ((input.items === void 0 && input.amounts === void 0) === (input.all === void 0)) {
3148
3341
  throw new ArcaInputError(
@@ -3279,7 +3472,7 @@ function assertOriginalExtensions(original) {
3279
3472
  ["associatedPeriod", "PeriodoAsoc"]
3280
3473
  ]) {
3281
3474
  if (original.raw[rawField] && original[field] === void 0) {
3282
- invalid3(`original ${field} could not be decoded`);
3475
+ invalid4(`original ${field} could not be decoded`);
3283
3476
  }
3284
3477
  }
3285
3478
  try {
@@ -3310,7 +3503,7 @@ function assertOriginalExtensions(original) {
3310
3503
  );
3311
3504
  }
3312
3505
  } catch {
3313
- invalid3("original extension fields are incomplete or malformed");
3506
+ invalid4("original extension fields are incomplete or malformed");
3314
3507
  }
3315
3508
  }
3316
3509
  function assertFullMode(input) {
@@ -3490,8 +3683,9 @@ async function issueInvoice(wsfe, input, inputOptions, context, select) {
3490
3683
  );
3491
3684
  }
3492
3685
  async function runOperation(wsfe, operation, input, prepare, options, context, replayAmounts, select) {
3686
+ const issuer = issuerTaxId(options, context);
3493
3687
  if (options.idempotencyKey === void 0 || !context?.store) {
3494
- return runAuthorization(wsfe, await prepare(), options);
3688
+ return runAuthorization(wsfe, await prepare(), options, issuer);
3495
3689
  }
3496
3690
  const store = context.store;
3497
3691
  const { environment, taxId } = context;
@@ -3587,7 +3781,7 @@ async function runOperation(wsfe, operation, input, prepare, options, context, r
3587
3781
  }
3588
3782
  if (await storeCall(() => store.add(key, JSON.stringify(record)))) {
3589
3783
  const outcome = await settle2(
3590
- runAuthorization(wsfe, prepared, options, number)
3784
+ runAuthorization(wsfe, prepared, options, issuer, number)
3591
3785
  );
3592
3786
  if (coordinated && outcome.kind !== "indeterminate") {
3593
3787
  await storeCall(
@@ -3626,6 +3820,7 @@ async function runOperation(wsfe, operation, input, prepare, options, context, r
3626
3820
  stored,
3627
3821
  readSettledRecord(recorded),
3628
3822
  options,
3823
+ taxId,
3629
3824
  (other) => storeCall(() => store.get(settledKey(environment, taxId, other)))
3630
3825
  );
3631
3826
  }
@@ -3637,6 +3832,7 @@ async function runOperation(wsfe, operation, input, prepare, options, context, r
3637
3832
  ...replayAmounts ? { amounts: replayAmounts } : {}
3638
3833
  },
3639
3834
  options,
3835
+ issuer,
3640
3836
  stored.number,
3641
3837
  true
3642
3838
  )
@@ -3664,7 +3860,7 @@ async function recordConflict(store, key, outcome) {
3664
3860
  return outcome;
3665
3861
  }
3666
3862
  const record = {
3667
- v: 1,
3863
+ v: 2,
3668
3864
  kind: "conflict",
3669
3865
  number: outcome.attempted.number,
3670
3866
  found: Object.fromEntries(
@@ -3678,9 +3874,12 @@ async function recordConflict(store, key, outcome) {
3678
3874
  function readSettledRecord(json) {
3679
3875
  try {
3680
3876
  const record = JSON.parse(json);
3681
- if (!record || record.v !== 1 || !Number.isSafeInteger(record.number) || (record.kind === "conflict" ? !record.found || typeof record.found !== "object" : record.kind !== "superseded" || typeof record.by !== "string")) {
3877
+ if (record?.v !== 1 && record?.v !== 2 || !Number.isSafeInteger(record.number) || (record.kind === "conflict" ? !record.found || typeof record.found !== "object" : record.kind !== "superseded" || typeof record.by !== "string")) {
3682
3878
  throw new Error("Invalid settled structure");
3683
3879
  }
3880
+ if (record.kind === "conflict" && record.v === 1) {
3881
+ return { ...record, v: 2, found: normalizeLegacySummary(record.found) };
3882
+ }
3684
3883
  return record;
3685
3884
  } catch (cause) {
3686
3885
  throw new ArcaConfigurationError(
@@ -3689,11 +3888,17 @@ function readSettledRecord(json) {
3689
3888
  );
3690
3889
  }
3691
3890
  }
3692
- async function settledOutcome(select, reservation, settled, options, settledFor) {
3891
+ async function settledOutcome(select, reservation, settled, options, taxId, settledFor) {
3693
3892
  if (settled.kind === "conflict") {
3694
3893
  return settledConflict(settled, reservation, options);
3695
3894
  }
3696
- const outcome = await consultReservation(select, reservation, options, true);
3895
+ const outcome = await consultReservation(
3896
+ select,
3897
+ reservation,
3898
+ options,
3899
+ taxId,
3900
+ true
3901
+ );
3697
3902
  const empty = outcome.kind === "indeterminate" && outcome.lookup.kind === "not_found";
3698
3903
  if (!empty && (outcome.kind !== "conflict" || await successionDisputed(settled.by, settledFor))) {
3699
3904
  return outcome;
@@ -3816,7 +4021,7 @@ async function nextNumber(wsfe, data, options) {
3816
4021
  }
3817
4022
  return number;
3818
4023
  }
3819
- async function runAuthorization(wsfe, { data, voucherClass, amounts }, options, reservedNumber, replay = false) {
4024
+ async function runAuthorization(wsfe, { data, voucherClass, amounts }, options, taxId, reservedNumber, replay = false) {
3820
4025
  const auth = {
3821
4026
  representedTaxId: options.representedTaxId,
3822
4027
  forceRefresh: options.forceRefresh,
@@ -3830,14 +4035,11 @@ async function runAuthorization(wsfe, { data, voucherClass, amounts }, options,
3830
4035
  number
3831
4036
  };
3832
4037
  const includedRequest = requestEvidence(data, number, options);
3833
- const voucher = (cae, caeExpiry) => ({
3834
- ...attempted,
3835
- voucherClass,
3836
- date: data.voucherDate,
4038
+ const voucher = (cae, caeExpiry) => issuedVoucher(
4039
+ { attempted, voucherClass, data, amounts, taxId },
3837
4040
  cae,
3838
- caeExpiry,
3839
- amounts
3840
- });
4041
+ caeExpiry
4042
+ );
3841
4043
  const recovery = {
3842
4044
  wsfe,
3843
4045
  auth,
@@ -3866,11 +4068,19 @@ async function runAuthorization(wsfe, { data, voucherClass, amounts }, options,
3866
4068
  return recoverInvoice({ ...recovery, attempt: attempt2, lookup });
3867
4069
  }
3868
4070
  }
3869
- const authorization = await wsfe.issue({
4071
+ let authorization = await wsfe.issue({
3870
4072
  ...auth,
3871
4073
  data,
3872
4074
  voucherNumber: number
3873
4075
  });
4076
+ if (authorization.kind === "indeterminate" && authorization.reason === "authentication_rejected" && auth.forceRefresh !== true) {
4077
+ authorization = await wsfe.issue({
4078
+ ...auth,
4079
+ forceRefresh: true,
4080
+ data,
4081
+ voucherNumber: number
4082
+ });
4083
+ }
3874
4084
  if (authorization.kind === "authorized" && authorization.caeExpiry && authorization.voucherNumber === number) {
3875
4085
  return {
3876
4086
  kind: "authorized",
@@ -4371,6 +4581,7 @@ async function recoverOperation(select, key, inputOptions, context) {
4371
4581
  record,
4372
4582
  readSettledRecord(recorded),
4373
4583
  options,
4584
+ context.taxId,
4374
4585
  (other) => storeCall(
4375
4586
  () => store.get(
4376
4587
  settledKey(
@@ -4385,10 +4596,15 @@ async function recoverOperation(select, key, inputOptions, context) {
4385
4596
  return await recordConflict(
4386
4597
  store,
4387
4598
  settled,
4388
- await consultReservation(select, record, options)
4599
+ await consultReservation(
4600
+ select,
4601
+ record,
4602
+ options,
4603
+ context.taxId
4604
+ )
4389
4605
  );
4390
4606
  }
4391
- function consultReservation(select, record, options, strangerAtNumber = false) {
4607
+ function consultReservation(select, record, options, taxId, strangerAtNumber = false) {
4392
4608
  const storedOptions = {
4393
4609
  ...options,
4394
4610
  service: record.service ?? "wsfe",
@@ -4414,16 +4630,68 @@ function consultReservation(select, record, options, strangerAtNumber = false) {
4414
4630
  record.number,
4415
4631
  storedOptions
4416
4632
  ),
4417
- voucher: (cae, caeExpiry) => ({
4418
- ...attempted,
4419
- voucherClass: prepared.voucherClass,
4420
- date: prepared.data.voucherDate,
4421
- amounts: prepared.amounts,
4633
+ voucher: (cae, caeExpiry) => issuedVoucher(
4634
+ {
4635
+ attempted,
4636
+ voucherClass: prepared.voucherClass,
4637
+ data: prepared.data,
4638
+ amounts: prepared.amounts,
4639
+ taxId: record.representedTaxId ?? taxId
4640
+ },
4422
4641
  cae,
4423
4642
  caeExpiry
4424
- })
4643
+ )
4425
4644
  });
4426
4645
  }
4646
+ function issuerTaxId(options, context) {
4647
+ return options.representedTaxId === void 0 ? context?.taxId : String(options.representedTaxId);
4648
+ }
4649
+ function issuedVoucher({
4650
+ attempted,
4651
+ voucherClass,
4652
+ data,
4653
+ amounts,
4654
+ taxId
4655
+ }, cae, caeExpiry) {
4656
+ const date = toIsoDate(data.voucherDate) ?? data.voucherDate;
4657
+ const qr = voucherQr({ attempted, data, taxId, date, cae });
4658
+ return {
4659
+ ...attempted,
4660
+ voucherClass,
4661
+ date,
4662
+ cae,
4663
+ caeExpiry: toIsoDate(caeExpiry) ?? caeExpiry,
4664
+ amounts,
4665
+ ...qr === void 0 ? {} : { qr }
4666
+ };
4667
+ }
4668
+ function voucherQr({
4669
+ attempted,
4670
+ data,
4671
+ taxId,
4672
+ date,
4673
+ cae
4674
+ }) {
4675
+ if (taxId === void 0) {
4676
+ return void 0;
4677
+ }
4678
+ try {
4679
+ return arcaQrUrl({
4680
+ taxId,
4681
+ ...attempted,
4682
+ date,
4683
+ total: Number(
4684
+ normalizeArcaAmountToMinorUnits(data.totalAmount, "totalAmount")
4685
+ ),
4686
+ currency: data.currencyId,
4687
+ ...data.exchangeRate === void 0 ? {} : { exchangeRate: data.exchangeRate },
4688
+ cae,
4689
+ document: { type: data.documentType, number: data.documentNumber }
4690
+ });
4691
+ } catch {
4692
+ return void 0;
4693
+ }
4694
+ }
4427
4695
  async function runSequenceBarrier({
4428
4696
  store,
4429
4697
  environment,
@@ -4465,10 +4733,15 @@ async function runSequenceBarrier({
4465
4733
  const outcome = await recordConflict(
4466
4734
  store,
4467
4735
  settled,
4468
- await consultReservation(select, record, {
4469
- forceRefresh: options.forceRefresh,
4470
- ...options.abortSignal === void 0 ? {} : { abortSignal: options.abortSignal }
4471
- })
4736
+ await consultReservation(
4737
+ select,
4738
+ record,
4739
+ {
4740
+ forceRefresh: options.forceRefresh,
4741
+ ...options.abortSignal === void 0 ? {} : { abortSignal: options.abortSignal }
4742
+ },
4743
+ taxId
4744
+ )
4472
4745
  );
4473
4746
  if (outcome.kind === "authorized" || outcome.kind === "conflict") {
4474
4747
  return {};
@@ -4497,7 +4770,7 @@ async function runSequenceBarrier({
4497
4770
  function readSequenceRecord(json) {
4498
4771
  try {
4499
4772
  const record = JSON.parse(json);
4500
- if (!record || record.v !== 1 || typeof record.key !== "string" || !Number.isSafeInteger(record.number)) {
4773
+ if (record?.v !== 1 || typeof record.key !== "string" || !Number.isSafeInteger(record.number)) {
4501
4774
  throw new Error("Invalid sequence structure");
4502
4775
  }
4503
4776
  return record;
@@ -4597,28 +4870,107 @@ function createSoapTransport(options) {
4597
4870
  }
4598
4871
 
4599
4872
  // src/wsaa/store-adapter.ts
4600
- function createWsaaStoreAdapter(store) {
4601
- const key = (value) => `arca:v1:wsaa:${serializeWsaaSessionKey(value)}`;
4873
+ import {
4874
+ createCipheriv,
4875
+ createDecipheriv,
4876
+ hkdfSync,
4877
+ randomBytes
4878
+ } from "crypto";
4879
+ var KEY_PREFIX = "arca:v2:wsaa:";
4880
+ var LEGACY_KEY_PREFIX = "arca:v1:wsaa:";
4881
+ var HKDF_SALT = "facturas:wsaa:v2";
4882
+ var RECORD_VERSION = 2;
4883
+ function createWsaaStoreAdapter(store, secret) {
4884
+ const key = (value) => `${KEY_PREFIX}${serializeWsaaSessionKey(value)}`;
4885
+ const legacyKey = (value) => `${LEGACY_KEY_PREFIX}${serializeWsaaSessionKey(value)}`;
4602
4886
  const remove = store.delete?.bind(store);
4603
4887
  const lock = store.withLock?.bind(store);
4888
+ const write = (value, credentials) => store.set(
4889
+ key(value),
4890
+ seal(JSON.stringify(credentials), cipherKey(secret, value))
4891
+ );
4604
4892
  return {
4605
4893
  get: (value) => storeCall(async () => {
4606
4894
  const json = await store.get(key(value));
4607
- if (json === null) {
4608
- return null;
4895
+ const sealed = json === null ? null : usable(open(json, cipherKey(secret, value)));
4896
+ if (sealed) {
4897
+ return sealed;
4609
4898
  }
4610
- const credentials = JSON.parse(json);
4611
- return credentials && typeof credentials.token === "string" && typeof credentials.sign === "string" && isWsaaCredentialValid(credentials) ? credentials : null;
4899
+ const legacy = usable(parseClear(await store.get(legacyKey(value))));
4900
+ if (legacy) {
4901
+ await write(value, legacy);
4902
+ }
4903
+ return legacy;
4612
4904
  }),
4613
- set: (value, credentials) => storeCall(() => store.set(key(value), JSON.stringify(credentials))),
4905
+ set: (value, credentials) => storeCall(() => write(value, credentials)),
4614
4906
  ...remove ? {
4615
4907
  delete: (value) => storeCall(() => remove(key(value)))
4616
4908
  } : {},
4617
4909
  ...lock ? {
4618
- withLock: (value, fn) => lock(key(value), fn)
4910
+ withLock: (value, fn) => lock(legacyKey(value), fn)
4619
4911
  } : {}
4620
4912
  };
4621
4913
  }
4914
+ function usable(credentials) {
4915
+ return credentials && typeof credentials.token === "string" && typeof credentials.sign === "string" && isWsaaCredentialValid(credentials) ? credentials : null;
4916
+ }
4917
+ function parseClear(json) {
4918
+ if (json === null) {
4919
+ return null;
4920
+ }
4921
+ try {
4922
+ return JSON.parse(json);
4923
+ } catch {
4924
+ return null;
4925
+ }
4926
+ }
4927
+ function cipherKey(secret, value) {
4928
+ return Buffer.from(
4929
+ hkdfSync(
4930
+ "sha256",
4931
+ secret.privateKeyPem,
4932
+ HKDF_SALT,
4933
+ serializeWsaaSessionKey(value),
4934
+ 32
4935
+ )
4936
+ );
4937
+ }
4938
+ function seal(plaintext, cipherKey2) {
4939
+ const iv = randomBytes(12);
4940
+ const cipher = createCipheriv("aes-256-gcm", cipherKey2, iv);
4941
+ const data = Buffer.concat([
4942
+ cipher.update(plaintext, "utf8"),
4943
+ cipher.final()
4944
+ ]);
4945
+ const record = {
4946
+ v: RECORD_VERSION,
4947
+ iv: iv.toString("base64url"),
4948
+ data: data.toString("base64url"),
4949
+ tag: cipher.getAuthTag().toString("base64url")
4950
+ };
4951
+ return JSON.stringify(record);
4952
+ }
4953
+ function open(json, cipherKey2) {
4954
+ try {
4955
+ const record = JSON.parse(json);
4956
+ if (!record || record.v !== RECORD_VERSION || typeof record.iv !== "string" || typeof record.data !== "string" || typeof record.tag !== "string") {
4957
+ return null;
4958
+ }
4959
+ const decipher = createDecipheriv(
4960
+ "aes-256-gcm",
4961
+ cipherKey2,
4962
+ Buffer.from(record.iv, "base64url")
4963
+ );
4964
+ decipher.setAuthTag(Buffer.from(record.tag, "base64url"));
4965
+ const plaintext = Buffer.concat([
4966
+ decipher.update(Buffer.from(record.data, "base64url")),
4967
+ decipher.final()
4968
+ ]).toString("utf8");
4969
+ return JSON.parse(plaintext);
4970
+ } catch {
4971
+ return null;
4972
+ }
4973
+ }
4622
4974
 
4623
4975
  // src/client.ts
4624
4976
  function createArcaClient(config = {}) {
@@ -4627,7 +4979,8 @@ function createArcaClient(config = {}) {
4627
4979
  const normalizedConfig = normalizeArcaClientConfig(discovered);
4628
4980
  if (normalizedConfig.store && !normalizedConfig.wsaaSessionStore) {
4629
4981
  normalizedConfig.wsaaSessionStore = createWsaaStoreAdapter(
4630
- normalizedConfig.store
4982
+ normalizedConfig.store,
4983
+ normalizedConfig
4631
4984
  );
4632
4985
  }
4633
4986
  const logger = createArcaLogger(normalizedConfig.logger);
@@ -4667,7 +5020,7 @@ import { createHash as createHash3, randomUUID as randomUUID2 } from "crypto";
4667
5020
  import {
4668
5021
  link,
4669
5022
  mkdir,
4670
- open,
5023
+ open as open2,
4671
5024
  readFile,
4672
5025
  rename,
4673
5026
  rmdir,
@@ -4840,7 +5193,7 @@ async function readHolder(holder) {
4840
5193
  async function renewHolder(holder, owner, value) {
4841
5194
  let file;
4842
5195
  try {
4843
- file = await open(holder, "r+");
5196
+ file = await open2(holder, "r+");
4844
5197
  } catch (error) {
4845
5198
  if (error.code === "ENOENT") {
4846
5199
  return;
@@ -4934,6 +5287,9 @@ export {
4934
5287
  ARCA_WSAA_CONFIG,
4935
5288
  discoverArcaClientConfig,
4936
5289
  storeCall,
5290
+ ARCA_QR_URL,
5291
+ arcaQrUrl,
5292
+ arcaQrPayload,
4937
5293
  matchWsfeVoucherIdentity,
4938
5294
  createMemoryWsaaSessionStore,
4939
5295
  createWsaaAuthModule,
@@ -4943,4 +5299,4 @@ export {
4943
5299
  withLease,
4944
5300
  createFileStore
4945
5301
  };
4946
- //# sourceMappingURL=chunk-KPWAQMR5.mjs.map
5302
+ //# sourceMappingURL=chunk-6XQTT3GH.mjs.map