termo_core 0.1.52 → 0.1.54
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/base/index.d.ts +1 -0
- package/dist/base/index.js +1 -0
- package/dist/base/log_http.d.ts +36 -0
- package/dist/base/log_http.js +134 -0
- package/dist/intranet/tipos.d.ts +26 -0
- package/package.json +1 -1
package/dist/base/index.d.ts
CHANGED
|
@@ -7,3 +7,4 @@ export { definir_tempo_limite_do_servico_neste_processo, endereco_do_servico_no_
|
|
|
7
7
|
export * as servicos from "./servicos.js";
|
|
8
8
|
export { CAMINHO_DO_TOKEN_DE_APP, definir_segredo_do_app, identificador_do_aplicativo, MARGEM_PARA_RENOVAR_O_TOKEN_EM_SEGUNDOS, segredo_do_app_configurado, token_do_aplicativo, VARIAVEL_DO_SEGREDO_DO_APP, type TokenDoAplicativoEmitido, } from "./token_do_aplicativo.js";
|
|
9
9
|
export { TODOS_OS_SERVICOS } from "./servicos.js";
|
|
10
|
+
export { definir_versao_do_log_http, enviar_logs_da_fila, guardar_log_http, MAXIMO_DE_LOGS_NA_FILA, MAXIMO_DE_LOGS_POR_LOTE, medir_requisicao_http, registrar_logs_http_fetch, registrar_logs_http_hono, registrar_logs_http_sveltekit, SEGUNDOS_ENTRE_ENVIOS, } from "./log_http.js";
|
package/dist/base/index.js
CHANGED
|
@@ -7,3 +7,4 @@ export { definir_tempo_limite_do_servico_neste_processo, endereco_do_servico_no_
|
|
|
7
7
|
export * as servicos from "./servicos.js";
|
|
8
8
|
export { CAMINHO_DO_TOKEN_DE_APP, definir_segredo_do_app, identificador_do_aplicativo, MARGEM_PARA_RENOVAR_O_TOKEN_EM_SEGUNDOS, segredo_do_app_configurado, token_do_aplicativo, VARIAVEL_DO_SEGREDO_DO_APP, } from "./token_do_aplicativo.js";
|
|
9
9
|
export { TODOS_OS_SERVICOS } from "./servicos.js";
|
|
10
|
+
export { definir_versao_do_log_http, enviar_logs_da_fila, guardar_log_http, MAXIMO_DE_LOGS_NA_FILA, MAXIMO_DE_LOGS_POR_LOTE, medir_requisicao_http, registrar_logs_http_fetch, registrar_logs_http_hono, registrar_logs_http_sveltekit, SEGUNDOS_ENTRE_ENVIOS, } from "./log_http.js";
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import type { LogEnviado } from "../tracing/tipos.js";
|
|
2
|
+
export declare const MAXIMO_DE_LOGS_POR_LOTE = 500;
|
|
3
|
+
export declare const MAXIMO_DE_LOGS_NA_FILA = 20000;
|
|
4
|
+
export declare const SEGUNDOS_ENTRE_ENVIOS = 5;
|
|
5
|
+
export declare function logs_aguardando_envio(): readonly LogEnviado[];
|
|
6
|
+
export declare function definir_versao_do_log_http(versao: string): void;
|
|
7
|
+
export declare function guardar_log_http(log: LogEnviado): void;
|
|
8
|
+
export declare function enviar_logs_da_fila(): Promise<void>;
|
|
9
|
+
/**
|
|
10
|
+
* Mede uma requisição Web (`Request`/`Response`) e guarda o log para o TermoTracing.
|
|
11
|
+
* `rota` é o padrão casado pelo roteador, por exemplo `/pedido/:id`.
|
|
12
|
+
*/
|
|
13
|
+
export declare function medir_requisicao_http(requisicao: Request, responder: () => Promise<Response>, rota?: string | null): Promise<Response>;
|
|
14
|
+
interface ContextoDoHono {
|
|
15
|
+
req: {
|
|
16
|
+
raw: Request;
|
|
17
|
+
routePath?: string;
|
|
18
|
+
};
|
|
19
|
+
res: Response;
|
|
20
|
+
}
|
|
21
|
+
/** Middleware do Hono: `app.use(registrar_logs_http_hono("1.2.3"))`. */
|
|
22
|
+
export declare function registrar_logs_http_hono(versao: string): (contexto: ContextoDoHono, proximo: () => Promise<void>) => Promise<void>;
|
|
23
|
+
interface EventoDoSvelteKit {
|
|
24
|
+
request: Request;
|
|
25
|
+
route: {
|
|
26
|
+
id: string | null;
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
/** `handle` do SvelteKit (`hooks.server.ts`): `export const handle = registrar_logs_http_sveltekit("1.2.3")`. */
|
|
30
|
+
export declare function registrar_logs_http_sveltekit(versao: string): ({ event, resolve }: {
|
|
31
|
+
event: EventoDoSvelteKit;
|
|
32
|
+
resolve: (evento: EventoDoSvelteKit) => Promise<Response>;
|
|
33
|
+
}) => Promise<Response>;
|
|
34
|
+
/** Envolve um `fetch(request)` qualquer (Bun.serve, Deno.serve, Cloudflare Workers). */
|
|
35
|
+
export declare function registrar_logs_http_fetch<Argumentos extends unknown[]>(versao: string, tratar: (requisicao: Request, ...argumentos: Argumentos) => Promise<Response>): (requisicao: Request, ...argumentos: Argumentos) => Promise<Response>;
|
|
36
|
+
export {};
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
import { ambiente_atual } from "./ambiente.js";
|
|
2
|
+
import { token_do_aplicativo } from "./token_do_aplicativo.js";
|
|
3
|
+
import { criar_log } from "../tracing/rotas.js";
|
|
4
|
+
export const MAXIMO_DE_LOGS_POR_LOTE = 500;
|
|
5
|
+
export const MAXIMO_DE_LOGS_NA_FILA = 20_000;
|
|
6
|
+
export const SEGUNDOS_ENTRE_ENVIOS = 5;
|
|
7
|
+
const fila_de_logs = [];
|
|
8
|
+
let versao_do_back_end = null;
|
|
9
|
+
let tarefa_de_envio = null;
|
|
10
|
+
let envio_em_andamento = false;
|
|
11
|
+
export function logs_aguardando_envio() {
|
|
12
|
+
return fila_de_logs;
|
|
13
|
+
}
|
|
14
|
+
export function definir_versao_do_log_http(versao) {
|
|
15
|
+
versao_do_back_end = versao || null;
|
|
16
|
+
}
|
|
17
|
+
export function guardar_log_http(log) {
|
|
18
|
+
if (fila_de_logs.length < MAXIMO_DE_LOGS_NA_FILA)
|
|
19
|
+
fila_de_logs.push(log);
|
|
20
|
+
if (tarefa_de_envio === null) {
|
|
21
|
+
tarefa_de_envio = setInterval(() => void enviar_logs_da_fila(), SEGUNDOS_ENTRE_ENVIOS * 1000);
|
|
22
|
+
const tarefa = tarefa_de_envio;
|
|
23
|
+
tarefa.unref?.();
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
export async function enviar_logs_da_fila() {
|
|
27
|
+
if (envio_em_andamento)
|
|
28
|
+
return;
|
|
29
|
+
envio_em_andamento = true;
|
|
30
|
+
try {
|
|
31
|
+
while (fila_de_logs.length > 0) {
|
|
32
|
+
const logs = fila_de_logs.splice(0, MAXIMO_DE_LOGS_POR_LOTE);
|
|
33
|
+
try {
|
|
34
|
+
const credencial_de_acesso = await token_do_aplicativo();
|
|
35
|
+
await criar_log(credencial_de_acesso, { ambiente: ambiente_atual(), versao: versao_do_back_end, logs });
|
|
36
|
+
}
|
|
37
|
+
catch {
|
|
38
|
+
continue;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
finally {
|
|
43
|
+
envio_em_andamento = false;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
function cabecalho(requisicao, nome) {
|
|
47
|
+
const valor = requisicao.headers.get(nome)?.trim();
|
|
48
|
+
return valor ? valor : null;
|
|
49
|
+
}
|
|
50
|
+
function ip_de_origem(requisicao) {
|
|
51
|
+
return (cabecalho(requisicao, "cf-connecting-ip") ??
|
|
52
|
+
cabecalho(requisicao, "x-forwarded-for")?.split(",")[0]?.trim() ??
|
|
53
|
+
cabecalho(requisicao, "x-real-ip"));
|
|
54
|
+
}
|
|
55
|
+
/** Lê `sub` e `email` do JWT sem conferir a assinatura: serve só para o log. */
|
|
56
|
+
function usuario_do_token(requisicao) {
|
|
57
|
+
const token = cabecalho(requisicao, "authorization")?.replace(/^Bearer\s+/i, "");
|
|
58
|
+
const carga = token?.split(".")[1];
|
|
59
|
+
if (!carga)
|
|
60
|
+
return { usuario_id: null, usuario_email: null };
|
|
61
|
+
try {
|
|
62
|
+
const base64 = carga.replace(/-/g, "+").replace(/_/g, "/");
|
|
63
|
+
const dados = JSON.parse(new TextDecoder().decode(Uint8Array.from(atob(base64), (letra) => letra.charCodeAt(0))));
|
|
64
|
+
return {
|
|
65
|
+
usuario_id: typeof dados.sub === "string" ? dados.sub : null,
|
|
66
|
+
usuario_email: typeof dados.email === "string" ? dados.email : null,
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
catch {
|
|
70
|
+
return { usuario_id: null, usuario_email: null };
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
async function mensagem_de_erro(resposta) {
|
|
74
|
+
if (resposta.status < 400 || !resposta.headers.get("content-type")?.includes("json"))
|
|
75
|
+
return null;
|
|
76
|
+
try {
|
|
77
|
+
const dados = (await resposta.clone().json());
|
|
78
|
+
const mensagem = ["erro", "mensagem", "message", "error"].map((campo) => dados[campo]).find((valor) => typeof valor === "string");
|
|
79
|
+
return mensagem ?? null;
|
|
80
|
+
}
|
|
81
|
+
catch {
|
|
82
|
+
return null;
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* Mede uma requisição Web (`Request`/`Response`) e guarda o log para o TermoTracing.
|
|
87
|
+
* `rota` é o padrão casado pelo roteador, por exemplo `/pedido/:id`.
|
|
88
|
+
*/
|
|
89
|
+
export async function medir_requisicao_http(requisicao, responder, rota) {
|
|
90
|
+
const inicio = performance.now();
|
|
91
|
+
const ocorrido_em = new Date().toISOString();
|
|
92
|
+
let resposta = null;
|
|
93
|
+
try {
|
|
94
|
+
resposta = await responder();
|
|
95
|
+
return resposta;
|
|
96
|
+
}
|
|
97
|
+
finally {
|
|
98
|
+
const status = resposta?.status ?? 500;
|
|
99
|
+
const mensagem = resposta ? await mensagem_de_erro(resposta) : "Erro sem resposta";
|
|
100
|
+
guardar_log_http({
|
|
101
|
+
metodo: requisicao.method,
|
|
102
|
+
rota: rota ?? null,
|
|
103
|
+
caminho: new URL(requisicao.url).pathname,
|
|
104
|
+
status,
|
|
105
|
+
duracao_ms: Math.round(performance.now() - inicio),
|
|
106
|
+
mensagem,
|
|
107
|
+
agente: cabecalho(requisicao, "user-agent"),
|
|
108
|
+
ip: ip_de_origem(requisicao),
|
|
109
|
+
requisicao_id: cabecalho(requisicao, "x-request-id"),
|
|
110
|
+
ocorrido_em,
|
|
111
|
+
...usuario_do_token(requisicao),
|
|
112
|
+
});
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
/** Middleware do Hono: `app.use(registrar_logs_http_hono("1.2.3"))`. */
|
|
116
|
+
export function registrar_logs_http_hono(versao) {
|
|
117
|
+
definir_versao_do_log_http(versao);
|
|
118
|
+
return async (contexto, proximo) => {
|
|
119
|
+
await medir_requisicao_http(contexto.req.raw, async () => {
|
|
120
|
+
await proximo();
|
|
121
|
+
return contexto.res;
|
|
122
|
+
}, contexto.req.routePath);
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
/** `handle` do SvelteKit (`hooks.server.ts`): `export const handle = registrar_logs_http_sveltekit("1.2.3")`. */
|
|
126
|
+
export function registrar_logs_http_sveltekit(versao) {
|
|
127
|
+
definir_versao_do_log_http(versao);
|
|
128
|
+
return ({ event, resolve }) => medir_requisicao_http(event.request, () => resolve(event), event.route.id);
|
|
129
|
+
}
|
|
130
|
+
/** Envolve um `fetch(request)` qualquer (Bun.serve, Deno.serve, Cloudflare Workers). */
|
|
131
|
+
export function registrar_logs_http_fetch(versao, tratar) {
|
|
132
|
+
definir_versao_do_log_http(versao);
|
|
133
|
+
return (requisicao, ...argumentos) => medir_requisicao_http(requisicao, () => tratar(requisicao, ...argumentos));
|
|
134
|
+
}
|
package/dist/intranet/tipos.d.ts
CHANGED
|
@@ -85,6 +85,7 @@ export interface ContaPagar {
|
|
|
85
85
|
numero_documento?: string | null;
|
|
86
86
|
ocorrencia?: string | null;
|
|
87
87
|
quantidade_parcelas?: number | null;
|
|
88
|
+
recebimentos: Array<ContaPagarRecebimento>;
|
|
88
89
|
saldo?: string | null;
|
|
89
90
|
serie_documento?: string | null;
|
|
90
91
|
situacao?: string | null;
|
|
@@ -97,6 +98,18 @@ export interface ContaPagarAutoComplete {
|
|
|
97
98
|
numero_documento?: string | null;
|
|
98
99
|
valor?: string | null;
|
|
99
100
|
}
|
|
101
|
+
export interface ContaPagarRecebimento {
|
|
102
|
+
data?: string | null;
|
|
103
|
+
id: number;
|
|
104
|
+
id_conta?: string | null;
|
|
105
|
+
id_externo: number;
|
|
106
|
+
tipo?: number | null;
|
|
107
|
+
valor_acrescimo?: string | null;
|
|
108
|
+
valor_desconto?: string | null;
|
|
109
|
+
valor_juro?: string | null;
|
|
110
|
+
valor_pago?: string | null;
|
|
111
|
+
valor_taxa?: string | null;
|
|
112
|
+
}
|
|
100
113
|
export interface ContaPagarResumo {
|
|
101
114
|
categoria_descricao?: string | null;
|
|
102
115
|
categoria_grupo?: string | null;
|
|
@@ -143,6 +156,7 @@ export interface ContaReceber {
|
|
|
143
156
|
ocorrencia?: string | null;
|
|
144
157
|
quantidade_parcelas?: number | null;
|
|
145
158
|
quantidade_parcelas_antecipadas?: number | null;
|
|
159
|
+
recebimentos: Array<ContaReceberRecebimento>;
|
|
146
160
|
saldo?: string | null;
|
|
147
161
|
serie_documento?: string | null;
|
|
148
162
|
situacao?: string | null;
|
|
@@ -156,6 +170,18 @@ export interface ContaReceberAutoComplete {
|
|
|
156
170
|
numero_documento?: string | null;
|
|
157
171
|
valor?: string | null;
|
|
158
172
|
}
|
|
173
|
+
export interface ContaReceberRecebimento {
|
|
174
|
+
data?: string | null;
|
|
175
|
+
id: number;
|
|
176
|
+
id_conta?: string | null;
|
|
177
|
+
id_externo: number;
|
|
178
|
+
tipo?: number | null;
|
|
179
|
+
valor_acrescimo?: string | null;
|
|
180
|
+
valor_desconto?: string | null;
|
|
181
|
+
valor_juro?: string | null;
|
|
182
|
+
valor_pago?: string | null;
|
|
183
|
+
valor_taxa?: string | null;
|
|
184
|
+
}
|
|
159
185
|
export interface ContaReceberResumo {
|
|
160
186
|
categoria_descricao?: string | null;
|
|
161
187
|
categoria_grupo?: string | null;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "termo_core",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.54",
|
|
4
4
|
"description": "Todos os clientes da Termotubos num pacote só: um módulo por serviço e cada rota da API como uma função com fetch, com o endereço resolvido pelo ambiente atual.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "TI Termotubos <ti@termotubos.com.br>",
|