@konstit/dne 0.1.0 → 0.2.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.
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{a as v,c as Z,d as ze,e as V,f as Zt,o as N}from"./chunks/index-s0h4vdva.js";var zi=Object.freeze(["bash","zsh","fish","powershell"]);import{Database as Fs}from"bun:sqlite";import{copyFile as $s,mkdir as ks,rename as Ps,rm as Ie}from"fs/promises";import{basename as Ws,dirname as Hs,join as qs}from"path";import{Database as Mo}from"bun:sqlite";class ee extends Error{constructor(e,t){super(e,t);this.name=new.target.name}}class Ye extends ee{path;code="IO_ERROR";constructor(e,t){super(`Unable to read binary database: ${e}`,t);this.path=e}}class p extends ee{code="INVALID_FORMAT";constructor(e,t){super(e,t)}}class pt extends ee{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 bt extends ee{code="READER_CLOSED";constructor(){super("Binary database is closed")}}var te=5,O=256,P=32,G=16,k=Uint8Array.from([68,78,69,66,73,78,0,0]),$n=4294967295,Qt=1e5,ue=100001,ne=10,Be=32,ht=0,re=2,ie=255,de=2295,x=3,M=8,fe=8,W=256,xe=32,F=["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 Ze(e){return Math.ceil(e/8)*8}function Oe(e){return Math.ceil(e/8)}function Ce(e,t){return Math.ceil(e*t/8)}function Le(){let e=new Uint8Array(256);for(let t=1;t<e.length;t++)e[t]=(e[t>>>1]??0)+(t&1);return e}function B(e){if(e<=255)return 1;if(e<=65535)return 2;if(e<=16777215)return 3;return 4}function Ne(e,t){if(e!==1&&e!==2&&e!==3&&e!==4)throw Error(`Unsupported binary ${t} width: ${e}`);return e}function Qe(e){return e===4?4294967295:2**(e*8)-1}function Xt(e,t,n){if(!Number.isSafeInteger(e)||e<0||e>Qe(t))throw Error(`Binary ${n} exceeds the ${t}-byte unsigned integer limit: ${e}`)}function R(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 T(e,t,n,r){if(Xt(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 kn(e){if(e.byteLength!==k.length)return!1;return k.every((t,n)=>e[n]===t)}function Pn(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 Xe=8,Ue=3,ve=1<<Ue,Yi=Le();function Hn(e,t,n){let r=new DataView(e.buffer,e.byteOffset,e.byteLength),i=[],o=[],a=-1;for(let D=0;D<t;D++){let H=R(r,D*n,n);if(H!==a)i.push(D),o.push(H),a=H}let s=i.length,c=Math.floor(Math.log2(t/s)),l=2**c,u=Math.ceil(t/l),d=u+s,f=Math.ceil(s*c/8),m=Math.ceil(d/8),b=Math.ceil(u/ve),h=Xe+f,y=h+m,g=y+b*4,w=new Uint8Array(g+s*n),E=new DataView(w.buffer);E.setUint32(0,s,!0),E.setUint8(4,c),E.setUint8(5,Ue),E.setUint8(6,n);for(let D=0;D<s;D++){let H=i[D]??0;Zi(w,Xe,D*c,c,H%l);let le=Math.floor(H/l)+D,q=h+(le>>>3);w[q]=(w[q]??0)|1<<(le&7),T(w,g+D*n,o[D]??0,n)}let I=0;for(let D=0;D<d;D++)if(((w[h+(D>>>3)]??0)&1<<(D&7))===0){if(I%ve===0)E.setUint32(y+(I>>>Ue)*4,D,!0);I++}return w}function qn(e,t,n,r){let i=e.getUint32(t.offset,!0),o=e.getUint8(t.offset+4),a=Math.ceil(n/2**o),s=a+i,c=t.offset+Xe,l=c+Math.ceil(i*o/8),u=l+Math.ceil(s/8),d=u+Math.ceil(a/ve)*4;return{highBitCount:s,highOffset:l,idWidth:r,idsOffset:d,lowBits:o,lowOffset:c,runCount:i,samplesOffset:u,zeroCount:a}}function jn(e,t,n,r,i){if(t.length<Xe)throw new p("Binary neighborhood runs are truncated");let o=e.getUint32(t.offset,!0),a=e.getUint8(t.offset+4);if(o<1||o>n||a>31||e.getUint8(t.offset+5)!==Ue||e.getUint8(t.offset+6)!==r||e.getUint8(t.offset+7)!==0)throw new p("Invalid binary neighborhood run header");let s=2**a,c=Math.ceil(n/s),l=c+o,u=Math.ceil(o*a/8),d=Math.ceil(l/8),f=Math.ceil(c/ve),m=t.offset+Xe,b=m+u,h=b+d,y=h+f*4;if(y+o*r!==t.offset+t.length)throw new p("Invalid binary neighborhood run length");let g=0,w=0,E=-1,I=-1;for(let D=0;D<l;D++){if((e.getUint8(b+(D>>>3))&1<<(D&7))===0){if(g>=c)throw new p("Invalid binary neighborhood run bitmap");if(g%ve===0&&e.getUint32(h+(g>>>Ue)*4,!0)!==D)throw new p("Invalid binary neighborhood run samples");g++;continue}if(w>=o)throw new p("Invalid binary neighborhood run bitmap");let le=Gn(e,m,w*a,a),q=g*s+le,Re=R(e,y+w*r,r);if(w===0&&q!==0||q<=E||q>=n||Re>i||Re===I)throw new p("Invalid binary neighborhood run");E=q,I=Re,w++}if(l%8!==0){let D=255<<(l&7);if((e.getUint8(b+(l>>>3))&D)!==0)throw new p("Invalid binary neighborhood run padding")}return{highBitCount:l,highOffset:b,idWidth:r,idsOffset:y,lowBits:a,lowOffset:m,runCount:o,samplesOffset:h,zeroCount:c}}function Vn(e,t,n){let r=2**t.lowBits,i=Math.floor(n/r),o=Wn(e,t,i)-i,a=i===0?0:Wn(e,t,i-1)-(i-1),s=n%r,c=a,l=o;while(c<l){let d=c+(l-c>>>1);if(Gn(e,t.lowOffset,d*t.lowBits,t.lowBits)<=s)c=d+1;else l=d}let u=c-1;return R(e,t.idsOffset+u*t.idWidth,t.idWidth)}function Wn(e,t,n){let r=n>>>Ue,i=e.getUint32(t.samplesOffset+r*4,!0),o=n-r*ve;if(o===0)return i;i++;while(o>0){let a=i&7,s=8-a,c=(1<<s)-1,l=~(e.getUint8(t.highOffset+(i>>>3))>>>a)&c,u=Yi[l]??0;if(u>=o)for(let d=0;o>0;d++){if(l&1<<d)o--;i++}else o-=u,i+=s}return i-1}function Gn(e,t,n,r){let i=0;for(let o=0;o<r;o++){let a=n+o;if(e.getUint8(t+(a>>>3))&1<<(a&7))i+=2**o}return i}function Zi(e,t,n,r,i){for(let o=0;o<r;o++)if(Math.floor(i/2**o)%2){let a=n+o,s=t+(a>>>3);e[s]=(e[s]??0)|1<<(a&7)}}function z(e){return Number.isInteger(e)&&e>0&&e<=4294967295}var Me=8,Kt=8,Fe=1<<Kt;function zn(e,t,n){let r=new DataView(e.buffer,e.byteOffset,e.byteLength),i=[],o=[],a=[],s=-1,c=-1;for(let y=0;y<t.length;y++){let g=R(r,y*n,n),w=t[y]??0;if(g!==s||w!==c)i.push(y),o.push(g),a.push(w),s=g,c=w}let l=i.length,u=Math.ceil(t.length/Fe),d=Me+(u+1)*4,f=d+l*4,m=new Uint8Array(f+l*n),b=new DataView(m.buffer);b.setUint32(0,l,!0),b.setUint8(4,Kt);let h=0;for(let y=0;y<u;y++){while(h+1<l&&(i[h+1]??0)<=y*Fe)h++;b.setUint32(Me+y*4,h,!0)}b.setUint32(Me+u*4,l,!0);for(let y=0;y<l;y++)b.setUint32(d+y*4,i[y]??0,!0),T(m,f+y*n,o[y]??0,n);return{ids:m,flags:Uint8Array.from(a)}}function Yn(e,t,n){let r=e.getUint32(t.offset,!0),i=t.offset+Me,o=i+(Math.ceil(n/Fe)+1)*4;return{count:r,directoryOffset:i,startsOffset:o,idsOffset:o+r*4}}function Zn(e,t,n,r){if(t.length<Me)throw new p("Binary locality runs are truncated");let i=e.getUint32(t.offset,!0);if(i===0||i>n||e.getUint32(t.offset+4,!0)!==Kt)throw new p("Invalid binary locality run header");let o=Math.ceil(n/Fe),a=t.offset+Me,s=a+(o+1)*4,c=s+i*4;if(c+i*r!==t.offset+t.length)throw new p("Invalid binary locality run length");let l=-1;for(let d=0;d<i;d++){let f=e.getUint32(s+d*4,!0);if(d===0&&f!==0||f<=l||f>=n)throw new p("Invalid binary locality run boundary");l=f}let u=0;for(let d=0;d<o;d++){while(u+1<i&&e.getUint32(s+(u+1)*4,!0)<=d*Fe)u++;if(e.getUint32(a+d*4,!0)!==u)throw new p("Invalid binary locality run directory")}if(e.getUint32(a+o*4,!0)!==i)throw new p("Invalid binary locality run sentinel");return{count:i,directoryOffset:a,startsOffset:s,idsOffset:c}}function Qn(e,t,n){let r=Math.floor(n/Fe),i=e.getUint32(t.directoryOffset+r*4,!0),o=Math.min(t.count,e.getUint32(t.directoryOffset+(r+1)*4,!0)+1);while(i+1<o){let a=i+(o-i>>>1);if(e.getUint32(t.startsOffset+a*4,!0)<=n)i=a;else o=a}return i}function $e(e){return Math.max(1,Math.ceil(Math.log2(e+1)))}function yt(e,t,n,r){let i=n*r,o=t+Math.floor(i/8),a=i&7,s=a+r,c=e.getUint8(o);if(s>8)c|=e.getUint8(o+1)<<8;if(s>16)c|=e.getUint8(o+2)<<16;if(s>24)c|=e.getUint8(o+3)<<24;let l=c>>>a&4294967295>>>32-r;if(s>32)l+=(e.getUint8(o+4)&(1<<s-32)-1)*2**(32-a);return l>>>0}function Xn(e,t,n,r){if(!Number.isInteger(r)||r<0||r>=2**n||n<1||n>32)throw Error(`Invalid ${n}-bit column value: ${r}`);let i=t*n,o=Math.floor(i/8),a=i&7,s=r*2**a,c=Math.ceil((a+n)/8);for(let l=0;l<c;l++)e[o+l]=(e[o+l]??0)|Math.floor(s/2**(l*8))&255}var Ke="4",ke=["M","D","P"],Pe=["municipio","distrito","povoado"],We=["sem_codificacao_por_logradouro","codificada_por_logradouro","inserida_na_codificacao_por_logradouro","em_codificacao_por_logradouro"],Qi=[{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 Kn(e={}){return Qi.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 me(e){let t=e.find((n)=>n.unifiedTable);if(!t)throw Error("Unified schema table not found");return t}function Je(e){return e.filter((t)=>t.columns.length>0)}function et(e){if(e.unifiedTable||e.fileGlob===null)return null;return e.fileGlob??`${e.originalName.toUpperCase()}.TXT`}function pe(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 oe={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},Zc=Object.keys(oe).map(Jt);function Jt(e){let t=e.trim().toUpperCase();if(!Object.hasOwn(oe,t))throw Error(`Unknown UF: ${e}`);return t}var Jn=new TextDecoder("utf-8",{fatal:!0});function er(e){try{if(!(e instanceof Uint8Array))throw new p("Binary database bytes must be a Uint8Array");let t=new DataView(e.buffer,e.byteOffset,e.byteLength),n=Xi(t);Ki(e,n);let r=Ji(e,t,n);eo(r.uf);let i=io(e,t,n,r),o=oo(t,n,r),a=ao(e,t,n,r),s=jn(t,n.sections.bairroIds,n.rowCount,i.idWidth,i.count),c=Zn(t,n.sections.municipalityIds,n.rowCount,n.municipalityIdWidth);co(t,n,s,c),fo(t,n,i),mo(e,t,n),po(e,t,n,r.logradouro),bo(t,n,r,i,s,c,a,o),wo(e,n.sections.metadata)}catch(t){if(t instanceof p)throw t;let n=t instanceof Error?t.message:String(t);throw new p(`Unable to validate binary database: ${n}`,{cause:t})}}function Xi(e){if(e.byteLength<O+P)throw new p("Binary database header is truncated");for(let n=0;n<k.length;n++)if(e.getUint8(n)!==k[n])throw new p("Invalid binary database magic");if(e.getUint16(8,!0)!==te)throw new p("Unsupported binary database version");if(e.getUint16(10,!0)!==O)throw new p("Unsupported binary database header size");if(e.getUint8(22)!==fe||e.getUint8(23)!==x)throw new p("Unsupported binary database block layout");if(e.getUint16(24,!0)!==F.length)throw new p("Unsupported binary database section table");let t={};for(let[n,r]of F.entries()){let i=xe+n*8;t[r]={length:e.getUint32(i+4,!0),offset:e.getUint32(i,!0)}}return{cepPrefixOffsetWidth:Ne(e.getUint8(20),"CEP prefix offset"),fileSize:e.getUint32(16,!0),municipalityCount:e.getUint32(28,!0),municipalityIdWidth:Ne(e.getUint8(21),"municipality id"),rowCount:e.getUint32(12,!0),sections:t}}function Ki(e,t){let n=e.byteLength-P;if(t.fileSize!==e.byteLength)throw new p(`Binary database size mismatch: header=${t.fileSize}, actual=${e.byteLength}`);if(n<O||n%8!==0)throw new p("Binary database payload has an invalid alignment");if(!t.rowCount||!t.municipalityCount)throw new p("Binary database must contain rows and municipalities");if(t.rowCount>Qe(t.cepPrefixOffsetWidth))throw new p("Binary row count does not fit the CEP prefix offset width");if(t.municipalityCount>Qe(t.municipalityIdWidth))throw new p("Binary municipality count does not fit its id width");if(t.cepPrefixOffsetWidth!==B(t.rowCount)||t.municipalityIdWidth!==B(t.municipalityCount))throw new p("Binary database uses a noncanonical integer width");He(e,26,28,"binary header reserved bytes"),He(e,248,O,"binary header reserved bytes");let r=O;for(let o of F){let a=t.sections[o];if(Eo(n,a,o),a.offset%8!==0||a.offset<r)throw new p(`Binary section is out of order or unaligned: ${o}`);He(e,r,a.offset,`${o} section padding`),r=a.offset+a.length}if(He(e,r,n,"final binary section padding"),Ze(r)!==n)throw new p("Binary database footer is not after aligned section data");Q(t.sections.cepPrefixOffsets,ue*t.cepPrefixOffsetWidth,"CEP prefix directory"),Q(t.sections.cepSuffixes,Ce(t.rowCount,ne),"CEP suffix column");for(let o of["complementoBitmap","nomeBitmap","localidadeNomeBitmap"])Q(t.sections[o],Oe(t.rowCount),"nullable bitmap");let i=(Math.ceil(t.rowCount/W)+1)*4;for(let o of["complementoRanks","nomeRanks","localidadeNomeRanks"])Q(t.sections[o],i,"sparse rank index")}function Ji(e,t,n){return{bairro:be(e,t,n.sections.bairroDictionary,"bairro",!1),bairroAbreviado:be(e,t,n.sections.bairroAbreviadoDictionary,"bairro abbreviation",!1),complemento:be(e,t,n.sections.complementoDictionary,"complemento",!1),logradouro:be(e,t,n.sections.logradouroDictionary,"logradouro",!0),municipio:be(e,t,n.sections.municipioDictionary,"municipio",!1),nome:be(e,t,n.sections.nomeDictionary,"nome",!1),uf:be(e,t,n.sections.ufDictionary,"uf",!1)}}function eo(e){for(let[t,n]of e.values.entries())en(n,t)}function en(e,t){let n;try{n=Jt(e)}catch(r){throw new p(`Invalid binary UF dictionary entry: ${t}`,{cause:r})}if(e!==n)throw new p(`Binary UF dictionary entry is not canonical: ${t}`);return n}function be(e,t,n,r,i){if(n.length<Be)throw new p(`Binary ${r} dictionary is truncated`);let o=t.getUint32(n.offset,!0),a=t.getUint32(n.offset+4,!0),s=t.getUint32(n.offset+8,!0),c=t.getUint32(n.offset+12,!0),l=t.getUint32(n.offset+16,!0),u=t.getUint32(n.offset+20,!0),d=t.getUint32(n.offset+24,!0),f=Ne(t.getUint8(n.offset+28),`${r} dictionary id`),m=t.getUint8(n.offset+30),b=t.getUint8(n.offset+31);if(m!==ht&&(m!==re||!i)||(m===ht?b!==0:b!==1&&b!==2))throw new p(`Unsupported binary ${r} dictionary codec or length width`);if(t.getUint8(n.offset+29)!==x)throw new p(`Unsupported binary ${r} dictionary block size`);let h=Math.ceil(o/M);if(a!==h||o>Qe(f))throw new p(`Binary ${r} dictionary has an invalid count or id width`);let y=b===2?2:1,g=m===re?de:0;if(s!==Be||c!==s+a*4||l!==c+o*y||u!==l+o+g||u>n.length||d!==n.length-u||f!==B(o))throw new p(`Binary ${r} dictionary has an invalid layout`);let w={blockCount:a,blockOffsetsOffset:n.offset+s,codec:m,count:o,idWidth:f,lengthWidth:y,lengthsOffset:n.offset+c,prefixesOffset:n.offset+l,region:n,suffixDataLength:d,suffixDataOffset:n.offset+u,symbolsOffset:n.offset+l+o,values:[]};return to(e,t,w,r),w.values=no(e,t,w,r),w}function to(e,t,n,r){if(n.blockCount&&t.getUint32(n.blockOffsetsOffset,!0)!==0)throw new p(`Binary ${r} dictionary has an invalid first block offset`);let i=0;for(let o=0;o<n.blockCount;o++){let a=t.getUint32(n.blockOffsetsOffset+o*4,!0);if(a<i||a>n.suffixDataLength)throw new p(`Binary ${r} dictionary has invalid block offsets`);i=a}if(n.codec===re)for(let o=0;o<ie;o++){let a=e[n.symbolsOffset+o]??0;if(a>8)throw new p(`Invalid binary ${r} FSST symbol length`);let s=n.symbolsOffset+ie+o*8;He(e,s+a,s+8,`binary ${r} FSST symbol padding`)}if(n.blockCount===0&&n.suffixDataLength!==0)throw new p(`Binary ${r} dictionary has unexpected payload`)}function no(e,t,n,r){let i=[],o=r==="bairro"||r==="municipio"||r==="uf",a;for(let s=0;s<n.blockCount;s++){let c=s*M,l=Math.min(n.count,c+M),u=t.getUint32(n.blockOffsetsOffset+s*4,!0),d=s+1<n.blockCount?t.getUint32(n.blockOffsetsOffset+(s+1)*4,!0):n.suffixDataLength,f=n.suffixDataOffset+u,m=n.suffixDataOffset+d,b=new Uint8Array;for(let h=c;h<l;h++){let y=e[n.prefixesOffset+h]??0;if(h===c&&y!==0||y>b.byteLength)throw new p(`Invalid binary ${r} dictionary prefix: ${h}`);let g;if(n.codec===ht){let E=e[n.lengthsOffset+h]??0;if(y>E)throw new p(`Invalid binary ${r} dictionary length: ${h}`);let I=E-y;if(f<n.suffixDataOffset||f+I>m)throw new p(`Invalid binary ${r} dictionary suffix: ${h}`);g=new Uint8Array(E),g.set(b.subarray(0,y)),g.set(e.subarray(f,f+I),y),f+=I}else{let E=n.lengthWidth===1?e[n.lengthsOffset+h]??0:t.getUint16(n.lengthsOffset+h*2,!0);if(f<n.suffixDataOffset||f+E>m)throw new p(`Invalid binary ${r} FSST suffix: ${h}`);if(E>510)throw new p(`Binary ${r} FSST suffix is too long: ${h}`);g=ro(e,n,f,E,b,y,r,h),f+=E}let w;try{w=Jn.decode(g)}catch(E){throw new p(`Invalid UTF-8 in binary ${r} dictionary entry: ${h}`,{cause:E})}if(a!==void 0&&a>=w)throw new p(`Binary ${r} dictionary is not strictly sorted: ${h}`);if(o)i.push(w);a=w,b=g}if(f!==m)throw new p(`Binary ${r} dictionary block length mismatch`)}return i}function ro(e,t,n,r,i,o,a,s){let c=new Uint8Array(255);c.set(i.subarray(0,o));let l=o,u=n,d=n+r;while(u<d){let f=e[u++]??0;if(f===255){if(u>=d||l>=255)throw new p(`Invalid binary ${a} FSST escape: ${s}`);c[l++]=e[u++]??0;continue}let m=e[t.symbolsOffset+f]??0;if(!m||m>8||l+m>255)throw new p(`Invalid binary ${a} FSST symbol: ${s}`);let b=t.symbolsOffset+ie+f*8;c.set(e.subarray(b,b+m),l),l+=m}return c.slice(0,l)}function io(e,t,n,r){let i=n.sections.bairros;if(i.length<G)throw new p("Binary neighborhood table is truncated");let o=t.getUint32(i.offset,!0),a=Ne(t.getUint8(i.offset+4),"original neighborhood id"),s=Ne(t.getUint8(i.offset+5),"original locality id"),c=a+s+r.bairro.idWidth+r.bairroAbreviado.idWidth+r.uf.idWidth;Q(i,G+o*c,"neighborhood table"),He(e,i.offset+6,i.offset+G,"neighborhood table reserved bytes");let l=i.offset+G,u=0,d=0,f=0;for(let m=0;m<o;m++){let b=l+m*c,h=R(t,b,a);b+=a;let y=R(t,b,s);b+=s;let g=R(t,b,r.bairro.idWidth);b+=r.bairro.idWidth;let w=R(t,b,r.bairroAbreviado.idWidth);b+=r.bairroAbreviado.idWidth;let E=R(t,b,r.uf.idWidth);if(h<=u||y===0||g===0||g>r.bairro.count||w>r.bairroAbreviado.count||E===0||E>r.uf.count)throw new p(`Invalid binary neighborhood record: ${m}`);if(!r.bairro.values[g-1])throw new p(`Binary neighborhood has an empty name: ${m}`);en(r.uf.values[E-1]??"",m),u=h,d=Math.max(d,h),f=Math.max(f,y)}if(a!==B(d)||s!==B(f))throw new p("Binary neighborhood table uses a noncanonical integer width");return{count:o,idWidth:B(o),localidadeIdWidth:s,originalIdWidth:a,recordWidth:c,recordsOffset:l}}function oo(e,t,n){let r=3+n.municipio.idWidth+n.uf.idWidth,i=t.sections.municipalities;Q(i,t.municipalityCount*r,"municipalities");let o=new Uint32Array(t.municipalityCount+1),a=0;for(let s=0;s<t.municipalityCount;s++){let c=i.offset+s*r,l=R(e,c,3),u=R(e,c+3,n.municipio.idWidth),d=R(e,c+3+n.municipio.idWidth,n.uf.idWidth);if(l<1e6||l>9999999||l<=a)throw new p(`Invalid binary IBGE municipality code: ${l}`);if(u===0||u>n.municipio.count||d===0||d>n.uf.count)throw new p(`Invalid binary municipality record: ${s}`);if(!n.municipio.values[u-1])throw new p(`Binary municipality has an empty name: ${s}`);let f=en(n.uf.values[d-1]??"",s);if(Math.floor(l/1e5)!==oe[f])throw new p(`IBGE municipality code does not match UF: ${l} (${f}, ${oe[f]})`);o[s+1]=d,a=l}return{ufIds:o}}function ao(e,t,n,r){let i=new Uint32Array(n.rowCount);for(let[o,a,s]of[["complemento",r.complemento,void 0],["nome",r.nome,void 0],["localidadeNome",r.bairro,i]])so(e,t,n.rowCount,n.sections[`${o}Bitmap`],n.sections[`${o}Ranks`],n.sections[`${o}Ids`],a.idWidth,a.count,o,s);return{localidadeNome:i}}function so(e,t,n,r,i,o,a,s,c,l){if(o.length%a!==0)throw new p(`Binary ${c} sparse ids have an invalid length`);let u=Math.ceil(n/W),d=0;for(let m=0;m<u;m++){let b=d;if(t.getUint32(i.offset+m*4,!0)!==b)throw new p(`Binary ${c} sparse rank mismatch: ${m}`);let y=m*W,g=Math.min(n,y+W);for(let w=y;w<g;w++){if(((e[r.offset+(w>>>3)]??0)&1<<(w&7))===0)continue;if(d>=o.length/a)throw new p(`Binary ${c} sparse id index is outside the column`);let I=R(t,o.offset+d*a,a);if(I===0||I>s)throw new p(`Invalid binary ${c} sparse id: ${I}`);if(l)l[w]=I;d++}}if(t.getUint32(i.offset+u*4,!0)!==d||o.length!==d*a)throw new p(`Binary ${c} sparse column has an invalid final rank`);_o(e,r,n,c)}function co(e,t,n,r){Q(t.sections.localidadeFlags,r.count,"locality indicators"),lo(e,n),uo(e,t.sections.localidadeFlags,t,r)}function lo(e,t){let n=t.runCount*t.lowBits;if(n%8!==0&&(e.getUint8(t.lowOffset+Math.floor(n/8))&255<<(n&7))!==0)throw new p("Invalid binary neighborhood run low-bit padding")}function uo(e,t,n,r){let i=-1,o=-1;for(let a=0;a<r.count;a++){let s=R(e,r.idsOffset+a*n.municipalityIdWidth,n.municipalityIdWidth),c=e.getUint8(t.offset+a);if(s===0||s>n.municipalityCount||(c&3)>=We.length||c>>>2>=Pe.length||s===i&&c===o)throw new p(`Invalid binary locality run: ${a}`);i=s,o=c}}function fo(e,t,n){let{bairroFaixaOffsets:r,bairroFaixas:i}=t.sections;if(Q(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 c=e.getUint32(r.offset+(s+1)*4,!0);if(c<a||c>o)throw new p("Invalid binary neighborhood range offsets");let l=-1,u=-1;for(let d=a;d<c;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<l||f===l&&m<=u)throw new p("Invalid binary neighborhood CEP range");l=f,u=m}a=c}if(a!==o)throw new p("Unreferenced binary neighborhood CEP ranges")}function mo(e,t,n){let r=n.sections.cepPrefixOffsets,i=new Uint32Array(ue),o=0;for(let s=0;s<ue;s++){let c=R(t,r.offset+s*n.cepPrefixOffsetWidth,n.cepPrefixOffsetWidth);if(c<o||c>n.rowCount)throw new p(`Invalid binary CEP prefix boundary: ${s}`);i[s]=c,o=c}if(i[0]!==0||i[Qt]!==n.rowCount)throw new p("Binary CEP prefix directory has invalid boundaries");for(let s=0;s<Qt;s++){let c=i[s]??0,l=i[s+1]??0,u=-1;for(let d=c;d<l;d++){let f=So(e,n.sections.cepSuffixes.offset,d);if(f>999||f<=u)throw new p(`Binary CEP suffixes are not strictly ordered: ${d}`);u=f}}let a=n.rowCount*ne;if(a%8!==0){if(((e[n.sections.cepSuffixes.offset+n.sections.cepSuffixes.length-1]??0)&255<<(a&7))!==0)throw new p("Invalid binary CEP suffix padding")}}function po(e,t,n,r){let i=n.sections.logradouroIds,o=$e(r.count);Q(i,Ce(n.rowCount,o),"logradouro ids");for(let s=0;s<n.rowCount;s++){let c=yt(t,i.offset,s,o);if(c>r.count)throw new p(`Invalid binary logradouro id: ${c}`)}let a=n.rowCount*o;if(a%8!==0){if(((e[i.offset+i.length-1]??0)&255<<(a&7))!==0)throw new p("Invalid binary logradouro id padding")}}function bo(e,t,n,r,i,o,a,s){let c=yo(e,i),l=go(e,t,o),u=0,d=0;for(let f=0;f<t.rowCount;f++){while(u+1<c.starts.length&&(c.starts[u+1]??0)<=f)u++;while(d+1<l.starts.length&&(l.starts[d+1]??0)<=f)d++;let m=c.ids[u]??0,b=l.ids[d]??0,y=(l.flags[d]??0)>>>2;if((a.localidadeNome[f]??0)!==0&&(m!==0||y===0))throw new p(`Invalid binary subordinate locality name: ${f}`);if(m!==0){if(ho(e,r,n,m)!==s.ufIds[b])throw new p(`Neighborhood and municipality UFs differ: ${f}`)}}}function ho(e,t,n,r){let i=t.recordsOffset+(r-1)*t.recordWidth+t.originalIdWidth+t.localidadeIdWidth+n.bairro.idWidth+n.bairroAbreviado.idWidth;return R(e,i,n.uf.idWidth)}function yo(e,t){let n=new Uint32Array(t.runCount),r=new Uint32Array(t.runCount),i=2**t.lowBits,o=0,a=0;for(let s=0;s<t.highBitCount;s++){if((e.getUint8(t.highOffset+(s>>>3))&1<<(s&7))===0){o++;continue}let l=Do(e,t.lowOffset,a*t.lowBits,t.lowBits);n[a]=o*i+l,r[a]=R(e,t.idsOffset+a*t.idWidth,t.idWidth),a++}return{ids:r,starts:n}}function go(e,t,n){let r=new Uint32Array(n.count),i=new Uint32Array(n.count),o=new Uint8Array(n.count);for(let a=0;a<n.count;a++)r[a]=e.getUint32(n.startsOffset+a*4,!0),i[a]=R(e,n.idsOffset+a*t.municipalityIdWidth,t.municipalityIdWidth),o[a]=e.getUint8(t.sections.localidadeFlags.offset+a);return{flags:o,ids:i,starts:r}}function wo(e,t){let n=e.subarray(t.offset,t.offset+t.length);if(n[0]===239&&n[1]===187&&n[2]===191)throw new p("Binary database metadata must not contain a UTF-8 BOM");let r;try{r=JSON.parse(Jn.decode(n))}catch(i){throw new p("Binary database metadata is invalid JSON or UTF-8",{cause:i})}if(!r||typeof r!=="object"||Array.isArray(r))throw new p("Binary database metadata must be an object");for(let i of Object.values(r))if(typeof i!=="string")throw new p("Binary database metadata values must be strings")}function Eo(e,t,n){if(t.offset<O||t.offset>e||t.length>e-t.offset)throw new p(`Binary ${n} region is outside the payload`)}function Q(e,t,n){if(e.length!==t)throw new p(`Binary ${n} region has an invalid length`)}function He(e,t,n,r){for(let i=t;i<n;i++)if((e[i]??0)!==0)throw new p(`Invalid ${r}`)}function _o(e,t,n,r){if(n%8!==0){if(((e[t.offset+t.length-1]??0)&255<<(n&7))!==0)throw new p(`Invalid binary ${r} bitmap padding`)}}function So(e,t,n){let r=n*ne,i=t+Math.floor(r/8),o=r&7;return((e[i]??0)|(e[i+1]??0)<<8|(e[i+2]??0)<<16)>>>o&1023}function Do(e,t,n,r){let i=0;for(let o=0;o<r;o++){let a=n+o;if(e.getUint8(t+(a>>>3))&1<<(a&7))i+=2**o}return i}function tr(e){er(e);let t=e.byteLength-P;e.set(new Bun.CryptoHasher("sha256").update(e.subarray(0,t)).digest(),t)}function nr(e){let t=e.byteLength-P,n=new Bun.CryptoHasher("sha256").update(e.subarray(0,t)).digest();for(let r=0;r<P;r++)if(e[t+r]!==n[r])throw new p("Binary database SHA-256 checksum mismatch")}var tt=255,Io=255,wt=8,rr=510,gt=65536,Ao=[64,128,160,192,224];function ar(e){if(!e.count)throw Error("Cannot train FSST with an empty dictionary");let t=Ro(e),n=xo(To(t),Bo(t),t),r=Co(e,n);return{compressedLengths:r.maxLength<=255?Uint8Array.from(r.lengths):vo(r.lengths),lengthWidth:r.maxLength<=255?1:2,payload:r.payload,symbols:n.symbols}}function Ro(e){let t=e.totalBytes,n=[],r=Math.min(e.count,gt,Math.ceil(gt/Math.max(1,t/e.count))),i=e.count/Math.max(1,r),o=2654435769,a=0;for(let s=0;s<r&&a<gt;s++){o=Math.imul(o,1664525)+1013904223>>>0;let c=Math.floor(o/4294967296*Math.max(1,i)),l=Math.min(e.count-1,Math.floor(s*i)+c),u=e.get(l);if(!u?.byteLength)continue;let d=gt-a;n.push(u.byteLength<=d?u:u.subarray(0,d)),a+=Math.min(u.byteLength,d)}return n}function To(e){let t=new Map;for(let r of e)for(let i=0;i+1<r.byteLength;i++){let o="",a=Math.min(r.byteLength,i+wt);for(let s=i;s<a;s++)if(o+=String.fromCharCode(r[s]??0),s-i+1>=2)t.set(o,(t.get(o)??0)+1)}let n=[];for(let[r,i]of t){let o=r.length;n.push({key:r,length:o,score:i*(o-1)})}return n.sort(Uo),n.slice(0,4096)}function Bo(e){let t=new Uint32Array(256);for(let n of e)for(let r of n)t[r]=(t[r]??0)+1;return Array.from({length:256},(n,r)=>r).filter((n)=>(t[n]??0)>0).sort((n,r)=>(t[r]??0)-(t[n]??0)||n-r)}function xo(e,t,n){let r=ir(t.slice(0,tt).map((o)=>Uint8Array.of(o))),i={table:r,size:or(n,r).size};for(let o of Ao){let a=e.slice(0,o),s=a.length,c=t.slice(0,tt-a.length).map((l)=>Uint8Array.of(l));for(let l=0;l<4;l++){let u=a.map((b)=>No(b.key)).concat(c),d=ir(u),f=or(n,d);if(f.size<i.size)i={table:d,size:f.size};let m=a.filter((b,h)=>(f.uses[h]??0)>0);if(m.length===a.length||s===e.length)break;while(m.length<o&&s<e.length){let b=e[s++];if(b)m.push(b)}a=m}}return i.table}function ir(e){let t=new Uint8Array(de),n=sr();for(let[r,i]of e.entries()){if(r>=tt||i.byteLength<1||i.byteLength>wt)break;t[r]=i.byteLength,t.set(i,tt+r*wt),Oo(n,i,r)}return{symbols:t,trie:n}}function sr(){return{code:-1,children:new Map}}function Oo(e,t,n){let r=e;for(let i of t){let o=r.children.get(i);if(!o)o=sr(),r.children.set(i,o);r=o}r.code=n}function or(e,t){let n=0,r=new Uint32Array(tt);for(let i of e){let o=0;while(o<i.byteLength){let a=cr(i,o,t.trie);if(a)n++,r[a.code]=(r[a.code]??0)+1,o+=a.length;else n+=2,o++}}return{size:n,uses:r}}function Co(e,t){let n=new Uint32Array(e.count),r=e.totalBytes*2,i=new Uint8Array(r),o=0,a=0;for(let s=0;s<e.count;s++){let c=e.get(s),l=o;o=Lo(c,t,i,o);let u=o-l;if(n[s]=u,a=Math.max(a,u),u>rr)throw Error(`FSST compressed suffix exceeds ${rr} bytes: ${u}`)}return{lengths:n,maxLength:a,payload:i.slice(0,o)}}function Lo(e,t,n,r){let i=0,o=r;while(i<e.byteLength){let a=cr(e,i,t.trie);if(a)n[o++]=a.code,i+=a.length;else n[o++]=Io,n[o++]=e[i++]??0}return o}function cr(e,t,n){let r=n,i=-1,o=0,a=Math.min(e.byteLength,t+wt);for(let s=t;s<a;s++){let c=r.children.get(e[s]??0);if(!c)break;if(r=c,r.code>=0)i=r.code,o=s-t+1}return i<0?void 0:{code:i,length:o}}function No(e){let t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return t}function Uo(e,t){return t.score-e.score||t.length-e.length||(e.key<t.key?-1:e.key>t.key?1:0)}function vo(e){let t=new Uint8Array(e.length*2),n=new DataView(t.buffer);for(let r=0;r<e.length;r++)n.setUint16(r*2,e[r]??0,!0);return t}var lr="dne",ur="dne.db",L="dne",he="bairros",Et="bairro_faixas",C="edne_metadata",dr=32768,fr=-200000,mr=1000,ae="https://www2.correios.com.br/sistemas/edne/download/eDNE_Basico.zip",pr=8,_t=2097152,br=30000,hr=2,yr=100,gr=1000,wr=2000;var rn=new TextEncoder,Fo=Le();async function Er(e,t,n=L){Jo();let r=new Mo(e,{readonly:!0});try{r.run("BEGIN");let i=Zo(r,n);if(St(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 ${rt(he)} ORDER BY bairro_id`).all(),a=new Map(o.map((A,j)=>[A.bairro_id,j+1])),s=B(o.length),c=$o(r,n,o),l=ko(c);l.logradouro=Po(l.logradouro);let u=[...c.municipalitiesByIbge.entries()].sort(([A],[j])=>A-j),d=u.length,f=B(d),m=new Map;for(let[A,[j]]of u.entries())m.set(j,A+1);let b=new Uint32Array(ue),h=new Uint8Array(Ce(i,ne)),y=$e(l.logradouro.count),g=new Uint8Array(Ce(i,y)),w=new Uint8Array(Oe(i)),E=new Uint8Array(c.complementoCount*l.complemento.idWidth),I=new Uint8Array(i*s),D=new Uint8Array(Oe(i)),H=new Uint8Array(c.localidadeNomeCount*l.bairro.idWidth),le=new Uint8Array(i*f),q=new Uint8Array(i),Re=new Uint8Array(Oe(i)),Cn=new Uint8Array(c.nomeCount*l.nome.idWidth),Ht=0,qt=0,jt=0,Te=0,Ln=-1,U=0;for(let A of _r(r,n)){let j=on(A.cep);if(j<=Ln)throw Error("CEP rows must be unique and ordered");Ln=j;let Mn=ke.indexOf(A.localidade_tipo);if(Mn===-1||![0,1,2,3].includes(A.localidade_situacao))throw Error(`Invalid locality indicators for CEP: ${A.cep}`);q[U]=Mn<<2|A.localidade_situacao;let Gi=Math.floor(j/1000);while(Te<=Gi)b[Te]=U,Te++;if(Pn(h,U,j%1000),Xn(g,U,y,Sr(l.logradouro,A.logradouro)),A.complemento!==null)nn(w,U),T(E,Ht*l.complemento.idWidth,se(l.complemento,A.complemento,"complemento"),l.complemento.idWidth),Ht++;let Yt=A.bairro_id===null?0:a.get(A.bairro_id);if(Yt===void 0)throw Error(`Unknown bairro_id for CEP: ${A.cep}`);if(T(I,U*s,Yt,s),A.localidade_nome!==null){if(Yt!==0||A.localidade_tipo==="M")throw Error(`Invalid subordinate locality name for CEP: ${A.cep}`);nn(D,U),T(H,jt*l.bairro.idWidth,se(l.bairro,A.localidade_nome,"localidade_nome"),l.bairro.idWidth),jt++}let Fn=m.get(A.municipio_cod_ibge);if(Fn===void 0)throw Error(`Missing municipality for IBGE code: ${A.municipio_cod_ibge}`);if(T(le,U*f,Fn,f),A.nome!==null)nn(Re,U),T(Cn,qt*l.nome.idWidth,se(l.nome,A.nome,"nome"),l.nome.idWidth),qt++;U++}if(U!==i)throw Error(`SQLite row count changed while exporting: expected ${i}, got ${U}`);if(Ht!==c.complementoCount||qt!==c.nomeCount||jt!==c.localidadeNomeCount)throw Error("SQLite nullable field counts changed while exporting");while(Te<ue)b[Te]=i,Te++;let Nn=B(i),Vt=tn(w,E,i),Gt=tn(Re,Cn,i),zt=tn(D,H,i),Un=Go(r,a),qi=rn.encode(JSON.stringify(Qo(r))),ji=jo(u,l),vn=zn(le,q,f),Vi={bairroDictionary:l.bairro.bytes,bairroAbreviadoDictionary:l.bairroAbreviado.bytes,bairroIds:Hn(I,i,s),bairros:Vo(o,l),bairroFaixaOffsets:Un.offsets,bairroFaixas:Un.ranges,cepPrefixOffsets:Ko(b,Nn),cepSuffixes:h,complementoBitmap:Vt.bitmap,complementoDictionary:l.complemento.bytes,complementoIds:Vt.ids,complementoRanks:Vt.ranks,localidadeFlags:vn.flags,localidadeNomeBitmap:zt.bitmap,localidadeNomeRanks:zt.ranks,localidadeNomeIds:zt.ids,logradouroDictionary:l.logradouro.bytes,logradouroIds:g,metadata:qi,municipalities:ji,municipalityIds:vn.ids,municipioDictionary:l.municipio.bytes,nomeBitmap:Gt.bitmap,nomeDictionary:l.nome.bytes,nomeIds:Gt.ids,nomeRanks:Gt.ranks,ufDictionary:l.uf.bytes};return await zo(t,i,d,f,Nn,Vi),r.run("COMMIT"),i}finally{r.close()}}function $o(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(!z(i.bairro_id)||!z(i.localidade_id)||!i.nome||!i.uf)throw Error(`Invalid neighborhood: ${i.bairro_id}`);r.strings.bairro.add(i.nome),nt(r.strings.bairroAbreviado,i.nome_abreviado),r.strings.uf.add(i.uf)}for(let i of _r(e,t)){if(nt(r.strings.logradouro,i.logradouro),nt(r.strings.complemento,i.complemento),nt(r.strings.bairro,i.localidade_nome),r.strings.municipio.add(i.municipio),r.strings.uf.add(i.uf),nt(r.strings.nome,i.nome),i.complemento!==null)r.complementoCount++;if(i.nome!==null)r.nomeCount++;if(i.localidade_nome!==null)r.localidadeNomeCount++;Xt(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 ko(e){return{bairro:ye(e.strings.bairro),bairroAbreviado:ye(e.strings.bairroAbreviado),complemento:ye(e.strings.complemento),logradouro:ye(e.strings.logradouro),municipio:ye(e.strings.municipio),nome:ye(e.strings.nome),uf:ye(e.strings.uf)}}function ye(e){let t=[...e].sort(),n=t.length,r=Math.ceil(n/M),i=new Uint32Array(r),o=new Uint8Array(n),a=new Uint8Array(n),s=new Map,c=new Uint8Array,l=0;for(let[g,w]of t.entries()){let E=rn.encode(w);if(E.byteLength>255)throw Error(`Binary string exceeds 255 UTF-8 bytes: ${w}`);let I=g%M===0?0:Xo(c,E);if(g%M===0)i[g>>>x]=l;o[g]=E.byteLength,a[g]=I,l+=E.byteLength-I,St(l,"dictionary suffix data length"),s.set(w,g+1),c=E}let u=Be,d=u+i.byteLength,f=d+o.byteLength,m=f+a.byteLength,b=new Uint8Array(m+l),h=new DataView(b.buffer);h.setUint32(0,n,!0),h.setUint32(4,r,!0),h.setUint32(8,u,!0),h.setUint32(12,d,!0),h.setUint32(16,f,!0),h.setUint32(20,m,!0),h.setUint32(24,l,!0),h.setUint8(28,B(n)),h.setUint8(29,x),b.set(Dt(i),u),b.set(o,d),b.set(a,f);let y=m;for(let[g,w]of t.entries()){let E=rn.encode(w),I=a[g]??0;b.set(E.subarray(I),y),y+=E.byteLength-I}return{bytes:b,count:n,ids:s,idWidth:B(n)}}function Po(e){let t=Wo(e);if(!t.count||t.suffixDataLength<=de)return e;let n=ar(t.source),r=Ho(e,t,n.compressedLengths,n.lengthWidth,n.symbols,n.payload);return r.byteLength<e.bytes.byteLength?{...e,bytes:r}:e}function Wo(e){let t=new DataView(e.bytes.buffer,e.bytes.byteOffset,e.bytes.byteLength),n=t.getUint32(0,!0),r=t.getUint32(4,!0),i=e.bytes.subarray(t.getUint32(8,!0),t.getUint32(12,!0)),o=new DataView(i.buffer,i.byteOffset,i.byteLength),a=e.bytes.subarray(t.getUint32(12,!0),t.getUint32(16,!0)),s=e.bytes.subarray(t.getUint32(16,!0),t.getUint32(20,!0)),c=t.getUint32(20,!0),l=t.getUint32(24,!0);return{blockCount:r,blockOffsets:i,count:n,lengths:a,prefixes:s,source:{count:n,totalBytes:l,get(d){let f=d>>>x,m=c+o.getUint32(f*4,!0),b=f*M;for(let y=b;y<d;y++)m+=(a[y]??0)-(s[y]??0);let h=(a[d]??0)-(s[d]??0);return e.bytes.subarray(m,m+h)}},suffixDataLength:l}}function Ho(e,t,n,r,i,o){let a=t.blockCount,s=new Uint32Array(a),c=0;for(let y=0;y<t.count;y++){if(y%M===0)s[y>>>x]=c;c+=qo(n,r,y),St(c,"FSST dictionary suffix data length")}if(c!==o.byteLength||i.byteLength!==de)throw Error("Invalid FSST encoder result");let l=Be,u=l+s.byteLength,d=u+n.byteLength,f=d+t.count,m=f+i.byteLength,b=new Uint8Array(m+o.byteLength),h=new DataView(b.buffer);return h.setUint32(0,t.count,!0),h.setUint32(4,a,!0),h.setUint32(8,l,!0),h.setUint32(12,u,!0),h.setUint32(16,d,!0),h.setUint32(20,m,!0),h.setUint32(24,o.byteLength,!0),h.setUint8(28,e.idWidth),h.setUint8(29,x),h.setUint8(30,re),h.setUint8(31,r),b.set(Dt(s),l),b.set(n,u),b.set(t.prefixes,d),b.set(i,f),b.set(o,m),b}function qo(e,t,n){if(t===1)return e[n]??0;let r=n*2;return(e[r]??0)|(e[r+1]??0)<<8}function jo(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;T(r,s,o,3),T(r,s+3,se(t.municipio,a.municipio,"municipio"),t.municipio.idWidth),T(r,s+3+t.municipio.idWidth,se(t.uf,a.uf,"uf"),t.uf.idWidth)}return r}function tn(e,t,n){let r=Math.ceil(n/W),i=new Uint32Array(r+1),o=0;for(let a=0;a<r;a++){i[a]=o;let s=a*(W>>>3),c=Math.min(s+(W>>>3),e.byteLength);for(let l=s;l<c;l++)o+=Fo[e[l]??0]??0}return i[r]=o,{bitmap:e,ids:t,ranks:Dt(i)}}function Vo(e,t){let n=B(e.at(-1)?.bairro_id??0),r=B(e.reduce((s,c)=>Math.max(s,c.localidade_id),0)),i=n+r+t.bairro.idWidth+t.bairroAbreviado.idWidth+t.uf.idWidth,o=new Uint8Array(G+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,c]of e.entries()){let l=G+s*i;T(o,l,c.bairro_id,n),l+=n,T(o,l,c.localidade_id,r),l+=r,T(o,l,se(t.bairro,c.nome,"bairro"),t.bairro.idWidth),l+=t.bairro.idWidth,T(o,l,Sr(t.bairroAbreviado,c.nome_abreviado),t.bairroAbreviado.idWidth),l+=t.bairroAbreviado.idWidth,T(o,l,se(t.uf,c.uf,"uf"),t.uf.idWidth)}return o}function Go(e,t){let n=e.query(`SELECT bairro_id, cep_inicial, cep_final FROM ${rt(Et)}
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[c,l]of n.entries()){let u=t.get(l.bairro_id);if(u===void 0)throw Error(`Unknown neighborhood in CEP range: ${l.bairro_id}`);let d=on(l.cep_inicial),f=on(l.cep_final);if(d>f)throw Error(`Reversed neighborhood CEP range: ${l.bairro_id}`);if(s?.bairro_id===l.bairro_id&&s.cep_inicial===l.cep_inicial&&s.cep_final===l.cep_final)throw Error(`Duplicate neighborhood CEP range: ${l.bairro_id}`);while(a<u)r[a++]=c;o.setUint32(c*8,d,!0),o.setUint32(c*8+4,f,!0),s=l}while(a<r.length)r[a++]=n.length;return{offsets:Dt(r),ranges:i}}async function zo(e,t,n,r,i,o){let a={},s=O;for(let d of F)s=Ze(s),a[d]={length:o[d].byteLength,offset:s},s+=o[d].byteLength;let c=Ze(s)+P;St(c,"file size");let l=Yo({cepPrefixOffsetWidth:i,fileSize:c,municipalityCount:n,municipalityIdWidth:r,rowCount:t,sections:a}),u=new Uint8Array(c);u.set(l);for(let d of F)u.set(o[d],a[d].offset);tr(u),await Bun.write(e,u)}function Yo(e){let t=new Uint8Array(O);t.set(k,0);let n=new DataView(t.buffer);n.setUint16(8,te,!0),n.setUint16(10,O,!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,fe),n.setUint8(23,x),n.setUint16(24,F.length,!0),n.setUint32(28,e.municipalityCount,!0);for(let[r,i]of F.entries()){let o=e.sections[i],a=xe+r*8;n.setUint32(a,o.offset,!0),n.setUint32(a+4,o.length,!0)}return t}function Zo(e,t){return e.query(`SELECT count(*) AS count FROM ${rt(t)}`).get().count}function*_r(e,t){let n=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 ${rt(t)}
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)} (
9
+ `);try{for(let r of n.iterate())yield r}finally{n.finalize()}}function Qo(e){if(!e.query("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?").get(C))return{};let n=e.query(`SELECT key, value FROM ${rt(C)}`).all();return Object.fromEntries(n.map((r)=>[r.key,r.value]))}function Sr(e,t){return t===null?0:se(e,t,"string")}function se(e,t,n){let r=e.ids.get(t);if(r===void 0)throw Error(`Missing binary ${n} dictionary value: ${t}`);return r}function nt(e,t){if(t!==null)e.add(t)}function Xo(e,t){let n=Math.min(e.byteLength,t.byteLength),r=0;while(r<n&&e[r]===t[r])r++;return r}function nn(e,t){let n=t>>>3;e[n]=(e[n]??0)|1<<(t&7)}function Ko(e,t){let n=new Uint8Array(e.length*t);for(let r=0;r<e.length;r++)T(n,r*t,e[r]??0,t);return n}function on(e){if(!/^\d{8}$/.test(e))throw Error(`Invalid CEP in SQLite database: ${e}`);return Number(e)}function Jo(){let e=new Uint16Array([1]);if(new Uint8Array(e.buffer)[0]!==1)throw Error("Binary database generation requires a little-endian platform")}function St(e,t){if(!Number.isSafeInteger(e)||e<0||e>$n)throw Error(`Binary ${t} exceeds the uint32 limit: ${e}`)}function Dt(e){return new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}function rt(e){return`"${e.replaceAll('"','""')}"`}class S 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 ea=/[\s,;]/;function qe(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,c=e.charCodeAt(t-2)-48,l=e.charCodeAt(t-1)-48;if((n|r|i|o|a|s|c|l|9-n|9-r|9-i|9-o|9-a|9-s|9-c|9-l)<0)return Number.NaN;return n*1e7+r*1e6+i*1e5+o*1e4+a*1000+s*100+c*10+l}function Ir(e){let t=e.trim(),n=qe(t);if(Number.isNaN(n))return;return String(n).padStart(8,"0")}async function*Ar(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 S("input-file-not-found",`Arquivo de entrada com CEPs n\xE3o encontrado: ${t}`);for(let i of e)yield i;if(r){yield*Dr(r.stream());return}if(!e.length&&!n)yield*Dr(Bun.stdin.stream())}async function*Dr(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(!ea.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 ba,readFileSync as $r,renameSync as ha,rmSync as Ct,statSync as ya,writeFileSync as ga}from"fs";import{homedir as vr}from"os";import{join as at,resolve as un}from"path";import{stat as fa}from"fs/promises";import{extname as ma,resolve as pa}from"path";import{fileURLToPath as ia}from"url";import{Buffer as ta}from"buffer";var Rr=new WeakMap,na=new TextDecoder;function ra(e,t){let n=new Uint8Array(ie),r=new Uint32Array(ie*2);for(let a=0;a<n.length;a++)n[a]=e.getUint8(t.symbolsOffset+a);for(let a=0;a<r.length;a++)r[a]=e.getUint32(t.symbolsOffset+ie+a*4,!0);let i=ta.alloc(272),o={lengths:n,words:r,output:i,view:new DataView(i.buffer,i.byteOffset,i.byteLength)};return Rr.set(t,o),o}function Tr(e,t,n,r){let{lengths:i,words:o,output:a,view:s}=Rr.get(n)??ra(t,n),c=r-1,l=c>>>x,u=n.suffixDataOffset+t.getUint32(n.blockOffsetsOffset+l*4,!0),d=0;for(let f=l*M;f<=c;f++){let m=n.lengthWidth===1?e[n.lengthsOffset+f]:t.getUint16(n.lengthsOffset+f*2,!0),b=u+m,h=e[n.prefixesOffset+f];while(u<b){let y=e[u++];if(y===255)a[h++]=e[u++];else s.setUint32(h,o[y*2],!0),s.setUint32(h+4,o[y*2+1],!0),h+=i[y]}d=h}return na.decode(a.subarray(0,d))}var xr=new TextDecoder,Br=Le();async function an(e){try{if(!await Bun.file(e).exists())return!1;let t=new Uint8Array(await Bun.file(e).slice(0,k.length).arrayBuffer());return kn(t)}catch(t){throw new Ye(e,{cause:t})}}class je{bairroCache;data;decodeScratch=new Uint8Array(255);dictionaries;bairros;bairroRuns;localityRuns;logradouroIdBits;header;mapped;metadataValue;municipalityCache;constructor(e=ia(new URL("../data/dne.bin",import.meta.url))){let t;try{t=Bun.mmap(e,{shared:!1})}catch(n){throw new Ye(e,{cause:n})}try{let n=new DataView(t.buffer,t.byteOffset,t.byteLength);oa(n),nr(t);let r=aa(n),i=sa(n,r),o=ca(n,r,i),a=qn(n,r.sections.bairroIds,r.rowCount,o.idWidth),s=Yn(n,r.sections.municipalityIds,r.rowCount),c=la(t,r.sections.metadata);this.mapped=t,this.data=n,this.header=r,this.dictionaries=i,this.bairros=o,this.bairroRuns=a,this.localityRuns=s,this.logradouroIdBits=$e(i.logradouro.count),this.metadataValue=Object.freeze(c),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 ee)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){this.assertOpen();let t=this.findCepIndex(e);return t===-1?void 0:this.readRow(t,e.replace("-",""))}queryMunicipality(e){if(this.assertOpen(),!Number.isInteger(e)||e<1e6||e>9999999)return;let t=3+this.dictionaries.municipio.idWidth+this.dictionaries.uf.idWidth,n=this.header.sections.municipalities.offset,r=0,i=this.header.municipalityCount-1;while(r<=i){let o=r+(i-r>>>1),a=this.readPackedInteger(n+o*t,3);if(a<e)r=o+1;else if(a>e)i=o-1;else{let{municipio:s,uf:c}=this.readMunicipality(o+1);return{municipio:s,uf:c}}}return}queryMunicipalityCodesByUf(e){if(this.assertOpen(),!Object.hasOwn(oe,e))return[];let t=oe[e]*1e5,n=t+1e5,r=3+this.dictionaries.municipio.idWidth+this.dictionaries.uf.idWidth,i=this.header.sections.municipalities.offset,o=0,a=this.header.municipalityCount;while(o<a){let c=o+(a-o>>>1);if(this.readPackedInteger(i+c*r,3)<t)o=c+1;else a=c}let s=[];for(let c=o;c<this.header.municipalityCount;c++){let l=this.readPackedInteger(i+c*r,3);if(l>=n)break;s.push(l)}return s}queryNeighborhood(e){this.assertOpen();let t=this.findNeighborhoodIndex(e);return t===0?void 0:this.readNeighborhood(t)}queryNeighborhoodByCep(e){this.assertOpen();let t=this.findCepIndex(e);if(t===-1)return;let n=this.readNeighborhoodIndex(t);return n===0?void 0:this.readNeighborhood(n)}queryNeighborhoodCepRanges(e){this.assertOpen();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),a=[];for(let s=i;s<o;s++){let c=this.readUint32(r.offset+s*8),l=this.readUint32(r.offset+s*8+4);a.push({cep_inicial:String(c).padStart(8,"0"),cep_final:String(l).padStart(8,"0")})}return a}rowCount(){return this.header.rowCount}assertOpen(){if(this.data===null)throw new bt}findCepIndex(e){let t=qe(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),c=s;while(a<c){let l=a+(c-a>>>1);if(this.readPacked10(l)<r)a=l+1;else c=l}if(a>=s||this.readPacked10(a)!==r)return-1;return a}findNeighborhoodIndex(e){if(!z(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){return Vn(this.data,this.bairroRuns,e)}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 c=this.readRequiredDictionaryString(this.dictionaries.bairro,this.readPackedInteger(o,this.dictionaries.bairro.idWidth));o+=this.dictionaries.bairro.idWidth;let l=this.readDictionaryString(this.dictionaries.bairroAbreviado,this.readPackedInteger(o,this.dictionaries.bairroAbreviado.idWidth));o+=this.dictionaries.bairroAbreviado.idWidth;let u=this.readRequiredDictionaryString(this.dictionaries.uf,this.readPackedInteger(o,this.dictionaries.uf.idWidth));return{bairro_id:a,localidade_id:s,nome:c,nome_abreviado:l,uf:u}}readRow(e,t){let n=this.header.sections,r=Qn(this.data,this.localityRuns,e),i=this.readPackedInteger(this.localityRuns.idsOffset+r*this.header.municipalityIdWidth,this.header.municipalityIdWidth),o=this.readMunicipality(i),a=this.data.getUint8(n.localidadeFlags.offset+r),s=We[a&3],c=Pe[a>>>2],l=this.readNeighborhoodIndex(e),u=this.readSparseId(n.localidadeNomeBitmap,n.localidadeNomeRanks,n.localidadeNomeIds,e,this.dictionaries.bairro.idWidth),d=l===0?u:this.readPackedInteger(this.bairros.recordsOffset+(l-1)*this.bairros.recordWidth+this.bairros.originalIdWidth+this.bairros.localidadeIdWidth,this.dictionaries.bairro.idWidth);return{bairro:this.readCachedDictionaryString(this.dictionaries.bairro,d,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:s,localidade_tipo:c,logradouro:this.readDictionaryString(this.dictionaries.logradouro,yt(this.data,n.logradouroIds.offset,e,this.logradouroIdBits)),municipio:o.municipio,municipio_cod_ibge:o.codigoIbge,nome:this.readDictionaryString(this.dictionaries.nome,this.readSparseId(n.nomeBitmap,n.nomeRanks,n.nomeIds,e,this.dictionaries.nome.idWidth)),uf:o.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),uf:this.readRequiredDictionaryString(this.dictionaries.uf,o)};return this.municipalityCache[e]=a,a}readSparseId(e,t,n,r,i){let o=this.mapped,a=r>>>3,s=o[e.offset+a],c=r&7;if((s&1<<c)===0)return 0;let l=r>>>fe,u=this.readUint32(t.offset+l*4),d=l*(W>>>3);for(let f=d;f<a;f++)u+=Br[o[e.offset+f]];return u+=Br[s&(1<<c)-1],this.readPackedInteger(n.offset+u*i,i)}readDictionaryString(e,t){if(t===0)return null;let n=this.mapped;if(e.codec===re)return Tr(n,this.data,e,t);let r=t-1,i=r>>>x,o=i<<x,a=this.readUint32(e.blockOffsetsOffset+i*4),s=e.suffixDataOffset+a,c=this.decodeScratch,l=0;for(let u=o;u<=r;u++){let d=n[e.lengthsOffset+u],f=n[e.prefixesOffset+u],m=d-f;c.set(n.subarray(s,s+m),f),s+=m,l=d}return xr.decode(c.subarray(0,l))}readCachedDictionaryString(e,t,n){if(t===0)return null;let r=n[t];if(r!==void 0)return r;let i=this.readRequiredDictionaryString(e,t);return n[t]=i,i}readRequiredDictionaryString(e,t){return this.readDictionaryString(e,t)}readPacked10(e){let t=this.mapped,n=this.header.sections.cepSuffixes,r=e*ne,i=r>>>3,o=r&7,a=n.offset+i;return(t[a]|t[a+1]<<8|t[a+2]<<16)>>>o&1023}readPackedInteger(e,t){return R(this.data,e,t)}readUint32(e){return this.data.getUint32(e,!0)}}function oa(e){if(e.byteLength<O+P)throw new p("Binary database header is truncated");for(let n=0;n<k.length;n++)if(e.getUint8(n)!==k[n])throw new p("Invalid binary database magic");let t=e.getUint16(8,!0);if(t!==te)throw new pt(t,te);if(e.getUint16(10,!0)!==O)throw new p("Unsupported binary database header size");if(e.getUint8(22)!==fe||e.getUint8(23)!==x)throw new p("Unsupported binary database block layout");if(e.getUint16(24,!0)!==F.length)throw new p("Unsupported binary database section table");if(e.getUint32(16,!0)!==e.byteLength)throw new p(`Binary database size mismatch: header=${e.getUint32(16,!0)}, actual=${e.byteLength}`)}function aa(e){let t={};for(let[n,r]of F.entries()){let i=xe+n*8;t[r]={length:e.getUint32(i+4,!0),offset:e.getUint32(i,!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:t}}function sa(e,t){return{bairro:ge(e,t.sections.bairroDictionary),bairroAbreviado:ge(e,t.sections.bairroAbreviadoDictionary),complemento:ge(e,t.sections.complementoDictionary),logradouro:ge(e,t.sections.logradouroDictionary),municipio:ge(e,t.sections.municipioDictionary),nome:ge(e,t.sections.nomeDictionary),uf:ge(e,t.sections.ufDictionary)}}function ge(e,t){let n=e.getUint32(t.offset,!0),r=t.offset+e.getUint32(t.offset+16,!0);return{blockCount:e.getUint32(t.offset+4,!0),blockOffsetsOffset:t.offset+e.getUint32(t.offset+8,!0),count:n,codec:e.getUint8(t.offset+30),idWidth:e.getUint8(t.offset+28),lengthsOffset:t.offset+e.getUint32(t.offset+12,!0),lengthWidth:e.getUint8(t.offset+31)===2?2:1,prefixesOffset:r,region:t,suffixDataLength:e.getUint32(t.offset+24,!0),suffixDataOffset:t.offset+e.getUint32(t.offset+20,!0),symbolsOffset:r+n}}function ca(e,t,n){let r=t.sections.bairros,i=e.getUint32(r.offset,!0),o=e.getUint8(r.offset+4),a=e.getUint8(r.offset+5),s=o+a+n.bairro.idWidth+n.bairroAbreviado.idWidth+n.uf.idWidth;return{count:i,idWidth:B(i),originalIdWidth:o,localidadeIdWidth:a,recordsOffset:r.offset+G,recordWidth:s}}function la(e,t){return JSON.parse(xr.decode(e.subarray(t.offset,t.offset+t.length)))}import{Database as da}from"bun:sqlite";class X extends Error{constructor(e,t){super(e,t);this.name=new.target.name}}class it extends X{path;code="IO_ERROR";constructor(e,t){super(`Unable to access SQLite database: ${e}`,t);this.path=e}}class ot extends X{code="INVALID_SCHEMA";constructor(e,t){super(e,t)}}class It extends X{code="INVALID_DATA";constructor(e,t){super(e,t)}}class At extends X{code="QUERY_ERROR";constructor(e,t){super(e,t)}}class Rt extends X{code="READER_CLOSED";constructor(){super("SQLite database is closed")}}function ua(e){return Cr(e,", ")}function Or(e){return Cr(e,`,
10
+ `)}function Cr(e,t){let n=e.columns.filter((o)=>o.primaryKey).map((o)=>_(o.name)),r=e.columns.map((o)=>{let a=[_(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 ${_(o.references.table)} (${_(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 ${_(e.name)} (
12
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
13
+ )${i}`;return`CREATE TABLE IF NOT EXISTS ${_(e.name)} (${r.join(t)})${i}`}function we(e){return`${e}_consulta`}function sn(e,t=he){return`CREATE VIEW ${_(we(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 ${_(e)} d
17
+ LEFT JOIN ${_(t)} b ON b.bairro_id = d.bairro_id`}function Tt(e,t){let n=me(t),r=t.find((o)=>o.originalName==="bairros");if(!r)throw Error("Neighborhood table definition is missing");let i=Je(t);e.run(`DROP VIEW IF EXISTS main.${_(we(n.name))}`);for(let o of[...i].reverse())e.run(`DROP TABLE IF EXISTS main.${_(o.name)}`);for(let o of i)e.run(ua(o));e.run(sn(n.name,r.name))}function _(e){return`"${e.replaceAll('"','""')}"`}class Bt{databasePath;db;closed=!1;normalizedSchemaReady=!1;constructor(e){this.databasePath=e;let t;try{t=new da(e,{readonly:!0}),t.run("PRAGMA busy_timeout = 30000"),this.db=t}catch(n){try{t?.close()}catch{}throw new it(e,{cause:n})}}close(){if(this.closed)return;try{this.db.close(),this.closed=!0}catch(e){throw new it(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(C))return;let e=this.db.query(`SELECT key, value FROM ${_(C)}`).all();return Object.fromEntries(e.map((t)=>[t.key,t.value]))})}queryCep(e){return this.readSafely(()=>{let t=qe(e);if(Number.isNaN(t))return;this.requireCurrentSchema();let n=this.db.query(`SELECT * FROM ${_(we(L))} 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 ot("Database schema lacks locality indicators. Rebuild the database with build --force.");let r=We[n.localidade_situacao],i=Pe[ke.indexOf(n.localidade_tipo)];if(r===void 0||i===void 0)throw new It("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(!z(e))return;return this.requireCurrentSchema(),this.db.query(`SELECT * FROM ${_(he)} WHERE bairro_id = ?`).get(e)??void 0})}queryNeighborhoodByCep(e){return this.readSafely(()=>{if(Number.isNaN(qe(e)))return;return this.requireCurrentSchema(),this.db.query(`
18
+ SELECT b.* FROM ${_(L)} d
19
+ JOIN ${_(he)} 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
+ `).get(e.replace("-",""))??void 0})}queryNeighborhoodCepRanges(e){return this.readSafely(()=>{if(!z(e))return[];return this.requireCurrentSchema(),this.db.query(`
22
+ SELECT cep_inicial, cep_final FROM ${_(Et)}
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(`
24
+ `).all(e)})}requireCurrentSchema(){if(!this.normalizedSchemaReady)this.normalizedSchemaReady=Boolean(this.db.query("SELECT 1 FROM sqlite_master WHERE type = 'view' AND name = ?").get(we(L)));if(!this.normalizedSchemaReady)throw new ot("Database schema lacks normalized neighborhoods. Rebuild the database with build --force.")}rowCount(e){return this.readSafely(()=>this.db.query(`SELECT count(*) AS count FROM ${_(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 Rt;try{return e()}catch(t){if(t instanceof X)throw t;throw new At(t instanceof Error?t.message:String(t),{cause:t})}}}function Lr(e){if(!e.startsWith("sqlite:///")){if(e.includes("://"))throw Error("Only sqlite:/// database URLs are supported");return e}return e.slice(10)}function K(e,t){let n=Lr(e);if(n===":memory:")return n;return pa(t==="binary"?`${n.slice(0,n.length-ma(n).length)}.bin`:n)}async function xt(e,t=L){if(e===":memory:"||!await Bun.file(e).exists())throw new S("database-not-found",`Base n\xE3o encontrada: ${e}`);let n;try{n=await an(e)?new je(e):new Bt(e)}catch(i){throw new S("database-invalid",`N\xE3o foi poss\xEDvel abrir a base '${e}': ${Ur(i)}`)}if(!(n instanceof je?t===L:n.hasTable(t)))throw n.close(),new S("database-not-ready",`A base '${e}' n\xE3o cont\xE9m a tabela '${t}'. Execute bunx @konstit/dne build primeiro.`);return n}async function Ee(e,t=L){if(e===":memory:"||!await Bun.file(e).exists())return cn(e);let n=null;try{n=(await fa(e)).size}catch{}try{let r=await an(e),i=r?new je(e):new Bt(e);try{let o=i instanceof je,a=o?t===L: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{...cn(e),error:Ur(r),exists:!0,size_bytes:n}}}function Nr(e){return{...cn(":memory:"),row_count:e}}function cn(e){return{exists:!1,format:null,metadata:null,path:e,ready:!1,row_count:null,schema:null,size_bytes:null}}function Ur(e){return e instanceof Error?e.message:String(e)}async function kr(e){let t=dn(e.database),n=qr(t),r=Sa(e.source??n?.source??ae),i=wa(e.expression,t,r,e.packageVersion),o=e.dryRun?"preview":n?"updated":"installed";if(!e.dryRun)await Ea(i,n);return{...i,next_run:jr(i.expression),status:o}}function Pr(e){let t=dn(e),n=Hr(t),r=qr(t);return{command:r?.command??null,database:t,expression:r?.expression??null,id:n,installed:r!==null,next_run:r?jr(r.expression):null,package_version:r?.package_version??null,runner:r?.runner??null,source:r?.source??null,title:n}}async function Wr(e){let t=dn(e),n=Lt(t),r=_e(n.metadata)||_e(n.runner);try{await Bun.cron.remove(n.title)}catch(i){throw new S("cron-remove-failed",`N\xE3o foi poss\xEDvel remover o agendamento: ${Vr(i)}`)}return Ct(n.metadata,{force:!0}),Ct(n.runner,{force:!0}),{database:t,id:n.title,removed:r,title:n.title}}function wa(e,t,n,r){let i=Bun.which("bunx");if(!i)throw new S("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 S("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=Lt(t),a=un(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 Ea(e,t){let n=Lt(e.database);ba(n.directory,{mode:448,recursive:!0});let r=Mr(n.runner),i=Mr(n.metadata);try{ln(n.runner,_a(e)),await Bun.cron(n.runner,e.expression,e.title),ln(n.metadata,`${JSON.stringify(e,null,2)}
25
+ `)}catch(o){Fr(n.runner,r),Fr(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 S("cron-install-failed",`N\xE3o foi poss\xEDvel instalar o agendamento: ${Vr(o)}`)}}function _a(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 S("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 dn(e){let t=K(e);if(t===":memory:")throw new S("invalid-cron-database","O agendamento exige um caminho persistente para a base.",2);if(/[\r\n\0]/.test(t))throw new S("invalid-cron-database","O caminho da base n\xE3o pode conter quebras de linha ou bytes nulos.",2);return t}function Sa(e){if(/[\r\n\0]/.test(e))throw new S("invalid-cron-source","A fonte n\xE3o pode conter quebras de linha ou bytes nulos.",2);return Da(e)?e:un(e)}function Hr(e){return`konstit-dne-${new Bun.CryptoHasher("sha256").update(e).digest("hex").slice(0,32)}`}function Lt(e){let t=Hr(e),n=Bun.env.XDG_STATE_HOME?un(Bun.env.XDG_STATE_HOME):process.platform==="darwin"?at(vr(),"Library","Application Support"):at(vr(),".local","state"),r=at(n,"konstit-dne","cron");return{directory:r,metadata:at(r,`${t}.json`),runner:at(r,`${t}.mjs`),title:t}}function qr(e){let t=Lt(e);if(!_e(t.metadata)&&!_e(t.runner))return null;if(!_e(t.metadata)||!_e(t.runner))throw new S("cron-config-invalid",`A configura\xE7\xE3o do agendamento '${t.title}' est\xE1 incompleta.`);try{let n=JSON.parse($r(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:ae}}catch{throw new S("cron-config-invalid",`A configura\xE7\xE3o do agendamento '${t.title}' \xE9 inv\xE1lida.`)}}function jr(e){return Bun.cron.parse(e)?.toISOString()??null}function ln(e,t){let n=`${e}.${process.pid}.${crypto.randomUUID()}.tmp`;try{ga(n,t,{mode:384}),ha(n,e)}finally{Ct(n,{force:!0})}}function Mr(e){return _e(e)?$r(e,"utf8"):null}function Fr(e,t){if(t===null)Ct(e,{force:!0});else ln(e,t)}function _e(e){try{return ya(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 Da(e){try{let t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"}catch{return!1}}function Vr(e){return e instanceof Error?e.message:String(e)}class Se extends Error{constructor(e){super(e);this.name="DneSourceQualityError"}}class fn{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++,zr(n.rejectionReasons,i),zr(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 Se(`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]=Yr(s);n[r]={...Yr(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={...Gr(),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=Gr(),n.files.set(t,r);return r}}function Gr(){return{read:0,accepted:0,rejected:0,rejectionReasons:new Map}}function zr(e,t){e.set(t,(e.get(t)??0)+1)}function Yr(e){return{read:e.read,accepted:e.accepted,rejected:e.rejected,rejection_reasons:Object.fromEntries(e.rejectionReasons)}}import{Database as Ia}from"bun:sqlite";import{mkdirSync as pn,readFileSync as Aa,renameSync as Ra,rmSync as Nt,statSync as bn,writeFileSync as Qr}from"fs";import{tmpdir as Ta}from"os";import{basename as Ba,dirname as mn,join as ct}from"path";var xa=30000,Oa=50,Ca=["SIGHUP","SIGINT","SIGTERM"];async function Xr(e,t){let n=La(e),r=ct(mn(e),`.${Ba(e)}.fetch.lock`),i={pid:process.pid,token:crypto.randomUUID()},o=performance.now()+xa,a=!1;pn(mn(e),{recursive:!0}),pn(mn(n),{mode:448,recursive:!0});while(Na(r)){if(Zr(r))continue;await u()}while(!Ua(n,i)){if(Zr(n))continue;await u()}if(a)t.finish();let s=!1,c=()=>{if(s)return;s=!0,l(),Fa(n,i.token)},l=$a(c);return{release:c};async function u(){if(!a)t("Aguardando outra atualiza\xE7\xE3o da base"),a=!0;if(performance.now()>=o)throw new S("update-in-progress",`Outra execu\xE7\xE3o de build j\xE1 est\xE1 atualizando a base '${e}'.`);await Bun.sleep(Oa)}}function La(e){let t=new Bun.CryptoHasher("sha256").update(e).digest("hex");return ct(Ta(),`konstit-dne-${process.getuid?.()??"unknown"}`,`fetch-${t}.lock`)}function Na(e){try{return bn(e),!0}catch(t){if(st(t))return!1;throw t}}function Ua(e,t){let n=`${e}.${t.pid}.${t.token}.tmp`;pn(n);try{return Qr(ct(n,"owner.json"),JSON.stringify(t),{flag:"wx"}),Ra(n,e),!0}catch(r){if(hn(r))return!1;throw r}finally{Nt(n,{force:!0,recursive:!0})}}function Zr(e){let t;try{t=bn(e)}catch(r){if(st(r))return!0;throw r}if(!t.isDirectory())return va(e);let n=Kr(e);if(n&&Ma(n.pid))return!1;try{Qr(ct(e,"reaper.json"),JSON.stringify({pid:process.pid,token:crypto.randomUUID()}),{flag:"wx"})}catch(r){if(hn(r))return!1;if(st(r))return!0;throw r}return Nt(e,{force:!0,recursive:!0}),!0}function va(e){let t=new Ia(e);try{t.run("PRAGMA busy_timeout = 0"),t.run("BEGIN IMMEDIATE"),t.run("ROLLBACK")}catch(n){if(ka(n))return!1;throw n}finally{t.close()}try{return Nt(e,{force:!0}),!0}catch(n){if(st(n))return!0;if(hn(n))return!1;try{if(bn(e).isDirectory())return!1}catch(r){if(st(r))return!0;throw r}throw n}}function Kr(e){try{let t=JSON.parse(Aa(ct(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 Ma(e){try{return process.kill(e,0),!0}catch(t){return!(t&&typeof t==="object"&&("code"in t)&&t.code==="ESRCH")}}function Fa(e,t){if(Kr(e)?.token===t)Nt(e,{force:!0,recursive:!0})}function $a(e){let t=()=>e(),n=Ca.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 hn(e){return yn(e,"EACCES","EEXIST","ENOTEMPTY","EPERM")}function st(e){return yn(e,"ENOENT")}function yn(e,...t){return Boolean(e&&typeof e==="object"&&"code"in e&&typeof e.code==="string"&&t.includes(e.code))}function ka(e){if(yn(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 Jr(){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 As,rm as Rs}from"fs/promises";import{tmpdir as Ts}from"os";import{join as _n}from"path";import{mkdir as Pa,rename as Wa,rm as Ha}from"fs/promises";import{basename as vt,dirname as qa,join as ii}from"path";var oi="Delimitado",ai="latin1",Lu=new TextDecoder(ai),ja=32,Va=20,Ga=10,za=16,Ya=30,Za=28,Ut=46,Qa=33639248,Xa=42,Ka=24,Ja=0,es=8,En=22,ts=101010256,ns=65535,si=En+ns,rs=16,is=12,os=28,as=26,ei=30,ss=67324752;class gn{path;files;constructor(e){this.path=e;this.files=Array.from(new Bun.Glob("*").scanSync({cwd:e,onlyFiles:!0})).sort()}matchingFiles(e){return di(this.files,e)}async*readLines(e){yield*mi(Bun.file(ii(this.path,e)).stream())}}class ci{path;files;entriesByFile;constructor(e,t){this.path=e;this.files=t.map((n)=>vt(n.name)).sort(),this.entriesByFile=new Map(t.map((n)=>[vt(n.name),n]))}matchingFiles(e){return di(this.files,e)}async*readLines(e){let t=this.entriesByFile.get(e);if(!t)throw Error(`DNE data file not found: ${e}`);yield*mi(fi(this.path,t))}}function li(e,t){if(!ni(e))return null;let n=new gn(e);if(!wn(n,t))return n;let r=ii(e,oi);if(!ni(r))return null;let i=new gn(r);return wn(i,t)?null:i}async function ui(e,t,n){let r=await ri(e),i=us(r);if(i)return await ps(e,i,n),ti(n,await ri(n),t);return ti(e,r,t)}function ti(e,t,n){let r=cs(t,n),i=new ci(e,r);return ls(i,r,n),i}function cs(e,t){return e.filter((n)=>ds(n.name,t))}function ls(e,t,n){if(!t.length)throw Error("ZIP file does not contain DNE Basico files");let r=wn(e,n);if(r)throw Error(`DNE data file not found: ${r}`)}function us(e){return e.find((t)=>{let n=vt(t.name).toLowerCase();return n.startsWith("edne_basico_")&&n.endsWith(".zip")})}function ni(e){try{return new Bun.Glob("*").scanSync({cwd:e,onlyFiles:!0}).next(),!0}catch{return!1}}function wn(e,t){for(let n of t){let r=et(n);if(r&&e.matchingFiles(r).length===0)return r}return null}function di(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 ds(e,t){let n=e.toLowerCase();if(!n.startsWith(`${oi.toLowerCase()}/`))return!1;let r=vt(n);return t.some((i)=>{let o=et(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 ri(e){let t=Bun.file(e),n=t.size;if(n<En)throw Error("Source is not a valid ZIP file");let r=Math.max(0,n-si),i=Buffer.from(await t.slice(r,n).arrayBuffer()),o=ms(i),a=i.readUInt32LE(o+is),s=i.readUInt32LE(o+rs),c=s+a;if(c>n)throw Error("Invalid ZIP central directory range");let l=Buffer.from(await t.slice(s,c).arrayBuffer());return fs(l)}function fs(e){let t=[],n=0;while(n<e.length){if(n+Ut>e.length||e.readUInt32LE(n)!==Qa)throw Error("Invalid ZIP central directory entry");let r=e.readUInt16LE(n+Ga),i=e.readUInt32LE(n+za),o=e.readUInt32LE(n+Va),a=e.readUInt32LE(n+Ka),s=e.readUInt16LE(n+Za),c=e.readUInt16LE(n+Ya),l=e.readUInt16LE(n+ja),u=e.readUInt32LE(n+Xa),d=Ut+s+c+l;if(n+d>e.length)throw Error("Invalid ZIP central directory entry size");let f=e.subarray(n+Ut,n+Ut+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 ms(e){for(let t=e.length-En;t>=Math.max(0,e.length-si);t--)if(e.readUInt32LE(t)===ts)return t;throw Error("Source is not a valid ZIP file")}async function*fi(e,t){let n=Bun.file(e),r=t.localHeaderOffset+ei,i=Buffer.from(await n.slice(t.localHeaderOffset,r).arrayBuffer());if(i.length!==ei||i.readUInt32LE(0)!==ss)throw Error(`Invalid ZIP local header for ${t.name}`);let o=i.readUInt16LE(as),a=i.readUInt16LE(os),s=r+o+a,c=s+t.compressedSize;if(c>n.size)throw Error(`Invalid ZIP data range for ${t.name}`);let l=n.slice(s,c).stream(),u;if(t.compression===Ja)u=l;else if(t.compression===es)u=l.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}`);bs(t,f)}async function ps(e,t,n){if(await Bun.file(n).exists())return;await Pa(qa(n),{recursive:!0});let r=`${n}.${process.pid}.${crypto.randomUUID()}.tmp`,i=Bun.file(r).writer(),o=!1;try{for await(let a of fi(e,t))await i.write(a);await i.end(),o=!0;try{await Wa(r,n)}catch(a){if(!await Bun.file(n).exists())throw a}}finally{if(!o)await Promise.resolve(i.end()).catch(()=>{});await Ha(r,{force:!0})}}async function*mi(e){let t=new TextDecoder(ai),n="";for await(let r of e){let i=n+t.decode(r,{stream:!0}),o=0,a=i.indexOf(`
27
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)}
28
+ `,o)}n=i.slice(o)}if(n+=t.decode(),n.endsWith("\r"))n=n.slice(0,-1);if(n)yield n}function bs(e,t){if(t!==e.crc32)throw Error(`CRC32 mismatch for ${e.name}`)}import{open as hi}from"fs/promises";class lt extends Error{constructor(e){super(e)}}async function yi(e,t,n,r={}){let i=ws(n.contentLength);if(!gs(n.acceptRanges)||i===null){await pi(e,t,r);return}try{await hs(e,t,i,r)}catch(o){if(!(o instanceof lt))throw o;await pi(e,t,r)}}async function hs(e,t,n,r){let i=Math.ceil(n/_t),o=await hi(t,"w"),a=new AbortController,s=wi(r.signal,a.signal);try{await o.truncate(n);let c=0,l=Array.from({length:Math.min(i,pr)},async()=>{while(!0){let u=c++;if(u>=i)return;let d=u*_t,f=Math.min(d+_t,n)-1;await ys(e,o,{start:d,end:f},n,{...r,signal:s})}});try{await Promise.all(l)}catch(u){throw a.abort(),await Promise.allSettled(l),u}}finally{await o.close()}}async function ys(e,t,n,r,i){await ut(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 lt(`Server ignored byte range ${n.start}-${n.end}`);throw Error(`Failed to download ${e}: ${o.status}`)}let a=Es(o.headers.get("content-range"));if(!a||a.start!==n.start||a.end!==n.end||a.length!==r)throw await o.body?.cancel(),new lt(`Server returned an invalid Content-Range for ${n.start}-${n.end}`);let s=new Uint8Array(await o.arrayBuffer()),c=n.end-n.start+1;if(s.byteLength!==c)throw new lt(`Server returned ${s.byteLength} bytes for range ${n.start}-${n.end}; expected ${c}`);await gi(t,s,n.start)},i)}async function pi(e,t,n){let r=await hi(t,"w");try{await ut(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 gi(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 ut(e,t,n,r={}){let i=r.timeoutMs??br,o=r.maxRetries??hr,a=r.retryBaseDelayMs??yr,s=r.retryMaxDelayMs??gr,c=r.retryAfterMaxMs??wr,l;for(let u=0;;u++){Ei(r.signal);let d=AbortSignal.timeout(i),f=wi(r.signal,d);try{let m=await fetch(e,{...t,signal:f,verbose:!1});if(_s(m.status)&&u<o){let b=Ds(m.headers.get("retry-after"),u,a,s,c);await m.body?.cancel(),await bi(b,r.signal);continue}l=await n(m);break}catch(m){if(r.signal?.aborted)throw r.signal.reason??m;if(u>=o||!Ss(m))throw m;let b=Math.min(a*2**u,s);await bi(b,r.signal)}}return l}async function gi(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 gs(e){return e?.split(",").some((t)=>t.trim().toLowerCase()==="bytes")??!1}function ws(e){if(e===null||!/^\d+$/.test(e))return null;let t=Number(e);return Number.isSafeInteger(t)?t:null}function Es(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 _s(e){return e===408||e===425||e===429||e>=500&&e<=599}function Ss(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 Ds(e,t,n,r,i){let o=Is(e);if(o!==null)return Math.min(o,i);return Math.min(n*2**t,r)}function Is(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 wi(e,t){return e?AbortSignal.any([e,t]):t}function Ei(e){if(e?.aborted)throw e.reason??new DOMException("The operation was aborted","AbortError")}async function bi(e,t){if(e<=0){Ei(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 Mt{source;options;tempDir;constructor(e,t={}){this.source=e;this.options=t}async resolve(e){try{return await this.resolveSource(this.source??ae,e)}catch(t){throw await this.cleanup(),t}}async cleanup(){if(this.tempDir)await Rs(this.tempDir,{recursive:!0,force:!0}),this.tempDir=void 0}async getTempDir(){return this.tempDir??=await As(_n(Ts(),"edne")),this.tempDir}async resolveSource(e,t){let n=e;if(xs(e))n=await this.download(e);if(await Bun.file(n).exists()){this.progress("Preparando a fonte ZIP");let i=_n(await this.getTempDir(),"edne-inner.zip"),o=await ui(n,t,i);return this.progress("Fonte ZIP pronta"),o}this.progress("Lendo a fonte do diret\xF3rio");let r=li(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=_n(n,"edne-download.zip");return this.progress("Baixando o arquivo DNE"),await yi(e,r,t),r}progress(e){this.options.onProgress?.(e)}}async function Ft(e,t={}){try{return await ut(e,{method:"HEAD"},async(n)=>{if(!n.ok)throw Error(`Failed to inspect DNE from ${e}: ${n.status}`);return _i(e,n.headers)},t)}catch{return await ut(e,{headers:{"accept-encoding":"identity",range:"bytes=0-0"}},async(n)=>{let r=Bs(e,n);if(await n.body?.cancel(),!n.ok)throw Error(`Failed to inspect DNE from ${e}: ${n.status}`);return r},t)}}function _i(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 Bs(e,t){let n=_i(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 xs(e){try{let t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"}catch{return!1}}import{Database as Ns}from"bun:sqlite";async function De(e,t,n,r,i){let o=et(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 c=r.counter(e.originalName,s);if(t.readText){let l=await t.readText(s);Cs(l,(u,d)=>{c.read(),i(Di(l,u,d,n),s,c)});continue}for await(let l of t.readLines(s))c.read(),i(Os(l,n),s,c)}}function Os(e,t){return Di(e,0,e.length,t)}function Di(e,t,n,r){let i=Array.from({length:r.length},()=>null),o=0,a=0,s=t;for(let c=t;c<=n;c++){if(c!==n&&e.charCodeAt(c)!==64)continue;if(a===r[o]){if(i[o]=Ls(e,s,c),o++,o===r.length)break}a++,s=c+1}return i}function Cs(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 Ls(e,t,n){if(t===n)return null;let r=e.charCodeAt(t),i=e.charCodeAt(n-1),o=Si(r)||Si(i)?e.slice(t,n).trim():e.slice(t,n);return o===""?null:o}function Si(e){return e<=32||e===160}class Sn{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 ${_(this.tableName)}
30
30
  (cep, logradouro, complemento, bairro_id, localidade_nome, municipio, municipio_cod_ibge, uf, nome, localidade_situacao, localidade_tipo)
31
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)} (
32
+ `),this.statements.set(e,t),t}}class In{schema;db;tableByOriginalName;unifiedTable;constructor(e,t){this.schema=t;this.db=new Ns(e),this.tableByOriginalName=new Map(t.map((n)=>[n.originalName,n])),this.unifiedTable=me(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 fn;return this.configureBulkLoad(),await this.transaction(async()=>{Tt(this.db,this.schema),this.createMetadataTable(),this.db.run(`DELETE FROM ${_(C)}`),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 Se("DNE source quality validation failed: no accepted localidade rows");s.flush();let c=this.rowCount(r.name);if(!c)throw new Se("DNE source quality validation failed: no CEP rows produced");let l=i.report(c);this.writeMetadata({...t,schema_version:Ke,quality_report:JSON.stringify(l),quality_rows_accepted:String(l.totals.accepted),quality_rows_read:String(l.totals.read),quality_rows_rejected:String(l.totals.rejected)})}finally{s.finalize()}}),this.rowCount(r.name)}async readLocalidades(e,t){let n=this.originalTable("log_localidade"),r=new Map;await De(n,e,pe(n,["locNu","uf","nome","cep","situacao","tipo","locNuSub","munNu"]),t,(o,a,s)=>{let[c=null,l=null,u=null,d=null,f=null,m=null,b=null,h=null]=o,y=ft([["locNu",c],["uf",l],["nome",u],["situacao",f],["tipo",m]]);if(y||!c||!l||!u){s.reject(y??"invalid_structure");return}if(!dt(l)){s.reject("invalid_uf");return}if(d!==null&&!Ve(d)){s.reject("invalid_cep");return}if(h!==null&&!vs(h)){s.reject("invalid_ibge");return}if(f!=="0"&&f!=="1"&&f!=="2"&&f!=="3"){s.reject("invalid_localidade_situacao");return}let g=ke.find((w)=>w===m);if(!g){s.reject("invalid_localidade_tipo");return}if(r.has(c)){s.reject("duplicate_localidade");return}r.set(c,{uf:l,nome:u,cep:d,locNuSub:b,munNu:h===null?null:Number(h),situacao:Number(f),tipo:g,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 De(r,e,pe(r,["baiNu","uf","locNu","bairro","abreviado"]),n,(o,a,s)=>{let[c=null,l=null,u=null,d=null,f=null]=o,m=ft([["baiNu",c],["uf",l],["locNu",u],["bairro",d]]);if(m||!c||!l||!u||!d){s.reject(m??"invalid_structure");return}let b=Ai(c);if(b===null||Ai(u)===null){s.reject("invalid_bairro_identifier");return}if(!dt(l)){s.reject("invalid_uf");return}let h=t.get(u);if(!h){s.reject("missing_localidade");return}if(h.uf!==l){s.reject("bairro_uf_mismatch");return}if(i.has(c)){s.reject("duplicate_bairro");return}i.set(c,{id:b,uf:l,locNu:u,nome:d,abreviado:f}),s.accept()}),i}insertBairros(e){let t=this.originalTable("bairros"),n=this.db.prepare(`
33
+ INSERT INTO ${_(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 ${_(i.name)} (bairro_id, cep_inicial, cep_final) VALUES (?, ?, ?)`);try{await De(r,e,pe(r,["baiNu","cepInicial","cepFinal"]),n,(s,c,l)=>{let[u=null,d=null,f=null]=s,m=u===null?void 0:t.get(u);if(!m){l.reject("missing_bairro");return}if(!Ve(d)||!Ve(f)){l.reject("invalid_cep_range");return}if(d>f){l.reject("reversed_cep_range");return}let b=`${m.id}:${d}:${f}`;if(o.has(b)){l.reject("duplicate_cep_range");return}o.add(b),a.run(m.id,d,f),l.accept()})}finally{a.finalize()}}prepareUnifiedInsert(e){return new Sn(this.db,e,mr)}rowCount(e){return this.db.query(`SELECT count(*) AS count FROM ${_(e)}`).get().count}async insertLogradouros(e,t,n,r,i){let o=this.originalTable("log_logradouro");await De(o,e,pe(o,["uf","locNu","baiNuIni","logNo","cep","tloTx","logStaTlo"]),i,(a,s,c)=>{let[l=null,u=null,d=null,f=null,m=null,b=null,h=null]=a,y=ft([["uf",l],["locNu",u],["baiNuIni",d],["logNo",f],["cep",m]]);if(y||!l||!u||!d||!f||!m){c.reject(y??"invalid_structure");return}if(!dt(l)){c.reject("invalid_uf");return}if(!Ve(m)){c.reject("invalid_cep");return}if(h==="S"&&!b){c.reject("missing_tloTx");return}let g=n.get(u);if(!g){c.reject("missing_localidade");return}let w=r.get(d);if(!w){c.reject("missing_bairro");return}if(g.uf!==l||w.uf!==l){c.reject("logradouro_uf_mismatch");return}if(w.locNu!==u){c.reject("bairro_localidade_mismatch");return}let E=Dn(g,n);if(!E){c.reject("missing_municipality");return}t.run(m,h==="S"?`${b} ${f}`:f,null,w.id,null,E.nome,E.munNu,l,null,g.situacao,g.tipo),c.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 De(i,e,pe(i,["uf","locNu","nome","endereco","cep"]),r,(o,a,s)=>{let[c=null,l=null,u=null,d=null,f=null]=o,m=ft([["uf",c],["locNu",l],["nome",u],["endereco",d],["cep",f]]);if(m||!c||!l||!u||!d||!f){s.reject(m??"invalid_structure");return}if(!dt(c)){s.reject("invalid_uf");return}if(!Ve(f)){s.reject("invalid_cep");return}let b=n.get(l);if(!b){s.reject("missing_localidade");return}if(b.uf!==c){s.reject("cpc_uf_mismatch");return}let h=Dn(b,n);if(!h){s.reject("missing_municipality");return}let[y,g]=Ii(d);t.run(f,y,g,null,null,h.nome,h.munNu,c,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 De(e,t,pe(e,["uf","locNu","baiNu","nome","endereco","cep"]),o,(a,s,c)=>{let[l=null,u=null,d=null,f=null,m=null,b=null]=a,h=ft([["uf",l],["locNu",u],["baiNu",d],["nome",f],["endereco",m],["cep",b]]);if(h||!l||!u||!d||!f||!m||!b){c.reject(h??"invalid_structure");return}if(!dt(l)){c.reject("invalid_uf");return}if(!Ve(b)){c.reject("invalid_cep");return}let y=r.get(u);if(!y){c.reject("missing_localidade");return}let g=i.get(d);if(!g){c.reject("missing_bairro");return}if(y.uf!==l||g.uf!==l){c.reject("address_uf_mismatch");return}if(g.locNu!==u){c.reject("bairro_localidade_mismatch");return}let w=Dn(y,r);if(!w){c.reject("missing_municipality");return}let[E,I]=Ii(m);n.run(b,E,I,g.id,null,w.nome,w.munNu,l,f,y.situacao,y.tipo),c.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 = ${dr}`),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 = ${fr}`)}createMetadataTable(){this.db.run(`
35
+ CREATE TABLE IF NOT EXISTS ${_(C)} (
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 t=this.db.prepare(`INSERT INTO ${_(C)} (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 Ii(e){let t=e.indexOf(",");if(t===-1)return[e.trim(),null];return[e.slice(0,t).trim(),e.slice(t+1).trim()]}function Ai(e){return/^\d{1,8}$/.test(e)&&z(Number(e))?Number(e):null}var Us=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 dt(e){return e!==null&&Us.has(e)}function Ve(e){return e!==null&&/^\d{8}$/.test(e)}function vs(e){if(!/^\d{7}$/.test(e))return!1;let t=Number(e);return Number.isSafeInteger(t)&&t>0}function ft(e){let t=e.find(([,n])=>n===null);return t?`missing_${t[0]}`:null}function Dn(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 Ri(e,t){if(e.schema_version!==Ke||e.source_kind!=="remote"||e.source_url!==t.url)return!1;let n=[An(e.source_etag,t.etag),An(e.source_last_modified,t.lastModified),An(e.source_content_length,t.contentLength)].filter((r)=>r!==null);return n.length>0&&n.every(Boolean)}function Ti(e,t,n){let r={loaded_at:new Date().toISOString(),package_version:n,schema_version:Ke,source_input:e,source_kind:t||Ms(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 An(e,t){if(!t)return null;return e===t}function Ms(e){try{let t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"}catch{return!1}}var js="0 0 * * 5",Rn="\x1B[0m",Vs="\x1B[1m",Gs="\x1B[36m",zs="\x1B[90m",Ys=/(--[^\r\n]*|\/\*[\s\S]*?(?:\*\/|$)|'(?:''|[^'])*'|"(?:""|[^"])*"|`(?:``|[^`])*`|\[(?:]]|[^\]])*]|\b(?:CREATE|TABLE|IF|NOT|EXISTS|TEXT|INTEGER|NULL|PRIMARY|KEY|WITHOUT|ROWID)\b)/gi,Pt="pt-BR",Zs=new Intl.NumberFormat(Pt),Qs=new Intl.NumberFormat(Pt,{maximumFractionDigits:1,minimumFractionDigits:1}),Xs=new Intl.NumberFormat(Pt,{maximumFractionDigits:1}),Li=1,Ae=2,Ks=3,Wt=await Jr(),Ni=Z("db",v.string,{default:ur,describe:"Caminho da base; build bin\xE1rio usa a extens\xE3o .bin.",global:!0,valueHint:"file",valueName:"CAMINHO"}),Ui=V("json",{describe:"Gravar um envelope JSON est\xE1vel em stdout.",global:!0}),vi=V("quiet",{describe:"Ocultar mensagens de progresso.",global:!0,short:"q"}),Mi=Zt("color"),Js=N(lr,{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:[Ni,Ui,vi,Mi],version:Wt,subcommands:[N("build",{args:[Z("format",v.enum(["sqlite","binary"]),{default:"sqlite",describe:"Formato da base de sa\xEDda.",valueName:"sqlite|binary"}),Z("source",v.string,{default:ae,describe:"Diret\xF3rio DNE, arquivo ZIP ou URL.",valueName:"CAMINHO|URL"}),V("force",{describe:"Ignorar metadados de atualiza\xE7\xE3o e recriar a base."}),V("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)=>rc(e,J(t))}),N("get",{args:[ze("input",v.string,{describe:"Um ou mais CEPs.",repeatable:!0,valueName:"CEP"}),Z("file",v.string,{describe:"Ler CEPs de um arquivo. Use - para stdin.",valueHint:"file",valueName:"CAMINHO"}),V("jsonl",{describe:"Gravar um resultado JSON por linha."})],about:"Consultar um ou mais CEPs",handler:(e,t)=>oc(e,J(t))}),N("status",{about:"Exibir tamanho, registros, estado do esquema e metadados da fonte",handler:(e,t)=>ac(J(t))}),N("schema",{args:[V("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)=>sc(e,J(t))}),N("doctor",{args:[V("offline",{describe:"N\xE3o verificar a fonte remota."}),Z("source",v.string,{default:ae,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)=>cc(e,J(t))}),N("sql",{args:[ze("query",v.string,{describe:"Instru\xE7\xE3o SELECT, WITH, PRAGMA ou EXPLAIN somente leitura.",required:!0,valueName:"CONSULTA"}),Z("limit",v.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)=>lc(e,J(t))}),N("cron",{about:"Gerenciar a atualiza\xE7\xE3o autom\xE1tica da base no sistema operacional",subcommands:[N("install",{args:[ze("expression",v.cron,{default:js,describe:"Express\xE3o cron. O padr\xE3o executa \xE0 meia-noite de sexta-feira.",valueName:"EXPRESS\xC3O"}),V("dry-run",{describe:"Exibir o agendamento sem alterar o sistema."}),Z("source",v.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)=>ec(e,J(t))}),N("status",{about:"Exibir o agendamento desta base",handler:(e,t)=>tc(J(t))}),N("remove",{about:"Remover o agendamento desta base",handler:(e,t)=>nc(J(t))})],subcommandRequired:!0,defaultToHelp:!0})],subcommandRequired:!0,defaultToHelp:!0});async function Fi(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 Js.run({argv:e,color:n,stdout:(r)=>console.log(Tn(r).trimEnd()),...t?{stderr:(r)=>$i(new S("invalid-arguments",Tn(wc(Bun.stripANSI(r))),Ae),!0)}:{stderr:(r)=>console.error(Tn(r).trimEnd())}})}catch(r){return fc(r,t)}}function J(e){return{color:e.global(Mi),database:e.global(Ni),json:e.global(Ui),quiet:e.global(vi)}}async function ec(e,t){let n=await kr({database:t.database,dryRun:e["dry-run"],expression:e.expression,packageVersion:Wt,source:e.source});if(t.json)Y(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: ${Ge(n.next_run??void 0)}`),console.log(`Base: ${n.database}`),console.log(`Fonte: ${n.source}`),console.log(`Comando: ${n.command}`)}return 0}function tc(e){let t=Pr(e.database);if(e.json)Y(t);else if(t.installed)console.log(`Agendamento instalado: ${t.expression}`),console.log(`Pr\xF3xima execu\xE7\xE3o: ${Ge(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 nc(e){let t=await Wr(e.database);if(e.json)Y(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 rc(e,t){let n=dc(t.quiet);try{return await ic(e,t,n)}finally{n.finish()}}async function ic(e,t,n){let r=performance.now(),i=K(t.database,e.format);if(e.format==="binary"&&i===":memory:")throw new S("invalid-format","O formato bin\xE1rio exige um caminho de arquivo.",Ae);if(e.check||i===":memory:")return Bi(e,t,n,r,i);let o=await Xr(i,n);try{return await Bi(e,t,n,r,i)}finally{o.release()}}async function Bi(e,t,n,r,i){let o=Pi(),a=e.source,s=Wi(a)?await uc(a,n):null;if(n.finish(),e.check){if(!s){let E=new Mt(a,{onProgress:n});try{await E.resolve(o)}catch(I){throw new S("source-unavailable",mt(I))}finally{await E.cleanup(),n.finish()}}let y=await Ee(i),g=s&&y.ready?await Ci(i,e.format,s):null,w={database:y,source:$t(a,s),status:g===null?"unknown":g?"current":"update-available",up_to_date:g};return mc(w,t.json),0}if(!e.force&&s&&await Ci(i,e.format,s)){let g={database:await Ee(i),elapsed_ms:xn(r),source:$t(a,s),status:"unchanged"};return xi(g,t.json),0}let c=i!==":memory:"&&await Bun.file(i).exists(),l=new Mt(a,{onProgress:n,remoteInfo:s??void 0}),u=await Bc(i),d=new In(u.path,o),f=!1,m=0;try{let y=await l.resolve(o);if(n(e.format==="binary"?"Carregando a base bin\xE1ria":"Carregando a base SQLite"),m=await d.loadFromSource(y,Ti(a,s,Wt),n),e.format==="sqlite"&&i!==":memory:")n("Compactando a base SQLite"),d.compact();d.close(),f=!0;let g=u.path;if(e.format==="binary")g=`${u.path}.bin`,n("Compactando a base bin\xE1ria"),await Er(u.path,g),await Ie(u.path,{force:!0});if(n(e.format==="binary"?"Confirmando a base bin\xE1ria":"Confirmando a base SQLite"),e.format==="sqlite"&&c)await Dc(i,u.path,o);else await u.commit(g);n.finish()}finally{if(!f)d.close();await u.cleanup(),await l.cleanup()}let h={database:i===":memory:"?Nr(m):await Ee(i),elapsed_ms:xn(r),source:$t(a,s),status:c?"updated":"created"};return xi(h,t.json),0}async function oc(e,t){if(t.json&&e.jsonl)throw new S("output-conflict","--json e --jsonl n\xE3o podem ser usados juntos.",Ae);let r=Ar(e.input,e.file)[Symbol.asyncIterator](),i=await r.next();if(i.done)throw new S("missing-input","Informe um CEP, --file CAMINHO ou uma entrada em stdin.",Ae);let o=d(i.value),a=K(t.database),s=await xt(a),c=[],l=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)Y({count:l,database:a,results:c});else if(!e.jsonl)pc(c);return u?Ks:0;function d(m){let b=Ir(m);if(b===void 0)throw new S("invalid-cep",`CEP inv\xE1lido '${m}'. Use 01001000 ou 01001-000.`,Ae,{input:m});return{cep:b,input:m}}function f(m){let b=s.queryCep(m.cep)??null,h={address:b,cep:m.cep,found:b!==null,input:m.input};if(l++,u||=!h.found,e.jsonl){process.stdout.write(`${JSON.stringify({ok:!0,data:{database:a,result:h}})}
41
+ `);return}c.push(h)}}async function ac(e){let t=await Ee(K(e.database));if(e.json)Y(t);else bc(t);return t.ready?0:Li}async function sc(e,t){let n=Pi(),r=me(n),i=null,o="declared",a=Je(n),s=`${[...a.map(Or),sn(r.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){i=K(t.database);let c=await xt(i);try{if(!("tableSchema"in c))o="binary";else{let l=a.map((d)=>c.tableSchema(d.name)).filter((d)=>d!==void 0).map(Ic),u=c.querySql(`SELECT sql FROM sqlite_master WHERE type = 'view' AND name = ${Hi(we(r.name))}`,1).rows[0]?.sql;if(typeof u==="string")l.push(u);if(l.length)s=`${l.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
+ `)};`,o="database"}}finally{c.close()}}if(t.json)Y({database:i,source:o,sql:s,table:L});else console.log(Rc(s,t.color));return 0}async function cc(e,t){let n=await Ee(K(t.database)),r=Sc(Bun.version),i={checked:!1,reachable:null,url:e.source};if(!e.offline)try{let s=await Ft(e.source);i={...$t(e.source,s),checked:!0,reachable:!0}}catch(s){i={checked:!0,error:mt(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 ${_c(n.path)}`,source:i,version:Wt};if(t.json)Y(a);else hc(a);return o?0:Li}async function lc(e,t){if(!/^\s*(?:SELECT|WITH|PRAGMA|EXPLAIN)\b/i.test(e.query))throw new S("write-query-denied","O comando sql permite somente instru\xE7\xF5es SELECT, WITH, PRAGMA e EXPLAIN.",Ae);let n=K(t.database),r=await xt(n);try{if(!("querySql"in r))throw new S("sql-unsupported","O comando sql exige uma base SQLite.",Ae);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)Y(o);else console.log(JSON.stringify(o,null,2))}finally{r.close()}return 0}async function uc(e,t){t("Inspecionando a fonte DNE remota");try{return await Ft(e)}catch(n){throw new S("source-unavailable",mt(n))}}function $t(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:Wi(e)?"remote":"local"}}function dc(e){let t=null,n=()=>{if(t!==null)process.stderr.write(` (${On(xn(t))})
46
+ `),t=null},r=(i)=>{if(n(),!e)t=performance.now(),process.stderr.write(i)};return r.finish=n,r}function Y(e){process.stdout.write(`${JSON.stringify({ok:!0,data:e},null,2)}
47
+ `)}function $i(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 fc(e,t){let n=e instanceof S?e:e instanceof Se?new S("source-quality-failed",mt(e)):new S("internal-error",mt(e));return $i(n,t),n.exitCode}function mc(e,t){if(t){Y(e);return}console.log(`Estado: ${Ec(e.status)}`),console.log(`Base: ${e.database.path}`),console.log(`Fonte: ${Bn(e.source.url??e.source.input)}`),console.log(`\xDAltima modifica\xE7\xE3o na fonte: ${Ge(Bn(e.source.last_modified))}`)}function xi(e,t){if(t){Y(e);return}let n=e.database.row_count===null?"quantidade desconhecida de registros":`${ce(e.database.row_count)} registros`,r=e.database.size_bytes===null?"tamanho desconhecido":ki(e.database.size_bytes);if(e.status==="unchanged"){let o=e.database.row_count===null?"quantidade desconhecida de registros":`${ce(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: ${Ge(Bn(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 pc(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,kt(t.found),t.address?.logradouro??"",t.address?.bairro??"",t.address?.municipio??"",t.address?.uf??""].join("\t"))}function bc(e){if(console.log(`Base: ${e.path}`),console.log(`Formato: ${e.format??"-"}`),console.log(`Existe: ${kt(e.exists)}`),console.log(`Pronta: ${kt(e.ready)}`),console.log(`Registros: ${e.row_count===null?"-":ce(e.row_count)}`),console.log(`Tamanho: ${e.size_bytes===null?"-":ki(e.size_bytes)}`),console.log(`Carregada em: ${Ge(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: ${Ge(e.metadata?.source_last_modified)}`),e.error)console.log(`Erro: ${e.error}`)}function hc(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: ${kt(e.healthy)}`),e.setup)console.log(`Configura\xE7\xE3o: ${e.setup}`)}function yc(e){return e instanceof Error?e.message:String(e)}function mt(e){return gc(yc(e))}function gc(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 Bn(e){return typeof e==="string"?e:""}function wc(e){return e.split(`
49
+ `).map((t)=>t.trim()).find(Boolean)?.replace(/^error:\s*/i,"")??"Argumentos inv\xE1lidos."}function xn(e){return Math.max(0,Math.round(performance.now()-e))}function ce(e){return Zs.format(e)}function Oi(e){return Qs.format(e)}function Ge(e){if(!e)return"-";let t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString(Pt)}function On(e){let t=Math.max(0,Math.round(e));if(t<1000)return`${ce(t)} ms`;let n=Math.round(t/1000);if(n<60){let a=Math.round(t/100)/10;return`${Xs.format(a)} s`}let r=Math.floor(n/3600),i=Math.floor(n%3600/60),o=n%60;return[r?`${ce(r)} h`:"",i?`${ce(i)} min`:"",o?`${ce(o)} s`:""].filter(Boolean).join(" ")}function ki(e){if(e<1024)return`${ce(e)} B`;if(e<1048576)return`${Oi(e/1024)} KiB`;return`${Oi(e/1048576)} MiB`}function kt(e){return e?"sim":"n\xE3o"}function Ec(e){return{current:"atualizada",unknown:"desconhecido","update-available":"atualiza\xE7\xE3o dispon\xEDvel"}[e]??e}function _c(e){return`'${e.replaceAll("'","'\\''")}'`}function Sc(e){let[t=0,n=0]=e.split(".").map(Number);return t>1||t===1&&n>=4}function Pi(){let e=Kn();return me(e).name=L,e}async function Dc(e,t,n){let r=Je(n),i=`${t}.attach`;await Ie(i,{force:!0}),await $s(t,i);let o=new Fs(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 ${Hi(i)} AS fresh`),o.run("BEGIN IMMEDIATE");try{Tt(o,n),o.run(`
50
+ CREATE TABLE IF NOT EXISTS ${_(C)} (
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 a of r){let s=a.columns.map((c)=>_(c.name)).join(", ");o.run(`
55
+ INSERT INTO main.${_(a.name)} (${s})
56
+ SELECT ${s} FROM fresh.${_(a.name)}
57
+ `)}o.run(`DELETE FROM main.${_(C)}`),o.run(`
58
+ INSERT INTO main.${_(C)} (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}
60
+ FROM fresh.${_(C)}
61
+ `),o.run("COMMIT")}catch(a){throw o.run("ROLLBACK"),a}finally{o.run("DETACH DATABASE fresh")}}finally{o.close(),await Ie(i,{force:!0})}}async function Ci(e,t,n){let r=await Ee(e);if(!r.ready||r.format!==t||!r.metadata)return!1;return Ri(r.metadata,n)}function Wi(e){try{let t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"}catch{return!1}}function Hi(e){return`'${e.replaceAll("'","''")}'`}function Ic(e){let t=e.indexOf("("),n=e.lastIndexOf(")");if(t===-1||n<=t)return e;let r=Ac(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
62
  ${r.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
+ ${o}`}function Ac(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 Rc(e,t){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:(n)=>Tc(n,t)}).trimEnd()}function Tc(e,t){if(!t)return e;return e.replaceAll(Ys,(n)=>{if(n.startsWith("--")||n.startsWith("/*"))return`${zs}${n}${Rn}`;if(n.startsWith('"')||n.startsWith("`")||n.startsWith("["))return`${Gs}${n}${Rn}`;if(n.startsWith("'"))return n;return`${Vs}${n}${Rn}`})}async function Bc(e){if(e===":memory:")return{path:e,commit:async(i)=>{},cleanup:async()=>{}};let t=Hs(e),n=qs(t,`.${Ws(e)}.${process.pid}.${Date.now()}.tmp`);await ks(t,{recursive:!0}),await Ie(n,{force:!0});let r=!1;return{path:n,commit:async(i=n)=>{await Ps(i,e),r=!0},cleanup:async()=>{if(!r)await Ie(n,{force:!0});await Ie(`${n}.bin`,{force:!0}),await Ie(`${n}-journal`,{force:!0})}}}process.exitCode=await Fi();
68
68
 
69
- //# debugId=1E5DEF2E51CCBE6764756E2164756E21
69
+ //# debugId=0C62C72F8315392C64756E2164756E21