@sinete/nfe 0.1.0 → 0.3.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.
Files changed (90) hide show
  1. package/README.md +55 -50
  2. package/dist/build/build.d.ts +23 -23
  3. package/dist/build/build.d.ts.map +1 -1
  4. package/dist/build/destinatario.d.ts +2 -2
  5. package/dist/build/ibscbs.d.ts.map +1 -1
  6. package/dist/build/nfce.d.ts +5 -5
  7. package/dist/build/nfce.d.ts.map +1 -1
  8. package/dist/build/pl.d.ts +4 -4
  9. package/dist/build/pl.d.ts.map +1 -1
  10. package/dist/build/rejeicoes.d.ts +7 -7
  11. package/dist/build/rejeicoes.d.ts.map +1 -1
  12. package/dist/build/textos.d.ts +26 -0
  13. package/dist/build/textos.d.ts.map +1 -0
  14. package/dist/build/values.d.ts +8 -8
  15. package/dist/build/values.d.ts.map +1 -1
  16. package/dist/decimal.d.ts +2 -2
  17. package/dist/decimal.d.ts.map +1 -1
  18. package/dist/format.d.ts +19 -19
  19. package/dist/format.d.ts.map +1 -1
  20. package/dist/ibs-cbs.d.ts +10 -5
  21. package/dist/ibs-cbs.d.ts.map +1 -1
  22. package/dist/ibs-cbs.js +35 -35
  23. package/dist/ibs-cbs.js.map +3 -3
  24. package/dist/index.d.ts +18 -18
  25. package/dist/index.d.ts.map +1 -1
  26. package/dist/index.js +796 -588
  27. package/dist/index.js.map +27 -26
  28. package/dist/issues.d.ts +10 -10
  29. package/dist/issues.d.ts.map +1 -1
  30. package/dist/model.d.ts +4 -4
  31. package/dist/ports.d.ts +15 -15
  32. package/dist/ports.d.ts.map +1 -1
  33. package/dist/rotulo.d.ts +2 -2
  34. package/dist/rotulo.d.ts.map +1 -1
  35. package/dist/rtc.d.ts +23 -23
  36. package/dist/rtc.d.ts.map +1 -1
  37. package/dist/services/client.d.ts +44 -40
  38. package/dist/services/client.d.ts.map +1 -1
  39. package/dist/services/gzip.d.ts +1 -1
  40. package/dist/services/gzip.d.ts.map +1 -1
  41. package/dist/services/index.d.ts +4 -4
  42. package/dist/services/index.d.ts.map +1 -1
  43. package/dist/services/outcome.d.ts +3 -3
  44. package/dist/services/outcome.d.ts.map +1 -1
  45. package/dist/services/proc.d.ts +6 -6
  46. package/dist/services/proc.d.ts.map +1 -1
  47. package/dist/services/recuperar.d.ts +8 -7
  48. package/dist/services/recuperar.d.ts.map +1 -1
  49. package/dist/services/resolver.d.ts +12 -11
  50. package/dist/services/resolver.d.ts.map +1 -1
  51. package/dist/services/soap.d.ts +8 -8
  52. package/dist/services/soap.d.ts.map +1 -1
  53. package/dist/time.d.ts +4 -4
  54. package/dist/time.d.ts.map +1 -1
  55. package/dist/versao-gerada.d.ts +1 -1
  56. package/package.json +9 -9
  57. package/src/build/build.ts +213 -203
  58. package/src/build/destinatario.ts +8 -8
  59. package/src/build/ibscbs.ts +10 -6
  60. package/src/build/icms.ts +6 -6
  61. package/src/build/nfce.ts +19 -19
  62. package/src/build/pl.ts +12 -12
  63. package/src/build/rejeicoes.ts +13 -13
  64. package/src/build/textos.ts +228 -0
  65. package/src/build/values.ts +14 -14
  66. package/src/data/arredondamento.json +1 -1
  67. package/src/data/cstat.json +6 -6
  68. package/src/data/fusos.json +1 -1
  69. package/src/data/nfce-urls.json +2 -2
  70. package/src/data/produtor-rural.json +1 -1
  71. package/src/data/resp-tec.json +1 -1
  72. package/src/decimal.ts +10 -9
  73. package/src/format.ts +29 -28
  74. package/src/ibs-cbs.ts +79 -74
  75. package/src/index.ts +29 -27
  76. package/src/issues.ts +11 -11
  77. package/src/model.ts +4 -4
  78. package/src/ports.ts +15 -15
  79. package/src/rotulo.ts +4 -4
  80. package/src/rtc.ts +91 -91
  81. package/src/services/client.ts +248 -217
  82. package/src/services/gzip.ts +7 -7
  83. package/src/services/index.ts +12 -10
  84. package/src/services/outcome.ts +9 -9
  85. package/src/services/proc.ts +50 -49
  86. package/src/services/recuperar.ts +29 -25
  87. package/src/services/resolver.ts +25 -23
  88. package/src/services/soap.ts +35 -35
  89. package/src/time.ts +6 -6
  90. package/src/versao-gerada.ts +1 -1
package/dist/index.js CHANGED
@@ -1,12 +1,20 @@
1
1
  // packages/nfe/src/build/build.ts
2
- import { ConfigError as ConfigError2, fixedClock as fixedClock2, formatarVerProc, isUf as isUf2, tpAmbOf as tpAmbOf2, ufBySigla as ufBySigla2, ValidationError } from "@sinete/core";
3
- import { base64Encode as base64Encode2, firstChild as firstChild3, parseXml as parseXml3, signXml } from "@sinete/core/xml";
4
- import { SerializeError, serialize as serialize2, validate as validate3 } from "@sinete/schemas";
2
+ import {
3
+ ErroDeConfiguracao as ErroDeConfiguracao2,
4
+ ErroDeValidacao,
5
+ ehUf as ehUf2,
6
+ formatarVerProc,
7
+ relogioFixo as relogioFixo2,
8
+ tpAmbDoAmbiente as tpAmbDoAmbiente2,
9
+ ufPorSigla as ufPorSigla2
10
+ } from "@sinete/core";
11
+ import { assinarXml, codificarBase64 as codificarBase642, lerXml as lerXml3, primeiroFilho as primeiroFilho3 } from "@sinete/core/xml";
12
+ import { ErroSerializacao, serializar as serializar2, validar as validar3 } from "@sinete/schemas";
5
13
  import { TIS as TISCt, TNFe_infNFeSupl, TTribNFe as TTribNFeCt } from "@sinete/schemas/nfe/PL_010f";
6
- import { buildChaveAcesso, parseChaveAcesso, parseCnpj as parseCnpj3, parseCpf, parseIe } from "@sinete/validators";
14
+ import { lerChaveAcesso, lerCnpj as lerCnpj3, lerCpf, lerIe, montarChaveAcesso } from "@sinete/validators";
7
15
  // packages/nfe/src/data/arredondamento.json
8
16
  var arredondamento_default = {
9
- descricao: "Modo de arredondamento dos valores calculados pelo builder, por família de campo. HALF_UP é o arredondamento comercial; HALF_EVEN é o bancário (NBR 5891). Quem emite pode sobrepor por família em BuildNfeOptions.arredondamento.",
17
+ descricao: "Modo de arredondamento dos valores calculados pelo builder, por família de campo. HALF_UP é o arredondamento comercial; HALF_EVEN é o bancário (NBR 5891). Quem emite pode sobrepor por família em MontarNfeOpcoes.arredondamento.",
10
18
  atualizadoEm: "2026-09-26",
11
19
  familias: {
12
20
  produto: {
@@ -37,7 +45,7 @@ var arredondamento_default = {
37
45
  };
38
46
  // packages/nfe/src/data/produtor-rural.json
39
47
  var produtor_rural_default = {
40
- descricao: "Regras do produtor rural que variam no tempo ou por UF. refNFP: a nota fiscal de produtor em papel (modelo 04) foi extinta; uma NF-e ainda pode referenciar uma nota modelo 04 emitida antes do fim da vigência na UF da nota referenciada. vedadaDesde é o primeiro AAMM em que a UF não aceita mais nota modelo 04 emitida; a referência a nota com AAMM igual ou posterior é recusada pelo builder. series: faixas de série por tipo de emitente na emissão pelo contribuinte (procEmi 0, a única que o buildNfe monta).",
48
+ descricao: "Regras do produtor rural que variam no tempo ou por UF. refNFP: a nota fiscal de produtor em papel (modelo 04) foi extinta; uma NF-e ainda pode referenciar uma nota modelo 04 emitida antes do fim da vigência na UF da nota referenciada. vedadaDesde é o primeiro AAMM em que a UF não aceita mais nota modelo 04 emitida; a referência a nota com AAMM igual ou posterior é recusada pelo builder. series: faixas de série por tipo de emitente na emissão pelo contribuinte (procEmi 0, a única que o montarNfe monta).",
41
49
  atualizadoEm: "2026-09-28",
42
50
  refNFP: {
43
51
  modelo04: {
@@ -62,7 +70,7 @@ var reforma_default = {
62
70
  };
63
71
  // packages/nfe/src/data/resp-tec.json
64
72
  var resp_tec_default = {
65
- descricao: "Exigência do grupo infRespTec e do CSRT por UF do emitente, com vigência por ambiente. infRespTec: 'obrigatorio' faz o builder recusar a nota sem responsável técnico; 'opcional' só o inclui quando informado. csrt: 'obrigatorio' exige idCSRT e hashCSRT (rejeição 975). Datas no formato AAAA-MM-DD, a partir de 00:00 de Brasília. UF ausente usa o padrão. A adesão é de cada UF (NT 2018.005); quem emite pode sobrepor em BuildNfeOptions.",
73
+ descricao: "Exigência do grupo infRespTec e do CSRT por UF do emitente, com vigência por ambiente. infRespTec: 'obrigatorio' faz o builder recusar a nota sem responsável técnico; 'opcional' só o inclui quando informado. csrt: 'obrigatorio' exige idCSRT e hashCSRT (rejeição 975). Datas no formato AAAA-MM-DD, a partir de 00:00 de Brasília. UF ausente usa o padrão. A adesão é de cada UF (NT 2018.005); quem emite pode sobrepor em MontarNfeOpcoes.",
66
74
  atualizadoEm: "2026-09-26",
67
75
  fonte: "NT 2018.005 v1.50 (responsável técnico e CSRT, adesão a critério da UF)",
68
76
  padrao: { infRespTec: "opcional", csrt: "opcional" },
@@ -76,7 +84,7 @@ var resp_tec_default = {
76
84
  };
77
85
 
78
86
  // packages/nfe/src/decimal.ts
79
- import { ConfigError } from "@sinete/core";
87
+ import { ErroDeConfiguracao } from "@sinete/core";
80
88
  var DECIMAL_TEXT = /^([+-])?(\d+)(?:\.(\d*))?(?:[eE]([+-]?\d+))?$|^([+-])?\.(\d+)(?:[eE]([+-]?\d+))?$/;
81
89
  var MAX_SCALE = 64;
82
90
  function pow10(n) {
@@ -95,13 +103,13 @@ class Decimal {
95
103
  static HUNDRED = new Decimal(100n, 0);
96
104
  static fromParts(coef, scale) {
97
105
  if (!Number.isInteger(scale) || scale < 0 || scale > MAX_SCALE)
98
- throw new ConfigError(`escala inválida: ${scale}`);
106
+ throw new ErroDeConfiguracao(`escala inválida: ${scale}`);
99
107
  return new Decimal(coef, scale);
100
108
  }
101
109
  static of(input) {
102
110
  const d = Decimal.tryOf(input);
103
111
  if (d === undefined)
104
- throw new ConfigError(`número decimal inválido: ${JSON.stringify(String(input))}`);
112
+ throw new ErroDeConfiguracao(`número decimal inválido: ${JSON.stringify(String(input))}`);
105
113
  return d;
106
114
  }
107
115
  static tryOf(input) {
@@ -161,7 +169,7 @@ class Decimal {
161
169
  dividedBy(other, scale, mode) {
162
170
  const o = Decimal.of(other);
163
171
  if (o.coef === 0n)
164
- throw new ConfigError("divisão por zero");
172
+ throw new ErroDeConfiguracao("divisão por zero");
165
173
  const shift = o.scale + scale + 1 - this.scale;
166
174
  const num = shift >= 0 ? this.coef * pow10(shift) : this.coef;
167
175
  const den = shift >= 0 ? o.coef : o.coef * pow10(-shift);
@@ -181,7 +189,7 @@ class Decimal {
181
189
  }
182
190
  round(scale, mode) {
183
191
  if (!Number.isInteger(scale) || scale < 0)
184
- throw new ConfigError(`casas decimais inválidas: ${scale}`);
192
+ throw new ErroDeConfiguracao(`casas decimais inválidas: ${scale}`);
185
193
  if (scale >= this.scale)
186
194
  return new Decimal(this.coef * pow10(scale - this.scale), scale);
187
195
  return roundCoef(this.coef, this.scale, scale, mode, false);
@@ -246,50 +254,50 @@ function roundCoef(coef, from, to, mode, sticky) {
246
254
  }
247
255
  return Decimal.fromParts(neg ? -q : q, to);
248
256
  }
249
- function dec(input) {
250
- return Decimal.of(input);
257
+ function dec(valor) {
258
+ return Decimal.of(valor);
251
259
  }
252
- function sum(values) {
260
+ function sum(valores) {
253
261
  let acc = Decimal.ZERO;
254
- for (const v of values)
262
+ for (const v of valores)
255
263
  acc = acc.plus(v);
256
264
  return acc;
257
265
  }
258
266
 
259
267
  // packages/nfe/src/format.ts
260
- var D1302 = { name: "TDec_1302", min: 2, max: 2, intDigits: 13 };
261
- var D1302_OPC = { name: "TDec_1302Opc", min: 2, max: 2, intDigits: 13, nonZero: true };
262
- var D0302A04 = { name: "TDec_0302a04", min: 2, max: 4, intDigits: 3 };
263
- var D0302A04_OPC = { name: "TDec_0302a04Opc", min: 2, max: 4, intDigits: 3 };
264
- var D0302 = { name: "TDec_0302Max100", min: 2, max: 2, intDigits: 3 };
265
- var D1104V = { name: "TDec_1104v", min: 0, max: 4, intDigits: 11 };
266
- var D1104 = { name: "TDec_1104", min: 4, max: 4, intDigits: 11 };
267
- var D1110V = { name: "TDec_1110v", min: 0, max: 10, intDigits: 11 };
268
- var D1204V = { name: "TDec_1204v", min: 0, max: 4, intDigits: 12 };
269
- var D1204 = { name: "TDec_1204", min: 4, max: 4, intDigits: 12 };
270
- var D1203 = { name: "TDec_1203", min: 3, max: 3, intDigits: 12 };
271
- function formatDecimal(value, format, mode = "HALF_UP") {
272
- const r = value.round(format.max, mode);
273
- let places = Math.max(format.min, Math.min(format.max, r.significantScale()));
274
- if (format.minBelowOne !== undefined && !r.isZero() && r.abs().lt(1))
275
- places = Math.max(places, format.minBelowOne);
276
- return r.toFixed(places, mode);
268
+ var D1302 = { nome: "TDec_1302", min: 2, max: 2, digitosInteiros: 13 };
269
+ var D1302_OPC = { nome: "TDec_1302Opc", min: 2, max: 2, digitosInteiros: 13, naoNulo: true };
270
+ var D0302A04 = { nome: "TDec_0302a04", min: 2, max: 4, digitosInteiros: 3 };
271
+ var D0302A04_OPC = { nome: "TDec_0302a04Opc", min: 2, max: 4, digitosInteiros: 3 };
272
+ var D0302 = { nome: "TDec_0302Max100", min: 2, max: 2, digitosInteiros: 3 };
273
+ var D1104V = { nome: "TDec_1104v", min: 0, max: 4, digitosInteiros: 11 };
274
+ var D1104 = { nome: "TDec_1104", min: 4, max: 4, digitosInteiros: 11 };
275
+ var D1110V = { nome: "TDec_1110v", min: 0, max: 10, digitosInteiros: 11 };
276
+ var D1204V = { nome: "TDec_1204v", min: 0, max: 4, digitosInteiros: 12 };
277
+ var D1204 = { nome: "TDec_1204", min: 4, max: 4, digitosInteiros: 12 };
278
+ var D1203 = { nome: "TDec_1203", min: 3, max: 3, digitosInteiros: 12 };
279
+ function formatarDecimal(valor, formato, modo = "HALF_UP") {
280
+ const r = valor.round(formato.max, modo);
281
+ let places = Math.max(formato.min, Math.min(formato.max, r.significantScale()));
282
+ if (formato.minimoAbaixoDeUm !== undefined && !r.isZero() && r.abs().lt(1))
283
+ places = Math.max(places, formato.minimoAbaixoDeUm);
284
+ return r.toFixed(places, modo);
277
285
  }
278
- function formatProblem(value, format) {
279
- if (value.isNegative())
286
+ function problemaDeFormato(valor, formato) {
287
+ if (valor.isNegative())
280
288
  return "valor negativo";
281
- if (format.nonZero && value.isZero())
289
+ if (formato.naoNulo && valor.isZero())
282
290
  return "valor zero não é aceito neste campo";
283
- if (value.significantScale() > format.max)
284
- return `mais de ${format.max} casas decimais`;
285
- const intDigits = value.round(0, "DOWN").abs().toString().replace(/^0$/, "").length;
286
- if (intDigits > format.intDigits)
287
- return `mais de ${format.intDigits} dígitos inteiros`;
291
+ if (valor.significantScale() > formato.max)
292
+ return `mais de ${formato.max} casas decimais`;
293
+ const intDigits = valor.round(0, "DOWN").abs().toString().replace(/^0$/, "").length;
294
+ if (intDigits > formato.digitosInteiros)
295
+ return `mais de ${formato.digitosInteiros} dígitos inteiros`;
288
296
  return;
289
297
  }
290
298
 
291
299
  // packages/nfe/src/issues.ts
292
- var NFE_ISSUE_CODES = [
300
+ var CODIGOS_OCORRENCIA_NFE = [
293
301
  "campo_obrigatorio",
294
302
  "campo_invalido",
295
303
  "campo_fora_do_pl",
@@ -326,7 +334,7 @@ class Issues {
326
334
  this.list = [];
327
335
  }
328
336
  add(path, code, message, origem = "entrada") {
329
- this.list.push({ path, code, message, origem });
337
+ this.list.push({ caminho: path, code, mensagem: message, origem });
330
338
  }
331
339
  montagem(path, code, message) {
332
340
  this.add(path, code, message, "montagem");
@@ -350,10 +358,10 @@ class Issues {
350
358
  }
351
359
 
352
360
  // packages/nfe/src/rtc.ts
353
- import { fixedClock, isUf, timeContext, ufByCUf } from "@sinete/core";
354
- import { officialRates, RateUnknownError } from "@sinete/ibs-cbs/aliquotas";
355
- import { ClassificationError, calculate, UnsupportedRegimeError } from "@sinete/ibs-cbs/calcular";
356
- import { documentFromRoc, validate } from "@sinete/ibs-cbs/validar";
361
+ import { contextoDeTempo, ehUf, relogioFixo, ufPorCUf } from "@sinete/core";
362
+ import { aliquotasOficiais, ErroAliquotaDesconhecida } from "@sinete/ibs-cbs/aliquotas";
363
+ import { calcular, ErroClassificacao, ErroRegimeNaoSuportado } from "@sinete/ibs-cbs/calcular";
364
+ import { documentoDoRoc, validar } from "@sinete/ibs-cbs/validar";
357
365
  var BASE = /^\d{1,13}(\.\d{1,2})?$/;
358
366
  function normalizado(v) {
359
367
  const [int = "0", frac = ""] = v.split(".");
@@ -363,7 +371,7 @@ function normalizado(v) {
363
371
  }
364
372
  var caminho = (nItem) => `itens[${nItem - 1}].impostos.ibsCbs`;
365
373
  function ufDoMunicipio(cMun) {
366
- return ufByCUf(cMun.slice(0, 2))?.sigla;
374
+ return ufPorCUf(cMun.slice(0, 2))?.sigla;
367
375
  }
368
376
  function localDaOperacao(nota) {
369
377
  if (nota.cMunFGIBS !== undefined) {
@@ -372,7 +380,7 @@ function localDaOperacao(nota) {
372
380
  return { uf, cMun: nota.cMunFGIBS };
373
381
  }
374
382
  const d = nota.destino;
375
- if (d !== undefined && d.UF !== "EX" && isUf(d.UF))
383
+ if (d !== undefined && d.UF !== "EX" && ehUf(d.UF))
376
384
  return { uf: d.UF, cMun: d.cMun };
377
385
  return { uf: nota.emitente.UF, cMun: nota.emitente.cMun };
378
386
  }
@@ -391,30 +399,30 @@ function grupoDoLeiaute(g, indDoacao) {
391
399
  };
392
400
  }
393
401
  function ocorrenciaDoMotor(e, itens) {
394
- if (e instanceof ClassificationError || e instanceof UnsupportedRegimeError) {
402
+ if (e instanceof ErroClassificacao || e instanceof ErroRegimeNaoSuportado) {
395
403
  const path = e.item !== undefined ? caminho(e.item) : caminho(itens[0]?.nItem ?? 1);
396
- return { path, code: e.code, message: e.message, origem: "entrada" };
404
+ return { caminho: path, code: e.code, mensagem: e.message, origem: "entrada" };
397
405
  }
398
- if (e instanceof RateUnknownError)
399
- return { path: "impostos.ibsCbs", code: e.code, message: e.message, origem: "montagem" };
406
+ if (e instanceof ErroAliquotaDesconhecida)
407
+ return { caminho: "impostos.ibsCbs", code: e.code, mensagem: e.message, origem: "montagem" };
400
408
  return;
401
409
  }
402
410
  var embarcado;
403
411
  function carregarDatasetEmbarcado() {
404
- embarcado ??= import("@sinete/ibs-cbs-dados/bundled").then((m) => m.bundledDataset(), (e) => {
412
+ embarcado ??= import("@sinete/ibs-cbs-dados/embarcado").then((m) => m.datasetEmbarcado(), (e) => {
405
413
  embarcado = undefined;
406
414
  throw e;
407
415
  });
408
416
  return embarcado;
409
417
  }
410
- function ibsCbsCalculator(options = {}) {
411
- const rates = options.rates ?? officialRates();
412
- const dataset = options.dataset;
418
+ function calculadoraIbsCbs(opcoes = {}) {
419
+ const rates = opcoes.aliquotas ?? aliquotasOficiais();
420
+ const dataset = opcoes.dataset;
413
421
  return {
414
422
  calcular(request) {
415
423
  if (dataset !== undefined)
416
- return calcularCom(dataset, rates, options, request);
417
- return carregarDatasetEmbarcado().then((ds) => calcularCom(ds, rates, options, request));
424
+ return calcularCom(dataset, rates, opcoes, request);
425
+ return carregarDatasetEmbarcado().then((ds) => calcularCom(ds, rates, opcoes, request));
418
426
  }
419
427
  };
420
428
  }
@@ -427,9 +435,9 @@ function calcularCom(dataset, rates, options, {
427
435
  for (const it of itens) {
428
436
  if (it.cCredPres !== undefined) {
429
437
  issues.push({
430
- path: caminho(it.nItem),
438
+ caminho: caminho(it.nItem),
431
439
  code: "ibscbs_nao_suportado",
432
- message: "crédito presumido (cCredPres) precisa do grupo gCredPresOper pronto (ibsCbs.grupo)",
440
+ mensagem: "crédito presumido (cCredPres) precisa do grupo gCredPresOper pronto (ibsCbs.grupo)",
433
441
  origem: "entrada"
434
442
  });
435
443
  continue;
@@ -437,18 +445,18 @@ function calcularCom(dataset, rates, options, {
437
445
  const base = it.vBC !== undefined ? it.vBC.toFixed(2) : options.base?.(it, nota);
438
446
  if (base === undefined) {
439
447
  issues.push({
440
- path: `${caminho(it.nItem)}.classificacao.vBC`,
448
+ caminho: `${caminho(it.nItem)}.classificacao.vBC`,
441
449
  code: "ibscbs_base_ausente",
442
- message: "informe vBC do IBS/CBS ou IbsCbsCalculatorOptions.base: a composição da base (UB16-10) ainda não tem regra publicada",
450
+ mensagem: "informe vBC do IBS/CBS ou CalculadoraIbsCbsOpcoes.base: a composição da base (UB16-10) ainda não tem regra publicada",
443
451
  origem: "entrada"
444
452
  });
445
453
  continue;
446
454
  }
447
455
  if (!BASE.test(base)) {
448
456
  issues.push({
449
- path: `${caminho(it.nItem)}.classificacao.vBC`,
457
+ caminho: `${caminho(it.nItem)}.classificacao.vBC`,
450
458
  code: "decimal_invalido",
451
- message: base,
459
+ mensagem: base,
452
460
  origem: it.vBC !== undefined ? "entrada" : "montagem"
453
461
  });
454
462
  continue;
@@ -458,92 +466,92 @@ function calcularCom(dataset, rates, options, {
458
466
  cst: it.CST,
459
467
  cClassTrib: it.cClassTrib,
460
468
  base,
461
- quantity: it.qTrib.toString(),
462
- unit: it.uTrib,
469
+ quantidade: it.qTrib.toString(),
470
+ unidade: it.uTrib,
463
471
  ...it.gTribRegular === undefined ? {} : { regular: { cst: it.gTribRegular.CSTReg, cClassTrib: it.gTribRegular.cClassTribReg } }
464
472
  });
465
473
  }
466
474
  if (issues.length > 0)
467
- return { itens: [], issues };
475
+ return { itens: [], ocorrencias: issues };
468
476
  const op = {
469
477
  modelo: Number(nota.mod),
470
- place: localDaOperacao(nota),
478
+ local: localDaOperacao(nota),
471
479
  ...nota.compraGov === undefined ? {} : {
472
- governmentPurchase: {
480
+ compraGovernamental: {
473
481
  tpEnteGov: Number(nota.compraGov.tpEnteGov),
474
482
  ...nota.compraGov.tpOperGov === "1" || nota.compraGov.tpOperGov === "2" ? { tpOperGov: Number(nota.compraGov.tpOperGov) } : {}
475
483
  }
476
484
  },
477
- items: classificados
485
+ itens: classificados
478
486
  };
479
- const time = timeContext({ emissao: fixedClock(nota.emissao), fatoGerador: fixedClock(nota.fatoGerador) });
487
+ const time = contextoDeTempo({ emissao: relogioFixo(nota.emissao), fatoGerador: relogioFixo(nota.fatoGerador) });
480
488
  let roc;
481
489
  try {
482
- roc = calculate(op, {
490
+ roc = calcular(op, {
483
491
  dataset,
484
- rates,
485
- time,
486
- ...options.utcOffsetMinutes === undefined ? {} : { utcOffsetMinutes: options.utcOffsetMinutes }
492
+ aliquotas: rates,
493
+ tempo: time,
494
+ ...options.deslocamentoMin === undefined ? {} : { deslocamentoMin: options.deslocamentoMin }
487
495
  });
488
496
  } catch (e) {
489
497
  const issue = ocorrenciaDoMotor(e, itens);
490
498
  if (issue === undefined)
491
499
  throw e;
492
- return { itens: [], issues: [issue] };
500
+ return { itens: [], ocorrencias: [issue] };
493
501
  }
494
502
  const redutor = roc.oper?.gCompraGov.pRedutor;
495
503
  if (nota.compraGov !== undefined && redutor !== undefined && normalizado(nota.compraGov.pRedutor.toString()) !== normalizado(redutor)) {
496
504
  issues.push({
497
- path: "gCompraGov.pRedutor",
505
+ caminho: "gCompraGov.pRedutor",
498
506
  code: "ibscbs_redutor_divergente",
499
- message: `pRedutor informado (${nota.compraGov.pRedutor.toString()}) difere do vigente no fato gerador (${redutor})`,
507
+ mensagem: `pRedutor informado (${nota.compraGov.pRedutor.toString()}) difere do vigente no fato gerador (${redutor})`,
500
508
  origem: "entrada"
501
509
  });
502
510
  }
503
511
  if (options.regras !== false) {
504
- const doc = documentFromRoc(roc, {
512
+ const doc = documentoDoRoc(roc, {
505
513
  modelo: op.modelo,
506
514
  crt: Number(nota.emitente.CRT),
507
515
  finNFe: Number(nota.finNFe),
508
516
  ...nota.tpNFDebito === undefined ? {} : { tpNFDebito: nota.tpNFDebito },
509
517
  ...nota.tpNFCredito === undefined ? {} : { tpNFCredito: nota.tpNFCredito },
510
- emitMun: nota.emitente.cMun,
511
- ...nota.destino === undefined ? {} : { destMun: nota.destino.cMun },
512
- items: itens.map((it) => ({ nItem: it.nItem, ncm: it.NCM, vProd: it.vProd.toFixed(2) }))
518
+ munEmitente: nota.emitente.cMun,
519
+ ...nota.destino === undefined ? {} : { munDestinatario: nota.destino.cMun },
520
+ itens: itens.map((it) => ({ nItem: it.nItem, ncm: it.NCM, vProd: it.vProd.toFixed(2) }))
513
521
  });
514
- const report = validate(doc, {
522
+ const report = validar(doc, {
515
523
  dataset,
516
- time,
524
+ tempo: time,
517
525
  ambiente: nota.ambiente,
518
- rates,
519
- ...options.utcOffsetMinutes === undefined ? {} : { utcOffsetMinutes: options.utcOffsetMinutes },
520
- ...options.regras?.rules === undefined ? {} : { rules: options.regras.rules },
521
- ...options.regras?.ignoreActivation === undefined ? {} : { ignoreActivation: options.regras.ignoreActivation }
526
+ aliquotas: rates,
527
+ ...options.deslocamentoMin === undefined ? {} : { deslocamentoMin: options.deslocamentoMin },
528
+ ...options.regras?.regras === undefined ? {} : { regras: options.regras.regras },
529
+ ...options.regras?.ignorarAtivacao === undefined ? {} : { ignorarAtivacao: options.regras.ignorarAtivacao }
522
530
  });
523
- for (const v of report.violations) {
531
+ for (const v of report.violacoes) {
524
532
  issues.push({
525
- path: v.item === undefined ? "total.IBSCBSTot" : caminho(v.item),
533
+ caminho: v.item === undefined ? "total.IBSCBSTot" : caminho(v.item),
526
534
  code: "ibscbs_regra_nt",
527
- message: `${v.rule} (rejeição ${v.cStat}): ${v.message} [${v.source}]`,
535
+ mensagem: `${v.regra} (rejeição ${v.cStat}): ${v.message} [${v.fonte}]`,
528
536
  origem: "montagem"
529
537
  });
530
538
  }
531
539
  }
532
540
  const porItem = new Map(itens.map((it) => [it.nItem, it]));
533
541
  return {
534
- itens: roc.items.map((r) => ({
542
+ itens: roc.itens.map((r) => ({
535
543
  nItem: r.nItem,
536
544
  IBSCBS: grupoDoLeiaute(r.IBSCBS, porItem.get(r.nItem)?.indDoacao)
537
545
  })),
538
- ...issues.length === 0 ? {} : { issues }
546
+ ...issues.length === 0 ? {} : { ocorrencias: issues }
539
547
  };
540
548
  }
541
549
 
542
550
  // packages/nfe/src/time.ts
543
- import { formatDateTimeOffset } from "@sinete/core";
551
+ import { formatarDataHoraComFuso } from "@sinete/core";
544
552
  // packages/nfe/src/data/fusos.json
545
553
  var fusos_default = {
546
- descricao: "Deslocamento do horário legal de cada UF em relação a UTC, em minutos, usado para formatar dhEmi, dhSaiEnt, dhCont e dhEvento quando quem emite não informa o fuso. Sem horário de verão desde 2019. UFs com mais de um fuso usam o da capital; o emitente de outro fuso informa offsetMinutes.",
554
+ descricao: "Deslocamento do horário legal de cada UF em relação a UTC, em minutos, usado para formatar dhEmi, dhSaiEnt, dhCont e dhEvento quando quem emite não informa o fuso. Sem horário de verão desde 2019. UFs com mais de um fuso usam o da capital; o emitente de outro fuso informa deslocamentoMin.",
547
555
  atualizadoEm: "2026-09-26",
548
556
  fontes: [
549
557
  "Lei 11.662/2008 e Lei 12.876/2013 (fusos horários do Brasil; Acre em UTC-5)",
@@ -562,19 +570,19 @@ var fusos_default = {
562
570
 
563
571
  // packages/nfe/src/time.ts
564
572
  var UF_OFFSETS = fusos_default.ufs;
565
- function offsetDaUf(uf) {
573
+ function deslocamentoDaUf(uf) {
566
574
  return Object.hasOwn(UF_OFFSETS, uf) ? UF_OFFSETS[uf] : fusos_default.padrao;
567
575
  }
568
- function formatDh(date, offsetMinutes) {
569
- return formatDateTimeOffset(date, offsetMinutes);
576
+ function formatarDh(data, deslocamentoMin) {
577
+ return formatarDataHoraComFuso(data, deslocamentoMin);
570
578
  }
571
579
 
572
580
  // packages/nfe/src/versao-gerada.ts
573
- var VERSAO_PACOTE = "0.1.0";
581
+ var VERSAO_PACOTE = "0.3.0";
574
582
 
575
583
  // packages/nfe/src/build/destinatario.ts
576
- import { ufBySigla } from "@sinete/core";
577
- import { parseCnpj } from "@sinete/validators";
584
+ import { ufPorSigla } from "@sinete/core";
585
+ import { lerCnpj } from "@sinete/validators";
578
586
  // packages/nfe/src/data/suframa.json
579
587
  var suframa_default = {
580
588
  descricao: "Onde a inscrição na Suframa do destinatário (ISUF) é aceita na NF-e: UFs inteiras e, no Amapá, só os municípios listados. Fora delas, rejeição 251.",
@@ -617,7 +625,7 @@ function conferirDestinatario(input, ide, issues) {
617
625
  }
618
626
  if (end !== undefined && !exterior) {
619
627
  const e = end;
620
- const cUF = ufBySigla(e.UF)?.cUF;
628
+ const cUF = ufPorSigla(e.UF)?.cUF;
621
629
  if (cUF !== undefined && digitos(e.cMun).slice(0, 2) !== cUF) {
622
630
  issues.add("destinatario.endereco.cMun", "combinacao_invalida", `município ${e.cMun} não é da UF ${e.UF} do destinatário (E10-20, rejeição 275)`);
623
631
  }
@@ -636,8 +644,8 @@ function conferirDestinatario(input, ide, issues) {
636
644
  const cnpj = (v) => {
637
645
  if (v === undefined)
638
646
  return;
639
- const r = parseCnpj(v);
640
- return r.ok ? r.value : undefined;
647
+ const r = lerCnpj(v);
648
+ return r.ok ? r.valor : undefined;
641
649
  };
642
650
  const cnpjDest = "CNPJ" in d ? cnpj(d.CNPJ) : undefined;
643
651
  const mesmoCnpj = cnpjDest !== undefined && cnpjDest === cnpj(input.emitente.CNPJ);
@@ -685,18 +693,18 @@ function conferirDestinatario(input, ide, issues) {
685
693
  }
686
694
 
687
695
  // packages/nfe/src/build/ibscbs.ts
688
- import { firstChild, parseXml } from "@sinete/core/xml";
689
- import { serialize, validate as validate2 } from "@sinete/schemas";
696
+ import { lerXml, primeiroFilho } from "@sinete/core/xml";
697
+ import { serializar, validar as validar2 } from "@sinete/schemas";
690
698
  var NFE_NS = "http://www.portalfiscal.inf.br/nfe";
691
699
  function grupoInvalido(ct, nome, value, path, issues) {
692
700
  if (value === undefined)
693
701
  return false;
694
702
  try {
695
- const doc = parseXml(`<w xmlns="${NFE_NS}">${serialize(ct, nome, value, NFE_NS)}</w>`);
696
- const el = firstChild(doc.root, nome, NFE_NS);
697
- const erros = el === undefined ? [{ path: "", code: "modelo_de_conteudo", message: "grupo vazio" }] : validate2(ct, el);
703
+ const doc = lerXml(`<w xmlns="${NFE_NS}">${serializar(ct, nome, value, NFE_NS)}</w>`);
704
+ const el = primeiroFilho(doc.raiz, nome, NFE_NS);
705
+ const erros = el === undefined ? [{ caminho: "", code: "modelo_de_conteudo", mensagem: "grupo vazio" }] : validar2(ct, el);
698
706
  for (const e of erros)
699
- issues.add(`${path}${e.path.replace(/^\/[^/]+/, "").replace(/\//g, ".")}`, "schema", `${e.code}: ${e.message}`);
707
+ issues.add(`${path}${e.caminho.replace(/^\/[^/]+/, "").replace(/\//g, ".")}`, "schema", `${e.code}: ${e.mensagem}`);
700
708
  return erros.length > 0;
701
709
  } catch (e) {
702
710
  issues.add(path, "schema", `grupo malformado: ${e.message}`);
@@ -809,9 +817,9 @@ class Ctx {
809
817
  this.issues.add(path, "decimal_invalido", "número decimal inválido (use ponto como separador, sem milhar)");
810
818
  return;
811
819
  }
812
- const problem = formatProblem(d, format);
820
+ const problem = problemaDeFormato(d, format);
813
821
  if (problem !== undefined) {
814
- this.issues.add(path, "decimal_invalido", `${problem} (${format.name})`);
822
+ this.issues.add(path, "decimal_invalido", `${problem} (${format.nome})`);
815
823
  return;
816
824
  }
817
825
  return d;
@@ -842,14 +850,14 @@ class Ctx {
842
850
  return g;
843
851
  }
844
852
  s(value, format) {
845
- return formatDecimal(value, format);
853
+ return formatarDecimal(value, format);
846
854
  }
847
855
  so(value, format) {
848
856
  if (value === undefined)
849
857
  return;
850
- if (format.nonZero && value.isZero())
858
+ if (format.naoNulo && value.isZero())
851
859
  return;
852
- return formatDecimal(value, format);
860
+ return formatarDecimal(value, format);
853
861
  }
854
862
  }
855
863
  function clean(o) {
@@ -1362,17 +1370,17 @@ function buildIcms(ctx, input, base, path) {
1362
1370
  }
1363
1371
 
1364
1372
  // packages/nfe/src/build/nfce.ts
1365
- import { tpAmbOf } from "@sinete/core";
1366
- import { base64Encode, c14n, firstChild as firstChild2, parseXml as parseXml2, SHA1_DIGEST_INFO_PREFIX } from "@sinete/core/xml";
1367
- import { parseCnpj as parseCnpj2 } from "@sinete/validators";
1373
+ import { tpAmbDoAmbiente } from "@sinete/core";
1374
+ import { c14n, codificarBase64, lerXml as lerXml2, PREFIXO_DIGEST_INFO_SHA1, primeiroFilho as primeiroFilho2 } from "@sinete/core/xml";
1375
+ import { lerCnpj as lerCnpj2 } from "@sinete/validators";
1368
1376
  // packages/nfe/src/data/nfce-urls.json
1369
1377
  var nfce_urls_default = {
1370
- descricao: "Endereços da NFC-e (modelo 65) por UF e ambiente: a consulta via QR Code (1ª parte da URL do infNFeSupl/qrCode, sem o '?p=' que o builder acrescenta) e a consulta por chave de acesso (infNFeSupl/urlChave, impressa no DANFC-e). Cada UF tem uma lista de endereços com a data de início ('desde', AAAA-MM-DD, 00:00 de Brasília); vale o mais recente cujo início não passou da data de emissão. As tabelas do ENCAT foram transcritas como publicadas, com três ajustes: o '?' final e o exemplo de parâmetros (AM: '?chNFe=1315....') foram retirados, porque o builder monta a query; o espaço dentro do endereço de homologação do MA ('homolog acao') foi juntado; e o endereço de MG por chave de acesso vem da página de web services da própria SEFAZ-MG, mais nova que a do ENCAT. Onde a tabela não dá o protocolo ('http://' ou 'https://'), a URL do QR Code fica null: o schema exige o protocolo e não há fonte para escolher um; informe BuildNfeOptions.urlQrCode. A regra ZX02-20 (rejeição 395) compara o endereço sem diferenciar maiúsculas e minúsculas; ZX03-20 (rejeição 878) é opcional por UF.",
1378
+ descricao: "Endereços da NFC-e (modelo 65) por UF e ambiente: a consulta via QR Code (1ª parte da URL do infNFeSupl/qrCode, sem o '?p=' que o builder acrescenta) e a consulta por chave de acesso (infNFeSupl/urlChave, impressa no DANFC-e). Cada UF tem uma lista de endereços com a data de início ('desde', AAAA-MM-DD, 00:00 de Brasília); vale o mais recente cujo início não passou da data de emissão. As tabelas do ENCAT foram transcritas como publicadas, com três ajustes: o '?' final e o exemplo de parâmetros (AM: '?chNFe=1315....') foram retirados, porque o builder monta a query; o espaço dentro do endereço de homologação do MA ('homolog acao') foi juntado; e o endereço de MG por chave de acesso vem da página de web services da própria SEFAZ-MG, mais nova que a do ENCAT. Onde a tabela não dá o protocolo ('http://' ou 'https://'), a URL do QR Code fica null: o schema exige o protocolo e não há fonte para escolher um; informe MontarNfeOpcoes.urlQrCode. A regra ZX02-20 (rejeição 395) compara o endereço sem diferenciar maiúsculas e minúsculas; ZX03-20 (rejeição 878) é opcional por UF.",
1371
1379
  atualizadoEm: "2026-09-26",
1372
1380
  fontes: [
1373
1381
  "Portal Nacional da NFC-e (ENCAT), URL por UF utilizada QR code: https://nfce.encat.org/desenvolvedor/qrcode/ (coletada em 26/09/2026)",
1374
1382
  "Portal Nacional da NFC-e (ENCAT), URL por UF utilizada para consulta chave, QR Code versão 2.0: https://nfce.encat.org/desenvolvedor/httpnfce-encat-orgconsulte-sua-nota-qr-code-versao-2-0/ (coletada em 26/09/2026)",
1375
- "SEFAZ-MG, web services da NFC-e: https://portalsped.fazenda.mg.gov.br/spedmg/nfce/web-services/ (a mesma fonte do nfceConsultaUrls do @sinete/transport) (coletada em 26/09/2026)",
1383
+ "SEFAZ-MG, web services da NFC-e: https://portalsped.fazenda.mg.gov.br/spedmg/nfce/web-services/ (a mesma fonte do urlsConsultaNfce do @sinete/transport) (coletada em 26/09/2026)",
1376
1384
  "MOC 7.0 Anexo I, regras ZX02-20 e ZX03-20; NT 2025.001 v1.03, grupo ZX (campos ZX02 qrCode e ZX03 urlChave)"
1377
1385
  ],
1378
1386
  qrCode: {
@@ -1558,11 +1566,11 @@ async function sha1(bytes) {
1558
1566
  }
1559
1567
  var hex = (b) => Array.from(b, (x) => x.toString(16).padStart(2, "0")).join("");
1560
1568
  async function digValHex(xml) {
1561
- const doc = parseXml2(xml);
1562
- const inf = firstChild2(doc.root, "infNFe", NFE_NS2);
1569
+ const doc = lerXml2(xml);
1570
+ const inf = primeiroFilho2(doc.raiz, "infNFe", NFE_NS2);
1563
1571
  if (inf === undefined)
1564
1572
  throw new Error("NF-e montada sem infNFe");
1565
- return hexDoDigestValue(base64Encode(await sha1(te.encode(c14n(inf)))));
1573
+ return hexDoDigestValue(codificarBase64(await sha1(te.encode(c14n(inf)))));
1566
1574
  }
1567
1575
  function hexDoDigestValue(digestValue) {
1568
1576
  return hex(te.encode(digestValue));
@@ -1571,7 +1579,7 @@ async function hashQrCodeV2(parametros, csc) {
1571
1579
  return hex(await sha1(te.encode(parametros + csc))).toUpperCase();
1572
1580
  }
1573
1581
  async function parametrosQrCode(d, qr) {
1574
- const tpAmb = tpAmbOf(d.ambiente);
1582
+ const tpAmb = tpAmbDoAmbiente(d.ambiente);
1575
1583
  const offline = d.tpEmis === "9";
1576
1584
  const dia = d.dhEmi.slice(8, 10);
1577
1585
  if (qr.versao === "3") {
@@ -1587,13 +1595,13 @@ async function parametrosQrCode(d, qr) {
1587
1595
  }
1588
1596
  async function assinarParametros(parametros, signer) {
1589
1597
  const bytes = te.encode(parametros);
1590
- if (signer.kind === "data")
1591
- return base64Encode(await signer.sign(bytes, "SHA-1"));
1598
+ if (signer.tipo === "dados")
1599
+ return codificarBase64(await signer.assinar(bytes, "SHA-1"));
1592
1600
  const h = await sha1(bytes);
1593
- const di = new Uint8Array(SHA1_DIGEST_INFO_PREFIX.length + h.length);
1594
- di.set(SHA1_DIGEST_INFO_PREFIX);
1595
- di.set(h, SHA1_DIGEST_INFO_PREFIX.length);
1596
- return base64Encode(await signer.signDigestInfo(di));
1601
+ const di = new Uint8Array(PREFIXO_DIGEST_INFO_SHA1.length + h.length);
1602
+ di.set(PREFIXO_DIGEST_INFO_SHA1);
1603
+ di.set(h, PREFIXO_DIGEST_INFO_SHA1.length);
1604
+ return codificarBase64(await signer.assinarDigestInfo(di));
1597
1605
  }
1598
1606
  var CFOP_ISSQN = "5933";
1599
1607
  var NFCE_LIMITE_SEM_DESTINATARIO = "10000.00";
@@ -1761,17 +1769,17 @@ function pagamentoNfce(pag, vNF, issues) {
1761
1769
  issues.add(path, "campo_obrigatorio", "cartão integrado à automação (tpIntegra 1) informa o CNPJ da credenciadora e o cAut (NT 2025.001, YA05-10, rejeição 392)");
1762
1770
  }
1763
1771
  if (c.CNPJ !== undefined) {
1764
- const r = parseCnpj2(c.CNPJ, { path: `${path}.CNPJ` });
1772
+ const r = lerCnpj2(c.CNPJ, { caminho: `${path}.CNPJ` });
1765
1773
  if (!r.ok)
1766
- issues.list.push(r.error);
1774
+ issues.list.push(r.erro);
1767
1775
  }
1768
1776
  });
1769
1777
  }
1770
1778
  var digitos2 = (s) => s.replace(/[^0-9A-Za-z]/g, "").toUpperCase();
1771
1779
 
1772
1780
  // packages/nfe/src/build/pl.ts
1773
- import { UnsupportedError } from "@sinete/core";
1774
- import { isComplexType, isElementParticle, isWildcard, selecionarPl } from "@sinete/schemas";
1781
+ import { ErroNaoSuportado } from "@sinete/core";
1782
+ import { ehComplexType, ehElementParticle, ehWildcard, selecionarPl } from "@sinete/schemas";
1775
1783
  import { TNFe_infNFe as Inf010e } from "@sinete/schemas/nfe/PL_010e";
1776
1784
  import { TNFe_infNFe as Inf010f } from "@sinete/schemas/nfe/PL_010f";
1777
1785
  var INF_NFE = {
@@ -1782,14 +1790,14 @@ function escolherPl(ambiente, emissao) {
1782
1790
  const vigencia = selecionarPl("nfe", ambiente, emissao);
1783
1791
  const infNFe = INF_NFE[vigencia.modulo];
1784
1792
  if (infNFe === undefined) {
1785
- throw new UnsupportedError(`@sinete/nfe não conhece o módulo ${vigencia.modulo}; atualize o pacote`);
1793
+ throw new ErroNaoSuportado(`@sinete/nfe não conhece o módulo ${vigencia.modulo}; atualize o pacote`);
1786
1794
  }
1787
1795
  return { vigencia, infNFe };
1788
1796
  }
1789
1797
  function memberNames(p, acc) {
1790
- if (isWildcard(p))
1798
+ if (ehWildcard(p))
1791
1799
  acc.add("$any");
1792
- else if (isElementParticle(p))
1800
+ else if (ehElementParticle(p))
1793
1801
  acc.add(p.e);
1794
1802
  else
1795
1803
  for (const i of p.i)
@@ -1797,10 +1805,10 @@ function memberNames(p, acc) {
1797
1805
  return acc;
1798
1806
  }
1799
1807
  function elementTypes(p, acc) {
1800
- if (isWildcard(p))
1808
+ if (ehWildcard(p))
1801
1809
  return acc;
1802
- if (isElementParticle(p)) {
1803
- if (isComplexType(p.t))
1810
+ if (ehElementParticle(p)) {
1811
+ if (ehComplexType(p.t))
1804
1812
  acc.set(p.e, p.t);
1805
1813
  } else
1806
1814
  for (const i of p.i)
@@ -1867,7 +1875,7 @@ function cstComIsento(input, idDest, issues) {
1867
1875
  issues.add(`itens[${n}].impostos.icms.CST`, "combinacao_invalida", `CST ${cst} não se usa com destinatário contribuinte isento de IE (indIEDest 2) (N12-80, rejeição 529)`);
1868
1876
  });
1869
1877
  }
1870
- var dataNoFuso = (instante, offsetMinutes) => formatDh(instante, offsetMinutes).slice(0, 10);
1878
+ var dataNoFuso = (instante, offsetMinutes) => formatarDh(instante, offsetMinutes).slice(0, 10);
1871
1879
  var OFFSET_BRASILIA = -180;
1872
1880
  function vencimentos(input, emissao, issues) {
1873
1881
  const dups = input.cobranca?.duplicatas;
@@ -1890,9 +1898,9 @@ function conferirEmitenteDoCertificado(nfe, titular) {
1890
1898
  if (base !== soDocumento(titular.cnpj).slice(0, 8)) {
1891
1899
  return [
1892
1900
  {
1893
- path: "emitente.CNPJ",
1901
+ caminho: "emitente.CNPJ",
1894
1902
  code: "emitente_difere_do_certificado",
1895
- message: `CNPJ-base ${base} do emitente difere do CNPJ-base do certificado (F03, rejeição 213)`,
1903
+ mensagem: `CNPJ-base ${base} do emitente difere do CNPJ-base do certificado (F03, rejeição 213)`,
1896
1904
  origem: "entrada"
1897
1905
  }
1898
1906
  ];
@@ -1901,9 +1909,9 @@ function conferirEmitenteDoCertificado(nfe, titular) {
1901
1909
  if (e.CPF !== undefined && titular.cpf !== undefined && soDocumento(e.CPF) !== soDocumento(titular.cpf)) {
1902
1910
  return [
1903
1911
  {
1904
- path: "emitente.CPF",
1912
+ caminho: "emitente.CPF",
1905
1913
  code: "emitente_difere_do_certificado",
1906
- message: "CPF do emitente difere do CPF do certificado (F03A, rejeição 227)",
1914
+ mensagem: "CPF do emitente difere do CPF do certificado (F03A, rejeição 227)",
1907
1915
  origem: "entrada"
1908
1916
  }
1909
1917
  ];
@@ -1911,6 +1919,192 @@ function conferirEmitenteDoCertificado(nfe, titular) {
1911
1919
  return [];
1912
1920
  }
1913
1921
 
1922
+ // packages/nfe/src/build/textos.ts
1923
+ import { conferirTipoSimples, ehComplexType as ehComplexType2, ehElementParticle as ehElementParticle2, ehWildcard as ehWildcard2 } from "@sinete/schemas";
1924
+ function textoXmlValido(texto) {
1925
+ for (const ch of texto) {
1926
+ const c = ch.codePointAt(0) ?? 0;
1927
+ const ok = c === 9 || c === 10 || c === 13 || c >= 32 && c <= 55295 || c >= 57344 && c <= 65533 || c >= 65536 && c <= 1114111;
1928
+ if (!ok)
1929
+ return false;
1930
+ }
1931
+ return true;
1932
+ }
1933
+ var CAMPOS = [
1934
+ ["natOp", "ide.natOp"],
1935
+ ["emitente.xNome", "emit.xNome"],
1936
+ ["emitente.xFant", "emit.xFant"],
1937
+ ["emitente.endereco.xLgr", "emit.enderEmit.xLgr"],
1938
+ ["emitente.endereco.nro", "emit.enderEmit.nro"],
1939
+ ["emitente.endereco.xCpl", "emit.enderEmit.xCpl"],
1940
+ ["emitente.endereco.xBairro", "emit.enderEmit.xBairro"],
1941
+ ["emitente.endereco.xMun", "emit.enderEmit.xMun"],
1942
+ ["destinatario.xNome", "dest.xNome"],
1943
+ ["destinatario.email", "dest.email"],
1944
+ ["destinatario.endereco.xLgr", "dest.enderDest.xLgr"],
1945
+ ["destinatario.endereco.nro", "dest.enderDest.nro"],
1946
+ ["destinatario.endereco.xCpl", "dest.enderDest.xCpl"],
1947
+ ["destinatario.endereco.xBairro", "dest.enderDest.xBairro"],
1948
+ ["destinatario.endereco.xMun", "dest.enderDest.xMun"],
1949
+ ["destinatario.endereco.xPais", "dest.enderDest.xPais"],
1950
+ ...["retirada", "entrega"].flatMap((g) => ["xNome", "xLgr", "nro", "xCpl", "xBairro", "xMun", "email"].map((c) => [`${g}.${c}`, `${g}.${c}`])),
1951
+ ["itens[].produto.cProd", "det.prod.cProd"],
1952
+ ["itens[].produto.xProd", "det.prod.xProd"],
1953
+ ["itens[].produto.uCom", "det.prod.uCom"],
1954
+ ["itens[].produto.uTrib", "det.prod.uTrib"],
1955
+ ["itens[].produto.xPed", "det.prod.xPed"],
1956
+ ["itens[].infAdProd", "det.infAdProd"],
1957
+ ["transporte.transportador.xNome", "transp.transporta.xNome"],
1958
+ ["transporte.transportador.xEnder", "transp.transporta.xEnder"],
1959
+ ["transporte.transportador.xMun", "transp.transporta.xMun"],
1960
+ ["transporte.volumes[].esp", "transp.vol.esp"],
1961
+ ["transporte.volumes[].marca", "transp.vol.marca"],
1962
+ ["transporte.volumes[].nVol", "transp.vol.nVol"],
1963
+ ["cobranca.fatura.nFat", "cobr.fat.nFat"],
1964
+ ["cobranca.duplicatas[].nDup", "cobr.dup.nDup"],
1965
+ ["pagamento.detPag[].xPag", "pag.detPag.xPag"],
1966
+ ["informacoesAdicionais.infAdFisco", "infAdic.infAdFisco"],
1967
+ ["informacoesAdicionais.infCpl", "infAdic.infCpl"],
1968
+ ["informacoesAdicionais.obsCont[].xTexto", "infAdic.obsCont.xTexto"],
1969
+ ["informacoesAdicionais.obsFisco[].xTexto", "infAdic.obsFisco.xTexto"],
1970
+ ["compra.xNEmp", "compra.xNEmp"],
1971
+ ["compra.xPed", "compra.xPed"],
1972
+ ["compra.xCont", "compra.xCont"]
1973
+ ];
1974
+ function elemento(p, nome) {
1975
+ if (p === undefined || ehWildcard2(p))
1976
+ return;
1977
+ if (ehElementParticle2(p))
1978
+ return p.e === nome ? p.t : undefined;
1979
+ for (const i of p.i) {
1980
+ const t = elemento(i, nome);
1981
+ if (t !== undefined)
1982
+ return t;
1983
+ }
1984
+ return;
1985
+ }
1986
+ function tipoEm(infNFe, caminho) {
1987
+ let t = infNFe;
1988
+ for (const nome of caminho.split(".")) {
1989
+ if (t === undefined || !ehComplexType2(t))
1990
+ return;
1991
+ t = elemento(t.c, nome);
1992
+ }
1993
+ return t === undefined || ehComplexType2(t) ? undefined : t;
1994
+ }
1995
+ var tiposPorPl = new WeakMap;
1996
+ function tiposDoPl(infNFe) {
1997
+ let m = tiposPorPl.get(infNFe);
1998
+ if (m === undefined) {
1999
+ const novo = new Map;
2000
+ for (const [entrada, xml] of CAMPOS) {
2001
+ const t = tipoEm(infNFe, xml);
2002
+ if (t !== undefined)
2003
+ novo.set(entrada, t);
2004
+ }
2005
+ m = novo;
2006
+ tiposPorPl.set(infNFe, m);
2007
+ }
2008
+ return m;
2009
+ }
2010
+ function valoresEm(raiz, caminho) {
2011
+ let atuais = [["", raiz]];
2012
+ for (const parte of caminho.split(".")) {
2013
+ const lista = parte.endsWith("[]");
2014
+ const chave = lista ? parte.slice(0, -2) : parte;
2015
+ const proximos = [];
2016
+ for (const [c, v] of atuais) {
2017
+ if (typeof v !== "object" || v === null)
2018
+ continue;
2019
+ const filho = v[chave];
2020
+ const base = c === "" ? chave : `${c}.${chave}`;
2021
+ if (!lista)
2022
+ proximos.push([base, filho]);
2023
+ else if (Array.isArray(filho))
2024
+ for (const [n, f] of filho.entries())
2025
+ proximos.push([`${base}[${n}]`, f]);
2026
+ }
2027
+ atuais = proximos;
2028
+ }
2029
+ return atuais;
2030
+ }
2031
+ function textosForaDoXml(valor, caminho, saida) {
2032
+ if (typeof valor === "string") {
2033
+ if (!textoXmlValido(valor))
2034
+ saida.push(caminho);
2035
+ } else if (Array.isArray(valor)) {
2036
+ for (const [n, v] of valor.entries())
2037
+ textosForaDoXml(v, `${caminho}[${n}]`, saida);
2038
+ } else if (typeof valor === "object" && valor !== null) {
2039
+ for (const [k, v] of Object.entries(valor))
2040
+ textosForaDoXml(v, caminho === "" ? k : `${caminho}.${k}`, saida);
2041
+ }
2042
+ }
2043
+ var CARACTERE_INVISIVEL = "caractere não aceito (símbolo ou caractere de controle)";
2044
+ var VISIVEL = /^[\p{L}\p{M}\p{N}\p{P}\p{S}]$/u;
2045
+ function caractereRecusado(tipo, valor) {
2046
+ for (const ch of new Set(valor)) {
2047
+ const saida = [];
2048
+ conferirTipoSimples(tipo, `A${ch}A`, "", saida);
2049
+ if (saida.some((o) => o.code === "padrao"))
2050
+ return ch;
2051
+ }
2052
+ return;
2053
+ }
2054
+ function mensagensDoTexto(tipo, valor, violadas) {
2055
+ if (violadas.length === 0)
2056
+ return [];
2057
+ if (valor.trim() === "")
2058
+ return ["não pode ficar em branco"];
2059
+ const tamanho = [...valor].length;
2060
+ const mensagens = new Set;
2061
+ for (const o of violadas) {
2062
+ if (o.code === "tamanho_maximo" && tipo.mx !== undefined)
2063
+ mensagens.add(`no máximo ${tipo.mx} caracteres (tem ${tamanho})`);
2064
+ else if (o.code === "tamanho_minimo" && tipo.mn !== undefined)
2065
+ mensagens.add(`no mínimo ${tipo.mn} caracteres (tem ${tamanho})`);
2066
+ else if (o.code === "tamanho" && tipo.l !== undefined)
2067
+ mensagens.add(`exatamente ${tipo.l} caracteres (tem ${tamanho})`);
2068
+ else if (o.code === "padrao") {
2069
+ const espaco = valor !== valor.trim();
2070
+ const ch = caractereRecusado(tipo, valor);
2071
+ if (espaco)
2072
+ mensagens.add("sem espaço no começo nem no fim");
2073
+ if (ch !== undefined)
2074
+ mensagens.add(VISIVEL.test(ch) ? `caractere não aceito: “${ch}”` : CARACTERE_INVISIVEL);
2075
+ if (!espaco && ch === undefined)
2076
+ mensagens.add("formato não aceito");
2077
+ } else
2078
+ mensagens.add("valor não aceito neste campo");
2079
+ }
2080
+ return [...mensagens];
2081
+ }
2082
+ function conferirTextosDaEntrada(entrada, infNFe, issues, substituidos = new Set) {
2083
+ const jaRecusados = new Set(issues.list.map((i) => i.caminho));
2084
+ const foraDoXml = [];
2085
+ textosForaDoXml(entrada, "", foraDoXml);
2086
+ for (const c of foraDoXml) {
2087
+ if (jaRecusados.has(c) || substituidos.has(c))
2088
+ continue;
2089
+ issues.add(c, "campo_invalido", CARACTERE_INVISIVEL);
2090
+ jaRecusados.add(c);
2091
+ }
2092
+ const tipos = tiposDoPl(infNFe);
2093
+ for (const [campo] of CAMPOS) {
2094
+ const tipo = tipos.get(campo);
2095
+ if (tipo === undefined)
2096
+ continue;
2097
+ for (const [caminho, valor] of valoresEm(entrada, campo)) {
2098
+ if (typeof valor !== "string" || jaRecusados.has(caminho) || substituidos.has(caminho))
2099
+ continue;
2100
+ const saida = [];
2101
+ conferirTipoSimples(tipo, valor, caminho, saida);
2102
+ for (const m of mensagensDoTexto(tipo, valor, saida))
2103
+ issues.add(caminho, "campo_invalido", m);
2104
+ }
2105
+ }
2106
+ }
2107
+
1914
2108
  // packages/nfe/src/build/tributos.ts
1915
2109
  function buildIpi(ctx, input, vOp, path) {
1916
2110
  const head = {
@@ -2058,7 +2252,7 @@ function buildIcmsUfDest(ctx, input, path) {
2058
2252
  // packages/nfe/src/build/build.ts
2059
2253
  var padrao;
2060
2254
  function calculadoraPadrao() {
2061
- padrao ??= ibsCbsCalculator();
2255
+ padrao ??= calculadoraIbsCbs();
2062
2256
  return padrao;
2063
2257
  }
2064
2258
  var NFE_NS3 = "http://www.portalfiscal.inf.br/nfe";
@@ -2068,7 +2262,7 @@ var MODES = Object.fromEntries(Object.entries(arredondamento_default.familias).m
2068
2262
  var SEM_GTIN = "SEM GTIN";
2069
2263
  var BRASILIA = -180;
2070
2264
  function diaBrasilia(d) {
2071
- return formatDh(d, BRASILIA).slice(0, 10);
2265
+ return formatarDh(d, BRASILIA).slice(0, 10);
2072
2266
  }
2073
2267
  function exigenciaRespTec(uf, ambiente, data) {
2074
2268
  const dia = diaBrasilia(data);
@@ -2087,29 +2281,29 @@ function exigenciaRespTec(uf, ambiente, data) {
2087
2281
  }
2088
2282
  async function hashCsrt(csrt, chave) {
2089
2283
  const d = await globalThis.crypto.subtle.digest("SHA-1", new TextEncoder().encode(csrt + chave));
2090
- return base64Encode2(new Uint8Array(d));
2284
+ return codificarBase642(new Uint8Array(d));
2091
2285
  }
2092
2286
  function documento(doc, path, issues) {
2093
2287
  if (doc.CNPJ !== undefined) {
2094
- const r = parseCnpj3(doc.CNPJ, { path: `${path}.CNPJ` });
2288
+ const r = lerCnpj3(doc.CNPJ, { caminho: `${path}.CNPJ` });
2095
2289
  if (!r.ok)
2096
- issues.list.push(r.error);
2097
- return { CNPJ: r.ok ? r.value : doc.CNPJ };
2290
+ issues.list.push(r.erro);
2291
+ return { CNPJ: r.ok ? r.valor : doc.CNPJ };
2098
2292
  }
2099
- const r = parseCpf(doc.CPF ?? "", { path: `${path}.CPF` });
2293
+ const r = lerCpf(doc.CPF ?? "", { caminho: `${path}.CPF` });
2100
2294
  if (!r.ok)
2101
- issues.list.push(r.error);
2102
- return { CPF: r.ok ? r.value : doc.CPF ?? "" };
2295
+ issues.list.push(r.erro);
2296
+ return { CPF: r.ok ? r.valor : doc.CPF ?? "" };
2103
2297
  }
2104
2298
  function ie(value, uf, path, issues, allowIsento) {
2105
2299
  if (value === undefined)
2106
2300
  return;
2107
- const r = parseIe(value, uf, { path, allowIsento });
2301
+ const r = lerIe(value, uf, { caminho: path, aceitarIsento: allowIsento });
2108
2302
  if (!r.ok) {
2109
- issues.list.push(r.error);
2303
+ issues.list.push(r.erro);
2110
2304
  return value;
2111
2305
  }
2112
- return r.value.value;
2306
+ return r.valor.valor;
2113
2307
  }
2114
2308
  function endereco(e) {
2115
2309
  return {
@@ -2129,9 +2323,9 @@ function isExterior(e) {
2129
2323
  }
2130
2324
  function gerarChave(parts, cNFInformado, random, issues) {
2131
2325
  const tentar = (cNF) => {
2132
- const chave = buildChaveAcesso({ ...parts, cNF });
2133
- const r = parseChaveAcesso(chave, { emissao: true, path: "chave" });
2134
- return r.ok ? { chave, ok: true } : { chave, ok: false, issue: r.error };
2326
+ const chave = montarChaveAcesso({ ...parts, cNF });
2327
+ const r = lerChaveAcesso(chave, { emissao: true, caminho: "chave" });
2328
+ return r.ok ? { chave, ok: true } : { chave, ok: false, issue: r.erro };
2135
2329
  };
2136
2330
  if (cNFInformado !== undefined) {
2137
2331
  if (!/^\d{8}$/.test(cNFInformado)) {
@@ -2143,9 +2337,9 @@ function gerarChave(parts, cNFInformado, random, issues) {
2143
2337
  const doCnf = r.issue.code === "chave_cnf_invalido";
2144
2338
  issues.list.push({
2145
2339
  ...r.issue,
2146
- path: doCnf ? "cNF" : r.issue.path,
2340
+ caminho: doCnf ? "cNF" : r.issue.caminho,
2147
2341
  code: "chave_invalida",
2148
- message: `${r.issue.message} (${r.issue.code})`,
2342
+ mensagem: `${r.issue.mensagem} (${r.issue.code})`,
2149
2343
  origem: doCnf ? "entrada" : "montagem"
2150
2344
  });
2151
2345
  }
@@ -2162,7 +2356,7 @@ function gerarChave(parts, cNFInformado, random, issues) {
2162
2356
  issues.list.push({
2163
2357
  ...r.issue,
2164
2358
  code: "chave_invalida",
2165
- message: `${r.issue.message} (${r.issue.code})`,
2359
+ mensagem: `${r.issue.mensagem} (${r.issue.code})`,
2166
2360
  origem: "montagem"
2167
2361
  });
2168
2362
  return;
@@ -2173,10 +2367,10 @@ function gerarChave(parts, cNFInformado, random, issues) {
2173
2367
  }
2174
2368
  function referencia(ref, path, issues) {
2175
2369
  const chave = (c, p) => {
2176
- const r = parseChaveAcesso(c, { path: p });
2370
+ const r = lerChaveAcesso(c, { caminho: p });
2177
2371
  if (!r.ok)
2178
- issues.list.push(r.error);
2179
- return r.ok ? r.value.chave : c;
2372
+ issues.list.push(r.erro);
2373
+ return r.ok ? r.valor.chave : c;
2180
2374
  };
2181
2375
  if ("refNFe" in ref)
2182
2376
  return { refNFe: chave(ref.refNFe, `${path}.refNFe`) };
@@ -2196,7 +2390,7 @@ function referencia(ref, path, issues) {
2196
2390
  const nfp = ref.refNFP;
2197
2391
  if (nfp.mod === "04") {
2198
2392
  const porUf = produtor_rural_default.refNFP.ufs;
2199
- const cUfSigla = Object.keys(porUf).find((k) => ufBySigla2(k)?.cUF === nfp.cUF);
2393
+ const cUfSigla = Object.keys(porUf).find((k) => ufPorSigla2(k)?.cUF === nfp.cUF);
2200
2394
  const vedadaDesde = cUfSigla ? porUf[cUfSigla]?.vedadaDesde ?? "" : produtor_rural_default.refNFP.modelo04.vedadaDesde;
2201
2395
  if (nfp.AAMM >= vedadaDesde) {
2202
2396
  issues.add(`${path}.refNFP.AAMM`, "referencia_vedada", `nota de produtor modelo 04 emitida em ${nfp.AAMM}, depois do fim do modelo (${vedadaDesde}; ${produtor_rural_default.refNFP.modelo04.fonte})`);
@@ -2215,25 +2409,16 @@ function referencia(ref, path, issues) {
2215
2409
  }
2216
2410
  };
2217
2411
  }
2218
- function textoXmlValido(texto) {
2219
- for (const ch of texto) {
2220
- const c = ch.codePointAt(0) ?? 0;
2221
- const ok = c === 9 || c === 10 || c === 13 || c >= 32 && c <= 55295 || c >= 57344 && c <= 65533 || c >= 65536 && c <= 1114111;
2222
- if (!ok)
2223
- return false;
2224
- }
2225
- return true;
2226
- }
2227
- function textosForaDoXml(value, path, issues) {
2412
+ function textosForaDoXml2(value, path, issues) {
2228
2413
  if (typeof value === "string") {
2229
2414
  if (!textoXmlValido(value))
2230
2415
  issues.montagem(path, "campo_invalido", "texto com caractere não permitido em XML");
2231
2416
  } else if (Array.isArray(value)) {
2232
2417
  for (const [n, v] of value.entries())
2233
- textosForaDoXml(v, `${path}[${n}]`, issues);
2418
+ textosForaDoXml2(v, `${path}[${n}]`, issues);
2234
2419
  } else if (typeof value === "object" && value !== null) {
2235
2420
  for (const [k, v] of Object.entries(value))
2236
- textosForaDoXml(v, `${path}.${k}`, issues);
2421
+ textosForaDoXml2(v, `${path}.${k}`, issues);
2237
2422
  }
2238
2423
  }
2239
2424
  function montarItem(ctx, item, n, normal) {
@@ -2415,11 +2600,11 @@ function montarItem(ctx, item, n, normal) {
2415
2600
  if (item.obsItem !== undefined)
2416
2601
  det.obsItem = item.obsItem;
2417
2602
  if (item.DFeReferenciado !== undefined) {
2418
- const r = parseChaveAcesso(item.DFeReferenciado.chaveAcesso, { path: `${path}.DFeReferenciado.chaveAcesso` });
2603
+ const r = lerChaveAcesso(item.DFeReferenciado.chaveAcesso, { caminho: `${path}.DFeReferenciado.chaveAcesso` });
2419
2604
  if (!r.ok)
2420
- ctx.issues.list.push(r.error);
2605
+ ctx.issues.list.push(r.erro);
2421
2606
  det.DFeReferenciado = clean({
2422
- chaveAcesso: r.ok ? r.value.chave : item.DFeReferenciado.chaveAcesso,
2607
+ chaveAcesso: r.ok ? r.valor.chave : item.DFeReferenciado.chaveAcesso,
2423
2608
  nItem: item.DFeReferenciado.nItem === undefined ? undefined : String(item.DFeReferenciado.nItem)
2424
2609
  });
2425
2610
  }
@@ -2443,36 +2628,36 @@ function composicao(m, incluirProd) {
2443
2628
  }
2444
2629
  return total;
2445
2630
  }
2446
- async function buildNfe(input, options) {
2631
+ async function montarNfe(entrada, opcoes) {
2447
2632
  const issues = new Issues;
2448
- const finNFeIn = input.finNFe ?? "1";
2449
- const mod = input.modelo ?? "55";
2633
+ const finNFeIn = entrada.finNFe ?? "1";
2634
+ const mod = entrada.modelo ?? "55";
2450
2635
  if (mod !== "55" && mod !== "65") {
2451
2636
  issues.add("modelo", "modelo_nao_suportado", `modelo ${String(mod)}: o builder monta NF-e (55) e NFC-e (65)`);
2452
- return { ok: false, issues: issues.classificadas };
2637
+ return { ok: false, ocorrencias: issues.classificadas };
2453
2638
  }
2454
2639
  const nfce = mod === "65";
2455
- const indPres = input.indPres ?? (nfce ? "1" : finNFeIn === "2" || finNFeIn === "3" ? "0" : "9");
2456
- const indFinal = input.indFinal ?? (nfce || input.destinatario?.indIEDest === "9" ? "1" : "0");
2457
- const ctx = new Ctx(issues, { ...MODES, ...options.arredondamento }, finNFeIn !== "2" && finNFeIn !== "3");
2458
- const pRedutorGov = input.gCompraGov && ctx.req(input.gCompraGov.pRedutor, "gCompraGov.pRedutor", D0302A04);
2459
- const emitUf = input.emitente.endereco.UF;
2460
- if (!isUf2(emitUf)) {
2640
+ const indPres = entrada.indPres ?? (nfce ? "1" : finNFeIn === "2" || finNFeIn === "3" ? "0" : "9");
2641
+ const indFinal = entrada.indFinal ?? (nfce || entrada.destinatario?.indIEDest === "9" ? "1" : "0");
2642
+ const ctx = new Ctx(issues, { ...MODES, ...opcoes.arredondamento }, finNFeIn !== "2" && finNFeIn !== "3");
2643
+ const pRedutorGov = entrada.gCompraGov && ctx.req(entrada.gCompraGov.pRedutor, "gCompraGov.pRedutor", D0302A04);
2644
+ const emitUf = entrada.emitente.endereco.UF;
2645
+ if (!ehUf2(emitUf)) {
2461
2646
  issues.add("emitente.endereco.UF", "campo_invalido", "UF do emitente inválida");
2462
- return { ok: false, issues: issues.classificadas };
2647
+ return { ok: false, ocorrencias: issues.classificadas };
2463
2648
  }
2464
- const cUF = ufBySigla2(emitUf)?.cUF ?? "";
2465
- const offset = options.offsetMinutes ?? offsetDaUf(emitUf);
2466
- const agora = options.time.emissao.now();
2467
- const fatoGerador = options.time.fatoGerador.now();
2468
- const dhEmi = formatDh(agora, offset);
2649
+ const cUF = ufPorSigla2(emitUf)?.cUF ?? "";
2650
+ const offset = opcoes.deslocamentoMin ?? deslocamentoDaUf(emitUf);
2651
+ const agora = opcoes.tempo.emissao.agora();
2652
+ const fatoGerador = opcoes.tempo.fatoGerador.agora();
2653
+ const dhEmi = formatarDh(agora, offset);
2469
2654
  const aamm = dhEmi.slice(2, 4) + dhEmi.slice(5, 7);
2470
- const tpAmb = tpAmbOf2(options.ambiente);
2471
- const pl = escolherPl(options.ambiente, fixedClock2(agora));
2472
- const e = input.emitente;
2655
+ const tpAmb = tpAmbDoAmbiente2(opcoes.ambiente);
2656
+ const pl = escolherPl(opcoes.ambiente, relogioFixo2(agora));
2657
+ const e = entrada.emitente;
2473
2658
  const emitDoc = documento(e, "emitente", issues);
2474
- const serie = Number(input.serie);
2475
- const nNF = Number(input.nNF);
2659
+ const serie = Number(entrada.serie);
2660
+ const nNF = Number(entrada.nNF);
2476
2661
  if (!Number.isInteger(serie) || serie < 0 || serie > 999)
2477
2662
  issues.add("serie", "serie_invalida", "série de 0 a 999");
2478
2663
  if (!Number.isInteger(nNF) || nNF < 1 || nNF > 999999999)
@@ -2496,7 +2681,7 @@ async function buildNfe(input, options) {
2496
2681
  CRT: e.CRT,
2497
2682
  ISUFEmit: e.ISUFEmit
2498
2683
  });
2499
- const d = input.destinatario;
2684
+ const d = entrada.destinatario;
2500
2685
  let dest;
2501
2686
  let destUf;
2502
2687
  if (d === undefined) {
@@ -2526,7 +2711,7 @@ async function buildNfe(input, options) {
2526
2711
  const destIe = d.IE !== undefined && destUf !== undefined && destUf !== "EX" ? ie(d.IE, destUf, "destinatario.IE", issues, false) : d.IE;
2527
2712
  dest = clean({
2528
2713
  ...docDest,
2529
- xNome: options.ambiente === "homologacao" ? XNOME_HOMOLOGACAO : d.xNome,
2714
+ xNome: opcoes.ambiente === "homologacao" ? XNOME_HOMOLOGACAO : d.xNome,
2530
2715
  enderDest,
2531
2716
  indIEDest: d.indIEDest,
2532
2717
  IE: destIe,
@@ -2535,7 +2720,7 @@ async function buildNfe(input, options) {
2535
2720
  email: d.email
2536
2721
  });
2537
2722
  }
2538
- const cont = input.contingencia;
2723
+ const cont = entrada.contingencia;
2539
2724
  const tpEmis = cont?.tpEmis ?? "1";
2540
2725
  if (cont !== undefined) {
2541
2726
  if (cont.xJust.length < 15 || cont.xJust.length > 256) {
@@ -2551,19 +2736,19 @@ async function buildNfe(input, options) {
2551
2736
  issues.add("contingencia.tpEmis", "contingencia_invalida", "a NFC-e não é autorizada pela SVC; a contingência dela é off-line, tpEmis 9 (B22-70, rejeição 783)");
2552
2737
  }
2553
2738
  }
2554
- const idDest = input.idDest ?? (nfce ? "1" : destUf === "EX" ? "3" : destUf !== undefined && destUf !== emitUf ? "2" : "1");
2555
- const tpImp = input.tpImp ?? (nfce ? "4" : "1");
2556
- conferirDestinatario(input, {
2739
+ const idDest = entrada.idDest ?? (nfce ? "1" : destUf === "EX" ? "3" : destUf !== undefined && destUf !== emitUf ? "2" : "1");
2740
+ const tpImp = entrada.tpImp ?? (nfce ? "4" : "1");
2741
+ conferirDestinatario(entrada, {
2557
2742
  mod,
2558
- tpNF: input.tpNF,
2743
+ tpNF: entrada.tpNF,
2559
2744
  idDest,
2560
- idDestInformado: input.idDest !== undefined,
2745
+ idDestInformado: entrada.idDest !== undefined,
2561
2746
  indFinal,
2562
- producao: options.ambiente === "producao"
2747
+ producao: opcoes.ambiente === "producao"
2563
2748
  }, issues);
2564
2749
  if (nfce) {
2565
- conferirNfce(input, {
2566
- tpNF: input.tpNF,
2750
+ conferirNfce(entrada, {
2751
+ tpNF: entrada.tpNF,
2567
2752
  idDest,
2568
2753
  tpImp,
2569
2754
  finNFe: finNFeIn,
@@ -2573,7 +2758,7 @@ async function buildNfe(input, options) {
2573
2758
  } else if (tpImp === "4" || tpImp === "5") {
2574
2759
  issues.add("tpImp", "campo_invalido", "tpImp 4 e 5 (DANFC-e) são da NFC-e (B21-20, rejeição 710)");
2575
2760
  }
2576
- const qr = options.qrCode ?? { versao: "3" };
2761
+ const qr = opcoes.qrCode ?? { versao: "3" };
2577
2762
  if (nfce && qr.versao === "2") {
2578
2763
  if (!/^\d{1,6}$/.test(qr.idCSC) || Number(qr.idCSC) === 0) {
2579
2764
  issues.montagem("qrCode.idCSC", "qrcode_invalido", "idCSC tem de 1 a 6 algarismos, diferente de zero (Manual do DANFE NFC-e 6.0, 4.6)");
@@ -2585,23 +2770,23 @@ async function buildNfe(input, options) {
2585
2770
  issues.montagem("qrCode.versao", "qrcode_invalido", "emitente pessoa física usa o QR Code versão 3 (NT 2025.001, ZX02-222, rejeição 444)");
2586
2771
  }
2587
2772
  }
2588
- const random = options.random ?? ((b) => globalThis.crypto.getRandomValues(b));
2773
+ const random = opcoes.aleatorio ?? ((b) => globalThis.crypto.getRandomValues(b));
2589
2774
  const emitente14 = "CNPJ" in emitDoc ? emitDoc.CNPJ : emitDoc.CPF;
2590
- const gerada = issues.empty ? gerarChave({ cUF, aamm, emitente: emitente14, mod, serie: String(serie), nNF: String(nNF), tpEmis }, input.cNF, random, issues) : undefined;
2775
+ const gerada = issues.empty ? gerarChave({ cUF, aamm, emitente: emitente14, mod, serie: String(serie), nNF: String(nNF), tpEmis }, entrada.cNF, random, issues) : undefined;
2591
2776
  const chave = gerada?.chave ?? "0".repeat(44);
2592
2777
  const cNF = gerada?.cNF ?? "00000000";
2593
2778
  const cDV = chave.slice(43);
2594
- if (input.itens.length === 0 || input.itens.length > 990) {
2779
+ if (entrada.itens.length === 0 || entrada.itens.length > 990) {
2595
2780
  issues.add("itens", "itens_limite", "a NF-e tem de 1 a 990 itens");
2596
2781
  }
2597
- const itens = input.itens.map((it, n) => montarItem(ctx, it, n, finNFeIn === "1"));
2782
+ const itens = entrada.itens.map((it, n) => montarItem(ctx, it, n, finNFeIn === "1"));
2598
2783
  const primeiro = itens[0];
2599
- if (nfce && options.ambiente === "homologacao" && primeiro !== undefined) {
2784
+ if (nfce && opcoes.ambiente === "homologacao" && primeiro !== undefined) {
2600
2785
  primeiro.det.prod.xProd = XPROD_HOMOLOGACAO_NFCE;
2601
2786
  }
2602
- const classificados = input.itens.map((it, n) => ({ it, n })).filter(({ it }) => it.impostos.ibsCbs?.classificacao !== undefined);
2787
+ const classificados = entrada.itens.map((it, n) => ({ it, n })).filter(({ it }) => it.impostos.ibsCbs?.classificacao !== undefined);
2603
2788
  if (classificados.length > 0) {
2604
- const calculadora = options.ibsCbs ?? calculadoraPadrao();
2789
+ const calculadora = opcoes.ibsCbs ?? calculadoraPadrao();
2605
2790
  const reqs = classificados.map(({ it, n }) => {
2606
2791
  const c = it.impostos.ibsCbs?.classificacao;
2607
2792
  const m = itens[n];
@@ -2637,23 +2822,23 @@ async function buildNfe(input, options) {
2637
2822
  vFCPUFDest: m.v.vFCPUFDest
2638
2823
  };
2639
2824
  });
2640
- const destino = input.entrega !== undefined ? { UF: input.entrega.UF, cMun: input.entrega.cMun } : d?.endereco !== undefined ? isExterior(d.endereco) ? { UF: "EX", cMun: "9999999" } : { UF: d.endereco.UF, cMun: d.endereco.cMun } : undefined;
2641
- const compra = input.gCompraGov;
2825
+ const destino = entrada.entrega !== undefined ? { UF: entrada.entrega.UF, cMun: entrada.entrega.cMun } : d?.endereco !== undefined ? isExterior(d.endereco) ? { UF: "EX", cMun: "9999999" } : { UF: d.endereco.UF, cMun: d.endereco.cMun } : undefined;
2826
+ const compra = entrada.gCompraGov;
2642
2827
  const resp = await calculadora.calcular({
2643
2828
  nota: {
2644
2829
  fatoGerador,
2645
2830
  emissao: agora,
2646
- ambiente: options.ambiente,
2831
+ ambiente: opcoes.ambiente,
2647
2832
  mod,
2648
- tpNF: input.tpNF,
2833
+ tpNF: entrada.tpNF,
2649
2834
  finNFe: finNFeIn,
2650
- ...input.tpNFDebito ? { tpNFDebito: input.tpNFDebito } : {},
2651
- ...input.tpNFCredito ? { tpNFCredito: input.tpNFCredito } : {},
2835
+ ...entrada.tpNFDebito ? { tpNFDebito: entrada.tpNFDebito } : {},
2836
+ ...entrada.tpNFCredito ? { tpNFCredito: entrada.tpNFCredito } : {},
2652
2837
  indFinal,
2653
2838
  indPres,
2654
2839
  emitente: { UF: emitUf, cMun: e.endereco.cMun, CRT: e.CRT },
2655
2840
  ...destino ? { destino } : {},
2656
- ...input.cMunFGIBS ? { cMunFGIBS: input.cMunFGIBS } : {},
2841
+ ...entrada.cMunFGIBS ? { cMunFGIBS: entrada.cMunFGIBS } : {},
2657
2842
  ...compra && pRedutorGov ? {
2658
2843
  compraGov: {
2659
2844
  tpEnteGov: compra.tpEnteGov,
@@ -2664,7 +2849,7 @@ async function buildNfe(input, options) {
2664
2849
  },
2665
2850
  itens: reqs
2666
2851
  });
2667
- issues.addAll(resp.issues ?? [], "montagem");
2852
+ issues.addAll(resp.ocorrencias ?? [], "montagem");
2668
2853
  for (const { n } of classificados) {
2669
2854
  const g = resp.itens.find((x) => x.nItem === n + 1);
2670
2855
  if (g === undefined) {
@@ -2678,7 +2863,7 @@ async function buildNfe(input, options) {
2678
2863
  const imp = m.det.imposto;
2679
2864
  const ib = `itens[${n}].impostos.ibsCbs`;
2680
2865
  const is = `itens[${n}].impostos.is`;
2681
- const ibsDaCalculadora = input.itens[n]?.impostos.ibsCbs?.grupo === undefined;
2866
+ const ibsDaCalculadora = entrada.itens[n]?.impostos.ibsCbs?.grupo === undefined;
2682
2867
  const antes = issues.list.length;
2683
2868
  decimaisInvalidos(imp.IBSCBS, ib, issues);
2684
2869
  if (ibsDaCalculadora)
@@ -2691,8 +2876,10 @@ async function buildNfe(input, options) {
2691
2876
  grupoInvalido(TISCt, "IS", imp.IS, is, issues);
2692
2877
  }
2693
2878
  });
2879
+ const substituidos = opcoes.ambiente === "homologacao" ? ["destinatario.xNome", ...nfce ? ["itens[0].produto.xProd"] : []] : [];
2880
+ conferirTextosDaEntrada(entrada, pl.infNFe, issues, new Set(substituidos));
2694
2881
  if (!issues.empty)
2695
- return { ok: false, issues: issues.classificadas };
2882
+ return { ok: false, ocorrencias: issues.classificadas };
2696
2883
  const gruposIbsCbs = itens.map((m) => m.det.imposto.IBSCBS).filter((g) => g !== undefined);
2697
2884
  const somaTributosNoItem = diaBrasilia(fatoGerador) >= reforma_default.vItemSomaTributosDesde;
2698
2885
  let vNFTot = Decimal.ZERO;
@@ -2789,39 +2976,39 @@ async function buildNfe(input, options) {
2789
2976
  const ide = clean({
2790
2977
  cUF,
2791
2978
  cNF,
2792
- natOp: input.natOp,
2979
+ natOp: entrada.natOp,
2793
2980
  mod,
2794
2981
  serie: String(serie),
2795
2982
  nNF: String(nNF),
2796
2983
  dhEmi,
2797
- dhSaiEnt: input.dhSaiEnt === undefined ? undefined : formatDh(input.dhSaiEnt, offset),
2798
- dPrevEntrega: input.dPrevEntrega,
2799
- tpNF: input.tpNF,
2984
+ dhSaiEnt: entrada.dhSaiEnt === undefined ? undefined : formatarDh(entrada.dhSaiEnt, offset),
2985
+ dPrevEntrega: entrada.dPrevEntrega,
2986
+ tpNF: entrada.tpNF,
2800
2987
  idDest,
2801
- cMunFG: input.cMunFG ?? e.endereco.cMun,
2802
- cMunFGIBS: input.cMunFGIBS,
2988
+ cMunFG: entrada.cMunFG ?? e.endereco.cMun,
2989
+ cMunFGIBS: entrada.cMunFGIBS,
2803
2990
  tpImp,
2804
2991
  tpEmis,
2805
2992
  cDV,
2806
2993
  tpAmb,
2807
2994
  finNFe,
2808
- tpNFDebito: input.tpNFDebito,
2809
- tpNFCredito: input.tpNFCredito,
2995
+ tpNFDebito: entrada.tpNFDebito,
2996
+ tpNFCredito: entrada.tpNFCredito,
2810
2997
  indFinal,
2811
2998
  indPres,
2812
- indIntermed: input.indIntermed ?? (["2", "3", "4", "9"].includes(indPres) ? "0" : undefined),
2999
+ indIntermed: entrada.indIntermed ?? (["2", "3", "4", "9"].includes(indPres) ? "0" : undefined),
2813
3000
  procEmi: "0",
2814
- verProc: options.verProc ?? formatarVerProc("sinete", VERSAO_PACOTE),
2815
- dhCont: cont === undefined ? undefined : formatDh(cont.dhCont, offset),
3001
+ verProc: opcoes.verProc ?? formatarVerProc("sinete", VERSAO_PACOTE),
3002
+ dhCont: cont === undefined ? undefined : formatarDh(cont.dhCont, offset),
2816
3003
  xJust: cont?.xJust,
2817
- NFref: input.referenciadas?.map((r, n) => referencia(r, `referenciadas[${n}]`, issues)),
2818
- gCompraGov: input.gCompraGov === undefined ? undefined : clean({
2819
- tpEnteGov: input.gCompraGov.tpEnteGov,
3004
+ NFref: entrada.referenciadas?.map((r, n) => referencia(r, `referenciadas[${n}]`, issues)),
3005
+ gCompraGov: entrada.gCompraGov === undefined ? undefined : clean({
3006
+ tpEnteGov: entrada.gCompraGov.tpEnteGov,
2820
3007
  pRedutor: ctx.s(pRedutorGov ?? Decimal.ZERO, D0302A04),
2821
- tpOperGov: input.gCompraGov.tpOperGov,
2822
- refDFeAnt: input.gCompraGov.refDFeAnt
3008
+ tpOperGov: entrada.gCompraGov.tpOperGov,
3009
+ refDFeAnt: entrada.gCompraGov.refDFeAnt
2823
3010
  }),
2824
- gPagAntecipado: input.gPagAntecipado === undefined ? undefined : { refNFe: [...input.gPagAntecipado] }
3011
+ gPagAntecipado: entrada.gPagAntecipado === undefined ? undefined : { refNFe: [...entrada.gPagAntecipado] }
2825
3012
  });
2826
3013
  const local = (l, path) => l === undefined ? undefined : clean({
2827
3014
  ...documento(l, path, issues),
@@ -2832,10 +3019,10 @@ async function buildNfe(input, options) {
2832
3019
  email: l.email,
2833
3020
  IE: l.IE
2834
3021
  });
2835
- if ((input.autXML?.length ?? 0) > 10)
3022
+ if ((entrada.autXML?.length ?? 0) > 10)
2836
3023
  issues.add("autXML", "campo_invalido", "no máximo 10 autorizados");
2837
- const autXML = input.autXML?.map((a, n) => documento(a, `autXML[${n}]`, issues));
2838
- const tr = input.transporte;
3024
+ const autXML = entrada.autXML?.map((a, n) => documento(a, `autXML[${n}]`, issues));
3025
+ const tr = entrada.transporte;
2839
3026
  const transp = { modFrete: tr?.modFrete ?? "9" };
2840
3027
  if (tr?.transportador !== undefined) {
2841
3028
  const t = tr.transportador;
@@ -2876,8 +3063,8 @@ async function buildNfe(input, options) {
2876
3063
  }));
2877
3064
  }
2878
3065
  let cobr;
2879
- if (input.cobranca !== undefined) {
2880
- const c = input.cobranca;
3066
+ if (entrada.cobranca !== undefined) {
3067
+ const c = entrada.cobranca;
2881
3068
  cobr = {};
2882
3069
  if (c.fatura !== undefined) {
2883
3070
  const f = c.fatura;
@@ -2901,10 +3088,10 @@ async function buildNfe(input, options) {
2901
3088
  }));
2902
3089
  }
2903
3090
  }
2904
- const pagIn = input.pagamento ?? { detPag: [{ tPag: "90", vPag: "0" }] };
2905
- const igualTotal = options.pagamentoIgualTotal === true;
3091
+ const pagIn = entrada.pagamento ?? { detPag: [{ tPag: "90", vPag: "0" }] };
3092
+ const igualTotal = opcoes.pagamentoIgualTotal === true;
2906
3093
  if (igualTotal) {
2907
- const unico = input.pagamento?.detPag.length === 1 ? input.pagamento.detPag[0] : undefined;
3094
+ const unico = entrada.pagamento?.detPag.length === 1 ? entrada.pagamento.detPag[0] : undefined;
2908
3095
  if (unico === undefined) {
2909
3096
  issues.add("pagamento.detPag", "pagamento_igual_total", "pagamentoIgualTotal pede exatamente um detPag");
2910
3097
  } else if (unico.tPag === "90") {
@@ -2924,13 +3111,13 @@ async function buildNfe(input, options) {
2924
3111
  })),
2925
3112
  vTroco: ctx.so(ctx.opt(pagIn.vTroco, "pagamento.vTroco", D1302), D1302)
2926
3113
  });
2927
- if (nfce && input.pagamento !== undefined && input.pagamento.detPag.length > 0 && issues.empty) {
3114
+ if (nfce && entrada.pagamento !== undefined && entrada.pagamento.detPag.length > 0 && issues.empty) {
2928
3115
  pagamentoNfce(pag, vNF, issues);
2929
3116
  }
2930
3117
  if (nfce && vNF.gt(Decimal.of(NFCE_LIMITE_SEM_DESTINATARIO)) && dest === undefined) {
2931
3118
  issues.add("destinatario", "campo_obrigatorio", `NFC-e acima de R$ ${NFCE_LIMITE_SEM_DESTINATARIO} identifica o destinatário (W16-40, rejeição 750)`);
2932
3119
  }
2933
- const ia = input.informacoesAdicionais;
3120
+ const ia = entrada.informacoesAdicionais;
2934
3121
  const infAdic = ia === undefined || Object.values(ia).every((x) => x === undefined) ? undefined : clean({
2935
3122
  infAdFisco: ia.infAdFisco,
2936
3123
  infCpl: ia.infCpl,
@@ -2938,19 +3125,19 @@ async function buildNfe(input, options) {
2938
3125
  obsFisco: ia.obsFisco,
2939
3126
  procRef: ia.procRef
2940
3127
  });
2941
- const exig = { ...exigenciaRespTec(emitUf, options.ambiente, agora), ...options.exigencias };
2942
- const rt = input.respTec ?? options.respTec;
3128
+ const exig = { ...exigenciaRespTec(emitUf, opcoes.ambiente, agora), ...opcoes.exigencias };
3129
+ const rt = entrada.respTec ?? opcoes.respTec;
2943
3130
  let infRespTec;
2944
3131
  if (rt === undefined) {
2945
3132
  if (exig.infRespTec === "obrigatorio") {
2946
3133
  issues.add("respTec", "resp_tec_obrigatorio", `a UF ${emitUf} exige o responsável técnico (rejeição 972)`);
2947
3134
  }
2948
3135
  } else {
2949
- const cnpjRt = parseCnpj3(rt.CNPJ, { path: "respTec.CNPJ" });
3136
+ const cnpjRt = lerCnpj3(rt.CNPJ, { caminho: "respTec.CNPJ" });
2950
3137
  if (!cnpjRt.ok)
2951
- issues.list.push(cnpjRt.error);
3138
+ issues.list.push(cnpjRt.erro);
2952
3139
  infRespTec = {
2953
- CNPJ: cnpjRt.ok ? cnpjRt.value : rt.CNPJ,
3140
+ CNPJ: cnpjRt.ok ? cnpjRt.valor : rt.CNPJ,
2954
3141
  xContato: rt.xContato,
2955
3142
  email: rt.email,
2956
3143
  fone: digits(rt.fone)
@@ -2968,66 +3155,69 @@ async function buildNfe(input, options) {
2968
3155
  ide,
2969
3156
  emit,
2970
3157
  dest,
2971
- retirada: local(input.retirada, "retirada"),
2972
- entrega: local(input.entrega, "entrega"),
3158
+ retirada: local(entrada.retirada, "retirada"),
3159
+ entrega: local(entrada.entrega, "entrega"),
2973
3160
  autXML,
2974
3161
  det: itens.map((m) => m.det),
2975
3162
  total,
2976
3163
  transp,
2977
3164
  cobr,
2978
3165
  pag,
2979
- infIntermed: input.infIntermed,
3166
+ infIntermed: entrada.infIntermed,
2980
3167
  infAdic,
2981
- exporta: input.exporta,
2982
- compra: input.compra,
2983
- cana: input.cana,
3168
+ exporta: entrada.exporta,
3169
+ compra: entrada.compra,
3170
+ cana: entrada.cana,
2984
3171
  infRespTec,
2985
- agropecuario: input.agropecuario
3172
+ agropecuario: entrada.agropecuario
2986
3173
  });
2987
- cstComIsento(input, idDest, issues);
2988
- vencimentos(input, { dhEmi, instante: agora }, issues);
3174
+ cstComIsento(entrada, idDest, issues);
3175
+ vencimentos(entrada, { dhEmi, instante: agora }, issues);
2989
3176
  camposForaDoPl(pl.infNFe, inf, "infNFe", pl.vigencia.pl, issues);
2990
- textosForaDoXml(inf, "infNFe", issues);
3177
+ textosForaDoXml2(inf, "infNFe", issues);
2991
3178
  if (!issues.empty)
2992
- return { ok: false, issues: issues.classificadas };
3179
+ return { ok: false, ocorrencias: issues.classificadas };
2993
3180
  let xml;
2994
3181
  try {
2995
- xml = `<NFe xmlns="${NFE_NS3}">${serialize2(pl.infNFe, "infNFe", inf, NFE_NS3)}</NFe>`;
3182
+ xml = `<NFe xmlns="${NFE_NS3}">${serializar2(pl.infNFe, "infNFe", inf, NFE_NS3)}</NFe>`;
2996
3183
  } catch (e) {
2997
- if (!(e instanceof SerializeError))
3184
+ if (!(e instanceof ErroSerializacao))
2998
3185
  throw e;
2999
- return { ok: false, issues: [{ path: e.path, code: "schema", message: e.message, origem: "montagem" }] };
3186
+ return {
3187
+ ok: false,
3188
+ ocorrencias: [{ caminho: e.caminho, code: "schema", mensagem: e.message, origem: "montagem" }]
3189
+ };
3000
3190
  }
3001
- const doc = parseXml3(xml);
3002
- const infEl = firstChild3(doc.root, "infNFe", NFE_NS3);
3003
- const schemaIssues = infEl === undefined ? [] : validate3(pl.infNFe, infEl);
3191
+ const doc = lerXml3(xml);
3192
+ const infEl = primeiroFilho3(doc.raiz, "infNFe", NFE_NS3);
3193
+ const schemaIssues = infEl === undefined ? [] : validar3(pl.infNFe, infEl);
3004
3194
  if (schemaIssues.length > 0) {
3005
3195
  return {
3006
3196
  ok: false,
3007
- issues: schemaIssues.map((i) => ({
3008
- path: i.path,
3197
+ ocorrencias: schemaIssues.map((i) => ({
3198
+ caminho: i.caminho,
3009
3199
  code: "schema",
3010
- message: `${i.code}: ${i.message}`,
3200
+ mensagem: `${i.code}: ${i.mensagem}`,
3011
3201
  origem: "montagem"
3012
3202
  }))
3013
3203
  };
3014
3204
  }
3015
3205
  let supl;
3016
3206
  if (nfce) {
3017
- const tabela = urlsNfce(emitUf, options.ambiente, diaBrasilia(agora));
3018
- const urlQr = options.urlQrCode ?? tabela.qrCode;
3019
- const urlChave = options.urlChave ?? tabela.urlChave;
3207
+ const tabela = urlsNfce(emitUf, opcoes.ambiente, diaBrasilia(agora));
3208
+ const urlQr = opcoes.urlQrCode ?? tabela.qrCode;
3209
+ const urlChave = opcoes.urlChave ?? tabela.urlChave;
3020
3210
  if (urlQr === undefined || !/^https?:\/\//i.test(urlQr)) {
3021
- issues.montagem("urlQrCode", "qrcode_invalido", `sem endereço completo do QR Code da NFC-e para ${emitUf} em ${options.ambiente}: informe urlQrCode (data/nfce-urls.json)`);
3211
+ issues.montagem("urlQrCode", "qrcode_invalido", `sem endereço completo do QR Code da NFC-e para ${emitUf} em ${opcoes.ambiente}: informe urlQrCode (data/nfce-urls.json)`);
3022
3212
  }
3023
3213
  if (urlChave === undefined) {
3024
3214
  issues.montagem("urlChave", "qrcode_invalido", `sem URL de consulta por chave da NFC-e para ${emitUf}: informe urlChave`);
3025
3215
  }
3026
3216
  if (urlQr === undefined || urlChave === undefined || !issues.empty)
3027
- return { ok: false, issues: issues.classificadas };
3217
+ return { ok: false, ocorrencias: issues.classificadas };
3028
3218
  const p = await parametrosQrCode({
3029
3219
  chave,
3030
- ambiente: options.ambiente,
3220
+ ambiente: opcoes.ambiente,
3031
3221
  tpEmis,
3032
3222
  dhEmi,
3033
3223
  vNF: inf.total.ICMSTot.vNF,
@@ -3037,11 +3227,11 @@ async function buildNfe(input, options) {
3037
3227
  supl = { versao: qr.versao, urlChave, base: `${urlQr.replace(/\?+$/, "")}?p=`, ...p };
3038
3228
  const suplIssues = conferirSupl(inserirSupl({ xml, nfce: supl }, supl.assinar ? ASSINATURA_2048 : undefined));
3039
3229
  if (suplIssues.length > 0)
3040
- return { ok: false, issues: suplIssues };
3230
+ return { ok: false, ocorrencias: suplIssues };
3041
3231
  }
3042
3232
  return {
3043
3233
  ok: true,
3044
- value: {
3234
+ valor: {
3045
3235
  chave,
3046
3236
  id: `NFe${chave}`,
3047
3237
  cNF,
@@ -3056,22 +3246,27 @@ async function buildNfe(input, options) {
3056
3246
  }
3057
3247
  };
3058
3248
  }
3059
- var ASSINATURA_2048 = base64Encode2(new Uint8Array(256));
3249
+ var ASSINATURA_2048 = codificarBase642(new Uint8Array(256));
3060
3250
  function conferirSupl(xml) {
3061
- const el = firstChild3(parseXml3(xml).root, "infNFeSupl", NFE_NS3);
3062
- const erros = el === undefined ? [] : validate3(TNFe_infNFeSupl, el);
3063
- return erros.map((i) => ({ path: i.path, code: "schema", message: `${i.code}: ${i.message}`, origem: "montagem" }));
3251
+ const el = primeiroFilho3(lerXml3(xml).raiz, "infNFeSupl", NFE_NS3);
3252
+ const erros = el === undefined ? [] : validar3(TNFe_infNFeSupl, el);
3253
+ return erros.map((i) => ({
3254
+ caminho: i.caminho,
3255
+ code: "schema",
3256
+ mensagem: `${i.code}: ${i.mensagem}`,
3257
+ origem: "montagem"
3258
+ }));
3064
3259
  }
3065
3260
  var escapeXml = (s) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
3066
- async function assinaturaQrCode(built, signer) {
3067
- return built.nfce?.assinar === true ? assinarParametros(built.nfce.parametros, signer) : undefined;
3261
+ async function assinaturaQrCode(nota, assinador) {
3262
+ return nota.nfce?.assinar === true ? assinarParametros(nota.nfce.parametros, assinador) : undefined;
3068
3263
  }
3069
- function comQrCode(built, assinatura) {
3070
- const xml = inserirSupl(built, assinatura);
3264
+ function comQrCode(nota, assinatura) {
3265
+ const xml = inserirSupl(nota, assinatura);
3071
3266
  if (assinatura !== undefined) {
3072
3267
  const issues = conferirSupl(xml);
3073
3268
  if (issues.length > 0)
3074
- throw new ValidationError("o QR Code da NFC-e não passou no schema", issues);
3269
+ throw new ErroDeValidacao("o QR Code da NFC-e não passou no schema", issues);
3075
3270
  }
3076
3271
  return xml;
3077
3272
  }
@@ -3079,24 +3274,24 @@ function inserirSupl(built, assinatura) {
3079
3274
  const s = built.nfce;
3080
3275
  if (s === undefined) {
3081
3276
  if (assinatura !== undefined)
3082
- throw new ConfigError2("a NF-e (modelo 55) não tem QR Code");
3277
+ throw new ErroDeConfiguracao2("a NF-e (modelo 55) não tem QR Code");
3083
3278
  return built.xml;
3084
3279
  }
3085
3280
  if (s.assinar && assinatura === undefined) {
3086
- throw new ConfigError2("NFC-e em contingência off-line com QR Code versão 3 precisa da assinatura (ZX02-334, rejeição 474)");
3281
+ throw new ErroDeConfiguracao2("NFC-e em contingência off-line com QR Code versão 3 precisa da assinatura (ZX02-334, rejeição 474)");
3087
3282
  }
3088
3283
  if (!s.assinar && assinatura !== undefined) {
3089
- throw new ConfigError2("este QR Code não leva assinatura (ZX02-330, rejeição 445)");
3284
+ throw new ErroDeConfiguracao2("este QR Code não leva assinatura (ZX02-330, rejeição 445)");
3090
3285
  }
3091
3286
  const fim = "</NFe>";
3092
3287
  if (!built.xml.endsWith(fim))
3093
- throw new ConfigError2("NFC-e montada fora da forma esperada");
3288
+ throw new ErroDeConfiguracao2("NFC-e montada fora da forma esperada");
3094
3289
  const qrCode = `${s.base}${s.parametros}${assinatura === undefined ? "" : `|${assinatura}`}`;
3095
3290
  const supl = `<infNFeSupl><qrCode>${escapeXml(qrCode)}</qrCode><urlChave>${escapeXml(s.urlChave)}</urlChave></infNFeSupl>`;
3096
3291
  return built.xml.slice(0, -fim.length) + supl + fim;
3097
3292
  }
3098
- async function signNfe(built, signer) {
3099
- return signXml(comQrCode(built, await assinaturaQrCode(built, signer)), { id: built.id }, signer);
3293
+ async function assinarNfe(nota, assinador) {
3294
+ return assinarXml(comQrCode(nota, await assinaturaQrCode(nota, assinador)), { id: nota.id }, assinador);
3100
3295
  }
3101
3296
  // packages/nfe/src/model.ts
3102
3297
  var MotivoDesoneracaoIcms = {
@@ -3182,7 +3377,7 @@ var GRUPOS = [
3182
3377
  { padrao: /^infNFe\.infRespTec\b/, rotulo: "Responsável técnico" },
3183
3378
  { padrao: /^infNFe\.exporta\b/, rotulo: "Exportação" }
3184
3379
  ];
3185
- var CAMPOS = {
3380
+ var CAMPOS2 = {
3186
3381
  IE: "Inscrição estadual",
3187
3382
  IEST: "Inscrição estadual do substituto tributário",
3188
3383
  IM: "Inscrição municipal",
@@ -3245,25 +3440,25 @@ var CAMPOS = {
3245
3440
  infCpl: "Informações complementares",
3246
3441
  infAdFisco: "Informações de interesse do fisco"
3247
3442
  };
3248
- var rotular = criarRotuloDoCaminho({ grupos: GRUPOS, campos: CAMPOS, padrao: "Dados da NF-e" });
3249
- function rotuloDoCaminho(path) {
3250
- return rotular(path);
3443
+ var rotular = criarRotuloDoCaminho({ grupos: GRUPOS, campos: CAMPOS2, padrao: "Dados da NF-e" });
3444
+ function rotuloDoCaminho(caminho) {
3445
+ return rotular(caminho);
3251
3446
  }
3252
3447
  // packages/nfe/src/services/client.ts
3253
3448
  import {
3254
- authorized,
3255
- ConfigError as ConfigError4,
3256
- denied,
3257
- noopLogger,
3258
- ProtocolError as ProtocolError4,
3259
- pending,
3260
- tpAmbOf as tpAmbOf3,
3261
- ufByCUf as ufByCUf2,
3262
- ufBySigla as ufBySigla3,
3263
- ValidationError as ValidationError2
3449
+ criarAutorizado,
3450
+ criarDenegado,
3451
+ criarPendente,
3452
+ ErroDeConfiguracao as ErroDeConfiguracao4,
3453
+ ErroDeValidacao as ErroDeValidacao2,
3454
+ ErroRespostaInvalida as ErroRespostaInvalida4,
3455
+ loggerSilencioso,
3456
+ tpAmbDoAmbiente as tpAmbDoAmbiente3,
3457
+ ufPorCUf as ufPorCUf2,
3458
+ ufPorSigla as ufPorSigla3
3264
3459
  } from "@sinete/core";
3265
- import { childElements as childElements2, firstChild as firstChild5, parseXml as parseXml6, signXml as signXml2, textOf as textOf2 } from "@sinete/core/xml";
3266
- import { decode, decodeXml, serialize as serialize3, serializeRoot, validate as validate4 } from "@sinete/schemas";
3460
+ import { assinarXml as assinarXml2, elementosFilhos as elementosFilhos2, lerXml as lerXml6, primeiroFilho as primeiroFilho5, textoDe as textoDe2 } from "@sinete/core/xml";
3461
+ import { decodificar, decodificarXml, serializar as serializar3, serializarRaiz, validar as validar4 } from "@sinete/schemas";
3267
3462
  import { ConsCadElement, TRetConsCad } from "@sinete/schemas/nfe/consulta-cadastro/PL_010d";
3268
3463
  import { consSitNFeElement, TProtNFe, TRetConsSitNFe } from "@sinete/schemas/nfe/consulta-protocolo/PL_010d";
3269
3464
  import {
@@ -3283,32 +3478,32 @@ import { TInutNFe_infInut, TRetInutNFe } from "@sinete/schemas/nfe/inutilizacao/
3283
3478
  import { TRetConsReciNFe, TRetEnviNFe } from "@sinete/schemas/nfe/PL_010f";
3284
3479
  import { consStatServElement, TRetConsStatServ } from "@sinete/schemas/nfe/status-servico/PL_009q";
3285
3480
  import { nfceEndpoint, nfeContingenciaDaUf, nfeEndpoint } from "@sinete/transport";
3286
- import { parseChaveAcesso as parseChaveAcesso2, parseCnpj as parseCnpj4, parseCpf as parseCpf2 } from "@sinete/validators";
3481
+ import { lerChaveAcesso as lerChaveAcesso2, lerCnpj as lerCnpj4, lerCpf as lerCpf2 } from "@sinete/validators";
3287
3482
 
3288
3483
  // packages/nfe/src/services/gzip.ts
3289
- import { ProtocolError, UnsupportedError as UnsupportedError2 } from "@sinete/core";
3290
- import { base64Decode } from "@sinete/core/xml";
3291
- async function gunzipBase64(b64) {
3484
+ import { ErroNaoSuportado as ErroNaoSuportado2, ErroRespostaInvalida } from "@sinete/core";
3485
+ import { decodificarBase64 } from "@sinete/core/xml";
3486
+ async function descomprimirGzipBase64(b64) {
3292
3487
  const Ds = globalThis.DecompressionStream;
3293
3488
  if (Ds === undefined)
3294
- throw new UnsupportedError2("DecompressionStream indisponível nesta runtime; docZip não pode ser lido");
3489
+ throw new ErroNaoSuportado2("DecompressionStream indisponível nesta runtime; docZip não pode ser lido");
3295
3490
  let bytes;
3296
3491
  try {
3297
- bytes = base64Decode(b64.trim());
3492
+ bytes = decodificarBase64(b64.trim());
3298
3493
  } catch (cause) {
3299
- throw new ProtocolError("docZip com base64 inválido", { cause });
3494
+ throw new ErroRespostaInvalida("docZip com base64 inválido", { cause });
3300
3495
  }
3301
3496
  try {
3302
3497
  const stream = new Blob([bytes]).stream().pipeThrough(new Ds("gzip"));
3303
3498
  return await new Response(stream).text();
3304
3499
  } catch (cause) {
3305
- throw new ProtocolError("docZip não é um gzip válido", { cause });
3500
+ throw new ErroRespostaInvalida("docZip não é um gzip válido", { cause });
3306
3501
  }
3307
3502
  }
3308
3503
 
3309
3504
  // packages/nfe/src/services/outcome.ts
3310
- import { rejected } from "@sinete/core";
3311
- import { enrichRejected } from "@sinete/rejeicoes";
3505
+ import { criarRecusado } from "@sinete/core";
3506
+ import { completarRecusado } from "@sinete/rejeicoes";
3312
3507
  // packages/nfe/src/data/cstat.json
3313
3508
  var cstat_default = {
3314
3509
  descricao: "Códigos de status de sucesso e de processamento (MOC 7.0 Anexo I, tabela 4.4.1) e os códigos que o @sinete/nfe trata de forma própria. Rejeições e denegações com mensagem oficial estão no @sinete/rejeicoes; aqui fica só o desfecho de cada código por serviço.",
@@ -3335,14 +3530,14 @@ var cstat_default = {
3335
3530
  consumoIndevido: ["656"],
3336
3531
  dicas: {
3337
3532
  "656": {
3338
- probableCause: "Consumo indevido: consultas repetidas à Distribuição DF-e sem documento novo (ultNSU igual a maxNSU) ou acima do limite de requisições por hora.",
3339
- suggestedFix: "Aguardar uma hora antes de consultar de novo e só repetir a consulta quando ultNSU for menor que maxNSU; guardar o ultNSU devolvido e continuar dele.",
3340
- source: "NT 2014.002 v1.02 (Distribuição DF-e), regras de consumo indevido"
3533
+ causaProvavel: "Consumo indevido: consultas repetidas à Distribuição DF-e sem documento novo (ultNSU igual a maxNSU) ou acima do limite de requisições por hora.",
3534
+ comoCorrigir: "Aguardar uma hora antes de consultar de novo e só repetir a consulta quando ultNSU for menor que maxNSU; guardar o ultNSU devolvido e continuar dele.",
3535
+ fonte: "NT 2014.002 v1.02 (Distribuição DF-e), regras de consumo indevido"
3341
3536
  },
3342
3537
  "217": {
3343
- probableCause: "A chave consultada não consta na base do autorizador consultado: a nota não foi recebida, ou foi autorizada em outro ambiente ou autorizador (SVC).",
3344
- suggestedFix: "Se o envio ficou sem resposta, reenviar exatamente o mesmo XML assinado; se foi emitida em contingência SVC, consultar no SVC.",
3345
- source: "MOC 7.0 Anexo I, serviço de consulta protocolo"
3538
+ causaProvavel: "A chave consultada não consta na base do autorizador consultado: a nota não foi recebida, ou foi autorizada em outro ambiente ou autorizador (SVC).",
3539
+ comoCorrigir: "Se o envio ficou sem resposta, reenviar exatamente o mesmo XML assinado; se foi emitida em contingência SVC, consultar no SVC.",
3540
+ fonte: "MOC 7.0 Anexo I, serviço de consulta protocolo"
3346
3541
  }
3347
3542
  }
3348
3543
  };
@@ -3354,68 +3549,68 @@ function cstatEm(cStat, classe) {
3354
3549
  return CLASSES[classe].includes(cStat);
3355
3550
  }
3356
3551
  function rejeitado(status) {
3357
- const r = enrichRejected(rejected(status));
3358
- if (r.hint !== undefined)
3552
+ const r = completarRecusado(criarRecusado(status));
3553
+ if (r.dica !== undefined)
3359
3554
  return r;
3360
3555
  const dica = Object.hasOwn(DICAS, status.cStat) ? DICAS[status.cStat] : undefined;
3361
- return dica === undefined ? r : rejected(status, dica);
3556
+ return dica === undefined ? r : criarRecusado(status, dica);
3362
3557
  }
3363
3558
 
3364
3559
  // packages/nfe/src/services/proc.ts
3365
- import { ConfigError as ConfigError3, ProtocolError as ProtocolError2 } from "@sinete/core";
3560
+ import { ErroDeConfiguracao as ErroDeConfiguracao3, ErroRespostaInvalida as ErroRespostaInvalida2 } from "@sinete/core";
3366
3561
  import {
3367
- attributeOf,
3368
- descendants,
3369
- firstChild as firstChild4,
3370
- inScopeNamespaces,
3371
- parseXml as parseXml4,
3372
- textOf,
3562
+ atributoDe,
3563
+ descendentes,
3564
+ lerXml as lerXml4,
3565
+ namespacesEmEscopo,
3566
+ primeiroFilho as primeiroFilho4,
3567
+ textoDe,
3373
3568
  XMLDSIG_NS
3374
3569
  } from "@sinete/core/xml";
3375
3570
  var NFE_NS4 = "http://www.portalfiscal.inf.br/nfe";
3376
3571
  var XML_DECL = /^?<\?xml[^?]*\?>\s*/;
3377
- function sliceElement(doc, el, parentDefaultNs = NFE_NS4) {
3378
- const slice = doc.source.slice(el.start, el.end);
3572
+ function recortarElemento(documento, el, nsPadraoDoPai = NFE_NS4) {
3573
+ const slice = documento.texto.slice(el.inicio, el.fim);
3379
3574
  const used = new Set;
3380
3575
  const cobertoDentro = (d, p) => {
3381
- for (let e = d;e; e = e === el ? null : e.parent)
3576
+ for (let e = d;e; e = e === el ? null : e.pai)
3382
3577
  if (e.namespaces.has(p))
3383
3578
  return true;
3384
3579
  return false;
3385
3580
  };
3386
- for (const d of descendants(el)) {
3387
- const prefixos = [d.prefix, ...d.attributes.map((a) => a.prefix)].filter((p) => p !== "" && p !== "xml");
3581
+ for (const d of descendentes(el)) {
3582
+ const prefixos = [d.prefixo, ...d.atributos.map((a) => a.prefixo)].filter((p) => p !== "" && p !== "xml");
3388
3583
  for (const p of prefixos)
3389
3584
  if (!cobertoDentro(d, p))
3390
3585
  used.add(p);
3391
3586
  }
3392
3587
  const extra = [];
3393
3588
  const inScope = new Map;
3394
- for (let e = el.parent;e; e = e.parent) {
3589
+ for (let e = el.pai;e; e = e.pai) {
3395
3590
  for (const [p, u] of e.namespaces)
3396
3591
  if (!inScope.has(p))
3397
3592
  inScope.set(p, u);
3398
3593
  }
3399
3594
  const herdado = inScope.get("") ?? "";
3400
- if (herdado !== parentDefaultNs && usaDefaultHerdado(el))
3595
+ if (herdado !== nsPadraoDoPai && usaDefaultHerdado(el))
3401
3596
  extra.push(` xmlns="${herdado}"`);
3402
3597
  for (const p of [...used].sort()) {
3403
3598
  const uri = inScope.get(p);
3404
3599
  if (uri === undefined)
3405
- throw new ProtocolError2(`prefixo ${p} sem declaração no recorte de ${el.name}`);
3600
+ throw new ErroRespostaInvalida2(`prefixo ${p} sem declaração no recorte de ${el.nome}`);
3406
3601
  extra.push(` xmlns:${p}="${uri}"`);
3407
3602
  }
3408
3603
  if (extra.length === 0)
3409
3604
  return slice;
3410
- const at = 1 + el.name.length;
3605
+ const at = 1 + el.nome.length;
3411
3606
  return slice.slice(0, at) + extra.join("") + slice.slice(at);
3412
3607
  }
3413
3608
  function usaDefaultHerdado(raiz) {
3414
- for (const d of descendants(raiz)) {
3415
- if (d.prefix !== "")
3609
+ for (const d of descendentes(raiz)) {
3610
+ if (d.prefixo !== "")
3416
3611
  continue;
3417
3612
  let coberto = false;
3418
- for (let e = d;e; e = e === raiz ? null : e.parent) {
3613
+ for (let e = d;e; e = e === raiz ? null : e.pai) {
3419
3614
  if (e.namespaces.has("")) {
3420
3615
  coberto = true;
3421
3616
  break;
@@ -3430,46 +3625,46 @@ function documentoAssinado(xml, raiz, elemento) {
3430
3625
  const text = xml.replace(XML_DECL, "");
3431
3626
  let doc;
3432
3627
  try {
3433
- doc = parseXml4(text);
3628
+ doc = lerXml4(text);
3434
3629
  } catch (cause) {
3435
- throw new ConfigError3(`${raiz} assinado malformado`, { cause });
3630
+ throw new ErroDeConfiguracao3(`${raiz} assinado malformado`, { cause });
3436
3631
  }
3437
- if (doc.root.local !== raiz || doc.root.ns !== NFE_NS4) {
3438
- throw new ConfigError3(`esperado <${raiz}> no namespace da NF-e, veio <${doc.root.name}>`);
3632
+ if (doc.raiz.local !== raiz || doc.raiz.ns !== NFE_NS4) {
3633
+ throw new ErroDeConfiguracao3(`esperado <${raiz}> no namespace da NF-e, veio <${doc.raiz.nome}>`);
3439
3634
  }
3440
- if (doc.root.namespaces.get("") !== NFE_NS4) {
3441
- throw new ConfigError3(`<${raiz}> assinado precisa declarar xmlns="${NFE_NS4}" na própria raiz`);
3635
+ if (doc.raiz.namespaces.get("") !== NFE_NS4) {
3636
+ throw new ErroDeConfiguracao3(`<${raiz}> assinado precisa declarar xmlns="${NFE_NS4}" na própria raiz`);
3442
3637
  }
3443
- const alvo = firstChild4(doc.root, elemento, NFE_NS4);
3444
- const id = alvo ? attributeOf(alvo, "Id") : undefined;
3445
- const sig = firstChild4(doc.root, "Signature", XMLDSIG_NS);
3638
+ const alvo = primeiroFilho4(doc.raiz, elemento, NFE_NS4);
3639
+ const id = alvo ? atributoDe(alvo, "Id") : undefined;
3640
+ const sig = primeiroFilho4(doc.raiz, "Signature", XMLDSIG_NS);
3446
3641
  const digest = sig && descendantText(sig, "DigestValue");
3447
3642
  if (!id || digest === undefined)
3448
- throw new ConfigError3(`${raiz} sem ${elemento} identificado ou sem assinatura`);
3449
- return { xml: text, id, digestValue: digest, doc };
3643
+ throw new ErroDeConfiguracao3(`${raiz} sem ${elemento} identificado ou sem assinatura`);
3644
+ return { xml: text, id, digestValue: digest, documento: doc };
3450
3645
  }
3451
3646
  function descendantText(el, local) {
3452
- for (const d of descendants(el))
3647
+ for (const d of descendentes(el))
3453
3648
  if (d.local === local && d.ns === XMLDSIG_NS)
3454
- return textOf(d).trim();
3649
+ return textoDe(d).trim();
3455
3650
  return;
3456
3651
  }
3457
3652
  function nfeAssinadaDoProc(xml) {
3458
3653
  const text = xml.replace(XML_DECL, "");
3459
3654
  let doc;
3460
3655
  try {
3461
- doc = parseXml4(text);
3656
+ doc = lerXml4(text);
3462
3657
  } catch (cause) {
3463
- throw new ConfigError3("nfeProc malformado", { cause });
3658
+ throw new ErroDeConfiguracao3("nfeProc malformado", { cause });
3464
3659
  }
3465
- const noProc = doc.root.local === "nfeProc" && doc.root.ns === NFE_NS4 ? firstChild4(doc.root, "NFe", NFE_NS4) : undefined;
3466
- const el = noProc ?? (doc.root.local === "NFe" && doc.root.ns === NFE_NS4 ? doc.root : undefined);
3660
+ const noProc = doc.raiz.local === "nfeProc" && doc.raiz.ns === NFE_NS4 ? primeiroFilho4(doc.raiz, "NFe", NFE_NS4) : undefined;
3661
+ const el = noProc ?? (doc.raiz.local === "NFe" && doc.raiz.ns === NFE_NS4 ? doc.raiz : undefined);
3467
3662
  if (el === undefined)
3468
- throw new ConfigError3(`esperado <nfeProc> ou <NFe> assinada, veio <${doc.root.name}>`);
3469
- const fatia = doc.source.slice(el.start, el.end);
3470
- const herdados = [...inScopeNamespaces(el)].filter(([p]) => p !== "xml" && !el.namespaces.has(p));
3663
+ throw new ErroDeConfiguracao3(`esperado <nfeProc> ou <NFe> assinada, veio <${doc.raiz.nome}>`);
3664
+ const fatia = doc.texto.slice(el.inicio, el.fim);
3665
+ const herdados = [...namespacesEmEscopo(el)].filter(([p]) => p !== "xml" && !el.namespaces.has(p));
3471
3666
  const decl = herdados.map(([p, uri]) => ` ${p === "" ? "xmlns" : `xmlns:${p}`}="${uri.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/"/g, "&quot;")}"`).join("");
3472
- const at = 1 + el.name.length;
3667
+ const at = 1 + el.nome.length;
3473
3668
  const assinado = decl === "" ? fatia : fatia.slice(0, at) + decl + fatia.slice(at);
3474
3669
  return documentoAssinado(assinado, "NFe", "infNFe").xml;
3475
3670
  }
@@ -3478,9 +3673,9 @@ function envelope(raiz, versao, partes) {
3478
3673
  }
3479
3674
 
3480
3675
  // packages/nfe/src/services/soap.ts
3481
- import { ProtocolError as ProtocolError3 } from "@sinete/core";
3482
- import { childElements, descendants as descendants2, parseXml as parseXml5 } from "@sinete/core/xml";
3483
- import { soap12ContentType, soap12Envelope, soapFault } from "@sinete/transport";
3676
+ import { ErroRespostaInvalida as ErroRespostaInvalida3 } from "@sinete/core";
3677
+ import { descendentes as descendentes2, elementosFilhos, lerXml as lerXml5 } from "@sinete/core/xml";
3678
+ import { contentTypeSoap12, envelopeSoap12, lerSoapFault } from "@sinete/transport";
3484
3679
  // packages/nfe/src/data/servicos.json
3485
3680
  var servicos_default = {
3486
3681
  descricao: "Web services SOAP 1.2 da NF-e 4.00: namespace do WSDL e operação (a action do Content-Type é <namespace>/<operação>). Na NF-e 4.00 não existe cabeçalho nfeCabecMsg; a mensagem vai em nfeDadosMsg no namespace do WSDL, e a resposta volta em nfeResultMsg. A Distribuição DF-e usa o envelope do WSDL próprio, com nfeDadosMsg dentro de nfeDistDFeInteresse.",
@@ -3532,7 +3727,7 @@ var SERVICOS = servicos_default.servicos;
3532
3727
  function servicoInfo(servico) {
3533
3728
  const s = SERVICOS[servico];
3534
3729
  if (!s)
3535
- throw new ProtocolError3(`serviço sem descrição em data/servicos.json: ${servico}`);
3730
+ throw new ErroRespostaInvalida3(`serviço sem descrição em data/servicos.json: ${servico}`);
3536
3731
  return s;
3537
3732
  }
3538
3733
  function soapBodyFor(servico, mensagem, autorizador) {
@@ -3545,62 +3740,62 @@ function soapBodyFor(servico, mensagem, autorizador) {
3545
3740
  async function chamar(c) {
3546
3741
  const s = servicoInfo(c.servico);
3547
3742
  const started = { servico: c.servico, autorizador: c.endpoint.autorizador, host: c.endpoint.host };
3548
- const res = await c.transport.send({
3743
+ const res = await c.transport.enviar({
3549
3744
  url: c.endpoint.url,
3550
3745
  endpoint: c.endpoint,
3551
- method: "POST",
3552
- headers: { "content-type": soap12ContentType(`${s.namespace}/${s.operacao}`) },
3553
- body: soap12Envelope(soapBodyFor(c.servico, c.mensagem, c.endpoint.autorizador)),
3746
+ metodo: "POST",
3747
+ cabecalhos: { "content-type": contentTypeSoap12(`${s.namespace}/${s.operacao}`) },
3748
+ corpo: envelopeSoap12(soapBodyFor(c.servico, c.mensagem, c.endpoint.autorizador)),
3554
3749
  ...c.timeoutMs === undefined ? {} : { timeoutMs: c.timeoutMs },
3555
3750
  ...c.signal === undefined ? {} : { signal: c.signal }
3556
3751
  });
3557
- const text = res.text();
3558
- const fault = soapFault(text);
3752
+ const text = res.texto();
3753
+ const fault = lerSoapFault(text);
3559
3754
  if (fault) {
3560
3755
  c.logger.warn("nfe.soap.fault", { ...started, status: res.status, code: fault.code });
3561
- throw new ProtocolError3(`SOAP fault de ${c.endpoint.host}: ${fault.reason ?? fault.code ?? "sem motivo"}`, {
3562
- details: { status: res.status, code: fault.code, reason: fault.reason, servico: c.servico }
3756
+ throw new ErroRespostaInvalida3(`SOAP fault de ${c.endpoint.host}: ${fault.reason ?? fault.code ?? "sem motivo"}`, {
3757
+ detalhes: { status: res.status, code: fault.code, reason: fault.reason, servico: c.servico }
3563
3758
  });
3564
3759
  }
3565
3760
  let doc;
3566
3761
  try {
3567
- doc = parseXml5(text.replace(/^/, ""));
3762
+ doc = lerXml5(text.replace(/^/, ""));
3568
3763
  } catch (cause) {
3569
- throw new ProtocolError3(`resposta de ${c.endpoint.host} não é XML (HTTP ${res.status})`, {
3764
+ throw new ErroRespostaInvalida3(`resposta de ${c.endpoint.host} não é XML (HTTP ${res.status})`, {
3570
3765
  cause,
3571
- details: { status: res.status, servico: c.servico }
3766
+ detalhes: { status: res.status, servico: c.servico }
3572
3767
  });
3573
3768
  }
3574
3769
  let ret;
3575
- for (const el of descendants2(doc.root)) {
3770
+ for (const el of descendentes2(doc.raiz)) {
3576
3771
  if (el.local === c.retorno && el.ns === NFE_NS4) {
3577
3772
  ret = el;
3578
3773
  break;
3579
3774
  }
3580
3775
  }
3581
3776
  if (!ret)
3582
- ret = retornoForaDoNamespace(doc.root, c.retorno);
3777
+ ret = retornoForaDoNamespace(doc.raiz, c.retorno);
3583
3778
  if (ret && ret.ns !== NFE_NS4) {
3584
3779
  c.logger.warn("nfe.soap.retorno_fora_do_namespace", { ...started, retorno: c.retorno, ns: ret.ns });
3585
3780
  }
3586
3781
  if (!ret) {
3587
- throw new ProtocolError3(`resposta de ${c.endpoint.host} sem <${c.retorno}> (HTTP ${res.status})`, {
3588
- details: { status: res.status, servico: c.servico }
3782
+ throw new ErroRespostaInvalida3(`resposta de ${c.endpoint.host} sem <${c.retorno}> (HTTP ${res.status})`, {
3783
+ detalhes: { status: res.status, servico: c.servico }
3589
3784
  });
3590
3785
  }
3591
- if (!Array.from(descendants2(ret)).some((el) => el.local === "cStat" && el.ns === NFE_NS4)) {
3592
- throw new ProtocolError3(`<${c.retorno}> de ${c.endpoint.host} sem cStat (HTTP ${res.status})`, {
3593
- details: { status: res.status, servico: c.servico }
3786
+ if (!Array.from(descendentes2(ret)).some((el) => el.local === "cStat" && el.ns === NFE_NS4)) {
3787
+ throw new ErroRespostaInvalida3(`<${c.retorno}> de ${c.endpoint.host} sem cStat (HTTP ${res.status})`, {
3788
+ detalhes: { status: res.status, servico: c.servico }
3594
3789
  });
3595
3790
  }
3596
3791
  c.logger.debug("nfe.soap.resposta", { ...started, status: res.status });
3597
3792
  return { doc, ret, status: res.status };
3598
3793
  }
3599
3794
  function retornoForaDoNamespace(root, retorno) {
3600
- for (const el of descendants2(root)) {
3795
+ for (const el of descendentes2(root)) {
3601
3796
  if (el.local !== retorno)
3602
3797
  continue;
3603
- const filhos = childElements(el);
3798
+ const filhos = elementosFilhos(el);
3604
3799
  if (filhos.length > 0 && filhos.every((f) => f.ns === NFE_NS4))
3605
3800
  return el;
3606
3801
  }
@@ -3628,26 +3823,26 @@ var defaultSleep = (ms, signal) => new Promise((resolve, reject) => {
3628
3823
  signal?.addEventListener("abort", onAbort, { once: true });
3629
3824
  });
3630
3825
  function chaveValida(chave, path) {
3631
- const r = parseChaveAcesso2(chave, { path });
3826
+ const r = lerChaveAcesso2(chave, { caminho: path });
3632
3827
  if (!r.ok)
3633
- throw new ValidationError2(`chave de acesso inválida: ${r.error.message}`, [r.error]);
3634
- return r.value;
3828
+ throw new ErroDeValidacao2(`chave de acesso inválida: ${r.erro.mensagem}`, [r.erro]);
3829
+ return r.valor;
3635
3830
  }
3636
3831
  function schemaIssues(what, issues) {
3637
3832
  if (issues.length > 0)
3638
- throw new ValidationError2(`${what} não confere com o schema`, issues);
3833
+ throw new ErroDeValidacao2(`${what} não confere com o schema`, issues);
3639
3834
  }
3640
3835
  function documentoAutor(a, path) {
3641
3836
  if (a.CNPJ !== undefined) {
3642
- const r = parseCnpj4(a.CNPJ, { path: `${path}.CNPJ` });
3837
+ const r = lerCnpj4(a.CNPJ, { caminho: `${path}.CNPJ` });
3643
3838
  if (!r.ok)
3644
- throw new ValidationError2("CNPJ do autor inválido", [r.error]);
3645
- return { CNPJ: r.value };
3839
+ throw new ErroDeValidacao2("CNPJ do autor inválido", [r.erro]);
3840
+ return { CNPJ: r.valor };
3646
3841
  }
3647
- const r = parseCpf2(a.CPF ?? "", { path: `${path}.CPF` });
3842
+ const r = lerCpf2(a.CPF ?? "", { caminho: `${path}.CPF` });
3648
3843
  if (!r.ok)
3649
- throw new ValidationError2("CPF do autor inválido", [r.error]);
3650
- return { CPF: r.value };
3844
+ throw new ErroDeValidacao2("CPF do autor inválido", [r.erro]);
3845
+ return { CPF: r.valor };
3651
3846
  }
3652
3847
  function autorDaChave(c) {
3653
3848
  return c.cnpj !== undefined ? { CNPJ: c.cnpj } : { CPF: c.cpf ?? c.emitente.slice(3) };
@@ -3659,11 +3854,11 @@ function autorDoEmitente(a, c) {
3659
3854
  const autor = documentoAutor(a, "autor");
3660
3855
  const [campo, valor] = "CNPJ" in autor ? ["CNPJ", autor.CNPJ] : ["CPF", autor.CPF];
3661
3856
  if (valor !== ("CNPJ" in daChave ? daChave.CNPJ : daChave.CPF) || campo !== ("CNPJ" in daChave ? "CNPJ" : "CPF")) {
3662
- throw new ValidationError2("o autor do evento não é o emitente da NF-e", [
3857
+ throw new ErroDeValidacao2("o autor do evento não é o emitente da NF-e", [
3663
3858
  {
3664
- path: `autor.${campo}`,
3859
+ caminho: `autor.${campo}`,
3665
3860
  code: "autor_difere_do_emitente",
3666
- message: `o autor de um evento do emitente é o ${"CNPJ" in daChave ? "CNPJ" : "CPF"} da chave (P12-44, rejeição 574)`,
3861
+ mensagem: `o autor de um evento do emitente é o ${"CNPJ" in daChave ? "CNPJ" : "CPF"} da chave (P12-44, rejeição 574)`,
3667
3862
  origem: "entrada"
3668
3863
  }
3669
3864
  ]);
@@ -3672,19 +3867,19 @@ function autorDoEmitente(a, c) {
3672
3867
  }
3673
3868
  var SVC_DO_TPEMIS = { "6": "SVC-AN", "7": "SVC-RS" };
3674
3869
  function chaveDoDocumento(a) {
3675
- const r = parseChaveAcesso2(a.id.slice(3), { path: "infNFe.Id", checkEmitente: false });
3870
+ const r = lerChaveAcesso2(a.id.slice(3), { caminho: "infNFe.Id", conferirEmitente: false });
3676
3871
  if (!r.ok)
3677
- throw new ConfigError4(`Id da NF-e assinada não é uma chave de acesso: ${r.error.message}`);
3678
- return r.value;
3872
+ throw new ErroDeConfiguracao4(`Id da NF-e assinada não é uma chave de acesso: ${r.erro.mensagem}`);
3873
+ return r.valor;
3679
3874
  }
3680
3875
  function avulso(doc, el) {
3681
- return sliceElement(doc, el, "");
3876
+ return recortarElemento(doc, el, "");
3682
3877
  }
3683
3878
  function lerProtocolo(doc, el) {
3684
- const { value } = decode(TProtNFe, el, doc.source);
3879
+ const { valor: value } = decodificar(TProtNFe, el, doc.texto);
3685
3880
  const inf = value.infProt;
3686
3881
  if (!inf)
3687
- throw new ProtocolError4("protNFe sem infProt");
3882
+ throw new ErroRespostaInvalida4("protNFe sem infProt");
3688
3883
  const p = {
3689
3884
  chNFe: inf.chNFe,
3690
3885
  cStat: inf.cStat,
@@ -3695,7 +3890,7 @@ function lerProtocolo(doc, el) {
3695
3890
  ...inf.nProt === undefined ? {} : { nProt: inf.nProt },
3696
3891
  ...inf.digVal === undefined ? {} : { digVal: inf.digVal }
3697
3892
  };
3698
- return { p, embutido: sliceElement(doc, el) };
3893
+ return { p, embutido: recortarElemento(doc, el) };
3699
3894
  }
3700
3895
  function desfechoDoProtocolo({ p, embutido }, a) {
3701
3896
  const status = { cStat: p.cStat, xMotivo: p.xMotivo };
@@ -3706,27 +3901,27 @@ function desfechoDoProtocolo({ p, embutido }, a) {
3706
3901
  let full = p;
3707
3902
  if (a) {
3708
3903
  if (`NFe${p.chNFe}` !== a.id) {
3709
- throw new ProtocolError4("protocolo de outra chave de acesso", { details: { chNFe: p.chNFe } });
3904
+ throw new ErroRespostaInvalida4("protocolo de outra chave de acesso", { detalhes: { chNFe: p.chNFe } });
3710
3905
  }
3711
3906
  if (p.digVal !== undefined && p.digVal !== a.digestValue) {
3712
- throw new ProtocolError4("digVal do protocolo difere do DigestValue da NF-e enviada", {
3713
- details: { chNFe: p.chNFe, cStat: p.cStat }
3907
+ throw new ErroRespostaInvalida4("digVal do protocolo difere do DigestValue da NF-e enviada", {
3908
+ detalhes: { chNFe: p.chNFe, cStat: p.cStat }
3714
3909
  });
3715
3910
  }
3716
3911
  if (p.digVal !== undefined)
3717
3912
  full = { ...p, nfeProc: envelope("nfeProc", "4.00", [a.xml, embutido]) };
3718
3913
  }
3719
- return autorizada ? authorized(status, full) : denied(status, full);
3914
+ return autorizada ? criarAutorizado(status, full) : criarDenegado(status, full);
3720
3915
  }
3721
3916
  function protNFeDaChave(parent, a) {
3722
- const prots = childElements2(parent).filter((e) => e.local === "protNFe" && e.ns === NFE_NS4);
3917
+ const prots = elementosFilhos2(parent).filter((e) => e.local === "protNFe" && e.ns === NFE_NS4);
3723
3918
  if (!a)
3724
3919
  return prots[0];
3725
3920
  const chave = a.id.slice(3);
3726
3921
  return prots.find((e) => {
3727
- const inf = firstChild5(e, "infProt", NFE_NS4);
3728
- const ch = inf && firstChild5(inf, "chNFe", NFE_NS4);
3729
- return ch !== undefined && textOf2(ch).trim() === chave;
3922
+ const inf = primeiroFilho5(e, "infProt", NFE_NS4);
3923
+ const ch = inf && primeiroFilho5(inf, "chNFe", NFE_NS4);
3924
+ return ch !== undefined && textoDe2(ch).trim() === chave;
3730
3925
  }) ?? (prots.length === 1 ? prots[0] : undefined);
3731
3926
  }
3732
3927
  var EVENTO_VERSAO = "1.00";
@@ -3737,36 +3932,39 @@ var MANIFESTACOES = {
3737
3932
  desconhecimento: { tpEvento: "210220", descEvento: "Desconhecimento da Operacao", ct: TEventoDesconhecimento },
3738
3933
  "nao-realizada": { tpEvento: "210240", descEvento: "Operacao nao Realizada", ct: TEventoNaoRealizada }
3739
3934
  };
3740
- function createNfeClient(options) {
3741
- const logger = (options.logger ?? noopLogger).child({ modulo: "nfe", ambiente: options.ambiente });
3742
- const sleep = options.sleep ?? defaultSleep;
3743
- const tpAmb = tpAmbOf3(options.ambiente);
3744
- const ufInfo = options.uf === undefined ? undefined : ufBySigla3(options.uf);
3745
- if (options.uf !== undefined && !ufInfo)
3746
- throw new ConfigError4(`UF inválida: ${String(options.uf)}`);
3935
+ function criarClienteNfe(opcoesDoCliente) {
3936
+ const logger = (opcoesDoCliente.logger ?? loggerSilencioso).child({
3937
+ modulo: "nfe",
3938
+ ambiente: opcoesDoCliente.ambiente
3939
+ });
3940
+ const sleep = opcoesDoCliente.esperar ?? defaultSleep;
3941
+ const tpAmb = tpAmbDoAmbiente3(opcoesDoCliente.ambiente);
3942
+ const ufInfo = opcoesDoCliente.uf === undefined ? undefined : ufPorSigla3(opcoesDoCliente.uf);
3943
+ if (opcoesDoCliente.uf !== undefined && !ufInfo)
3944
+ throw new ErroDeConfiguracao4(`UF inválida: ${String(opcoesDoCliente.uf)}`);
3747
3945
  const ufPadrao = (servico) => {
3748
- if (options.uf === undefined || ufInfo === undefined) {
3749
- throw new ConfigError4(`${servico} precisa da UF: informe NfeClientOptions.uf`);
3946
+ if (opcoesDoCliente.uf === undefined || ufInfo === undefined) {
3947
+ throw new ErroDeConfiguracao4(`${servico} precisa da UF: informe ClienteNfeOpcoes.uf`);
3750
3948
  }
3751
- return { uf: options.uf, cUF: ufInfo.cUF };
3949
+ return { uf: opcoesDoCliente.uf, cUF: ufInfo.cUF };
3752
3950
  };
3753
- const offsetDe = (uf) => options.offsetMinutes ?? offsetDaUf(uf);
3951
+ const offsetDe = (uf) => opcoesDoCliente.deslocamentoMin ?? deslocamentoDaUf(uf);
3754
3952
  const idLote = () => {
3755
- const id = options.idLote ? options.idLote() : String(options.clock.now().getTime()).slice(-15);
3953
+ const id = opcoesDoCliente.idLote ? opcoesDoCliente.idLote() : String(opcoesDoCliente.relogio.agora().getTime()).slice(-15);
3756
3954
  if (!/^[0-9]{1,15}$/.test(id))
3757
- throw new ConfigError4(`idLote inválido: ${id}`);
3955
+ throw new ErroDeConfiguracao4(`idLote inválido: ${id}`);
3758
3956
  return id;
3759
3957
  };
3760
- const endpointNfce = (servico, uf) => options.nfceEndpoint ? options.nfceEndpoint(servico, uf) : nfceEndpoint({ ambiente: options.ambiente, servico, uf });
3958
+ const endpointNfce = (servico, uf) => opcoesDoCliente.endpointNfce ? opcoesDoCliente.endpointNfce(servico, uf) : nfceEndpoint({ ambiente: opcoesDoCliente.ambiente, servico, uf });
3761
3959
  const endpoint = (servico, mod = "55") => {
3762
3960
  const { uf } = ufPadrao(servico);
3763
3961
  if (mod === "65")
3764
3962
  return endpointNfce(servico, uf);
3765
3963
  return nfeEndpoint({
3766
- ambiente: options.ambiente,
3964
+ ambiente: opcoesDoCliente.ambiente,
3767
3965
  servico,
3768
3966
  uf,
3769
- ...options.contingencia === undefined ? {} : { contingencia: options.contingencia }
3967
+ ...opcoesDoCliente.contingencia === undefined ? {} : { contingencia: opcoesDoCliente.contingencia }
3770
3968
  });
3771
3969
  };
3772
3970
  const endpointDaChave = (servico, c, naUf = false) => {
@@ -3774,76 +3972,78 @@ function createNfeClient(options) {
3774
3972
  return endpointNfce(servico, c.uf);
3775
3973
  const svc = naUf || c.tpEmis === undefined ? undefined : SVC_DO_TPEMIS[c.tpEmis];
3776
3974
  return nfeEndpoint({
3777
- ambiente: options.ambiente,
3975
+ ambiente: opcoesDoCliente.ambiente,
3778
3976
  servico,
3779
3977
  ...svc === undefined ? { uf: c.uf } : { autorizador: svc }
3780
3978
  });
3781
3979
  };
3782
3980
  const call = (ep, servico, mensagem, retorno, signal) => chamar({
3783
- transport: options.transport,
3981
+ transport: opcoesDoCliente.transporte,
3784
3982
  endpoint: ep,
3785
3983
  servico,
3786
3984
  mensagem,
3787
3985
  retorno,
3788
3986
  logger,
3789
- ...options.timeoutMs === undefined ? {} : { timeoutMs: options.timeoutMs },
3987
+ ...opcoesDoCliente.timeoutMs === undefined ? {} : { timeoutMs: opcoesDoCliente.timeoutMs },
3790
3988
  ...signal === undefined ? {} : { signal }
3791
3989
  });
3792
3990
  const autorPadrao = (a, path) => {
3793
- const autor = a ?? options.autor;
3991
+ const autor = a ?? opcoesDoCliente.autor;
3794
3992
  if (!autor)
3795
- throw new ConfigError4(`informe o CNPJ ou CPF do autor (${path} ou NfeClientOptions.autor)`);
3993
+ throw new ErroDeConfiguracao4(`informe o CNPJ ou CPF do autor (${path} ou ClienteNfeOpcoes.autor)`);
3796
3994
  return documentoAutor(autor, path);
3797
3995
  };
3798
3996
  async function consultarRecibo(nRec, nfeAssinada, opcoes = {}) {
3799
3997
  if (!/^[0-9]{15}$/.test(nRec))
3800
- throw new ConfigError4(`número de recibo inválido: ${nRec}`);
3998
+ throw new ErroDeConfiguracao4(`número de recibo inválido: ${nRec}`);
3801
3999
  const a = nfeAssinada === undefined ? undefined : documentoAssinado(nfeAssinada, "NFe", "infNFe");
3802
4000
  const c = a === undefined ? undefined : chaveDoDocumento(a);
3803
4001
  if (c !== undefined && opcoes.mod !== undefined && opcoes.mod !== c.mod) {
3804
- throw new ConfigError4(`mod ${opcoes.mod} não é o da NF-e assinada (${c.mod})`);
4002
+ throw new ErroDeConfiguracao4(`mod ${opcoes.mod} não é o da NF-e assinada (${c.mod})`);
3805
4003
  }
3806
4004
  const msg = envelope("consReciNFe", "4.00", [`<tpAmb>${tpAmb}</tpAmb><nRec>${nRec}</nRec>`]);
3807
4005
  const ep = c === undefined ? endpoint("NFeRetAutorizacao", opcoes.mod ?? "55") : endpointDaChave("NFeRetAutorizacao", c);
3808
4006
  const r = await call(ep, "NFeRetAutorizacao", msg, "retConsReciNFe", opcoes.signal);
3809
- const v = decode(TRetConsReciNFe, r.ret, r.doc.source).value;
4007
+ const v = decodificar(TRetConsReciNFe, r.ret, r.doc.texto).valor;
3810
4008
  if (v.nRec !== undefined && v.nRec !== nRec) {
3811
- throw new ProtocolError4("retorno de outro recibo", { details: { nRec: v.nRec } });
4009
+ throw new ErroRespostaInvalida4("retorno de outro recibo", { detalhes: { nRec: v.nRec } });
3812
4010
  }
3813
4011
  const status = { cStat: v.cStat, xMotivo: v.xMotivo };
3814
4012
  logger.info("nfe.recibo", { nRec, cStat: v.cStat });
3815
4013
  if (cstatEm(v.cStat, "loteEmProcessamento") || cstatEm(v.cStat, "loteRecebido"))
3816
- return pending(status, { ref: nRec });
4014
+ return criarPendente(status, { referencia: nRec });
3817
4015
  if (cstatEm(v.cStat, "loteProcessado")) {
3818
4016
  const el = protNFeDaChave(r.ret, a);
3819
4017
  if (!el)
3820
- throw new ProtocolError4("lote processado sem o protNFe da NF-e", { details: { nRec } });
4018
+ throw new ErroRespostaInvalida4("lote processado sem o protNFe da NF-e", { detalhes: { nRec } });
3821
4019
  return desfechoDoProtocolo(lerProtocolo(r.doc, el), a);
3822
4020
  }
3823
4021
  return rejeitado(status);
3824
4022
  }
3825
- async function consultar(chave, nfeAssinada) {
4023
+ async function consultar(chave, nfeAssinada, opcoes) {
3826
4024
  const c = chaveValida(chave, "chNFe");
3827
4025
  const a = nfeAssinada === undefined ? undefined : documentoAssinado(nfeAssinada, "NFe", "infNFe");
3828
4026
  if (a && a.id !== `NFe${c.chave}`)
3829
- throw new ConfigError4("a NF-e assinada não é a da chave consultada");
3830
- const msg = serializeRoot(consSitNFeElement, { versao: "4.00", tpAmb, xServ: "CONSULTAR", chNFe: c.chave });
4027
+ throw new ErroDeConfiguracao4("a NF-e assinada não é a da chave consultada");
4028
+ const msg = serializarRaiz(consSitNFeElement, { versao: "4.00", tpAmb, xServ: "CONSULTAR", chNFe: c.chave });
3831
4029
  const ep = endpointDaChave("NfeConsultaProtocolo", c);
3832
- const r = await call(ep, "NfeConsultaProtocolo", msg, "retConsSitNFe");
3833
- const v = decode(TRetConsSitNFe, r.ret, r.doc.source).value;
4030
+ const r = await call(ep, "NfeConsultaProtocolo", msg, "retConsSitNFe", opcoes?.signal);
4031
+ const v = decodificar(TRetConsSitNFe, r.ret, r.doc.texto).valor;
3834
4032
  const status = { cStat: v.cStat, xMotivo: v.xMotivo };
3835
4033
  logger.info("nfe.consulta", { chNFe: c.chave, cStat: v.cStat });
3836
4034
  const situacao = cstatEm(v.cStat, "autorizada") ? "autorizada" : cstatEm(v.cStat, "cancelada") ? "cancelada" : cstatEm(v.cStat, "denegada") ? "denegada" : undefined;
3837
4035
  if (situacao === undefined)
3838
4036
  return rejeitado(status);
3839
- const protEl = firstChild5(r.ret, "protNFe", NFE_NS4);
3840
- const eventos = childElements2(r.ret).filter((e) => e.local === "procEventoNFe" && e.ns === NFE_NS4).map((e) => avulso(r.doc, e));
4037
+ const protEl = primeiroFilho5(r.ret, "protNFe", NFE_NS4);
4038
+ const eventos = elementosFilhos2(r.ret).filter((e) => e.local === "procEventoNFe" && e.ns === NFE_NS4).map((e) => avulso(r.doc, e));
3841
4039
  let protocolo;
3842
4040
  let digValConfere;
3843
4041
  if (protEl) {
3844
4042
  const { p, embutido } = lerProtocolo(r.doc, protEl);
3845
4043
  if (p.chNFe !== c.chave) {
3846
- throw new ProtocolError4("protocolo de outra chave de acesso na consulta", { details: { chNFe: p.chNFe } });
4044
+ throw new ErroRespostaInvalida4("protocolo de outra chave de acesso na consulta", {
4045
+ detalhes: { chNFe: p.chNFe }
4046
+ });
3847
4047
  }
3848
4048
  protocolo = p;
3849
4049
  if (a) {
@@ -3859,12 +4059,12 @@ function createNfeClient(options) {
3859
4059
  ...protocolo === undefined ? {} : { protocolo },
3860
4060
  ...digValConfere === undefined ? {} : { digValConfere }
3861
4061
  };
3862
- return situacao === "denegada" ? denied(status, value) : authorized(status, value);
4062
+ return situacao === "denegada" ? criarDenegado(status, value) : criarAutorizado(status, value);
3863
4063
  }
3864
4064
  async function enviarEvento(p) {
3865
4065
  const nSeq = p.nSeqEvento;
3866
4066
  if (!Number.isInteger(nSeq) || nSeq < 1 || nSeq > 99)
3867
- throw new ConfigError4(`nSeqEvento inválido: ${nSeq}`);
4067
+ throw new ErroDeConfiguracao4(`nSeqEvento inválido: ${nSeq}`);
3868
4068
  const nSeqEvento = String(nSeq);
3869
4069
  const id = `ID${p.tpEvento}${p.chave}${nSeqEvento.padStart(2, "0")}`;
3870
4070
  const inf = {
@@ -3873,62 +4073,62 @@ function createNfeClient(options) {
3873
4073
  tpAmb,
3874
4074
  ...p.autor,
3875
4075
  chNFe: p.chave,
3876
- dhEvento: formatDh(options.clock.now(), p.offsetMinutes),
4076
+ dhEvento: formatarDh(opcoesDoCliente.relogio.agora(), p.offsetMinutes),
3877
4077
  tpEvento: p.tpEvento,
3878
4078
  nSeqEvento,
3879
4079
  verEvento: EVENTO_VERSAO,
3880
4080
  detEvento: p.detEvento
3881
4081
  };
3882
- const infXml = serialize3(p.ct, "infEvento", inf, NFE_NS4);
4082
+ const infXml = serializar3(p.ct, "infEvento", inf, NFE_NS4);
3883
4083
  const evento = `<evento xmlns="${NFE_NS4}" versao="${EVENTO_VERSAO}">${infXml}</evento>`;
3884
- const infEl = firstChild5(parseXml6(evento).root, "infEvento", NFE_NS4);
3885
- schemaIssues("evento", validate4(p.ct, infEl));
3886
- const assinado = await signXml2(evento, { id }, options.signer);
4084
+ const infEl = primeiroFilho5(lerXml6(evento).raiz, "infEvento", NFE_NS4);
4085
+ schemaIssues("evento", validar4(p.ct, infEl));
4086
+ const assinado = await assinarXml2(evento, { id }, opcoesDoCliente.assinador);
3887
4087
  const msg = envelope("envEvento", EVENTO_VERSAO, [`<idLote>${idLote()}</idLote>`, assinado]);
3888
- const r = await call(p.endpoint, "RecepcaoEvento", msg, "retEnvEvento");
3889
- const v = decode(TRetEnvEvento, r.ret, r.doc.source).value;
4088
+ const r = await call(p.endpoint, "RecepcaoEvento", msg, "retEnvEvento", p.signal);
4089
+ const v = decodificar(TRetEnvEvento, r.ret, r.doc.texto).valor;
3890
4090
  logger.info("nfe.evento", { chNFe: p.chave, tpEvento: p.tpEvento, cStat: v.cStat });
3891
4091
  if (!cstatEm(v.cStat, "loteEventoProcessado"))
3892
4092
  return rejeitado({ cStat: v.cStat, xMotivo: v.xMotivo });
3893
- const retEl = childElements2(r.ret).find((e) => e.local === "retEvento" && e.ns === NFE_NS4);
4093
+ const retEl = elementosFilhos2(r.ret).find((e) => e.local === "retEvento" && e.ns === NFE_NS4);
3894
4094
  const ret = v.retEvento?.[0]?.infEvento;
3895
4095
  if (!retEl || !ret)
3896
- throw new ProtocolError4("lote de evento processado sem retEvento");
4096
+ throw new ErroRespostaInvalida4("lote de evento processado sem retEvento");
3897
4097
  const divergentes = [
3898
4098
  ["chNFe", ret.chNFe, p.chave],
3899
4099
  ["tpEvento", ret.tpEvento, p.tpEvento],
3900
4100
  ["nSeqEvento", ret.nSeqEvento === undefined ? undefined : String(Number(ret.nSeqEvento)), nSeqEvento]
3901
4101
  ].filter(([, veio, enviado]) => veio !== undefined && veio !== enviado);
3902
4102
  if (divergentes.length > 0) {
3903
- throw new ProtocolError4("retEvento de outro evento", {
3904
- details: Object.fromEntries(divergentes.map(([k, veio]) => [k, veio]))
4103
+ throw new ErroRespostaInvalida4("retEvento de outro evento", {
4104
+ detalhes: Object.fromEntries(divergentes.map(([k, veio]) => [k, veio]))
3905
4105
  });
3906
4106
  }
3907
4107
  const status = { cStat: ret.cStat, xMotivo: ret.xMotivo };
3908
4108
  if (!cstatEm(ret.cStat, "eventoRegistrado"))
3909
4109
  return rejeitado(status);
3910
- return authorized(status, {
4110
+ return criarAutorizado(status, {
3911
4111
  chNFe: p.chave,
3912
4112
  tpEvento: p.tpEvento,
3913
4113
  nSeqEvento,
3914
4114
  dhRegEvento: ret.dhRegEvento,
3915
4115
  retEvento: avulso(r.doc, retEl),
3916
- procEventoNFe: envelope("procEventoNFe", EVENTO_VERSAO, [assinado, sliceElement(r.doc, retEl)]),
4116
+ procEventoNFe: envelope("procEventoNFe", EVENTO_VERSAO, [assinado, recortarElemento(r.doc, retEl)]),
3917
4117
  ...ret.nProt === undefined ? {} : { nProt: ret.nProt }
3918
4118
  });
3919
4119
  }
3920
4120
  const client = {
3921
- options,
4121
+ opcoes: opcoesDoCliente,
3922
4122
  async statusServico(opcoes) {
3923
4123
  const { cUF } = ufPadrao("NfeStatusServico");
3924
- const msg = serializeRoot(consStatServElement, { versao: "4.00", tpAmb, cUF, xServ: "STATUS" });
3925
- const r = await call(endpoint("NfeStatusServico", opcoes?.mod), "NfeStatusServico", msg, "retConsStatServ");
3926
- const v = decode(TRetConsStatServ, r.ret, r.doc.source).value;
4124
+ const msg = serializarRaiz(consStatServElement, { versao: "4.00", tpAmb, cUF, xServ: "STATUS" });
4125
+ const r = await call(endpoint("NfeStatusServico", opcoes?.mod), "NfeStatusServico", msg, "retConsStatServ", opcoes?.signal);
4126
+ const v = decodificar(TRetConsStatServ, r.ret, r.doc.texto).valor;
3927
4127
  const status = { cStat: v.cStat, xMotivo: v.xMotivo };
3928
4128
  logger.info("nfe.status", { cStat: v.cStat });
3929
4129
  if (!cstatEm(v.cStat, "servicoEmOperacao"))
3930
4130
  return rejeitado(status);
3931
- return authorized(status, {
4131
+ return criarAutorizado(status, {
3932
4132
  cUF: v.cUF,
3933
4133
  verAplic: v.verAplic,
3934
4134
  dhRecbto: v.dhRecbto,
@@ -3946,15 +4146,15 @@ function createNfeClient(options) {
3946
4146
  ]);
3947
4147
  const ep = endpointDaChave("NFeAutorizacao", chaveDoDocumento(a));
3948
4148
  const r = await call(ep, "NFeAutorizacao", msg, "retEnviNFe", opcoes.signal);
3949
- const v = decode(TRetEnviNFe, r.ret, r.doc.source).value;
4149
+ const v = decodificar(TRetEnviNFe, r.ret, r.doc.texto).valor;
3950
4150
  const status = { cStat: v.cStat, xMotivo: v.xMotivo };
3951
4151
  logger.info("nfe.autorizacao", { chNFe: a.id.slice(3), cStat: v.cStat, sincrono });
3952
4152
  if (cstatEm(v.cStat, "loteRecebido")) {
3953
4153
  const nRec = v.infRec?.nRec;
3954
4154
  if (!nRec)
3955
- throw new ProtocolError4("lote recebido sem número de recibo");
4155
+ throw new ErroRespostaInvalida4("lote recebido sem número de recibo");
3956
4156
  const tMed = Number(v.infRec?.tMed ?? "0");
3957
- return pending(status, { ref: nRec, retryAfterMs: Math.max(1, tMed) * 1000 });
4157
+ return criarPendente(status, { referencia: nRec, aguardarMs: Math.max(1, tMed) * 1000 });
3958
4158
  }
3959
4159
  const protEl = protNFeDaChave(r.ret, a);
3960
4160
  if (protEl)
@@ -3968,21 +4168,23 @@ function createNfeClient(options) {
3968
4168
  const mult = politica.multiplicador ?? 1.5;
3969
4169
  const teto = politica.esperaMaximaMs ?? 30000;
3970
4170
  if (!(max >= 1) || !(minimo >= 0) || !(mult >= 1) || !(teto >= minimo)) {
3971
- throw new ConfigError4("política de consulta do recibo inválida", { details: { max, minimo, mult, teto } });
4171
+ throw new ErroDeConfiguracao4("política de consulta do recibo inválida", {
4172
+ detalhes: { max, minimo, mult, teto }
4173
+ });
3972
4174
  }
3973
4175
  let espera = minimo;
3974
4176
  let ultimo;
3975
4177
  for (let i = 0;i < max; i++) {
3976
4178
  await sleep(espera, politica.signal);
3977
4179
  ultimo = await consultarRecibo(nRec, nfeAssinada, politica);
3978
- if (ultimo.status !== "pending")
4180
+ if (ultimo.tipo !== "pendente")
3979
4181
  return ultimo;
3980
- espera = Math.min(teto, Math.max(minimo, Math.round(espera * mult), ultimo.retryAfterMs ?? 0));
4182
+ espera = Math.min(teto, Math.max(minimo, Math.round(espera * mult), ultimo.aguardarMs ?? 0));
3981
4183
  }
3982
4184
  return ultimo;
3983
4185
  },
3984
4186
  consultar,
3985
- async cancelar(p) {
4187
+ async cancelar(p, opcoes) {
3986
4188
  const c = chaveValida(p.chave, "chave");
3987
4189
  return enviarEvento({
3988
4190
  ct: TEventoCanc,
@@ -3993,17 +4195,18 @@ function createNfeClient(options) {
3993
4195
  autor: autorDoEmitente(p.autor, c),
3994
4196
  detEvento: { versao: EVENTO_VERSAO, descEvento: "Cancelamento", nProt: p.nProt, xJust: p.xJust },
3995
4197
  endpoint: endpointDaChave("RecepcaoEvento", c),
3996
- offsetMinutes: offsetDe(c.uf)
4198
+ offsetMinutes: offsetDe(c.uf),
4199
+ signal: opcoes?.signal
3997
4200
  });
3998
4201
  },
3999
- async cancelarPorSubstituicao(p) {
4202
+ async cancelarPorSubstituicao(p, opcoes) {
4000
4203
  const c = chaveValida(p.chave, "chave");
4001
4204
  if (c.mod !== "65") {
4002
- throw new ValidationError2("cancelamento por substituição só existe para NFC-e", [
4205
+ throw new ErroDeValidacao2("cancelamento por substituição só existe para NFC-e", [
4003
4206
  {
4004
- path: "chave",
4207
+ caminho: "chave",
4005
4208
  code: "modelo_nao_suportado",
4006
- message: "O evento 110112 é exclusivo da NFC-e (modelo 65)"
4209
+ mensagem: "O evento 110112 é exclusivo da NFC-e (modelo 65)"
4007
4210
  }
4008
4211
  ]);
4009
4212
  }
@@ -4027,13 +4230,14 @@ function createNfeClient(options) {
4027
4230
  autor: autorDoEmitente(p.autor, c),
4028
4231
  detEvento,
4029
4232
  endpoint: endpointDaChave("RecepcaoEvento", c),
4030
- offsetMinutes: offsetDe(c.uf)
4233
+ offsetMinutes: offsetDe(c.uf),
4234
+ signal: opcoes?.signal
4031
4235
  });
4032
4236
  },
4033
- async cartaCorrecao(p) {
4237
+ async cartaCorrecao(p, opcoes) {
4034
4238
  const c = chaveValida(p.chave, "chave");
4035
4239
  if (!Number.isInteger(p.nSeqEvento) || p.nSeqEvento < 1 || p.nSeqEvento > 20) {
4036
- throw new ConfigError4(`nSeqEvento da CC-e vai de 1 a 20: ${p.nSeqEvento}`);
4240
+ throw new ErroDeConfiguracao4(`nSeqEvento da CC-e vai de 1 a 20: ${p.nSeqEvento}`);
4037
4241
  }
4038
4242
  return enviarEvento({
4039
4243
  ct: TEventoCce,
@@ -4049,14 +4253,15 @@ function createNfeClient(options) {
4049
4253
  xCondUso: XCONDUSO
4050
4254
  },
4051
4255
  endpoint: endpointDaChave("RecepcaoEvento", c, true),
4052
- offsetMinutes: offsetDe(c.uf)
4256
+ offsetMinutes: offsetDe(c.uf),
4257
+ signal: opcoes?.signal
4053
4258
  });
4054
4259
  },
4055
- async manifestar(p) {
4260
+ async manifestar(p, opcoes) {
4056
4261
  const c = chaveValida(p.chave, "chave");
4057
4262
  const m = MANIFESTACOES[p.tipo];
4058
4263
  if (!m)
4059
- throw new ConfigError4(`tipo de manifestação desconhecido: ${String(p.tipo)}`);
4264
+ throw new ErroDeConfiguracao4(`tipo de manifestação desconhecido: ${String(p.tipo)}`);
4060
4265
  return enviarEvento({
4061
4266
  ct: m.ct,
4062
4267
  tpEvento: m.tpEvento,
@@ -4069,18 +4274,19 @@ function createNfeClient(options) {
4069
4274
  descEvento: m.descEvento,
4070
4275
  ...p.xJust === undefined ? {} : { xJust: p.xJust }
4071
4276
  },
4072
- endpoint: nfeEndpoint({ ambiente: options.ambiente, servico: "RecepcaoEvento", autorizador: "AN" }),
4073
- offsetMinutes: offsetDe(options.uf ?? c.uf)
4277
+ endpoint: nfeEndpoint({ ambiente: opcoesDoCliente.ambiente, servico: "RecepcaoEvento", autorizador: "AN" }),
4278
+ offsetMinutes: offsetDe(opcoesDoCliente.uf ?? c.uf),
4279
+ signal: opcoes?.signal
4074
4280
  });
4075
4281
  },
4076
- async inutilizar(p) {
4282
+ async inutilizar(p, opcoes) {
4077
4283
  const autor = autorPadrao(p.autor, "autor");
4078
4284
  if (!("CNPJ" in autor)) {
4079
- throw new ValidationError2("inutilização não se aplica ao emitente pessoa física", [
4285
+ throw new ErroDeValidacao2("inutilização não se aplica ao emitente pessoa física", [
4080
4286
  {
4081
- path: "autor.CPF",
4287
+ caminho: "autor.CPF",
4082
4288
  code: "inutilizacao_emitente_cpf",
4083
- message: "O pedido de inutilização só existe para emitente CNPJ (NT 2018.001 v1.10, item 6.1)"
4289
+ mensagem: "O pedido de inutilização só existe para emitente CNPJ (NT 2018.001 v1.10, item 6.1)"
4084
4290
  }
4085
4291
  ]);
4086
4292
  }
@@ -4099,16 +4305,16 @@ function createNfeClient(options) {
4099
4305
  ["nNFFin", fin, /^[1-9][0-9]{0,8}$/]
4100
4306
  ]) {
4101
4307
  if (!re.test(x))
4102
- throw new ConfigError4(`${k} inválido para inutilização: ${x}`);
4308
+ throw new ErroDeConfiguracao4(`${k} inválido para inutilização: ${x}`);
4103
4309
  }
4104
4310
  if (Number(fin) < Number(ini))
4105
- throw new ConfigError4("nNFFin menor que nNFIni");
4311
+ throw new ErroDeConfiguracao4("nNFFin menor que nNFIni");
4106
4312
  if (Number(serie) >= 910 && Number(serie) <= 969) {
4107
- throw new ValidationError2("série de emitente pessoa física não se inutiliza", [
4313
+ throw new ErroDeValidacao2("série de emitente pessoa física não se inutiliza", [
4108
4314
  {
4109
- path: "serie",
4315
+ caminho: "serie",
4110
4316
  code: "inutilizacao_serie_cpf",
4111
- message: "Série 910 a 969 identifica emitente CPF: a SEFAZ rejeita com 266 (NT 2018.001 v1.10, regra I02a)"
4317
+ mensagem: "Série 910 a 969 identifica emitente CPF: a SEFAZ rejeita com 266 (NT 2018.001 v1.10, regra I02a)"
4112
4318
  }
4113
4319
  ]);
4114
4320
  }
@@ -4126,14 +4332,14 @@ function createNfeClient(options) {
4126
4332
  nNFFin: fin,
4127
4333
  xJust: p.xJust
4128
4334
  };
4129
- const infXml = serialize3(TInutNFe_infInut, "infInut", inf, NFE_NS4);
4335
+ const infXml = serializar3(TInutNFe_infInut, "infInut", inf, NFE_NS4);
4130
4336
  const inut = envelope("inutNFe", "4.00", [infXml]);
4131
- const infEl = firstChild5(parseXml6(inut).root, "infInut", NFE_NS4);
4132
- schemaIssues("pedido de inutilização", validate4(TInutNFe_infInut, infEl));
4133
- const assinado = await signXml2(inut, { id }, options.signer);
4134
- const ep = mod === "65" ? endpointNfce("NfeInutilizacao", uf) : nfeEndpoint({ ambiente: options.ambiente, servico: "NfeInutilizacao", uf });
4135
- const r = await call(ep, "NfeInutilizacao", assinado, "retInutNFe");
4136
- const v = decode(TRetInutNFe, r.ret, r.doc.source).value;
4337
+ const infEl = primeiroFilho5(lerXml6(inut).raiz, "infInut", NFE_NS4);
4338
+ schemaIssues("pedido de inutilização", validar4(TInutNFe_infInut, infEl));
4339
+ const assinado = await assinarXml2(inut, { id }, opcoesDoCliente.assinador);
4340
+ const ep = mod === "65" ? endpointNfce("NfeInutilizacao", uf) : nfeEndpoint({ ambiente: opcoesDoCliente.ambiente, servico: "NfeInutilizacao", uf });
4341
+ const r = await call(ep, "NfeInutilizacao", assinado, "retInutNFe", opcoes?.signal);
4342
+ const v = decodificar(TRetInutNFe, r.ret, r.doc.texto).valor;
4137
4343
  const status = { cStat: v.infInut.cStat, xMotivo: v.infInut.xMotivo };
4138
4344
  logger.info("nfe.inutilizacao", { id, cStat: status.cStat });
4139
4345
  if (!cstatEm(status.cStat, "inutilizacaoHomologada"))
@@ -4150,65 +4356,65 @@ function createNfeClient(options) {
4150
4356
  ];
4151
4357
  const fora = confere.filter(([, veio, pedido]) => veio !== undefined && veio !== pedido);
4152
4358
  if (fora.length > 0) {
4153
- throw new ProtocolError4("retInutNFe de outra faixa", {
4154
- details: Object.fromEntries(fora.map(([k, v]) => [k, v]))
4359
+ throw new ErroRespostaInvalida4("retInutNFe de outra faixa", {
4360
+ detalhes: Object.fromEntries(fora.map(([k, v]) => [k, v]))
4155
4361
  });
4156
4362
  }
4157
- return authorized(status, {
4363
+ return criarAutorizado(status, {
4158
4364
  dhRecbto: v.infInut.dhRecbto,
4159
4365
  retInutNFe: avulso(r.doc, r.ret),
4160
- procInutNFe: envelope("ProcInutNFe", "4.00", [assinado, sliceElement(r.doc, r.ret)]),
4366
+ procInutNFe: envelope("ProcInutNFe", "4.00", [assinado, recortarElemento(r.doc, r.ret)]),
4161
4367
  ...v.infInut.nProt === undefined ? {} : { nProt: v.infInut.nProt }
4162
4368
  });
4163
4369
  },
4164
- async consultarCadastro(p) {
4370
+ async consultarCadastro(p, opcoes) {
4165
4371
  const doc = "CNPJ" in p ? documentoAutor({ CNPJ: p.CNPJ }, "CNPJ") : ("CPF" in p) ? documentoAutor({ CPF: p.CPF }, "CPF") : { IE: p.IE.replace(/[^0-9A-Za-z]/g, "").toUpperCase() };
4166
- const msg = serializeRoot(ConsCadElement, { versao: "2.00", infCons: { xServ: "CONS-CAD", UF: p.uf, ...doc } });
4167
- const ep = nfeEndpoint({ ambiente: options.ambiente, servico: "NfeConsultaCadastro", uf: p.uf });
4168
- const r = await call(ep, "NfeConsultaCadastro", msg, "retConsCad");
4169
- const v = decode(TRetConsCad, r.ret, r.doc.source).value;
4372
+ const msg = serializarRaiz(ConsCadElement, { versao: "2.00", infCons: { xServ: "CONS-CAD", UF: p.uf, ...doc } });
4373
+ const ep = nfeEndpoint({ ambiente: opcoesDoCliente.ambiente, servico: "NfeConsultaCadastro", uf: p.uf });
4374
+ const r = await call(ep, "NfeConsultaCadastro", msg, "retConsCad", opcoes?.signal);
4375
+ const v = decodificar(TRetConsCad, r.ret, r.doc.texto).valor;
4170
4376
  const i = v.infCons;
4171
4377
  const status = { cStat: i.cStat, xMotivo: i.xMotivo };
4172
4378
  logger.info("nfe.cadastro", { uf: p.uf, cStat: i.cStat });
4173
4379
  if (!cstatEm(i.cStat, "cadastroEncontrado"))
4174
4380
  return rejeitado(status);
4175
- return authorized(status, { UF: i.UF, dhCons: i.dhCons, infCad: i.infCad ?? [] });
4381
+ return criarAutorizado(status, { UF: i.UF, dhCons: i.dhCons, infCad: i.infCad ?? [] });
4176
4382
  },
4177
4383
  async distribuicaoDFe(consulta, opcoes = {}) {
4178
4384
  const autor = autorPadrao(opcoes.autor, "autor");
4179
4385
  const nsu = (x, k) => {
4180
4386
  const s = String(x);
4181
4387
  if (!/^[0-9]{1,15}$/.test(s))
4182
- throw new ConfigError4(`${k} inválido: ${s}`);
4388
+ throw new ErroDeConfiguracao4(`${k} inválido: ${s}`);
4183
4389
  return s.padStart(15, "0");
4184
4390
  };
4185
4391
  const grupo = "ultNSU" in consulta ? { distNSU: { ultNSU: nsu(consulta.ultNSU, "ultNSU") } } : ("NSU" in consulta) ? { consNSU: { NSU: nsu(consulta.NSU, "NSU") } } : { consChNFe: { chNFe: chaveValida(consulta.chNFe, "chNFe").chave } };
4186
4392
  const cUFAutor = opcoes.cUFAutor ?? ufPadrao("NFeDistribuicaoDFe").cUF;
4187
- if (ufByCUf2(cUFAutor) === undefined)
4188
- throw new ConfigError4(`cUFAutor inválido: ${cUFAutor}`);
4189
- const msg = serializeRoot(distDFeIntElement, {
4393
+ if (ufPorCUf2(cUFAutor) === undefined)
4394
+ throw new ErroDeConfiguracao4(`cUFAutor inválido: ${cUFAutor}`);
4395
+ const msg = serializarRaiz(distDFeIntElement, {
4190
4396
  versao: "1.01",
4191
4397
  tpAmb,
4192
4398
  cUFAutor,
4193
4399
  ...autor,
4194
4400
  ...grupo
4195
4401
  });
4196
- const ep = nfeEndpoint({ ambiente: options.ambiente, servico: "NFeDistribuicaoDFe" });
4197
- const r = await call(ep, "NFeDistribuicaoDFe", msg, "retDistDFeInt");
4198
- const v = decode(retDistDFeInt, r.ret, r.doc.source).value;
4402
+ const ep = nfeEndpoint({ ambiente: opcoesDoCliente.ambiente, servico: "NFeDistribuicaoDFe" });
4403
+ const r = await call(ep, "NFeDistribuicaoDFe", msg, "retDistDFeInt", opcoes.signal);
4404
+ const v = decodificar(retDistDFeInt, r.ret, r.doc.texto).valor;
4199
4405
  const status = { cStat: v.cStat, xMotivo: v.xMotivo };
4200
4406
  logger.info("nfe.distribuicao", { cStat: v.cStat, ultNSU: v.ultNSU, maxNSU: v.maxNSU });
4201
4407
  const base = { ultNSU: v.ultNSU, maxNSU: v.maxNSU, dhResp: v.dhResp };
4202
4408
  if (cstatEm(v.cStat, "distribuicaoNenhumDocumento"))
4203
- return authorized(status, { ...base, documentos: [] });
4409
+ return criarAutorizado(status, { ...base, documentos: [] });
4204
4410
  if (!cstatEm(v.cStat, "distribuicaoDocumentos"))
4205
4411
  return rejeitado(status);
4206
4412
  const documentos = [];
4207
4413
  for (const z of v.loteDistDFeInt?.docZip ?? []) {
4208
- const xml = await gunzipBase64(z.$text);
4414
+ const xml = await descomprimirGzipBase64(z.$text);
4209
4415
  documentos.push(documentoDistribuido(z.NSU ?? "", z.schema, xml));
4210
4416
  }
4211
- return authorized(status, { ...base, documentos });
4417
+ return criarAutorizado(status, { ...base, documentos });
4212
4418
  }
4213
4419
  };
4214
4420
  return client;
@@ -4217,9 +4423,9 @@ function documentoDistribuido(NSU, schema, xml) {
4217
4423
  const nome = schema.replace(/_v?\d.*$/, "");
4218
4424
  const base = { NSU, schema, xml };
4219
4425
  if (nome === "resNFe")
4220
- return { ...base, tipo: "resNFe", resNFe: decodeXml(resNFeElement, xml).value };
4426
+ return { ...base, tipo: "resNFe", resNFe: decodificarXml(resNFeElement, xml).valor };
4221
4427
  if (nome === "resEvento")
4222
- return { ...base, tipo: "resEvento", resEvento: decodeXml(resEventoElement, xml).value };
4428
+ return { ...base, tipo: "resEvento", resEvento: decodificarXml(resEventoElement, xml).valor };
4223
4429
  if (nome === "procNFe")
4224
4430
  return { ...base, tipo: "procNFe" };
4225
4431
  if (nome === "procEventoNFe")
@@ -4227,23 +4433,23 @@ function documentoDistribuido(NSU, schema, xml) {
4227
4433
  return { ...base, tipo: "outro" };
4228
4434
  }
4229
4435
  // packages/nfe/src/services/recuperar.ts
4230
- import { firstChild as firstChild6, parseXml as parseXml7, textOf as textOf3 } from "@sinete/core/xml";
4436
+ import { lerXml as lerXml7, primeiroFilho as primeiroFilho6, textoDe as textoDe3 } from "@sinete/core/xml";
4231
4437
  function campo(el, local) {
4232
- const c = firstChild6(el, local, NFE_NS4);
4233
- return c === undefined ? undefined : textOf3(c).trim();
4438
+ const c = primeiroFilho6(el, local, NFE_NS4);
4439
+ return c === undefined ? undefined : textoDe3(c).trim();
4234
4440
  }
4235
4441
  function lerProcEvento(xml) {
4236
4442
  let doc;
4237
4443
  try {
4238
- doc = parseXml7(xml);
4444
+ doc = lerXml7(xml);
4239
4445
  } catch {
4240
4446
  return;
4241
4447
  }
4242
- const evento = firstChild6(doc.root, "evento", NFE_NS4);
4243
- const pedido = evento === undefined ? undefined : firstChild6(evento, "infEvento", NFE_NS4);
4244
- const retEl = firstChild6(doc.root, "retEvento", NFE_NS4);
4245
- const ret = retEl === undefined ? undefined : firstChild6(retEl, "infEvento", NFE_NS4);
4246
- if (doc.root.local !== "procEventoNFe" || pedido === undefined || retEl === undefined || ret === undefined) {
4448
+ const evento = primeiroFilho6(doc.raiz, "evento", NFE_NS4);
4449
+ const pedido = evento === undefined ? undefined : primeiroFilho6(evento, "infEvento", NFE_NS4);
4450
+ const retEl = primeiroFilho6(doc.raiz, "retEvento", NFE_NS4);
4451
+ const ret = retEl === undefined ? undefined : primeiroFilho6(retEl, "infEvento", NFE_NS4);
4452
+ if (doc.raiz.local !== "procEventoNFe" || pedido === undefined || retEl === undefined || ret === undefined) {
4247
4453
  return;
4248
4454
  }
4249
4455
  const cStat = campo(ret, "cStat");
@@ -4268,19 +4474,21 @@ function lerProcEvento(xml) {
4268
4474
  tpEvento,
4269
4475
  nSeqEvento: String(Number(nSeq)),
4270
4476
  dhRegEvento,
4271
- retEvento: sliceElement(doc, retEl, ""),
4477
+ retEvento: recortarElemento(doc, retEl, ""),
4272
4478
  procEventoNFe: xml,
4273
4479
  ...nProt === undefined ? {} : { nProt }
4274
4480
  };
4275
4481
  }
4276
- async function recuperarEventoRegistrado(client, chave, tpEvento) {
4277
- const consulta = await client.consultar(chave);
4278
- if (consulta.status !== "authorized" && consulta.status !== "denied")
4482
+ async function recuperarEventoRegistrado(cliente, chave, tpEvento, nSeqEvento, opcoes) {
4483
+ const consulta = await cliente.consultar(chave, undefined, opcoes);
4484
+ if (consulta.tipo !== "autorizado" && consulta.tipo !== "denegado")
4279
4485
  return { registrado: false, consulta };
4280
4486
  let achado;
4281
- for (const xml of consulta.value.eventos) {
4487
+ for (const xml of consulta.valor.eventos) {
4282
4488
  const e = lerProcEvento(xml);
4283
- if (e === undefined || e.chNFe !== consulta.value.chNFe || e.tpEvento !== tpEvento)
4489
+ if (e === undefined || e.chNFe !== consulta.valor.chNFe || e.tpEvento !== tpEvento)
4490
+ continue;
4491
+ if (nSeqEvento !== undefined && Number(e.nSeqEvento) !== nSeqEvento)
4284
4492
  continue;
4285
4493
  if (achado === undefined || Number(e.nSeqEvento) > Number(achado.nSeqEvento))
4286
4494
  achado = e;
@@ -4288,83 +4496,83 @@ async function recuperarEventoRegistrado(client, chave, tpEvento) {
4288
4496
  return achado === undefined ? { registrado: false, consulta } : { registrado: true, evento: achado, consulta };
4289
4497
  }
4290
4498
  // packages/nfe/src/services/resolver.ts
4291
- import { authorized as authorized2, denied as denied2 } from "@sinete/core";
4499
+ import { criarAutorizado as criarAutorizado2, criarDenegado as criarDenegado2 } from "@sinete/core";
4292
4500
  var CHAVE_NO_MOTIVO = /\[\s*chNFe\s*:\s*([0-9]{6}[0-9A-Z]{12}[0-9]{26})\s*\]/i;
4293
4501
  function chaveDaDuplicidade(xMotivo) {
4294
4502
  return CHAVE_NO_MOTIVO.exec(xMotivo)?.[1]?.toUpperCase();
4295
4503
  }
4296
- async function resolverEnvioSemResposta(client, nfeAssinada, anterior) {
4504
+ async function resolverEnvioSemResposta(cliente, nfeAssinada, anterior, opcoes) {
4297
4505
  const a = documentoAssinado(nfeAssinada, "NFe", "infNFe");
4298
4506
  const chave = a.id.slice(3);
4299
- if (anterior && anterior.status === "rejected" && cstatEm(anterior.cStat, "duplicidadeChaveDiferente")) {
4507
+ if (anterior && anterior.tipo === "recusado" && cstatEm(anterior.cStat, "duplicidadeChaveDiferente")) {
4300
4508
  const outra = chaveDaDuplicidade(anterior.xMotivo);
4301
4509
  return { acao: "divergente", motivo: anterior, ...outra === undefined ? {} : { chNFe: outra } };
4302
4510
  }
4303
- const consulta = await client.consultar(chave, nfeAssinada);
4304
- if (consulta.status === "rejected") {
4511
+ const consulta = await cliente.consultar(chave, nfeAssinada, opcoes);
4512
+ if (consulta.tipo === "recusado") {
4305
4513
  if (cstatEm(consulta.cStat, "naoConsta"))
4306
4514
  return { acao: "reenviar", nfeAssinada: a.xml };
4307
4515
  if (cstatEm(consulta.cStat, "outraNfeNoNumero")) {
4308
4516
  const outra = chaveDaDuplicidade(consulta.xMotivo);
4309
4517
  return { acao: "divergente", motivo: consulta, ...outra === undefined ? {} : { chNFe: outra } };
4310
4518
  }
4311
- return { acao: "indefinida", outcome: consulta };
4519
+ return { acao: "indefinida", resultado: consulta };
4312
4520
  }
4313
- if (consulta.status === "pending")
4314
- return { acao: "indefinida", outcome: consulta };
4315
- const v = consulta.value;
4521
+ if (consulta.tipo === "pendente")
4522
+ return { acao: "indefinida", resultado: consulta };
4523
+ const v = consulta.valor;
4316
4524
  const p = v.protocolo;
4317
4525
  if (!p)
4318
- return { acao: "indefinida", outcome: consulta };
4526
+ return { acao: "indefinida", resultado: consulta };
4319
4527
  const conteudo = p.digVal === undefined ? "sem-digval" : v.digValConfere === true ? "confere" : "difere";
4320
4528
  const protStatus = { cStat: p.cStat, xMotivo: p.xMotivo };
4321
4529
  if (v.situacao === "denegada")
4322
- return { acao: "concluida", situacao: "denegada", conteudo, outcome: denied2(protStatus, p) };
4530
+ return { acao: "concluida", situacao: "denegada", conteudo, resultado: criarDenegado2(protStatus, p) };
4323
4531
  if (conteudo === "difere")
4324
4532
  return { acao: "divergente", chNFe: chave, consulta, motivo: consulta };
4325
4533
  if (conteudo === "sem-digval")
4326
4534
  return { acao: "sem-prova", situacao: v.situacao, consulta };
4327
4535
  if (p.nfeProc === undefined)
4328
- return { acao: "indefinida", outcome: consulta };
4329
- return { acao: "concluida", situacao: v.situacao, conteudo, outcome: authorized2(protStatus, p) };
4536
+ return { acao: "indefinida", resultado: consulta };
4537
+ return { acao: "concluida", situacao: v.situacao, conteudo, resultado: criarAutorizado2(protStatus, p) };
4330
4538
  }
4331
4539
  export {
4540
+ CODIGOS_OCORRENCIA_NFE,
4332
4541
  Decimal,
4333
4542
  MotivoDesoneracaoIcms,
4334
4543
  NFCE_LIMITE_SEM_DESTINATARIO,
4335
- NFE_ISSUE_CODES,
4336
4544
  NFE_NS3 as NFE_NS,
4337
4545
  TipoPagamento,
4338
4546
  XNOME_HOMOLOGACAO,
4339
4547
  XPROD_HOMOLOGACAO_NFCE,
4548
+ assinarNfe,
4340
4549
  assinaturaQrCode,
4341
4550
  autorizadorContingencia,
4342
- buildNfe,
4551
+ calculadoraIbsCbs,
4343
4552
  carregarDatasetEmbarcado,
4344
4553
  chaveDaDuplicidade,
4345
4554
  comQrCode,
4346
4555
  conferirEmitenteDoCertificado,
4347
- createNfeClient,
4556
+ criarClienteNfe,
4348
4557
  dec,
4558
+ descomprimirGzipBase64,
4559
+ deslocamentoDaUf,
4349
4560
  documentoAssinado,
4350
4561
  exigenciaRespTec,
4351
- formatDecimal,
4352
- formatDh,
4353
- formatProblem,
4354
- gunzipBase64,
4562
+ formatarDecimal,
4563
+ formatarDh,
4355
4564
  hashCsrt,
4356
- ibsCbsCalculator,
4357
4565
  localDaOperacao,
4566
+ montarNfe,
4358
4567
  nfeAssinadaDoProc,
4359
- offsetDaUf,
4568
+ problemaDeFormato,
4569
+ recortarElemento,
4360
4570
  recuperarEventoRegistrado,
4361
4571
  resolverEnvioSemResposta,
4362
4572
  rotuloDoCaminho,
4363
- signNfe,
4364
- sliceElement,
4365
4573
  sum,
4366
4574
  urlsNfce
4367
4575
  };
4368
4576
 
4369
- //# debugId=91E6FDD0B4D20CBD64756E2164756E21
4577
+ //# debugId=9351F0AE81B9EE1064756E2164756E21
4370
4578
  //# sourceMappingURL=index.js.map