@konstit/dne 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (82) hide show
  1. package/README.md +85 -352
  2. package/dist/address-search-index.d.ts +34 -0
  3. package/dist/address-search-index.js +326 -0
  4. package/dist/address-search-index.js.map +1 -0
  5. package/dist/address-search-pool-errors.d.ts +15 -0
  6. package/dist/address-search-pool-errors.js +25 -0
  7. package/dist/address-search-pool-errors.js.map +1 -0
  8. package/dist/address-search-pool.d.ts +40 -0
  9. package/dist/address-search-pool.js +215 -0
  10. package/dist/address-search-pool.js.map +1 -0
  11. package/dist/address-search-rank.d.ts +5 -0
  12. package/dist/address-search-rank.js +89 -0
  13. package/dist/address-search-rank.js.map +1 -0
  14. package/dist/address-search-text.d.ts +6 -0
  15. package/dist/address-search-text.js +16 -0
  16. package/dist/address-search-text.js.map +1 -0
  17. package/dist/address-search-worker-runtime.d.ts +41 -0
  18. package/dist/address-search-worker-runtime.js +38 -0
  19. package/dist/address-search-worker-runtime.js.map +1 -0
  20. package/dist/address-search-worker-source.d.ts +2 -0
  21. package/dist/address-search-worker-source.js +5 -0
  22. package/dist/address-search-worker-source.js.map +1 -0
  23. package/dist/address-search.d.ts +31 -0
  24. package/dist/address-search.js +152 -0
  25. package/dist/address-search.js.map +1 -0
  26. package/dist/bairro-runs.d.ts +20 -0
  27. package/dist/bairro-runs.js +202 -0
  28. package/dist/bairro-runs.js.map +1 -0
  29. package/dist/binary-db-errors.d.ts +1 -1
  30. package/dist/binary-db-errors.js +1 -1
  31. package/dist/binary-db-errors.js.map +1 -1
  32. package/dist/binary-db-format.d.ts +10 -2
  33. package/dist/binary-db-format.js +9 -1
  34. package/dist/binary-db-format.js.map +1 -1
  35. package/dist/binary-db-integrity.d.ts +4 -0
  36. package/dist/binary-db-integrity.js +20 -0
  37. package/dist/binary-db-integrity.js.map +1 -0
  38. package/dist/binary-db-reader.d.ts +46 -28
  39. package/dist/binary-db-reader.js +237 -360
  40. package/dist/binary-db-reader.js.map +1 -1
  41. package/dist/binary-db-validator.d.ts +13 -0
  42. package/dist/binary-db-validator.js +709 -0
  43. package/dist/binary-db-validator.js.map +1 -0
  44. package/dist/chunks/dynamic-completion-wbp85hh9-cytdw6ns.js +7 -0
  45. package/dist/chunks/dynamic-completion-wbp85hh9-cytdw6ns.js.map +10 -0
  46. package/dist/chunks/index-338dn00y.js +18 -0
  47. package/dist/chunks/index-338dn00y.js.map +10 -0
  48. package/dist/expand.d.ts +8 -0
  49. package/dist/expand.js +1484 -0
  50. package/dist/expand.js.map +1 -0
  51. package/dist/fsst.d.ts +18 -0
  52. package/dist/fsst.js +117 -0
  53. package/dist/fsst.js.map +1 -0
  54. package/dist/index.js +48 -48
  55. package/dist/index.js.map +30 -18
  56. package/dist/library.d.ts +9 -2
  57. package/dist/library.js +9 -2
  58. package/dist/library.js.map +1 -1
  59. package/dist/locality-runs.d.ts +18 -0
  60. package/dist/locality-runs.js +108 -0
  61. package/dist/locality-runs.js.map +1 -0
  62. package/dist/packed-bits.d.ts +6 -0
  63. package/dist/packed-bits.js +41 -0
  64. package/dist/packed-bits.js.map +1 -0
  65. package/dist/settings.d.ts +0 -2
  66. package/dist/settings.js +0 -2
  67. package/dist/settings.js.map +1 -1
  68. package/dist/shared-file.d.ts +2 -0
  69. package/dist/shared-file.js +35 -0
  70. package/dist/shared-file.js.map +1 -0
  71. package/dist/sqlite-db-reader.d.ts +13 -4
  72. package/dist/sqlite-db-reader.js +39 -17
  73. package/dist/sqlite-db-reader.js.map +1 -1
  74. package/dist/types.d.ts +29 -4
  75. package/dist/types.js +73 -4
  76. package/dist/types.js.map +1 -1
  77. package/package.json +13 -10
  78. package/data/dne.bin +0 -0
  79. package/dist/chunks/dynamic-completion-403da357-4jc4w04x.js +0 -7
  80. package/dist/chunks/dynamic-completion-403da357-4jc4w04x.js.map +0 -10
  81. package/dist/chunks/index-s0h4vdva.js +0 -17
  82. package/dist/chunks/index-s0h4vdva.js.map +0 -10
package/dist/index.js CHANGED
@@ -1,69 +1,69 @@
1
1
  #!/usr/bin/env bun
2
2
  // @bun
3
- import{a as C,c as F,d as _e,e as O,f as Dt,o as R}from"./chunks/index-s0h4vdva.js";var ai=Object.freeze(["bash","zsh","fish","powershell"]);import{Database as sa}from"bun:sqlite";import{copyFile as ca,mkdir as la,rename as ua,rm as ue}from"fs/promises";import{basename as da,dirname as fa,join as ma}from"path";import{Database as ci}from"bun:sqlite";import{open as li}from"fs/promises";function B(e){return Number.isInteger(e)&&e>0&&e<=4294967295}var me=1,v=256,X=16,Q=Uint8Array.from([68,78,69,66,73,78,0,0]),gn=4294967295,hn=1e5,Ie=100001,Se=10,De=32,P=3,pe=8,Ae=8,K=256,je=32,k=["metadata","cepPrefixOffsets","cepSuffixes","logradouroIds","complementoBitmap","complementoRanks","complementoIds","bairroIds","municipalityIds","nomeBitmap","nomeRanks","nomeIds","municipalities","logradouroDictionary","complementoDictionary","bairroDictionary","municipioDictionary","ufDictionary","nomeDictionary","localidadeFlags","bairros","bairroFaixaOffsets","bairroFaixas","bairroAbreviadoDictionary","localidadeNomeBitmap","localidadeNomeRanks","localidadeNomeIds"];function At(e){return Math.ceil(e/8)*8}function z(e){return Math.ceil(e/8)}function Ge(e,t){return Math.ceil(e*t/8)}function Qe(){let e=new Uint8Array(256);for(let t=1;t<e.length;t++)e[t]=(e[t>>>1]??0)+(t&1);return e}function M(e){if(e<=255)return 1;if(e<=65535)return 2;if(e<=16777215)return 3;return 4}function be(e,t){if(e!==1&&e!==2&&e!==3&&e!==4)throw Error(`Unsupported binary ${t} width: ${e}`);return e}function Te(e){return e===4?4294967295:2**(e*8)-1}function Tt(e,t,n){if(!Number.isSafeInteger(e)||e<0||e>Te(t))throw Error(`Binary ${n} exceeds the ${t}-byte unsigned integer limit: ${e}`)}function q(e,t,n){switch(n){case 1:return e.getUint8(t);case 2:return e.getUint16(t,!0);case 3:return e.getUint8(t)|e.getUint8(t+1)<<8|e.getUint8(t+2)<<16;case 4:return e.getUint32(t,!0)}}function D(e,t,n,r){if(Tt(n,r,"column value"),e[t]=n&255,r>1)e[t+1]=n>>>8&255;if(r>2)e[t+2]=n>>>16&255;if(r>3)e[t+3]=n>>>24&255}function yn(e){if(e.byteLength!==Q.length)return!1;return Q.every((t,n)=>e[n]===t)}function En(e,t,n){if(n<0||n>=1024)throw Error(`CEP suffix exceeds 10 bits: ${n}`);let r=t*10,i=r>>>3,o=r&7,a=n<<o;if(e[i]=(e[i]??0)|a&255,i+1<e.byteLength)e[i+1]=(e[i+1]??0)|a>>>8&255;if(i+2<e.byteLength)e[i+2]=(e[i+2]??0)|a>>>16&255}var Re="4",ge=["M","D","P"],ze=["municipio","distrito","povoado"],Ze=["sem_codificacao_por_logradouro","codificada_por_logradouro","inserida_na_codificacao_por_logradouro","em_codificacao_por_logradouro"],si=[{name:"log_localidade",originalName:"log_localidade",sourceFields:{locNu:0,uf:1,nome:2,cep:3,situacao:4,tipo:5,locNuSub:6,munNu:8},columns:[]},{name:"log_bairro",originalName:"log_bairro",sourceFields:{baiNu:0,uf:1,locNu:2,bairro:3,abreviado:4},columns:[]},{name:"log_faixa_bairro",originalName:"log_faixa_bairro",sourceFields:{baiNu:0,cepInicial:1,cepFinal:2},columns:[]},{name:"log_cpc",originalName:"log_cpc",sourceFields:{uf:1,locNu:2,nome:3,endereco:4,cep:5},columns:[]},{name:"log_logradouro",originalName:"log_logradouro",fileGlob:"LOG_LOGRADOURO_*.TXT",sourceFields:{uf:1,locNu:2,baiNuIni:3,logNo:5,cep:7,tloTx:8,logStaTlo:9},columns:[]},{name:"log_grande_usuario",originalName:"log_grande_usuario",sourceFields:{uf:1,locNu:2,baiNu:3,nome:5,endereco:6,cep:7},columns:[]},{name:"log_unid_oper",originalName:"log_unid_oper",sourceFields:{uf:1,locNu:2,baiNu:3,nome:5,endereco:6,cep:7},columns:[]},{name:"bairros",originalName:"bairros",fileGlob:null,columns:[{name:"bairro_id",type:"INTEGER",primaryKey:!0,check:"bairro_id > 0"},{name:"localidade_id",type:"INTEGER",notNull:!0,check:"localidade_id > 0"},{name:"uf",type:"TEXT",notNull:!0},{name:"nome",type:"TEXT",notNull:!0},{name:"nome_abreviado",type:"TEXT"}]},{name:"bairro_faixas",originalName:"bairro_faixas",fileGlob:null,withoutRowid:!0,columns:[{name:"bairro_id",type:"INTEGER",primaryKey:!0,references:{table:"bairros",column:"bairro_id"}},{name:"cep_inicial",type:"TEXT",primaryKey:!0,check:"length(cep_inicial) = 8 AND cep_inicial NOT GLOB '*[^0-9]*'"},{name:"cep_final",type:"TEXT",primaryKey:!0,check:"length(cep_final) = 8 AND cep_final NOT GLOB '*[^0-9]*' AND cep_inicial <= cep_final"}]},{name:"cep_unificado",originalName:"cep_unificado",fileGlob:null,unifiedTable:!0,columns:[{name:"cep",type:"TEXT",primaryKey:!0,comment:"Cont\xE9m somente os oito d\xEDgitos do CEP, sem separadores."},{name:"logradouro",type:"TEXT"},{name:"complemento",type:"TEXT"},{name:"bairro_id",type:"INTEGER",references:{table:"bairros",column:"bairro_id"}},{name:"localidade_nome",type:"TEXT",comment:"Original district or village name for a locality-wide CEP.",check:"localidade_nome IS NULL OR (bairro_id IS NULL AND localidade_tipo IN ('D', 'P'))"},{name:"municipio",type:"TEXT",notNull:!0},{name:"municipio_cod_ibge",type:"INTEGER",notNull:!0},{name:"uf",type:"TEXT",notNull:!0},{name:"nome",type:"TEXT"},{name:"localidade_situacao",type:"INTEGER",notNull:!0,check:"localidade_situacao IN (0, 1, 2, 3)"},{name:"localidade_tipo",type:"TEXT",notNull:!0,check:"localidade_tipo IN ('M', 'D', 'P')"}]}];function wn(e={}){return si.map((t)=>({...t,name:e[t.originalName]??t.name,columns:t.columns.map((n)=>({...n,...n.references?{references:{...n.references,table:e[n.references.table]??n.references.table}}:{}})),sourceFields:t.sourceFields?{...t.sourceFields}:void 0}))}function J(e){let t=e.find((n)=>n.unifiedTable);if(!t)throw Error("Unified schema table not found");return t}function Ne(e){return e.filter((t)=>t.columns.length>0)}function xe(e){if(e.unifiedTable||e.fileGlob===null)return null;return e.fileGlob??`${e.originalName.toUpperCase()}.TXT`}function ee(e,t){if(!e.sourceFields)throw Error(`Source fields for table '${e.originalName}' not found`);return t.map((n)=>{let r=e.sourceFields?.[n];if(r===void 0)throw Error(`Source field '${n}' for table '${e.originalName}' not found`);return r})}var _n="dne",In="dne.db",T="dne",te="bairros",Ye="bairro_faixas",A="edne_metadata",Sn=32768,Dn=-200000,An=1000,Z="https://www2.correios.com.br/sistemas/edne/download/eDNE_Basico.zip",Tn=8,Ve=2097152,Rn=30000,Nn=2,xn=100,Cn=1000,Ln=2000;var xt=new TextEncoder,ui=Qe();async function vn(e,t,n=T){Ii();let r=new ci(e,{readonly:!0});try{r.run("BEGIN");let i=yi(r,n);if(Lt(i,"row count"),!i)throw Error("Cannot create a binary database without rows");let o=r.query(`SELECT bairro_id, localidade_id, uf, nome, nome_abreviado
4
- FROM ${Le(te)} ORDER BY bairro_id`).all(),a=new Map(o.map((_,L)=>[_.bairro_id,L+1])),s=M(o.length),l=di(r,n,o),c=fi(l),u=[...l.municipalitiesByIbge.entries()].sort(([_],[L])=>_-L),d=u.length,f=M(d),m=new Map;for(let[_,[L]]of u.entries())m.set(L,_+1);let b=new Uint32Array(Ie),g=new Uint8Array(Ge(i,Se)),w=new Uint8Array(i*c.logradouro.idWidth),h=new Uint8Array(z(i)),I=new Uint8Array(l.complementoCount*c.complemento.idWidth),S=new Uint8Array(i*s),N=new Uint8Array(z(i)),an=new Uint8Array(l.localidadeNomeCount*c.bairro.idWidth),sn=new Uint8Array(i*f),cn=new Uint8Array(i),ln=new Uint8Array(z(i)),un=new Uint8Array(l.nomeCount*c.nome.idWidth),ht=0,yt=0,Et=0,fe=0,dn=-1,x=0;for(let _ of Mn(r,n)){let L=Ct(_.cep);if(L<=dn)throw Error("CEP rows must be unique and ordered");dn=L;let pn=ge.indexOf(_.localidade_tipo);if(pn===-1||![0,1,2,3].includes(_.localidade_situacao))throw Error(`Invalid locality indicators for CEP: ${_.cep}`);cn[x]=pn<<2|_.localidade_situacao;let oi=Math.floor(L/1000);while(fe<=oi)b[fe]=x,fe++;if(En(g,x,L%1000),D(w,x*c.logradouro.idWidth,$n(c.logradouro,_.logradouro),c.logradouro.idWidth),_.complemento!==null)Nt(h,x),D(I,ht*c.complemento.idWidth,Y(c.complemento,_.complemento,"complemento"),c.complemento.idWidth),ht++;let St=_.bairro_id===null?0:a.get(_.bairro_id);if(St===void 0)throw Error(`Unknown bairro_id for CEP: ${_.cep}`);if(D(S,x*s,St,s),_.localidade_nome!==null){if(St!==0||_.localidade_tipo==="M")throw Error(`Invalid subordinate locality name for CEP: ${_.cep}`);Nt(N,x),D(an,Et*c.bairro.idWidth,Y(c.bairro,_.localidade_nome,"localidade_nome"),c.bairro.idWidth),Et++}let bn=m.get(_.municipio_cod_ibge);if(bn===void 0)throw Error(`Missing municipality for IBGE code: ${_.municipio_cod_ibge}`);if(D(sn,x*f,bn,f),_.nome!==null)Nt(ln,x),D(un,yt*c.nome.idWidth,Y(c.nome,_.nome,"nome"),c.nome.idWidth),yt++;x++}if(x!==i)throw Error(`SQLite row count changed while exporting: expected ${i}, got ${x}`);if(ht!==l.complementoCount||yt!==l.nomeCount||Et!==l.localidadeNomeCount)throw Error("SQLite nullable field counts changed while exporting");while(fe<Ie)b[fe]=i,fe++;let fn=M(i),wt=Rt(h,I,i),_t=Rt(ln,un,i),It=Rt(N,an,i),mn=bi(r,a),ni=xt.encode(JSON.stringify(Ei(r))),ri=mi(u,c),ii={bairroDictionary:c.bairro.bytes,bairroAbreviadoDictionary:c.bairroAbreviado.bytes,bairroIds:S,bairros:pi(o,c),bairroFaixaOffsets:mn.offsets,bairroFaixas:mn.ranges,cepPrefixOffsets:_i(b,fn),cepSuffixes:g,complementoBitmap:wt.bitmap,complementoDictionary:c.complemento.bytes,complementoIds:wt.ids,complementoRanks:wt.ranks,localidadeFlags:cn,localidadeNomeBitmap:It.bitmap,localidadeNomeRanks:It.ranks,localidadeNomeIds:It.ids,logradouroDictionary:c.logradouro.bytes,logradouroIds:w,metadata:ni,municipalities:ri,municipalityIds:sn,municipioDictionary:c.municipio.bytes,nomeBitmap:_t.bitmap,nomeDictionary:c.nome.bytes,nomeIds:_t.ids,nomeRanks:_t.ranks,ufDictionary:c.uf.bytes};return await gi(t,i,d,f,fn,ii),r.run("COMMIT"),i}finally{r.close()}}function di(e,t,n){let r={complementoCount:0,localidadeNomeCount:0,municipalitiesByIbge:new Map,nomeCount:0,strings:{bairro:new Set,bairroAbreviado:new Set,complemento:new Set,logradouro:new Set,municipio:new Set,nome:new Set,uf:new Set}};for(let i of n){if(!B(i.bairro_id)||!B(i.localidade_id)||!i.nome||!i.uf)throw Error(`Invalid neighborhood: ${i.bairro_id}`);r.strings.bairro.add(i.nome),Ce(r.strings.bairroAbreviado,i.nome_abreviado),r.strings.uf.add(i.uf)}for(let i of Mn(e,t)){if(Ce(r.strings.logradouro,i.logradouro),Ce(r.strings.complemento,i.complemento),Ce(r.strings.bairro,i.localidade_nome),r.strings.municipio.add(i.municipio),r.strings.uf.add(i.uf),Ce(r.strings.nome,i.nome),i.complemento!==null)r.complementoCount++;if(i.nome!==null)r.nomeCount++;if(i.localidade_nome!==null)r.localidadeNomeCount++;Tt(i.municipio_cod_ibge,3,"municipio_cod_ibge");let o=r.municipalitiesByIbge.get(i.municipio_cod_ibge);if(o&&(o.municipio!==i.municipio||o.uf!==i.uf))throw Error(`IBGE code maps to multiple municipalities: ${i.municipio_cod_ibge}`);r.municipalitiesByIbge.set(i.municipio_cod_ibge,{municipio:i.municipio,uf:i.uf})}return r}function fi(e){return{bairro:ne(e.strings.bairro),bairroAbreviado:ne(e.strings.bairroAbreviado),complemento:ne(e.strings.complemento),logradouro:ne(e.strings.logradouro),municipio:ne(e.strings.municipio),nome:ne(e.strings.nome),uf:ne(e.strings.uf)}}function ne(e){let t=[...e].sort(),n=t.length,r=Math.ceil(n/pe),i=new Uint32Array(r),o=new Uint8Array(n),a=new Uint8Array(n),s=new Map,l=new Uint8Array,c=0;for(let[h,I]of t.entries()){let S=xt.encode(I);if(S.byteLength>255)throw Error(`Binary string exceeds 255 UTF-8 bytes: ${I}`);let N=h%pe===0?0:wi(l,S);if(h%pe===0)i[h>>>P]=c;o[h]=S.byteLength,a[h]=N,c+=S.byteLength-N,Lt(c,"dictionary suffix data length"),s.set(I,h+1),l=S}let u=De,d=u+i.byteLength,f=d+o.byteLength,m=f+a.byteLength,b=new Uint8Array(m+c),g=new DataView(b.buffer);g.setUint32(0,n,!0),g.setUint32(4,r,!0),g.setUint32(8,u,!0),g.setUint32(12,d,!0),g.setUint32(16,f,!0),g.setUint32(20,m,!0),g.setUint32(24,c,!0),g.setUint8(28,M(n)),g.setUint8(29,P),b.set(Ot(i),u),b.set(o,d),b.set(a,f);let w=m;for(let[h,I]of t.entries()){let S=xt.encode(I),N=a[h]??0;b.set(S.subarray(N),w),w+=S.byteLength-N}return{bytes:b,count:n,ids:s,idWidth:M(n)}}function mi(e,t){let n=3+t.municipio.idWidth+t.uf.idWidth,r=new Uint8Array(e.length*n);for(let[i,[o,a]]of e.entries()){let s=i*n;D(r,s,o,3),D(r,s+3,Y(t.municipio,a.municipio,"municipio"),t.municipio.idWidth),D(r,s+3+t.municipio.idWidth,Y(t.uf,a.uf,"uf"),t.uf.idWidth)}return r}function Rt(e,t,n){let r=Math.ceil(n/K),i=new Uint32Array(r+1),o=0;for(let a=0;a<r;a++){i[a]=o;let s=a*(K>>>3),l=Math.min(s+(K>>>3),e.byteLength);for(let c=s;c<l;c++)o+=ui[e[c]??0]??0}return i[r]=o,{bitmap:e,ids:t,ranks:Ot(i)}}function pi(e,t){let n=M(e.at(-1)?.bairro_id??0),r=M(e.reduce((s,l)=>Math.max(s,l.localidade_id),0)),i=n+r+t.bairro.idWidth+t.bairroAbreviado.idWidth+t.uf.idWidth,o=new Uint8Array(X+e.length*i),a=new DataView(o.buffer);a.setUint32(0,e.length,!0),a.setUint8(4,n),a.setUint8(5,r);for(let[s,l]of e.entries()){let c=X+s*i;D(o,c,l.bairro_id,n),c+=n,D(o,c,l.localidade_id,r),c+=r,D(o,c,Y(t.bairro,l.nome,"bairro"),t.bairro.idWidth),c+=t.bairro.idWidth,D(o,c,$n(t.bairroAbreviado,l.nome_abreviado),t.bairroAbreviado.idWidth),c+=t.bairroAbreviado.idWidth,D(o,c,Y(t.uf,l.uf,"uf"),t.uf.idWidth)}return o}function bi(e,t){let n=e.query(`SELECT bairro_id, cep_inicial, cep_final FROM ${Le(Ye)}
5
- ORDER BY bairro_id, cep_inicial, cep_final`).all(),r=new Uint32Array(t.size+1),i=new Uint8Array(n.length*8),o=new DataView(i.buffer),a=0,s;for(let[l,c]of n.entries()){let u=t.get(c.bairro_id);if(u===void 0)throw Error(`Unknown neighborhood in CEP range: ${c.bairro_id}`);let d=Ct(c.cep_inicial),f=Ct(c.cep_final);if(d>f)throw Error(`Reversed neighborhood CEP range: ${c.bairro_id}`);if(s?.bairro_id===c.bairro_id&&s.cep_inicial===c.cep_inicial&&s.cep_final===c.cep_final)throw Error(`Duplicate neighborhood CEP range: ${c.bairro_id}`);while(a<u)r[a++]=l;o.setUint32(l*8,d,!0),o.setUint32(l*8+4,f,!0),s=c}while(a<r.length)r[a++]=n.length;return{offsets:Ot(r),ranges:i}}async function gi(e,t,n,r,i,o){let a={},s=v;for(let d of k)s=At(s),a[d]={length:o[d].byteLength,offset:s},s+=o[d].byteLength;let l=At(s);Lt(l,"file size");let c=hi({cepPrefixOffsetWidth:i,fileSize:l,municipalityCount:n,municipalityIdWidth:r,rowCount:t,sections:a}),u=await li(e,"w");try{await On(u,c);let d=c.byteLength;for(let f of k){let m=a[f];await Bn(u,m.offset-d),await On(u,o[f]),d=m.offset+m.length}await Bn(u,l-d)}finally{await u.close()}}function hi(e){let t=new Uint8Array(v);t.set(Q,0);let n=new DataView(t.buffer);n.setUint16(8,me,!0),n.setUint16(10,v,!0),n.setUint32(12,e.rowCount,!0),n.setUint32(16,e.fileSize,!0),n.setUint8(20,e.cepPrefixOffsetWidth),n.setUint8(21,e.municipalityIdWidth),n.setUint8(22,Ae),n.setUint8(23,P),n.setUint16(24,k.length,!0),n.setUint32(28,e.municipalityCount,!0);for(let[r,i]of k.entries()){let o=e.sections[i],a=je+r*8;n.setUint32(a,o.offset,!0),n.setUint32(a+4,o.length,!0)}return t}function yi(e,t){return e.query(`SELECT count(*) AS count FROM ${Le(t)}`).get().count}function*Mn(e,t){let n=e.query(`
3
+ import{t,o,s,a,f,r}from"./chunks/index-338dn00y.js";var go=Object.freeze(["bash","zsh","fish","powershell"]);import{Database as kc}from"bun:sqlite";import{statSync as io}from"fs";import{copyFile as Hc,mkdir as uo,mkdtemp as Wc,rename as lo,rm as ge}from"fs/promises";import{basename as jc,dirname as jn,extname as qc,join as qn,resolve as Zc}from"path";import{createHash as ko}from"crypto";var Do={ACAMPAMENTO:["ACAMP"],"ACESSO A AVENIDA":["AC AV"],"ACESSO DE PEDESTRE":["AC PED"],"ACESSO ESTADUAL":["AC ESTD"],"ACESSO LOCAL":["AC LOCAL"],"ACESSO PARA RUA":["AC R"],ADRO:["AD"],AEROPORTO:["AER"],ALCA:[],"ALCA DE ACESSO":["ALC ACES"],ALDEIA:["ALD"],"ALDEIA INDIGENA":["ALD IND"],ALTO:["AT"],ANEL:["AN"],"ANEL VIARIO":["AN VR"],"ANTIGA ESTACAO":["ANT ETC"],"ANTIGA ESTRADA":["ANT EST"],AREA:[],"AREA ESPECIAL":["AE"],"AREA VERDE":["A VERDE"],ARTERIA:["ART"],ATALHO:["ATL"],"AVENIDA CENTRAL":["AV CENT"],"AVENIDA CIRCULAR":["AV CIRC"],"AVENIDA CONTORNO":["AV CONT"],"AVENIDA ESPLANADA":["AV ESP"],"AVENIDA EXPRESSA":["AV EXP"],"AVENIDA INDUSTRIAL":["AV IND"],"AVENIDA INTEGRACAO":["AV INT"],"AVENIDA MARGINAL DIREITA":["AV MARG DIR"],"AVENIDA MARGINAL ESQUERDA":["AV MARG ESQ"],"AVENIDA MARGINAL NORTE":["AV MARG NORTE"],"AVENIDA NORTE SUL":["AV NORTE SUL"],"AVENIDA PERIMETRAL":["AV PER"],"AVENIDA VELHA":["AV VA"],BAIXA:["BX"],BALAO:["BLO"],BALNEARIO:["BALN"],"BECO 1":["BC 1"],"BECO 2":["BC 2"],"BECO 3":["BC 3"],BELVEDERE:["BELV"],BLOCO:["BL"],BLOCOS:["BLS"],BOSQUE:["BSQ"],BOULEVARD:["BVD"],BULEVAR:["BLV"],BURACO:[],CAIS:[],CALCADAO:[],CALCADINHO:["CALCNHO"],"CAMINHO DE SERVIDAO":["CAM SERV"],CAMPO:["CPO"],CAMPUS:[],CANAL:["CAN"],CENTRO:["CENTR"],"CENTRO ADMINISTRATIVO":["CENTR ADMIN"],"CENTRO COMERCIAL":["CENTR COMERC"],CHACARAS:["CHS"],CHAPADAO:["CHAP"],CICLOVIA:["CICL"],CIRCULAR:["CIRC"],COLINA:["CLNA"],COLONIA:["COL"],"COMPLEXO VIARIO":["CMP VR"],COMUNIDADE:["COM"],"COMUNIDADE QUILOMBOLA":["COM QUILOMB"],"COMUNIDADE RURAL":["COM RURA"],"COMUNIDADE SITIO":["COM SIT"],"COMUNIDADE URBANA":["COM URBA"],CONDOMINIO:["COND"],"CONDOMINIO RESIDENCIAL":["COND RES"],"CONJUNTO HABITACIONAL":["CJ HAB"],"CONJUNTO MUTIRAO":["CJ MUT"],"CONJUNTO RESIDENCIAL":["CJ RES"],CONTORNO:["CONT"],"CONTORNO VIARIO":["CONT VR"],CORREDOR:[],CORREGO:["CRG"],DESCIDA:["DSC"],DESVIO:["DSV"],DIAGONAL:["DIAG"],DISTRITO:[],EDIFICIO:["ED"],EIXO:["EX"],"EIXO INDUSTRIAL":["EX IND"],"EIXO PRINCIPAL":["EX PRINC"],ELEVADA:["EVD"],ELEVADO:["EVDO"],ENSEADA:["ENS"],ENTRADA:["ENT"],"ENTRADA PARTICULAR":["ENT PART"],"ENTRE BLOCO":["EBL"],"ENTRE QUADRA":["EQ"],ESCADA:["ESC"],"ESCADA DE PEDRA":["ESC PEDRA"],ESCADAO:["ESCO"],ESCADARIA:["ESCAD"],ESPLANADA:["ESP"],ESTACAO:["ETC"],"ESTACAO TRANSFORMADORA":["ECT TRANS"],ESTACIONAMENTO:["ESTC"],ESTADIO:["ETD"],ESTANCIA:["ETN"],"ESTRADA ANTIGA":["EST ANT"],"ESTRADA DE FERRO":["EST FER"],"ESTRADA DE LIGACAO":["EST LIG"],"ESTRADA DE SERVIDAO":["EST SRV"],"ESTRADA ECOTURISTICA":["EST ECOT"],"ESTRADA ESTADUAL":["EST ESTD"],"ESTRADA FEDERAL":["EST FED"],"ESTRADA INTERMUNICIPAL":["EST INTERM"],"ESTRADA MARGINAL":["EST MARG"],"ESTRADA MUNICIPAL":["EST MUN"],"ESTRADA MUNICIPAL PARA":["EST MUN PRA"],"ESTRADA NOVA":["EST N"],"ESTRADA PARA":["EST PRA"],"ESTRADA PARTICULAR":["EST PART"],"ESTRADA PRINCIPAL":["EST PRINC"],"ESTRADA REAL":["EST REAL"],"ESTRADA VELHA":["EST VELHA"],"ESTRADA VICINAL":["EST VIC"],"ESTRADA VICINAL MUNICIPAL":["EST VIC MUN"],EXPANSAO:["EXPAN"],FAIXA:["FX"],FAVELA:["FAV"],FAZENDA:["FAZ"],FEIRA:["FRA"],FERROVIA:["FER"],FOLHA:["FL"],FONTE:["FNT"],FORTE:["FTE"],GALERIA:[],GLEBA:["GLB"],GRANJA:["GJA"],ILHA:["IA"],ILHOTA:["IOA"],"JARDIM PUBLICO":["JD PUB"],"JARDIM RESIDENCIAL":["JD RES"],JARDINETE:["JDE"],LAGO:[],LAGOA:["LGA"],LARGO:["LRG"],"LARGO DA BASILICA":["LRG BAS"],LIGACAO:["LIG"],LOCALIDADE:["LOC"],LOTE:["LT"],MARGEM:["MRG"],MARGINAL:["MARG"],MARINA:["MNA"],MERCADO:["MERC"],MIRANTE:["MT"],MODULO:["MOD"],"MODULO COMERCIAL":["MC"],MONTE:["MTE"],MORRO:["MRO"],"NOVA AVENIDA":["N AV"],"NUCLEO HABITACIONAL":["NUC HAB"],"NUCLEO RURAL":["NUC RURAL"],OCUPACAO:["OCUP"],"ORLA FLUVIAL":["OR FL"],OUTEIRO:["OUT"],PARADOURO:["PDO"],PARALELA:["PAR"],PARCELAMENTO:["PARC"],"PARQUE MUNICIPAL":["PRQ MUNIC"],"PARQUE RESIDENCIAL":["PRQ RES"],"PASSAGEM DE PEDESTRES":["PSG PED"],"PASSAGEM PARTICULAR":["PSG PART"],"PASSAGEM SUBTERRANEA":["PSG SUB"],PASSARELA:["PSA"],PASSEIO:["PAS"],"PASSEIO PUBLICO":["PAS PUB"],PATIO:["PAT"],PEDESTRE:["PED"],"PISTA LATERAL":["PTA LAT"],PONTA:["PTA"],PONTE:["PTE"],PONTILHAO:["PNTL"],PORTO:[],POVOADO:["POV"],"PRACA DA MATRIZ":["PC MATRIZ"],"PRACA DE ESPORTES":["PC ESP"],"PRACA E CAMPO":["PC CPO"],"PRACA GIRATORIA":["PRCA GIRT"],"PRACA ROTATORIA":["PCA ROT"],PRACINHA:[],PRAIA:[],PROJECAO:[],"PROLONGAMENTO DA AVENIDA":["PRL AV"],"PROLONGAMENTO DA RUA":["PRL R"],QUADRA:[],"QUARTA LADEIRA":["4 LD"],"QUINTA LADEIRA":["5 LD"],QUINTAS:["QTAS"],RAMAL:["RAM"],RAMPA:["RMP"],RECANTO:["REC"],RECREIO:["RCR"],RETA:[],RETIRO:["RER"],RETORNO:["RTN"],"RODO ANEL":["ROD AN"],"RODOVIA DE ACESSO":["ROD AC"],"RODOVIA ESTADUAL":["ROD ESTD"],"RODOVIA MUNICIPAL":["ROD MUN"],"RODOVIA VICINAL":["ROD VIC"],ROTATORIA:["RTT"],ROTULA:[],"RUA CIRCULAR":["R CIRC"],"RUA CONTORNO":["R CONT"],"RUA DE LIGACAO":["R LIG"],"RUA DE PEDESTRE":["R PED"],"RUA FERROVIARIA":["R FERR"],"RUA INDUSTRIAL":["R IND"],"RUA INTEGRACAO":["R INTEG"],"RUA MARGINAL":[],"RUA PEDESTRE":["RPED"],"RUA PERIMETRAL":[],"RUA PRINCIPAL":["R PRINC"],"RUA PROJETADA":[],"RUA TRANSVERSAL":["R TRANSV"],"RUA VELHA":["R VELHA"],"RUA VICINAL":["R VIC"],RUELA:["RLA"],"SEGUNDA AVENIDA":["SEG AV"],"SEMI ANEL VIARIO":["S AN V"],SERVIDAO:["SRV"],"SERVIDAO DE PASSAGEM":["SRV PSG"],SETOR:[],"SISTEMA VIARIO":["SIS VR"],SUBIDA:["SUB"],TEMPORARIO:["TEMP"],"TERCEIRA AVENIDA":["TERC AV"],TERMINAL:["TER"],TIFA:["TF"],"TRAVESSA DA RUA":["TV DA RUA"],"TRAVESSA DE PEDESTRE":["TV PED"],"TRAVESSA I":["TV I"],"TRAVESSA II":["TV II"],"TRAVESSA III":["TV III"],"TRAVESSA PARTICULAR":["TV PART"],"TRAVESSA PROJETADA":["TV PROJ"],"TRAVESSA VELHA":["TV VELHA"],TRAVESSIA:["TRAVESS"],TRECHO:[],TREVO:[],"TREVO ROTATORIO":["TRV RTTO"],TRILHA:["TL"],"TRILHA DE ACESSO":["TL DE AC"],TRINCHEIRA:["TCH"],TUNEL:["TUN"],UNIDADE:["UNID"],VALA:["VAL"],VALE:["VLE"],VARIANTE:["VRTE"],"VARIANTE DA ESTRADA":["VRTE EST"],VEREDA:[],"VIA CIRCULAR":["V CIRCU"],"VIA COLETORA":["V COLET"],"VIA COSTEIRA":["V COST"],"VIA CULTURAL":["V CULT"],"VIA DE ACESSO":["V AC"],"VIA DE CIRCULACAO":["V CIRC"],"VIA DE PEDESTRE":["V PED"],"VIA DE PEDESTRES":["V PEDS"],"VIA DIRETRIZ":["VL DIR"],"VIA ELEVADO":["V EVD"],"VIA ESTRADA MUNICIPAL":["V EST MUN"],"VIA EXPRESSA":["V EXP"],"VIA LATERAL":["V LAT"],"VIA LITORANEA":["V LIT"],"VIA LOCAL":["V LOCAL"],"VIA MARGINAL":["V MARG"],"VIA MUNICIPAL":["V MUN"],"VIA PEDESTRE":["VPED"],"VIA PRINCIPAL":["V PRINC"],VICINAL:["VC"],"VICINAL MUNICIPAL":["VC MUN"],"VIELA DA RUA":[],"VIELA DE ACESSO":[],"VIELA MUNICIPAL":[],"VILA RURAL":["VL R"],"ZIGUE ZAGUE":["ZIG ZAG"],"ZONA RURAL":["Z R"],"1 ACESSO":["1 AC"],"1 ALTO":["1 AT"],"1 AVENIDA":["1 AV"],"1 BECO":["1 BC"],"1 ESCADA":["1 ESC"],"1 ESCADARIA":["1 ESCAD"],"1 LADEIRA":["1 LD"],"1 PARALELA":["1 PAR"],"1 PARQUE":["1 PRQ"],"1 RUA":["1 R"],"1 SUBIDA":["1 SUB"],"1 TRAVESSA":["1 TV"],"1 TRAVESSA DA AVENIDA":["1 TV DA AV"],"1 TRAVESSA DA RODOVIA":["1 TV DA ROD"],"1 TRAVESSA DA RUA":["1 TV DA R"],"1 VIA COLETORA":["1 V COLET"],"1 VIELA":["1 VLA"],"1 VILA":["1 VL"],"10 AVENIDA":["10 AV"],"10 ESCADARIA":["10 ESCAD"],"10 RUA":["10 R"],"10 TRAVESSA":["10 TV"],"11 AVENIDA":["11 AV"],"11 RUA":["11 R"],"11 TRAVESSA":["11 TV"],"12 RUA":["12 R"],"12 TRAVESSA":["12 TV"],"13 TRAVESSA":["13 TV"],"14 TRAVESSA":["14 TV"],"15 TRAVESSA":["15 TV"],"16 TRAVESSA":["16 TV"],"17 TRAVESSA":["17 TV"],"18 TRAVESSA":["18 TV"],"19 TRAVESSA":["19 TV"],"2 ACESSO":["2 AC"],"2 ALAMEDA":["2 AL"],"2 ALTO":["2 AT"],"2 AVENIDA":["2 AV"],"2 BECO":["2 BC"],"2 ESCADA":["2 ESC"],"2 ESCADARIA":["2 ESCAD"],"2 LADEIRA":["2 LD"],"2 PARALELA":["2 PAR"],"2 PARQUE":["2 PRQ"],"2 RUA":["2 R"],"2 SUBIDA":["2 SUB"],"2 TRAVESSA":["2 TV"],"2 TRAVESSA DA RODOVIA":["2 TV ROD"],"2 TRAVESSA DA RUA":["2 TV DA R"],"2 VIA":["2 V"],"2 VIA COLETORA":["2 V COLET"],"2 VIELA":["2 VLA"],"2 VILA":["2 VL"],"20 TRAVESSA":["20 TV"],"21 TRAVESSA":["21 TV"],"22 TRAVESSA":["22 TV"],"26 TRAVESSA":["26 TV"],"3 ACESSO":["3 AC"],"3 ALTO":["3 AT"],"3 AVENIDA":["3 AV"],"3 BECO":["3 BC"],"3 ESCADARIA":["3 ESCAD"],"3 LADEIRA":["3 LD"],"3 PARALELA":["3 PAR"],"3 PARQUE":["3 PRQ"],"3 RUA":["3 R"],"3 SUBIDA":["3 SUB"],"3 TRAVESSA":["3 TV"],"3 TRAVESSA DA RUA":["3 TV DA R"],"3 VILA":["3 VL"],"4 ALTO":["4 AT"],"4 AVENIDA":["4 AV"],"4 BECO":["4 BC"],"4 ESCADARIA":["4 ESCAD"],"4 PARALELA":["4 PAR"],"4 RUA":["4 R"],"4 SUBIDA":["4 SUB"],"4 TRAVESSA":["4 TV"],"4 TRAVESSA DA RUA":["4 TV DA R"],"4 VILA":["4 VL"],"5 ALTO":["5 AT"],"5 AVENIDA":["5 AV"],"5 BECO":["5 BC"],"5 ESCADARIA":["5 ESCAD"],"5 PARALELA":["5 PAR"],"5 RUA":["5 R"],"5 SUBIDA":["5 SUB"],"5 TRAVESSA":["5 TV"],"5 TRAVESSA DA RUA":["5 TV DA R"],"5 VILA":["5 VL"],"6 AVENIDA":["6 AV"],"6 BECO":["6 BC"],"6 ESCADARIA":["6 ESCAD"],"6 RUA":["6 R"],"6 SUBIDA":["6 SUB"],"6 TRAVESSA":["6 TV"],"6 VILA":["6 VL"],"7 AVENIDA":["7 AV"],"7 ESCADARIA":["7 ESCAD"],"7 RUA":["7 R"],"7 TRAVESSA":["7 TV"],"8 AVENIDA":["8 AV"],"8 ESCADARIA":["8 ESCAD"],"8 RUA":["8 R"],"8 TRAVESSA":["8 TV"],"9 AVENIDA":["9 AV"],"9 ESCADARIA":["9 ESCAD"],"9 RUA":["9 R"],"9 TRAVESSA":["9 TV"]},yo={ABADE:["AB"],ABADESSA:["ABS"],ABOLICIONISTA:["ABOLIC"],ACADEMICA:["ACDA"],ACADEMICO:["ACDO"],ADMINISTRADOR:["ADM"],ADVOGADA:[],"ADVOGADO DOUTOR":["ADV DR"],AGENTE:["AG"],"AGENTE ADMINISTRATIVO":["AG ADM"],"AGENTE DE ESTACAO":["AG EST"],"AGENTE DE INVESTIGACAO":["AG INV"],"AGENTE FISCAL":["AG FISC"],"AGENTE POLICIAL":["AG POL"],"AGENTE POSTAL":["AG POS"],AGRICULTOR:[],AGRICULTORA:[],AGRIMENSOR:["AGRIM"],AGRONOMA:[],AGRONOMO:[],AGROPECUARISTA:["AGROP"],AJUDANTE:["AJ"],"ALCAIDE MOR":["ALC MOR"],ALFAIATE:["ALFT"],"ALMIRANTE MARQUES":["ALM MQ"],"ALMIRANTE PADRE":["ALM PE"],ALMOCREVE:["ALMOC"],ALMOTACEL:["ALMOT"],ALUNA:[],ALUNO:[],AMBIENTALISTA:["AMB"],ANALISTA:["ANL"],ANCIAO:["ANC"],ANJO:[],ANSPECADA:["ANSP"],ANTROPOLOGO:["ANT"],APICULTOR:["APIC"],APOSENTADA:[],APOSENTADO:[],APOSTOLO:["APOST"],"APOSTOLO SANTO":["APOST STO"],"APOSTOLO SAO":["APOST S"],APRENDIZ:["APDZ"],APRESENTADOR:["APRES"],ARCANJO:["ARCJ"],ARCEBISPO:["ARC"],"ARCEBISPO DOM":["ARC D"],ARQUEOLOGA:[],ARQUEOLOGO:[],ARQUITETA:[],"ARQUITETO PROFESSOR":["ARQ PRF"],ARQUIVISTA:["ARQVA"],ARTESA:["ARTSA"],ARTESAO:["ARTS"],ARTIFICE:["ARTF"],ARTISTA:["ART"],"ARTISTA PLASTICA":["ART PLSTA"],"ARTISTA PLASTICO":["ART PLSTO"],ARTISTAS:["ARTIS"],ASPIRANTE:["ASP"],"ASSISTENTE SOCIAL":["ASS SOC"],ASTROLOGO:["ASTL"],ASTRONAUTA:["ASTN"],ASTRONOMO:["ASTR"],ATENDENTE:["ATDE"],ATIRADOR:["ATDOR"],ATLETA:["ATL"],ATOR:[],ATRIZ:["ATZ"],AUDITOR:[],"AUDITOR FISCAL":["AUD FISC"],AUDITORA:[],AUTOR:["ATR"],AUTORA:[],"AUXILIAR DE ESCRITORIO":["AUX ESC"],AVIADOR:[],"AVIADOR MARQUES":["AV MQ"],"AVIADOR MILITAR":["AV MIL"],AVIADORA:[],AVO:[],BABALORIXA:["BORIXA"],BACAMARTEIRO:[],BACHAREL:["BEL"],BAILARINA:["BAILA"],"BAILARINA ESPECIAL":["BAILA ESP"],BAILARINO:["BAIL"],BALCONISTA:["BAL"],BANCARIA:["BANCA"],BANCARIO:["BANC"],BANDEIRANTE:["BANTE"],BANDEIREIRO:["BEIRO"],BANDEIRINHA:["BINHA"],BANDEIRISTA:["BISTA"],BARBEIRO:["BARB"],BARONESA:["BRA"],BARONEZA:["BRZA"],BEATA:["BTA"],"BEATA MADRE":["BTA ME"],BEATO:["BTO"],"BEATO FREI":["BTO FR"],"BEATO MONSENHOR":["BTO MNS"],"BEATO PADRE":["BTO PE"],"BEM AVENTURADO":["B AVENT"],BENEMERITA:["BENA"],BENEMERITO:["BEN"],BENFEITOR:["BENF"],"BENFEITOR JOVEM":["BENF JOV"],BENZEDEIRA:["BENZ"],BIBLIOTECARIA:["BIBL"],BILHETEIRA:["BILHET"],BIOLOGA:["BIOLA"],BIOLOGO:["BIOL"],"BISPO DOM":["BPO D"],BOMBEIRA:["BOMBR"],BOMBEIRO:["BOMB"],BOTANICO:["BOT"],"BRIGADEIRO DO AR":["BRG AR"],CABELEIREIRA:["CABELA"],CABO:["CB"],"CABO FREI":["CB FR"],"CABO POLICIA MILITAR":["CB PM"],CADETE:["CAD"],CAFEICULTOR:["CAF"],CAMAREIRA:["CAR"],CAMARISTA:["CAT"],CAMINHONEIRO:["CAMHRO"],CANTOR:["CT"],"CANTOR E COMPOSITOR":["CT E CPTO"],"CANTOR SERTANEJO":["CT SERT"],CANTORA:["CTA"],CAPATAZ:["CAPZ"],CAPELAO:["CAPL"],"CAPELAO MILITAR":["CAPL MIL"],CAPITA:[],"CAPITAO AVIADOR":["CAP AV"],"CAPITAO BARAO":["CAP BR"],"CAPITAO CAPELAO":["CAP CAPL"],"CAPITAO DOUTOR":["CAP DR"],"CAPITAO FREI":["CAP FR"],"CAPITAO INDIO":["CAP ID"],"CAPITAO MEDICO":["CAP MED"],"CAPITAO MOR":["CAP MOR"],"CAPITAO PRIMO":["CAP PRIM"],"CAPITAO POLICIA MILITAR":["CAP PM"],CARCEREIRO:["CARC"],"CARDEAL BISPO DOM":["CARD BPO D"],"CARDEAL DOM":["CARD D"],CARNAVALESCO:["CARNAV"],CARPINTEIRO:["CARP"],CARRETEIRO:["CARR"],CARROCEIRO:["CARROC"],CARTEIRO:["CART"],CARTORARIO:["CRTO"],CARTUNISTA:["CARTUN"],CATEQUISTA:["CATQ"],CAVALHEIRO:["CAV"],CEGO:[],CENOTECNICO:["CEN"],CENTENARIA:["CENTIA"],CENTENARIO:["CENT"],CERAMISTA:["CER"],CHANCELER:[],CHEFE:[],CHOFER:["CHOF"],CICLISTA:["CICL"],CIDADA:[],"CIDADA EMERITA DOUTORA":["CID EMTA DRA"],CIDADAO:[],"CIDADAO PRESTANTE":["CID PREST"],CIENTISTA:["CIENT"],CINEASTA:["CINET"],CINEGRAFISTA:["CINEG"],CIRURGIAO:["CIRURG"],COLETOR:["COL"],COLETORA:["COLRA"],COLONIZADOR:["COLON"],COLUNISTA:["COLU"],"COLUNISTA SOCIAL":["COLU SOC"],COMADRE:["CME"],COMANDANTE:["CMTE"],"COMANDANTE AVIADOR":["CMTE AV"],COMBATENTE:["CBTE"],COMEDIANTE:["COMED"],COMENDADOR:["CDOR"],"COMENDADOR CAPITAO":["CDOR CAP"],"COMENDADOR DOUTOR":["CDOR DR"],"COMENDADOR PROFESSOR":["CDOR PRF"],COMENDADORA:["CDORA"],COMERCIANTE:["COTE"],COMERCIARIO:["COMERC"],COMISSARIA:["CMISA"],COMISSARIO:["CMISO"],"COMISSARIO DE POLICIA":["CMISO POL"],COMODORO:["CDRO"],COMPADRE:["COPE"],COMPANHEIRA:["COMPA"],"COMPANHEIRA LEAO":["COMPA LEAO"],COMPANHEIRO:["COMPO"],COMPOSITOR:["CPTO"],COMPOSITORA:["CPTA"],COMUNITARIA:["CMTA"],COMUNITARIO:["CMTO"],CONDE:["CD"],CONDESSA:["CDA"],CONEGO:["CON"],"CONEGO DOUTOR":["CON DR"],CONFRADE:["COFE"],CONSELHEIRA:["CNSA"],"CONSELHEIRA TUTELAR":[],CONSELHEIRO:["CNSO"],"CONSELHEIRO DOUTOR":["CNSO DR"],"CONSELHEIRO TUTELAR":[],CONSTRUTOR:["CONST"],CONSUL:["CSL"],CONSULESA:["CSLA"],CONTABILISTA:["CONTAB"],CONTADOR:["CONT"],CONTADORA:["CONTA"],COOPERADOR:["COOP"],CORNETEIRO:["CORN"],"CORONEL AVIADOR":["CEL AV"],"CORONEL BOMBEIRO":["CEL BOMB"],"CORONEL DOUTOR":["CEL DR"],"CORONEL POLICIA MILITAR":["CEL PM"],CORREDOR:["CRDR"],CORRETOR:["CORT"],"CORRETOR CONEGO":["CORT CON"],COSTUREIRA:["COST"],CRONISTA:["CRTA"],CRUZADOR:["CRUZ"],DELEGADA:["DELA"],DELEGADO:["DEL"],"DELEGADO DOUTOR":["DEL DR"],DENTISTA:["DENT"],DEPUTADA:["DEPA"],"DEPUTADO DOUTOR":["DEP DR"],"DEPUTADO ESTADUAL":["DEP EST"],"DEPUTADO FEDERAL":["DEP FED"],"DEPUTADO FEDERAL DOUTOR":["DEP FED DR"],DESBRAVADOR:["DESB"],"DESEMBARGADOR DOUTOR":["DES DR"],DESENHISTA:["DENH"],DESPACHANTE:["DECH"],DESPORTISTA:["DESP"],DETETIVE:["DET"],DIACONISA:[],DICIONARISTA:["DIC"],DIPLOMATA:["DIPL"],DIRETOR:["DIR"],"DIRETOR PUBLICITARIO":["DIR PUBL"],DIRETORA:["DIRA"],DISCIPULO:["DISCI"],DISTRIBUIDOR:["DIST"],DIVULGADOR:["DIVU"],DOADORA:["DOA"],"DOM ABADE":["D AB"],"DOM BISPO":["D BPO"],"DOM FREI":["D FR"],"DOM INFANTE":["D INF"],DOMESTICA:["DOME"],"DONA SANTA":["DA STA"],"DONA SINHA":["DA SINHA"],DONATARIO:["DONT"],"DOUTOR DEPUTADO":["DR DEP"],"DOUTOR INFANTE":["DR INF"],"DOUTOR PROFESSOR":["DR PRF"],"DOUTOR VEREADOR":["DR VER"],DOUTORES:["DRS"],"DUQUE ENGENHEIRO AGRONOMO":["DQ ENG AGRON"],ECOLOGISTA:["ECOL"],ECONOMISTA:["ECON"],EDITOR:["ED"],EDUCADOR:[],EDUCADORA:[],ELETRICISTA:["ELETR"],EMANCIPADOR:["EMANC"],"EMANCIPADORA PROFESSORA":["EMANC PRFA"],EMBAIXATRIZ:["EMBZ"],EMBOLADOR:["EMBL"],EMPRESARIA:["EMPA"],EMPRESARIO:["EMP"],ENCONTRISTA:["ENC"],"ENGENHEIRA QUIMICA":["ENGA QUIMA"],"ENGENHEIRO AGRIMENSOR":["ENG AGRIM"],"ENGENHEIRO AGRONOMO":["ENG AGRON"],"ENGENHEIRO ARQUITETO":["ENG ARQ"],"ENGENHEIRO CIVIL":["ENG CIV"],"ENGENHEIRO DOUTOR":["ENG DR"],"ENGENHEIRO QUIMICO":["ENG QUIM"],ENGRAXATE:["ENGX"],ENXADRISTA:["ENX"],ESCOTEIRO:["ESCT"],ESCRAVA:["EVA"],ESCRAVO:["EVO"],ESCREVENTE:["ESCREV"],ESCRITOR:["ESC"],ESCRITORA:["ESCA"],ESCRIVA:["ESCR"],ESCRIVAO:["EVAO"],ESCULTOR:["ETOR"],ESCULTORA:["ETORA"],ESPERANTISTA:["ESPTA"],ESPORTISTA:["ESP"],ESTATISTICA:["ESTA"],ESTATISTICO:["ESTO"],ESTIVADOR:["ESTV"],ESTUDANTE:["ESTUD"],EVANGELICA:["EVGCA"],EVANGELICO:["EVGCO"],EVANGELISTA:["EVGTA"],EVANGELIZADORA:["EVGDRA"],EXATOR:["EXT"],"EX COMBATENTE":["EX COMB"],EXPEDICIONARIO:["EXP"],"EXPEDICIONARIO CABO":["EXP CB"],"EXPEDICIONARIO SOLDADO":["EXP SD"],"EXPEDICIONARIO TENENTE":["EXP TEN"],EXPEDICIONARIOS:["EXPS"],"EX PREFEITO":["EX PREF"],"EX PREFEITO DOUTOR":["EX PREF DR"],"EX VEREADOR":["EX VER"],FARMACEUTICA:["FARMAC"],FARMACEUTICO:["FARM"],FAZENDEIRO:["FZDRO"],FEIRANTE:["FEI"],FERROVIARIA:["FRVA"],FERROVIARIO:["FRO"],FILANTROPO:["FTPO"],FILOSOFO:["FIL"],FISCAL:["FISC"],"FISCAL DE TRANSITO":["FISC TRANS"],"FISCAL MUNICIPAL":["FISC MUN"],FISICO:["FIS"],FOLCLORISTA:["FOLC"],FOLIAO:["FLO"],FORROZEIRO:["FORR"],FOTOGRAFA:[],FOTOGRAFO:[],"FOTOGRAFO JORNALISTICO":["FOT JORN"],FRADE:["FDE"],"FREI MADRE":["FR ME"],"FREI SANTA":["FR STA"],"FREI SAO":["FR S"],FREIRA:["FRA"],FUNCIONARIA:[],"FUNCIONARIA PUBLICA":[],FUNCIONARIO:[],"FUNCIONARIO PUBLICO":[],FUNDADOR:["FUND"],FUNILEIRO:["FUNIL"],FURRIEL:["FURR"],FUZILEIRO:["FUZ"],"FUZILEIRO NAVAL":["FUZ NAVAL"],GARCOM:["GAR"],GAZETEIRO:["GAZET"],"GENERAL DE BRIGADA":["GEN BRIG"],"GENERAL DE DIVISAO":["GEN DIV"],"GENERAL DE EXERCITO":["GEN EX"],"GENERAL DOUTOR":["GEN DR"],GENERALISSIMO:["GENRL"],GEOGRAFO:["GEOGR"],GEOLOGO:["GEOL"],GOLEIRO:["GOL"],"GOVERNADOR DOUTOR":["GOV DR"],"GOVERNADOR GENERAL":["GOV GEN"],"GRA DUQUESA":["GR DQA"],GRAFICO:["GRAF"],GRAO:["GR"],"GRAO MESTRE":["GR MTE"],GUARDA:["GDA"],"GUARDA CIVIL METROPOLITANO":["GDA CIV METR"],"GUARDA CIVIL MUNICIPAL":["GDA CIV MUN"],"GUARDA DE TRANSITO":["GDA TRANS"],"GUARDA MUNICIPAL":["GDA MUN"],"GUARDA TERRITORIAL":["GT"],"GUARDA CIVIL":["GDA CIV"],"GUARDA MARINHA":["GDA M"],"GUARDA MOR":["GDA MOR"],GUARDIAO:["GDAO"],GUERREIRA:[],GUERREIRO:[],HEROI:["HRO"],HEROINA:["HRA"],HEROIS:["HRIS"],HIDROGRAFO:["HIDGO"],HISTORIADOR:["HISTO"],HISTORIADORA:["HISTA"],HUMORISTA:["HUM"],ILUSTRADOR:["ILUST"],IMACULADA:["IMAC"],IMIGRANTE:["IMIG"],IMIGRANTES:["IMIGS"],IMPERADOR:["IMP"],"IMPERADOR DOM":["IMP D"],IMPERATRIZ:["IMPZ"],"IMPERATRIZ DONA":["IMPZ DA"],INDIA:["IDA"],INDIO:["ID"],INDUSTRIAL:["IND"],"INFANTE DOM":["INF D"],INSPETOR:["INSP"],INSPETORA:["INSPA"],INTENDENTE:["INT"],"INTENDENTE CORONEL":["INT CEL"],"INTENDENTE DOUTOR":["INT DR"],"INTERDISTRITAL COMENDADOR":["INTR CDOR"],INTERVENTOR:["INVO"],INVENTOR:["INV"],INVESTIGADOR:["INTGO"],"INVESTIGADOR DE POLICIA":["INTGO POL"],INVESTIGADORA:["INTGA"],IRMANDADE:["IRMD"],IRMAOS:["IMOS"],IRMAS:["IMAS"],JANGADEIRO:["JAN"],JARDINEIRA:["JARDA"],JARDINEIRO:["JARD"],JOGADOR:["JOG"],JORNALISTA:["JORN"],"JORNALISTA DOUTOR":["JORN DR"],"JORNALISTA PROFESSOR":["JORN PRF"],JOVEM:["JOV"],JOVENS:["JOVS"],"JUIZ DE DIREITO":["JZ DIR"],"JUIZ DE DIREITO DOUTOR":["JZ DIR DR"],"JUIZ DE ORFAO CAPITAO":["JUIZ DE O CAP"],"JUIZ DE PAZ":["JZ PZ"],"JUIZ DOUTOR":["JZ DR"],"JUIZ ORDINARIO":["JUIZ ORD"],JUIZA:["JZA"],JURISTA:["JUR"],LABORATORISTA:["LAB"],LAVADEIRA:["LAVAD"],LAVRADOR:["LAV"],LEGIONARIO:["LEG"],LEILOEIRO:["LEIL"],LIBERTADOR:["LIB"],"LIBERTADOR DOM":["LIB D"],"LIDER COMUNITARIA":["LID COMA"],"LIDER COMUNITARIO":["LID COM"],LIVREIRO:["LIV"],LOCUTOR:["LOC"],LORD:[],MACOM:["MAC"],MADAME:["MME"],"MADRE ABADESSA":["ME ABS"],MADRINHA:["MAD"],MADRINHEIRO:["MADO"],MAE:[],MAESTRINA:["MCA"],"MAESTRO CAPITAO":["MTO CAP"],"MAESTRO PROFESSOR":["MTO PRF"],"MAESTRO REVERENDO":["MTO REV"],"MAESTRO TENENTE":["MTO TEN"],MAGICO:["MAGI"],MAGISTRADO:["MAG"],"MAJOR AVIADOR":["MAJ AV"],"MAJOR DE EXERCITO":["MAJ EX"],"MAJOR DOUTOR":["MAJ DR"],"MAJOR MEDICO":["MAJ MED"],"MAJOR BRIGADEIRO":["MAJ BRG"],"MAJOR BRIGADEIRO DO AR":["MAJ BRG AR"],"MAJOR POLICIA MILITAR":["MAJ PM"],MAQUINISTA:["MAQ"],MARCENEIRO:["MARC"],MARCHANTE:["MARCH"],"MARECHAL DOUTOR":["MAL DR"],"MARECHAL DO AR":["MAL AR"],MARINHEIRO:[],MARQUESA:["MQA"],MECANICO:["MEC"],MEDICA:[],"MEDICO INDUSTRIAL":["MED IND"],MEDIUM:["MEDM"],MENINA:[],MENINO:[],MENSAGEIRO:["MENS"],MERGULHADOR:["MRG"],"MESTRA DE REISADO":["MTA REISADO"],MESTRE:["MTE"],"MESTRE DE GUERREIRO":["MTE GERR"],"MESTRE DE OBRA":["MTE OBRA"],"MESTRE PROFESSOR":["MTE PRF"],MESTRES:["MTES"],METALURGICO:["MET"],MINEIRO:["MNO"],"MINISTRO DOUTOR":["MIN DR"],MIRANTE:["MIRA"],MISS:[],MISSIONARIA:["MISA"],MISSIONARIO:["MIS"],MISTER:["MR"],MONGE:["MGE"],MONITOR:["MON"],MONSENHOR:["MNS"],"MONSENHOR DOM":["MNS D"],"MONSENHOR DOUTOR":["MNS DR"],MONSIEUR:["MSR"],MOTORISTA:["MOT"],MOTOTAXISTA:["MTAX"],MUNICIPALISTA:["MUN"],"MUNICIPALISTA DOUTOR":["MUN DR"],MUSEOLOGA:["MUSEOL"],MUSICISTA:["MUSIC"],MUSICO:["MUS"],"MUSICO E COMPOSITOR":["MUS E CPTO"],NATURALISTA:["NAT"],NAVEGADOR:["NAV"],NONO:[],NORMALISTA:["NOR"],"NOSSA SENHORA IMACULADA":["N SRA IMAC"],"NOSSO SENHOR":["N SR"],NUNCIO:["NCO"],NUTRICIONISTA:["NUTRA"],OBREIRO:["OBRE"],ODONTOLOGA:["ODONTA"],ODONTOLOGO:["ODONT"],OFICIAL:["OF"],"OFICIAL DE JUSTICA":["OF JUST"],"OFICIAL POLICIAL MILITAR":["OF POL MIL"],OGUM:["OG"],OPERADOR:["OPE"],OPERARIA:["OPA"],OPERARIO:["OP"],ORGANISTA:["ORG"],OUVIDOR:["OUV"],OXOSSI:["OX"],PADEIRO:["PDO"],"PADRE CONEGO":["PE CON"],"PADRE DOM":["PE D"],"PADRE FREI":["PE FR"],"PADRE SANTO":["PE STO"],"PADRE SEGUNDO":["PE SEG"],PADRES:["PES"],PADRINHO:["PAD"],PADROEIRO:["PADR"],PAI:[],PAISAGISTA:["PAISAG"],PAPA:[],"PAPA SANTO":["PAPA STO"],"PAPA SAO":["PAPA S"],PARTEIRA:[],"PARTEIRA DONA":["PART DA"],"PARTEIRA MAE":["PART MAE"],PASSISTA:["PAS"],PASTOR:["PST"],"PASTOR DOUTOR":["PST DR"],"PASTOR TENENTE":["PAST TEN"],PASTORA:["PSTA"],PATRAO:["PAT"],"PATRAO MOR":["PAT MOR"],PATRIARCA:["PTCA"],PATRIOTA:["PATR"],PATRONO:["PTNO"],PATRULHEIRA:["PTRA"],PATRULHEIRO:["PTRO"],PEDESTRE:["PED"],PEDREIRO:["PEDR"],PERITO:["PER"],PESCADOR:["PESC"],PIANISTA:["PNTA"],PILOTO:["PIL"],PINTOR:[],PINTORA:["PTA"],PIONEIRA:["PIONA"],PIONEIRO:["PION"],"PIONEIRO SANTO":["PIO STO"],POCEIRO:["POC"],POETA:["POE"],"POETA DOUTOR":["POE DR"],"POETA ESCRITOR":["POE ESC"],"POETA PRUDENTINO":["POE PRUD"],POETISA:["POT"],"POETISA DONA":["POT DA"],POLICIAL:["POL"],"POLICIAL CIVIL":["POL CIV"],"POLICIAL MILITAR":["POL MIL"],"POLICIAL PENAL":["POL PENAL"],PORTUARIO:["PORT"],POSTALISTA:["POST"],PRACA:["PRC"],PRACINHA:["PRAC"],PREFEITA:["PREFA"],"PREFEITA SANTA":["PREFA STA"],"PREFEITO CORONEL":["PREF CEL"],"PREFEITO DOUTOR":["PREF DR"],PREGADOR:["PRG"],PRESBITERO:["PRESB"],"PRESIDENTE BARAO":["PRES BR"],"PRESIDENTE DOUTOR":["PRES DR"],"PRESIDENTE GENERAL":["PRES GEN"],"PRESIDENTE MARECHAL":["PRES MAL"],PRIMA:["PMA"],"PRIMEIRA DAMA":["PRI DAM"],"PRIMEIRO MINISTRO":["P MIN"],"PRIMEIRO SARGENTO":["P SRG"],"PRIMEIRO SARGENTO POLICIA MILITAR":["P SRG PM"],"PRIMEIRO TENENTE":["P TEN"],"PRIMEIRO TENENTE AVIADOR":["P TEN AV"],PRIMO:["PMO"],PRINCESA:["PRCA"],"PRINCESA DONA":["PRCA DA"],PRINCEZA:["PRZA"],PRINCIPE:["PRCE"],"PRINCIPE DOM":["PRCE D"],PROCURADOR:["PROC"],PROFESSOR:["PRF"],"PROFESSOR CAPITAO":["PRF CAP"],"PROFESSOR DOUTOR":["PRF DR"],"PROFESSOR DOUTOR ENGENHEIRO":["PRF DR ENG"],"PROFESSOR E ENGENHEIRO DOUTOR":["PRF ENG DR"],"PROFESSOR E JORNALISTA":["PRF E JORN"],"PROFESSOR ENGENHEIRO":["PRF ENG"],"PROFESSOR INDIO":["PRF ID"],"PROFESSOR IRMAO":["PRF IRMO"],"PROFESSOR PADRE":["PRF PE"],"PROFESSOR VELHO":["PRF VO"],PROFESSORA:["PRFA"],"PROFESSORA DONA":["PRFA DA"],"PROFESSORA DOUTORA":["PRFA DRA"],"PROFESSORA MADRE":["PRFA ME"],"PROFESSORA SENHORINHA":["PRFA SNR"],"PROFESSORA SINHA":["PRFA SINHA"],PROFETA:["PRTA"],PROGRAMADOR:["PROG"],PROJETISTA:[],PROMOTOR:["PROM"],"PROMOTOR DE JUSTICA":["PROM JUST"],PROMOTORA:["PROMA"],PROTETICO:[],PROTETOR:["PROTE"],PROTETORA:[],PROVEDOR:["PROV"],"PROVEDOR MARQUES":["PROV MQ"],"PROVEDOR CONSELHEIRO":["PROV CNSO"],PSICANALISTA:["PSICAN"],PSICOLOGA:[],PSICOLOGO:[],PUBLICITARIO:["PUBL"],QUADRINHISTA:["QUADRIN"],QUIMICO:["QUIM"],QUITANDEIRO:["QITAN"],RABINO:["RAB"],RADIALISTA:["RAD"],"RADIALISTA DOUTOR":["RAD DR"],"RADIO AMADOR":["RAD AM"],RADIOTELEGRAFISTA:["RADIOTELEG"],RAINHA:["RNH"],"RAINHA DONA":["RNH DA"],"RAINHA GINGA":["RNH GINGA"],REGENTE:["REG"],REI:[],REITOR:["RTO"],RELIGIOSA:["RELIG"],REMADOR:["REM"],REPENTISTA:["REPENT"],REPORTER:["REP"],"REPORTER CINEMATOGRAFICO":["REP CINEM"],"REVERENDISSIMO PADRE":["REVMO PE"],REVERENDO:["REV"],"REVERENDO DOUTOR":["REV DR"],"REVERENDO PROFESSOR":["REV PRF"],RITMISTA:["RITM"],ROTARIANA:["ROTR"],ROTARIANO:[],SACERDOTE:["SAC"],SAMBISTA:["SAMB"],SANFONEIRO:["SANF"],"SANTA MADRE":["STA ME"],SANTISSIMA:["STMA"],SANTISSIMO:["STMO"],"SANTO BEATO":["STO BTO"],"SANTO PAPA":["STO PAPA"],SANTOS:["STOS"],"SAO FREI":["S FR"],"SAO PAPA":["S PAPA"],SAPATEIRO:["SAPTO"],SARGENTO:["SRG"],"SARGENTO DA AERONAUTICA":["SRG AER"],"SARGENTO POLICIA MILITAR":["SRG PM"],"SARGENTO AVIADOR":["SRG AV"],"SARGENTO BOMBEIRO":["SRG BOMB"],"SARGENTO EXPEDICIONARIO":["SRG EXP"],"SARGENTO MOR":["SRG MOR"],"SARGENTO RODOVIARIO":["SRG ROD"],"SEGUNDO SARGENTO":["S SRG"],"SEGUNDO SARGENTO POLICIA MILITAR":["S SRG PM"],"SEGUNDO TENENTE":["S TEN"],"SEGUNDO TENENTE AVIADOR":["S TEN AV"],SEMINARISTA:["SEMIN"],SENADORA:["SENA"],"SENHOR MESTRE":["SR MTE"],"SENHORA DONA":["SRA DA"],SENHORINHA:["SRHA"],SERESTEIRO:["SEREST"],SERINGUEIRO:["SERING"],SERRALHEIRO:["SERR"],SERTANISTA:["SERT"],SERVENTUARIA:["SERVTUA"],SERVENTUARIO:["SERVT"],SERVIDOR:[],"SERVIDOR MUNICIPAL":["SERV MUN"],"SERVIDOR PUBLICO":[],"SERVIDOR PUBLICO MUNICIPAL":["SERV PUB MUN"],SERVIDORA:[],"SERVIDORA PUBLICA":[],SEU:[],SIA:[],SINALEIRO:["SIN"],SINDICALISTA:["SIND"],SINHA:["SNH"],SINHAZINHA:["SNHZ"],SINHO:["SINH"],SIR:[],SOCIOLOGO:["SOC"],SOCORRISTA:["SOCORR"],SOLDADO:["SD"],"SOLDADO BOMBEIRO":["SD BOMB"],"SOLDADO CONSTITUCIONALISTA":["SD CONST"],"SOLDADO DO EXERCITO":["SD EX"],"SOLDADO EXPEDICIONARIO":["SD EXP"],"SOLDADO POLICIA MILITAR":["SD PM"],SOLICITADOR:["SOLIC"],SOROR:["SRO"],SUBDELEGADO:["SUBDEL"],SUBOFICIAL:["SO"],SUBPREFEITO:["SUBPREF"],SUBTENENTE:["SUBTEN"],"SUBTENENTE AVIADOR":["SUBTEN AV"],"SUBTENENTE POLICIA MILITAR":["SUBTEN PM"],SULTAO:["SUL"],SUPERVISOR:["SUP"],TABELIA:[],TABELIAO:[],"TABELIAO PUBLICO":["TAB PUBL"],TABERNEIRO:["TBRO"],TAIFEIRO:["TAF"],TAXISTA:["TAX"],TEATROLOGO:["TEAT"],TECELA:["TECEL"],TECNICO:["TEC"],"TECNICO AGRICOLA":["TEC AGR"],TELEFONISTA:["TELF"],TELEGRAFISTA:["TELG"],"TENENTE ENFERMEIRA":["TEN ENFA"],"TENENTE JOVEM":["TEN JOV"],"TENENTE MAESTRO":["TEN MTO"],"TENENTE AVIADOR":["TEN AV"],"TENENTE BRIGADEIRO":["TEN BRG"],"TENENTE CORONEL EB":["TEN CEL EB"],"TENENTE CORONEL AVIADOR":["TEN CEL AV"],"TENENTE CORONEL POLICIA MILITAR":["TEN CEL PM"],"TENENTE GENERAL":["TEN GEN"],"TENENTE POLICIA MILITAR":["TEN PM"],TENISTA:["TNIS"],TENOR:["TNR"],"TERCEIRO SARGENTO":["T SRG"],"TERCEIRO SARGENTO AERONAUTICA":["T SRG AER"],"TERCEIRO SARGENTO POLICIA MILITAR":["T SRG PM"],TERRITORIO:["TRT"],TIA:[],TIO:[],TIPOGRAFO:["TIP"],TONELEIRO:["TON"],TOPOGRAFO:["TOP"],TRABALHADOR:["TRAB"],TRADICIONALISTA:["TRAD"],TRATORISTA:["TRAT"],TREINADOR:["TRN"],TROPEIRO:["TROP"],TROVADOR:[],TROVADORA:[],UNIVERSITARIA:["UNIVA"],UNIVERSITARIO:["UNIV"],USINEIRO:["USI"],VAQUEIRO:["VAQ"],VELHA:["VA"],VELHO:[],VENERAVEL:["VEN"],"VEREADOR CACIQUE":["VER CAC"],"VEREADOR DOUTOR":["VER DR"],"VEREADOR ENGENHEIRO":["VER ENG"],"VEREADOR IRMAO":["VER IMO"],"VEREADOR PROFESSOR":["VER PRF"],VEREADORA:["VERA"],VETERANO:["VET"],"VETERANOS CONSTITUCIONALISTAS":["VET CONST"],VETERINARIA:["VETA"],VETERINARIO:["VETO"],"VICE CONSUL":["V CSL"],"VICE GOVERNADOR":["V GOV"],VICENTINO:["VIC"],"VICE PREFEITO":["V PREF"],"VICE PRESIDENTE":["V PRES"],"VICE REI":["V REI"],VIGIA:["VGA"],VIGILANTE:["VGTE"],"VIGILANTE RODOVIARIO":["VGTE ROD"],VIOLEIRO:["VIOL"],VIOLINISTA:["VIOLIN"],VIOLONCELISTA:["VCTA"],VIOLONISTA:["VIOLON"],VIRGEM:["VIR"],VISCONDE:["VSC"],VISCONDESSA:["VSCA"],VIUVA:["VVA"],VO:[],VOLUNTARIA:["VLTA"],VOLUNTARIO:["VLTO"],VOLUNTARIOS:["VLTOS"],VOVO:[],"2 TENENTE PM":["2 TPM"]};function Yn(e,n){let i={...e};for(let[c,u]of Object.entries(n))i[c]=[...new Set([...e[c]??[],...u])];return i}var No=Yn({ACESSO:[],ALAMEDA:["AL","ALAM"],AUTOESTRADA:["AUTO ESTRADA","AUTO ESTR","AUTOESTR"],AVENIDA:["AV","AVA","AVE","AVEN"],"AVENIDA MARGINAL":["AVE MARG","AV MARG","AVA MARG","AVENIDA MARG"],AZINHAGA:["AZ"],BECO:["BC","BCO"],CALCADA:["CC"],CALCADINHA:["CACLCADINHA","CCNH"],CAMINHO:["CAM","CAMNO"],"CONJUNTO HABITACIONAL":["CONJ HAB"],ESTRADA:["ES","EST","ESTR"],"ESTRADA MARGINAL":["ESTR MARG","ESTRADA MARG"],"ESTRADA MUNICIPAL":["EM","E M","ESTR M","ESTRADA M"],"ESTRADA NACIONAL":["EN","E N","ESTR N","ESTRADA N"],"ESTRADA REGIONAL":["ER","E R","ESTR R","ESTRADA R"],ITINERARIO:[],"ITINERARIO COMPLEMENTAR":["IC","I C"],"ITINERARIO PRINCIPAL":["IP","I P"],LARGO:["LG","LGO","L"],LADEIRA:["LD","LAD"],PARADA:["PDA"],PASSAGEM:["PSG"],PRACA:["PC","PCA","PR"],PRACETA:["PCT","PCTA"],RAMPA:[],RETORNO:["RET"],RODOVIA:["ROD","RVIA","RDVIA"],RODOANEL:[],ROTUNDA:["ROT"],RUA:["R"],"RUA PARTICULAR":["R PART","RPART"],RUAS:["RS"],RUELA:[],TRANSVERSAL:["TRANSV"],TRAVESSA:["TV","TRAV","TR","TRV"],TUNEL:[],VIA:["V"],VIADUTO:["VD","VDTO"],VIELA:["VE"],VOLTA:[]},Do),Co={BAIRRO:["B","BO","BR","BRO"],CHACARA:["CH","CHAC"],CONJUNTO:["CJ","CONJ"],LUGAR:["LUG"],PARQUE:["PQ","PRQ","PARQ"],QUINTA:["QU","QTA"],SITIO:["SIT"],URBANIZACAO:["URB"],VILA:["VL","VLA"],ZONA:["ZN"]},Lo={"CAMARA MUNICIPAL":["CM","C M"]},wo={DIREITO:["DTO","DT"],ESQUERDO:["ESQ"],FRENTE:["FT"],PARTICULAR:["PART"],PONTO:["PTO","PNTO"],PROJECTADA:["PROJ"],PROLONGAMENTO:["PROLNG","PRL"]},Kn={ADVOGADO:["ADVO","ADV.O"],ALFERES:["ALF"],ALMIRANTE:["ALM"],ARCEBISPO:["ARCO","ARC.O"],ARQUITETO:["ARQ"],BARAO:["BAR"],BARONESA:[],BISPO:["BPO","B.PO"],BRIGADEIRO:["BRG","BRIG"],CACIQUE:["CAC"],CAPITAO:["CAP","CAPT"],"CAPITAO DE CORVETA":["CAP CORV"],"CAPITAO DE FRAGATA":["CAP FRAG"],"CAPITAO DE MAR E GUERRA":["CAP M G","CAP MG"],"CAPITAO TENENTE":["CAP TEN","CAP TTE"],CARDEAL:["CARD"],COMANDANTE:["CMDT"],COMENDADOR:["COMEND","CMDR","COMOR","COM.OR"],CONDE:["CDE"],CONDESSA:["CDESSA"],CONSELHEIRO:["CONS"],CORONEL:["COR","CEL"],"CONTRA ALMIRANTE":["C ALM"],DEPUTADO:["DEP"],DESEMBARGADOR:["DES"],DESEMBARGADORA:["DESA","DES.A"],DIACONO:["DIAC"],DIACONA:["DIACA"],DOM:[],DONA:["D\xAA","D.\xAA","D.A"],DOUTOR:["DR"],DOUTORA:["DR\xAA","DRA","D.R\xAA","D.RA"],DUQUE:["DQ"],DUQUESA:["DQSA","DQA"],EMBAIXADOR:["EMB"],EMINENCIA:["EMA","EM.A"],EMINENTISSIMO:["EMMO","EM.MO"],ENFERMEIRA:["ENF\xAA","ENFA","ENF.\xAA","ENF.A"],ENFERMEIRO:["ENF\xBA","ENF\xB0","ENFO","ENF","ENF.\xBA","ENF.\xB0","ENF.O"],ENGENHEIRA:["ENG\xAA","ENGA","ENG.\xAA","ENG.A"],ENGENHEIRO:["ENG\xBA","ENG\xB0","ENG.\xBA","ENG.\xB0","ENG","ENGO","ENG.O"],EXCELENCIA:["EX\xAA","EXA","EX.\xAA","EX.A"],EXCELENTISSIMA:["EXM\xAA","EXMA","EX.M\xAA","EX.MA"],EXCELENTISSIMO:["EXM\xBA","EXM\xB0","EXMO","EX.M\xBA","EX.M\xB0","EX.MO"],FREI:["FR"],GENERAL:["GEN","GAL","G.AL"],GOVERNADOR:["GOV","GOVDOR","GOVD.OR","GOV.DOR"],ILUSTRISSIMA:["ILM\xAA","ILMA","IL.M\xAA","IL.MA"],ILUSTRISSIMO:["ILM\xBA","ILM\xB0","ILMO","IL.M\xBA","IL.M\xB0","IL.MO"],INFANTE:["INF"],IRMA:["IM\xAA","IMA"],IRMAO:["IM\xBA","IM\xB0","IMO"],JUIZ:["JZ"],MAESTRA:["MTA","MTRA","MSTRA"],MAESTRO:["MTO","MTRO","MSTRO"],MAJOR:["MAJ"],"MAJOR BRIGADEIRO":["MAJ BRIG"],MARECHAL:["MAR","MAL","M.AL"],MARQUES:["MQ","MARQ"],MARQUESA:["MQSA","MARQA"],MADRE:[],MEDICO:["MED"],MESTRA:["M\xAA","MA","M.\xAA","M.A"],MESTRE:[],MINISTERIO:[],MINISTRO:["MIN"],MONSENHOR:["MONS"],"NOSSA SENHORA":["NSRA","NSA","N\xAA S\xAA","N\xAAS\xAA","N SR\xAA","N\xAA SR\xAA","N SA","N SRA","N.S.A.","N.S.A"],"NOSSO SENHOR":["NS","N.S.","N.S","N S"],PADRE:["PDE","PE","P.E"],PASTOR:["PR"],PREFEITO:["PREF"],PRESIDENTE:["PRESID","PRES"],PROFESSOR:["PROF","PROF\xBA","PROF\xB0"],PROFESSORA:["PROFA","PROF.A","PROF\xAA","PROF.\xAA"],PROFESSORAS:["PROFAS"],PROFESSORES:["PROFS"],REVERENDA:["REVDA","REV.DA"],REVERENDO:["REVDO","REV.DO"],REVERENDISSIMA:["REVMA","REV.MA"],REVERENDISSIMO:["REVMO","REV.MO"],SANTA:["ST\xAA","STA","ST.\xAA","ST.A"],SANTO:["ST\xBA","ST\xB0","STO","ST","ST.\xBA","ST.\xB0","ST.O"],SAO:[],SARGENTO:["SGT","SARG","SGTO","SARGTO"],"SARGENTO AJUDANTE":["SARG AJTE","SARG AJ.TE"],SECRETARIA:["SEC.A","SECR.A","SECRA"],SECRETARIO:["SEC","SECR"],SENADOR:["SEN"],SENHOR:["SR","S.R"],SENHORES:["SRS","S.RS"],SENHORA:["S\xAA","SA","SR\xAA","SRA","SR.\xAA","SR.A","S.RA","S.R\xAA"],SENHORAS:["SRAS","S.RAS"],SENHORITA:["SRTA","SR.TA"],SENHORITAS:["SRTAS","SR.TAS"],TENENTE:["TEN","TTE","T.TE"],"TENENTE CORONEL":["TEN C.EL","TEN CEL","TTE CEL","T.TE C.EL"],TESOUREIRO:["TES"],VEREADOR:["VER"],"VICE ALMIRANTE":["V ALM"],VIGARIO:["VIG","VIGO","VIG.O"],VISCONDE:["VISC","VDE","V.DE"],VISCONDESA:["VDESSA","V.DESSA"]};function Mo(e){let n=e.replaceAll(".","").replaceAll("\xAA","A").replace(/[\u00BA\u00B0]/g,"O");return n==="DA"?"DONA":n}var er=Object.fromEntries(Object.values(Kn).flatMap((e)=>e.flatMap((n)=>n.split(" "))).filter((e)=>/[.\u00AA\u00BA\u00B0]/.test(e)).map((e)=>[e.replace(/\.$/,""),Mo(e)])),tr=Yn(Object.fromEntries(Object.entries(Kn).map(([e,n])=>[e,[...new Set(n.map((i)=>i.split(" ").map((c)=>er[c.replace(/\.$/,"")]??c).join(" ")))]])),yo),Uo={JARDIM:["JD","JDM"],JARDINS:["JDS"],VILA:["VL","VLA"],HABITACIONAL:["HAB"],RESIDENCIAL:["RES"],CIDADE:["CID"],LOTEAMENTO:["LOT"],NUCLEO:["NUC"]};function ln(e){let n=new Map;for(let[i,c]of Object.entries(e))for(let u of c)if(!n.has(u))n.set(u,i);return n}var dn={...No,...Co,...Lo},Po=ln(dn),Jn=ln(wo),nr=ln(tr);nr.delete("ED");var Bo=new Set(Object.entries({...dn,...Uo}).flatMap(([e,n])=>[e,...n])),_o=Object.entries(dn).flatMap(([e,n])=>n.filter((i)=>i.includes(" ")).map((i)=>({alias:i,name:e}))).sort((e,n)=>n.alias.length-e.alias.length),xo=Object.entries(tr).flatMap(([e,n])=>[e,...n]).filter((e)=>e.includes(" ")).sort((e,n)=>n.length-e.length),Vo=new RegExp(`\\b(?:${xo.join("|")}|[A-Z0-9]+)\\b`,"g");function Fo(e){let n=e.normalize("NFD").replace(/\p{M}/gu,"").replace(/[a-z\u0080-\u{10FFFF}]/gu,(i)=>{let c=i.toUpperCase();return c.length===i.length?c:i});if(/[.\u00AA\u00BA\u00B0]/.test(e))n=(n.match(/[A-Z0-9\u00AA\u00BA\u00B0]+(?:\.[A-Z0-9\u00AA\u00BA\u00B0]+)*/g)??[]).map((i)=>er[i]??i).join(" ");return n.replace(/[^A-Z0-9]+/g," ").trim()}function vo(e){for(let{alias:n,name:i}of _o)if(e.startsWith(`${n} `))return i+e.slice(n.length);return e}function rr(e){let n=vo(Fo(e)).match(Vo)??[];return n.map((i,c)=>{if(c===n.length-1)return Jn.get(i)??i;let u=c===0?Po.get(i):void 0;if(u!==void 0)return u;let l=Jn.get(i)??nr.get(i);if(l!==void 0)return l;if(i==="D"&&(c===0||c===1&&Bo.has(n[0]??"")))return"DOM";return i}).join(" ")}function Vt(e){return rr(e).toLowerCase().match(/[a-z0-9]+/g)??[]}var Oe=5,q=256,X=32,re=16,K=Uint8Array.from([68,78,69,66,73,78,0,0]),ir=4294967295,fn=1e5,Me=100001,pe=10,Ze=32,Ft=0,Ie=2,me=255,Ue=2295,H=3,J=8,Pe=8,ee=256,ze=32,Y=["metadata","cepPrefixOffsets","cepSuffixes","logradouroIds","complementoBitmap","complementoRanks","complementoIds","bairroIds","municipalityIds","nomeBitmap","nomeRanks","nomeIds","municipalities","logradouroDictionary","complementoDictionary","bairroDictionary","municipioDictionary","ufDictionary","nomeDictionary","localidadeFlags","bairros","bairroFaixaOffsets","bairroFaixas","bairroAbreviadoDictionary","localidadeNomeBitmap","localidadeNomeRanks","localidadeNomeIds"];function ft(e){return Math.ceil(e/8)*8}function Qe(e){return Math.ceil(e/8)}function Xe(e,n){return Math.ceil(e*n/8)}function Je(){let e=new Uint8Array(256);for(let n=1;n<e.length;n++)e[n]=(e[n>>>1]??0)+(n&1);return e}function v(e){if(e<=255)return 1;if(e<=65535)return 2;if(e<=16777215)return 3;return 4}function ie(e,n){if(e!==1&&e!==2&&e!==3&&e!==4)throw Error(`Unsupported binary ${n} width: ${e}`);return e}function At(e){return e===4?4294967295:2**(e*8)-1}function An(e,n,i){if(!Number.isSafeInteger(e)||e<0||e>At(n))throw Error(`Binary ${i} exceeds the ${n}-byte unsigned integer limit: ${e}`)}function _(e,n,i){switch(i){case 1:return e.getUint8(n);case 2:return e.getUint16(n,!0);case 3:return e.getUint8(n)|e.getUint8(n+1)<<8|e.getUint8(n+2)<<16;case 4:return e.getUint32(n,!0)}}function F(e,n,i,c){if(An(i,c,"column value"),e[n]=i&255,c>1)e[n+1]=i>>>8&255;if(c>2)e[n+2]=i>>>16&255;if(c>3)e[n+3]=i>>>24&255}function or(e){if(e.byteLength!==K.length)return!1;return K.every((n,i)=>e[i]===n)}function ar(e,n,i){if(i<0||i>=1024)throw Error(`CEP suffix exceeds 10 bits: ${i}`);let c=n*10,u=c>>>3,l=c&7,d=i<<l;if(e[u]=(e[u]??0)|d&255,u+1<e.byteLength)e[u+1]=(e[u+1]??0)|d>>>8&255;if(u+2<e.byteLength)e[u+2]=(e[u+2]??0)|d>>>16&255}var de={RO:11,AC:12,AM:13,RR:14,PA:15,AP:16,TO:17,MA:21,PI:22,CE:23,RN:24,PB:25,PE:26,AL:27,SE:28,BA:29,MG:31,ES:32,RJ:33,SP:35,PR:41,SC:42,RS:43,MS:50,MT:51,GO:52,DF:53},vt=Object.keys(de),Go={RO:"Rond\xF4nia",AC:"Acre",AM:"Amazonas",RR:"Roraima",PA:"Par\xE1",AP:"Amap\xE1",TO:"Tocantins",MA:"Maranh\xE3o",PI:"Piau\xED",CE:"Cear\xE1",RN:"Rio Grande do Norte",PB:"Para\xEDba",PE:"Pernambuco",AL:"Alagoas",SE:"Sergipe",BA:"Bahia",MG:"Minas Gerais",ES:"Esp\xEDrito Santo",RJ:"Rio de Janeiro",SP:"S\xE3o Paulo",PR:"Paran\xE1",SC:"Santa Catarina",RS:"Rio Grande do Sul",MS:"Mato Grosso do Sul",MT:"Mato Grosso",GO:"Goi\xE1s",DF:"Distrito Federal"},Yu=new Map(vt.map((e)=>[$o(Go[e]),e])),Ku=new Map(vt.map((e)=>[de[e],e]));function sr(e){let n=e.trim().toUpperCase();if(!Object.hasOwn(de,n))return;return n}function $o(e){return e.trim().normalize("NFD").replace(/\p{M}/gu,"").toUpperCase()}var cr="DNESRCH1",ur=2,Et=80,Be=32;function lr(e){let n=e.checksum(),i=e.rowCount(),c=new Uint32Array(i),u=new Uint32Array(i),l=new Uint32Array(i*4),d=[],A=new Map,E=[],R=new Map,O=[],p=[[]],I=new Map([["",0]]),m=new Map,S=(N)=>{let P=m.get(N);if(!P)P=Vt(N),m.set(N,P);return P},h=0;for(let N of e.entries()){c[h]=Number(N.cep);let P=A.get(N.municipio_cod_ibge);if(P===void 0)P=d.length,A.set(N.municipio_cod_ibge,P),d.push({code:N.municipio_cod_ibge,uf:N.uf});u[h]=P;let le=new Set,xt=[Vt(N.logradouro??""),Vt(N.nome??""),S(N.bairro??""),S(N.municipio)];for(let[dt,B]of xt.entries()){let Q=B.join(" "),Ee=I.get(Q);if(Ee===void 0)Ee=p.length,I.set(Q,Ee),p.push(B.map((we)=>{let Re=R.get(we);if(Re===void 0)Re=E.length,R.set(we,Re),E.push(we),O.push([]);return Re}));l[h*4+dt]=Ee;for(let we of p[Ee])le.add(we)}for(let dt of le)O[dt].push(h);h++}let b=[...E.keys()].sort((N,P)=>E[N]<E[P]?-1:1),g=new Uint32Array(E.length);for(let[N,P]of b.entries())g[P]=N;let D=new TextEncoder().encode(JSON.stringify(b.map((N)=>E[N]))),y=[0],U=b.map((N)=>{let P=qo(O[N]);return y.push(y[y.length-1]+P.length),P}),L=y[y.length-1],V=v(p.length-1),W=v(E.length-1),C=v(d.length-1),x=p.reduce((N,P)=>N+P.length,0),j=Et+i*4,qe=j+i*C,ye=qe+i*4*V,Ne=ye+d.length*6,ue=Ne+(p.length+1)*4,lt=ue+x*W,k=lt+y.length*4,G=new Uint8Array(k+D.length+L+Be),ne=new DataView(G.buffer);G.set(new TextEncoder().encode(cr));for(let[N,P]of[[8,ur],[12,i],[16,D.length],[20,E.length],[24,L],[28,p.length],[64,x],[68,d.length]])ne.setUint32(N,P,!0);G.set(Buffer.from(n,"hex"),32),G.set([V,W,C],72);for(let N=0;N<i;N++){ne.setUint32(Et+N*4,c[N],!0),F(G,j+N*C,u[N],C);for(let P=0;P<4;P++)F(G,qe+(N*4+P)*V,l[N*4+P],V)}for(let[N,{code:P,uf:le}]of d.entries())ne.setUint32(ye+N*6,P,!0),G.set([le.charCodeAt(0),le.charCodeAt(1)],ye+N*6+4);let Ce=0;for(let[N,P]of p.entries()){ne.setUint32(Ne+N*4,Ce,!0);for(let le of P)F(G,ue+Ce++*W,g[le],W)}ne.setUint32(Ne+p.length*4,Ce,!0);for(let[N,P]of y.entries())ne.setUint32(lt+N*4,P,!0);G.set(D,k);let Le=k+D.length;for(let N of U)G.set(N,Le),Le+=N.length;return G.set(dr(G.subarray(0,-Be)),Le),Ho(G,n,i),G}function Ho(e,n,i){if(e.length<Et+Be||new TextDecoder().decode(e.subarray(0,8))!==cr)throw Error("Invalid address search index header");let c=new DataView(e.buffer,e.byteOffset,e.byteLength);if(c.getUint32(8,!0)!==ur)throw Error("Unsupported address search index version; rebuild the search index");if(!dr(e.subarray(0,-Be)).equals(e.subarray(-Be)))throw Error("Invalid address search index checksum");if(Buffer.from(e.subarray(32,64)).toString("hex")!==n||c.getUint32(12,!0)!==i)throw Error("Address search index belongs to a different database");let u=c.getUint32(16,!0),l=c.getUint32(20,!0),d=c.getUint32(24,!0),A=c.getUint32(28,!0),E=c.getUint32(64,!0),R=c.getUint32(68,!0),O=ie(c.getUint8(72),"search field"),p=ie(c.getUint8(73),"search token"),I=ie(c.getUint8(74),"search municipality"),m=Et+i*4,S=m+i*I,h=S+i*4*O,b=h+R*6,g=b+(A+1)*4,D=g+E*p,y=D+(l+1)*4,U=y+u;if(!A||!R||c.getUint8(75)!==0||c.getUint32(76,!0)!==0||U+d+Be!==e.length)throw Error("Invalid address search index size");let L=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(e.subarray(y,U)));if(!Array.isArray(L)||L.length!==l||L.some((C,x)=>typeof C!=="string"||!/^[a-z0-9]+$/.test(C)||x>0&&L[x-1]>=C))throw Error("Invalid address search vocabulary");let V={data:c,terms:L,offsets:D,postings:e.subarray(U,-Be),rowCount:i,rowMunicipalities:m,rowFields:S,fieldOffsets:b,fieldCount:A,fieldTokens:g,fieldWidth:O,tokenWidth:p,municipalityWidth:I,municipalityCodes:[],municipalityUfs:[],municipalityByCode:new Map};for(let C=0;C<R;C++){let x=c.getUint32(h+C*6,!0),j=String.fromCharCode(c.getUint8(h+C*6+4),c.getUint8(h+C*6+5));if(x<1e6||x>9999999||!vt.includes(j)||V.municipalityByCode.has(x))throw Error("Invalid address search municipality");V.municipalityCodes.push(x),V.municipalityUfs.push(j),V.municipalityByCode.set(x,C)}let W=-1;for(let C=0;C<i;C++){let x=c.getUint32(Et+C*4,!0);if(x<=W||x>99999999)throw Error("Invalid address search CEP");if(W=x,jo(V,C)>=R)throw Error("Invalid address search municipality reference");for(let j=0;j<4;j++)if(_(c,S+(C*4+j)*O,O)>=A)throw Error("Invalid address search field reference")}if(c.getUint32(b,!0)!==0||c.getUint32(b+A*4,!0)!==E)throw Error("Invalid address search field offsets");for(let C=0;C<A;C++){let x=c.getUint32(b+C*4,!0),j=c.getUint32(b+(C+1)*4,!0);if(j<x||j>E)throw Error("Invalid address search field range")}for(let C=0;C<E;C++)if(_(c,g+C*p,p)>=l)throw Error("Invalid address search field token");if(c.getUint32(D,!0)!==0||c.getUint32(D+l*4,!0)!==d)throw Error("Invalid address search posting offsets");for(let C=0;C<l;C++)Wo(V,C);return V}function Wo(e,n,i){let c=e.data.getUint32(e.offsets+n*4,!0),u=e.data.getUint32(e.offsets+(n+1)*4,!0);if(u<=c||u>e.postings.length)throw Error("Invalid address search posting range");let l=-1;while(c<u){let d=0,A=1,E;do{if(c>=u||A>268435456)throw Error("Invalid address search posting encoding");E=e.postings[c++],d+=(E&127)*A,A*=128}while(E&128);let R=l+d;if(d===0||R>=e.rowCount)throw Error("Invalid address search posting row");i?.(R),l=R}}function jo(e,n){return _(e.data,e.rowMunicipalities+n*e.municipalityWidth,e.municipalityWidth)}function qo(e){let n=[],i=-1;for(let c of e){let u=c-i;while(u>=128)n.push(u%128|128),u=Math.floor(u/128);n.push(u),i=c}return new Uint8Array(n)}function dr(e){return ko("sha256").update(e).digest()}import{readFileSync as Ma}from"fs";class Se extends Error{constructor(e,n){super(e,n);this.name=new.target.name}}class Rt extends Se{path;code="IO_ERROR";constructor(e,n){super(`Unable to read binary database: ${e}`,n);this.path=e}}class T extends Se{code="INVALID_FORMAT";constructor(e,n){super(e,n)}}class Gt extends Se{actualVersion;supportedVersion;code="UNSUPPORTED_VERSION";constructor(e,n){super(`Unsupported binary database version: ${e}. Rebuild the database with build --force.`);this.actualVersion=e;this.supportedVersion=n}}class $t extends Se{code="READER_CLOSED";constructor(){super("Binary database is closed")}}var Ot=8,Ye=3,Ke=1<<Ye,Zo=Je();function Ar(e,n,i){let c=new DataView(e.buffer,e.byteOffset,e.byteLength),u=[],l=[],d=-1;for(let L=0;L<n;L++){let V=_(c,L*i,i);if(V!==d)u.push(L),l.push(V),d=V}let A=u.length,E=Math.floor(Math.log2(n/A)),R=2**E,O=Math.ceil(n/R),p=O+A,I=Math.ceil(A*E/8),m=Math.ceil(p/8),S=Math.ceil(O/Ke),h=Ot+I,b=h+m,g=b+S*4,D=new Uint8Array(g+A*i),y=new DataView(D.buffer);y.setUint32(0,A,!0),y.setUint8(4,E),y.setUint8(5,Ye),y.setUint8(6,i);for(let L=0;L<A;L++){let V=u[L]??0;zo(D,Ot,L*E,E,V%R);let W=Math.floor(V/R)+L,C=h+(W>>>3);D[C]=(D[C]??0)|1<<(W&7),F(D,g+L*i,l[L]??0,i)}let U=0;for(let L=0;L<p;L++)if(((D[h+(L>>>3)]??0)&1<<(L&7))===0){if(U%Ke===0)y.setUint32(b+(U>>>Ye)*4,L,!0);U++}return D}function Er(e,n,i,c){let u=e.getUint32(n.offset,!0),l=e.getUint8(n.offset+4),d=Math.ceil(i/2**l),A=d+u,E=n.offset+Ot,R=E+Math.ceil(u*l/8),O=R+Math.ceil(A/8),p=O+Math.ceil(d/Ke)*4;return{highBitCount:A,highOffset:R,idWidth:c,idsOffset:p,lowBits:l,lowOffset:E,runCount:u,samplesOffset:O,zeroCount:d}}function Rr(e,n,i,c,u){if(n.length<Ot)throw new T("Binary neighborhood runs are truncated");let l=e.getUint32(n.offset,!0),d=e.getUint8(n.offset+4);if(l<1||l>i||d>31||e.getUint8(n.offset+5)!==Ye||e.getUint8(n.offset+6)!==c||e.getUint8(n.offset+7)!==0)throw new T("Invalid binary neighborhood run header");let A=2**d,E=Math.ceil(i/A),R=E+l,O=Math.ceil(l*d/8),p=Math.ceil(R/8),I=Math.ceil(E/Ke),m=n.offset+Ot,S=m+O,h=S+p,b=h+I*4;if(b+l*c!==n.offset+n.length)throw new T("Invalid binary neighborhood run length");let g=0,D=0,y=-1,U=-1;for(let L=0;L<R;L++){if((e.getUint8(S+(L>>>3))&1<<(L&7))===0){if(g>=E)throw new T("Invalid binary neighborhood run bitmap");if(g%Ke===0&&e.getUint32(h+(g>>>Ye)*4,!0)!==L)throw new T("Invalid binary neighborhood run samples");g++;continue}if(D>=l)throw new T("Invalid binary neighborhood run bitmap");let W=pr(e,m,D*d,d),C=g*A+W,x=_(e,b+D*c,c);if(D===0&&C!==0||C<=y||C>=i||x>u||x===U)throw new T("Invalid binary neighborhood run");y=C,U=x,D++}if(R%8!==0){let L=255<<(R&7);if((e.getUint8(S+(R>>>3))&L)!==0)throw new T("Invalid binary neighborhood run padding")}return{highBitCount:R,highOffset:S,idWidth:c,idsOffset:b,lowBits:d,lowOffset:m,runCount:l,samplesOffset:h,zeroCount:E}}function Or(e,n,i){let c=2**n.lowBits,u=Math.floor(i/c),l=fr(e,n,u)-u,d=u===0?0:fr(e,n,u-1)-(u-1),A=i%c,E=d,R=l;while(E<R){let p=E+(R-E>>>1);if(pr(e,n.lowOffset,p*n.lowBits,n.lowBits)<=A)E=p+1;else R=p}let O=E-1;return _(e,n.idsOffset+O*n.idWidth,n.idWidth)}function fr(e,n,i){let c=i>>>Ye,u=e.getUint32(n.samplesOffset+c*4,!0),l=i-c*Ke;if(l===0)return u;u++;while(l>0){let d=u&7,A=8-d,E=(1<<A)-1,R=~(e.getUint8(n.highOffset+(u>>>3))>>>d)&E,O=Zo[R]??0;if(O>=l)for(let p=0;l>0;p++){if(R&1<<p)l--;u++}else l-=O,u+=A}return u-1}function pr(e,n,i,c){let u=0;for(let l=0;l<c;l++){let d=i+l;if(e.getUint8(n+(d>>>3))&1<<(d&7))u+=2**l}return u}function zo(e,n,i,c,u){for(let l=0;l<c;l++)if(Math.floor(u/2**l)%2){let d=i+l,A=n+(d>>>3);e[A]=(e[A]??0)|1<<(d&7)}}function oe(e){return Number.isInteger(e)&&e>0&&e<=4294967295}var et=8,En=8,tt=1<<En;function Ir(e,n,i){let c=new DataView(e.buffer,e.byteOffset,e.byteLength),u=[],l=[],d=[],A=-1,E=-1;for(let b=0;b<n.length;b++){let g=_(c,b*i,i),D=n[b]??0;if(g!==A||D!==E)u.push(b),l.push(g),d.push(D),A=g,E=D}let R=u.length,O=Math.ceil(n.length/tt),p=et+(O+1)*4,I=p+R*4,m=new Uint8Array(I+R*i),S=new DataView(m.buffer);S.setUint32(0,R,!0),S.setUint8(4,En);let h=0;for(let b=0;b<O;b++){while(h+1<R&&(u[h+1]??0)<=b*tt)h++;S.setUint32(et+b*4,h,!0)}S.setUint32(et+O*4,R,!0);for(let b=0;b<R;b++)S.setUint32(p+b*4,u[b]??0,!0),F(m,I+b*i,l[b]??0,i);return{ids:m,flags:Uint8Array.from(d)}}function mr(e,n,i){let c=e.getUint32(n.offset,!0),u=n.offset+et,l=u+(Math.ceil(i/tt)+1)*4;return{count:c,directoryOffset:u,startsOffset:l,idsOffset:l+c*4}}function Sr(e,n,i,c){if(n.length<et)throw new T("Binary locality runs are truncated");let u=e.getUint32(n.offset,!0);if(u===0||u>i||e.getUint32(n.offset+4,!0)!==En)throw new T("Invalid binary locality run header");let l=Math.ceil(i/tt),d=n.offset+et,A=d+(l+1)*4,E=A+u*4;if(E+u*c!==n.offset+n.length)throw new T("Invalid binary locality run length");let R=-1;for(let p=0;p<u;p++){let I=e.getUint32(A+p*4,!0);if(p===0&&I!==0||I<=R||I>=i)throw new T("Invalid binary locality run boundary");R=I}let O=0;for(let p=0;p<l;p++){while(O+1<u&&e.getUint32(A+(O+1)*4,!0)<=p*tt)O++;if(e.getUint32(d+p*4,!0)!==O)throw new T("Invalid binary locality run directory")}if(e.getUint32(d+l*4,!0)!==u)throw new T("Invalid binary locality run sentinel");return{count:u,directoryOffset:d,startsOffset:A,idsOffset:E}}function hr(e,n,i){let c=Math.floor(i/tt),u=e.getUint32(n.directoryOffset+c*4,!0),l=Math.min(n.count,e.getUint32(n.directoryOffset+(c+1)*4,!0)+1);while(u+1<l){let d=u+(l-u>>>1);if(e.getUint32(n.startsOffset+d*4,!0)<=i)u=d;else l=d}return u}function nt(e){return Math.max(1,Math.ceil(Math.log2(e+1)))}function kt(e,n,i,c){let u=i*c,l=n+Math.floor(u/8),d=u&7,A=d+c,E=e.getUint8(l);if(A>8)E|=e.getUint8(l+1)<<8;if(A>16)E|=e.getUint8(l+2)<<16;if(A>24)E|=e.getUint8(l+3)<<24;let R=E>>>d&4294967295>>>32-c;if(A>32)R+=(e.getUint8(l+4)&(1<<A-32)-1)*2**(32-d);return R>>>0}function Tr(e,n,i,c){if(!Number.isInteger(c)||c<0||c>=2**i||i<1||i>32)throw Error(`Invalid ${i}-bit column value: ${c}`);let u=n*i,l=Math.floor(u/8),d=u&7,A=c*2**d,E=Math.ceil((d+i)/8);for(let R=0;R<E;R++)e[l+R]=(e[l+R]??0)|Math.floor(A/2**(R*8))&255}var pt="4",rt=["M","D","P"],it=["municipio","distrito","povoado"],ot=["sem_codificacao_por_logradouro","codificada_por_logradouro","inserida_na_codificacao_por_logradouro","em_codificacao_por_logradouro"],Qo=[{name:"log_localidade",originalName:"log_localidade",sourceFields:{locNu:0,uf:1,nome:2,cep:3,situacao:4,tipo:5,locNuSub:6,munNu:8},columns:[]},{name:"log_bairro",originalName:"log_bairro",sourceFields:{baiNu:0,uf:1,locNu:2,bairro:3,abreviado:4},columns:[]},{name:"log_faixa_bairro",originalName:"log_faixa_bairro",sourceFields:{baiNu:0,cepInicial:1,cepFinal:2},columns:[]},{name:"log_cpc",originalName:"log_cpc",sourceFields:{uf:1,locNu:2,nome:3,endereco:4,cep:5},columns:[]},{name:"log_logradouro",originalName:"log_logradouro",fileGlob:"LOG_LOGRADOURO_*.TXT",sourceFields:{uf:1,locNu:2,baiNuIni:3,logNo:5,cep:7,tloTx:8,logStaTlo:9},columns:[]},{name:"log_grande_usuario",originalName:"log_grande_usuario",sourceFields:{uf:1,locNu:2,baiNu:3,nome:5,endereco:6,cep:7},columns:[]},{name:"log_unid_oper",originalName:"log_unid_oper",sourceFields:{uf:1,locNu:2,baiNu:3,nome:5,endereco:6,cep:7},columns:[]},{name:"bairros",originalName:"bairros",fileGlob:null,columns:[{name:"bairro_id",type:"INTEGER",primaryKey:!0,check:"bairro_id > 0"},{name:"localidade_id",type:"INTEGER",notNull:!0,check:"localidade_id > 0"},{name:"uf",type:"TEXT",notNull:!0},{name:"nome",type:"TEXT",notNull:!0},{name:"nome_abreviado",type:"TEXT"}]},{name:"bairro_faixas",originalName:"bairro_faixas",fileGlob:null,withoutRowid:!0,columns:[{name:"bairro_id",type:"INTEGER",primaryKey:!0,references:{table:"bairros",column:"bairro_id"}},{name:"cep_inicial",type:"TEXT",primaryKey:!0,check:"length(cep_inicial) = 8 AND cep_inicial NOT GLOB '*[^0-9]*'"},{name:"cep_final",type:"TEXT",primaryKey:!0,check:"length(cep_final) = 8 AND cep_final NOT GLOB '*[^0-9]*' AND cep_inicial <= cep_final"}]},{name:"cep_unificado",originalName:"cep_unificado",fileGlob:null,unifiedTable:!0,columns:[{name:"cep",type:"TEXT",primaryKey:!0,comment:"Cont\xE9m somente os oito d\xEDgitos do CEP, sem separadores."},{name:"logradouro",type:"TEXT"},{name:"complemento",type:"TEXT"},{name:"bairro_id",type:"INTEGER",references:{table:"bairros",column:"bairro_id"}},{name:"localidade_nome",type:"TEXT",comment:"Original district or village name for a locality-wide CEP.",check:"localidade_nome IS NULL OR (bairro_id IS NULL AND localidade_tipo IN ('D', 'P'))"},{name:"municipio",type:"TEXT",notNull:!0},{name:"municipio_cod_ibge",type:"INTEGER",notNull:!0},{name:"uf",type:"TEXT",notNull:!0},{name:"nome",type:"TEXT"},{name:"localidade_situacao",type:"INTEGER",notNull:!0,check:"localidade_situacao IN (0, 1, 2, 3)"},{name:"localidade_tipo",type:"TEXT",notNull:!0,check:"localidade_tipo IN ('M', 'D', 'P')"}]}];function br(e={}){return Qo.map((n)=>({...n,name:e[n.originalName]??n.name,columns:n.columns.map((i)=>({...i,...i.references?{references:{...i.references,table:e[i.references.table]??i.references.table}}:{}})),sourceFields:n.sourceFields?{...n.sourceFields}:void 0}))}function _e(e){let n=e.find((i)=>i.unifiedTable);if(!n)throw Error("Unified schema table not found");return n}function It(e){return e.filter((n)=>n.columns.length>0)}function mt(e){if(e.unifiedTable||e.fileGlob===null)return null;return e.fileGlob??`${e.originalName.toUpperCase()}.TXT`}function xe(e,n){if(!e.sourceFields)throw Error(`Source fields for table '${e.originalName}' not found`);return n.map((i)=>{let c=e.sourceFields?.[i];if(c===void 0)throw Error(`Source field '${i}' for table '${e.originalName}' not found`);return c})}var gr=new TextDecoder("utf-8",{fatal:!0});function Dr(e){try{if(!(e instanceof Uint8Array))throw new T("Binary database bytes must be a Uint8Array");let n=new DataView(e.buffer,e.byteOffset,e.byteLength),i=Xo(n);Jo(e,i);let c=Yo(e,n,i);Ko(c.uf);let u=ra(e,n,i,c),l=ia(n,i,c),d=oa(e,n,i,c),A=Rr(n,i.sections.bairroIds,i.rowCount,u.idWidth,u.count),E=Sr(n,i.sections.municipalityIds,i.rowCount,i.municipalityIdWidth);sa(n,i,A,E),la(n,i,u),da(e,n,i),fa(e,n,i,c.logradouro),Aa(n,i,c,u,A,E,d,l),pa(e,i.sections.metadata)}catch(n){if(n instanceof T)throw n;let i=n instanceof Error?n.message:String(n);throw new T(`Unable to validate binary database: ${i}`,{cause:n})}}function Xo(e){if(e.byteLength<q+X)throw new T("Binary database header is truncated");for(let i=0;i<K.length;i++)if(e.getUint8(i)!==K[i])throw new T("Invalid binary database magic");if(e.getUint16(8,!0)!==Oe)throw new T("Unsupported binary database version");if(e.getUint16(10,!0)!==q)throw new T("Unsupported binary database header size");if(e.getUint8(22)!==Pe||e.getUint8(23)!==H)throw new T("Unsupported binary database block layout");if(e.getUint16(24,!0)!==Y.length)throw new T("Unsupported binary database section table");let n={};for(let[i,c]of Y.entries()){let u=ze+i*8;n[c]={length:e.getUint32(u+4,!0),offset:e.getUint32(u,!0)}}return{cepPrefixOffsetWidth:ie(e.getUint8(20),"CEP prefix offset"),fileSize:e.getUint32(16,!0),municipalityCount:e.getUint32(28,!0),municipalityIdWidth:ie(e.getUint8(21),"municipality id"),rowCount:e.getUint32(12,!0),sections:n}}function Jo(e,n){let i=e.byteLength-X;if(n.fileSize!==e.byteLength)throw new T(`Binary database size mismatch: header=${n.fileSize}, actual=${e.byteLength}`);if(i<q||i%8!==0)throw new T("Binary database payload has an invalid alignment");if(!n.rowCount||!n.municipalityCount)throw new T("Binary database must contain rows and municipalities");if(n.rowCount>At(n.cepPrefixOffsetWidth))throw new T("Binary row count does not fit the CEP prefix offset width");if(n.municipalityCount>At(n.municipalityIdWidth))throw new T("Binary municipality count does not fit its id width");if(n.cepPrefixOffsetWidth!==v(n.rowCount)||n.municipalityIdWidth!==v(n.municipalityCount))throw new T("Binary database uses a noncanonical integer width");at(e,26,28,"binary header reserved bytes"),at(e,248,q,"binary header reserved bytes");let c=q;for(let l of Y){let d=n.sections[l];if(Ia(i,d,l),d.offset%8!==0||d.offset<c)throw new T(`Binary section is out of order or unaligned: ${l}`);at(e,c,d.offset,`${l} section padding`),c=d.offset+d.length}if(at(e,c,i,"final binary section padding"),ft(c)!==i)throw new T("Binary database footer is not after aligned section data");fe(n.sections.cepPrefixOffsets,Me*n.cepPrefixOffsetWidth,"CEP prefix directory"),fe(n.sections.cepSuffixes,Xe(n.rowCount,pe),"CEP suffix column");for(let l of["complementoBitmap","nomeBitmap","localidadeNomeBitmap"])fe(n.sections[l],Qe(n.rowCount),"nullable bitmap");let u=(Math.ceil(n.rowCount/ee)+1)*4;for(let l of["complementoRanks","nomeRanks","localidadeNomeRanks"])fe(n.sections[l],u,"sparse rank index")}function Yo(e,n,i){return{bairro:Ve(e,n,i.sections.bairroDictionary,"bairro",!1),bairroAbreviado:Ve(e,n,i.sections.bairroAbreviadoDictionary,"bairro abbreviation",!1),complemento:Ve(e,n,i.sections.complementoDictionary,"complemento",!1),logradouro:Ve(e,n,i.sections.logradouroDictionary,"logradouro",!0),municipio:Ve(e,n,i.sections.municipioDictionary,"municipio",!1),nome:Ve(e,n,i.sections.nomeDictionary,"nome",!1),uf:Ve(e,n,i.sections.ufDictionary,"uf",!1)}}function Ko(e){for(let[n,i]of e.values.entries())Rn(i,n)}function Rn(e,n){let i=sr(e);if(i===void 0)throw new T(`Invalid binary UF dictionary entry: ${n}`);if(e!==i)throw new T(`Binary UF dictionary entry is not canonical: ${n}`);return i}function Ve(e,n,i,c,u){if(i.length<Ze)throw new T(`Binary ${c} dictionary is truncated`);let l=n.getUint32(i.offset,!0),d=n.getUint32(i.offset+4,!0),A=n.getUint32(i.offset+8,!0),E=n.getUint32(i.offset+12,!0),R=n.getUint32(i.offset+16,!0),O=n.getUint32(i.offset+20,!0),p=n.getUint32(i.offset+24,!0),I=ie(n.getUint8(i.offset+28),`${c} dictionary id`),m=n.getUint8(i.offset+30),S=n.getUint8(i.offset+31);if(m!==Ft&&(m!==Ie||!u)||(m===Ft?S!==0:S!==1&&S!==2))throw new T(`Unsupported binary ${c} dictionary codec or length width`);if(n.getUint8(i.offset+29)!==H)throw new T(`Unsupported binary ${c} dictionary block size`);let h=Math.ceil(l/J);if(d!==h||l>At(I))throw new T(`Binary ${c} dictionary has an invalid count or id width`);let b=S===2?2:1,g=m===Ie?Ue:0;if(A!==Ze||E!==A+d*4||R!==E+l*b||O!==R+l+g||O>i.length||p!==i.length-O||I!==v(l))throw new T(`Binary ${c} dictionary has an invalid layout`);let D={blockCount:d,blockOffsetsOffset:i.offset+A,codec:m,count:l,idWidth:I,lengthWidth:b,lengthsOffset:i.offset+E,prefixesOffset:i.offset+R,region:i,suffixDataLength:p,suffixDataOffset:i.offset+O,symbolsOffset:i.offset+R+l,values:[]};return ea(e,n,D,c),D.values=ta(e,n,D,c),D}function ea(e,n,i,c){if(i.blockCount&&n.getUint32(i.blockOffsetsOffset,!0)!==0)throw new T(`Binary ${c} dictionary has an invalid first block offset`);let u=0;for(let l=0;l<i.blockCount;l++){let d=n.getUint32(i.blockOffsetsOffset+l*4,!0);if(d<u||d>i.suffixDataLength)throw new T(`Binary ${c} dictionary has invalid block offsets`);u=d}if(i.codec===Ie)for(let l=0;l<me;l++){let d=e[i.symbolsOffset+l]??0;if(d>8)throw new T(`Invalid binary ${c} FSST symbol length`);let A=i.symbolsOffset+me+l*8;at(e,A+d,A+8,`binary ${c} FSST symbol padding`)}if(i.blockCount===0&&i.suffixDataLength!==0)throw new T(`Binary ${c} dictionary has unexpected payload`)}function ta(e,n,i,c){let u=[],l=c==="bairro"||c==="municipio"||c==="uf",d;for(let A=0;A<i.blockCount;A++){let E=A*J,R=Math.min(i.count,E+J),O=n.getUint32(i.blockOffsetsOffset+A*4,!0),p=A+1<i.blockCount?n.getUint32(i.blockOffsetsOffset+(A+1)*4,!0):i.suffixDataLength,I=i.suffixDataOffset+O,m=i.suffixDataOffset+p,S=new Uint8Array;for(let h=E;h<R;h++){let b=e[i.prefixesOffset+h]??0;if(h===E&&b!==0||b>S.byteLength)throw new T(`Invalid binary ${c} dictionary prefix: ${h}`);let g;if(i.codec===Ft){let y=e[i.lengthsOffset+h]??0;if(b>y)throw new T(`Invalid binary ${c} dictionary length: ${h}`);let U=y-b;if(I<i.suffixDataOffset||I+U>m)throw new T(`Invalid binary ${c} dictionary suffix: ${h}`);g=new Uint8Array(y),g.set(S.subarray(0,b)),g.set(e.subarray(I,I+U),b),I+=U}else{let y=i.lengthWidth===1?e[i.lengthsOffset+h]??0:n.getUint16(i.lengthsOffset+h*2,!0);if(I<i.suffixDataOffset||I+y>m)throw new T(`Invalid binary ${c} FSST suffix: ${h}`);if(y>510)throw new T(`Binary ${c} FSST suffix is too long: ${h}`);g=na(e,i,I,y,S,b,c,h),I+=y}let D;try{D=gr.decode(g)}catch(y){throw new T(`Invalid UTF-8 in binary ${c} dictionary entry: ${h}`,{cause:y})}if(d!==void 0&&d>=D)throw new T(`Binary ${c} dictionary is not strictly sorted: ${h}`);if(l)u.push(D);d=D,S=g}if(I!==m)throw new T(`Binary ${c} dictionary block length mismatch`)}return u}function na(e,n,i,c,u,l,d,A){let E=new Uint8Array(255);E.set(u.subarray(0,l));let R=l,O=i,p=i+c;while(O<p){let I=e[O++]??0;if(I===255){if(O>=p||R>=255)throw new T(`Invalid binary ${d} FSST escape: ${A}`);E[R++]=e[O++]??0;continue}let m=e[n.symbolsOffset+I]??0;if(!m||m>8||R+m>255)throw new T(`Invalid binary ${d} FSST symbol: ${A}`);let S=n.symbolsOffset+me+I*8;E.set(e.subarray(S,S+m),R),R+=m}return E.slice(0,R)}function ra(e,n,i,c){let u=i.sections.bairros;if(u.length<re)throw new T("Binary neighborhood table is truncated");let l=n.getUint32(u.offset,!0),d=ie(n.getUint8(u.offset+4),"original neighborhood id"),A=ie(n.getUint8(u.offset+5),"original locality id"),E=d+A+c.bairro.idWidth+c.bairroAbreviado.idWidth+c.uf.idWidth;fe(u,re+l*E,"neighborhood table"),at(e,u.offset+6,u.offset+re,"neighborhood table reserved bytes");let R=u.offset+re,O=0,p=0,I=0;for(let m=0;m<l;m++){let S=R+m*E,h=_(n,S,d);S+=d;let b=_(n,S,A);S+=A;let g=_(n,S,c.bairro.idWidth);S+=c.bairro.idWidth;let D=_(n,S,c.bairroAbreviado.idWidth);S+=c.bairroAbreviado.idWidth;let y=_(n,S,c.uf.idWidth);if(h<=O||b===0||g===0||g>c.bairro.count||D>c.bairroAbreviado.count||y===0||y>c.uf.count)throw new T(`Invalid binary neighborhood record: ${m}`);if(!c.bairro.values[g-1])throw new T(`Binary neighborhood has an empty name: ${m}`);Rn(c.uf.values[y-1]??"",m),O=h,p=Math.max(p,h),I=Math.max(I,b)}if(d!==v(p)||A!==v(I))throw new T("Binary neighborhood table uses a noncanonical integer width");return{count:l,idWidth:v(l),localidadeIdWidth:A,originalIdWidth:d,recordWidth:E,recordsOffset:R}}function ia(e,n,i){let c=3+i.municipio.idWidth+i.uf.idWidth,u=n.sections.municipalities;fe(u,n.municipalityCount*c,"municipalities");let l=new Uint32Array(n.municipalityCount+1),d=0;for(let A=0;A<n.municipalityCount;A++){let E=u.offset+A*c,R=_(e,E,3),O=_(e,E+3,i.municipio.idWidth),p=_(e,E+3+i.municipio.idWidth,i.uf.idWidth);if(R<1e6||R>9999999||R<=d)throw new T(`Invalid binary IBGE municipality code: ${R}`);if(O===0||O>i.municipio.count||p===0||p>i.uf.count)throw new T(`Invalid binary municipality record: ${A}`);if(!i.municipio.values[O-1])throw new T(`Binary municipality has an empty name: ${A}`);let I=Rn(i.uf.values[p-1]??"",A);if(Math.floor(R/1e5)!==de[I])throw new T(`IBGE municipality code does not match UF: ${R} (${I}, ${de[I]})`);l[A+1]=p,d=R}return{ufIds:l}}function oa(e,n,i,c){let u=new Uint32Array(i.rowCount);for(let[l,d,A]of[["complemento",c.complemento,void 0],["nome",c.nome,void 0],["localidadeNome",c.bairro,u]])aa(e,n,i.rowCount,i.sections[`${l}Bitmap`],i.sections[`${l}Ranks`],i.sections[`${l}Ids`],d.idWidth,d.count,l,A);return{localidadeNome:u}}function aa(e,n,i,c,u,l,d,A,E,R){if(l.length%d!==0)throw new T(`Binary ${E} sparse ids have an invalid length`);let O=Math.ceil(i/ee),p=0;for(let m=0;m<O;m++){let S=p;if(n.getUint32(u.offset+m*4,!0)!==S)throw new T(`Binary ${E} sparse rank mismatch: ${m}`);let b=m*ee,g=Math.min(i,b+ee);for(let D=b;D<g;D++){if(((e[c.offset+(D>>>3)]??0)&1<<(D&7))===0)continue;if(p>=l.length/d)throw new T(`Binary ${E} sparse id index is outside the column`);let U=_(n,l.offset+p*d,d);if(U===0||U>A)throw new T(`Invalid binary ${E} sparse id: ${U}`);if(R)R[D]=U;p++}}if(n.getUint32(u.offset+O*4,!0)!==p||l.length!==p*d)throw new T(`Binary ${E} sparse column has an invalid final rank`);ma(e,c,i,E)}function sa(e,n,i,c){fe(n.sections.localidadeFlags,c.count,"locality indicators"),ca(e,i),ua(e,n.sections.localidadeFlags,n,c)}function ca(e,n){let i=n.runCount*n.lowBits;if(i%8!==0&&(e.getUint8(n.lowOffset+Math.floor(i/8))&255<<(i&7))!==0)throw new T("Invalid binary neighborhood run low-bit padding")}function ua(e,n,i,c){let u=-1,l=-1;for(let d=0;d<c.count;d++){let A=_(e,c.idsOffset+d*i.municipalityIdWidth,i.municipalityIdWidth),E=e.getUint8(n.offset+d);if(A===0||A>i.municipalityCount||(E&3)>=ot.length||E>>>2>=it.length||A===u&&E===l)throw new T(`Invalid binary locality run: ${d}`);u=A,l=E}}function la(e,n,i){let{bairroFaixaOffsets:c,bairroFaixas:u}=n.sections;if(fe(c,(i.count+1)*4,"neighborhood range offsets"),u.length%8!==0||e.getUint32(c.offset,!0)!==0)throw new T("Invalid binary neighborhood range layout");let l=u.length/8,d=0;for(let A=0;A<i.count;A++){let E=e.getUint32(c.offset+(A+1)*4,!0);if(E<d||E>l)throw new T("Invalid binary neighborhood range offsets");let R=-1,O=-1;for(let p=d;p<E;p++){let I=e.getUint32(u.offset+p*8,!0),m=e.getUint32(u.offset+p*8+4,!0);if(I>m||m>99999999||I<R||I===R&&m<=O)throw new T("Invalid binary neighborhood CEP range");R=I,O=m}d=E}if(d!==l)throw new T("Unreferenced binary neighborhood CEP ranges")}function da(e,n,i){let c=i.sections.cepPrefixOffsets,u=new Uint32Array(Me),l=0;for(let A=0;A<Me;A++){let E=_(n,c.offset+A*i.cepPrefixOffsetWidth,i.cepPrefixOffsetWidth);if(E<l||E>i.rowCount)throw new T(`Invalid binary CEP prefix boundary: ${A}`);u[A]=E,l=E}if(u[0]!==0||u[fn]!==i.rowCount)throw new T("Binary CEP prefix directory has invalid boundaries");for(let A=0;A<fn;A++){let E=u[A]??0,R=u[A+1]??0,O=-1;for(let p=E;p<R;p++){let I=Sa(e,i.sections.cepSuffixes.offset,p);if(I>999||I<=O)throw new T(`Binary CEP suffixes are not strictly ordered: ${p}`);O=I}}let d=i.rowCount*pe;if(d%8!==0){if(((e[i.sections.cepSuffixes.offset+i.sections.cepSuffixes.length-1]??0)&255<<(d&7))!==0)throw new T("Invalid binary CEP suffix padding")}}function fa(e,n,i,c){let u=i.sections.logradouroIds,l=nt(c.count);fe(u,Xe(i.rowCount,l),"logradouro ids");for(let A=0;A<i.rowCount;A++){let E=kt(n,u.offset,A,l);if(E>c.count)throw new T(`Invalid binary logradouro id: ${E}`)}let d=i.rowCount*l;if(d%8!==0){if(((e[u.offset+u.length-1]??0)&255<<(d&7))!==0)throw new T("Invalid binary logradouro id padding")}}function Aa(e,n,i,c,u,l,d,A){let E=Ra(e,u),R=Oa(e,n,l),O=0,p=0;for(let I=0;I<n.rowCount;I++){while(O+1<E.starts.length&&(E.starts[O+1]??0)<=I)O++;while(p+1<R.starts.length&&(R.starts[p+1]??0)<=I)p++;let m=E.ids[O]??0,S=R.ids[p]??0,b=(R.flags[p]??0)>>>2;if((d.localidadeNome[I]??0)!==0&&(m!==0||b===0))throw new T(`Invalid binary subordinate locality name: ${I}`);if(m!==0){if(Ea(e,c,i,m)!==A.ufIds[S])throw new T(`Neighborhood and municipality UFs differ: ${I}`)}}}function Ea(e,n,i,c){let u=n.recordsOffset+(c-1)*n.recordWidth+n.originalIdWidth+n.localidadeIdWidth+i.bairro.idWidth+i.bairroAbreviado.idWidth;return _(e,u,i.uf.idWidth)}function Ra(e,n){let i=new Uint32Array(n.runCount),c=new Uint32Array(n.runCount),u=2**n.lowBits,l=0,d=0;for(let A=0;A<n.highBitCount;A++){if((e.getUint8(n.highOffset+(A>>>3))&1<<(A&7))===0){l++;continue}let R=ha(e,n.lowOffset,d*n.lowBits,n.lowBits);i[d]=l*u+R,c[d]=_(e,n.idsOffset+d*n.idWidth,n.idWidth),d++}return{ids:c,starts:i}}function Oa(e,n,i){let c=new Uint32Array(i.count),u=new Uint32Array(i.count),l=new Uint8Array(i.count);for(let d=0;d<i.count;d++)c[d]=e.getUint32(i.startsOffset+d*4,!0),u[d]=_(e,i.idsOffset+d*n.municipalityIdWidth,n.municipalityIdWidth),l[d]=e.getUint8(n.sections.localidadeFlags.offset+d);return{flags:l,ids:u,starts:c}}function pa(e,n){let i=e.subarray(n.offset,n.offset+n.length);if(i[0]===239&&i[1]===187&&i[2]===191)throw new T("Binary database metadata must not contain a UTF-8 BOM");let c;try{c=JSON.parse(gr.decode(i))}catch(u){throw new T("Binary database metadata is invalid JSON or UTF-8",{cause:u})}if(!c||typeof c!=="object"||Array.isArray(c))throw new T("Binary database metadata must be an object");for(let u of Object.values(c))if(typeof u!=="string")throw new T("Binary database metadata values must be strings")}function Ia(e,n,i){if(n.offset<q||n.offset>e||n.length>e-n.offset)throw new T(`Binary ${i} region is outside the payload`)}function fe(e,n,i){if(e.length!==n)throw new T(`Binary ${i} region has an invalid length`)}function at(e,n,i,c){for(let u=n;u<i;u++)if((e[u]??0)!==0)throw new T(`Invalid ${c}`)}function ma(e,n,i,c){if(i%8!==0){if(((e[n.offset+n.length-1]??0)&255<<(i&7))!==0)throw new T(`Invalid binary ${c} bitmap padding`)}}function Sa(e,n,i){let c=i*pe,u=n+Math.floor(c/8),l=c&7;return((e[u]??0)|(e[u+1]??0)<<8|(e[u+2]??0)<<16)>>>l&1023}function ha(e,n,i,c){let u=0;for(let l=0;l<c;l++){let d=i+l;if(e.getUint8(n+(d>>>3))&1<<(d&7))u+=2**l}return u}function yr(e){Dr(e);let n=e.byteLength-X;e.set(new Bun.CryptoHasher("sha256").update(e.subarray(0,n)).digest(),n)}function Nr(e){let n=e.byteLength-X,i=new Bun.CryptoHasher("sha256").update(e.subarray(0,n)).digest();for(let c=0;c<X;c++)if(e[n+c]!==i[c])throw new T("Binary database SHA-256 checksum mismatch")}class w extends Error{code;exitCode;details;constructor(e,n,i=1,c){super(n);this.code=e;this.exitCode=i;this.details=c;this.name="UserError"}}var Ta=/[\s,;]/;function st(e){let n=e.length;if(n!==8&&n!==9)return Number.NaN;if(n===9&&e.charCodeAt(5)!==45)return Number.NaN;let i=e.charCodeAt(0)-48,c=e.charCodeAt(1)-48,u=e.charCodeAt(2)-48,l=e.charCodeAt(3)-48,d=e.charCodeAt(4)-48,A=e.charCodeAt(n-3)-48,E=e.charCodeAt(n-2)-48,R=e.charCodeAt(n-1)-48;if((i|c|u|l|d|A|E|R|9-i|9-c|9-u|9-l|9-d|9-A|9-E|9-R)<0)return Number.NaN;return i*1e7+c*1e6+u*1e5+l*1e4+d*1000+A*100+E*10+R}function Lr(e){let n=e.trim(),i=st(n);if(Number.isNaN(i))return;return String(i).padStart(8,"0")}async function*wr(e,n,i=process.stdin.isTTY===!0){let c=n?n==="-"?Bun.stdin:Bun.file(n):null;if(n&&n!=="-"&&c&&!await c.exists())throw new w("input-file-not-found",`Arquivo de entrada com CEPs n\xE3o encontrado: ${n}`);for(let u of e)yield u;if(c){yield*Cr(c.stream());return}if(!e.length&&!i)yield*Cr(Bun.stdin.stream())}async function*Cr(e){let n=new TextDecoder,i="";for await(let c of e){let u=i+n.decode(c,{stream:!0}),l=0;for(let d=0;d<u.length;d++){if(!Ta.test(u[d]??""))continue;if(d>l)yield u.slice(l,d);l=d+1}i=u.slice(l)}if(i+=n.decode(),i)yield i}import{Buffer as ba}from"buffer";var Mr=new WeakMap,ga=new TextDecoder;function Da(e,n){let i=new Uint8Array(me),c=new Uint32Array(me*2);for(let d=0;d<i.length;d++)i[d]=e.getUint8(n.symbolsOffset+d);for(let d=0;d<c.length;d++)c[d]=e.getUint32(n.symbolsOffset+me+d*4,!0);let u=ba.alloc(272),l={lengths:i,words:c,output:u,view:new DataView(u.buffer,u.byteOffset,u.byteLength)};return Mr.set(n,l),l}function Ur(e,n,i,c){let{lengths:u,words:l,output:d,view:A}=Mr.get(i)??Da(n,i),E=c-1,R=E>>>H,O=i.suffixDataOffset+n.getUint32(i.blockOffsetsOffset+R*4,!0),p=0;for(let I=R*J;I<=E;I++){let m=i.lengthWidth===1?e[i.lengthsOffset+I]:n.getUint16(i.lengthsOffset+I*2,!0),S=O+m,h=e[i.prefixesOffset+I];while(O<S){let b=e[O++];if(b===255)d[h++]=e[O++];else A.setUint32(h,l[b*2],!0),A.setUint32(h+4,l[b*2+1],!0),h+=u[b]}p=h}return ga.decode(d.subarray(0,p))}import{closeSync as ya,fstatSync as Na,openSync as Ca,readFileSync as La,readSync as wa}from"fs";function Pr(e){let n;try{n=Ca(e,"r")}catch(i){if(i.code!=="ENOENT")throw i;let c=La(e),u=new SharedArrayBuffer(c.byteLength);return new Uint8Array(u).set(c),u}try{let i=new SharedArrayBuffer(Na(n).size),c=new Uint8Array(i),u=0;while(u<c.byteLength){let l=wa(n,c,u,c.byteLength-u,u);if(l===0)throw Error(`File ended while loading shared snapshot: ${e}`);u+=l}return i}finally{ya(n)}}var _r=new TextDecoder,Br=Je();async function On(e){try{if(!await Bun.file(e).exists())return!1;let n=new Uint8Array(await Bun.file(e).slice(0,K.length).arrayBuffer());return or(n)}catch(n){throw new Rt(e,{cause:n})}}class he{bairroCache;data;decodeScratch=new Uint8Array(255);dictionaries;bairros;bairroRuns;localityRuns;logradouroIdBits;header;bytes;metadataValue;municipalityCache;constructor(e){let n=e instanceof SharedArrayBuffer?new Uint8Array(e):Ua(e);try{let i=new DataView(n.buffer,n.byteOffset,n.byteLength);Pa(i),Nr(n);let c=Ba(i),u=_a(i,c),l=xa(i,c,u),d=Er(i,c.sections.bairroIds,c.rowCount,l.idWidth),A=mr(i,c.sections.municipalityIds,c.rowCount),E=Va(n,c.sections.metadata);this.bytes=n,this.data=i,this.header=c,this.dictionaries=u,this.bairros=l,this.bairroRuns=d,this.localityRuns=A,this.logradouroIdBits=nt(u.logradouro.count),this.metadataValue=Object.freeze(E),this.bairroCache=Array.from({length:u.bairro.count+1}),this.municipalityCache=Array.from({length:c.municipalityCount+1})}catch(i){if(this.bytes=null,this.data=null,i instanceof Se)throw i;throw new T("Unable to decode binary database",{cause:i})}}close(){this.bairroCache=[],this.data=null,this.bytes=null,this.municipalityCache=[]}[Symbol.dispose](){this.close()}metadata(){return this.metadataValue}queryCep(e){this.assertOpen();let n=this.findCepIndex(e);return n===-1?void 0:this.readRow(n,e.replace("-",""))}queryMunicipality(e){if(this.assertOpen(),!Number.isInteger(e)||e<1e6||e>9999999)return;let n=3+this.dictionaries.municipio.idWidth+this.dictionaries.uf.idWidth,i=this.header.sections.municipalities.offset,c=0,u=this.header.municipalityCount-1;while(c<=u){let l=c+(u-c>>>1),d=this.readPackedInteger(i+l*n,3);if(d<e)c=l+1;else if(d>e)u=l-1;else{let{municipio:A,uf:E}=this.readMunicipality(l+1);return{municipio:A,uf:E}}}return}queryMunicipalityCodesByUf(e){if(this.assertOpen(),!Object.hasOwn(de,e))return[];let n=de[e]*1e5,i=n+1e5,c=3+this.dictionaries.municipio.idWidth+this.dictionaries.uf.idWidth,u=this.header.sections.municipalities.offset,l=0,d=this.header.municipalityCount;while(l<d){let E=l+(d-l>>>1);if(this.readPackedInteger(u+E*c,3)<n)l=E+1;else d=E}let A=[];for(let E=l;E<this.header.municipalityCount;E++){let R=this.readPackedInteger(u+E*c,3);if(R>=i)break;A.push(R)}return A}queryNeighborhood(e){this.assertOpen();let n=this.findNeighborhoodIndex(e);return n===0?void 0:this.readNeighborhood(n)}queryNeighborhoodByCep(e){this.assertOpen();let n=this.findCepIndex(e);if(n===-1)return;let i=this.readNeighborhoodIndex(n);return i===0?void 0:this.readNeighborhood(i)}queryNeighborhoodCepRanges(e){this.assertOpen();let n=this.findNeighborhoodIndex(e);if(n===0)return[];let{bairroFaixaOffsets:i,bairroFaixas:c}=this.header.sections,u=this.readUint32(i.offset+(n-1)*4),l=this.readUint32(i.offset+n*4),d=[];for(let A=u;A<l;A++){let E=this.readUint32(c.offset+A*8),R=this.readUint32(c.offset+A*8+4);d.push({cep_inicial:String(E).padStart(8,"0"),cep_final:String(R).padStart(8,"0")})}return d}rowCount(){return this.header.rowCount}checksum(){return this.assertOpen(),Buffer.from(this.bytes.subarray(-X)).toString("hex")}*entries(){this.assertOpen();let e=this.header.sections.cepPrefixOffsets,n=this.header.cepPrefixOffsetWidth,i=0;for(let c=0;c<this.header.rowCount;c++){while(c>=this.readPackedInteger(e.offset+(i+1)*n,n))i++;let u=String(i*1000+this.readPacked10(c)).padStart(8,"0");yield this.readRow(c,u),this.assertOpen()}}assertOpen(){if(this.data===null)throw new $t}findCepIndex(e){let n=st(e);if(Number.isNaN(n))return-1;let i=Math.floor(n/1000),c=n%1000,u=this.header.sections.cepPrefixOffsets,l=this.header.cepPrefixOffsetWidth,d=this.readPackedInteger(u.offset+i*l,l),A=this.readPackedInteger(u.offset+(i+1)*l,l),E=A;while(d<E){let R=d+(E-d>>>1);if(this.readPacked10(R)<c)d=R+1;else E=R}if(d>=A||this.readPacked10(d)!==c)return-1;return d}findNeighborhoodIndex(e){if(!oe(e))return 0;let n=0,i=this.bairros.count;while(n<i){let u=n+(i-n>>>1);if(this.readPackedInteger(this.bairros.recordsOffset+u*this.bairros.recordWidth,this.bairros.originalIdWidth)<e)n=u+1;else i=u}if(n===this.bairros.count)return 0;return this.readPackedInteger(this.bairros.recordsOffset+n*this.bairros.recordWidth,this.bairros.originalIdWidth)===e?n+1:0}readNeighborhoodIndex(e){return Or(this.data,this.bairroRuns,e)}readNeighborhood(e){let{originalIdWidth:n,localidadeIdWidth:i,recordsOffset:c,recordWidth:u}=this.bairros,l=c+(e-1)*u,d=this.readPackedInteger(l,n);l+=n;let A=this.readPackedInteger(l,i);l+=i;let E=this.readRequiredDictionaryString(this.dictionaries.bairro,this.readPackedInteger(l,this.dictionaries.bairro.idWidth));l+=this.dictionaries.bairro.idWidth;let R=this.readDictionaryString(this.dictionaries.bairroAbreviado,this.readPackedInteger(l,this.dictionaries.bairroAbreviado.idWidth));l+=this.dictionaries.bairroAbreviado.idWidth;let O=this.readRequiredDictionaryString(this.dictionaries.uf,this.readPackedInteger(l,this.dictionaries.uf.idWidth));return{bairro_id:d,localidade_id:A,nome:E,nome_abreviado:R,uf:O}}readRow(e,n){let i=this.header.sections,c=hr(this.data,this.localityRuns,e),u=this.readPackedInteger(this.localityRuns.idsOffset+c*this.header.municipalityIdWidth,this.header.municipalityIdWidth),l=this.readMunicipality(u),d=this.data.getUint8(i.localidadeFlags.offset+c),A=ot[d&3],E=it[d>>>2],R=this.readNeighborhoodIndex(e),O=this.readSparseId(i.localidadeNomeBitmap,i.localidadeNomeRanks,i.localidadeNomeIds,e,this.dictionaries.bairro.idWidth),p=R===0?O:this.readPackedInteger(this.bairros.recordsOffset+(R-1)*this.bairros.recordWidth+this.bairros.originalIdWidth+this.bairros.localidadeIdWidth,this.dictionaries.bairro.idWidth);return{bairro:this.readCachedDictionaryString(this.dictionaries.bairro,p,this.bairroCache),cep:n,complemento:this.readDictionaryString(this.dictionaries.complemento,this.readSparseId(i.complementoBitmap,i.complementoRanks,i.complementoIds,e,this.dictionaries.complemento.idWidth)),localidade_situacao:A,localidade_tipo:E,logradouro:this.readDictionaryString(this.dictionaries.logradouro,kt(this.data,i.logradouroIds.offset,e,this.logradouroIdBits)),municipio:l.municipio,municipio_cod_ibge:l.codigoIbge,nome:this.readDictionaryString(this.dictionaries.nome,this.readSparseId(i.nomeBitmap,i.nomeRanks,i.nomeIds,e,this.dictionaries.nome.idWidth)),uf:l.uf}}readMunicipality(e){let n=this.municipalityCache[e];if(n)return n;let i=3+this.dictionaries.municipio.idWidth+this.dictionaries.uf.idWidth,c=this.header.sections.municipalities.offset+(e-1)*i,u=this.readPackedInteger(c+3,this.dictionaries.municipio.idWidth),l=this.readPackedInteger(c+3+this.dictionaries.municipio.idWidth,this.dictionaries.uf.idWidth),d={codigoIbge:this.readPackedInteger(c,3),municipio:this.readRequiredDictionaryString(this.dictionaries.municipio,u),uf:this.readRequiredDictionaryString(this.dictionaries.uf,l)};return this.municipalityCache[e]=d,d}readSparseId(e,n,i,c,u){let l=this.bytes,d=c>>>3,A=l[e.offset+d],E=c&7;if((A&1<<E)===0)return 0;let R=c>>>Pe,O=this.readUint32(n.offset+R*4),p=R*(ee>>>3);for(let I=p;I<d;I++)O+=Br[l[e.offset+I]];return O+=Br[A&(1<<E)-1],this.readPackedInteger(i.offset+O*u,u)}readDictionaryString(e,n){if(n===0)return null;let i=this.bytes;if(e.codec===Ie)return Ur(i,this.data,e,n);let c=n-1,u=c>>>H,l=u<<H,d=this.readUint32(e.blockOffsetsOffset+u*4),A=e.suffixDataOffset+d,E=this.decodeScratch,R=0;for(let O=l;O<=c;O++){let p=i[e.lengthsOffset+O],I=i[e.prefixesOffset+O],m=p-I;E.set(i.subarray(A,A+m),I),A+=m,R=p}return _r.decode(E.subarray(0,R))}readCachedDictionaryString(e,n,i){if(n===0)return null;let c=i[n];if(c!==void 0)return c;let u=this.readRequiredDictionaryString(e,n);return i[n]=u,u}readRequiredDictionaryString(e,n){return this.readDictionaryString(e,n)}readPacked10(e){let n=this.bytes,i=this.header.sections.cepSuffixes,c=e*pe,u=c>>>3,l=c&7,d=i.offset+u;return(n[d]|n[d+1]<<8|n[d+2]<<16)>>>l&1023}readPackedInteger(e,n){return _(this.data,e,n)}readUint32(e){return this.data.getUint32(e,!0)}}function Ua(e,n=!1){try{return n?new Uint8Array(Pr(e)):Ma(e)}catch(i){throw new Rt(e,{cause:i})}}function Pa(e){if(e.byteLength<q+X)throw new T("Binary database header is truncated");for(let i=0;i<K.length;i++)if(e.getUint8(i)!==K[i])throw new T("Invalid binary database magic");let n=e.getUint16(8,!0);if(n!==Oe)throw new Gt(n,Oe);if(e.getUint16(10,!0)!==q)throw new T("Unsupported binary database header size");if(e.getUint8(22)!==Pe||e.getUint8(23)!==H)throw new T("Unsupported binary database block layout");if(e.getUint16(24,!0)!==Y.length)throw new T("Unsupported binary database section table");if(e.getUint32(16,!0)!==e.byteLength)throw new T(`Binary database size mismatch: header=${e.getUint32(16,!0)}, actual=${e.byteLength}`)}function Ba(e){let n={};for(let[i,c]of Y.entries()){let u=ze+i*8;n[c]={length:e.getUint32(u+4,!0),offset:e.getUint32(u,!0)}}return{cepPrefixOffsetWidth:e.getUint8(20),fileSize:e.getUint32(16,!0),municipalityCount:e.getUint32(28,!0),municipalityIdWidth:e.getUint8(21),rowCount:e.getUint32(12,!0),sections:n}}function _a(e,n){return{bairro:Fe(e,n.sections.bairroDictionary),bairroAbreviado:Fe(e,n.sections.bairroAbreviadoDictionary),complemento:Fe(e,n.sections.complementoDictionary),logradouro:Fe(e,n.sections.logradouroDictionary),municipio:Fe(e,n.sections.municipioDictionary),nome:Fe(e,n.sections.nomeDictionary),uf:Fe(e,n.sections.ufDictionary)}}function Fe(e,n){let i=e.getUint32(n.offset,!0),c=n.offset+e.getUint32(n.offset+16,!0);return{blockCount:e.getUint32(n.offset+4,!0),blockOffsetsOffset:n.offset+e.getUint32(n.offset+8,!0),count:i,codec:e.getUint8(n.offset+30),idWidth:e.getUint8(n.offset+28),lengthsOffset:n.offset+e.getUint32(n.offset+12,!0),lengthWidth:e.getUint8(n.offset+31)===2?2:1,prefixesOffset:c,region:n,suffixDataLength:e.getUint32(n.offset+24,!0),suffixDataOffset:n.offset+e.getUint32(n.offset+20,!0),symbolsOffset:c+i}}function xa(e,n,i){let c=n.sections.bairros,u=e.getUint32(c.offset,!0),l=e.getUint8(c.offset+4),d=e.getUint8(c.offset+5),A=l+d+i.bairro.idWidth+i.bairroAbreviado.idWidth+i.uf.idWidth;return{count:u,idWidth:v(u),originalIdWidth:l,localidadeIdWidth:d,recordsOffset:c.offset+re,recordWidth:A}}function Va(e,n){return JSON.parse(_r.decode(e.subarray(n.offset,n.offset+n.length)))}import{Database as Xa}from"bun:sqlite";var Wt=255,Fa=255,pn=8,xr=510,Ht=65536,va=[64,128,160,192,224];function vr(e){if(!e.count)throw Error("Cannot train FSST with an empty dictionary");let n=Ga(e),i=Ha($a(n),ka(n),n),c=ja(e,i);return{compressedLengths:c.maxLength<=255?Uint8Array.from(c.lengths):Qa(c.lengths),lengthWidth:c.maxLength<=255?1:2,payload:c.payload,symbols:i.symbols}}function Ga(e){let n=e.totalBytes,i=[],c=Math.min(e.count,Ht,Math.ceil(Ht/Math.max(1,n/e.count))),u=e.count/Math.max(1,c),l=2654435769,d=0;for(let A=0;A<c&&d<Ht;A++){l=Math.imul(l,1664525)+1013904223>>>0;let E=Math.floor(l/4294967296*Math.max(1,u)),R=Math.min(e.count-1,Math.floor(A*u)+E),O=e.get(R);if(!O?.byteLength)continue;let p=Ht-d;i.push(O.byteLength<=p?O:O.subarray(0,p)),d+=Math.min(O.byteLength,p)}return i}function $a(e){let n=new Map;for(let c of e)for(let u=0;u+1<c.byteLength;u++){let l="",d=Math.min(c.byteLength,u+pn);for(let A=u;A<d;A++)if(l+=String.fromCharCode(c[A]??0),A-u+1>=2)n.set(l,(n.get(l)??0)+1)}let i=[];for(let[c,u]of n){let l=c.length;i.push({key:c,length:l,score:u*(l-1)})}return i.sort(za),i.slice(0,4096)}function ka(e){let n=new Uint32Array(256);for(let i of e)for(let c of i)n[c]=(n[c]??0)+1;return Array.from({length:256},(i,c)=>c).filter((i)=>(n[i]??0)>0).sort((i,c)=>(n[c]??0)-(n[i]??0)||i-c)}function Ha(e,n,i){let c=Vr(n.slice(0,Wt).map((l)=>Uint8Array.of(l))),u={table:c,size:Fr(i,c).size};for(let l of va){let d=e.slice(0,l),A=d.length,E=n.slice(0,Wt-d.length).map((R)=>Uint8Array.of(R));for(let R=0;R<4;R++){let O=d.map((S)=>Za(S.key)).concat(E),p=Vr(O),I=Fr(i,p);if(I.size<u.size)u={table:p,size:I.size};let m=d.filter((S,h)=>(I.uses[h]??0)>0);if(m.length===d.length||A===e.length)break;while(m.length<l&&A<e.length){let S=e[A++];if(S)m.push(S)}d=m}}return u.table}function Vr(e){let n=new Uint8Array(Ue),i=Gr();for(let[c,u]of e.entries())n[c]=u.byteLength,n.set(u,Wt+c*pn),Wa(i,u,c);return{symbols:n,trie:i}}function Gr(){return{code:-1,children:new Map}}function Wa(e,n,i){let c=e;for(let u of n){let l=c.children.get(u);if(!l)l=Gr(),c.children.set(u,l);c=l}c.code=i}function Fr(e,n){let i=0,c=new Uint32Array(Wt);for(let u of e){let l=0;while(l<u.byteLength){let d=$r(u,l,n.trie);if(d)i++,c[d.code]=(c[d.code]??0)+1,l+=d.length;else i+=2,l++}}return{size:i,uses:c}}function ja(e,n){let i=new Uint32Array(e.count),c=e.totalBytes*2,u=new Uint8Array(c),l=0,d=0;for(let A=0;A<e.count;A++){let E=e.get(A),R=l;l=qa(E,n,u,l);let O=l-R;if(i[A]=O,d=Math.max(d,O),O>xr)throw Error(`FSST compressed suffix exceeds ${xr} bytes: ${O}`)}return{lengths:i,maxLength:d,payload:u.slice(0,l)}}function qa(e,n,i,c){let u=0,l=c;while(u<e.byteLength){let d=$r(e,u,n.trie);if(d)i[l++]=d.code,u+=d.length;else i[l++]=Fa,i[l++]=e[u++]??0}return l}function $r(e,n,i){let c=i,u=-1,l=0,d=Math.min(e.byteLength,n+pn);for(let A=n;A<d;A++){let E=c.children.get(e[A]??0);if(!E)break;if(c=E,c.code>=0)u=c.code,l=A-n+1}return u<0?void 0:{code:u,length:l}}function Za(e){let n=new Uint8Array(e.length);for(let i=0;i<e.length;i++)n[i]=e.charCodeAt(i);return n}function za(e,n){return n.score-e.score||n.length-e.length||(e.key<n.key?-1:e.key>n.key?1:0)}function Qa(e){let n=new Uint8Array(e.length*2),i=new DataView(n.buffer);for(let c=0;c<e.length;c++)i.setUint16(c*2,e[c]??0,!0);return n}var kr="dne",Hr="dne.db",z="dne",Te="bairros",St="bairro_faixas",Z="edne_metadata",Wr=32768,jr=-200000,qr=1000,Zr=8,jt=2097152,zr=30000,Qr=2,Xr=100,Jr=1000,Yr=2000;var Sn=new TextEncoder,Ja=Je();async function Kr(e,n,i=z){As();let c=new Xa(e,{readonly:!0});try{c.run("BEGIN");let u=us(c,i);if(qt(u,"row count"),!u)throw Error("Cannot create a binary database without rows");let l=c.query(`SELECT bairro_id, localidade_id, uf, nome, nome_abreviado
4
+ FROM ${Tt(Te)} ORDER BY bairro_id`).all(),d=new Map(l.map((B,Q)=>[B.bairro_id,Q+1])),A=v(l.length),E=Ya(c,i,l),R=Ka(E);R.logradouro=es(R.logradouro);let O=[...E.municipalitiesByIbge.entries()].sort(([B],[Q])=>B-Q),p=O.length,I=v(p),m=new Map;for(let[B,[Q]]of O.entries())m.set(Q,B+1);let S=new Uint32Array(Me),h=new Uint8Array(Xe(u,pe)),b=nt(R.logradouro.count),g=new Uint8Array(Xe(u,b)),D=new Uint8Array(Qe(u)),y=new Uint8Array(E.complementoCount*R.complemento.idWidth),U=new Uint8Array(u*A),L=new Uint8Array(Qe(u)),V=new Uint8Array(E.localidadeNomeCount*R.bairro.idWidth),W=new Uint8Array(u*I),C=new Uint8Array(u),x=new Uint8Array(Qe(u)),j=new Uint8Array(E.nomeCount*R.nome.idWidth),qe=0,ye=0,Ne=0,ue=0,lt=-1,k=0;for(let B of ei(c,i)){let Q=hn(B.cep);if(Q<=lt)throw Error("CEP rows must be unique and ordered");lt=Q;let Ee=rt.indexOf(B.localidade_tipo);if(Ee===-1||![0,1,2,3].includes(B.localidade_situacao))throw Error(`Invalid locality indicators for CEP: ${B.cep}`);C[k]=Ee<<2|B.localidade_situacao;let we=Math.floor(Q/1000);while(ue<=we)S[ue]=k,ue++;if(ar(h,k,Q%1000),Tr(g,k,b,ti(R.logradouro,B.logradouro)),B.complemento!==null)mn(D,k),F(y,qe*R.complemento.idWidth,be(R.complemento,B.complemento,"complemento"),R.complemento.idWidth),qe++;let Re=B.bairro_id===null?0:d.get(B.bairro_id);if(Re===void 0)throw Error(`Unknown bairro_id for CEP: ${B.cep}`);if(F(U,k*A,Re,A),B.localidade_nome!==null){if(Re!==0||B.localidade_tipo==="M")throw Error(`Invalid subordinate locality name for CEP: ${B.cep}`);mn(L,k),F(V,Ne*R.bairro.idWidth,be(R.bairro,B.localidade_nome,"localidade_nome"),R.bairro.idWidth),Ne++}let Xn=m.get(B.municipio_cod_ibge);if(Xn===void 0)throw Error(`Missing municipality for IBGE code: ${B.municipio_cod_ibge}`);if(F(W,k*I,Xn,I),B.nome!==null)mn(x,k),F(j,ye*R.nome.idWidth,be(R.nome,B.nome,"nome"),R.nome.idWidth),ye++;k++}if(k!==u)throw Error(`SQLite row count changed while exporting: expected ${u}, got ${k}`);if(qe!==E.complementoCount||ye!==E.nomeCount||Ne!==E.localidadeNomeCount)throw Error("SQLite nullable field counts changed while exporting");while(ue<Me)S[ue]=u,ue++;let G=v(u),ne=In(D,y,u),Ce=In(x,j,u),Le=In(L,V,u),N=as(c,d),P=Sn.encode(JSON.stringify(ls(c))),le=is(O,R),xt=Ir(W,C,I),dt={bairroDictionary:R.bairro.bytes,bairroAbreviadoDictionary:R.bairroAbreviado.bytes,bairroIds:Ar(U,u,A),bairros:os(l,R),bairroFaixaOffsets:N.offsets,bairroFaixas:N.ranges,cepPrefixOffsets:fs(S,G),cepSuffixes:h,complementoBitmap:ne.bitmap,complementoDictionary:R.complemento.bytes,complementoIds:ne.ids,complementoRanks:ne.ranks,localidadeFlags:xt.flags,localidadeNomeBitmap:Le.bitmap,localidadeNomeRanks:Le.ranks,localidadeNomeIds:Le.ids,logradouroDictionary:R.logradouro.bytes,logradouroIds:g,metadata:P,municipalities:le,municipalityIds:xt.ids,municipioDictionary:R.municipio.bytes,nomeBitmap:Ce.bitmap,nomeDictionary:R.nome.bytes,nomeIds:Ce.ids,nomeRanks:Ce.ranks,ufDictionary:R.uf.bytes};return await ss(n,u,p,I,G,dt),c.run("COMMIT"),u}finally{c.close()}}function Ya(e,n,i){let c={complementoCount:0,localidadeNomeCount:0,municipalitiesByIbge:new Map,nomeCount:0,strings:{bairro:new Set,bairroAbreviado:new Set,complemento:new Set,logradouro:new Set,municipio:new Set,nome:new Set,uf:new Set}};for(let u of i){if(!oe(u.bairro_id)||!oe(u.localidade_id)||!u.nome||!u.uf)throw Error(`Invalid neighborhood: ${u.bairro_id}`);c.strings.bairro.add(u.nome),ht(c.strings.bairroAbreviado,u.nome_abreviado),c.strings.uf.add(u.uf)}for(let u of ei(e,n)){if(ht(c.strings.logradouro,u.logradouro),ht(c.strings.complemento,u.complemento),ht(c.strings.bairro,u.localidade_nome),c.strings.municipio.add(u.municipio),c.strings.uf.add(u.uf),ht(c.strings.nome,u.nome),u.complemento!==null)c.complementoCount++;if(u.nome!==null)c.nomeCount++;if(u.localidade_nome!==null)c.localidadeNomeCount++;An(u.municipio_cod_ibge,3,"municipio_cod_ibge");let l=c.municipalitiesByIbge.get(u.municipio_cod_ibge);if(l&&(l.municipio!==u.municipio||l.uf!==u.uf))throw Error(`IBGE code maps to multiple municipalities: ${u.municipio_cod_ibge}`);c.municipalitiesByIbge.set(u.municipio_cod_ibge,{municipio:u.municipio,uf:u.uf})}return c}function Ka(e){return{bairro:ve(e.strings.bairro),bairroAbreviado:ve(e.strings.bairroAbreviado),complemento:ve(e.strings.complemento),logradouro:ve(e.strings.logradouro),municipio:ve(e.strings.municipio),nome:ve(e.strings.nome),uf:ve(e.strings.uf)}}function ve(e){let n=[...e].sort(),i=n.length,c=Math.ceil(i/J),u=new Uint32Array(c),l=new Uint8Array(i),d=new Uint8Array(i),A=new Map,E=new Uint8Array,R=0;for(let[g,D]of n.entries()){let y=Sn.encode(D);if(y.byteLength>255)throw Error(`Binary string exceeds 255 UTF-8 bytes: ${D}`);let U=g%J===0?0:ds(E,y);if(g%J===0)u[g>>>H]=R;l[g]=y.byteLength,d[g]=U,R+=y.byteLength-U,qt(R,"dictionary suffix data length"),A.set(D,g+1),E=y}let O=Ze,p=O+u.byteLength,I=p+l.byteLength,m=I+d.byteLength,S=new Uint8Array(m+R),h=new DataView(S.buffer);h.setUint32(0,i,!0),h.setUint32(4,c,!0),h.setUint32(8,O,!0),h.setUint32(12,p,!0),h.setUint32(16,I,!0),h.setUint32(20,m,!0),h.setUint32(24,R,!0),h.setUint8(28,v(i)),h.setUint8(29,H),S.set(Zt(u),O),S.set(l,p),S.set(d,I);let b=m;for(let[g,D]of n.entries()){let y=Sn.encode(D),U=d[g]??0;S.set(y.subarray(U),b),b+=y.byteLength-U}return{bytes:S,count:i,ids:A,idWidth:v(i)}}function es(e){let n=ts(e);if(!n.count||n.suffixDataLength<=Ue)return e;let i=vr(n.source),c=ns(e,n,i.compressedLengths,i.lengthWidth,i.symbols,i.payload);return c.byteLength<e.bytes.byteLength?{...e,bytes:c}:e}function ts(e){let n=new DataView(e.bytes.buffer,e.bytes.byteOffset,e.bytes.byteLength),i=n.getUint32(0,!0),c=n.getUint32(4,!0),u=e.bytes.subarray(n.getUint32(8,!0),n.getUint32(12,!0)),l=new DataView(u.buffer,u.byteOffset,u.byteLength),d=e.bytes.subarray(n.getUint32(12,!0),n.getUint32(16,!0)),A=e.bytes.subarray(n.getUint32(16,!0),n.getUint32(20,!0)),E=n.getUint32(20,!0),R=n.getUint32(24,!0);return{blockCount:c,blockOffsets:u,count:i,lengths:d,prefixes:A,source:{count:i,totalBytes:R,get(p){let I=p>>>H,m=E+l.getUint32(I*4,!0),S=I*J;for(let b=S;b<p;b++)m+=(d[b]??0)-(A[b]??0);let h=(d[p]??0)-(A[p]??0);return e.bytes.subarray(m,m+h)}},suffixDataLength:R}}function ns(e,n,i,c,u,l){let d=n.blockCount,A=new Uint32Array(d),E=0;for(let b=0;b<n.count;b++){if(b%J===0)A[b>>>H]=E;E+=rs(i,c,b),qt(E,"FSST dictionary suffix data length")}if(E!==l.byteLength||u.byteLength!==Ue)throw Error("Invalid FSST encoder result");let R=Ze,O=R+A.byteLength,p=O+i.byteLength,I=p+n.count,m=I+u.byteLength,S=new Uint8Array(m+l.byteLength),h=new DataView(S.buffer);return h.setUint32(0,n.count,!0),h.setUint32(4,d,!0),h.setUint32(8,R,!0),h.setUint32(12,O,!0),h.setUint32(16,p,!0),h.setUint32(20,m,!0),h.setUint32(24,l.byteLength,!0),h.setUint8(28,e.idWidth),h.setUint8(29,H),h.setUint8(30,Ie),h.setUint8(31,c),S.set(Zt(A),R),S.set(i,O),S.set(n.prefixes,p),S.set(u,I),S.set(l,m),S}function rs(e,n,i){if(n===1)return e[i]??0;let c=i*2;return(e[c]??0)|(e[c+1]??0)<<8}function is(e,n){let i=3+n.municipio.idWidth+n.uf.idWidth,c=new Uint8Array(e.length*i);for(let[u,[l,d]]of e.entries()){let A=u*i;F(c,A,l,3),F(c,A+3,be(n.municipio,d.municipio,"municipio"),n.municipio.idWidth),F(c,A+3+n.municipio.idWidth,be(n.uf,d.uf,"uf"),n.uf.idWidth)}return c}function In(e,n,i){let c=Math.ceil(i/ee),u=new Uint32Array(c+1),l=0;for(let d=0;d<c;d++){u[d]=l;let A=d*(ee>>>3),E=Math.min(A+(ee>>>3),e.byteLength);for(let R=A;R<E;R++)l+=Ja[e[R]??0]??0}return u[c]=l,{bitmap:e,ids:n,ranks:Zt(u)}}function os(e,n){let i=v(e.at(-1)?.bairro_id??0),c=v(e.reduce((A,E)=>Math.max(A,E.localidade_id),0)),u=i+c+n.bairro.idWidth+n.bairroAbreviado.idWidth+n.uf.idWidth,l=new Uint8Array(re+e.length*u),d=new DataView(l.buffer);d.setUint32(0,e.length,!0),d.setUint8(4,i),d.setUint8(5,c);for(let[A,E]of e.entries()){let R=re+A*u;F(l,R,E.bairro_id,i),R+=i,F(l,R,E.localidade_id,c),R+=c,F(l,R,be(n.bairro,E.nome,"bairro"),n.bairro.idWidth),R+=n.bairro.idWidth,F(l,R,ti(n.bairroAbreviado,E.nome_abreviado),n.bairroAbreviado.idWidth),R+=n.bairroAbreviado.idWidth,F(l,R,be(n.uf,E.uf,"uf"),n.uf.idWidth)}return l}function as(e,n){let i=e.query(`SELECT bairro_id, cep_inicial, cep_final FROM ${Tt(St)}
5
+ ORDER BY bairro_id, cep_inicial, cep_final`).all(),c=new Uint32Array(n.size+1),u=new Uint8Array(i.length*8),l=new DataView(u.buffer),d=0,A;for(let[E,R]of i.entries()){let O=n.get(R.bairro_id);if(O===void 0)throw Error(`Unknown neighborhood in CEP range: ${R.bairro_id}`);let p=hn(R.cep_inicial),I=hn(R.cep_final);if(p>I)throw Error(`Reversed neighborhood CEP range: ${R.bairro_id}`);if(A?.bairro_id===R.bairro_id&&A.cep_inicial===R.cep_inicial&&A.cep_final===R.cep_final)throw Error(`Duplicate neighborhood CEP range: ${R.bairro_id}`);while(d<O)c[d++]=E;l.setUint32(E*8,p,!0),l.setUint32(E*8+4,I,!0),A=R}while(d<c.length)c[d++]=i.length;return{offsets:Zt(c),ranges:u}}async function ss(e,n,i,c,u,l){let d={},A=q;for(let p of Y)A=ft(A),d[p]={length:l[p].byteLength,offset:A},A+=l[p].byteLength;let E=ft(A)+X;qt(E,"file size");let R=cs({cepPrefixOffsetWidth:u,fileSize:E,municipalityCount:i,municipalityIdWidth:c,rowCount:n,sections:d}),O=new Uint8Array(E);O.set(R);for(let p of Y)O.set(l[p],d[p].offset);yr(O),await Bun.write(e,O)}function cs(e){let n=new Uint8Array(q);n.set(K,0);let i=new DataView(n.buffer);i.setUint16(8,Oe,!0),i.setUint16(10,q,!0),i.setUint32(12,e.rowCount,!0),i.setUint32(16,e.fileSize,!0),i.setUint8(20,e.cepPrefixOffsetWidth),i.setUint8(21,e.municipalityIdWidth),i.setUint8(22,Pe),i.setUint8(23,H),i.setUint16(24,Y.length,!0),i.setUint32(28,e.municipalityCount,!0);for(let[c,u]of Y.entries()){let l=e.sections[u],d=ze+c*8;i.setUint32(d,l.offset,!0),i.setUint32(d+4,l.length,!0)}return n}function us(e,n){return e.query(`SELECT count(*) AS count FROM ${Tt(n)}`).get().count}function*ei(e,n){let i=e.query(`
6
6
  SELECT cep, logradouro, complemento, bairro_id, localidade_nome, municipio, municipio_cod_ibge, uf, nome, localidade_situacao, localidade_tipo
7
- FROM ${Le(t)}
7
+ FROM ${Tt(n)}
8
8
  ORDER BY cep
9
- `);try{for(let r of n.iterate())yield r}finally{n.finalize()}}function Ei(e){if(!e.query("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?").get(A))return{};let n=e.query(`SELECT key, value FROM ${Le(A)}`).all();return Object.fromEntries(n.map((r)=>[r.key,r.value]))}function $n(e,t){return t===null?0:Y(e,t,"string")}function Y(e,t,n){let r=e.ids.get(t);if(r===void 0)throw Error(`Missing binary ${n} dictionary value: ${t}`);return r}function Ce(e,t){if(t!==null)e.add(t)}function wi(e,t){let n=Math.min(e.byteLength,t.byteLength),r=0;while(r<n&&e[r]===t[r])r++;return r}function Nt(e,t){let n=t>>>3;e[n]=(e[n]??0)|1<<(t&7)}function _i(e,t){let n=new Uint8Array(e.length*t);for(let r=0;r<e.length;r++)D(n,r*t,e[r]??0,t);return n}function Ct(e){if(!/^\d{8}$/.test(e))throw Error(`Invalid CEP in SQLite database: ${e}`);return Number(e)}function Ii(){let e=new Uint16Array([1]);if(new Uint8Array(e.buffer)[0]!==1)throw Error("Binary database generation requires a little-endian platform")}function Lt(e,t){if(!Number.isSafeInteger(e)||e<0||e>gn)throw Error(`Binary ${t} exceeds the uint32 limit: ${e}`)}function Ot(e){return new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}async function On(e,t){await e.write(t)}async function Bn(e,t){if(t>0)await e.write(new Uint8Array(t))}function Le(e){return`"${e.replaceAll('"','""')}"`}class E extends Error{code;exitCode;details;constructor(e,t,n=1,r){super(t);this.code=e;this.exitCode=n;this.details=r;this.name="UserError"}}var Si=/[\s,;]/;function he(e){let t=e.length;if(t!==8&&t!==9)return Number.NaN;if(t===9&&e.charCodeAt(5)!==45)return Number.NaN;let n=e.charCodeAt(0)-48,r=e.charCodeAt(1)-48,i=e.charCodeAt(2)-48,o=e.charCodeAt(3)-48,a=e.charCodeAt(4)-48,s=e.charCodeAt(t-3)-48,l=e.charCodeAt(t-2)-48,c=e.charCodeAt(t-1)-48;if((n|r|i|o|a|s|l|c|9-n|9-r|9-i|9-o|9-a|9-s|9-l|9-c)<0)return Number.NaN;return n*1e7+r*1e6+i*1e5+o*1e4+a*1000+s*100+l*10+c}function Fn(e){let t=e.trim(),n=he(t);if(Number.isNaN(n))return;return String(n).padStart(8,"0")}async function*Pn(e,t,n=process.stdin.isTTY===!0){let r=t?t==="-"?Bun.stdin:Bun.file(t):null;if(t&&t!=="-"&&r&&!await r.exists())throw new E("input-file-not-found",`Arquivo de entrada com CEPs n\xE3o encontrado: ${t}`);for(let i of e)yield i;if(r){yield*Un(r.stream());return}if(!e.length&&!n)yield*Un(Bun.stdin.stream())}async function*Un(e){let t=new TextDecoder,n="";for await(let r of e){let i=n+t.decode(r,{stream:!0}),o=0;for(let a=0;a<i.length;a++){if(!Si.test(i[a]??""))continue;if(a>o)yield i.slice(o,a);o=a+1}n=i.slice(o)}if(n+=t.decode(),n)yield n}import{mkdirSync as Fi,readFileSync as Xn,renameSync as Pi,rmSync as at,statSync as ki,writeFileSync as qi}from"fs";import{homedir as Zn}from"os";import{join as $e,resolve as Ft}from"path";import{stat as Mi}from"fs/promises";import{extname as $i,resolve as Ui}from"path";import{fileURLToPath as Di}from"url";class W extends Error{constructor(e,t){super(e,t);this.name=new.target.name}}class Oe extends W{path;code="IO_ERROR";constructor(e,t){super(`Unable to read binary database: ${e}`,t);this.path=e}}class p extends W{code="INVALID_FORMAT";constructor(e,t){super(e,t)}}class Xe extends W{actualVersion;supportedVersion;code="UNSUPPORTED_VERSION";constructor(e,t){super(`Unsupported binary database version: ${e}. Rebuild the database with build --force.`);this.actualVersion=e;this.supportedVersion=t}}class Be extends W{code="READER_CLOSED";constructor(){super("Binary database is closed")}}var kn={RO:11,AC:12,AM:13,RR:14,PA:15,AP:16,TO:17,MA:21,PI:22,CE:23,RN:24,PB:25,PE:26,AL:27,SE:28,BA:29,MG:31,ES:32,RJ:33,SP:35,PR:41,SC:42,RS:43,MS:50,MT:51,GO:52,DF:53},Ss=Object.keys(kn).map(Ke);function Ke(e){let t=e.trim().toUpperCase();if(!Object.hasOwn(kn,t))throw Error(`Unknown UF: ${e}`);return t}var Wn=new TextDecoder,qn=Qe();async function vt(e){try{if(!await Bun.file(e).exists())return!1;let t=new Uint8Array(await Bun.file(e).slice(0,Q.length).arrayBuffer());return yn(t)}catch(t){throw new Oe(e,{cause:t})}}class ye{bairroCache;data;decodeScratch=new Uint8Array(255);dictionaries;bairros;header;mapped;metadataValue;municipalityCache;constructor(e=Di(new URL("../data/dne.bin",import.meta.url))){let t;try{t=Bun.mmap(e,{shared:!1})}catch(n){throw new Oe(e,{cause:n})}try{let n=new DataView(t.buffer,t.byteOffset,t.byteLength),r=Ai(n);Ti(n,r);let i=Ri(n,r),o=Ni(n,r,i);Ci(n,r,i,o);let a=Li(t,r.sections.metadata);this.mapped=t,this.data=n,this.header=r,this.dictionaries=i,this.bairros=o,this.metadataValue=a,this.bairroCache=Array.from({length:i.bairro.count+1}),this.municipalityCache=Array.from({length:r.municipalityCount+1})}catch(n){if(this.mapped=null,this.data=null,n instanceof W)throw n;throw new p("Unable to decode binary database",{cause:n})}}close(){this.bairroCache=[],this.data=null,this.mapped=null,this.municipalityCache=[]}metadata(){return this.metadataValue}queryCep(e){return this.readSafely(()=>{let t=this.findCepIndex(e);return t===-1?void 0:this.readRow(t,e.replace("-",""))})}queryNeighborhood(e){return this.readSafely(()=>{let t=this.findNeighborhoodIndex(e);return t===0?void 0:this.readNeighborhood(t)})}queryNeighborhoodByCep(e){return this.readSafely(()=>{let t=this.findCepIndex(e);if(t===-1)return;let n=this.readNeighborhoodIndex(t);return n===0?void 0:this.readNeighborhood(n)})}queryNeighborhoodCepRanges(e){return this.readSafely(()=>{let t=this.findNeighborhoodIndex(e);if(t===0)return[];let{bairroFaixaOffsets:n,bairroFaixas:r}=this.header.sections,i=this.readUint32(n.offset+(t-1)*4),o=this.readUint32(n.offset+t*4);if(i>o||o>r.length/8)throw new p("Invalid binary neighborhood range offsets");let a=[];for(let s=i;s<o;s++){let l=this.readUint32(r.offset+s*8),c=this.readUint32(r.offset+s*8+4);if(l>c||c>99999999)throw new p("Invalid binary neighborhood CEP range");a.push({cep_inicial:String(l).padStart(8,"0"),cep_final:String(c).padStart(8,"0")})}return a})}rowCount(){return this.header.rowCount}readSafely(e){try{return this.requireData(),e()}catch(t){if(t instanceof W)throw t;throw new p("Unable to decode binary database record",{cause:t})}}findCepIndex(e){let t=he(e);if(Number.isNaN(t))return-1;let n=Math.floor(t/1000),r=t%1000,i=this.header.sections.cepPrefixOffsets,o=this.header.cepPrefixOffsetWidth,a=this.readPackedInteger(i.offset+n*o,o),s=this.readPackedInteger(i.offset+(n+1)*o,o),l=s;if(a>s||s>this.header.rowCount)throw new p(`Invalid binary CEP prefix range: ${n}`);while(a<l){let c=a+(l-a>>>1);if(this.readPacked10(c)<r)a=c+1;else l=c}if(a>=s||this.readPacked10(a)!==r)return-1;return a}findNeighborhoodIndex(e){if(!B(e))return 0;let t=0,n=this.bairros.count;while(t<n){let i=t+(n-t>>>1);if(this.readPackedInteger(this.bairros.recordsOffset+i*this.bairros.recordWidth,this.bairros.originalIdWidth)<e)t=i+1;else n=i}if(t===this.bairros.count)return 0;return this.readPackedInteger(this.bairros.recordsOffset+t*this.bairros.recordWidth,this.bairros.originalIdWidth)===e?t+1:0}readNeighborhoodIndex(e){let t=this.readPackedInteger(this.header.sections.bairroIds.offset+e*this.bairros.idWidth,this.bairros.idWidth);if(t>this.bairros.count)throw new p(`Invalid binary neighborhood index: ${t}`);return t}readNeighborhood(e){let{originalIdWidth:t,localidadeIdWidth:n,recordsOffset:r,recordWidth:i}=this.bairros,o=r+(e-1)*i,a=this.readPackedInteger(o,t);o+=t;let s=this.readPackedInteger(o,n);o+=n;let l=this.readRequiredDictionaryString(this.dictionaries.bairro,this.readPackedInteger(o,this.dictionaries.bairro.idWidth),"bairro");o+=this.dictionaries.bairro.idWidth;let c=this.readDictionaryString(this.dictionaries.bairroAbreviado,this.readPackedInteger(o,this.dictionaries.bairroAbreviado.idWidth));o+=this.dictionaries.bairroAbreviado.idWidth;let u=Ke(this.readRequiredDictionaryString(this.dictionaries.uf,this.readPackedInteger(o,this.dictionaries.uf.idWidth),"uf"));return{bairro_id:a,localidade_id:s,nome:l,nome_abreviado:c,uf:u}}readRow(e,t){let n=this.header.sections,r=this.readPackedInteger(n.municipalityIds.offset+e*this.header.municipalityIdWidth,this.header.municipalityIdWidth);if(r===0||r>this.header.municipalityCount)throw new p(`Invalid binary municipality id: ${r}`);let i=this.readMunicipality(r),o=this.requireData().getUint8(n.localidadeFlags.offset+e),a=Ze[o&3],s=ze[o>>>2];if(a===void 0||s===void 0)throw new p(`Invalid binary locality indicators: ${o}`);let l=this.readNeighborhoodIndex(e),c=this.readSparseId(n.localidadeNomeBitmap,n.localidadeNomeRanks,n.localidadeNomeIds,e,this.dictionaries.bairro.idWidth);if(c!==0&&(l!==0||s==="municipio"))throw new p("Invalid binary subordinate locality name");let u=l===0?c:this.readPackedInteger(this.bairros.recordsOffset+(l-1)*this.bairros.recordWidth+this.bairros.originalIdWidth+this.bairros.localidadeIdWidth,this.dictionaries.bairro.idWidth);if(l!==0&&u===0)throw new p("Null binary neighborhood name");return{bairro:this.readCachedDictionaryString(this.dictionaries.bairro,u,this.bairroCache),cep:t,complemento:this.readDictionaryString(this.dictionaries.complemento,this.readSparseId(n.complementoBitmap,n.complementoRanks,n.complementoIds,e,this.dictionaries.complemento.idWidth)),localidade_situacao:a,localidade_tipo:s,logradouro:this.readDictionaryString(this.dictionaries.logradouro,this.readPackedInteger(n.logradouroIds.offset+e*this.dictionaries.logradouro.idWidth,this.dictionaries.logradouro.idWidth)),municipio:i.municipio,municipio_cod_ibge:i.codigoIbge,nome:this.readDictionaryString(this.dictionaries.nome,this.readSparseId(n.nomeBitmap,n.nomeRanks,n.nomeIds,e,this.dictionaries.nome.idWidth)),uf:i.uf}}readMunicipality(e){let t=this.municipalityCache[e];if(t)return t;let n=3+this.dictionaries.municipio.idWidth+this.dictionaries.uf.idWidth,r=this.header.sections.municipalities.offset+(e-1)*n,i=this.readPackedInteger(r+3,this.dictionaries.municipio.idWidth),o=this.readPackedInteger(r+3+this.dictionaries.municipio.idWidth,this.dictionaries.uf.idWidth),a={codigoIbge:this.readPackedInteger(r,3),municipio:this.readRequiredDictionaryString(this.dictionaries.municipio,i,"municipio"),uf:Ke(this.readRequiredDictionaryString(this.dictionaries.uf,o,"uf"))};return this.municipalityCache[e]=a,a}readSparseId(e,t,n,r,i){let o=this.requireMapped(),a=r>>>3,s=o[e.offset+a]??0,l=r&7;if((s&1<<l)===0)return 0;let c=r>>>Ae,u=this.readUint32(t.offset+c*4),d=c*(K>>>3);for(let f=d;f<a;f++)u+=qn[o[e.offset+f]??0]??0;if(u+=qn[s&(1<<l)-1]??0,(u+1)*i>n.length)throw new p(`Invalid binary sparse id index: ${u}`);return this.readPackedInteger(n.offset+u*i,i)}readDictionaryString(e,t){if(t===0)return null;if(t>e.count)throw new p(`Invalid binary string id: ${t}`);let n=this.requireMapped(),r=t-1,i=r>>>P,o=i<<P,a=this.readUint32(e.blockOffsetsOffset+i*4);if(a>e.suffixDataLength)throw new p(`Invalid binary string block offset: ${a}`);let s=e.suffixDataOffset+a,l=this.decodeScratch,c=0;for(let u=o;u<=r;u++){let d=n[e.lengthsOffset+u]??0,f=n[e.prefixesOffset+u]??0;if(u===o&&f!==0||f>c||f>d)throw new p(`Invalid binary front-coded string: ${t}`);let m=d-f;if(s<e.suffixDataOffset||s+m>e.suffixDataOffset+e.suffixDataLength)throw new p(`Invalid binary string suffix: ${t}`);l.set(n.subarray(s,s+m),f),s+=m,c=d}return Wn.decode(l.subarray(0,c))}readCachedDictionaryString(e,t,n){if(t===0)return null;let r=n[t];if(r!==void 0)return r;let i=this.readDictionaryString(e,t);if(i!==null)n[t]=i;return i}readRequiredDictionaryString(e,t,n){let r=this.readDictionaryString(e,t);if(r===null)throw new p(`Binary database has a null required field: ${n}`);return r}readPacked10(e){let t=this.requireMapped(),n=this.header.sections.cepSuffixes,r=e*Se,i=r>>>3,o=r&7,a=n.offset+i;return((t[a]??0)|(t[a+1]??0)<<8|(t[a+2]??0)<<16)>>>o&1023}readPackedInteger(e,t){return q(this.requireData(),e,t)}readUint32(e){return this.requireData().getUint32(e,!0)}requireData(){if(!this.data)throw new Be;return this.data}requireMapped(){if(!this.mapped)throw new Be;return this.mapped}}function Ai(e){if(e.byteLength<v)throw new p("Binary database header is truncated");for(let r=0;r<Q.length;r++)if(e.getUint8(r)!==Q[r])throw new p("Invalid binary database magic");let t=e.getUint16(8,!0);if(t!==me)throw new Xe(t,me);if(e.getUint16(10,!0)!==v)throw new p("Unsupported binary database header size");if(e.getUint8(22)!==Ae||e.getUint8(23)!==P)throw new p("Unsupported binary database block layout");if(e.getUint16(24,!0)!==k.length)throw new p("Unsupported binary database section table");let n={};for(let[r,i]of k.entries()){let o=je+r*8;n[i]={length:e.getUint32(o+4,!0),offset:e.getUint32(o,!0)}}return{cepPrefixOffsetWidth:be(e.getUint8(20),"CEP prefix offset"),fileSize:e.getUint32(16,!0),municipalityCount:e.getUint32(28,!0),municipalityIdWidth:be(e.getUint8(21),"municipality id"),rowCount:e.getUint32(12,!0),sections:n}}function Ti(e,t){if(t.fileSize!==e.byteLength)throw new p(`Binary database size mismatch: header=${t.fileSize}, actual=${e.byteLength}`);if(!t.rowCount||!t.municipalityCount)throw new p("Binary database must contain rows and municipalities");if(t.rowCount>Te(t.cepPrefixOffsetWidth))throw new p("Binary row count does not fit the CEP prefix offset width");if(t.municipalityCount>Te(t.municipalityIdWidth))throw new p("Binary municipality count does not fit its id width");let n=v;for(let i of k){let o=t.sections[i];if(Oi(e.byteLength,o,i),o.offset<n)throw new p(`Binary section is out of order or overlaps: ${i}`);n=o.offset+o.length}if(t.sections.cepPrefixOffsets.length!==Ie*t.cepPrefixOffsetWidth)throw new p("Binary CEP prefix directory has an invalid length");if(t.sections.cepSuffixes.length!==Ge(t.rowCount,Se))throw new p("Binary CEP suffix column has an invalid length");if(t.sections.complementoBitmap.length!==z(t.rowCount)||t.sections.nomeBitmap.length!==z(t.rowCount)||t.sections.localidadeNomeBitmap.length!==z(t.rowCount))throw new p("Binary nullable bitmap has an invalid length");let r=(Math.ceil(t.rowCount/K)+1)*4;if(t.sections.complementoRanks.length!==r||t.sections.nomeRanks.length!==r||t.sections.localidadeNomeRanks.length!==r)throw new p("Binary sparse rank index has an invalid length")}function Ri(e,t){return{bairro:re(e,t.sections.bairroDictionary,"bairro"),bairroAbreviado:re(e,t.sections.bairroAbreviadoDictionary,"bairro abbreviation"),complemento:re(e,t.sections.complementoDictionary,"complemento"),logradouro:re(e,t.sections.logradouroDictionary,"logradouro"),municipio:re(e,t.sections.municipioDictionary,"municipio"),nome:re(e,t.sections.nomeDictionary,"nome"),uf:re(e,t.sections.ufDictionary,"uf")}}function re(e,t,n){if(t.length<De)throw new p(`Binary ${n} dictionary is truncated`);let r=e.getUint32(t.offset,!0),i=e.getUint32(t.offset+4,!0),o=e.getUint32(t.offset+8,!0),a=e.getUint32(t.offset+12,!0),s=e.getUint32(t.offset+16,!0),l=e.getUint32(t.offset+20,!0),c=e.getUint32(t.offset+24,!0),u=be(e.getUint8(t.offset+28),`${n} dictionary id`);if(e.getUint8(t.offset+29)!==P)throw new p(`Unsupported binary ${n} dictionary block size`);if(i!==Math.ceil(r/pe))throw new p(`Binary ${n} dictionary has an invalid block count`);if(r>Te(u))throw new p(`Binary ${n} dictionary does not fit its id width`);if(o!==De||a!==o+i*4||s!==a+r||l!==s+r||l>t.length||c!==t.length-l)throw new p(`Binary ${n} dictionary has an invalid layout`);let d={blockCount:i,blockOffsetsOffset:t.offset+o,count:r,idWidth:u,lengthsOffset:t.offset+a,prefixesOffset:t.offset+s,region:t,suffixDataLength:c,suffixDataOffset:t.offset+l};if(i&&e.getUint32(d.blockOffsetsOffset,!0)!==0)throw new p(`Binary ${n} dictionary has an invalid first block offset`);return d}function Ni(e,t,n){let r=t.sections.bairros;if(r.length<X)throw new p("Binary neighborhood table is truncated");let i=e.getUint32(r.offset,!0),o=be(e.getUint8(r.offset+4),"original neighborhood id"),a=be(e.getUint8(r.offset+5),"original locality id"),s=o+a+n.bairro.idWidth+n.bairroAbreviado.idWidth+n.uf.idWidth;ie(r,X+i*s,"neighborhood table");let l=r.offset+X,c=0;for(let u=0;u<i;u++){let d=l+u*s,f=q(e,d,o);d+=o;let m=q(e,d,a);d+=a;let b=q(e,d,n.bairro.idWidth);d+=n.bairro.idWidth;let g=q(e,d,n.bairroAbreviado.idWidth);d+=n.bairroAbreviado.idWidth;let w=q(e,d,n.uf.idWidth);if(f<=c||m===0||b===0||b>n.bairro.count||g>n.bairroAbreviado.count||w===0||w>n.uf.count)throw new p(`Invalid binary neighborhood record: ${u}`);c=f}return{count:i,idWidth:M(i),originalIdWidth:o,localidadeIdWidth:a,recordsOffset:l,recordWidth:s}}function xi(e,t,n){let{bairroFaixaOffsets:r,bairroFaixas:i}=t.sections;if(ie(r,(n.count+1)*4,"neighborhood range offsets"),i.length%8!==0||e.getUint32(r.offset,!0)!==0)throw new p("Invalid binary neighborhood range layout");let o=i.length/8,a=0;for(let s=0;s<n.count;s++){let l=e.getUint32(r.offset+(s+1)*4,!0);if(l<a||l>o)throw new p("Invalid binary neighborhood range offsets");let c=-1,u=-1;for(let d=a;d<l;d++){let f=e.getUint32(i.offset+d*8,!0),m=e.getUint32(i.offset+d*8+4,!0);if(f>m||m>99999999||f<c||f===c&&m<=u)throw new p("Invalid binary neighborhood CEP range");c=f,u=m}a=l}if(a!==o)throw new p("Unreferenced binary neighborhood CEP ranges")}function Ci(e,t,n,r){let i=t.sections;ie(i.localidadeFlags,t.rowCount,"locality indicators"),ie(i.logradouroIds,t.rowCount*n.logradouro.idWidth,"logradouro ids"),ie(i.bairroIds,t.rowCount*r.idWidth,"bairro indexes"),ie(i.municipalityIds,t.rowCount*t.municipalityIdWidth,"municipality ids");let o=3+n.municipio.idWidth+n.uf.idWidth;ie(i.municipalities,t.municipalityCount*o,"municipalities"),Bt(e,i.complementoRanks,i.complementoIds,n.complemento.idWidth,"complemento"),Bt(e,i.nomeRanks,i.nomeIds,n.nome.idWidth,"nome"),Bt(e,i.localidadeNomeRanks,i.localidadeNomeIds,n.bairro.idWidth,"localidade_nome"),xi(e,t,r);let a=q(e,i.cepPrefixOffsets.offset,t.cepPrefixOffsetWidth),s=q(e,i.cepPrefixOffsets.offset+hn*t.cepPrefixOffsetWidth,t.cepPrefixOffsetWidth);if(a!==0||s!==t.rowCount)throw new p("Binary CEP prefix directory has invalid boundaries")}function Bt(e,t,n,r,i){let o=e.getUint32(t.offset+t.length-4,!0);if(n.length!==o*r)throw new p(`Binary ${i} sparse ids have an invalid length`)}function Li(e,t){let n=Wn.decode(e.subarray(t.offset,t.offset+t.length)),r;try{r=JSON.parse(n)}catch(i){throw new p("Binary database metadata is invalid JSON",{cause:i})}if(!r||typeof r!=="object"||Array.isArray(r))throw new p("Binary database metadata must be an object");return r}function Oi(e,t,n){if(t.offset<v||t.offset>e||t.length>e-t.offset)throw new p(`Binary ${n} region is outside the file`)}function ie(e,t,n){if(e.length!==t)throw new p(`Binary ${n} region has an invalid length`)}import{Database as vi}from"bun:sqlite";class H extends Error{constructor(e,t){super(e,t);this.name=new.target.name}}class ve extends H{path;code="IO_ERROR";constructor(e,t){super(`Unable to access SQLite database: ${e}`,t);this.path=e}}class Me extends H{code="INVALID_SCHEMA";constructor(e,t){super(e,t)}}class Je extends H{code="INVALID_DATA";constructor(e,t){super(e,t)}}class et extends H{code="QUERY_ERROR";constructor(e,t){super(e,t)}}class tt extends H{code="READER_CLOSED";constructor(){super("SQLite database is closed")}}function Bi(e){return jn(e,", ")}function Hn(e){return jn(e,`,
10
- `)}function jn(e,t){let n=e.columns.filter((o)=>o.primaryKey).map((o)=>y(o.name)),r=e.columns.map((o)=>{let a=[y(o.name),o.type];if(o.notNull||o.primaryKey)a.push("NOT NULL");if(o.check)a.push(`CHECK (${o.check})`);if(o.references)a.push(`REFERENCES ${y(o.references.table)} (${y(o.references.column)})`);if(o.comment)a.push(`/* ${o.comment} */`);return a.join(" ")});if(n.length)r.push(`PRIMARY KEY (${n.join(", ")})`);let i=e.withoutRowid??e.unifiedTable?" WITHOUT ROWID":"";if(t.includes(`
11
- `))return`CREATE TABLE IF NOT EXISTS ${y(e.name)} (
12
- ${r.join(t)}
13
- )${i}`;return`CREATE TABLE IF NOT EXISTS ${y(e.name)} (${r.join(t)})${i}`}function oe(e){return`${e}_consulta`}function Mt(e,t=te){return`CREATE VIEW ${y(oe(e))} AS
9
+ `);try{for(let c of i.iterate())yield c}finally{i.finalize()}}function ls(e){if(!e.query("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?").get(Z))return{};let i=e.query(`SELECT key, value FROM ${Tt(Z)}`).all();return Object.fromEntries(i.map((c)=>[c.key,c.value]))}function ti(e,n){return n===null?0:be(e,n,"string")}function be(e,n,i){let c=e.ids.get(n);if(c===void 0)throw Error(`Missing binary ${i} dictionary value: ${n}`);return c}function ht(e,n){if(n!==null)e.add(n)}function ds(e,n){let i=Math.min(e.byteLength,n.byteLength),c=0;while(c<i&&e[c]===n[c])c++;return c}function mn(e,n){let i=n>>>3;e[i]=(e[i]??0)|1<<(n&7)}function fs(e,n){let i=new Uint8Array(e.length*n);for(let c=0;c<e.length;c++)F(i,c*n,e[c]??0,n);return i}function hn(e){if(!/^\d{8}$/.test(e))throw Error(`Invalid CEP in SQLite database: ${e}`);return Number(e)}function As(){let e=new Uint16Array([1]);if(new Uint8Array(e.buffer)[0]!==1)throw Error("Binary database generation requires a little-endian platform")}function qt(e,n){if(!Number.isSafeInteger(e)||e<0||e>ir)throw Error(`Binary ${n} exceeds the uint32 limit: ${e}`)}function Zt(e){return new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}function Tt(e){return`"${e.replaceAll('"','""')}"`}import{mkdirSync as ms,readFileSync as li,renameSync as Ss,rmSync as Kt,statSync as hs,writeFileSync as Ts}from"fs";import{homedir as si}from"os";import{join as Nt,resolve as Dn}from"path";import{stat as Os}from"fs/promises";import{extname as ps,resolve as Is}from"path";import{Database as Rs}from"bun:sqlite";class Ae extends Error{constructor(e,n){super(e,n);this.name=new.target.name}}class bt extends Ae{path;code="IO_ERROR";constructor(e,n){super(`Unable to access SQLite database: ${e}`,n);this.path=e}}class gt extends Ae{code="INVALID_SCHEMA";constructor(e,n){super(e,n)}}class zt extends Ae{code="INVALID_DATA";constructor(e,n){super(e,n)}}class Dt extends Ae{code="QUERY_ERROR";constructor(e,n){super(e,n)}}class Qt extends Ae{code="READER_CLOSED";constructor(){super("SQLite database is closed")}}function Es(e){return ri(e,", ")}function ni(e){return ri(e,`,
10
+ `)}function ri(e,n){let i=e.columns.filter((l)=>l.primaryKey).map((l)=>M(l.name)),c=e.columns.map((l)=>{let d=[M(l.name),l.type];if(l.notNull||l.primaryKey)d.push("NOT NULL");if(l.check)d.push(`CHECK (${l.check})`);if(l.references)d.push(`REFERENCES ${M(l.references.table)} (${M(l.references.column)})`);if(l.comment)d.push(`/* ${l.comment} */`);return d.join(" ")});if(i.length)c.push(`PRIMARY KEY (${i.join(", ")})`);let u=e.withoutRowid??e.unifiedTable?" WITHOUT ROWID":"";if(n.includes(`
11
+ `))return`CREATE TABLE IF NOT EXISTS ${M(e.name)} (
12
+ ${c.join(n)}
13
+ )${u}`;return`CREATE TABLE IF NOT EXISTS ${M(e.name)} (${c.join(n)})${u}`}function Ge(e){return`${e}_consulta`}function Tn(e,n=Te){return`CREATE VIEW ${M(Ge(e))} AS
14
14
  SELECT d.cep, d.logradouro, d.complemento, COALESCE(b.nome, d.localidade_nome) AS bairro,
15
15
  d.municipio, d.municipio_cod_ibge, d.uf, d.nome, d.localidade_situacao, d.localidade_tipo
16
- FROM ${y(e)} d
17
- LEFT JOIN ${y(t)} b ON b.bairro_id = d.bairro_id`}function nt(e,t){let n=J(t),r=t.find((o)=>o.originalName==="bairros");if(!r)throw Error("Neighborhood table definition is missing");let i=Ne(t);e.run(`DROP VIEW IF EXISTS main.${y(oe(n.name))}`);for(let o of[...i].reverse())e.run(`DROP TABLE IF EXISTS main.${y(o.name)}`);for(let o of i)e.run(Bi(o));e.run(Mt(n.name,r.name))}function y(e){return`"${e.replaceAll('"','""')}"`}class rt{databasePath;db;closed=!1;normalizedSchemaReady=!1;constructor(e){this.databasePath=e;let t;try{t=new vi(e,{readonly:!0}),t.run("PRAGMA busy_timeout = 30000"),this.db=t}catch(n){try{t?.close()}catch{}throw new ve(e,{cause:n})}}close(){if(this.closed)return;try{this.db.close(),this.closed=!0}catch(e){throw new ve(this.databasePath,{cause:e})}}hasTable(e){return this.readSafely(()=>Boolean(this.db.query("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?").get(e)))}metadata(){return this.readSafely(()=>{if(!this.hasTable(A))return;let e=this.db.query(`SELECT key, value FROM ${y(A)}`).all();return Object.fromEntries(e.map((t)=>[t.key,t.value]))})}queryCep(e){return this.readSafely(()=>{let t=he(e);if(Number.isNaN(t))return;this.requireCurrentSchema();let n=this.db.query(`SELECT * FROM ${y(oe(T))} WHERE cep = ?`).get(e.length===8?e:`${e.slice(0,5)}${e.slice(6)}`);if(!n)return;if(n.localidade_situacao===void 0||n.localidade_tipo===void 0)throw new Me("Database schema lacks locality indicators. Rebuild the database with build --force.");let r=Ze[n.localidade_situacao],i=ze[ge.indexOf(n.localidade_tipo)];if(r===void 0||i===void 0)throw new Je("Database contains invalid locality indicators. Rebuild the database with build --force.");return{...n,localidade_situacao:r,localidade_tipo:i}})}queryNeighborhood(e){return this.readSafely(()=>{if(!B(e))return;return this.requireCurrentSchema(),this.db.query(`SELECT * FROM ${y(te)} WHERE bairro_id = ?`).get(e)??void 0})}queryNeighborhoodByCep(e){return this.readSafely(()=>{if(Number.isNaN(he(e)))return;return this.requireCurrentSchema(),this.db.query(`
18
- SELECT b.* FROM ${y(T)} d
19
- JOIN ${y(te)} b ON b.bairro_id = d.bairro_id
16
+ FROM ${M(e)} d
17
+ LEFT JOIN ${M(n)} b ON b.bairro_id = d.bairro_id`}function Xt(e,n){let i=_e(n),c=n.find((l)=>l.originalName==="bairros");if(!c)throw Error("Neighborhood table definition is missing");let u=It(n);e.run(`DROP VIEW IF EXISTS main.${M(Ge(i.name))}`);for(let l of[...u].reverse())e.run(`DROP TABLE IF EXISTS main.${M(l.name)}`);for(let l of u)e.run(Es(l));e.run(Tn(i.name,c.name))}function M(e){return`"${e.replaceAll('"','""')}"`}class Jt{databasePath;db;closed=!1;normalizedSchemaReady=!1;cepStatement;neighborhoodStatement;neighborhoodByCepStatement;neighborhoodCepRangesStatement;constructor(e){this.databasePath=e;let n;try{n=new Rs(e,{readonly:!0}),n.run("PRAGMA busy_timeout = 30000"),this.db=n}catch(i){try{n?.close()}catch{}throw new bt(e,{cause:i})}}close(){if(this.closed)return;try{this.db.close(!0),this.cepStatement=void 0,this.neighborhoodStatement=void 0,this.neighborhoodByCepStatement=void 0,this.neighborhoodCepRangesStatement=void 0,this.closed=!0}catch(e){throw new bt(this.databasePath,{cause:e})}}[Symbol.dispose](){this.close()}hasTable(e){return this.readSafely(()=>Boolean(this.db.query("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?").get(e)))}metadata(){return this.readSafely(()=>{if(!this.hasTable(Z))return;let e=this.db.query(`SELECT key, value FROM ${M(Z)}`).all();return Object.fromEntries(e.map((n)=>[n.key,n.value]))})}queryCep(e){return this.readSafely(()=>{let n=st(e);if(Number.isNaN(n))return;this.requireCurrentSchema(),this.cepStatement??=this.db.prepare(`SELECT * FROM ${M(Ge(z))} WHERE cep = ?`);let i=this.cepStatement.get(e.length===8?e:`${e.slice(0,5)}${e.slice(6)}`);if(!i)return;if(i.localidade_situacao===void 0||i.localidade_tipo===void 0)throw new gt("Database schema lacks locality indicators. Rebuild the database with build --force.");let c=ot[i.localidade_situacao],u=it[rt.indexOf(i.localidade_tipo)];if(c===void 0||u===void 0)throw new zt("Database contains invalid locality indicators. Rebuild the database with build --force.");return{...i,localidade_situacao:c,localidade_tipo:u}})}queryNeighborhood(e){return this.readSafely(()=>{if(!oe(e))return;return this.requireCurrentSchema(),this.neighborhoodStatement??=this.db.prepare(`SELECT * FROM ${M(Te)} WHERE bairro_id = ?`),this.neighborhoodStatement.get(e)??void 0})}queryNeighborhoodByCep(e){return this.readSafely(()=>{if(Number.isNaN(st(e)))return;return this.requireCurrentSchema(),this.neighborhoodByCepStatement??=this.db.prepare(`
18
+ SELECT b.* FROM ${M(z)} d
19
+ JOIN ${M(Te)} b ON b.bairro_id = d.bairro_id
20
20
  WHERE d.cep = ?
21
- `).get(e.replace("-",""))??void 0})}queryNeighborhoodCepRanges(e){return this.readSafely(()=>{if(!B(e))return[];return this.requireCurrentSchema(),this.db.query(`
22
- SELECT cep_inicial, cep_final FROM ${y(Ye)}
21
+ `),this.neighborhoodByCepStatement.get(e.replace("-",""))??void 0})}queryNeighborhoodCepRanges(e){return this.readSafely(()=>{if(!oe(e))return[];return this.requireCurrentSchema(),this.neighborhoodCepRangesStatement??=this.db.prepare(`
22
+ SELECT cep_inicial, cep_final FROM ${M(St)}
23
23
  WHERE bairro_id = ? ORDER BY cep_inicial, cep_final
24
- `).all(e)})}requireCurrentSchema(){if(!this.normalizedSchemaReady)this.normalizedSchemaReady=Boolean(this.db.query("SELECT 1 FROM sqlite_master WHERE type = 'view' AND name = ?").get(oe(T)));if(!this.normalizedSchemaReady)throw new Me("Database schema lacks normalized neighborhoods. Rebuild the database with build --force.")}rowCount(e){return this.readSafely(()=>this.db.query(`SELECT count(*) AS count FROM ${y(e)}`).get().count)}tableSchema(e){return this.readSafely(()=>this.db.query("SELECT sql FROM sqlite_master WHERE type = 'table' AND name = ?").get(e)?.sql??void 0)}querySql(e,t){return this.readSafely(()=>{let n=[],r=this.db.query(e);try{for(let i of r.iterate())if(n.push(i),n.length>t)break}finally{r.finalize()}return{rows:n.slice(0,t),truncated:n.length>t}})}readSafely(e){if(this.closed)throw new tt;try{return e()}catch(t){if(t instanceof H)throw t;throw new et(t instanceof Error?t.message:String(t),{cause:t})}}}function Gn(e){if(!e.startsWith("sqlite:///")){if(e.includes("://"))throw Error("Only sqlite:/// database URLs are supported");return e}return e.slice(10)}function j(e,t){let n=Gn(e);if(n===":memory:")return n;return Ui(t==="binary"?`${n.slice(0,n.length-$i(n).length)}.bin`:n)}async function it(e,t=T){if(e===":memory:"||!await Bun.file(e).exists())throw new E("database-not-found",`Base n\xE3o encontrada: ${e}`);let n;try{n=await vt(e)?new ye(e):new rt(e)}catch(i){throw new E("database-invalid",`N\xE3o foi poss\xEDvel abrir a base '${e}': ${zn(i)}`)}if(!(n instanceof ye?t===T:n.hasTable(t)))throw n.close(),new E("database-not-ready",`A base '${e}' n\xE3o cont\xE9m a tabela '${t}'. Execute bunx @konstit/dne build primeiro.`);return n}async function ae(e,t=T){if(e===":memory:"||!await Bun.file(e).exists())return $t(e);let n=null;try{n=(await Mi(e)).size}catch{}try{let r=await vt(e),i=r?new ye(e):new rt(e);try{let o=i instanceof ye,a=o?t===T:i.hasTable(t);return{exists:!0,format:r?"binary":"sqlite",metadata:i.metadata()??null,path:e,ready:a,row_count:a?o?i.rowCount():i.rowCount(t):null,schema:a&&!o?i.tableSchema(t)??null:null,size_bytes:n}}finally{i.close()}}catch(r){return{...$t(e),error:zn(r),exists:!0,size_bytes:n}}}function Qn(e){return{...$t(":memory:"),row_count:e}}function $t(e){return{exists:!1,format:null,metadata:null,path:e,ready:!1,row_count:null,schema:null,size_bytes:null}}function zn(e){return e instanceof Error?e.message:String(e)}async function Kn(e){let t=Pt(e.database),n=nr(t),r=Gi(e.source??n?.source??Z),i=Wi(e.expression,t,r,e.packageVersion),o=e.dryRun?"preview":n?"updated":"installed";if(!e.dryRun)await Hi(i,n);return{...i,next_run:rr(i.expression),status:o}}function Jn(e){let t=Pt(e),n=tr(t),r=nr(t);return{command:r?.command??null,database:t,expression:r?.expression??null,id:n,installed:r!==null,next_run:r?rr(r.expression):null,package_version:r?.package_version??null,runner:r?.runner??null,source:r?.source??null,title:n}}async function er(e){let t=Pt(e),n=st(t),r=se(n.metadata)||se(n.runner);try{await Bun.cron.remove(n.title)}catch(i){throw new E("cron-remove-failed",`N\xE3o foi poss\xEDvel remover o agendamento: ${ir(i)}`)}return at(n.metadata,{force:!0}),at(n.runner,{force:!0}),{database:t,id:n.title,removed:r,title:n.title}}function Wi(e,t,n,r){let i=Bun.which("bunx");if(!i)throw new E("bunx-not-found","O execut\xE1vel bunx n\xE3o foi encontrado. Instale o Bun antes de criar o agendamento.");if(/[\r\n\0]/.test(e)||/[\r\n\0]/.test(i))throw new E("invalid-cron-value","A express\xE3o cron e o caminho do bunx n\xE3o podem conter quebras de linha ou bytes nulos.",2);let o=st(t),a=Ft(i),s=`@konstit/dne@${r}`;return{command:[ot(a),ot(s),"build","--db",ot(t),"--source",ot(n),"--quiet"].join(" "),database:t,expression:e,id:o.title,package_version:r,runner:o.runner,source:n,title:o.title}}async function Hi(e,t){let n=st(e.database);Fi(n.directory,{mode:448,recursive:!0});let r=Yn(n.runner),i=Yn(n.metadata);try{Ut(n.runner,ji(e)),await Bun.cron(n.runner,e.expression,e.title),Ut(n.metadata,`${JSON.stringify(e,null,2)}
25
- `)}catch(o){Vn(n.runner,r),Vn(n.metadata,i);try{if(t)await Bun.cron(t.runner,t.expression,t.title);else await Bun.cron.remove(e.title)}catch{}throw new E("cron-install-failed",`N\xE3o foi poss\xEDvel instalar o agendamento: ${ir(o)}`)}}function ji(e){let t=[Bun.which("bunx"),`@konstit/dne@${e.package_version}`,"build","--db",e.database,"--source",e.source,"--quiet"];if(t[0]===null)throw new E("bunx-not-found","O execut\xE1vel bunx n\xE3o foi encontrado.");return[`const command = ${JSON.stringify(t)};`,"","export default {"," async scheduled() {"," const child = Bun.spawn(command, { stderr: 'inherit', stdout: 'ignore' });"," const exitCode = await child.exited;"," if (exitCode !== 0) {"," throw new Error('@konstit/dne build failed with exit code ' + exitCode);"," }"," },","};",""].join(`
26
- `)}function Pt(e){let t=j(e);if(t===":memory:")throw new E("invalid-cron-database","O agendamento exige um caminho persistente para a base.",2);if(/[\r\n\0]/.test(t))throw new E("invalid-cron-database","O caminho da base n\xE3o pode conter quebras de linha ou bytes nulos.",2);return t}function Gi(e){if(/[\r\n\0]/.test(e))throw new E("invalid-cron-source","A fonte n\xE3o pode conter quebras de linha ou bytes nulos.",2);return Qi(e)?e:Ft(e)}function tr(e){return`konstit-dne-${new Bun.CryptoHasher("sha256").update(e).digest("hex").slice(0,32)}`}function st(e){let t=tr(e),n=Bun.env.XDG_STATE_HOME?Ft(Bun.env.XDG_STATE_HOME):process.platform==="darwin"?$e(Zn(),"Library","Application Support"):$e(Zn(),".local","state"),r=$e(n,"konstit-dne","cron");return{directory:r,metadata:$e(r,`${t}.json`),runner:$e(r,`${t}.mjs`),title:t}}function nr(e){let t=st(e);if(!se(t.metadata)&&!se(t.runner))return null;if(!se(t.metadata)||!se(t.runner))throw new E("cron-config-invalid",`A configura\xE7\xE3o do agendamento '${t.title}' est\xE1 incompleta.`);try{let n=JSON.parse(Xn(t.metadata,"utf8"));if(n.database!==e||n.id!==t.title||n.title!==t.title||n.runner!==t.runner||typeof n.command!=="string"||typeof n.expression!=="string"||typeof n.package_version!=="string")throw Error("invalid cron metadata");return Bun.cron.parse(n.expression),{...n,source:typeof n.source==="string"?n.source:Z}}catch{throw new E("cron-config-invalid",`A configura\xE7\xE3o do agendamento '${t.title}' \xE9 inv\xE1lida.`)}}function rr(e){return Bun.cron.parse(e)?.toISOString()??null}function Ut(e,t){let n=`${e}.${process.pid}.${crypto.randomUUID()}.tmp`;try{qi(n,t,{mode:384}),Pi(n,e)}finally{at(n,{force:!0})}}function Yn(e){return se(e)?Xn(e,"utf8"):null}function Vn(e,t){if(t===null)at(e,{force:!0});else Ut(e,t)}function se(e){try{return ki(e),!0}catch(t){if(t&&typeof t==="object"&&"code"in t&&t.code==="ENOENT")return!1;throw t}}function ot(e){return`'${e.replaceAll("'","'\\''")}'`}function Qi(e){try{let t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"}catch{return!1}}function ir(e){return e instanceof Error?e.message:String(e)}class ce extends Error{constructor(e){super(e);this.name="DneSourceQualityError"}}class kt{stages;constructor(){this.stages=new Map}counter(e,t){let n=this.stage(e),r=this.file(e,t);return{read(){n.read++,r.read++},accept(){n.accepted++,r.accepted++},reject(i){n.rejected++,r.rejected++,ar(n.rejectionReasons,i),ar(r.rejectionReasons,i)}}}assertValid(){let e=Array.from(this.stages.values()).reduce((r,i)=>r+i.rejected,0);if(!e)return;let t=new Map;for(let r of this.stages.values())for(let[i,o]of r.rejectionReasons)t.set(i,(t.get(i)??0)+o);let n=Array.from(t).map(([r,i])=>`${r}=${i}`).join(", ");throw new ce(`DNE source quality validation failed: ${e} rejected row(s) (${n})`)}report(e){let t={read:0,accepted:0,rejected:0},n={};for(let[r,i]of this.stages){t.read+=i.read,t.accepted+=i.accepted,t.rejected+=i.rejected;let o={};for(let[a,s]of i.files)o[a]=sr(s);n[r]={...sr(i),files:o}}return{version:1,status:"passed",output_rows:e,totals:t,stages:n}}stage(e){let t=this.stages.get(e);if(!t)t={...or(),files:new Map},this.stages.set(e,t);return t}file(e,t){let n=this.stage(e),r=n.files.get(t);if(!r)r=or(),n.files.set(t,r);return r}}function or(){return{read:0,accepted:0,rejected:0,rejectionReasons:new Map}}function ar(e,t){e.set(t,(e.get(t)??0)+1)}function sr(e){return{read:e.read,accepted:e.accepted,rejected:e.rejected,rejection_reasons:Object.fromEntries(e.rejectionReasons)}}import{Database as zi}from"bun:sqlite";import{mkdirSync as Wt,readFileSync as Zi,renameSync as Yi,rmSync as ct,statSync as Ht,writeFileSync as lr}from"fs";import{tmpdir as Vi}from"os";import{basename as Xi,dirname as qt,join as Fe}from"path";var Ki=30000,Ji=50,eo=["SIGHUP","SIGINT","SIGTERM"];async function ur(e,t){let n=to(e),r=Fe(qt(e),`.${Xi(e)}.fetch.lock`),i={pid:process.pid,token:crypto.randomUUID()},o=performance.now()+Ki,a=!1;Wt(qt(e),{recursive:!0}),Wt(qt(n),{mode:448,recursive:!0});while(no(r)){if(cr(r))continue;await u()}while(!ro(n,i)){if(cr(n))continue;await u()}if(a)t.finish();let s=!1,l=()=>{if(s)return;s=!0,c(),ao(n,i.token)},c=so(l);return{release:l};async function u(){if(!a)t("Aguardando outra atualiza\xE7\xE3o da base"),a=!0;if(performance.now()>=o)throw new E("update-in-progress",`Outra execu\xE7\xE3o de build j\xE1 est\xE1 atualizando a base '${e}'.`);await Bun.sleep(Ji)}}function to(e){let t=new Bun.CryptoHasher("sha256").update(e).digest("hex");return Fe(Vi(),`konstit-dne-${process.getuid?.()??"unknown"}`,`fetch-${t}.lock`)}function no(e){try{return Ht(e),!0}catch(t){if(Ue(t))return!1;throw t}}function ro(e,t){let n=`${e}.${t.pid}.${t.token}.tmp`;Wt(n);try{return lr(Fe(n,"owner.json"),JSON.stringify(t),{flag:"wx"}),Yi(n,e),!0}catch(r){if(jt(r))return!1;throw r}finally{ct(n,{force:!0,recursive:!0})}}function cr(e){let t;try{t=Ht(e)}catch(r){if(Ue(r))return!0;throw r}if(!t.isDirectory())return io(e);let n=dr(e);if(n&&oo(n.pid))return!1;try{lr(Fe(e,"reaper.json"),JSON.stringify({pid:process.pid,token:crypto.randomUUID()}),{flag:"wx"})}catch(r){if(jt(r))return!1;if(Ue(r))return!0;throw r}return ct(e,{force:!0,recursive:!0}),!0}function io(e){let t=new zi(e);try{t.run("PRAGMA busy_timeout = 0"),t.run("BEGIN IMMEDIATE"),t.run("ROLLBACK")}catch(n){if(co(n))return!1;throw n}finally{t.close()}try{return ct(e,{force:!0}),!0}catch(n){if(Ue(n))return!0;if(jt(n))return!1;try{if(Ht(e).isDirectory())return!1}catch(r){if(Ue(r))return!0;throw r}throw n}}function dr(e){try{let t=JSON.parse(Zi(Fe(e,"owner.json"),"utf8"));return Number.isInteger(t.pid)&&Number(t.pid)>0&&typeof t.token==="string"?{pid:Number(t.pid),token:t.token}:null}catch{return null}}function oo(e){try{return process.kill(e,0),!0}catch(t){return!(t&&typeof t==="object"&&("code"in t)&&t.code==="ESRCH")}}function ao(e,t){if(dr(e)?.token===t)ct(e,{force:!0,recursive:!0})}function so(e){let t=()=>e(),n=eo.map((r)=>{let i=()=>{e(),process.kill(process.pid,r)};return process.once(r,i),{handler:i,signal:r}});return process.once("exit",t),()=>{process.off("exit",t);for(let{handler:r,signal:i}of n)process.off(i,r)}}function jt(e){return Gt(e,"EACCES","EEXIST","ENOTEMPTY","EPERM")}function Ue(e){return Gt(e,"ENOENT")}function Gt(e,...t){return Boolean(e&&typeof e==="object"&&"code"in e&&typeof e.code==="string"&&t.includes(e.code))}function co(e){if(Gt(e,"SQLITE_BUSY","SQLITE_LOCKED"))return!0;let t=e instanceof Error?e.message:String(e);return/database is locked|database table is locked/i.test(t)}async function fr(){let e=await Bun.file(new URL("../package.json",import.meta.url)).json();if(typeof e.version!=="string"||!e.version)throw Error("package.json has no valid version");return e.version}import{mkdtemp as Yo,rm as Vo}from"fs/promises";import{tmpdir as Xo}from"os";import{join as Yt}from"path";import{mkdir as lo,rename as uo,rm as fo}from"fs/promises";import{basename as ut,dirname as mo,join as hr}from"path";var yr="Delimitado",Er="latin1",Ic=new TextDecoder(Er),po=32,bo=20,go=10,ho=16,yo=30,Eo=28,lt=46,wo=33639248,_o=42,Io=24,So=0,Do=8,Zt=22,Ao=101010256,To=65535,wr=Zt+To,Ro=16,No=12,xo=28,Co=26,mr=30,Lo=67324752;class Qt{path;files;constructor(e){this.path=e;this.files=Array.from(new Bun.Glob("*").scanSync({cwd:e,onlyFiles:!0})).sort()}matchingFiles(e){return Dr(this.files,e)}async*readLines(e){yield*Tr(Bun.file(hr(this.path,e)).stream())}}class _r{path;files;entriesByFile;constructor(e,t){this.path=e;this.files=t.map((n)=>ut(n.name)).sort(),this.entriesByFile=new Map(t.map((n)=>[ut(n.name),n]))}matchingFiles(e){return Dr(this.files,e)}async*readLines(e){let t=this.entriesByFile.get(e);if(!t)throw Error(`DNE data file not found: ${e}`);yield*Tr(Ar(this.path,t))}}function Ir(e,t){if(!br(e))return null;let n=new Qt(e);if(!zt(n,t))return n;let r=hr(e,yr);if(!br(r))return null;let i=new Qt(r);return zt(i,t)?null:i}async function Sr(e,t,n){let r=await gr(e),i=vo(r);if(i)return await Fo(e,i,n),pr(n,await gr(n),t);return pr(e,r,t)}function pr(e,t,n){let r=Oo(t,n),i=new _r(e,r);return Bo(i,r,n),i}function Oo(e,t){return e.filter((n)=>Mo(n.name,t))}function Bo(e,t,n){if(!t.length)throw Error("ZIP file does not contain DNE Basico files");let r=zt(e,n);if(r)throw Error(`DNE data file not found: ${r}`)}function vo(e){return e.find((t)=>{let n=ut(t.name).toLowerCase();return n.startsWith("edne_basico_")&&n.endsWith(".zip")})}function br(e){try{return new Bun.Glob("*").scanSync({cwd:e,onlyFiles:!0}).next(),!0}catch{return!1}}function zt(e,t){for(let n of t){let r=xe(n);if(r&&e.matchingFiles(r).length===0)return r}return null}function Dr(e,t){if(!t.includes("*"))return e.filter((i)=>i===t);let[n="",r=""]=t.split("*",2);return e.filter((i)=>i.startsWith(n)&&i.endsWith(r))}function Mo(e,t){let n=e.toLowerCase();if(!n.startsWith(`${yr.toLowerCase()}/`))return!1;let r=ut(n);return t.some((i)=>{let o=xe(i)?.toLowerCase();if(!o)return!1;if(!o.includes("*"))return r===o;let[a="",s=""]=o.split("*",2);return r.startsWith(a)&&r.endsWith(s)})}async function gr(e){let t=Bun.file(e),n=t.size;if(n<Zt)throw Error("Source is not a valid ZIP file");let r=Math.max(0,n-wr),i=Buffer.from(await t.slice(r,n).arrayBuffer()),o=Uo(i),a=i.readUInt32LE(o+No),s=i.readUInt32LE(o+Ro),l=s+a;if(l>n)throw Error("Invalid ZIP central directory range");let c=Buffer.from(await t.slice(s,l).arrayBuffer());return $o(c)}function $o(e){let t=[],n=0;while(n<e.length){if(n+lt>e.length||e.readUInt32LE(n)!==wo)throw Error("Invalid ZIP central directory entry");let r=e.readUInt16LE(n+go),i=e.readUInt32LE(n+ho),o=e.readUInt32LE(n+bo),a=e.readUInt32LE(n+Io),s=e.readUInt16LE(n+Eo),l=e.readUInt16LE(n+yo),c=e.readUInt16LE(n+po),u=e.readUInt32LE(n+_o),d=lt+s+l+c;if(n+d>e.length)throw Error("Invalid ZIP central directory entry size");let f=e.subarray(n+lt,n+lt+s).toString("utf8");if(!f.endsWith("/"))t.push({name:f,compression:r,crc32:i,compressedSize:o,uncompressedSize:a,localHeaderOffset:u});n+=d}return t}function Uo(e){for(let t=e.length-Zt;t>=Math.max(0,e.length-wr);t--)if(e.readUInt32LE(t)===Ao)return t;throw Error("Source is not a valid ZIP file")}async function*Ar(e,t){let n=Bun.file(e),r=t.localHeaderOffset+mr,i=Buffer.from(await n.slice(t.localHeaderOffset,r).arrayBuffer());if(i.length!==mr||i.readUInt32LE(0)!==Lo)throw Error(`Invalid ZIP local header for ${t.name}`);let o=i.readUInt16LE(Co),a=i.readUInt16LE(xo),s=r+o+a,l=s+t.compressedSize;if(l>n.size)throw Error(`Invalid ZIP data range for ${t.name}`);let c=n.slice(s,l).stream(),u;if(t.compression===So)u=c;else if(t.compression===Do)u=c.pipeThrough(new DecompressionStream("deflate-raw"));else throw Error(`Unsupported ZIP compression method ${t.compression} for ${t.name}`);let d=0,f=0;for await(let m of u)d+=m.byteLength,f=Bun.hash.crc32(m,f),yield m;if(t.uncompressedSize&&d!==t.uncompressedSize)throw Error(`Invalid decompressed size for ${t.name}`);Po(t,f)}async function Fo(e,t,n){if(await Bun.file(n).exists())return;await lo(mo(n),{recursive:!0});let r=`${n}.${process.pid}.${crypto.randomUUID()}.tmp`,i=Bun.file(r).writer(),o=!1;try{for await(let a of Ar(e,t))await i.write(a);await i.end(),o=!0;try{await uo(r,n)}catch(a){if(!await Bun.file(n).exists())throw a}}finally{if(!o)await Promise.resolve(i.end()).catch(()=>{});await fo(r,{force:!0})}}async function*Tr(e){let t=new TextDecoder(Er),n="";for await(let r of e){let i=n+t.decode(r,{stream:!0}),o=0,a=i.indexOf(`
27
- `);while(a!==-1){let s=a>o&&i.charCodeAt(a-1)===13?a-1:a;if(s>o)yield i.slice(o,s);o=a+1,a=i.indexOf(`
28
- `,o)}n=i.slice(o)}if(n+=t.decode(),n.endsWith("\r"))n=n.slice(0,-1);if(n)yield n}function Po(e,t){if(t!==e.crc32)throw Error(`CRC32 mismatch for ${e.name}`)}import{open as xr}from"fs/promises";class Pe extends Error{constructor(e){super(e)}}async function Cr(e,t,n,r={}){let i=Ho(n.contentLength);if(!Wo(n.acceptRanges)||i===null){await Rr(e,t,r);return}try{await ko(e,t,i,r)}catch(o){if(!(o instanceof Pe))throw o;await Rr(e,t,r)}}async function ko(e,t,n,r){let i=Math.ceil(n/Ve),o=await xr(t,"w"),a=new AbortController,s=Or(r.signal,a.signal);try{await o.truncate(n);let l=0,c=Array.from({length:Math.min(i,Tn)},async()=>{while(!0){let u=l++;if(u>=i)return;let d=u*Ve,f=Math.min(d+Ve,n)-1;await qo(e,o,{start:d,end:f},n,{...r,signal:s})}});try{await Promise.all(c)}catch(u){throw a.abort(),await Promise.allSettled(c),u}}finally{await o.close()}}async function qo(e,t,n,r,i){await ke(e,{headers:{"accept-encoding":"identity",range:`bytes=${n.start}-${n.end}`}},async(o)=>{if(o.status!==206){if(await o.body?.cancel(),o.ok)throw new Pe(`Server ignored byte range ${n.start}-${n.end}`);throw Error(`Failed to download ${e}: ${o.status}`)}let a=jo(o.headers.get("content-range"));if(!a||a.start!==n.start||a.end!==n.end||a.length!==r)throw await o.body?.cancel(),new Pe(`Server returned an invalid Content-Range for ${n.start}-${n.end}`);let s=new Uint8Array(await o.arrayBuffer()),l=n.end-n.start+1;if(s.byteLength!==l)throw new Pe(`Server returned ${s.byteLength} bytes for range ${n.start}-${n.end}; expected ${l}`);await Lr(t,s,n.start)},i)}async function Rr(e,t,n){let r=await xr(t,"w");try{await ke(e,{},async(i)=>{if(!i.ok)throw await i.body?.cancel(),Error(`Failed to download ${e}: ${i.status}`);if(!i.body)throw Error(`Failed to stream ${e}: empty response body`);await r.truncate(0);let o=i.body.getReader(),a=0;try{while(!0){let s=await o.read();if(s.done)break;await Lr(r,s.value,a),a+=s.value.byteLength}}catch(s){throw await o.cancel().catch(()=>{}),s}finally{o.releaseLock()}},n)}finally{await r.close()}}async function ke(e,t,n,r={}){let i=r.timeoutMs??Rn,o=r.maxRetries??Nn,a=r.retryBaseDelayMs??xn,s=r.retryMaxDelayMs??Cn,l=r.retryAfterMaxMs??Ln,c;for(let u=0;;u++){Br(r.signal);let d=AbortSignal.timeout(i),f=Or(r.signal,d);try{let m=await fetch(e,{...t,signal:f,verbose:!1});if(Go(m.status)&&u<o){let b=zo(m.headers.get("retry-after"),u,a,s,l);await m.body?.cancel(),await Nr(b,r.signal);continue}c=await n(m);break}catch(m){if(r.signal?.aborted)throw r.signal.reason??m;if(u>=o||!Qo(m))throw m;let b=Math.min(a*2**u,s);await Nr(b,r.signal)}}return c}async function Lr(e,t,n){let r=0;while(r<t.byteLength){let i=await e.write(t,r,t.byteLength-r,n+r);if(!i.bytesWritten)throw Error("Failed to write downloaded content");r+=i.bytesWritten}}function Wo(e){return e?.split(",").some((t)=>t.trim().toLowerCase()==="bytes")??!1}function Ho(e){if(e===null||!/^\d+$/.test(e))return null;let t=Number(e);return Number.isSafeInteger(t)?t:null}function jo(e){let t=e?/^bytes (\d+)-(\d+)\/(\d+)$/i.exec(e):null;if(!t?.[1]||!t[2]||!t[3])return null;return{start:Number(t[1]),end:Number(t[2]),length:Number(t[3])}}function Go(e){return e===408||e===425||e===429||e>=500&&e<=599}function Qo(e){if(!(e instanceof Error))return!1;if(e.name==="AbortError"||e.name==="TimeoutError"||e instanceof TypeError)return!0;let t="code"in e&&typeof e.code==="string"?e.code:void 0;return t==="ECONNRESET"||t==="ECONNREFUSED"||t==="EHOSTUNREACH"||t==="ENETUNREACH"||t==="ETIMEDOUT"||t==="EAI_AGAIN"}function zo(e,t,n,r,i){let o=Zo(e);if(o!==null)return Math.min(o,i);return Math.min(n*2**t,r)}function Zo(e){if(e===null)return null;let t=e.trim();if(/^\d+(?:\.\d+)?$/.test(t))return Number(t)*1000;let n=Date.parse(t);return Number.isNaN(n)?null:Math.max(0,n-Date.now())}function Or(e,t){return e?AbortSignal.any([e,t]):t}function Br(e){if(e?.aborted)throw e.reason??new DOMException("The operation was aborted","AbortError")}async function Nr(e,t){if(e<=0){Br(t);return}await new Promise((n,r)=>{let o=setTimeout(()=>{t?.removeEventListener("abort",a),n()},e),a=()=>{clearTimeout(o),r(t?.reason??new DOMException("The operation was aborted","AbortError"))};if(t?.addEventListener("abort",a,{once:!0}),t?.aborted)a()})}class dt{source;options;tempDir;constructor(e,t={}){this.source=e;this.options=t}async resolve(e){try{return await this.resolveSource(this.source??Z,e)}catch(t){throw await this.cleanup(),t}}async cleanup(){if(this.tempDir)await Vo(this.tempDir,{recursive:!0,force:!0}),this.tempDir=void 0}async getTempDir(){return this.tempDir??=await Yo(Yt(Xo(),"edne")),this.tempDir}async resolveSource(e,t){let n=e;if(Jo(e))n=await this.download(e);if(await Bun.file(n).exists()){this.progress("Preparando a fonte ZIP");let i=Yt(await this.getTempDir(),"edne-inner.zip"),o=await Sr(n,t,i);return this.progress("Fonte ZIP pronta"),o}this.progress("Lendo a fonte do diret\xF3rio");let r=Ir(n,t);if(r)return this.progress("Fonte do diret\xF3rio pronta"),r;throw Error(`DNE source not found: ${n}`)}async download(e){let t=this.options.remoteInfo??await ft(e),n=await this.getTempDir(),r=Yt(n,"edne-download.zip");return this.progress("Baixando o arquivo DNE"),await Cr(e,r,t),r}progress(e){this.options.onProgress?.(e)}}async function ft(e,t={}){try{return await ke(e,{method:"HEAD"},async(n)=>{if(!n.ok)throw Error(`Failed to inspect DNE from ${e}: ${n.status}`);return vr(e,n.headers)},t)}catch{return await ke(e,{headers:{"accept-encoding":"identity",range:"bytes=0-0"}},async(n)=>{let r=Ko(e,n);if(await n.body?.cancel(),!n.ok)throw Error(`Failed to inspect DNE from ${e}: ${n.status}`);return r},t)}}function vr(e,t){return{url:e,lastModified:t.get("last-modified"),etag:t.get("etag"),contentLength:t.get("content-length"),acceptRanges:t.get("accept-ranges")}}function Ko(e,t){let n=vr(e,t.headers);if(t.status!==206)return n;let r=/^bytes 0-0\/(\d+)$/i.exec(t.headers.get("content-range")??"");return{...n,contentLength:r?.[1]??null,acceptRanges:n.acceptRanges??"bytes"}}function Jo(e){try{let t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"}catch{return!1}}import{Database as ra}from"bun:sqlite";async function le(e,t,n,r,i){let o=xe(e);if(!o)return;let a=t.matchingFiles(o);if(!a.length)throw Error(`DNE data file not found: ${o}`);for(let s of a){let l=r.counter(e.originalName,s);if(t.readText){let c=await t.readText(s);ta(c,(u,d)=>{l.read(),i($r(c,u,d,n),s,l)});continue}for await(let c of t.readLines(s))l.read(),i(ea(c,n),s,l)}}function ea(e,t){return $r(e,0,e.length,t)}function $r(e,t,n,r){let i=Array.from({length:r.length},()=>null),o=0,a=0,s=t;for(let l=t;l<=n;l++){if(l!==n&&e.charCodeAt(l)!==64)continue;if(a===r[o]){if(i[o]=na(e,s,l),o++,o===r.length)break}a++,s=l+1}return i}function ta(e,t){let n=0;for(let r=0;r<=e.length;r++){if(r!==e.length&&e.charCodeAt(r)!==10)continue;let i=r;if(i>n&&e.charCodeAt(i-1)===13)i--;if(i>n)t(n,i);n=r+1}}function na(e,t,n){if(t===n)return null;let r=e.charCodeAt(t),i=e.charCodeAt(n-1),o=Mr(r)||Mr(i)?e.slice(t,n).trim():e.slice(t,n);return o===""?null:o}function Mr(e){return e<=32||e===160}class Vt{db;tableName;batchSize;rows=[];statements=new Map;constructor(e,t,n){this.db=e;this.tableName=t;this.batchSize=n}run(...e){if(this.rows.push(e),this.rows.length>=this.batchSize)this.flush()}flush(){if(!this.rows.length)return;let e=this.rows;this.rows=[];let t=Array.from({length:e.length*11},()=>null);for(let n=0;n<e.length;n++){let r=e[n];if(!r)throw Error(`Missing row at index ${n}`);let i=n*11;for(let o=0;o<r.length;o++)t[i+o]=r[o]??null}this.statementFor(e.length).run(...t)}finalize(){for(let e of this.statements.values())e.finalize();this.statements.clear()}statementFor(e){let t=this.statements.get(e);if(t)return t;let n=Array.from({length:e},()=>"(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)").join(", ");return t=this.db.prepare(`
29
- INSERT INTO ${y(this.tableName)}
24
+ `),this.neighborhoodCepRangesStatement.all(e)})}requireCurrentSchema(){if(!this.normalizedSchemaReady)this.normalizedSchemaReady=Boolean(this.db.query("SELECT 1 FROM sqlite_master WHERE type = 'view' AND name = ?").get(Ge(z)))&&this.hasTable(Te)&&this.hasTable(St);if(!this.normalizedSchemaReady)throw new gt("Database schema lacks normalized neighborhoods. Rebuild the database with build --force.")}rowCount(e){return this.readSafely(()=>this.db.query(`SELECT count(*) AS count FROM ${M(e)}`).get().count)}tableSchema(e){return this.readSafely(()=>this.db.query("SELECT sql FROM sqlite_master WHERE type = 'table' AND name = ?").get(e)?.sql??void 0)}querySql(e,n){return this.readSafely(()=>{if(!Number.isSafeInteger(n)||n<=0)throw new Dt("SQL row limit must be a positive safe integer.");let i=[],c=!1,u=this.db.query(e);try{for(let l of u.iterate()){if(i.length===n){c=!0;break}i.push(l)}}finally{u.finalize()}return{rows:i,truncated:c}})}readSafely(e){if(this.closed)throw new Qt;try{return e()}catch(n){if(n instanceof Ae)throw n;throw new Dt(n instanceof Error?n.message:String(n),{cause:n})}}}function ii(e){if(!e.startsWith("sqlite:///")){if(e.includes("://"))throw Error("Only sqlite:/// database URLs are supported");return e}return e.slice(10)}function ae(e,n){let i=ii(e);if(i===":memory:")return i;return Is(n==="binary"?`${i.slice(0,i.length-ps(i).length)}.bin`:i)}async function yt(e,n=z){if(e===":memory:"||!await Bun.file(e).exists())throw new w("database-not-found",`Base n\xE3o encontrada: ${e}`);let i;try{i=await On(e)?new he(e):new Jt(e)}catch(u){throw new w("database-invalid",`N\xE3o foi poss\xEDvel abrir a base '${e}': ${ai(u)}`)}if(!(i instanceof he?n===z:i.hasTable(n)))throw i.close(),new w("database-not-ready",`A base '${e}' n\xE3o cont\xE9m a tabela '${n}'. Execute bunx @konstit/dne build --source CAMINHO_OU_URL primeiro.`);return i}async function $e(e,n=z){if(e===":memory:"||!await Bun.file(e).exists())return bn(e);let i=null;try{i=(await Os(e)).size}catch{}try{let c=await On(e),u=c?new he(e):new Jt(e);try{let l=u instanceof he,d=l?n===z:u.hasTable(n);return{exists:!0,format:c?"binary":"sqlite",metadata:u.metadata()??null,path:e,ready:d,row_count:d?l?u.rowCount():u.rowCount(n):null,schema:d&&!l?u.tableSchema(n)??null:null,size_bytes:i}}finally{u.close()}}catch(c){return{...bn(e),error:ai(c),exists:!0,size_bytes:i}}}function oi(e){return{...bn(":memory:"),row_count:e}}function bn(e){return{exists:!1,format:null,metadata:null,path:e,ready:!1,row_count:null,schema:null,size_bytes:null}}function ai(e){return e instanceof Error?e.message:String(e)}async function di(e){let n=yn(e.database),i=Ri(n),c=ys(e.source),u=bs(e.expression,n,c,e.packageVersion),l=e.dryRun?"preview":i?"updated":"installed";if(!e.dryRun)await gs(u,i);return{...u,next_run:Oi(u.expression),status:l}}function fi(e){let n=yn(e),i=Ei(n),c=Ri(n);return{command:c?.command??null,database:n,expression:c?.expression??null,id:i,installed:c!==null,next_run:c?Oi(c.expression):null,package_version:c?.package_version??null,runner:c?.runner??null,source:c?.source??null,title:i}}async function Ai(e){let n=yn(e),i=en(n),c=ke(i.metadata)||ke(i.runner);try{await Bun.cron.remove(i.title)}catch(u){throw new w("cron-remove-failed",`N\xE3o foi poss\xEDvel remover o agendamento: ${pi(u)}`)}return Kt(i.metadata,{force:!0}),Kt(i.runner,{force:!0}),{database:n,id:i.title,removed:c,title:i.title}}function bs(e,n,i,c){let u=Bun.which("bunx");if(!u)throw new w("bunx-not-found","O execut\xE1vel bunx n\xE3o foi encontrado. Instale o Bun antes de criar o agendamento.");if(/[\r\n\0]/.test(e)||/[\r\n\0]/.test(u))throw new w("invalid-cron-value","A express\xE3o cron e o caminho do bunx n\xE3o podem conter quebras de linha ou bytes nulos.",2);let l=en(n),d=Dn(u),A=`@konstit/dne@${c}`;return{command:[Yt(d),Yt(A),"build","--db",Yt(n),"--source",Yt(i),"--quiet"].join(" "),database:n,expression:e,id:l.title,package_version:c,runner:l.runner,source:i,title:l.title}}async function gs(e,n){let i=en(e.database);ms(i.directory,{mode:448,recursive:!0});let c=ci(i.runner),u=ci(i.metadata);try{gn(i.runner,Ds(e)),await Bun.cron(i.runner,e.expression,e.title),gn(i.metadata,`${JSON.stringify(e,null,2)}
25
+ `)}catch(l){ui(i.runner,c),ui(i.metadata,u);try{if(n)await Bun.cron(n.runner,n.expression,n.title);else await Bun.cron.remove(e.title)}catch{}throw new w("cron-install-failed",`N\xE3o foi poss\xEDvel instalar o agendamento: ${pi(l)}`)}}function Ds(e){let n=[Bun.which("bunx"),`@konstit/dne@${e.package_version}`,"build","--db",e.database,"--source",e.source,"--quiet"];if(n[0]===null)throw new w("bunx-not-found","O execut\xE1vel bunx n\xE3o foi encontrado.");return[`const command = ${JSON.stringify(n)};`,"","export default {"," async scheduled() {"," const child = Bun.spawn(command, { stderr: 'inherit', stdout: 'ignore' });"," const exitCode = await child.exited;"," if (exitCode !== 0) {"," throw new Error('@konstit/dne build failed with exit code ' + exitCode);"," }"," },","};",""].join(`
26
+ `)}function yn(e){let n=ae(e);if(n===":memory:")throw new w("invalid-cron-database","O agendamento exige um caminho persistente para a base.",2);if(/[\r\n\0]/.test(n))throw new w("invalid-cron-database","O caminho da base n\xE3o pode conter quebras de linha ou bytes nulos.",2);return n}function ys(e){if(/[\r\n\0]/.test(e))throw new w("invalid-cron-source","A fonte n\xE3o pode conter quebras de linha ou bytes nulos.",2);return Ns(e)?e:Dn(e)}function Ei(e){return`konstit-dne-${new Bun.CryptoHasher("sha256").update(e).digest("hex").slice(0,32)}`}function en(e){let n=Ei(e),i=Bun.env.XDG_STATE_HOME?Dn(Bun.env.XDG_STATE_HOME):process.platform==="darwin"?Nt(si(),"Library","Application Support"):Nt(si(),".local","state"),c=Nt(i,"konstit-dne","cron");return{directory:c,metadata:Nt(c,`${n}.json`),runner:Nt(c,`${n}.mjs`),title:n}}function Ri(e){let n=en(e);if(!ke(n.metadata)&&!ke(n.runner))return null;if(!ke(n.metadata)||!ke(n.runner))throw new w("cron-config-invalid",`A configura\xE7\xE3o do agendamento '${n.title}' est\xE1 incompleta.`);try{let i=JSON.parse(li(n.metadata,"utf8"));if(i.database!==e||i.id!==n.title||i.title!==n.title||i.runner!==n.runner||typeof i.command!=="string"||typeof i.expression!=="string"||typeof i.package_version!=="string")throw Error("invalid cron metadata");return Bun.cron.parse(i.expression),{...i,source:typeof i.source==="string"?i.source:null}}catch{throw new w("cron-config-invalid",`A configura\xE7\xE3o do agendamento '${n.title}' \xE9 inv\xE1lida.`)}}function Oi(e){return Bun.cron.parse(e)?.toISOString()??null}function gn(e,n){let i=`${e}.${process.pid}.${crypto.randomUUID()}.tmp`;try{Ts(i,n,{mode:384}),Ss(i,e)}finally{Kt(i,{force:!0})}}function ci(e){return ke(e)?li(e,"utf8"):null}function ui(e,n){if(n===null)Kt(e,{force:!0});else gn(e,n)}function ke(e){try{return hs(e),!0}catch(n){if(n&&typeof n==="object"&&"code"in n&&n.code==="ENOENT")return!1;throw n}}function Yt(e){return`'${e.replaceAll("'","'\\''")}'`}function Ns(e){try{let n=new URL(e);return n.protocol==="http:"||n.protocol==="https:"}catch{return!1}}function pi(e){return e instanceof Error?e.message:String(e)}class He extends Error{constructor(e){super(e);this.name="DneSourceQualityError"}}class Nn{stages;constructor(){this.stages=new Map}counter(e,n){let i=this.stage(e),c=this.file(e,n);return{read(){i.read++,c.read++},accept(){i.accepted++,c.accepted++},reject(u){i.rejected++,c.rejected++,mi(i.rejectionReasons,u),mi(c.rejectionReasons,u)}}}assertValid(){let e=Array.from(this.stages.values()).reduce((c,u)=>c+u.rejected,0);if(!e)return;let n=new Map;for(let c of this.stages.values())for(let[u,l]of c.rejectionReasons)n.set(u,(n.get(u)??0)+l);let i=Array.from(n).map(([c,u])=>`${c}=${u}`).join(", ");throw new He(`DNE source quality validation failed: ${e} rejected row(s) (${i})`)}report(e){let n={read:0,accepted:0,rejected:0},i={};for(let[c,u]of this.stages){n.read+=u.read,n.accepted+=u.accepted,n.rejected+=u.rejected;let l={};for(let[d,A]of u.files)l[d]=Si(A);i[c]={...Si(u),files:l}}return{version:1,status:"passed",output_rows:e,totals:n,stages:i}}stage(e){let n=this.stages.get(e);if(!n)n={...Ii(),files:new Map},this.stages.set(e,n);return n}file(e,n){let i=this.stage(e),c=i.files.get(n);if(!c)c=Ii(),i.files.set(n,c);return c}}function Ii(){return{read:0,accepted:0,rejected:0,rejectionReasons:new Map}}function mi(e,n){e.set(n,(e.get(n)??0)+1)}function Si(e){return{read:e.read,accepted:e.accepted,rejected:e.rejected,rejection_reasons:Object.fromEntries(e.rejectionReasons)}}import{Database as Cs}from"bun:sqlite";import{mkdirSync as Ln,readFileSync as Ls,renameSync as ws,rmSync as tn,statSync as wn,writeFileSync as Ti}from"fs";import{tmpdir as Ms}from"os";import{basename as Us,dirname as Cn,join as Lt}from"path";var Ps=30000,Bs=50,_s=["SIGHUP","SIGINT","SIGTERM"];async function bi(e,n){let i=xs(e),c=Lt(Cn(e),`.${Us(e)}.fetch.lock`),u={pid:process.pid,token:crypto.randomUUID()},l=performance.now()+Ps,d=!1;Ln(Cn(e),{recursive:!0}),Ln(Cn(i),{mode:448,recursive:!0});while(Vs(c)){if(hi(c))continue;await O()}while(!Fs(i,u)){if(hi(i))continue;await O()}if(d)n.finish();let A=!1,E=()=>{if(A)return;A=!0,R(),$s(i,u.token)},R=ks(E);return{release:E};async function O(){if(!d)n("Aguardando outra atualiza\xE7\xE3o da base"),d=!0;if(performance.now()>=l)throw new w("update-in-progress",`Outra execu\xE7\xE3o de build j\xE1 est\xE1 atualizando a base '${e}'.`);await Bun.sleep(Bs)}}function xs(e){let n=new Bun.CryptoHasher("sha256").update(e).digest("hex");return Lt(Ms(),`konstit-dne-${process.getuid?.()??"unknown"}`,`fetch-${n}.lock`)}function Vs(e){try{return wn(e),!0}catch(n){if(Ct(n))return!1;throw n}}function Fs(e,n){let i=`${e}.${n.pid}.${n.token}.tmp`;Ln(i);try{return Ti(Lt(i,"owner.json"),JSON.stringify(n),{flag:"wx"}),ws(i,e),!0}catch(c){if(Mn(c))return!1;throw c}finally{tn(i,{force:!0,recursive:!0})}}function hi(e){let n;try{n=wn(e)}catch(c){if(Ct(c))return!0;throw c}if(!n.isDirectory())return vs(e);let i=gi(e);if(i&&Gs(i.pid))return!1;try{Ti(Lt(e,"reaper.json"),JSON.stringify({pid:process.pid,token:crypto.randomUUID()}),{flag:"wx"})}catch(c){if(Mn(c))return!1;if(Ct(c))return!0;throw c}return tn(e,{force:!0,recursive:!0}),!0}function vs(e){let n=new Cs(e);try{n.run("PRAGMA busy_timeout = 0"),n.run("BEGIN IMMEDIATE"),n.run("ROLLBACK")}catch(i){if(Hs(i))return!1;throw i}finally{n.close()}try{return tn(e,{force:!0}),!0}catch(i){if(Ct(i))return!0;if(Mn(i))return!1;try{if(wn(e).isDirectory())return!1}catch(c){if(Ct(c))return!0;throw c}throw i}}function gi(e){try{let n=JSON.parse(Ls(Lt(e,"owner.json"),"utf8"));return Number.isInteger(n.pid)&&Number(n.pid)>0&&typeof n.token==="string"?{pid:Number(n.pid),token:n.token}:null}catch{return null}}function Gs(e){try{return process.kill(e,0),!0}catch(n){return!(n&&typeof n==="object"&&("code"in n)&&n.code==="ESRCH")}}function $s(e,n){if(gi(e)?.token===n)tn(e,{force:!0,recursive:!0})}function ks(e){let n=()=>e(),i=_s.map((c)=>{let u=()=>{e(),process.kill(process.pid,c)};return process.once(c,u),{handler:u,signal:c}});return process.once("exit",n),()=>{process.off("exit",n);for(let{handler:c,signal:u}of i)process.off(u,c)}}function Mn(e){return Un(e,"EACCES","EEXIST","ENOTEMPTY","EPERM")}function Ct(e){return Un(e,"ENOENT")}function Un(e,...n){return Boolean(e&&typeof e==="object"&&"code"in e&&typeof e.code==="string"&&n.includes(e.code))}function Hs(e){if(Un(e,"SQLITE_BUSY","SQLITE_LOCKED"))return!0;let n=e instanceof Error?e.message:String(e);return/database is locked|database table is locked/i.test(n)}async function Di(){let e=await Bun.file(new URL("../package.json",import.meta.url)).json();if(typeof e.version!=="string"||!e.version)throw Error("package.json has no valid version");return e.version}import{mkdir as Ws,rename as js,rm as qs}from"fs/promises";import{basename as rn,dirname as Zs,join as wi}from"path";var Mi="Delimitado",Ui="latin1",Kd=new TextDecoder(Ui),zs=32,Qs=20,Xs=10,Js=16,Ys=30,Ks=28,nn=46,ec=33639248,tc=42,nc=24,rc=0,ic=8,_n=22,oc=101010256,ac=65535,Pi=_n+ac,sc=16,cc=12,uc=28,lc=26,yi=30,dc=67324752;class Pn{path;files;constructor(e){this.path=e;this.files=Array.from(new Bun.Glob("*").scanSync({cwd:e,onlyFiles:!0})).sort()}matchingFiles(e){return vi(this.files,e)}async*readLines(e){yield*$i(Bun.file(wi(this.path,e)).stream())}}class Bi{path;files;entriesByFile;constructor(e,n){this.path=e;this.files=n.map((i)=>rn(i.name)).sort(),this.entriesByFile=new Map(n.map((i)=>[rn(i.name),i]))}matchingFiles(e){return vi(this.files,e)}async*readLines(e){let n=this.entriesByFile.get(e);if(!n)throw Error(`DNE data file not found: ${e}`);yield*$i(Gi(this.path,n))}}function _i(e,n){if(!Ci(e))return null;let i=new Pn(e);if(!Bn(i,n))return i;let c=wi(e,Mi);if(!Ci(c))return null;let u=new Pn(c);return Bn(u,n)?null:u}async function xi(e,n,i){let c=await Li(e),u=Fi(c),l;if(u)await Rc(e,u,i),l=Ni(i,await Li(i),n);else l=Ni(e,c,n);return l.zipEntries=xn(c,n),l}function Ni(e,n,i){let c=Vi(n,i),u=new Bi(e,c);return fc(u,c,i),u}function Vi(e,n){return e.filter((i)=>Ac(i.name,n))}function fc(e,n,i){if(!n.length)throw Error("ZIP file does not contain DNE Basico files");let c=Bn(e,i);if(c)throw Error(`DNE data file not found: ${c}`)}function Fi(e){return e.find((n)=>{let i=rn(n.name).toLowerCase();return i.startsWith("edne_basico_")&&i.endsWith(".zip")})}function xn(e,n){let i=Fi(e);return(i?[i]:Vi(e,n)).map((c)=>({name:c.name,size:c.uncompressedSize,crc32:c.crc32.toString(16).padStart(8,"0")})).sort((c,u)=>c.name<u.name?-1:c.name>u.name?1:0)}function Ci(e){try{return new Bun.Glob("*").scanSync({cwd:e,onlyFiles:!0}).next(),!0}catch{return!1}}function Bn(e,n){for(let i of n){let c=mt(i);if(c&&e.matchingFiles(c).length===0)return c}return null}function vi(e,n){if(!n.includes("*"))return e.filter((u)=>u===n);let[i="",c=""]=n.split("*",2);return e.filter((u)=>u.startsWith(i)&&u.endsWith(c))}function Ac(e,n){let i=e.toLowerCase();if(!i.startsWith(`${Mi.toLowerCase()}/`))return!1;let c=rn(i);return n.some((u)=>{let l=mt(u)?.toLowerCase();if(!l)return!1;if(!l.includes("*"))return c===l;let[d="",A=""]=l.split("*",2);return c.startsWith(d)&&c.endsWith(A)})}async function Li(e){let n=Bun.file(e),i=n.size;if(i<_n)throw Error("Source is not a valid ZIP file");let c=Math.max(0,i-Pi),u=Buffer.from(await n.slice(c,i).arrayBuffer()),l=Ec(u),d=u.readUInt32LE(l+cc),A=u.readUInt32LE(l+sc),E=A+d;if(E>i)throw Error("Invalid ZIP central directory range");let R=Buffer.from(await n.slice(A,E).arrayBuffer());return Vn(R)}function Vn(e,n){let i=[],c=0,u=0;while(c<e.length){if(c+nn>e.length||e.readUInt32LE(c)!==ec)throw Error("Invalid ZIP central directory entry");let l=e.readUInt16LE(c+Xs),d=e.readUInt32LE(c+Js),A=e.readUInt32LE(c+Qs),E=e.readUInt32LE(c+nc),R=e.readUInt16LE(c+Ks),O=e.readUInt16LE(c+Ys),p=e.readUInt16LE(c+zs),I=e.readUInt32LE(c+tc),m=nn+R+O+p;if(c+m>e.length)throw Error("Invalid ZIP central directory entry size");let S=e.subarray(c+nn,c+nn+R).toString("utf8");if(!S.endsWith("/"))i.push({name:S,flags:e.readUInt16LE(c+8),disk:e.readUInt16LE(c+34),compression:l,crc32:d,compressedSize:A,uncompressedSize:E,localHeaderOffset:I});c+=m,u++}if(n!==void 0&&u!==n)throw Error("Invalid ZIP central directory entry count");return i}function Ec(e){for(let n=e.length-_n;n>=Math.max(0,e.length-Pi);n--)if(e.readUInt32LE(n)===oc)return n;throw Error("Source is not a valid ZIP file")}async function*Gi(e,n){let i=Bun.file(e),c=n.localHeaderOffset+yi,u=Buffer.from(await i.slice(n.localHeaderOffset,c).arrayBuffer());if(u.length!==yi||u.readUInt32LE(0)!==dc)throw Error(`Invalid ZIP local header for ${n.name}`);let l=u.readUInt16LE(lc),d=u.readUInt16LE(uc),A=c+l+d,E=A+n.compressedSize;if(E>i.size)throw Error(`Invalid ZIP data range for ${n.name}`);let R=i.slice(A,E).stream(),O;if(n.compression===rc)O=R;else if(n.compression===ic)O=R.pipeThrough(new DecompressionStream("deflate-raw"));else throw Error(`Unsupported ZIP compression method ${n.compression} for ${n.name}`);let p=0,I=0;for await(let m of O)p+=m.byteLength,I=Bun.hash.crc32(m,I),yield m;if(n.uncompressedSize&&p!==n.uncompressedSize)throw Error(`Invalid decompressed size for ${n.name}`);Oc(n,I)}async function Rc(e,n,i){if(await Bun.file(i).exists())return;await Ws(Zs(i),{recursive:!0});let c=`${i}.${process.pid}.${crypto.randomUUID()}.tmp`,u=Bun.file(c).writer(),l=!1;try{for await(let d of Gi(e,n))await u.write(d);await u.end(),l=!0;try{await js(c,i)}catch(d){if(!await Bun.file(i).exists())throw d}}finally{if(!l)await Promise.resolve(u.end()).catch(()=>{});await qs(c,{force:!0})}}async function*$i(e){let n=new TextDecoder(Ui),i="";for await(let c of e){let u=i+n.decode(c,{stream:!0}),l=0,d=u.indexOf(`
27
+ `);while(d!==-1){let A=d>l&&u.charCodeAt(d-1)===13?d-1:d;if(A>l)yield u.slice(l,A);l=d+1,d=u.indexOf(`
28
+ `,l)}i=u.slice(l)}if(i+=n.decode(),i.endsWith("\r"))i=i.slice(0,-1);if(i)yield i}function Oc(e,n){if(n!==e.crc32)throw Error(`CRC32 mismatch for ${e.name}`)}import{open as Wi}from"fs/promises";class wt extends Error{constructor(e){super(e)}}async function ji(e,n,i,c={}){let u=Sc(i.contentLength);if(!mc(i.acceptRanges)||u===null){await ki(e,n,c);return}try{await pc(e,n,u,c)}catch(l){if(!(l instanceof wt))throw l;await ki(e,n,c)}}async function pc(e,n,i,c){let u=Math.ceil(i/jt),l=await Wi(n,"w"),d=new AbortController,A=Zi(c.signal,d.signal);try{await l.truncate(i);let E=0,R=Array.from({length:Math.min(u,Zr)},async()=>{while(!0){let O=E++;if(O>=u)return;let p=O*jt,I=Math.min(p+jt,i)-1;await Ic(e,l,{start:p,end:I},i,{...c,signal:A})}});try{await Promise.all(R)}catch(O){throw d.abort(),await Promise.allSettled(R),O}}finally{await l.close()}}async function Ic(e,n,i,c,u){await We(e,{headers:{"accept-encoding":"identity",range:`bytes=${i.start}-${i.end}`}},async(l)=>{if(l.status!==206){if(await l.body?.cancel(),l.ok)throw new wt(`Server ignored byte range ${i.start}-${i.end}`);throw Error(`Failed to download ${e}: ${l.status}`)}let d=hc(l.headers.get("content-range"));if(!d||d.start!==i.start||d.end!==i.end||d.length!==c)throw await l.body?.cancel(),new wt(`Server returned an invalid Content-Range for ${i.start}-${i.end}`);let A=new Uint8Array(await l.arrayBuffer()),E=i.end-i.start+1;if(A.byteLength!==E)throw new wt(`Server returned ${A.byteLength} bytes for range ${i.start}-${i.end}; expected ${E}`);await qi(n,A,i.start)},u)}async function ki(e,n,i){let c=await Wi(n,"w");try{await We(e,{},async(u)=>{if(!u.ok)throw await u.body?.cancel(),Error(`Failed to download ${e}: ${u.status}`);if(!u.body)throw Error(`Failed to stream ${e}: empty response body`);await c.truncate(0);let l=u.body.getReader(),d=0;try{while(!0){let A=await l.read();if(A.done)break;await qi(c,A.value,d),d+=A.value.byteLength}}catch(A){throw await l.cancel().catch(()=>{}),A}finally{l.releaseLock()}},i)}finally{await c.close()}}async function We(e,n,i,c={}){let u=c.timeoutMs??zr,l=c.maxRetries??Qr,d=c.retryBaseDelayMs??Xr,A=c.retryMaxDelayMs??Jr,E=c.retryAfterMaxMs??Yr,R;for(let O=0;;O++){zi(c.signal);let p=AbortSignal.timeout(u),I=Zi(c.signal,p);try{let m=await fetch(e,{...n,signal:I,verbose:!1});if(Tc(m.status)&&O<l){let S=gc(m.headers.get("retry-after"),O,d,A,E);await m.body?.cancel(),await Hi(S,c.signal);continue}R=await i(m);break}catch(m){if(c.signal?.aborted)throw c.signal.reason??m;if(O>=l||!bc(m))throw m;let S=Math.min(d*2**O,A);await Hi(S,c.signal)}}return R}async function qi(e,n,i){let c=0;while(c<n.byteLength){let u=await e.write(n,c,n.byteLength-c,i+c);if(!u.bytesWritten)throw Error("Failed to write downloaded content");c+=u.bytesWritten}}function mc(e){return e?.split(",").some((n)=>n.trim().toLowerCase()==="bytes")??!1}function Sc(e){if(e===null||!/^\d+$/.test(e))return null;let n=Number(e);return Number.isSafeInteger(n)?n:null}function hc(e){let n=e?/^bytes (\d+)-(\d+)\/(\d+)$/i.exec(e):null;if(!n?.[1]||!n[2]||!n[3])return null;return{start:Number(n[1]),end:Number(n[2]),length:Number(n[3])}}function Tc(e){return e===408||e===425||e===429||e>=500&&e<=599}function bc(e){if(!(e instanceof Error))return!1;if(e.name==="AbortError"||e.name==="TimeoutError"||e instanceof TypeError)return!0;let n="code"in e&&typeof e.code==="string"?e.code:void 0;return n==="ECONNRESET"||n==="ECONNREFUSED"||n==="EHOSTUNREACH"||n==="ENETUNREACH"||n==="ETIMEDOUT"||n==="EAI_AGAIN"}function gc(e,n,i,c,u){let l=Dc(e);if(l!==null)return Math.min(l,u);return Math.min(i*2**n,c)}function Dc(e){if(e===null)return null;let n=e.trim();if(/^\d+(?:\.\d+)?$/.test(n))return Number(n)*1000;let i=Date.parse(n);return Number.isNaN(i)?null:Math.max(0,i-Date.now())}function Zi(e,n){return e?AbortSignal.any([e,n]):n}function zi(e){if(e?.aborted)throw e.reason??new DOMException("The operation was aborted","AbortError")}async function Hi(e,n){if(e<=0){zi(n);return}await new Promise((i,c)=>{let l=setTimeout(()=>{n?.removeEventListener("abort",d),i()},e),d=()=>{clearTimeout(l),c(n?.reason??new DOMException("The operation was aborted","AbortError"))};if(n?.addEventListener("abort",d,{once:!0}),n?.aborted)d()})}import{mkdtemp as yc,rm as Nc}from"fs/promises";import{tmpdir as Cc}from"os";import{join as Fn}from"path";class on{source;options;tempDir;constructor(e,n={}){this.source=e;this.options=n}async resolve(e){try{return await this.resolveSource(this.source,e)}catch(n){throw await this.cleanup(),n}}async cleanup(){if(this.tempDir)await Nc(this.tempDir,{recursive:!0,force:!0}),this.tempDir=void 0}async getTempDir(){return this.tempDir??=await yc(Fn(Cc(),"edne")),this.tempDir}async resolveSource(e,n){let i=e;if(wc(e))i=await this.download(e);if(await Bun.file(i).exists()){this.progress("Preparando a fonte ZIP");let u=Fn(await this.getTempDir(),"edne-inner.zip"),l=await xi(i,n,u);return this.progress("Fonte ZIP pronta"),l}this.progress("Lendo a fonte do diret\xF3rio");let c=_i(i,n);if(c)return this.progress("Fonte do diret\xF3rio pronta"),c;throw Error(`DNE source not found: ${i}`)}async download(e){let n=this.options.remoteInfo??await Mt(e),i=await this.getTempDir(),c=Fn(i,"edne-download.zip");return this.progress("Baixando o arquivo DNE"),await ji(e,c,n),c}progress(e){this.options.onProgress?.(e)}}async function Mt(e,n={}){try{return await We(e,{method:"HEAD"},async(i)=>{if(!i.ok)throw Error(`Failed to inspect DNE from ${e}: ${i.status}`);return Qi(e,i.headers)},n)}catch{return await We(e,{headers:{"accept-encoding":"identity",range:"bytes=0-0"}},async(i)=>{let c=Lc(e,i);if(await i.body?.cancel(),!i.ok)throw Error(`Failed to inspect DNE from ${e}: ${i.status}`);return c},n)}}function Qi(e,n){return{url:e,lastModified:n.get("last-modified"),etag:n.get("etag"),contentLength:n.get("content-length"),acceptRanges:n.get("accept-ranges")}}function Lc(e,n){let i=Qi(e,n.headers);if(n.status!==206)return i;let c=/^bytes 0-0\/(\d+)$/i.exec(n.headers.get("content-range")??"");return{...i,contentLength:c?.[1]??null,acceptRanges:i.acceptRanges??"bytes"}}function wc(e){try{let n=new URL(e);return n.protocol==="http:"||n.protocol==="https:"}catch{return!1}}var Ut=22,Mc=Ut+65535,Uc=4194304;async function Ji(e,n,i={}){try{return await Pc(e,n,i)}catch(c){if(i.signal?.aborted)throw i.signal.reason??c;return{...await Mt(e,i),acceptRanges:null,zipEntries:null}}}async function Pc(e,n,i){let c=await vn(e,{suffix:Ut},i),u=Xi(c.bytes);if(u<0)c=await vn(e,{suffix:Mc},i),u=Xi(c.bytes);if(u<0)throw Error("Missing ZIP central directory trailer");let l=c.bytes.subarray(u),d=l.readUInt16LE(10),A=l.readUInt32LE(12),E=l.readUInt32LE(16),R=c.start+u;if(l.readUInt16LE(4)!==0||l.readUInt16LE(6)!==0||l.readUInt16LE(8)!==d||d===0||d===65535||A===0||A>Uc||E===4294967295||E+A!==R)throw Error("Unsupported ZIP central directory layout");let O=E>=c.start?c.bytes.subarray(E-c.start,E-c.start+A):(await vn(e,{start:E,end:E+A-1,total:c.total},i)).bytes,p=Vn(O,d);if(p.some((m)=>m.disk!==0||(m.flags&8257)!==0||m.compressedSize===4294967295||m.uncompressedSize===4294967295||m.localHeaderOffset+30+m.compressedSize>E||m.compression!==0&&m.compression!==8))throw Error("Unsupported ZIP entry layout");let I=xn(p,n);if(I.length===0||new Set(I.map((m)=>m.name)).size!==I.length)throw Error("Missing or ambiguous DNE ZIP entries");return{...c.info,zipEntries:I}}function Xi(e){for(let n=e.length-Ut;n>=0;n--)if(e.readUInt32LE(n)===101010256&&n+Ut+e.readUInt16LE(n+20)===e.length)return n;return-1}async function vn(e,n,i){let c="suffix"in n?`bytes=-${n.suffix}`:`bytes=${n.start}-${n.end}`;return We(e,{headers:{range:c,"accept-encoding":"identity"}},async(u)=>{try{let l=/^bytes (\d+)-(\d+)\/(\d+)$/i.exec(u.headers.get("content-range")??"");if(u.status!==206||!l)throw Error("ZIP range inspection is not supported");let d=Number(l[1]),A=Number(l[2]),E=Number(l[3]),R="suffix"in n?Math.max(0,E-n.suffix):n.start,O="suffix"in n?E-1:n.end,p=u.headers.get("content-encoding"),I=u.headers.get("content-length");if(!Number.isSafeInteger(E)||E<Ut||d!==R||A!==O||!("suffix"in n)&&E!==n.total||p!==null&&p!=="identity"||I!==null&&Number(I)!==A-d+1)throw Error("Invalid ZIP range response");let m=await Bc(u,A-d+1),S={url:e,etag:u.headers.get("etag"),lastModified:u.headers.get("last-modified"),contentLength:String(E),acceptRanges:"bytes"};return{bytes:m,start:d,total:E,info:S}}finally{await u.body?.cancel()}},i)}async function Bc(e,n){if(!e.body)throw Error("Empty ZIP range response");let i=e.body.getReader(),c=Buffer.alloc(n),u=0;try{while(!0){let l=await i.read();if(l.done)break;if(u+l.value.length>n)throw Error("Oversized ZIP range response");c.set(l.value,u),u+=l.value.length}if(u!==n)throw Error("Truncated ZIP range response");return c}finally{i.releaseLock()}}import{Database as Fc}from"bun:sqlite";async function je(e,n,i,c,u){let l=mt(e);if(!l)return;let d=n.matchingFiles(l);if(!d.length)throw Error(`DNE data file not found: ${l}`);for(let A of d){let E=c.counter(e.originalName,A);if(n.readText){let R=await n.readText(A);xc(R,(O,p)=>{E.read(),u(Ki(R,O,p,i),A,E)});continue}for await(let R of n.readLines(A))E.read(),u(_c(R,i),A,E)}}function _c(e,n){return Ki(e,0,e.length,n)}function Ki(e,n,i,c){let u=Array.from({length:c.length},()=>null),l=0,d=0,A=n;for(let E=n;E<=i;E++){if(E!==i&&e.charCodeAt(E)!==64)continue;if(d===c[l]){if(u[l]=Vc(e,A,E),l++,l===c.length)break}d++,A=E+1}return u}function xc(e,n){let i=0;for(let c=0;c<=e.length;c++){if(c!==e.length&&e.charCodeAt(c)!==10)continue;let u=c;if(u>i&&e.charCodeAt(u-1)===13)u--;if(u>i)n(i,u);i=c+1}}function Vc(e,n,i){if(n===i)return null;let c=e.charCodeAt(n),u=e.charCodeAt(i-1),l=Yi(c)||Yi(u)?e.slice(n,i).trim():e.slice(n,i);return l===""?null:l}function Yi(e){return e<=32||e===160}class Gn{db;tableName;batchSize;rows=[];statements=new Map;constructor(e,n,i){this.db=e;this.tableName=n;this.batchSize=i}run(...e){if(this.rows.push(e),this.rows.length>=this.batchSize)this.flush()}flush(){if(!this.rows.length)return;let e=this.rows;this.rows=[];let n=Array.from({length:e.length*11},()=>null);for(let[i,c]of e.entries()){let u=i*11;for(let l=0;l<c.length;l++)n[u+l]=c[l]??null}this.statementFor(e.length).run(...n)}finalize(){for(let e of this.statements.values())e.finalize();this.statements.clear()}statementFor(e){let n=this.statements.get(e);if(n)return n;let i=Array.from({length:e},()=>"(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)").join(", ");return n=this.db.prepare(`
29
+ INSERT INTO ${M(this.tableName)}
30
30
  (cep, logradouro, complemento, bairro_id, localidade_nome, municipio, municipio_cod_ibge, uf, nome, localidade_situacao, localidade_tipo)
31
- VALUES ${n}
32
- `),this.statements.set(e,t),t}}class Kt{schema;db;tableByOriginalName;unifiedTable;constructor(e,t){this.schema=t;this.db=new ra(e),this.tableByOriginalName=new Map(t.map((n)=>[n.originalName,n])),this.unifiedTable=J(t)}close(){this.db.run("PRAGMA locking_mode = NORMAL"),this.db.run("PRAGMA wal_checkpoint(TRUNCATE);"),this.db.close()}compact(){this.db.run("VACUUM")}async loadFromSource(e,t={},n=()=>{}){let r=this.unifiedTable,i=new kt;return this.configureBulkLoad(),await this.transaction(async()=>{nt(this.db,this.schema),this.createMetadataTable(),this.db.run(`DELETE FROM ${y(A)}`),n("Lendo munic\xEDpios");let o=await this.readLocalidades(e,i);n("Lendo bairros");let a=await this.readBairros(e,o,i);this.insertBairros(a),n("Carregando faixas de CEP dos bairros"),await this.insertFaixasBairro(e,a,i);let s=this.prepareUnifiedInsert(r.name);try{if(n("Carregando logradouros"),await this.insertLogradouros(e,s,o,a,i),n("Carregando munic\xEDpios"),this.insertLocalidades(s,o),this.insertLocalidadesSubordinadas(s,o),n("Carregando endere\xE7os especiais"),await this.insertCpcs(e,s,o,i),await this.insertGrandesUsuarios(e,s,o,a,i),await this.insertUnidadesOperacionais(e,s,o,a,i),i.assertValid(),!o.size)throw new ce("DNE source quality validation failed: no accepted localidade rows");s.flush();let l=this.rowCount(r.name);if(!l)throw new ce("DNE source quality validation failed: no CEP rows produced");let c=i.report(l);this.writeMetadata({...t,schema_version:Re,quality_report:JSON.stringify(c),quality_rows_accepted:String(c.totals.accepted),quality_rows_read:String(c.totals.read),quality_rows_rejected:String(c.totals.rejected)})}finally{s.finalize()}}),this.rowCount(r.name)}async readLocalidades(e,t){let n=this.originalTable("log_localidade"),r=new Map;await le(n,e,ee(n,["locNu","uf","nome","cep","situacao","tipo","locNuSub","munNu"]),t,(o,a,s)=>{let[l=null,c=null,u=null,d=null,f=null,m=null,b=null,g=null]=o,w=We([["locNu",l],["uf",c],["nome",u],["situacao",f],["tipo",m]]);if(w||!l||!c||!u){s.reject(w??"invalid_structure");return}if(!qe(c)){s.reject("invalid_uf");return}if(d!==null&&!Ee(d)){s.reject("invalid_cep");return}if(g!==null&&!oa(g)){s.reject("invalid_ibge");return}if(f!=="0"&&f!=="1"&&f!=="2"&&f!=="3"){s.reject("invalid_localidade_situacao");return}let h=ge.find((I)=>I===m);if(!h){s.reject("invalid_localidade_tipo");return}if(r.has(l)){s.reject("duplicate_localidade");return}r.set(l,{uf:c,nome:u,cep:d,locNuSub:b,munNu:g===null?null:Number(g),situacao:Number(f),tipo:h,quality:s})});let i=new Map;for(let[o,a]of r){let s=a.locNuSub?r.get(a.locNuSub):void 0;if(a.locNuSub&&(!s||s.munNu===null)){a.quality.reject("missing_parent_localidade");continue}if(s&&s.uf!==a.uf){a.quality.reject("localidade_uf_mismatch");continue}if(!a.locNuSub&&a.munNu===null){a.quality.reject("missing_ibge");continue}i.set(o,a),a.quality.accept()}return i}async readBairros(e,t,n){let r=this.originalTable("log_bairro"),i=new Map;return await le(r,e,ee(r,["baiNu","uf","locNu","bairro","abreviado"]),n,(o,a,s)=>{let[l=null,c=null,u=null,d=null,f=null]=o,m=We([["baiNu",l],["uf",c],["locNu",u],["bairro",d]]);if(m||!l||!c||!u||!d){s.reject(m??"invalid_structure");return}let b=Fr(l);if(b===null||Fr(u)===null){s.reject("invalid_bairro_identifier");return}if(!qe(c)){s.reject("invalid_uf");return}let g=t.get(u);if(!g){s.reject("missing_localidade");return}if(g.uf!==c){s.reject("bairro_uf_mismatch");return}if(i.has(l)){s.reject("duplicate_bairro");return}i.set(l,{id:b,uf:c,locNu:u,nome:d,abreviado:f}),s.accept()}),i}insertBairros(e){let t=this.originalTable("bairros"),n=this.db.prepare(`
33
- INSERT INTO ${y(t.name)} (bairro_id, localidade_id, uf, nome, nome_abreviado) VALUES (?, ?, ?, ?, ?)
34
- `);try{for(let r of e.values())n.run(r.id,Number(r.locNu),r.uf,r.nome,r.abreviado)}finally{n.finalize()}}async insertFaixasBairro(e,t,n){let r=this.originalTable("log_faixa_bairro"),i=this.originalTable("bairro_faixas"),o=new Set,a=this.db.prepare(`INSERT INTO ${y(i.name)} (bairro_id, cep_inicial, cep_final) VALUES (?, ?, ?)`);try{await le(r,e,ee(r,["baiNu","cepInicial","cepFinal"]),n,(s,l,c)=>{let[u=null,d=null,f=null]=s,m=u===null?void 0:t.get(u);if(!m){c.reject("missing_bairro");return}if(!Ee(d)||!Ee(f)){c.reject("invalid_cep_range");return}if(d>f){c.reject("reversed_cep_range");return}let b=`${m.id}:${d}:${f}`;if(o.has(b)){c.reject("duplicate_cep_range");return}o.add(b),a.run(m.id,d,f),c.accept()})}finally{a.finalize()}}prepareUnifiedInsert(e){return new Vt(this.db,e,An)}rowCount(e){return this.db.query(`SELECT count(*) AS count FROM ${y(e)}`).get().count}async insertLogradouros(e,t,n,r,i){let o=this.originalTable("log_logradouro");await le(o,e,ee(o,["uf","locNu","baiNuIni","logNo","cep","tloTx","logStaTlo"]),i,(a,s,l)=>{let[c=null,u=null,d=null,f=null,m=null,b=null,g=null]=a,w=We([["uf",c],["locNu",u],["baiNuIni",d],["logNo",f],["cep",m]]);if(w||!c||!u||!d||!f||!m){l.reject(w??"invalid_structure");return}if(!qe(c)){l.reject("invalid_uf");return}if(!Ee(m)){l.reject("invalid_cep");return}if(g==="S"&&!b){l.reject("missing_tloTx");return}let h=n.get(u);if(!h){l.reject("missing_localidade");return}let I=r.get(d);if(!I){l.reject("missing_bairro");return}if(h.uf!==c||I.uf!==c){l.reject("logradouro_uf_mismatch");return}if(I.locNu!==u){l.reject("bairro_localidade_mismatch");return}let S=Xt(h,n);if(!S){l.reject("missing_municipality");return}t.run(m,g==="S"?`${b} ${f}`:f,null,I.id,null,S.nome,S.munNu,c,null,h.situacao,h.tipo),l.accept()})}insertLocalidades(e,t){for(let n of t.values())if(n.cep&&n.locNuSub===null&&n.munNu!==null)e.run(n.cep,null,null,null,null,n.nome,n.munNu,n.uf,null,n.situacao,n.tipo)}insertLocalidadesSubordinadas(e,t){for(let n of t.values()){let r=n.locNuSub?t.get(n.locNuSub):void 0;if(n.cep&&r?.munNu!==null&&r?.munNu!==void 0)e.run(n.cep,null,null,null,n.nome,r.nome,r.munNu,n.uf,null,n.situacao,n.tipo)}}async insertCpcs(e,t,n,r){let i=this.originalTable("log_cpc");await le(i,e,ee(i,["uf","locNu","nome","endereco","cep"]),r,(o,a,s)=>{let[l=null,c=null,u=null,d=null,f=null]=o,m=We([["uf",l],["locNu",c],["nome",u],["endereco",d],["cep",f]]);if(m||!l||!c||!u||!d||!f){s.reject(m??"invalid_structure");return}if(!qe(l)){s.reject("invalid_uf");return}if(!Ee(f)){s.reject("invalid_cep");return}let b=n.get(c);if(!b){s.reject("missing_localidade");return}if(b.uf!==l){s.reject("cpc_uf_mismatch");return}let g=Xt(b,n);if(!g){s.reject("missing_municipality");return}let[w,h]=Ur(d);t.run(f,w,h,null,null,g.nome,g.munNu,l,u,b.situacao,b.tipo),s.accept()})}async insertGrandesUsuarios(e,t,n,r,i){await this.insertNamedAddresses(this.originalTable("log_grande_usuario"),e,t,n,r,i)}async insertUnidadesOperacionais(e,t,n,r,i){await this.insertNamedAddresses(this.originalTable("log_unid_oper"),e,t,n,r,i)}async insertNamedAddresses(e,t,n,r,i,o){await le(e,t,ee(e,["uf","locNu","baiNu","nome","endereco","cep"]),o,(a,s,l)=>{let[c=null,u=null,d=null,f=null,m=null,b=null]=a,g=We([["uf",c],["locNu",u],["baiNu",d],["nome",f],["endereco",m],["cep",b]]);if(g||!c||!u||!d||!f||!m||!b){l.reject(g??"invalid_structure");return}if(!qe(c)){l.reject("invalid_uf");return}if(!Ee(b)){l.reject("invalid_cep");return}let w=r.get(u);if(!w){l.reject("missing_localidade");return}let h=i.get(d);if(!h){l.reject("missing_bairro");return}if(w.uf!==c||h.uf!==c){l.reject("address_uf_mismatch");return}if(h.locNu!==u){l.reject("bairro_localidade_mismatch");return}let I=Xt(w,r);if(!I){l.reject("missing_municipality");return}let[S,N]=Ur(m);n.run(b,S,N,h.id,null,I.nome,I.munNu,c,f,w.situacao,w.tipo),l.accept()})}originalTable(e){let t=this.tableByOriginalName.get(e);if(!t)throw Error(`Table with original name '${e}' not found`);return t}configureBulkLoad(){this.db.run(`PRAGMA page_size = ${Sn}`),this.db.run("PRAGMA journal_mode = MEMORY"),this.db.run("PRAGMA foreign_keys = ON"),this.db.run("PRAGMA synchronous = OFF"),this.db.run("PRAGMA temp_store = MEMORY"),this.db.run("PRAGMA locking_mode = EXCLUSIVE"),this.db.run(`PRAGMA cache_size = ${Dn}`)}createMetadataTable(){this.db.run(`
35
- CREATE TABLE IF NOT EXISTS ${y(A)} (
31
+ VALUES ${i}
32
+ `),this.statements.set(e,n),n}}class kn{schema;db;tableByOriginalName;unifiedTable;constructor(e,n){this.schema=n;this.db=new Fc(e),this.tableByOriginalName=new Map(n.map((i)=>[i.originalName,i])),this.unifiedTable=_e(n)}close(){this.db.run("PRAGMA locking_mode = NORMAL"),this.db.run("PRAGMA wal_checkpoint(TRUNCATE);"),this.db.close()}compact(){this.db.run("VACUUM")}async loadFromSource(e,n={},i=()=>{}){let c=this.unifiedTable,u=new Nn;return this.configureBulkLoad(),await this.transaction(async()=>{Xt(this.db,this.schema),this.createMetadataTable(),this.db.run(`DELETE FROM ${M(Z)}`),i("Lendo munic\xEDpios");let l=await this.readLocalidades(e,u);i("Lendo bairros");let d=await this.readBairros(e,l,u);this.insertBairros(d),i("Carregando faixas de CEP dos bairros"),await this.insertFaixasBairro(e,d,u);let A=this.prepareUnifiedInsert(c.name);try{if(i("Carregando logradouros"),await this.insertLogradouros(e,A,l,d,u),i("Carregando munic\xEDpios"),this.insertLocalidades(A,l),this.insertLocalidadesSubordinadas(A,l),i("Carregando endere\xE7os especiais"),await this.insertCpcs(e,A,l,u),await this.insertGrandesUsuarios(e,A,l,d,u),await this.insertUnidadesOperacionais(e,A,l,d,u),u.assertValid(),!l.size)throw new He("DNE source quality validation failed: no accepted localidade rows");A.flush();let E=this.rowCount(c.name);if(!E)throw new He("DNE source quality validation failed: no CEP rows produced");let R=u.report(E);this.writeMetadata({...n,schema_version:pt,quality_report:JSON.stringify(R),quality_rows_accepted:String(R.totals.accepted),quality_rows_read:String(R.totals.read),quality_rows_rejected:String(R.totals.rejected)})}finally{A.finalize()}}),this.rowCount(c.name)}async readLocalidades(e,n){let i=this.originalTable("log_localidade"),c=new Map;await je(i,e,xe(i,["locNu","uf","nome","cep","situacao","tipo","locNuSub","munNu"]),n,(l,d,A)=>{let[E=null,R=null,O=null,p=null,I=null,m=null,S=null,h=null]=l,b=Bt([["locNu",E],["uf",R],["nome",O],["situacao",I],["tipo",m]]);if(b||!E||!R||!O){A.reject(b??"invalid_structure");return}if(!Pt(R)){A.reject("invalid_uf");return}if(p!==null&&!ct(p)){A.reject("invalid_cep");return}if(h!==null&&!Gc(h)){A.reject("invalid_ibge");return}if(I!=="0"&&I!=="1"&&I!=="2"&&I!=="3"){A.reject("invalid_localidade_situacao");return}let g=rt.find((D)=>D===m);if(!g){A.reject("invalid_localidade_tipo");return}if(c.has(E)){A.reject("duplicate_localidade");return}c.set(E,{uf:R,nome:O,cep:p,locNuSub:S,munNu:h===null?null:Number(h),situacao:Number(I),tipo:g,quality:A})});let u=new Map;for(let[l,d]of c){let A=d.locNuSub?c.get(d.locNuSub):void 0;if(d.locNuSub&&(!A||A.munNu===null)){d.quality.reject("missing_parent_localidade");continue}if(A&&A.uf!==d.uf){d.quality.reject("localidade_uf_mismatch");continue}if(!d.locNuSub&&d.munNu===null){d.quality.reject("missing_ibge");continue}u.set(l,d),d.quality.accept()}return u}async readBairros(e,n,i){let c=this.originalTable("log_bairro"),u=new Map;return await je(c,e,xe(c,["baiNu","uf","locNu","bairro","abreviado"]),i,(l,d,A)=>{let[E=null,R=null,O=null,p=null,I=null]=l,m=Bt([["baiNu",E],["uf",R],["locNu",O],["bairro",p]]);if(m||!E||!R||!O||!p){A.reject(m??"invalid_structure");return}let S=to(E);if(S===null||to(O)===null){A.reject("invalid_bairro_identifier");return}if(!Pt(R)){A.reject("invalid_uf");return}let h=n.get(O);if(!h){A.reject("missing_localidade");return}if(h.uf!==R){A.reject("bairro_uf_mismatch");return}if(u.has(E)){A.reject("duplicate_bairro");return}u.set(E,{id:S,uf:R,locNu:O,nome:p,abreviado:I}),A.accept()}),u}insertBairros(e){let n=this.originalTable("bairros"),i=this.db.prepare(`
33
+ INSERT INTO ${M(n.name)} (bairro_id, localidade_id, uf, nome, nome_abreviado) VALUES (?, ?, ?, ?, ?)
34
+ `);try{for(let c of e.values())i.run(c.id,Number(c.locNu),c.uf,c.nome,c.abreviado)}finally{i.finalize()}}async insertFaixasBairro(e,n,i){let c=this.originalTable("log_faixa_bairro"),u=this.originalTable("bairro_faixas"),l=new Set,d=this.db.prepare(`INSERT INTO ${M(u.name)} (bairro_id, cep_inicial, cep_final) VALUES (?, ?, ?)`);try{await je(c,e,xe(c,["baiNu","cepInicial","cepFinal"]),i,(A,E,R)=>{let[O=null,p=null,I=null]=A,m=O===null?void 0:n.get(O);if(!m){R.reject("missing_bairro");return}if(!ct(p)||!ct(I)){R.reject("invalid_cep_range");return}if(p>I){R.reject("reversed_cep_range");return}let S=`${m.id}:${p}:${I}`;if(l.has(S)){R.reject("duplicate_cep_range");return}l.add(S),d.run(m.id,p,I),R.accept()})}finally{d.finalize()}}prepareUnifiedInsert(e){return new Gn(this.db,e,qr)}rowCount(e){return this.db.query(`SELECT count(*) AS count FROM ${M(e)}`).get().count}async insertLogradouros(e,n,i,c,u){let l=this.originalTable("log_logradouro");await je(l,e,xe(l,["uf","locNu","baiNuIni","logNo","cep","tloTx","logStaTlo"]),u,(d,A,E)=>{let[R=null,O=null,p=null,I=null,m=null,S=null,h=null]=d,b=Bt([["uf",R],["locNu",O],["baiNuIni",p],["logNo",I],["cep",m]]);if(b||!R||!O||!p||!I||!m){E.reject(b??"invalid_structure");return}if(!Pt(R)){E.reject("invalid_uf");return}if(!ct(m)){E.reject("invalid_cep");return}if(h==="S"&&!S){E.reject("missing_tloTx");return}let g=i.get(O);if(!g){E.reject("missing_localidade");return}let D=c.get(p);if(!D){E.reject("missing_bairro");return}if(g.uf!==R||D.uf!==R){E.reject("logradouro_uf_mismatch");return}if(D.locNu!==O){E.reject("bairro_localidade_mismatch");return}let y=$n(g,i);if(!y){E.reject("missing_municipality");return}n.run(m,h==="S"?`${S} ${I}`:I,null,D.id,null,y.nome,y.munNu,R,null,g.situacao,g.tipo),E.accept()})}insertLocalidades(e,n){for(let i of n.values())if(i.cep&&i.locNuSub===null&&i.munNu!==null)e.run(i.cep,null,null,null,null,i.nome,i.munNu,i.uf,null,i.situacao,i.tipo)}insertLocalidadesSubordinadas(e,n){for(let i of n.values()){let c=i.locNuSub?n.get(i.locNuSub):void 0;if(i.cep&&c?.munNu!==null&&c?.munNu!==void 0)e.run(i.cep,null,null,null,i.nome,c.nome,c.munNu,i.uf,null,i.situacao,i.tipo)}}async insertCpcs(e,n,i,c){let u=this.originalTable("log_cpc");await je(u,e,xe(u,["uf","locNu","nome","endereco","cep"]),c,(l,d,A)=>{let[E=null,R=null,O=null,p=null,I=null]=l,m=Bt([["uf",E],["locNu",R],["nome",O],["endereco",p],["cep",I]]);if(m||!E||!R||!O||!p||!I){A.reject(m??"invalid_structure");return}if(!Pt(E)){A.reject("invalid_uf");return}if(!ct(I)){A.reject("invalid_cep");return}let S=i.get(R);if(!S){A.reject("missing_localidade");return}if(S.uf!==E){A.reject("cpc_uf_mismatch");return}let h=$n(S,i);if(!h){A.reject("missing_municipality");return}let[b,g]=eo(p);n.run(I,b,g,null,null,h.nome,h.munNu,E,O,S.situacao,S.tipo),A.accept()})}async insertGrandesUsuarios(e,n,i,c,u){await this.insertNamedAddresses(this.originalTable("log_grande_usuario"),e,n,i,c,u)}async insertUnidadesOperacionais(e,n,i,c,u){await this.insertNamedAddresses(this.originalTable("log_unid_oper"),e,n,i,c,u)}async insertNamedAddresses(e,n,i,c,u,l){await je(e,n,xe(e,["uf","locNu","baiNu","nome","endereco","cep"]),l,(d,A,E)=>{let[R=null,O=null,p=null,I=null,m=null,S=null]=d,h=Bt([["uf",R],["locNu",O],["baiNu",p],["nome",I],["endereco",m],["cep",S]]);if(h||!R||!O||!p||!I||!m||!S){E.reject(h??"invalid_structure");return}if(!Pt(R)){E.reject("invalid_uf");return}if(!ct(S)){E.reject("invalid_cep");return}let b=c.get(O);if(!b){E.reject("missing_localidade");return}let g=u.get(p);if(!g){E.reject("missing_bairro");return}if(b.uf!==R||g.uf!==R){E.reject("address_uf_mismatch");return}if(g.locNu!==O){E.reject("bairro_localidade_mismatch");return}let D=$n(b,c);if(!D){E.reject("missing_municipality");return}let[y,U]=eo(m);i.run(S,y,U,g.id,null,D.nome,D.munNu,R,I,b.situacao,b.tipo),E.accept()})}originalTable(e){let n=this.tableByOriginalName.get(e);if(!n)throw Error(`Table with original name '${e}' not found`);return n}configureBulkLoad(){this.db.run(`PRAGMA page_size = ${Wr}`),this.db.run("PRAGMA journal_mode = MEMORY"),this.db.run("PRAGMA foreign_keys = ON"),this.db.run("PRAGMA synchronous = OFF"),this.db.run("PRAGMA temp_store = MEMORY"),this.db.run("PRAGMA locking_mode = EXCLUSIVE"),this.db.run(`PRAGMA cache_size = ${jr}`)}createMetadataTable(){this.db.run(`
35
+ CREATE TABLE IF NOT EXISTS ${M(Z)} (
36
36
  key TEXT PRIMARY KEY NOT NULL,
37
37
  value TEXT NOT NULL
38
38
  )
39
- `)}writeMetadata(e){let t=this.db.prepare(`INSERT INTO ${y(A)} (key, value) VALUES (?, ?)`);try{for(let[n,r]of Object.entries(e))t.run(n,r)}finally{t.finalize()}}async transaction(e){this.db.run("BEGIN");try{await e(),this.db.run("COMMIT")}catch(t){throw this.db.run("ROLLBACK"),t}}}function Ur(e){let t=e.indexOf(",");if(t===-1)return[e.trim(),null];return[e.slice(0,t).trim(),e.slice(t+1).trim()]}function Fr(e){return/^\d{1,8}$/.test(e)&&B(Number(e))?Number(e):null}var ia=new Set(["AC","AL","AM","AP","BA","CE","DF","ES","GO","MA","MG","MS","MT","PA","PB","PE","PI","PR","RJ","RN","RO","RR","RS","SC","SE","SP","TO"]);function qe(e){return e!==null&&ia.has(e)}function Ee(e){return e!==null&&/^\d{8}$/.test(e)}function oa(e){if(!/^\d{7}$/.test(e))return!1;let t=Number(e);return Number.isSafeInteger(t)&&t>0}function We(e){let t=e.find(([,n])=>n===null);return t?`missing_${t[0]}`:null}function Xt(e,t){let n=e.locNuSub?t.get(e.locNuSub):e;if(!n||n.munNu===null)return null;return{nome:n.nome,munNu:n.munNu}}function Pr(e,t){if(e.schema_version!==Re||e.source_kind!=="remote"||e.source_url!==t.url)return!1;let n=[Jt(e.source_etag,t.etag),Jt(e.source_last_modified,t.lastModified),Jt(e.source_content_length,t.contentLength)].filter((r)=>r!==null);return n.length>0&&n.every(Boolean)}function kr(e,t,n){let r={loaded_at:new Date().toISOString(),package_version:n,schema_version:Re,source_input:e,source_kind:t||aa(e)?"remote":"local"};if(t)r.source_url=t.url,r.source_last_modified=t.lastModified??"",r.source_etag=t.etag??"",r.source_content_length=t.contentLength??"";return r}function Jt(e,t){if(!t)return null;return e===t}function aa(e){try{let t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"}catch{return!1}}var pa="0 0 * * 5",en="\x1B[0m",ba="\x1B[1m",ga="\x1B[36m",ha="\x1B[90m",ya=/(--[^\r\n]*|\/\*[\s\S]*?(?:\*\/|$)|'(?:''|[^'])*'|"(?:""|[^"])*"|`(?:``|[^`])*`|\[(?:]]|[^\]])*]|\b(?:CREATE|TABLE|IF|NOT|EXISTS|TEXT|INTEGER|NULL|PRIMARY|KEY|WITHOUT|ROWID)\b)/gi,bt="pt-BR",Ea=new Intl.NumberFormat(bt),wa=new Intl.NumberFormat(bt,{maximumFractionDigits:1,minimumFractionDigits:1}),_a=new Intl.NumberFormat(bt,{maximumFractionDigits:1}),Gr=1,de=2,Ia=3,gt=await fr(),Qr=F("db",C.string,{default:In,describe:"Caminho da base; build bin\xE1rio usa a extens\xE3o .bin.",global:!0,valueHint:"file",valueName:"CAMINHO"}),zr=O("json",{describe:"Gravar um envelope JSON est\xE1vel em stdout.",global:!0}),Zr=O("quiet",{describe:"Ocultar mensagens de progresso.",global:!0,short:"q"}),Yr=Dt("color"),Sa=R(_n,{about:"Criar e consultar uma base local com os CEPs do Brasil.",afterHelp:["Exemplos:"," bunx @konstit/dne build --db ./dne.db"," bunx @konstit/dne build --format binary"," bunx @konstit/dne get 01001-000 --db ./dne.db"," bunx @konstit/dne status --db ./dne.db"," bunx @konstit/dne cron install --db ./dne.db"].join(`
40
- `),args:[Qr,zr,Zr,Yr],version:gt,subcommands:[R("build",{args:[F("format",C.enum(["sqlite","binary"]),{default:"sqlite",describe:"Formato da base de sa\xEDda.",valueName:"sqlite|binary"}),F("source",C.string,{default:Z,describe:"Diret\xF3rio DNE, arquivo ZIP ou URL.",valueName:"CAMINHO|URL"}),O("force",{describe:"Ignorar metadados de atualiza\xE7\xE3o e recriar a base."}),O("check",{describe:"Verificar a atualiza\xE7\xE3o da fonte sem alterar a base."})],about:"Criar ou atualizar a base SQLite ou bin\xE1ria",conflicts:[["force","check"]],handler:(e,t)=>Ra(e,G(t))}),R("get",{args:[_e("input",C.string,{describe:"Um ou mais CEPs.",repeatable:!0,valueName:"CEP"}),F("file",C.string,{describe:"Ler CEPs de um arquivo. Use - para stdin.",valueHint:"file",valueName:"CAMINHO"}),O("jsonl",{describe:"Gravar um resultado JSON por linha."})],about:"Consultar um ou mais CEPs",handler:(e,t)=>xa(e,G(t))}),R("status",{about:"Exibir tamanho, registros, estado do esquema e metadados da fonte",handler:(e,t)=>Ca(G(t))}),R("schema",{args:[O("expected",{describe:"Exibir o esquema declarado pela CLI em vez do esquema da base."})],about:"Exibir o esquema atual ou esperado da tabela de CEPs",handler:(e,t)=>La(e,G(t))}),R("doctor",{args:[O("offline",{describe:"N\xE3o verificar a fonte remota."}),F("source",C.string,{default:Z,describe:"URL da fonte remota que ser\xE1 verificada.",valueName:"URL"})],about:"Verificar Bun, configura\xE7\xE3o da base e acesso \xE0 fonte",handler:(e,t)=>Oa(e,G(t))}),R("sql",{args:[_e("query",C.string,{describe:"Instru\xE7\xE3o SELECT, WITH, PRAGMA ou EXPLAIN somente leitura.",required:!0,valueName:"CONSULTA"}),F("limit",C.range(1,1e4),{default:100,describe:"Quantidade m\xE1xima de registros retornados.",valueName:"REGISTROS"})],about:"Executar uma consulta SQL somente leitura com limite",handler:(e,t)=>Ba(e,G(t))}),R("cron",{about:"Gerenciar a atualiza\xE7\xE3o autom\xE1tica da base no sistema operacional",subcommands:[R("install",{args:[_e("expression",C.cron,{default:pa,describe:"Express\xE3o cron. O padr\xE3o executa \xE0 meia-noite de sexta-feira.",valueName:"EXPRESS\xC3O"}),O("dry-run",{describe:"Exibir o agendamento sem alterar o sistema."}),F("source",C.string,{describe:"Diret\xF3rio DNE, arquivo ZIP ou URL usado pelo agendamento.",valueName:"CAMINHO|URL"})],about:"Instalar ou substituir o agendamento desta base",handler:(e,t)=>Da(e,G(t))}),R("status",{about:"Exibir o agendamento desta base",handler:(e,t)=>Aa(G(t))}),R("remove",{about:"Remover o agendamento desta base",handler:(e,t)=>Ta(G(t))})],subcommandRequired:!0,defaultToHelp:!0})],subcommandRequired:!0,defaultToHelp:!0});async function Vr(e=Bun.argv.slice(2)){let t=e.includes("--json")||e.includes("--jsonl"),n=process.stdout.isTTY===!0&&Bun.env.TERM!=="dumb";try{return await Sa.run({argv:e,color:n,stdout:(r)=>console.log(tn(r).trimEnd()),...t?{stderr:(r)=>Xr(new E("invalid-arguments",tn(Ha(Bun.stripANSI(r))),de),!0)}:{stderr:(r)=>console.error(tn(r).trimEnd())}})}catch(r){return $a(r,t)}}function G(e){return{color:e.global(Yr),database:e.global(Qr),json:e.global(zr),quiet:e.global(Zr)}}async function Da(e,t){let n=await Kn({database:t.database,dryRun:e["dry-run"],expression:e.expression,packageVersion:gt,source:e.source});if(t.json)U(n);else{let r=n.status==="preview"?"Agendamento que seria instalado":n.status==="updated"?"Agendamento atualizado":"Agendamento instalado";console.log(`${r}: ${n.expression}`),console.log(`Pr\xF3xima execu\xE7\xE3o: ${we(n.next_run??void 0)}`),console.log(`Base: ${n.database}`),console.log(`Fonte: ${n.source}`),console.log(`Comando: ${n.command}`)}return 0}function Aa(e){let t=Jn(e.database);if(e.json)U(t);else if(t.installed)console.log(`Agendamento instalado: ${t.expression}`),console.log(`Pr\xF3xima execu\xE7\xE3o: ${we(t.next_run??void 0)}`),console.log(`Base: ${t.database}`),console.log(`Fonte: ${t.source}`),console.log(`Pacote: @konstit/dne@${t.package_version}`),console.log(`Comando: ${t.command}`);else console.log(`Nenhum agendamento instalado para a base: ${t.database}`);return 0}async function Ta(e){let t=await er(e.database);if(e.json)U(t);else if(t.removed)console.log(`Agendamento removido para a base: ${t.database}`);else console.log(`Nenhum agendamento instalado para a base: ${t.database}`);return 0}async function Ra(e,t){let n=Ma(t.quiet);try{return await Na(e,t,n)}finally{n.finish()}}async function Na(e,t,n){let r=performance.now(),i=j(t.database,e.format);if(e.format==="binary"&&i===":memory:")throw new E("invalid-format","O formato bin\xE1rio exige um caminho de arquivo.",de);if(e.check||i===":memory:")return qr(e,t,n,r,i);let o=await ur(i,n);try{return await qr(e,t,n,r,i)}finally{o.release()}}async function qr(e,t,n,r,i){let o=Jr(),a=e.source,s=ei(a)?await va(a,n):null;if(n.finish(),e.check){if(!s){let S=new dt(a,{onProgress:n});try{await S.resolve(o)}catch(N){throw new E("source-unavailable",He(N))}finally{await S.cleanup(),n.finish()}}let w=await ae(i),h=s&&w.ready?await jr(i,e.format,s):null,I={database:w,source:mt(a,s),status:h===null?"unknown":h?"current":"update-available",up_to_date:h};return Ua(I,t.json),0}if(!e.force&&s&&await jr(i,e.format,s)){let h={database:await ae(i),elapsed_ms:rn(r),source:mt(a,s),status:"unchanged"};return Wr(h,t.json),0}let l=i!==":memory:"&&await Bun.file(i).exists(),c=new dt(a,{onProgress:n,remoteInfo:s??void 0}),u=await Ka(i),d=new Kt(u.path,o),f=!1,m=0;try{let w=await c.resolve(o);if(n(e.format==="binary"?"Carregando a base bin\xE1ria":"Carregando a base SQLite"),m=await d.loadFromSource(w,kr(a,s,gt),n),e.format==="sqlite"&&i!==":memory:")n("Compactando a base SQLite"),d.compact();d.close(),f=!0;let h=u.path;if(e.format==="binary")h=`${u.path}.bin`,n("Compactando a base bin\xE1ria"),await vn(u.path,h),await ue(u.path,{force:!0});if(n(e.format==="binary"?"Confirmando a base bin\xE1ria":"Confirmando a base SQLite"),e.format==="sqlite"&&l)await za(i,u.path,o);else await u.commit(h);n.finish()}finally{if(!f)d.close();await u.cleanup(),await c.cleanup()}let g={database:i===":memory:"?Qn(m):await ae(i),elapsed_ms:rn(r),source:mt(a,s),status:l?"updated":"created"};return Wr(g,t.json),0}async function xa(e,t){if(t.json&&e.jsonl)throw new E("output-conflict","--json e --jsonl n\xE3o podem ser usados juntos.",de);let r=Pn(e.input,e.file)[Symbol.asyncIterator](),i=await r.next();if(i.done)throw new E("missing-input","Informe um CEP, --file CAMINHO ou uma entrada em stdin.",de);let o=d(i.value),a=j(t.database),s=await it(a),l=[],c=0,u=!1;try{f(o);while(!0){let m=await r.next();if(m.done)break;f(d(m.value))}}finally{s.close()}if(t.json)U({count:c,database:a,results:l});else if(!e.jsonl)Fa(l);return u?Ia:0;function d(m){let b=Fn(m);if(b===void 0)throw new E("invalid-cep",`CEP inv\xE1lido '${m}'. Use 01001000 ou 01001-000.`,de,{input:m});return{cep:b,input:m}}function f(m){let b=s.queryCep(m.cep)??null,g={address:b,cep:m.cep,found:b!==null,input:m.input};if(c++,u||=!g.found,e.jsonl){process.stdout.write(`${JSON.stringify({ok:!0,data:{database:a,result:g}})}
41
- `);return}l.push(g)}}async function Ca(e){let t=await ae(j(e.database));if(e.json)U(t);else Pa(t);return t.ready?0:Gr}async function La(e,t){let n=Jr(),r=J(n),i=null,o="declared",a=Ne(n),s=`${[...a.map(Hn),Mt(r.name)].join(`;
39
+ `)}writeMetadata(e){let n=this.db.prepare(`INSERT INTO ${M(Z)} (key, value) VALUES (?, ?)`);try{for(let[i,c]of Object.entries(e))n.run(i,c)}finally{n.finalize()}}async transaction(e){this.db.run("BEGIN");try{await e(),this.db.run("COMMIT")}catch(n){throw this.db.run("ROLLBACK"),n}}}function eo(e){let n=e.indexOf(",");if(n===-1)return[e.trim(),null];return[e.slice(0,n).trim(),e.slice(n+1).trim()]}function to(e){return/^\d{1,8}$/.test(e)&&oe(Number(e))?Number(e):null}var vc=new Set(["AC","AL","AM","AP","BA","CE","DF","ES","GO","MA","MG","MS","MT","PA","PB","PE","PI","PR","RJ","RN","RO","RR","RS","SC","SE","SP","TO"]);function Pt(e){return e!==null&&vc.has(e)}function ct(e){return e!==null&&/^\d{8}$/.test(e)}function Gc(e){if(!/^\d{7}$/.test(e))return!1;let n=Number(e);return Number.isSafeInteger(n)&&n>0}function Bt(e){let n=e.find(([,i])=>i===null);return n?`missing_${n[0]}`:null}function $n(e,n){let i=e.locNuSub?n.get(e.locNuSub):e;if(!i||i.munNu===null)return null;return{nome:i.nome,munNu:i.munNu}}function no(e,n){if(e.schema_version!==pt||e.source_kind!=="remote"||e.source_url!==n.url||!n.zipEntries?.length)return!1;return e.source_zip_entries===JSON.stringify(n.zipEntries)}function ro(e,n,i){let c={loaded_at:new Date().toISOString(),package_version:i,schema_version:pt,source_input:e,source_kind:n||$c(e)?"remote":"local"};if(n){if(c.source_url=n.url,c.source_last_modified=n.lastModified??"",c.source_etag=n.etag??"",c.source_content_length=n.contentLength??"",n.zipEntries?.length)c.source_zip_entries=JSON.stringify(n.zipEntries)}return c}function $c(e){try{let n=new URL(e);return n.protocol==="http:"||n.protocol==="https:"}catch{return!1}}var zc="0 0 * * 5",Hn="\x1B[0m",Qc="\x1B[1m",Xc="\x1B[36m",Jc="\x1B[90m",Yc=/(--[^\r\n]*|\/\*[\s\S]*?(?:\*\/|$)|'(?:''|[^'])*'|"(?:""|[^"])*"|`(?:``|[^`])*`|\[(?:]]|[^\]])*]|\b(?:CREATE|TABLE|IF|NOT|EXISTS|TEXT|INTEGER|NULL|PRIMARY|KEY|WITHOUT|ROWID)\b)/gi,cn="pt-BR",Kc=new Intl.NumberFormat(cn),eu=new Intl.NumberFormat(cn,{maximumFractionDigits:1,minimumFractionDigits:1}),tu=new Intl.NumberFormat(cn,{maximumFractionDigits:1}),fo=1,ce=2,nu=3,un=await Di(),Ao=o("db",t.string,{default:Hr,describe:"Caminho da base; build bin\xE1rio usa a extens\xE3o .bin.",global:!0,valueHint:"file",valueName:"CAMINHO"}),Eo=a("json",{describe:"Gravar um envelope JSON est\xE1vel em stdout.",global:!0}),Ro=a("quiet",{describe:"Ocultar mensagens de progresso.",global:!0,short:"q"}),Oo=f("color"),ru=r(kr,{about:"Criar e consultar uma base local com os CEPs do Brasil.",afterHelp:["Exemplos:"," bunx @konstit/dne build --db ./dne.db --source ./eDNE_Basico.zip"," bunx @konstit/dne build --format binary --source ./eDNE_Basico.zip"," bunx @konstit/dne build-search-index --db ./dne.bin"," bunx @konstit/dne get 01001-000 --db ./dne.db"," bunx @konstit/dne status --db ./dne.db"," bunx @konstit/dne cron install --db ./dne.db --source https://example.com/eDNE_Basico.zip"].join(`
40
+ `),args:[Ao,Eo,Ro,Oo],version:un,subcommands:[r("build",{args:[o("format",t.enum(["sqlite","binary"]),{default:"sqlite",describe:"Formato da base de sa\xEDda.",valueName:"sqlite|binary"}),o("source",t.string,{required:!0,describe:"Diret\xF3rio DNE, arquivo ZIP ou URL.",valueName:"CAMINHO|URL",env:"EDNE_SOURCE_URL"}),a("force",{describe:"Ignorar metadados de atualiza\xE7\xE3o e recriar a base."}),a("check",{describe:"Verificar a atualiza\xE7\xE3o da fonte sem alterar a base."})],about:"Criar ou atualizar a base SQLite ou bin\xE1ria",conflicts:[["force","check"]],handler:(e,n)=>su(e,se(n))}),r("build-search-index",{about:"Construir o \xEDndice de autocomplete de uma base bin\xE1ria existente",args:[o("output",t.string,{describe:"Caminho do \xEDndice; padr\xE3o: <base>.search.bin, ao lado da base.",valueName:"CAMINHO",valueHint:"file"})],handler:(e,n)=>lu(e,se(n))}),r("get",{args:[s("input",t.string,{describe:"Um ou mais CEPs.",repeatable:!0,valueName:"CEP"}),o("file",t.string,{describe:"Ler CEPs de um arquivo. Use - para stdin.",valueHint:"file",valueName:"CAMINHO"}),a("jsonl",{describe:"Gravar um resultado JSON por linha."})],about:"Consultar um ou mais CEPs",handler:(e,n)=>uu(e,se(n))}),r("status",{about:"Exibir tamanho, registros, estado do esquema e metadados da fonte",handler:(e,n)=>du(se(n))}),r("schema",{args:[a("expected",{describe:"Exibir o esquema declarado pela CLI em vez do esquema da base."})],about:"Exibir o esquema atual ou esperado da tabela de CEPs",handler:(e,n)=>fu(e,se(n))}),r("doctor",{args:[a("offline",{describe:"N\xE3o verificar a fonte remota."}),o("source",t.string,{describe:"URL da fonte remota. Obrigat\xF3ria sem --offline.",valueName:"URL",env:"EDNE_SOURCE_URL"})],about:"Verificar Bun, configura\xE7\xE3o da base e acesso \xE0 fonte",handler:(e,n)=>Au(e,se(n))}),r("sql",{args:[s("query",t.string,{describe:"Instru\xE7\xE3o SELECT, WITH, PRAGMA ou EXPLAIN somente leitura.",required:!0,valueName:"CONSULTA"}),o("limit",t.range(1,1e4),{default:100,describe:"Quantidade m\xE1xima de registros retornados.",valueName:"REGISTROS"})],about:"Executar uma consulta SQL somente leitura com limite",handler:(e,n)=>Eu(e,se(n))}),r("cron",{about:"Gerenciar a atualiza\xE7\xE3o autom\xE1tica da base no sistema operacional",subcommands:[r("install",{args:[s("expression",t.cron,{default:zc,describe:"Express\xE3o cron. O padr\xE3o executa \xE0 meia-noite de sexta-feira.",valueName:"EXPRESS\xC3O"}),a("dry-run",{describe:"Exibir o agendamento sem alterar o sistema."}),o("source",t.string,{required:!0,describe:"Diret\xF3rio DNE, arquivo ZIP ou URL usado pelo agendamento.",valueName:"CAMINHO|URL",env:"EDNE_SOURCE_URL"})],about:"Instalar ou substituir o agendamento desta base",handler:(e,n)=>iu(e,se(n))}),r("status",{about:"Exibir o agendamento desta base",handler:(e,n)=>ou(se(n))}),r("remove",{about:"Remover o agendamento desta base",handler:(e,n)=>au(se(n))})],subcommandRequired:!0,defaultToHelp:!0})],subcommandRequired:!0,defaultToHelp:!0});async function po(e=Bun.argv.slice(2)){let n=e.includes("--json")||e.includes("--jsonl"),i=process.stdout.isTTY===!0&&Bun.env.TERM!=="dumb";try{return await ru.run({argv:e,color:i,stdout:(c)=>console.log(Wn(c).trimEnd()),...n?{stderr:(c)=>mo(new w("invalid-arguments",Wn(bu(Bun.stripANSI(c))),ce),!0)}:{stderr:(c)=>console.error(Wn(c).trimEnd())}})}catch(c){return Ou(c,n)}}function se(e){return{color:e.global(Oo),database:e.global(Ao),json:e.global(Eo),quiet:e.global(Ro)}}async function iu(e,n){let i=await di({database:n.database,dryRun:e["dry-run"],expression:e.expression,packageVersion:un,source:e.source});if(n.json)te(i);else{let c=i.status==="preview"?"Agendamento que seria instalado":i.status==="updated"?"Agendamento atualizado":"Agendamento instalado";console.log(`${c}: ${i.expression}`),console.log(`Pr\xF3xima execu\xE7\xE3o: ${ut(i.next_run??void 0)}`),console.log(`Base: ${i.database}`),console.log(`Fonte: ${i.source}`),console.log(`Comando: ${i.command}`)}return 0}function ou(e){let n=fi(e.database);if(e.json)te(n);else if(n.installed)console.log(`Agendamento instalado: ${n.expression}`),console.log(`Pr\xF3xima execu\xE7\xE3o: ${ut(n.next_run??void 0)}`),console.log(`Base: ${n.database}`),console.log(`Fonte: ${n.source}`),console.log(`Pacote: @konstit/dne@${n.package_version}`),console.log(`Comando: ${n.command}`);else console.log(`Nenhum agendamento instalado para a base: ${n.database}`);return 0}async function au(e){let n=await Ai(e.database);if(e.json)te(n);else if(n.removed)console.log(`Agendamento removido para a base: ${n.database}`);else console.log(`Nenhum agendamento instalado para a base: ${n.database}`);return 0}async function su(e,n){let i=Io(n.quiet);try{return await cu(e,n,i)}finally{i.finish()}}async function cu(e,n,i){let c=performance.now(),u=ae(n.database,e.format);if(e.format==="binary"&&u===":memory:")throw new w("invalid-format","O formato bin\xE1rio exige um caminho de arquivo.",ce);if(e.check||u===":memory:")return oo(e,n,i,c,u);let l=await bi(u,i);try{return await oo(e,n,i,c,u)}finally{l.release()}}async function oo(e,n,i,c,u){let l=ho(),d=e.source,A=To(d)?await Ru(d,i,l,!e.check):null;if(i.finish(),e.check){if(!A){let y=new on(d,{onProgress:i});try{await y.resolve(l)}catch(U){throw new w("source-unavailable",_t(U))}finally{await y.cleanup(),i.finish()}}let b=await $e(u),g=A&&b.ready?await co(u,e.format,A):null,D={database:b,source:an(d,A),status:g===null?"unknown":g?"current":"update-available",up_to_date:g};return pu(D,n.json),0}if(!e.force&&A&&await co(u,e.format,A)){let g={database:await $e(u),elapsed_ms:zn(c),source:an(d,A),status:"unchanged"};return ao(g,n.json),0}let E=u!==":memory:"&&await Bun.file(u).exists(),R=new on(d,{onProgress:i,remoteInfo:A??void 0}),O=await Uu(u),p=new kn(O.path,l),I=!1,m=0;try{let b=await R.resolve(l);if(A)A.zipEntries=b.zipEntries??null;if(i(e.format==="binary"?"Carregando a base bin\xE1ria":"Carregando a base SQLite"),m=await p.loadFromSource(b,ro(d,A,un),i),e.format==="sqlite"&&u!==":memory:")i("Compactando a base SQLite"),p.compact();p.close(),I=!0;let g=O.path;if(e.format==="binary")g=`${O.path}.bin`,i("Compactando a base bin\xE1ria"),await Kr(O.path,g),await ge(O.path,{force:!0});if(i(e.format==="binary"?"Confirmando a base bin\xE1ria":"Confirmando a base SQLite"),e.format==="sqlite"&&E)await Nu(u,O.path,l);else await O.commit(g);i.finish()}finally{if(!I)p.close();await O.cleanup(),await R.cleanup()}let h={database:u===":memory:"?oi(m):await $e(u),elapsed_ms:zn(c),source:an(d,A),status:E?"updated":"created"};return ao(h,n.json),0}async function uu(e,n){if(n.json&&e.jsonl)throw new w("output-conflict","--json e --jsonl n\xE3o podem ser usados juntos.",ce);let c=wr(e.input,e.file)[Symbol.asyncIterator](),u=await c.next();if(u.done)throw new w("missing-input","Informe um CEP, --file CAMINHO ou uma entrada em stdin.",ce);let l=p(u.value),d=ae(n.database),A=await yt(d),E=[],R=0,O=!1;try{I(l);while(!0){let m=await c.next();if(m.done)break;I(p(m.value))}}finally{A.close()}if(n.json)te({count:R,database:d,results:E});else if(!e.jsonl)Iu(E);return O?nu:0;function p(m){let S=Lr(m);if(S===void 0)throw new w("invalid-cep",`CEP inv\xE1lido '${m}'. Use 01001000 ou 01001-000.`,ce,{input:m});return{cep:S,input:m}}function I(m){let S=A.queryCep(m.cep)??null,h={address:S,cep:m.cep,found:S!==null,input:m.input};if(R++,O||=!h.found,e.jsonl){process.stdout.write(`${JSON.stringify({ok:!0,data:{database:d,result:h}})}
41
+ `);return}E.push(h)}}async function lu(e,n){let i=performance.now(),c=ae(n.database),u=await yt(c),l=Io(n.quiet);try{if(!(u instanceof he))throw new w("invalid-format","O \xEDndice de busca exige uma base bin\xE1ria. Use build --format binary primeiro.",ce);let d=Zc(e.output??`${c.slice(0,c.length-qc(c).length)}.search.bin`),A=io(c),E=io(d,{throwIfNoEntry:!1});if(E?.dev===A.dev&&E?.ino===A.ino)throw new w("invalid-output","O caminho do \xEDndice deve ser diferente do caminho da base.",ce);await uo(jn(d),{recursive:!0}),l("Construindo o \xEDndice de busca");let R=lr(u),O=await Wc(qn(jn(d),".dne-search-"));try{let I=qn(O,"index.bin");await Bun.write(I,R),await lo(I,d)}finally{await ge(O,{recursive:!0,force:!0})}l.finish();let p={database:c,index:d,row_count:u.rowCount(),size_bytes:R.length,elapsed_ms:performance.now()-i};if(n.json)te(p);else console.log(`\xCDndice de busca criado: ${d} (${p.row_count} registros, ${p.size_bytes} bytes)`);return 0}finally{u.close(),l.finish()}}async function du(e){let n=await $e(ae(e.database));if(e.json)te(n);else mu(n);return n.ready?0:fo}async function fu(e,n){let i=ho(),c=_e(i),u=null,l="declared",d=It(i),A=`${[...d.map(ni),Tn(c.name)].join(`;
42
42
 
43
- `)};`;if(!e.expected){i=j(t.database);let l=await it(i);try{if(!("tableSchema"in l))o="binary";else{let c=a.map((d)=>l.tableSchema(d.name)).filter((d)=>d!==void 0).map(Za),u=l.querySql(`SELECT sql FROM sqlite_master WHERE type = 'view' AND name = ${ti(oe(r.name))}`,1).rows[0]?.sql;if(typeof u==="string")c.push(u);if(c.length)s=`${c.join(`;
43
+ `)};`;if(!e.expected){u=ae(n.database);let E=await yt(u);try{if(!("tableSchema"in E))l="binary";else{let R=d.map((p)=>E.tableSchema(p.name)).filter((p)=>p!==void 0).map(Cu),O=E.querySql(`SELECT sql FROM sqlite_master WHERE type = 'view' AND name = ${bo(Ge(c.name))}`,1).rows[0]?.sql;if(typeof O==="string")R.push(O);if(R.length)A=`${R.join(`;
44
44
 
45
- `)};`,o="database"}}finally{l.close()}}if(t.json)U({database:i,source:o,sql:s,table:T});else console.log(Va(s,t.color));return 0}async function Oa(e,t){let n=await ae(j(t.database)),r=Qa(Bun.version),i={checked:!1,reachable:null,url:e.source};if(!e.offline)try{let s=await ft(e.source);i={...mt(e.source,s),checked:!0,reachable:!0}}catch(s){i={checked:!0,error:He(s),reachable:!1,url:e.source}}let o=r&&n.ready&&i.reachable!==!1,a={auth:{required:!1,source:"not-required"},database:n,healthy:o,runtime:{compatible:r,minimum_version:"1.4.0",name:"bun",version:Bun.version},setup:n.ready?null:`Execute bunx @konstit/dne build --db ${Ga(n.path)}`,source:i,version:gt};if(t.json)U(a);else ka(a);return o?0:Gr}async function Ba(e,t){if(!/^\s*(?:SELECT|WITH|PRAGMA|EXPLAIN)\b/i.test(e.query))throw new E("write-query-denied","O comando sql permite somente instru\xE7\xF5es SELECT, WITH, PRAGMA e EXPLAIN.",de);let n=j(t.database),r=await it(n);try{if(!("querySql"in r))throw new E("sql-unsupported","O comando sql exige uma base SQLite.",de);let i=r.querySql(e.query,e.limit),o={columns:i.rows[0]?Object.keys(i.rows[0]):[],database:n,limit:e.limit,...i};if(t.json)U(o);else console.log(JSON.stringify(o,null,2))}finally{r.close()}return 0}async function va(e,t){t("Inspecionando a fonte DNE remota");try{return await ft(e)}catch(n){throw new E("source-unavailable",He(n))}}function mt(e,t){return t?{accept_ranges:t.acceptRanges,content_length:t.contentLength,etag:t.etag,kind:"remote",last_modified:t.lastModified,url:t.url}:{input:e,kind:ei(e)?"remote":"local"}}function Ma(e){let t=null,n=()=>{if(t!==null)process.stderr.write(` (${on(rn(t))})
46
- `),t=null},r=(i)=>{if(n(),!e)t=performance.now(),process.stderr.write(i)};return r.finish=n,r}function U(e){process.stdout.write(`${JSON.stringify({ok:!0,data:e},null,2)}
47
- `)}function Xr(e,t){if(t){process.stderr.write(`${JSON.stringify({error:{code:e.code,...e.details?{details:e.details}:{},message:e.message},ok:!1})}
48
- `);return}console.error(`erro: ${e.message}`)}function $a(e,t){let n=e instanceof E?e:e instanceof ce?new E("source-quality-failed",He(e)):new E("internal-error",He(e));return Xr(n,t),n.exitCode}function Ua(e,t){if(t){U(e);return}console.log(`Estado: ${ja(e.status)}`),console.log(`Base: ${e.database.path}`),console.log(`Fonte: ${nn(e.source.url??e.source.input)}`),console.log(`\xDAltima modifica\xE7\xE3o na fonte: ${we(nn(e.source.last_modified))}`)}function Wr(e,t){if(t){U(e);return}let n=e.database.row_count===null?"quantidade desconhecida de registros":`${V(e.database.row_count)} registros`,r=e.database.size_bytes===null?"tamanho desconhecido":Kr(e.database.size_bytes);if(e.status==="unchanged"){let o=e.database.row_count===null?"quantidade desconhecida de registros":`${V(e.database.row_count)} registros`;console.log(`A base DNE j\xE1 est\xE1 atualizada: ${e.database.path} (${o}, ${r}).`),console.log(`\xDAltima modifica\xE7\xE3o na fonte: ${we(nn(e.source.last_modified))}`),console.log(`Verifica\xE7\xE3o conclu\xEDda em ${on(e.elapsed_ms)}.`);return}let i=e.status==="updated"?"Base atualizada":"Base criada";console.log(`${i}: ${e.database.path} (${n}, ${r}, ${on(e.elapsed_ms)}).`)}function Fa(e){if(e.length===1){let t=e[0];if(!t?.address){console.error(`CEP n\xE3o encontrado: ${t?.cep??""}`);return}console.log(t.address);return}console.log("cep\tencontrado\tlogradouro\tbairro\tmunic\xEDpio\tuf");for(let t of e)console.log([t.cep,pt(t.found),t.address?.logradouro??"",t.address?.bairro??"",t.address?.municipio??"",t.address?.uf??""].join("\t"))}function Pa(e){if(console.log(`Base: ${e.path}`),console.log(`Formato: ${e.format??"-"}`),console.log(`Existe: ${pt(e.exists)}`),console.log(`Pronta: ${pt(e.ready)}`),console.log(`Registros: ${e.row_count===null?"-":V(e.row_count)}`),console.log(`Tamanho: ${e.size_bytes===null?"-":Kr(e.size_bytes)}`),console.log(`Carregada em: ${we(e.metadata?.loaded_at)}`),console.log(`Pacote: @konstit/dne@${e.metadata?.package_version??"-"}`),console.log(`Fonte: ${e.metadata?.source_url??e.metadata?.source_input??"-"}`),console.log(`\xDAltima modifica\xE7\xE3o da fonte: ${we(e.metadata?.source_last_modified)}`),e.error)console.log(`Erro: ${e.error}`)}function ka(e){if(console.log(`CLI: dne ${e.version}`),console.log(`Ambiente: ${e.runtime.name} ${e.runtime.version} (${e.runtime.compatible?"compat\xEDvel":"n\xE3o compat\xEDvel"})`),console.log(`Base: ${e.database.ready?"pronta":"configura\xE7\xE3o necess\xE1ria"} (${e.database.path})`),console.log(`Fonte: ${e.source.reachable===null?"n\xE3o verificada":e.source.reachable?"acess\xEDvel":"inacess\xEDvel"}`),console.log(`Saud\xE1vel: ${pt(e.healthy)}`),e.setup)console.log(`Configura\xE7\xE3o: ${e.setup}`)}function qa(e){return e instanceof Error?e.message:String(e)}function He(e){return Wa(qa(e))}function Wa(e){let n={"Failed to write downloaded content":"Falha ao gravar o conte\xFAdo baixado","Invalid ZIP central directory entry":"Entrada inv\xE1lida no diret\xF3rio central do ZIP","Invalid ZIP central directory entry size":"Tamanho inv\xE1lido de entrada no diret\xF3rio central do ZIP","Invalid ZIP central directory range":"Intervalo inv\xE1lido do diret\xF3rio central do ZIP","Only sqlite:/// database URLs are supported":"Somente URLs de base no formato sqlite:/// s\xE3o aceitas","package.json has no valid version":"package.json n\xE3o cont\xE9m uma vers\xE3o v\xE1lida","Source is not a valid ZIP file":"A fonte n\xE3o \xE9 um arquivo ZIP v\xE1lido","Unified schema table not found":"Tabela unificada n\xE3o encontrada no schema","ZIP file does not contain DNE Basico files":"O arquivo ZIP n\xE3o cont\xE9m arquivos do DNE B\xE1sico"}[e];if(n)return n;return e.replace(/^Failed to download (.+): (\d+)$/,"Falha ao baixar $1: $2").replace(/^Failed to stream (.+): empty response body$/,"Falha ao transmitir $1: corpo da resposta vazio").replace(/^Failed to inspect DNE from (.+): (\d+)$/,"Falha ao inspecionar o DNE em $1: $2").replace(/^DNE source not found: (.+)$/,"Fonte DNE n\xE3o encontrada: $1").replace(/^DNE source quality validation failed: (.+)$/,"A valida\xE7\xE3o de qualidade da fonte DNE falhou: $1").replace(/^DNE data file not found: (.+)$/,"Arquivo de dados DNE n\xE3o encontrado: $1").replace(/^Invalid ZIP local header for (.+)$/,"Cabe\xE7alho local ZIP inv\xE1lido para $1").replace(/^Invalid ZIP data range for (.+)$/,"Intervalo de dados ZIP inv\xE1lido para $1").replace(/^Invalid decompressed size for (.+)$/,"Tamanho descompactado inv\xE1lido para $1").replace(/^Unsupported ZIP compression method (\d+) for (.+)$/,"M\xE9todo de compacta\xE7\xE3o ZIP $1 n\xE3o aceito para $2").replace(/^CRC32 mismatch for (.+)$/,"CRC32 divergente para $1").replace(/^Server ignored byte range (.+)$/,"O servidor ignorou o intervalo de bytes $1").replace(/^Server returned an invalid Content-Range for (.+)$/,"O servidor retornou um Content-Range inv\xE1lido para $1").replace(/^Server returned (\d+) bytes for range (.+); expected (\d+)$/,"O servidor retornou $1 bytes para o intervalo $2; eram esperados $3").replace(/^Missing row at index (\d+)$/,"Registro ausente no \xEDndice $1").replace(/^Table with original name '(.+)' not found$/,"Tabela com nome original '$1' n\xE3o encontrada")}function tn(e){return e.replaceAll("Usage:","Uso:").replaceAll("Arguments:","Argumentos:").replaceAll("Commands:","Comandos:").replaceAll("Options:","Op\xE7\xF5es:").replaceAll("Print help for a subcommand","Exibir ajuda de um subcomando").replaceAll("Print help","Exibir ajuda").replaceAll("Print version","Exibir vers\xE3o").replaceAll("Enable or disable color output","Ativar ou desativar cores na sa\xEDda").replaceAll("expected a schedulable Bun cron expression","esperada uma express\xE3o cron v\xE1lida").replaceAll("[env:","[vari\xE1vel:").replaceAll("[default:","[padr\xE3o:").replaceAll("For more information, try '--help'.","Para mais informa\xE7\xF5es, use '--help'.").replaceAll("error:","erro:").replace(/invalid value (.+?) for (.+?): expected value matching (.+)/g,"valor inv\xE1lido $1 para $2: esperado valor compat\xEDvel com $3").replace(/invalid value (.+?) for (.+?): expected a number from (.+?) to (.+)/g,"valor inv\xE1lido $1 para $2: esperado n\xFAmero entre $3 e $4").replace(/invalid value (.+?) for (.+?): (.+)/g,"valor inv\xE1lido $1 para $2: $3").replace(/unexpected argument (.+)/g,"argumento inesperado $1").replace(/arguments (.+?) and (.+?) cannot be used together/g,"os argumentos $1 e $2 n\xE3o podem ser usados juntos").replace(/argument (.+?) requires at least (\d+) value\(s\)/g,"o argumento $1 exige pelo menos $2 valor(es)").replace(/the following required arguments were not provided:/g,"os seguintes argumentos obrigat\xF3rios n\xE3o foram informados:").replace(/a similar argument exists:/g,"existe um argumento semelhante:")}function nn(e){return typeof e==="string"?e:""}function Ha(e){return e.split(`
49
- `).map((t)=>t.trim()).find(Boolean)?.replace(/^error:\s*/i,"")??"Argumentos inv\xE1lidos."}function rn(e){return Math.max(0,Math.round(performance.now()-e))}function V(e){return Ea.format(e)}function Hr(e){return wa.format(e)}function we(e){if(!e)return"-";let t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString(bt)}function on(e){let t=Math.max(0,Math.round(e));if(t<1000)return`${V(t)} ms`;let n=Math.round(t/1000);if(n<60){let a=Math.round(t/100)/10;return`${_a.format(a)} s`}let r=Math.floor(n/3600),i=Math.floor(n%3600/60),o=n%60;return[r?`${V(r)} h`:"",i?`${V(i)} min`:"",o?`${V(o)} s`:""].filter(Boolean).join(" ")}function Kr(e){if(e<1024)return`${V(e)} B`;if(e<1048576)return`${Hr(e/1024)} KiB`;return`${Hr(e/1048576)} MiB`}function pt(e){return e?"sim":"n\xE3o"}function ja(e){return{current:"atualizada",unknown:"desconhecido","update-available":"atualiza\xE7\xE3o dispon\xEDvel"}[e]??e}function Ga(e){return`'${e.replaceAll("'","'\\''")}'`}function Qa(e){let[t=0,n=0]=e.split(".").map(Number);return t>1||t===1&&n>=4}function Jr(){let e=wn();return J(e).name=T,e}async function za(e,t,n){let r=Ne(n),i=`${t}.attach`;await ue(i,{force:!0}),await ca(t,i);let o=new sa(e);try{o.run("PRAGMA busy_timeout = 30000"),o.run("PRAGMA journal_mode = WAL"),o.run("PRAGMA synchronous = NORMAL"),o.run("PRAGMA foreign_keys = ON"),o.run(`ATTACH DATABASE ${ti(i)} AS fresh`),o.run("BEGIN IMMEDIATE");try{nt(o,n),o.run(`
50
- CREATE TABLE IF NOT EXISTS ${y(A)} (
45
+ `)};`,l="database"}}finally{E.close()}}if(n.json)te({database:u,source:l,sql:A,table:z});else console.log(wu(A,n.color));return 0}async function Au(e,n){if(!e.offline&&!e.source)throw new w("invalid-arguments","Informe --source URL ou use --offline.",ce);let i=await $e(ae(n.database)),c=yu(Bun.version),u={checked:!1,reachable:null,url:e.source??null};if(!e.offline&&e.source)try{let A=await Mt(e.source);u={...an(e.source,A),checked:!0,reachable:!0}}catch(A){u={checked:!0,error:_t(A),reachable:!1,url:e.source}}let l=c&&i.ready&&u.reachable!==!1,d={auth:{required:!1,source:"not-required"},database:i,healthy:l,runtime:{compatible:c,minimum_version:"1.4.0",name:"bun",version:Bun.version},setup:i.ready?null:`Execute bunx @konstit/dne build --db ${Du(i.path)} --source CAMINHO_OU_URL`,source:u,version:un};if(n.json)te(d);else Su(d);return l?0:fo}async function Eu(e,n){if(!/^\s*(?:SELECT|WITH|PRAGMA|EXPLAIN)\b/i.test(e.query))throw new w("write-query-denied","O comando sql permite somente instru\xE7\xF5es SELECT, WITH, PRAGMA e EXPLAIN.",ce);let i=ae(n.database),c=await yt(i);try{if(!("querySql"in c))throw new w("sql-unsupported","O comando sql exige uma base SQLite.",ce);let u=c.querySql(e.query,e.limit),l={columns:u.rows[0]?Object.keys(u.rows[0]):[],database:i,limit:e.limit,...u};if(n.json)te(l);else console.log(JSON.stringify(l,null,2))}finally{c.close()}return 0}async function Ru(e,n,i,c){n("Inspecionando a fonte DNE remota");try{return await Ji(e,i)}catch(u){if(c)return{url:e,etag:null,lastModified:null,contentLength:null,acceptRanges:null,zipEntries:null};throw new w("source-unavailable",_t(u))}}function an(e,n){return n?{accept_ranges:n.acceptRanges,content_length:n.contentLength,etag:n.etag,kind:"remote",last_modified:n.lastModified,url:n.url,zip_entries:n.zipEntries??null}:{input:e,kind:To(e)?"remote":"local"}}function Io(e){let n=null,i=()=>{if(n!==null)process.stderr.write(` (${Qn(zn(n))})
46
+ `),n=null},c=(u)=>{if(i(),!e)n=performance.now(),process.stderr.write(u)};return c.finish=i,c}function te(e){process.stdout.write(`${JSON.stringify({ok:!0,data:e},null,2)}
47
+ `)}function mo(e,n){if(n){process.stderr.write(`${JSON.stringify({error:{code:e.code,...e.details?{details:e.details}:{},message:e.message},ok:!1})}
48
+ `);return}console.error(`erro: ${e.message}`)}function Ou(e,n){let i=e instanceof w?e:e instanceof He?new w("source-quality-failed",_t(e)):new w("internal-error",_t(e));return mo(i,n),i.exitCode}function pu(e,n){if(n){te(e);return}console.log(`Estado: ${gu(e.status)}`),console.log(`Base: ${e.database.path}`),console.log(`Fonte: ${Zn(e.source.url??e.source.input)}`),console.log(`\xDAltima modifica\xE7\xE3o na fonte: ${ut(Zn(e.source.last_modified))}`)}function ao(e,n){if(n){te(e);return}let i=e.database.row_count===null?"quantidade desconhecida de registros":`${De(e.database.row_count)} registros`,c=e.database.size_bytes===null?"tamanho desconhecido":So(e.database.size_bytes);if(e.status==="unchanged"){let l=e.database.row_count===null?"quantidade desconhecida de registros":`${De(e.database.row_count)} registros`;console.log(`A base DNE j\xE1 est\xE1 atualizada: ${e.database.path} (${l}, ${c}).`),console.log(`\xDAltima modifica\xE7\xE3o na fonte: ${ut(Zn(e.source.last_modified))}`),console.log(`Verifica\xE7\xE3o conclu\xEDda em ${Qn(e.elapsed_ms)}.`);return}let u=e.status==="updated"?"Base atualizada":"Base criada";console.log(`${u}: ${e.database.path} (${i}, ${c}, ${Qn(e.elapsed_ms)}).`)}function Iu(e){if(e.length===1){let n=e[0];if(!n?.address){console.error(`CEP n\xE3o encontrado: ${n?.cep??""}`);return}console.log(n.address);return}console.log("cep\tencontrado\tlogradouro\tbairro\tmunic\xEDpio\tuf");for(let n of e)console.log([n.cep,sn(n.found),n.address?.logradouro??"",n.address?.bairro??"",n.address?.municipio??"",n.address?.uf??""].join("\t"))}function mu(e){if(console.log(`Base: ${e.path}`),console.log(`Formato: ${e.format??"-"}`),console.log(`Existe: ${sn(e.exists)}`),console.log(`Pronta: ${sn(e.ready)}`),console.log(`Registros: ${e.row_count===null?"-":De(e.row_count)}`),console.log(`Tamanho: ${e.size_bytes===null?"-":So(e.size_bytes)}`),console.log(`Carregada em: ${ut(e.metadata?.loaded_at)}`),console.log(`Pacote: @konstit/dne@${e.metadata?.package_version??"-"}`),console.log(`Fonte: ${e.metadata?.source_url??e.metadata?.source_input??"-"}`),console.log(`\xDAltima modifica\xE7\xE3o da fonte: ${ut(e.metadata?.source_last_modified)}`),e.error)console.log(`Erro: ${e.error}`)}function Su(e){if(console.log(`CLI: dne ${e.version}`),console.log(`Ambiente: ${e.runtime.name} ${e.runtime.version} (${e.runtime.compatible?"compat\xEDvel":"n\xE3o compat\xEDvel"})`),console.log(`Base: ${e.database.ready?"pronta":"configura\xE7\xE3o necess\xE1ria"} (${e.database.path})`),console.log(`Fonte: ${e.source.reachable===null?"n\xE3o verificada":e.source.reachable?"acess\xEDvel":"inacess\xEDvel"}`),console.log(`Saud\xE1vel: ${sn(e.healthy)}`),e.setup)console.log(`Configura\xE7\xE3o: ${e.setup}`)}function hu(e){return e instanceof Error?e.message:String(e)}function _t(e){return Tu(hu(e))}function Tu(e){let i={"Failed to write downloaded content":"Falha ao gravar o conte\xFAdo baixado","Invalid ZIP central directory entry":"Entrada inv\xE1lida no diret\xF3rio central do ZIP","Invalid ZIP central directory entry size":"Tamanho inv\xE1lido de entrada no diret\xF3rio central do ZIP","Invalid ZIP central directory range":"Intervalo inv\xE1lido do diret\xF3rio central do ZIP","Only sqlite:/// database URLs are supported":"Somente URLs de base no formato sqlite:/// s\xE3o aceitas","package.json has no valid version":"package.json n\xE3o cont\xE9m uma vers\xE3o v\xE1lida","Source is not a valid ZIP file":"A fonte n\xE3o \xE9 um arquivo ZIP v\xE1lido","Unified schema table not found":"Tabela unificada n\xE3o encontrada no schema","ZIP file does not contain DNE Basico files":"O arquivo ZIP n\xE3o cont\xE9m arquivos do DNE B\xE1sico"}[e];if(i)return i;return e.replace(/^Failed to download (.+): (\d+)$/,"Falha ao baixar $1: $2").replace(/^Failed to stream (.+): empty response body$/,"Falha ao transmitir $1: corpo da resposta vazio").replace(/^Failed to inspect DNE from (.+): (\d+)$/,"Falha ao inspecionar o DNE em $1: $2").replace(/^DNE source not found: (.+)$/,"Fonte DNE n\xE3o encontrada: $1").replace(/^DNE source quality validation failed: (.+)$/,"A valida\xE7\xE3o de qualidade da fonte DNE falhou: $1").replace(/^DNE data file not found: (.+)$/,"Arquivo de dados DNE n\xE3o encontrado: $1").replace(/^Invalid ZIP local header for (.+)$/,"Cabe\xE7alho local ZIP inv\xE1lido para $1").replace(/^Invalid ZIP data range for (.+)$/,"Intervalo de dados ZIP inv\xE1lido para $1").replace(/^Invalid decompressed size for (.+)$/,"Tamanho descompactado inv\xE1lido para $1").replace(/^Unsupported ZIP compression method (\d+) for (.+)$/,"M\xE9todo de compacta\xE7\xE3o ZIP $1 n\xE3o aceito para $2").replace(/^CRC32 mismatch for (.+)$/,"CRC32 divergente para $1").replace(/^Server ignored byte range (.+)$/,"O servidor ignorou o intervalo de bytes $1").replace(/^Server returned an invalid Content-Range for (.+)$/,"O servidor retornou um Content-Range inv\xE1lido para $1").replace(/^Server returned (\d+) bytes for range (.+); expected (\d+)$/,"O servidor retornou $1 bytes para o intervalo $2; eram esperados $3").replace(/^Missing row at index (\d+)$/,"Registro ausente no \xEDndice $1").replace(/^Table with original name '(.+)' not found$/,"Tabela com nome original '$1' n\xE3o encontrada")}function Wn(e){return e.replaceAll("Usage:","Uso:").replaceAll("Arguments:","Argumentos:").replaceAll("Commands:","Comandos:").replaceAll("Options:","Op\xE7\xF5es:").replaceAll("Print help for a subcommand","Exibir ajuda de um subcomando").replaceAll("Print help","Exibir ajuda").replaceAll("Print version","Exibir vers\xE3o").replaceAll("Enable or disable color output","Ativar ou desativar cores na sa\xEDda").replaceAll("expected a schedulable Bun cron expression","esperada uma express\xE3o cron v\xE1lida").replaceAll("[env:","[vari\xE1vel:").replaceAll("[default:","[padr\xE3o:").replaceAll("For more information, try '--help'.","Para mais informa\xE7\xF5es, use '--help'.").replaceAll("error:","erro:").replace(/invalid value (.+?) for (.+?): expected value matching (.+)/g,"valor inv\xE1lido $1 para $2: esperado valor compat\xEDvel com $3").replace(/invalid value (.+?) for (.+?): expected a number from (.+?) to (.+)/g,"valor inv\xE1lido $1 para $2: esperado n\xFAmero entre $3 e $4").replace(/invalid value (.+?) for (.+?): (.+)/g,"valor inv\xE1lido $1 para $2: $3").replace(/unexpected argument (.+)/g,"argumento inesperado $1").replace(/arguments (.+?) and (.+?) cannot be used together/g,"os argumentos $1 e $2 n\xE3o podem ser usados juntos").replace(/argument (.+?) requires at least (\d+) value\(s\)/g,"o argumento $1 exige pelo menos $2 valor(es)").replace(/the following required arguments were not provided:/g,"os seguintes argumentos obrigat\xF3rios n\xE3o foram informados:").replace(/a similar argument exists:/g,"existe um argumento semelhante:")}function Zn(e){return typeof e==="string"?e:""}function bu(e){return e.split(`
49
+ `).map((n)=>n.trim()).find(Boolean)?.replace(/^error:\s*/i,"")??"Argumentos inv\xE1lidos."}function zn(e){return Math.max(0,Math.round(performance.now()-e))}function De(e){return Kc.format(e)}function so(e){return eu.format(e)}function ut(e){if(!e)return"-";let n=new Date(e);return Number.isNaN(n.getTime())?e:n.toLocaleString(cn)}function Qn(e){let n=Math.max(0,Math.round(e));if(n<1000)return`${De(n)} ms`;let i=Math.round(n/1000);if(i<60){let d=Math.round(n/100)/10;return`${tu.format(d)} s`}let c=Math.floor(i/3600),u=Math.floor(i%3600/60),l=i%60;return[c?`${De(c)} h`:"",u?`${De(u)} min`:"",l?`${De(l)} s`:""].filter(Boolean).join(" ")}function So(e){if(e<1024)return`${De(e)} B`;if(e<1048576)return`${so(e/1024)} KiB`;return`${so(e/1048576)} MiB`}function sn(e){return e?"sim":"n\xE3o"}function gu(e){return{current:"atualizada",unknown:"desconhecido","update-available":"atualiza\xE7\xE3o dispon\xEDvel"}[e]??e}function Du(e){return`'${e.replaceAll("'","'\\''")}'`}function yu(e){let[n=0,i=0]=e.split(".").map(Number);return n>1||n===1&&i>=4}function ho(){let e=br();return _e(e).name=z,e}async function Nu(e,n,i){let c=It(i),u=`${n}.attach`;await ge(u,{force:!0}),await Hc(n,u);let l=new kc(e);try{l.run("PRAGMA busy_timeout = 30000"),l.run("PRAGMA journal_mode = WAL"),l.run("PRAGMA synchronous = NORMAL"),l.run("PRAGMA foreign_keys = ON"),l.run(`ATTACH DATABASE ${bo(u)} AS fresh`),l.run("BEGIN IMMEDIATE");try{Xt(l,i),l.run(`
50
+ CREATE TABLE IF NOT EXISTS ${M(Z)} (
51
51
  key TEXT PRIMARY KEY NOT NULL,
52
52
  value TEXT NOT NULL
53
53
  )
54
- `);for(let a of r){let s=a.columns.map((l)=>y(l.name)).join(", ");o.run(`
55
- INSERT INTO main.${y(a.name)} (${s})
56
- SELECT ${s} FROM fresh.${y(a.name)}
57
- `)}o.run(`DELETE FROM main.${y(A)}`),o.run(`
58
- INSERT INTO main.${y(A)} (key, value)
54
+ `);for(let d of c){let A=d.columns.map((E)=>M(E.name)).join(", ");l.run(`
55
+ INSERT INTO main.${M(d.name)} (${A})
56
+ SELECT ${A} FROM fresh.${M(d.name)}
57
+ `)}l.run(`DELETE FROM main.${M(Z)}`),l.run(`
58
+ INSERT INTO main.${M(Z)} (key, value)
59
59
  SELECT key, value
60
- FROM fresh.${y(A)}
61
- `),o.run("COMMIT")}catch(a){throw o.run("ROLLBACK"),a}finally{o.run("DETACH DATABASE fresh")}}finally{o.close(),await ue(i,{force:!0})}}async function jr(e,t,n){let r=await ae(e);if(!r.ready||r.format!==t||!r.metadata)return!1;return Pr(r.metadata,n)}function ei(e){try{let t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"}catch{return!1}}function ti(e){return`'${e.replaceAll("'","''")}'`}function Za(e){let t=e.indexOf("("),n=e.lastIndexOf(")");if(t===-1||n<=t)return e;let r=Ya(e.slice(t+1,n));if(!r.length)return e;let i=e.slice(0,t+1).trimEnd(),o=e.slice(n).trimStart();return`${i}
62
- ${r.join(`,
60
+ FROM fresh.${M(Z)}
61
+ `),l.run("COMMIT")}catch(d){throw l.run("ROLLBACK"),d}finally{l.run("DETACH DATABASE fresh")}}finally{l.close(),await ge(u,{force:!0})}}async function co(e,n,i){let c=await $e(e);if(!c.ready||c.format!==n||!c.metadata)return!1;return no(c.metadata,i)}function To(e){try{let n=new URL(e);return n.protocol==="http:"||n.protocol==="https:"}catch{return!1}}function bo(e){return`'${e.replaceAll("'","''")}'`}function Cu(e){let n=e.indexOf("("),i=e.lastIndexOf(")");if(n===-1||i<=n)return e;let c=Lu(e.slice(n+1,i));if(!c.length)return e;let u=e.slice(0,n+1).trimEnd(),l=e.slice(i).trimStart();return`${u}
62
+ ${c.join(`,
63
63
  `)}
64
- ${o}`}function Ya(e){let t=[],n=0,r=0,i=null,o=null;for(let a=0;a<e.length;a++){let s=e[a];if(o==="line"){if(s===`
65
- `||s==="\r")o=null;continue}if(o==="block"){if(s==="*"&&e[a+1]==="/")o=null,a++;continue}if(i){if(s===i)if(e[a+1]===i)a++;else i=null;continue}if(s==="-"&&e[a+1]==="-")o="line",a++;else if(s==="/"&&e[a+1]==="*")o="block",a++;else if(s==="'"||s==='"'||s==="`")i=s;else if(s==="[")i="]";else if(s==="(")r++;else if(s===")")r--;else if(s===","&&r===0)t.push(e.slice(n,a).trim()),n=a+1}return t.push(e.slice(n).trim()),t.filter(Boolean)}function Va(e,t){return Bun.markdown.render(`\`\`\`sql
64
+ ${l}`}function Lu(e){let n=[],i=0,c=0,u=null,l=null;for(let d=0;d<e.length;d++){let A=e[d];if(l==="line"){if(A===`
65
+ `||A==="\r")l=null;continue}if(l==="block"){if(A==="*"&&e[d+1]==="/")l=null,d++;continue}if(u){if(A===u)if(e[d+1]===u)d++;else u=null;continue}if(A==="-"&&e[d+1]==="-")l="line",d++;else if(A==="/"&&e[d+1]==="*")l="block",d++;else if(A==="'"||A==='"'||A==="`")u=A;else if(A==="[")u="]";else if(A==="(")c++;else if(A===")")c--;else if(A===","&&c===0)n.push(e.slice(i,d).trim()),i=d+1}return n.push(e.slice(i).trim()),n.filter(Boolean)}function wu(e,n){return Bun.markdown.render(`\`\`\`sql
66
66
  ${e}
67
- \`\`\``,{code:(n)=>Xa(n,t)}).trimEnd()}function Xa(e,t){if(!t)return e;return e.replaceAll(ya,(n)=>{if(n.startsWith("--")||n.startsWith("/*"))return`${ha}${n}${en}`;if(n.startsWith('"')||n.startsWith("`")||n.startsWith("["))return`${ga}${n}${en}`;if(n.startsWith("'"))return n;return`${ba}${n}${en}`})}async function Ka(e){if(e===":memory:")return{path:e,commit:async(i)=>{},cleanup:async()=>{}};let t=fa(e),n=ma(t,`.${da(e)}.${process.pid}.${Date.now()}.tmp`);await la(t,{recursive:!0}),await ue(n,{force:!0});let r=!1;return{path:n,commit:async(i=n)=>{await ua(i,e),r=!0},cleanup:async()=>{if(!r)await ue(n,{force:!0});await ue(`${n}.bin`,{force:!0}),await ue(`${n}-journal`,{force:!0})}}}process.exitCode=await Vr();
67
+ \`\`\``,{code:(i)=>Mu(i,n)}).trimEnd()}function Mu(e,n){if(!n)return e;return e.replaceAll(Yc,(i)=>{if(i.startsWith("--")||i.startsWith("/*"))return`${Jc}${i}${Hn}`;if(i.startsWith('"')||i.startsWith("`")||i.startsWith("["))return`${Xc}${i}${Hn}`;if(i.startsWith("'"))return i;return`${Qc}${i}${Hn}`})}async function Uu(e){if(e===":memory:")return{path:e,commit:async(u)=>{},cleanup:async()=>{}};let n=jn(e),i=qn(n,`.${jc(e)}.${process.pid}.${Date.now()}.tmp`);await uo(n,{recursive:!0}),await ge(i,{force:!0});let c=!1;return{path:i,commit:async(u=i)=>{await lo(u,e),c=!0},cleanup:async()=>{if(!c)await ge(i,{force:!0});await ge(`${i}.bin`,{force:!0}),await ge(`${i}-journal`,{force:!0})}}}process.exitCode=await po();
68
68
 
69
- //# debugId=1E5DEF2E51CCBE6764756E2164756E21
69
+ //# debugId=0B29B0764C76F3BB64756E2164756E21