validation-br 2.2.0 → 2.6.0-beta.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 (118) hide show
  1. package/dist/cjs/_exceptions/ValidationBRError.d.ts +12 -0
  2. package/dist/cjs/_exceptions/ValidationBRError.js +30 -1
  3. package/dist/cjs/_helpers/pix-fields.d.ts +106 -0
  4. package/dist/cjs/_helpers/pix-fields.js +296 -0
  5. package/dist/cjs/_helpers/utils.d.ts +0 -1
  6. package/dist/cjs/_helpers/utils.js +0 -1
  7. package/dist/cjs/base.d.ts +12 -8
  8. package/dist/cjs/base.js +16 -0
  9. package/dist/cjs/boleto.d.ts +41 -7
  10. package/dist/cjs/boleto.js +58 -16
  11. package/dist/cjs/caepf.d.ts +36 -6
  12. package/dist/cjs/caepf.js +64 -25
  13. package/dist/cjs/carplate.d.ts +40 -7
  14. package/dist/cjs/carplate.js +61 -24
  15. package/dist/cjs/cep.d.ts +39 -13
  16. package/dist/cjs/cep.js +73 -36
  17. package/dist/cjs/certidao.d.ts +44 -2
  18. package/dist/cjs/certidao.js +68 -15
  19. package/dist/cjs/cib.d.ts +166 -0
  20. package/dist/cjs/cib.js +232 -0
  21. package/dist/cjs/cnh.d.ts +37 -6
  22. package/dist/cjs/cnh.js +67 -28
  23. package/dist/cjs/cnpj.d.ts +37 -7
  24. package/dist/cjs/cnpj.js +65 -26
  25. package/dist/cjs/cpf.d.ts +38 -10
  26. package/dist/cjs/cpf.js +66 -30
  27. package/dist/cjs/email.d.ts +35 -3
  28. package/dist/cjs/email.js +56 -24
  29. package/dist/cjs/index.d.ts +3 -1
  30. package/dist/cjs/index.js +25 -21
  31. package/dist/cjs/judicial-process.d.ts +39 -11
  32. package/dist/cjs/judicial-process.js +71 -31
  33. package/dist/cjs/nup17.d.ts +35 -10
  34. package/dist/cjs/nup17.js +61 -31
  35. package/dist/cjs/phone.d.ts +48 -16
  36. package/dist/cjs/phone.js +81 -38
  37. package/dist/cjs/pis-pasep.d.ts +37 -10
  38. package/dist/cjs/pis-pasep.js +65 -30
  39. package/dist/cjs/pix-copy-paste.d.ts +4 -0
  40. package/dist/cjs/pix-copy-paste.js +4 -0
  41. package/dist/cjs/pix-key.d.ts +58 -4
  42. package/dist/cjs/pix-key.js +97 -44
  43. package/dist/cjs/pix.d.ts +193 -0
  44. package/dist/cjs/pix.js +191 -0
  45. package/dist/cjs/postal-track-code.d.ts +39 -15
  46. package/dist/cjs/postal-track-code.js +63 -35
  47. package/dist/cjs/renavam.d.ts +36 -12
  48. package/dist/cjs/renavam.js +64 -33
  49. package/dist/cjs/standard-schema/index.d.ts +5 -2
  50. package/dist/cjs/standard-schema/index.js +6 -3
  51. package/dist/cjs/tituloEleitor.d.ts +39 -10
  52. package/dist/cjs/tituloEleitor.js +74 -31
  53. package/dist/cjs/uf.d.ts +30 -2
  54. package/dist/cjs/uf.js +54 -25
  55. package/dist/cjs/uuid.d.ts +36 -2
  56. package/dist/cjs/uuid.js +56 -16
  57. package/dist/esm/_exceptions/ValidationBRError.d.ts +12 -0
  58. package/dist/esm/_exceptions/ValidationBRError.js +26 -0
  59. package/dist/esm/_helpers/pix-fields.d.ts +106 -0
  60. package/dist/esm/_helpers/pix-fields.js +292 -0
  61. package/dist/esm/_helpers/utils.d.ts +0 -1
  62. package/dist/esm/_helpers/utils.js +0 -1
  63. package/dist/esm/base.d.ts +12 -8
  64. package/dist/esm/base.js +16 -0
  65. package/dist/esm/boleto.d.ts +41 -7
  66. package/dist/esm/boleto.js +58 -16
  67. package/dist/esm/caepf.d.ts +36 -6
  68. package/dist/esm/caepf.js +66 -27
  69. package/dist/esm/carplate.d.ts +40 -7
  70. package/dist/esm/carplate.js +61 -24
  71. package/dist/esm/cep.d.ts +39 -13
  72. package/dist/esm/cep.js +73 -36
  73. package/dist/esm/certidao.d.ts +44 -2
  74. package/dist/esm/certidao.js +68 -15
  75. package/dist/esm/cib.d.ts +166 -0
  76. package/dist/esm/cib.js +228 -0
  77. package/dist/esm/cnh.d.ts +37 -6
  78. package/dist/esm/cnh.js +69 -30
  79. package/dist/esm/cnpj.d.ts +37 -7
  80. package/dist/esm/cnpj.js +67 -28
  81. package/dist/esm/cpf.d.ts +38 -10
  82. package/dist/esm/cpf.js +68 -32
  83. package/dist/esm/email.d.ts +35 -3
  84. package/dist/esm/email.js +56 -21
  85. package/dist/esm/index.d.ts +3 -1
  86. package/dist/esm/index.js +23 -20
  87. package/dist/esm/judicial-process.d.ts +39 -11
  88. package/dist/esm/judicial-process.js +72 -32
  89. package/dist/esm/nup17.d.ts +35 -10
  90. package/dist/esm/nup17.js +63 -33
  91. package/dist/esm/phone.d.ts +48 -16
  92. package/dist/esm/phone.js +81 -38
  93. package/dist/esm/pis-pasep.d.ts +37 -10
  94. package/dist/esm/pis-pasep.js +67 -32
  95. package/dist/esm/pix-copy-paste.d.ts +4 -0
  96. package/dist/esm/pix-copy-paste.js +4 -0
  97. package/dist/esm/pix-key.d.ts +58 -4
  98. package/dist/esm/pix-key.js +97 -44
  99. package/dist/esm/pix.d.ts +193 -0
  100. package/dist/esm/pix.js +187 -0
  101. package/dist/esm/postal-track-code.d.ts +39 -15
  102. package/dist/esm/postal-track-code.js +64 -36
  103. package/dist/esm/renavam.d.ts +36 -12
  104. package/dist/esm/renavam.js +66 -35
  105. package/dist/esm/standard-schema/index.d.ts +5 -2
  106. package/dist/esm/standard-schema/index.js +5 -2
  107. package/dist/esm/tituloEleitor.d.ts +39 -10
  108. package/dist/esm/tituloEleitor.js +76 -33
  109. package/dist/esm/uf.d.ts +30 -2
  110. package/dist/esm/uf.js +55 -26
  111. package/dist/esm/uuid.d.ts +36 -2
  112. package/dist/esm/uuid.js +56 -13
  113. package/package.json +4 -3
  114. package/readme.md +166 -918
  115. package/dist/cjs/cbi_sinter.d.ts +0 -84
  116. package/dist/cjs/cbi_sinter.js +0 -131
  117. package/dist/esm/cbi_sinter.d.ts +0 -84
  118. package/dist/esm/cbi_sinter.js +0 -127
@@ -1,4 +1,9 @@
1
1
  import { Base } from './base';
2
+ import { CNPJ } from './cnpj';
3
+ import { CPF } from './cpf';
4
+ import { Email } from './email';
5
+ import { Phone } from './phone';
6
+ import { UUID } from './uuid';
2
7
  export declare enum PixKeys {
3
8
  email = "email",
4
9
  cpf = "cpf",
@@ -6,28 +11,77 @@ export declare enum PixKeys {
6
11
  evp = "evp",
7
12
  phone = "phone"
8
13
  }
14
+ export type PixTypeFn = CPF | CNPJ | UUID | Email | Phone;
9
15
  /**
10
16
  *
11
17
  * Valida se é uma chave pix
12
18
  *
13
19
  */
14
20
  export declare class PixKey extends Base {
15
- protected _value: string;
16
21
  protected _mask: null;
17
22
  private _type?;
18
- constructor(_value: string);
23
+ private _instance?;
24
+ /**
25
+ * Tabela de referência entre tipos e a função
26
+ */
27
+ static types: ({
28
+ type: PixKeys;
29
+ fn: typeof CPF;
30
+ } | {
31
+ type: PixKeys;
32
+ fn: typeof CNPJ;
33
+ } | {
34
+ type: PixKeys;
35
+ fn: typeof UUID;
36
+ } | {
37
+ type: PixKeys;
38
+ fn: typeof Email;
39
+ } | {
40
+ type: PixKeys;
41
+ fn: typeof Phone;
42
+ })[];
43
+ constructor(value: string | PixTypeFn);
19
44
  get type(): PixKeys | undefined;
45
+ get fn(): PixTypeFn;
46
+ get value(): string;
20
47
  /**
21
48
  * Delega a ocultação para a classe correspondente ao tipo identificado da chave Pix
22
49
  * (`CPF`, `CNPJ`, `Email`, `Phone` ou `UUID`).
23
50
  */
24
51
  redact(): string;
25
52
  /**
26
- * Gera uma chave fake
53
+ * isValid()
54
+ * Diz se um valor é uma chave Pix válida (CPF, CNPJ, chave aleatória, e-mail ou telefone),
55
+ * sem criar uma instância e sem lançar exceção.
56
+ *
57
+ * @example
58
+ * PixKey.isValid('123.456.789-09') // -> true
59
+ * PixKey.isValid('fulano@exemplo.com') // -> true
60
+ * PixKey.isValid(' fulano@exemplo.com') // -> false
61
+ */
62
+ static isValid(value: string): boolean;
63
+ mask(): string;
64
+ /**
65
+ * Gera uma chave válida aleatória
66
+ */
67
+ static generate(options?: PixKeyOptions): PixKey;
68
+ /**
69
+ * @deprecated Use generate(). Será removido em uma versão futura.
27
70
  */
28
71
  static fake(options?: PixKeyOptions): PixKey;
72
+ /**
73
+ * Procura o tipo da chave e diz se algum deles aceitou o valor.
74
+ */
29
75
  protected validate(): boolean;
30
- protected normalize(): void;
76
+ /**
77
+ * Define a função, tipo e instância a partir do valor.
78
+ *
79
+ */
80
+ protected getFnFromValue(): void;
81
+ /**
82
+ * Acha o tipo PixKey a partir da instância
83
+ */
84
+ protected getTypeFromInstance(): PixKeys;
31
85
  }
32
86
  export interface PixKeyOptions {
33
87
  type?: PixKeys;
@@ -7,7 +7,6 @@ const base_1 = require("./base");
7
7
  const cnpj_1 = require("./cnpj");
8
8
  const cpf_1 = require("./cpf");
9
9
  const email_1 = require("./email");
10
- const _1 = require(".");
11
10
  const phone_1 = require("./phone");
12
11
  const uuid_1 = require("./uuid");
13
12
  var PixKeys;
@@ -24,35 +23,56 @@ var PixKeys;
24
23
  *
25
24
  */
26
25
  class PixKey extends base_1.Base {
27
- constructor(_value) {
28
- super(_value);
29
- this._value = _value;
26
+ constructor(value) {
27
+ super(typeof value == 'string' ? value : value === null || value === void 0 ? void 0 : value.value);
30
28
  this._mask = null;
31
- this.normalize();
32
- if (!this.validate()) {
29
+ if (typeof value == 'string') {
30
+ // Sem trim(): cada tipo de chave confere o próprio formato, e espaço nas pontas é rejeitado
31
+ if (!this.validate()) {
32
+ throw new ValidationBRError_1.InvalidFormatException();
33
+ }
34
+ }
35
+ else if (PixKey.types.some(({ fn }) => value instanceof fn)) {
36
+ this._instance = value;
37
+ this._type = this.getTypeFromInstance();
38
+ }
39
+ else {
33
40
  throw new ValidationBRError_1.InvalidFormatException();
34
41
  }
35
42
  }
36
43
  get type() {
37
44
  return this._type;
38
45
  }
46
+ get fn() {
47
+ return this._instance;
48
+ }
49
+ get value() {
50
+ if (this._type == PixKeys.evp)
51
+ return this._instance.mask();
52
+ return this._instance.value;
53
+ }
39
54
  /**
40
55
  * Delega a ocultação para a classe correspondente ao tipo identificado da chave Pix
41
56
  * (`CPF`, `CNPJ`, `Email`, `Phone` ou `UUID`).
42
57
  */
43
58
  redact() {
44
- switch (this._type) {
45
- case PixKeys.cpf:
46
- return new cpf_1.CPF(this._value).redact();
47
- case PixKeys.cnpj:
48
- return new cnpj_1.CNPJ(this._value).redact();
49
- case PixKeys.email:
50
- return new email_1.Email(this._value).redact();
51
- case PixKeys.phone:
52
- return new phone_1.Phone(this._value).redact();
53
- default:
54
- return new uuid_1.UUID(this._value).redact();
55
- }
59
+ return this._instance.redact();
60
+ }
61
+ /**
62
+ * isValid()
63
+ * Diz se um valor é uma chave Pix válida (CPF, CNPJ, chave aleatória, e-mail ou telefone),
64
+ * sem criar uma instância e sem lançar exceção.
65
+ *
66
+ * @example
67
+ * PixKey.isValid('123.456.789-09') // -> true
68
+ * PixKey.isValid('fulano@exemplo.com') // -> true
69
+ * PixKey.isValid(' fulano@exemplo.com') // -> false
70
+ */
71
+ static isValid(value) {
72
+ return PixKey.types.some(({ fn }) => fn.isValid(value));
73
+ }
74
+ mask() {
75
+ return this._instance.mask();
56
76
  }
57
77
  //
58
78
  //
@@ -60,46 +80,79 @@ class PixKey extends base_1.Base {
60
80
  //
61
81
  //
62
82
  /**
63
- * Gera uma chave fake
83
+ * Gera uma chave válida aleatória
84
+ */
85
+ static generate(options = {}) {
86
+ const fn = options.type
87
+ ? PixKey.types.find(({ type }) => type == options.type).fn
88
+ : random_1.Random.fromArray([cnpj_1.CNPJ, cpf_1.CPF, phone_1.Phone, email_1.Email, uuid_1.UUID]);
89
+ return new PixKey(fn.generate());
90
+ // let fn;
91
+ // switch (options.type) {
92
+ // case PixKeys.cnpj: fn = CNPJ;
93
+ // case PixKeys.cpf: fn = CPF;
94
+ // case PixKeys.phone: fn = Phone;
95
+ // case PixKeys.email: fn = Email;
96
+ // case PixKeys.evp: fn = UUID;
97
+ // default:
98
+ // fn = Random.fromArray([CNPJ, CPF, Phone, Email, UUID])
99
+ // }
100
+ // return new PixKey(fn.generate().toString());
101
+ }
102
+ /**
103
+ * @deprecated Use generate(). Será removido em uma versão futura.
64
104
  */
65
105
  static fake(options = {}) {
66
- if (!options.type) {
67
- options.type = random_1.Random.fromArray([
68
- PixKeys.cnpj, PixKeys.cpf, PixKeys.email, PixKeys.evp, PixKeys.phone,
69
- ]);
70
- }
71
- if ((options === null || options === void 0 ? void 0 : options.type) == PixKeys.cnpj)
72
- return new PixKey(cnpj_1.CNPJ.fake().toString());
73
- if ((options === null || options === void 0 ? void 0 : options.type) == PixKeys.cpf)
74
- return new PixKey(cpf_1.CPF.fake().toString());
75
- if ((options === null || options === void 0 ? void 0 : options.type) == PixKeys.phone)
76
- return new PixKey(phone_1.Phone.fake().toString());
77
- if ((options === null || options === void 0 ? void 0 : options.type) == PixKeys.email)
78
- return new PixKey(email_1.Email.fake().toString());
79
- return new PixKey(uuid_1.UUID.fake().toString());
106
+ return PixKey.generate(options);
80
107
  }
81
108
  //
82
109
  //
83
110
  // PROTECTED
84
111
  //
85
112
  //
113
+ /**
114
+ * Procura o tipo da chave e diz se algum deles aceitou o valor.
115
+ */
86
116
  validate() {
87
- return [
88
- { type: PixKeys.cpf, fn: _1.isCPF },
89
- { type: PixKeys.cnpj, fn: _1.isCNPJ },
90
- { type: PixKeys.evp, fn: _1.isUUID },
91
- { type: PixKeys.email, fn: _1.isEmail },
92
- { type: PixKeys.phone, fn: _1.isPhone },
93
- ].some(({ type, fn }) => {
94
- if (fn(this._value)) {
117
+ var _a;
118
+ this.getFnFromValue();
119
+ return ((_a = this._instance) === null || _a === void 0 ? void 0 : _a.value) ? true : false;
120
+ }
121
+ /**
122
+ * Define a função, tipo e instância a partir do valor.
123
+ *
124
+ */
125
+ getFnFromValue() {
126
+ PixKey.types.some(({ type, fn }) => {
127
+ try {
128
+ // Tenta instanciar
129
+ this._instance = new fn(this._value);
95
130
  this._type = type;
96
131
  return true;
97
132
  }
98
- return false;
133
+ catch (error) {
134
+ return false;
135
+ }
99
136
  });
100
137
  }
101
- normalize() {
102
- this._value = this._value.trim().toLocaleLowerCase();
138
+ /**
139
+ * Acha o tipo PixKey a partir da instância
140
+ */
141
+ getTypeFromInstance() {
142
+ const found = PixKey.types.find(({ type, fn }) => {
143
+ return this._instance instanceof fn;
144
+ });
145
+ return found.type;
103
146
  }
104
147
  }
105
148
  exports.PixKey = PixKey;
149
+ /**
150
+ * Tabela de referência entre tipos e a função
151
+ */
152
+ PixKey.types = [
153
+ { type: PixKeys.cpf, fn: cpf_1.CPF },
154
+ { type: PixKeys.cnpj, fn: cnpj_1.CNPJ },
155
+ { type: PixKeys.evp, fn: uuid_1.UUID },
156
+ { type: PixKeys.email, fn: email_1.Email },
157
+ { type: PixKeys.phone, fn: phone_1.Phone },
158
+ ];
@@ -0,0 +1,193 @@
1
+ /**
2
+ * Pix
3
+ * Valida, lê e gera o Pix copia e cola (BR Code)
4
+ *
5
+ * @doc
6
+ * O Pix copia e cola é uma sequência de campos no formato "id + tamanho + valor":
7
+ * 2 dígitos de id, 2 dígitos de tamanho e o valor. Alguns campos têm outros campos
8
+ * dentro (26 e 62).
9
+ *
10
+ * - O código sempre começa com o campo 00 (formato), que vale "01": 000201
11
+ *
12
+ * - O código sempre termina com o campo 63 (CRC), que tem 4 caracteres
13
+ * hexadecimais: 6304XXXX
14
+ *
15
+ * - Entre o início e o fim, os campos podem estar em qualquer ordem. A geração
16
+ * usa sempre a ordem padrão
17
+ *
18
+ * - O valor não é alterado: espaços antes ou depois tornam o código inválido, e o
19
+ * código nunca é reordenado nem tem o CRC recalculado
20
+ *
21
+ * - A geração só cria Pix estático (com chave). O Pix dinâmico (com URL) é apenas
22
+ * lido e validado
23
+ *
24
+ * 1) Exemplo (campos separados para leitura)
25
+ * 000201 Formato
26
+ * 26330014BR.GOV.BCB.PIX011101234567890 Conta: arranjo e chave
27
+ * 52040000 Categoria
28
+ * 5303986 Moeda (real)
29
+ * 5802BR País
30
+ * 5904Jose Nome
31
+ * 6004Assu Cidade
32
+ * 62070503*** Dados adicionais: txId
33
+ * 6304XXXX CRC
34
+ *
35
+ * 2) Cálculo do CRC
36
+ * - CRC16/CCITT-FALSE (polinômio 0x1021, valor inicial 0xFFFF) sobre todo o código
37
+ * até o "6304", inclusive
38
+ *
39
+ * Fonte: Manual do BR Code (Banco Central)
40
+ * https://www.bcb.gov.br/content/estabilidadefinanceira/SiteAssets/Manual%20do%20BR%20Code.pdf
41
+ *
42
+ * @param {String} value Pix copia e cola
43
+ */
44
+ import { Base } from './base';
45
+ import type { CEP } from './cep';
46
+ import type { PixKey, PixTypeFn } from './pix-key';
47
+ export declare class Pix extends Base {
48
+ protected _value: string;
49
+ protected _mask: null;
50
+ /** Campos lidos no construtor */
51
+ private readonly _parsed;
52
+ /**
53
+ * Formato aceito: começa em 000201 e termina em 6304 + 4 caracteres hexadecimais.
54
+ * O ponto não aceita quebra de linha.
55
+ */
56
+ private static readonly _pattern;
57
+ /**
58
+ * Formato do código sem o CRC: começa em 000201 e termina em 6304.
59
+ * É o que o checksum() recebe.
60
+ */
61
+ private static readonly _basePattern;
62
+ constructor(_value: string);
63
+ /**
64
+ * Oculta o miolo do código (chave, nome, cidade e valor), mantendo os
65
+ * 12 primeiros caracteres e os 8 últimos (6304 + CRC).
66
+ * Ex.: `000201010212...***...6304FF60`
67
+ */
68
+ redact(): string;
69
+ /**
70
+ * parse()
71
+ * Devolve os campos do código, com o valor de cada um como está escrito nele.
72
+ *
73
+ * @example
74
+ * new Pix(code).parse().name // -> 'Jose'
75
+ */
76
+ parse(): PixParsed;
77
+ /**
78
+ * isValid()
79
+ * Diz se um código é válido, sem lançar exceção.
80
+ *
81
+ * @example
82
+ * Pix.isValid(code) // -> true
83
+ * Pix.isValid(` ${code}`) // -> false
84
+ */
85
+ static isValid(value: string): boolean;
86
+ /**
87
+ * parse()
88
+ * Valida um código e devolve os seus campos.
89
+ *
90
+ * @throws Quando o código é inválido; a mensagem indica o motivo
91
+ * @example
92
+ * Pix.parse(code).account.key // -> '01234567890'
93
+ */
94
+ static parse(value: string): PixParsed;
95
+ /**
96
+ * checksum()
97
+ * Calcula o CRC de um código SEM o CRC incluído, ou seja, terminando em 6304.
98
+ *
99
+ * @example
100
+ * Pix.checksum('000201...6304') // -> '1D3D'
101
+ */
102
+ static checksum(value: string): string;
103
+ /**
104
+ * generate()
105
+ * Cria um Pix estático a partir dos dados do recebedor.
106
+ *
107
+ * @example
108
+ * Pix.generate({ key: 'fulano@exemplo.com', name: 'Fulano', city: 'Assu' })
109
+ * // -> Pix { value: '000201...6304XXXX' }
110
+ */
111
+ static generate(input: PixGenerateInput): Pix;
112
+ /**
113
+ * _matches()
114
+ * Confere o início (000201) e o fim (6304 + CRC) do código.
115
+ * Só aceita texto.
116
+ */
117
+ private static _matches;
118
+ /**
119
+ * _check()
120
+ * Compara o CRC informado com o calculado. O CRC pode vir em minúsculas.
121
+ */
122
+ private static _check;
123
+ /**
124
+ * _read()
125
+ * Lê os campos do código, sem o campo do CRC.
126
+ */
127
+ private static _read;
128
+ }
129
+ /** Dados para gerar um Pix estático */
130
+ export interface PixGenerateInput {
131
+ /** Chave Pix: texto, PixKey ou instância de CPF, CNPJ, Email, Phone ou UUID. Até 77 caracteres */
132
+ key: string | PixKey | PixTypeFn;
133
+ /** Nome do recebedor. Convertido para ASCII e cortado em 25 caracteres */
134
+ name: string;
135
+ /** Cidade do recebedor. Convertida para ASCII e cortada em 15 caracteres */
136
+ city: string;
137
+ /** Valor, com ponto como separador decimal. Sem valor (ou zero), o pagador informa quanto pagar */
138
+ amount?: number | string | null;
139
+ /** Identificador da transação: até 25 letras e números. Sem ele, é usado *** */
140
+ txId?: string | number | null;
141
+ /** Descrição. Convertida para ASCII e cortada em 25 caracteres */
142
+ description?: string | null;
143
+ /** CEP do recebedor, em texto ou instância de CEP. Número é rejeitado, porque perde o zero à esquerda */
144
+ zipcode?: string | CEP | null;
145
+ /** Indica um código que só pode ser pago uma vez */
146
+ isUnique?: boolean;
147
+ }
148
+ /** Campos de um Pix já lido. Os comentários indicam o id de cada um */
149
+ export interface PixParsed {
150
+ /** 00: versão do formato */
151
+ format: string;
152
+ /** 01: "12" indica um código de uso único */
153
+ initiation?: string;
154
+ /** 26: conta do recebedor */
155
+ account: {
156
+ /** 00: identificador do arranjo de pagamento */
157
+ gui: string;
158
+ /** 01: chave Pix (Pix estático) */
159
+ key?: string;
160
+ /** 02: descrição */
161
+ description?: string;
162
+ /** 25: URL da cobrança (Pix dinâmico) */
163
+ url?: string;
164
+ };
165
+ /** 52: categoria do recebedor */
166
+ category: string;
167
+ /** 53: moeda (986 é o real) */
168
+ currency: string;
169
+ /** 54: valor */
170
+ amount?: string;
171
+ /** 58: país */
172
+ country: string;
173
+ /** 59: nome do recebedor */
174
+ name: string;
175
+ /** 60: cidade do recebedor */
176
+ city: string;
177
+ /** 61: CEP do recebedor */
178
+ zipcode?: string;
179
+ /** 62: dados adicionais */
180
+ additional?: {
181
+ /** 05: identificador da transação */
182
+ txId?: string;
183
+ /** 50: sistema de pagamento */
184
+ system?: {
185
+ /** 00: identificador do sistema */
186
+ gui?: string;
187
+ /** 01: versão do sistema */
188
+ version?: string;
189
+ };
190
+ };
191
+ /** 63: CRC */
192
+ crc: string;
193
+ }
@@ -0,0 +1,191 @@
1
+ "use strict";
2
+ /**
3
+ * Pix
4
+ * Valida, lê e gera o Pix copia e cola (BR Code)
5
+ *
6
+ * @doc
7
+ * O Pix copia e cola é uma sequência de campos no formato "id + tamanho + valor":
8
+ * 2 dígitos de id, 2 dígitos de tamanho e o valor. Alguns campos têm outros campos
9
+ * dentro (26 e 62).
10
+ *
11
+ * - O código sempre começa com o campo 00 (formato), que vale "01": 000201
12
+ *
13
+ * - O código sempre termina com o campo 63 (CRC), que tem 4 caracteres
14
+ * hexadecimais: 6304XXXX
15
+ *
16
+ * - Entre o início e o fim, os campos podem estar em qualquer ordem. A geração
17
+ * usa sempre a ordem padrão
18
+ *
19
+ * - O valor não é alterado: espaços antes ou depois tornam o código inválido, e o
20
+ * código nunca é reordenado nem tem o CRC recalculado
21
+ *
22
+ * - A geração só cria Pix estático (com chave). O Pix dinâmico (com URL) é apenas
23
+ * lido e validado
24
+ *
25
+ * 1) Exemplo (campos separados para leitura)
26
+ * 000201 Formato
27
+ * 26330014BR.GOV.BCB.PIX011101234567890 Conta: arranjo e chave
28
+ * 52040000 Categoria
29
+ * 5303986 Moeda (real)
30
+ * 5802BR País
31
+ * 5904Jose Nome
32
+ * 6004Assu Cidade
33
+ * 62070503*** Dados adicionais: txId
34
+ * 6304XXXX CRC
35
+ *
36
+ * 2) Cálculo do CRC
37
+ * - CRC16/CCITT-FALSE (polinômio 0x1021, valor inicial 0xFFFF) sobre todo o código
38
+ * até o "6304", inclusive
39
+ *
40
+ * Fonte: Manual do BR Code (Banco Central)
41
+ * https://www.bcb.gov.br/content/estabilidadefinanceira/SiteAssets/Manual%20do%20BR%20Code.pdf
42
+ *
43
+ * @param {String} value Pix copia e cola
44
+ */
45
+ Object.defineProperty(exports, "__esModule", { value: true });
46
+ exports.Pix = void 0;
47
+ const ValidationBRError_1 = require("./_exceptions/ValidationBRError");
48
+ const crc_1 = require("./_helpers/crc");
49
+ const pix_fields_1 = require("./_helpers/pix-fields");
50
+ const base_1 = require("./base");
51
+ class Pix extends base_1.Base {
52
+ constructor(_value) {
53
+ super(_value);
54
+ this._value = _value;
55
+ this._mask = null;
56
+ // O formato é conferido com o valor exatamente como chegou
57
+ if (!Pix._matches(this._value)) {
58
+ throw new ValidationBRError_1.InvalidFormatException();
59
+ }
60
+ if (!Pix._check(this._value)) {
61
+ throw new ValidationBRError_1.InvalidChecksumException();
62
+ }
63
+ // Confere os campos em todos os níveis; a mensagem do erro indica o campo
64
+ this._parsed = Pix._read(this._value);
65
+ }
66
+ //
67
+ //
68
+ //
69
+ //
70
+ //
71
+ //
72
+ /**
73
+ * Oculta o miolo do código (chave, nome, cidade e valor), mantendo os
74
+ * 12 primeiros caracteres e os 8 últimos (6304 + CRC).
75
+ * Ex.: `000201010212...***...6304FF60`
76
+ */
77
+ redact() {
78
+ return `${this._value.slice(0, 12)}...***...${this._value.slice(-8)}`;
79
+ }
80
+ /**
81
+ * parse()
82
+ * Devolve os campos do código, com o valor de cada um como está escrito nele.
83
+ *
84
+ * @example
85
+ * new Pix(code).parse().name // -> 'Jose'
86
+ */
87
+ parse() {
88
+ // Cópia, para quem recebe não alterar a instância (os campos são só texto)
89
+ return JSON.parse(JSON.stringify(this._parsed));
90
+ }
91
+ //
92
+ //
93
+ //
94
+ //
95
+ //
96
+ //
97
+ /**
98
+ * isValid()
99
+ * Diz se um código é válido, sem lançar exceção.
100
+ *
101
+ * @example
102
+ * Pix.isValid(code) // -> true
103
+ * Pix.isValid(` ${code}`) // -> false
104
+ */
105
+ static isValid(value) {
106
+ try {
107
+ new Pix(value);
108
+ return true;
109
+ }
110
+ catch {
111
+ return false;
112
+ }
113
+ }
114
+ /**
115
+ * parse()
116
+ * Valida um código e devolve os seus campos.
117
+ *
118
+ * @throws Quando o código é inválido; a mensagem indica o motivo
119
+ * @example
120
+ * Pix.parse(code).account.key // -> '01234567890'
121
+ */
122
+ static parse(value) {
123
+ return new Pix(value).parse();
124
+ }
125
+ /**
126
+ * checksum()
127
+ * Calcula o CRC de um código SEM o CRC incluído, ou seja, terminando em 6304.
128
+ *
129
+ * @example
130
+ * Pix.checksum('000201...6304') // -> '1D3D'
131
+ */
132
+ static checksum(value) {
133
+ if (!value)
134
+ throw new ValidationBRError_1.EmptyValueException();
135
+ if (typeof value !== 'string' || !Pix._basePattern.test(value))
136
+ throw new ValidationBRError_1.InvalidFormatException();
137
+ return new crc_1.CRC(value).calculate();
138
+ }
139
+ /**
140
+ * generate()
141
+ * Cria um Pix estático a partir dos dados do recebedor.
142
+ *
143
+ * @example
144
+ * Pix.generate({ key: 'fulano@exemplo.com', name: 'Fulano', city: 'Assu' })
145
+ * // -> Pix { value: '000201...6304XXXX' }
146
+ */
147
+ static generate(input) {
148
+ const body = `${pix_fields_1.PixFields.build(input)}6304`;
149
+ return new Pix(`${body}${Pix.checksum(body)}`);
150
+ }
151
+ //
152
+ //
153
+ //
154
+ //
155
+ //
156
+ //
157
+ /**
158
+ * _matches()
159
+ * Confere o início (000201) e o fim (6304 + CRC) do código.
160
+ * Só aceita texto.
161
+ */
162
+ static _matches(value) {
163
+ return typeof value === 'string' && Pix._pattern.test(value);
164
+ }
165
+ /**
166
+ * _check()
167
+ * Compara o CRC informado com o calculado. O CRC pode vir em minúsculas.
168
+ */
169
+ static _check(value) {
170
+ return Pix.checksum(value.slice(0, -4)) === value.slice(-4).toUpperCase();
171
+ }
172
+ /**
173
+ * _read()
174
+ * Lê os campos do código, sem o campo do CRC.
175
+ */
176
+ static _read(value) {
177
+ const fields = pix_fields_1.PixFields.read(value.slice(0, -8));
178
+ return { ...fields, crc: value.slice(-4) };
179
+ }
180
+ }
181
+ exports.Pix = Pix;
182
+ /**
183
+ * Formato aceito: começa em 000201 e termina em 6304 + 4 caracteres hexadecimais.
184
+ * O ponto não aceita quebra de linha.
185
+ */
186
+ Pix._pattern = /^000201.*6304[0-9A-F]{4}$/i;
187
+ /**
188
+ * Formato do código sem o CRC: começa em 000201 e termina em 6304.
189
+ * É o que o checksum() recebe.
190
+ */
191
+ Pix._basePattern = /^000201.*6304$/;