@grupo-argenta/schema-kit-nest 0.0.20 → 0.0.21
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/config/naming-strategy.d.ts +6 -0
- package/config/naming-strategy.js +17 -0
- package/config/redis.constants.d.ts +1 -0
- package/config/redis.constants.js +4 -0
- package/context-logger.service.d.ts +4 -0
- package/context-logger.service.js +23 -0
- package/decorators/date-range.d.ts +4 -0
- package/decorators/date-range.js +17 -0
- package/decorators/encrypted.d.ts +10 -0
- package/decorators/encrypted.js +15 -0
- package/decorators/file-column.d.ts +17 -0
- package/decorators/file-column.js +20 -0
- package/decorators/get-user.decorator.d.ts +6 -0
- package/decorators/get-user.decorator.js +12 -0
- package/decorators/luxon.d.ts +6 -0
- package/decorators/luxon.js +20 -0
- package/decorators/multipart.decorator.d.ts +4 -0
- package/decorators/multipart.decorator.js +51 -0
- package/decorators/post-get.decorator.d.ts +10 -0
- package/decorators/post-get.decorator.js +25 -0
- package/decorators/query-or-body.decorator.d.ts +8 -0
- package/decorators/query-or-body.decorator.js +15 -0
- package/decorators/when.decorator.d.ts +8 -0
- package/decorators/when.decorator.js +16 -0
- package/html/components/badge.d.ts +13 -0
- package/html/components/badge.js +29 -0
- package/html/components/colors.d.ts +11 -0
- package/html/components/colors.js +15 -0
- package/html/components/component.d.ts +11 -0
- package/html/components/component.js +35 -0
- package/html/components/default/default-footer.d.ts +6 -0
- package/html/components/default/default-footer.js +18 -0
- package/html/components/default/default-header.d.ts +13 -0
- package/html/components/default/default-header.js +30 -0
- package/html/components/env-badge.d.ts +7 -0
- package/html/components/env-badge.js +29 -0
- package/html/components/grid.d.ts +17 -0
- package/html/components/grid.js +44 -0
- package/html/components/shell.d.ts +18 -0
- package/html/components/shell.js +423 -0
- package/html/components/table.d.ts +16 -0
- package/html/components/table.js +55 -0
- package/html/components/unordered-list.d.ts +6 -0
- package/html/components/unordered-list.js +21 -0
- package/index.d.ts +49 -0
- package/index.js +65 -0
- package/interfaces/paginated-result.d.ts +21 -0
- package/interfaces/paginated-result.js +12 -0
- package/modules/auth/access-token.d.ts +27 -0
- package/modules/auth/access-token.js +14 -0
- package/modules/auth/known-module.d.ts +45 -0
- package/modules/auth/known-module.js +46 -0
- package/modules/auth/refresh-token.d.ts +18 -0
- package/modules/auth/refresh-token.js +2 -0
- package/modules/auth/token-type.d.ts +4 -0
- package/modules/auth/token-type.js +8 -0
- package/modules/encrypted-column/encrypted-column.module.d.ts +16 -0
- package/modules/encrypted-column/encrypted-column.module.js +35 -0
- package/modules/pubsub/pubsub-dynamic-topic.service.d.ts +77 -0
- package/modules/pubsub/pubsub-dynamic-topic.service.js +324 -0
- package/modules/pubsub/pubsub-redeliver-subscriber.service.d.ts +14 -0
- package/modules/pubsub/pubsub-redeliver-subscriber.service.js +77 -0
- package/modules/pubsub/pubsub-redeliver.service.d.ts +22 -0
- package/modules/pubsub/pubsub-redeliver.service.js +48 -0
- package/modules/pubsub/pubsub.constants.d.ts +2 -0
- package/modules/pubsub/pubsub.constants.js +5 -0
- package/modules/pubsub/pubsub.methods.d.ts +18 -0
- package/modules/pubsub/pubsub.methods.js +18 -0
- package/modules/pubsub/pubsub.methods.redelivery.d.ts +3 -0
- package/modules/pubsub/pubsub.methods.redelivery.js +2 -0
- package/modules/redis/redis.module.d.ts +10 -0
- package/modules/redis/redis.module.js +59 -0
- package/modules/redis/redis.options.d.ts +7 -0
- package/modules/redis/redis.options.js +4 -0
- package/modules/storage/storage.service.d.ts +16 -0
- package/modules/storage/storage.service.js +61 -0
- package/monitoramento/http-request-log/http-request-log.controller.d.ts +184 -0
- package/monitoramento/http-request-log/http-request-log.controller.js +32 -0
- package/monitoramento/http-request-log/http-request-log.dto.d.ts +220 -0
- package/monitoramento/http-request-log/http-request-log.dto.js +42 -0
- package/monitoramento/http-request-log/http-request-log.entity.d.ts +17 -0
- package/monitoramento/http-request-log/http-request-log.entity.js +87 -0
- package/monitoramento/http-request-log/http-request-log.module.d.ts +2 -0
- package/monitoramento/http-request-log/http-request-log.module.js +26 -0
- package/monitoramento/http-request-log/http-request-log.service.d.ts +8 -0
- package/monitoramento/http-request-log/http-request-log.service.js +35 -0
- package/monitoramento/index.d.ts +17 -0
- package/monitoramento/index.js +33 -0
- package/monitoramento/migrations/1792689106394-create_http_request_logs_table.d.ts +5 -0
- package/monitoramento/migrations/1792689106394-create_http_request_logs_table.js +96 -0
- package/monitoramento/migrations/1792689106395-create_pubsub_message_logs_table.d.ts +5 -0
- package/monitoramento/migrations/1792689106395-create_pubsub_message_logs_table.js +157 -0
- package/monitoramento/monitoramento.constants.d.ts +2 -0
- package/monitoramento/monitoramento.constants.js +5 -0
- package/monitoramento/monitoramento.entities.d.ts +1 -0
- package/monitoramento/monitoramento.entities.js +7 -0
- package/monitoramento/monitoramento.module.d.ts +6 -0
- package/monitoramento/monitoramento.module.js +61 -0
- package/monitoramento/monitoramento.options.d.ts +15 -0
- package/monitoramento/monitoramento.options.js +2 -0
- package/monitoramento/outbound-request.interceptor.d.ts +14 -0
- package/monitoramento/outbound-request.interceptor.js +113 -0
- package/monitoramento/pubsub-message-log/pubsub-message-log.controller.d.ts +257 -0
- package/monitoramento/pubsub-message-log/pubsub-message-log.controller.js +34 -0
- package/monitoramento/pubsub-message-log/pubsub-message-log.dto.d.ts +320 -0
- package/monitoramento/pubsub-message-log/pubsub-message-log.dto.js +57 -0
- package/monitoramento/pubsub-message-log/pubsub-message-log.entity.d.ts +44 -0
- package/monitoramento/pubsub-message-log/pubsub-message-log.entity.js +152 -0
- package/monitoramento/pubsub-message-log/pubsub-message-log.module.d.ts +2 -0
- package/monitoramento/pubsub-message-log/pubsub-message-log.module.js +26 -0
- package/monitoramento/pubsub-message-log/pubsub-message-log.service.d.ts +20 -0
- package/monitoramento/pubsub-message-log/pubsub-message-log.service.js +99 -0
- package/monitoramento/pubsub-self-check/pubsub-self-check.controller.d.ts +9 -0
- package/monitoramento/pubsub-self-check/pubsub-self-check.controller.js +45 -0
- package/monitoramento/pubsub-self-check/pubsub-self-check.module.d.ts +11 -0
- package/monitoramento/pubsub-self-check/pubsub-self-check.module.js +41 -0
- package/monitoramento/pubsub-self-check/pubsub-self-check.options.d.ts +10 -0
- package/monitoramento/pubsub-self-check/pubsub-self-check.options.js +4 -0
- package/monitoramento/pubsub-self-check/pubsub-self-check.service.d.ts +68 -0
- package/monitoramento/pubsub-self-check/pubsub-self-check.service.js +213 -0
- package/package.json +1 -1
- package/schema/abstract.entity.d.ts +28 -0
- package/schema/abstract.entity.js +68 -0
- package/schema/schema-builder.d.ts +131 -0
- package/schema/schema-builder.js +162 -0
- package/schema/schema.controller.d.ts +51 -0
- package/schema/schema.controller.js +121 -0
- package/schema/schema.service.d.ts +81 -0
- package/schema/schema.service.js +305 -0
- package/schema/typeorm-extensions.d.ts +6 -0
- package/schema/typeorm-extensions.js +6 -0
- package/schema/zod-extensions/cnpj.validator.d.ts +28 -0
- package/schema/zod-extensions/cnpj.validator.js +133 -0
- package/schema/zod-extensions/cpf-cnpj.validator.d.ts +2 -0
- package/schema/zod-extensions/cpf-cnpj.validator.js +8 -0
- package/schema/zod-extensions/cpf.validator.d.ts +18 -0
- package/schema/zod-extensions/cpf.validator.js +166 -0
- package/schema/zod-extensions.d.ts +50 -0
- package/schema/zod-extensions.js +144 -0
- package/schema-kit.module.d.ts +2 -0
- package/schema-kit.module.js +23 -0
- package/transformers/date-range.transformer.d.ts +6 -0
- package/transformers/date-range.transformer.js +44 -0
- package/transformers/encrypted.transformer.d.ts +11 -0
- package/transformers/encrypted.transformer.js +35 -0
- package/transformers/luxon.transformer.d.ts +3 -0
- package/transformers/luxon.transformer.js +12 -0
- package/utils/utils.d.ts +49 -0
- package/utils/utils.js +79 -0
- package/validators/ip-validator.d.ts +3 -0
- package/validators/ip-validator.js +8 -0
- package/validators/pubsub-delete.validator.d.ts +6 -0
- package/validators/pubsub-delete.validator.js +11 -0
- package/validators/url-validator.d.ts +3 -0
- package/validators/url-validator.js +8 -0
- package/validators/uuid-validator.d.ts +3 -0
- package/validators/uuid-validator.js +8 -0
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.isCnpjValid = isValid;
|
|
4
|
+
/**
|
|
5
|
+
* Calcula o dígito verificador de um CNPJ usando o algoritmo Módulo 11
|
|
6
|
+
* com pesos cíclicos 2..9.
|
|
7
|
+
*
|
|
8
|
+
* Aceita tanto CNPJs puramente numéricos quanto no formato alfanumérico
|
|
9
|
+
* da Nota Técnica RFB 49/2024 (letras A-Z convertidas via ASCII - 48).
|
|
10
|
+
*
|
|
11
|
+
* @param digits - String com 12 dígitos (para DV1) ou 13 dígitos (para DV2).
|
|
12
|
+
* @returns Dígito verificador (0..9).
|
|
13
|
+
*/
|
|
14
|
+
function cnpjDigit(digits) {
|
|
15
|
+
let sum = 0;
|
|
16
|
+
let weight = 2;
|
|
17
|
+
for (let i = digits.length - 1; i >= 0; i--) {
|
|
18
|
+
sum += (digits.charCodeAt(i) - 48) * weight;
|
|
19
|
+
weight = weight === 9 ? 2 : weight + 1;
|
|
20
|
+
}
|
|
21
|
+
const mod = sum % 11;
|
|
22
|
+
return mod < 2 ? 0 : 11 - mod;
|
|
23
|
+
}
|
|
24
|
+
const BLACKLIST = new Set([
|
|
25
|
+
'00000000000000',
|
|
26
|
+
'11111111111111',
|
|
27
|
+
'22222222222222',
|
|
28
|
+
'33333333333333',
|
|
29
|
+
'44444444444444',
|
|
30
|
+
'55555555555555',
|
|
31
|
+
'66666666666666',
|
|
32
|
+
'77777777777777',
|
|
33
|
+
'88888888888888',
|
|
34
|
+
'99999999999999',
|
|
35
|
+
]);
|
|
36
|
+
const STRICT_STRIP_REGEX = /[./-]/g;
|
|
37
|
+
const LOOSE_STRIP_REGEX = /[^\dA-Z]/g;
|
|
38
|
+
const STRICT_MASK_REGEX = /^(?:[\dA-Z]{2}\.[\dA-Z]{3}\.[\dA-Z]{3}\/[\dA-Z]{4}-\d{2}|[\dA-Z]{12}\d{2})$/;
|
|
39
|
+
const VALID_CHARS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
|
|
40
|
+
/**
|
|
41
|
+
* Remove caracteres de máscara e normaliza um CNPJ.
|
|
42
|
+
*
|
|
43
|
+
* Em modo padrão (loose), converte minúsculas para maiúsculas e remove
|
|
44
|
+
* qualquer caractere que não seja dígito ou letra A-Z. Em modo strict,
|
|
45
|
+
* remove apenas `.`, `/` e `-` (máscara oficial) sem normalizar o case.
|
|
46
|
+
*
|
|
47
|
+
* @param value - Entrada a ser normalizada.
|
|
48
|
+
* @param strict - Se `true`, só remove os caracteres da máscara oficial.
|
|
49
|
+
* @returns Apenas dígitos e letras A-Z remanescentes.
|
|
50
|
+
*/
|
|
51
|
+
function strip(value, strict) {
|
|
52
|
+
if (typeof value !== 'string')
|
|
53
|
+
return '';
|
|
54
|
+
const normalized = strict ? value : value.toUpperCase();
|
|
55
|
+
const regex = strict ? STRICT_STRIP_REGEX : LOOSE_STRIP_REGEX;
|
|
56
|
+
return normalized.replace(regex, '');
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Aplica a máscara oficial `XX.XXX.XXX/XXXX-YY` no CNPJ (numérico ou
|
|
60
|
+
* alfanumérico). Os 2 últimos caracteres (DVs) são sempre numéricos.
|
|
61
|
+
*
|
|
62
|
+
* @param value - CNPJ cru ou já formatado.
|
|
63
|
+
* @returns CNPJ mascarado, ou entrada normalizada quando não casar com o
|
|
64
|
+
* padrão de 14 posições.
|
|
65
|
+
*/
|
|
66
|
+
function format(value) {
|
|
67
|
+
return strip(value).replace(/^([\dA-Z]{2})([\dA-Z]{3})([\dA-Z]{3})([\dA-Z]{4})(\d{2})$/, '$1.$2.$3/$4-$5');
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* Valida um CNPJ verificando tamanho, lista negra, shape dos DVs e os
|
|
71
|
+
* dois dígitos verificadores via Módulo 11.
|
|
72
|
+
*
|
|
73
|
+
* Aceita tanto CNPJs puramente numéricos (formato legado) quanto
|
|
74
|
+
* alfanuméricos (novo formato da Nota Técnica RFB 49/2024 — vigência
|
|
75
|
+
* obrigatória em julho/2026).
|
|
76
|
+
*
|
|
77
|
+
* @param value - CNPJ (cru, formatado ou com lixo, conforme `strict`).
|
|
78
|
+
* @param strict - Se `true`, só aceita máscara canônica ou 14 caracteres
|
|
79
|
+
* `[0-9A-Z]` sem normalização de case.
|
|
80
|
+
* @returns `true` se o CNPJ é válido; `false` caso contrário.
|
|
81
|
+
*
|
|
82
|
+
* @example
|
|
83
|
+
* ```ts
|
|
84
|
+
* cnpj.isValid('54.550.752/0001-55') // true
|
|
85
|
+
* cnpj.isValid('54550752000155') // true
|
|
86
|
+
* cnpj.isValid('12ABC34501DE35') // true (novo formato RFB)
|
|
87
|
+
* cnpj.isValid('12.ABC.345/01DE-35') // true
|
|
88
|
+
* ```
|
|
89
|
+
*/
|
|
90
|
+
function isValid(value, strict) {
|
|
91
|
+
if (strict && (typeof value !== 'string' || !STRICT_MASK_REGEX.test(value))) {
|
|
92
|
+
return false;
|
|
93
|
+
}
|
|
94
|
+
const stripped = strip(value, strict);
|
|
95
|
+
if (!stripped || stripped.length !== 14 || BLACKLIST.has(stripped)) {
|
|
96
|
+
return false;
|
|
97
|
+
}
|
|
98
|
+
// DVs (últimas 2 posições) devem ser numéricos pela regra da RFB.
|
|
99
|
+
if (!/^\d{2}$/.test(stripped.slice(-2))) {
|
|
100
|
+
return false;
|
|
101
|
+
}
|
|
102
|
+
let numbers = stripped.slice(0, 12);
|
|
103
|
+
numbers += cnpjDigit(numbers);
|
|
104
|
+
numbers += cnpjDigit(numbers);
|
|
105
|
+
return numbers.slice(-2) === stripped.slice(-2);
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* Gera um CNPJ alfanumérico matematicamente válido, seguindo o formato
|
|
109
|
+
* da Nota Técnica RFB 49/2024.
|
|
110
|
+
*
|
|
111
|
+
* @param options - Boolean legado (apenas `formatted`) ou objeto de opções.
|
|
112
|
+
* @returns CNPJ gerado com 14 caracteres (12 alfanuméricos + 2 DVs
|
|
113
|
+
* numéricos) ou a máscara oficial.
|
|
114
|
+
*
|
|
115
|
+
* @example
|
|
116
|
+
* ```ts
|
|
117
|
+
* cnpj.generate() // '58A0Z919U001O6'
|
|
118
|
+
* cnpj.generate(true) // '58.A0Z.919/U001-O6' (nope — DVs sempre numéricos)
|
|
119
|
+
* cnpj.generate({ formatted: true }) // '58.A0Z.919/U001-06'
|
|
120
|
+
* ```
|
|
121
|
+
*/
|
|
122
|
+
// Mantido para gerar CNPJs em testes/seeds, ainda sem uso no código.
|
|
123
|
+
// oxlint-disable-next-line no-unused-vars
|
|
124
|
+
function generate(options) {
|
|
125
|
+
const opts = typeof options === 'boolean' ? { formatted: options } : (options ?? {});
|
|
126
|
+
let numbers = '';
|
|
127
|
+
for (let i = 0; i < 12; i++) {
|
|
128
|
+
numbers += VALID_CHARS.charAt(Math.floor(Math.random() * VALID_CHARS.length));
|
|
129
|
+
}
|
|
130
|
+
numbers += cnpjDigit(numbers);
|
|
131
|
+
numbers += cnpjDigit(numbers);
|
|
132
|
+
return opts.formatted ? format(numbers) : numbers;
|
|
133
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.isCpfCnpjValid = isValid;
|
|
4
|
+
const cnpj_validator_1 = require("./cnpj.validator");
|
|
5
|
+
const cpf_validator_1 = require("./cpf.validator");
|
|
6
|
+
function isValid(value) {
|
|
7
|
+
return (0, cpf_validator_1.isCpfValid)(value) || (0, cnpj_validator_1.isCnpjValid)(value);
|
|
8
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Valida um CPF verificando tamanho, lista negra e os dois dígitos
|
|
3
|
+
* verificadores via Módulo 11.
|
|
4
|
+
*
|
|
5
|
+
* @param value - CPF (cru, formatado ou com lixo, conforme `strict`).
|
|
6
|
+
* @param strict - Se `true`, só aceita máscara canônica `XXX.XXX.XXX-XX`
|
|
7
|
+
* ou 11 dígitos puros. Se `false` ou omitido, remove qualquer lixo.
|
|
8
|
+
* @returns `true` se o CPF é válido; `false` caso contrário.
|
|
9
|
+
*
|
|
10
|
+
* @example
|
|
11
|
+
* ```ts
|
|
12
|
+
* cpf.isValid('295.379.955-93') // true
|
|
13
|
+
* cpf.isValid('29537995593') // true
|
|
14
|
+
* cpf.isValid('00000000000') // false (blacklist)
|
|
15
|
+
* ```
|
|
16
|
+
*/
|
|
17
|
+
declare function isValid(value: string, strict?: boolean): boolean;
|
|
18
|
+
export { isValid as isCpfValid };
|
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.isCpfValid = isValid;
|
|
4
|
+
/**
|
|
5
|
+
* Calcula o dígito verificador de um CPF usando o algoritmo Módulo 11
|
|
6
|
+
* com pesos lineares crescentes.
|
|
7
|
+
*
|
|
8
|
+
* @param digits - String com 9 dígitos (para DV1) ou 10 dígitos (para DV2).
|
|
9
|
+
* @returns Dígito verificador (0..9).
|
|
10
|
+
*/
|
|
11
|
+
function cpfDigit(digits) {
|
|
12
|
+
let sum = 0;
|
|
13
|
+
const n = digits.length;
|
|
14
|
+
for (let i = n - 1; i >= 0; i--) {
|
|
15
|
+
sum += (digits.charCodeAt(i) - 48) * (n - i + 1);
|
|
16
|
+
}
|
|
17
|
+
const mod = sum % 11;
|
|
18
|
+
return mod < 2 ? 0 : 11 - mod;
|
|
19
|
+
}
|
|
20
|
+
const BLACKLIST = new Set([
|
|
21
|
+
'00000000000',
|
|
22
|
+
'11111111111',
|
|
23
|
+
'22222222222',
|
|
24
|
+
'33333333333',
|
|
25
|
+
'44444444444',
|
|
26
|
+
'55555555555',
|
|
27
|
+
'66666666666',
|
|
28
|
+
'77777777777',
|
|
29
|
+
'88888888888',
|
|
30
|
+
'99999999999',
|
|
31
|
+
'12345678909',
|
|
32
|
+
]);
|
|
33
|
+
const STRICT_STRIP_REGEX = /[.-]/g;
|
|
34
|
+
const LOOSE_STRIP_REGEX = /[^\d]/g;
|
|
35
|
+
const STRICT_MASK_REGEX = /^(?:\d{3}\.\d{3}\.\d{3}-\d{2}|\d{11})$/;
|
|
36
|
+
/**
|
|
37
|
+
* Mapa dos 27 UFs brasileiros para seus dígitos de Região Fiscal da
|
|
38
|
+
* Receita Federal (0..9), codificados na 9ª posição do CPF.
|
|
39
|
+
*
|
|
40
|
+
* @example
|
|
41
|
+
* ```ts
|
|
42
|
+
* FISCAL_REGION_BY_UF.SP // 8 (São Paulo — 8ª Região Fiscal)
|
|
43
|
+
* FISCAL_REGION_BY_UF.RS // 0 (Rio Grande do Sul — 10ª Região Fiscal)
|
|
44
|
+
* ```
|
|
45
|
+
*/
|
|
46
|
+
const FISCAL_REGION_BY_UF = {
|
|
47
|
+
DF: 1,
|
|
48
|
+
GO: 1,
|
|
49
|
+
MS: 1,
|
|
50
|
+
MT: 1,
|
|
51
|
+
TO: 1,
|
|
52
|
+
AC: 2,
|
|
53
|
+
AM: 2,
|
|
54
|
+
AP: 2,
|
|
55
|
+
PA: 2,
|
|
56
|
+
RO: 2,
|
|
57
|
+
RR: 2,
|
|
58
|
+
CE: 3,
|
|
59
|
+
MA: 3,
|
|
60
|
+
PI: 3,
|
|
61
|
+
AL: 4,
|
|
62
|
+
PB: 4,
|
|
63
|
+
PE: 4,
|
|
64
|
+
RN: 4,
|
|
65
|
+
BA: 5,
|
|
66
|
+
SE: 5,
|
|
67
|
+
MG: 6,
|
|
68
|
+
ES: 7,
|
|
69
|
+
RJ: 7,
|
|
70
|
+
SP: 8,
|
|
71
|
+
PR: 9,
|
|
72
|
+
SC: 9,
|
|
73
|
+
RS: 0,
|
|
74
|
+
};
|
|
75
|
+
/**
|
|
76
|
+
* Remove caracteres de máscara e normaliza um CPF.
|
|
77
|
+
*
|
|
78
|
+
* @param value - Entrada a ser normalizada.
|
|
79
|
+
* @param strict - Se `true`, remove apenas `.` e `-`. Se `false` ou omitido,
|
|
80
|
+
* remove qualquer caractere não numérico.
|
|
81
|
+
* @returns Apenas os dígitos remanescentes.
|
|
82
|
+
*/
|
|
83
|
+
function strip(value, strict) {
|
|
84
|
+
if (typeof value !== 'string')
|
|
85
|
+
return '';
|
|
86
|
+
const regex = strict ? STRICT_STRIP_REGEX : LOOSE_STRIP_REGEX;
|
|
87
|
+
return value.replace(regex, '');
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* Aplica a máscara oficial `XXX.XXX.XXX-XX` no CPF.
|
|
91
|
+
*
|
|
92
|
+
* @param value - CPF cru ou já formatado.
|
|
93
|
+
* @returns O CPF com máscara, ou a entrada normalizada quando não casar
|
|
94
|
+
* com o padrão de 11 dígitos.
|
|
95
|
+
*/
|
|
96
|
+
function format(value) {
|
|
97
|
+
return strip(value).replace(/^(\d{3})(\d{3})(\d{3})(\d{2})$/, '$1.$2.$3-$4');
|
|
98
|
+
}
|
|
99
|
+
/**
|
|
100
|
+
* Valida um CPF verificando tamanho, lista negra e os dois dígitos
|
|
101
|
+
* verificadores via Módulo 11.
|
|
102
|
+
*
|
|
103
|
+
* @param value - CPF (cru, formatado ou com lixo, conforme `strict`).
|
|
104
|
+
* @param strict - Se `true`, só aceita máscara canônica `XXX.XXX.XXX-XX`
|
|
105
|
+
* ou 11 dígitos puros. Se `false` ou omitido, remove qualquer lixo.
|
|
106
|
+
* @returns `true` se o CPF é válido; `false` caso contrário.
|
|
107
|
+
*
|
|
108
|
+
* @example
|
|
109
|
+
* ```ts
|
|
110
|
+
* cpf.isValid('295.379.955-93') // true
|
|
111
|
+
* cpf.isValid('29537995593') // true
|
|
112
|
+
* cpf.isValid('00000000000') // false (blacklist)
|
|
113
|
+
* ```
|
|
114
|
+
*/
|
|
115
|
+
function isValid(value, strict) {
|
|
116
|
+
if (strict && (typeof value !== 'string' || !STRICT_MASK_REGEX.test(value))) {
|
|
117
|
+
return false;
|
|
118
|
+
}
|
|
119
|
+
const stripped = strip(value, strict);
|
|
120
|
+
if (!stripped || stripped.length !== 11 || BLACKLIST.has(stripped)) {
|
|
121
|
+
return false;
|
|
122
|
+
}
|
|
123
|
+
let numbers = stripped.slice(0, 9);
|
|
124
|
+
numbers += cpfDigit(numbers);
|
|
125
|
+
numbers += cpfDigit(numbers);
|
|
126
|
+
return numbers.slice(-2) === stripped.slice(-2);
|
|
127
|
+
}
|
|
128
|
+
/**
|
|
129
|
+
* Gera um CPF matematicamente válido, opcionalmente formatado ou
|
|
130
|
+
* vinculado a uma UF específica (via Região Fiscal da RFB).
|
|
131
|
+
*
|
|
132
|
+
* @param options - Boolean legado (apenas `formatted`) ou objeto com
|
|
133
|
+
* `formatted` e/ou `state`. Quando `state` é informado, a 9ª posição
|
|
134
|
+
* recebe o dígito da Região Fiscal correspondente.
|
|
135
|
+
* @returns CPF gerado, com 11 dígitos crus ou a máscara oficial.
|
|
136
|
+
* @throws {TypeError} Se `options.state` for informado mas não for um UF
|
|
137
|
+
* conhecido.
|
|
138
|
+
*
|
|
139
|
+
* @example
|
|
140
|
+
* ```ts
|
|
141
|
+
* cpf.generate() // '32564428777'
|
|
142
|
+
* cpf.generate(true) // '325.644.287-77'
|
|
143
|
+
* cpf.generate({ state: 'SP' }) // '...8??' (8ª posição = RF SP)
|
|
144
|
+
* cpf.generate({ formatted: true, state: 'SP' }) // '325.644.287-77' (9ª = '8')
|
|
145
|
+
* ```
|
|
146
|
+
*/
|
|
147
|
+
// oxlint-disable-next-line no-unused-vars
|
|
148
|
+
function generate(options) {
|
|
149
|
+
const opts = typeof options === 'boolean' ? { formatted: options } : (options ?? {});
|
|
150
|
+
let numbers = '';
|
|
151
|
+
for (let i = 0; i < 8; i++) {
|
|
152
|
+
numbers += Math.floor(Math.random() * 10);
|
|
153
|
+
}
|
|
154
|
+
if (opts.state !== undefined) {
|
|
155
|
+
if (!Object.hasOwn(FISCAL_REGION_BY_UF, opts.state)) {
|
|
156
|
+
throw new TypeError(`UF '${opts.state}' desconhecida — use uma das: ${Object.keys(FISCAL_REGION_BY_UF).join(', ')}`);
|
|
157
|
+
}
|
|
158
|
+
numbers += FISCAL_REGION_BY_UF[opts.state];
|
|
159
|
+
}
|
|
160
|
+
else {
|
|
161
|
+
numbers += Math.floor(Math.random() * 10);
|
|
162
|
+
}
|
|
163
|
+
numbers += cpfDigit(numbers);
|
|
164
|
+
numbers += cpfDigit(numbers);
|
|
165
|
+
return opts.formatted ? format(numbers) : numbers;
|
|
166
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import * as z from 'zod';
|
|
2
|
+
import { DateTime } from 'luxon';
|
|
3
|
+
export declare const fromJson: (v: unknown) => any;
|
|
4
|
+
/** Cria um schema para um array em formato JSON. ie: '["a", "b", "c"]'
|
|
5
|
+
* Utilizado para parse de query params que são arrays, mas chegam como string.
|
|
6
|
+
* Aceita também o array já parseado, e cada item pode vir como ele mesmo ou como JSON.
|
|
7
|
+
* ie: ['a', 'b'] ou ['{"field":"uuid","order":"DESC"}']
|
|
8
|
+
*/
|
|
9
|
+
declare function jsonStringArray<T extends z.core.SomeType>(element: T, params?: Parameters<typeof z.array>[1]): z.ZodPreprocess<z.ZodArray<z.ZodUnion<readonly [T, z.ZodPreprocess<T, unknown>]>>, unknown>;
|
|
10
|
+
/** Cria um schema que, se o valor for inválido, retorna undefined em vez de falhar. */
|
|
11
|
+
declare function invalidAsUndefined<T extends z.ZodType>(s: T): z.ZodCatch<z.ZodOptional<T>>;
|
|
12
|
+
/** Cria um schema para DateTime (luxon). Aceita a instância ou uma string ISO com offset. */
|
|
13
|
+
declare function dateTime(): z.ZodUnion<readonly [z.ZodCustom<DateTime<boolean>, DateTime<boolean>>, z.ZodPipe<z.ZodISODateTime, z.ZodTransform<DateTime<true> | DateTime<false>, string>>]>;
|
|
14
|
+
/** Intervalo [início, fim] de DateTime.
|
|
15
|
+
* @param params.nullish cada ponta aceita null (intervalo aberto)
|
|
16
|
+
* @param params.dayEdges expande as pontas para início/fim do dia
|
|
17
|
+
* Encadeie `.nullish()` / `.optional()` para o intervalo inteiro. */
|
|
18
|
+
declare function dateTimeSpan<N extends boolean = false>(params?: {
|
|
19
|
+
nullish?: N;
|
|
20
|
+
dayEdges?: boolean;
|
|
21
|
+
}): z.ZodType<[N extends true ? DateTime<boolean> | null : DateTime<boolean>, N extends true ? DateTime<boolean> | null : DateTime<boolean>], [N extends true ? string | DateTime<boolean> | null : string | DateTime<boolean>, N extends true ? string | DateTime<boolean> | null : string | DateTime<boolean>]>;
|
|
22
|
+
declare function timeSpan(): z.ZodTuple<[z.ZodISOTime, z.ZodISOTime], null>;
|
|
23
|
+
declare function cpf(): z.ZodString;
|
|
24
|
+
declare function cnpj(): z.ZodString;
|
|
25
|
+
declare function cpfCnpj(): z.ZodUnion<readonly [z.ZodString, z.ZodString]>;
|
|
26
|
+
declare function phone(): z.ZodE164;
|
|
27
|
+
declare function cep(): z.ZodString;
|
|
28
|
+
/** Campo de `@FileColumn()`: um `File` novo, ou a URL já existente que o front devolve (mantém o arquivo atual) */
|
|
29
|
+
declare function file(): z.ZodUnion<readonly [z.ZodFile, z.ZodString]>;
|
|
30
|
+
/** Campo de `@FileColumn({ multiple: true })` */
|
|
31
|
+
declare function files(): z.ZodArray<z.ZodUnion<readonly [z.ZodFile, z.ZodString]>>;
|
|
32
|
+
declare function json(): z.ZodPipe<z.ZodUnion<readonly [z.ZodString, z.ZodRecord<z.ZodString, z.ZodUnknown>]>, z.ZodTransform<any, string | Record<string, unknown>>>;
|
|
33
|
+
export declare const zExt: {
|
|
34
|
+
jsonStringArray: typeof jsonStringArray;
|
|
35
|
+
invalidAsUndefined: typeof invalidAsUndefined;
|
|
36
|
+
dateTime: typeof dateTime;
|
|
37
|
+
dateTimeSpan: typeof dateTimeSpan;
|
|
38
|
+
timeSpan: typeof timeSpan;
|
|
39
|
+
span: <S extends z.ZodType, E extends z.ZodType = S>(start: S, end?: E) => z.ZodTuple<[S, E], null>;
|
|
40
|
+
time: typeof z.iso.time;
|
|
41
|
+
cpf: typeof cpf;
|
|
42
|
+
cnpj: typeof cnpj;
|
|
43
|
+
cpfCnpj: typeof cpfCnpj;
|
|
44
|
+
phone: typeof phone;
|
|
45
|
+
cep: typeof cep;
|
|
46
|
+
file: typeof file;
|
|
47
|
+
files: typeof files;
|
|
48
|
+
json: typeof json;
|
|
49
|
+
};
|
|
50
|
+
export {};
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
14
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
15
|
+
}) : function(o, v) {
|
|
16
|
+
o["default"] = v;
|
|
17
|
+
});
|
|
18
|
+
var __importStar = (this && this.__importStar) || (function () {
|
|
19
|
+
var ownKeys = function(o) {
|
|
20
|
+
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
21
|
+
var ar = [];
|
|
22
|
+
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
23
|
+
return ar;
|
|
24
|
+
};
|
|
25
|
+
return ownKeys(o);
|
|
26
|
+
};
|
|
27
|
+
return function (mod) {
|
|
28
|
+
if (mod && mod.__esModule) return mod;
|
|
29
|
+
var result = {};
|
|
30
|
+
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
31
|
+
__setModuleDefault(result, mod);
|
|
32
|
+
return result;
|
|
33
|
+
};
|
|
34
|
+
})();
|
|
35
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
36
|
+
exports.zExt = exports.fromJson = void 0;
|
|
37
|
+
const z = __importStar(require("zod"));
|
|
38
|
+
const luxon_1 = require("luxon");
|
|
39
|
+
const cpf_validator_1 = require("./zod-extensions/cpf.validator");
|
|
40
|
+
// Complex index params (sort, filters) arrive as JSON strings in the query
|
|
41
|
+
const fromJson = (v) => {
|
|
42
|
+
if (typeof v !== 'string')
|
|
43
|
+
return v;
|
|
44
|
+
try {
|
|
45
|
+
return JSON.parse(v);
|
|
46
|
+
}
|
|
47
|
+
catch {
|
|
48
|
+
return v;
|
|
49
|
+
}
|
|
50
|
+
};
|
|
51
|
+
exports.fromJson = fromJson;
|
|
52
|
+
/** Cria um schema para um array em formato JSON. ie: '["a", "b", "c"]'
|
|
53
|
+
* Utilizado para parse de query params que são arrays, mas chegam como string.
|
|
54
|
+
* Aceita também o array já parseado, e cada item pode vir como ele mesmo ou como JSON.
|
|
55
|
+
* ie: ['a', 'b'] ou ['{"field":"uuid","order":"DESC"}']
|
|
56
|
+
*/
|
|
57
|
+
function jsonStringArray(element, params) {
|
|
58
|
+
// Tenta o item como está primeiro, para não converter strings como '123' em number
|
|
59
|
+
const item = z.union([element, z.preprocess(exports.fromJson, element)]);
|
|
60
|
+
return z.preprocess(exports.fromJson, z.array(item, params));
|
|
61
|
+
}
|
|
62
|
+
/** Cria um schema que, se o valor for inválido, retorna undefined em vez de falhar. */
|
|
63
|
+
function invalidAsUndefined(s) {
|
|
64
|
+
return s.optional().catch(undefined);
|
|
65
|
+
}
|
|
66
|
+
/** Cria um schema para DateTime (luxon). Aceita a instância ou uma string ISO com offset. */
|
|
67
|
+
function dateTime() {
|
|
68
|
+
const schema = z.union([
|
|
69
|
+
z.custom((v) => luxon_1.DateTime.isDateTime(v)),
|
|
70
|
+
z.iso.datetime({ offset: true }).transform((v) => luxon_1.DateTime.fromISO(v)),
|
|
71
|
+
]);
|
|
72
|
+
// z.custom não é representável em JSON Schema (Swagger); expõe como string ISO
|
|
73
|
+
schema._zod.toJSONSchema = () => ({ type: 'string', format: 'date-time' });
|
|
74
|
+
return schema;
|
|
75
|
+
}
|
|
76
|
+
const span = (start, end) => z.tuple([start, (end ?? start)]);
|
|
77
|
+
/** Expande para o dia inteiro: início 00:00:00.000, fim 23:59:59.999. Pontas nulas ficam nulas. */
|
|
78
|
+
const toDayEdges = ([start, end]) => [start?.startOf('day') ?? start, end?.endOf('day') ?? end];
|
|
79
|
+
/** Intervalo [início, fim] de DateTime.
|
|
80
|
+
* @param params.nullish cada ponta aceita null (intervalo aberto)
|
|
81
|
+
* @param params.dayEdges expande as pontas para início/fim do dia
|
|
82
|
+
* Encadeie `.nullish()` / `.optional()` para o intervalo inteiro. */
|
|
83
|
+
function dateTimeSpan(params) {
|
|
84
|
+
const end = (params?.nullish ? dateTime().nullish() : dateTime());
|
|
85
|
+
const schema = span(end);
|
|
86
|
+
return (params?.dayEdges ? schema.transform((toDayEdges)) : schema);
|
|
87
|
+
}
|
|
88
|
+
function timeSpan() {
|
|
89
|
+
return span(z.iso.time());
|
|
90
|
+
}
|
|
91
|
+
const time = z.iso.time;
|
|
92
|
+
function cpf() {
|
|
93
|
+
return z.string().refine(cpf_validator_1.isCpfValid, { message: 'CPF inválido' });
|
|
94
|
+
}
|
|
95
|
+
function cnpj() {
|
|
96
|
+
return z.string().regex(/^\d{14}$/, { message: 'CNPJ inválido' });
|
|
97
|
+
}
|
|
98
|
+
function cpfCnpj() {
|
|
99
|
+
return z.union([cpf(), cnpj()]);
|
|
100
|
+
}
|
|
101
|
+
function phone() {
|
|
102
|
+
return z.e164();
|
|
103
|
+
}
|
|
104
|
+
function cep() {
|
|
105
|
+
return z.string().regex(/^\d{5}-\d{3}$/, { message: 'CEP inválido' });
|
|
106
|
+
}
|
|
107
|
+
/** Campo de `@FileColumn()`: um `File` novo, ou a URL já existente que o front devolve (mantém o arquivo atual) */
|
|
108
|
+
function file() {
|
|
109
|
+
return z.union([z.file(), z.string()]);
|
|
110
|
+
}
|
|
111
|
+
/** Campo de `@FileColumn({ multiple: true })` */
|
|
112
|
+
function files() {
|
|
113
|
+
return z.array(file());
|
|
114
|
+
}
|
|
115
|
+
function json() {
|
|
116
|
+
return z.union([z.string(), z.record(z.string(), z.unknown())]).transform((v) => {
|
|
117
|
+
if (typeof v === 'string') {
|
|
118
|
+
try {
|
|
119
|
+
return JSON.parse(v);
|
|
120
|
+
}
|
|
121
|
+
catch {
|
|
122
|
+
throw new Error('JSON inválido');
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
return v;
|
|
126
|
+
});
|
|
127
|
+
}
|
|
128
|
+
exports.zExt = {
|
|
129
|
+
jsonStringArray,
|
|
130
|
+
invalidAsUndefined,
|
|
131
|
+
dateTime,
|
|
132
|
+
dateTimeSpan,
|
|
133
|
+
timeSpan,
|
|
134
|
+
span,
|
|
135
|
+
time,
|
|
136
|
+
cpf,
|
|
137
|
+
cnpj,
|
|
138
|
+
cpfCnpj,
|
|
139
|
+
phone,
|
|
140
|
+
cep,
|
|
141
|
+
file,
|
|
142
|
+
files,
|
|
143
|
+
json,
|
|
144
|
+
};
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
|
|
3
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
4
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
5
|
+
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
6
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
7
|
+
};
|
|
8
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
9
|
+
exports.SchemaKitModule = void 0;
|
|
10
|
+
const common_1 = require("@nestjs/common");
|
|
11
|
+
const pubsub_1 = require("@google-cloud/pubsub");
|
|
12
|
+
const context_logger_service_1 = require("./context-logger.service");
|
|
13
|
+
const storage_service_1 = require("./modules/storage/storage.service");
|
|
14
|
+
let SchemaKitModule = class SchemaKitModule {
|
|
15
|
+
};
|
|
16
|
+
exports.SchemaKitModule = SchemaKitModule;
|
|
17
|
+
exports.SchemaKitModule = SchemaKitModule = __decorate([
|
|
18
|
+
(0, common_1.Global)(),
|
|
19
|
+
(0, common_1.Module)({
|
|
20
|
+
providers: [context_logger_service_1.ContextLogger, { provide: pubsub_1.PubSub, useValue: new pubsub_1.PubSub() }, storage_service_1.StorageService],
|
|
21
|
+
exports: [context_logger_service_1.ContextLogger, pubsub_1.PubSub, storage_service_1.StorageService],
|
|
22
|
+
})
|
|
23
|
+
], SchemaKitModule);
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import { DateTime } from 'luxon';
|
|
2
|
+
import { ValueTransformer } from 'typeorm';
|
|
3
|
+
/** Intervalo [início, fim] dos inputs *-span do front, fechado nas duas pontas; null é uma ponta aberta (infinita) */
|
|
4
|
+
export type Span<T = DateTime> = [T | null, T | null];
|
|
5
|
+
export declare const dateRangeTransformer: ValueTransformer;
|
|
6
|
+
export declare const dateTimeRangeTransformer: ValueTransformer;
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.dateTimeRangeTransformer = exports.dateRangeTransformer = void 0;
|
|
4
|
+
const luxon_1 = require("luxon");
|
|
5
|
+
/**
|
|
6
|
+
* Converte o Span no literal de range do postgres (`daterange`, `tstzrange`) e vice-versa.
|
|
7
|
+
* O postgres normaliza o daterange para `[início,fim)`; na leitura o fim volta a ser o último dia incluso.
|
|
8
|
+
*/
|
|
9
|
+
const rangeTransformer = (subtype) => ({
|
|
10
|
+
to: (value) => {
|
|
11
|
+
if (value === null || value === undefined)
|
|
12
|
+
return value;
|
|
13
|
+
const [inicio, fim] = value.map((ponta) => (ponta == null ? '' : `"${toBound(ponta, subtype)}"`));
|
|
14
|
+
return `[${inicio},${fim}]`;
|
|
15
|
+
},
|
|
16
|
+
from: (value) => {
|
|
17
|
+
if (value === null || value === undefined)
|
|
18
|
+
return value;
|
|
19
|
+
if (value === 'empty')
|
|
20
|
+
return null;
|
|
21
|
+
const inicioIncluso = value.startsWith('[');
|
|
22
|
+
const fimIncluso = value.endsWith(']');
|
|
23
|
+
const [inicio, fim] = value
|
|
24
|
+
.slice(1, -1)
|
|
25
|
+
.split(',')
|
|
26
|
+
.map((ponta) => ponta.replaceAll('"', ''));
|
|
27
|
+
return [fromBound(inicio, subtype, inicioIncluso ? 0 : 1), fromBound(fim, subtype, fimIncluso ? 0 : -1)];
|
|
28
|
+
},
|
|
29
|
+
});
|
|
30
|
+
function toBound(ponta, subtype) {
|
|
31
|
+
return subtype === 'date' ? ponta.toISODate() : ponta.toISO();
|
|
32
|
+
}
|
|
33
|
+
/** `ajusteDias` desloca a ponta exclusiva de um daterange para o dia incluso */
|
|
34
|
+
function fromBound(ponta, subtype, ajusteDias) {
|
|
35
|
+
if (!ponta)
|
|
36
|
+
return null;
|
|
37
|
+
if (subtype === 'date') {
|
|
38
|
+
return luxon_1.DateTime.fromISO(ponta).plus({ days: ajusteDias });
|
|
39
|
+
}
|
|
40
|
+
// tstzrange vem no formato do postgres (`2026-11-03 13:45:00-03`)
|
|
41
|
+
return luxon_1.DateTime.fromSQL(ponta);
|
|
42
|
+
}
|
|
43
|
+
exports.dateRangeTransformer = rangeTransformer('date');
|
|
44
|
+
exports.dateTimeRangeTransformer = rangeTransformer('timestamptz');
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { ValueTransformer } from 'typeorm';
|
|
2
|
+
export interface EncryptedValue {
|
|
3
|
+
iv: string;
|
|
4
|
+
data: string;
|
|
5
|
+
}
|
|
6
|
+
/**
|
|
7
|
+
* Encrypts the value (JSON serialized) with AES-256-GCM using a fresh IV per write.
|
|
8
|
+
* The env var name comes from `EncryptedColumnModule.forRoot`, and the key is read from `process.env` on each call,
|
|
9
|
+
* since transformers run outside Nest's DI.
|
|
10
|
+
*/
|
|
11
|
+
export declare const encryptedTransformer: () => ValueTransformer;
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.encryptedTransformer = void 0;
|
|
4
|
+
const utils_1 = require("../utils/utils");
|
|
5
|
+
const encrypted_column_module_1 = require("../modules/encrypted-column/encrypted-column.module");
|
|
6
|
+
/**
|
|
7
|
+
* Encrypts the value (JSON serialized) with AES-256-GCM using a fresh IV per write.
|
|
8
|
+
* The env var name comes from `EncryptedColumnModule.forRoot`, and the key is read from `process.env` on each call,
|
|
9
|
+
* since transformers run outside Nest's DI.
|
|
10
|
+
*/
|
|
11
|
+
const encryptedTransformer = () => {
|
|
12
|
+
const getKey = () => {
|
|
13
|
+
const envKey = encrypted_column_module_1.EncryptedColumnModule.getKeyEnv();
|
|
14
|
+
const key = process.env[envKey];
|
|
15
|
+
if (!key || !/^[0-9a-fA-F]{64}$/.test(key)) {
|
|
16
|
+
throw new Error(`${envKey} must be a 32 byte hex string`);
|
|
17
|
+
}
|
|
18
|
+
return key;
|
|
19
|
+
};
|
|
20
|
+
return {
|
|
21
|
+
to: (value) => {
|
|
22
|
+
if (value === null || value === undefined)
|
|
23
|
+
return value;
|
|
24
|
+
const iv = utils_1.Utils.randomBytes(12);
|
|
25
|
+
const data = utils_1.Utils.AES256GCM.encrypt({ data: JSON.stringify(value), iv, key: getKey() });
|
|
26
|
+
return { iv, data };
|
|
27
|
+
},
|
|
28
|
+
from: (value) => {
|
|
29
|
+
if (value === null || value === undefined)
|
|
30
|
+
return value;
|
|
31
|
+
return JSON.parse(utils_1.Utils.AES256GCM.decrypt({ data: value.data, iv: value.iv, key: getKey() }));
|
|
32
|
+
},
|
|
33
|
+
};
|
|
34
|
+
};
|
|
35
|
+
exports.encryptedTransformer = encryptedTransformer;
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.dateOnlyTransformer = exports.dateTimeTransformer = void 0;
|
|
4
|
+
const luxon_1 = require("luxon");
|
|
5
|
+
exports.dateTimeTransformer = {
|
|
6
|
+
to: (value) => value?.toJSDate() ?? value,
|
|
7
|
+
from: (value) => (value ? luxon_1.DateTime.fromJSDate(value) : value),
|
|
8
|
+
};
|
|
9
|
+
exports.dateOnlyTransformer = {
|
|
10
|
+
to: (value) => value?.toISODate() ?? value,
|
|
11
|
+
from: (value) => value instanceof Date ? luxon_1.DateTime.fromJSDate(value) : value ? luxon_1.DateTime.fromISO(value) : value,
|
|
12
|
+
};
|