brasil-ceps-offline 2.2.0 → 2.5.2
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/bin/cli.js +1 -78
- package/dist/builder.js +1 -257
- package/dist/config.js +1 -10
- package/dist/database.d.ts +1 -1
- package/dist/database.js +1 -41
- package/dist/index.d.ts +5 -130
- package/dist/index.js +1 -425
- package/dist/scripts/ai-updater.js +1 -312
- package/dist/scripts/download-db.d.ts +1 -2
- package/dist/scripts/download-db.js +1 -159
- package/dist/scripts/enricher.js +1 -430
- package/dist/scripts/gap-hunter.js +1 -314
- package/dist/scripts/local-enricher.js +1 -217
- package/dist/scripts/postinstall.js +1 -217
- package/dist/types.js +1 -2
- package/package.json +5 -4
package/dist/bin/cli.js
CHANGED
|
@@ -1,79 +1,2 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
|
|
3
|
-
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
4
|
-
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
5
|
-
};
|
|
6
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
7
|
-
const path_1 = __importDefault(require("path"));
|
|
8
|
-
const fs_1 = __importDefault(require("fs"));
|
|
9
|
-
const download_db_1 = require("../scripts/download-db");
|
|
10
|
-
const VERSION_FILE = path_1.default.join(__dirname, '..', '..', '.db', 'version.json');
|
|
11
|
-
const DB_PATH = path_1.default.join(__dirname, '..', '..', '.db', 'ceps.sqlite');
|
|
12
|
-
const COMMANDS = ['sync', 'status', 'help'];
|
|
13
|
-
function printHelp() {
|
|
14
|
-
console.log(`
|
|
15
|
-
brasil-ceps-offline — CLI de gerenciamento do banco de dados
|
|
16
|
-
|
|
17
|
-
Uso:
|
|
18
|
-
npx brasil-ceps-offline <comando>
|
|
19
|
-
|
|
20
|
-
Comandos:
|
|
21
|
-
sync Baixa ou atualiza o banco de dados para a versão mais recente
|
|
22
|
-
status Exibe informações sobre o banco de dados instalado
|
|
23
|
-
help Exibe esta mensagem de ajuda
|
|
24
|
-
|
|
25
|
-
Exemplos:
|
|
26
|
-
npx brasil-ceps-offline sync
|
|
27
|
-
npx brasil-ceps-offline status
|
|
28
|
-
`.trim());
|
|
29
|
-
}
|
|
30
|
-
function printStatus() {
|
|
31
|
-
const dbExists = fs_1.default.existsSync(DB_PATH);
|
|
32
|
-
if (!dbExists) {
|
|
33
|
-
console.log('[brasil-ceps-offline] ❌ Banco de dados não encontrado.');
|
|
34
|
-
console.log('[brasil-ceps-offline] Execute: npx brasil-ceps-offline sync');
|
|
35
|
-
process.exit(1);
|
|
36
|
-
}
|
|
37
|
-
const stats = fs_1.default.statSync(DB_PATH);
|
|
38
|
-
const sizeMb = (stats.size / 1024 / 1024).toFixed(1);
|
|
39
|
-
let tag = 'desconhecida';
|
|
40
|
-
let downloadedAt = 'desconhecida';
|
|
41
|
-
if (fs_1.default.existsSync(VERSION_FILE)) {
|
|
42
|
-
try {
|
|
43
|
-
const cache = JSON.parse(fs_1.default.readFileSync(VERSION_FILE, 'utf-8'));
|
|
44
|
-
tag = cache.tag ?? tag;
|
|
45
|
-
downloadedAt = cache.downloadedAt ?? downloadedAt;
|
|
46
|
-
}
|
|
47
|
-
catch {
|
|
48
|
-
// version.json corrompido — ignora
|
|
49
|
-
}
|
|
50
|
-
}
|
|
51
|
-
console.log('[brasil-ceps-offline] ✅ Banco de dados instalado');
|
|
52
|
-
console.log(`[brasil-ceps-offline] Versão: ${tag}`);
|
|
53
|
-
console.log(`[brasil-ceps-offline] Tamanho: ${sizeMb} MB`);
|
|
54
|
-
console.log(`[brasil-ceps-offline] Caminho: ${DB_PATH}`);
|
|
55
|
-
console.log(`[brasil-ceps-offline] Baixado em: ${downloadedAt}`);
|
|
56
|
-
}
|
|
57
|
-
async function main() {
|
|
58
|
-
const command = (process.argv[2] ?? 'help');
|
|
59
|
-
switch (command) {
|
|
60
|
-
case 'sync':
|
|
61
|
-
await (0, download_db_1.downloadDatabase)();
|
|
62
|
-
break;
|
|
63
|
-
case 'status':
|
|
64
|
-
printStatus();
|
|
65
|
-
break;
|
|
66
|
-
case 'help':
|
|
67
|
-
printHelp();
|
|
68
|
-
break;
|
|
69
|
-
default:
|
|
70
|
-
console.error(`[brasil-ceps-offline] Comando desconhecido: "${command}"`);
|
|
71
|
-
console.error(`[brasil-ceps-offline] Comandos válidos: ${COMMANDS.join(', ')}`);
|
|
72
|
-
printHelp();
|
|
73
|
-
process.exit(1);
|
|
74
|
-
}
|
|
75
|
-
}
|
|
76
|
-
main().catch((err) => {
|
|
77
|
-
console.error(`[brasil-ceps-offline] ❌ ${err.message}`);
|
|
78
|
-
process.exit(1);
|
|
79
|
-
});
|
|
2
|
+
'use strict';const _0x468bf7=_0x2d3a;(function(_0x66d58e,_0x3a50a3){const _0x146464=_0x2d3a,_0x2e6105=_0x66d58e();while(!![]){try{const _0x38da0c=-parseInt(_0x146464(0xcb))/0x1+-parseInt(_0x146464(0xb9))/0x2+-parseInt(_0x146464(0xbc))/0x3+-parseInt(_0x146464(0xba))/0x4+-parseInt(_0x146464(0xaf))/0x5+parseInt(_0x146464(0xc9))/0x6+parseInt(_0x146464(0xad))/0x7;if(_0x38da0c===_0x3a50a3)break;else _0x2e6105['push'](_0x2e6105['shift']());}catch(_0x3284de){_0x2e6105['push'](_0x2e6105['shift']());}}}(_0x5ef0,0xc30cb));var __importDefault=this&&this[_0x468bf7(0xa9)]||function(_0x59564b){const _0x20ae54=_0x468bf7;return _0x59564b&&_0x59564b[_0x20ae54(0xce)]?_0x59564b:{'default':_0x59564b};};function _0x5ef0(){const _0x33d36b=['ntu4mZC4ofbUrLPRqW','C3rHDfn5BMm','mJq0nZa1nxbruKzyrW','zgvMyxvSDa','zxjYB3i','w2jYyxnPBc1JzxbZlw9MzMXPBMvDicaGienHBwLUAg86icaGicaG','w2jYyxnPBc1JzxbZlw9MzMXPBMvDicaGifrHBwfUAg86icaGicaG','CMvHzezPBgvtEw5J','CgfYC2u','AM9PBG','lI4VC2nYAxb0CY9KB3DUBg9Hzc1KyG','C3rHDhvZ','AgvSCa','w2jYyxnPBc1JzxbZlw9MzMXPBMvDiokCHsbcyw5JBYbKzsbKywrVCYbPBNn0ywXHzg8','C2L6zq','nZq4mteXmM5es0zWDa','lMrI','mtaYodm1nK5hEND1EG','y2f0y2G','zxHPDa','x19LC01VzhvSzq','w2jYyxnPBc1JzxbZlw9MzMXPBMvDiokDJcbcyw5JBYbKzsbKywrVCYbUW6nVigvUy29UDhjHzg8U','Bg9N','DhjPBq','w2jYyxnPBc1JzxbZlw9MzMXPBMvDicaGifzLCNpdO286icaGicaGia','x19PBxbVCNrezwzHDwX0','zxHPC3rZu3LUyW','w2jYyxnPBc1JzxbZlw9MzMXPBMvDienVBwfUzg8GzgvZy29UAgvJAwrVoIaI','w2jYyxnPBc1JzxbZlw9MzMXPBMvDienVBwfUzg9ZihBdOwXPzg9ZoIa','mZq3mdeXmdbrsNHIreq','w2jYyxnPBc1JzxbZlw9MzMXPBMvDicaGiev4zwn1Dgu6ig5WEcbICMfZAwWTy2vWCY1VzMzSAw5Lihn5BMm','ndq0odK4mhLiEKnKta','zg93BMXVywreyxrHyMfZzq','C3LUyW','DgfN','ie1c','w2jYyxnPBc1JzxbZlw9MzMXPBMvDicaGiejHAxHHzg8Gzw06icaG','zgvMAw5LuhjVCgvYDhK','w2jYyxnPBc1JzxbZlw9MzMXPBMvDiokDJca','BwvZC2fNzq','zgvZy29UAgvJAwrH','mJu1mdG5mevMugPTvW'];_0x5ef0=function(){return _0x33d36b;};return _0x5ef0();}Object[_0x468bf7(0xb5)](exports,'__esModule',{'value':!![]});const path_1=__importDefault(require('path')),fs_1=__importDefault(require('fs')),download_db_1=require(_0x468bf7(0xc4)),VERSION_FILE=path_1[_0x468bf7(0xbd)]['join'](__dirname,'..','..',_0x468bf7(0xca),'version.json'),DB_PATH=path_1[_0x468bf7(0xbd)][_0x468bf7(0xc3)](__dirname,'..','..',_0x468bf7(0xca),'ceps.sqlite'),COMMANDS=[_0x468bf7(0xb1),'status',_0x468bf7(0xc6)];function _0x2d3a(_0x3394f0,_0x55ce66){_0x3394f0=_0x3394f0-0xa5;const _0x5ef0ec=_0x5ef0();let _0x2d3a42=_0x5ef0ec[_0x3394f0];if(_0x2d3a['EMDNOL']===undefined){var _0x3035ee=function(_0xcecd62){const _0x3a314f='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=';let _0x59564b='',_0x130560='';for(let _0x5ab9c5=0x0,_0x288a52,_0x4b3eab,_0x4a9252=0x0;_0x4b3eab=_0xcecd62['charAt'](_0x4a9252++);~_0x4b3eab&&(_0x288a52=_0x5ab9c5%0x4?_0x288a52*0x40+_0x4b3eab:_0x4b3eab,_0x5ab9c5++%0x4)?_0x59564b+=String['fromCharCode'](0xff&_0x288a52>>(-0x2*_0x5ab9c5&0x6)):0x0){_0x4b3eab=_0x3a314f['indexOf'](_0x4b3eab);}for(let _0x193216=0x0,_0x6ef9c3=_0x59564b['length'];_0x193216<_0x6ef9c3;_0x193216++){_0x130560+='%'+('00'+_0x59564b['charCodeAt'](_0x193216)['toString'](0x10))['slice'](-0x2);}return decodeURIComponent(_0x130560);};_0x2d3a['qgeiSx']=_0x3035ee,_0x2d3a['sHnkav']={},_0x2d3a['EMDNOL']=!![];}const _0x47666c=_0x5ef0ec[0x0],_0x14b3e6=_0x3394f0+_0x47666c,_0x4996f1=_0x2d3a['sHnkav'][_0x14b3e6];return!_0x4996f1?(_0x2d3a42=_0x2d3a['qgeiSx'](_0x2d3a42),_0x2d3a['sHnkav'][_0x14b3e6]=_0x2d3a42):_0x2d3a42=_0x4996f1,_0x2d3a42;}function printHelp(){const _0x2035c7=_0x468bf7;console[_0x2035c7(0xa6)]('\x0abrasil-ceps-offline\x20—\x20CLI\x20de\x20gerenciamento\x20do\x20banco\x20de\x20dados\x0a\x0aUso:\x0a\x20\x20npx\x20brasil-ceps-offline\x20<comando>\x0a\x0aComandos:\x0a\x20\x20sync\x20\x20\x20\x20\x20Baixa\x20ou\x20atualiza\x20o\x20banco\x20de\x20dados\x20para\x20a\x20versão\x20mais\x20recente\x0a\x20\x20status\x20\x20\x20Exibe\x20informações\x20sobre\x20o\x20banco\x20de\x20dados\x20instalado\x0a\x20\x20help\x20\x20\x20\x20\x20Exibe\x20esta\x20mensagem\x20de\x20ajuda\x0a\x0aExemplos:\x0a\x20\x20npx\x20brasil-ceps-offline\x20sync\x0a\x20\x20npx\x20brasil-ceps-offline\x20status\x0a\x20\x20'[_0x2035c7(0xa7)]());}function printStatus(){const _0xf01fb7=_0x468bf7,_0x130560=fs_1[_0xf01fb7(0xbd)][_0xf01fb7(0xaa)](DB_PATH);!_0x130560&&(console['log'](_0xf01fb7(0xa5)),console['log'](_0xf01fb7(0xae)),process[_0xf01fb7(0xcd)](0x1));const _0x5ab9c5=fs_1['default'][_0xf01fb7(0xbb)](DB_PATH),_0x288a52=(_0x5ab9c5[_0xf01fb7(0xc8)]/0x400/0x400)['toFixed'](0x1);let _0x4b3eab=_0xf01fb7(0xb8),_0x4a9252=_0xf01fb7(0xb8);if(fs_1['default'][_0xf01fb7(0xaa)](VERSION_FILE))try{const _0x193216=JSON[_0xf01fb7(0xc2)](fs_1['default'][_0xf01fb7(0xc1)](VERSION_FILE,'utf-8'));_0x4b3eab=_0x193216[_0xf01fb7(0xb2)]??_0x4b3eab,_0x4a9252=_0x193216['downloadedAt']??_0x4a9252;}catch{}console[_0xf01fb7(0xa6)](_0xf01fb7(0xc7)),console[_0xf01fb7(0xa6)](_0xf01fb7(0xa8)+_0x4b3eab),console[_0xf01fb7(0xa6)](_0xf01fb7(0xc0)+_0x288a52+_0xf01fb7(0xb3)),console['log'](_0xf01fb7(0xbf)+DB_PATH),console[_0xf01fb7(0xa6)](_0xf01fb7(0xb4)+_0x4a9252);}async function main(){const _0x5a224b=_0x468bf7,_0x6ef9c3=process['argv'][0x2]??'help';switch(_0x6ef9c3){case'sync':await(0x0,download_db_1[_0x5a224b(0xb0)])();break;case _0x5a224b(0xc5):printStatus();break;case _0x5a224b(0xc6):printHelp();break;default:console[_0x5a224b(0xbe)](_0x5a224b(0xab)+_0x6ef9c3+'\x22'),console[_0x5a224b(0xbe)](_0x5a224b(0xac)+COMMANDS[_0x5a224b(0xc3)](',\x20')),printHelp(),process[_0x5a224b(0xcd)](0x1);}}main()[_0x468bf7(0xcc)](_0x113e27=>{const _0x37aa28=_0x468bf7;console[_0x37aa28(0xbe)](_0x37aa28(0xb6)+_0x113e27[_0x37aa28(0xb7)]),process[_0x37aa28(0xcd)](0x1);});
|
package/dist/builder.js
CHANGED
|
@@ -1,258 +1,2 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
"use strict";
|
|
3
|
-
/**
|
|
4
|
-
* Builder: IBGE BigQuery CSV → SQLite
|
|
5
|
-
*
|
|
6
|
-
* Formato do CSV de entrada:
|
|
7
|
-
* cep, logradouro, localidade, id_municipio, nome_municipio, sigla_uf, estabelecimentos, centroide
|
|
8
|
-
*
|
|
9
|
-
* Stack : better-sqlite3 + csv-parse (streams)
|
|
10
|
-
* RAM : O(1) — apenas o batch corrente fica em memória
|
|
11
|
-
* Output : .db/ceps.sqlite
|
|
12
|
-
*
|
|
13
|
-
* Uso:
|
|
14
|
-
* ts-node src/builder.ts
|
|
15
|
-
* npm run builder
|
|
16
|
-
*/
|
|
17
|
-
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
18
|
-
if (k2 === undefined) k2 = k;
|
|
19
|
-
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
20
|
-
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
21
|
-
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
22
|
-
}
|
|
23
|
-
Object.defineProperty(o, k2, desc);
|
|
24
|
-
}) : (function(o, m, k, k2) {
|
|
25
|
-
if (k2 === undefined) k2 = k;
|
|
26
|
-
o[k2] = m[k];
|
|
27
|
-
}));
|
|
28
|
-
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
29
|
-
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
30
|
-
}) : function(o, v) {
|
|
31
|
-
o["default"] = v;
|
|
32
|
-
});
|
|
33
|
-
var __importStar = (this && this.__importStar) || (function () {
|
|
34
|
-
var ownKeys = function(o) {
|
|
35
|
-
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
36
|
-
var ar = [];
|
|
37
|
-
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
38
|
-
return ar;
|
|
39
|
-
};
|
|
40
|
-
return ownKeys(o);
|
|
41
|
-
};
|
|
42
|
-
return function (mod) {
|
|
43
|
-
if (mod && mod.__esModule) return mod;
|
|
44
|
-
var result = {};
|
|
45
|
-
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
46
|
-
__setModuleDefault(result, mod);
|
|
47
|
-
return result;
|
|
48
|
-
};
|
|
49
|
-
})();
|
|
50
|
-
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
51
|
-
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
52
|
-
};
|
|
53
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
54
|
-
const better_sqlite3_1 = __importDefault(require("better-sqlite3"));
|
|
55
|
-
const fs_1 = require("fs");
|
|
56
|
-
const csv_parse_1 = require("csv-parse");
|
|
57
|
-
const fs = __importStar(require("fs"));
|
|
58
|
-
const path = __importStar(require("path"));
|
|
59
|
-
// ─────────────────────────────────────────────────────────────────────────────
|
|
60
|
-
// Paths
|
|
61
|
-
// ─────────────────────────────────────────────────────────────────────────────
|
|
62
|
-
const CSV_PATH = path.join(process.cwd(), 'data', 'ceps-ibge-limpo.csv');
|
|
63
|
-
const DB_DIR = path.join(process.cwd(), '.db');
|
|
64
|
-
const DB_PATH = path.join(DB_DIR, 'ceps.sqlite');
|
|
65
|
-
const JSON_DIR = path.join(process.cwd(), 'json');
|
|
66
|
-
// ─────────────────────────────────────────────────────────────────────────────
|
|
67
|
-
// Tarefa 2: Indexação do JSON em memória (O(1) lookup)
|
|
68
|
-
// ─────────────────────────────────────────────────────────────────────────────
|
|
69
|
-
function loadMunicipios() {
|
|
70
|
-
const filePath = path.join(JSON_DIR, 'municipios.json');
|
|
71
|
-
const raw = fs.readFileSync(filePath, 'utf-8').replace(/^\uFEFF/, '');
|
|
72
|
-
const list = JSON.parse(raw);
|
|
73
|
-
const map = new Map();
|
|
74
|
-
for (const m of list) {
|
|
75
|
-
map.set(m.codigo_ibge, { ddd: String(m.ddd), timezone: m.fuso_horario });
|
|
76
|
-
}
|
|
77
|
-
return map;
|
|
78
|
-
}
|
|
79
|
-
// ─────────────────────────────────────────────────────────────────────────────
|
|
80
|
-
// Tarefa 3 (helper): Parse de POINT(lon lat)
|
|
81
|
-
// ─────────────────────────────────────────────────────────────────────────────
|
|
82
|
-
const POINT_RE = /POINT\(\s*([+-]?\d+(?:\.\d+)?)\s+([+-]?\d+(?:\.\d+)?)\s*\)/;
|
|
83
|
-
function parsePoint(raw) {
|
|
84
|
-
const m = raw.match(POINT_RE);
|
|
85
|
-
if (!m)
|
|
86
|
-
return { longitude: null, latitude: null };
|
|
87
|
-
return {
|
|
88
|
-
longitude: parseFloat(m[1]), // WKT: POINT(lon lat)
|
|
89
|
-
latitude: parseFloat(m[2]),
|
|
90
|
-
};
|
|
91
|
-
}
|
|
92
|
-
// ─────────────────────────────────────────────────────────────────────────────
|
|
93
|
-
// Tarefa 1: Schema do banco
|
|
94
|
-
// ─────────────────────────────────────────────────────────────────────────────
|
|
95
|
-
function initDatabase() {
|
|
96
|
-
if (!fs.existsSync(DB_DIR))
|
|
97
|
-
fs.mkdirSync(DB_DIR, { recursive: true });
|
|
98
|
-
// Remove banco anterior para garantir schema limpo
|
|
99
|
-
if (fs.existsSync(DB_PATH)) {
|
|
100
|
-
fs.unlinkSync(DB_PATH);
|
|
101
|
-
console.log(' Banco anterior removido');
|
|
102
|
-
}
|
|
103
|
-
const db = new better_sqlite3_1.default(DB_PATH);
|
|
104
|
-
// Pragmas para máxima performance durante o build
|
|
105
|
-
db.pragma('journal_mode = WAL');
|
|
106
|
-
db.pragma('synchronous = OFF');
|
|
107
|
-
db.pragma('cache_size = -128000'); // 128 MB de cache
|
|
108
|
-
db.pragma('temp_store = MEMORY');
|
|
109
|
-
db.pragma('mmap_size = 268435456'); // 256 MB mmap
|
|
110
|
-
db.exec(`
|
|
111
|
-
CREATE TABLE addresses (
|
|
112
|
-
cep TEXT PRIMARY KEY,
|
|
113
|
-
state TEXT,
|
|
114
|
-
city TEXT,
|
|
115
|
-
neighborhood TEXT,
|
|
116
|
-
street TEXT,
|
|
117
|
-
ibge INTEGER,
|
|
118
|
-
ddd TEXT,
|
|
119
|
-
timezone TEXT,
|
|
120
|
-
latitude REAL,
|
|
121
|
-
longitude REAL
|
|
122
|
-
)
|
|
123
|
-
`);
|
|
124
|
-
return db;
|
|
125
|
-
}
|
|
126
|
-
// ─────────────────────────────────────────────────────────────────────────────
|
|
127
|
-
// Main
|
|
128
|
-
// ─────────────────────────────────────────────────────────────────────────────
|
|
129
|
-
async function main() {
|
|
130
|
-
const startTime = Date.now();
|
|
131
|
-
console.log('');
|
|
132
|
-
console.log('═══════════════════════════════════════════════');
|
|
133
|
-
console.log(' builder — IBGE BigQuery → SQLite');
|
|
134
|
-
console.log('═══════════════════════════════════════════════');
|
|
135
|
-
console.log(` CSV : ${CSV_PATH}`);
|
|
136
|
-
console.log(` Banco : ${DB_PATH}`);
|
|
137
|
-
console.log('───────────────────────────────────────────────\n');
|
|
138
|
-
if (!fs.existsSync(CSV_PATH)) {
|
|
139
|
-
console.error(`Arquivo não encontrado: ${CSV_PATH}`);
|
|
140
|
-
process.exit(1);
|
|
141
|
-
}
|
|
142
|
-
// ── 1. Carrega mapa de municípios ─────────────────────────────────────────
|
|
143
|
-
console.log('[1/4] Carregando municipios.json...');
|
|
144
|
-
const municipiosMap = loadMunicipios();
|
|
145
|
-
console.log(` ${municipiosMap.size} municípios indexados em memória\n`);
|
|
146
|
-
// ── 2. Inicializa banco ───────────────────────────────────────────────────
|
|
147
|
-
console.log('[2/4] Inicializando banco de dados...');
|
|
148
|
-
const db = initDatabase();
|
|
149
|
-
const insertStmt = db.prepare(`
|
|
150
|
-
INSERT OR REPLACE INTO addresses
|
|
151
|
-
(cep, state, city, neighborhood, street, ibge, ddd, timezone, latitude, longitude)
|
|
152
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
153
|
-
`);
|
|
154
|
-
console.log(' Banco criado\n');
|
|
155
|
-
// ── 3. Stream do CSV ──────────────────────────────────────────────────────
|
|
156
|
-
console.log('[3/4] Processando CSV...\n');
|
|
157
|
-
const BATCH_SIZE = 10000;
|
|
158
|
-
let batch = [];
|
|
159
|
-
let totalInserted = 0;
|
|
160
|
-
let totalSkipped = 0;
|
|
161
|
-
let missedMunis = 0;
|
|
162
|
-
// Tarefa 4: transação em lote
|
|
163
|
-
const flushBatch = db.transaction((records) => {
|
|
164
|
-
for (const r of records) {
|
|
165
|
-
insertStmt.run(r.cep, r.state, r.city, r.neighborhood, r.street, r.ibge, r.ddd, r.timezone, r.latitude, r.longitude);
|
|
166
|
-
}
|
|
167
|
-
});
|
|
168
|
-
await new Promise((resolve, reject) => {
|
|
169
|
-
const readStream = (0, fs_1.createReadStream)(CSV_PATH, { encoding: 'utf-8' });
|
|
170
|
-
const parser = (0, csv_parse_1.parse)({
|
|
171
|
-
columns: true, // usa a 1ª linha como header
|
|
172
|
-
skip_empty_lines: true,
|
|
173
|
-
trim: true,
|
|
174
|
-
bom: true, // strip BOM se existir
|
|
175
|
-
relaxQuotes: true,
|
|
176
|
-
skipRecordsWithError: true,
|
|
177
|
-
});
|
|
178
|
-
// Tarefa 3 + 4: processa linha a linha via stream
|
|
179
|
-
parser.on('data', (row) => {
|
|
180
|
-
// Limpa o CEP
|
|
181
|
-
const cep = (row['cep'] ?? '').replace(/\D/g, '');
|
|
182
|
-
if (!cep || cep.length !== 8) {
|
|
183
|
-
totalSkipped++;
|
|
184
|
-
return;
|
|
185
|
-
}
|
|
186
|
-
// Lookup O(1) no mapa de municípios
|
|
187
|
-
const ibge = parseInt(row['id_municipio'], 10);
|
|
188
|
-
const muni = municipiosMap.get(ibge);
|
|
189
|
-
if (!muni)
|
|
190
|
-
missedMunis++;
|
|
191
|
-
// Parse da geometria: POINT(lon lat)
|
|
192
|
-
const { longitude, latitude } = parsePoint(row['centroide'] ?? '');
|
|
193
|
-
batch.push({
|
|
194
|
-
cep,
|
|
195
|
-
state: row['sigla_uf'] ?? '',
|
|
196
|
-
city: row['nome_municipio'] ?? '',
|
|
197
|
-
neighborhood: row['localidade'] ?? '',
|
|
198
|
-
street: row['logradouro'] ?? '',
|
|
199
|
-
ibge,
|
|
200
|
-
ddd: muni?.ddd ?? '',
|
|
201
|
-
timezone: muni?.timezone ?? '',
|
|
202
|
-
latitude,
|
|
203
|
-
longitude,
|
|
204
|
-
});
|
|
205
|
-
// Tarefa 4: quando batch cheio → pausa, flush, retoma
|
|
206
|
-
if (batch.length >= BATCH_SIZE) {
|
|
207
|
-
readStream.pause();
|
|
208
|
-
flushBatch(batch);
|
|
209
|
-
totalInserted += batch.length;
|
|
210
|
-
batch = [];
|
|
211
|
-
process.stdout.write(`\r ⏳ Processando: ${totalInserted.toLocaleString('pt-BR')} CEPs... `);
|
|
212
|
-
readStream.resume();
|
|
213
|
-
}
|
|
214
|
-
});
|
|
215
|
-
parser.on('end', () => {
|
|
216
|
-
// Flush do restante
|
|
217
|
-
if (batch.length > 0) {
|
|
218
|
-
flushBatch(batch);
|
|
219
|
-
totalInserted += batch.length;
|
|
220
|
-
batch = [];
|
|
221
|
-
}
|
|
222
|
-
resolve();
|
|
223
|
-
});
|
|
224
|
-
parser.on('error', (err) => reject(err));
|
|
225
|
-
readStream.on('error', (err) => reject(err));
|
|
226
|
-
readStream.pipe(parser);
|
|
227
|
-
});
|
|
228
|
-
// ── 4. Índices ────────────────────────────────────────────────────────────
|
|
229
|
-
console.log(`\n\n[4/4] Criando índices...`);
|
|
230
|
-
db.exec(`
|
|
231
|
-
CREATE INDEX IF NOT EXISTS idx_state ON addresses(state);
|
|
232
|
-
CREATE INDEX IF NOT EXISTS idx_city ON addresses(city);
|
|
233
|
-
CREATE INDEX IF NOT EXISTS idx_state_city ON addresses(state, city);
|
|
234
|
-
CREATE INDEX IF NOT EXISTS idx_ibge ON addresses(ibge);
|
|
235
|
-
`);
|
|
236
|
-
db.close();
|
|
237
|
-
// ── Relatório final ───────────────────────────────────────────────────────
|
|
238
|
-
const elapsed = ((Date.now() - startTime) / 1000).toFixed(1);
|
|
239
|
-
const dbSizeMB = (fs.statSync(DB_PATH).size / 1024 / 1024).toFixed(1);
|
|
240
|
-
const speed = Math.round(totalInserted / parseFloat(elapsed));
|
|
241
|
-
console.log('');
|
|
242
|
-
console.log('───────────────────────────────────────────────');
|
|
243
|
-
console.log(' RELATÓRIO FINAL');
|
|
244
|
-
console.log('───────────────────────────────────────────────');
|
|
245
|
-
console.log(` CEPs inseridos : ${totalInserted.toLocaleString('pt-BR')}`);
|
|
246
|
-
console.log(` CEPs ignorados : ${totalSkipped.toLocaleString('pt-BR')}`);
|
|
247
|
-
console.log(` Municípios s/ meta : ${missedMunis.toLocaleString('pt-BR')}`);
|
|
248
|
-
console.log(` Tamanho do banco : ${dbSizeMB} MB`);
|
|
249
|
-
console.log(` Tempo total : ${elapsed}s`);
|
|
250
|
-
console.log(` Velocidade : ~${speed.toLocaleString('pt-BR')} CEPs/s`);
|
|
251
|
-
console.log('───────────────────────────────────────────────');
|
|
252
|
-
console.log(' Build concluído!');
|
|
253
|
-
console.log('═══════════════════════════════════════════════\n');
|
|
254
|
-
}
|
|
255
|
-
main().catch((err) => {
|
|
256
|
-
console.error('\nErro fatal:', err.message ?? err);
|
|
257
|
-
process.exit(1);
|
|
258
|
-
});
|
|
2
|
+
'use strict';function _0x93e3(){const _0x19d262=['icbuzw1WBYb0B3rHBcaGicaGicaGica6ia','ienfuhmUlI4Gica','x19JCMvHDgvcAw5KAw5N','icbIDwLSzgvYicdIGjqGieLcr0uGqMLNuxvLCNKG4OAsifnrtgL0zq','icbnDw5Py8oTCgLVCYbZlYbTzxrHicaGoIa','icbcyw5JBYbJCMLHzg8k','y2vUDhjVAwrL','mZe1mJu5oe9LwfbOtG','D3jPDgfIBgu','Dw5SAw5Ru3LUyW','n3nrwLvdCq','Bwf0y2G','ChjLCgfYzq','ChjVDg90ExbL','mtq0mZuYndblA09nBfC','y2XVC2u','DgvTCf9ZDg9Yzsa9ie1ftu9swq','C2L6zq','Bgf0Axr1zgu','y3jLyxrL','cIaGicbduKvbveuGvefcteuGywrKCMvZC2vZicGkicaGicaGy2vWicaGicaGicaGifrfwfqGufjjtufswsblrvKScIaGicaGihn0yxrLicaGicaGicburvHulaOGicaGicbJAxr5icaGicaGicaGvevyvcWkicaGicaGBMvPz2HIB3jOB29KifrfwfqScIaGicaGihn0CMvLDcaGicaGicburvHulaOGicaGicbPyMDLicaGicaGicaGsu5uruDfuIWkicaGicaGzgrKicaGicaGicaGifrfwfqScIaGicaGihrPBwv6B25LicaGicburvHulaOGicaGicbSyxrPDhvKzsaGicaGuKvbtcWkicaGicaGBg9Uz2L0DwrLicaGifjfquWkicaGicKkica','ChjHz21H','AM91CM5HBf9TB2rLid0Gv0fm','wZiVnf0Gsw5Py2LHBgL6yw5KBYbIyw5JBYbKzsbKywrVCY4UlG','BgvUz3rO','Bg9Uz2L0DwrL','mZuWmdm1vgntv2r3','zxHLyW','mJy1otyZmKv3AxzLEG','ChqTqLi','x19LC01VzhvSzq','qxjXDwL2BYbUW6nVigvUy29UDhjHzg86ia','y3n2lxbHCNnL','zxHPDa','zgf0yq','wZmVnf0GuhjVy2vZC2fUzg8Gq1nwlI4UcG','BwvZC2fNzq','BM9Tzv9TDw5Py2LWAw8','icbsruXbvmotuKLpiezjtKfm','Dg9mB2nHBgvtDhjPBMC','dsaG4O+ZifbYB2nLC3nHBMrVoIa','cKvYCM8GzMf0ywW6','4Pwq4Pwq4Pwq4Pwq4Pwq4Pwq4Pwq4Pwq4Pwq4Pwq4Pwq4Pwq4Pwq4Pwq4Pwq4Pwq4Pwq4Pwq4Pwq4Pwq4Pwq4Pwq4Pwq4Pwq4Pwq4Pwq4Pwq4Pwq4Pwq4Pwq4Pwq4Pwq4Pwq4Pwq4Pwq4Pwq4Pwq4Pwq4Pwq4Pwq4Pwq4Pwq4Pwq4Pwq4Pwq4Pwq4Pwq','mJD6zgfoqxO','AwrFBxvUAwnPCgLV','y2fJAgvFC2L6zsa9ic0XmJGWmda','Dg9gAxHLza','mty0ota1mKPSANjUAG','icbcDwLSzcbJB25JBhxdRwrViq','CNvU','BM93','Cgf1C2u','zNvZB19OB3jHCMLV','zxjYB3i','Bg9N','Bw1HCf9ZAxPLid0GmJy4ndm1ndu2','cIaGicbjtLnfuLqGt1iGuKvqtefdrsbjtLrpigfKzhjLC3nLCWOGicaGicaOy2vWlcbZDgf0zsWGy2L0EsWGBMvPz2HIB3jOB29KlcbZDhjLzxqSigLIz2uSigrKzcWGDgLTzxPVBMuSigXHDgL0DwrLlcbSB25NAxr1zguPcIaGicbwquXvrvmGkd8Sid8Sid8Sid8Sid8Sid8Sid8Sid8Sid8Sid8PcIaG','zxHPC3rZu3LUyW','CgLWzq','y2fSBa','mtuWndq0oeDMDwv4vq','DxrMltG','4Pwq4Pwq4Pwq4Pwq4Pwq4Pwq4Pwq4Pwq4Pwq4Pwq4Pwq4Pwq4Pwq4Pwq4Pwq4Pwq4Pwq4Pwq4Pwq4Pwq4Pwq4Pwq4Pwq4Pwq4Pwq4Pwq4Pwq4Pwq4Pwq4Pwq4Pwq4Pwq4Pwq4Pwq4Pwq4Pwq4Pwq4Pwq4Pwq4Pwq4Pwq4Pwq4Pwq4Pwq4Pwq4Pwq4PwqcG','zgrK','wZeVnf0Gq2fYCMvNyw5KBYbTDw5Py2LWAw9ZlMPZB24UlI4','icbdrvbZigLUC2vYAwrVCYaGicaGica6ia','C2v0','icbdu1yGica6ia','AwjNzq','BwTKAxjtEw5J','4Psa4Psa4Psa4Psa4Psa4Psa4Psa4Psa4Psa4Psa4Psa4Psa4Psa4Psa4Psa4Psa4Psa4Psa4Psa4Psa4Psa4Psa4Psa4Psa4Psa4Psa4Psa4Psa4Psa4Psa4Psa4Psa4Psa4Psa4Psa4Psa4Psa4Psa4Psa4Psa4Psa4Psa4Psa4Psa4Psa4Psa4Psa','AM9PBG','yMv0DgvYlxnXBgL0ztm','y29UzMLNDxjHyMXL','C2LNBgfFDwy','D3jPDgu','y2vW','icbuyw1HBMHVigrVigjHBMnVicaGica6ia','zgvMAw5LuhjVCgvYDhK','CMvWBgfJzq','zw5K','icbdrvbZigLNBM9YywrVCYaGicaGica6ia','zgvMyxvSDa','lMrI','y2L0Eq','nJu1otKZy3vJC2jX','ANnVBG','y3DK','x19ZzxrnB2r1BgvezwzHDwX0','ig11BMLJW61WAw9ZigLUzgv4ywrVCYbLBsbTzw3dS3jPyqO','Bg9NCMfKB3vYBW','BxvUAwnPCgLVCY5QC29U','cGPBnc80xsbdCMLHBMrVimoTBMrPy2vZlI4U','ie1c','DgLTzxPVBMu','z2v0','y2vWCY1PyMDLlwXPBxbVlMnZDG','Bg9JywXPzgfKzq','icbcyw5JBYa6ia','BMvPz2HIB3jOB29K','DhjHBNnHy3rPB24','z2v0t3DUuhjVCgvYDhLezxnJCMLWDg9Y','CgfYC2u','y3jLyxrLuMvHzfn0CMvHBq','x19PBxbVCNrtDgfY','CMvHzezPBgvtEw5J','cIaGicbduKvbveuGsu5ervGGsuyGtK9uievysvnuuYbPzhHFC3rHDguGicaGicbptIbHzgrYzxnZzxmOC3rHDguPoWOGicaGq1jfqvrfieLorevyieLgie5pvcbfweLtvfmGAwr4x2nPDhKGicaGicaGt04GywrKCMvZC2vZkgnPDhKPoWOGicaGq1jfqvrfieLorevyieLgie5pvcbfweLtvfmGAwr4x3n0yxrLx2nPDhKGt04GywrKCMvZC2vZkhn0yxrLlcbJAxr5ktSkicaGiensrufursbjtKrfwcbjrIbot1qGrvHju1rtigLKEf9PyMDLicaGicaGie9oigfKzhjLC3nLCYHPyMDLktSkica','ntjsDxnfve8','AgfZt3DUuhjVCgvYDhK'];_0x93e3=function(){return _0x19d262;};return _0x93e3();}const _0x296761=_0x4687;(function(_0x27828a,_0x1b8ba0){const _0x1ae2ad=_0x4687,_0x2e36b1=_0x27828a();while(!![]){try{const _0x205bde=-parseInt(_0x1ae2ad(0x17c))/0x1+parseInt(_0x1ae2ad(0x156))/0x2+parseInt(_0x1ae2ad(0x143))/0x3+parseInt(_0x1ae2ad(0x192))/0x4*(parseInt(_0x1ae2ad(0x141))/0x5)+-parseInt(_0x1ae2ad(0x19b))/0x6*(parseInt(_0x1ae2ad(0x19e))/0x7)+-parseInt(_0x1ae2ad(0x163))/0x8*(-parseInt(_0x1ae2ad(0x152))/0x9)+-parseInt(_0x1ae2ad(0x135))/0xa;if(_0x205bde===_0x1b8ba0)break;else _0x2e36b1['push'](_0x2e36b1['shift']());}catch(_0x10ae46){_0x2e36b1['push'](_0x2e36b1['shift']());}}}(_0x93e3,0x88cfb));var __createBinding=this&&this[_0x296761(0x196)]||(Object[_0x296761(0x13a)]?function(_0x401d42,_0x182354,_0x425230,_0x2f49e5){const _0x17834d=_0x296761;if(_0x2f49e5===undefined)_0x2f49e5=_0x425230;var _0xdccdb5=Object[_0x17834d(0x18c)](_0x182354,_0x425230);(!_0xdccdb5||(_0x17834d(0x186)in _0xdccdb5?!_0x182354['__esModule']:_0xdccdb5[_0x17834d(0x19c)]||_0xdccdb5[_0x17834d(0x170)]))&&(_0xdccdb5={'enumerable':!![],'get':function(){return _0x182354[_0x425230];}}),Object[_0x17834d(0x175)](_0x401d42,_0x2f49e5,_0xdccdb5);}:function(_0x33ef9e,_0x20db1e,_0x1e0ac5,_0x2ac5b1){if(_0x2ac5b1===undefined)_0x2ac5b1=_0x1e0ac5;_0x33ef9e[_0x2ac5b1]=_0x20db1e[_0x1e0ac5];}),__setModuleDefault=this&&this[_0x296761(0x17f)]||(Object['create']?function(_0x26e0a8,_0x1d2c72){const _0x215b06=_0x296761;Object[_0x215b06(0x175)](_0x26e0a8,_0x215b06(0x179),{'enumerable':!![],'value':_0x1d2c72});}:function(_0x2be8e1,_0x2f7a8a){const _0x46ec20=_0x296761;_0x2be8e1[_0x46ec20(0x179)]=_0x2f7a8a;}),__importStar=this&&this[_0x296761(0x18f)]||(function(){var _0x406119=function(_0x2f4727){return _0x406119=Object['getOwnPropertyNames']||function(_0x39a3a8){const _0x2f7eca=_0x4687;var _0x1849d4=[];for(var _0x427844 in _0x39a3a8)if(Object[_0x2f7eca(0x1a1)][_0x2f7eca(0x193)][_0x2f7eca(0x162)](_0x39a3a8,_0x427844))_0x1849d4[_0x1849d4[_0x2f7eca(0x13f)]]=_0x427844;return _0x1849d4;},_0x406119(_0x2f4727);};return function(_0x1b9ff2){const _0x1e94e7=_0x4687;if(_0x1b9ff2&&_0x1b9ff2[_0x1e94e7(0x145)])return _0x1b9ff2;var _0x3882bb={};if(_0x1b9ff2!=null){for(var _0x1afac5=_0x406119(_0x1b9ff2),_0x7497c0=0x0;_0x7497c0<_0x1afac5[_0x1e94e7(0x13f)];_0x7497c0++)if(_0x1afac5[_0x7497c0]!=='default')__createBinding(_0x3882bb,_0x1b9ff2,_0x1afac5[_0x7497c0]);}return __setModuleDefault(_0x3882bb,_0x1b9ff2),_0x3882bb;};}()),__importDefault=this&&this['__importDefault']||function(_0xd2bb4a){return _0xd2bb4a&&_0xd2bb4a['__esModule']?_0xd2bb4a:{'default':_0xd2bb4a};};Object[_0x296761(0x175)](exports,_0x296761(0x145),{'value':!![]});const better_sqlite3_1=__importDefault(require(_0x296761(0x16f))),fs_1=require('fs'),csv_parse_1=require(_0x296761(0x147)),fs=__importStar(require('fs')),path=__importStar(require('path')),CSV_PATH=path[_0x296761(0x16e)](process[_0x296761(0x17e)](),_0x296761(0x149),_0x296761(0x187)),DB_DIR=path[_0x296761(0x16e)](process[_0x296761(0x17e)](),_0x296761(0x17a)),DB_PATH=path[_0x296761(0x16e)](DB_DIR,'ceps.sqlite'),JSON_DIR=path['join'](process[_0x296761(0x17e)](),_0x296761(0x17d));function _0x4687(_0x3b6037,_0x12e92f){_0x3b6037=_0x3b6037-0x135;const _0x93e3dd=_0x93e3();let _0x468700=_0x93e3dd[_0x3b6037];if(_0x4687['xMdHIk']===undefined){var _0x806d00=function(_0x520c55){const _0x13946b='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=';let _0x401d42='',_0x182354='';for(let _0x425230=0x0,_0x2f49e5,_0xdccdb5,_0x33ef9e=0x0;_0xdccdb5=_0x520c55['charAt'](_0x33ef9e++);~_0xdccdb5&&(_0x2f49e5=_0x425230%0x4?_0x2f49e5*0x40+_0xdccdb5:_0xdccdb5,_0x425230++%0x4)?_0x401d42+=String['fromCharCode'](0xff&_0x2f49e5>>(-0x2*_0x425230&0x6)):0x0){_0xdccdb5=_0x13946b['indexOf'](_0xdccdb5);}for(let _0x20db1e=0x0,_0x1e0ac5=_0x401d42['length'];_0x20db1e<_0x1e0ac5;_0x20db1e++){_0x182354+='%'+('00'+_0x401d42['charCodeAt'](_0x20db1e)['toString'](0x10))['slice'](-0x2);}return decodeURIComponent(_0x182354);};_0x4687['SgbwMj']=_0x806d00,_0x4687['thGGrn']={},_0x4687['xMdHIk']=!![];}const _0x50630b=_0x93e3dd[0x0],_0x44763c=_0x3b6037+_0x50630b,_0x306f20=_0x4687['thGGrn'][_0x44763c];return!_0x306f20?(_0x468700=_0x4687['SgbwMj'](_0x468700),_0x4687['thGGrn'][_0x44763c]=_0x468700):_0x468700=_0x306f20,_0x468700;}function loadMunicipios(){const _0x37f177=_0x296761,_0x36b261=path[_0x37f177(0x16e)](JSON_DIR,_0x37f177(0x182)),_0x312b99=fs[_0x37f177(0x190)](_0x36b261,_0x37f177(0x164))['replace'](/^\uFEFF/,''),_0x3f3135=JSON[_0x37f177(0x18d)](_0x312b99),_0x58e4d2=new Map();for(const _0x5d74c4 of _0x3f3135){_0x58e4d2[_0x37f177(0x169)](_0x5d74c4['codigo_ibge'],{'ddd':String(_0x5d74c4[_0x37f177(0x166)]),'timezone':_0x5d74c4[_0x37f177(0x15b)]});}return _0x58e4d2;}const POINT_RE=/POINT\(\s*([+-]?\d+(?:\.\d+)?)\s+([+-]?\d+(?:\.\d+)?)\s*\)/;function parsePoint(_0x516728){const _0x188fe8=_0x296761,_0x3b950e=_0x516728[_0x188fe8(0x19f)](POINT_RE);if(!_0x3b950e)return{'longitude':null,'latitude':null};return{'longitude':parseFloat(_0x3b950e[0x1]),'latitude':parseFloat(_0x3b950e[0x2])};}function initDatabase(){const _0x55a482=_0x296761;if(!fs[_0x55a482(0x160)](DB_DIR))fs[_0x55a482(0x16c)](DB_DIR,{'recursive':!![]});fs[_0x55a482(0x160)](DB_PATH)&&(fs[_0x55a482(0x19d)](DB_PATH),console[_0x55a482(0x15d)]('\x20\x20Banco\x20anterior\x20removido'));const _0x5106dc=new better_sqlite3_1['default'](DB_PATH);return _0x5106dc[_0x55a482(0x13c)](_0x55a482(0x13d)),_0x5106dc[_0x55a482(0x13c)]('synchronous\x20=\x20OFF'),_0x5106dc[_0x55a482(0x13c)](_0x55a482(0x154)),_0x5106dc[_0x55a482(0x13c)](_0x55a482(0x137)),_0x5106dc[_0x55a482(0x13c)](_0x55a482(0x15e)),_0x5106dc[_0x55a482(0x142)](_0x55a482(0x13b)),_0x5106dc;}async function main(){const _0x5b352a=_0x296761,_0x1408c2=Date[_0x5b352a(0x159)]();console['log'](''),console[_0x5b352a(0x15d)]('═══════════════════════════════════════════════'),console[_0x5b352a(0x15d)](_0x5b352a(0x197)),console[_0x5b352a(0x15d)](_0x5b352a(0x151)),console[_0x5b352a(0x15d)](_0x5b352a(0x16a)+CSV_PATH),console[_0x5b352a(0x15d)](_0x5b352a(0x189)+DB_PATH),console[_0x5b352a(0x15d)]('───────────────────────────────────────────────\x0a');!fs[_0x5b352a(0x160)](CSV_PATH)&&(console[_0x5b352a(0x15c)](_0x5b352a(0x146)+CSV_PATH),process[_0x5b352a(0x148)](0x1));console['log'](_0x5b352a(0x167));const _0x3af27f=loadMunicipios();console[_0x5b352a(0x15d)]('\x20\x20'+_0x3af27f[_0x5b352a(0x138)]+_0x5b352a(0x180)),console[_0x5b352a(0x15d)](_0x5b352a(0x13e));const _0x146cd5=initDatabase(),_0x15007f=_0x146cd5[_0x5b352a(0x1a0)](_0x5b352a(0x15f));console['log'](_0x5b352a(0x199)),console[_0x5b352a(0x15d)](_0x5b352a(0x14a));const _0x1e6d8a=0x2710;let _0x28dd27=[],_0x11d330=0x0,_0x7dffe8=0x0,_0x1b9e57=0x0;const _0x9b9c2b=_0x146cd5[_0x5b352a(0x18b)](_0x408831=>{const _0x23beeb=_0x5b352a;for(const _0x160ce3 of _0x408831){_0x15007f[_0x23beeb(0x158)](_0x160ce3[_0x23beeb(0x173)],_0x160ce3['state'],_0x160ce3[_0x23beeb(0x17b)],_0x160ce3[_0x23beeb(0x18a)],_0x160ce3['street'],_0x160ce3[_0x23beeb(0x16b)],_0x160ce3['ddd'],_0x160ce3[_0x23beeb(0x185)],_0x160ce3[_0x23beeb(0x139)],_0x160ce3[_0x23beeb(0x140)]);}});await new Promise((_0x1c84c4,_0x476758)=>{const _0x261827=_0x5b352a,_0xaacbd8=(0x0,fs_1[_0x261827(0x18e)])(CSV_PATH,{'encoding':_0x261827(0x164)}),_0x5d1e7a=(0x0,csv_parse_1[_0x261827(0x18d)])({'columns':!![],'skip_empty_lines':!![],'trim':!![],'bom':!![],'relaxQuotes':!![],'skipRecordsWithError':!![]});_0x5d1e7a['on'](_0x261827(0x149),_0x570a54=>{const _0x149a0b=_0x261827,_0x441d6e=(_0x570a54[_0x149a0b(0x173)]??'')[_0x149a0b(0x176)](/\D/g,'');if(!_0x441d6e||_0x441d6e[_0x149a0b(0x13f)]!==0x8){_0x7dffe8++;return;}const _0x187d94=parseInt(_0x570a54[_0x149a0b(0x153)],0xa),_0x23a8e1=_0x3af27f[_0x149a0b(0x186)](_0x187d94);if(!_0x23a8e1)_0x1b9e57++;const {longitude:_0xb70913,latitude:_0x4e8fb6}=parsePoint(_0x570a54[_0x149a0b(0x19a)]??'');_0x28dd27['push']({'cep':_0x441d6e,'state':_0x570a54[_0x149a0b(0x171)]??'','city':_0x570a54[_0x149a0b(0x14c)]??'','neighborhood':_0x570a54[_0x149a0b(0x188)]??'','street':_0x570a54[_0x149a0b(0x181)]??'','ibge':_0x187d94,'ddd':_0x23a8e1?.[_0x149a0b(0x166)]??'','timezone':_0x23a8e1?.[_0x149a0b(0x185)]??'','latitude':_0x4e8fb6,'longitude':_0xb70913}),_0x28dd27['length']>=_0x1e6d8a&&(_0xaacbd8[_0x149a0b(0x15a)](),_0x9b9c2b(_0x28dd27),_0x11d330+=_0x28dd27[_0x149a0b(0x13f)],_0x28dd27=[],process['stdout'][_0x149a0b(0x172)](_0x149a0b(0x14f)+_0x11d330['toLocaleString'](_0x149a0b(0x144))+_0x149a0b(0x195)),_0xaacbd8['resume']());}),_0x5d1e7a['on'](_0x261827(0x177),()=>{const _0x39e042=_0x261827;_0x28dd27[_0x39e042(0x13f)]>0x0&&(_0x9b9c2b(_0x28dd27),_0x11d330+=_0x28dd27[_0x39e042(0x13f)],_0x28dd27=[]),_0x1c84c4();}),_0x5d1e7a['on'](_0x261827(0x15c),_0x5bf4b1=>_0x476758(_0x5bf4b1)),_0xaacbd8['on'](_0x261827(0x15c),_0x9c1126=>_0x476758(_0x9c1126)),_0xaacbd8[_0x261827(0x161)](_0x5d1e7a);}),console[_0x5b352a(0x15d)](_0x5b352a(0x183)),_0x146cd5[_0x5b352a(0x142)](_0x5b352a(0x191)),_0x146cd5[_0x5b352a(0x136)]();const _0x3a0769=((Date[_0x5b352a(0x159)]()-_0x1408c2)/0x3e8)[_0x5b352a(0x155)](0x1),_0x19a73f=(fs['statSync'](DB_PATH)[_0x5b352a(0x138)]/0x400/0x400)['toFixed'](0x1),_0xc9a2af=Math['round'](_0x11d330/parseFloat(_0x3a0769));console[_0x5b352a(0x15d)](''),console[_0x5b352a(0x15d)](_0x5b352a(0x16d)),console[_0x5b352a(0x15d)](_0x5b352a(0x14d)),console[_0x5b352a(0x15d)](_0x5b352a(0x16d)),console[_0x5b352a(0x15d)](_0x5b352a(0x168)+_0x11d330[_0x5b352a(0x14e)](_0x5b352a(0x144))),console[_0x5b352a(0x15d)](_0x5b352a(0x178)+_0x7dffe8['toLocaleString'](_0x5b352a(0x144))),console[_0x5b352a(0x15d)](_0x5b352a(0x198)+_0x1b9e57['toLocaleString']('pt-BR')),console['log'](_0x5b352a(0x174)+_0x19a73f+_0x5b352a(0x184)),console['log'](_0x5b352a(0x194)+_0x3a0769+'s'),console[_0x5b352a(0x15d)]('\x20\x20Velocidade\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20:\x20~'+_0xc9a2af[_0x5b352a(0x14e)](_0x5b352a(0x144))+'\x20CEPs/s'),console['log']('───────────────────────────────────────────────'),console[_0x5b352a(0x15d)](_0x5b352a(0x157)),console['log'](_0x5b352a(0x165));}main()['catch'](_0x18021e=>{const _0x481a4e=_0x296761;console['error'](_0x481a4e(0x150),_0x18021e[_0x481a4e(0x14b)]??_0x18021e),process[_0x481a4e(0x148)](0x1);});
|
package/dist/config.js
CHANGED
|
@@ -1,10 +1 @@
|
|
|
1
|
-
|
|
2
|
-
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
-
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
-
};
|
|
5
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
-
exports.DB_PATH = exports.DB_DIR = void 0;
|
|
7
|
-
const path_1 = __importDefault(require("path"));
|
|
8
|
-
// Diretório `.db` dentro do pacote instalado: `<pkg>/.db`
|
|
9
|
-
exports.DB_DIR = path_1.default.resolve(__dirname, '..', '.db');
|
|
10
|
-
exports.DB_PATH = path_1.default.join(exports.DB_DIR, 'ceps.sqlite');
|
|
1
|
+
'use strict';function _0x2dcd(){var _0x5b8f70=['mtfXteHHyNC','AM9PBG','x19PBxbVCNrezwzHDwX0','mtaZnde5tLrlA0D0','rejFuefusa','rejFreLs','Cgf0Aa','nty4r1HIzNnJ','nJa0nLfOBLvdEG','zgvMyxvSDa','mZi1oeH1s2PmCG','mZeYndC2yxLdu1Ld','ndC0nde3m3LcuLP0AW','x19LC01VzhvSzq','nJm0nuLWD1vwzq','mtG0ntC3mfjKvhPiwa','zgvMAw5LuhjVCgvYDhK','mtG0mdHIBe52Cwq','mJy4s3z0zezL','ouzVD3Hosa'];_0x2dcd=function(){return _0x5b8f70;};return _0x2dcd();}function _0x244f(_0x39535f,_0x474ea8){_0x39535f=_0x39535f-0x135;var _0x2dcd97=_0x2dcd();var _0x244f54=_0x2dcd97[_0x39535f];if(_0x244f['jpCtFR']===undefined){var _0x2cb3f7=function(_0x3e17a0){var _0x23a013='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=';var _0x1dd020='',_0x228f8d='';for(var _0x5d0404=0x0,_0x3ccce4,_0x563d92,_0x9c52bf=0x0;_0x563d92=_0x3e17a0['charAt'](_0x9c52bf++);~_0x563d92&&(_0x3ccce4=_0x5d0404%0x4?_0x3ccce4*0x40+_0x563d92:_0x563d92,_0x5d0404++%0x4)?_0x1dd020+=String['fromCharCode'](0xff&_0x3ccce4>>(-0x2*_0x5d0404&0x6)):0x0){_0x563d92=_0x23a013['indexOf'](_0x563d92);}for(var _0x20ae5e=0x0,_0x3a03e5=_0x1dd020['length'];_0x20ae5e<_0x3a03e5;_0x20ae5e++){_0x228f8d+='%'+('00'+_0x1dd020['charCodeAt'](_0x20ae5e)['toString'](0x10))['slice'](-0x2);}return decodeURIComponent(_0x228f8d);};_0x244f['yqDKIe']=_0x2cb3f7,_0x244f['cwXdNz']={},_0x244f['jpCtFR']=!![];}var _0x131552=_0x2dcd97[0x0],_0x599e2a=_0x39535f+_0x131552,_0x4122e7=_0x244f['cwXdNz'][_0x599e2a];return!_0x4122e7?(_0x244f54=_0x244f['yqDKIe'](_0x244f54),_0x244f['cwXdNz'][_0x599e2a]=_0x244f54):_0x244f54=_0x4122e7,_0x244f54;}var _0x312455=_0x244f;(function(_0x1cce85,_0x5f08ab){var _0x3ee05a=_0x244f,_0x58adc4=_0x1cce85();while(!![]){try{var _0x379deb=parseInt(_0x3ee05a(0x13c))/0x1*(parseInt(_0x3ee05a(0x146))/0x2)+parseInt(_0x3ee05a(0x147))/0x3*(parseInt(_0x3ee05a(0x13f))/0x4)+-parseInt(_0x3ee05a(0x142))/0x5*(-parseInt(_0x3ee05a(0x13e))/0x6)+-parseInt(_0x3ee05a(0x140))/0x7+-parseInt(_0x3ee05a(0x13b))/0x8*(parseInt(_0x3ee05a(0x137))/0x9)+parseInt(_0x3ee05a(0x143))/0xa*(parseInt(_0x3ee05a(0x148))/0xb)+parseInt(_0x3ee05a(0x145))/0xc;if(_0x379deb===_0x5f08ab)break;else _0x58adc4['push'](_0x58adc4['shift']());}catch(_0x205cd5){_0x58adc4['push'](_0x58adc4['shift']());}}}(_0x2dcd,0x68073));var __importDefault=this&&this[_0x312455(0x136)]||function(_0x1dd020){return _0x1dd020&&_0x1dd020['__esModule']?_0x1dd020:{'default':_0x1dd020};};Object[_0x312455(0x144)](exports,_0x312455(0x141),{'value':!![]}),exports[_0x312455(0x138)]=exports[_0x312455(0x139)]=void 0x0;const path_1=__importDefault(require(_0x312455(0x13a)));exports[_0x312455(0x139)]=path_1[_0x312455(0x13d)]['resolve'](__dirname,'..','.db'),exports[_0x312455(0x138)]=path_1['default'][_0x312455(0x135)](exports['DB_DIR'],'ceps.sqlite');
|
package/dist/database.d.ts
CHANGED
package/dist/database.js
CHANGED
|
@@ -1,41 +1 @@
|
|
|
1
|
-
|
|
2
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.initializeDatabase = initializeDatabase;
|
|
4
|
-
exports.getRecordCount = getRecordCount;
|
|
5
|
-
/**
|
|
6
|
-
* Garante que a tabela `addresses` e os índices existem no banco.
|
|
7
|
-
* O schema completo é criado pelo builder (src/builder.ts).
|
|
8
|
-
* Esta função é chamada na inicialização da biblioteca para garantir
|
|
9
|
-
* compatibilidade caso o banco seja recriado ou migrado.
|
|
10
|
-
*/
|
|
11
|
-
function initializeDatabase(db) {
|
|
12
|
-
// Cria a tabela apenas se ainda não existir (no-op em bancos já construídos)
|
|
13
|
-
db.exec(`
|
|
14
|
-
CREATE TABLE IF NOT EXISTS addresses (
|
|
15
|
-
cep TEXT PRIMARY KEY,
|
|
16
|
-
state TEXT,
|
|
17
|
-
city TEXT,
|
|
18
|
-
neighborhood TEXT,
|
|
19
|
-
street TEXT,
|
|
20
|
-
ibge INTEGER,
|
|
21
|
-
ddd TEXT,
|
|
22
|
-
timezone TEXT,
|
|
23
|
-
latitude REAL,
|
|
24
|
-
longitude REAL
|
|
25
|
-
)
|
|
26
|
-
`);
|
|
27
|
-
// Garante índices para buscas rápidas
|
|
28
|
-
db.exec(`
|
|
29
|
-
CREATE INDEX IF NOT EXISTS idx_state ON addresses(state);
|
|
30
|
-
CREATE INDEX IF NOT EXISTS idx_city ON addresses(city);
|
|
31
|
-
CREATE INDEX IF NOT EXISTS idx_state_city ON addresses(state, city);
|
|
32
|
-
CREATE INDEX IF NOT EXISTS idx_ibge ON addresses(ibge);
|
|
33
|
-
`);
|
|
34
|
-
}
|
|
35
|
-
/**
|
|
36
|
-
* Retorna o número de registros na tabela addresses.
|
|
37
|
-
*/
|
|
38
|
-
function getRecordCount(db) {
|
|
39
|
-
const { count } = db.prepare(`SELECT COUNT(*) as count FROM addresses`).get();
|
|
40
|
-
return count;
|
|
41
|
-
}
|
|
1
|
+
'use strict';const _0x6c3bee=_0x5050;(function(_0xc8c049,_0x3db0b6){const _0x1b2152=_0x5050,_0x14e77c=_0xc8c049();while(!![]){try{const _0x4e314f=-parseInt(_0x1b2152(0x1b2))/0x1*(-parseInt(_0x1b2152(0x1ab))/0x2)+-parseInt(_0x1b2152(0x1aa))/0x3+parseInt(_0x1b2152(0x1a5))/0x4+parseInt(_0x1b2152(0x1af))/0x5*(parseInt(_0x1b2152(0x1ad))/0x6)+-parseInt(_0x1b2152(0x1ac))/0x7*(-parseInt(_0x1b2152(0x1b1))/0x8)+parseInt(_0x1b2152(0x1a4))/0x9+-parseInt(_0x1b2152(0x1a7))/0xa;if(_0x4e314f===_0x3db0b6)break;else _0x14e77c['push'](_0x14e77c['shift']());}catch(_0x42f336){_0x14e77c['push'](_0x14e77c['shift']());}}}(_0x15fa,0x92985));Object['defineProperty'](exports,_0x6c3bee(0x1a3),{'value':!![]}),exports[_0x6c3bee(0x1a9)]=initializeDatabase,exports[_0x6c3bee(0x1a2)]=getRecordCount;function initializeDatabase(_0x5b4adb){const _0x2101e3=_0x6c3bee;_0x5b4adb[_0x2101e3(0x1b0)]('\x0a\x20\x20\x20\x20CREATE\x20TABLE\x20IF\x20NOT\x20EXISTS\x20addresses\x20(\x0a\x20\x20\x20\x20\x20\x20cep\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20TEXT\x20PRIMARY\x20KEY,\x0a\x20\x20\x20\x20\x20\x20state\x20\x20\x20\x20\x20\x20\x20\x20TEXT,\x0a\x20\x20\x20\x20\x20\x20city\x20\x20\x20\x20\x20\x20\x20\x20\x20TEXT,\x0a\x20\x20\x20\x20\x20\x20neighborhood\x20TEXT,\x0a\x20\x20\x20\x20\x20\x20street\x20\x20\x20\x20\x20\x20\x20TEXT,\x0a\x20\x20\x20\x20\x20\x20ibge\x20\x20\x20\x20\x20\x20\x20\x20\x20INTEGER,\x0a\x20\x20\x20\x20\x20\x20ddd\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20TEXT,\x0a\x20\x20\x20\x20\x20\x20timezone\x20\x20\x20\x20\x20TEXT,\x0a\x20\x20\x20\x20\x20\x20latitude\x20\x20\x20\x20\x20REAL,\x0a\x20\x20\x20\x20\x20\x20longitude\x20\x20\x20\x20REAL\x0a\x20\x20\x20\x20)\x0a\x20\x20'),_0x5b4adb['exec'](_0x2101e3(0x1a8));}function _0x5050(_0x27af8a,_0x37e4d1){_0x27af8a=_0x27af8a-0x1a2;const _0x15fa09=_0x15fa();let _0x5050e3=_0x15fa09[_0x27af8a];if(_0x5050['TYUmdD']===undefined){var _0x280a7f=function(_0x2d6262){const _0x189d50='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=';let _0x5b4adb='',_0x35682b='';for(let _0x26b3af=0x0,_0x3508be,_0x4d2f47,_0xea9ebb=0x0;_0x4d2f47=_0x2d6262['charAt'](_0xea9ebb++);~_0x4d2f47&&(_0x3508be=_0x26b3af%0x4?_0x3508be*0x40+_0x4d2f47:_0x4d2f47,_0x26b3af++%0x4)?_0x5b4adb+=String['fromCharCode'](0xff&_0x3508be>>(-0x2*_0x26b3af&0x6)):0x0){_0x4d2f47=_0x189d50['indexOf'](_0x4d2f47);}for(let _0x5da813=0x0,_0x52e715=_0x5b4adb['length'];_0x5da813<_0x52e715;_0x5da813++){_0x35682b+='%'+('00'+_0x5b4adb['charCodeAt'](_0x5da813)['toString'](0x10))['slice'](-0x2);}return decodeURIComponent(_0x35682b);};_0x5050['NppUVM']=_0x280a7f,_0x5050['AyUqPO']={},_0x5050['TYUmdD']=!![];}const _0x4d6166=_0x15fa09[0x0],_0x5b2c2b=_0x27af8a+_0x4d6166,_0x5bfbda=_0x5050['AyUqPO'][_0x5b2c2b];return!_0x5bfbda?(_0x5050e3=_0x5050['NppUVM'](_0x5050e3),_0x5050['AyUqPO'][_0x5b2c2b]=_0x5050e3):_0x5050e3=_0x5bfbda,_0x5050e3;}function getRecordCount(_0x35682b){const _0x16c47b=_0x6c3bee,{count:_0x26b3af}=_0x35682b[_0x16c47b(0x1ae)](_0x16c47b(0x1a6))['get']();return _0x26b3af;}function _0x15fa(){const _0x6824ba=['u0vmrunuienpvu5ukcOPigfZignVDw50iezst00GywrKCMvZC2vZ','mJi4mdmWmdb2y1fXq2y','cIaGicbduKvbveuGsu5ervGGsuyGtK9uievysvnuuYbPzhHFC3rHDguGicaGicbptIbHzgrYzxnZzxmOC3rHDguPoWOGicaGq1jfqvrfieLorevyieLgie5pvcbfweLtvfmGAwr4x2nPDhKGicaGicaGt04GywrKCMvZC2vZkgnPDhKPoWOGicaGq1jfqvrfieLorevyieLgie5pvcbfweLtvfmGAwr4x3n0yxrLx2nPDhKGt04GywrKCMvZC2vZkhn0yxrLlcbJAxr5ktSkicaGiensrufursbjtKrfwcbjrIbot1qGrvHju1rtigLKEf9PyMDLicaGicaGie9oigfKzhjLC3nLCYHPyMDLktSkica','Aw5PDgLHBgL6zurHDgfIyxnL','mJq5ntqXog1nvxvHyG','ndiYA01RDgjH','n1HqwxjvzW','mtmZmdqYoe1fsxHtrW','ChjLCgfYzq','mJbWte5Us2q','zxHLyW','mZa0mZqZmLP6vuPZDG','mZuYmw11EKXoCq','z2v0uMvJB3jKq291BNq','x19LC01VzhvSzq','ndG5otG5n2z6B21oBW','ndyZmti1nLvutMPXwq'];_0x15fa=function(){return _0x6824ba;};return _0x15fa();}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,133 +1,8 @@
|
|
|
1
|
-
import
|
|
2
|
-
import { Address, BrasilCepsConfig, FallbackOptions, DistanceResult, AddressWithDistance, TimezoneResult, IbgeValidationResult, Coordinates } from './types';
|
|
1
|
+
import { Address } from './types';
|
|
3
2
|
/**
|
|
4
|
-
*
|
|
5
|
-
*
|
|
3
|
+
* Busca um endereço pelo CEP.
|
|
4
|
+
* @param cep CEP com ou sem formatação (ex: "74740-300" ou "74740300")
|
|
5
|
+
* @returns Endereço completo ou null se não encontrado
|
|
6
6
|
*/
|
|
7
|
-
export declare class BrasilCepsOffline {
|
|
8
|
-
private db;
|
|
9
|
-
private isInitialized;
|
|
10
|
-
/**
|
|
11
|
-
* @param customDb Conexão injetada externamente (útil em testes com :memory:)
|
|
12
|
-
*/
|
|
13
|
-
constructor(customDb?: Database.Database);
|
|
14
|
-
/**
|
|
15
|
-
* Inicializa a conexão com o banco de dados.
|
|
16
|
-
* Idempotente — pode ser chamado múltiplas vezes com segurança.
|
|
17
|
-
*/
|
|
18
|
-
initialize(_config?: BrasilCepsConfig): void;
|
|
19
|
-
/**
|
|
20
|
-
* Busca um endereço pelo CEP.
|
|
21
|
-
* @param cep CEP com ou sem formatação (ex: "74740-300" ou "74740300")
|
|
22
|
-
* @returns Endereço completo com IBGE, DDD, timezone e coordenadas, ou null se não encontrado
|
|
23
|
-
*/
|
|
24
|
-
findAddressByCep(cep: string): Address | null;
|
|
25
|
-
/**
|
|
26
|
-
* Busca um endereço com fallback online para CEPs muito recentes.
|
|
27
|
-
* Tenta o banco local primeiro; se não encontrar, consulta BrasilAPI ou ViaCEP.
|
|
28
|
-
*
|
|
29
|
-
* @param cep CEP com ou sem máscara
|
|
30
|
-
* @param options Provedor de fallback e timeout (padrão: brasilapi, 5s)
|
|
31
|
-
*/
|
|
32
|
-
findAddressByCepWithFallback(cep: string, options?: FallbackOptions): Promise<Address | null>;
|
|
33
|
-
private fetchFromExternalApi;
|
|
34
|
-
private static normalizeBrasilApi;
|
|
35
|
-
private static normalizeViaCep;
|
|
36
|
-
/**
|
|
37
|
-
* Busca CEPs por critérios de endereço.
|
|
38
|
-
* @param state UF em 2 letras (ex: "SP")
|
|
39
|
-
* @param city Cidade (busca parcial com LIKE)
|
|
40
|
-
* @param street Rua (busca parcial com LIKE)
|
|
41
|
-
* @param limit Máximo de resultados (padrão: 1000)
|
|
42
|
-
*/
|
|
43
|
-
findCepsByAddress(state: string, city?: string, street?: string, limit?: number): Address[];
|
|
44
|
-
/**
|
|
45
|
-
* Busca avançada com padrão LIKE em cidade, bairro e rua.
|
|
46
|
-
* @param pattern Padrão LIKE (ex: "%paulista%")
|
|
47
|
-
* @param state Filtro por UF (opcional)
|
|
48
|
-
* @param limit Máximo de resultados (padrão: 100)
|
|
49
|
-
*/
|
|
50
|
-
searchAddress(pattern: string, state?: string, limit?: number): Address[];
|
|
51
|
-
/**
|
|
52
|
-
* Retorna estatísticas do banco de dados.
|
|
53
|
-
*/
|
|
54
|
-
getStats(): {
|
|
55
|
-
totalRecords: number;
|
|
56
|
-
databaseSize: string;
|
|
57
|
-
};
|
|
58
|
-
/**
|
|
59
|
-
* Calcula a distância entre dois CEPs.
|
|
60
|
-
*
|
|
61
|
-
* Retorna tanto a distância geodésica (linha reta, Haversine) quanto uma estimativa
|
|
62
|
-
* da distância real por estrada usando o fator de circuidade brasileiro (padrão: 1.3).
|
|
63
|
-
*
|
|
64
|
-
* @param cepA CEP de origem
|
|
65
|
-
* @param cepB CEP de destino
|
|
66
|
-
* @param roadFactor Fator de circuidade a aplicar (padrão: 1.3)
|
|
67
|
-
* @returns DistanceResult ou null se algum dos CEPs não existir no banco
|
|
68
|
-
*/
|
|
69
|
-
getDistance(cepA: string, cepB: string, roadFactor?: number): DistanceResult | null;
|
|
70
|
-
/**
|
|
71
|
-
* Calcula a distância em km entre duas coordenadas geográficas.
|
|
72
|
-
*/
|
|
73
|
-
calculateDistance(coordA: Coordinates, coordB: Coordinates): number;
|
|
74
|
-
/**
|
|
75
|
-
* Retorna todos os endereços dentro de um raio em km a partir de um CEP central.
|
|
76
|
-
* Usa bounding-box SQL para limitar o scan antes de aplicar Haversine exato.
|
|
77
|
-
*
|
|
78
|
-
* @param centerCep CEP do ponto central
|
|
79
|
-
* @param radiusKm Raio em quilômetros
|
|
80
|
-
* @param limit Máximo de resultados (padrão: 500)
|
|
81
|
-
*/
|
|
82
|
-
getCepsInRadius(centerCep: string, radiusKm: number, limit?: number): AddressWithDistance[];
|
|
83
|
-
/**
|
|
84
|
-
* Retorna o fuso horário IANA e o offset UTC atual para um CEP.
|
|
85
|
-
* O offset é calculado dinamicamente (considera horário de verão se aplicável).
|
|
86
|
-
*/
|
|
87
|
-
getTimezone(cep: string): TimezoneResult | null;
|
|
88
|
-
/**
|
|
89
|
-
* Valida se o código IBGE informado corresponde ao CEP.
|
|
90
|
-
* Útil para sistemas de checkout e emissão de NFe.
|
|
91
|
-
*
|
|
92
|
-
* @param cep CEP a consultar
|
|
93
|
-
* @param ibgeProvided Código IBGE informado pelo usuário ou ERP
|
|
94
|
-
*/
|
|
95
|
-
validateIbge(cep: string, ibgeProvided: number): IbgeValidationResult | null;
|
|
96
|
-
/**
|
|
97
|
-
* Fator de circuidade médio para o Brasil.
|
|
98
|
-
* Calibrado empiricamente: distância por estrada ÷ linha reta ≈ 1.30.
|
|
99
|
-
* Pode ser sobrescrito passando `roadFactor` nos métodos que o aceitam.
|
|
100
|
-
*/
|
|
101
|
-
static readonly DEFAULT_ROAD_FACTOR = 1.3;
|
|
102
|
-
/** Fórmula de Haversine — retorna distância geodésica (linha reta) em km. */
|
|
103
|
-
private static haversine;
|
|
104
|
-
/**
|
|
105
|
-
* Resolve o offset UTC atual de um fuso IANA usando Intl.DateTimeFormat.
|
|
106
|
-
* Funciona corretamente com horário de verão (onde aplicável).
|
|
107
|
-
*/
|
|
108
|
-
private static resolveUtcOffset;
|
|
109
|
-
/**
|
|
110
|
-
* Fecha a conexão com o banco de dados.
|
|
111
|
-
*/
|
|
112
|
-
close(): void;
|
|
113
|
-
private ensureInitialized;
|
|
114
|
-
}
|
|
115
|
-
export declare const brasilCeps: BrasilCepsOffline;
|
|
116
|
-
/** Inicializa e retorna o singleton. */
|
|
117
|
-
export declare function init(): BrasilCepsOffline;
|
|
118
|
-
/** Busca um endereço pelo CEP. Retorna null se não encontrado. */
|
|
119
7
|
export declare function findByCep(cep: string): Address | null;
|
|
120
|
-
|
|
121
|
-
export declare function findByAddress(state: string, city?: string, street?: string): Address[];
|
|
122
|
-
/** Busca avançada com padrão LIKE. */
|
|
123
|
-
export declare function search(pattern: string, state?: string, limit?: number): Address[];
|
|
124
|
-
/** Calcula a distância em km entre dois CEPs. */
|
|
125
|
-
export declare function getDistance(cepA: string, cepB: string): DistanceResult | null;
|
|
126
|
-
/** Retorna endereços dentro de um raio em km a partir de um CEP central. */
|
|
127
|
-
export declare function getCepsInRadius(centerCep: string, radiusKm: number, limit?: number): AddressWithDistance[];
|
|
128
|
-
/** Retorna fuso horário IANA e offset UTC atual de um CEP. */
|
|
129
|
-
export declare function getTimezone(cep: string): TimezoneResult | null;
|
|
130
|
-
/** Valida se o código IBGE informado corresponde ao CEP. */
|
|
131
|
-
export declare function validateIbge(cep: string, ibgeProvided: number): IbgeValidationResult | null;
|
|
132
|
-
export { downloadDatabase } from './scripts/download-db';
|
|
133
|
-
export type { Address, DistanceResult, AddressWithDistance, TimezoneResult, IbgeValidationResult, Coordinates, FallbackOptions, BrasilCepsConfig, } from './types';
|
|
8
|
+
export type { Address, BrasilCepsConfig } from './types';
|